From 948f446a139eb93c97e71525e1a6ccc54d254d52 Mon Sep 17 00:00:00 2001 From: mnovak Date: Wed, 25 Nov 2026 12:51:08 +0100 Subject: [PATCH] [domistream] Tests: fuzz targets assert invariants Every target now checks properties instead of only calling the parser: parse -> encode -> parse stability (RTSP request, ENet, input), caps and TooLarge past them, chunking invariance of the framer, XML vs status parser agreement, seal/open round trips, no forged GCM tags. New targets for the parsers and state machines that had none: server_cert_der, enet_client, media_decrypt, video_depacketizer, audio_depacketizer, fec_reconstruct, pairing_session, rtsp_client (25 targets). --- fuzz/Cargo.toml | 58 ++++++++++++++++++++++++- fuzz/fuzz_targets/app_list.rs | 19 ++++++-- fuzz/fuzz_targets/audio_depacketizer.rs | 45 +++++++++++++++++++ fuzz/fuzz_targets/audio_packet.rs | 19 ++++++-- fuzz/fuzz_targets/control_frame.rs | 22 ++++++++-- fuzz/fuzz_targets/control_message.rs | 18 ++++++-- fuzz/fuzz_targets/enet_client.rs | 52 ++++++++++++++++++++++ fuzz/fuzz_targets/enet_datagram.rs | 14 ++++-- fuzz/fuzz_targets/fec_reconstruct.rs | 40 +++++++++++++++++ fuzz/fuzz_targets/input.rs | 13 ++++-- fuzz/fuzz_targets/launch_response.rs | 18 ++++++-- fuzz/fuzz_targets/media_decrypt.rs | 21 +++++++++ fuzz/fuzz_targets/pair_response.rs | 16 +++++-- fuzz/fuzz_targets/pairing_session.rs | 42 ++++++++++++++++++ fuzz/fuzz_targets/rtp_header.rs | 12 +++-- fuzz/fuzz_targets/rtsp_client.rs | 38 ++++++++++++++++ fuzz/fuzz_targets/rtsp_framer.rs | 38 +++++++++++----- fuzz/fuzz_targets/rtsp_request.rs | 9 ++-- fuzz/fuzz_targets/rtsp_response.rs | 17 ++++++-- fuzz/fuzz_targets/sdp.rs | 27 ++++++++++-- fuzz/fuzz_targets/server_cert_der.rs | 24 ++++++++++ fuzz/fuzz_targets/server_cert_pem.rs | 19 ++++++-- fuzz/fuzz_targets/server_info.rs | 21 +++++++-- fuzz/fuzz_targets/video_depacketizer.rs | 41 +++++++++++++++++ fuzz/fuzz_targets/video_packet.rs | 20 +++++++-- fuzz/fuzz_targets/xml.rs | 36 +++++++++++++-- 26 files changed, 636 insertions(+), 63 deletions(-) create mode 100644 fuzz/fuzz_targets/audio_depacketizer.rs create mode 100644 fuzz/fuzz_targets/enet_client.rs create mode 100644 fuzz/fuzz_targets/fec_reconstruct.rs create mode 100644 fuzz/fuzz_targets/media_decrypt.rs create mode 100644 fuzz/fuzz_targets/pairing_session.rs create mode 100644 fuzz/fuzz_targets/rtsp_client.rs create mode 100644 fuzz/fuzz_targets/server_cert_der.rs create mode 100644 fuzz/fuzz_targets/video_depacketizer.rs diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index a20290a..e82bf43 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -1,4 +1,4 @@ -# Fuzz targets: one per DomiStream parser. Its own workspace, built only for fuzzing, never released. +# Fuzz targets: one per DomiStream parser and state machine; each asserts invariants (round trips, caps). Its own workspace, built only for fuzzing, never released. # # Linux, nightly, cargo-fuzz: # cargo fuzz run -- -max_total_time=600 @@ -155,3 +155,59 @@ path = "fuzz_targets/audio_packet.rs" test = false doc = false bench = false + +[[bin]] +name = "server_cert_der" +path = "fuzz_targets/server_cert_der.rs" +test = false +doc = false +bench = false + +[[bin]] +name = "enet_client" +path = "fuzz_targets/enet_client.rs" +test = false +doc = false +bench = false + +[[bin]] +name = "media_decrypt" +path = "fuzz_targets/media_decrypt.rs" +test = false +doc = false +bench = false + +[[bin]] +name = "video_depacketizer" +path = "fuzz_targets/video_depacketizer.rs" +test = false +doc = false +bench = false + +[[bin]] +name = "audio_depacketizer" +path = "fuzz_targets/audio_depacketizer.rs" +test = false +doc = false +bench = false + +[[bin]] +name = "fec_reconstruct" +path = "fuzz_targets/fec_reconstruct.rs" +test = false +doc = false +bench = false + +[[bin]] +name = "pairing_session" +path = "fuzz_targets/pairing_session.rs" +test = false +doc = false +bench = false + +[[bin]] +name = "rtsp_client" +path = "fuzz_targets/rtsp_client.rs" +test = false +doc = false +bench = false diff --git a/fuzz/fuzz_targets/app_list.rs b/fuzz/fuzz_targets/app_list.rs index 559bcdb..5dc0dc8 100644 --- a/fuzz/fuzz_targets/app_list.rs +++ b/fuzz/fuzz_targets/app_list.rs @@ -1,11 +1,24 @@ -//! Fuzzes `/applist` answers: never panics, whatever the bytes. -//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic. +//! Fuzzes `/applist` answers. +//! Asserts invariants, not only "no panic": at most MAX_APPS apps, titles within the cap, ids unique. //! How to run: see the comment at the top of `fuzz/Cargo.toml`. #![no_main] use libfuzzer_sys::fuzz_target; +use domistream::http::applist::{MAX_APP_TITLE_BYTES, MAX_APPLIST_BYTES, MAX_APPS}; + fuzz_target!(|data: &[u8]| { - let _ = domistream::http::parse_app_list(data); + let r = domistream::http::parse_app_list(data); + if data.len() > MAX_APPLIST_BYTES { + assert!(matches!(r, Err(domistream::Error::TooLarge { .. }))); + } + if let Ok(apps) = r { + assert!(apps.len() <= MAX_APPS); + let mut ids: Vec = apps.iter().map(|a| a.id).collect(); + ids.sort_unstable(); + ids.dedup(); + assert_eq!(ids.len(), apps.len(), "duplicate ids accepted"); + assert!(apps.iter().all(|a| a.title.len() <= MAX_APP_TITLE_BYTES)); + } }); diff --git a/fuzz/fuzz_targets/audio_depacketizer.rs b/fuzz/fuzz_targets/audio_depacketizer.rs new file mode 100644 index 0000000..5dde58e --- /dev/null +++ b/fuzz/fuzz_targets/audio_depacketizer.rs @@ -0,0 +1,45 @@ +//! Fuzzes the audio depacketizer with a sequence of datagrams (FEC on, a Cauchy test matrix). +//! Asserts invariants, not only "no panic": never two events for one sequence number in a short run; output stays bounded by the input. +//! How to run: see the comment at the top of `fuzz/Cargo.toml`. + +#![no_main] + +use libfuzzer_sys::fuzz_target; + +use core::time::Duration; +use std::collections::HashSet; + +use domistream::Instant; +use domistream::audio::{AudioConfig, AudioDepacketizer, AudioEvent, AudioFec}; + +// 1 / (x ^ y) over GF(2^8)/0x11D with x in {0, 1} and y in {2, 3, 4, 5}: a 2 x 4 Cauchy matrix, the same one +// tests/common builds with gf::cauchy(2, 4). +const MATRIX: [u8; 8] = [0x8e, 0xf4, 0x47, 0xa7, 0xf4, 0x8e, 0xa7, 0x47]; + +fuzz_target!(|data: &[u8]| { + let cfg = AudioConfig { cipher: None, packet_duration_ms: 5, fec: AudioFec::ParityMatrix(MATRIX), loss_timeout: Duration::from_millis(20) }; + let Ok(mut d) = AudioDepacketizer::new(cfg) else { return }; + let mut rest = data; + let mut us = 0u64; + let mut seen = HashSet::new(); + let mut out_bytes = 0usize; + while let Some((&len, tail)) = rest.split_first() { + let len = usize::from(len).min(tail.len()); + let (g, tail) = tail.split_at(len); + rest = tail; + us += 1000; + let _ = d.push(Instant::from_micros(us), g); + let _ = d.handle_timeout(Instant::from_micros(us)); + while let Some(e) = d.poll_event() { + let seq = match &e { + AudioEvent::Packet { sequence, opus, .. } => { + out_bytes += opus.len(); + *sequence + } + AudioEvent::Lost { sequence } => *sequence, + }; + assert!(seen.insert(seq), "two events for sequence {seq}"); + } + } + assert!(out_bytes <= data.len() * 2, "FEC rebuilds packets, but not out of nothing"); +}); diff --git a/fuzz/fuzz_targets/audio_packet.rs b/fuzz/fuzz_targets/audio_packet.rs index 394184c..35cccea 100644 --- a/fuzz/fuzz_targets/audio_packet.rs +++ b/fuzz/fuzz_targets/audio_packet.rs @@ -1,11 +1,24 @@ -//! Fuzzes audio packets: never panics, whatever the bytes. -//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic. +//! Fuzzes audio packets. +//! Asserts invariants, not only "no panic": payload types and shard indices are the ones PROTOCOL.md allows; payloads are never empty. //! How to run: see the comment at the top of `fuzz/Cargo.toml`. #![no_main] use libfuzzer_sys::fuzz_target; +use domistream::audio::AudioPacket; +use domistream::audio::packet::{AUDIO_FEC_PAYLOAD_TYPE, AUDIO_PAYLOAD_TYPE, MAX_AUDIO_PACKET_BYTES}; + fuzz_target!(|data: &[u8]| { - let _ = domistream::audio::parse_audio_packet(data); + match domistream::audio::parse_audio_packet(data) { + Ok(AudioPacket::Data { rtp, payload }) => { + assert_eq!(rtp.payload_type, AUDIO_PAYLOAD_TYPE); + assert!(!payload.is_empty() && data.len() <= MAX_AUDIO_PACKET_BYTES); + } + Ok(AudioPacket::Parity { rtp, fec, parity }) => { + assert_eq!(rtp.payload_type, AUDIO_FEC_PAYLOAD_TYPE); + assert!(fec.shard_index <= 1 && !parity.is_empty()); + } + Err(_) => {} + } }); diff --git a/fuzz/fuzz_targets/control_frame.rs b/fuzz/fuzz_targets/control_frame.rs index 0dde0cd..7243199 100644 --- a/fuzz/fuzz_targets/control_frame.rs +++ b/fuzz/fuzz_targets/control_frame.rs @@ -1,11 +1,27 @@ -//! Fuzzes encrypted control frames (outer fields): never panics, whatever the bytes. -//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic. +//! Fuzzes encrypted control frames (outer fields), their opening, and seal/open round trips. +//! Asserts invariants, not only "no panic": the length field matches the bytes, random frames never pass the GCM tag, and seal then open gives the plaintext back. //! How to run: see the comment at the top of `fuzz/Cargo.toml`. #![no_main] use libfuzzer_sys::fuzz_target; +use domistream::control::frame::{FRAME_HEADER_LEN, MAX_FRAME_BYTES, MIN_FRAME_BYTES}; +use domistream::control::{ControlCipher, Direction, parse_encrypted_frame}; + fuzz_target!(|data: &[u8]| { - let _ = domistream::control::parse_encrypted_frame(data); + if let Ok(f) = parse_encrypted_frame(data) { + assert!(data.len() >= MIN_FRAME_BYTES && data.len() <= MAX_FRAME_BYTES); + assert_eq!(f.ciphertext.len() + FRAME_HEADER_LEN, data.len()); + assert_eq!(&f.tag[..], &data[8..24]); + // A fuzzer forging a GCM tag would be a finding of its own. + assert_eq!(ControlCipher::new([0x42; 16]).open(Direction::HostToClient, data), Err(domistream::Error::Crypto)); + } + if data.len() >= 4 && data.len() + FRAME_HEADER_LEN <= MAX_FRAME_BYTES { + let c = ControlCipher::new([0x24; 16]); + let seq = u32::from_le_bytes([data[0], data[1], data[2], data[3]]); + let sealed = c.seal(seq, Direction::ClientToHost, data).expect("seal"); + assert_eq!(c.open(Direction::ClientToHost, &sealed), Ok((seq, data.to_vec()))); + assert!(c.open(Direction::HostToClient, &sealed).is_err()); + } }); diff --git a/fuzz/fuzz_targets/control_message.rs b/fuzz/fuzz_targets/control_message.rs index db2bd4c..1d7ef0d 100644 --- a/fuzz/fuzz_targets/control_message.rs +++ b/fuzz/fuzz_targets/control_message.rs @@ -1,11 +1,23 @@ -//! Fuzzes decrypted control messages from the host: never panics, whatever the bytes. -//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic. +//! Fuzzes decrypted control messages from the host. +//! Asserts invariants, not only "no panic": the split matches the length field; a host message always splits as a message; Other keeps the body length. //! How to run: see the comment at the top of `fuzz/Cargo.toml`. #![no_main] use libfuzzer_sys::fuzz_target; +use domistream::control::{HostMessage, parse_host_message, parse_message}; + fuzz_target!(|data: &[u8]| { - let _ = domistream::control::parse_host_message(data); + let raw = parse_message(data); + if let Ok(r) = raw { + assert_eq!(r.body.len() + 4, data.len()); + assert_eq!(r.message_type, u16::from_le_bytes([data[0], data[1]])); + } + if let Ok(m) = parse_host_message(data) { + assert!(raw.is_ok(), "a host message must split as a message first"); + if let HostMessage::Other { body_len, .. } = m { + assert_eq!(body_len + 4, data.len()); + } + } }); diff --git a/fuzz/fuzz_targets/enet_client.rs b/fuzz/fuzz_targets/enet_client.rs new file mode 100644 index 0000000..6f5cda2 --- /dev/null +++ b/fuzz/fuzz_targets/enet_client.rs @@ -0,0 +1,52 @@ +//! Fuzzes the ENet client peer: a connecting peer fed a sequence of datagrams. +//! Asserts invariants, not only "no panic": never panics; delivered packets are within MAX_PACKET_BYTES; outgoing datagrams parse and stay within the MTU. +//! How to run: see the comment at the top of `fuzz/Cargo.toml`. + +#![no_main] + +use libfuzzer_sys::fuzz_target; + +use core::time::Duration; + +use domistream::enet::protocol::parse_datagram; +use domistream::enet::{EnetClient, EnetConfig, EnetEvent, MAX_PACKET_BYTES}; +use domistream::{Instant, RandomSource}; + +struct Fixed; +impl RandomSource for Fixed { + fn fill(&mut self, dest: &mut [u8]) { + dest.fill(0x5A); + } +} + +fuzz_target!(|data: &[u8]| { + let cfg = EnetConfig { + channel_count: 2, + mtu: 1400, + connect_data: 0, + ping_interval: Duration::from_millis(500), + timeout: Duration::from_secs(10), + }; + let Ok(mut c) = EnetClient::connect(cfg, Instant::ZERO, &mut Fixed) else { return }; + // Datagrams separated by a 2-byte big-endian length; time advances 1 ms per datagram. + let mut rest = data; + let mut ms = 0u64; + while rest.len() >= 2 { + let len = usize::from(u16::from_be_bytes([rest[0], rest[1]])).min(rest.len() - 2); + let (d, tail) = rest[2..].split_at(len); + rest = tail; + ms += 1; + let now = Instant::from_micros(ms * 1000); + let _ = c.handle_datagram(now, d); + let _ = c.handle_timeout(now); + while let Some(out) = c.poll_transmit(now) { + assert!(out.len() <= usize::from(cfg.mtu)); + parse_datagram(&out).expect("the client's own datagrams parse"); + } + while let Some(e) = c.poll_event() { + if let EnetEvent::Received { data, .. } = e { + assert!(data.len() <= MAX_PACKET_BYTES); + } + } + } +}); diff --git a/fuzz/fuzz_targets/enet_datagram.rs b/fuzz/fuzz_targets/enet_datagram.rs index 19e34d2..46ac832 100644 --- a/fuzz/fuzz_targets/enet_datagram.rs +++ b/fuzz/fuzz_targets/enet_datagram.rs @@ -1,11 +1,19 @@ -//! Fuzzes ENet datagrams: never panics, whatever the bytes. -//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic. +//! Fuzzes ENet datagrams. +//! Asserts invariants, not only "no panic": parse -> encode -> parse is stable and within the datagram and command caps. //! How to run: see the comment at the top of `fuzz/Cargo.toml`. #![no_main] use libfuzzer_sys::fuzz_target; +use domistream::enet::protocol::{MAX_COMMANDS_PER_DATAGRAM, MAX_DATAGRAM_BYTES, encode_datagram, parse_datagram}; + fuzz_target!(|data: &[u8]| { - let _ = domistream::enet::protocol::parse_datagram(data); + if let Ok(d) = parse_datagram(data) { + assert!(data.len() <= MAX_DATAGRAM_BYTES); + assert!(d.commands.len() <= MAX_COMMANDS_PER_DATAGRAM); + let bytes = encode_datagram(&d).expect("a parsed datagram encodes"); + assert!(bytes.len() <= MAX_DATAGRAM_BYTES); + assert_eq!(parse_datagram(&bytes), Ok(d)); + } }); diff --git a/fuzz/fuzz_targets/fec_reconstruct.rs b/fuzz/fuzz_targets/fec_reconstruct.rs new file mode 100644 index 0000000..c7681a1 --- /dev/null +++ b/fuzz/fuzz_targets/fec_reconstruct.rs @@ -0,0 +1,40 @@ +//! Fuzzes Reed-Solomon reconstruction with fuzzer-chosen shapes and erasures. +//! Asserts invariants, not only "no panic": up to m erasures always rebuild the encoded data byte-exact; more are refused; hostile shard sets never panic. +//! How to run: see the comment at the top of `fuzz/Cargo.toml`. + +#![no_main] + +use libfuzzer_sys::fuzz_target; + +use domistream::fec::ReedSolomon; + +fuzz_target!(|data: &[u8]| { + if data.len() < 4 { + return; + } + let k = 1 + usize::from(data[0]) % 32; + let m = 1 + usize::from(data[1]) % 16; + let len = 1 + usize::from(data[2]) % 32; + let Ok(code) = ReedSolomon::new(k, m) else { return }; + let body = &data[3..]; + let mut shards: Vec> = + (0..k).map(|i| (0..len).map(|x| body[(i * len + x) % body.len()]).collect()).collect(); + shards.extend((0..m).map(|_| vec![0; len])); + code.encode(&mut shards).expect("encode"); + let mask = u32::from(body[body.len() - 1]); + let lost: Vec = (0..k + m).filter(|&i| (mask.rotate_left(i as u32) ^ (i as u32 * 7)) % 3 == 0).collect(); + let mut s: Vec>> = + shards.iter().enumerate().map(|(i, v)| (!lost.contains(&i)).then(|| v.clone())).collect(); + let r = code.reconstruct(&mut s); + if lost.len() <= m { + r.expect("<= m erasures rebuild"); + for (a, b) in s.iter().zip(&shards) { + assert_eq!(a.as_deref(), Some(b.as_slice())); + } + } else { + assert!(matches!(r, Err(domistream::Error::Truncated { .. }))); + } + // The raw bytes as a hostile shard set. + let mut hostile: Vec>> = body.chunks(len).map(|c| (c[0] & 1 == 0).then(|| c.to_vec())).collect(); + let _ = code.reconstruct(&mut hostile); +}); diff --git a/fuzz/fuzz_targets/input.rs b/fuzz/fuzz_targets/input.rs index 2c8ec11..737cffb 100644 --- a/fuzz/fuzz_targets/input.rs +++ b/fuzz/fuzz_targets/input.rs @@ -1,11 +1,18 @@ -//! Fuzzes INPUT_DATA messages: never panics, whatever the bytes. -//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic. +//! Fuzzes INPUT_DATA messages. +//! Asserts invariants, not only "no panic": parse -> encode -> parse is stable; an accepted message's length field matches. //! How to run: see the comment at the top of `fuzz/Cargo.toml`. #![no_main] use libfuzzer_sys::fuzz_target; +use domistream::input::{MAX_INPUT_MESSAGE_BYTES, encode_input, parse_input}; + fuzz_target!(|data: &[u8]| { - let _ = domistream::input::parse_input(data); + if let Ok(e) = parse_input(data) { + assert!(data.len() <= MAX_INPUT_MESSAGE_BYTES); + assert_eq!(usize::from(u16::from_le_bytes([data[2], data[3]])) + 4, data.len()); + let bytes = encode_input(&e).expect("a parsed event encodes"); + assert_eq!(parse_input(&bytes), Ok(e)); + } }); diff --git a/fuzz/fuzz_targets/launch_response.rs b/fuzz/fuzz_targets/launch_response.rs index e48eabb..58e47c0 100644 --- a/fuzz/fuzz_targets/launch_response.rs +++ b/fuzz/fuzz_targets/launch_response.rs @@ -1,11 +1,23 @@ -//! Fuzzes `/launch` and `/resume` answers: never panics, whatever the bytes. -//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic. +//! Fuzzes `/launch` and `/resume` answers. +//! Asserts invariants, not only "no panic": a session URL is within the cap, starts with rtsp:// and has no control characters. //! How to run: see the comment at the top of `fuzz/Cargo.toml`. #![no_main] use libfuzzer_sys::fuzz_target; +use domistream::http::launch::{MAX_LAUNCH_RESPONSE_BYTES, MAX_SESSION_URL_BYTES}; + fuzz_target!(|data: &[u8]| { - let _ = domistream::http::parse_launch_response(data); + let r = domistream::http::parse_launch_response(data); + if data.len() > MAX_LAUNCH_RESPONSE_BYTES { + assert!(matches!(r, Err(domistream::Error::TooLarge { .. }))); + } + if let Ok(l) = r { + if let Some(url) = l.session_url { + assert!(url.len() <= MAX_SESSION_URL_BYTES); + assert!(url.starts_with("rtsp://")); + assert!(!url.chars().any(char::is_control)); + } + } }); diff --git a/fuzz/fuzz_targets/media_decrypt.rs b/fuzz/fuzz_targets/media_decrypt.rs new file mode 100644 index 0000000..0859ce6 --- /dev/null +++ b/fuzz/fuzz_targets/media_decrypt.rs @@ -0,0 +1,21 @@ +//! Fuzzes the video (AES-GCM) and audio (AES-CBC) decryption of hostile packets. +//! Asserts invariants, not only "no panic": random video packets never pass the tag; audio output is shorter than its input, which is whole blocks. +//! How to run: see the comment at the top of `fuzz/Cargo.toml`. + +#![no_main] + +use libfuzzer_sys::fuzz_target; + +use domistream::SessionKeys; +use domistream::audio::AudioCipher; +use domistream::video::VideoCipher; + +fuzz_target!(|data: &[u8]| { + if let Ok(p) = VideoCipher::new([0x42; 16]).decrypt(data) { + panic!("forged video packet accepted: {} bytes", p.len()); + } + let seq = data.first().map_or(0, |b| u16::from(*b)); + if let Ok(p) = AudioCipher::new(&SessionKeys { rikey: [0x42; 16], rikeyid: 7 }).decrypt(seq, data) { + assert!(p.len() < data.len() && data.len() % 16 == 0); + } +}); diff --git a/fuzz/fuzz_targets/pair_response.rs b/fuzz/fuzz_targets/pair_response.rs index 2c44e80..9ded678 100644 --- a/fuzz/fuzz_targets/pair_response.rs +++ b/fuzz/fuzz_targets/pair_response.rs @@ -1,11 +1,21 @@ -//! Fuzzes pairing answers: never panics, whatever the bytes. -//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic. +//! Fuzzes pairing answers. +//! Asserts invariants, not only "no panic": decoded values are at most half the body (hex), oversize is TooLarge. //! How to run: see the comment at the top of `fuzz/Cargo.toml`. #![no_main] use libfuzzer_sys::fuzz_target; +use domistream::pairing::MAX_PAIR_RESPONSE_BYTES; + fuzz_target!(|data: &[u8]| { - let _ = domistream::pairing::parse_pair_response(data); + let r = domistream::pairing::parse_pair_response(data); + if data.len() > MAX_PAIR_RESPONSE_BYTES { + assert!(matches!(r, Err(domistream::Error::TooLarge { .. }))); + } + if let Ok(p) = r { + for v in [&p.plain_cert, &p.challenge_response, &p.pairing_secret].into_iter().flatten() { + assert!(v.len() * 2 <= data.len()); + } + } }); diff --git a/fuzz/fuzz_targets/pairing_session.rs b/fuzz/fuzz_targets/pairing_session.rs new file mode 100644 index 0000000..b04928e --- /dev/null +++ b/fuzz/fuzz_targets/pairing_session.rs @@ -0,0 +1,42 @@ +//! Fuzzes the pairing state machine: a session with the test-only identity fed fuzzer bodies at each step. +//! Asserts invariants, not only "no panic": a host that knows neither the PIN's key nor the host key never gets the session to Paired, and Failed is terminal. +//! How to run: see the comment at the top of `fuzz/Cargo.toml`. + +#![no_main] + +use libfuzzer_sys::fuzz_target; + +use domistream::RandomSource; +use domistream::pairing::{ClientIdentity, PairingSession, PairingState, PairingStep, Pin}; + +const VECTORS: &str = include_str!("../../crates/domistream/tests/fixtures/pairing.txt"); + +fn value(name: &str) -> Vec { + let prefix = format!("{name} = "); + let line = VECTORS.lines().find(|l| l.starts_with(&prefix)).expect("fixture value"); + let hex = &line[prefix.len()..]; + (0..hex.len()).step_by(2).map(|i| u8::from_str_radix(&hex[i..i + 2], 16).expect("hex")).collect() +} + +struct Fixed; +impl RandomSource for Fixed { + fn fill(&mut self, dest: &mut [u8]) { + dest.fill(0x33); + } +} + +fuzz_target!(|data: &[u8]| { + let Ok(id) = ClientIdentity::from_der(&value("client_cert_der"), &value("client_key_pkcs8_der")) else { return }; + let Ok(pin) = Pin::from_digits("4071") else { return }; + let Ok((mut s, _)) = PairingSession::start(&id, "0123456789ABCDEF", "fuzz", pin, &mut Fixed) else { return }; + // Bodies separated by 0xFF bytes (never valid in the XML); the HTTP status is always 200. + for body in data.split(|b| *b == 0xFF).take(6) { + let before = s.state(); + let r = s.handle_response(&id, 200, body, &mut Fixed); + assert!(!matches!(r, Ok(PairingStep::Paired(_))), "paired with a host that cannot know the PIN key"); + if let PairingState::Failed(_) = before { + assert!(r.is_err()); + assert_eq!(s.state(), before, "Failed is terminal"); + } + } +}); diff --git a/fuzz/fuzz_targets/rtp_header.rs b/fuzz/fuzz_targets/rtp_header.rs index 3a92d48..57be334 100644 --- a/fuzz/fuzz_targets/rtp_header.rs +++ b/fuzz/fuzz_targets/rtp_header.rs @@ -1,5 +1,5 @@ -//! Fuzzes the RTP header: never panics, whatever the bytes. -//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic. +//! Fuzzes the RTP header. +//! Asserts invariants, not only "no panic": success means at least 12 bytes and version 2, with the fields read big-endian from the bytes. //! How to run: see the comment at the top of `fuzz/Cargo.toml`. #![no_main] @@ -7,5 +7,11 @@ use libfuzzer_sys::fuzz_target; fuzz_target!(|data: &[u8]| { - let _ = domistream::rtp::parse_rtp_header(data); + if let Ok(h) = domistream::rtp::parse_rtp_header(data) { + assert!(data.len() >= domistream::rtp::RTP_HEADER_LEN); + assert_eq!(h.flags >> 6, 2); + assert_eq!(h.flags, data[0]); + assert_eq!(h.sequence, u16::from_be_bytes([data[2], data[3]])); + assert_eq!(h.timestamp, u32::from_be_bytes([data[4], data[5], data[6], data[7]])); + } }); diff --git a/fuzz/fuzz_targets/rtsp_client.rs b/fuzz/fuzz_targets/rtsp_client.rs new file mode 100644 index 0000000..122b889 --- /dev/null +++ b/fuzz/fuzz_targets/rtsp_client.rs @@ -0,0 +1,38 @@ +//! Fuzzes the RTSP client state machine with hostile answers. +//! Asserts invariants, not only "no panic": the requests it emits always parse, and it never reports Ready before a full exchange. +//! How to run: see the comment at the top of `fuzz/Cargo.toml`. + +#![no_main] + +use libfuzzer_sys::fuzz_target; + +use domistream::http::launch::AudioLayout; +use domistream::rtsp::client::VideoCodec; +use domistream::rtsp::{EncryptionFlags, RtspClient, RtspProgress, StreamConfig, parse_request}; + +fuzz_target!(|data: &[u8]| { + let config = StreamConfig { + width: 1920, + height: 1080, + fps: 60, + bitrate_kbps: 20_000, + packet_size: 1024, + codec: VideoCodec::Hevc, + hdr: false, + audio: AudioLayout::Stereo, + audio_packet_duration_ms: 5, + min_fec_packets: 2, + reference_frame_invalidation: true, + encryption: EncryptionFlags(7), + }; + let Ok(mut c) = RtspClient::new("rtsp://192.0.2.10:48010", config) else { return }; + // Answers separated by NUL bytes. + for (answers, answer) in data.split(|b| *b == 0).take(8).enumerate() { + if let Some(req) = c.poll_request() { + parse_request(&req).expect("the client's requests parse"); + } + if let Ok(RtspProgress::Ready(_)) = c.handle_response(answer) { + assert!(answers >= 6, "Ready after {} answers", answers + 1); + } + } +}); diff --git a/fuzz/fuzz_targets/rtsp_framer.rs b/fuzz/fuzz_targets/rtsp_framer.rs index da81e86..367e0b3 100644 --- a/fuzz/fuzz_targets/rtsp_framer.rs +++ b/fuzz/fuzz_targets/rtsp_framer.rs @@ -1,23 +1,37 @@ -//! Fuzzes the RTSP framer over a chunked byte stream: never panics, whatever the bytes. -//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic. +//! Fuzzes the RTSP framer over a chunked byte stream. +//! Asserts invariants, not only "no panic": never buffers past the cap, and the messages do not depend on how the stream is chunked (chunked vs one push). //! How to run: see the comment at the top of `fuzz/Cargo.toml`. #![no_main] use libfuzzer_sys::fuzz_target; +use domistream::rtsp::{MAX_RTSP_MESSAGE_BYTES, RtspFramer}; + +fn frame(stream: &[u8], chunk: usize) -> Option>> { + let mut f = RtspFramer::new(); + let mut out = Vec::new(); + for piece in stream.chunks(chunk) { + f.push(piece).ok()?; + assert!(f.buffered() <= MAX_RTSP_MESSAGE_BYTES); + while let Some(m) = f.next_message().ok()? { + let _ = domistream::rtsp::parse_response(&m); + out.push(m); + } + } + if let Some(last) = f.finish().ok()? { + out.push(last); + } + Some(out) +} + fuzz_target!(|data: &[u8]| { // First byte picks the chunk size, so libFuzzer explores message boundaries across pushes. let Some((&chunk, rest)) = data.split_first() else { return }; - let chunk = usize::from(chunk).max(1); - let mut framer = domistream::rtsp::RtspFramer::new(); - for piece in rest.chunks(chunk) { - if framer.push(piece).is_err() { - return; - } - while let Ok(Some(message)) = framer.next_message() { - let _ = domistream::rtsp::parse_response(&message); - } + let chunked = frame(rest, usize::from(chunk).max(1)); + let whole = frame(rest, rest.len().max(1)); + if let (Some(a), Some(b)) = (&chunked, &whole) { + assert_eq!(a, b, "framing depends on chunking"); + assert!(a.iter().map(Vec::len).sum::() <= rest.len()); } - let _ = framer.finish(); }); diff --git a/fuzz/fuzz_targets/rtsp_request.rs b/fuzz/fuzz_targets/rtsp_request.rs index e9dc2b8..b4afed0 100644 --- a/fuzz/fuzz_targets/rtsp_request.rs +++ b/fuzz/fuzz_targets/rtsp_request.rs @@ -1,5 +1,5 @@ -//! Fuzzes RTSP requests: never panics, whatever the bytes. -//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic. +//! Fuzzes RTSP requests. +//! Asserts invariants, not only "no panic": parse -> encode -> parse is stable. //! How to run: see the comment at the top of `fuzz/Cargo.toml`. #![no_main] @@ -7,5 +7,8 @@ use libfuzzer_sys::fuzz_target; fuzz_target!(|data: &[u8]| { - let _ = domistream::rtsp::parse_request(data); + if let Ok(req) = domistream::rtsp::parse_request(data) { + let bytes = req.encode().expect("a parsed request encodes"); + assert_eq!(domistream::rtsp::parse_request(&bytes), Ok(req)); + } }); diff --git a/fuzz/fuzz_targets/rtsp_response.rs b/fuzz/fuzz_targets/rtsp_response.rs index f155f1a..a479b60 100644 --- a/fuzz/fuzz_targets/rtsp_response.rs +++ b/fuzz/fuzz_targets/rtsp_response.rs @@ -1,11 +1,22 @@ -//! Fuzzes RTSP responses: never panics, whatever the bytes. -//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic. +//! Fuzzes RTSP responses. +//! Asserts invariants, not only "no panic": header count, line length and body within the caps. //! How to run: see the comment at the top of `fuzz/Cargo.toml`. #![no_main] use libfuzzer_sys::fuzz_target; +use domistream::rtsp::{MAX_RTSP_HEADERS, MAX_RTSP_LINE_BYTES, MAX_RTSP_MESSAGE_BYTES}; + fuzz_target!(|data: &[u8]| { - let _ = domistream::rtsp::parse_response(data); + let r = domistream::rtsp::parse_response(data); + if data.len() > MAX_RTSP_MESSAGE_BYTES { + assert!(matches!(r, Err(domistream::Error::TooLarge { .. }))); + } + if let Ok(m) = r { + assert!(m.headers.len() <= MAX_RTSP_HEADERS); + assert!(m.reason.len() <= MAX_RTSP_LINE_BYTES); + assert!(m.headers.iter().all(|(k, v)| k.len() + v.len() <= MAX_RTSP_LINE_BYTES)); + assert!(m.body.len() <= data.len()); + } }); diff --git a/fuzz/fuzz_targets/sdp.rs b/fuzz/fuzz_targets/sdp.rs index 7776f0b..d798d9a 100644 --- a/fuzz/fuzz_targets/sdp.rs +++ b/fuzz/fuzz_targets/sdp.rs @@ -1,13 +1,32 @@ -//! Fuzzes SDP payloads and the host capabilities read from them: never panics, whatever the bytes. -//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic. +//! Fuzzes SDP payloads, the host capabilities read from them, and `surround-params` values. +//! Asserts invariants, not only "no panic": line and config caps hold; every Opus config obeys RFC 7845's rules. //! How to run: see the comment at the top of `fuzz/Cargo.toml`. #![no_main] use libfuzzer_sys::fuzz_target; +use domistream::rtsp::sdp::{self, MAX_AUDIO_CHANNELS, MAX_OPUS_CONFIGS, MAX_SDP_LINES, OpusConfig}; + +fn valid(c: &OpusConfig) { + assert!(c.channels >= 1 && usize::from(c.channels) <= MAX_AUDIO_CHANNELS); + assert!(c.coupled_streams <= c.streams && c.streams >= 1); + assert_eq!(c.mapping.len(), usize::from(c.channels)); + let total = u16::from(c.streams) + u16::from(c.coupled_streams); + assert!(c.mapping.iter().all(|&m| u16::from(m) < total)); +} + fuzz_target!(|data: &[u8]| { - if let Ok(sdp) = domistream::rtsp::sdp::parse_sdp(data) { - let _ = domistream::rtsp::HostCapabilities::from_sdp(&sdp); + if let Ok(s) = sdp::parse_sdp(data) { + assert!(s.attributes.len() + s.other.len() <= MAX_SDP_LINES); + if let Ok(caps) = domistream::rtsp::HostCapabilities::from_sdp(&s) { + assert!(caps.opus_configs.len() <= MAX_OPUS_CONFIGS); + caps.opus_configs.iter().for_each(valid); + } + } + if let Ok(text) = core::str::from_utf8(data) { + if let Ok(c) = sdp::parse_surround_params(text) { + valid(&c); + } } }); diff --git a/fuzz/fuzz_targets/server_cert_der.rs b/fuzz/fuzz_targets/server_cert_der.rs new file mode 100644 index 0000000..4887ad2 --- /dev/null +++ b/fuzz/fuzz_targets/server_cert_der.rs @@ -0,0 +1,24 @@ +//! Fuzzes stored certificates and identities (`ServerCert::from_der`, `ClientIdentity::from_der`). +//! Asserts invariants, not only "no panic": accepted DER round-trips; an identity never loads from a cert and key that do not match (first byte splits the input). +//! How to run: see the comment at the top of `fuzz/Cargo.toml`. + +#![no_main] + +use libfuzzer_sys::fuzz_target; + +use domistream::pairing::{ClientIdentity, ServerCert}; + +fuzz_target!(|data: &[u8]| { + if let Ok(c) = ServerCert::from_der(data) { + assert_eq!(c.der(), data); + assert_eq!(c.matches(data), Ok(true)); + } + let Some((&split, rest)) = data.split_first() else { return }; + let at = (usize::from(split) * rest.len()) / 255; + let (cert, key) = rest.split_at(at.min(rest.len())); + if let Ok(id) = ClientIdentity::from_der(cert, key) { + assert_eq!(id.cert_der(), cert); + let sig = id.sign(b"fuzz").expect("a loaded identity signs"); + ServerCert::from_der(cert).expect("its cert loads").verify(b"fuzz", &sig).expect("key matches cert"); + } +}); diff --git a/fuzz/fuzz_targets/server_cert_pem.rs b/fuzz/fuzz_targets/server_cert_pem.rs index 2d7b083..d3d5c40 100644 --- a/fuzz/fuzz_targets/server_cert_pem.rs +++ b/fuzz/fuzz_targets/server_cert_pem.rs @@ -1,11 +1,24 @@ -//! Fuzzes the host certificate PEM (`plaincert`): never panics, whatever the bytes. -//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic. +//! Fuzzes the host certificate PEM (`plaincert`). +//! Asserts invariants, not only "no panic": an accepted PEM gives a DER that loads again, equals itself, pins itself, and has a signature. //! How to run: see the comment at the top of `fuzz/Cargo.toml`. #![no_main] use libfuzzer_sys::fuzz_target; +use domistream::pairing::ServerCert; +use domistream::pairing::identity::{MAX_CERT_DER_BYTES, MAX_CERT_PEM_BYTES}; + fuzz_target!(|data: &[u8]| { - let _ = domistream::pairing::ServerCert::from_pem(data); + let r = ServerCert::from_pem(data); + if data.len() > MAX_CERT_PEM_BYTES { + assert!(matches!(r, Err(domistream::Error::TooLarge { .. }))); + } + if let Ok(c) = r { + assert!(c.der().len() <= MAX_CERT_DER_BYTES); + let again = ServerCert::from_der(c.der()).expect("the DER of an accepted PEM loads"); + assert_eq!(again, c); + assert_eq!(c.matches(c.der()), Ok(true)); + assert!(!c.signature().expect("signature").is_empty()); + } }); diff --git a/fuzz/fuzz_targets/server_info.rs b/fuzz/fuzz_targets/server_info.rs index af21874..7ea458e 100644 --- a/fuzz/fuzz_targets/server_info.rs +++ b/fuzz/fuzz_targets/server_info.rs @@ -1,11 +1,26 @@ -//! Fuzzes `/serverinfo` answers: never panics, whatever the bytes. -//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic. +//! Fuzzes `/serverinfo` answers. +//! Asserts invariants, not only "no panic": string fields within MAX_SERVERINFO_FIELD_BYTES, required fields non-empty, oversize is TooLarge. //! How to run: see the comment at the top of `fuzz/Cargo.toml`. #![no_main] use libfuzzer_sys::fuzz_target; +use domistream::http::serverinfo::{MAX_SERVERINFO_BYTES, MAX_SERVERINFO_FIELD_BYTES}; + fuzz_target!(|data: &[u8]| { - let _ = domistream::http::parse_server_info(data); + let r = domistream::http::parse_server_info(data); + if data.len() > MAX_SERVERINFO_BYTES { + assert!(matches!(r, Err(domistream::Error::TooLarge { .. }))); + } + if let Ok(s) = r { + for f in [&s.hostname, &s.app_version, &s.unique_id, &s.state] { + assert!(f.len() <= MAX_SERVERINFO_FIELD_BYTES); + } + for f in [&s.gfe_version, &s.local_ip].into_iter().flatten() { + assert!(f.len() <= MAX_SERVERINFO_FIELD_BYTES); + } + assert!(!s.hostname.is_empty() && !s.unique_id.is_empty()); + let _ = s.is_busy(); + } }); diff --git a/fuzz/fuzz_targets/video_depacketizer.rs b/fuzz/fuzz_targets/video_depacketizer.rs new file mode 100644 index 0000000..904b18a --- /dev/null +++ b/fuzz/fuzz_targets/video_depacketizer.rs @@ -0,0 +1,41 @@ +//! Fuzzes the video depacketizer with a sequence of datagrams. +//! Asserts invariants, not only "no panic": frames stay within MAX_FRAME_BYTES and come out in increasing frame order; lost ranges are forward ranges. +//! How to run: see the comment at the top of `fuzz/Cargo.toml`. + +#![no_main] + +use libfuzzer_sys::fuzz_target; + +use core::time::Duration; + +use domistream::Instant; +use domistream::video::{MAX_FRAME_BYTES, VideoConfig, VideoDepacketizer, VideoEvent}; + +fuzz_target!(|data: &[u8]| { + let cfg = VideoConfig { packet_size: 64, cipher: None, frame_timeout: Duration::from_millis(20) }; + let Ok(mut d) = VideoDepacketizer::new(cfg) else { return }; + let mut rest = data; + let mut us = 0u64; + let mut prev: Option = None; + // Datagrams separated by a 1-byte length; time advances 1 ms per datagram. + while let Some((&len, tail)) = rest.split_first() { + let len = usize::from(len).min(tail.len()); + let (g, tail) = tail.split_at(len); + rest = tail; + us += 1000; + let _ = d.push(Instant::from_micros(us), g); + let _ = d.handle_timeout(Instant::from_micros(us)); + while let Some(e) = d.poll_event() { + match e { + VideoEvent::Frame(f) => { + assert!(f.bitstream.len() <= MAX_FRAME_BYTES); + if let Some(p) = prev { + assert!(f.frame_index.wrapping_sub(p).wrapping_sub(1) < 1 << 31, "frame order"); + } + prev = Some(f.frame_index); + } + VideoEvent::FrameLost { first, last } => assert!(last.wrapping_sub(first) < 1 << 31), + } + } + } +}); diff --git a/fuzz/fuzz_targets/video_packet.rs b/fuzz/fuzz_targets/video_packet.rs index f132815..9864d88 100644 --- a/fuzz/fuzz_targets/video_packet.rs +++ b/fuzz/fuzz_targets/video_packet.rs @@ -1,12 +1,24 @@ -//! Fuzzes video packets and the frame header: never panics, whatever the bytes. -//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic. +//! Fuzzes video packets and the frame header. +//! Asserts invariants, not only "no panic": FEC fields are consistent on success, the payload is the rest of the packet, the frame header keeps its raw bytes. //! How to run: see the comment at the top of `fuzz/Cargo.toml`. #![no_main] use libfuzzer_sys::fuzz_target; +use domistream::video::packet::{FRAME_HEADER_LEN, MAX_VIDEO_PACKET_BYTES, PAYLOAD_OFFSET, parse_frame_header}; + fuzz_target!(|data: &[u8]| { - let _ = domistream::video::parse_video_packet(data); - let _ = domistream::video::packet::parse_frame_header(data); + if let Ok(p) = domistream::video::parse_video_packet(data) { + assert!(data.len() >= PAYLOAD_OFFSET && data.len() <= MAX_VIDEO_PACKET_BYTES); + assert_eq!(p.payload.len() + PAYLOAD_OFFSET, data.len()); + let f = p.nv.fec; + assert!(f.data_shards > 0 && f.block_index <= f.last_block_index && f.last_block_index < 4); + let m = domistream::fec::parity_count(usize::from(f.data_shards), f.fec_percentage).expect("a consistent block"); + assert!(usize::from(f.shard_index) < usize::from(f.data_shards) + m); + assert!(usize::from(f.data_shards) + m <= domistream::fec::MAX_SHARDS); + } + if let Ok(h) = parse_frame_header(data) { + assert_eq!(&h.raw[..], &data[..FRAME_HEADER_LEN]); + } }); diff --git a/fuzz/fuzz_targets/xml.rs b/fuzz/fuzz_targets/xml.rs index b62d549..c4d42ba 100644 --- a/fuzz/fuzz_targets/xml.rs +++ b/fuzz/fuzz_targets/xml.rs @@ -1,11 +1,41 @@ -//! Fuzzes the XML reader behind every HTTP answer: never panics, whatever the bytes. -//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic. +//! Fuzzes the XML reader behind every HTTP answer, and `parse_status_response` on the same bytes. +//! Asserts invariants, not only "no panic": every cap holds on success, size over the cap is TooLarge, and the status parser agrees with the XML parser. //! How to run: see the comment at the top of `fuzz/Cargo.toml`. #![no_main] use libfuzzer_sys::fuzz_target; +use domistream::Error; +use domistream::http::xml::{self, Element, MAX_XML_ATTRIBUTES, MAX_XML_BYTES, MAX_XML_DEPTH, MAX_XML_ELEMENTS, MAX_XML_TEXT_BYTES}; + +fn walk(e: &Element, depth: usize, count: &mut usize) { + *count += 1; + assert!(depth <= MAX_XML_DEPTH); + assert!(e.attributes.len() <= MAX_XML_ATTRIBUTES); + assert!(e.text.len() <= MAX_XML_TEXT_BYTES); + for c in &e.children { + walk(c, depth + 1, count); + } +} + fuzz_target!(|data: &[u8]| { - let _ = domistream::http::xml::parse(data); + let parsed = xml::parse(data); + if data.len() > MAX_XML_BYTES { + assert!(matches!(parsed, Err(Error::TooLarge { .. }))); + } + if let Ok(d) = &parsed { + assert_eq!(d.root.name, "root"); + let mut count = 0; + walk(&d.root, 1, &mut count); + assert!(count <= MAX_XML_ELEMENTS); + } + let status = domistream::http::parse_status_response(data); + match (&parsed, &status) { + (Ok(d), Ok(())) => assert_eq!(d.status_code, 200), + (Ok(d), Err(Error::HostStatus { code })) => assert_eq!(d.status_code, *code), + (Ok(_), Err(e)) => panic!("xml parsed but status failed with {e:?}"), + (Err(_), Ok(())) => panic!("status accepted what xml refused"), + (Err(_), Err(_)) => {} + } });