5 Commits

Author SHA1 Message Date
mnovak e4ca1509c8 [domistream] Tests: RTSP parsers, framer, SDP and client
Bad start lines, header floods, line cap, lying Content-Length (over, under,
past the cap, past u64), 64 KiB+1 in the framer, chunking invariance,
surround-params against RFC 7845, ANNOUNCE intersection, and the client state
machine with hostile answers.
2026-11-25 12:51:03 +01:00
mnovak d0fe9a906c [domistream] Tests: pairing state machine against recorded vectors
Walks every state with a recorded transcript (fixtures from tools/vectors).
Wrong PIN, wrong hash, wrong cert, rogue and flipped signatures, wrong sizes,
out-of-order, replayed and cross-session answers all end in Failed(reason);
Paired cannot be reached by skipping a step. Crypto helpers, certificates,
identities and the PIN against the same vectors.
2026-11-25 12:51:01 +01:00
mnovak b261d7ddc9 [domistream] Tests: hostile HTTP and XML input
XML reader, serverinfo, applist, launch and status answers: empty, 1 byte,
max-1, max, max+1, huge; depth bombs, element, attribute and text caps,
entities, DTD and billion laughs, namespaces. Request builders refuse bad ids
and query injection. proptest round trip of generated XML trees.
2026-11-25 12:51:01 +01:00
mnovak 9d94b66975 [domistream] Tests: sans-I/O guard and secret hygiene
Fails if src/ uses std::net, Instant::now, SystemTime::now, std::thread,
std::fs, processes, env reads or OS randomness (comments stripped, grouped
std imports caught). Checks forbid(unsafe_code) and that Debug never prints
rikey, the PIN or the private key.
2026-11-25 12:51:00 +01:00
mnovak 7326767f37 [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).
2026-11-25 12:51:00 +01:00
8 changed files with 3631 additions and 0 deletions
+6
View File
@@ -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 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 rand_core = "0.10" # adapter from our RandomSource to the RustCrypto RNG traits
zeroize = "1.8" # wipe keys on drop 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"
+717
View File
@@ -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<u8> {
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<usize> {
let mut all: Vec<usize> = (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<T>(&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<u8>,
pos: usize,
}
impl ScriptedRng {
pub fn new(bytes: Vec<u8>) -> 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<u8> {
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<String, String>);
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<u8> {
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<u8> {
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 <label>-----` block of a PEM text.
pub fn pem_blocks(pem: &str, label: &str) -> Vec<Vec<u8>> {
let begin = format!("-----BEGIN {label}-----");
let end = format!("-----END {label}-----");
let mut out = Vec::new();
let mut rest = pem;
while let Some(start) = rest.find(&begin) {
let after = &rest[start + begin.len()..];
let stop = after.find(&end).expect("PEM end line");
out.push(base64_decode(&after[..stop]));
rest = &after[stop + end.len()..];
}
out
}
// ------------------------------------------------------------------------------------------------ HTTP helpers
/// Splits a `path?query` into the path and its decoded parameters, in order.
pub fn parse_query(path_and_query: &str) -> (String, Vec<(String, String)>) {
let (path, query) = path_and_query.split_once('?').unwrap_or((path_and_query, ""));
let params = query
.split('&')
.filter(|p| !p.is_empty())
.map(|p| {
let (k, v) = p.split_once('=').unwrap_or((p, ""));
(percent_decode(k), percent_decode(v))
})
.collect();
(path.to_string(), params)
}
pub fn percent_decode(s: &str) -> String {
let b = s.as_bytes();
let mut out = Vec::new();
let mut i = 0;
while i < b.len() {
if b[i] == b'%' && i + 2 < b.len() {
let h = std::str::from_utf8(&b[i + 1..i + 3]).expect("utf8");
out.push(u8::from_str_radix(h, 16).expect("percent escape"));
i += 3;
} else if b[i] == b'+' {
out.push(b' ');
i += 1;
} else {
out.push(b[i]);
i += 1;
}
}
String::from_utf8(out).expect("decoded query is UTF-8")
}
/// The single value of `name`; fails when it is missing or repeated (parameter injection).
pub fn param<'a>(params: &'a [(String, String)], name: &str) -> &'a str {
let found: Vec<&(String, String)> = params.iter().filter(|(k, _)| k == name).collect();
assert_eq!(found.len(), 1, "query parameter `{name}` must appear exactly once in {params:?}");
&found[0].1
}
/// `<root status_code="200">` + elements + `</root>`.
pub fn xml_root(status: u32, inner: &str) -> Vec<u8> {
format!("<root status_code=\"{status}\">{inner}</root>").into_bytes()
}
/// A child element sequence of exactly `len` bytes (`len >= 7`): `<x>aaa…</x>` pieces of at most 207 bytes, so no
/// single text is long and the element count stays small.
pub fn xml_filler(len: usize) -> String {
assert!(len >= 7, "filler needs at least 7 bytes");
let mut out = String::with_capacity(len);
let mut remaining = len;
while remaining > 0 {
let piece = if remaining <= 207 {
remaining
} else if remaining - 207 >= 7 {
207
} else {
remaining - 7
};
out.push_str("<x>");
out.extend(std::iter::repeat_n('a', piece - 7));
out.push_str("</x>");
remaining -= piece;
}
assert_eq!(out.len(), len);
out
}
/// A document `<root status_code="200">{inner}{filler}</root>` of exactly `total` bytes.
pub fn xml_padded_to(inner: &str, total: usize) -> Vec<u8> {
let bare = xml_root(200, inner).len();
assert!(total >= bare + 7, "target {total} too small for {bare} + filler");
let doc = xml_root(200, &format!("{inner}{}", xml_filler(total - bare)));
assert_eq!(doc.len(), total);
doc
}
/// All subsets of `0..n` with exactly `size` elements, in lexicographic order.
pub fn subsets_of(n: usize, size: usize) -> Vec<Vec<usize>> {
fn go(start: usize, n: usize, size: usize, cur: &mut Vec<usize>, out: &mut Vec<Vec<usize>>) {
if cur.len() == size {
out.push(cur.clone());
return;
}
for i in start..n {
cur.push(i);
go(i + 1, n, size, cur, out);
cur.pop();
}
}
let mut out = Vec::new();
go(0, n, size, &mut Vec::new(), &mut out);
out
}
// ------------------------------------------------------------------------------------------------ GF(2^8)
/// An independent GF(2^8) reference with polynomial 0x11D (`docs/PROTOCOL.md` 5.3), from the field definition.
pub mod gf {
pub fn mul(mut a: u8, mut b: u8) -> u8 {
let mut p = 0u8;
while b != 0 {
if b & 1 != 0 {
p ^= a;
}
let carry = a & 0x80 != 0;
a <<= 1;
if carry {
a ^= 0x1D;
}
b >>= 1;
}
p
}
pub fn inv(a: u8) -> u8 {
assert!(a != 0, "no inverse of 0");
(1..=255u8).find(|&b| mul(a, b) == 1).expect("field inverse")
}
/// A `rows × cols` Cauchy matrix `1 / (x_i + y_j)` with `x_i = i`, `y_j = rows + j`: every square submatrix is
/// invertible, so `[I; C]` is MDS.
pub fn cauchy(rows: usize, cols: usize) -> Vec<u8> {
assert!(rows + cols <= 256);
let mut m = Vec::with_capacity(rows * cols);
for i in 0..rows {
for j in 0..cols {
m.push(inv((i as u8) ^ ((rows + j) as u8)));
}
}
m
}
/// Parity shards for `data` with a row-major `parity × data` matrix.
pub fn encode(matrix: &[u8], data: &[Vec<u8>], parity: usize) -> Vec<Vec<u8>> {
let k = data.len();
let len = data[0].len();
(0..parity)
.map(|r| {
(0..len)
.map(|x| (0..k).fold(0u8, |acc, c| acc ^ mul(matrix[r * k + c], data[c][x])))
.collect()
})
.collect()
}
}
// ------------------------------------------------------------------------------------------------ video
/// One video packet as the test host built it.
#[derive(Clone, Debug)]
pub struct VPkt {
pub bytes: Vec<u8>,
pub frame_index: u32,
pub block: u8,
pub shard_index: u16,
pub data_shards: u16,
pub parity_shards: u16,
pub is_parity: bool,
}
/// What a frame should come out as.
#[derive(Clone, Debug)]
pub struct VExpect {
pub frame_index: u32,
pub header: [u8; 8],
pub bitstream: Vec<u8>,
pub rtp_timestamp: u32,
}
/// A test host that packetizes frames as `docs/PROTOCOL.md` 5.2-5.3 describe (Moonshine-style frame header).
#[derive(Clone, Debug)]
pub struct VideoHost {
pub packet_size: u16,
pub next_sequence: u16,
pub timestamp: u32,
/// When set, parity is computed over data shards whose bytes 0-31 are replaced by this pattern (a host may
/// compute parity before writing headers), so a recovered shard's header is guaranteed garbage.
pub scramble_parity_headers: bool,
}
impl VideoHost {
pub fn new(packet_size: u16) -> Self {
Self { packet_size, next_sequence: 0, timestamp: 90_000, scramble_parity_headers: false }
}
pub fn payload_len(&self) -> usize {
usize::from(self.packet_size) - 16
}
/// An Annex-B bitstream of about `len` bytes that ends in a nonzero byte (so trimming the zero padding by
/// either the frame header's length or the content gives the same answer: UNKNOWN U13).
pub fn bitstream(rng: &mut SeqRng, len: usize) -> Vec<u8> {
let mut b = vec![0, 0, 0, 1, 0x65];
b.extend(rng.bytes(len.saturating_sub(6)));
b.push(0x80 | rng.bytes(1)[0]);
b
}
/// Packetizes one frame into `blocks` FEC blocks at `fec_percentage`.
pub fn frame(
&mut self,
frame_index: u32,
bitstream: &[u8],
fec_percentage: u8,
blocks: usize,
) -> (Vec<VPkt>, VExpect) {
let payload_len = self.payload_len();
let total_len = 8 + bitstream.len();
let shards_total = total_len.div_ceil(payload_len);
let last_payload_len = total_len - (shards_total - 1) * payload_len;
let mut header = [0u8; 8];
header[0] = 0x01;
header[1..3].copy_from_slice(&7u16.to_le_bytes());
header[3] = 2; // key frame
header[4..8].copy_from_slice(&(last_payload_len as u32).to_le_bytes());
let mut data = header.to_vec();
data.extend_from_slice(bitstream);
data.resize(shards_total * payload_len, 0);
let blocks = blocks.clamp(1, 4).min(shards_total);
let base = shards_total / blocks;
let extra = shards_total % blocks;
let last_block = (blocks - 1) as u8;
let mut packets = Vec::new();
let mut shard_offset = 0;
for b in 0..blocks {
let k = base + usize::from(b < extra);
let m = (k * usize::from(fec_percentage)).div_ceil(100);
assert!(k + m <= 255, "test frame needs k + m <= 255");
let mut shards: Vec<Vec<u8>> = Vec::with_capacity(k + m);
for i in 0..k {
let global = shard_offset + i;
let mut flags = 0x01;
if global == 0 {
flags |= 0x04;
}
if global == shards_total - 1 {
flags |= 0x02;
}
let mut p = self.header(frame_index, flags, b as u8, last_block, i, k, fec_percentage);
p.extend_from_slice(&data[global * payload_len..(global + 1) * payload_len]);
shards.push(p);
}
if m > 0 {
let code = domistream::fec::ReedSolomon::new(k, m)
.expect("ReedSolomon::new for the test host (Phase A: Unimplemented)");
let shard_len = shards[0].len();
let mut work: Vec<Vec<u8>> = shards.clone();
if self.scramble_parity_headers {
for (i, s) in work.iter_mut().enumerate() {
for (x, byte) in s[..32].iter_mut().enumerate() {
*byte = (0xA5 ^ (i as u8).wrapping_mul(31) ^ (x as u8).wrapping_mul(7)) | 1;
}
}
}
work.extend((0..m).map(|_| vec![0u8; shard_len]));
code.encode(&mut work).expect("ReedSolomon::encode for the test host");
for j in 0..m {
let mut p = self.header(frame_index, 0, b as u8, last_block, k + j, k, fec_percentage);
p.extend_from_slice(&work[k + j][32..]);
shards.push(p);
}
}
for (i, bytes) in shards.into_iter().enumerate() {
packets.push(VPkt {
bytes,
frame_index,
block: b as u8,
shard_index: i as u16,
data_shards: k as u16,
parity_shards: m as u16,
is_parity: i >= k,
});
}
shard_offset += k;
}
let expect = VExpect { frame_index, header, bitstream: bitstream.to_vec(), rtp_timestamp: self.timestamp };
self.timestamp = self.timestamp.wrapping_add(1500);
(packets, expect)
}
/// RTP header + 4 reserved + NV header for the next sequence number (all packets of a frame share the
/// timestamp).
#[allow(clippy::too_many_arguments)]
fn header(
&mut self,
frame_index: u32,
flags: u8,
block: u8,
last_block: u8,
shard_index: usize,
data_shards: usize,
fec_percentage: u8,
) -> Vec<u8> {
let seq = self.next_sequence;
self.next_sequence = self.next_sequence.wrapping_add(1);
let mut p = Vec::with_capacity(usize::from(self.packet_size) + 16);
p.extend_from_slice(&[0x90, 0x00]);
p.extend_from_slice(&seq.to_be_bytes());
p.extend_from_slice(&self.timestamp.to_be_bytes());
p.extend_from_slice(&0u32.to_be_bytes());
p.extend_from_slice(&[0; 4]);
p.extend_from_slice(&(u32::from(seq) << 8).to_le_bytes());
p.extend_from_slice(&frame_index.to_le_bytes());
p.push(flags);
p.push(0);
p.push(0x10);
p.push((block << 4) | (last_block << 6));
let fec_info =
(u32::from(fec_percentage) << 4) | ((shard_index as u32) << 12) | ((data_shards as u32) << 22);
p.extend_from_slice(&fec_info.to_le_bytes());
p
}
}
/// Builds one NV video packet by hand from the field table (`docs/PROTOCOL.md` 5.2).
#[allow(clippy::too_many_arguments)]
pub fn video_packet_bytes(
seq: u16,
timestamp: u32,
frame_index: u32,
flags: u8,
multi_fec_blocks: u8,
fec_info: u32,
payload: &[u8],
) -> Vec<u8> {
let mut p = vec![0x90, 0x00];
p.extend_from_slice(&seq.to_be_bytes());
p.extend_from_slice(&timestamp.to_be_bytes());
p.extend_from_slice(&0u32.to_be_bytes());
p.extend_from_slice(&[0; 4]);
p.extend_from_slice(&(u32::from(seq) << 8).to_le_bytes());
p.extend_from_slice(&frame_index.to_le_bytes());
p.extend_from_slice(&[flags, 0, 0x10, multi_fec_blocks]);
p.extend_from_slice(&fec_info.to_le_bytes());
p.extend_from_slice(payload);
p
}
pub fn fec_info(fec_percentage: u8, shard_index: u16, data_shards: u16) -> u32 {
(u32::from(fec_percentage) << 4) | (u32::from(shard_index) << 12) | (u32::from(data_shards) << 22)
}
/// AES-128-GCM sealing of a plaintext video packet with the layout of `docs/PROTOCOL.md` 7, using RustCrypto as
/// the test oracle (checked against the .NET vectors in `media.rs`).
pub fn video_encrypt(key: &[u8; 16], counter: u64, frame_number: u32, plaintext: &[u8]) -> Vec<u8> {
use aes_gcm::aead::{AeadInOut, KeyInit};
let cipher = aes_gcm::Aes128Gcm::new_from_slice(key).expect("key");
let mut iv = [0u8; 12];
iv[..8].copy_from_slice(&counter.to_le_bytes());
iv[11] = b'V';
let mut buf = plaintext.to_vec();
let tag = cipher
.encrypt_inout_detached(&iv.into(), b"", buf.as_mut_slice().into())
.expect("gcm encrypt");
let mut out = iv.to_vec();
out.extend_from_slice(&frame_number.to_le_bytes());
out.extend_from_slice(tag.as_slice());
out.extend_from_slice(&buf);
out
}
// ------------------------------------------------------------------------------------------------ audio
/// AES-128-CBC + PKCS#7 with the audio IV of `docs/PROTOCOL.md` 6.3 (`rikeyid + seq`, wrapping), RustCrypto as
/// the test oracle (checked against the openssl vectors in `media.rs`).
pub fn audio_encrypt(key: &[u8; 16], rikeyid: u32, seq: u16, plaintext: &[u8]) -> Vec<u8> {
use cbc::cipher::{BlockModeEncrypt, KeyIvInit, block_padding::Pkcs7};
let mut iv = [0u8; 16];
iv[..4].copy_from_slice(&rikeyid.wrapping_add(u32::from(seq)).to_be_bytes());
let mut buf = vec![0u8; (plaintext.len() / 16 + 1) * 16];
buf[..plaintext.len()].copy_from_slice(plaintext);
let len = cbc::Encryptor::<aes::Aes128>::new(key.into(), &iv.into())
.encrypt_padded::<Pkcs7>(&mut buf, plaintext.len())
.expect("cbc encrypt")
.len();
buf.truncate(len);
buf
}
/// One audio packet as the test host built it.
#[derive(Clone, Debug)]
pub struct APkt {
pub bytes: Vec<u8>,
pub sequence: u16,
pub block: usize,
/// 0..4 data, 4..6 parity.
pub index: usize,
}
/// What a data packet should come out as.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AExpect {
pub sequence: u16,
pub timestamp_ms: u32,
pub opus: Vec<u8>,
}
/// Parity packets' RTP sequence number: "continues after the 4 data packets" (PROTOCOL.md 6.2), read as
/// base + 4 + shard index. The depacketizer must key parity by the FEC header's base sequence, not by this.
pub fn audio_parity_rtp_sequence(base: u16, shard: u8) -> u16 {
base.wrapping_add(4).wrapping_add(u16::from(shard))
}
/// A test host for audio: blocks of 4 data + 2 parity packets (`docs/PROTOCOL.md` 6.2-6.4).
pub struct AudioHost {
pub key: [u8; 16],
pub rikeyid: u32,
pub encrypt: bool,
pub matrix: [u8; 8],
pub duration_ms: u32,
pub opus_len: usize,
}
impl AudioHost {
/// `blocks` consecutive blocks starting at `first_seq` (a multiple of 4) and `first_ts`.
pub fn blocks(&self, rng: &mut SeqRng, first_seq: u16, first_ts: u32, blocks: usize) -> (Vec<APkt>, Vec<AExpect>) {
assert_eq!(first_seq % 4, 0);
let mut packets = Vec::new();
let mut expect = Vec::new();
for b in 0..blocks {
let base_seq = first_seq.wrapping_add((4 * b) as u16);
let base_ts = first_ts.wrapping_add(4 * b as u32 * self.duration_ms);
let mut shards = Vec::new();
for i in 0..4u16 {
let seq = base_seq.wrapping_add(i);
let ts = base_ts.wrapping_add(u32::from(i) * self.duration_ms);
let opus = rng.bytes(self.opus_len);
let payload =
if self.encrypt { audio_encrypt(&self.key, self.rikeyid, seq, &opus) } else { opus.clone() };
let mut p = vec![0x80, 97];
p.extend_from_slice(&seq.to_be_bytes());
p.extend_from_slice(&ts.to_be_bytes());
p.extend_from_slice(&0u32.to_be_bytes());
p.extend_from_slice(&payload);
packets.push(APkt { bytes: p, sequence: seq, block: b, index: usize::from(i) });
expect.push(AExpect { sequence: seq, timestamp_ms: ts, opus });
shards.push(payload);
}
let parity = gf::encode(&self.matrix, &shards, 2);
for (j, par) in parity.iter().enumerate() {
let seq = audio_parity_rtp_sequence(base_seq, j as u8);
let mut p = vec![0x80, 127];
p.extend_from_slice(&seq.to_be_bytes());
p.extend_from_slice(&base_ts.to_be_bytes());
p.extend_from_slice(&0u32.to_be_bytes());
p.push(j as u8);
p.push(97);
p.extend_from_slice(&base_seq.to_be_bytes());
p.extend_from_slice(&base_ts.to_be_bytes());
p.extend_from_slice(&0u32.to_be_bytes());
p.extend_from_slice(par);
packets.push(APkt { bytes: p, sequence: seq, block: b, index: 4 + j });
}
}
(packets, expect)
}
}
/// The 2 × 4 Cauchy parity matrix the audio tests pass through `AudioFec::ParityMatrix` (U16 is unmeasured; any
/// MDS matrix must work).
pub fn audio_test_matrix() -> [u8; 8] {
gf::cauchy(2, 4).try_into().expect("2x4")
}
+663
View File
@@ -0,0 +1,663 @@
//! Hostile input for the HTTP side (`docs/PROTOCOL.md` 1.1-1.4): the XML reader, serverinfo, applist, launch and
//! status answers, and the request builders. Every case asserts a specific result.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
mod common;
use common::{param, parse_query, xml_padded_to, xml_root};
use domistream::Error;
use domistream::http::xml::{self, MAX_XML_ATTRIBUTES, MAX_XML_BYTES, MAX_XML_DEPTH, MAX_XML_ELEMENTS, MAX_XML_TEXT_BYTES};
use domistream::http::{self, Scheme};
use proptest::prelude::*;
/// Asserts `Err(TooLarge { max, .. })` for caps where `actual` is a count the parser chooses how to report.
macro_rules! assert_cap {
($e:expr, $max:expr) => {
match $e {
Err(Error::TooLarge { max, .. }) => assert_eq!(max, $max, "TooLarge.max"),
other => panic!("expected Err(TooLarge {{ max: {} }}), got {:?}", $max, other),
}
};
}
// ================================================================================================ XML
#[test]
fn xml_minimal_documents() {
let d = xml::parse(br#"<root status_code="200"/>"#).unwrap();
assert_eq!(d.status_code, 200);
assert_eq!(d.status_message, None);
assert_eq!(d.root.name, "root");
assert!(d.root.children.is_empty());
let d = xml::parse(br#"<?xml version="1.0" encoding="utf-8"?><root status_code="200"></root>"#).unwrap();
assert_eq!(d.status_code, 200);
let d = xml::parse(br#"<root status_code="401" status_message="The client is not authorized"/>"#).unwrap();
assert_eq!(d.status_code, 401, "xml::parse reports the status; refusing it is the callers' job");
assert_eq!(d.status_message.as_deref(), Some("The client is not authorized"));
}
#[test]
fn xml_tree_text_and_attributes() {
let d = xml::parse(br#"<root status_code="200" a="1"><x k="v&amp;w">t1<y/>t2</x><z>&lt;&gt;&amp;&quot;&apos;&#65;&#x42;</z></root>"#)
.unwrap();
assert_eq!(d.root.attributes, vec![("status_code".into(), "200".into()), ("a".into(), "1".into())]);
let x = &d.root.children[0];
assert_eq!(x.name, "x");
assert_eq!(x.attributes, vec![("k".into(), "v&w".into())]);
assert_eq!(x.text, "t1t2", "text is concatenated around child elements");
assert_eq!(x.children[0].name, "y");
assert_eq!(d.root.children[1].text, "<>&\"'AB");
}
#[test]
fn xml_text_is_not_trimmed() {
let d = xml::parse(b"<root status_code=\"200\"><a> x \n</a></root>").unwrap();
assert_eq!(d.root.children[0].text, " x \n");
}
#[test]
fn xml_empty_and_tiny_inputs() {
assert_err!(xml::parse(b""), Error::Malformed { .. });
assert_err!(xml::parse(b"<"), Error::Malformed { .. });
assert_err!(xml::parse(b"x"), Error::Malformed { .. });
assert_err!(xml::parse(b"<root"), Error::Malformed { .. });
assert_err!(xml::parse(b"<root status_code=\"200\">"), Error::Malformed { .. }, "unclosed root");
}
#[test]
fn xml_refuses_non_documents() {
for (bad, why) in [
(&br#"<other status_code="200"/>"#[..], "root must be `root`"),
(br#"<root/>"#, "no status_code"),
(br#"<root status_code="abc"/>"#, "status_code not decimal"),
(br#"<root status_code=""/>"#, "empty status_code"),
(br#"<root status_code="99999999999"/>"#, "status_code over u32"),
(br#"<root status_code="-200"/>"#, "negative status_code"),
(br#"<root status_code=200/>"#, "unquoted attribute"),
(br#"<root status_code="200" status_code="200"/>"#, "duplicate attribute"),
(br#"<root status_code="200"><a></b></root>"#, "mismatched end tag"),
(br#"<root status_code="200"><a></root>"#, "unclosed child"),
(br#"<root status_code="200"/><root status_code="200"/>"#, "two roots"),
(br#"<root status_code="200"/>garbage"#, "text after the root"),
(br#"<root status_code="200">&unknown;</root>"#, "unknown entity"),
(br#"<root status_code="200">&amp</root>"#, "entity without ;"),
(br#"<root status_code="200">a & b</root>"#, "bare &"),
(br#"<root status_code="200">&#0;</root>"#, "NUL character reference"),
(br#"<root status_code="200">&#xD800;</root>"#, "surrogate character reference"),
(br#"<root status_code="200">&#x110000;</root>"#, "character reference past Unicode"),
(br#"<root status_code="200">&#99999999999999999999;</root>"#, "overflowing character reference"),
(br#"<root status_code="200">&#xZZ;</root>"#, "bad hex reference"),
(br#"<root status_code="200"><a b="<"/></root>"#, "< in attribute value"),
(br#"<!DOCTYPE root><root status_code="200"/>"#, "DTD"),
(br#"<?xml version="1.0"?><!DOCTYPE r [<!ENTITY a "aaaa">]><root status_code="200">&a;</root>"#, "entity declaration"),
(br#"<root status_code="200"><?pi data?></root>"#, "processing instruction in the body"),
(br#" <?xml version="1.0"?><root status_code="200"/>"#, "XML declaration not at the start"),
(br#"<root xmlns:a="urn:x" status_code="200"><a:b/></root>"#, "namespaces"),
(b"<root status_code=\"200\">\xff\xfe</root>", "not UTF-8"),
(b"<root status_code=\"200\">\xc3</root>", "truncated UTF-8"),
(br#"<1root status_code="200"/>"#, "bad name"),
] {
assert_err!(xml::parse(bad), Error::Malformed { .. }, "{why}");
}
}
#[test]
fn xml_billion_laughs_is_refused_without_expansion() {
let mut doc = String::from("<?xml version=\"1.0\"?><!DOCTYPE lolz [<!ENTITY lol \"lol\">");
for i in 1..10 {
doc.push_str(&format!("<!ENTITY lol{i} \"{}\">", format!("&lol{};", i - 1).repeat(10)));
}
doc.push_str("]><root status_code=\"200\">&lol9;</root>");
assert_err!(xml::parse(doc.as_bytes()), Error::Malformed { .. });
}
#[test]
fn xml_size_boundaries() {
// max-1 and max are fine (a valid document of exactly that size), max+1 is refused before parsing.
for len in [MAX_XML_BYTES - 1, MAX_XML_BYTES] {
let d = xml::parse(&xml_padded_to("", len)).unwrap_or_else(|e| panic!("{len} bytes: {e:?}"));
assert_eq!(d.status_code, 200);
}
let over = xml_padded_to("", MAX_XML_BYTES + 1);
assert_too_large!(xml::parse(&over), MAX_XML_BYTES, MAX_XML_BYTES + 1);
// Huge: refused on size alone, whatever the content.
let huge = vec![b'<'; 4 * MAX_XML_BYTES];
assert_too_large!(xml::parse(&huge), MAX_XML_BYTES, 4 * MAX_XML_BYTES);
}
fn nested(depth: usize) -> Vec<u8> {
// root is depth 1
let mut s = String::from("<root status_code=\"200\">");
for _ in 1..depth {
s.push_str("<a>");
}
for _ in 1..depth {
s.push_str("</a>");
}
s.push_str("</root>");
s.into_bytes()
}
#[test]
fn xml_depth_cap() {
let d = xml::parse(&nested(MAX_XML_DEPTH)).unwrap();
let mut e = &d.root;
let mut depth = 1;
while let Some(c) = e.children.first() {
e = c;
depth += 1;
}
assert_eq!(depth, MAX_XML_DEPTH);
assert_cap!(xml::parse(&nested(MAX_XML_DEPTH + 1)), MAX_XML_DEPTH);
}
#[test]
fn xml_depth_bomb_does_not_recurse() {
// 300 000 open tags in under 1 MiB: a recursive parser overflows the stack; a strict one stops at depth 9.
let mut s = String::from("<root status_code=\"200\">");
s.push_str(&"<a>".repeat(300_000));
assert!(s.len() < MAX_XML_BYTES);
assert_cap!(xml::parse(s.as_bytes()), MAX_XML_DEPTH);
// Same with the closing tags present.
s.push_str(&"</a>".repeat(300_000));
s.push_str("</root>");
assert!(s.len() < MAX_XML_BYTES * 2);
if s.len() <= MAX_XML_BYTES {
assert_cap!(xml::parse(s.as_bytes()), MAX_XML_DEPTH);
}
}
#[test]
fn xml_element_cap() {
let ok = xml_root(200, &"<a/>".repeat(MAX_XML_ELEMENTS - 1));
assert_eq!(xml::parse(&ok).unwrap().root.children.len(), MAX_XML_ELEMENTS - 1);
let over = xml_root(200, &"<a/>".repeat(MAX_XML_ELEMENTS));
assert_cap!(xml::parse(&over), MAX_XML_ELEMENTS);
}
#[test]
fn xml_attribute_cap() {
let attrs = |n: usize| (1..n).map(|i| format!(" a{i}=\"{i}\"")).collect::<String>();
let ok = format!("<root status_code=\"200\"{}/>", attrs(MAX_XML_ATTRIBUTES));
assert_eq!(xml::parse(ok.as_bytes()).unwrap().root.attributes.len(), MAX_XML_ATTRIBUTES);
let over = format!("<root status_code=\"200\"{}/>", attrs(MAX_XML_ATTRIBUTES + 1));
assert_cap!(xml::parse(over.as_bytes()), MAX_XML_ATTRIBUTES);
}
#[test]
fn xml_text_cap_counts_unescaped_bytes() {
let ok = xml_root(200, &format!("<t>{}</t>", "a".repeat(MAX_XML_TEXT_BYTES)));
assert_eq!(xml::parse(&ok).unwrap().root.children[0].text.len(), MAX_XML_TEXT_BYTES);
let over = xml_root(200, &format!("<t>{}</t>", "a".repeat(MAX_XML_TEXT_BYTES + 1)));
assert_cap!(xml::parse(&over), MAX_XML_TEXT_BYTES);
// 5 raw bytes per unescaped byte: the cap is on the result, not the input.
let ok = xml_root(200, &format!("<t>{}</t>", "&amp;".repeat(MAX_XML_TEXT_BYTES)));
assert_eq!(xml::parse(&ok).unwrap().root.children[0].text.len(), MAX_XML_TEXT_BYTES);
let over = xml_root(200, &format!("<t>{}</t>", "&amp;".repeat(MAX_XML_TEXT_BYTES + 1)));
assert_cap!(xml::parse(&over), MAX_XML_TEXT_BYTES);
}
// ------------------------------------------------------------------------------------------------ XML properties
#[derive(Clone, Debug)]
struct Tree {
name: String,
attrs: Vec<(String, String)>,
text: String,
children: Vec<Tree>,
}
fn escape(s: &str) -> String {
s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;").replace('\'', "&apos;")
}
fn serialize(t: &Tree, out: &mut String) {
out.push('<');
out.push_str(&t.name);
for (k, v) in &t.attrs {
out.push_str(&format!(" {k}=\"{}\"", escape(v)));
}
out.push('>');
out.push_str(&escape(&t.text));
for c in &t.children {
serialize(c, out);
}
out.push_str(&format!("</{}>", t.name));
}
fn same(e: &xml::Element, t: &Tree) -> bool {
e.name == t.name
&& e.attributes == t.attrs
&& e.text == t.text
&& e.children.len() == t.children.len()
&& e.children.iter().zip(&t.children).all(|(a, b)| same(a, b))
}
fn tree(depth: u32) -> impl Strategy<Value = Tree> {
// No leading x/X: names starting with "xml" are reserved, and `xmlns` would be a namespace declaration.
let name = "[a-wA-W][a-zA-Z0-9_]{0,6}";
let text = "[ -~&<>\"'é]{0,12}";
let attrs = proptest::collection::btree_map("[a-w][a-z0-9]{0,4}", text, 0..3)
.prop_map(|m| m.into_iter().filter(|(k, _)| k != "status_code").collect::<Vec<_>>());
let leaf = (name, attrs.clone(), text).prop_map(|(name, attrs, text)| Tree {
name: name.to_string(),
attrs,
text,
children: vec![],
});
leaf.prop_recursive(depth, 24, 4, move |inner| {
("[a-wA-W][a-zA-Z0-9_]{0,6}", attrs.clone(), "[ -~]{0,8}", proptest::collection::vec(inner, 0..4)).prop_map(
|(name, attrs, text, children)| Tree { name, attrs, text, children },
)
})
}
proptest! {
#![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })]
/// Serialize a random tree (depth <= MAX_XML_DEPTH - 1 under root), parse it back, get the same tree.
#[test]
fn xml_round_trips_generated_trees(children in proptest::collection::vec(tree(5), 0..4), code in 100u32..600) {
let root = Tree {
name: "root".into(),
attrs: vec![("status_code".into(), code.to_string())],
text: String::new(),
children,
};
let mut s = String::new();
serialize(&root, &mut s);
let d = xml::parse(s.as_bytes()).map_err(|e| TestCaseError::fail(format!("{e:?} for {s}")))?;
prop_assert_eq!(d.status_code, code);
prop_assert!(same(&d.root, &root), "tree differs for {}", s);
}
/// Arbitrary bytes: never panics; any success respects every cap.
#[test]
fn xml_never_panics_and_respects_caps(data in proptest::collection::vec(any::<u8>(), 0..2048)) {
if let Ok(d) = xml::parse(&data) {
fn walk(e: &xml::Element, depth: usize, count: &mut usize) -> bool {
*count += 1;
depth <= MAX_XML_DEPTH
&& e.attributes.len() <= MAX_XML_ATTRIBUTES
&& e.text.len() <= MAX_XML_TEXT_BYTES
&& e.children.iter().all(|c| walk(c, depth + 1, count))
}
let mut count = 0;
prop_assert!(walk(&d.root, 1, &mut count));
prop_assert!(count <= MAX_XML_ELEMENTS);
prop_assert_eq!(d.root.name.as_str(), "root");
}
}
/// Mutating a valid document (one byte flipped, truncated) never panics, and truncation is always an error.
#[test]
fn xml_truncation_is_an_error(cut in 0usize..60) {
let doc = br#"<root status_code="200"><a k="v">text&amp;</a><b/></root>"#;
let cut = cut.min(doc.len() - 1);
prop_assert!(xml::parse(&doc[..cut]).is_err());
}
}
// ================================================================================================ serverinfo
const SERVERINFO: &str = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root status_code=\"200\">\n\
<hostname>LAB-PC</hostname>\n<appversion>7.1.431.-1</appversion>\n<GfeVersion>3.23.0.74</GfeVersion>\n\
<uniqueid>0123456789ABCDEF0123456789ABCDEF</uniqueid>\n<HttpsPort>47984</HttpsPort>\n\
<ExternalPort>47989</ExternalPort>\n<mac>00:11:22:aa:BB:ff</mac>\n<LocalIP>192.0.2.10</LocalIP>\n\
<MaxLumaPixelsHEVC>1869449984</MaxLumaPixelsHEVC>\n<ServerCodecModeSupport>259</ServerCodecModeSupport>\n\
<SupportedDisplayMode></SupportedDisplayMode>\n<PairStatus>0</PairStatus>\n<currentgame>0</currentgame>\n\
<state>SUNSHINE_SERVER_FREE</state>\n</root>\n";
fn serverinfo_with(field: &str, value: Option<&str>) -> Vec<u8> {
let open = format!("<{field}>");
let close = format!("</{field}>");
let start = SERVERINFO.find(&open).unwrap_or_else(|| panic!("{field} in sample"));
let end = SERVERINFO[start..].find(&close).unwrap() + start + close.len();
let replacement = value.map(|v| format!("{open}{v}{close}")).unwrap_or_default();
format!("{}{}{}", &SERVERINFO[..start], replacement, &SERVERINFO[end..]).into_bytes()
}
#[test]
fn serverinfo_sample() {
let s = http::parse_server_info(SERVERINFO.as_bytes()).unwrap();
assert_eq!(s.hostname, "LAB-PC");
assert_eq!(s.app_version, "7.1.431.-1");
assert_eq!(s.gfe_version.as_deref(), Some("3.23.0.74"));
assert_eq!(s.unique_id, "0123456789ABCDEF0123456789ABCDEF");
assert_eq!(s.https_port, 47984);
assert_eq!(s.http_port, Some(47989));
assert_eq!(s.mac, Some([0x00, 0x11, 0x22, 0xAA, 0xBB, 0xFF]));
assert_eq!(s.local_ip.as_deref(), Some("192.0.2.10"));
assert_eq!(s.max_luma_pixels_hevc, Some(1_869_449_984));
assert_eq!(s.codec_mode_support, Some(259));
assert!(!s.paired);
assert_eq!(s.current_game, 0);
assert_eq!(s.state, "SUNSHINE_SERVER_FREE");
assert!(!s.is_busy().unwrap());
}
#[test]
fn serverinfo_optional_fields() {
let s = http::parse_server_info(&serverinfo_with("mac", Some(""))).unwrap();
assert_eq!(s.mac, None, "empty mac is None");
let s = http::parse_server_info(&serverinfo_with("GfeVersion", None)).unwrap();
assert_eq!(s.gfe_version, None);
let s = http::parse_server_info(&serverinfo_with("ExternalPort", None)).unwrap();
assert_eq!(s.http_port, None);
let s = http::parse_server_info(&serverinfo_with("PairStatus", Some("1"))).unwrap();
assert!(s.paired);
}
#[test]
fn serverinfo_busy() {
let s = http::parse_server_info(&serverinfo_with("state", Some("SUNSHINE_SERVER_BUSY"))).unwrap();
assert!(s.is_busy().unwrap());
let s = http::parse_server_info(&serverinfo_with("currentgame", Some("881448767"))).unwrap();
assert_eq!(s.current_game, 881_448_767);
assert!(s.is_busy().unwrap());
}
#[test]
fn serverinfo_refuses_bad_fields() {
for field in ["hostname", "uniqueid", "HttpsPort"] {
assert_err!(http::parse_server_info(&serverinfo_with(field, None)), Error::Malformed { .. }, "missing {field}");
}
for (field, value) in [
("HttpsPort", "70000"),
("HttpsPort", "-1"),
("HttpsPort", ""),
("HttpsPort", "0x1F"),
("HttpsPort", " 47984"),
("ExternalPort", "65536"),
("currentgame", "abc"),
("currentgame", "4294967296"),
("MaxLumaPixelsHEVC", "1e9"),
("ServerCodecModeSupport", "-3"),
("mac", "00:11:22:33:44"),
("mac", "00:11:22:33:44:55:66"),
("mac", "zz:11:22:33:44:55"),
] {
assert_err!(
http::parse_server_info(&serverinfo_with(field, Some(value))),
Error::Malformed { .. },
"{field}={value:?}"
);
}
}
#[test]
fn serverinfo_field_cap() {
use domistream::http::serverinfo::MAX_SERVERINFO_FIELD_BYTES as MAX;
let ok = "h".repeat(MAX);
assert_eq!(http::parse_server_info(&serverinfo_with("hostname", Some(&ok))).unwrap().hostname, ok);
assert_cap!(http::parse_server_info(&serverinfo_with("hostname", Some(&"h".repeat(MAX + 1)))), MAX);
assert_cap!(http::parse_server_info(&serverinfo_with("state", Some(&"s".repeat(MAX + 1)))), MAX);
}
#[test]
fn serverinfo_status_and_sizes() {
use domistream::http::serverinfo::MAX_SERVERINFO_BYTES as MAX;
assert_err!(http::parse_server_info(&xml_root(503, "")), Error::HostStatus { code: 503 });
assert_err!(http::parse_server_info(b""), Error::Malformed { .. });
assert_err!(http::parse_server_info(b"<"), Error::Malformed { .. });
let inner = SERVERINFO
.trim_start_matches("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root status_code=\"200\">")
.trim_end_matches("</root>\n");
for len in [MAX - 1, MAX] {
let s = http::parse_server_info(&xml_padded_to(inner, len)).unwrap_or_else(|e| panic!("{len}: {e:?}"));
assert_eq!(s.hostname, "LAB-PC");
}
assert_too_large!(http::parse_server_info(&xml_padded_to(inner, MAX + 1)), MAX, MAX + 1);
assert_too_large!(http::parse_server_info(&vec![b' '; 64 * MAX]), MAX, 64 * MAX);
}
// ================================================================================================ applist
#[test]
fn applist_sample() {
let body = xml_root(
200,
"<App><IsHdrSupported>1</IsHdrSupported><AppTitle>Desktop</AppTitle><ID>881448767</ID></App>\
<App><AppTitle>Steam &amp; Friends</AppTitle><ID>2</ID><IsHdrSupported>0</IsHdrSupported></App>\
<App><AppTitle>No HDR field</AppTitle><ID>3</ID></App>",
);
let apps = http::parse_app_list(&body).unwrap();
assert_eq!(
apps,
vec![
http::App { id: 881_448_767, title: "Desktop".into(), hdr_supported: true },
http::App { id: 2, title: "Steam & Friends".into(), hdr_supported: false },
http::App { id: 3, title: "No HDR field".into(), hdr_supported: false },
]
);
assert_eq!(http::parse_app_list(&xml_root(200, "")).unwrap(), vec![]);
}
#[test]
fn applist_refuses_bad_apps() {
for (inner, why) in [
("<App><AppTitle>A</AppTitle></App>", "no ID"),
("<App><ID>1</ID></App>", "no AppTitle"),
("<App><AppTitle>A</AppTitle><ID>-1</ID></App>", "negative ID"),
("<App><AppTitle>A</AppTitle><ID>abc</ID></App>", "ID not decimal"),
("<App><AppTitle>A</AppTitle><ID>4294967296</ID></App>", "ID over u32"),
("<App><AppTitle>A</AppTitle><ID>1</ID></App><App><AppTitle>B</AppTitle><ID>1</ID></App>", "duplicate ID"),
] {
assert_err!(http::parse_app_list(&xml_root(200, inner)), Error::Malformed { .. }, "{why}");
}
assert_err!(http::parse_app_list(&xml_root(401, "")), Error::HostStatus { code: 401 });
}
#[test]
fn applist_caps() {
use domistream::http::applist::{MAX_APP_TITLE_BYTES, MAX_APPLIST_BYTES, MAX_APPS};
let app = |i: usize, title: &str| format!("<App><AppTitle>{title}</AppTitle><ID>{i}</ID></App>");
let t = "t".repeat(MAX_APP_TITLE_BYTES);
assert_eq!(http::parse_app_list(&xml_root(200, &app(1, &t))).unwrap()[0].title, t);
assert_cap!(http::parse_app_list(&xml_root(200, &app(1, &"t".repeat(MAX_APP_TITLE_BYTES + 1)))), MAX_APP_TITLE_BYTES);
// Multi-byte titles: the cap is in bytes.
assert_cap!(http::parse_app_list(&xml_root(200, &app(1, &"é".repeat(MAX_APP_TITLE_BYTES / 2 + 1)))), MAX_APP_TITLE_BYTES);
let list = |n: usize| (0..n).map(|i| app(i, "g")).collect::<String>();
assert_eq!(http::parse_app_list(&xml_root(200, &list(MAX_APPS))).unwrap().len(), MAX_APPS);
assert_cap!(http::parse_app_list(&xml_root(200, &list(MAX_APPS + 1))), MAX_APPS);
let inner = app(1, "Desktop");
for len in [MAX_APPLIST_BYTES - 1, MAX_APPLIST_BYTES] {
let apps = http::parse_app_list(&xml_padded_to(&inner, len)).unwrap_or_else(|e| panic!("{len}: {e:?}"));
assert_eq!(apps.len(), 1, "unknown elements are ignored");
}
assert_too_large!(http::parse_app_list(&xml_padded_to(&inner, MAX_APPLIST_BYTES + 1)), MAX_APPLIST_BYTES, MAX_APPLIST_BYTES + 1);
assert_too_large!(http::parse_app_list(&vec![b'<'; 3 * MAX_APPLIST_BYTES]), MAX_APPLIST_BYTES, 3 * MAX_APPLIST_BYTES);
}
// ================================================================================================ launch
#[test]
fn launch_response_sample() {
let r = http::parse_launch_response(&xml_root(
200,
"<sessionUrl0>rtsp://192.0.2.10:48010</sessionUrl0><gamesession>1</gamesession>",
))
.unwrap();
assert!(r.game_session);
assert_eq!(r.session_url.as_deref(), Some("rtsp://192.0.2.10:48010"));
let r = http::parse_launch_response(&xml_root(200, "<gamesession>1</gamesession>")).unwrap();
assert_eq!(r.session_url, None, "missing sessionUrl0 is None (UNKNOWN U4)");
let r = http::parse_launch_response(&xml_root(200, "<gamesession>0</gamesession>")).unwrap();
assert!(!r.game_session);
}
#[test]
fn launch_response_refuses_bad_urls() {
for url in [
"http://192.0.2.10:48010",
"rtsp://192.0.2.10",
"rtsp://192.0.2.10:",
"rtsp://192.0.2.10:99999",
"rtsp://192.0.2.10:-1",
"rtsp://:48010",
"rtsp://192.0.2.10:48010\r\nCSeq: 9",
"rtsp://192.0.2.10:48a",
"",
] {
let body = xml_root(200, &format!("<sessionUrl0>{url}</sessionUrl0><gamesession>1</gamesession>"));
assert_err!(http::parse_launch_response(&body), Error::Malformed { .. }, "{url:?}");
}
}
#[test]
fn launch_response_caps() {
use domistream::http::launch::{MAX_LAUNCH_RESPONSE_BYTES as MAX, MAX_SESSION_URL_BYTES as URL};
let prefix = "rtsp://";
let suffix = ":48010";
// A host name of DNS labels of 9 letters, so only the length is unusual.
let host = |n: usize| {
let len = n - prefix.len() - suffix.len();
(0..len).map(|i| if i % 10 == 9 && i + 1 < len { '.' } else { 'h' }).collect::<String>()
};
let ok = format!("{prefix}{}{suffix}", host(URL));
let r = http::parse_launch_response(&xml_root(200, &format!("<sessionUrl0>{ok}</sessionUrl0>"))).unwrap();
assert_eq!(r.session_url.as_deref(), Some(ok.as_str()));
let over = format!("{prefix}{}{suffix}", host(URL + 1));
assert_cap!(http::parse_launch_response(&xml_root(200, &format!("<sessionUrl0>{over}</sessionUrl0>"))), URL);
let inner = "<gamesession>1</gamesession>";
for len in [MAX - 1, MAX] {
assert!(http::parse_launch_response(&xml_padded_to(inner, len)).unwrap().game_session);
}
assert_too_large!(http::parse_launch_response(&xml_padded_to(inner, MAX + 1)), MAX, MAX + 1);
assert_too_large!(http::parse_launch_response(&vec![0u8; 1 << 20]), MAX, 1 << 20);
assert_err!(http::parse_launch_response(&xml_root(503, "")), Error::HostStatus { code: 503 });
assert_err!(http::parse_launch_response(b""), Error::Malformed { .. });
}
#[test]
fn status_response() {
assert_eq!(http::parse_status_response(&xml_root(200, "")), Ok(()));
assert_err!(http::parse_status_response(&xml_root(404, "")), Error::HostStatus { code: 404 });
assert_err!(http::parse_status_response(b"OK"), Error::Malformed { .. });
assert_err!(http::parse_status_response(b""), Error::Malformed { .. });
assert_too_large!(http::parse_status_response(&vec![b' '; MAX_XML_BYTES + 1]), MAX_XML_BYTES, MAX_XML_BYTES + 1);
}
// ================================================================================================ requests
const UID: &str = "0123456789ABCDEF";
#[test]
fn simple_requests() {
let r = http::server_info_request(Scheme::Http, UID).unwrap();
assert_eq!(r.scheme, Scheme::Http);
let (path, q) = parse_query(&r.path_and_query);
assert_eq!(path, "/serverinfo");
assert_eq!(param(&q, "uniqueid"), UID);
assert_eq!(http::server_info_request(Scheme::Https, UID).unwrap().scheme, Scheme::Https);
for (r, want) in [
(http::app_list_request(UID).unwrap(), "/applist"),
(http::cancel_request(UID).unwrap(), "/cancel"),
(http::unpair_request(UID).unwrap(), "/unpair"),
] {
assert_eq!(r.scheme, Scheme::Https, "{want} goes over HTTPS");
let (path, q) = parse_query(&r.path_and_query);
assert_eq!(path, want);
assert_eq!(param(&q, "uniqueid"), UID);
}
}
#[test]
fn requests_refuse_bad_unique_ids() {
use domistream::http::MAX_UNIQUE_ID_BYTES as MAX;
for bad in [String::new(), "a".repeat(MAX + 1)] {
assert_err!(http::server_info_request(Scheme::Http, &bad), Error::Malformed { .. });
assert_err!(http::app_list_request(&bad), Error::Malformed { .. });
assert_err!(http::cancel_request(&bad), Error::Malformed { .. });
assert_err!(http::unpair_request(&bad), Error::Malformed { .. });
}
assert!(http::server_info_request(Scheme::Http, &"a".repeat(MAX)).is_ok());
}
#[test]
fn requests_cannot_be_injected() {
// A unique id with query syntax is refused or encoded; it never adds a parameter.
for evil in ["a&uniqueid=b", "a#frag", "a b", "a\r\nX: y", "a=b", "%26"] {
match http::server_info_request(Scheme::Http, evil) {
Err(Error::Malformed { .. }) => {}
Ok(r) => {
let (path, q) = parse_query(&r.path_and_query);
assert_eq!(path, "/serverinfo");
assert_eq!(param(&q, "uniqueid"), evil);
assert!(!r.path_and_query.contains(['\r', '\n', ' ', '#']), "{:?}", r.path_and_query);
}
other => panic!("{evil:?}: {other:?}"),
}
}
}
fn launch_params() -> http::LaunchParams {
http::LaunchParams {
app_id: 881_448_767,
width: 1920,
height: 1080,
fps: 60,
keys: domistream::SessionKeys { rikey: *b"\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa\xbb\xcc\xdd\xee\xff", rikeyid: 1_234_567 },
hdr: false,
audio: http::launch::AudioLayout::Stereo,
}
}
#[test]
fn launch_request_parameters() {
let r = http::launch::launch_request(&launch_params(), UID).unwrap();
assert_eq!(r.scheme, Scheme::Https);
let (path, q) = parse_query(&r.path_and_query);
assert_eq!(path, "/launch");
assert_eq!(param(&q, "uniqueid"), UID);
assert_eq!(param(&q, "appid"), "881448767");
assert_eq!(param(&q, "mode"), "1920x1080x60");
assert_eq!(param(&q, "rikey").to_lowercase(), "00112233445566778899aabbccddeeff");
assert_eq!(param(&q, "rikeyid"), "1234567");
assert_eq!(param(&q, "hdrMode"), "0");
assert_eq!(param(&q, "surroundAudioInfo"), "196610", "stereo = 0x30002");
let mut p = launch_params();
p.hdr = true;
let (_, q) = parse_query(&http::launch::launch_request(&p, UID).unwrap().path_and_query);
assert_eq!(param(&q, "hdrMode"), "1");
for broken in [
http::LaunchParams { width: 0, ..launch_params() },
http::LaunchParams { height: 0, ..launch_params() },
http::LaunchParams { fps: 0, ..launch_params() },
] {
assert_err!(http::launch::launch_request(&broken, UID), Error::Malformed { .. });
}
assert_err!(http::launch::launch_request(&launch_params(), ""), Error::Malformed { .. });
}
#[test]
fn resume_request_parameters() {
let keys = launch_params().keys;
let r = http::launch::resume_request(&keys, UID).unwrap();
assert_eq!(r.scheme, Scheme::Https);
let (path, q) = parse_query(&r.path_and_query);
assert_eq!(path, "/resume");
assert_eq!(param(&q, "rikey").to_lowercase(), "00112233445566778899aabbccddeeff");
assert_eq!(param(&q, "rikeyid"), "1234567");
assert_err!(http::launch::resume_request(&keys, ""), Error::Malformed { .. });
}
#[test]
fn session_keys_are_fresh() {
let a = domistream::SessionKeys::generate(&mut common::SeqRng::new(1)).unwrap();
let b = domistream::SessionKeys::generate(&mut common::SeqRng::new(2)).unwrap();
let a2 = domistream::SessionKeys::generate(&mut common::SeqRng::new(1)).unwrap();
assert_eq!(a, a2, "keys come only from the caller's randomness");
assert_ne!(a.rikey, b.rikey);
assert_ne!(a.rikey, [0; 16]);
}
+258
View File
@@ -0,0 +1,258 @@
//! Repository rules that are checked by reading the crate itself: the sans-I/O guard (no sockets, clocks,
//! threads, files or OS randomness in `src/`), `forbid(unsafe_code)`, and that `Debug` never prints a secret.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
mod common;
use std::path::{Path, PathBuf};
/// Things `src/` must never contain outside comments (CLAUDE.md "Sans-I/O"). The left side is matched with all
/// whitespace removed, so `std :: net` and `use std::{fs, net}` are caught too.
const FORBIDDEN: &[(&str, &str)] = &[
("std::net", "sockets"),
("Instant::now", "clock reads"),
("SystemTime::now", "clock reads"),
("std::time::Instant", "the std clock type (use crate::Instant)"),
("std::time::SystemTime", "the std clock type"),
("UNIX_EPOCH", "clock reads"),
("std::thread", "threads"),
("thread::spawn", "threads"),
("std::fs", "files"),
("File::open", "files"),
("File::create", "files"),
("std::process", "processes"),
("std::env::var", "environment reads"),
("OsRng", "OS randomness (randomness comes in through RandomSource)"),
("thread_rng", "OS randomness"),
("getrandom", "OS randomness"),
("rand::random", "OS randomness"),
("tokio", "async runtimes"),
("mio::", "async runtimes"),
];
/// Grouped imports `use std::{…}` naming a forbidden module.
const FORBIDDEN_IN_STD_GROUP: &[&str] = &["net", "fs", "thread", "process"];
fn rust_files(dir: &Path, out: &mut Vec<PathBuf>) {
for entry in std::fs::read_dir(dir).expect("read src dir") {
let path = entry.expect("dir entry").path();
if path.is_dir() {
rust_files(&path, out);
} else if path.extension().is_some_and(|e| e == "rs") {
out.push(path);
}
}
}
/// The code of a file with `//` comments (line and doc comments) and `/* */` comments removed. String literals are
/// kept: a forbidden name inside a string still fails, on purpose.
fn strip_comments(src: &str) -> String {
let mut out = String::with_capacity(src.len());
let mut chars = src.chars().peekable();
let mut in_str = false;
while let Some(c) = chars.next() {
if in_str {
out.push(c);
if c == '\\' {
if let Some(n) = chars.next() {
out.push(n);
}
} else if c == '"' {
in_str = false;
}
continue;
}
match (c, chars.peek()) {
('"', _) => {
in_str = true;
out.push(c);
}
('/', Some('/')) => {
for n in chars.by_ref() {
if n == '\n' {
out.push('\n');
break;
}
}
}
('/', Some('*')) => {
chars.next();
let mut prev = ' ';
for n in chars.by_ref() {
if prev == '*' && n == '/' {
break;
}
prev = n;
}
}
_ => out.push(c),
}
}
out
}
fn violations_in(code: &str) -> Vec<String> {
let squashed: String = code.chars().filter(|c| !c.is_whitespace()).collect();
let mut found = Vec::new();
for (needle, why) in FORBIDDEN {
if squashed.contains(needle) {
found.push(format!("`{needle}` ({why})"));
}
}
let mut rest = squashed.as_str();
while let Some(i) = rest.find("std::{") {
let group = &rest[i + 6..];
let end = group.find('}').unwrap_or(group.len());
for item in group[..end].split(',') {
let head = item.split("::").next().unwrap_or("");
if FORBIDDEN_IN_STD_GROUP.contains(&head) {
found.push(format!("`std::{{{head}}}` (grouped import)"));
}
}
rest = &group[end.min(group.len())..];
}
found
}
#[test]
fn src_is_sans_io() {
let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
let mut files = Vec::new();
rust_files(&src, &mut files);
assert!(files.len() >= 20, "expected the whole crate under {}", src.display());
let mut report = Vec::new();
for file in &files {
let code = strip_comments(&std::fs::read_to_string(file).expect("read source"));
for v in violations_in(&code) {
report.push(format!("{}: {v}", file.strip_prefix(&src).unwrap_or(file).display()));
}
}
assert!(report.is_empty(), "sans-I/O rule broken:\n{}", report.join("\n"));
}
#[test]
fn guard_catches_what_it_should() {
// The guard itself must work, or `src_is_sans_io` proves nothing.
for bad in [
"use std::net::UdpSocket;",
"let t = std::time::Instant::now();",
"let t = Instant :: now();",
"let t = SystemTime::now();",
"std::thread::spawn(|| {});",
"let f = std::fs::read(\"x\");",
"use std::{fs, io};",
"use std::{io, net::TcpStream};",
"let mut r = rand::rngs::OsRng;",
"getrandom::fill(&mut b);",
] {
assert!(!violations_in(&strip_comments(bad)).is_empty(), "guard missed: {bad}");
}
for fine in [
"// no std::net here, only a comment",
"/// Docs may say Instant::now is forbidden.",
"/* std::fs in a block comment */ let x = 1;",
"use crate::Instant; let t = Instant::from_micros(5);",
"use std::{fmt, error};",
"use core::time::Duration;",
] {
assert!(violations_in(&strip_comments(fine)).is_empty(), "guard flagged: {fine}");
}
}
#[test]
fn every_module_forbids_unsafe() {
let lib = std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("src/lib.rs")).expect("lib.rs");
assert!(lib.contains("#![forbid(unsafe_code)]"), "lib.rs must carry #![forbid(unsafe_code)]");
let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
let mut files = Vec::new();
rust_files(&src, &mut files);
for file in files {
let code = strip_comments(&std::fs::read_to_string(&file).expect("read"));
assert_eq!(
code.matches("unsafe").count(),
code.matches("unsafe_code").count(),
"{}: `unsafe` in src",
file.display()
);
assert!(!code.contains("allow(unsafe_code)"), "{}: unsafe allowed", file.display());
}
}
// ------------------------------------------------------------------------------------------------ secrets
const KEY: [u8; 16] = [0xA1, 0xB2, 0xC3, 0xD4, 0xE5, 0xF6, 0x17, 0x28, 0x39, 0x4A, 0x5B, 0x6C, 0x7D, 0x8E, 0x9F, 0x10];
/// Every way the key could show up in a `Debug` string.
fn leaks_key(s: &str) -> bool {
let lower = s.to_lowercase();
lower.contains(&common::to_hex(&KEY))
|| lower.contains("161, 178")
|| lower.contains("0xa1, 0xb2")
|| lower.contains("a1b2c3")
|| s.contains("[161")
}
#[test]
fn debug_never_prints_keys() {
let keys = domistream::SessionKeys { rikey: KEY, rikeyid: 7 };
let control = domistream::control::ControlCipher::new(KEY);
let video = domistream::video::VideoCipher::new(KEY);
let audio = domistream::audio::AudioCipher::new(&keys);
let config = domistream::control::ControlConfig {
enet: domistream::enet::EnetConfig {
channel_count: 1,
mtu: 1400,
connect_data: 0,
ping_interval: core::time::Duration::from_millis(500),
timeout: core::time::Duration::from_secs(10),
},
rikey: KEY,
ping_interval: core::time::Duration::from_millis(100),
};
for (what, s) in [
("SessionKeys", format!("{keys:?}")),
("ControlCipher", format!("{control:?}")),
("VideoCipher", format!("{video:?}")),
("AudioCipher", format!("{audio:?}")),
("ControlConfig", format!("{config:?}")),
("VideoConfig", format!("{:?}", domistream::video::VideoConfig {
packet_size: 1024,
cipher: Some(video.clone()),
frame_timeout: core::time::Duration::from_millis(100),
})),
] {
assert!(!leaks_key(&s), "{what} Debug leaks the key: {s}");
assert!(s.contains("redacted"), "{what} Debug should say the key is redacted: {s}");
}
// rikeyid is not secret: it may show.
assert!(format!("{keys:?}").contains('7'));
}
#[test]
fn debug_never_prints_the_pin_or_the_private_key() {
// Pin and ClientIdentity can only be made through the API (Phase A: Unimplemented, so these fail now).
let pin = domistream::pairing::Pin::from_digits("4071").expect("Pin::from_digits");
let s = format!("{pin:?}");
assert!(!s.contains("4071") && !s.contains("52, 48, 55, 49"), "Pin Debug leaks the PIN: {s}");
let v = common::pairing_vectors();
let key = v.bytes("client_key_pkcs8_der");
let identity = domistream::pairing::ClientIdentity::from_der(&v.bytes("client_cert_der"), &key)
.expect("ClientIdentity::from_der");
let s = format!("{identity:?}");
assert!(s.contains("redacted"), "{s}");
let key_hex = common::to_hex(&key[key.len() - 32..]);
assert!(!s.to_lowercase().contains(&key_hex), "ClientIdentity Debug leaks key bytes");
assert!(!s.contains(&format!("{:?}", &key[key.len() - 8..])), "ClientIdentity Debug leaks key bytes");
}
#[test]
fn error_display_has_no_secret_material() {
// Errors are fixed strings and numbers; make sure the variants that come out of crypto paths say nothing.
for e in [domistream::Error::Crypto, domistream::Error::PairingRefused] {
let s = format!("{e} {e:?}");
assert!(!leaks_key(&s), "{s}");
assert!(s.len() < 80, "crypto errors are deliberately short: {s}");
}
}
+791
View File
@@ -0,0 +1,791 @@
//! Pairing (`docs/PROTOCOL.md` 1.5) against recorded vectors made by independent tools
//! (`tools/vectors/gen_vectors.py`: Python hashlib, the OpenSSL CLI). The keys are test-only.
//!
//! Recorded transcript assumption: the state machine draws its randomness as salt (step 1), then C (step 2), then
//! secret_c (step 3), 16 bytes each, and nothing else. [`common::ScriptedRng`] fails loudly if that changes.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
mod common;
use common::{
CLIENT_CERT_PEM, CLIENT_KEY_PEM, EC_CERT_PEM, HOST_CERT_PEM, ROGUE_CERT_PEM, ScriptedRng, SeqRng, Vectors, hex,
param, parse_query, pem_blocks, to_hex, to_hex_upper, xml_padded_to, xml_root,
};
use domistream::Error;
use domistream::http::{HttpRequest, Scheme};
use domistream::pairing::crypto;
use domistream::pairing::identity::{MAX_CERT_DER_BYTES, MAX_CERT_PEM_BYTES};
use domistream::pairing::{
ClientIdentity, MAX_PAIR_RESPONSE_BYTES, MAX_SIGNATURE_BYTES, PairingFailure, PairingSession, PairingState,
PairingStep, Pin, ServerCert, parse_pair_response,
};
const UID: &str = "0123456789ABCDEF";
const DEVICE: &str = "DomiStreamTestTV";
fn v() -> Vectors {
common::pairing_vectors()
}
fn client() -> ClientIdentity {
let v = v();
ClientIdentity::from_der(&v.bytes("client_cert_der"), &v.bytes("client_key_pkcs8_der"))
.expect("ClientIdentity::from_der(test-only client)")
}
fn rogue() -> ClientIdentity {
let v = v();
ClientIdentity::from_der(&v.bytes("rogue_cert_der"), &v.bytes("rogue_key_pkcs8_der")).expect("rogue identity")
}
fn pin() -> Pin {
Pin::from_digits(v().str("pin")).expect("Pin::from_digits")
}
fn rng_a() -> ScriptedRng {
let v = v();
ScriptedRng::new([v.bytes("salt"), v.bytes("client_challenge"), v.bytes("client_secret")].concat())
}
fn rng_b() -> ScriptedRng {
let v = v();
ScriptedRng::new([v.bytes("salt_b"), v.bytes("client_challenge_b"), v.bytes("client_secret_b")].concat())
}
// ------------------------------------------------------------------------------------------------ host answers
fn answer(paired: bool, element: Option<(&str, &[u8])>) -> Vec<u8> {
let mut inner = format!("<paired>{}</paired>", u8::from(paired));
if let Some((name, value)) = element {
// Upper-case hex: the parser must accept both cases (PROTOCOL.md 1.1).
inner.push_str(&format!("<{name}>{}</{name}>", to_hex_upper(value)));
}
xml_root(200, &inner)
}
fn resp1() -> Vec<u8> {
answer(true, Some(("plaincert", HOST_CERT_PEM.as_bytes())))
}
fn resp2() -> Vec<u8> {
answer(true, Some(("challengeresponse", &v().bytes("step2_challengeresponse"))))
}
fn resp3() -> Vec<u8> {
answer(true, Some(("pairingsecret", &v().bytes("step3_pairingsecret"))))
}
fn resp_ok() -> Vec<u8> {
answer(true, None)
}
/// The recorded host answers, in order.
fn transcript() -> Vec<Vec<u8>> {
vec![resp1(), resp2(), resp3(), resp_ok(), resp_ok()]
}
/// A session that has been fed the first `steps` recorded answers.
fn session_after(steps: usize) -> (PairingSession, ScriptedRng, ClientIdentity) {
let id = client();
let mut rng = rng_a();
let (mut s, _) = PairingSession::start(&id, UID, DEVICE, pin(), &mut rng).expect("PairingSession::start");
for body in transcript().into_iter().take(steps) {
s.handle_response(&id, 200, &body, &mut rng).expect("recorded answer");
}
(s, rng, id)
}
const STATES: [PairingState; 5] = [
PairingState::AwaitServerCert,
PairingState::AwaitChallengeResponse,
PairingState::AwaitPairingSecret,
PairingState::AwaitClientSecretAck,
PairingState::AwaitPairChallenge,
];
fn sent(step: PairingStep) -> HttpRequest {
match step {
PairingStep::Send(r) => r,
PairingStep::Paired(p) => panic!("expected a request, pairing already finished: {p:?}"),
}
}
fn hex_param(req: &HttpRequest, name: &str) -> Vec<u8> {
let (path, q) = parse_query(&req.path_and_query);
assert_eq!(path, "/pair");
hex(param(&q, name))
}
/// Feeds `body` and checks the session fails into `Failed(reason)`.
fn expect_failure(s: &mut PairingSession, id: &ClientIdentity, rng: &mut ScriptedRng, status: u16, body: &[u8], reason: PairingFailure) {
let r = s.handle_response(id, status, body, rng);
assert!(r.is_err(), "expected a failure ({reason:?}), got {r:?}");
assert_eq!(s.state(), PairingState::Failed(reason), "result was {r:?}");
// Failed is terminal.
assert_err!(s.handle_response(id, 200, &resp_ok(), rng), Error::State { .. });
assert_eq!(s.state(), PairingState::Failed(reason));
}
// ================================================================================================ happy path
#[test]
fn recorded_transcript_walks_every_state() {
let v = v();
let id = client();
let mut rng = rng_a();
let (mut s, req1) = PairingSession::start(&id, UID, DEVICE, pin(), &mut rng).unwrap();
assert_eq!(s.state(), PairingState::AwaitServerCert);
// Step 1 (HTTP): getservercert, salt, client certificate; blocks on the host, so a long timeout.
assert_eq!(req1.scheme, Scheme::Http);
assert!(req1.timeout.is_some_and(|t| t >= core::time::Duration::from_secs(30)), "step 1 timeout {:?}", req1.timeout);
let (path, q) = parse_query(&req1.path_and_query);
assert_eq!(path, "/pair");
assert_eq!(param(&q, "uniqueid"), UID);
assert_eq!(param(&q, "phrase"), "getservercert");
assert_eq!(hex(param(&q, "salt")), v.bytes("salt"));
let pem = String::from_utf8(hex(param(&q, "clientcert"))).expect("clientcert is PEM text");
assert_eq!(pem_blocks(&pem, "CERTIFICATE"), vec![v.bytes("client_cert_der")], "clientcert is the identity's cert");
// Step 2: clientchallenge = E_K(C).
let req2 = sent(s.handle_response(&id, 200, &resp1(), &mut rng).unwrap());
assert_eq!(s.state(), PairingState::AwaitChallengeResponse);
assert_eq!(req2.scheme, Scheme::Http);
assert_eq!(hex_param(&req2, "clientchallenge"), v.bytes("step2_clientchallenge"));
assert_eq!(param(&parse_query(&req2.path_and_query).1, "uniqueid"), UID);
// Step 3: serverchallengeresp = E_K(H_c).
let req3 = sent(s.handle_response(&id, 200, &resp2(), &mut rng).unwrap());
assert_eq!(s.state(), PairingState::AwaitPairingSecret);
assert_eq!(hex_param(&req3, "serverchallengeresp"), v.bytes("step3_serverchallengeresp"));
// Step 4: clientpairingsecret = secret_c || Sign_client(secret_c), after checking the host's proof.
let req4 = sent(s.handle_response(&id, 200, &resp3(), &mut rng).unwrap());
assert_eq!(s.state(), PairingState::AwaitClientSecretAck);
assert_eq!(hex_param(&req4, "clientpairingsecret"), v.bytes("step4_clientpairingsecret"));
// Step 5 (HTTPS): pairchallenge.
let req5 = sent(s.handle_response(&id, 200, &resp_ok(), &mut rng).unwrap());
assert_eq!(s.state(), PairingState::AwaitPairChallenge);
assert_eq!(req5.scheme, Scheme::Https, "step 5 runs over HTTPS with the client certificate");
assert_eq!(param(&parse_query(&req5.path_and_query).1, "phrase"), "pairchallenge");
match s.handle_response(&id, 200, &resp_ok(), &mut rng).unwrap() {
PairingStep::Paired(host) => assert_eq!(host.server_cert.der(), v.bytes("host_cert_der").as_slice()),
PairingStep::Send(r) => panic!("expected Paired, got another request {r:?}"),
}
assert_eq!(s.state(), PairingState::Paired);
assert_eq!(rng.drawn(), 48, "salt + C + secret_c");
assert_err!(s.handle_response(&id, 200, &resp_ok(), &mut rng), Error::State { .. });
assert_eq!(s.state(), PairingState::Paired);
}
#[test]
fn lower_case_hex_answers_work_too() {
let id = client();
let mut rng = rng_a();
let (mut s, _) = PairingSession::start(&id, UID, DEVICE, pin(), &mut rng).unwrap();
for body in transcript() {
let lower = String::from_utf8(body).unwrap();
// Lower-case only the hex payloads (element names keep their case).
let mut out = String::new();
let mut in_text = false;
for c in lower.chars() {
match c {
'>' => {
in_text = true;
out.push(c);
}
'<' => {
in_text = false;
out.push(c);
}
_ if in_text => out.push(c.to_ascii_lowercase()),
_ => out.push(c),
}
}
s.handle_response(&id, 200, out.as_bytes(), &mut rng).unwrap();
}
assert_eq!(s.state(), PairingState::Paired);
}
// ================================================================================================ no shortcuts
#[test]
fn paired_needs_exactly_five_answers() {
// An answer carrying every element at once still moves one step at a time.
let v = v();
let all = xml_root(
200,
&format!(
"<paired>1</paired><plaincert>{}</plaincert><challengeresponse>{}</challengeresponse><pairingsecret>{}</pairingsecret>",
to_hex(HOST_CERT_PEM.as_bytes()),
to_hex(&v.bytes("step2_challengeresponse")),
to_hex(&v.bytes("step3_pairingsecret")),
),
);
let id = client();
let mut rng = rng_a();
let (mut s, _) = PairingSession::start(&id, UID, DEVICE, pin(), &mut rng).unwrap();
for (i, want) in STATES.iter().enumerate().skip(1) {
let step = s.handle_response(&id, 200, &all, &mut rng).unwrap();
assert!(matches!(step, PairingStep::Send(_)), "answer {} must not finish pairing", i);
assert_eq!(s.state(), *want, "after {i} answers");
}
assert!(matches!(s.handle_response(&id, 200, &all, &mut rng).unwrap(), PairingStep::Paired(_)));
assert_eq!(s.state(), PairingState::Paired);
}
#[test]
fn a_bare_paired_answer_cannot_skip_any_step() {
// `<paired>1</paired>` is all steps 4 and 5 need. Fed early, it must fail, never jump ahead.
for steps in 0..3 {
let (mut s, mut rng, id) = session_after(steps);
assert_eq!(s.state(), STATES[steps]);
expect_failure(&mut s, &id, &mut rng, 200, &resp_ok(), PairingFailure::MalformedAnswer);
}
}
#[test]
fn out_of_order_answers_fail() {
// Each state fed an answer meant for another state (replayed or reordered by an attacker).
let cases: Vec<(usize, Vec<u8>)> = vec![
(0, resp2()),
(0, resp3()),
(1, resp1()),
(1, resp3()),
(2, resp1()),
(2, resp2()),
];
for (steps, body) in cases {
let (mut s, mut rng, id) = session_after(steps);
expect_failure(&mut s, &id, &mut rng, 200, &body, PairingFailure::MalformedAnswer);
}
}
#[test]
fn replayed_answers_from_another_session_fail() {
// Session B (fresh randomness) fed session A's recorded answers: the host proof cannot match.
let id = client();
let mut rng = rng_b();
let (mut s, _) = PairingSession::start(&id, UID, DEVICE, pin(), &mut rng).unwrap();
s.handle_response(&id, 200, &resp1(), &mut rng).unwrap();
s.handle_response(&id, 200, &resp2(), &mut rng).unwrap();
assert_eq!(s.state(), PairingState::AwaitPairingSecret);
let r = s.handle_response(&id, 200, &resp3(), &mut rng);
assert_err!(r, Error::PairingRefused);
assert_eq!(s.state(), PairingState::Failed(PairingFailure::ProofMismatch));
}
#[test]
fn replaying_the_same_answer_twice_fails() {
// Step 2's answer accepted, then replayed in place of step 3's.
let (mut s, mut rng, id) = session_after(2);
expect_failure(&mut s, &id, &mut rng, 200, &resp2(), PairingFailure::MalformedAnswer);
}
// ================================================================================================ hostile host
#[test]
fn host_refusal_at_every_step() {
for steps in 0..5 {
let (mut s, mut rng, id) = session_after(steps);
let body = answer(false, None);
let r = s.handle_response(&id, 200, &body, &mut rng);
assert_err!(r, Error::PairingRefused, "step {}", steps + 1);
assert_eq!(s.state(), PairingState::Failed(PairingFailure::HostRefused), "step {}", steps + 1);
}
}
#[test]
fn host_status_errors_at_every_step() {
for steps in 0..5 {
let (mut s, mut rng, id) = session_after(steps);
let r = s.handle_response(&id, 200, &xml_root(500, "<paired>1</paired>"), &mut rng);
assert_err!(r, Error::HostStatus { code: 500 }, "step {}", steps + 1);
assert_eq!(s.state(), PairingState::Failed(PairingFailure::HostStatus));
let (mut s, mut rng, id) = session_after(steps);
let good = transcript().swap_remove(steps);
let r = s.handle_response(&id, 404, &good, &mut rng);
assert_err!(r, Error::HostStatus { code: 404 }, "HTTP 404 at step {}", steps + 1);
assert_eq!(s.state(), PairingState::Failed(PairingFailure::HostStatus));
}
}
#[test]
fn malformed_answers_at_every_step() {
let bodies: Vec<Vec<u8>> = vec![
b"".to_vec(),
b"garbage".to_vec(),
b"<root status_code=\"200\"><paired>1</paired>".to_vec(),
xml_root(200, ""),
xml_root(200, "<paired>yes</paired>"),
xml_root(200, "<paired>1</paired><plaincert>zz</plaincert><challengeresponse>zz</challengeresponse><pairingsecret>zz</pairingsecret>"),
xml_root(200, "<paired>1</paired><plaincert>abc</plaincert><challengeresponse>abc</challengeresponse><pairingsecret>abc</pairingsecret>"),
];
for steps in 0..3 {
for body in &bodies {
let (mut s, mut rng, id) = session_after(steps);
expect_failure(&mut s, &id, &mut rng, 200, body, PairingFailure::MalformedAnswer);
}
}
}
#[test]
fn wrong_pin_is_a_proof_mismatch() {
let v = v();
let (mut s, mut rng, id) = session_after(1);
s.handle_response(&id, 200, &answer(true, Some(("challengeresponse", &v.bytes("step2_challengeresponse_wrong_pin")))), &mut rng)
.unwrap();
let r = s.handle_response(&id, 200, &resp3(), &mut rng);
assert_err!(r, Error::PairingRefused);
assert_eq!(s.state(), PairingState::Failed(PairingFailure::ProofMismatch));
}
#[test]
fn wrong_host_hash_is_a_proof_mismatch() {
let v = v();
for name in ["step2_challengeresponse_wrong_hash", "step2_challengeresponse_wrong_cert"] {
let (mut s, mut rng, id) = session_after(1);
s.handle_response(&id, 200, &answer(true, Some(("challengeresponse", &v.bytes(name)))), &mut rng).unwrap();
let r = s.handle_response(&id, 200, &resp3(), &mut rng);
assert_err!(r, Error::PairingRefused, "{name}");
assert_eq!(s.state(), PairingState::Failed(PairingFailure::ProofMismatch), "{name}");
}
}
#[test]
fn tampered_challenge_response() {
let v = v();
// Block 0 or 1 holds H_s: flipping it must end in ProofMismatch once the secret arrives.
for byte in [0usize, 17, 31] {
let mut cr = v.bytes("step2_challengeresponse");
cr[byte] ^= 0x01;
let (mut s, mut rng, id) = session_after(1);
s.handle_response(&id, 200, &answer(true, Some(("challengeresponse", &cr))), &mut rng).unwrap();
assert_err!(s.handle_response(&id, 200, &resp3(), &mut rng), Error::PairingRefused);
assert_eq!(s.state(), PairingState::Failed(PairingFailure::ProofMismatch), "byte {byte}");
}
// Block 2 holds S_c: the client cannot see it, but it must feed S_c into H_c (so step 3 changes).
let mut cr = v.bytes("step2_challengeresponse");
cr[40] ^= 0x01;
let (mut s, mut rng, id) = session_after(1);
let req3 = sent(s.handle_response(&id, 200, &answer(true, Some(("challengeresponse", &cr))), &mut rng).unwrap());
assert_ne!(hex_param(&req3, "serverchallengeresp"), v.bytes("step3_serverchallengeresp"));
}
#[test]
fn wrong_challenge_response_sizes() {
let v = v();
let good = v.bytes("step2_challengeresponse");
let cases: Vec<Vec<u8>> = vec![
good[..32].to_vec(),
good[..47].to_vec(),
[good.clone(), vec![0; 1]].concat(),
[good.clone(), vec![0; 16]].concat(),
vec![],
];
for cr in cases {
let (mut s, mut rng, id) = session_after(1);
expect_failure(&mut s, &id, &mut rng, 200, &answer(true, Some(("challengeresponse", &cr))), PairingFailure::MalformedAnswer);
}
}
#[test]
fn bad_host_signatures() {
let v = v();
// Signed by another key.
let (mut s, mut rng, id) = session_after(2);
let r = s.handle_response(&id, 200, &answer(true, Some(("pairingsecret", &v.bytes("step3_pairingsecret_rogue_signature")))), &mut rng);
assert_err!(r, Error::PairingRefused);
assert_eq!(s.state(), PairingState::Failed(PairingFailure::BadHostSignature));
// One bit of the signature flipped, the signature cut short, or zeroed.
let good = v.bytes("step3_pairingsecret");
let mut flipped = good.clone();
*flipped.last_mut().unwrap() ^= 0x80;
let mut zeroed = good.clone();
zeroed[16..].fill(0);
for ps in [flipped, good[..good.len() - 1].to_vec(), zeroed, [good[..16].to_vec(), vec![0x01]].concat()] {
let (mut s, mut rng, id) = session_after(2);
let r = s.handle_response(&id, 200, &answer(true, Some(("pairingsecret", &ps))), &mut rng);
assert_err!(r, Error::PairingRefused);
assert_eq!(s.state(), PairingState::Failed(PairingFailure::BadHostSignature));
}
// The secret itself changed: both checks fail; either reason is a refusal.
let mut secret = good.clone();
secret[0] ^= 1;
let (mut s, mut rng, id) = session_after(2);
assert_err!(s.handle_response(&id, 200, &answer(true, Some(("pairingsecret", &secret))), &mut rng), Error::PairingRefused);
assert!(matches!(
s.state(),
PairingState::Failed(PairingFailure::ProofMismatch | PairingFailure::BadHostSignature)
));
}
#[test]
fn wrong_pairing_secret_sizes() {
let v = v();
let secret = v.bytes("server_secret");
for ps in [secret[..15].to_vec(), secret.clone(), [secret.clone(), vec![0x55; MAX_SIGNATURE_BYTES + 1]].concat(), vec![]] {
let (mut s, mut rng, id) = session_after(2);
expect_failure(&mut s, &id, &mut rng, 200, &answer(true, Some(("pairingsecret", &ps))), PairingFailure::MalformedAnswer);
}
}
#[test]
fn bad_host_certificates() {
let two = format!("{HOST_CERT_PEM}{ROGUE_CERT_PEM}");
let mut long = HOST_CERT_PEM.to_string();
long.push_str(&"\n".repeat(MAX_CERT_PEM_BYTES));
let cut = &HOST_CERT_PEM[..HOST_CERT_PEM.len() / 2];
for pem in [
"".to_string(),
"hello".to_string(),
EC_CERT_PEM.to_string(),
two,
CLIENT_KEY_PEM.to_string(),
cut.to_string(),
long,
] {
let (mut s, mut rng, id) = session_after(0);
expect_failure(&mut s, &id, &mut rng, 200, &answer(true, Some(("plaincert", pem.as_bytes()))), PairingFailure::MalformedAnswer);
}
}
#[test]
fn identity_must_stay_the_same() {
let (mut s, mut rng, _) = session_after(1);
assert_err!(s.handle_response(&rogue(), 200, &resp2(), &mut rng), Error::Malformed { .. });
}
#[test]
fn start_refuses_bad_names_and_injection() {
use domistream::http::{MAX_DEVICE_NAME_BYTES, MAX_UNIQUE_ID_BYTES};
let id = client();
for (uid, dev) in [
("", DEVICE),
(&*"a".repeat(MAX_UNIQUE_ID_BYTES + 1), DEVICE),
(UID, ""),
(UID, &*"d".repeat(MAX_DEVICE_NAME_BYTES + 1)),
] {
assert_err!(PairingSession::start(&id, uid, dev, pin(), &mut rng_a()), Error::Malformed { .. });
}
// A device name with query syntax is refused or encoded: never a second `phrase`.
for evil in ["tv&phrase=pairchallenge", "tv\r\nHost: x", "tv#x", "tv salt=00"] {
match PairingSession::start(&id, UID, evil, pin(), &mut rng_a()) {
Err(Error::Malformed { .. }) => {}
Ok((_, req)) => {
let (_, q) = parse_query(&req.path_and_query);
assert_eq!(param(&q, "phrase"), "getservercert");
assert_eq!(param(&q, "devicename"), evil);
assert!(!req.path_and_query.contains(['\r', '\n', ' ', '#']));
}
Err(e) => panic!("{evil:?}: {e:?}"),
}
}
}
// ================================================================================================ crypto vectors
#[test]
fn derive_key_vectors() {
let v = v();
for i in 0..4 {
let salt: [u8; 16] = v.arr16(&format!("derive_{i}_salt"));
let p = Pin::from_digits(v.str(&format!("derive_{i}_pin"))).unwrap();
assert_eq!(crypto::derive_key(&salt, &p).unwrap().to_vec(), v.bytes(&format!("derive_{i}_key")), "vector {i}");
}
assert_eq!(crypto::derive_key(&v.arr16("salt"), &pin()).unwrap().to_vec(), v.bytes("key"));
}
#[test]
fn ecb_vectors() {
let v = v();
for blocks in 1..=4 {
let key = v.arr16(&format!("ecb_{blocks}_key"));
let plain = v.bytes(&format!("ecb_{blocks}_plain"));
let cipher = v.bytes(&format!("ecb_{blocks}_cipher"));
assert_eq!(crypto::ecb_encrypt(&key, &plain).unwrap(), cipher, "{blocks} blocks");
assert_eq!(crypto::ecb_decrypt(&key, &cipher).unwrap(), plain, "{blocks} blocks");
}
let key = v.arr16("key");
assert_eq!(crypto::ecb_encrypt(&key, &v.bytes("client_challenge")).unwrap(), v.bytes("step2_clientchallenge"));
for len in [1usize, 15, 17, 47] {
assert_err!(crypto::ecb_encrypt(&key, &vec![0; len]), Error::Malformed { .. }, "{len} bytes");
assert_err!(crypto::ecb_decrypt(&key, &vec![0; len]), Error::Malformed { .. }, "{len} bytes");
}
}
#[test]
fn proof_hash_vectors() {
let v = v();
for i in 0..6 {
let h = crypto::proof_hash(
&v.arr16(&format!("proof_{i}_challenge")),
&v.bytes(&format!("proof_{i}_signature")),
&v.arr16(&format!("proof_{i}_secret")),
)
.unwrap();
assert_eq!(h.to_vec(), v.bytes(&format!("proof_{i}_hash")), "vector {i}");
}
let h = crypto::proof_hash(&v.arr16("client_challenge"), &v.bytes("host_cert_signature"), &v.arr16("server_secret"));
assert_eq!(h.unwrap().to_vec(), v.bytes("host_proof"));
let h = crypto::proof_hash(&v.arr16("server_challenge"), &v.bytes("client_cert_signature"), &v.arr16("client_secret"));
assert_eq!(h.unwrap().to_vec(), v.bytes("client_proof"));
assert_too_large!(
crypto::proof_hash(&[0; 16], &vec![0; MAX_SIGNATURE_BYTES + 1], &[0; 16]),
MAX_SIGNATURE_BYTES,
MAX_SIGNATURE_BYTES + 1
);
}
#[test]
fn split_helpers() {
let v = v();
let key = v.arr16("key");
let decrypted = crypto::ecb_decrypt(&key, &v.bytes("step2_challengeresponse")).unwrap();
let (h, sc) = crypto::split_challenge_response(&decrypted).unwrap();
assert_eq!(h.to_vec(), v.bytes("host_proof"));
assert_eq!(sc.to_vec(), v.bytes("server_challenge"));
for len in [0usize, 1, 32, 47, 49, 64] {
assert_err!(crypto::split_challenge_response(&vec![0; len]), Error::Malformed { .. }, "{len}");
}
let ps = v.bytes("step3_pairingsecret");
let (secret, sig) = crypto::split_pairing_secret(&ps).unwrap();
assert_eq!(secret.to_vec(), v.bytes("server_secret"));
assert_eq!(sig, v.bytes("server_secret_signature").as_slice());
assert_eq!(crypto::split_pairing_secret(&[7; 17]).unwrap().1, &[7]);
assert_eq!(crypto::split_pairing_secret(&vec![7; 16 + MAX_SIGNATURE_BYTES]).unwrap().1.len(), MAX_SIGNATURE_BYTES);
for len in [0usize, 1, 15, 16] {
assert_err!(crypto::split_pairing_secret(&vec![0; len]), Error::Malformed { .. }, "{len}");
}
assert_too_large!(
crypto::split_pairing_secret(&vec![0; 16 + MAX_SIGNATURE_BYTES + 1]),
MAX_SIGNATURE_BYTES,
MAX_SIGNATURE_BYTES + 1
);
}
// ================================================================================================ certificates
#[test]
fn server_cert_from_recorded_pem() {
let v = v();
let c = ServerCert::from_pem(HOST_CERT_PEM.as_bytes()).unwrap();
assert_eq!(c.der(), v.bytes("host_cert_der").as_slice());
assert_eq!(c.signature().unwrap(), v.bytes("host_cert_signature"));
assert_eq!(ServerCert::from_der(&v.bytes("host_cert_der")).unwrap(), c);
c.verify(&v.bytes("server_secret"), &v.bytes("server_secret_signature")).unwrap();
}
#[test]
fn server_cert_verify_refuses() {
let v = v();
let c = ServerCert::from_pem(HOST_CERT_PEM.as_bytes()).unwrap();
let secret = v.bytes("server_secret");
let sig = v.bytes("server_secret_signature");
let mut flipped = sig.clone();
flipped[100] ^= 0x04;
let rogue_sig = &v.bytes("step3_pairingsecret_rogue_signature")[16..];
let mut other = secret.clone();
other[15] ^= 1;
assert_err!(c.verify(&secret, &flipped), Error::Crypto);
assert_err!(c.verify(&secret, rogue_sig), Error::Crypto);
assert_err!(c.verify(&other, &sig), Error::Crypto);
assert_err!(c.verify(&secret, &sig[..255]), Error::Crypto);
assert_err!(c.verify(&secret, &[]), Error::Crypto);
assert_err!(c.verify(&secret, &[sig.clone(), vec![0]].concat()), Error::Crypto);
}
#[test]
fn server_cert_pinning() {
let v = v();
let der = v.bytes("host_cert_der");
let c = ServerCert::from_der(&der).unwrap();
assert_eq!(c.matches(&der), Ok(true));
let mut flipped = der.clone();
flipped[der.len() / 2] ^= 1;
assert_eq!(c.matches(&flipped), Ok(false));
assert_eq!(c.matches(&der[..der.len() - 1]), Ok(false));
assert_eq!(c.matches(&[der.clone(), vec![0]].concat()), Ok(false));
assert_eq!(c.matches(&v.bytes("rogue_cert_der")), Ok(false));
assert_eq!(c.matches(&[]), Ok(false));
assert_too_large!(c.matches(&vec![0; MAX_CERT_DER_BYTES + 1]), MAX_CERT_DER_BYTES, MAX_CERT_DER_BYTES + 1);
}
#[test]
fn server_cert_hostile_pem() {
let cut = &HOST_CERT_PEM[..HOST_CERT_PEM.len() - 40];
let bad_b64 = HOST_CERT_PEM.replacen('M', "!", 3);
let two = format!("{HOST_CERT_PEM}{CLIENT_CERT_PEM}");
for (pem, why) in [
("", "empty"),
("x", "one byte"),
("-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE-----\n", "empty block"),
(cut, "cut"),
(&*bad_b64, "bad base64"),
(&*two, "two certificates"),
(CLIENT_KEY_PEM, "a private key"),
(EC_CERT_PEM, "not an RSA key"),
] {
assert_err!(ServerCert::from_pem(pem.as_bytes()), Error::Malformed { .. }, "{why}");
}
let mut big = HOST_CERT_PEM.as_bytes().to_vec();
big.resize(MAX_CERT_PEM_BYTES + 1, b'\n');
assert_too_large!(ServerCert::from_pem(&big), MAX_CERT_PEM_BYTES, MAX_CERT_PEM_BYTES + 1);
assert_too_large!(ServerCert::from_pem(&vec![b'A'; 1 << 24]), MAX_CERT_PEM_BYTES, 1 << 24);
}
#[test]
fn server_cert_hostile_der() {
let der = v().bytes("host_cert_der");
for (bad, why) in [
(vec![], "empty"),
(vec![0x30], "one byte"),
(der[..der.len() - 1].to_vec(), "cut"),
([der.clone(), vec![0]].concat(), "trailing byte"),
({
let mut d = der.clone();
d[1] = 0x84; // outer length claims 4 length bytes: lies about the size
d
}, "lying length"),
] {
assert_err!(ServerCert::from_der(&bad), Error::Malformed { .. }, "{why}");
}
let mut big = der.clone();
big.resize(MAX_CERT_DER_BYTES + 1, 0);
assert_too_large!(ServerCert::from_der(&big), MAX_CERT_DER_BYTES, MAX_CERT_DER_BYTES + 1);
}
#[test]
fn client_identity_from_recorded_keys() {
let v = v();
let id = client();
assert_eq!(id.cert_der(), v.bytes("client_cert_der").as_slice());
assert_eq!(id.key_pkcs8_der(), v.bytes("client_key_pkcs8_der").as_slice());
assert_eq!(id.cert_signature().unwrap(), v.bytes("client_cert_signature"));
assert_eq!(id.sign(&v.bytes("sign_data")).unwrap(), v.bytes("sign_data_client_signature"), "PKCS#1 v1.5 is deterministic");
assert_eq!(id.sign(&v.bytes("client_secret")).unwrap(), v.bytes("client_secret_signature"));
let pem = id.cert_pem().unwrap();
assert_eq!(pem_blocks(&pem, "CERTIFICATE"), vec![v.bytes("client_cert_der")]);
assert_eq!(pem_blocks(CLIENT_CERT_PEM, "CERTIFICATE"), vec![v.bytes("client_cert_der")], "fixture sanity");
}
#[test]
fn client_identity_refuses() {
use domistream::pairing::identity::MAX_KEY_DER_BYTES;
let v = v();
let cert = v.bytes("client_cert_der");
let key = v.bytes("client_key_pkcs8_der");
assert_err!(ClientIdentity::from_der(&cert, &v.bytes("rogue_key_pkcs8_der")), Error::Malformed { .. }, "key of another cert");
assert_err!(ClientIdentity::from_der(&v.bytes("rogue_cert_der"), &key), Error::Malformed { .. });
assert_err!(ClientIdentity::from_der(&[], &key), Error::Malformed { .. });
assert_err!(ClientIdentity::from_der(&cert, &[]), Error::Malformed { .. });
assert_err!(ClientIdentity::from_der(&cert, &key[..key.len() - 1]), Error::Malformed { .. });
assert_err!(ClientIdentity::from_der(&cert, &cert), Error::Malformed { .. });
let mut big_cert = cert.clone();
big_cert.resize(MAX_CERT_DER_BYTES + 1, 0);
assert_too_large!(ClientIdentity::from_der(&big_cert, &key), MAX_CERT_DER_BYTES, MAX_CERT_DER_BYTES + 1);
let mut big_key = key.clone();
big_key.resize(MAX_KEY_DER_BYTES + 1, 0);
assert_too_large!(ClientIdentity::from_der(&cert, &big_key), MAX_KEY_DER_BYTES, MAX_KEY_DER_BYTES + 1);
}
#[test]
fn client_identity_generate() {
let id = ClientIdentity::generate(&mut SeqRng::new(0xD0D0), "Living Room TV", 1_764_000_000).unwrap();
let cert = ServerCert::from_der(id.cert_der()).expect("a generated cert is a valid RSA X.509 certificate");
let sig = id.sign(b"hello").unwrap();
assert_eq!(sig.len(), domistream::pairing::identity::CLIENT_KEY_BITS / 8);
cert.verify(b"hello", &sig).expect("the cert carries the identity's public key");
let again = ClientIdentity::from_der(id.cert_der(), id.key_pkcs8_der()).unwrap();
assert_eq!(again.cert_der(), id.cert_der());
assert!(id.cert_der().windows(14).any(|w| w == b"Living Room TV"), "CN in the certificate");
assert_eq!(id.cert_signature().unwrap(), cert.signature().unwrap());
assert_err!(ClientIdentity::generate(&mut SeqRng::new(1), "", 0), Error::Malformed { .. });
assert_err!(ClientIdentity::generate(&mut SeqRng::new(1), &"n".repeat(10_000), 0), Error::Malformed { .. });
}
// ================================================================================================ PIN
#[test]
fn pin_from_digits() {
assert_eq!(Pin::from_digits("0000").unwrap().as_bytes(), b"0000");
assert_eq!(Pin::from_digits("4071").unwrap().as_bytes(), b"4071");
for bad in ["", "1", "123", "12345", "12a4", " 123", "123 ", "-123", "+123", "\u{0661}\u{0662}\u{0663}\u{0664}", "1234", "12\u{0}4"] {
assert_err!(Pin::from_digits(bad), Error::Malformed { .. }, "{bad:?}");
}
}
#[test]
fn pin_generate_is_uniform_digits() {
let mut rng = SeqRng::new(42);
let mut counts = [[0u32; 10]; 4];
let draws = 4000;
for _ in 0..draws {
let p = Pin::generate(&mut rng).unwrap();
for (pos, d) in p.as_bytes().iter().enumerate() {
assert!(d.is_ascii_digit(), "{d:#x}");
counts[pos][usize::from(d - b'0')] += 1;
}
}
// 400 expected per digit and position; a 4-sigma band (sd ~ 19) catches modulo bias of a u8 draw (+20 %).
for (pos, row) in counts.iter().enumerate() {
for (digit, &n) in row.iter().enumerate() {
assert!((324..=476).contains(&n), "digit {digit} at position {pos}: {n} of {draws}");
}
}
let a = Pin::generate(&mut SeqRng::new(9)).unwrap();
let b = Pin::generate(&mut SeqRng::new(9)).unwrap();
assert_eq!(a, b, "the PIN comes only from the caller's randomness");
}
// ================================================================================================ answer parser
#[test]
fn pair_response_parser() {
let r = parse_pair_response(&xml_root(200, "<paired>1</paired><plaincert>4142</plaincert>")).unwrap();
assert!(r.paired);
assert_eq!(r.plain_cert.as_deref(), Some(&b"AB"[..]));
assert_eq!(r.challenge_response, None);
let r = parse_pair_response(&xml_root(200, "<paired>0</paired><challengeresponse>aBcD</challengeresponse>")).unwrap();
assert!(!r.paired);
assert_eq!(r.challenge_response.as_deref(), Some(&[0xAB, 0xCD][..]));
let r = parse_pair_response(&xml_root(200, "<paired>1</paired><pairingsecret>00ff</pairingsecret>")).unwrap();
assert_eq!(r.pairing_secret.as_deref(), Some(&[0x00, 0xFF][..]));
for (inner, why) in [
("", "no paired"),
("<plaincert>4142</plaincert>", "no paired"),
("<paired>1</paired><plaincert>414</plaincert>", "odd hex"),
("<paired>1</paired><plaincert>41 42</plaincert>", "space in hex"),
("<paired>1</paired><plaincert>4G</plaincert>", "not hex"),
("<paired>1</paired><challengeresponse>0x41</challengeresponse>", "0x prefix"),
] {
assert_err!(parse_pair_response(&xml_root(200, inner)), Error::Malformed { .. }, "{why}");
}
assert_err!(parse_pair_response(&xml_root(400, "<paired>0</paired>")), Error::HostStatus { code: 400 });
assert_err!(parse_pair_response(b""), Error::Malformed { .. });
assert_err!(parse_pair_response(b"<"), Error::Malformed { .. });
}
#[test]
fn pair_response_sizes() {
let inner = "<paired>1</paired>";
for len in [MAX_PAIR_RESPONSE_BYTES - 1, MAX_PAIR_RESPONSE_BYTES] {
assert!(parse_pair_response(&xml_padded_to(inner, len)).unwrap().paired, "{len}");
}
assert_too_large!(
parse_pair_response(&xml_padded_to(inner, MAX_PAIR_RESPONSE_BYTES + 1)),
MAX_PAIR_RESPONSE_BYTES,
MAX_PAIR_RESPONSE_BYTES + 1
);
assert_too_large!(parse_pair_response(&vec![b'0'; 1 << 22]), MAX_PAIR_RESPONSE_BYTES, 1 << 22);
// A plaincert near the cap: the hex text is within MAX_XML_TEXT_BYTES and decodes to half its size.
let cert = vec![0x41u8; 30_000];
let r = parse_pair_response(&answer(true, Some(("plaincert", &cert)))).unwrap();
assert_eq!(r.plain_cert.unwrap().len(), 30_000);
}
+727
View File
@@ -0,0 +1,727 @@
//! RTSP (`docs/PROTOCOL.md` 2): message parsers, the TCP framer (64 KiB cap), SDP and `surround-params`, the
//! ANNOUNCE builder and the client state machine, all with hostile input.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
mod common;
use domistream::Error;
use domistream::http::launch::AudioLayout;
use domistream::rtsp::client::VideoCodec;
use domistream::rtsp::sdp::{self, MAX_OPUS_CONFIGS, MAX_SDP_BYTES, MAX_SDP_LINES};
use domistream::rtsp::{
EncryptionFlags, HostCapabilities, MAX_RTSP_HEADERS, MAX_RTSP_LINE_BYTES, MAX_RTSP_MESSAGE_BYTES, Method,
RtspClient, RtspClientState, RtspFramer, RtspProgress, RtspRequest, StreamConfig, parse_request, parse_response,
};
use proptest::prelude::*;
macro_rules! assert_cap {
($e:expr, $max:expr) => {
match $e {
Err(Error::TooLarge { max, .. }) => assert_eq!(max, $max, "TooLarge.max"),
other => panic!("expected Err(TooLarge {{ max: {} }}), got {:?}", $max, other),
}
};
}
fn response(status: &str, headers: &[(&str, &str)], body: &[u8]) -> Vec<u8> {
let mut m = format!("RTSP/1.0 {status}\r\n");
for (k, v) in headers {
m.push_str(&format!("{k}: {v}\r\n"));
}
m.push_str("\r\n");
let mut m = m.into_bytes();
m.extend_from_slice(body);
m
}
/// A 200 answer padded with a body to exactly `total` bytes.
fn response_of_size(total: usize) -> Vec<u8> {
let probe = response("200 OK", &[("CSeq", "1"), ("Content-Length", "00000")], b"");
let body_len = total - probe.len();
let cl = format!("{body_len:05}");
let m = response("200 OK", &[("CSeq", "1"), ("Content-Length", &cl)], &vec![b'b'; body_len]);
assert_eq!(m.len(), total);
m
}
// ================================================================================================ responses
#[test]
fn response_sample() {
let r = parse_response(&response("200 OK", &[("CSeq", "1"), ("Content-Length", "5")], b"hello")).unwrap();
assert_eq!(r.status, 200);
assert_eq!(r.reason, "OK");
assert_eq!(r.headers, vec![("CSeq".into(), "1".into()), ("Content-Length".into(), "5".into())]);
assert_eq!(r.body, b"hello");
assert_eq!(r.header("cseq"), Some("1"));
assert_eq!(r.header("CONTENT-LENGTH"), Some("5"));
// Without Content-Length the payload is everything after the headers (UNKNOWN U5).
let r = parse_response(&response("404 Not Found", &[("CSeq", "2")], b"rest")).unwrap();
assert_eq!(r.status, 404);
assert_eq!(r.reason, "Not Found");
assert_eq!(r.body, b"rest");
let r = parse_response(&response("200 OK", &[("content-length", "0")], b"")).unwrap();
assert!(r.body.is_empty());
}
#[test]
fn response_bad_start_lines() {
for bad in [
&b""[..],
b"R",
b"HTTP/1.1 200 OK\r\n\r\n",
b"RTSP/1.0 abc OK\r\n\r\n",
b"RTSP/1.0 2000 OK\r\n\r\n",
b"RTSP/1.0 -20 OK\r\n\r\n",
b"RTSP/1.0\r\n\r\n",
b"RTSP/2.0 200 OK\r\n\r\n",
b" RTSP/1.0 200 OK\r\n\r\n",
b"\r\n\r\n",
] {
assert_err!(parse_response(bad), Error::Malformed { .. }, "{:?}", String::from_utf8_lossy(bad));
}
}
#[test]
fn response_bad_headers() {
for bad in [
&b"RTSP/1.0 200 OK\r\nno colon here\r\n\r\n"[..],
b"RTSP/1.0 200 OK\r\n: empty name\r\n\r\n",
b"RTSP/1.0 200 OK\r\nCSeq: \xff\xfe\r\n\r\n",
b"RTSP/1.0 200 OK\r\nCSeq: 1\rX: y\r\n\r\n",
] {
assert_err!(parse_response(bad), Error::Malformed { .. }, "{:?}", String::from_utf8_lossy(bad));
}
// Headers that never end.
assert_err!(parse_response(b"RTSP/1.0 200 OK\r\nCSeq: 1\r\n"), Error::Truncated { .. });
}
#[test]
fn response_lying_content_length() {
// Over: claims more than is there.
assert_err!(parse_response(&response("200 OK", &[("Content-Length", "10")], b"12345")), Error::Truncated { .. });
// Under: more bytes than it claims.
assert_err!(parse_response(&response("200 OK", &[("Content-Length", "2")], b"12345")), Error::Malformed { .. });
for cl in ["abc", "-1", "+5", "5 5", "0x5", "", "5;"] {
assert_err!(parse_response(&response("200 OK", &[("Content-Length", cl)], b"12345")), Error::Malformed { .. }, "{cl:?}");
}
// Two different lengths.
assert_err!(
parse_response(&response("200 OK", &[("Content-Length", "5"), ("Content-Length", "4")], b"12345")),
Error::Malformed { .. }
);
// Past the cap: refused as too large, not waited for.
assert_cap!(parse_response(&response("200 OK", &[("Content-Length", "65537")], b"")), MAX_RTSP_MESSAGE_BYTES);
assert_cap!(parse_response(&response("200 OK", &[("Content-Length", "4294967295")], b"")), MAX_RTSP_MESSAGE_BYTES);
// Past u64: a number that big is over the cap or not a number; either way refused, never wrapped.
let r = parse_response(&response("200 OK", &[("Content-Length", "99999999999999999999999")], b""));
assert!(matches!(r, Err(Error::TooLarge { .. } | Error::Malformed { .. })), "{r:?}");
}
#[test]
fn response_header_flood() {
let names: Vec<String> = (0..=MAX_RTSP_HEADERS).map(|i| format!("X-H{i}")).collect();
let headers = |n: usize| names[..n].iter().map(|n| (n.as_str(), "v")).collect::<Vec<_>>();
assert_eq!(parse_response(&response("200 OK", &headers(MAX_RTSP_HEADERS), b"")).unwrap().headers.len(), MAX_RTSP_HEADERS);
assert_cap!(parse_response(&response("200 OK", &headers(MAX_RTSP_HEADERS + 1), b"")), MAX_RTSP_HEADERS);
// A flood of empty-valued headers in under 64 KiB.
let flood: Vec<(String, &str)> = (0..5000).map(|i| (format!("F{i}"), "")).collect();
let flood: Vec<(&str, &str)> = flood.iter().map(|(k, v)| (k.as_str(), *v)).collect();
assert_cap!(parse_response(&response("200 OK", &flood, b"")), MAX_RTSP_HEADERS);
}
#[test]
fn response_line_cap() {
// "X: " + value, without CRLF.
let value = |line: usize| "v".repeat(line - 3);
let ok = value(MAX_RTSP_LINE_BYTES);
assert_eq!(parse_response(&response("200 OK", &[("X", &ok)], b"")).unwrap().header("x"), Some(ok.as_str()));
assert_cap!(parse_response(&response("200 OK", &[("X", &value(MAX_RTSP_LINE_BYTES + 1))], b"")), MAX_RTSP_LINE_BYTES);
let reason = "r".repeat(MAX_RTSP_LINE_BYTES);
assert_cap!(parse_response(&response(&format!("200 {reason}"), &[], b"")), MAX_RTSP_LINE_BYTES);
}
#[test]
fn response_size_boundaries() {
for len in [MAX_RTSP_MESSAGE_BYTES - 1, MAX_RTSP_MESSAGE_BYTES] {
let r = parse_response(&response_of_size(len)).unwrap_or_else(|e| panic!("{len}: {e:?}"));
assert_eq!(r.status, 200);
}
assert_too_large!(parse_response(&response_of_size(MAX_RTSP_MESSAGE_BYTES + 1)), MAX_RTSP_MESSAGE_BYTES, MAX_RTSP_MESSAGE_BYTES + 1);
assert_too_large!(parse_response(&vec![b'R'; 1 << 24]), MAX_RTSP_MESSAGE_BYTES, 1 << 24);
}
// ================================================================================================ requests
#[test]
fn request_parse_and_encode() {
let raw = b"OPTIONS rtsp://192.0.2.10:48010 RTSP/1.0\r\nCSeq: 1\r\nX-GS-ClientVersion: 14\r\n\r\n";
let r = parse_request(raw).unwrap();
assert_eq!(r.method, Method::Options);
assert_eq!(r.target, "rtsp://192.0.2.10:48010");
assert_eq!(r.headers, vec![("CSeq".into(), "1".into()), ("X-GS-ClientVersion".into(), "14".into())]);
assert!(r.body.is_empty());
assert_eq!(r.encode().unwrap(), raw.to_vec(), "encode emits exactly the given headers, CRLF, empty line");
let announce = RtspRequest {
method: Method::Announce,
target: "streamid=control/13/0".into(),
headers: vec![("CSeq".into(), "6".into()), ("Content-Length".into(), "6".into())],
body: b"v=0\r\n\r".to_vec(),
};
let bytes = announce.encode().unwrap();
assert!(bytes.starts_with(b"ANNOUNCE streamid=control/13/0 RTSP/1.0\r\n"));
assert_eq!(parse_request(&bytes).unwrap(), announce);
for (m, name) in [
(Method::Options, "OPTIONS"),
(Method::Describe, "DESCRIBE"),
(Method::Setup, "SETUP"),
(Method::Announce, "ANNOUNCE"),
(Method::Play, "PLAY"),
] {
let req = RtspRequest { method: m, target: "x".into(), headers: vec![("CSeq".into(), "1".into())], body: vec![] };
assert!(req.encode().unwrap().starts_with(format!("{name} x RTSP/1.0\r\n").as_bytes()));
}
}
#[test]
fn request_refuses_unknown_methods_and_bad_lines() {
for m in ["GET_PARAMETER", "TEARDOWN", "options", "GET", "PAUSE"] {
let raw = format!("{m} rtsp://h:1 RTSP/1.0\r\nCSeq: 1\r\n\r\n");
assert_err!(parse_request(raw.as_bytes()), Error::UnexpectedValue { .. }, "{m}");
}
for bad in [&b""[..], b"O", b"OPTIONS\r\n\r\n", b"OPTIONS rtsp://h:1\r\n\r\n", b"OPTIONS rtsp://h:1 RTSP/9.9\r\n\r\n"] {
assert_err!(parse_request(bad), Error::Malformed { .. }, "{:?}", String::from_utf8_lossy(bad));
}
assert_too_large!(parse_request(&vec![b'O'; MAX_RTSP_MESSAGE_BYTES + 1]), MAX_RTSP_MESSAGE_BYTES, MAX_RTSP_MESSAGE_BYTES + 1);
}
#[test]
fn encode_refuses_header_injection() {
let base = || RtspRequest { method: Method::Setup, target: "streamid=video/0/0".into(), headers: vec![("CSeq".into(), "4".into())], body: vec![] };
let mut cases = Vec::new();
for evil in ["a\r\nX: y", "a\ny", "a\rb"] {
cases.push(RtspRequest { target: evil.into(), ..base() });
cases.push(RtspRequest { headers: vec![(evil.into(), "v".into())], ..base() });
cases.push(RtspRequest { headers: vec![("Transport".into(), evil.into())], ..base() });
}
cases.push(RtspRequest { headers: vec![("Bad:Name".into(), "v".into())], ..base() });
cases.push(RtspRequest { headers: vec![(String::new(), "v".into())], ..base() });
cases.push(RtspRequest { target: String::new(), ..base() });
for req in cases {
assert_err!(req.encode(), Error::Malformed { .. }, "{req:?}");
}
let big = RtspRequest { body: vec![0; MAX_RTSP_MESSAGE_BYTES], ..base() };
assert_cap!(big.encode(), MAX_RTSP_MESSAGE_BYTES);
}
fn method() -> impl Strategy<Value = Method> {
prop_oneof![Just(Method::Options), Just(Method::Describe), Just(Method::Setup), Just(Method::Announce), Just(Method::Play)]
}
proptest! {
#![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })]
/// encode then parse gives the request back.
#[test]
fn request_round_trip(
m in method(),
target in "[!-~]{1,40}",
headers in proptest::collection::vec(("[A-Za-z][A-Za-z0-9-]{0,15}", "[!-~]([ -~]{0,30}[!-~])?"), 0..10),
body in proptest::collection::vec(any::<u8>(), 0..200),
) {
let mut headers: Vec<(String, String)> =
headers.into_iter().filter(|(k, _)| !k.eq_ignore_ascii_case("content-length")).collect();
headers.insert(0, ("CSeq".into(), "1".into()));
if !body.is_empty() {
headers.push(("Content-Length".into(), body.len().to_string()));
}
let req = RtspRequest { method: m, target, headers, body };
let bytes = req.encode().map_err(|e| TestCaseError::fail(format!("{e:?}")))?;
prop_assert_eq!(parse_request(&bytes), Ok(req));
}
/// Arbitrary bytes never panic, and a parsed response respects the caps.
#[test]
fn response_never_panics(data in proptest::collection::vec(any::<u8>(), 0..1024)) {
if let Ok(r) = parse_response(&data) {
prop_assert!(r.headers.len() <= MAX_RTSP_HEADERS);
prop_assert!(r.body.len() <= data.len());
prop_assert!(r.reason.len() <= MAX_RTSP_LINE_BYTES);
}
let _ = parse_request(&data);
}
}
// ================================================================================================ framer
fn drain(f: &mut RtspFramer) -> Vec<Vec<u8>> {
let mut out = Vec::new();
while let Some(m) = f.next_message().unwrap() {
out.push(m);
}
out
}
#[test]
fn framer_cuts_messages() {
let a = response("200 OK", &[("CSeq", "1"), ("Content-Length", "5")], b"hello");
let b = response("200 OK", &[("CSeq", "2"), ("Content-Length", "0")], b"");
let mut f = RtspFramer::new();
f.push(&[a.clone(), b.clone()].concat()).unwrap();
assert_eq!(drain(&mut f), vec![a.clone(), b.clone()]);
assert_eq!(f.buffered(), 0);
assert_eq!(f.finish(), Ok(None));
// One byte at a time: same messages, nothing early.
let mut f = RtspFramer::new();
let stream = [a.clone(), b.clone()].concat();
let mut got = Vec::new();
for (i, byte) in stream.iter().enumerate() {
f.push(std::slice::from_ref(byte)).unwrap();
got.extend(drain(&mut f));
if i + 1 < a.len() {
assert!(got.is_empty(), "message returned before its last byte");
}
}
assert_eq!(got, vec![a, b]);
}
#[test]
fn framer_partial_second_message_stays_buffered() {
let a = response("200 OK", &[("Content-Length", "2")], b"ok");
let partial = b"RTSP/1.0 200 OK\r\nCont";
let mut f = RtspFramer::new();
f.push(&[a.clone(), partial.to_vec()].concat()).unwrap();
assert_eq!(f.next_message().unwrap(), Some(a));
assert_eq!(f.next_message().unwrap(), None);
assert_eq!(f.buffered(), partial.len());
}
#[test]
fn framer_without_content_length_waits_for_close() {
let m = response("200 OK", &[("CSeq", "1")], b"payload until close");
let mut f = RtspFramer::new();
f.push(&m).unwrap();
assert_eq!(f.next_message().unwrap(), None, "no Content-Length: the message ends at close (U5)");
assert_eq!(f.finish().unwrap(), Some(m));
assert_eq!(f.buffered(), 0);
}
#[test]
fn framer_close_mid_body_is_truncated() {
let mut f = RtspFramer::new();
f.push(&response("200 OK", &[("Content-Length", "10")], b"12345")).unwrap();
assert_eq!(f.next_message().unwrap(), None);
assert_err!(f.finish(), Error::Truncated { .. });
}
#[test]
fn framer_cap_64k_plus_one() {
// Bytes that never form a complete header section.
let mut f = RtspFramer::new();
f.push(&vec![b'a'; MAX_RTSP_MESSAGE_BYTES]).unwrap();
assert_eq!(f.next_message().unwrap(), None);
assert_eq!(f.buffered(), MAX_RTSP_MESSAGE_BYTES);
assert_too_large!(f.push(b"a"), MAX_RTSP_MESSAGE_BYTES, MAX_RTSP_MESSAGE_BYTES + 1);
// One push over the cap.
let mut f = RtspFramer::new();
assert_too_large!(f.push(&vec![b'a'; MAX_RTSP_MESSAGE_BYTES + 1]), MAX_RTSP_MESSAGE_BYTES, MAX_RTSP_MESSAGE_BYTES + 1);
// A whole message of exactly the cap is fine.
let mut f = RtspFramer::new();
let m = response_of_size(MAX_RTSP_MESSAGE_BYTES);
f.push(&m).unwrap();
assert_eq!(f.next_message().unwrap(), Some(m));
}
/// Pushes `bytes` and asks for a message; the first error from either call.
fn push_then_next(f: &mut RtspFramer, bytes: &[u8]) -> domistream::Result<Option<Vec<u8>>> {
f.push(bytes)?;
f.next_message()
}
#[test]
fn framer_refuses_lying_content_length_early() {
// The header says the message will be over the cap: refused now, without waiting for (or buffering) it.
for cl in ["65537", "4294967295", "18446744073709551615"] {
let mut f = RtspFramer::new();
let r = push_then_next(&mut f, &response("200 OK", &[("Content-Length", cl)], b"x"));
assert!(matches!(r, Err(Error::TooLarge { .. } | Error::Malformed { .. })), "{cl}: {r:?}");
}
let mut f = RtspFramer::new();
assert_cap!(push_then_next(&mut f, &response("200 OK", &[("Content-Length", "65537")], b"")), MAX_RTSP_MESSAGE_BYTES);
for cl in ["abc", "-1", "1 2"] {
let mut f = RtspFramer::new();
assert_err!(push_then_next(&mut f, &response("200 OK", &[("Content-Length", cl)], b"")), Error::Malformed { .. }, "{cl}");
}
}
#[test]
fn framer_empty_pushes() {
let mut f = RtspFramer::new();
f.push(b"").unwrap();
assert_eq!(f.next_message().unwrap(), None);
assert_eq!(f.finish().unwrap(), None);
}
proptest! {
#![proptest_config(ProptestConfig { cases: 128, ..ProptestConfig::default() })]
/// Any chunking of a stream of messages yields the same messages.
#[test]
fn framer_is_chunking_invariant(bodies in proptest::collection::vec(proptest::collection::vec(any::<u8>(), 0..300), 1..6), cuts in proptest::collection::vec(1usize..200, 1..50)) {
let msgs: Vec<Vec<u8>> = bodies.iter().enumerate()
.map(|(i, b)| response("200 OK", &[("CSeq", &i.to_string()), ("Content-Length", &b.len().to_string())], b))
.collect();
let stream = msgs.concat();
let mut f = RtspFramer::new();
let mut got = Vec::new();
let mut pos = 0;
let mut cut = cuts.iter().cycle();
while pos < stream.len() {
let end = (pos + cut.next().copied().unwrap_or(1)).min(stream.len());
f.push(&stream[pos..end]).map_err(|e| TestCaseError::fail(format!("{e:?}")))?;
while let Some(m) = f.next_message().map_err(|e| TestCaseError::fail(format!("{e:?}")))? {
got.push(m);
}
prop_assert!(f.buffered() <= MAX_RTSP_MESSAGE_BYTES);
pos = end;
}
prop_assert_eq!(got, msgs);
prop_assert_eq!(f.finish(), Ok(None));
}
}
// ================================================================================================ SDP
const DESCRIBE_SDP: &str = "v=0\r\no=- 0 14 IN IPv4 0.0.0.0\r\ns=Lab host\r\n\
a=x-ss-general.featureFlags:3\r\n\
a=x-ss-general.encryptionSupported:7\r\n\
a=x-nv-video[0].refPicInvalidation:1\r\n\
a=rtpmap:98 AV1/90000\r\n\
a=fmtp:96 packetization-mode=1\r\n\
sprop-parameter-sets=AAAAAU\r\n\
a=fmtp:97 surround-params=21101\r\n\
a=fmtp:97 surround-params=642012345\r\n\
a=fmtp:97 surround-params=85301234567\r\n\
a=recvonly\r\n";
#[test]
fn sdp_sample() {
let s = sdp::parse_sdp(DESCRIBE_SDP.as_bytes()).unwrap();
assert_eq!(s.attribute("x-ss-general.featureFlags"), Some("3"));
assert_eq!(s.attribute("rtpmap"), Some("98 AV1/90000"));
assert_eq!(s.attribute("fmtp"), Some("96 packetization-mode=1"), "first one wins");
assert_eq!(s.attribute("recvonly"), Some(""), "flag attribute");
assert_eq!(s.attributes.iter().filter(|(n, _)| n == "fmtp").count(), 4);
assert_eq!(s.other[0], ('v', "0".to_string()));
assert!(s.other.iter().any(|(t, v)| *t == '\0' && v.contains("sprop-parameter-sets")), "{:?}", s.other);
// LF-only line ends give the same result.
assert_eq!(sdp::parse_sdp(DESCRIBE_SDP.replace("\r\n", "\n").as_bytes()).unwrap(), s);
assert_eq!(sdp::parse_sdp(b"").unwrap(), sdp::Sdp::default());
}
#[test]
fn sdp_hostile() {
for (bad, why) in [
(&b"v=0\r\nno equals sign\r\n"[..], "line without ="),
(b"a=x:\xff\r\n", "not UTF-8"),
(b"=x\r\n", "empty type"),
] {
assert_err!(sdp::parse_sdp(bad), Error::Malformed { .. }, "{why}");
}
let lines = |n: usize| "a=x:1\n".repeat(n);
assert_eq!(sdp::parse_sdp(lines(MAX_SDP_LINES).as_bytes()).unwrap().attributes.len(), MAX_SDP_LINES);
assert_cap!(sdp::parse_sdp(lines(MAX_SDP_LINES + 1).as_bytes()), MAX_SDP_LINES);
let sized = |n: usize| {
let mut s = "a=pad:".to_string();
s.push_str(&"p".repeat(n - s.len() - 1));
s.push('\n');
s
};
for n in [MAX_SDP_BYTES - 1, MAX_SDP_BYTES] {
assert!(sdp::parse_sdp(sized(n).as_bytes()).is_ok(), "{n}");
}
assert_too_large!(sdp::parse_sdp(sized(MAX_SDP_BYTES + 1).as_bytes()), MAX_SDP_BYTES, MAX_SDP_BYTES + 1);
assert_too_large!(sdp::parse_sdp(&vec![b'a'; 1 << 20]), MAX_SDP_BYTES, 1 << 20);
}
#[test]
fn surround_params() {
let c = sdp::parse_surround_params("21101").unwrap();
assert_eq!((c.channels, c.streams, c.coupled_streams, c.mapping.clone()), (2, 1, 1, vec![0, 1]));
let c = sdp::parse_surround_params("642012345").unwrap();
assert_eq!((c.channels, c.streams, c.coupled_streams), (6, 4, 2));
assert_eq!(c.mapping, vec![0, 1, 2, 3, 4, 5]);
let c = sdp::parse_surround_params("85301234567").unwrap();
assert_eq!((c.channels, c.streams, c.coupled_streams, c.mapping.len()), (8, 5, 3, 8));
let c = sdp::parse_surround_params("11000").unwrap_err();
assert!(matches!(c, Error::Malformed { .. }), "one channel needs one mapping digit, not two");
assert_eq!(sdp::parse_surround_params("1100").unwrap().mapping, vec![0]);
for (bad, why) in [
("", "empty"),
("2", "cut"),
("2110", "one mapping digit short"),
("211012", "one mapping digit too many"),
("21102", "mapping 2 >= streams + coupled"),
("21201", "coupled > streams"),
("01100", "zero channels"),
("20001", "zero streams"),
("2a101", "not a digit"),
("2 1101", "space"),
("9530123456789", "9 channels > MAX_AUDIO_CHANNELS"),
("-2110", "sign"),
] {
assert_err!(sdp::parse_surround_params(bad), Error::Malformed { .. }, "{why}: {bad:?}");
}
}
#[test]
fn host_capabilities() {
let caps = HostCapabilities::from_sdp(&sdp::parse_sdp(DESCRIBE_SDP.as_bytes()).unwrap()).unwrap();
assert_eq!(caps.encryption_supported, EncryptionFlags(7));
assert_eq!(caps.feature_flags.0, 3);
assert!(caps.reference_frame_invalidation);
assert!(caps.av1);
assert_eq!(caps.opus_configs.len(), 3);
assert_eq!(caps.opus_configs[0].mapping, vec![0, 1]);
let none = HostCapabilities::from_sdp(&sdp::parse_sdp(b"v=0\n").unwrap()).unwrap();
assert_eq!(none, HostCapabilities::default());
for bad in [
"a=x-ss-general.encryptionSupported:x\n",
"a=x-ss-general.encryptionSupported:256\n",
"a=x-ss-general.featureFlags:-1\n",
"a=fmtp:97 surround-params=2110\n",
"a=fmtp:97 surround-params=\n",
] {
let s = sdp::parse_sdp(bad.as_bytes()).unwrap();
assert_err!(HostCapabilities::from_sdp(&s), Error::Malformed { .. }, "{bad:?}");
}
let many = "a=fmtp:97 surround-params=21101\n".repeat(MAX_OPUS_CONFIGS + 1);
assert_cap!(HostCapabilities::from_sdp(&sdp::parse_sdp(many.as_bytes()).unwrap()), MAX_OPUS_CONFIGS);
let max = "a=fmtp:97 surround-params=21101\n".repeat(MAX_OPUS_CONFIGS);
assert_eq!(HostCapabilities::from_sdp(&sdp::parse_sdp(max.as_bytes()).unwrap()).unwrap().opus_configs.len(), MAX_OPUS_CONFIGS);
}
fn config() -> StreamConfig {
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(EncryptionFlags::CONTROL_V2 | EncryptionFlags::VIDEO | EncryptionFlags::AUDIO),
}
}
#[test]
fn announce_payload() {
let host = HostCapabilities::from_sdp(&sdp::parse_sdp(DESCRIBE_SDP.as_bytes()).unwrap()).unwrap();
let s = sdp::parse_sdp(&sdp::build_announce(&config(), &host).unwrap()).expect("ANNOUNCE is valid SDP");
assert_eq!(s.attribute("x-nv-video[0].clientViewportWd"), Some("1920"));
assert_eq!(s.attribute("x-nv-video[0].clientViewportHt"), Some("1080"));
assert_eq!(s.attribute("x-nv-video[0].maxFPS"), Some("60"));
assert_eq!(s.attribute("x-nv-video[0].packetSize"), Some("1024"));
assert_eq!(s.attribute("x-ml-video.configuredBitrateKbps"), Some("20000"));
assert_eq!(s.attribute("x-nv-aqos.packetDuration"), Some("5"));
assert_eq!(s.attribute("x-nv-vqos[0].fec.minRequiredFecPackets"), Some("2"));
assert_eq!(s.attribute("x-ss-general.encryptionEnabled"), Some("7"));
// Only what both sides support is turned on.
let mut partial = host.clone();
partial.encryption_supported = EncryptionFlags(EncryptionFlags::CONTROL_V2 | EncryptionFlags::AUDIO);
let s = sdp::parse_sdp(&sdp::build_announce(&config(), &partial).unwrap()).unwrap();
assert_eq!(s.attribute("x-ss-general.encryptionEnabled"), Some("5"));
}
#[test]
fn announce_refuses_what_the_host_lacks() {
let host = HostCapabilities::from_sdp(&sdp::parse_sdp(DESCRIBE_SDP.as_bytes()).unwrap()).unwrap();
let mut no_v2 = host.clone();
no_v2.encryption_supported = EncryptionFlags(EncryptionFlags::VIDEO | EncryptionFlags::AUDIO);
assert_err!(sdp::build_announce(&config(), &no_v2), Error::Unsupported { .. });
let mut no_av1 = host.clone();
no_av1.av1 = false;
assert_err!(sdp::build_announce(&StreamConfig { codec: VideoCodec::Av1, ..config() }, &no_av1), Error::Unsupported { .. });
assert!(sdp::build_announce(&StreamConfig { codec: VideoCodec::Av1, ..config() }, &host).is_ok());
}
// ================================================================================================ client
const URL: &str = "rtsp://192.0.2.10:48010";
fn describe_answer(cseq: u32, sdp: &str) -> Vec<u8> {
response("200 OK", &[("CSeq", &cseq.to_string()), ("Content-Length", &sdp.len().to_string())], sdp.as_bytes())
}
fn setup_answer(cseq: u32, port: &str) -> Vec<u8> {
response(
"200 OK",
&[("CSeq", &cseq.to_string()), ("Session", "DEADBEEFCAFE;timeout = 90"), ("Transport", &format!("server_port={port}"))],
b"",
)
}
fn ok_answer(cseq: u32) -> Vec<u8> {
response("200 OK", &[("CSeq", &cseq.to_string())], b"")
}
fn next_request(c: &mut RtspClient) -> RtspRequest {
let bytes = c.poll_request().expect("a request is due");
assert_eq!(c.poll_request(), None, "each request is returned once");
parse_request(&bytes).expect("the client's request parses")
}
fn cseq(r: &RtspRequest) -> u32 {
r.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case("cseq")).expect("CSeq").1.parse().expect("CSeq number")
}
#[test]
fn client_full_negotiation() {
let mut c = RtspClient::new(URL, config()).unwrap();
assert_eq!(c.state(), RtspClientState::Options);
let expect = [
(Method::Options, RtspClientState::Describe),
(Method::Describe, RtspClientState::SetupAudio),
(Method::Setup, RtspClientState::SetupVideo),
(Method::Setup, RtspClientState::SetupControl),
(Method::Setup, RtspClientState::Announce),
(Method::Announce, RtspClientState::Play),
];
let mut last_cseq = 0;
let streams = ["streamid=audio", "streamid=video", "streamid=control"];
for (i, (method, next_state)) in expect.iter().enumerate() {
let req = next_request(&mut c);
assert_eq!(req.method, *method, "request {i}");
let n = cseq(&req);
assert!(n > last_cseq, "CSeq counts up");
last_cseq = n;
if *method == Method::Setup {
assert!(req.target.contains(streams[i - 2]), "SETUP {} target {:?}", i - 2, req.target);
assert!(req.headers.iter().any(|(k, _)| k.eq_ignore_ascii_case("transport")), "SETUP has Transport");
}
if *method == Method::Announce {
let s = sdp::parse_sdp(&req.body).unwrap();
assert_eq!(s.attribute("x-ss-general.encryptionEnabled"), Some("7"));
}
let answer = match i {
1 => describe_answer(n, DESCRIBE_SDP),
2 => setup_answer(n, "48000"),
3 => setup_answer(n, "47998"),
4 => setup_answer(n, "47999"),
_ => ok_answer(n),
};
assert_eq!(c.handle_response(&answer).unwrap(), RtspProgress::Continue);
assert_eq!(c.state(), *next_state);
}
let play = next_request(&mut c);
assert_eq!(play.method, Method::Play);
match c.handle_response(&ok_answer(cseq(&play))).unwrap() {
RtspProgress::Ready(n) => {
assert_eq!((n.ports.audio, n.ports.video, n.ports.control), (48000, 47998, 47999));
assert_eq!(n.encryption, EncryptionFlags(7));
assert_eq!(n.opus.mapping, vec![0, 1]);
assert_eq!(n.opus.channels, 2);
assert_eq!(n.session_id.as_deref(), Some("DEADBEEFCAFE"));
assert!(n.host.av1);
assert!(!n.ping_payload.is_empty());
}
RtspProgress::Continue => panic!("PLAY answered: expected Ready"),
}
assert_eq!(c.state(), RtspClientState::Ready);
assert_eq!(c.poll_request(), None);
assert_err!(c.handle_response(&ok_answer(last_cseq + 2)), Error::State { .. });
}
/// Runs the negotiation, answering with `answers(i, cseq)`; returns the first error and the state then.
fn run_until_error(answers: impl Fn(usize, u32) -> Vec<u8>) -> (Error, RtspClientState) {
let mut c = RtspClient::new(URL, config()).unwrap();
for i in 0..7 {
let req = next_request(&mut c);
if let Err(e) = c.handle_response(&answers(i, cseq(&req))) {
return (e, c.state());
}
}
panic!("negotiation finished without an error");
}
fn good(i: usize, n: u32) -> Vec<u8> {
match i {
1 => describe_answer(n, DESCRIBE_SDP),
2 => setup_answer(n, "48000"),
3 => setup_answer(n, "47998"),
4 => setup_answer(n, "47999"),
_ => ok_answer(n),
}
}
#[test]
fn client_refuses_hostile_answers() {
let (e, s) = run_until_error(|i, n| if i == 1 { ok_answer(n + 1) } else { good(i, n) });
assert!(matches!(e, Error::Malformed { .. }), "CSeq mismatch: {e:?}");
assert_eq!(s, RtspClientState::Failed);
let (e, s) = run_until_error(|i, n| if i == 1 { response("404 Not Found", &[("CSeq", &n.to_string())], b"") } else { good(i, n) });
assert_eq!(e, Error::HostStatus { code: 404 });
assert_eq!(s, RtspClientState::Failed);
let no_v2 = DESCRIBE_SDP.replace("encryptionSupported:7", "encryptionSupported:6");
let (e, _) = run_until_error(|i, n| if i == 1 { describe_answer(n, &no_v2) } else { good(i, n) });
assert!(matches!(e, Error::Unsupported { .. }), "host without control V2: {e:?}");
for port in ["0", "70000", "abc", ""] {
let (e, s) = run_until_error(|i, n| if i == 3 { setup_answer(n, port) } else { good(i, n) });
assert!(matches!(e, Error::Malformed { .. }), "server_port={port:?}: {e:?}");
assert_eq!(s, RtspClientState::Failed);
}
let (e, _) = run_until_error(|i, n| if i == 2 { ok_answer(n) } else { good(i, n) });
assert!(matches!(e, Error::Malformed { .. }), "SETUP answer without Transport: {e:?}");
let (e, _) = run_until_error(|i, n| if i == 1 { describe_answer(n, "v=0\nbroken line\n") } else { good(i, n) });
assert!(matches!(e, Error::Malformed { .. }), "bad SDP: {e:?}");
let (e, _) = run_until_error(|i, n| if i == 0 { b"garbage".to_vec() } else { good(i, n) });
assert!(matches!(e, Error::Malformed { .. }), "garbage: {e:?}");
}
#[test]
fn client_answer_without_request() {
let mut c = RtspClient::new(URL, config()).unwrap();
let req = next_request(&mut c);
c.handle_response(&ok_answer(cseq(&req))).unwrap();
// DESCRIBE is due but its answer arrives twice.
let d = next_request(&mut c);
c.handle_response(&describe_answer(cseq(&d), DESCRIBE_SDP)).unwrap();
assert_err!(c.handle_response(&describe_answer(cseq(&d), DESCRIBE_SDP)), Error::State { .. });
}
#[test]
fn client_refuses_bad_setup() {
for url in ["http://192.0.2.10:48010", "rtsp://192.0.2.10", "rtsp://:48010", "", "rtsp://h:99999", "rtsp://h:1\r\nX: y"] {
assert_err!(RtspClient::new(url, config()), Error::Malformed { .. }, "{url:?}");
}
for broken in [
StreamConfig { width: 0, ..config() },
StreamConfig { height: 0, ..config() },
StreamConfig { fps: 0, ..config() },
StreamConfig { bitrate_kbps: 0, ..config() },
StreamConfig { packet_size: 0, ..config() },
] {
assert_err!(RtspClient::new(URL, broken), Error::Malformed { .. });
}
}
+32
View File
@@ -0,0 +1,32 @@
// AES-128-GCM test vectors for DomiStream (control frames and video packets), computed with .NET's AesGcm, a
// crypto implementation independent of the RustCrypto crates DomiStream uses.
//
// Run by gen_vectors.py (`dotnet run gcm_vectors.cs -- <input> <output>`), never by hand. Input lines:
// <name> <key hex> <nonce hex> <plaintext hex>
// Output lines:
// <name> <ciphertext hex> <tag hex>
// No associated data, 16-byte tags (docs/PROTOCOL.md 3.2 and 7). Keys are fixed test-only values.
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
var input = File.ReadAllLines(args[0]);
var output = new StringBuilder();
foreach (var line in input)
{
if (line.Trim().Length == 0) continue;
var parts = line.Split(' ');
var key = Convert.FromHexString(parts[1]);
var nonce = Convert.FromHexString(parts[2]);
var plaintext = parts[3] == "-" ? Array.Empty<byte>() : Convert.FromHexString(parts[3]);
var ciphertext = new byte[plaintext.Length];
var tag = new byte[16];
using var gcm = new AesGcm(key, 16);
gcm.Encrypt(nonce, plaintext, ciphertext, tag);
output.Append(parts[0]).Append(' ')
.Append(ciphertext.Length == 0 ? "-" : Convert.ToHexString(ciphertext)).Append(' ')
.Append(Convert.ToHexString(tag)).Append('\n');
}
File.WriteAllText(args[1], output.ToString());
+437
View File
@@ -0,0 +1,437 @@
#!/usr/bin/env python3
"""Generates DomiStream's crypto test vectors with tools that are independent of the RustCrypto crates DomiStream
uses: Python's hashlib (SHA-256), the OpenSSL 3.x command line (RSA keys, X.509 certificates, PKCS#1 v1.5 SHA-256
signatures, AES-128-ECB without padding, AES-128-CBC with PKCS#7) and .NET's AesGcm (AES-128-GCM, gcm_vectors.cs).
Everything written here is TEST-ONLY: the keys are made fresh on this machine for the tests, never a real host's
or client's, and must never be used for anything else. Values follow docs/PROTOCOL.md (sections in the comments).
python tools/vectors/gen_vectors.py # recompute vectors, keep the existing test keys
python tools/vectors/gen_vectors.py --fresh-keys # also make new test keys and certificates
Environment: DOMISTREAM_OPENSSL (path to openssl, default: Git for Windows' OpenSSL 3.5, then PATH) and
DOMISTREAM_DOTNET (default: dotnet on PATH). Standard library only; nothing is installed or downloaded.
Output: crates/domistream/tests/fixtures/ (text only: hex and PEM).
"""
import argparse
import hashlib
import os
import shutil
import subprocess
import sys
import tempfile
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
HERE = os.path.dirname(os.path.abspath(__file__))
FIXTURES = os.path.join(ROOT, "crates", "domistream", "tests", "fixtures")
HEADER = (
"# Generated by tools/vectors/gen_vectors.py. TEST-ONLY values and keys, made for DomiStream's tests.\n"
"# Never a real host's or client's key. Do not edit by hand: change the script and run it again.\n"
)
def find_openssl():
env = os.environ.get("DOMISTREAM_OPENSSL")
if env:
return env
git = r"C:\Program Files\Git\mingw64\bin\openssl.exe"
if os.path.exists(git):
return git
found = shutil.which("openssl")
if not found:
sys.exit("openssl not found; set DOMISTREAM_OPENSSL")
return found
OPENSSL = find_openssl()
DOTNET = os.environ.get("DOMISTREAM_DOTNET") or shutil.which("dotnet") or "dotnet"
WORK = tempfile.mkdtemp(prefix="domistream-vectors-")
OPENSSL_CNF = os.path.join(WORK, "openssl.cnf")
with open(OPENSSL_CNF, "w", encoding="ascii") as f:
f.write("[req]\ndistinguished_name = dn\nprompt = no\n[dn]\n")
def run(args, stdin=None):
env = dict(os.environ, OPENSSL_CONF=OPENSSL_CNF)
proc = subprocess.run(args, input=stdin, capture_output=True, env=env, check=False)
if proc.returncode != 0:
sys.exit(f"command failed: {args}\n{proc.stderr.decode(errors='replace')}")
return proc.stdout
def openssl(*args, stdin=None):
return run([OPENSSL, *args], stdin=stdin)
def fixed(label, n):
"""A fixed, reproducible test value: the first n bytes of SHA-256 of a label (chained when n > 32)."""
out = b""
counter = 0
while len(out) < n:
out += hashlib.sha256(f"domistream-test:{label}:{counter}".encode()).digest()
counter += 1
return out[:n]
def sha256(*parts):
h = hashlib.sha256()
for p in parts:
h.update(p)
return h.digest()
def tmp(name, data=None):
path = os.path.join(WORK, name)
if data is not None:
with open(path, "wb") as f:
f.write(data)
return path
# ---------------------------------------------------------------- AES via the OpenSSL CLI
def ecb_encrypt(key, data):
assert len(data) % 16 == 0
return openssl("enc", "-aes-128-ecb", "-nopad", "-K", key.hex(), stdin=data)
def ecb_decrypt(key, data):
return openssl("enc", "-d", "-aes-128-ecb", "-nopad", "-K", key.hex(), stdin=data)
def cbc_encrypt(key, iv, data):
return openssl("enc", "-aes-128-cbc", "-K", key.hex(), "-iv", iv.hex(), stdin=data)
# ---------------------------------------------------------------- RSA and X.509 via the OpenSSL CLI
def make_rsa_identity(stem, common_name):
key = os.path.join(FIXTURES, f"{stem}-key.pem")
cert = os.path.join(FIXTURES, f"{stem}-cert.pem")
openssl("genpkey", "-algorithm", "RSA", "-pkeyopt", "rsa_keygen_bits:2048", "-out", key)
openssl("req", "-x509", "-new", "-key", key, "-sha256", "-days", "7300", "-subj", f"/CN={common_name}",
"-config", OPENSSL_CNF, "-out", cert)
def make_ec_cert(stem):
key = tmp(f"{stem}-key.pem")
cert = os.path.join(FIXTURES, f"{stem}-cert.pem")
openssl("genpkey", "-algorithm", "EC", "-pkeyopt", "ec_paramgen_curve:P-256", "-out", key)
openssl("req", "-x509", "-new", "-key", key, "-sha256", "-days", "7300", "-subj", "/CN=DomiStream test-only EC",
"-config", OPENSSL_CNF, "-out", cert)
def cert_der(stem):
return openssl("x509", "-in", os.path.join(FIXTURES, f"{stem}-cert.pem"), "-outform", "DER")
def key_pkcs8_der(stem):
return openssl("pkcs8", "-topk8", "-nocrypt", "-in", os.path.join(FIXTURES, f"{stem}-key.pem"), "-outform", "DER")
def sign(stem, data):
"""RSASSA-PKCS1-v1_5 with SHA-256 (OpenSSL's default padding for RSA keys)."""
sig = openssl("dgst", "-sha256", "-sign", os.path.join(FIXTURES, f"{stem}-key.pem"), tmp("data.bin", data))
# Check it with the certificate's public key, so a vector never carries a signature OpenSSL itself rejects.
pub = tmp("pub.pem", openssl("x509", "-in", os.path.join(FIXTURES, f"{stem}-cert.pem"), "-pubkey", "-noout"))
openssl("dgst", "-sha256", "-verify", pub, "-signature", tmp("sig.bin", sig), tmp("data.bin", data))
return sig
def der_read(buf, pos):
"""One DER TLV at pos: (tag, content_start, content_end)."""
tag = buf[pos]
length = buf[pos + 1]
pos += 2
if length & 0x80:
n = length & 0x7F
length = int.from_bytes(buf[pos:pos + n], "big")
pos += n
return tag, pos, pos + length
def cert_signature_value(der):
"""The raw signatureValue bytes of an X.509 certificate (RFC 5280 4.1): the BIT STRING's content after its
unused-bits octet."""
tag, start, end = der_read(der, 0)
assert tag == 0x30 and end == len(der)
_, _, tbs_end = der_read(der, start) # tbsCertificate
_, _, alg_end = der_read(der, tbs_end) # signatureAlgorithm
tag, sig_start, sig_end = der_read(der, alg_end)
assert tag == 0x03 and sig_end == end
assert der[sig_start] == 0, "unused bits in signatureValue"
return der[sig_start + 1:sig_end]
# ---------------------------------------------------------------- AES-GCM via .NET
def gcm_batch(rows):
"""rows: (name, key, nonce, plaintext) -> {name: (ciphertext, tag)}"""
lines = [f"{n} {k.hex()} {iv.hex()} {pt.hex() if pt else '-'}" for n, k, iv, pt in rows]
src = tmp("gcm_in.txt", ("\n".join(lines) + "\n").encode())
dst = tmp("gcm_out.txt")
run([DOTNET, "run", os.path.join(HERE, "gcm_vectors.cs"), "--", src, dst])
out = {}
with open(dst, encoding="ascii") as f:
for line in f:
name, ct, tag = line.split()
out[name] = (b"" if ct == "-" else bytes.fromhex(ct), bytes.fromhex(tag))
return out
# ---------------------------------------------------------------- writers
def write_vectors(filename, title, entries):
path = os.path.join(FIXTURES, filename)
with open(path, "w", encoding="ascii", newline="\n") as f:
f.write(HEADER)
f.write(f"# {title}\n")
for name, value in entries:
if name.startswith("#"):
f.write(f"\n{name}\n")
continue
if isinstance(value, bytes):
value = value.hex()
f.write(f"{name} = {value}\n")
print("wrote", os.path.relpath(path, ROOT))
# ---------------------------------------------------------------- pairing (PROTOCOL.md 1.5)
def pairing_vectors():
host_der = cert_der("test-only-host")
client_der = cert_der("test-only-client")
rogue_der = cert_der("test-only-rogue")
host_sig = cert_signature_value(host_der)
client_sig = cert_signature_value(client_der)
pin = b"4071"
wrong_pin = b"4072"
# The client's randomness, in the order the state machine draws it: salt (step 1), C (step 2), secret_c (step 3).
salt = fixed("salt-a", 16)
c = fixed("client-challenge-a", 16)
secret_c = fixed("client-secret-a", 16)
# A second session (different randomness) for the replay test.
salt_b = fixed("salt-b", 16)
c_b = fixed("client-challenge-b", 16)
secret_c_b = fixed("client-secret-b", 16)
# The host's values.
s_c = fixed("server-challenge", 16)
secret_s = fixed("server-secret", 16)
key = sha256(salt, pin)[:16]
req2 = ecb_encrypt(key, c)
assert ecb_decrypt(key, req2) == c
h_s = sha256(c, host_sig, secret_s)
resp2 = ecb_encrypt(key, h_s + s_c)
h_c = sha256(s_c, client_sig, secret_c)
req3 = ecb_encrypt(key, h_c)
secret_s_sig = sign("test-only-host", secret_s)
resp3 = secret_s + secret_s_sig
secret_c_sig = sign("test-only-client", secret_c)
req4 = secret_c + secret_c_sig
# Wrong PIN on the host: the host decrypts the client challenge with its own key and answers with it.
key_wrong = sha256(salt, wrong_pin)[:16]
c_seen_by_host = ecb_decrypt(key_wrong, req2)
resp2_wrong_pin = ecb_encrypt(key_wrong, sha256(c_seen_by_host, host_sig, secret_s) + s_c)
# Right key, but H_s over a different host secret than the one the host reveals in step 3.
resp2_wrong_hash = ecb_encrypt(key, sha256(c, host_sig, fixed("other-server-secret", 16)) + s_c)
# Right key, but H_s over the rogue certificate's signature instead of the host's.
resp2_wrong_cert = ecb_encrypt(key, sha256(c, cert_signature_value(rogue_der), secret_s) + s_c)
# Step 3 signed by a key other than the host certificate's.
resp3_rogue = secret_s + sign("test-only-rogue", secret_s)
sign_data = b"DomiStream test-only signing input"
entries = [
("# Identities (DER, hex). PEM forms: test-only-*.pem next to this file.", None),
("host_cert_der", host_der),
("host_cert_signature", host_sig),
("client_cert_der", client_der),
("client_key_pkcs8_der", key_pkcs8_der("test-only-client")),
("client_cert_signature", client_sig),
("rogue_cert_der", rogue_der),
("rogue_key_pkcs8_der", key_pkcs8_der("test-only-rogue")),
("# Session A: the client's randomness (rng stream = salt || client_challenge || client_secret)", None),
("pin", pin.decode()),
("wrong_pin", wrong_pin.decode()),
("salt", salt),
("client_challenge", c),
("client_secret", secret_c),
("# Host values", None),
("server_challenge", s_c),
("server_secret", secret_s),
("# Derived, step by step", None),
("key", key),
("step2_clientchallenge", req2),
("host_proof", h_s),
("step2_challengeresponse", resp2),
("client_proof", h_c),
("step3_serverchallengeresp", req3),
("server_secret_signature", secret_s_sig),
("step3_pairingsecret", resp3),
("client_secret_signature", secret_c_sig),
("step4_clientpairingsecret", req4),
("# Hostile host answers", None),
("step2_challengeresponse_wrong_pin", resp2_wrong_pin),
("step2_challengeresponse_wrong_hash", resp2_wrong_hash),
("step2_challengeresponse_wrong_cert", resp2_wrong_cert),
("step3_pairingsecret_rogue_signature", resp3_rogue),
("# Session B: different randomness, for replaying session A's answers", None),
("salt_b", salt_b),
("client_challenge_b", c_b),
("client_secret_b", secret_c_b),
("# ClientIdentity::sign over a fixed input (PKCS#1 v1.5 is deterministic)", None),
("sign_data", sign_data),
("sign_data_client_signature", sign("test-only-client", sign_data)),
]
# derive_key over several salts and PINs.
entries.append(("# derive_key: SHA-256(salt || pin)[0..16]", None))
for i, p in enumerate([b"0000", b"9999", b"1234", b"4071"]):
s = fixed(f"derive-salt-{i}", 16)
entries += [(f"derive_{i}_salt", s), (f"derive_{i}_pin", p.decode()), (f"derive_{i}_key", sha256(s, p)[:16])]
# AES-128-ECB, no padding, 1 to 4 blocks.
entries.append(("# ecb: AES-128-ECB without padding", None))
for blocks in [1, 2, 3, 4]:
k = fixed(f"ecb-key-{blocks}", 16)
pt = fixed(f"ecb-plain-{blocks}", 16 * blocks)
entries += [(f"ecb_{blocks}_key", k), (f"ecb_{blocks}_plain", pt), (f"ecb_{blocks}_cipher", ecb_encrypt(k, pt))]
# proof_hash with signatures of several lengths (RSA-1024 .. RSA-8192, plus 0 and 1 byte).
entries.append(("# proof_hash: SHA-256(challenge || signature || secret)", None))
for i, n in enumerate([0, 1, 128, 256, 512, 1024]):
ch = fixed(f"proof-challenge-{i}", 16)
sg = fixed(f"proof-signature-{i}", n)
se = fixed(f"proof-secret-{i}", 16)
entries += [(f"proof_{i}_challenge", ch), (f"proof_{i}_signature", sg if n else "-"),
(f"proof_{i}_secret", se), (f"proof_{i}_hash", sha256(ch, sg, se))]
write_vectors("pairing.txt", "Pairing (PROTOCOL.md 1.5): SHA-256 hashlib, AES-ECB + RSA openssl", entries)
# ---------------------------------------------------------------- control frames (PROTOCOL.md 3.2)
def control_nonce(seq, direction):
return seq.to_bytes(4, "little") + bytes(6) + direction + b"C"
def control_vectors():
key = fixed("control-rikey", 16)
cases = [
# (name, seq, direction byte, plaintext)
("c_ping_0", 0, b"C", bytes.fromhex("00020000")),
("c_input_1", 1, b"C", bytes.fromhex("06020c000000000807000000ffff0000")),
("c_ping_ffff", 0xFFFF, b"C", bytes.fromhex("00020000")),
("c_ping_10000", 0x10000, b"C", bytes.fromhex("00020000")),
("c_ping_fffffffe", 0xFFFFFFFE, b"C", bytes.fromhex("00020000")),
("c_ping_ffffffff", 0xFFFFFFFF, b"C", bytes.fromhex("00020000")),
("h_rumble_0", 0, b"H", bytes.fromhex("0b010a00000000000100ff7f0080")),
("h_rumble_7", 7, b"H", bytes.fromhex("0b010a00000000000100ff7f0080")),
("h_termination_ffffffff", 0xFFFFFFFF, b"H", bytes.fromhex("0901040080030023")),
("h_rgb_2a", 0x2A, b"H", bytes.fromhex("0255050003001020ff")),
]
out = gcm_batch([(n, key, control_nonce(s, d), pt) for n, s, d, pt in cases])
entries = [("key", key)]
for name, seq, direction, pt in cases:
ct, tag = out[name]
frame = (1).to_bytes(2, "little") + (4 + 16 + len(ct)).to_bytes(2, "little") + seq.to_bytes(4, "little")
frame += tag + ct
entries += [
(f"# {name}", None),
(f"{name}_sequence", f"{seq:08x}"),
(f"{name}_direction", direction.decode()),
(f"{name}_nonce", control_nonce(seq, direction)),
(f"{name}_plain", pt),
(f"{name}_frame", frame),
]
write_vectors("control_gcm.txt", "Control frames (PROTOCOL.md 3.2): AES-128-GCM by .NET AesGcm", entries)
# ---------------------------------------------------------------- video encryption (PROTOCOL.md 7)
def video_vectors():
key = fixed("video-rikey", 16)
cases = []
for name, counter, frame_number, n in [
("v_0", 0, 0, 48),
("v_1", 1, 0, 48),
("v_big_counter", 0x0102030405060708, 0x11223344, 64),
("v_1040", 7, 3, 1040),
]:
pt = fixed(f"video-plain-{name}", n)
iv = counter.to_bytes(8, "little") + bytes(3) + b"V"
cases.append((name, counter, frame_number, iv, pt))
out = gcm_batch([(n, key, iv, pt) for n, _, _, iv, pt in cases])
entries = [("key", key)]
for name, counter, frame_number, iv, pt in cases:
ct, tag = out[name]
packet = iv + frame_number.to_bytes(4, "little") + tag + ct
entries += [(f"# {name}", None), (f"{name}_plain", pt), (f"{name}_packet", packet)]
write_vectors("video_gcm.txt", "Video packets (PROTOCOL.md 7): AES-128-GCM by .NET AesGcm", entries)
# ---------------------------------------------------------------- audio encryption (PROTOCOL.md 6.3)
def audio_vectors():
key = fixed("audio-rikey", 16)
entries = [("key", key)]
for name, rikeyid, seq, n in [
("a_0", 0, 0, 20),
("a_1", 0x01020304, 1, 20),
("a_ffff", 0x00000010, 0xFFFF, 33),
("a_wrap", 0xFFFFFFFE, 5, 16),
("a_exact_block", 7, 100, 32),
("a_one_byte", 7, 101, 1),
]:
iv = ((rikeyid + seq) & 0xFFFFFFFF).to_bytes(4, "big") + bytes(12)
pt = fixed(f"audio-plain-{name}", n)
entries += [
(f"# {name}", None),
(f"{name}_rikeyid", f"{rikeyid:08x}"),
(f"{name}_sequence", f"{seq:04x}"),
(f"{name}_iv", iv),
(f"{name}_plain", pt),
(f"{name}_cipher", cbc_encrypt(key, iv, pt)),
]
write_vectors("audio_cbc.txt", "Audio payloads (PROTOCOL.md 6.3): AES-128-CBC + PKCS#7 by openssl", entries)
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--fresh-keys", action="store_true", help="make new test-only keys and certificates")
args = parser.parse_args()
print("openssl:", openssl("version").decode().strip())
os.makedirs(FIXTURES, exist_ok=True)
stems = ["test-only-host", "test-only-client", "test-only-rogue"]
missing = any(not os.path.exists(os.path.join(FIXTURES, f"{s}-cert.pem")) for s in stems)
if args.fresh_keys or missing:
make_rsa_identity("test-only-host", "DomiStream test-only host")
make_rsa_identity("test-only-client", "DomiStream test-only client")
make_rsa_identity("test-only-rogue", "DomiStream test-only rogue")
make_ec_cert("test-only-ec")
print("made fresh test-only keys")
pairing_vectors()
control_vectors()
video_vectors()
audio_vectors()
shutil.rmtree(WORK, ignore_errors=True)
if __name__ == "__main__":
main()