FAQ - Help and questions

What is fuzzing, and how do I start testing a Rust parser with random input?

#security#fuzzing#testingpublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Fuzzing feeds a function huge numbers of generated inputs and watches for panics, hangs and crashes. Start by wrapping your parser in a function that must never panic, try it with a simple random generator, and then move to cargo-fuzz with libFuzzer, which also learns which inputs reach new code.

Checked with rustc 1.93.0, Windows 11 (cargo-fuzz was not run for this thread)

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

A parser sees input that its author did not imagine. A fuzzer produces inputs by the million and reports the ones that make the code panic, run out of memory or loop forever. One rule makes it work: the function under test must have a property that is always true, for example "never panics, whatever the bytes".

You can see the idea without any tool. The program below has a parser with a bug (it trusts a length byte) and the corrected version. A tiny deterministic random generator makes 10,000 inputs, and the program counts panics for each parser. This is not a real fuzzer: it does not learn from the code it runs and it explores far less. It shows what a fuzzer finds.

src/main.rsrust
use std::panic;

/// A parser with a bug: the first byte is a length, and it is trusted.
fn parse_buggy(data: &[u8]) -> &[u8] {
    let len = data[0] as usize;
    &data[1..1 + len]
}

/// The same parser, written to return None on bad input.
fn parse_fixed(data: &[u8]) -> Option<&[u8]> {
    let len = *data.first()? as usize;
    data.get(1..1usize.checked_add(len)?)
}

/// A tiny deterministic pseudo-random generator (xorshift), so every run sees the same inputs.
struct Rng(u64);
impl Rng {
    fn next(&mut self) -> u64 {
        self.0 ^= self.0 << 13;
        self.0 ^= self.0 >> 7;
        self.0 ^= self.0 << 17;
        self.0
    }
}

fn main() {
    panic::set_hook(Box::new(|_| {})); // keep the output readable: we count panics instead
    let mut rng = Rng(0x2545_F491_4F6C_DD1D);
    let (mut buggy_panics, mut fixed_panics) = (0, 0);
    let runs = 10_000;
    for _ in 0..runs {
        let len = (rng.next() % 300) as usize;
        let input: Vec<u8> = (0..len).map(|_| rng.next() as u8).collect();
        if panic::catch_unwind(|| parse_buggy(&input).len()).is_err() {
            buggy_panics += 1;
        }
        if panic::catch_unwind(|| parse_fixed(&input).map(|s| s.len())).is_err() {
            fixed_panics += 1;
        }
    }
    println!("inputs tried: {runs}");
    println!("buggy parser panicked: {buggy_panics}");
    println!("fixed parser panicked: {fixed_panics}");
}
text
inputs tried: 10000
buggy parser panicked: 4279
fixed parser panicked: 0

The same seed gives the same result on every run, so a failing input can be reproduced.

Using a real fuzzer: cargo-fuzz#

cargo-fuzz runs libFuzzer, a coverage-guided fuzzer, and generates a project skeleton. It needs a nightly Rust toolchain, and its documentation lists the supported platforms; read the Rust Fuzz Book before you start, because this thread did not run it. The outline is:

text
cargo install cargo-fuzz
cargo fuzz init
cargo fuzz add parse_frame
cargo +nightly fuzz run parse_frame

The target is a few lines: it receives a byte slice and calls your parser, ignoring the result. Any panic is a finding; the tool saves the input that caused it so you can add it to your tests.

How to do it#

  1. Pick the code that handles untrusted bytes (parsers, decoders, protocol handlers).
  2. Make it a function from &[u8] to a Result; keep the fuzz target thin.
  3. Start with a few valid examples as a corpus; the fuzzer mutates them.
  4. Run it for minutes, then for longer in CI on a schedule, with memory and time limits.
  5. Turn each crash into a regression test, then fix the parser (see the threads on length fields and non-panicking operations).
  6. Combine with debug assertions and, for unsafe code, with Miri or sanitizers.

Common mistakes#

  • Fuzzing a function that needs an environment (network, clock). Fuzz the pure part.
  • Ignoring hangs and out-of-memory findings because they are not "crashes".
  • Running once and never again. Coverage-guided fuzzing improves with time and with a growing corpus.

Is property testing the same thing?#

It is a close relative: you state a property and the tool generates inputs to break it. Property-testing libraries are good for logic with structured inputs; coverage-guided fuzzers are strong for byte-level parsers.

How long should a fuzzing run last?#

There is no fixed answer: stop when the coverage stops growing and no findings appear for a long time, then keep a shorter run in CI and a longer one on a schedule.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet