Skip to content

Commit

Permalink
fuzz: Modernize fuzz crate, fix tcp_headers not compiling.
Browse files Browse the repository at this point in the history
  • Loading branch information
Dirbaio committed Oct 3, 2021
1 parent dfe8265 commit a5e4e5a
Show file tree
Hide file tree
Showing 4 changed files with 165 additions and 98 deletions.
16 changes: 7 additions & 9 deletions fuzz/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand All @@ -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
10 changes: 6 additions & 4 deletions fuzz/fuzz_targets/packet_parser.rs
Original file line number Diff line number Diff line change
@@ -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)
);
});
93 changes: 49 additions & 44 deletions fuzz/fuzz_targets/tcp_headers.rs
Original file line number Diff line number Diff line change
@@ -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)]
Expand All @@ -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 {
Expand All @@ -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]);
Expand All @@ -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 = {
Expand All @@ -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);
Expand All @@ -114,28 +115,28 @@ 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];
let neighbor_cache = NeighborCache::new(&mut neighbor_cache_entries[..]);

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
Expand All @@ -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) {
Expand All @@ -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)),
}
}
});
Loading

0 comments on commit a5e4e5a

Please sign in to comment.