Skip to content

Commit 1dd2d94

Browse files
committed
fuzz
1 parent ad05cca commit 1dd2d94

11 files changed

+384
-55
lines changed

fuzz/.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
hfuzz_target
22
target
33
hfuzz_workspace
4+
corpus

fuzz/Cargo.toml

+5-2
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ bitcoin = { version = "0.32.2", features = ["secp-lowmemory"] }
2727
afl = { version = "0.12", optional = true }
2828
honggfuzz = { version = "0.5", optional = true, default-features = false }
2929
libfuzzer-sys = { version = "0.4", optional = true }
30+
component = "0.1.1"
31+
llvm-tools = "0.1.1"
3032

3133
[build-dependencies]
3234
cc = "1.0"
@@ -36,10 +38,11 @@ cc = "1.0"
3638
members = ["."]
3739

3840
[profile.release]
39-
lto = true
40-
codegen-units = 1
41+
lto = "off"
4142
debug-assertions = true
4243
overflow-checks = true
44+
opt-level = 0
45+
debug = true
4346

4447
# When testing a large fuzz corpus, -O1 offers a nice speedup
4548
[profile.dev]

fuzz/src/bin/gen_target.sh

+1
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ GEN_TEST bolt11_deser
1717
GEN_TEST onion_message
1818
GEN_TEST peer_crypt
1919
GEN_TEST process_network_graph
20+
GEN_TEST process_onion_failure
2021
GEN_TEST refund_deser
2122
GEN_TEST router
2223
GEN_TEST zbase32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
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+
#![cfg_attr(rustfmt, rustfmt_skip)]
15+
16+
#[cfg(not(fuzzing))]
17+
compile_error!("Fuzz targets need cfg=fuzzing");
18+
19+
#[cfg(not(hashes_fuzz))]
20+
compile_error!("Fuzz targets need cfg=hashes_fuzz");
21+
22+
#[cfg(not(secp256k1_fuzz))]
23+
compile_error!("Fuzz targets need cfg=secp256k1_fuzz");
24+
25+
extern crate lightning_fuzz;
26+
use lightning_fuzz::process_onion_failure::*;
27+
28+
#[cfg(feature = "afl")]
29+
#[macro_use] extern crate afl;
30+
#[cfg(feature = "afl")]
31+
fn main() {
32+
fuzz!(|data| {
33+
process_onion_failure_run(data.as_ptr(), data.len());
34+
});
35+
}
36+
37+
#[cfg(feature = "honggfuzz")]
38+
#[macro_use] extern crate honggfuzz;
39+
#[cfg(feature = "honggfuzz")]
40+
fn main() {
41+
loop {
42+
fuzz!(|data| {
43+
process_onion_failure_run(data.as_ptr(), data.len());
44+
});
45+
}
46+
}
47+
48+
#[cfg(feature = "libfuzzer_fuzz")]
49+
#[macro_use] extern crate libfuzzer_sys;
50+
#[cfg(feature = "libfuzzer_fuzz")]
51+
fuzz_target!(|data: &[u8]| {
52+
process_onion_failure_run(data.as_ptr(), data.len());
53+
});
54+
55+
#[cfg(feature = "stdin_fuzz")]
56+
fn main() {
57+
use std::io::Read;
58+
59+
let mut data = Vec::with_capacity(8192);
60+
std::io::stdin().read_to_end(&mut data).unwrap();
61+
process_onion_failure_run(data.as_ptr(), data.len());
62+
}
63+
64+
#[test]
65+
fn run_test_cases() {
66+
use std::fs;
67+
use std::io::Read;
68+
use lightning_fuzz::utils::test_logger::StringBuffer;
69+
70+
use std::sync::{atomic, Arc};
71+
{
72+
let data: Vec<u8> = vec![0];
73+
process_onion_failure_run(data.as_ptr(), data.len());
74+
}
75+
let mut threads = Vec::new();
76+
let threads_running = Arc::new(atomic::AtomicUsize::new(0));
77+
if let Ok(tests) = fs::read_dir("test_cases/process_onion_failure") {
78+
for test in tests {
79+
let mut data: Vec<u8> = Vec::new();
80+
let path = test.unwrap().path();
81+
fs::File::open(&path).unwrap().read_to_end(&mut data).unwrap();
82+
threads_running.fetch_add(1, atomic::Ordering::AcqRel);
83+
84+
let thread_count_ref = Arc::clone(&threads_running);
85+
let main_thread_ref = std::thread::current();
86+
threads.push((path.file_name().unwrap().to_str().unwrap().to_string(),
87+
std::thread::spawn(move || {
88+
let string_logger = StringBuffer::new();
89+
90+
let panic_logger = string_logger.clone();
91+
let res = if ::std::panic::catch_unwind(move || {
92+
process_onion_failure_test(&data, panic_logger);
93+
}).is_err() {
94+
Some(string_logger.into_string())
95+
} else { None };
96+
thread_count_ref.fetch_sub(1, atomic::Ordering::AcqRel);
97+
main_thread_ref.unpark();
98+
res
99+
})
100+
));
101+
while threads_running.load(atomic::Ordering::Acquire) > 32 {
102+
std::thread::park();
103+
}
104+
}
105+
}
106+
let mut failed_outputs = Vec::new();
107+
for (test, thread) in threads.drain(..) {
108+
if let Some(output) = thread.join().unwrap() {
109+
println!("\nOutput of {}:\n{}\n", test, output);
110+
failed_outputs.push(test);
111+
}
112+
}
113+
if !failed_outputs.is_empty() {
114+
println!("Test cases which failed: ");
115+
for case in failed_outputs {
116+
println!("{}", case);
117+
}
118+
panic!();
119+
}
120+
}

fuzz/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ pub mod onion_hop_data;
2828
pub mod onion_message;
2929
pub mod peer_crypt;
3030
pub mod process_network_graph;
31+
pub mod process_onion_failure;
3132
pub mod refund_deser;
3233
pub mod router;
3334
pub mod zbase32;

fuzz/src/process_onion_failure.rs

+170
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,170 @@
1+
// FUZZER COMMANDS:
2+
// RUSTFLAGS="--cfg hashes_fuzz --cfg=secp256k1_fuzz" cargo +nightly fuzz run --features "libfuzzer_fuzz" process_onion_failure_target
3+
// RUSTFLAGS="--cfg hashes_fuzz --cfg=secp256k1_fuzz" cargo +nightly fuzz coverage -v --features "libfuzzer_fuzz" process_onion_failure_target
4+
// llvm-cov show target/aarch64-apple-darwin/coverage/aarch64-apple-darwin/release/process_onion_failure_target --instr-profile=/Users/joost/repo/rust-lightning/fuzz/coverage/process_onion_failure_target/coverage.profdata --format=html --output-dir=reports
5+
6+
use std::sync::Arc;
7+
8+
use bitcoin::{
9+
key::Secp256k1,
10+
secp256k1::{PublicKey, SecretKey},
11+
};
12+
use lightning::{
13+
blinded_path::BlindedHop,
14+
ln::{
15+
channelmanager::{HTLCSource, PaymentId},
16+
msgs::OnionErrorPacket,
17+
},
18+
routing::router::{BlindedTail, Path, RouteHop, TrampolineHop},
19+
types::features::{ChannelFeatures, NodeFeatures},
20+
util::logger::Logger,
21+
};
22+
23+
// Imports that need to be added manually
24+
use crate::utils::test_logger::{self};
25+
26+
/// Actual fuzz test, method signature and name are fixed
27+
fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
28+
let mut read_pos = 0;
29+
macro_rules! get_slice {
30+
($len: expr) => {{
31+
let slice_len = $len as usize;
32+
if data.len() < read_pos + slice_len {
33+
return;
34+
}
35+
read_pos += slice_len;
36+
&data[read_pos - slice_len..read_pos]
37+
}};
38+
}
39+
40+
macro_rules! get_u8 {
41+
() => {
42+
get_slice!(1)[0]
43+
};
44+
}
45+
46+
macro_rules! get_u16 {
47+
() => {
48+
match get_slice!(2).try_into() {
49+
Ok(val) => u16::from_be_bytes(val),
50+
Err(_) => return,
51+
}
52+
};
53+
}
54+
55+
macro_rules! get_u32 {
56+
() => {
57+
match get_slice!(4).try_into() {
58+
Ok(val) => u32::from_be_bytes(val),
59+
Err(_) => return,
60+
}
61+
};
62+
}
63+
64+
macro_rules! get_u64 {
65+
() => {
66+
match get_slice!(8).try_into() {
67+
Ok(val) => u64::from_be_bytes(val),
68+
Err(_) => return,
69+
}
70+
};
71+
}
72+
73+
macro_rules! get_bool {
74+
() => {
75+
get_slice!(1)[0] != 0
76+
};
77+
}
78+
79+
macro_rules! get_pubkey {
80+
() => {
81+
match PublicKey::from_slice(get_slice!(33)) {
82+
Ok(val) => val,
83+
Err(_) => return,
84+
}
85+
};
86+
}
87+
88+
let secp_ctx = Secp256k1::new();
89+
let logger: Arc<dyn Logger> = Arc::new(test_logger::TestLogger::new("".to_owned(), out));
90+
91+
let session_priv = match SecretKey::from_slice(get_slice!(32)) {
92+
Ok(val) => val,
93+
Err(_) => return,
94+
};
95+
96+
let payment_id = match get_slice!(32).try_into() {
97+
Ok(val) => PaymentId(val),
98+
Err(_) => return,
99+
};
100+
101+
let mut hops = Vec::<RouteHop>::new();
102+
let hop_count = get_slice!(1)[0] as usize;
103+
for _ in 0..hop_count {
104+
hops.push(RouteHop {
105+
pubkey: get_pubkey!(),
106+
node_features: NodeFeatures::empty(),
107+
short_channel_id: get_u64!(),
108+
channel_features: ChannelFeatures::empty(),
109+
fee_msat: get_u64!(),
110+
cltv_expiry_delta: get_u32!(),
111+
maybe_announced_channel: get_bool!(),
112+
});
113+
}
114+
115+
let blinded_tail = match get_bool!() {
116+
true => {
117+
let mut trampoline_hops = Vec::<TrampolineHop>::new();
118+
let trampoline_hop_count = get_slice!(1)[0] as usize;
119+
for _ in 0..trampoline_hop_count {
120+
trampoline_hops.push(TrampolineHop {
121+
pubkey: get_pubkey!(),
122+
node_features: NodeFeatures::empty(),
123+
fee_msat: get_u64!(),
124+
cltv_expiry_delta: get_u32!(),
125+
});
126+
}
127+
let mut blinded_hops = Vec::<BlindedHop>::new();
128+
let blinded_hop_count = get_slice!(1)[0] as usize;
129+
for _ in 0..blinded_hop_count {
130+
blinded_hops.push(BlindedHop {
131+
blinded_node_id: get_pubkey!(),
132+
encrypted_payload: get_slice!(get_u8!()).to_vec(),
133+
});
134+
}
135+
Some(BlindedTail {
136+
trampoline_hops,
137+
hops: blinded_hops,
138+
blinding_point: get_pubkey!(),
139+
excess_final_cltv_expiry_delta: get_u32!(),
140+
final_value_msat: get_u64!(),
141+
})
142+
},
143+
false => None,
144+
};
145+
146+
let path = Path { hops, blinded_tail };
147+
148+
let htlc_source = HTLCSource::OutboundRoute {
149+
path,
150+
session_priv,
151+
first_hop_htlc_msat: get_u64!(),
152+
payment_id,
153+
};
154+
155+
let failure_len = get_u16!();
156+
let encrypted_packet = OnionErrorPacket { data: get_slice!(failure_len).into() };
157+
158+
lightning::ln::process_onion_failure(&secp_ctx, &logger, &htlc_source, encrypted_packet);
159+
}
160+
161+
/// Method that needs to be added manually, {name}_test
162+
pub fn process_onion_failure_test<Out: test_logger::Output>(data: &[u8], out: Out) {
163+
do_test(data, out);
164+
}
165+
166+
/// Method that needs to be added manually, {name}_run
167+
#[no_mangle]
168+
pub extern "C" fn process_onion_failure_run(data: *const u8, datalen: usize) {
169+
do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull {});
170+
}

fuzz/targets.h

+1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ void bolt11_deser_run(const unsigned char* data, size_t data_len);
1010
void onion_message_run(const unsigned char* data, size_t data_len);
1111
void peer_crypt_run(const unsigned char* data, size_t data_len);
1212
void process_network_graph_run(const unsigned char* data, size_t data_len);
13+
void process_onion_failure_run(const unsigned char* data, size_t data_len);
1314
void refund_deser_run(const unsigned char* data, size_t data_len);
1415
void router_run(const unsigned char* data, size_t data_len);
1516
void zbase32_run(const unsigned char* data, size_t data_len);

0 commit comments

Comments
 (0)