rust-lightning/fuzz/fuzz_targets/peer_crypt_target.rs
Matt Corallo 1d2774dd64 Add some fuzz targets.
Sadly none of them are really any good without some hand-holding to
generate good input data, and unless sha256 gets stubbed out I'm
not sure they're gonna get good without a symbolic execution fuzzer
2018-03-23 13:16:24 -04:00

124 lines
2.6 KiB
Rust

extern crate lightning;
extern crate secp256k1;
use lightning::ln::peer_channel_encryptor::PeerChannelEncryptor;
use secp256k1::key::{PublicKey,SecretKey};
use secp256k1::Secp256k1;
#[inline]
fn slice_to_be16(v: &[u8]) -> u16 {
((v[0] as u16) << 8*1) |
((v[1] as u16) << 8*0)
}
#[inline]
pub fn do_test(data: &[u8]) {
let mut read_pos = 0;
macro_rules! get_slice {
($len: expr) => {
{
let slice_len = $len as usize;
if data.len() < read_pos + slice_len {
return;
}
read_pos += slice_len;
&data[read_pos - slice_len..read_pos]
}
}
}
let secp_ctx = Secp256k1::new();
let our_network_key = match SecretKey::from_slice(&secp_ctx, get_slice!(32)) {
Ok(key) => key,
Err(_) => return,
};
let mut crypter = if get_slice!(1)[0] != 0 {
let their_pubkey = match PublicKey::from_slice(&secp_ctx, get_slice!(33)) {
Ok(key) => key,
Err(_) => return,
};
let mut crypter = PeerChannelEncryptor::new_outbound(their_pubkey);
crypter.get_act_one();
match crypter.process_act_two(get_slice!(50), &our_network_key) {
Ok(_) => {},
Err(_) => return,
}
assert!(crypter.is_ready_for_encryption());
crypter
} else {
let mut crypter = PeerChannelEncryptor::new_inbound(&our_network_key);
match crypter.process_act_one_with_key(get_slice!(50), &our_network_key) {
Ok(_) => {},
Err(_) => return,
}
match crypter.process_act_three(get_slice!(66)) {
Ok(_) => {},
Err(_) => return,
}
assert!(crypter.is_ready_for_encryption());
crypter
};
loop {
if get_slice!(1)[0] == 0 {
crypter.encrypt_message(get_slice!(slice_to_be16(get_slice!(2))));
} else {
let len = match crypter.decrypt_length_header(get_slice!(16+2)) {
Ok(len) => len,
Err(_) => return,
};
match crypter.decrypt_message(get_slice!(len as usize + 16)) {
Ok(_) => {},
Err(_) => return,
}
}
}
}
#[cfg(feature = "afl")]
extern crate afl;
#[cfg(feature = "afl")]
fn main() {
afl::read_stdio_bytes(|data| {
do_test(&data);
});
}
#[cfg(feature = "honggfuzz")]
#[macro_use] extern crate honggfuzz;
#[cfg(feature = "honggfuzz")]
fn main() {
loop {
fuzz!(|data| {
do_test(data);
});
}
}
#[cfg(test)]
mod tests {
fn extend_vec_from_hex(hex: &str, out: &mut Vec<u8>) {
let mut b = 0;
for (idx, c) in hex.as_bytes().iter().enumerate() {
b <<= 4;
match *c {
b'A'...b'F' => b |= c - b'A' + 10,
b'a'...b'f' => b |= c - b'a' + 10,
b'0'...b'9' => b |= c - b'0',
_ => panic!("Bad hex"),
}
if (idx & 1) == 1 {
out.push(b);
b = 0;
}
}
}
#[test]
fn duplicate_crash() {
let mut a = Vec::new();
extend_vec_from_hex("01", &mut a);
super::do_test(&a);
}
}