fuzz: cargo-fuzz harness for the ratchet/qr/dispatch/file parsers

Four pure parsers eat untrusted peer input and had no structured fuzzing:

- ratchet_frame  -> RatchetState::from_bytes + RatchetState::decrypt
                    (the 'rat ' frame parser: prefix, version, length,
                    N/PN bounds, DH step, AEAD open)
- qr_decode      -> qr::decode on pasted/scanned invite strings
- dispatch_classify -> dispatch::classify on raw decrypted plaintext,
                    including the 'rat ' -> Kind::Ratchet routing arm
- file_decode    -> file::decode on 'fil ' chunk frames

No src/ change: every target calls the shipped public API. The fuzz crate is
its own workspace (empty [workspace] table), so no root Cargo.toml dependency
is added and cargo build/test at the root never compiles it.

Seeds in fuzz/seeds/ are committed and copied into the gitignored working
corpus by scripts/run-fuzz.sh; each target asserts properties a panic-free
decode must hold (a rejected ratchet frame leaves the state byte-identical,
a decoded invite is 32/32/onion-shaped, a decoded chunk re-encodes).

Verified: cargo +nightly fuzz list -> 4 targets; scripts/run-fuzz.sh with
FUZZ_SECS=60 FUZZ_JOBS=4 -> exit 0, oom/timeout/crash: 0/0/0 for all four,
fuzz/artifacts/* empty.
This commit is contained in:
rust-dev 2026-09-17 20:52:44 -04:00 • committed by agent
commit f06073e7dc
No known key found for this signature in database
30 changed files with 6645 additions and 0 deletions

9
fuzz/.gitignore vendored Normal file
View file

@ -0,0 +1,9 @@
# Build output and crash artifacts are not source.
target/
artifacts/
coverage/
# The working corpus is machine-local: libFuzzer grows it on every run, and
# that growth is noise in a diff. The hand-built regression inputs live in
# seeds/ and are copied into corpus/ by scripts/run-fuzz.sh; fold a reproducer
# from artifacts/ into seeds/ once the bug behind it is fixed.
corpus/

6352
fuzz/Cargo.lock generated Normal file

File diff suppressed because it is too large Load diff

44
fuzz/Cargo.toml Normal file
View file

@ -0,0 +1,44 @@
[package]
name = "onionwire-fuzz"
version = "0.0.0"
publish = false
edition = "2021"
[package.metadata]
cargo-fuzz = true
# Detach from the parent package: this crate is nightly-only and must never be
# part of a normal `cargo build` / `cargo test` of the root crate.
[workspace]
[dependencies]
libfuzzer-sys = "0.4"
onionwire = { path = ".." }
[[bin]]
name = "ratchet_frame"
path = "fuzz_targets/ratchet_frame.rs"
test = false
doc = false
bench = false
[[bin]]
name = "qr_decode"
path = "fuzz_targets/qr_decode.rs"
test = false
doc = false
bench = false
[[bin]]
name = "dispatch_classify"
path = "fuzz_targets/dispatch_classify.rs"
test = false
doc = false
bench = false
[[bin]]
name = "file_decode"
path = "fuzz_targets/file_decode.rs"
test = false
doc = false
bench = false

26
fuzz/README.md Normal file
View file

@ -0,0 +1,26 @@
# Fuzzing OnionWire
Structured fuzzing for the four parsers that eat untrusted peer input. A crash
here is a remote-triggerable panic, so a reproducer must be fixed in `src/` and
then folded into `fuzz/seeds/<target>/` as a regression input.
| target | entry points |
|---|---|
| `ratchet_frame` | `ratchet::RatchetState::from_bytes`, `RatchetState::decrypt` (the `rat ` frame parser) |
| `qr_decode` | `qr::decode` (pasted/scanned invite strings) |
| `dispatch_classify` | `dispatch::classify` (routes a `rat ` frame to the ratchet parser) |
| `file_decode` | `file::decode` (`fil ` chunk frames) |
Nothing in `src/` changes for this: every target calls the shipped public API.
```sh
rustup toolchain install nightly --profile minimal
cargo install cargo-fuzz
scripts/run-fuzz.sh # all four, 60s each
FUZZ_SECS=300 scripts/run-fuzz.sh ratchet_frame
```
`fuzz/corpus/` is gitignored (libFuzzer grows it locally); `fuzz/seeds/` is
committed and copied in by the script. Crash reproducers land in
`fuzz/artifacts/<target>/`. Needs rustup's `cargo` on `PATH` — the `+nightly`
directive does not work through a distro `cargo` package.

View file

@ -0,0 +1,26 @@
//! Untrusted decrypted plaintext against the application dispatch classifier.
//!
//! `dispatch::classify` runs on every inbound message before anything else
//! looks at it, and its `Ratchet` arm is what routes a `rat `-prefixed message
//! into the ratchet parser (`src/ratchet.rs` `Frame::parse`). It takes raw
//! bytes — never a `&str` — so all 255 byte values are in scope, and it must
//! classify (or `Drop`) every input without panicking.
#![no_main]
use libfuzzer_sys::fuzz_target;
use onionwire::dispatch::{self, Kind};
fuzz_target!(|data: &[u8]| {
let kind = dispatch::classify(data);
// Total and deterministic: every input maps to exactly one variant, and the
// answer is stable across calls (no interior state, no ordering dependence).
assert_eq!(kind, dispatch::classify(data));
// The routing invariant that matters: the `rat ` prefix is never shadowed by
// the `[a-z]{3} ` catch-all, so a ratchet frame always reaches the ratchet
// parser rather than being dropped as an unknown prefix.
if data.starts_with(b"rat ") {
assert_eq!(kind, Kind::Ratchet);
}
});

View file

@ -0,0 +1,26 @@
//! Untrusted file-chunk bytes against the chunk decoder.
//!
//! A peer can send a `fil ` chunk at any time; `file::decode` header-parses it
//! (hex transfer id, filename, hex sha256, `idx/total`, then the payload) before
//! anything is written to disk. It must return `None` for every malformed
//! chunk and never panic — including on absurd `idx`/`total` and on filenames
//! that fail `safe_name`.
#![no_main]
use libfuzzer_sys::fuzz_target;
use onionwire::file;
fuzz_target!(|data: &[u8]| {
if let Some(chunk) = file::decode(data) {
// A chunk it accepted must survive an encode round-trip and decode
// back to the same header, byte for byte.
let re = file::encode(&chunk);
let again = file::decode(&re).expect("encoded chunk must decode");
assert_eq!(again.xfer_id, chunk.xfer_id);
assert_eq!(again.filename, chunk.filename);
assert_eq!(again.sha256, chunk.sha256);
assert_eq!(again.idx, chunk.idx);
assert_eq!(again.total, chunk.total);
assert_eq!(again.data, chunk.data);
}
});

View file

@ -0,0 +1,28 @@
//! Untrusted invite strings against the QR/invite decoder.
//!
//! `qr::decode` takes a `&str` (the invite is pasted or scanned as text), so the
//! fuzzer input is read lossily as UTF-8. It must return `Err` for every
//! malformed invite — bad hex, wrong lengths, a non-v3 onion, a foreign
//! signature over a well-formed body — and never panic on any of them. The
//! `onionwire:v1:k=…` string is a QR code's payload, so the byte budget is
//! attacker-sized and the parse must stay bounded.
#![no_main]
use libfuzzer_sys::fuzz_target;
use onionwire::qr;
fuzz_target!(|data: &[u8]| {
let raw = String::from_utf8_lossy(data);
// The decoder is total over `&str`: no panic, no hang, no runaway allocation.
if let Ok(payload) = qr::decode(&raw) {
// Anything it accepted must be shaped as the payload promises; a decode
// that returns a malformed payload is as bad as a panic downstream.
assert_eq!(payload.pubkey.len(), 32);
assert_eq!(payload.signed_prekey.len(), 32);
assert!(payload.onion.ends_with(".onion"));
}
// Determinism: the same invite must decode to the same answer.
assert_eq!(qr::decode(&raw).is_ok(), qr::decode(&raw).is_ok());
});

View file

@ -0,0 +1,48 @@
//! Untrusted peer bytes against the Double Ratchet frame parser.
//!
//! Two entry points, both reachable from the network:
//!
//! - `RatchetState::from_bytes` — persisted-state restore (a tampered or
//! truncated blob from the store must be an `Err`, never a panic).
//! - `RatchetState::decrypt` — the wire path (`Frame::parse` + `plan_*` +
//! `open`); every field in the header is attacker-controlled.
//!
//! Neither call may panic, and neither may leave the state mutated on a frame
//! it rejects (asserted in `tests/ratchet.rs`, re-checked cheaply here by
//! re-serializing after every decrypt).
#![no_main]
use libfuzzer_sys::fuzz_target;
use onionwire::ratchet::{RatchetKeyPair, RatchetState};
fuzz_target!(|data: &[u8]| {
// Restore path: arbitrary bytes as a persisted ratchet state.
if let Ok(state) = RatchetState::from_bytes(data) {
// A state that parsed must re-serialize without panicking.
let _ = state.to_bytes();
}
// Wire path: a fresh bootstrap epoch for every input, so one iteration can
// never influence the next. The keys are fixed (not fuzzed) on purpose:
// the interesting surface is `data` as the frame.
let mut state = RatchetState::bootstrap(
[0x42u8; 32],
RatchetKeyPair::from_secret([0x11u8; 32]),
[0x33u8; 32],
);
let before = state.to_bytes();
match state.decrypt(data) {
Ok(_) => {
// A frame this state accepts must have advanced the receiving chain.
let _ = state.recv_index();
}
Err(_) => {
// Refuse-and-roll-back: a rejected frame leaves the state untouched.
assert_eq!(state.to_bytes(), before, "rejected frame mutated the state");
}
}
// Re-encrypting a byte-identical state must stay a pure function.
let _ = state.encrypt(b"fuzz");
});

View file

View file

@ -0,0 +1 @@
loc abc.onion

View file

@ -0,0 +1 @@
ﳽ

Binary file not shown.

View file

@ -0,0 +1 @@
zzz whatever

View file

@ -0,0 +1,5 @@
fil 01010101010101010101010101010101
note.txt
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
1/1
x

View file

@ -0,0 +1 @@
fil

View file

@ -0,0 +1,5 @@
fil 01010101010101010101010101010101
note.txt
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
0/1
hello

View file

@ -0,0 +1,5 @@
fil 01010101010101010101010101010101
../etc/passwd
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
0/2
x

Binary file not shown.

View file

@ -0,0 +1 @@
onionwire:v1:k=deadbeef

View file

@ -0,0 +1 @@
onionwire:v1:k=abababababababababababababababababababababababababababababababab:o=short.onion:spk=cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd:sig=efefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefef

View file

@ -0,0 +1 @@
onionwire:v1:k=ab:o=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.onion:spk=cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd:sig=efefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefef

View file

@ -0,0 +1 @@
onionwire:v1:k=abababababababababababababababababababababababababababababababab:o=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.onion:spk=cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd:sig=efefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefefef

Binary file not shown.

Binary file not shown.

View file

@ -0,0 +1 @@
rat

View file

@ -0,0 +1 @@
Û²ù t\˜mMÓN>d}5îu°Û/F[µEM‚ì=g<>T ¥ <09>†Ø¸…¯Ä¥¥lN¤ø<¼ž#&<-/øŠEÒ›(?s¨íói

Binary file not shown.

Binary file not shown.

Binary file not shown.

61
scripts/run-fuzz.sh Executable file
View file

@ -0,0 +1,61 @@
#!/usr/bin/env sh
# Run an OnionWire fuzz target. Needs a nightly toolchain and cargo-fuzz:
#
# rustup toolchain install nightly --profile minimal
# cargo install cargo-fuzz
#
# `cargo` must be rustup's shim, not a distro package: the `+nightly` directive
# only works through rustup. `export PATH="$HOME/.cargo/bin:$PATH"` if in doubt.
#
# Usage:
# scripts/run-fuzz.sh # all four targets, 60s each
# scripts/run-fuzz.sh qr_decode # one target
# FUZZ_SECS=300 scripts/run-fuzz.sh ratchet_frame
# FUZZ_JOBS=4 scripts/run-fuzz.sh # fork N workers per target
#
# Every target is a pure parser/decryptor over untrusted peer input, so a
# non-zero exit means libFuzzer found a crash: the reproducer lands in
# fuzz/artifacts/<target>/ and is named crash-<hash>.
#
# Reproduce a crash without fuzzing:
# cargo +nightly fuzz run <target> fuzz/artifacts/<target>/crash-<hash>
#
# Fold a fixed crash into the regression seeds (committed, so it runs every time
# instead of being rediscovered):
# cp fuzz/artifacts/<target>/crash-<hash> fuzz/seeds/<target>/
set -eu
cd "$(dirname "$0")/.."
TARGETS="ratchet_frame qr_decode dispatch_classify file_decode"
SECS="${FUZZ_SECS:-60}"
JOBS="${FUZZ_JOBS:-1}"
# A build tree per machine, outside the repo: the fuzz crate links the whole
# onionwire graph (Arti, SQLCipher, vendored OpenSSL) and must not share a
# target dir with a stable build.
: "${CARGO_TARGET_DIR:=$HOME/.cargo/fuzz-target}"
export CARGO_TARGET_DIR
: "${TMPDIR:=/var/tmp/onionwire-fuzz-tmp}"
export TMPDIR
mkdir -p "$TMPDIR"
if [ "$#" -gt 0 ]; then
TARGETS="$*"
fi
for t in $TARGETS; do
if [ ! -d "fuzz/corpus/$t" ]; then
mkdir -p "fuzz/corpus/$t"
fi
# Seed the working corpus from fuzz/seeds (hand-built regression inputs).
# fuzz/corpus itself is gitignored: libFuzzer grows it, and that growth is
# machine-local noise, not source.
cp -n fuzz/seeds/"$t"/* "fuzz/corpus/$t"/ 2>/dev/null || true
printf '\n=== fuzz %s (%ss, %s jobs) ===\n' "$t" "$SECS" "$JOBS"
cargo +nightly fuzz run "$t" -j "$JOBS" -- -max_total_time="$SECS"
done
printf '\nall targets survived %ss each\n' "$SECS"