Skip to content

Commit 73716fa

Browse files
committed
Fuzz test for parsing bech32-encoded Refund
A refund is serialized as a TLV stream and encoded in bech32 without a checksum. Add a fuzz test that parses the bech32-encoded TLV stream and deserializes the underlying Refund before serializing it and re-encoding it. Then compare the original Refund with one obtained by parsing the re-encoded TLV stream.
1 parent ff74d0c commit 73716fa

File tree

7 files changed

+149
-3
lines changed

7 files changed

+149
-3
lines changed

fuzz/src/bin/gen_target.sh

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ GEN_TEST offer_deser
1313
GEN_TEST onion_message
1414
GEN_TEST peer_crypt
1515
GEN_TEST process_network_graph
16+
GEN_TEST refund_deser
1617
GEN_TEST router
1718
GEN_TEST zbase32
1819

fuzz/src/bin/refund_deser_target.rs

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
// This file is Copyright its original authors, visible in version control
2+
// history.
3+
//
4+
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5+
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7+
// You may not use this file except in accordance with one or both of these
8+
// licenses.
9+
10+
// This file is auto-generated by gen_target.sh based on target_template.txt
11+
// To modify it, modify target_template.txt and run gen_target.sh instead.
12+
13+
#![cfg_attr(feature = "libfuzzer_fuzz", no_main)]
14+
15+
#[cfg(not(fuzzing))]
16+
compile_error!("Fuzz targets need cfg=fuzzing");
17+
18+
extern crate lightning_fuzz;
19+
use lightning_fuzz::refund_deser::*;
20+
21+
#[cfg(feature = "afl")]
22+
#[macro_use] extern crate afl;
23+
#[cfg(feature = "afl")]
24+
fn main() {
25+
fuzz!(|data| {
26+
refund_deser_run(data.as_ptr(), data.len());
27+
});
28+
}
29+
30+
#[cfg(feature = "honggfuzz")]
31+
#[macro_use] extern crate honggfuzz;
32+
#[cfg(feature = "honggfuzz")]
33+
fn main() {
34+
loop {
35+
fuzz!(|data| {
36+
refund_deser_run(data.as_ptr(), data.len());
37+
});
38+
}
39+
}
40+
41+
#[cfg(feature = "libfuzzer_fuzz")]
42+
#[macro_use] extern crate libfuzzer_sys;
43+
#[cfg(feature = "libfuzzer_fuzz")]
44+
fuzz_target!(|data: &[u8]| {
45+
refund_deser_run(data.as_ptr(), data.len());
46+
});
47+
48+
#[cfg(feature = "stdin_fuzz")]
49+
fn main() {
50+
use std::io::Read;
51+
52+
let mut data = Vec::with_capacity(8192);
53+
std::io::stdin().read_to_end(&mut data).unwrap();
54+
refund_deser_run(data.as_ptr(), data.len());
55+
}
56+
57+
#[test]
58+
fn run_test_cases() {
59+
use std::fs;
60+
use std::io::Read;
61+
use lightning_fuzz::utils::test_logger::StringBuffer;
62+
63+
use std::sync::{atomic, Arc};
64+
{
65+
let data: Vec<u8> = vec![0];
66+
refund_deser_run(data.as_ptr(), data.len());
67+
}
68+
let mut threads = Vec::new();
69+
let threads_running = Arc::new(atomic::AtomicUsize::new(0));
70+
if let Ok(tests) = fs::read_dir("test_cases/refund_deser") {
71+
for test in tests {
72+
let mut data: Vec<u8> = Vec::new();
73+
let path = test.unwrap().path();
74+
fs::File::open(&path).unwrap().read_to_end(&mut data).unwrap();
75+
threads_running.fetch_add(1, atomic::Ordering::AcqRel);
76+
77+
let thread_count_ref = Arc::clone(&threads_running);
78+
let main_thread_ref = std::thread::current();
79+
threads.push((path.file_name().unwrap().to_str().unwrap().to_string(),
80+
std::thread::spawn(move || {
81+
let string_logger = StringBuffer::new();
82+
83+
let panic_logger = string_logger.clone();
84+
let res = if ::std::panic::catch_unwind(move || {
85+
refund_deser_test(&data, panic_logger);
86+
}).is_err() {
87+
Some(string_logger.into_string())
88+
} else { None };
89+
thread_count_ref.fetch_sub(1, atomic::Ordering::AcqRel);
90+
main_thread_ref.unpark();
91+
res
92+
})
93+
));
94+
while threads_running.load(atomic::Ordering::Acquire) > 32 {
95+
std::thread::park();
96+
}
97+
}
98+
}
99+
let mut failed_outputs = Vec::new();
100+
for (test, thread) in threads.drain(..) {
101+
if let Some(output) = thread.join().unwrap() {
102+
println!("\nOutput of {}:\n{}\n", test, output);
103+
failed_outputs.push(test);
104+
}
105+
}
106+
if !failed_outputs.is_empty() {
107+
println!("Test cases which failed: ");
108+
for case in failed_outputs {
109+
println!("{}", case);
110+
}
111+
panic!();
112+
}
113+
}

fuzz/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ pub mod offer_deser;
2121
pub mod onion_message;
2222
pub mod peer_crypt;
2323
pub mod process_network_graph;
24+
pub mod refund_deser;
2425
pub mod router;
2526
pub mod zbase32;
2627

fuzz/src/refund_deser.rs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// This file is Copyright its original authors, visible in version control
2+
// history.
3+
//
4+
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5+
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7+
// You may not use this file except in accordance with one or both of these
8+
// licenses.
9+
10+
use crate::utils::test_logger;
11+
use lightning::offers::refund::Refund;
12+
13+
#[inline]
14+
pub fn do_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
15+
if let Ok(bech32_encoded) = std::str::from_utf8(data) {
16+
if let Ok(refund) = bech32_encoded.parse::<Refund>() {
17+
let bech32_encoded = refund.to_string();
18+
assert_eq!(refund, bech32_encoded.parse::<Refund>().unwrap());
19+
}
20+
}
21+
}
22+
23+
pub fn refund_deser_test<Out: test_logger::Output>(data: &[u8], out: Out) {
24+
do_test(data, out);
25+
}
26+
27+
#[no_mangle]
28+
pub extern "C" fn refund_deser_run(data: *const u8, datalen: usize) {
29+
do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull {});
30+
}

fuzz/targets.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ void offer_deser_run(const unsigned char* data, size_t data_len);
66
void onion_message_run(const unsigned char* data, size_t data_len);
77
void peer_crypt_run(const unsigned char* data, size_t data_len);
88
void process_network_graph_run(const unsigned char* data, size_t data_len);
9+
void refund_deser_run(const unsigned char* data, size_t data_len);
910
void router_run(const unsigned char* data, size_t data_len);
1011
void zbase32_run(const unsigned char* data, size_t data_len);
1112
void msg_accept_channel_run(const unsigned char* data, size_t data_len);

lightning/src/offers/payer.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ use crate::prelude::*;
1717
/// [`InvoiceRequest::payer_id`].
1818
///
1919
/// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id
20-
#[derive(Clone, Debug)]
20+
#[derive(Clone, Debug, PartialEq)]
2121
pub(super) struct PayerContents(pub Vec<u8>);
2222

2323
tlv_stream!(PayerTlvStream, PayerTlvStreamRef, 0..1, {

lightning/src/offers/refund.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,7 @@ impl RefundBuilder {
202202
///
203203
/// [`Invoice`]: crate::offers::invoice::Invoice
204204
/// [`Offer`]: crate::offers::offer::Offer
205-
#[derive(Clone, Debug)]
205+
#[derive(Clone, Debug, PartialEq)]
206206
pub struct Refund {
207207
pub(super) bytes: Vec<u8>,
208208
pub(super) contents: RefundContents,
@@ -211,7 +211,7 @@ pub struct Refund {
211211
/// The contents of a [`Refund`], which may be shared with an [`Invoice`].
212212
///
213213
/// [`Invoice`]: crate::offers::invoice::Invoice
214-
#[derive(Clone, Debug)]
214+
#[derive(Clone, Debug, PartialEq)]
215215
pub(super) struct RefundContents {
216216
payer: PayerContents,
217217
// offer fields

0 commit comments

Comments
 (0)