Skip to content

Commit fe4bcd7

Browse files
committed
fuzz
1 parent ad05cca commit fe4bcd7

10 files changed

+315
-9
lines changed

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

+167
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
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, Features, NodeFeatures},
20+
util::{logger::Logger, test_utils::TestLogger},
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+
let secp_ctx = Secp256k1::new();
41+
42+
let logger: Arc<dyn Logger> = Arc::new(test_logger::TestLogger::new("".to_owned(), out));
43+
44+
macro_rules! get_u64 {
45+
() => {
46+
match get_slice!(8).try_into() {
47+
Ok(val) => u64::from_be_bytes(val),
48+
Err(_) => return,
49+
}
50+
};
51+
}
52+
53+
macro_rules! get_u32 {
54+
() => {
55+
match get_slice!(4).try_into() {
56+
Ok(val) => u32::from_be_bytes(val),
57+
Err(_) => return,
58+
}
59+
};
60+
}
61+
62+
macro_rules! get_bool {
63+
() => {
64+
get_slice!(1)[0] != 0
65+
};
66+
}
67+
68+
macro_rules! get_u8 {
69+
() => {
70+
get_slice!(1)[0]
71+
};
72+
}
73+
74+
let session_priv = match SecretKey::from_slice(get_slice!(32)) {
75+
Ok(val) => val,
76+
Err(_) => return,
77+
};
78+
79+
let payment_id = match get_slice!(32).try_into() {
80+
Ok(val) => PaymentId(val),
81+
Err(_) => return,
82+
};
83+
84+
macro_rules! get_pubkey {
85+
() => {
86+
match PublicKey::from_slice(get_slice!(33)) {
87+
Ok(val) => val,
88+
Err(_) => return,
89+
}
90+
};
91+
}
92+
93+
let mut hops = Vec::<RouteHop>::new();
94+
let hop_count = get_slice!(1)[0] as usize;
95+
for i in 0..hop_count {
96+
hops.push(RouteHop {
97+
pubkey: get_pubkey!(),
98+
node_features: NodeFeatures::empty(),
99+
short_channel_id: get_u64!(),
100+
channel_features: ChannelFeatures::empty(),
101+
fee_msat: get_u64!(),
102+
cltv_expiry_delta: get_u32!(),
103+
maybe_announced_channel: get_bool!(),
104+
});
105+
}
106+
107+
let blinded_tail = match get_bool!() {
108+
true => {
109+
let mut trampoline_hops = Vec::<TrampolineHop>::new();
110+
let trampoline_hop_count = get_slice!(1)[0] as usize;
111+
for i in 0..trampoline_hop_count {
112+
trampoline_hops.push(TrampolineHop {
113+
pubkey: get_pubkey!(),
114+
node_features: NodeFeatures::empty(),
115+
fee_msat: get_u64!(),
116+
cltv_expiry_delta: get_u32!(),
117+
});
118+
}
119+
let mut blinded_hops = Vec::<BlindedHop>::new();
120+
let blinded_hop_count = get_slice!(1)[0] as usize;
121+
for i in 0..blinded_hop_count {
122+
blinded_hops.push(BlindedHop {
123+
blinded_node_id: get_pubkey!(),
124+
encrypted_payload: get_slice!(get_u8!()).to_vec(),
125+
});
126+
}
127+
Some(BlindedTail {
128+
trampoline_hops,
129+
hops: blinded_hops,
130+
blinding_point: get_pubkey!(),
131+
excess_final_cltv_expiry_delta: get_u32!(),
132+
final_value_msat: get_u64!(),
133+
})
134+
},
135+
false => None,
136+
};
137+
138+
let path = Path { hops, blinded_tail };
139+
140+
let htlc_source = HTLCSource::OutboundRoute {
141+
path,
142+
session_priv,
143+
first_hop_htlc_msat: get_u64!(),
144+
payment_id,
145+
};
146+
147+
let failure_len = u16::from_be_bytes(get_slice!(2).try_into().unwrap());
148+
let encrypted_packet = OnionErrorPacket { data: get_slice!(failure_len as u64).into() };
149+
150+
lightning::ln::onion_utils::process_onion_failure(
151+
&secp_ctx,
152+
&logger,
153+
&htlc_source,
154+
encrypted_packet,
155+
);
156+
}
157+
158+
/// Method that needs to be added manually, {name}_test
159+
pub fn process_onion_failure_test<Out: test_logger::Output>(data: &[u8], out: Out) {
160+
do_test(data, out);
161+
}
162+
163+
/// Method that needs to be added manually, {name}_run
164+
#[no_mangle]
165+
pub extern "C" fn process_onion_failure_run(data: *const u8, datalen: usize) {
166+
do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull {});
167+
}

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);

lightning/src/ln/channelmanager.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -678,7 +678,7 @@ impl_writeable_tlv_based_enum!(SentHTLCId,
678678
/// Tracks the inbound corresponding to an outbound HTLC
679679
#[allow(clippy::derive_hash_xor_eq)] // Our Hash is faithful to the data, we just don't have SecretKey::hash
680680
#[derive(Clone, Debug, PartialEq, Eq)]
681-
pub(crate) enum HTLCSource {
681+
pub enum HTLCSource {
682682
PreviousHopData(HTLCPreviousHopData),
683683
OutboundRoute {
684684
path: Path,

lightning/src/ln/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ pub mod channel;
3939
#[cfg(not(fuzzing))]
4040
pub(crate) mod channel;
4141

42-
pub(crate) mod onion_utils;
42+
pub mod onion_utils;
4343
mod outbound_payment;
4444
pub mod wire;
4545

lightning/src/ln/msgs.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -2350,10 +2350,10 @@ impl Debug for TrampolineOnionPacket {
23502350
}
23512351

23522352
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
2353-
pub(crate) struct OnionErrorPacket {
2353+
pub struct OnionErrorPacket {
23542354
// This really should be a constant size slice, but the spec lets these things be up to 128KB?
23552355
// (TODO) We limit it in decode to much lower...
2356-
pub(crate) data: Vec<u8>,
2356+
pub data: Vec<u8>,
23572357
}
23582358

23592359
impl From<UpdateFailHTLC> for OnionErrorPacket {

0 commit comments

Comments
 (0)