Skip to content

Commit 806b7f0

Browse files
authored
Merge pull request #3054 from TheBlueMatt/2024-04-fuzz-bolt11
Add fuzzing coverage for BOLT11 invoice deserialization
2 parents 676f242 + 8db1226 commit 806b7f0

File tree

13 files changed

+200
-124
lines changed

13 files changed

+200
-124
lines changed

.github/workflows/build.yml

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -191,13 +191,10 @@ jobs:
191191
- name: Pin the regex dependency
192192
run: |
193193
cd fuzz && cargo update -p regex --precise "1.9.6" --verbose && cd ..
194-
cd lightning-invoice/fuzz && cargo update -p regex --precise "1.9.6" --verbose
195194
- name: Sanity check fuzz targets on Rust ${{ env.TOOLCHAIN }}
196195
run: cd fuzz && RUSTFLAGS="--cfg=fuzzing" cargo test --verbose --color always
197196
- name: Run fuzzers
198197
run: cd fuzz && ./ci-fuzz.sh && cd ..
199-
- name: Run lightning-invoice fuzzers
200-
run: cd lightning-invoice/fuzz && RUSTFLAGS="--cfg=fuzzing" cargo test --verbose && ./ci-fuzz.sh
201198

202199
linting:
203200
runs-on: ubuntu-latest

fuzz/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ stdin_fuzz = []
1919

2020
[dependencies]
2121
lightning = { path = "../lightning", features = ["regex", "hashbrown", "_test_utils"] }
22+
lightning-invoice = { path = "../lightning-invoice" }
2223
lightning-rapid-gossip-sync = { path = "../lightning-rapid-gossip-sync" }
2324
bitcoin = { version = "0.30.2", features = ["secp-lowmemory"] }
2425
hex = { package = "hex-conservative", version = "0.1.1", default-features = false }

fuzz/src/bin/bolt11_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::bolt11_deser::*;
20+
21+
#[cfg(feature = "afl")]
22+
#[macro_use] extern crate afl;
23+
#[cfg(feature = "afl")]
24+
fn main() {
25+
fuzz!(|data| {
26+
bolt11_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+
bolt11_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+
bolt11_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+
bolt11_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+
bolt11_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/bolt11_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+
bolt11_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/bin/gen_target.sh

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

fuzz/src/bolt11_deser.rs

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
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 bitcoin::bech32::{u5, FromBase32, ToBase32};
12+
use bitcoin::secp256k1::{Secp256k1, SecretKey};
13+
use lightning_invoice::{
14+
Bolt11Invoice, RawBolt11Invoice, RawDataPart, RawHrp, RawTaggedField, TaggedField,
15+
};
16+
use std::str::FromStr;
17+
18+
#[inline]
19+
pub fn do_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
20+
// Read a fake HRP length byte
21+
let hrp_len = std::cmp::min(*data.get(0).unwrap_or(&0) as usize, data.len());
22+
if let Ok(s) = std::str::from_utf8(&data[..hrp_len]) {
23+
let hrp = match RawHrp::from_str(s) {
24+
Ok(hrp) => hrp,
25+
Err(_) => return,
26+
};
27+
let bech32 =
28+
data.iter().skip(hrp_len).map(|x| u5::try_from_u8(x % 32).unwrap()).collect::<Vec<_>>();
29+
let invoice_data = match RawDataPart::from_base32(&bech32) {
30+
Ok(invoice) => invoice,
31+
Err(_) => return,
32+
};
33+
34+
// Our data encoding is not worse than the input
35+
assert!(invoice_data.to_base32().len() <= bech32.len());
36+
37+
// Our data serialization is loss-less
38+
assert_eq!(
39+
RawDataPart::from_base32(&invoice_data.to_base32())
40+
.expect("faild parsing out own encoding"),
41+
invoice_data
42+
);
43+
44+
if invoice_data.tagged_fields.iter().any(|field| {
45+
matches!(field, RawTaggedField::KnownSemantics(TaggedField::PayeePubKey(_)))
46+
}) {
47+
// We could forge a signature using the fact that signing is insecure in fuzz mode, but
48+
// easier to just skip and rely on the fact that no-PayeePubKey invoices do pubkey
49+
// recovery
50+
return;
51+
}
52+
53+
let raw_invoice = RawBolt11Invoice { hrp, data: invoice_data };
54+
let signed_raw_invoice = match raw_invoice.sign(|hash| {
55+
let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
56+
Ok::<_, ()>(Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key))
57+
}) {
58+
Ok(inv) => inv,
59+
Err(_) => return,
60+
};
61+
62+
if let Ok(invoice) = Bolt11Invoice::from_signed(signed_raw_invoice) {
63+
invoice.amount_milli_satoshis();
64+
}
65+
}
66+
}
67+
68+
pub fn bolt11_deser_test<Out: test_logger::Output>(data: &[u8], out: Out) {
69+
do_test(data, out);
70+
}
71+
72+
#[no_mangle]
73+
pub extern "C" fn bolt11_deser_run(data: *const u8, datalen: usize) {
74+
do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull {});
75+
}

fuzz/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ pub mod indexedmap;
2222
pub mod invoice_deser;
2323
pub mod invoice_request_deser;
2424
pub mod offer_deser;
25+
pub mod bolt11_deser;
2526
pub mod onion_message;
2627
pub mod peer_crypt;
2728
pub mod process_network_graph;

fuzz/targets.h

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

lightning-invoice/fuzz/.gitignore

Lines changed: 0 additions & 2 deletions
This file was deleted.

lightning-invoice/fuzz/Cargo.toml

Lines changed: 0 additions & 28 deletions
This file was deleted.

lightning-invoice/fuzz/ci-fuzz.sh

Lines changed: 0 additions & 19 deletions
This file was deleted.

lightning-invoice/fuzz/fuzz_targets/serde_data_part.rs

Lines changed: 0 additions & 69 deletions
This file was deleted.

lightning-invoice/src/de.rs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,11 @@ mod hrp_sm {
4343
}
4444

4545
impl States {
46-
fn next_state(&self, read_symbol: char) -> Result<States, super::Bolt11ParseError> {
46+
fn next_state(&self, read_byte: u8) -> Result<States, super::Bolt11ParseError> {
47+
let read_symbol = match char::from_u32(read_byte.into()) {
48+
Some(symb) if symb.is_ascii() => symb,
49+
_ => return Err(super::Bolt11ParseError::MalformedHRP),
50+
};
4751
match *self {
4852
States::Start => {
4953
if read_symbol == 'l' {
@@ -119,7 +123,7 @@ mod hrp_sm {
119123
*range = Some(new_range);
120124
}
121125

122-
fn step(&mut self, c: char) -> Result<(), super::Bolt11ParseError> {
126+
fn step(&mut self, c: u8) -> Result<(), super::Bolt11ParseError> {
123127
let next_state = self.state.next_state(c)?;
124128
match next_state {
125129
States::ParseCurrencyPrefix => {
@@ -158,7 +162,7 @@ mod hrp_sm {
158162

159163
pub fn parse_hrp(input: &str) -> Result<(&str, &str, &str), super::Bolt11ParseError> {
160164
let mut sm = StateMachine::new();
161-
for c in input.chars() {
165+
for c in input.bytes() {
162166
sm.step(c)?;
163167
}
164168

rustfmt_excluded_files

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
./fuzz/src/bech32_parse.rs
44
./fuzz/src/bin/base32_target.rs
55
./fuzz/src/bin/bech32_parse_target.rs
6+
./fuzz/src/bin/bolt11_deser_target.rs
67
./fuzz/src/bin/chanmon_consistency_target.rs
78
./fuzz/src/bin/chanmon_deser_target.rs
89
./fuzz/src/bin/fromstr_to_netaddress_target.rs

0 commit comments

Comments
 (0)