fuzz: Modernize fuzz crate, fix tcp_headers not compiling.
parent
b674f0d0ba
commit
8058a6289f
|
@ -3,21 +3,15 @@ name = "smoltcp-fuzz"
|
|||
version = "0.0.1"
|
||||
authors = ["Automatically generated"]
|
||||
publish = false
|
||||
edition = "2018"
|
||||
|
||||
[package.metadata]
|
||||
cargo-fuzz = true
|
||||
|
||||
[dependencies]
|
||||
libfuzzer-sys = "0.4"
|
||||
getopts = "0.2"
|
||||
|
||||
[dependencies.smoltcp]
|
||||
path = ".."
|
||||
|
||||
[dependencies.libfuzzer-sys]
|
||||
git = "https://github.com/rust-fuzz/libfuzzer-sys.git"
|
||||
|
||||
[profile.release]
|
||||
codegen-units = 1 # needed to prevent weird linker error about sancov guards
|
||||
smoltcp = { path = "..", features = [ "medium-ethernet" ] }
|
||||
|
||||
# Prevent this from interfering with workspaces
|
||||
[workspace]
|
||||
|
@ -26,7 +20,11 @@ members = ["."]
|
|||
[[bin]]
|
||||
name = "packet_parser"
|
||||
path = "fuzz_targets/packet_parser.rs"
|
||||
test = false
|
||||
doc = false
|
||||
|
||||
[[bin]]
|
||||
name = "tcp_headers"
|
||||
path = "fuzz_targets/tcp_headers.rs"
|
||||
test = false
|
||||
doc = false
|
||||
|
|
|
@ -1,8 +1,10 @@
|
|||
#![no_main]
|
||||
#[macro_use] extern crate libfuzzer_sys;
|
||||
extern crate smoltcp;
|
||||
use libfuzzer_sys::fuzz_target;
|
||||
use smoltcp::wire::*;
|
||||
|
||||
fuzz_target!(|data: &[u8]| {
|
||||
use smoltcp::wire::*;
|
||||
format!("{}", PrettyPrinter::<EthernetFrame<&'static [u8]>>::new("", &data));
|
||||
format!(
|
||||
"{}",
|
||||
PrettyPrinter::<EthernetFrame<&'static [u8]>>::new("", &data)
|
||||
);
|
||||
});
|
||||
|
|
|
@ -1,26 +1,20 @@
|
|||
#![no_main]
|
||||
#[macro_use] extern crate libfuzzer_sys;
|
||||
extern crate smoltcp;
|
||||
|
||||
use std as core;
|
||||
extern crate getopts;
|
||||
|
||||
use core::cmp;
|
||||
use libfuzzer_sys::fuzz_target;
|
||||
use smoltcp::iface::{InterfaceBuilder, NeighborCache};
|
||||
use smoltcp::phy::{Loopback, Medium};
|
||||
use smoltcp::wire::{EthernetAddress, EthernetFrame, EthernetProtocol};
|
||||
use smoltcp::wire::{IpAddress, IpCidr, Ipv4Packet, Ipv6Packet, TcpPacket};
|
||||
use smoltcp::iface::{NeighborCache, InterfaceBuilder};
|
||||
use smoltcp::socket::{SocketSet, TcpSocket, TcpSocketBuffer};
|
||||
use smoltcp::time::{Duration, Instant};
|
||||
use smoltcp::wire::{EthernetAddress, EthernetFrame, EthernetProtocol};
|
||||
use smoltcp::wire::{IpAddress, IpCidr, Ipv4Packet, Ipv6Packet, TcpPacket};
|
||||
use std::cmp;
|
||||
|
||||
mod utils {
|
||||
include!("../utils.rs");
|
||||
}
|
||||
#[path = "../utils.rs"]
|
||||
mod utils;
|
||||
|
||||
mod mock {
|
||||
use smoltcp::time::{Duration, Instant};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{Ordering, AtomicUsize};
|
||||
use smoltcp::time::{Duration, Instant};
|
||||
|
||||
// should be AtomicU64 but that's unstable
|
||||
#[derive(Debug, Clone)]
|
||||
|
@ -33,7 +27,8 @@ mod mock {
|
|||
}
|
||||
|
||||
pub fn advance(&self, duration: Duration) {
|
||||
self.0.fetch_add(duration.total_millis() as usize, Ordering::SeqCst);
|
||||
self.0
|
||||
.fetch_add(duration.total_millis() as usize, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
pub fn elapsed(&self) -> Instant {
|
||||
|
@ -52,7 +47,10 @@ impl TcpHeaderFuzzer {
|
|||
//
|
||||
// Otherwise, it replaces the entire rest of the TCP header with the fuzzer's output.
|
||||
pub fn new(data: &[u8]) -> TcpHeaderFuzzer {
|
||||
let copy_len = cmp::min(data.len(), 56 /* max TCP header length without port numbers*/);
|
||||
let copy_len = cmp::min(
|
||||
data.len(),
|
||||
56, /* max TCP header length without port numbers*/
|
||||
);
|
||||
|
||||
let mut fuzzer = TcpHeaderFuzzer([0; 56], copy_len);
|
||||
fuzzer.0[..copy_len].copy_from_slice(&data[..copy_len]);
|
||||
|
@ -68,13 +66,16 @@ impl smoltcp::phy::Fuzzer for TcpHeaderFuzzer {
|
|||
|
||||
let tcp_packet_offset = {
|
||||
let eth_frame = EthernetFrame::new_unchecked(&frame_data);
|
||||
EthernetFrame::<&mut [u8]>::header_len() + match eth_frame.ethertype() {
|
||||
EthernetProtocol::Ipv4 =>
|
||||
Ipv4Packet::new_unchecked(eth_frame.payload()).header_len() as usize,
|
||||
EthernetProtocol::Ipv6 =>
|
||||
Ipv6Packet::new_unchecked(eth_frame.payload()).header_len() as usize,
|
||||
_ => return
|
||||
}
|
||||
EthernetFrame::<&mut [u8]>::header_len()
|
||||
+ match eth_frame.ethertype() {
|
||||
EthernetProtocol::Ipv4 => {
|
||||
Ipv4Packet::new_unchecked(eth_frame.payload()).header_len() as usize
|
||||
}
|
||||
EthernetProtocol::Ipv6 => {
|
||||
Ipv6Packet::new_unchecked(eth_frame.payload()).header_len() as usize
|
||||
}
|
||||
_ => return,
|
||||
}
|
||||
};
|
||||
|
||||
let tcp_is_syn = {
|
||||
|
@ -95,7 +96,7 @@ impl smoltcp::phy::Fuzzer for TcpHeaderFuzzer {
|
|||
(tcp_packet[12] as usize >> 4) * 4
|
||||
};
|
||||
|
||||
let tcp_packet = &mut frame_data[tcp_packet_offset+4..];
|
||||
let tcp_packet = &mut frame_data[tcp_packet_offset + 4..];
|
||||
|
||||
let replacement_data = &self.0[..self.1];
|
||||
let copy_len = cmp::min(replacement_data.len(), tcp_header_len);
|
||||
|
@ -114,17 +115,17 @@ fuzz_target!(|data: &[u8]| {
|
|||
let clock = mock::Clock::new();
|
||||
|
||||
let device = {
|
||||
|
||||
let (mut opts, mut free) = utils::create_options();
|
||||
utils::add_middleware_options(&mut opts, &mut free);
|
||||
|
||||
let mut matches = utils::parse_options(&opts, free);
|
||||
let device = utils::parse_middleware_options(&mut matches, Loopback::new(Medium::Ethernet),
|
||||
/*loopback=*/true);
|
||||
let device = utils::parse_middleware_options(
|
||||
&mut matches,
|
||||
Loopback::new(Medium::Ethernet),
|
||||
/*loopback=*/ true,
|
||||
);
|
||||
|
||||
smoltcp::phy::FuzzInjector::new(device,
|
||||
EmptyFuzzer(),
|
||||
TcpHeaderFuzzer::new(data))
|
||||
smoltcp::phy::FuzzInjector::new(device, EmptyFuzzer(), TcpHeaderFuzzer::new(data))
|
||||
};
|
||||
|
||||
let mut neighbor_cache_entries = [None; 8];
|
||||
|
@ -132,10 +133,10 @@ fuzz_target!(|data: &[u8]| {
|
|||
|
||||
let ip_addrs = [IpCidr::new(IpAddress::v4(127, 0, 0, 1), 8)];
|
||||
let mut iface = InterfaceBuilder::new(device)
|
||||
.ethernet_addr(EthernetAddress::default())
|
||||
.neighbor_cache(neighbor_cache)
|
||||
.ip_addrs(ip_addrs)
|
||||
.finalize();
|
||||
.ethernet_addr(EthernetAddress::default())
|
||||
.neighbor_cache(neighbor_cache)
|
||||
.ip_addrs(ip_addrs)
|
||||
.finalize();
|
||||
|
||||
let server_socket = {
|
||||
// It is not strictly necessary to use a `static mut` and unsafe code here, but
|
||||
|
@ -162,7 +163,7 @@ fuzz_target!(|data: &[u8]| {
|
|||
let server_handle = socket_set.add(server_socket);
|
||||
let client_handle = socket_set.add(client_socket);
|
||||
|
||||
let mut did_listen = false;
|
||||
let mut did_listen = false;
|
||||
let mut did_connect = false;
|
||||
let mut done = false;
|
||||
while !done && clock.elapsed() < Instant::from_millis(4_000) {
|
||||
|
@ -187,24 +188,28 @@ fuzz_target!(|data: &[u8]| {
|
|||
let mut socket = socket_set.get::<TcpSocket>(client_handle);
|
||||
if !socket.is_open() {
|
||||
if !did_connect {
|
||||
socket.connect((IpAddress::v4(127, 0, 0, 1), 1234),
|
||||
(IpAddress::Unspecified, 65000)).unwrap();
|
||||
socket
|
||||
.connect(
|
||||
(IpAddress::v4(127, 0, 0, 1), 1234),
|
||||
(IpAddress::Unspecified, 65000),
|
||||
)
|
||||
.unwrap();
|
||||
did_connect = true;
|
||||
}
|
||||
}
|
||||
|
||||
if socket.can_send() {
|
||||
socket.send_slice(b"0123456789abcdef0123456789abcdef0123456789abcdef").unwrap();
|
||||
socket
|
||||
.send_slice(b"0123456789abcdef0123456789abcdef0123456789abcdef")
|
||||
.unwrap();
|
||||
socket.close();
|
||||
}
|
||||
}
|
||||
|
||||
match iface.poll_delay(&socket_set, clock.elapsed()) {
|
||||
Some(Duration { millis: 0 }) => {},
|
||||
Some(delay) => {
|
||||
clock.advance(delay)
|
||||
},
|
||||
None => clock.advance(Duration::from_millis(1))
|
||||
Some(Duration { millis: 0 }) => {}
|
||||
Some(delay) => clock.advance(delay),
|
||||
None => clock.advance(Duration::from_millis(1)),
|
||||
}
|
||||
}
|
||||
});
|
||||
|
|
144
fuzz/utils.rs
144
fuzz/utils.rs
|
@ -1,18 +1,17 @@
|
|||
// TODO: this is literally a copy of examples/utils.rs, but without an allow dead code attribute.
|
||||
// The include logic does not allow having attributes in included files.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::str::{self, FromStr};
|
||||
use std::rc::Rc;
|
||||
use std::io;
|
||||
use std::fs::File;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
use getopts::{Matches, Options};
|
||||
use std::env;
|
||||
use std::fs::File;
|
||||
use std::io;
|
||||
use std::io::Write;
|
||||
use std::process;
|
||||
use getopts::{Options, Matches};
|
||||
use std::str::{self, FromStr};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use smoltcp::phy::{Device, EthernetTracer, FaultInjector};
|
||||
use smoltcp::phy::{PcapWriter, PcapSink, PcapMode, PcapLinkType};
|
||||
use smoltcp::phy::{Device, FaultInjector, Tracer};
|
||||
use smoltcp::phy::{PcapMode, PcapWriter};
|
||||
use smoltcp::time::Duration;
|
||||
|
||||
pub fn create_options() -> (Options, Vec<&'static str>) {
|
||||
|
@ -29,10 +28,17 @@ pub fn parse_options(options: &Options, free: Vec<&str>) -> Matches {
|
|||
}
|
||||
Ok(matches) => {
|
||||
if matches.opt_present("h") || matches.free.len() != free.len() {
|
||||
let brief = format!("Usage: {} [OPTION]... {}",
|
||||
env::args().nth(0).unwrap(), free.join(" "));
|
||||
let brief = format!(
|
||||
"Usage: {} [OPTION]... {}",
|
||||
env::args().nth(0).unwrap(),
|
||||
free.join(" ")
|
||||
);
|
||||
print!("{}", options.usage(&brief));
|
||||
process::exit(if matches.free.len() != free.len() { 1 } else { 0 })
|
||||
process::exit(if matches.free.len() != free.len() {
|
||||
1
|
||||
} else {
|
||||
0
|
||||
})
|
||||
}
|
||||
matches
|
||||
}
|
||||
|
@ -41,46 +47,102 @@ pub fn parse_options(options: &Options, free: Vec<&str>) -> Matches {
|
|||
|
||||
pub fn add_middleware_options(opts: &mut Options, _free: &mut Vec<&str>) {
|
||||
opts.optopt("", "pcap", "Write a packet capture file", "FILE");
|
||||
opts.optopt("", "drop-chance", "Chance of dropping a packet (%)", "CHANCE");
|
||||
opts.optopt("", "corrupt-chance", "Chance of corrupting a packet (%)", "CHANCE");
|
||||
opts.optopt("", "size-limit", "Drop packets larger than given size (octets)", "SIZE");
|
||||
opts.optopt("", "tx-rate-limit", "Drop packets after transmit rate exceeds given limit \
|
||||
(packets per interval)", "RATE");
|
||||
opts.optopt("", "rx-rate-limit", "Drop packets after transmit rate exceeds given limit \
|
||||
(packets per interval)", "RATE");
|
||||
opts.optopt("", "shaping-interval", "Sets the interval for rate limiting (ms)", "RATE");
|
||||
opts.optopt(
|
||||
"",
|
||||
"drop-chance",
|
||||
"Chance of dropping a packet (%)",
|
||||
"CHANCE",
|
||||
);
|
||||
opts.optopt(
|
||||
"",
|
||||
"corrupt-chance",
|
||||
"Chance of corrupting a packet (%)",
|
||||
"CHANCE",
|
||||
);
|
||||
opts.optopt(
|
||||
"",
|
||||
"size-limit",
|
||||
"Drop packets larger than given size (octets)",
|
||||
"SIZE",
|
||||
);
|
||||
opts.optopt(
|
||||
"",
|
||||
"tx-rate-limit",
|
||||
"Drop packets after transmit rate exceeds given limit \
|
||||
(packets per interval)",
|
||||
"RATE",
|
||||
);
|
||||
opts.optopt(
|
||||
"",
|
||||
"rx-rate-limit",
|
||||
"Drop packets after transmit rate exceeds given limit \
|
||||
(packets per interval)",
|
||||
"RATE",
|
||||
);
|
||||
opts.optopt(
|
||||
"",
|
||||
"shaping-interval",
|
||||
"Sets the interval for rate limiting (ms)",
|
||||
"RATE",
|
||||
);
|
||||
}
|
||||
|
||||
pub fn parse_middleware_options<D>(matches: &mut Matches, device: D, loopback: bool)
|
||||
-> FaultInjector<EthernetTracer<PcapWriter<D, Rc<PcapSink>>>>
|
||||
where D: for<'a> Device<'a>
|
||||
pub fn parse_middleware_options<D>(
|
||||
matches: &mut Matches,
|
||||
device: D,
|
||||
loopback: bool,
|
||||
) -> FaultInjector<Tracer<PcapWriter<D, Box<dyn Write>>>>
|
||||
where
|
||||
D: for<'a> Device<'a>,
|
||||
{
|
||||
let drop_chance = matches.opt_str("drop-chance").map(|s| u8::from_str(&s).unwrap())
|
||||
.unwrap_or(0);
|
||||
let corrupt_chance = matches.opt_str("corrupt-chance").map(|s| u8::from_str(&s).unwrap())
|
||||
.unwrap_or(0);
|
||||
let size_limit = matches.opt_str("size-limit").map(|s| usize::from_str(&s).unwrap())
|
||||
.unwrap_or(0);
|
||||
let tx_rate_limit = matches.opt_str("tx-rate-limit").map(|s| u64::from_str(&s).unwrap())
|
||||
.unwrap_or(0);
|
||||
let rx_rate_limit = matches.opt_str("rx-rate-limit").map(|s| u64::from_str(&s).unwrap())
|
||||
.unwrap_or(0);
|
||||
let shaping_interval = matches.opt_str("shaping-interval").map(|s| u64::from_str(&s).unwrap())
|
||||
.unwrap_or(0);
|
||||
let drop_chance = matches
|
||||
.opt_str("drop-chance")
|
||||
.map(|s| u8::from_str(&s).unwrap())
|
||||
.unwrap_or(0);
|
||||
let corrupt_chance = matches
|
||||
.opt_str("corrupt-chance")
|
||||
.map(|s| u8::from_str(&s).unwrap())
|
||||
.unwrap_or(0);
|
||||
let size_limit = matches
|
||||
.opt_str("size-limit")
|
||||
.map(|s| usize::from_str(&s).unwrap())
|
||||
.unwrap_or(0);
|
||||
let tx_rate_limit = matches
|
||||
.opt_str("tx-rate-limit")
|
||||
.map(|s| u64::from_str(&s).unwrap())
|
||||
.unwrap_or(0);
|
||||
let rx_rate_limit = matches
|
||||
.opt_str("rx-rate-limit")
|
||||
.map(|s| u64::from_str(&s).unwrap())
|
||||
.unwrap_or(0);
|
||||
let shaping_interval = matches
|
||||
.opt_str("shaping-interval")
|
||||
.map(|s| u64::from_str(&s).unwrap())
|
||||
.unwrap_or(0);
|
||||
|
||||
let pcap_writer: Box<io::Write>;
|
||||
let pcap_writer: Box<dyn io::Write>;
|
||||
if let Some(pcap_filename) = matches.opt_str("pcap") {
|
||||
pcap_writer = Box::new(File::create(pcap_filename).expect("cannot open file"))
|
||||
} else {
|
||||
pcap_writer = Box::new(io::sink())
|
||||
}
|
||||
|
||||
let seed = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().subsec_nanos();
|
||||
let seed = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.subsec_nanos();
|
||||
|
||||
let device = PcapWriter::new(device, Rc::new(RefCell::new(pcap_writer)) as Rc<PcapSink>,
|
||||
if loopback { PcapMode::TxOnly } else { PcapMode::Both },
|
||||
PcapLinkType::Ethernet);
|
||||
let device = EthernetTracer::new(device, |_timestamp, _printer| {
|
||||
let device = PcapWriter::new(
|
||||
device,
|
||||
pcap_writer,
|
||||
if loopback {
|
||||
PcapMode::TxOnly
|
||||
} else {
|
||||
PcapMode::Both
|
||||
},
|
||||
);
|
||||
|
||||
let device = Tracer::new(device, |_timestamp, _printer| {
|
||||
#[cfg(feature = "log")]
|
||||
trace!("{}", _printer);
|
||||
});
|
||||
|
|
Loading…
Reference in New Issue