parent
1bdf155ead
commit
4f4b209103
|
@ -7,12 +7,18 @@ publish = false
|
|||
[package.metadata]
|
||||
cargo-fuzz = true
|
||||
|
||||
[dependencies]
|
||||
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
|
||||
|
||||
# Prevent this from interfering with workspaces
|
||||
[workspace]
|
||||
members = ["."]
|
||||
|
@ -20,3 +26,7 @@ members = ["."]
|
|||
[[bin]]
|
||||
name = "packet_parser"
|
||||
path = "fuzz_targets/packet_parser.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "tcp_headers"
|
||||
path = "fuzz_targets/tcp_headers.rs"
|
||||
|
|
|
@ -0,0 +1,209 @@
|
|||
#![no_main]
|
||||
#[macro_use] extern crate libfuzzer_sys;
|
||||
extern crate smoltcp;
|
||||
|
||||
use std as core;
|
||||
extern crate getopts;
|
||||
|
||||
use core::cmp;
|
||||
use smoltcp::phy::Loopback;
|
||||
use smoltcp::wire::{EthernetAddress, EthernetFrame, EthernetProtocol};
|
||||
use smoltcp::wire::{IpAddress, IpCidr, Ipv4Packet, Ipv6Packet, TcpPacket};
|
||||
use smoltcp::iface::{NeighborCache, EthernetInterfaceBuilder};
|
||||
use smoltcp::socket::{SocketSet, TcpSocket, TcpSocketBuffer};
|
||||
use smoltcp::time::{Duration, Instant};
|
||||
|
||||
mod utils {
|
||||
include!("../utils.rs");
|
||||
}
|
||||
|
||||
mod mock {
|
||||
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)]
|
||||
pub struct Clock(Arc<AtomicUsize>);
|
||||
|
||||
impl Clock {
|
||||
pub fn new() -> Clock {
|
||||
Clock(Arc::new(AtomicUsize::new(0)))
|
||||
}
|
||||
|
||||
pub fn advance(&self, duration: Duration) {
|
||||
self.0.fetch_add(duration.total_millis() as usize, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
pub fn elapsed(&self) -> Instant {
|
||||
Instant::from_millis(self.0.load(Ordering::SeqCst) as i64)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct TcpHeaderFuzzer([u8; 56], usize);
|
||||
|
||||
impl TcpHeaderFuzzer {
|
||||
// The fuzzer won't fuzz any packets with the SYN flag set in order to make sure the connection
|
||||
// is established before the fuzzed headers arrive.
|
||||
//
|
||||
// It will also not fuzz the source and dest port so it reaches the open socket.
|
||||
//
|
||||
// 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 mut fuzzer = TcpHeaderFuzzer([0; 56], copy_len);
|
||||
fuzzer.0[..copy_len].copy_from_slice(&data[..copy_len]);
|
||||
fuzzer
|
||||
}
|
||||
}
|
||||
|
||||
impl smoltcp::phy::Fuzzer for TcpHeaderFuzzer {
|
||||
fn fuzz_packet(&self, frame_data: &mut [u8]) {
|
||||
if self.1 == 0 {
|
||||
return;
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
};
|
||||
|
||||
let tcp_is_syn = {
|
||||
let tcp_packet = TcpPacket::new_checked(&frame_data[tcp_packet_offset..]).unwrap();
|
||||
tcp_packet.syn()
|
||||
};
|
||||
|
||||
if tcp_is_syn {
|
||||
return;
|
||||
}
|
||||
|
||||
if !frame_data.ends_with(b"abcdef") {
|
||||
return;
|
||||
}
|
||||
|
||||
let tcp_header_len = {
|
||||
let tcp_packet = &frame_data[tcp_packet_offset..];
|
||||
(tcp_packet[12] as usize >> 4) * 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);
|
||||
assert!(copy_len < tcp_packet.len());
|
||||
tcp_packet[..copy_len].copy_from_slice(&replacement_data[..copy_len]);
|
||||
}
|
||||
}
|
||||
|
||||
struct EmptyFuzzer();
|
||||
|
||||
impl smoltcp::phy::Fuzzer for EmptyFuzzer {
|
||||
fn fuzz_packet(&self, _: &mut [u8]) {}
|
||||
}
|
||||
|
||||
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(),
|
||||
/*loopback=*/true);
|
||||
|
||||
smoltcp::phy::FuzzInjector::new(device,
|
||||
EmptyFuzzer(),
|
||||
TcpHeaderFuzzer::new(data))
|
||||
};
|
||||
|
||||
let mut neighbor_cache_entries = [None; 8];
|
||||
let neighbor_cache = NeighborCache::new(&mut neighbor_cache_entries[..]);
|
||||
|
||||
let ip_addrs = [IpCidr::new(IpAddress::v4(127, 0, 0, 1), 8)];
|
||||
let mut iface = EthernetInterfaceBuilder::new(device)
|
||||
.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
|
||||
// on embedded systems that smoltcp targets it is far better to allocate the data
|
||||
// statically to verify that it fits into RAM rather than get undefined behavior
|
||||
// when stack overflows.
|
||||
static mut TCP_SERVER_RX_DATA: [u8; 1024] = [0; 1024];
|
||||
static mut TCP_SERVER_TX_DATA: [u8; 1024] = [0; 1024];
|
||||
let tcp_rx_buffer = TcpSocketBuffer::new(unsafe { &mut TCP_SERVER_RX_DATA[..] });
|
||||
let tcp_tx_buffer = TcpSocketBuffer::new(unsafe { &mut TCP_SERVER_TX_DATA[..] });
|
||||
TcpSocket::new(tcp_rx_buffer, tcp_tx_buffer)
|
||||
};
|
||||
|
||||
let client_socket = {
|
||||
static mut TCP_CLIENT_RX_DATA: [u8; 1024] = [0; 1024];
|
||||
static mut TCP_CLIENT_TX_DATA: [u8; 1024] = [0; 1024];
|
||||
let tcp_rx_buffer = TcpSocketBuffer::new(unsafe { &mut TCP_CLIENT_RX_DATA[..] });
|
||||
let tcp_tx_buffer = TcpSocketBuffer::new(unsafe { &mut TCP_CLIENT_TX_DATA[..] });
|
||||
TcpSocket::new(tcp_rx_buffer, tcp_tx_buffer)
|
||||
};
|
||||
|
||||
let mut socket_set_entries: [_; 2] = Default::default();
|
||||
let mut socket_set = SocketSet::new(&mut socket_set_entries[..]);
|
||||
let server_handle = socket_set.add(server_socket);
|
||||
let client_handle = socket_set.add(client_socket);
|
||||
|
||||
let mut did_listen = false;
|
||||
let mut did_connect = false;
|
||||
let mut done = false;
|
||||
while !done && clock.elapsed() < Instant::from_millis(4_000) {
|
||||
let _ = iface.poll(&mut socket_set, clock.elapsed());
|
||||
|
||||
{
|
||||
let mut socket = socket_set.get::<TcpSocket>(server_handle);
|
||||
if !socket.is_active() && !socket.is_listening() {
|
||||
if !did_listen {
|
||||
socket.listen(1234).unwrap();
|
||||
did_listen = true;
|
||||
}
|
||||
}
|
||||
|
||||
if socket.can_recv() {
|
||||
socket.close();
|
||||
done = true;
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
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();
|
||||
did_connect = true;
|
||||
}
|
||||
}
|
||||
|
||||
if socket.can_send() {
|
||||
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))
|
||||
}
|
||||
}
|
||||
});
|
|
@ -0,0 +1,95 @@
|
|||
// 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 std::env;
|
||||
use std::process;
|
||||
use getopts::{Options, Matches};
|
||||
|
||||
use smoltcp::phy::{Device, EthernetTracer, FaultInjector};
|
||||
use smoltcp::phy::{PcapWriter, PcapSink, PcapMode, PcapLinkType};
|
||||
use smoltcp::time::Duration;
|
||||
|
||||
pub fn create_options() -> (Options, Vec<&'static str>) {
|
||||
let mut opts = Options::new();
|
||||
opts.optflag("h", "help", "print this help menu");
|
||||
(opts, Vec::new())
|
||||
}
|
||||
|
||||
pub fn parse_options(options: &Options, free: Vec<&str>) -> Matches {
|
||||
match options.parse(env::args().skip(1)) {
|
||||
Err(err) => {
|
||||
println!("{}", err);
|
||||
process::exit(1)
|
||||
}
|
||||
Ok(matches) => {
|
||||
if matches.opt_present("h") || matches.free.len() != free.len() {
|
||||
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 })
|
||||
}
|
||||
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");
|
||||
}
|
||||
|
||||
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>
|
||||
{
|
||||
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>;
|
||||
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 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| {
|
||||
#[cfg(feature = "log")]
|
||||
trace!("{}", _printer);
|
||||
});
|
||||
let mut device = FaultInjector::new(device, seed);
|
||||
device.set_drop_chance(drop_chance);
|
||||
device.set_corrupt_chance(corrupt_chance);
|
||||
device.set_max_packet_size(size_limit);
|
||||
device.set_max_tx_rate(tx_rate_limit);
|
||||
device.set_max_rx_rate(rx_rate_limit);
|
||||
device.set_bucket_interval(Duration::from_millis(shaping_interval));
|
||||
device
|
||||
}
|
Loading…
Reference in New Issue