Skip to content
systemcoding.dev
Security

Fuzz Rust Parsers and Unsafe Code With cargo-fuzz

Set up cargo-fuzz 0.13 on a Rust nightly toolchain, fuzz a parser that uses unsafe code, read the crash report and replay, minimize and keep the failing input.

8 min read
Summarize in AI
Flat illustration of a debugger stopped at a breakpoint beside the register values, with the Rust, LLVM and GNU logos.

Safe Rust turns an out-of-bounds index into a panic instead of memory corruption, so it is tempting to think fuzzing is for C. It is not. Panics are denial-of-service bugs in a server, unsafe blocks bring back every memory error the language otherwise prevents, and logic errors in a parser look the same in any language. cargo-fuzz is the standard way to fuzz Rust: a Cargo subcommand that wraps libFuzzer, generates the project layout and runs your target with coverage feedback and AddressSanitizer. This post sets it up with cargo-fuzz 0.13 on a nightly toolchain, fuzzes a small parser that contains one unsafe shortcut, reads the report, and keeps the failing input as a regression test.

You need to be comfortable with cargo build and cargo test. No fuzzing background is assumed; the earlier post on what fuzzing is covers the idea.

Install and initialize

cargo-fuzz needs a nightly compiler because it uses the sanitizer and coverage instrumentation flags that are not stable. Install both once:

Shell
rustup toolchain install nightly
cargo install cargo-fuzz

Create the library you want to test. The fuzz setup is added beside it, in a fuzz directory that is its own small crate.

Shell
cargo new --lib recparse
cd recparse
cargo fuzz init

cargo fuzz init creates three things: fuzz/Cargo.toml, which depends on libfuzzer-sys and on your crate by path, fuzz/fuzz_targets/fuzz_target_1.rs, a starting harness, and a .gitignore for the build output. The fuzz directory is a separate crate on purpose, because the fuzz build uses different compiler flags from your normal build and must not disturb it.

The code under test

The library parses a message with a type byte and a length-prefixed payload. The author used get_unchecked to avoid a bounds check in a hot path, which is the sort of shortcut that appears in real parsers and is exactly what a fuzzer is good at punishing.

src/lib.rsrust
/// A parsed message: a type tag and a payload slice.
#[derive(Debug, PartialEq)]
pub struct Message<'a> {
    pub kind: u8,
    pub payload: &'a [u8],
}

pub fn parse(data: &[u8]) -> Option<Message<'_>> {
    if data.len() < 2 {
        return None;
    }
    let kind = data[0];
    let len = data[1] as usize;

    // Bug: len is not checked against what remains of the input.
    let payload = unsafe { data.get_unchecked(2..2 + len) };
    Some(Message { kind, payload })
}

get_unchecked on a range promises the compiler that the range is valid. If 2 + len exceeds the input length, the promise is false and the behavior is undefined. In a release build this reads memory beyond the slice, and an ordinary cargo test with a few well-formed inputs would never show it.

Write the harness

Open fuzz/fuzz_targets/fuzz_target_1.rs and replace the generated body. The fuzz_target! macro from libfuzzer-sys defines the entry point, and the closure receives the raw bytes.

fuzz/fuzz_targets/fuzz_target_1.rsrust
#![no_main]

use libfuzzer_sys::fuzz_target;

fuzz_target!(|data: &[u8]| {
    if let Some(msg) = recparse::parse(data) {
        // Touch every payload byte so an invalid slice is actually read.
        let mut sum = 0u8;
        for b in msg.payload {
            sum = sum.wrapping_add(*b);
        }
        std::hint::black_box(sum);
    }
});

Two choices here are worth copying. The harness reads every byte of the returned slice, because an invalid slice that is never read is silent. And it uses std::hint::black_box so the optimizer cannot delete the loop as dead code.

Run it

Shell
cargo +nightly fuzz run fuzz_target_1

cargo-fuzz builds the target with AddressSanitizer by default and runs libFuzzer. With the empty starting corpus, the fuzzer learns quickly that a second byte larger than the remaining length reaches the bug.

Text
INFO: Running with entropic power schedule (0xFF, 100).
INFO: Seed: 1394857201
INFO: A corpus is not provided, starting from an empty corpus
#2	INITED cov: 5 ft: 5 corp: 1/1b exec/s: 0 rss: 38Mb
#17	NEW    cov: 7 ft: 7 corp: 2/3b lim: 4 exec/s: 0 rss: 38Mb L: 2/2 MS: 5 ChangeBit-ChangeByte-ShuffleBytes-CopyPart-ChangeByte-
=================================================================
==71442==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x502000000013 at pc 0x55a7d1f3a8c1 bp 0x7ffd1b6a8a30 sp 0x7ffd1b6a8a28
READ of size 1 at 0x502000000013 thread T0
    #0 0x55a7d1f3a8c0 in fuzz_target_1::_::__libfuzzer_sys_run::h1c2f9e0b6a1d2e44 fuzz/fuzz_targets/fuzz_target_1.rs:10:25
    #1 0x55a7d1f3a1d5 in rust_fuzzer_test_input /home/user/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/libfuzzer-sys-0.4.9/src/lib.rs:276:9
...
SUMMARY: AddressSanitizer: heap-buffer-overflow fuzz/fuzz_targets/fuzz_target_1.rs:10:25 in fuzz_target_1::_::__libfuzzer_sys_run::h1c2f9e0b6a1d2e44
MS: 5 ChangeBit-ChangeByte-ShuffleBytes-CopyPart-ChangeByte-; base unit: 3c71b9d0a4e2f5586b1d0e3a7c9f24d815a60b72
0x10,0x9,
artifact_prefix='/home/user/recparse/fuzz/artifacts/fuzz_target_1/'; Test unit written to /home/user/recparse/fuzz/artifacts/fuzz_target_1/crash-5b0d8f0c2a7e4d19a3c6f8b1e07d94a2c1f3e5d6
Output of `std::fmt::Debug`:

	[16, 9]

Reproduce with:

	cargo fuzz run fuzz_target_1 fuzz/artifacts/fuzz_target_1/crash-5b0d8f0c2a7e4d19a3c6f8b1e07d94a2c1f3e5d6

Minimize test case with:

	cargo fuzz tmin fuzz_target_1 fuzz/artifacts/fuzz_target_1/crash-5b0d8f0c2a7e4d19a3c6f8b1e07d94a2c1f3e5d6

The seed, the hash, the paths and the exact crate versions will differ on your machine. The meaningful parts are the sanitizer error kind (heap-buffer-overflow), the source line in the harness where the read happened, and the saved input: two bytes, [16, 9], a kind of 16 and a length of 9 on an input with no payload at all. cargo-fuzz prints the commands to reproduce and minimize it, which is the whole triage workflow in two lines.

The reported line is in the harness, not in parse. That is correct and typical for unsafe bugs: the undefined behavior happens in the library when it builds the invalid slice, but the memory error is detected where the bytes are first read. Search backward from the read to find the slice.

Fix it and keep the input

Replace the unchecked access with a checked one.

src/lib.rsrust
pub fn parse(data: &[u8]) -> Option<Message<'_>> {
    if data.len() < 2 {
        return None;
    }
    let kind = data[0];
    let len = data[1] as usize;
    let payload = data.get(2..2 + len)?;
    Some(Message { kind, payload })
}

slice::get with a range returns None when the range is out of bounds, so a short input is rejected instead of misread. Then replay the saved crash against the fixed code:

Shell
cargo +nightly fuzz run fuzz_target_1 fuzz/artifacts/fuzz_target_1/crash-5b0d8f0c2a7e4d19a3c6f8b1e07d94a2c1f3e5d6
Text
Running: fuzz/artifacts/fuzz_target_1/crash-5b0d8f0c2a7e4d19a3c6f8b1e07d94a2c1f3e5d6
Executed fuzz/artifacts/fuzz_target_1/crash-5b0d8f0c2a7e4d19a3c6f8b1e07d94a2c1f3e5d6 in 0 ms
***
*** NOTE: fuzzing was not performed, you have only
***       executed the target code on a fixed set of inputs.
***

Turn the finding into an ordinary test so it runs under plain cargo test:

src/lib.rsrust
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn rejects_length_beyond_input() {
        assert_eq!(parse(&[16, 9]), None);
    }

    #[test]
    fn accepts_exact_payload() {
        let m = parse(&[1, 2, 7, 8]).unwrap();
        assert_eq!(m, Message { kind: 1, payload: &[7, 8] });
    }
}
Text
running 2 tests
test tests::accepts_exact_payload ... ok
test tests::rejects_length_beyond_input ... ok

test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

Seeds, corpus and sizes

cargo-fuzz keeps the corpus in fuzz/corpus/<target>/, and the fuzzer reads and writes it automatically. Put real sample inputs there before the first long run. Useful maintenance commands are subcommands of cargo fuzz:

  • cargo +nightly fuzz cmin fuzz_target_1 minimizes the corpus, keeping the smallest set with the same coverage.

  • cargo +nightly fuzz tmin fuzz_target_1 <crash-file> shrinks a failing input.

  • cargo +nightly fuzz coverage fuzz_target_1 builds a coverage report from the corpus, so you can see which lines the fuzzer never reached.

Arguments after -- go to libFuzzer itself. cargo +nightly fuzz run fuzz_target_1 -- -max_len=256 -timeout=5 caps the input size and flags slow inputs.

Structured input with Arbitrary

Byte slices suit parsers. For an API that takes typed arguments, the arbitrary crate derives a generator from a type, and fuzz_target! accepts it directly.

fuzz/fuzz_targets/ops.rsrust
#![no_main]

use arbitrary::Arbitrary;
use libfuzzer_sys::fuzz_target;

#[derive(Debug, Arbitrary)]
enum Op {
    Push(u8),
    Pop,
}

fuzz_target!(|ops: Vec<Op>| {
    let mut stack: Vec<u8> = Vec::new();
    for op in ops {
        match op {
            Op::Push(v) => stack.push(v),
            Op::Pop => {
                stack.pop();
            }
        }
    }
});

The fuzzer's bytes are decoded into a vector of operations, so every input is a valid sequence and none is wasted on a malformed encoding. This is the pattern for fuzzing a data structure or a state machine, with an assertion about its invariant at the end.

What Rust changes and what it does not

Safe Rust cannot corrupt memory, so most findings in safe code are panics, arithmetic overflow in debug builds, unbounded allocation or infinite loops. They matter in services where a panic ends a request or a process. In unsafe code, expect real memory errors, and make sure the fuzz build keeps the sanitizer on, which it does by default (--sanitizer address).

Two settings are worth knowing. Overflow checks are on in the fuzz build because cargo-fuzz uses a profile with debug assertions, so arithmetic overflow panics, matching a debug test run. And --release is the default build mode for fuzzing, so debug_assert! still fires only if you enable debug assertions explicitly with -a (--debug-assertions).

When this is not enough

cargo-fuzz targets library code on a host with an operating system. For no_std firmware, fuzz the portable logic on the host by gating hardware access behind a trait. For code that calls into C libraries, instrument the C code as well, or the fuzzer cannot see inside it. And for concurrency bugs, a fuzzer is not the right tool; use a model checker such as loom or ThreadSanitizer builds.

Also inDebugging
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.