//! "Caps every length before it allocates": with a counting global allocator (`peak_alloc`, no unsafe code of //! ours), feeds every parser small inputs whose length fields lie (claim gigabytes) and arbitrary inputs, and checks //! the peak heap growth stays within a bound tied to the input and the parser's caps, never to a claimed length. //! //! The counters are process-wide, so this file holds exactly one #[test] that runs everything in sequence. #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)] mod common; use domistream::{Instant, SessionKeys}; use peak_alloc::PeakAlloc; use proptest::prelude::*; use proptest::test_runner::{Config, TestRunner}; #[global_allocator] static ALLOC: PeakAlloc = PeakAlloc; /// Heap bytes `f` needs at its peak, beyond what was in use when it started. fn peak_of(f: impl FnOnce() -> R) -> usize { ALLOC.reset_peak_usage(); let before = ALLOC.current_usage(); let r = f(); let peak = ALLOC.peak_usage(); drop(r); peak.saturating_sub(before) } /// The budget for a parser given `input` bytes: its output may be a few times the input, plus fixed slack. A parser /// that trusts a lying length field blows far past this. fn budget(input: usize) -> usize { 64 * input + 256 * 1024 } fn check(what: &str, input: &[u8], f: impl FnOnce(&[u8]) -> bool) { let mut ran = false; let used = peak_of(|| ran = f(input)); assert!(ran, "{what}: Unimplemented, so its allocation is not measured yet"); assert!( used <= budget(input.len()), "{what}: {used} bytes at peak for a {}-byte input (budget {})", input.len(), budget(input.len()) ); } /// A parser under test: a name and a call that consumes the input. type Parser = (&'static str, fn(&[u8]) -> bool); /// A parser and the hostile input for it. type Case = (&'static str, Vec, fn(&[u8]) -> bool); fn lying_inputs() -> Vec { let mut v: Vec = Vec::new(); // RTSP: Content-Length claims 4 GiB. let rtsp = b"RTSP/1.0 200 OK\r\nCSeq: 1\r\nContent-Length: 4294967295\r\n\r\nabc".to_vec(); v.push(("rtsp response", rtsp.clone(), |b| common::implemented(&domistream::rtsp::parse_response(b)))); v.push(( "rtsp request", b"ANNOUNCE x RTSP/1.0\r\nCSeq: 1\r\nContent-Length: 4294967295\r\n\r\nabc".to_vec(), |b| common::implemented(&domistream::rtsp::parse_request(b)), )); v.push(("rtsp framer", rtsp, |b| { let mut f = domistream::rtsp::RtspFramer::new(); let pushed = f.push(b); let next = f.next_message(); let finished = f.finish(); common::implemented(&pushed) && common::implemented(&next) && common::implemented(&finished) })); // ENet: data length 65535 with 3 bytes, fragment claiming 4 GiB and 4 billion fragments. v.push(("enet reliable", vec![0x00, 0x01, 0x86, 0x00, 0x00, 0x01, 0xFF, 0xFF, 1, 2, 3], |b| { common::implemented(&domistream::enet::protocol::parse_datagram(b)) })); let mut frag = vec![0x00, 0x01, 0x88, 0x00, 0x00, 0x01]; frag.extend_from_slice(&1u16.to_be_bytes()); // start sequence frag.extend_from_slice(&10u16.to_be_bytes()); // data length frag.extend_from_slice(&u32::MAX.to_be_bytes()); // fragment count frag.extend_from_slice(&0u32.to_be_bytes()); // fragment number frag.extend_from_slice(&u32::MAX.to_be_bytes()); // total length frag.extend_from_slice(&0u32.to_be_bytes()); // offset frag.extend_from_slice(&[0; 10]); v.push(("enet fragment", frag, |b| common::implemented(&domistream::enet::protocol::parse_datagram(b)))); // Control: frame and message length fields at 65535. let mut frame = vec![0x01, 0x00, 0xFF, 0xFF, 0, 0, 0, 0]; frame.extend_from_slice(&[0; 16 + 8]); v.push(("control frame", frame.clone(), |b| common::implemented(&domistream::control::parse_encrypted_frame(b)))); v.push(("control open", frame, |b| { common::implemented( &domistream::control::ControlCipher::new([1; 16]).open(domistream::control::Direction::HostToClient, b), ) })); v.push(("control message", vec![0x0b, 0x01, 0xFF, 0xFF, 1, 2], |b| { common::implemented(&domistream::control::parse_host_message(b)) })); // Input: size field u32::MAX, length 65535. v.push(("input", vec![0x06, 0x02, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0, 0, 0, 1, 2], |b| { common::implemented(&domistream::input::parse_input(b)) })); // Video: 1023 data shards, frame header claiming a 4 GiB last payload. let p = common::video_packet_bytes(1, 0, 0, 0x05, 0, common::fec_info(200, 0, 1023), &[0xFF; 48]); v.push(("video packet", p.clone(), |b| common::implemented(&domistream::video::parse_video_packet(b)))); v.push(("frame header", vec![1, 0, 0, 2, 0xFF, 0xFF, 0xFF, 0xFF], |b| { common::implemented(&domistream::video::packet::parse_frame_header(b)) })); // Audio, XML, PEM, DER with lying lengths. v.push(( "audio packet", vec![0x80, 127, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 97, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], |b| common::implemented(&domistream::audio::parse_audio_packet(b)), )); v.push(("xml", b"�".to_vec(), |b| { common::implemented(&domistream::http::xml::parse(b)) })); let mut der = vec![0x30, 0x84, 0xFF, 0xFF, 0xFF, 0xFF]; der.extend_from_slice(&[0x30; 20]); v.push(("server cert der", der.clone(), |b| common::implemented(&domistream::pairing::ServerCert::from_der(b)))); v.push(("client identity der", der, |b| common::implemented(&domistream::pairing::ClientIdentity::from_der(b, b)))); v.push(("pem", b"-----BEGIN CERTIFICATE-----\nMIT/////\n-----END CERTIFICATE-----\n".to_vec(), |b| { common::implemented(&domistream::pairing::ServerCert::from_pem(b)) })); v.push(("pairing secret", vec![0; 17], |b| { common::implemented(&domistream::pairing::crypto::split_pairing_secret(b)) })); v } /// Stateful receivers: the bound is their caps (frames or blocks in flight), never a claimed size. fn depacketizer_checks() { use domistream::video::{MAX_FRAME_BYTES, MAX_FRAMES_IN_FLIGHT, VideoConfig, VideoDepacketizer}; let cap = MAX_FRAMES_IN_FLIGHT * MAX_FRAME_BYTES + 1024 * 1024; let used = peak_of(|| { let mut d = VideoDepacketizer::new(VideoConfig { packet_size: 1024, cipher: None, frame_timeout: core::time::Duration::from_millis(50), }) .unwrap(); // One packet each of many frames that each announce 4 blocks of 255 shards. for frame in 0..64u32 { let mut p = common::video_packet_bytes( frame as u16, 0, frame, 0x05, 3 << 6, common::fec_info(0, 0, 255), &[0xAB; 1024 - 16], ); p.resize(1024 + 16, 0); let _ = d.push(Instant::ZERO, &p); } d }); assert!(used <= cap, "video depacketizer: {used} bytes at peak (cap {cap})"); use domistream::audio::{AudioConfig, AudioDepacketizer, AudioFec, MAX_BLOCKS_IN_FLIGHT}; let cap = MAX_BLOCKS_IN_FLIGHT * 6 * domistream::audio::packet::MAX_AUDIO_PACKET_BYTES + 256 * 1024; let used = peak_of(|| { let mut d = AudioDepacketizer::new(AudioConfig { cipher: Some(domistream::audio::AudioCipher::new(&SessionKeys { rikey: [1; 16], rikeyid: 0 })), packet_duration_ms: 5, fec: AudioFec::ParityMatrix(common::audio_test_matrix()), loss_timeout: core::time::Duration::from_millis(40), }) .unwrap(); for seq in (0..2000u16).step_by(13) { let mut p = vec![0x80, 97]; p.extend_from_slice(&seq.wrapping_mul(97).to_be_bytes()); p.extend_from_slice(&[0; 8]); p.extend_from_slice(&[0x11; 2000]); let _ = d.push(Instant::ZERO, &p); } d }); assert!(used <= cap, "audio depacketizer: {used} bytes at peak (cap {cap})"); use domistream::enet::{EnetClient, EnetConfig, MAX_PACKET_BYTES}; let used = peak_of(|| { let cfg = EnetConfig { channel_count: 2, mtu: 1400, connect_data: 0, ping_interval: core::time::Duration::from_millis(500), timeout: core::time::Duration::from_secs(10), }; let mut c = EnetClient::connect(cfg, Instant::ZERO, &mut common::SeqRng::new(1)).unwrap(); // Fragments of 4 billion pieces and gigabyte totals, addressed to every peer id. for peer in 0..64u16 { let mut d = peer.to_be_bytes().to_vec(); d.extend_from_slice(&[0x88, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x04]); d.extend_from_slice(&u32::MAX.to_be_bytes()); d.extend_from_slice(&7u32.to_be_bytes()); d.extend_from_slice(&u32::MAX.to_be_bytes()); d.extend_from_slice(&0u32.to_be_bytes()); d.extend_from_slice(&[1, 2, 3, 4]); let _ = c.handle_datagram(Instant::ZERO, &d); } c }); assert!(used <= 4 * MAX_PACKET_BYTES + 256 * 1024, "enet client: {used} bytes at peak"); } #[test] fn parsers_never_allocate_past_their_caps() { for (what, input, f) in lying_inputs() { check(what, &input, f); } depacketizer_checks(); // Arbitrary inputs to every stateless parser. let mut runner = TestRunner::new(Config { cases: 400, ..Config::default() }); let parsers: Vec = vec![ ("xml", |b| common::implemented(&domistream::http::xml::parse(b))), ("serverinfo", |b| common::implemented(&domistream::http::parse_server_info(b))), ("applist", |b| common::implemented(&domistream::http::parse_app_list(b))), ("launch", |b| common::implemented(&domistream::http::parse_launch_response(b))), ("pair response", |b| common::implemented(&domistream::pairing::parse_pair_response(b))), ("pem", |b| common::implemented(&domistream::pairing::ServerCert::from_pem(b))), ("der", |b| common::implemented(&domistream::pairing::ServerCert::from_der(b))), ("rtsp response", |b| common::implemented(&domistream::rtsp::parse_response(b))), ("rtsp request", |b| common::implemented(&domistream::rtsp::parse_request(b))), ("sdp", |b| common::implemented(&domistream::rtsp::sdp::parse_sdp(b))), ("enet", |b| common::implemented(&domistream::enet::protocol::parse_datagram(b))), ("control frame", |b| common::implemented(&domistream::control::parse_encrypted_frame(b))), ("control message", |b| common::implemented(&domistream::control::parse_host_message(b))), ("input", |b| common::implemented(&domistream::input::parse_input(b))), ("rtp", |b| common::implemented(&domistream::rtp::parse_rtp_header(b))), ("video", |b| common::implemented(&domistream::video::parse_video_packet(b))), ("audio", |b| common::implemented(&domistream::audio::parse_audio_packet(b))), ("video decrypt", |b| common::implemented(&domistream::video::VideoCipher::new([2; 16]).decrypt(b))), ("audio decrypt", |b| { common::implemented( &domistream::audio::AudioCipher::new(&SessionKeys { rikey: [2; 16], rikeyid: 0 }).decrypt(0, b), ) }), ]; for (what, f) in parsers { runner .run(&proptest::collection::vec(any::(), 0..1500), |data| { let mut ran = false; let used = peak_of(|| ran = f(&data)); prop_assert!(ran, "{}: Unimplemented", what); prop_assert!( used <= budget(data.len()), "{}: {} bytes at peak for {} input bytes", what, used, data.len() ); Ok(()) }) .unwrap_or_else(|e| panic!("{what}: {e}")); } }