From 7326767f37e01668675d81c98473ade744d6e5ff Mon Sep 17 00:00:00 2001 From: mnovak Date: Wed, 25 Nov 2026 12:51:00 +0100 Subject: [PATCH] [domistream] Tests: vector generator and shared test helpers tools/vectors/gen_vectors.py makes the crypto vectors with tools independent of RustCrypto: Python hashlib (SHA-256), the OpenSSL 3.5 CLI (RSA-2048 test-only keys, X.509 certs, PKCS#1 v1.5 SHA-256 signatures, AES-128-ECB -nopad, AES-128-CBC) and .NET 10 AesGcm (gcm_vectors.cs). Output goes to crates/domistream/tests/fixtures (text only); not generated in this commit. tests/common: seeded and scripted RandomSource, fixture reader, an independent GF(2^8)/0x11D reference with Cauchy matrices, and test hosts that packetize video (PROTOCOL.md 5.2-5.3) and audio (6.2-6.4). Dev-dependencies: proptest (std only, no fork/timeout) and peak_alloc (MIT, counting allocator for the allocation-cap test). --- crates/domistream/Cargo.toml | 6 + crates/domistream/tests/common/mod.rs | 717 ++++++++++++++++++++++++++ tools/vectors/gcm_vectors.cs | 32 ++ tools/vectors/gen_vectors.py | 437 ++++++++++++++++ 4 files changed, 1192 insertions(+) create mode 100644 crates/domistream/tests/common/mod.rs create mode 100644 tools/vectors/gcm_vectors.cs create mode 100644 tools/vectors/gen_vectors.py diff --git a/crates/domistream/Cargo.toml b/crates/domistream/Cargo.toml index 990a745..f282913 100644 --- a/crates/domistream/Cargo.toml +++ b/crates/domistream/Cargo.toml @@ -21,3 +21,9 @@ rsa = "0.10" # client key, PKCS#1 v1.5 SHA-256 sign/verify (crypto-bigin x509-cert = { version = "0.3", features = ["builder", "pem"] } # client certificate, host certificate parsing rand_core = "0.10" # adapter from our RandomSource to the RustCrypto RNG traits zeroize = "1.8" # wipe keys on drop + +# Tests only. proptest without fork/timeout (no subprocesses, no threads); peak_alloc (MIT) is a counting global +# allocator, so tests can check that parsers never allocate past their caps without any unsafe code of ours. +[dev-dependencies] +proptest = { version = "1.12", default-features = false, features = ["std"] } +peak_alloc = "0.3" diff --git a/crates/domistream/tests/common/mod.rs b/crates/domistream/tests/common/mod.rs new file mode 100644 index 0000000..8799434 --- /dev/null +++ b/crates/domistream/tests/common/mod.rs @@ -0,0 +1,717 @@ +//! Helpers shared by the integration tests: deterministic randomness, fixture loading, an independent GF(2^8) +//! reference, and builders for video and audio streams. Test code: panics are the way a test fails. + +#![allow(dead_code, unreachable_pub, clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing)] + +use std::collections::HashMap; + +use domistream::RandomSource; + +// ------------------------------------------------------------------------------------------------ assertions + +/// Asserts that `$e` is `Err` matching `$p` (an `Error` pattern), printing the actual value otherwise. +#[macro_export] +macro_rules! assert_err { + ($e:expr, $p:pat) => { + match $e { + Err($p) => {} + other => panic!("expected Err({}), got {:?}", stringify!($p), other), + } + }; + ($e:expr, $p:pat, $($ctx:tt)+) => { + match $e { + Err($p) => {} + other => panic!("expected Err({}), got {:?}: {}", stringify!($p), other, format!($($ctx)+)), + } + }; +} + +/// Asserts `Err(TooLarge { max, actual, .. })` with the given numbers. +#[macro_export] +macro_rules! assert_too_large { + ($e:expr, $max:expr, $actual:expr) => { + match $e { + Err(domistream::Error::TooLarge { max, actual, .. }) => { + assert_eq!(max, $max, "TooLarge.max"); + assert_eq!(actual, $actual, "TooLarge.actual"); + } + other => panic!("expected Err(TooLarge {{ max: {}, actual: {} }}), got {:?}", $max, $actual, other), + } + }; +} + +// ------------------------------------------------------------------------------------------------ randomness + +/// A seeded, deterministic random source (splitmix64). Never for production. +#[derive(Clone, Debug)] +pub struct SeqRng(u64); + +impl SeqRng { + pub fn new(seed: u64) -> Self { + Self(seed) + } + + pub fn next_u64(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + + /// Uniform in `0..n` (n > 0); bias is irrelevant for test data. + pub fn below(&mut self, n: usize) -> usize { + (self.next_u64() % n as u64) as usize + } + + pub fn bytes(&mut self, n: usize) -> Vec { + let mut v = vec![0; n]; + self.fill(&mut v); + v + } + + /// `count` distinct indices from `0..n`, sorted. + pub fn subset(&mut self, n: usize, count: usize) -> Vec { + let mut all: Vec = (0..n).collect(); + for i in 0..count.min(n) { + let j = i + self.below(n - i); + all.swap(i, j); + } + let mut chosen = all[..count.min(n)].to_vec(); + chosen.sort_unstable(); + chosen + } + + pub fn shuffle(&mut self, items: &mut [T]) { + for i in (1..items.len()).rev() { + let j = self.below(i + 1); + items.swap(i, j); + } + } +} + +impl RandomSource for SeqRng { + fn fill(&mut self, dest: &mut [u8]) { + for chunk in dest.chunks_mut(8) { + let word = self.next_u64().to_le_bytes(); + chunk.copy_from_slice(&word[..chunk.len()]); + } + } +} + +/// Hands out a fixed byte stream (a recorded transcript's randomness) and fails the test when the code under +/// test draws more than was recorded. +#[derive(Debug)] +pub struct ScriptedRng { + bytes: Vec, + pos: usize, +} + +impl ScriptedRng { + pub fn new(bytes: Vec) -> Self { + Self { bytes, pos: 0 } + } + + pub fn drawn(&self) -> usize { + self.pos + } +} + +impl RandomSource for ScriptedRng { + fn fill(&mut self, dest: &mut [u8]) { + let end = self.pos + dest.len(); + assert!( + end <= self.bytes.len(), + "the code drew {} random bytes but the recorded transcript holds only {} \ + (fixture assumption: salt, then C, then secret_c, 16 bytes each)", + end, + self.bytes.len() + ); + dest.copy_from_slice(&self.bytes[self.pos..end]); + self.pos = end; + } +} + +// ------------------------------------------------------------------------------------------------ fixtures + +pub fn hex(s: &str) -> Vec { + let s: String = s.chars().filter(|c| !c.is_whitespace()).collect(); + if s == "-" { + return Vec::new(); + } + assert!(s.len() % 2 == 0, "odd hex length"); + (0..s.len()).step_by(2).map(|i| u8::from_str_radix(&s[i..i + 2], 16).expect("hex digit")).collect() +} + +pub fn to_hex(b: &[u8]) -> String { + b.iter().map(|x| format!("{x:02x}")).collect() +} + +pub fn to_hex_upper(b: &[u8]) -> String { + b.iter().map(|x| format!("{x:02X}")).collect() +} + +/// A `name = value` fixture file written by `tools/vectors/gen_vectors.py`. +pub struct Vectors(HashMap); + +impl Vectors { + pub fn parse(text: &str) -> Self { + let mut map = HashMap::new(); + for line in text.lines() { + let line = line.trim(); + if line.is_empty() || line.starts_with('#') { + continue; + } + let (k, v) = line.split_once(" = ").expect("fixture line `name = value`"); + map.insert(k.to_string(), v.to_string()); + } + Self(map) + } + + pub fn str(&self, name: &str) -> &str { + self.0.get(name).unwrap_or_else(|| panic!("fixture value `{name}` missing")) + } + + pub fn bytes(&self, name: &str) -> Vec { + hex(self.str(name)) + } + + pub fn arr16(&self, name: &str) -> [u8; 16] { + self.bytes(name).try_into().unwrap_or_else(|_| panic!("`{name}` is not 16 bytes")) + } + + pub fn u32_hex(&self, name: &str) -> u32 { + u32::from_str_radix(self.str(name), 16).expect("hex u32") + } +} + +pub fn pairing_vectors() -> Vectors { + Vectors::parse(include_str!("../fixtures/pairing.txt")) +} + +pub fn control_vectors() -> Vectors { + Vectors::parse(include_str!("../fixtures/control_gcm.txt")) +} + +pub fn video_vectors() -> Vectors { + Vectors::parse(include_str!("../fixtures/video_gcm.txt")) +} + +pub fn audio_vectors() -> Vectors { + Vectors::parse(include_str!("../fixtures/audio_cbc.txt")) +} + +pub const HOST_CERT_PEM: &str = include_str!("../fixtures/test-only-host-cert.pem"); +pub const CLIENT_CERT_PEM: &str = include_str!("../fixtures/test-only-client-cert.pem"); +pub const ROGUE_CERT_PEM: &str = include_str!("../fixtures/test-only-rogue-cert.pem"); +pub const EC_CERT_PEM: &str = include_str!("../fixtures/test-only-ec-cert.pem"); +pub const CLIENT_KEY_PEM: &str = include_str!("../fixtures/test-only-client-key.pem"); + +/// Base64 (RFC 4648, standard alphabet, padding allowed) to bytes; panics on anything else. +pub fn base64_decode(s: &str) -> Vec { + let mut out = Vec::new(); + let mut acc = 0u32; + let mut bits = 0; + for c in s.bytes().filter(|c| !c.is_ascii_whitespace()) { + let v = match c { + b'A'..=b'Z' => c - b'A', + b'a'..=b'z' => c - b'a' + 26, + b'0'..=b'9' => c - b'0' + 52, + b'+' => 62, + b'/' => 63, + b'=' => break, + _ => panic!("not base64: {c:#x}"), + }; + acc = (acc << 6) | u32::from(v); + bits += 6; + if bits >= 8 { + bits -= 8; + out.push((acc >> bits) as u8); + } + } + out +} + +/// The DER inside every `-----BEGIN