//! 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). //! //! Both bootstrap shapes are exercised: a classical friend (`remote_kem_pub = //! None`) and a hybrid friend, whose peer ML-KEM ratchet key is a real //! encapsulation key of `kem::PK_LEN` bytes derived from a fixed seed. A //! garbage key would only ever hit the "invalid encapsulation key" error path. #![no_main] use libfuzzer_sys::fuzz_target; use onionwire::kem::{self, PK_LEN, SEED_LEN}; use onionwire::ratchet::{RatchetKeyPair, RatchetState}; use std::sync::OnceLock; /// A canonical ML-KEM-768 encapsulation key, built once: key generation is /// deterministic for a fixed seed, so this only pays for itself on iteration 1. fn peer_kem_pub() -> &'static [u8] { static PK: OnceLock> = OnceLock::new(); PK.get_or_init(|| { let pk = kem::pk_from_seed(&[0x44u8; SEED_LEN]).expect("64 bytes is a valid ML-KEM seed"); assert_eq!(pk.len(), PK_LEN, "crate ML-KEM public key length changed"); pk }) } fn bootstrap(remote_kem_pub: Option<&[u8]>) -> RatchetState { // The keys are fixed (not fuzzed) on purpose: the interesting surface is // `data` as the frame. RatchetState::bootstrap( [0x42u8; 32], RatchetKeyPair::from_secret([0x11u8; 32]), [0x33u8; 32], remote_kem_pub, ) } /// Feed `data` to a fresh state and hold the existing invariants: a reject must /// roll back, an accept must have advanced the receiving chain, and re-sending /// from the resulting state must not panic. fn exercise(remote_kem_pub: Option<&[u8]>, data: &[u8]) { let mut state = bootstrap(remote_kem_pub); 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"); } 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. Classical and hybrid, both. exercise(None, data); exercise(Some(peer_kem_pub()), data); });