19 Commits

Author SHA1 Message Date
mnovak e67daea536 [domistream] Tests: properties cannot pass against Unimplemented
The never-panic properties (XML, RTSP, ENet, control, input, media) and the
allocation-cap checks only asserted inside `if let Ok`, so a stub returning
Unimplemented for everything passed them. Each now also requires the parser
to answer something other than Unimplemented (common::implemented); the XML
truncation property wants Malformed or Truncated, not any error.
2026-11-25 13:15:00 +01:00
mnovak 2740d3dd45 [domistream] Tests: first compile, clippy clean
Temporaries borrowed past their statement (control, media), clippy's
is_multiple_of, needless index loop and type complexity. input.rs: the
MOUSE_MOVE_ABS builder dropped the y field; the PROTOCOL.md cross-check would
have caught it at runtime.
2026-11-25 13:08:24 +01:00
mnovak 8d0bebfbc3 [domistream] Crypto: aes-gcm without default features
default-features = false, features = ["aes", "alloc"]: aes-gcm's default
pulls in getrandom, which would make the OS RNG reachable inside a crate whose
randomness must only come through RandomSource. Approved by the build lead.
Cargo.lock also gains the test-only dev-dependencies (proptest, peak_alloc).
2026-11-25 13:08:24 +01:00
mnovak b57e97a38b [domistream] Tests: fixtures from tools/vectors
Generated by tools/vectors/gen_vectors.py with Python hashlib, OpenSSL 3.5.7
(Git for Windows) and .NET 10 AesGcm. Keys and certificates are TEST-ONLY,
made fresh on this machine for these tests: RSA-2048 host, client and rogue
identities, and an EC certificate for the non-RSA refusal.
2026-11-25 13:08:24 +01:00
mnovak da1f3afd52 [domistream] Tests: rustfmt 2026-11-25 12:52:38 +01:00
mnovak 948f446a13 [domistream] Tests: fuzz targets assert invariants
Every target now checks properties instead of only calling the parser:
parse -> encode -> parse stability (RTSP request, ENet, input), caps and
TooLarge past them, chunking invariance of the framer, XML vs status parser
agreement, seal/open round trips, no forged GCM tags. New targets for the
parsers and state machines that had none: server_cert_der, enet_client,
media_decrypt, video_depacketizer, audio_depacketizer, fec_reconstruct,
pairing_session, rtsp_client (25 targets).
2026-11-25 12:51:08 +01:00
mnovak 71e34e8d9d [domistream] Tests: allocation caps
A counting global allocator (peak_alloc) checks that small inputs with lying
length fields and arbitrary inputs never make a parser allocate past a bound
tied to the input and its caps; depacketizers and the ENet peer stay within
their in-flight caps.
2026-11-25 12:51:07 +01:00
mnovak 9c59b69bf0 [domistream] Tests: audio depacketizer with the parity-matrix hook
All 64 loss patterns of a 4+2 block with two different MDS matrices through
AudioFec::ParityMatrix (U16 unmeasured), encrypted and plain; FEC disabled;
sequence wrap; duplicates; reordering; far-past and far-future; hostile
parity; the loss timeout.
2026-11-25 12:51:06 +01:00
mnovak 240190041d [domistream] Tests: video depacketizer loss patterns
Generated multi-block frames with random, bursty, all-parity, all-data,
last-packet loss, reordering and duplicates; RTP sequence and frame index
wraps; far-past and far-future strays; recovered shard headers deliberately
garbage (bytes 0-31 untrusted); encryption with tampering. Frames are
byte-exact or reported in FrameLost, never corrupt.
2026-11-25 12:51:06 +01:00
mnovak f3ad3afe00 [domistream] Tests: Reed-Solomon erasure patterns
Every erasure pattern of size <= m for k 1..=8, m 1..=4 and the Wolf 4+2
example; k = 1..=255-m sweeps for m in 1,2,3,4,8,16,64,127,254; > m refused
with Truncated. with_parity_matrix checked byte-exact against an independent
GF(2^8) Cauchy construction and refused for non-MDS matrices.
2026-11-25 12:51:05 +01:00
mnovak ecc9908082 [domistream] Tests: media packet parsers and ciphers
RTP header, video packet and frame header, audio packet at every size
boundary; inconsistent FEC fields; video AES-GCM against .NET vectors and
audio AES-CBC against openssl vectors, including rikeyid + seq wrap and bad
padding. The RustCrypto test oracles are checked against the same vectors.
2026-11-25 12:51:04 +01:00
mnovak fbfcd588a5 [domistream] Tests: input vectors from the field tables
INPUT_DATA built from PROTOCOL.md 4 field tables, cross-checked against its
example bytes; encode, parse, equal for every known type; unknown types,
UNKNOWN-layout types, wrong lengths, lying length and size fields, changed
constants and out-of-range values refused.
2026-11-25 12:51:04 +01:00
mnovak fea864d16e [domistream] Tests: control frames, replay and messages
Nonce layout (seq LE, 6 zero, direction, 'C'), seal against .NET AesGcm
vectors, every tampered byte, wrong direction and key, lying length fields.
ControlStream drops replayed, older, reflected and forged frames and refuses
seq 0 after u32::MAX. Host message layouts and client message encoding.
2026-11-25 12:51:03 +01:00
mnovak 38a455a717 [domistream] Tests: ENet codec and client peer
Byte vectors built from the PROTOCOL.md 3.1 field definitions, every command
size, truncation, compressed and unknown commands, 32/33 commands and
4096/4097 bytes. Client: handshake, reliable sequence past 0xFFFF -> 0,
duplicates, far-future and far-past, lying fragments, retransmission,
timeout and disconnect.
2026-11-25 12:51:03 +01:00
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
70 changed files with 8959 additions and 2865 deletions
Generated
+78
View File
@@ -55,6 +55,12 @@ version = "1.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
[[package]]
name = "bitflags"
version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]] [[package]]
name = "block-buffer" name = "block-buffer"
version = "0.12.1" version = "0.12.1"
@@ -89,6 +95,17 @@ version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "chacha20"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
dependencies = [
"cfg-if",
"cpufeatures",
"rand_core",
]
[[package]] [[package]]
name = "cipher" name = "cipher"
version = "0.5.2" version = "0.5.2"
@@ -112,6 +129,12 @@ version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a"
[[package]]
name = "core_detect"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48"
[[package]] [[package]]
name = "cpubits" name = "cpubits"
version = "0.1.1" version = "0.1.1"
@@ -225,6 +248,8 @@ dependencies = [
"aes", "aes",
"aes-gcm", "aes-gcm",
"cbc", "cbc",
"peak_alloc",
"proptest",
"rand_core", "rand_core",
"rsa", "rsa",
"sha2", "sha2",
@@ -302,6 +327,12 @@ dependencies = [
"autocfg", "autocfg",
] ]
[[package]]
name = "peak_alloc"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccc90935a8dd139fdf341762773687a1e361d3f54b396a55d9dd1f7001e484bb"
[[package]] [[package]]
name = "pem-rfc7468" name = "pem-rfc7468"
version = "1.0.0" version = "1.0.0"
@@ -351,6 +382,22 @@ dependencies = [
"unicode-ident", "unicode-ident",
] ]
[[package]]
name = "proptest"
version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0"
dependencies = [
"bitflags",
"chacha20",
"core_detect",
"num-traits",
"rand",
"rand_xorshift",
"regex-syntax",
"unarray",
]
[[package]] [[package]]
name = "quote" name = "quote"
version = "1.0.47" version = "1.0.47"
@@ -366,12 +413,37 @@ version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "rand"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11"
dependencies = [
"getrandom",
"rand_core",
]
[[package]] [[package]]
name = "rand_core" name = "rand_core"
version = "0.10.1" version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
[[package]]
name = "rand_xorshift"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf"
dependencies = [
"rand_core",
]
[[package]]
name = "regex-syntax"
version = "0.8.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"
[[package]] [[package]]
name = "rsa" name = "rsa"
version = "0.10.0" version = "0.10.0"
@@ -523,6 +595,12 @@ version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "unarray"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94"
[[package]] [[package]]
name = "unicode-ident" name = "unicode-ident"
version = "1.0.27" version = "1.0.27"
+7 -1
View File
@@ -14,10 +14,16 @@ workspace = true
# Crypto: RustCrypto only, pure Rust, all MIT OR Apache-2.0 (fits CPAL-1.0). Chosen in Phase A, used in Phase B. # Crypto: RustCrypto only, pure Rust, all MIT OR Apache-2.0 (fits CPAL-1.0). Chosen in Phase A, used in Phase B.
[dependencies] [dependencies]
aes = "0.9" # AES-128 block cipher (pairing ECB) aes = "0.9" # AES-128 block cipher (pairing ECB)
aes-gcm = "0.11" # control and video AES-128-GCM aes-gcm = { version = "0.11", default-features = false, features = ["aes", "alloc"] } # control and video AES-128-GCM; no getrandom, randomness only through RandomSource
cbc = "0.2" # audio AES-128-CBC cbc = "0.2" # audio AES-128-CBC
sha2 = "0.11" # pairing SHA-256 sha2 = "0.11" # pairing SHA-256
rsa = "0.10" # client key, PKCS#1 v1.5 SHA-256 sign/verify (crypto-bigint, constant time) rsa = "0.10" # client key, PKCS#1 v1.5 SHA-256 sign/verify (crypto-bigint, constant time)
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"
+259
View File
@@ -0,0 +1,259 @@
//! "Caps every length before it allocates": with a counting global allocator (`peak_alloc`, no unsafe code of
//! ours), feeds every parser small inputs whose length fields lie (claim gigabytes) and arbitrary inputs, and checks
//! the peak heap growth stays within a bound tied to the input and the parser's caps, never to a claimed length.
//!
//! The counters are process-wide, so this file holds exactly one #[test] that runs everything in sequence.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
mod common;
use domistream::{Instant, SessionKeys};
use peak_alloc::PeakAlloc;
use proptest::prelude::*;
use proptest::test_runner::{Config, TestRunner};
#[global_allocator]
static ALLOC: PeakAlloc = PeakAlloc;
/// Heap bytes `f` needs at its peak, beyond what was in use when it started.
fn peak_of<R>(f: impl FnOnce() -> R) -> usize {
ALLOC.reset_peak_usage();
let before = ALLOC.current_usage();
let r = f();
let peak = ALLOC.peak_usage();
drop(r);
peak.saturating_sub(before)
}
/// The budget for a parser given `input` bytes: its output may be a few times the input, plus fixed slack. A parser
/// that trusts a lying length field blows far past this.
fn budget(input: usize) -> usize {
64 * input + 256 * 1024
}
fn check(what: &str, input: &[u8], f: impl FnOnce(&[u8]) -> bool) {
let mut ran = false;
let used = peak_of(|| ran = f(input));
assert!(ran, "{what}: Unimplemented, so its allocation is not measured yet");
assert!(
used <= budget(input.len()),
"{what}: {used} bytes at peak for a {}-byte input (budget {})",
input.len(),
budget(input.len())
);
}
/// A parser under test: a name and a call that consumes the input.
type Parser = (&'static str, fn(&[u8]) -> bool);
/// A parser and the hostile input for it.
type Case = (&'static str, Vec<u8>, fn(&[u8]) -> bool);
fn lying_inputs() -> Vec<Case> {
let mut v: Vec<Case> = Vec::new();
// RTSP: Content-Length claims 4 GiB.
let rtsp = b"RTSP/1.0 200 OK\r\nCSeq: 1\r\nContent-Length: 4294967295\r\n\r\nabc".to_vec();
v.push(("rtsp response", rtsp.clone(), |b| common::implemented(&domistream::rtsp::parse_response(b))));
v.push((
"rtsp request",
b"ANNOUNCE x RTSP/1.0\r\nCSeq: 1\r\nContent-Length: 4294967295\r\n\r\nabc".to_vec(),
|b| common::implemented(&domistream::rtsp::parse_request(b)),
));
v.push(("rtsp framer", rtsp, |b| {
let mut f = domistream::rtsp::RtspFramer::new();
let pushed = f.push(b);
let next = f.next_message();
let finished = f.finish();
common::implemented(&pushed) && common::implemented(&next) && common::implemented(&finished)
}));
// ENet: data length 65535 with 3 bytes, fragment claiming 4 GiB and 4 billion fragments.
v.push(("enet reliable", vec![0x00, 0x01, 0x86, 0x00, 0x00, 0x01, 0xFF, 0xFF, 1, 2, 3], |b| {
common::implemented(&domistream::enet::protocol::parse_datagram(b))
}));
let mut frag = vec![0x00, 0x01, 0x88, 0x00, 0x00, 0x01];
frag.extend_from_slice(&1u16.to_be_bytes()); // start sequence
frag.extend_from_slice(&10u16.to_be_bytes()); // data length
frag.extend_from_slice(&u32::MAX.to_be_bytes()); // fragment count
frag.extend_from_slice(&0u32.to_be_bytes()); // fragment number
frag.extend_from_slice(&u32::MAX.to_be_bytes()); // total length
frag.extend_from_slice(&0u32.to_be_bytes()); // offset
frag.extend_from_slice(&[0; 10]);
v.push(("enet fragment", frag, |b| common::implemented(&domistream::enet::protocol::parse_datagram(b))));
// Control: frame and message length fields at 65535.
let mut frame = vec![0x01, 0x00, 0xFF, 0xFF, 0, 0, 0, 0];
frame.extend_from_slice(&[0; 16 + 8]);
v.push(("control frame", frame.clone(), |b| common::implemented(&domistream::control::parse_encrypted_frame(b))));
v.push(("control open", frame, |b| {
common::implemented(
&domistream::control::ControlCipher::new([1; 16]).open(domistream::control::Direction::HostToClient, b),
)
}));
v.push(("control message", vec![0x0b, 0x01, 0xFF, 0xFF, 1, 2], |b| {
common::implemented(&domistream::control::parse_host_message(b))
}));
// Input: size field u32::MAX, length 65535.
v.push(("input", vec![0x06, 0x02, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0, 0, 0, 1, 2], |b| {
common::implemented(&domistream::input::parse_input(b))
}));
// Video: 1023 data shards, frame header claiming a 4 GiB last payload.
let p = common::video_packet_bytes(1, 0, 0, 0x05, 0, common::fec_info(200, 0, 1023), &[0xFF; 48]);
v.push(("video packet", p.clone(), |b| common::implemented(&domistream::video::parse_video_packet(b))));
v.push(("frame header", vec![1, 0, 0, 2, 0xFF, 0xFF, 0xFF, 0xFF], |b| {
common::implemented(&domistream::video::packet::parse_frame_header(b))
}));
// Audio, XML, PEM, DER with lying lengths.
v.push((
"audio packet",
vec![0x80, 127, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 97, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
|b| common::implemented(&domistream::audio::parse_audio_packet(b)),
));
v.push(("xml", b"<root status_code=\"200\"><a>&#99999999999;</a></root>".to_vec(), |b| {
common::implemented(&domistream::http::xml::parse(b))
}));
let mut der = vec![0x30, 0x84, 0xFF, 0xFF, 0xFF, 0xFF];
der.extend_from_slice(&[0x30; 20]);
v.push(("server cert der", der.clone(), |b| common::implemented(&domistream::pairing::ServerCert::from_der(b))));
v.push(("client identity der", der, |b| common::implemented(&domistream::pairing::ClientIdentity::from_der(b, b))));
v.push(("pem", b"-----BEGIN CERTIFICATE-----\nMIT/////\n-----END CERTIFICATE-----\n".to_vec(), |b| {
common::implemented(&domistream::pairing::ServerCert::from_pem(b))
}));
v.push(("pairing secret", vec![0; 17], |b| {
common::implemented(&domistream::pairing::crypto::split_pairing_secret(b))
}));
v
}
/// Stateful receivers: the bound is their caps (frames or blocks in flight), never a claimed size.
fn depacketizer_checks() {
use domistream::video::{MAX_FRAME_BYTES, MAX_FRAMES_IN_FLIGHT, VideoConfig, VideoDepacketizer};
let cap = MAX_FRAMES_IN_FLIGHT * MAX_FRAME_BYTES + 1024 * 1024;
let used = peak_of(|| {
let mut d = VideoDepacketizer::new(VideoConfig {
packet_size: 1024,
cipher: None,
frame_timeout: core::time::Duration::from_millis(50),
})
.unwrap();
// One packet each of many frames that each announce 4 blocks of 255 shards.
for frame in 0..64u32 {
let mut p = common::video_packet_bytes(
frame as u16,
0,
frame,
0x05,
3 << 6,
common::fec_info(0, 0, 255),
&[0xAB; 1024 - 16],
);
p.resize(1024 + 16, 0);
let _ = d.push(Instant::ZERO, &p);
}
d
});
assert!(used <= cap, "video depacketizer: {used} bytes at peak (cap {cap})");
use domistream::audio::{AudioConfig, AudioDepacketizer, AudioFec, MAX_BLOCKS_IN_FLIGHT};
let cap = MAX_BLOCKS_IN_FLIGHT * 6 * domistream::audio::packet::MAX_AUDIO_PACKET_BYTES + 256 * 1024;
let used = peak_of(|| {
let mut d = AudioDepacketizer::new(AudioConfig {
cipher: Some(domistream::audio::AudioCipher::new(&SessionKeys { rikey: [1; 16], rikeyid: 0 })),
packet_duration_ms: 5,
fec: AudioFec::ParityMatrix(common::audio_test_matrix()),
loss_timeout: core::time::Duration::from_millis(40),
})
.unwrap();
for seq in (0..2000u16).step_by(13) {
let mut p = vec![0x80, 97];
p.extend_from_slice(&seq.wrapping_mul(97).to_be_bytes());
p.extend_from_slice(&[0; 8]);
p.extend_from_slice(&[0x11; 2000]);
let _ = d.push(Instant::ZERO, &p);
}
d
});
assert!(used <= cap, "audio depacketizer: {used} bytes at peak (cap {cap})");
use domistream::enet::{EnetClient, EnetConfig, MAX_PACKET_BYTES};
let used = peak_of(|| {
let cfg = EnetConfig {
channel_count: 2,
mtu: 1400,
connect_data: 0,
ping_interval: core::time::Duration::from_millis(500),
timeout: core::time::Duration::from_secs(10),
};
let mut c = EnetClient::connect(cfg, Instant::ZERO, &mut common::SeqRng::new(1)).unwrap();
// Fragments of 4 billion pieces and gigabyte totals, addressed to every peer id.
for peer in 0..64u16 {
let mut d = peer.to_be_bytes().to_vec();
d.extend_from_slice(&[0x88, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x04]);
d.extend_from_slice(&u32::MAX.to_be_bytes());
d.extend_from_slice(&7u32.to_be_bytes());
d.extend_from_slice(&u32::MAX.to_be_bytes());
d.extend_from_slice(&0u32.to_be_bytes());
d.extend_from_slice(&[1, 2, 3, 4]);
let _ = c.handle_datagram(Instant::ZERO, &d);
}
c
});
assert!(used <= 4 * MAX_PACKET_BYTES + 256 * 1024, "enet client: {used} bytes at peak");
}
#[test]
fn parsers_never_allocate_past_their_caps() {
for (what, input, f) in lying_inputs() {
check(what, &input, f);
}
depacketizer_checks();
// Arbitrary inputs to every stateless parser.
let mut runner = TestRunner::new(Config { cases: 400, ..Config::default() });
let parsers: Vec<Parser> = vec![
("xml", |b| common::implemented(&domistream::http::xml::parse(b))),
("serverinfo", |b| common::implemented(&domistream::http::parse_server_info(b))),
("applist", |b| common::implemented(&domistream::http::parse_app_list(b))),
("launch", |b| common::implemented(&domistream::http::parse_launch_response(b))),
("pair response", |b| common::implemented(&domistream::pairing::parse_pair_response(b))),
("pem", |b| common::implemented(&domistream::pairing::ServerCert::from_pem(b))),
("der", |b| common::implemented(&domistream::pairing::ServerCert::from_der(b))),
("rtsp response", |b| common::implemented(&domistream::rtsp::parse_response(b))),
("rtsp request", |b| common::implemented(&domistream::rtsp::parse_request(b))),
("sdp", |b| common::implemented(&domistream::rtsp::sdp::parse_sdp(b))),
("enet", |b| common::implemented(&domistream::enet::protocol::parse_datagram(b))),
("control frame", |b| common::implemented(&domistream::control::parse_encrypted_frame(b))),
("control message", |b| common::implemented(&domistream::control::parse_host_message(b))),
("input", |b| common::implemented(&domistream::input::parse_input(b))),
("rtp", |b| common::implemented(&domistream::rtp::parse_rtp_header(b))),
("video", |b| common::implemented(&domistream::video::parse_video_packet(b))),
("audio", |b| common::implemented(&domistream::audio::parse_audio_packet(b))),
("video decrypt", |b| common::implemented(&domistream::video::VideoCipher::new([2; 16]).decrypt(b))),
("audio decrypt", |b| {
common::implemented(
&domistream::audio::AudioCipher::new(&SessionKeys { rikey: [2; 16], rikeyid: 0 }).decrypt(0, b),
)
}),
];
for (what, f) in parsers {
runner
.run(&proptest::collection::vec(any::<u8>(), 0..1500), |data| {
let mut ran = false;
let used = peak_of(|| ran = f(&data));
prop_assert!(ran, "{}: Unimplemented", what);
prop_assert!(
used <= budget(data.len()),
"{}: {} bytes at peak for {} input bytes",
what,
used,
data.len()
);
Ok(())
})
.unwrap_or_else(|e| panic!("{what}: {e}"));
}
}
+423
View File
@@ -0,0 +1,423 @@
//! The audio depacketizer (`docs/PROTOCOL.md` 6): blocks of 4 data + 2 parity packets with a parity matrix passed
//! through the `AudioFec::ParityMatrix` hook (U16 is unmeasured, so any MDS matrix must work; the tests use a
//! Cauchy matrix and a second one), AES-128-CBC payloads, every loss pattern of a block, sequence wrap, duplicates,
//! reordering, far-past and far-future packets.
//!
//! Reading of PROTOCOL.md 6.2: a parity packet's RTP sequence "continues after the 4 data packets" (base + 4 +
//! shard), which overlaps the next block's data sequence numbers; the receiver must key parity by the FEC header's
//! base sequence and the payload type, never by the parity packet's RTP sequence.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
mod common;
use core::time::Duration;
use std::collections::HashMap;
use common::{AExpect, APkt, AudioHost, SeqRng, audio_test_matrix, subsets_of};
use domistream::audio::packet::MAX_AUDIO_PACKET_BYTES;
use domistream::audio::{AudioCipher, AudioConfig, AudioDepacketizer, AudioEvent, AudioFec, AudioStats};
use domistream::{Error, Instant, SessionKeys};
use proptest::prelude::*;
const KEY: [u8; 16] = *b"audio-test-key!!";
const RIKEYID: u32 = 0xFFFF_FFF0; // rikeyid + sequence wraps inside the tests
const DURATION: u32 = 5;
fn host(encrypt: bool, matrix: [u8; 8]) -> AudioHost {
AudioHost { key: KEY, rikeyid: RIKEYID, encrypt, matrix, duration_ms: DURATION, opus_len: 37 }
}
fn config(encrypt: bool, fec: AudioFec) -> AudioConfig {
AudioConfig {
cipher: encrypt.then(|| AudioCipher::new(&SessionKeys { rikey: KEY, rikeyid: RIKEYID })),
packet_duration_ms: DURATION as u8,
fec,
loss_timeout: Duration::from_millis(40),
}
}
struct Run {
events: Vec<AudioEvent>,
stats: AudioStats,
}
fn run(cfg: AudioConfig, datagrams: &[Vec<u8>]) -> Run {
let mut d = AudioDepacketizer::new(cfg).expect("AudioDepacketizer::new");
let mut now = 1_000_000u64;
let mut events = Vec::new();
for g in datagrams {
d.push(Instant::from_micros(now), g).expect("push never fails within the size cap");
now += 10;
while let Some(e) = d.poll_event() {
events.push(e);
}
}
for _ in 0..64 {
now += 10_000_000;
d.handle_timeout(Instant::from_micros(now)).unwrap();
while let Some(e) = d.poll_event() {
events.push(e);
}
if d.poll_timeout().is_none() {
break;
}
}
Run { events, stats: d.stats() }
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Want {
/// Arrived as sent.
Packet,
/// Lost and rebuilt by FEC.
Recovered,
/// Gone: reported lost.
Lost,
}
/// Every data sequence number gets exactly one event, in stream order; packets are byte-exact with the right
/// timestamp; `recovered` is set exactly for rebuilt ones.
fn check(expect: &[AExpect], want: &[Want], r: &Run) {
let pos: HashMap<u16, usize> = expect.iter().enumerate().map(|(i, e)| (e.sequence, i)).collect();
let mut seen = vec![false; expect.len()];
let mut prev: Option<usize> = None;
for e in &r.events {
let (seq, i) = match e {
AudioEvent::Packet { sequence, .. } | AudioEvent::Lost { sequence } => (
*sequence,
*pos.get(sequence)
.unwrap_or_else(|| panic!("event for sequence {sequence} that was never a data packet")),
),
};
assert!(!seen[i], "two events for sequence {seq}");
assert!(prev.is_none_or(|p| i > p), "sequence {seq} out of order");
prev = Some(i);
seen[i] = true;
match (e, want[i]) {
(AudioEvent::Packet { timestamp_ms, opus, recovered, .. }, Want::Packet | Want::Recovered) => {
assert_eq!(opus, &expect[i].opus, "sequence {seq} corrupt");
assert_eq!(*timestamp_ms, expect[i].timestamp_ms, "sequence {seq} timestamp");
assert_eq!(*recovered, want[i] == Want::Recovered, "sequence {seq} recovered flag");
}
(AudioEvent::Lost { .. }, Want::Lost) => {}
(got, w) => panic!("sequence {seq}: want {w:?}, got {got:?}"),
}
}
for (i, s) in seen.iter().enumerate() {
assert!(s, "no event for sequence {} (want {:?})", expect[i].sequence, want[i]);
}
}
/// What must come out of a block, given which of its 6 packets arrived.
fn block_want(arrived: &[bool; 6], fec: bool) -> [Want; 4] {
let count = arrived.iter().filter(|a| **a).count();
let mut w = [Want::Packet; 4];
for (i, slot) in w.iter_mut().enumerate() {
if !arrived[i] {
*slot = if fec && count >= 4 { Want::Recovered } else { Want::Lost };
}
}
w
}
/// Blocks `1..blocks-1` lose what `lose(block, index)` says; the first and last blocks arrive whole.
fn scenario(
h: &AudioHost,
seed: u64,
first_seq: u16,
blocks: usize,
fec: bool,
lose: impl Fn(usize, usize) -> bool,
) -> (Vec<AExpect>, Vec<Want>, Vec<Vec<u8>>) {
let mut rng = SeqRng::new(seed);
let (packets, expect) = h.blocks(&mut rng, first_seq, 0x7000_0000, blocks);
let mut want = Vec::new();
let mut datagrams = Vec::new();
for b in 0..blocks {
let mut arrived = [true; 6];
for p in packets.iter().filter(|p| p.block == b) {
if b != 0 && b + 1 != blocks && lose(b, p.index) {
arrived[p.index] = false;
} else {
datagrams.push(p.bytes.clone());
}
}
want.extend(block_want(&arrived, fec));
}
(expect, want, datagrams)
}
// ================================================================================================ every pattern
#[test]
fn every_loss_pattern_of_a_block() {
// All 64 subsets of the 6 packets lost in the middle block, encrypted, with the Cauchy matrix.
let h = host(true, audio_test_matrix());
for size in 0..=6 {
for lost in subsets_of(6, size) {
let (expect, want, dg) = scenario(&h, 1, 0, 3, true, |b, i| b == 1 && lost.contains(&i));
check(&expect, &want, &run(config(true, AudioFec::ParityMatrix(h.matrix)), &dg));
}
}
}
#[test]
fn every_loss_pattern_plaintext_and_another_matrix() {
// A second MDS matrix (rows 1,1,1,1 and 1,2,4,8) and no encryption.
let m = [1, 1, 1, 1, 1, 2, 4, 8];
let h = host(false, m);
for size in 0..=6 {
for lost in subsets_of(6, size) {
let (expect, want, dg) = scenario(&h, 2, 400, 3, true, |b, i| b == 1 && lost.contains(&i));
check(&expect, &want, &run(config(false, AudioFec::ParityMatrix(m)), &dg));
}
}
}
#[test]
fn fec_disabled_reports_losses() {
let h = host(true, audio_test_matrix());
for lost in [vec![0usize], vec![3], vec![1, 2], vec![0, 4, 5]] {
let (expect, want, dg) = scenario(&h, 3, 8, 3, false, |b, i| b == 1 && lost.contains(&i));
check(&expect, &want, &run(config(true, AudioFec::Disabled), &dg));
}
}
#[test]
fn random_losses_over_many_blocks() {
let h = host(true, audio_test_matrix());
for (seed, pct) in [(10u64, 5usize), (11, 15), (12, 30), (13, 50)] {
let mut rng = SeqRng::new(seed * 31);
let mask: Vec<bool> = (0..60 * 6).map(|_| rng.below(100) < pct).collect();
let (expect, want, dg) = scenario(&h, seed, 0, 60, true, |b, i| mask[b * 6 + i]);
let r = run(config(true, AudioFec::ParityMatrix(h.matrix)), &dg);
check(&expect, &want, &r);
assert_eq!(r.stats.recovered, want.iter().filter(|w| **w == Want::Recovered).count() as u64);
assert_eq!(r.stats.lost, want.iter().filter(|w| **w == Want::Lost).count() as u64);
}
}
// ================================================================================================ order and strays
#[test]
fn sequence_wraps() {
// Blocks from 0xFFF0 through 0x000F: data sequence 0xFFFF -> 0, base sequence wrap, rikeyid + seq wrap.
let h = host(true, audio_test_matrix());
let (expect, want, dg) = scenario(&h, 20, 0xFFF0, 8, true, |b, i| (b + i).is_multiple_of(5));
assert!(expect.iter().any(|e| e.sequence == 0xFFFF) && expect.iter().any(|e| e.sequence == 0));
check(&expect, &want, &run(config(true, AudioFec::ParityMatrix(h.matrix)), &dg));
}
#[test]
fn duplicates_are_dropped() {
let h = host(true, audio_test_matrix());
let (expect, want, dg) = scenario(&h, 21, 0, 10, true, |b, i| (b * 7 + i).is_multiple_of(6));
let doubled: Vec<Vec<u8>> = dg.iter().flat_map(|g| [g.clone(), g.clone()]).collect();
let r = run(config(true, AudioFec::ParityMatrix(h.matrix)), &doubled);
check(&expect, &want, &r);
assert!(r.stats.packets_dropped >= dg.len() as u64 / 2, "{:?}", r.stats);
}
#[test]
fn reordered_within_and_across_blocks() {
let h = host(true, audio_test_matrix());
for seed in 30..36u64 {
let (expect, want, mut dg) = scenario(&h, seed, 0, 12, true, |b, i| (b + i + seed as usize).is_multiple_of(7));
let mut rng = SeqRng::new(seed);
let mut i = 6; // the first block stays first, so the stream has a known start
while i < dg.len() {
let end = (i + 9).min(dg.len());
rng.shuffle(&mut dg[i..end]);
i = end;
}
check(&expect, &want, &run(config(true, AudioFec::ParityMatrix(h.matrix)), &dg));
}
}
#[test]
fn far_past_and_far_future() {
let h = host(true, audio_test_matrix());
let mut rng = SeqRng::new(40);
let (packets, expect) = h.blocks(&mut rng, 1000, 0, 6);
let (old, _) = h.blocks(&mut SeqRng::new(41), 1000u16.wrapping_sub(400), 0, 1);
let (future, _) = h.blocks(&mut SeqRng::new(42), 1000u16.wrapping_add(20_000), 0, 1);
let mut dg: Vec<Vec<u8>> = packets.iter().filter(|p| p.block < 3).map(|p| p.bytes.clone()).collect();
dg.extend(old.iter().map(|p| p.bytes.clone()));
dg.extend(packets.iter().filter(|p| p.block < 2).map(|p| p.bytes.clone())); // replays
dg.extend(future.iter().take(1).map(|p| p.bytes.clone()));
dg.extend(packets.iter().filter(|p| p.block >= 3).map(|p| p.bytes.clone()));
let r = run(config(true, AudioFec::ParityMatrix(h.matrix)), &dg);
assert!(r.stats.packets_dropped >= 6 + 12, "far-past block and replays dropped: {:?}", r.stats);
// No event is ever a corrupt packet, the far-past block never comes out, and the first blocks do, in order.
// (Whether the lone far-future packet is played or dropped is the receiver's choice.)
let (_, future_expect) = h.blocks(&mut SeqRng::new(42), 1000u16.wrapping_add(20_000), 0, 1);
let by_seq: HashMap<u16, &AExpect> = expect.iter().chain(&future_expect[..1]).map(|e| (e.sequence, e)).collect();
let mut first_blocks = 0;
for e in &r.events {
if let AudioEvent::Packet { sequence, opus, .. } = e {
assert!(!(600..604).contains(sequence), "far-past sequence {sequence} played");
let want = by_seq
.get(sequence)
.unwrap_or_else(|| panic!("a packet for sequence {sequence} that only strays carried"));
assert_eq!(opus, &want.opus);
if (1000..1012).contains(sequence) {
first_blocks += 1;
}
}
}
assert_eq!(first_blocks, 12);
}
fn parity_of(packets: &[APkt], block: usize, index: usize) -> Vec<u8> {
packets.iter().find(|p| p.block == block && p.index == index).unwrap().bytes.clone()
}
#[test]
fn hostile_parity_never_corrupts() {
let h = host(true, audio_test_matrix());
let mut rng = SeqRng::new(50);
let (packets, expect) = h.blocks(&mut rng, 0, 0, 3);
let mut hostile = Vec::new();
// Parity for block 1 with a base sequence that is not a multiple of 4.
let mut p = parity_of(&packets, 1, 4);
p[14..16].copy_from_slice(&5u16.to_be_bytes());
hostile.push(p);
// Parity shorter than the data shards.
let mut p = parity_of(&packets, 1, 5);
p.truncate(p.len() - 16);
hostile.push(p);
// Parity claiming to protect another payload type.
let mut p = parity_of(&packets, 1, 4);
p[13] = 96;
hostile.push(p);
// Block 1 loses data 0 and 1; only the hostile parity (and nothing else) is offered for it.
let mut dg: Vec<Vec<u8>> = packets.iter().filter(|p| p.block == 0).map(|p| p.bytes.clone()).collect();
dg.extend(packets.iter().filter(|p| p.block == 1 && (2..4).contains(&p.index)).map(|p| p.bytes.clone()));
dg.extend(hostile);
dg.extend(packets.iter().filter(|p| p.block == 2).map(|p| p.bytes.clone()));
let mut want = vec![Want::Packet; 12];
want[4] = Want::Lost;
want[5] = Want::Lost;
check(&expect, &want, &run(config(true, AudioFec::ParityMatrix(h.matrix)), &dg));
}
#[test]
fn undecryptable_data_is_dropped_and_rebuilt() {
// Copies of a data packet with a ciphertext of a wrong length or no payload: dropped, never output, and the
// packet is rebuilt from the rest of its block.
let h = host(true, audio_test_matrix());
let mut rng = SeqRng::new(60);
let (packets, expect) = h.blocks(&mut rng, 0, 0, 3);
let mut dg: Vec<Vec<u8>> = Vec::new();
for p in &packets {
if p.block == 1 && p.index == 2 {
let mut empty = p.bytes.clone();
empty.truncate(12);
dg.push(empty);
let mut odd = p.bytes.clone();
odd.pop();
dg.push(odd);
} else {
dg.push(p.bytes.clone());
}
}
let mut want = vec![Want::Packet; 12];
want[6] = Want::Recovered;
let r = run(config(true, AudioFec::ParityMatrix(h.matrix)), &dg);
check(&expect, &want, &r);
assert!(r.stats.packets_dropped >= 2);
}
// ================================================================================================ API edges
#[test]
fn config_refusals() {
assert_err!(
AudioDepacketizer::new(AudioConfig { packet_duration_ms: 0, ..config(true, AudioFec::Disabled) }),
Error::Malformed { .. }
);
let mut zero = audio_test_matrix();
zero[5] = 0;
for bad in [zero, [1; 8], [1, 2, 3, 4, 2, 4, 6, 8], [0; 8]] {
assert_err!(
AudioDepacketizer::new(config(true, AudioFec::ParityMatrix(bad))),
Error::Malformed { .. },
"{bad:?} is not MDS"
);
}
assert!(AudioDepacketizer::new(config(false, AudioFec::ParityMatrix(audio_test_matrix()))).is_ok());
}
#[test]
fn push_sizes() {
let mut d = AudioDepacketizer::new(config(true, AudioFec::Disabled)).unwrap();
assert_too_large!(
d.push(Instant::ZERO, &vec![0x80; MAX_AUDIO_PACKET_BYTES + 1]),
MAX_AUDIO_PACKET_BYTES,
MAX_AUDIO_PACKET_BYTES + 1
);
assert_too_large!(d.push(Instant::ZERO, &vec![0x80; 1 << 20]), MAX_AUDIO_PACKET_BYTES, 1 << 20);
for g in [
vec![],
vec![0x80],
vec![0x80, 97, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
vec![0xFF; 40],
vec![0x80; MAX_AUDIO_PACKET_BYTES],
] {
assert_eq!(d.push(Instant::ZERO, &g), Ok(()));
}
assert_eq!(d.stats().packets_dropped, 5);
assert_eq!(d.poll_event(), None);
}
#[test]
fn a_missing_packet_waits_for_the_loss_timeout() {
let h = host(false, audio_test_matrix());
let mut rng = SeqRng::new(70);
let (packets, expect) = h.blocks(&mut rng, 0, 0, 2);
let mut d = AudioDepacketizer::new(config(false, AudioFec::Disabled)).unwrap();
let t = Instant::from_micros(3_000_000);
// Data 0 and 2 of block 0: 0 comes out, 1 is missing, 2 waits behind it.
d.push(t, &packets[0].bytes).unwrap();
d.push(t, &packets[2].bytes).unwrap();
assert!(matches!(d.poll_event(), Some(AudioEvent::Packet { sequence: 0, .. })));
assert_eq!(d.poll_event(), None, "sequence 2 waits for 1");
let deadline = d.poll_timeout().expect("a deadline for sequence 1");
assert!(deadline > t && deadline <= t.saturating_add(Duration::from_millis(40)));
d.handle_timeout(t.saturating_add(Duration::from_millis(39))).unwrap();
assert_eq!(d.poll_event(), None, "not before the loss timeout");
d.handle_timeout(t.saturating_add(Duration::from_millis(40))).unwrap();
assert_eq!(d.poll_event(), Some(AudioEvent::Lost { sequence: 1 }));
match d.poll_event() {
Some(AudioEvent::Packet { sequence: 2, opus, recovered: false, .. }) => assert_eq!(opus, expect[2].opus),
other => panic!("{other:?}"),
}
}
proptest! {
#![proptest_config(ProptestConfig { cases: 64, ..ProptestConfig::default() })]
/// Random loss masks and reordering over random lengths: exact, rebuilt or lost, never corrupt.
#[test]
fn generated_patterns(seed in any::<u64>(), first in 0u16..16_384, loss in 0usize..50, opus_len in 1usize..120) {
let mut h = host(true, audio_test_matrix());
h.opus_len = opus_len;
let mut rng = SeqRng::new(seed);
let mask: Vec<bool> = (0..20 * 6).map(|_| rng.below(100) < loss).collect();
let (expect, want, mut dg) = scenario(&h, seed, first * 4, 20, true, |b, i| mask[b * 6 + i]);
let mut i = 6;
while i < dg.len() {
let end = (i + 1 + rng.below(8)).min(dg.len());
rng.shuffle(&mut dg[i..end]);
i = end;
}
check(&expect, &want, &run(config(true, AudioFec::ParityMatrix(h.matrix)), &dg));
}
#[test]
fn arbitrary_datagrams(datagrams in proptest::collection::vec(proptest::collection::vec(any::<u8>(), 0..80), 0..60)) {
let r = run(config(true, AudioFec::ParityMatrix(audio_test_matrix())), &datagrams);
prop_assert!(r.events.len() <= datagrams.len() * 4 + 4);
}
}
+716
View File
@@ -0,0 +1,716 @@
//! 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),
}
};
}
/// False for `Err(Unimplemented)`. "Never panics" properties assert this on every result, so they cannot pass
/// against a stub that returns `Unimplemented` for everything.
pub fn implemented<T>(r: &domistream::Result<T>) -> bool {
!matches!(r, Err(domistream::Error::Unimplemented))
}
// ------------------------------------------------------------------------------------------------ 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().is_multiple_of(2), "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")
}
+638
View File
@@ -0,0 +1,638 @@
//! Control channel (`docs/PROTOCOL.md` 3.2, 3.3): nonce layout, AES-GCM frames against .NET vectors
//! (`tools/vectors/gcm_vectors.cs`), tampering, direction, replay and sequence wrap through [`ControlStream`], and the
//! message layouts.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
mod common;
use core::time::Duration;
use common::SeqRng;
use domistream::control::frame::{FRAME_HEADER_LEN, MAX_FRAME_BYTES, MIN_FRAME_BYTES, nonce};
use domistream::control::message::{MAX_MESSAGE_BYTES, MotionKind, encode_client_message};
use domistream::control::{
ClientMessage, ControlCipher, ControlConfig, ControlEvent, ControlStream, Direction, HostMessage, MessageType,
parse_encrypted_frame, parse_host_message, parse_message,
};
use domistream::enet::EnetConfig;
use domistream::enet::protocol::{Command, CommandBody, ConnectParams, Datagram, encode_datagram, parse_datagram};
use domistream::input::InputEvent;
use domistream::{Error, Instant};
use proptest::prelude::*;
const NAMES: [&str; 10] = [
"c_ping_0",
"c_input_1",
"c_ping_ffff",
"c_ping_10000",
"c_ping_fffffffe",
"c_ping_ffffffff",
"h_rumble_0",
"h_rumble_7",
"h_termination_ffffffff",
"h_rgb_2a",
];
fn dir(v: &common::Vectors, name: &str) -> Direction {
match v.str(&format!("{name}_direction")) {
"C" => Direction::ClientToHost,
"H" => Direction::HostToClient,
other => panic!("direction {other}"),
}
}
// ================================================================================================ nonce
fn expected_nonce(seq: u32, direction: Direction) -> [u8; 12] {
let mut n = [0u8; 12];
n[..4].copy_from_slice(&seq.to_le_bytes());
n[10] = match direction {
Direction::ClientToHost => b'C',
Direction::HostToClient => b'H',
};
n[11] = b'C';
n
}
#[test]
fn nonce_layout() {
// seq LE, then 6 zero bytes, then the direction byte, then 'C'.
assert_eq!(nonce(0, Direction::ClientToHost).unwrap(), [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, b'C', b'C']);
assert_eq!(nonce(1, Direction::HostToClient).unwrap(), [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, b'H', b'C']);
assert_eq!(
nonce(0x1234_5678, Direction::ClientToHost).unwrap(),
[0x78, 0x56, 0x34, 0x12, 0, 0, 0, 0, 0, 0, b'C', b'C']
);
for seq in [0xFFFF, 0x1_0000, 0xFFFF_FFFE, u32::MAX] {
for d in [Direction::ClientToHost, Direction::HostToClient] {
assert_eq!(nonce(seq, d).unwrap(), expected_nonce(seq, d), "{seq:#x} {d:?}");
}
}
assert_ne!(nonce(5, Direction::ClientToHost).unwrap(), nonce(5, Direction::HostToClient).unwrap());
let v = common::control_vectors();
for name in NAMES {
let seq = v.u32_hex(&format!("{name}_sequence"));
assert_eq!(nonce(seq, dir(&v, name)).unwrap().to_vec(), v.bytes(&format!("{name}_nonce")), "{name}");
}
}
proptest! {
#[test]
fn nonce_matches_the_definition(seq in any::<u32>(), host in any::<bool>()) {
let d = if host { Direction::HostToClient } else { Direction::ClientToHost };
prop_assert_eq!(nonce(seq, d), Ok(expected_nonce(seq, d)));
}
}
// ================================================================================================ seal / open
#[test]
fn seal_matches_dotnet_vectors() {
let v = common::control_vectors();
let c = ControlCipher::new(v.arr16("key"));
for name in NAMES {
let seq = v.u32_hex(&format!("{name}_sequence"));
let d = dir(&v, name);
let plain = v.bytes(&format!("{name}_plain"));
let frame = v.bytes(&format!("{name}_frame"));
assert_eq!(c.seal(seq, d, &plain).unwrap(), frame, "{name}");
assert_eq!(c.open(d, &frame).unwrap(), (seq, plain.clone()), "{name}");
let f = parse_encrypted_frame(&frame).unwrap();
assert_eq!(f.sequence, seq);
assert_eq!(f.ciphertext.len(), plain.len());
assert_eq!(f.tag.to_vec(), frame[8..24].to_vec());
}
}
#[test]
fn seal_open_round_trip() {
let c = ControlCipher::new([7; 16]);
for len in [4usize, 5, 16, 100, MAX_FRAME_BYTES - FRAME_HEADER_LEN] {
let plain: Vec<u8> = (0..len).map(|i| i as u8).collect();
for d in [Direction::ClientToHost, Direction::HostToClient] {
let f = c.seal(42, d, &plain).unwrap();
assert_eq!(f.len(), FRAME_HEADER_LEN + len);
assert_eq!(&f[..2], &[0x01, 0x00]);
assert_eq!(u16::from_le_bytes([f[2], f[3]]) as usize, f.len() - 4);
assert_eq!(c.open(d, &f).unwrap(), (42, plain.clone()));
}
}
match c.seal(0, Direction::ClientToHost, &vec![0; MAX_FRAME_BYTES - FRAME_HEADER_LEN + 1]) {
Err(Error::TooLarge { max, .. }) => assert_eq!(max, MAX_FRAME_BYTES),
other => panic!("{other:?}"),
}
}
#[test]
fn tampering_is_refused() {
let v = common::control_vectors();
let c = ControlCipher::new(v.arr16("key"));
let frame = v.bytes("h_rumble_7_frame");
let d = Direction::HostToClient;
for i in 4..frame.len() {
let mut t = frame.clone();
t[i] ^= 0x01;
// seq (4..8) changes the nonce, tag (8..24) and ciphertext (24..) break the tag.
assert_err!(c.open(d, &t), Error::Crypto, "byte {i} flipped");
}
let mut t = frame.clone();
t[2] ^= 1;
assert_err!(c.open(d, &t), Error::Malformed { .. }, "length field");
let mut t = frame.clone();
t[0] = 0x02;
assert_err!(c.open(d, &t), Error::UnexpectedValue { .. }, "type field");
}
#[test]
fn wrong_direction_and_wrong_key_are_refused() {
let v = common::control_vectors();
let c = ControlCipher::new(v.arr16("key"));
for name in NAMES {
let other = match dir(&v, name) {
Direction::ClientToHost => Direction::HostToClient,
Direction::HostToClient => Direction::ClientToHost,
};
assert_err!(c.open(other, &v.bytes(&format!("{name}_frame"))), Error::Crypto, "{name} opened the other way");
}
let mut key = v.arr16("key");
key[0] ^= 1;
assert_err!(ControlCipher::new(key).open(Direction::HostToClient, &v.bytes("h_rumble_0_frame")), Error::Crypto);
}
#[test]
fn frame_parser_hostile_sizes() {
let frame_of = |total: usize| {
let mut f = vec![0x01, 0x00];
f.extend_from_slice(&((total - 4) as u16).to_le_bytes());
f.resize(total, 0xAB);
f
};
assert_err!(parse_encrypted_frame(&[]), Error::Truncated { .. });
assert_err!(parse_encrypted_frame(&[0x01]), Error::Truncated { .. });
assert_err!(parse_encrypted_frame(&frame_of(MIN_FRAME_BYTES)[..MIN_FRAME_BYTES - 1]), Error::Truncated { .. });
assert_err!(
parse_encrypted_frame(&frame_of(FRAME_HEADER_LEN)),
Error::Truncated { .. },
"no room for a message header"
);
assert_eq!(parse_encrypted_frame(&frame_of(MIN_FRAME_BYTES)).unwrap().ciphertext.len(), 4);
assert_eq!(
parse_encrypted_frame(&frame_of(MAX_FRAME_BYTES - 1)).unwrap().ciphertext.len(),
MAX_FRAME_BYTES - 1 - FRAME_HEADER_LEN
);
assert_eq!(
parse_encrypted_frame(&frame_of(MAX_FRAME_BYTES)).unwrap().ciphertext.len(),
MAX_FRAME_BYTES - FRAME_HEADER_LEN
);
let mut over = frame_of(MAX_FRAME_BYTES);
over.push(0);
assert_too_large!(parse_encrypted_frame(&over), MAX_FRAME_BYTES, MAX_FRAME_BYTES + 1);
assert_too_large!(parse_encrypted_frame(&vec![1; 1 << 20]), MAX_FRAME_BYTES, 1 << 20);
}
#[test]
fn frame_parser_lying_lengths() {
let mut f = vec![0x01, 0x00, 0, 0, 1, 0, 0, 0];
f.extend_from_slice(&[0; 16]);
f.extend_from_slice(&[9; 10]);
for (len, why) in [
(f.len() - 4 + 1, "over by one"),
(f.len() - 4 - 1, "under by one"),
(0xFFFF, "max"),
(0, "zero"),
(20, "header only"),
] {
let mut t = f.clone();
t[2..4].copy_from_slice(&(len as u16).to_le_bytes());
assert_err!(parse_encrypted_frame(&t), Error::Malformed { .. }, "{why}");
}
let mut t = f.clone();
t[0..2].copy_from_slice(&0x0002u16.to_le_bytes());
assert_err!(parse_encrypted_frame(&t), Error::UnexpectedValue { .. });
t[0..2].copy_from_slice(&0x0100u16.to_le_bytes());
assert_err!(parse_encrypted_frame(&t), Error::UnexpectedValue { .. }, "big-endian 0x0001");
}
// ================================================================================================ messages
fn msg(ty: u16, body: &[u8]) -> Vec<u8> {
let mut m = ty.to_le_bytes().to_vec();
m.extend_from_slice(&(body.len() as u16).to_le_bytes());
m.extend_from_slice(body);
m
}
#[test]
fn message_split() {
let m = msg(0x010b, &[1, 2, 3]);
let r = parse_message(&m).unwrap();
assert_eq!(r.message_type, 0x010b);
assert_eq!(r.body, &[1, 2, 3]);
assert_eq!(parse_message(&msg(0x7777, &[])).unwrap().body, &[] as &[u8]);
assert_err!(parse_message(&[]), Error::Truncated { .. });
assert_err!(parse_message(&[0x0b, 0x01, 0x00]), Error::Truncated { .. });
let mut over = msg(0x010b, &[1, 2, 3]);
over[2] = 4;
assert_err!(parse_message(&over), Error::Malformed { .. }, "length over");
let mut under = msg(0x010b, &[1, 2, 3]);
under[2] = 2;
assert_err!(parse_message(&under), Error::Malformed { .. }, "length under");
let mut lie = msg(0x010b, &[1, 2, 3]);
lie[2..4].copy_from_slice(&0xFFFFu16.to_le_bytes());
assert_err!(parse_message(&lie), Error::Malformed { .. }, "length 65535");
let max = msg(0x7777, &vec![0; MAX_MESSAGE_BYTES - 4]);
assert_eq!(parse_message(&max).unwrap().body.len(), MAX_MESSAGE_BYTES - 4);
assert_too_large!(
parse_message(&msg(0x7777, &vec![0; MAX_MESSAGE_BYTES - 3])),
MAX_MESSAGE_BYTES,
MAX_MESSAGE_BYTES + 1
);
}
#[test]
fn message_type_codes() {
for (code, t) in [
(0x0305, MessageType::StartA),
(0x0307, MessageType::StartB),
(0x0301, MessageType::InvalidateRefFrames),
(0x0302, MessageType::IdrFrame),
(0x0201, MessageType::LossStats),
(0x0204, MessageType::FrameStats),
(0x0206, MessageType::InputData),
(0x0200, MessageType::PeriodicPing),
(0x0100, MessageType::Termination),
(0x0109, MessageType::TerminationExtended),
(0x010e, MessageType::HdrMode),
(0x010b, MessageType::RumbleData),
(0x5500, MessageType::RumbleTriggers),
(0x5501, MessageType::MotionEvent),
(0x5502, MessageType::RgbLed),
(0x5503, MessageType::TriggerEffect),
] {
assert_eq!(MessageType::try_from(code), Ok(t), "{code:#06x}");
assert_eq!(t as u16, code);
}
for code in [0u16, 0x0001, 0x0101, 0x5504, 0xFFFF] {
assert_err!(MessageType::try_from(code), Error::UnexpectedValue { .. }, "{code:#06x}");
}
}
#[test]
fn host_messages_from_the_field_tables() {
// Host event bodies are taken as little-endian (UNKNOWN U23), except the extended termination code (BE).
let cases = [
(
msg(0x010b, &[0, 0, 0, 0, 0x01, 0x00, 0xFF, 0x7F, 0x00, 0x80]),
HostMessage::Rumble { controller: 1, low_frequency: 0x7FFF, high_frequency: 0x8000 },
),
(
msg(0x5500, &[0x02, 0x00, 0x34, 0x12, 0xCD, 0xAB]),
HostMessage::RumbleTriggers { controller: 2, left: 0x1234, right: 0xABCD },
),
(
msg(0x5501, &[0x03, 0x00, 0xC8, 0x00, 0x01]),
HostMessage::MotionEvent { controller: 3, rate_hz: 200, kind: MotionKind::Accelerometer },
),
(
msg(0x5501, &[0x03, 0x00, 0x00, 0x00, 0x02]),
HostMessage::MotionEvent { controller: 3, rate_hz: 0, kind: MotionKind::Gyroscope },
),
(
msg(0x5502, &[0x03, 0x00, 0x10, 0x20, 0xFF]),
HostMessage::RgbLed { controller: 3, r: 0x10, g: 0x20, b: 0xFF },
),
(msg(0x0109, &[0x80, 0x03, 0x00, 0x23]), HostMessage::Termination { error_code: Some(0x8003_0023) }),
(msg(0x0109, &[0x00, 0x00, 0x00, 0x01]), HostMessage::Termination { error_code: Some(1) }),
(msg(0x0100, &[]), HostMessage::Termination { error_code: None }),
(msg(0x010e, &[0x00]), HostMessage::HdrMode { enabled: false, metadata: None }),
(msg(0x7777, &[1, 2, 3]), HostMessage::Other { message_type: 0x7777, body_len: 3 }),
(msg(0x5503, &[9; 12]), HostMessage::Other { message_type: 0x5503, body_len: 12 }),
];
for (bytes, want) in cases {
assert_eq!(parse_host_message(&bytes), Ok(want.clone()), "{want:?}");
}
// HDR on with metadata.
let mut body = vec![0x01];
body.extend((1..=15u16).flat_map(|i| (i * 1000).to_le_bytes()));
match parse_host_message(&msg(0x010e, &body)).unwrap() {
HostMessage::HdrMode { enabled, metadata } => {
assert!(enabled);
let m = metadata.expect("31-byte body carries metadata");
assert_eq!(m.display_primaries[0], (1000, 2000), "first two u16 are the red primary");
}
other => panic!("{other:?}"),
}
// The plaintexts of the .NET vectors are messages too.
let v = common::control_vectors();
assert_eq!(
parse_host_message(&v.bytes("h_termination_ffffffff_plain")),
Ok(HostMessage::Termination { error_code: Some(0x8003_0023) })
);
}
#[test]
fn host_messages_with_wrong_bodies() {
for (ty, len) in [
(0x010b, 9),
(0x010b, 11),
(0x5500, 5),
(0x5500, 7),
(0x5501, 4),
(0x5501, 6),
(0x5502, 4),
(0x5502, 6),
(0x0109, 3),
(0x0109, 5),
(0x010e, 0),
(0x010e, 10),
(0x010e, 32),
] {
assert_err!(
parse_host_message(&msg(ty, &vec![0x01; len])),
Error::Malformed { .. },
"{ty:#06x} with {len} bytes"
);
}
for kind in [0u8, 3, 0xFF] {
assert_err!(
parse_host_message(&msg(0x5501, &[0, 0, 1, 0, kind])),
Error::UnexpectedValue { .. },
"motion kind {kind}"
);
}
assert_err!(parse_host_message(&[0x0b, 0x01]), Error::Truncated { .. });
let mut lie = msg(0x010b, &[0; 10]);
lie[2] = 200;
assert_err!(parse_host_message(&lie), Error::Malformed { .. });
}
#[test]
fn client_messages() {
let m = encode_client_message(&ClientMessage::InvalidateRefFrames { first: 5, last: 9 }).unwrap();
let mut want = vec![0x01, 0x03, 0x18, 0x00];
want.extend_from_slice(&5u32.to_le_bytes());
want.extend_from_slice(&[0; 4]);
want.extend_from_slice(&9u32.to_le_bytes());
want.extend_from_slice(&[0; 12]);
assert_eq!(m, want);
let ev = InputEvent::MouseMoveRel { dx: -1, dy: 0 };
assert_eq!(
encode_client_message(&ClientMessage::Input(ev.clone())).unwrap(),
domistream::input::encode_input(&ev).unwrap()
);
// Bodies still UNKNOWN (U10) are refused rather than guessed.
for m in [ClientMessage::StartA, ClientMessage::StartB, ClientMessage::PeriodicPing, ClientMessage::RequestIdrFrame]
{
assert_err!(encode_client_message(&m), Error::Unsupported { .. }, "{m:?}");
}
}
proptest! {
#![proptest_config(ProptestConfig { cases: 512, ..ProptestConfig::default() })]
#[test]
fn message_parsers_never_panic(data in proptest::collection::vec(any::<u8>(), 0..300)) {
let raw = parse_message(&data);
prop_assert!(common::implemented(&raw));
if let Ok(raw) = raw {
prop_assert_eq!(raw.body.len() + 4, data.len());
}
let host = parse_host_message(&data);
prop_assert!(common::implemented(&host));
if let Ok(HostMessage::Other { body_len, .. }) = host {
prop_assert_eq!(body_len + 4, data.len());
}
prop_assert!(common::implemented(&parse_encrypted_frame(&data)));
prop_assert!(common::implemented(&ControlCipher::new([3; 16]).open(Direction::HostToClient, &data)));
}
#[test]
fn open_never_accepts_random_frames(seq in any::<u32>(), tag in proptest::array::uniform16(any::<u8>()), ct in proptest::collection::vec(any::<u8>(), 4..64)) {
let mut f = vec![0x01, 0x00];
f.extend_from_slice(&((4 + 16 + ct.len()) as u16).to_le_bytes());
f.extend_from_slice(&seq.to_le_bytes());
f.extend_from_slice(&tag);
f.extend_from_slice(&ct);
prop_assert_eq!(ControlCipher::new([3; 16]).open(Direction::HostToClient, &f), Err(Error::Crypto));
}
}
// ================================================================================================ control stream
const KEY: [u8; 16] = *b"control-test-key";
fn stream_config() -> ControlConfig {
ControlConfig {
enet: EnetConfig {
channel_count: 1,
mtu: 1400,
connect_data: 0,
ping_interval: Duration::from_millis(500),
timeout: Duration::from_secs(10),
},
rikey: KEY,
ping_interval: Duration::from_millis(100),
}
}
struct Host {
stream: ControlStream,
to_client: u16,
reliable: u16,
now_ms: u64,
host: ControlCipher,
}
impl Host {
fn deliver(&mut self, frame: Vec<u8>) {
self.reliable = self.reliable.wrapping_add(1);
let c = Command {
acknowledge: true,
channel_id: 0,
reliable_sequence: self.reliable,
body: CommandBody::SendReliable(frame),
};
self.now_ms += 1;
let d = encode_datagram(&Datagram {
peer_id: self.to_client,
session_id: 0,
sent_time: Some(self.now_ms as u16),
commands: vec![c],
})
.unwrap();
self.stream.handle_datagram(Instant::from_micros(self.now_ms * 1000), &d).expect("a well-formed datagram");
}
fn deliver_sealed(&mut self, seq: u32, plain: &[u8]) {
let f = self.host.seal(seq, Direction::HostToClient, plain).unwrap();
self.deliver(f);
}
fn events(&mut self) -> Vec<ControlEvent> {
let mut out = Vec::new();
while let Some(e) = self.stream.poll_event() {
out.push(e);
}
out
}
/// Frames the client sent on channel 0, opened.
fn sent_frames(&mut self) -> Vec<(u32, Vec<u8>)> {
let mut out = Vec::new();
while let Some(d) = self.stream.poll_transmit(Instant::from_micros(self.now_ms * 1000)) {
for c in parse_datagram(&d).unwrap().commands {
let data = match c.body {
CommandBody::SendReliable(data) if c.channel_id == 0 => data,
_ => continue,
};
out.push(self.host.open(Direction::ClientToHost, &data).expect("the client seals with 'C'"));
}
}
out
}
}
fn connected_stream() -> Host {
let mut stream =
ControlStream::connect(stream_config(), Instant::ZERO, &mut SeqRng::new(11)).expect("ControlStream::connect");
let d = parse_datagram(&stream.poll_transmit(Instant::ZERO).expect("connect datagram")).unwrap();
let (params, seq) = d
.commands
.iter()
.find_map(|c| match &c.body {
CommandBody::Connect { params, .. } => Some((*params, c.reliable_sequence)),
_ => None,
})
.expect("connect");
let verify = ConnectParams { outgoing_peer_id: 0, incoming_session_id: 0, outgoing_session_id: 0, ..params };
let reply = encode_datagram(&Datagram {
peer_id: params.outgoing_peer_id,
session_id: 0,
sent_time: Some(1),
commands: vec![
Command {
acknowledge: false,
channel_id: 0xFF,
reliable_sequence: 0,
body: CommandBody::Acknowledge {
received_reliable_sequence: seq,
received_sent_time: d.sent_time.unwrap_or(0),
},
},
Command {
acknowledge: true,
channel_id: 0xFF,
reliable_sequence: 1,
body: CommandBody::VerifyConnect(verify),
},
],
})
.unwrap();
stream.handle_datagram(Instant::from_micros(1000), &reply).unwrap();
let mut h =
Host { stream, to_client: params.outgoing_peer_id, reliable: 0, now_ms: 1, host: ControlCipher::new(KEY) };
assert_eq!(h.events(), vec![ControlEvent::Connected]);
h
}
fn rumble(controller: u16) -> (Vec<u8>, HostMessage) {
(
msg(0x010b, &[0, 0, 0, 0, controller as u8, 0, 1, 0, 2, 0]),
HostMessage::Rumble { controller, low_frequency: 1, high_frequency: 2 },
)
}
#[test]
fn host_frames_in_order_and_with_gaps() {
let mut h = connected_stream();
for (seq, c) in [(0u32, 1u16), (1, 2), (2, 3), (10, 4), (1000, 5)] {
let (m, want) = rumble(c);
h.deliver_sealed(seq, &m);
assert_eq!(h.events(), vec![ControlEvent::Message(want)], "seq {seq}");
}
}
#[test]
fn replayed_and_old_host_frames_are_dropped() {
let mut h = connected_stream();
let (m, want) = rumble(1);
let f5 = h.host.seal(5, Direction::HostToClient, &m).unwrap();
h.deliver(f5.clone());
assert_eq!(h.events(), vec![ControlEvent::Message(want.clone())]);
// The very same frame again (new ENet command, so ENet itself delivers it): a replay.
h.deliver(f5);
assert_eq!(h.events(), vec![ControlEvent::Dropped], "replayed seq 5");
// A valid frame with an older or equal number.
h.deliver_sealed(3, &m);
assert_eq!(h.events(), vec![ControlEvent::Dropped], "older seq 3");
h.deliver_sealed(5, &rumble(9).0);
assert_eq!(h.events(), vec![ControlEvent::Dropped], "equal seq 5, other content");
// The stream continues.
h.deliver_sealed(6, &m);
assert_eq!(h.events(), vec![ControlEvent::Message(want)]);
}
#[test]
fn tampered_and_reflected_frames_are_dropped() {
let mut h = connected_stream();
let (m, want) = rumble(1);
let mut bad = h.host.seal(0, Direction::HostToClient, &m).unwrap();
bad[30] ^= 0x10;
h.deliver(bad);
assert_eq!(h.events(), vec![ControlEvent::Dropped], "bad tag");
// A frame sealed client-to-host (an attacker reflecting the client's own traffic).
let reflected = h.host.seal(1, Direction::ClientToHost, &m).unwrap();
h.deliver(reflected);
assert_eq!(h.events(), vec![ControlEvent::Dropped], "wrong direction");
// A frame under another key.
let other = ControlCipher::new([0; 16]).seal(2, Direction::HostToClient, &m).unwrap();
h.deliver(other);
assert_eq!(h.events(), vec![ControlEvent::Dropped], "wrong key");
// Not a frame at all.
h.deliver(vec![0xFF; 40]);
assert_eq!(h.events(), vec![ControlEvent::Dropped], "garbage");
// A failed frame does not burn its sequence number: seq 0 is still accepted.
h.deliver_sealed(0, &m);
assert_eq!(h.events(), vec![ControlEvent::Message(want)]);
}
#[test]
fn host_sequence_at_u32_wrap() {
let mut h = connected_stream();
let (m, want) = rumble(1);
h.deliver_sealed(0xFFFF_FFFE, &m);
h.deliver_sealed(0xFFFF_FFFF, &m);
assert_eq!(h.events(), vec![ControlEvent::Message(want.clone()), ControlEvent::Message(want)]);
// Nothing is greater than u32::MAX: a wrapped 0 is a replay, never accepted.
h.deliver_sealed(0, &m);
h.deliver_sealed(1, &m);
assert_eq!(h.events(), vec![ControlEvent::Dropped, ControlEvent::Dropped]);
}
#[test]
fn client_frames_count_up_from_zero() {
let mut h = connected_stream();
let msgs = [
ClientMessage::InvalidateRefFrames { first: 1, last: 2 },
ClientMessage::Input(InputEvent::MouseMoveRel { dx: 3, dy: -4 }),
ClientMessage::Input(InputEvent::Scroll { amount: 120 }),
];
for m in &msgs {
h.stream.send(Instant::from_micros(2000), m).unwrap();
}
let sent = h.sent_frames();
assert_eq!(sent.len(), msgs.len());
for (i, ((seq, plain), m)) in sent.iter().zip(&msgs).enumerate() {
assert_eq!(*seq, i as u32, "sequence numbers start at 0 and never repeat (U11)");
assert_eq!(plain, &encode_client_message(m).unwrap());
}
assert_err!(h.stream.send(Instant::from_micros(2000), &ClientMessage::StartA), Error::Unsupported { .. });
}
#[test]
fn closed_stream_refuses() {
let mut h = connected_stream();
h.stream.close(Instant::from_micros(3000)).unwrap();
assert_err!(h.stream.close(Instant::from_micros(3001)), Error::Closed);
}
+813
View File
@@ -0,0 +1,813 @@
//! ENet (`docs/PROTOCOL.md` 3.1): the datagram codec against byte vectors built from the field definitions, hostile
//! datagrams, and the client peer driven by a scripted host: handshake, reliable sequence numbers at the 0xFFFF
//! wrap, duplicates, far-future and far-past, fragments with lying lengths, retransmission and timeouts.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
mod common;
use core::time::Duration;
use common::SeqRng;
use domistream::enet::protocol::{
Command, CommandBody, ConnectParams, Datagram, Fragment, MAX_COMMANDS_PER_DATAGRAM, MAX_DATAGRAM_BYTES, NO_PEER_ID,
encode_datagram, parse_datagram,
};
use domistream::enet::{Delivery, EnetClient, EnetConfig, EnetEvent, EnetState, MAX_PACKET_BYTES, MAX_SEND_QUEUE};
use domistream::{Error, Instant};
use proptest::prelude::*;
// ================================================================================================ codec vectors
fn cmd(acknowledge: bool, channel_id: u8, reliable_sequence: u16, body: CommandBody) -> Command {
Command { acknowledge, channel_id, reliable_sequence, body }
}
#[test]
fn ping_vector() {
// peer 1, session 0, sent-time flag; ping with acknowledge flag on channel 0xFF, reliable sequence 1.
let bytes = [0x80, 0x01, 0x12, 0x34, 0x85, 0xFF, 0x00, 0x01];
let want = Datagram {
peer_id: 1,
session_id: 0,
sent_time: Some(0x1234),
commands: vec![cmd(true, 0xFF, 1, CommandBody::Ping)],
};
assert_eq!(parse_datagram(&bytes).unwrap(), want);
assert_eq!(encode_datagram(&want).unwrap(), bytes);
}
#[test]
fn acknowledge_reliable_disconnect_vectors() {
// peer 0xABC, session 2, no sent time: 0x2ABC.
let mut bytes = vec![0x2A, 0xBC];
bytes.extend_from_slice(&[0x01, 0x00, 0x00, 0x05, 0x00, 0x07, 0x12, 0x34]); // acknowledge (8)
bytes.extend_from_slice(&[0x86, 0x00, 0x00, 0x02, 0x00, 0x03, 0xAA, 0xBB, 0xCC]); // send reliable (6 + 3)
bytes.extend_from_slice(&[0x84, 0xFF, 0x00, 0x03, 0x00, 0x00, 0x00, 0x2A]); // disconnect (8)
let want = Datagram {
peer_id: 0x0ABC,
session_id: 2,
sent_time: None,
commands: vec![
cmd(false, 0, 5, CommandBody::Acknowledge { received_reliable_sequence: 7, received_sent_time: 0x1234 }),
cmd(true, 0, 2, CommandBody::SendReliable(vec![0xAA, 0xBB, 0xCC])),
cmd(true, 0xFF, 3, CommandBody::Disconnect { data: 42 }),
],
};
assert_eq!(parse_datagram(&bytes).unwrap(), want);
assert_eq!(encode_datagram(&want).unwrap(), bytes);
}
fn params(connect_id: u32) -> ConnectParams {
ConnectParams {
outgoing_peer_id: 3,
incoming_session_id: 0xFF,
outgoing_session_id: 0xFF,
mtu: 1400,
window_size: 32768,
channel_count: 2,
incoming_bandwidth: 0,
outgoing_bandwidth: 0,
packet_throttle_interval: 5000,
packet_throttle_acceleration: 2,
packet_throttle_deceleration: 2,
connect_id,
}
}
fn frag(start: u16, count: u32, number: u32, total: u32, offset: u32, data: Vec<u8>) -> Fragment {
Fragment {
start_sequence: start,
fragment_count: count,
fragment_number: number,
total_length: total,
fragment_offset: offset,
data,
}
}
/// Every command kind, with the total size PROTOCOL.md 3.1 gives for it.
fn every_command() -> Vec<(Command, usize)> {
vec![
(cmd(false, 0, 1, CommandBody::Acknowledge { received_reliable_sequence: 9, received_sent_time: 77 }), 8),
(cmd(true, 0xFF, 1, CommandBody::Connect { params: params(0xDEAD_BEEF), data: 0x1234_5678 }), 48),
(cmd(true, 0xFF, 1, CommandBody::VerifyConnect(params(0xDEAD_BEEF))), 44),
(cmd(true, 0xFF, 2, CommandBody::Disconnect { data: 0 }), 8),
(cmd(true, 0xFF, 3, CommandBody::Ping), 4),
(cmd(true, 0, 4, CommandBody::SendReliable(vec![1, 2, 3, 4, 5])), 6 + 5),
(cmd(false, 1, 4, CommandBody::SendUnreliable { unreliable_sequence: 0xFFFF, data: vec![9; 7] }), 8 + 7),
(cmd(true, 0, 5, CommandBody::SendFragment(frag(5, 2, 0, 20, 0, vec![1; 10]))), 24 + 10),
(cmd(false, 0, 0, CommandBody::SendUnsequenced { unsequenced_group: 513, data: vec![3; 2] }), 8 + 2),
(cmd(true, 0xFF, 6, CommandBody::BandwidthLimit { incoming: 1, outgoing: 2 }), 12),
(cmd(true, 0xFF, 7, CommandBody::ThrottleConfigure { interval: 5000, acceleration: 2, deceleration: 2 }), 16),
(cmd(false, 0, 8, CommandBody::SendUnreliableFragment(frag(8, 3, 2, 30, 20, vec![4; 10]))), 24 + 10),
]
}
#[test]
fn every_command_round_trips_with_its_wire_size() {
for (c, size) in every_command() {
for sent_time in [None, Some(0xBEEF)] {
let d = Datagram { peer_id: 7, session_id: 1, sent_time, commands: vec![c.clone()] };
let bytes = encode_datagram(&d).unwrap();
let header = if sent_time.is_some() { 4 } else { 2 };
assert_eq!(bytes.len(), header + size, "{:?}", c.body);
assert_eq!(bytes[header] & 0x0F, kind(&c.body), "command number of {:?}", c.body);
assert_eq!(bytes[header] & 0x80 != 0, c.acknowledge);
assert_eq!(parse_datagram(&bytes).unwrap(), d);
}
}
let all = Datagram {
peer_id: 0x0FFF,
session_id: 3,
sent_time: Some(1),
commands: every_command().into_iter().map(|(c, _)| c).collect(),
};
assert_eq!(parse_datagram(&encode_datagram(&all).unwrap()).unwrap(), all);
}
fn kind(b: &CommandBody) -> u8 {
match b {
CommandBody::Acknowledge { .. } => 1,
CommandBody::Connect { .. } => 2,
CommandBody::VerifyConnect(_) => 3,
CommandBody::Disconnect { .. } => 4,
CommandBody::Ping => 5,
CommandBody::SendReliable(_) => 6,
CommandBody::SendUnreliable { .. } => 7,
CommandBody::SendFragment(_) => 8,
CommandBody::SendUnsequenced { .. } => 9,
CommandBody::BandwidthLimit { .. } => 10,
CommandBody::ThrottleConfigure { .. } => 11,
CommandBody::SendUnreliableFragment(_) => 12,
}
}
#[test]
fn unsequenced_carries_its_flag() {
let d = Datagram {
peer_id: 0,
session_id: 0,
sent_time: None,
commands: vec![cmd(false, 0, 0, CommandBody::SendUnsequenced { unsequenced_group: 1, data: vec![1] })],
};
let bytes = encode_datagram(&d).unwrap();
assert_eq!(bytes[2] & 0x40, 0x40, "unsequenced flag");
}
// ================================================================================================ hostile datagrams
#[test]
fn hostile_truncation() {
for (bad, why) in [
(&[][..], "empty"),
(&[0x00][..], "one byte"),
(&[0x80, 0x01, 0x12][..], "sent-time flag, cut sent time"),
(&[0x00, 0x01, 0x85, 0xFF, 0x00][..], "cut command header"),
(&[0x00, 0x01, 0x01, 0x00, 0x00, 0x05, 0x00, 0x07][..], "cut acknowledge"),
(&[0x00, 0x01, 0x86, 0x00, 0x00, 0x01, 0x00][..], "cut data length"),
(&[0x00, 0x01, 0x86, 0x00, 0x00, 0x01, 0x00, 0x0A, 1, 2, 3][..], "data length over"),
(&[0x00, 0x01, 0x86, 0x00, 0x00, 0x01, 0xFF, 0xFF, 1][..], "data length 65535"),
(&[0x00, 0x01, 0x86, 0x00, 0x00, 0x01, 0x00, 0x01, 1, 2, 3][..], "data length under: 2 stray bytes"),
] {
assert_err!(parse_datagram(bad), Error::Truncated { .. }, "{why}");
}
// A connect cut at every length.
let full = encode_datagram(&Datagram {
peer_id: NO_PEER_ID,
session_id: 0,
sent_time: Some(0),
commands: vec![every_command()[1].0.clone()],
})
.unwrap();
for cut in 5..full.len() {
assert_err!(parse_datagram(&full[..cut]), Error::Truncated { .. }, "connect cut at {cut}");
}
}
#[test]
fn hostile_values() {
assert_err!(parse_datagram(&[0x40, 0x01, 0x85, 0xFF, 0x00, 0x01]), Error::UnexpectedValue { .. }, "compressed");
assert_err!(
parse_datagram(&[0xC0, 0x01, 0x00, 0x00, 0x85, 0xFF, 0x00, 0x01]),
Error::UnexpectedValue { .. },
"compressed + time"
);
for number in [0u8, 13, 14, 15] {
assert_err!(
parse_datagram(&[0x00, 0x01, 0x80 | number, 0xFF, 0x00, 0x01, 0, 0, 0, 0]),
Error::UnexpectedValue { .. },
"command {number}"
);
}
// A good command followed by an unknown one: the whole datagram is refused.
assert_err!(
parse_datagram(&[0x00, 0x01, 0x85, 0xFF, 0x00, 0x01, 0x0E, 0x00, 0x00, 0x00]),
Error::UnexpectedValue { .. }
);
}
#[test]
fn hostile_sizes() {
let ping = [0x85, 0xFF, 0x00, 0x01];
let pings = |n: usize| {
let mut b = vec![0x00, 0x01];
for _ in 0..n {
b.extend_from_slice(&ping);
}
b
};
assert_eq!(parse_datagram(&pings(MAX_COMMANDS_PER_DATAGRAM)).unwrap().commands.len(), MAX_COMMANDS_PER_DATAGRAM);
match parse_datagram(&pings(MAX_COMMANDS_PER_DATAGRAM + 1)) {
Err(Error::TooLarge { max, .. }) => assert_eq!(max, MAX_COMMANDS_PER_DATAGRAM),
other => panic!("33 commands: {other:?}"),
}
// A reliable packet filling the datagram exactly; one byte more is over.
let reliable = |data: usize| {
let mut b = vec![0x00, 0x01, 0x86, 0x00, 0x00, 0x01];
b.extend_from_slice(&(data as u16).to_be_bytes());
b.extend(std::iter::repeat_n(0x5A, data));
b
};
let max_data = MAX_DATAGRAM_BYTES - 8;
assert_eq!(reliable(max_data).len(), MAX_DATAGRAM_BYTES);
assert!(parse_datagram(&reliable(max_data)).is_ok());
assert_eq!(parse_datagram(&reliable(max_data - 1)).unwrap().commands.len(), 1);
assert_too_large!(parse_datagram(&reliable(max_data + 1)), MAX_DATAGRAM_BYTES, MAX_DATAGRAM_BYTES + 1);
assert_too_large!(parse_datagram(&vec![0; 1 << 20]), MAX_DATAGRAM_BYTES, 1 << 20);
}
#[test]
fn encode_refuses_oversized() {
let many = Datagram {
peer_id: 0,
session_id: 0,
sent_time: None,
commands: vec![cmd(true, 0xFF, 1, CommandBody::Ping); MAX_COMMANDS_PER_DATAGRAM + 1],
};
assert!(matches!(encode_datagram(&many), Err(Error::TooLarge { .. })));
let big = Datagram {
peer_id: 0,
session_id: 0,
sent_time: None,
commands: vec![cmd(true, 0, 1, CommandBody::SendReliable(vec![0; MAX_DATAGRAM_BYTES]))],
};
assert!(matches!(encode_datagram(&big), Err(Error::TooLarge { .. })));
}
fn body() -> impl Strategy<Value = CommandBody> {
let data = || proptest::collection::vec(any::<u8>(), 0..64);
let fragment = || {
(any::<u16>(), any::<u32>(), any::<u32>(), any::<u32>(), any::<u32>(), data())
.prop_map(|(a, b, c, d, e, f)| frag(a, b, c, d, e, f))
};
let cparams = || {
proptest::array::uniform12(any::<u32>()).prop_map(|a| ConnectParams {
outgoing_peer_id: (a[0] & 0xFFFF) as u16,
incoming_session_id: a[1] as u8,
outgoing_session_id: (a[1] >> 8) as u8,
mtu: a[2],
window_size: a[3],
channel_count: a[4],
incoming_bandwidth: a[5],
outgoing_bandwidth: a[6],
packet_throttle_interval: a[7],
packet_throttle_acceleration: a[8],
packet_throttle_deceleration: a[9],
connect_id: a[10],
})
};
prop_oneof![
(any::<u16>(), any::<u16>())
.prop_map(|(a, b)| CommandBody::Acknowledge { received_reliable_sequence: a, received_sent_time: b }),
(cparams(), any::<u32>()).prop_map(|(params, data)| CommandBody::Connect { params, data }),
cparams().prop_map(CommandBody::VerifyConnect),
any::<u32>().prop_map(|data| CommandBody::Disconnect { data }),
Just(CommandBody::Ping),
data().prop_map(CommandBody::SendReliable),
(any::<u16>(), data())
.prop_map(|(unreliable_sequence, data)| CommandBody::SendUnreliable { unreliable_sequence, data }),
fragment().prop_map(CommandBody::SendFragment),
(any::<u16>(), data())
.prop_map(|(unsequenced_group, data)| CommandBody::SendUnsequenced { unsequenced_group, data }),
(any::<u32>(), any::<u32>())
.prop_map(|(incoming, outgoing)| CommandBody::BandwidthLimit { incoming, outgoing }),
(any::<u32>(), any::<u32>(), any::<u32>()).prop_map(|(interval, acceleration, deceleration)| {
CommandBody::ThrottleConfigure { interval, acceleration, deceleration }
}),
fragment().prop_map(CommandBody::SendUnreliableFragment),
]
}
proptest! {
#![proptest_config(ProptestConfig { cases: 512, ..ProptestConfig::default() })]
#[test]
fn datagram_round_trip(
peer_id in 0u16..=0x0FFF,
session_id in 0u8..4,
sent_time in proptest::option::of(any::<u16>()),
commands in proptest::collection::vec((any::<bool>(), any::<u8>(), any::<u16>(), body()), 1..8),
) {
let commands = commands.into_iter().map(|(a, ch, s, b)| cmd(a, ch, s, b)).collect();
let d = Datagram { peer_id, session_id, sent_time, commands };
let bytes = encode_datagram(&d).map_err(|e| TestCaseError::fail(format!("{e:?}")))?;
prop_assert!(bytes.len() <= MAX_DATAGRAM_BYTES);
prop_assert_eq!(parse_datagram(&bytes), Ok(d));
}
/// Arbitrary bytes: no panic; a parsed datagram re-encodes to something that parses to the same value.
#[test]
fn datagram_parse_is_stable(data in proptest::collection::vec(any::<u8>(), 0..512)) {
let parsed = parse_datagram(&data);
prop_assert!(common::implemented(&parsed));
if let Ok(d) = parsed {
prop_assert!(d.commands.len() <= MAX_COMMANDS_PER_DATAGRAM);
prop_assert!(d.peer_id <= 0x0FFF && d.session_id < 4);
let again = encode_datagram(&d).map_err(|e| TestCaseError::fail(format!("{e:?}")))?;
prop_assert_eq!(parse_datagram(&again), Ok(d));
}
}
}
// ================================================================================================ client peer
fn config() -> EnetConfig {
EnetConfig {
channel_count: 2,
mtu: 1400,
connect_data: 0x0000_1234,
ping_interval: Duration::from_millis(500),
timeout: Duration::from_secs(10),
}
}
fn at(ms: u64) -> Instant {
Instant::from_micros(ms * 1000)
}
/// The client and the scripted host's view of it.
struct Link {
client: EnetClient,
/// Peer id the host addresses the client with (from the client's connect).
to_client: u16,
/// Next reliable sequence the host uses per channel.
host_seq: [u16; 256],
now_ms: u64,
}
impl Link {
fn host_datagram(&self, commands: Vec<Command>) -> Vec<u8> {
encode_datagram(&Datagram {
peer_id: self.to_client,
session_id: 0,
sent_time: Some(self.now_ms as u16),
commands,
})
.unwrap()
}
fn feed(&mut self, commands: Vec<Command>) -> domistream::Result<()> {
self.now_ms += 1;
let d = self.host_datagram(commands);
self.client.handle_datagram(at(self.now_ms), &d)
}
fn reliable(&mut self, channel: u8, data: &[u8]) -> Command {
let s = &mut self.host_seq[usize::from(channel)];
*s = s.wrapping_add(1);
cmd(true, channel, *s, CommandBody::SendReliable(data.to_vec()))
}
/// Everything the client wants to send now, parsed.
fn transmitted(&mut self) -> Vec<Datagram> {
let mut out = Vec::new();
while let Some(d) = self.client.poll_transmit(at(self.now_ms)) {
assert!(d.len() <= MAX_DATAGRAM_BYTES);
out.push(parse_datagram(&d).expect("the client's datagrams parse"));
assert!(out.len() < 10_000, "poll_transmit never ends");
}
out
}
fn events(&mut self) -> Vec<EnetEvent> {
let mut out = Vec::new();
while let Some(e) = self.client.poll_event() {
out.push(e);
assert!(out.len() < 100_000, "poll_event never ends");
}
out
}
fn received(&mut self) -> Vec<Vec<u8>> {
self.events()
.into_iter()
.map(|e| match e {
EnetEvent::Received { data, .. } => data,
other => panic!("unexpected event {other:?}"),
})
.collect()
}
}
/// Starts a client and returns it with its connect command.
fn start() -> (EnetClient, Datagram, ConnectParams, u32, u16) {
let mut client = EnetClient::connect(config(), at(0), &mut SeqRng::new(5)).expect("EnetClient::connect");
assert_eq!(client.state(), EnetState::Connecting);
let d = parse_datagram(&client.poll_transmit(at(0)).expect("connect datagram")).unwrap();
let c =
d.commands.iter().find(|c| matches!(c.body, CommandBody::Connect { .. })).expect("a connect command").clone();
let (params, data) = match c.body {
CommandBody::Connect { params, data } => (params, data),
_ => unreachable!(),
};
(client, d.clone(), params, data, c.reliable_sequence)
}
/// A connected link: connect, then the host's acknowledge + verify connect.
fn connected() -> Link {
let (client, d, params, _, connect_seq) = start();
let mut link = Link { client, to_client: params.outgoing_peer_id, host_seq: [0; 256], now_ms: 0 };
let verify = ConnectParams { outgoing_peer_id: 0, incoming_session_id: 0, outgoing_session_id: 0, ..params };
link.feed(vec![
cmd(
false,
0xFF,
0,
CommandBody::Acknowledge {
received_reliable_sequence: connect_seq,
received_sent_time: d.sent_time.unwrap_or(0),
},
),
cmd(true, 0xFF, 1, CommandBody::VerifyConnect(verify)),
])
.expect("verify connect");
assert_eq!(link.events(), vec![EnetEvent::Connected]);
assert_eq!(link.client.state(), EnetState::Connected);
link.transmitted();
link
}
#[test]
fn connect_offers_the_config() {
let (_, d, params, data, _) = start();
assert_eq!(d.peer_id, NO_PEER_ID, "no peer id yet");
assert_eq!(params.mtu, u32::from(config().mtu));
assert_eq!(params.channel_count, u32::from(config().channel_count));
assert_eq!(data, config().connect_data);
let c = &d.commands[0];
assert!(c.acknowledge && c.channel_id == 0xFF, "connect is reliable, connection-level");
// The connect id comes from the caller's randomness.
let (_, _, p2, _, _) = start();
assert_eq!(p2.connect_id, params.connect_id);
}
#[test]
fn connect_refuses_configs_outside_enet_limits() {
for bad in [
EnetConfig { mtu: 575, ..config() },
EnetConfig { mtu: 4097, ..config() },
EnetConfig { mtu: 0, ..config() },
EnetConfig { channel_count: 0, ..config() },
] {
assert_err!(EnetClient::connect(bad, at(0), &mut SeqRng::new(1)), Error::Malformed { .. }, "{bad:?}");
}
for ok in [
EnetConfig { mtu: 576, ..config() },
EnetConfig { mtu: 4096, ..config() },
EnetConfig { channel_count: 255, ..config() },
] {
assert!(EnetClient::connect(ok, at(0), &mut SeqRng::new(1)).is_ok(), "{ok:?}");
}
}
#[test]
fn verify_with_wrong_connect_id_does_not_connect() {
let (client, _, params, _, _) = start();
let mut link = Link { client, to_client: params.outgoing_peer_id, host_seq: [0; 256], now_ms: 0 };
let verify = ConnectParams {
connect_id: params.connect_id ^ 1,
outgoing_peer_id: 0,
incoming_session_id: 0,
outgoing_session_id: 0,
..params
};
let _ = link.feed(vec![cmd(true, 0xFF, 1, CommandBody::VerifyConnect(verify))]);
assert_eq!(link.client.state(), EnetState::Connecting);
assert!(link.events().is_empty());
}
#[test]
fn garbage_never_changes_state() {
let mut link = connected();
for bad in [&[][..], &[0x00][..], &[0x40, 0x00, 0x85, 0xFF, 0, 1][..], &[0x00, 0x00, 0x8F, 0, 0, 0][..]] {
assert!(link.client.handle_datagram(at(5), bad).is_err(), "{bad:?}");
assert_eq!(link.client.state(), EnetState::Connected);
}
assert_too_large!(
link.client.handle_datagram(at(5), &vec![0; MAX_DATAGRAM_BYTES + 1]),
MAX_DATAGRAM_BYTES,
MAX_DATAGRAM_BYTES + 1
);
assert!(link.events().is_empty());
}
#[test]
fn datagrams_for_another_peer_are_dropped() {
let mut link = connected();
let c = link.reliable(0, b"not for you");
let other = encode_datagram(&Datagram {
peer_id: link.to_client ^ 0x0001,
session_id: 0,
sent_time: Some(1),
commands: vec![c],
})
.unwrap();
assert_eq!(link.client.handle_datagram(at(9), &other), Ok(()));
assert!(link.events().is_empty());
}
#[test]
fn reliable_in_order_reordered_and_duplicated() {
let mut link = connected();
let a = link.reliable(0, b"one");
let b = link.reliable(0, b"two");
let c = link.reliable(0, b"three");
link.feed(vec![c.clone()]).unwrap();
link.feed(vec![b.clone()]).unwrap();
assert!(link.received().is_empty(), "nothing before sequence 1");
link.feed(vec![a.clone()]).unwrap();
assert_eq!(link.received(), vec![b"one".to_vec(), b"two".to_vec(), b"three".to_vec()]);
// Duplicates (retransmissions by the host) are acknowledged but never delivered twice.
link.feed(vec![a, b.clone(), c]).unwrap();
link.feed(vec![b]).unwrap();
assert!(link.received().is_empty());
let acks: usize = link
.transmitted()
.iter()
.flat_map(|d| &d.commands)
.filter(|c| matches!(c.body, CommandBody::Acknowledge { .. }))
.count();
assert!(acks >= 4, "duplicates are still acknowledged ({acks})");
}
#[test]
fn reliable_sequence_wraps_at_0xffff() {
// 70 000 reliable packets, one per datagram: the sequence passes 0xFFFF -> 0 and order is kept.
let mut link = connected();
let total = 70_000u32;
let mut got = 0u32;
for i in 0..total {
let c = link.reliable(0, &i.to_le_bytes());
link.feed(vec![c]).unwrap();
for data in link.received() {
assert_eq!(data, got.to_le_bytes(), "packet {got} out of order");
got += 1;
}
link.transmitted();
}
assert_eq!(got, total);
assert_eq!(link.host_seq[0], (total % 65_536) as u16);
}
#[test]
fn far_future_and_far_past_are_dropped() {
let mut link = connected();
for i in 0..10u8 {
let c = link.reliable(0, &[i]);
link.feed(vec![c]).unwrap();
}
assert_eq!(link.received().len(), 10);
let next = link.host_seq[0];
for seq in [next.wrapping_add(40_000), next.wrapping_add(0x8000), next.wrapping_sub(30_000), next.wrapping_sub(5)] {
let _ = link.feed(vec![cmd(true, 0, seq, CommandBody::SendReliable(b"evil".to_vec()))]);
assert!(link.received().is_empty(), "sequence {seq} (next {next}) must not be delivered");
}
// The stream continues normally.
let c = link.reliable(0, b"ok");
link.feed(vec![c]).unwrap();
assert_eq!(link.received(), vec![b"ok".to_vec()]);
assert_eq!(link.client.state(), EnetState::Connected);
}
#[test]
fn channels_outside_the_negotiated_count_are_not_delivered() {
let mut link = connected();
let c = link.reliable(200, b"x");
let _ = link.feed(vec![c]);
assert!(link.received().is_empty());
assert_eq!(link.client.state(), EnetState::Connected);
}
fn fragments(link: &mut Link, data: &[u8], piece: usize) -> Vec<Command> {
let count = data.len().div_ceil(piece) as u32;
let start = link.host_seq[0].wrapping_add(1);
(0..count)
.map(|n| {
link.host_seq[0] = link.host_seq[0].wrapping_add(1);
let off = n as usize * piece;
let chunk = data[off..(off + piece).min(data.len())].to_vec();
cmd(
true,
0,
link.host_seq[0],
CommandBody::SendFragment(frag(start, count, n, data.len() as u32, off as u32, chunk)),
)
})
.collect()
}
#[test]
fn fragments_reassemble_in_any_order() {
let mut link = connected();
let data: Vec<u8> = (0..3000u32).map(|i| (i * 7) as u8).collect();
let mut frags = fragments(&mut link, &data, 1000);
frags.swap(0, 2);
for f in frags {
link.feed(vec![f]).unwrap();
}
assert_eq!(link.received(), vec![data]);
}
#[test]
fn fragments_with_lying_lengths() {
// Total length over the reassembly cap.
let mut link = connected();
link.host_seq[0] += 1;
let s = link.host_seq[0];
let r = link.feed(vec![cmd(
true,
0,
s,
CommandBody::SendFragment(frag(s, 2, 0, MAX_PACKET_BYTES as u32 + 1, 0, vec![0; 100])),
)]);
assert_too_large!(r, MAX_PACKET_BYTES, MAX_PACKET_BYTES + 1);
assert!(link.events().is_empty());
// Other lies: never delivered, never a panic, the connection survives.
for f in [
frag(0, 0, 0, 10, 0, vec![0; 10]), // zero fragments
frag(0, 2, 2, 20, 0, vec![0; 10]), // number >= count
frag(0, 2, 0, 20, 15, vec![0; 10]), // offset + length past total
frag(0, 2, 0, 5, 0, vec![0; 10]), // fragment longer than total
frag(0, u32::MAX, 0, 100, 0, vec![0; 10]), // absurd count for a small total
frag(0, 2, 0, u32::MAX, 0, vec![0; 10]), // absurd total
frag(0, 2, 1, 20, u32::MAX - 3, vec![0; 10]), // offset overflow
] {
let mut link = connected();
link.host_seq[0] += 1;
let s = link.host_seq[0];
let r =
link.feed(vec![cmd(true, 0, s, CommandBody::SendFragment(Fragment { start_sequence: s, ..f.clone() }))]);
assert!(link.events().is_empty(), "{f:?} -> {r:?}");
assert_eq!(link.client.state(), EnetState::Connected, "{f:?}");
}
}
#[test]
fn send_rules() {
let (mut client, ..) = start();
assert_err!(client.send(at(1), 0, Delivery::Reliable, b"x"), Error::State { .. }, "before connected");
let mut link = connected();
assert_err!(link.client.send(at(2), 2, Delivery::Reliable, b"x"), Error::UnexpectedValue { .. }, "channel 2 of 2");
assert_err!(link.client.send(at(2), 255, Delivery::Reliable, b"x"), Error::UnexpectedValue { .. });
match link.client.send(at(2), 0, Delivery::Reliable, &vec![0; MAX_PACKET_BYTES + 1]) {
Err(Error::TooLarge { max, .. }) => assert_eq!(max, MAX_PACKET_BYTES),
other => panic!("{other:?}"),
}
}
#[test]
fn send_queue_is_capped() {
let mut link = connected();
for i in 0..MAX_SEND_QUEUE {
link.client.send(at(3), 0, Delivery::Reliable, &[i as u8]).unwrap_or_else(|e| panic!("packet {i}: {e:?}"));
}
match link.client.send(at(3), 0, Delivery::Reliable, b"one too many") {
Err(Error::TooLarge { max, .. }) => assert_eq!(max, MAX_SEND_QUEUE),
other => panic!("{other:?}"),
}
}
#[test]
fn large_sends_are_fragmented_within_the_mtu() {
let mut link = connected();
let data: Vec<u8> = (0..5000u32).map(|i| i as u8).collect();
link.client.send(at(4), 1, Delivery::Reliable, &data).unwrap();
let mut pieces = Vec::new();
while let Some(d) = link.client.poll_transmit(at(4)) {
assert!(d.len() <= usize::from(config().mtu), "datagram of {} over the MTU", d.len());
for c in parse_datagram(&d).unwrap().commands {
if let CommandBody::SendFragment(f) = c.body {
assert_eq!(c.channel_id, 1);
assert_eq!(f.total_length, 5000);
pieces.push(f);
}
}
}
pieces.sort_by_key(|f| f.fragment_number);
assert_eq!(pieces.len() as u32, pieces[0].fragment_count);
let mut whole = vec![0u8; 5000];
for f in &pieces {
whole[f.fragment_offset as usize..f.fragment_offset as usize + f.data.len()].copy_from_slice(&f.data);
}
assert_eq!(whole, data);
}
#[test]
fn reliable_sends_are_retransmitted_until_acknowledged() {
let mut link = connected();
link.client.send(at(10), 0, Delivery::Reliable, b"hello").unwrap();
let first = link.transmitted();
let sent = first
.iter()
.flat_map(|d| &d.commands)
.find(|c| c.body == CommandBody::SendReliable(b"hello".to_vec()))
.expect("sent")
.clone();
let when = link.client.poll_timeout().expect("a retransmission deadline");
link.now_ms = when.as_micros() / 1000 + 1;
link.client.handle_timeout(at(link.now_ms)).unwrap();
let again = link.transmitted();
assert!(
again
.iter()
.flat_map(|d| &d.commands)
.any(|c| c.reliable_sequence == sent.reliable_sequence && c.body == sent.body),
"retransmitted"
);
// Acknowledge it: no more retransmissions of that command.
link.feed(vec![cmd(
false,
0,
0,
CommandBody::Acknowledge { received_reliable_sequence: sent.reliable_sequence, received_sent_time: 10 },
)])
.unwrap();
for _ in 0..5 {
if let Some(t) = link.client.poll_timeout() {
link.now_ms = link.now_ms.max(t.as_micros() / 1000 + 1);
link.client.handle_timeout(at(link.now_ms)).unwrap();
}
assert!(
!link.transmitted().iter().flat_map(|d| &d.commands).any(|c| c.body == sent.body),
"acknowledged command sent again"
);
}
}
#[test]
fn silence_times_out() {
let mut link = connected();
link.client.send(at(1), 0, Delivery::Reliable, b"anyone?").unwrap();
let end = at(1 + config().timeout.as_millis() as u64 * 4);
let mut guard = 0;
while link.client.state() != EnetState::Disconnected {
let t = link.client.poll_timeout().expect("a deadline while waiting for an acknowledgement");
assert!(t <= end, "no timeout by {end:?}");
link.client.handle_timeout(t).unwrap();
let _ = link.client.poll_transmit(t);
guard += 1;
assert!(guard < 10_000);
}
assert!(link.events().contains(&EnetEvent::TimedOut));
}
#[test]
fn host_disconnect_closes() {
let mut link = connected();
link.feed(vec![cmd(true, 0xFF, 2, CommandBody::Disconnect { data: 7 })]).unwrap();
assert_eq!(link.events(), vec![EnetEvent::Disconnected { data: 7 }]);
assert_eq!(link.client.state(), EnetState::Disconnected);
let c = link.reliable(0, b"late");
assert_err!(link.feed(vec![c]), Error::Closed);
assert_err!(link.client.disconnect(at(100), 0), Error::Closed);
}
#[test]
fn client_disconnect() {
let mut link = connected();
link.client.disconnect(at(5), 9).unwrap();
assert_eq!(link.client.state(), EnetState::Disconnecting);
let sent = link.transmitted();
assert!(sent.iter().flat_map(|d| &d.commands).any(|c| c.body == CommandBody::Disconnect { data: 9 }));
}
proptest! {
#![proptest_config(ProptestConfig { cases: 128, ..ProptestConfig::default() })]
/// A connected client fed arbitrary datagrams never panics and never leaves Connected without a reason.
#[test]
fn client_survives_arbitrary_datagrams(datagrams in proptest::collection::vec(proptest::collection::vec(any::<u8>(), 0..200), 1..20)) {
let mut link = connected();
for d in datagrams {
let _ = link.client.handle_datagram(at(7), &d);
while link.client.poll_transmit(at(7)).is_some() {}
for e in link.events() {
if let EnetEvent::Received { data, .. } = e {
prop_assert!(data.len() <= MAX_PACKET_BYTES);
}
}
}
}
}
+365
View File
@@ -0,0 +1,365 @@
//! Reed-Solomon over GF(2^8) / 0x11D (`docs/PROTOCOL.md` 5.3, 6.4). The video construction is UNKNOWN U14, so the
//! tests check what any correct systematic MDS code must do: data passes through, every erasure pattern of at most
//! `m` shards is rebuilt byte-exact, more than `m` is refused. With an explicit matrix
//! (`with_parity_matrix`, a Cauchy matrix computed by the independent GF(2^8) reference in `common::gf`), the parity
//! bytes themselves are checked.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
mod common;
use common::{SeqRng, gf};
use domistream::Error;
use domistream::fec::{MAX_SHARD_BYTES, MAX_SHARDS, ReedSolomon, parity_count};
use proptest::prelude::*;
fn data_shards(rng: &mut SeqRng, k: usize, len: usize) -> Vec<Vec<u8>> {
(0..k).map(|_| rng.bytes(len)).collect()
}
/// Encodes `data` with `code`: data shards plus zeroed parity buffers, filled in place.
fn encoded(code: &ReedSolomon, data: &[Vec<u8>]) -> Vec<Vec<u8>> {
let len = data[0].len();
let mut shards: Vec<Vec<u8>> = data.to_vec();
shards.extend((0..code.parity_shards()).map(|_| vec![0u8; len]));
code.encode(&mut shards).expect("encode");
assert_eq!(&shards[..data.len()], data, "systematic: data shards pass through unchanged");
shards
}
fn erase(shards: &[Vec<u8>], lost: &[usize]) -> Vec<Option<Vec<u8>>> {
shards.iter().enumerate().map(|(i, s)| if lost.contains(&i) { None } else { Some(s.clone()) }).collect()
}
fn check_recovers(code: &ReedSolomon, full: &[Vec<u8>], lost: &[usize]) {
let mut s = erase(full, lost);
code.reconstruct(&mut s)
.unwrap_or_else(|e| panic!("k={} m={} lost {lost:?}: {e:?}", code.data_shards(), code.parity_shards()));
for (i, (got, want)) in s.iter().zip(full).enumerate() {
assert_eq!(
got.as_deref(),
Some(want.as_slice()),
"k={} m={} lost {lost:?}: shard {i}",
code.data_shards(),
code.parity_shards()
);
}
}
fn check_refuses(code: &ReedSolomon, full: &[Vec<u8>], lost: &[usize]) {
let mut s = erase(full, lost);
assert_err!(
code.reconstruct(&mut s),
Error::Truncated { .. },
"k={} m={} lost {lost:?}",
code.data_shards(),
code.parity_shards()
);
}
fn subsets(n: usize, size: usize) -> Vec<Vec<usize>> {
common::subsets_of(n, size)
}
// ================================================================================================ parameters
#[test]
fn parity_counts() {
for (k, pct, m) in [
(4usize, 50u8, 2usize),
(1, 1, 1),
(1, 100, 1),
(10, 0, 0),
(100, 100, 100),
(3, 33, 1),
(3, 34, 2),
(7, 20, 2),
(127, 100, 127),
(255, 0, 0),
(2, 255, 6),
] {
assert_eq!(parity_count(k, pct), Ok(m), "ceil({k} * {pct} / 100)");
}
assert_err!(parity_count(0, 50), Error::UnexpectedValue { .. });
assert_err!(parity_count(255, 200), Error::UnexpectedValue { .. }, "510 parity shards");
assert_err!(parity_count(200, 255), Error::UnexpectedValue { .. });
}
#[test]
fn code_parameters() {
for (k, m) in [(0usize, 1usize), (1, 0), (0, 0), (255, 1), (1, 255), (200, 100), (usize::MAX, 1)] {
assert_err!(ReedSolomon::new(k, m), Error::UnexpectedValue { .. }, "k={k} m={m}");
}
for (k, m) in [(1usize, 1usize), (254, 1), (1, 254), (128, 127), (4, 2)] {
let c = ReedSolomon::new(k, m).unwrap_or_else(|e| panic!("k={k} m={m}: {e:?}"));
assert_eq!((c.data_shards(), c.parity_shards(), c.parity_matrix().len()), (k, m, k * m));
}
assert_eq!(MAX_SHARDS, 255);
}
#[test]
fn explicit_matrix_is_used_exactly() {
let mut rng = SeqRng::new(1);
for (k, m) in [(4usize, 2usize), (1, 1), (10, 4), (2, 6), (200, 55)] {
let matrix = gf::cauchy(m, k);
let code = ReedSolomon::with_parity_matrix(k, m, &matrix).unwrap();
assert_eq!(code.parity_matrix(), matrix.as_slice());
let data = data_shards(&mut rng, k, 33);
let full = encoded(&code, &data);
assert_eq!(
&full[k..],
gf::encode(&matrix, &data, m).as_slice(),
"k={k} m={m}: parity = matrix x data over GF(2^8)/0x11D"
);
check_recovers(&code, &full, &(0..m.min(k)).collect::<Vec<_>>());
}
// A second MDS matrix (rows 1,1,1,1 and 1,2,4,8): every square submatrix is invertible.
let v = [1, 1, 1, 1, 1, 2, 4, 8];
let code = ReedSolomon::with_parity_matrix(4, 2, &v).unwrap();
let data = data_shards(&mut rng, 4, 5);
let full = encoded(&code, &data);
assert_eq!(&full[4..], gf::encode(&v, &data, 2).as_slice());
for size in 0..=2 {
for lost in subsets(6, size) {
check_recovers(&code, &full, &lost);
}
}
}
#[test]
fn explicit_matrix_refusals() {
let good = gf::cauchy(2, 4);
assert_err!(ReedSolomon::with_parity_matrix(4, 2, &good[..7]), Error::Malformed { .. }, "short");
assert_err!(
ReedSolomon::with_parity_matrix(4, 2, &[good.clone(), vec![1]].concat()),
Error::Malformed { .. },
"long"
);
assert_err!(ReedSolomon::with_parity_matrix(4, 2, &[]), Error::Malformed { .. }, "empty");
let mut zero = good.clone();
zero[3] = 0;
assert_err!(
ReedSolomon::with_parity_matrix(4, 2, &zero),
Error::Malformed { .. },
"a zero entry: a 1x1 submatrix is singular"
);
assert_err!(
ReedSolomon::with_parity_matrix(4, 2, &[1, 1, 1, 1, 1, 1, 1, 1]),
Error::Malformed { .. },
"equal rows"
);
assert_err!(
ReedSolomon::with_parity_matrix(4, 2, &[1, 2, 3, 4, 2, 4, 6, 8]),
Error::Malformed { .. },
"row 2 = 2 x row 1"
);
assert_err!(
ReedSolomon::with_parity_matrix(4, 2, &[1, 2, 3, 4, 1, 2, 5, 6]),
Error::Malformed { .. },
"a singular 2x2 minor (cols 0,1)"
);
assert_err!(ReedSolomon::with_parity_matrix(0, 2, &[]), Error::UnexpectedValue { .. });
assert_err!(ReedSolomon::with_parity_matrix(255, 1, &vec![1; 255]), Error::UnexpectedValue { .. });
}
// ================================================================================================ encode / reconstruct shapes
#[test]
fn encode_shape_errors() {
let code = ReedSolomon::new(4, 2).unwrap();
assert_err!(code.encode(&mut vec![vec![0u8; 8]; 5]), Error::Malformed { .. }, "5 shards for 4 + 2");
assert_err!(code.encode(&mut vec![vec![0u8; 8]; 7]), Error::Malformed { .. }, "7 shards");
let mut uneven = vec![vec![0u8; 8]; 6];
uneven[2].push(0);
assert_err!(code.encode(&mut uneven), Error::Malformed { .. }, "unequal lengths");
let mut uneven = vec![vec![0u8; 8]; 6];
uneven[5].pop();
assert_err!(code.encode(&mut uneven), Error::Malformed { .. }, "parity buffer of another length");
assert!(code.encode(&mut vec![vec![1u8; MAX_SHARD_BYTES]; 6]).is_ok());
assert_too_large!(code.encode(&mut vec![vec![1u8; MAX_SHARD_BYTES + 1]; 6]), MAX_SHARD_BYTES, MAX_SHARD_BYTES + 1);
}
#[test]
fn reconstruct_shape_errors() {
let code = ReedSolomon::new(4, 2).unwrap();
let full = encoded(&code, &data_shards(&mut SeqRng::new(2), 4, 8));
let mut s = erase(&full, &[0]);
s.pop();
assert_err!(code.reconstruct(&mut s), Error::Malformed { .. }, "5 entries");
let mut s = erase(&full, &[0]);
s[3].as_mut().unwrap().push(9);
assert_err!(code.reconstruct(&mut s), Error::Malformed { .. }, "unequal lengths");
let mut s: Vec<Option<Vec<u8>>> = vec![None; 6];
assert_err!(code.reconstruct(&mut s), Error::Truncated { .. }, "everything lost");
let mut s: Vec<Option<Vec<u8>>> = vec![Some(vec![0; MAX_SHARD_BYTES + 1]); 6];
s[0] = None;
assert_too_large!(code.reconstruct(&mut s), MAX_SHARD_BYTES, MAX_SHARD_BYTES + 1);
// Nothing lost: unchanged.
let mut s = erase(&full, &[]);
code.reconstruct(&mut s).unwrap();
assert!(s.iter().zip(&full).all(|(a, b)| a.as_deref() == Some(b.as_slice())));
}
// ================================================================================================ erasure patterns
#[test]
fn every_pattern_small_codes_exhaustive() {
// k = 1..=8, m = 1..=4: every erasure pattern of size <= m recovers; every pattern of size m + 1 is refused.
let mut rng = SeqRng::new(3);
for k in 1..=8 {
for m in 1..=4 {
let code = ReedSolomon::new(k, m).unwrap();
let full = encoded(&code, &data_shards(&mut rng, k, 7));
for size in 0..=m {
for lost in subsets(k + m, size) {
check_recovers(&code, &full, &lost);
}
}
for lost in subsets(k + m, m + 1) {
check_refuses(&code, &full, &lost);
}
}
}
}
#[test]
fn every_pattern_wolf_example() {
// 4 KB at packetSize 1024 and 50 %: 4 data + 2 parity (PROTOCOL.md 5.3), full-size shards.
let mut rng = SeqRng::new(4);
let code = ReedSolomon::new(4, parity_count(4, 50).unwrap()).unwrap();
let full = encoded(&code, &data_shards(&mut rng, 4, 1024 + 16));
for size in 0..=2 {
for lost in subsets(6, size) {
check_recovers(&code, &full, &lost);
}
}
for size in 3..=6 {
for lost in subsets(6, size) {
check_refuses(&code, &full, &lost);
}
}
}
/// k = 1..=255 - m for one m: one worst-case pattern of exactly m erasures (data first) and one random pattern
/// recover; m + 1 erasures are refused.
fn sweep(m: usize, seed: u64) {
let mut rng = SeqRng::new(seed);
for k in 1..=(MAX_SHARDS - m) {
let code = ReedSolomon::new(k, m).unwrap_or_else(|e| panic!("k={k} m={m}: {e:?}"));
let full = encoded(&code, &data_shards(&mut rng, k, 3));
let data_first: Vec<usize> = (0..m).collect();
check_recovers(&code, &full, &data_first);
check_recovers(&code, &full, &rng.subset(k + m, m));
check_refuses(&code, &full, &rng.subset(k + m, m + 1));
}
}
#[test]
fn sweep_m1() {
sweep(1, 11);
}
#[test]
fn sweep_m2() {
sweep(2, 12);
}
#[test]
fn sweep_m3() {
sweep(3, 13);
}
#[test]
fn sweep_m4() {
sweep(4, 14);
}
#[test]
fn sweep_m8() {
sweep(8, 18);
}
#[test]
fn sweep_m16() {
sweep(16, 116);
}
#[test]
fn sweep_m64() {
sweep(64, 164);
}
#[test]
fn sweep_m127() {
sweep(127, 1127);
}
#[test]
fn sweep_m254() {
sweep(254, 1254);
}
#[test]
fn large_codes_random_patterns() {
// The biggest blocks: many random patterns of every size up to m.
let mut rng = SeqRng::new(5);
for (k, m) in [(250usize, 5usize), (200, 55), (128, 127), (64, 191)] {
let code = ReedSolomon::new(k, m).unwrap();
let full = encoded(&code, &data_shards(&mut rng, k, 4));
for _ in 0..6 {
let size = 1 + rng.below(m);
check_recovers(&code, &full, &rng.subset(k + m, size));
}
check_refuses(&code, &full, &rng.subset(k + m, m + 1));
check_refuses(&code, &full, &(0..k + m).collect::<Vec<_>>());
}
}
#[test]
fn explicit_matrix_sweep() {
// The independent Cauchy construction through the crate's decoder, every k for a few m.
let mut rng = SeqRng::new(6);
for m in [1usize, 2, 5] {
for k in (1..=(MAX_SHARDS - m)).step_by(7) {
let matrix = gf::cauchy(m, k);
let code = ReedSolomon::with_parity_matrix(k, m, &matrix).unwrap();
let data = data_shards(&mut rng, k, 2);
let mut full = data.clone();
full.extend(gf::encode(&matrix, &data, m));
check_recovers(&code, &full, &rng.subset(k + m, m));
check_refuses(&code, &full, &rng.subset(k + m, m + 1));
}
}
}
proptest! {
#![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })]
#[test]
fn random_codes_and_patterns(k in 1usize..40, m in 1usize..12, len in 1usize..48, seed in any::<u64>(), lost_count in 0usize..16) {
let mut rng = SeqRng::new(seed);
let code = ReedSolomon::new(k, m).map_err(|e| TestCaseError::fail(format!("{e:?}")))?;
let full = encoded(&code, &data_shards(&mut rng, k, len));
let lost = rng.subset(k + m, lost_count.min(k + m));
let mut s = erase(&full, &lost);
let r = code.reconstruct(&mut s);
if lost.len() <= m {
prop_assert!(r.is_ok(), "{:?}", r);
for (got, want) in s.iter().zip(&full) {
prop_assert_eq!(got.as_deref(), Some(want.as_slice()));
}
} else {
prop_assert!(matches!(r, Err(Error::Truncated { .. })), "{:?}", r);
}
}
/// Corrupted (not erased) input never panics; reconstruction only fills the gaps.
#[test]
fn hostile_shards_never_panic(k in 1usize..10, m in 1usize..5, shards in proptest::collection::vec(proptest::option::of(proptest::collection::vec(any::<u8>(), 0..8)), 0..16)) {
let code = ReedSolomon::new(k, m).map_err(|e| TestCaseError::fail(format!("{e:?}")))?;
let mut s = shards.clone();
if code.reconstruct(&mut s).is_ok() {
prop_assert_eq!(s.len(), k + m);
for (before, after) in shards.iter().zip(&s) {
prop_assert!(after.is_some());
if let Some(b) = before {
prop_assert_eq!(Some(b), after.as_ref(), "present shards are never changed");
}
}
}
let mut v: Vec<Vec<u8>> = shards.into_iter().flatten().collect();
let _ = code.encode(&mut v);
}
}
+46
View File
@@ -0,0 +1,46 @@
# Generated by tools/vectors/gen_vectors.py. TEST-ONLY values and keys, made for DomiStream's tests.
# Never a real host's or client's key. Do not edit by hand: change the script and run it again.
# Audio payloads (PROTOCOL.md 6.3): AES-128-CBC + PKCS#7 by openssl
key = d05ec7c0d6467eb59891afa2d5bac8cd
# a_0
a_0_rikeyid = 00000000
a_0_sequence = 0000
a_0_iv = 00000000000000000000000000000000
a_0_plain = e2b07b75e63ca4ee1066e8c35f04cd3d6c0e3b49
a_0_cipher = bcb3ba283cbd9e6e21a85cb7c82a6b0b2b5ba88448b27b81b3b38d0da5873ee6
# a_1
a_1_rikeyid = 01020304
a_1_sequence = 0001
a_1_iv = 01020305000000000000000000000000
a_1_plain = 1ef35c80a79a71277c80985c68e71c17a68061f9
a_1_cipher = 8da792c5451bb13afad0326493d01dc0e1e86619675dcb93112c7fd03bb1f4e3
# a_ffff
a_ffff_rikeyid = 00000010
a_ffff_sequence = ffff
a_ffff_iv = 0001000f000000000000000000000000
a_ffff_plain = 8f86081f436a725c6e3538471be3a0e73fbd581c2254a0326de14ea410c5aed34a
a_ffff_cipher = d8d61d717b41e9fac495efa94161a5f2b9b834ad17a6cc29cd31c61ea48b123f8f2e148a245387e0fb8e44fdab45a3e6
# a_wrap
a_wrap_rikeyid = fffffffe
a_wrap_sequence = 0005
a_wrap_iv = 00000003000000000000000000000000
a_wrap_plain = 5f2be5a92e6267e05e915bbdd2e154f8
a_wrap_cipher = f66ad3bd1328dc4415f4437f9c7d4140514a24a63f6167b0e0d93e3e25d10b13
# a_exact_block
a_exact_block_rikeyid = 00000007
a_exact_block_sequence = 0064
a_exact_block_iv = 0000006b000000000000000000000000
a_exact_block_plain = d3965032409e8fbc2767e9e3209b153a363ad6d3c88c3d50b4625db697d421f4
a_exact_block_cipher = 77b8a7998781a734cfe433ad4c1384fa8656d619124824ef58a3a793a2761f9451f10846b539e9250f82e7dce83905f2
# a_one_byte
a_one_byte_rikeyid = 00000007
a_one_byte_sequence = 0065
a_one_byte_iv = 0000006c000000000000000000000000
a_one_byte_plain = 4a
a_one_byte_cipher = 13736f9bfb2042185802224de780c210
+74
View File
@@ -0,0 +1,74 @@
# Generated by tools/vectors/gen_vectors.py. TEST-ONLY values and keys, made for DomiStream's tests.
# Never a real host's or client's key. Do not edit by hand: change the script and run it again.
# Control frames (PROTOCOL.md 3.2): AES-128-GCM by .NET AesGcm
key = f5a83e5684dabb0e7c674717cd69805e
# c_ping_0
c_ping_0_sequence = 00000000
c_ping_0_direction = C
c_ping_0_nonce = 000000000000000000004343
c_ping_0_plain = 00020000
c_ping_0_frame = 0100180000000000bc758312dd6af89c112a8e1671c57118a0a42167
# c_input_1
c_input_1_sequence = 00000001
c_input_1_direction = C
c_input_1_nonce = 010000000000000000004343
c_input_1_plain = 06020c000000000807000000ffff0000
c_input_1_frame = 0100240001000000945d76e7f2792e2e1df2d0b8c98a09366e3234ba5ba2b1fd3ea3b339ec5f6b17
# c_ping_ffff
c_ping_ffff_sequence = 0000ffff
c_ping_ffff_direction = C
c_ping_ffff_nonce = ffff00000000000000004343
c_ping_ffff_plain = 00020000
c_ping_ffff_frame = 01001800ffff000006c5df5c8000b8dff6b6c6f5f60c7fb6417d8c2f
# c_ping_10000
c_ping_10000_sequence = 00010000
c_ping_10000_direction = C
c_ping_10000_nonce = 000001000000000000004343
c_ping_10000_plain = 00020000
c_ping_10000_frame = 01001800000001004f12b2df608fadbc587f1228f4e01e78714eaa59
# c_ping_fffffffe
c_ping_fffffffe_sequence = fffffffe
c_ping_fffffffe_direction = C
c_ping_fffffffe_nonce = feffffff0000000000004343
c_ping_fffffffe_plain = 00020000
c_ping_fffffffe_frame = 01001800feffffffba40d7311e6306d78196235981640015e0d2d244
# c_ping_ffffffff
c_ping_ffffffff_sequence = ffffffff
c_ping_ffffffff_direction = C
c_ping_ffffffff_nonce = ffffffff0000000000004343
c_ping_ffffffff_plain = 00020000
c_ping_ffffffff_frame = 01001800ffffffffa0beeb4b19262485ccd17558f12ecc4c0ebac660
# h_rumble_0
h_rumble_0_sequence = 00000000
h_rumble_0_direction = H
h_rumble_0_nonce = 000000000000000000004843
h_rumble_0_plain = 0b010a00000000000100ff7f0080
h_rumble_0_frame = 0100220000000000d217a640b6e026700af1848ab267de85c4a257fd47db295c80917d5fe1ba
# h_rumble_7
h_rumble_7_sequence = 00000007
h_rumble_7_direction = H
h_rumble_7_nonce = 070000000000000000004843
h_rumble_7_plain = 0b010a00000000000100ff7f0080
h_rumble_7_frame = 01002200070000003e865385552ebe576988fa1c307ad18596efab2054254f247169c571aeed
# h_termination_ffffffff
h_termination_ffffffff_sequence = ffffffff
h_termination_ffffffff_direction = H
h_termination_ffffffff_nonce = ffffffff0000000000004843
h_termination_ffffffff_plain = 0901040080030023
h_termination_ffffffff_frame = 01001c00ffffffff7f93a9df27f4323599666c9ff57ce9fdfdb84ee2a62ce07f
# h_rgb_2a
h_rgb_2a_sequence = 0000002a
h_rgb_2a_direction = H
h_rgb_2a_nonce = 2a0000000000000000004843
h_rgb_2a_plain = 0255050003001020ff
h_rgb_2a_frame = 01001d002a0000004031b5e4d1c986da2e435cbdb35b0534d5283b1ed36d35d93c
+104
View File
@@ -0,0 +1,104 @@
# Generated by tools/vectors/gen_vectors.py. TEST-ONLY values and keys, made for DomiStream's tests.
# Never a real host's or client's key. Do not edit by hand: change the script and run it again.
# Pairing (PROTOCOL.md 1.5): SHA-256 hashlib, AES-ECB + RSA openssl
# Identities (DER, hex). PEM forms: test-only-*.pem next to this file.
host_cert_der = 308202f7308201dfa003020102021453ffa5e8f3bb59f51bc3f0b303a8b242f68a9225300d06092a864886f70d01010b050030243122302006035504030c19446f6d6953747265616d20746573742d6f6e6c7920686f7374301e170d3236313132353131353734385a170d3436313132303131353734385a30243122302006035504030c19446f6d6953747265616d20746573742d6f6e6c7920686f737430820122300d06092a864886f70d01010105000382010f003082010a0282010100f34e316da47362a0548d80770f204616f955b275b9289125281eab7f3c68c9ff0ebdffd042635aa1241890821abe8c29bc658654a7a4f9be7cf4f7a0bf3a2e6946b8ee268fdf81d07fc4824c49fdcf21dcd0219a99df621392e818e8d206ae5f5cd9ece75b677c5dcb7dbed654148fa2a16d52b59f0f6deeb64914763fcd764ffc66396b389cf0a34acceb8d1ec01dc9e4c402e2e056e622868cdfa92d6e8427e181424becf1a548d0aea546ecdd07bfb666a3bfe6f2174d106bffe0763d59bcbdbae2325a05437a6d37ba4c7d7fba6673e857ef992ac1435814b60bcbf117661b628cc55ebb9a989d211032e04ec8629d3b6e4b3fcfaa2f0214972e6da19f0f0203010001a321301f301d0603551d0e04160414df2bf26edc1b25c936cf0d8b36221c7358e7196a300d06092a864886f70d01010b0500038201010016068c20e1c05101f15aac904a4c63a885a8a1a196a8599e09a9d19cbd9b4c2cf55b6658f87cb3d176b0d79496be59ac9410fff55252d720452fb7a8f013153a4f30570dabbb3abe6f72fa8962c339d02a0211cb224520413be706cbe5d45fcc4d15db36ea04c3efbcde527418d20fbfe37a2272d72cf3ca67a430c5be66b9a204e4ebe2146aad59568d25a910eebbf926147a958fec9dcb516392218d63bb020ff56555cee446e48b7123c36ca860b7ace554d82c63a0561b0f46121f534b656c57b11d54e2061ee71fb1fd2a275f7bcf0c9de411fe71fb094d9625bf1ed7a8c3f89a1bd6843fd898cad82f2135a2c41a8d01eec80ca98fa89442e4d119aeaf
host_cert_signature = 16068c20e1c05101f15aac904a4c63a885a8a1a196a8599e09a9d19cbd9b4c2cf55b6658f87cb3d176b0d79496be59ac9410fff55252d720452fb7a8f013153a4f30570dabbb3abe6f72fa8962c339d02a0211cb224520413be706cbe5d45fcc4d15db36ea04c3efbcde527418d20fbfe37a2272d72cf3ca67a430c5be66b9a204e4ebe2146aad59568d25a910eebbf926147a958fec9dcb516392218d63bb020ff56555cee446e48b7123c36ca860b7ace554d82c63a0561b0f46121f534b656c57b11d54e2061ee71fb1fd2a275f7bcf0c9de411fe71fb094d9625bf1ed7a8c3f89a1bd6843fd898cad82f2135a2c41a8d01eec80ca98fa89442e4d119aeaf
client_cert_der = 308202fb308201e3a00302010202146ae17755afe25dccd90323fa8f53b1821c360779300d06092a864886f70d01010b050030263124302206035504030c1b446f6d6953747265616d20746573742d6f6e6c7920636c69656e74301e170d3236313132353131353734385a170d3436313132303131353734385a30263124302206035504030c1b446f6d6953747265616d20746573742d6f6e6c7920636c69656e7430820122300d06092a864886f70d01010105000382010f003082010a028201010094a302935bdedd0ed7824d746e28bea961712819f8cc1f4d8bb8b4bd9c6e620beb707f10da164cb295fef6b5cdcd03787f3b37de8e5c302be7b7605b5d92ea7adeaec6a593c9fb5804e25f66d7d67e2b59867105806ef7dc3280ca0a279ef1e86eaf41e959e6a5541d63ad33e4274264d32b66943c213cdb08f3ae05732e82e19ea4666be8219f17e7cf5d4b187bfdb21bd8d7d0819f3f510561514abe2ec5a1efdec85cccb5dc51385c8a8929c4a782d9792e01ddaa94b5f79d012af8aaf00e1f99acaefd671f91b11f3f6e83a623482a83147d6da18b0d6e4ed93f99b43e7ecf9e1b66ef6bca52b13f6eae3378fc683fa73bbe55fc141352e94a05b277bacf0203010001a321301f301d0603551d0e0416041440ef12a47352cc507a4a0d9d1e046076d27c6315300d06092a864886f70d01010b050003820101003fa87ccd4d90d25fcc44cf1ab755b436b506a09dc49faef6d051ea770cad2319687f86012d074aabeaf07e9aadaccf9605517f8af94ec0f081b526a25ba18db15c589c4f6fcb9716bb10c1f27ff29a732042de321305f56833fa329e351434607ac1943a00b0497f7bb06cc9cceccfdf6c311e9924183c211e2bf43444239995a9d93227d54af9468c8445d144ff2017d6e699c3ad0b80af7117d0914c2d51d0b282cc7bd8dade8df1912fa7594dae43b527b8dd34d2c4d74b93dc780e24c0d6e0989502903ef7710265c8b6e978babaf9a355067973a8c3b79aa491995384f60d426e9c67bfbec890610d2392d8b0f5664e30e7bc2304ff1d3a3b055f591c44
client_key_pkcs8_der = 308204bd020100300d06092a864886f70d0101010500048204a7308204a3020100028201010094a302935bdedd0ed7824d746e28bea961712819f8cc1f4d8bb8b4bd9c6e620beb707f10da164cb295fef6b5cdcd03787f3b37de8e5c302be7b7605b5d92ea7adeaec6a593c9fb5804e25f66d7d67e2b59867105806ef7dc3280ca0a279ef1e86eaf41e959e6a5541d63ad33e4274264d32b66943c213cdb08f3ae05732e82e19ea4666be8219f17e7cf5d4b187bfdb21bd8d7d0819f3f510561514abe2ec5a1efdec85cccb5dc51385c8a8929c4a782d9792e01ddaa94b5f79d012af8aaf00e1f99acaefd671f91b11f3f6e83a623482a83147d6da18b0d6e4ed93f99b43e7ecf9e1b66ef6bca52b13f6eae3378fc683fa73bbe55fc141352e94a05b277bacf0203010001028201000fc252c115f204a510b3678beb2c15bef6ae5d2e97c2e8a4bba62b3f9948d8cb63bc8b3459b31891acb69a28bf77b7a0fc78665d89e17b58045adc74037152bc11451d99ab9834366a5a27fc4af11a72752cfc69b56ace8bc1ad06fed9a1900b7144d2abaf94f53d7c5a37a07355b843e161ce1ff45a1fce275e52ba903243bd07b564065e2dbc9b5676b996013e486b7bfb1d186b6c1bda781d0279d8cecafb8e99e76fc7a26cee330d9662d4a89ea60f3f3caa3caede3d5a0cf0d561a1f6ffca1bf73607247aa5d316bfb8e9bda82974fb61a1d3efcf97d590b684c6032ae9141e81b17c50ae69990e6d39be5133fc8d86d76a937014cda22442e30d1608c902818100d04c3e3ce5acb9969cb6efaf092773a4ba19aa034c838b9734d1932c4a5b61459764f527a57dd03dff9f9dae75b69763a0775092f63ce49f65b2e24fc9c27705104bab333ebfbb55c39220de0b5543cc79e8bfd753bb52ed632c8001f5da0056554963406952297dfca5fa78a32db701a44f3701ba225c331e49d185a8aba35902818100b6ad0d4772743453a94ca1d34b05db2b697f9f70e5e09d6eea4740745bd15629d992c8cfafb6784228d92aced6a2288f72e03b249de31222e6c9f16174f84143d1ce21d4d11c985f99e5ce639d9911c4da8dd184cb03b12f2957e0ac9bc48ba0f858f68fdb2e8271a7d52594c3575cd774712a648f85571073ec1566997ad267028180269006f1b53f9df8413928f489c851038d24953219273d5f97fab8b97966a38283bdc0193fed23f16672c1797bf77add89e6acf718393bc63ac8bc57332e1a64c89889b06a0c8afd1cc0dfeedbc0445605b7ce5469ff032249bb0253da952a7cd13b4df1adcdf53a8adc9b9b5bf269b017204739bda100dac1dfbeb774fb99b9028181009274f5c38578b3072c21db502ac2fc2fb6fa721b32c23d96525063d5a65394302356f296c83a93f9ff03f5b53511775162f971916ee0418727df5a1e17887dd2e0dfd1f1ece16f2c9e97473c487b136aef0a6aa37b9c6f2eef879c02e733d1fa7181e9d3f61738cfe48e17fe480abfcda176a5555057c830d1afc28caa9a751b0281805304170f6fc7b08f45c848c534527fc4b210990589b060c02840b5c79d57589d83ef8f0d2c4551798346eda321bb3b6e0facf3f6d9e99e4dee87f35b9460bb4df7179713a3165b996980a1aaddf95146454841dc4fa9a08adbe417c47893270dd2af3abcad97e5a91ccf4e921fbd97928fadbeed4a86f78b88590bfa557de919
client_cert_signature = 3fa87ccd4d90d25fcc44cf1ab755b436b506a09dc49faef6d051ea770cad2319687f86012d074aabeaf07e9aadaccf9605517f8af94ec0f081b526a25ba18db15c589c4f6fcb9716bb10c1f27ff29a732042de321305f56833fa329e351434607ac1943a00b0497f7bb06cc9cceccfdf6c311e9924183c211e2bf43444239995a9d93227d54af9468c8445d144ff2017d6e699c3ad0b80af7117d0914c2d51d0b282cc7bd8dade8df1912fa7594dae43b527b8dd34d2c4d74b93dc780e24c0d6e0989502903ef7710265c8b6e978babaf9a355067973a8c3b79aa491995384f60d426e9c67bfbec890610d2392d8b0f5664e30e7bc2304ff1d3a3b055f591c44
rogue_cert_der = 308202f9308201e1a00302010202140413e99f50d883e0d804fec044ee90b64bf4f9a3300d06092a864886f70d01010b050030253123302106035504030c1a446f6d6953747265616d20746573742d6f6e6c7920726f677565301e170d3236313132353131353734385a170d3436313132303131353734385a30253123302106035504030c1a446f6d6953747265616d20746573742d6f6e6c7920726f67756530820122300d06092a864886f70d01010105000382010f003082010a0282010100bd30b5cd7eb6c6a2ea7b4f2786e69e1c68ea221bbae80c0e9778f50e3b93085da0f1fa1e461adde49d5af92c112d01a4ec4030f4ee699a00f98564b696a5826fa0563cef27b36af7cfaef35aecdaa698effce30e2065862bc428e238915f1cee5ea8caab79935fac83f3f3bbc7fb3e1fcbd0e58fa898bf3135009b924d5d5542f6acb40852066e0b9a5690426ec7ebde95e023c0aee16b7f02b9fdeadcb52a9cb4780290d38be12d65ee1d2b154c047ae1d9bda1e56afa62849c14143e11190b8f49443cde18365fea050688465b8a9af8c4eceb72970c753021c3ebcc992458aba8a6fd748c85c9df047119d2cebac0e2821c8786d2878a559190f46249f8610203010001a321301f301d0603551d0e04160414db730a3dc30b6edaaeec268b6166bb35e4fdfd34300d06092a864886f70d01010b050003820101009e97849350ca8ca8607aeb832f572b2a3df07ab9e7b310be0b6974086f11d93e64610d03d1f131548a22e8ed70d30a6f1bc67c56de7f5109da8bfb4356a294a43bc0edd63a571ecd0f7b7334fd31f89e4f739c7fdc79f98920ce10319cadaea3499cb4506398331136f5c3d223b43061d4302fb7410ab0260cd95623b6b364d29811104b662dee30892ef2a7f1d6b747aa2a9110b90f790bf5732c0b0d75f38a2aaf3cfe50634778b6ec788e639b9a9f00c5206531991888797279821656f3475b5d43364861a12a56151a5aa143cbbe983a1db6ba093df445c93e1177654a3abb88a7affa805d2dc5f3b33eb0ff9448f04e565e91191431cdbd0d15346d0b2d
rogue_key_pkcs8_der = 308204bd020100300d06092a864886f70d0101010500048204a7308204a30201000282010100bd30b5cd7eb6c6a2ea7b4f2786e69e1c68ea221bbae80c0e9778f50e3b93085da0f1fa1e461adde49d5af92c112d01a4ec4030f4ee699a00f98564b696a5826fa0563cef27b36af7cfaef35aecdaa698effce30e2065862bc428e238915f1cee5ea8caab79935fac83f3f3bbc7fb3e1fcbd0e58fa898bf3135009b924d5d5542f6acb40852066e0b9a5690426ec7ebde95e023c0aee16b7f02b9fdeadcb52a9cb4780290d38be12d65ee1d2b154c047ae1d9bda1e56afa62849c14143e11190b8f49443cde18365fea050688465b8a9af8c4eceb72970c753021c3ebcc992458aba8a6fd748c85c9df047119d2cebac0e2821c8786d2878a559190f46249f861020301000102820100123f7cc5a7a37708d73f920cb0b715488db90995ada33ca87aa53cd3c4dcc3798e70d08c737c1b6b75df04ba22a4f9ebdfaab85e2391d57c231521f7f7935abfac122d59eef5200beb8107317db7804aaf992f88590919d6265b4028af22e2ae3e3c9f21c77df6c433cd07b514ceafb90ee665020483c92b349ecca2a1aa2f3335bf1a4dcd1d441300ae17ea1766100c70c0c9424a1f4a0a7fc370d8f59ae035ce06346b3d7ee8dba5b4d6f24a0e2fb6fa0a67b801dd444377604df1685014e08d0ef969ef4ffb5c9d54226e724205b230572e883828aaab058036257600c5a79488d895b8ef642c83f4568212ebc1989f807bdd5a02d72dbf25f0d8116c28f102818100f9b5fe0019425036bd8df96f9294db7796fe9267f8c42ec1cca243dd94d734fe72c71e44ebb42d3b9f3fd015833ee8f163db04b26efccc3e0eddd81b0ee3d75d25380991129600de20b8d9f74986ea6e87ab6a1eda44b2814c792ee0f9ef41a60c98afe0064f2af3a38550274f95901039cec357b641b4b6818825766f8fc35902818100c1f48311a17b5d212e6c9d17ead7ef534027bda0dd2bf111029f2b3d14af0f4c03e910b48428f7fd4b96356334a9be7ee6d1cf33f121138e53b6ab1cc835d30b6e7341a924adde886e3255f3ce5463bdd6e325a835ac220eb13d225aab5eed48ae2177424db46cf4183fadf21ee0170b0c19709f28e517c5b62435b850d0e44902818100c13a63ff7d8c43f7e7fc69cd3d7734d0b8a5eb72cb1c3c3638fc4359be683d98bc067ad4c8339760f09cf78efe0d7b41f78c2e7948cb13dcddb22b1cdd0bcfc6431bb6c36cc7688a7a75b02cdbd7aba6b6131dbe1c1656af191719007c46f8dcde1874d7fce9dc09c63a4dc8ed9b856c18df776773202b0fa2f25052f287239902818078e13832ebcea3fb4320c4439cc4d9ceabe458c6023219bb3d441041b03b6eb0349bb4229d5f9f37493da3a661b30d1bb025c11aa144b918724a1d99019ab21ea4c6c67c7174bf858e10670b5d63b10a26fc4882ee788a7d57af3f52fd0d5b9b799337eda5da3631674f80ccaebb81010c986a5d77b2583f8bc64388cd2d73a902818057da5867c5776dcbd4c255290dc2f603b7672fe340f1739855df3f332d3287e14aeaad4585a7374df7e46962484a2824358996fecbdd028b8e0bdb0244fb5b0ebe7da580e08e928e40f43dc8742a946ec69455c497e36142334889c120372997fc4d275e444bcff13ea4b5585b8158e02a8baa48ace594227a17a2804060e802
# Session A: the client's randomness (rng stream = salt || client_challenge || client_secret)
pin = 4071
wrong_pin = 4072
salt = 0675c95e8a7e4c7acc568797397ed89e
client_challenge = d2b5889e7e822d424f97fba908b48fdd
client_secret = 7fd88cf5f73f75b9cb3cebd9265b394d
# Host values
server_challenge = 9b316d43ef0d7426e9c9d05aed472d9d
server_secret = a0433d1811811ebe4a616282e92d11cf
# Derived, step by step
key = 3d47dce112b5a7f2b2fcb584bc69a94d
step2_clientchallenge = aa8551207cc0c95332c3e1915e8f11ee
host_proof = dc4ab364cd3845b2e9c138c5583ca5f23a117d1fd57c27c9e93451841e53754c
step2_challengeresponse = 25e0d2926cdc57f171461f50e8345225a449a3382b015f052829c02ed0b73fd26481419e3e79b09c09f5d826abc522c5
client_proof = 72ce1283ca9781fb356a2f74009659803168351407dc80dfd376847b15921df5
step3_serverchallengeresp = 365a519f4ea9de5f91f7297ac15b707d5cda97deaa5b90060dd6e00b4057251a
server_secret_signature = 530848b0bcb5764e33796bbd3ecc64a80ff9b6668163b7e8db11dc31527fd06a4e932b544e5899ac20a80a9c0eda973dc0b3fdce20d0fba9d1687c53a5f548b80e1dfedcc8af569f29515a4c4ceacb39b06728eb7247ebbac735393120ddb9dc4822724538944510c9a27db64558121223ae88420053a319fd8b86a710b8548840f7078fe7d3931a8e7865fa6434439ae105a2fb837e192f99c0f4ae2462462724f9bee1d8070972fe4d5a5985feece913f944c7170cf6e0908f88a34e12cb4e441e8eda2cb7bb93354f4facdfed60467a9695c502bcbe6c25b514ba10d625e96586a28dccb3d066152b2147aed6f57c8676d2d6f36014f77e8e64ecb74a2b79
step3_pairingsecret = a0433d1811811ebe4a616282e92d11cf530848b0bcb5764e33796bbd3ecc64a80ff9b6668163b7e8db11dc31527fd06a4e932b544e5899ac20a80a9c0eda973dc0b3fdce20d0fba9d1687c53a5f548b80e1dfedcc8af569f29515a4c4ceacb39b06728eb7247ebbac735393120ddb9dc4822724538944510c9a27db64558121223ae88420053a319fd8b86a710b8548840f7078fe7d3931a8e7865fa6434439ae105a2fb837e192f99c0f4ae2462462724f9bee1d8070972fe4d5a5985feece913f944c7170cf6e0908f88a34e12cb4e441e8eda2cb7bb93354f4facdfed60467a9695c502bcbe6c25b514ba10d625e96586a28dccb3d066152b2147aed6f57c8676d2d6f36014f77e8e64ecb74a2b79
client_secret_signature = 67c7de68387431676d228bc37b37575c798dc530132100f4ffc3774c719c8adc2e55dc55065c56f9518f19bbc588c3f0d374a560dfd8d9ebac856c3402ecf631926fecffe4a9a78eb2ebb8aeb0c4de07710371534e31948adc324c59012397e0d8203444cd32213cdd0030302d97ed19a64cc5bf624fdfd5d63617b98dbbc39c18c27da15eb7da52f228f27c5613404ac1ca5438f55c657abec03a2a1d231121e582a269488422534a888cfe763a7ceaeb39b63d4e60a5c266060b7ca6770d0ab2e03c8282f9a0eabf6c62d4b59ad17fb90a2992f919d347c86842c5d95e3a221164714a9838a347599ce4555e34b6d7d29c20ec86d56adba11670da841ab784
step4_clientpairingsecret = 7fd88cf5f73f75b9cb3cebd9265b394d67c7de68387431676d228bc37b37575c798dc530132100f4ffc3774c719c8adc2e55dc55065c56f9518f19bbc588c3f0d374a560dfd8d9ebac856c3402ecf631926fecffe4a9a78eb2ebb8aeb0c4de07710371534e31948adc324c59012397e0d8203444cd32213cdd0030302d97ed19a64cc5bf624fdfd5d63617b98dbbc39c18c27da15eb7da52f228f27c5613404ac1ca5438f55c657abec03a2a1d231121e582a269488422534a888cfe763a7ceaeb39b63d4e60a5c266060b7ca6770d0ab2e03c8282f9a0eabf6c62d4b59ad17fb90a2992f919d347c86842c5d95e3a221164714a9838a347599ce4555e34b6d7d29c20ec86d56adba11670da841ab784
# Hostile host answers
step2_challengeresponse_wrong_pin = 75cd553a5eac50deb0cd3b3b203dc3ed16532f8401d157d331b4e00497edb4545e8c44238479d7c9446f79d866fc68c5
step2_challengeresponse_wrong_hash = 46a43219effaf5f645c5950e990647bc72c5a4691db568b39b719c20c463e31b6481419e3e79b09c09f5d826abc522c5
step2_challengeresponse_wrong_cert = 9d106087e89ef627ed88e13503a36079e7407bddc7a8e61988a546e8eab057636481419e3e79b09c09f5d826abc522c5
step3_pairingsecret_rogue_signature = a0433d1811811ebe4a616282e92d11cf246a7dee0b2b67ac82623108496917eeeb0bf4c1688def6a617f736763050739a078593782129ef9b0be272964eb24696e7dd43fbdf2bfea618f303f8d8678e10bcc82d6207553f2c67be08f75f202152f72444308b2b63e79cbb0c15ded19b2d21f808b0c1d7dd4b8384807ae360e16840d5a86a8a135e46fa9f20cee949ab29b8cc49944041ce14f3845c599a205af416414662e19fbe41090d913b5969b2a6fc8675004c02075339acc498eef1c1acbb0e7d88f119c6ee7e3984c79ac1594f88c09063395e324320053797b3a419c1570505e02502a3b244462f73f45736dfd57cd2af2ba4c0855bb6f335abf09bf0b65e9a9eecd56756c1b83cc54a8e3ee
# Session B: different randomness, for replaying session A's answers
salt_b = da0bbbd95453b0a976ae6630947d0a9d
client_challenge_b = f3af034962a9ab8b8ba94b522efeb099
client_secret_b = c27871ab54ea3f790a9532c003b78522
# ClientIdentity::sign over a fixed input (PKCS#1 v1.5 is deterministic)
sign_data = 446f6d6953747265616d20746573742d6f6e6c79207369676e696e6720696e707574
sign_data_client_signature = 7fd8b58d941c069341c02dc4ecde5e98cdc3d4bb7d117e3e77c116fb2fe69853454f820361f8309b04397155b928e44fd4bae6308832627e48be744bd42a4ee46deb8b3a459672a10e96fa58e7debf35fc86694669570483b8fbe04153058336b50b42fba55389ebbb07e0213ccb2606f2c0d12e4722fa299cc16208643ec1bc3d99d6ec79a51c2c70b754ed72e49b85ada460140985bf21d2ba621b14e7341574fab19d1b7d13a2330046f18a5e008dff10d2260d4c615db4bfd59f9795ac3ed24c9fa7231850f488c32a654d3614decf315bbc33e8a6a127bb5b1c0eb406d24585bc8fd7a37e29637cd847c1857454949017542f986026784aa5debd7b9285
# derive_key: SHA-256(salt || pin)[0..16]
derive_0_salt = f8b30d70e5b0008c08f810a5a8fc5df9
derive_0_pin = 0000
derive_0_key = b78936fa27b843afc14734e4048662ea
derive_1_salt = e7a045e0c6d09c8c974cdeaaf13af7df
derive_1_pin = 9999
derive_1_key = 7b3e5e69c7dcc9836ce8277767618a35
derive_2_salt = 9d75e745c278f4b605e582324a143a4c
derive_2_pin = 1234
derive_2_key = 2cafd262f85bdebbe1d3b9a5d718d2a5
derive_3_salt = fe703787a74ae00919c71af343882078
derive_3_pin = 4071
derive_3_key = 10a0275e93fa660865bc4d2185f701d3
# ecb: AES-128-ECB without padding
ecb_1_key = 47f07b74b1b7d34a6942bcd0c8c8d226
ecb_1_plain = 0bfb32813994563998633410daa23888
ecb_1_cipher = c640c02f95da13177fe0a9ab62c8a9a2
ecb_2_key = bba955b56d6b85f283f665f504465afe
ecb_2_plain = 612da985f348b205e410a05158f3bc3c7e4204cb09ef880749a0ff7758e88b6c
ecb_2_cipher = 25fac3e4d328d4eada87c90fcfabf0b9cd840b467ebfdcd0257b37e9a8fc0488
ecb_3_key = 650d6d2059045c6751dda639064eba49
ecb_3_plain = 9d0db75b8d10d73d581ae77b77eb287d297352212ca9c54632a3d462e77733849234e26b2bff700ab70c24f4d6889d09
ecb_3_cipher = 5dba0bdef7130719252bfb27f78cc36999bf162b8ab371a7bb13e4213ea1cd882b654936605b2b1075de8ab52d9c3084
ecb_4_key = cce40b2793a8875f3e87cbbdeba015c7
ecb_4_plain = 53f9b09390f41b244bbde180f5e7bf2f2c762aed0d4b47d75da1c44af32af83cf48a88418d4245b28d6802576b297e2f4636cc48cf325a2bfb36ef11dd2a94a5
ecb_4_cipher = 5c3091ff1960905cadcd7131e59567885f51f5b3654d4e1ba11f2dd3cb0515deec7e9ea9d2afbe40c8d5c7b5dc8b269f34d014763683ca9db600c98405e6f8e1
# proof_hash: SHA-256(challenge || signature || secret)
proof_0_challenge = abcad06bd4e492689cd5926df9100c27
proof_0_signature = -
proof_0_secret = 6ee4f062874e4c848d94f63d04160de7
proof_0_hash = 73ea89c8b23f1b28c9c55ae2e56e5f3898784d8c4682758eab6e36e6843f9374
proof_1_challenge = d115b311d27bc924561a6ef9b764c2fd
proof_1_signature = 07
proof_1_secret = a9772fa047ca1a8d23484457108d4516
proof_1_hash = 9aa6d607ded2d6fc7e4533d75cbb6208c6e1df818b8129a5e0bc997942c46845
proof_2_challenge = abf024597adc7b52fb17a9d8b7df5813
proof_2_signature = 838237fa0fca3fab1fd94adbadfe0de900a4924f1cfe101012d1251b48fab489c204c48e68084020fde01500c81bd4e971208b6a16b71d6e5b0a5d7d243a4a8caa59ce1623a0f7a43572849684a5cc9c356301c076a68e947db827d8449179362f67895d55ebb2764209c5b72772bc04a5032f3ca705249dada034ba6ef20e6c
proof_2_secret = e583442683d1be3b218e9c510a965500
proof_2_hash = 508761b918a82d13a90a2e400bbc0d6dc2cfaea457979a04a6b64faaf2101372
proof_3_challenge = 4076d9e84a76edda18afd13040dba441
proof_3_signature = ad7ca0c5cc82d13fa18cf31f153eda0a48fb9c87ae2efac89ee05fa3dd8cf35e026650404f3c2369c75636d8d7018f6bcbfaaaa7bc5f90b3ef5831ce0d9f31899c2302c0924d05a52524b43350f2ab3de7b4d2165c8dc629c1eaea8203fd975775d4ee2d82807383c038f273fc2d05de8804bf3f4d91412ad75d82bb981b652b8a4110f6789d63a35550f76884b8d89b3ebc2a682367027afca0dd3fd6aeb49f387baa4336f22481f4f7dbad9314a3d0c4209bd1eda5b3f72799f7e718f34a157799655d4d9cb5f4da8b8c2ed81b644fdec096670e46601f90b8ee28f22407ff3ca7c0426f55747412b92a07449eadb9d09a27f3355ca72789f790a3e5156e51
proof_3_secret = 51927fba549d832e503b2fe7e3334906
proof_3_hash = c3c9b78dd993581e9bb19ad496641ba817f67812b7f9e1ea77ec8e3023f3c980
proof_4_challenge = e20ad31b7f61b888d33f9a81b0bb5173
proof_4_signature = 05721bf7769763ceffaf7c3ddf001fe527a113e204dc499c30490efa021eb7ca0d6775bbdb1b43d606f4aae4478ffa8cc0ced04d87e337d219604dae2698cb569b954f4c81f8b1f10f3329c44c283673e3818fbce574bd0a0ebaab50630818d00c829eb4923795cd7ef1dfad3c8a20e263fa054d15655041cb5c5c9d168ec89d394eddf22b2fe3db603b83bdaac074448f0d96036b99bb88e0d3d4c6a252f4390c4d3bcca032105232311b89127eef24f6e3244c92d352bb68ddd21f89faa19380f67a1206c59fd15ec29f855971c3185fcdb7d2a6bdd1eaaa10cd9e6862eeedca09a2c34705fbe9519efda9e8f18e504a1d5bfd70e48ceffdd6feef8b4f05a43f86862afa6da3b8a1d55251533d32db1e123b969ecc821ab1e555362b33cd9bd587079b28b2ae0c8608832d1b375e74f2d83baa0e9e9448cd37b9d4211505b38458a8605e9e2ca56c45b095642325caf2a41881741b2c5a083f6ebb3a2e00b4b4c01e807f82a3fe70030a9da9debf1d176a802ed19aa0241c67d0741fe48dc85dd8baf42263a02d9d10156d2b058b5059d301ed5456bb0e2df9c5862dc7580e567bcbad6fca59837e66e15cb8941ccc423e810cb598982fef3ac71c75f51586ed4bd178f96ac144d64086b35ffa66334b2898fe326bcf97bc7ea7618daea38a00bf8df54e452da6bf60f3e94dcf41e73744041bf698c2c6c0ac26b8f4ac63db
proof_4_secret = 768514c2db82b020ffd805b94b829af9
proof_4_hash = 8c0f55414f6ee38be15638cee5e8058febd618a90e6d7492460d962e0567f8e9
proof_5_challenge = c033776eddbebfce3d438548b70783cf
proof_5_signature = 47a713bf31800d6c87996396d2a30efc61e85acc7814115e41364f2b3c30b6862a4da3258155eda966e9f5d2dda0e101a9b32bd9748494d6c83badc07c8b4387322de01c2e2544da5c62c9db8de7288734092672a3f6b53cf7998dc9e3ed19cf4123b677052107c4ac6c828efe5c43607677a1a557ca10e50e5a49cdb6a12738c1ac82bbcaf37d94fe9e23ba4ea2c61c9f6b0cba8be53d96b51bf1a45fd9f429e53bcc59d36e5ed2b0986b29814fcfe2ad81b7f7cbb814d0a6be50619ef3d0ad06b4bf0ceaf1d28b6022e0a8327b425f803ed5688f248faf527c9de2ca820aca1698e393ac4e9b63a743f0a600fe4c47dc39d62bb7493cf5441e0a727926117cbc56765c30a183959d02070cf0654bf4ce50ea1f227f03ab78663212c7a7069700dbaac44ecac8e64f00819dc5e356e3d28f26b4db128edc0bd43a131f96639283aef28ad69777f7f800b6a8cd566f7eca285e27a6a57f1193c7bbb151a908a157846d844fa95a62e99221655efc2041c2e03a290d1cbf7c42480e9dc190e173e3d06a678d0b3ddbf74907839a5cea86b6cd3ce8ec8b9325053873ca5b580e4f2706a70aec4eddd72bc1700b18486cb661abf1d6cf9200bcc0326c9cc7dcbcc82fbb76286709ef1886d649818cf24a7d8eeb7e31f5b6eebaeb253ce386f07590608bfce1ffdc7163972f6f1eed1f63c0b2a8def2e2b4a5998d3ffab67c42ab28e0889fd141032fa99758e97a871fb2d27f4e5da6e7ba2c018c79b9d4ff6ca7e5b5f433e4f2839c1dc32524ea2b11973e28540107b2d3dba3930efea47299b8188eb87c4faa4a8adbf3a5c5d8d601e0bb9f0b89ffd19a60d7f8ec1313adb84a618885a370d7a64c3bd7bffa5d7f70d97cd9c4d5b04421c239bcd798efea0e03d3916edb1de8bd6649a6bcc3e90885339cfd6b861b0470dac19508781bb01935d35649a532b74678213baae7e264c11168c393c11bc485e2d7a289905ef3c4f80184d34c6375fb22caa60e311b9d9bd1864cafddbc89038be39d5ba9816d5732ab42da5f805000069f79835acd96ea9e1b00b2b393a122a7d5a9d2a3c0ed892b050dfae37368f0123a3ffd8961054f5227976665641f41f8bd2b60187743cc3fc07505870b8024510b78970e861c79752f5711cc5e6e1b512b7ef84ff7515737c938a6d97d533bf85e6e36b2e67aaec72fa6c8410f585e72ed47df24b164a2aba65fd9c6587b075839f0fb2e8b3507d776255913d6b4ef1f0edc4d4a56fede42841e35c1838d6b2f0d9de38b1f2654b5c253a7c22fa7a08fcd109842c9a3ef1ccb3dd2980532643939e668f190f49fa51f3b49fafaa24f5645e4f4c8fe8e73e150dd88c636b23c1a125d391052d80128f6288e7f05e344d6706ddea5f228823a19bfb504fcd1da90fa82f29c6c21eb2301cd0d5bf048b588530cfeb81ee0a2aec0
proof_5_secret = c302d079cd10e6911a1ca96a15dd205e
proof_5_hash = 8db2e4a0d395918a37370efd4432132e929ad7fec0c2090d5aa0feef1b068ea1
@@ -0,0 +1,18 @@
-----BEGIN CERTIFICATE-----
MIIC+zCCAeOgAwIBAgIUauF3Va/iXczZAyP6j1Oxghw2B3kwDQYJKoZIhvcNAQEL
BQAwJjEkMCIGA1UEAwwbRG9taVN0cmVhbSB0ZXN0LW9ubHkgY2xpZW50MB4XDTI2
MTEyNTExNTc0OFoXDTQ2MTEyMDExNTc0OFowJjEkMCIGA1UEAwwbRG9taVN0cmVh
bSB0ZXN0LW9ubHkgY2xpZW50MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC
AQEAlKMCk1ve3Q7Xgk10bii+qWFxKBn4zB9Ni7i0vZxuYgvrcH8Q2hZMspX+9rXN
zQN4fzs33o5cMCvnt2BbXZLqet6uxqWTyftYBOJfZtfWfitZhnEFgG733DKAygon
nvHobq9B6VnmpVQdY60z5CdCZNMrZpQ8ITzbCPOuBXMuguGepGZr6CGfF+fPXUsY
e/2yG9jX0IGfP1EFYVFKvi7Foe/eyFzMtdxROFyKiSnEp4LZeS4B3aqUtfedASr4
qvAOH5msrv1nH5GxHz9ug6YjSCqDFH1toYsNbk7ZP5m0Pn7Pnhtm72vKUrE/bq4z
ePxoP6c7vlX8FBNS6UoFsne6zwIDAQABoyEwHzAdBgNVHQ4EFgQUQO8SpHNSzFB6
Sg2dHgRgdtJ8YxUwDQYJKoZIhvcNAQELBQADggEBAD+ofM1NkNJfzETPGrdVtDa1
BqCdxJ+u9tBR6ncMrSMZaH+GAS0HSqvq8H6arazPlgVRf4r5TsDwgbUmoluhjbFc
WJxPb8uXFrsQwfJ/8ppzIELeMhMF9Wgz+jKeNRQ0YHrBlDoAsEl/e7Bsyczsz99s
MR6ZJBg8IR4r9DREI5mVqdkyJ9VK+UaMhEXRRP8gF9bmmcOtC4CvcRfQkUwtUdCy
gsx72NrejfGRL6dZTa5DtSe43TTSxNdLk9x4DiTA1uCYlQKQPvdxAmXItul4urr5
o1UGeXOow7eapJGZU4T2DUJunGe/vsiQYQ0jktiw9WZOMOe8IwT/HTo7BV9ZHEQ=
-----END CERTIFICATE-----
@@ -0,0 +1,28 @@
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCUowKTW97dDteC
TXRuKL6pYXEoGfjMH02LuLS9nG5iC+twfxDaFkyylf72tc3NA3h/OzfejlwwK+e3
YFtdkup63q7GpZPJ+1gE4l9m19Z+K1mGcQWAbvfcMoDKCiee8ehur0HpWealVB1j
rTPkJ0Jk0ytmlDwhPNsI864Fcy6C4Z6kZmvoIZ8X589dSxh7/bIb2NfQgZ8/UQVh
UUq+LsWh797IXMy13FE4XIqJKcSngtl5LgHdqpS1950BKviq8A4fmayu/WcfkbEf
P26DpiNIKoMUfW2hiw1uTtk/mbQ+fs+eG2bva8pSsT9urjN4/Gg/pzu+VfwUE1Lp
SgWyd7rPAgMBAAECggEAD8JSwRXyBKUQs2eL6ywVvvauXS6Xwuiku6YrP5lI2Mtj
vIs0WbMYkay2mii/d7eg/HhmXYnhe1gEWtx0A3FSvBFFHZmrmDQ2alon/ErxGnJ1
LPxptWrOi8GtBv7ZoZALcUTSq6+U9T18Wjegc1W4Q+Fhzh/0Wh/OJ15SupAyQ70H
tWQGXi28m1Z2uZYBPkhre/sdGGtsG9p4HQJ52M7K+46Z52/HomzuMw2WYtSonqYP
PzyqPK7ePVoM8NVhofb/yhv3NgckeqXTFr+46b2oKXT7YaHT78+X1ZC2hMYDKukU
HoGxfFCuaZkObTm+UTP8jYbXapNwFM2iJELjDRYIyQKBgQDQTD485ay5lpy2768J
J3OkuhmqA0yDi5c00ZMsSlthRZdk9SelfdA9/5+drnW2l2Ogd1CS9jzkn2Wy4k/J
wncFEEurMz6/u1XDkiDeC1VDzHnov9dTu1LtYyyAAfXaAFZVSWNAaVIpffyl+nij
LbcBpE83AboiXDMeSdGFqKujWQKBgQC2rQ1HcnQ0U6lModNLBdsraX+fcOXgnW7q
R0B0W9FWKdmSyM+vtnhCKNkqztaiKI9y4DskneMSIubJ8WF0+EFD0c4h1NEcmF+Z
5c5jnZkRxNqN0YTLA7EvKVfgrJvEi6D4WPaP2y6CcafVJZTDV1zXdHEqZI+FVxBz
7BVmmXrSZwKBgCaQBvG1P534QTko9InIUQONJJUyGSc9X5f6uLl5ZqOCg73AGT/t
I/FmcsF5e/d63YnmrPcYOTvGOsi8VzMuGmTImImwagyK/RzA3+7bwERWBbfOVGn/
AyJJuwJT2pUqfNE7TfGtzfU6itybm1vyabAXIEc5vaEA2sHfvrd0+5m5AoGBAJJ0
9cOFeLMHLCHbUCrC/C+2+nIbMsI9llJQY9WmU5QwI1bylsg6k/n/A/W1NRF3UWL5
cZFu4EGHJ99aHheIfdLg39Hx7OFvLJ6XRzxIexNq7wpqo3ucby7vh5wC5zPR+nGB
6dP2FzjP5I4X/kgKv82hdqVVUFfIMNGvwoyqmnUbAoGAUwQXD2/HsI9FyEjFNFJ/
xLIQmQWJsGDAKEC1x51XWJ2D748NLEVReYNG7aMhuztuD6zz9tnpnk3uh/NblGC7
TfcXlxOjFluZaYChqt35UUZFSEHcT6mgitvkF8R4kycN0q86vK2X5akcz06SH72X
ko+tvu1KhveLiFkL+lV96Rk=
-----END PRIVATE KEY-----
+10
View File
@@ -0,0 +1,10 @@
-----BEGIN CERTIFICATE-----
MIIBZjCCAQ2gAwIBAgIUCcp/vRy2b7AOspBrIACXxnsnc5MwCgYIKoZIzj0EAwIw
IjEgMB4GA1UEAwwXRG9taVN0cmVhbSB0ZXN0LW9ubHkgRUMwHhcNMjYxMTI1MTE1
NzQ4WhcNNDYxMTIwMTE1NzQ4WjAiMSAwHgYDVQQDDBdEb21pU3RyZWFtIHRlc3Qt
b25seSBFQzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABNuZD4n+3lhlp9jGS7X/
4LGuHRr8UtTj2G+flfq6x7d5kDShH2oDmh4UAGdBi34QNl6FE2JGyLs4O6Vd5WBk
3NejITAfMB0GA1UdDgQWBBTfus0Yc0ctMaFMWaTFYL8qjq+dBDAKBggqhkjOPQQD
AgNHADBEAiBY7+HZrI0lMSvAh7SP+8csdHlp1htEEz1nxLRVY4KVSwIgHkV8EwkN
yC7oIz36v0nG483KpHAQ4Ej8Wu4rfXgXxpk=
-----END CERTIFICATE-----
@@ -0,0 +1,18 @@
-----BEGIN CERTIFICATE-----
MIIC9zCCAd+gAwIBAgIUU/+l6PO7WfUbw/CzA6iyQvaKkiUwDQYJKoZIhvcNAQEL
BQAwJDEiMCAGA1UEAwwZRG9taVN0cmVhbSB0ZXN0LW9ubHkgaG9zdDAeFw0yNjEx
MjUxMTU3NDhaFw00NjExMjAxMTU3NDhaMCQxIjAgBgNVBAMMGURvbWlTdHJlYW0g
dGVzdC1vbmx5IGhvc3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDz
TjFtpHNioFSNgHcPIEYW+VWydbkokSUoHqt/PGjJ/w69/9BCY1qhJBiQghq+jCm8
ZYZUp6T5vnz096C/Oi5pRrjuJo/fgdB/xIJMSf3PIdzQIZqZ32ITkugY6NIGrl9c
2eznW2d8Xct9vtZUFI+ioW1StZ8Pbe62SRR2P812T/xmOWs4nPCjSszrjR7AHcnk
xALi4FbmIoaM36ktboQn4YFCS+zxpUjQrqVG7N0Hv7Zmo7/m8hdNEGv/4HY9Wby9
uuIyWgVDem03ukx9f7pmc+hX75kqwUNYFLYLy/EXZhtijMVeu5qYnSEQMuBOyGKd
O25LP8+qLwIUly5toZ8PAgMBAAGjITAfMB0GA1UdDgQWBBTfK/Ju3BslyTbPDYs2
IhxzWOcZajANBgkqhkiG9w0BAQsFAAOCAQEAFgaMIOHAUQHxWqyQSkxjqIWooaGW
qFmeCanRnL2bTCz1W2ZY+Hyz0Xaw15SWvlmslBD/9VJS1yBFL7eo8BMVOk8wVw2r
uzq+b3L6iWLDOdAqAhHLIkUgQTvnBsvl1F/MTRXbNuoEw++83lJ0GNIPv+N6InLX
LPPKZ6Qwxb5muaIE5OviFGqtWVaNJakQ7rv5JhR6lY/snctRY5IhjWO7Ag/1ZVXO
5Ebki3Ejw2yoYLes5VTYLGOgVhsPRhIfU0tlbFexHVTiBh7nH7H9Kidfe88MneQR
/nH7CU2WJb8e16jD+Job1oQ/2JjK2C8hNaLEGo0B7sgMqY+olELk0Rmurw==
-----END CERTIFICATE-----
+28
View File
@@ -0,0 +1,28 @@
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDzTjFtpHNioFSN
gHcPIEYW+VWydbkokSUoHqt/PGjJ/w69/9BCY1qhJBiQghq+jCm8ZYZUp6T5vnz0
96C/Oi5pRrjuJo/fgdB/xIJMSf3PIdzQIZqZ32ITkugY6NIGrl9c2eznW2d8Xct9
vtZUFI+ioW1StZ8Pbe62SRR2P812T/xmOWs4nPCjSszrjR7AHcnkxALi4FbmIoaM
36ktboQn4YFCS+zxpUjQrqVG7N0Hv7Zmo7/m8hdNEGv/4HY9Wby9uuIyWgVDem03
ukx9f7pmc+hX75kqwUNYFLYLy/EXZhtijMVeu5qYnSEQMuBOyGKdO25LP8+qLwIU
ly5toZ8PAgMBAAECggEAdTyZTqauPrjY5TIgrHY1r75HD+3v4V9HEzTsGCwopiSz
mtPYKxUqx3jYKVG3x1dMiQ42kzYQpZKnLXbgyyQi1vGQDJkiPGWV7OroihAhL5y2
hMecckaUQLBKDC6rfTKqmtgbckO18tRTSG0bY3pg19GHFxKS6WFkZAuEw5Hs0/O4
M37ev3KYGhASPLXOgobfvQruQoVJg5OsX0Z6mJYXTB0iZDflUADp5QwgelcNU5ax
Ra+muHWfJFUuNn0cFH95yXT6Qprwg74f0tdY47i5RyPJQKfvY8GUG08o+ObTMK0I
y3lKMZZ27YcttNBpWmPbqipJPrcW05yUvGooKNDR8QKBgQD9vzrtuFcfIdo7TgqX
3MunamxU3JBPU5Ync439q+vsVsqwSTgmroeyMBXuLcgkxOWgvez6yx3qojJLw3LV
LZ46SInaEOG/VVfG/Hnq+QrFi5hOMEpdD12nueURRVWNoCOBHgyrS2ClGZnEEgDt
BanMGmJRSQ6+6gTyijweQq7meQKBgQD1dzqn5XL3zeJRpb7xqoXDiJByvsJErGQM
pYRF0MV7YpNjG9YUGmLLs7ACbfeXvXsoJbHg21ynOWVwEKAYuAWmlvUohz9KYA+i
eGHjTeseeb9pguib22+bWe8cxww7Lgn/hg7nO07DK4vSFePRKpR7iDDXFrLjm2vw
zuPmGC5vxwKBgDbLPKZo0Cdg4Ac+avswKqoUSSBqIJ+ApUQPp/HHVkLK2yoGJaH0
vki0KYgtSrLl8dAsMyhVBDjOnZ3OrtVp7GkZkOsOCjGO9E1757fd332ZD2KS+vvt
fYPimJyKJFdY5VHUc1fqBwyf4px8ZsbIGkqAyApVhGGllzvoreK685nBAoGBAL76
FZO9S/aKo5OcnfPOFSZtYN01l1XwviKswD3FUXBO4JcSeDvJz6Xm1oD9Z84SKPiy
YzOr1+lvGYHYHYc93X+gIXt3xoEqPd/NQ3OjEtPyKz9/D1T7pFi83vGH1/dPOY4p
kfzLwtrMTYuVZls9gqqd6kneKi41pQSFIwDJPY/PAoGAfGZIHMksLXjCiTQ9GH2p
1E4ZOf6M+9xp9Hhw1SL6RSOd6aeqmFgb1waFWytXGVokzLwug8N1CFt4G8m4akep
cXcqsWd3M4l+Rr7TM3cKrv+Hz9LcgvX7dRHsoQgJKgUIZs2WaxOY4NG81oEoOTuN
clPqmFUVDSKB5N95YxnPR7M=
-----END PRIVATE KEY-----
@@ -0,0 +1,18 @@
-----BEGIN CERTIFICATE-----
MIIC+TCCAeGgAwIBAgIUBBPpn1DYg+DYBP7ARO6Qtkv0+aMwDQYJKoZIhvcNAQEL
BQAwJTEjMCEGA1UEAwwaRG9taVN0cmVhbSB0ZXN0LW9ubHkgcm9ndWUwHhcNMjYx
MTI1MTE1NzQ4WhcNNDYxMTIwMTE1NzQ4WjAlMSMwIQYDVQQDDBpEb21pU3RyZWFt
IHRlc3Qtb25seSByb2d1ZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
AL0wtc1+tsai6ntPJ4bmnhxo6iIbuugMDpd49Q47kwhdoPH6HkYa3eSdWvksES0B
pOxAMPTuaZoA+YVktpalgm+gVjzvJ7Nq98+u81rs2qaY7/zjDiBlhivEKOI4kV8c
7l6oyqt5k1+sg/Pzu8f7Ph/L0OWPqJi/MTUAm5JNXVVC9qy0CFIGbguaVpBCbsfr
3pXgI8Cu4Wt/Arn96ty1Kpy0eAKQ04vhLWXuHSsVTAR64dm9oeVq+mKEnBQUPhEZ
C49JRDzeGDZf6gUGiEZbipr4xOzrcpcMdTAhw+vMmSRYq6im/XSMhcnfBHEZ0s66
wOKCHIeG0oeKVZGQ9GJJ+GECAwEAAaMhMB8wHQYDVR0OBBYEFNtzCj3DC27aruwm
i2FmuzXk/f00MA0GCSqGSIb3DQEBCwUAA4IBAQCel4STUMqMqGB664MvVysqPfB6
ueezEL4LaXQIbxHZPmRhDQPR8TFUiiLo7XDTCm8bxnxW3n9RCdqL+0NWopSkO8Dt
1jpXHs0Pe3M0/TH4nk9znH/cefmJIM4QMZytrqNJnLRQY5gzETb1w9IjtDBh1DAv
t0EKsCYM2VYjtrNk0pgREEtmLe4wiS7yp/HWt0eqKpEQuQ95C/VzLAsNdfOKKq88
/lBjR3i27HiOY5uanwDFIGUxmRiIeXJ5ghZW80dbXUM2SGGhKlYVGlqhQ8u+mDod
troJPfRFyT4Rd2VKOruIp6/6gF0txfOzPrD/lEjwTlZekRkUMc29DRU0bQst
-----END CERTIFICATE-----
@@ -0,0 +1,28 @@
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC9MLXNfrbGoup7
TyeG5p4caOoiG7roDA6XePUOO5MIXaDx+h5GGt3knVr5LBEtAaTsQDD07mmaAPmF
ZLaWpYJvoFY87yezavfPrvNa7NqmmO/84w4gZYYrxCjiOJFfHO5eqMqreZNfrIPz
87vH+z4fy9Dlj6iYvzE1AJuSTV1VQvastAhSBm4LmlaQQm7H696V4CPAruFrfwK5
/erctSqctHgCkNOL4S1l7h0rFUwEeuHZvaHlavpihJwUFD4RGQuPSUQ83hg2X+oF
BohGW4qa+MTs63KXDHUwIcPrzJkkWKuopv10jIXJ3wRxGdLOusDighyHhtKHilWR
kPRiSfhhAgMBAAECggEAEj98xaejdwjXP5IMsLcVSI25CZWtozyoeqU808Tcw3mO
cNCMc3wba3XfBLoipPnr36q4XiOR1XwjFSH395Nav6wSLVnu9SAL64EHMX23gEqv
mS+IWQkZ1iZbQCivIuKuPjyfIcd99sQzzQe1FM6vuQ7mZQIEg8krNJ7MoqGqLzM1
vxpNzR1EEwCuF+oXZhAMcMDJQkofSgp/w3DY9ZrgNc4GNGs9fujbpbTW8koOL7b6
Cme4Ad1EQ3dgTfFoUBTgjQ75ae9P+1ydVCJuckIFsjBXLog4KKqrBYA2JXYAxaeU
iNiVuO9kLIP0VoIS68GYn4B73VoC1y2/JfDYEWwo8QKBgQD5tf4AGUJQNr2N+W+S
lNt3lv6SZ/jELsHMokPdlNc0/nLHHkTrtC07nz/QFYM+6PFj2wSybvzMPg7d2BsO
49ddJTgJkRKWAN4guNn3SYbqboerah7aRLKBTHku4PnvQaYMmK/gBk8q86OFUCdP
lZAQOc7DV7ZBtLaBiCV2b4/DWQKBgQDB9IMRoXtdIS5snRfq1+9TQCe9oN0r8REC
nys9FK8PTAPpELSEKPf9S5Y1YzSpvn7m0c8z8SETjlO2qxzINdMLbnNBqSSt3ohu
MlXzzlRjvdbjJag1rCIOsT0iWqte7UiuIXdCTbRs9Bg/rfIe4BcLDBlwnyjlF8W2
JDW4UNDkSQKBgQDBOmP/fYxD9+f8ac09dzTQuKXrcsscPDY4/ENZvmg9mLwGetTI
M5dg8Jz3jv4Ne0H3jC55SMsT3N2yKxzdC8/GQxu2w2zHaIp6dbAs29erprYTHb4c
FlavGRcZAHxG+NzeGHTX/OncCcY6Tcjtm4VsGN93Z3MgKw+i8lBS8ocjmQKBgHjh
ODLrzqP7QyDEQ5zE2c6r5FjGAjIZuz1EEEGwO26wNJu0Ip1fnzdJPaOmYbMNG7Al
wRqhRLkYckodmQGash6kxsZ8cXS/hY4QZwtdY7EKJvxIgu54in1Xrz9S/Q1bm3mT
N+2l2jYxZ0+AzK67gQEMmGpdd7JYP4vGQ4jNLXOpAoGAV9pYZ8V3bcvUwlUpDcL2
A7dnL+NA8XOYVd8/My0yh+FK6q1Fhac3TffkaWJISigkNYmW/svdAouOC9sCRPtb
Dr59pYDgjpKOQPQ9yHQqlG7GlFXEl+NhQjNIicEgNymX/E0nXkRLz/E+pLVYW4FY
4CqLqkis5ZQieheigEBg6AI=
-----END PRIVATE KEY-----
+20
View File
@@ -0,0 +1,20 @@
# Generated by tools/vectors/gen_vectors.py. TEST-ONLY values and keys, made for DomiStream's tests.
# Never a real host's or client's key. Do not edit by hand: change the script and run it again.
# Video packets (PROTOCOL.md 7): AES-128-GCM by .NET AesGcm
key = 3087d2f8aacc5739add080dd7fc924a4
# v_0
v_0_plain = f7d0644a408e95fa6d7161da4db5b01113030728d20c8dc583ba41fb9399b55c138ccf93bfb1816aa7c3b60efb77a5d8
v_0_packet = 00000000000000000000005600000000f2cb1e2e00026bd57ff480120baf7e9e1e87270a2ab54f90a18b8e27f5accc46e2a8f239d75caaf25790ce49c9a5ce99c47e09fe76f4a70bb244487f5a4810f0
# v_1
v_1_plain = a90afba6e31047d24f4f14b1cb81c6db02b2d299f0d8200fe27edda0fe21cee033c634c5349a9c8cb49650bf059d4754
v_1_packet = 01000000000000000000005600000000dd08edab787f9abe2a5b4f9fda9d9d0178ad4dd1a1a2deb38853e90e6aed3a56f303b2f0b9f31b0f40fdf0b0f5fee300957b6b4ba8afad3617a8cd227e68e058
# v_big_counter
v_big_counter_plain = 7fdd44c6e2e0ea29e71c28deba014e95313718ab54b11db92a5da93c9f1c1f710067b83b97e4ec0ac0284cd62c20f56059a6f602abeebd5e16ecb4c258423e32
v_big_counter_packet = 080706050403020100000056443322114e1be44271991d303ea62e0348d059b4e323f418f9e6989362c2d8b861ad1263b6081e01dc36d2c704bc54e79d0a2b795e3100383c1290405ae08bd6a48f5c35afe45f2bd6f7f7c327a7fb526f580d83
# v_1040
v_1040_plain = 6db2038ec91958faac7add888327646591a80cf0a27652fb433ce4194c6830405706ef40cab5a0dc25cee87c5a8b071bdca7b10c221ce9da6cd01f0ced6ecfa131d0debf06efaf0aa53cedf888a6bbf99e96e51797dfba233b6cccfb63802f0261851a1a6bfe072206f1162739223ca450ab8c1f83adefa0ae9442ea1b889ec8475a3ee74c5f55b4ac5f26362424f8ee951223307d72a0dd2dd96ee11a3e10579c34bc2118519a5b67bd17c3807630e50771d807435388b664276e4f13f961075940d1c571a6306e0f60b7eb2ffcb2965bd180406744903e6fd6326d86836dd2c1fa58c5e78f36b2b47eb5ae726b802ea22b6e7251ee1d96248e59ae57d007379e841d0c8dc834d81f5cffb750cb45da6281aa82c7ef8be8253c4faf099a1d8ce05f41f7f462524dc85325795c5c48be2988f1b9b66f3bcda74543d8ddc8fc19597c4183d705c90438cb93d8af18795d50f60cef208a845a5ddd896e61fa3b60fabd466da57736ba4e9e1905591a89aadeb4b49b52e580c8ca8aca2e589125140de93a9ae87e05547e55574400ae43ce1dc7bb535c361948a7fd3e23087a891d21f03635722681a96e675c82cfaf03addce349acb946574d78a63f9c547089004c355f7d825406ab11bec3d44a5d199cdf0777aaaf88a93894324beae0bec66ebd74ad9011b2b5c71c216dd9580658960287b040b414b096a10124473fb66f475f42384ff481b8723c5eb0398231613e239f9697d78491949800c73916e53424313530c0820591a820eaf7c29b361a46e960a3a8c7e5fdcc4c65234b36db1ee5d5801e031a36d490069ac54d31d17157fd2a46e61c9dbecf70844e28422f292d433ab51f02308f6848ac6417a505bfb78965d3564eea5de5e2fbe704e7f180fb8781db6c75d46b05f9902bf50a15e86d23070357f9fdd19f710e20811dafad4d6ba4ef20e5e565287e7db70093e03a244e8c5f11d23dd099c8274a3eff520aa0f5f7a71608e49cd41b10cf89ca9d561dc9622e952b449267f5b283d3c87b8ef558da78ccfd98277e9ca0cb354b09f2142cda5d4d15d8703e02857de3bc51cbddd86cd312d8f9afec663a383cbe43c250fc39b9897b475de0ef6850ab2fc899d201fc679595077b08b7da650af17d1ac30e054a8a55e7d741c44107cf66804d86a31d25b4b8ab194d327ee1d6b17edca12aee55f8c37979b8eb6f407ce7e4f393414eaf93ac18a367605c86169a430d1c829957bb4569f011796151b08dfb571312922fd5fc5da577980358f570d7f4f4e9f0ae56c43a7b2015f8f41e4eec6a26c24fd99f44632b2b961c37d4d0b878919b80a9179fb73ce0a9c799547d67aa7678d9da2d61068eb85e6058bde560844eb80433d82df523be4042c891c02209cdd7c4a40c19bf64040ee2454d677691d774e916a8043ee5ba206883aad21bc1d7ddefb50c7c3cd5f1a1cd06da4bbf0b24
v_1040_packet = 070000000000000000000056030000009f0960cb7d592ee72c1c45da2c30b7b5e56339239ca58b674eb8052fe093508e322d53e9fd6d4e452795b35c6b5cd94b1afbf488de7f36a90b944b95823099c8c216d41ec9261b9d2ad6a6fe516bd751ca31e3b85f4df7b9652b56faa8cf5231254197051b10bb6ee2c6fb6752f5999572e34c4649962647b0fc459abdde343b26dbeb19d82dad1bf7f8667ca2f025533816ad2d2eaf03979e1a53572b0355f27cfa936fb844c1e6dacdb25d3d93e4f84c96dc2dd3956e5101ffa4f014659107483dba9b9ae3aa9220e378ce1cd223be080c3ae94bed1781b5edb0a8521c329f6afd20758d91e92f7de997cdaa52d15803a501a76ea449f719c52ba6a21e962004a3963a6e333126a8f358385c5e8168b576a3d9d855d754e014ce69e126d4f12530faa090cabbe95df8f10ae2de9e33faa2e0d79ea0b529adc5de085b44b79788d1d7621bae91fcbe7b0d3a874c94d45f42068d9cfc8ea2b692edf624aa9da1e0747b972933bc4885dc7712edc89ff4f55b6ddfb686519ea2ebff377fed5727baed7f81a71d1a2178d447f3fb1055a8e0b5271bc75a54f951610af3c02d7d5e752f067c940e31cee57d77eb750a7f0d73b87a4f940531fbefc9275b2f9a10753f46dd6e8ef3f2d6232525a545f12224ec365349cc4c5cad05364b18a3291c9509d22c6445f9c7777edc298cb0a83d2a0328e3cfc2e6ccb2a94c8d5d1d97e309aace8ffb496771aa4dbf98f26f9d570dcb6f9e6561e399fb7a774c0c700c13e36a22bd002292c853d3066d954d2a91cba714d0b43b88adef6d2240ca5e878ad6d1fe7f0eba7bd32d4bb0c65ab16a51cc2c2ce732e40b8a5efeba0da3fa886e0ba82d3474a9c9141ae029e7b2c3a2ac117953f44525127871b60a7852317ac593584f680efb1355dc1da30d3efbd45b07a8b8de15aa36a6eb04db0ffd564db466724ab5794ddf9047af393aa49ce24ea3d75894db2f1fe9bcacb476c056ee1dc62737cf4ea86ecdff9355a62c406d22b748bcd4db6d74c3a587646368695150e4c0c09cfefff39a5e043f6c1ffc488821b91cd8ba89fe0f740870c766b2c9a97451a2aa25a141daf58621c8c87eaf4d8d986cd0d0db1431137b77498bc180444397f2bcecb0dfce9b0f48db7f77fb14a19764dba945126de708a37c8976d43876d02eb3b02b741a7e00115e4f53fbb8ec676011e1daa5da45f12f93413e84ae24ba0aa96b40b144f773d7e7f9ceaf9793794e28534419c24aee86bcba4251876ace0833e0d0c0291d0147f9cc0afd27b64daf387f421458463d0383194f37becb135d5bae8b2186a796f577404d155c3259ae336a090130b675811c84f358458dc8f0cda407dff4ef6aaaca874e8034725d6f7f36c954bfe397a33dd1bb64c65ef30485447ab46333299080e3c99e42be55e55f6713ab9a2f4b750b6bddcb6740bb82f7ed3f5391a1631cec7bce65b776f4f3393beea54a3fd12786a356664f3f
+687
View File
@@ -0,0 +1,687 @@
//! 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)) {
let parsed = xml::parse(&data);
prop_assert!(common::implemented(&parsed));
if let Ok(d) = parsed {
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);
let r = xml::parse(&doc[..cut]);
prop_assert!(matches!(r, Err(Error::Malformed { .. } | Error::Truncated { .. })), "{:?}", r);
}
}
// ================================================================================================ 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]);
}
+264
View File
@@ -0,0 +1,264 @@
//! 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}");
}
}
+466
View File
@@ -0,0 +1,466 @@
//! INPUT_DATA (`docs/PROTOCOL.md` 4): vectors rebuilt from the field tables with our own builder, cross-checked
//! against the example bytes in PROTOCOL.md; encode, parse, equal; refusals of unknown types and wrong lengths.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
mod common;
use common::hex;
use domistream::Error;
use domistream::input::{
ButtonFlags, ControllerCapabilities, ControllerKind, GamepadState, INPUT_HEADER_LEN, InputEvent, InputType,
MAX_INPUT_MESSAGE_BYTES, MouseButton, encode_input, parse_input,
};
use proptest::prelude::*;
/// `0x0206 LE ‖ length LE (= 4 + size) ‖ size BE (= 4 + data) ‖ input type LE ‖ data`.
fn input_message(input_type: u32, data: &[u8]) -> Vec<u8> {
let size = 4 + data.len();
let mut m = 0x0206u16.to_le_bytes().to_vec();
m.extend_from_slice(&((4 + size) as u16).to_le_bytes());
m.extend_from_slice(&(size as u32).to_be_bytes());
m.extend_from_slice(&input_type.to_le_bytes());
m.extend_from_slice(data);
m
}
fn be16(v: i16) -> [u8; 2] {
v.to_be_bytes()
}
fn rel(dx: i16, dy: i16) -> Vec<u8> {
input_message(0x07, &[be16(dx), be16(dy)].concat())
}
fn abs(x: i16, y: i16, w: u16, h: u16) -> Vec<u8> {
input_message(0x05, &[&be16(x)[..], &be16(y), &[0, 0], &w.to_be_bytes(), &h.to_be_bytes()].concat())
}
fn button(down: bool, b: u8) -> Vec<u8> {
input_message(if down { 0x08 } else { 0x09 }, &[b])
}
fn key(down: bool, flags: u8, code: u16, modifiers: u8) -> Vec<u8> {
input_message(if down { 0x03 } else { 0x04 }, &[&[flags][..], &code.to_le_bytes(), &[modifiers, 0, 0]].concat())
}
fn scroll(amount: i16) -> Vec<u8> {
// amount1 and amount2 both carry the amount, as in the PROTOCOL.md example; hosts read amount1.
input_message(0x0A, &[&be16(amount)[..], &be16(amount), &[0, 0]].concat())
}
fn hscroll(amount: i16) -> Vec<u8> {
input_message(0x5500_0001, &be16(amount))
}
fn gamepad(g: &GamepadState) -> Vec<u8> {
let mut d = Vec::new();
d.extend_from_slice(&0x001Au16.to_le_bytes());
d.extend_from_slice(&u16::from(g.controller).to_le_bytes());
d.extend_from_slice(&g.active_mask.to_le_bytes());
d.extend_from_slice(&0x0014u16.to_le_bytes());
d.extend_from_slice(&((g.buttons.0 & 0xFFFF) as u16).to_le_bytes());
d.push(g.left_trigger);
d.push(g.right_trigger);
for v in [g.left_stick_x, g.left_stick_y, g.right_stick_x, g.right_stick_y] {
d.extend_from_slice(&v.to_le_bytes());
}
d.extend_from_slice(&0x009Cu16.to_le_bytes());
d.extend_from_slice(&((g.buttons.0 >> 16) as u16).to_le_bytes());
d.extend_from_slice(&0x0055u16.to_le_bytes());
assert_eq!(d.len(), 26);
input_message(0x0C, &d)
}
/// Arrival: controller, type, capabilities, supported buttons (u32, taken as LE like the other gamepad fields:
/// PROTOCOL.md gives no byte order, UNKNOWN U22).
fn arrival(controller: u8, kind: u8, caps: u8, buttons: u32) -> Vec<u8> {
input_message(0x5500_0004, &[&[controller, kind, caps][..], &buttons.to_le_bytes()].concat())
}
fn pad(controller: u8, mask: u16, ry: i16) -> GamepadState {
GamepadState { controller, active_mask: mask, right_stick_y: ry, ..GamepadState::default() }
}
#[test]
fn builder_matches_the_protocol_md_examples() {
// Our field-table builder reproduces every example in PROTOCOL.md §4 byte for byte.
assert_eq!(rel(-1, 0), hex("06 02 0C 00 00 00 00 08 07 00 00 00 FF FF 00 00"));
assert_eq!(abs(1464, 528, 1919, 1079), hex("06 02 12 00 00 00 00 0E 05 00 00 00 05 B8 02 10 00 00 07 7F 04 37"));
assert_eq!(button(true, 1), hex("06 02 09 00 00 00 00 05 08 00 00 00 01"));
assert_eq!(key(true, 0, 0x80A4, 0x04), hex("06 02 0E 00 00 00 00 0A 03 00 00 00 00 A4 80 04 00 00"));
assert_eq!(scroll(-120), hex("06 02 0E 00 00 00 00 0A 0A 00 00 00 FF 88 FF 88 00 00"));
assert_eq!(hscroll(30), hex("06 02 0A 00 00 00 00 06 01 00 00 55 00 1E"));
assert_eq!(
gamepad(&pad(0, 1, -104)),
hex(
"06 02 22 00 00 00 00 1E 0C 00 00 00 1A 00 00 00 01 00 14 00 00 00 00 00 00 00 00 00 00 00 98 FF 9C 00 00 00 55 00"
)
);
}
fn vectors() -> Vec<(InputEvent, Vec<u8>)> {
let full = GamepadState {
controller: 15,
active_mask: 0x8001,
buttons: ButtonFlags(
ButtonFlags::A | ButtonFlags::DPAD_UP | ButtonFlags::HOME | ButtonFlags::PADDLE1 | ButtonFlags::MISC,
),
left_trigger: 0x80,
right_trigger: 0xFF,
left_stick_x: i16::MIN,
left_stick_y: i16::MAX,
right_stick_x: -1,
right_stick_y: 1,
};
vec![
(InputEvent::MouseMoveRel { dx: -1, dy: 0 }, rel(-1, 0)),
(InputEvent::MouseMoveRel { dx: i16::MIN, dy: i16::MAX }, rel(i16::MIN, i16::MAX)),
(InputEvent::MouseMoveAbs { x: 1464, y: 528, width: 1919, height: 1079 }, abs(1464, 528, 1919, 1079)),
(InputEvent::MouseMoveAbs { x: -5, y: 0, width: 0xFFFF, height: 1 }, abs(-5, 0, 0xFFFF, 1)),
(InputEvent::MouseButton { pressed: true, button: MouseButton::Left }, button(true, 1)),
(InputEvent::MouseButton { pressed: false, button: MouseButton::Left }, button(false, 1)),
(InputEvent::MouseButton { pressed: true, button: MouseButton::Middle }, button(true, 2)),
(InputEvent::MouseButton { pressed: false, button: MouseButton::Right }, button(false, 3)),
(InputEvent::MouseButton { pressed: true, button: MouseButton::Side }, button(true, 4)),
(InputEvent::MouseButton { pressed: true, button: MouseButton::Extra }, button(true, 5)),
(InputEvent::Key { pressed: true, flags: 0, key_code: 0x80A4, modifiers: 0x04 }, key(true, 0, 0x80A4, 0x04)),
(InputEvent::Key { pressed: false, flags: 0, key_code: 0x0041, modifiers: 0 }, key(false, 0, 0x0041, 0)),
(
InputEvent::Key { pressed: true, flags: 0xFF, key_code: 0xFFFF, modifiers: 0xFF },
key(true, 0xFF, 0xFFFF, 0xFF),
),
(InputEvent::Scroll { amount: -120 }, scroll(-120)),
(InputEvent::Scroll { amount: 120 }, scroll(120)),
(InputEvent::HScroll { amount: 30 }, hscroll(30)),
(InputEvent::HScroll { amount: -32768 }, hscroll(-32768)),
(InputEvent::Gamepad(pad(0, 1, -104)), gamepad(&pad(0, 1, -104))),
(InputEvent::Gamepad(pad(1, 0, 0)), gamepad(&pad(1, 0, 0))),
(InputEvent::Gamepad(full), gamepad(&full)),
(
InputEvent::ControllerArrival {
controller: 2,
kind: ControllerKind::PlayStation,
capabilities: ControllerCapabilities(0xFF),
supported_buttons: ButtonFlags(0x003F_FFFF),
},
arrival(2, 2, 0xFF, 0x003F_FFFF),
),
(
InputEvent::ControllerArrival {
controller: 0,
kind: ControllerKind::Unknown,
capabilities: ControllerCapabilities(ControllerCapabilities::RUMBLE),
supported_buttons: ButtonFlags(0),
},
arrival(0, 0, 0x02, 0),
),
(
InputEvent::ControllerArrival {
controller: 15,
kind: ControllerKind::Nintendo,
capabilities: ControllerCapabilities(0),
supported_buttons: ButtonFlags(ButtonFlags::A),
},
arrival(15, 3, 0, 0x1000),
),
(
InputEvent::ControllerArrival {
controller: 3,
kind: ControllerKind::Xbox,
capabilities: ControllerCapabilities(0x23),
supported_buttons: ButtonFlags(0xFFFF),
},
arrival(3, 1, 0x23, 0xFFFF),
),
]
}
#[test]
fn encode_then_parse_then_equal() {
for (event, bytes) in vectors() {
assert_eq!(encode_input(&event).unwrap(), bytes, "encode {event:?}");
assert_eq!(parse_input(&bytes).unwrap(), event, "parse {event:?}");
assert_eq!(parse_input(&encode_input(&event).unwrap()).unwrap(), event);
}
}
#[test]
fn input_type_codes() {
for (code, t) in [
(0x03, InputType::KeyDown),
(0x04, InputType::KeyUp),
(0x05, InputType::MouseMoveAbs),
(0x07, InputType::MouseMoveRel),
(0x08, InputType::MouseButtonDown),
(0x09, InputType::MouseButtonUp),
(0x0A, InputType::MouseScroll),
(0x0C, InputType::ControllerMulti),
(0x0D, InputType::Haptics),
(0x17, InputType::Utf8Text),
(0x5500_0001, InputType::MouseHScroll),
(0x5500_0002, InputType::Touch),
(0x5500_0003, InputType::Pen),
(0x5500_0004, InputType::ControllerArrival),
(0x5500_0005, InputType::ControllerTouch),
(0x5500_0006, InputType::ControllerMotion),
(0x5500_0007, InputType::ControllerBattery),
] {
assert_eq!(InputType::try_from(code), Ok(t), "{code:#x}");
}
for code in [0u32, 1, 2, 6, 0x0B, 0x0E, 0x16, 0x18, 0x5500_0000, 0x5500_0008, 0x0100_0007, u32::MAX] {
assert_err!(InputType::try_from(code), Error::UnexpectedValue { .. }, "{code:#x}");
}
}
#[test]
fn unknown_and_unsupported_types() {
for code in [0u32, 1, 6, 0x5500_0008, 0x0700_0000, u32::MAX] {
assert_err!(parse_input(&input_message(code, &[0; 4])), Error::UnexpectedValue { .. }, "type {code:#x}");
}
// Known types whose layout is UNKNOWN U21.
for code in [0x0D, 0x17, 0x5500_0002, 0x5500_0003, 0x5500_0005, 0x5500_0006, 0x5500_0007] {
assert_err!(parse_input(&input_message(code, &[0; 8])), Error::Unsupported { .. }, "type {code:#x}");
}
}
#[test]
fn wrong_data_lengths() {
// (type, correct data length)
for (code, len) in [
(0x07u32, 4usize),
(0x05, 10),
(0x08, 1),
(0x09, 1),
(0x03, 6),
(0x04, 6),
(0x0A, 6),
(0x5500_0001, 2),
(0x0C, 26),
(0x5500_0004, 7),
] {
for wrong in [0, len - 1, len + 1, len + 16] {
let mut data = vec![0u8; wrong];
if code == 0x08 || code == 0x09 {
data.fill(1); // a valid button number, so only the length is wrong
}
assert_err!(
parse_input(&input_message(code, &data)),
Error::Malformed { .. },
"type {code:#x} with {wrong} bytes (wants {len})"
);
}
}
}
#[test]
fn lying_length_and_size_fields() {
let good = rel(5, 5);
let cases: Vec<(Vec<u8>, &str)> = vec![
(
{
let mut m = good.clone();
m[2] += 1;
m
},
"length over",
),
(
{
let mut m = good.clone();
m[2] -= 1;
m
},
"length under",
),
(
{
let mut m = good.clone();
m[2..4].copy_from_slice(&0xFFFFu16.to_le_bytes());
m
},
"length 65535",
),
(
{
let mut m = good.clone();
m[7] += 1;
m
},
"size over",
),
(
{
let mut m = good.clone();
m[7] -= 1;
m
},
"size under",
),
(
{
let mut m = good.clone();
m[4..8].copy_from_slice(&u32::MAX.to_be_bytes());
m
},
"size u32::MAX",
),
(
{
let mut m = good.clone();
m[4..8].copy_from_slice(&8u32.to_le_bytes());
m
},
"size written little-endian",
),
(
{
let mut m = good.clone();
m[0..2].copy_from_slice(&0x0207u16.to_le_bytes());
m
},
"not INPUT_DATA",
),
(
{
let mut m = good.clone();
m[0..2].copy_from_slice(&0x0206u16.to_be_bytes());
m
},
"message type big-endian",
),
([good.clone(), vec![0]].concat(), "trailing byte"),
];
for (m, why) in cases {
assert_err!(parse_input(&m), Error::Malformed { .. }, "{why}");
}
}
#[test]
fn hostile_sizes() {
assert_err!(parse_input(&[]), Error::Truncated { .. });
assert_err!(parse_input(&[0x06]), Error::Truncated { .. });
assert_err!(parse_input(&rel(1, 1)[..INPUT_HEADER_LEN - 1]), Error::Truncated { .. });
assert_err!(
parse_input(&input_message(0x07, &[])[..INPUT_HEADER_LEN]),
Error::Malformed { .. },
"header only: no data"
);
// max - 1, max, max + 1, huge: valid framing, data too long for any known type.
for len in [MAX_INPUT_MESSAGE_BYTES - 1, MAX_INPUT_MESSAGE_BYTES] {
let m = input_message(0x07, &vec![0; len - INPUT_HEADER_LEN]);
assert_eq!(m.len(), len);
assert_err!(parse_input(&m), Error::Malformed { .. }, "{len}");
}
let m = input_message(0x07, &vec![0; MAX_INPUT_MESSAGE_BYTES + 1 - INPUT_HEADER_LEN]);
assert_too_large!(parse_input(&m), MAX_INPUT_MESSAGE_BYTES, MAX_INPUT_MESSAGE_BYTES + 1);
assert_too_large!(parse_input(&vec![0; 1 << 20]), MAX_INPUT_MESSAGE_BYTES, 1 << 20);
}
#[test]
fn bad_field_values() {
for b in [0u8, 6, 0xFF] {
assert_err!(parse_input(&button(true, b)), Error::UnexpectedValue { .. }, "button {b}");
}
let mut g = gamepad(&pad(16, 1, 0));
assert_err!(parse_input(&g), Error::UnexpectedValue { .. }, "controller 16");
for (offset, why) in [(12usize, "0x1A"), (18, "0x14"), (32, "0x9C"), (36, "0x55")] {
g = gamepad(&pad(0, 1, 0));
g[offset] ^= 0x01;
assert_err!(parse_input(&g), Error::Malformed { .. }, "constant {why} changed");
}
assert_err!(parse_input(&arrival(16, 1, 0, 0)), Error::UnexpectedValue { .. }, "arrival controller 16");
assert_err!(parse_input(&arrival(0, 4, 0, 0)), Error::UnexpectedValue { .. }, "controller kind 4");
for e in [
InputEvent::Gamepad(pad(16, 1, 0)),
InputEvent::Gamepad(pad(255, 1, 0)),
InputEvent::ControllerArrival {
controller: 16,
kind: ControllerKind::Xbox,
capabilities: ControllerCapabilities(0),
supported_buttons: ButtonFlags(0),
},
] {
assert_err!(encode_input(&e), Error::UnexpectedValue { .. }, "{e:?}");
}
}
fn event() -> impl Strategy<Value = InputEvent> {
let button = prop_oneof![
Just(MouseButton::Left),
Just(MouseButton::Middle),
Just(MouseButton::Right),
Just(MouseButton::Side),
Just(MouseButton::Extra)
];
let kind = prop_oneof![
Just(ControllerKind::Unknown),
Just(ControllerKind::Xbox),
Just(ControllerKind::PlayStation),
Just(ControllerKind::Nintendo)
];
let gamepad = (0u8..=15, any::<u16>(), any::<u32>(), any::<u8>(), any::<u8>(), any::<[i16; 4]>()).prop_map(
|(c, m, b, l, r, s)| GamepadState {
controller: c,
active_mask: m,
buttons: ButtonFlags(b),
left_trigger: l,
right_trigger: r,
left_stick_x: s[0],
left_stick_y: s[1],
right_stick_x: s[2],
right_stick_y: s[3],
},
);
prop_oneof![
(any::<i16>(), any::<i16>()).prop_map(|(dx, dy)| InputEvent::MouseMoveRel { dx, dy }),
(any::<i16>(), any::<i16>(), any::<u16>(), any::<u16>())
.prop_map(|(x, y, width, height)| InputEvent::MouseMoveAbs { x, y, width, height }),
(any::<bool>(), button).prop_map(|(pressed, button)| InputEvent::MouseButton { pressed, button }),
(any::<bool>(), any::<u8>(), any::<u16>(), any::<u8>())
.prop_map(|(pressed, flags, key_code, modifiers)| InputEvent::Key { pressed, flags, key_code, modifiers }),
any::<i16>().prop_map(|amount| InputEvent::Scroll { amount }),
any::<i16>().prop_map(|amount| InputEvent::HScroll { amount }),
gamepad.prop_map(InputEvent::Gamepad),
(0u8..=15, kind, any::<u8>(), any::<u32>()).prop_map(|(controller, kind, c, b)| {
InputEvent::ControllerArrival {
controller,
kind,
capabilities: ControllerCapabilities(c),
supported_buttons: ButtonFlags(b),
}
}),
]
}
proptest! {
#![proptest_config(ProptestConfig { cases: 1024, ..ProptestConfig::default() })]
#[test]
fn any_event_round_trips(e in event()) {
let bytes = encode_input(&e).map_err(|err| TestCaseError::fail(format!("{err:?}")))?;
prop_assert!(bytes.len() <= MAX_INPUT_MESSAGE_BYTES);
prop_assert_eq!(&bytes[..2], &[0x06, 0x02]);
prop_assert_eq!(u16::from_le_bytes([bytes[2], bytes[3]]) as usize, bytes.len() - 4);
prop_assert_eq!(u32::from_be_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]) as usize, bytes.len() - 8);
prop_assert_eq!(parse_input(&bytes), Ok(e));
}
/// Arbitrary bytes never panic; whatever parses re-encodes to an equal event.
#[test]
fn parse_is_stable(data in proptest::collection::vec(any::<u8>(), 0..64)) {
let parsed = parse_input(&data);
prop_assert!(common::implemented(&parsed));
if let Ok(e) = parsed {
let again = encode_input(&e).map_err(|err| TestCaseError::fail(format!("{err:?}")))?;
prop_assert_eq!(parse_input(&again), Ok(e));
}
}
/// Valid framing around random data of every known type never panics.
#[test]
fn framed_random_data(code in prop_oneof![Just(3u32), Just(4), Just(5), Just(7), Just(8), Just(9), Just(0x0A), Just(0x0C), Just(0x5500_0001), Just(0x5500_0004)], data in proptest::collection::vec(any::<u8>(), 0..40)) {
prop_assert!(common::implemented(&parse_input(&input_message(code, &data))));
}
}
+389
View File
@@ -0,0 +1,389 @@
//! Packet parsers and ciphers of the media streams (`docs/PROTOCOL.md` 5.2, 6.2, 6.3, 7): RTP header, video packet
//! and frame header, audio packet, video AES-GCM (.NET vectors) and audio AES-CBC (openssl vectors). Also checks the
//! RustCrypto test oracles in `common` against the same independent vectors.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
mod common;
use common::{fec_info, video_packet_bytes};
use domistream::audio::packet::{AUDIO_FEC_HEADER_LEN, MAX_AUDIO_PACKET_BYTES};
use domistream::audio::{AudioCipher, AudioPacket, parse_audio_packet};
use domistream::rtp::{RTP_HEADER_LEN, parse_rtp_header};
use domistream::video::packet::{FRAME_HEADER_LEN, MAX_VIDEO_PACKET_BYTES, PAYLOAD_OFFSET, parse_frame_header};
use domistream::video::{ENCRYPTION_PREFIX_LEN, FrameType, VideoCipher, parse_video_packet};
use domistream::{Error, SessionKeys};
use proptest::prelude::*;
// ================================================================================================ RTP
#[test]
fn rtp_header() {
let h = parse_rtp_header(&[0x80, 0x61, 0x12, 0x34, 0x00, 0x00, 0x03, 0xE8, 0xCA, 0xFE, 0xBA, 0xBE]).unwrap();
assert_eq!((h.flags, h.payload_type, h.sequence, h.timestamp, h.ssrc), (0x80, 97, 0x1234, 1000, 0xCAFE_BABE));
let h = parse_rtp_header(&[0x90, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0, 0, 0, 0, 1, 2, 3]).unwrap();
assert_eq!((h.flags, h.sequence, h.timestamp), (0x90, 0xFFFF, u32::MAX), "the rest is ignored");
for len in [0usize, 1, RTP_HEADER_LEN - 1] {
match parse_rtp_header(&vec![0x80; len]) {
Err(Error::Truncated { needed, actual, .. }) => assert_eq!((needed, actual), (RTP_HEADER_LEN, len)),
other => panic!("{len} bytes: {other:?}"),
}
}
for first in [0x00u8, 0x40, 0xC0, 0x3F] {
let mut p = vec![first, 97];
p.resize(12, 0);
assert_err!(parse_rtp_header(&p), Error::UnexpectedValue { .. }, "version bits {first:#x}");
}
assert!(parse_rtp_header(&vec![0x80; 1 << 20]).is_ok(), "only the first 12 bytes matter");
}
// ================================================================================================ video packet
#[test]
fn video_packet_fields() {
let payload: Vec<u8> = (0..48u8).collect();
let p = video_packet_bytes(0xABCD, 0x0102_0304, 77, 0x05, (1 << 4) | (2 << 6), fec_info(50, 3, 4), &payload);
let v = parse_video_packet(&p).unwrap();
assert_eq!(v.rtp.sequence, 0xABCD);
assert_eq!(v.rtp.timestamp, 0x0102_0304);
assert_eq!(v.rtp.flags, 0x90);
assert_eq!(v.nv.stream_packet_index, 0xABCD << 8);
assert_eq!(v.nv.frame_index, 77);
assert_eq!(v.nv.flags.0, 0x05);
assert_eq!(v.nv.multi_fec_flags, 0x10);
assert_eq!(v.nv.fec.shard_index, 3);
assert_eq!(v.nv.fec.data_shards, 4);
assert_eq!(v.nv.fec.fec_percentage, 50);
assert_eq!(v.nv.fec.block_index, 1);
assert_eq!(v.nv.fec.last_block_index, 2);
assert_eq!(v.payload, payload.as_slice());
// Parity shard 5 of 4 + 2 is in range.
assert!(parse_video_packet(&video_packet_bytes(1, 0, 0, 0, 0, fec_info(50, 5, 4), &payload)).is_ok());
// Bits 0-3 of fecInfo are not part of any field.
let p = video_packet_bytes(1, 0, 0, 1, 0, fec_info(50, 0, 4) | 0xF, &payload);
let v = parse_video_packet(&p).unwrap();
assert_eq!((v.nv.fec.shard_index, v.nv.fec.data_shards, v.nv.fec.fec_percentage), (0, 4, 50));
}
#[test]
fn video_packet_hostile_sizes() {
let at = |len: usize| {
let mut p = video_packet_bytes(1, 0, 0, 1, 0, fec_info(0, 0, 1), &[]);
p.resize(len, 0xEE);
p
};
for len in [0usize, 1, 16, PAYLOAD_OFFSET - 1] {
assert_err!(parse_video_packet(&at(len)[..len]), Error::Truncated { .. }, "{len}");
}
assert!(parse_video_packet(&at(PAYLOAD_OFFSET)).unwrap().payload.is_empty());
for len in [MAX_VIDEO_PACKET_BYTES - 1, MAX_VIDEO_PACKET_BYTES] {
assert_eq!(parse_video_packet(&at(len)).unwrap().payload.len(), len - PAYLOAD_OFFSET);
}
assert_too_large!(
parse_video_packet(&at(MAX_VIDEO_PACKET_BYTES + 1)),
MAX_VIDEO_PACKET_BYTES,
MAX_VIDEO_PACKET_BYTES + 1
);
assert_too_large!(parse_video_packet(&at(1 << 20)), MAX_VIDEO_PACKET_BYTES, 1 << 20);
}
#[test]
fn video_packet_inconsistent_fec_fields() {
let pay = [0u8; 16];
for (blocks, info, why) in [
(0u8, fec_info(50, 0, 0), "zero data shards"),
(0, fec_info(50, 6, 4), "shard index past data + parity (4 + 2)"),
(0, fec_info(0, 4, 4), "parity index with 0 % FEC"),
(0, fec_info(50, 1023, 4), "shard index 1023"),
(0, fec_info(100, 0, 200), "200 + 200 shards > 255"),
(0, fec_info(0, 0, 1023), "1023 data shards > 255"),
((2 << 4) | (1 << 6), fec_info(50, 0, 4), "block index past last block index"),
(3 << 4, fec_info(50, 0, 4), "block 3 of block 0"),
] {
assert_err!(
parse_video_packet(&video_packet_bytes(1, 0, 0, 1, blocks, info, &pay)),
Error::Malformed { .. },
"{why}"
);
}
let mut p = video_packet_bytes(1, 0, 0, 1, 0, fec_info(0, 0, 1), &pay);
p[0] = 0x50;
assert_err!(parse_video_packet(&p), Error::UnexpectedValue { .. }, "RTP version 1");
}
#[test]
fn frame_header() {
// Moonshine-style fields.
let h = parse_frame_header(&[0x01, 0x34, 0x12, 0x02, 0x10, 0x00, 0x00, 0x00, 0xAA]).unwrap();
assert_eq!(h.raw, [0x01, 0x34, 0x12, 0x02, 0x10, 0x00, 0x00, 0x00]);
assert_eq!(
(h.header_type, h.processing_latency, h.frame_type, h.last_payload_len),
(0x01, 0x1234, FrameType::Key, 16)
);
for (b, t) in [
(1u8, FrameType::Predicted),
(2, FrameType::Key),
(5, FrameType::Recovery),
(0, FrameType::Other(0)),
(0x68, FrameType::Other(0x68)),
] {
assert_eq!(parse_frame_header(&[1, 0, 0, b, 0, 0, 0, 0]).unwrap().frame_type, t);
}
// Wolf's constant (UNKNOWN U13): parsed, raw kept.
let wolf = [0x01, 0x37, 0x63, 0x68, 0x61, 0x72, 0x73, 0x73];
let h = parse_frame_header(&wolf).unwrap();
assert_eq!(h.raw, wolf);
assert_eq!(h.last_payload_len, 0x7373_7261);
for len in 0..FRAME_HEADER_LEN {
assert_err!(parse_frame_header(&wolf[..len]), Error::Truncated { .. }, "{len}");
}
}
// ================================================================================================ audio packet
fn audio_data(seq: u16, payload: &[u8]) -> Vec<u8> {
let mut p = vec![0x80, 97];
p.extend_from_slice(&seq.to_be_bytes());
p.extend_from_slice(&1000u32.to_be_bytes());
p.extend_from_slice(&0u32.to_be_bytes());
p.extend_from_slice(payload);
p
}
fn audio_parity(shard: u8, pt: u8, base_seq: u16, base_ts: u32, parity: &[u8]) -> Vec<u8> {
let mut p = vec![0x80, 127];
p.extend_from_slice(&base_seq.wrapping_add(4).to_be_bytes());
p.extend_from_slice(&base_ts.to_be_bytes());
p.extend_from_slice(&0u32.to_be_bytes());
p.extend_from_slice(&[shard, pt]);
p.extend_from_slice(&base_seq.to_be_bytes());
p.extend_from_slice(&base_ts.to_be_bytes());
p.extend_from_slice(&0x1122_3344u32.to_be_bytes());
p.extend_from_slice(parity);
p
}
#[test]
fn audio_packets() {
match parse_audio_packet(&audio_data(5, &[1, 2, 3])).unwrap() {
AudioPacket::Data { rtp, payload } => {
assert_eq!((rtp.payload_type, rtp.sequence, rtp.timestamp), (97, 5, 1000));
assert_eq!(payload, &[1, 2, 3]);
}
other => panic!("{other:?}"),
}
match parse_audio_packet(&audio_parity(1, 97, 0xFFFC, 0xDEAD_BEEF, &[9; 32])).unwrap() {
AudioPacket::Parity { rtp, fec, parity } => {
assert_eq!(rtp.payload_type, 127);
assert_eq!(
(fec.shard_index, fec.payload_type, fec.base_sequence, fec.base_timestamp, fec.ssrc),
(1, 97, 0xFFFC, 0xDEAD_BEEF, 0x1122_3344)
);
assert_eq!(parity, &[9; 32]);
}
other => panic!("{other:?}"),
}
}
#[test]
fn audio_packet_hostile() {
for pt in [0u8, 96, 98, 126] {
let mut p = audio_data(1, &[1]);
p[1] = pt;
assert_err!(parse_audio_packet(&p), Error::UnexpectedValue { .. }, "payload type {pt}");
}
assert_err!(
parse_audio_packet(&audio_parity(2, 97, 0, 0, &[1; 16])),
Error::UnexpectedValue { .. },
"parity shard 2"
);
assert_err!(parse_audio_packet(&audio_parity(0xFF, 97, 0, 0, &[1; 16])), Error::UnexpectedValue { .. });
for len in [0usize, 1, RTP_HEADER_LEN - 1, RTP_HEADER_LEN] {
assert_err!(parse_audio_packet(&audio_data(1, &[])[..len]), Error::Truncated { .. }, "data, {len} bytes");
}
let par = audio_parity(0, 97, 0, 0, &[]);
for len in [
RTP_HEADER_LEN,
RTP_HEADER_LEN + 1,
RTP_HEADER_LEN + AUDIO_FEC_HEADER_LEN - 1,
RTP_HEADER_LEN + AUDIO_FEC_HEADER_LEN,
] {
assert_err!(parse_audio_packet(&par[..len]), Error::Truncated { .. }, "parity, {len} bytes");
}
let at = |len: usize| audio_data(1, &vec![7; len - RTP_HEADER_LEN]);
for len in [MAX_AUDIO_PACKET_BYTES - 1, MAX_AUDIO_PACKET_BYTES] {
assert!(parse_audio_packet(&at(len)).is_ok(), "{len}");
}
assert_too_large!(
parse_audio_packet(&at(MAX_AUDIO_PACKET_BYTES + 1)),
MAX_AUDIO_PACKET_BYTES,
MAX_AUDIO_PACKET_BYTES + 1
);
assert_too_large!(parse_audio_packet(&at(1 << 20)), MAX_AUDIO_PACKET_BYTES, 1 << 20);
}
// ================================================================================================ video cipher
const VIDEO: [&str; 4] = ["v_0", "v_1", "v_big_counter", "v_1040"];
#[test]
fn video_decrypt_matches_dotnet_vectors() {
let v = common::video_vectors();
let c = VideoCipher::new(v.arr16("key"));
for name in VIDEO {
assert_eq!(
c.decrypt(&v.bytes(&format!("{name}_packet"))).unwrap(),
v.bytes(&format!("{name}_plain")),
"{name}"
);
}
}
#[test]
fn video_oracle_matches_dotnet_vectors() {
let v = common::video_vectors();
let key = v.arr16("key");
for (name, counter, frame) in
[("v_0", 0u64, 0u32), ("v_1", 1, 0), ("v_big_counter", 0x0102_0304_0506_0708, 0x1122_3344), ("v_1040", 7, 3)]
{
assert_eq!(
common::video_encrypt(&key, counter, frame, &v.bytes(&format!("{name}_plain"))),
v.bytes(&format!("{name}_packet")),
"{name}"
);
}
}
#[test]
fn video_decrypt_refuses() {
let v = common::video_vectors();
let c = VideoCipher::new(v.arr16("key"));
let p = v.bytes("v_1_packet");
for i in (0..11).chain(16..p.len()) {
let mut t = p.clone();
t[i] ^= 0x01;
assert_err!(c.decrypt(&t), Error::Crypto, "byte {i} flipped (IV, tag or ciphertext)");
}
let mut t = p.clone();
t[11] = b'v';
assert_err!(c.decrypt(&t), Error::Malformed { .. }, "IV byte 11 must be 'V'");
for len in [0usize, 1, ENCRYPTION_PREFIX_LEN - 1] {
assert_err!(c.decrypt(&p[..len]), Error::Truncated { .. }, "{len}");
}
let mut key = v.arr16("key");
key[15] ^= 0x80;
assert_err!(VideoCipher::new(key).decrypt(&p), Error::Crypto);
let mut big = p.clone();
big.resize(MAX_VIDEO_PACKET_BYTES + 1, 0);
assert_too_large!(c.decrypt(&big), MAX_VIDEO_PACKET_BYTES, MAX_VIDEO_PACKET_BYTES + 1);
}
// ================================================================================================ audio cipher
const AUDIO: [&str; 6] = ["a_0", "a_1", "a_ffff", "a_wrap", "a_exact_block", "a_one_byte"];
fn audio_cipher(v: &common::Vectors, name: &str) -> (AudioCipher, u16) {
let keys = SessionKeys { rikey: v.arr16("key"), rikeyid: v.u32_hex(&format!("{name}_rikeyid")) };
(AudioCipher::new(&keys), u16::from_str_radix(v.str(&format!("{name}_sequence")), 16).unwrap())
}
#[test]
fn audio_iv_and_decrypt_match_openssl_vectors() {
let v = common::audio_vectors();
for name in AUDIO {
let (c, seq) = audio_cipher(&v, name);
assert_eq!(
c.iv(seq).unwrap().to_vec(),
v.bytes(&format!("{name}_iv")),
"{name}: IV = BE(rikeyid + seq) || 12 zero, wrapping"
);
assert_eq!(
c.decrypt(seq, &v.bytes(&format!("{name}_cipher"))).unwrap(),
v.bytes(&format!("{name}_plain")),
"{name}"
);
}
}
#[test]
fn audio_oracle_matches_openssl_vectors() {
let v = common::audio_vectors();
for name in AUDIO {
let rikeyid = v.u32_hex(&format!("{name}_rikeyid"));
let seq = u16::from_str_radix(v.str(&format!("{name}_sequence")), 16).unwrap();
assert_eq!(
common::audio_encrypt(&v.arr16("key"), rikeyid, seq, &v.bytes(&format!("{name}_plain"))),
v.bytes(&format!("{name}_cipher")),
"{name}"
);
}
}
#[test]
fn audio_decrypt_refuses() {
use cbc::cipher::{BlockModeEncrypt, KeyIvInit, block_padding::NoPadding};
let v = common::audio_vectors();
let (c, seq) = audio_cipher(&v, "a_0");
for len in [0usize, 1, 15, 17, 31] {
assert_err!(c.decrypt(seq, &vec![0; len]), Error::Malformed { .. }, "{len} bytes");
}
// Blocks whose decryption ends in bad PKCS#7 padding.
let iv = c.iv(seq).unwrap();
for last in [&[0u8][..], &[17], &[16, 16, 16, 15], &[2, 3]] {
let mut block = [0x41u8; 16];
block[16 - last.len()..].copy_from_slice(last);
let mut buf = block;
cbc::Encryptor::<aes::Aes128>::new((&v.arr16("key")).into(), &iv.into())
.encrypt_padded::<NoPadding>(&mut buf, 16)
.unwrap();
assert_err!(c.decrypt(seq, &buf), Error::Crypto, "padding ending {last:?}");
}
}
proptest! {
#![proptest_config(ProptestConfig { cases: 512, ..ProptestConfig::default() })]
#[test]
fn media_parsers_never_panic(data in proptest::collection::vec(any::<u8>(), 0..200)) {
let rtp = parse_rtp_header(&data);
let video = parse_video_packet(&data);
let frame = parse_frame_header(&data);
let audio = parse_audio_packet(&data);
prop_assert!(common::implemented(&rtp) && common::implemented(&video) && common::implemented(&frame) && common::implemented(&audio));
if let Ok(h) = rtp {
prop_assert!(data.len() >= RTP_HEADER_LEN);
prop_assert_eq!(h.flags >> 6, 2);
}
if let Ok(p) = video {
prop_assert_eq!(p.payload.len() + PAYLOAD_OFFSET, data.len());
prop_assert!(p.nv.fec.data_shards > 0);
prop_assert!(p.nv.fec.block_index <= p.nv.fec.last_block_index);
}
if let Ok(h) = frame {
prop_assert_eq!(&h.raw[..], &data[..FRAME_HEADER_LEN]);
}
match audio {
Ok(AudioPacket::Data { payload, .. }) => prop_assert!(!payload.is_empty()),
Ok(AudioPacket::Parity { fec, parity, .. }) => prop_assert!(!parity.is_empty() && fec.shard_index <= 1),
Err(_) => {}
}
prop_assert!(common::implemented(&VideoCipher::new([1; 16]).decrypt(&data)));
let audio_cipher = AudioCipher::new(&SessionKeys { rikey: [1; 16], rikeyid: 0 });
prop_assert!(common::implemented(&audio_cipher.decrypt(0, &data)));
}
#[test]
fn audio_round_trip_through_the_oracle(rikeyid in any::<u32>(), seq in any::<u16>(), plain in proptest::collection::vec(any::<u8>(), 0..100)) {
let key = [0x5Au8; 16];
let c = AudioCipher::new(&SessionKeys { rikey: key, rikeyid });
let ct = common::audio_encrypt(&key, rikeyid, seq, &plain);
prop_assert_eq!(c.decrypt(seq, &ct), Ok(plain));
}
#[test]
fn video_round_trip_through_the_oracle(counter in any::<u64>(), frame in any::<u32>(), plain in proptest::collection::vec(any::<u8>(), 32..300)) {
let key = [0xA5u8; 16];
let p = common::video_encrypt(&key, counter, frame, &plain);
prop_assert_eq!(VideoCipher::new(key).decrypt(&p), Ok(plain));
}
}
+865
View File
@@ -0,0 +1,865 @@
//! 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, state) in STATES.iter().enumerate().take(3) {
let (mut s, mut rng, id) = session_after(steps);
assert_eq!(s.state(), *state);
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);
}
+787
View File
@@ -0,0 +1,787 @@
//! 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)) {
let parsed = parse_response(&data);
prop_assert!(common::implemented(&parsed));
if let Ok(r) = parsed {
prop_assert!(r.headers.len() <= MAX_RTSP_HEADERS);
prop_assert!(r.body.len() <= data.len());
prop_assert!(r.reason.len() <= MAX_RTSP_LINE_BYTES);
}
prop_assert!(common::implemented(&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 { .. });
}
}
+670
View File
@@ -0,0 +1,670 @@
//! The video depacketizer (`docs/PROTOCOL.md` 5) driven with generated loss patterns over multi-block frames:
//! random, bursty, all parity lost, all data lost but recoverable, last packet lost, reordered, duplicated,
//! sequence and frame index wraps, far-past and far-future packets, encryption. Every frame comes out byte-exact or
//! is reported in a `FrameLost` range; never a corrupt frame.
//!
//! The test host (`common::VideoHost`) packetizes as PROTOCOL.md 5.2-5.3 say, computes parity with the crate's own
//! `ReedSolomon::new` (U14 is unknown; `fec.rs` tests the code itself) and writes the parity packets' headers after
//! the parity, so bytes 0-31 of any recovered data shard are garbage.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
mod common;
use core::time::Duration;
use std::collections::{BTreeMap, BTreeSet, HashMap};
use common::{SeqRng, VExpect, VPkt, VideoHost, fec_info, video_packet_bytes};
use domistream::video::packet::MAX_VIDEO_PACKET_BYTES;
use domistream::video::{MAX_FRAMES_IN_FLIGHT, VideoCipher, VideoConfig, VideoDepacketizer, VideoEvent, VideoStats};
use domistream::{Error, Instant};
use proptest::prelude::*;
const PACKET_SIZE: u16 = 64; // payload 48 bytes, packet 80 bytes
const TIMEOUT: Duration = Duration::from_millis(50);
const KEY: [u8; 16] = *b"video-test-key!!";
fn config(cipher: bool) -> VideoConfig {
VideoConfig { packet_size: PACKET_SIZE, cipher: cipher.then(|| VideoCipher::new(KEY)), frame_timeout: TIMEOUT }
}
/// One frame of a scenario: its packets as sent and what must come out.
#[derive(Clone, Debug)]
struct Frame {
packets: Vec<VPkt>,
expect: VExpect,
}
fn frames(rng: &mut SeqRng, host: &mut VideoHost, first_index: u32, n: usize, percentages: &[u8]) -> Vec<Frame> {
(0..n)
.map(|i| {
let len = 10 + rng.below(48 * 14);
let bitstream = VideoHost::bitstream(rng, len);
let pct = percentages[rng.below(percentages.len())];
let blocks = 1 + rng.below(4);
let (packets, expect) = host.frame(first_index.wrapping_add(i as u32), &bitstream, pct, blocks);
Frame { packets, expect }
})
.collect()
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Outcome {
Deliver,
Lose,
}
/// Whether a frame can be rebuilt from the packets that arrive (by shard identity, duplicates counted once).
fn outcome(frame: &Frame, arrived: &[&VPkt]) -> Outcome {
let mut have: BTreeMap<u8, BTreeSet<u16>> = BTreeMap::new();
for p in arrived {
have.entry(p.block).or_default().insert(p.shard_index);
}
let blocks: BTreeMap<u8, u16> = frame.packets.iter().map(|p| (p.block, p.data_shards)).collect();
if blocks.iter().all(|(b, k)| have.get(b).map_or(0, BTreeSet::len) >= usize::from(*k)) {
Outcome::Deliver
} else {
Outcome::Lose
}
}
/// Data shards a frame lost (what `recovered_shards` must say when it is delivered).
fn data_lost(frame: &Frame, arrived: &[&VPkt]) -> u16 {
let got: BTreeSet<(u8, u16)> = arrived.iter().map(|p| (p.block, p.shard_index)).collect();
frame.packets.iter().filter(|p| !p.is_parity && !got.contains(&(p.block, p.shard_index))).count() as u16
}
struct Run {
events: Vec<VideoEvent>,
stats: VideoStats,
}
fn run_with(cipher: bool, datagrams: &[Vec<u8>]) -> Run {
let mut d = VideoDepacketizer::new(config(cipher)).expect("VideoDepacketizer::new");
let mut now = 1_000_000u64;
let mut events = Vec::new();
for g in datagrams {
d.push(Instant::from_micros(now), g).expect("push never fails for packets within the size cap");
now += 10;
while let Some(e) = d.poll_event() {
events.push(e);
}
}
// Flush: let every incomplete frame time out.
for _ in 0..64 {
now += 10_000_000;
d.handle_timeout(Instant::from_micros(now)).unwrap();
while let Some(e) = d.poll_event() {
events.push(e);
}
if d.poll_timeout().is_none() {
break;
}
}
Run { events, stats: d.stats() }
}
/// Every Frame event is byte-exact, in order, at most once; every frame marked `Deliver` came out; every frame marked
/// `Lose` is in a FrameLost range; nothing is both.
fn check(frames: &[Frame], outcomes: &[Outcome], recovered: Option<&[u16]>, run: &Run) {
let pos: HashMap<u32, usize> = frames.iter().enumerate().map(|(i, f)| (f.expect.frame_index, i)).collect();
let mut delivered = vec![false; frames.len()];
let mut lost = vec![false; frames.len()];
let mut last_pos: Option<usize> = None;
for e in &run.events {
match e {
VideoEvent::Frame(f) => {
let &i = pos.get(&f.frame_index).unwrap_or_else(|| panic!("frame {} was never sent", f.frame_index));
let want = &frames[i].expect;
assert!(
f.bitstream == want.bitstream,
"frame {} corrupt: {} bytes, want {}",
f.frame_index,
f.bitstream.len(),
want.bitstream.len()
);
assert_eq!(f.header.raw, want.header, "frame {} header", f.frame_index);
assert_eq!(f.rtp_timestamp, want.rtp_timestamp, "frame {} timestamp", f.frame_index);
assert!(f.completed_at >= f.first_packet_at);
assert!(!delivered[i], "frame {} delivered twice", f.frame_index);
assert!(last_pos.is_none_or(|l| i > l), "frame {} out of order", f.frame_index);
if let Some(r) = recovered {
assert_eq!(f.recovered_shards, r[i], "frame {} recovered shards", f.frame_index);
}
last_pos = Some(i);
delivered[i] = true;
}
VideoEvent::FrameLost { first, last } => {
let span = last.wrapping_sub(*first);
assert!(span < 1 << 31, "FrameLost {first}..={last} is not a forward range");
for (i, f) in frames.iter().enumerate() {
if f.expect.frame_index.wrapping_sub(*first) <= span {
lost[i] = true;
}
}
}
}
}
for (i, f) in frames.iter().enumerate() {
let idx = f.expect.frame_index;
assert!(!(delivered[i] && lost[i]), "frame {idx} both delivered and reported lost");
match outcomes[i] {
Outcome::Deliver => {
assert!(delivered[i], "frame {idx} was recoverable but not delivered (lost: {})", lost[i])
}
Outcome::Lose => assert!(lost[i], "frame {idx} was not recoverable but not reported lost"),
}
}
}
/// Runs a scenario where `keep(frame_number, packet_number_in_frame, packet)` decides what arrives (frames 0 and
/// last are always kept whole), optionally reordered and duplicated.
fn scenario(
seed: u64,
n: usize,
percentages: &[u8],
keep: impl Fn(&mut SeqRng, usize, usize, &VPkt) -> bool,
) -> (Vec<Frame>, Vec<Outcome>, Vec<u16>, Vec<Vec<u8>>) {
let mut rng = SeqRng::new(seed);
let mut host = VideoHost::new(PACKET_SIZE);
let fs = frames(&mut rng, &mut host, 0, n, percentages);
let mut outcomes = Vec::new();
let mut recovered = Vec::new();
let mut datagrams = Vec::new();
for (fi, f) in fs.iter().enumerate() {
let arrived: Vec<&VPkt> = f
.packets
.iter()
.enumerate()
.filter(|(pi, p)| fi == 0 || fi == n - 1 || keep(&mut rng, fi, *pi, p))
.map(|(_, p)| p)
.collect();
outcomes.push(outcome(f, &arrived));
recovered.push(data_lost(f, &arrived));
datagrams.extend(arrived.iter().map(|p| p.bytes.clone()));
}
(fs, outcomes, recovered, datagrams)
}
const MIXED: &[u8] = &[0, 10, 20, 50, 100, 200];
// ================================================================================================ patterns
#[test]
fn no_loss() {
let (fs, out, rec, dg) = scenario(1, 30, MIXED, |_, _, _, _| true);
assert!(out.iter().all(|o| *o == Outcome::Deliver));
let r = run_with(false, &dg);
check(&fs, &out, Some(&rec), &r);
assert_eq!(r.stats.frames, 30);
assert_eq!(r.stats.frames_lost, 0);
assert_eq!(r.stats.shards_recovered, 0);
assert_eq!(r.stats.packets_dropped, 0);
assert_eq!(r.stats.packets, dg.len() as u64);
}
#[test]
fn random_loss() {
for (seed, p) in [(10u64, 5usize), (11, 15), (12, 30), (13, 50), (14, 15), (15, 30)] {
let (fs, out, rec, dg) = scenario(seed, 40, MIXED, move |rng, _, _, _| rng.below(100) >= p);
let r = run_with(false, &dg);
check(&fs, &out, Some(&rec), &r);
let delivered = out.iter().filter(|o| **o == Outcome::Deliver).count() as u64;
assert_eq!(r.stats.frames, delivered, "seed {seed}");
// At least the shards of delivered frames; blocks rebuilt inside frames that were lost anyway may add more.
assert!(
r.stats.shards_recovered
>= rec
.iter()
.zip(&out)
.filter(|(_, o)| **o == Outcome::Deliver)
.map(|(r, _)| u64::from(*r))
.sum::<u64>()
);
}
}
#[test]
fn bursty_loss() {
for seed in 20..26u64 {
// One burst of 1..=8 consecutive packets per frame, at a random place.
let mut rng = SeqRng::new(seed * 7);
let bursts: Vec<(usize, usize)> = (0..40).map(|_| (rng.below(30), 1 + rng.below(8))).collect();
let (fs, out, rec, dg) = scenario(seed, 40, MIXED, move |_, fi, pi, _| {
let (start, len) = bursts[fi];
!(start..start + len).contains(&pi)
});
check(&fs, &out, Some(&rec), &run_with(false, &dg));
}
// A burst across a frame boundary: the tail of one frame and the head of the next.
let (fs, _, _, _) = scenario(27, 3, &[50], |_, _, _, _| true);
let mut dg = Vec::new();
let mut arrived: Vec<Vec<&VPkt>> = vec![Vec::new(); 3];
for (fi, f) in fs.iter().enumerate() {
for (pi, p) in f.packets.iter().enumerate() {
let tail = fi == 1 && pi + 2 >= f.packets.len();
let head = fi == 2 && pi < 2;
if !(tail || head) {
arrived[fi].push(p);
dg.push(p.bytes.clone());
}
}
}
let out: Vec<Outcome> = fs.iter().zip(&arrived).map(|(f, a)| outcome(f, a)).collect();
check(&fs, &out, None, &run_with(false, &dg));
}
#[test]
fn all_parity_lost() {
let (fs, out, rec, dg) = scenario(30, 30, &[20, 50, 100], |_, _, _, p| !p.is_parity);
assert!(out.iter().all(|o| *o == Outcome::Deliver));
assert!(rec.iter().all(|r| *r == 0));
check(&fs, &out, Some(&rec), &run_with(false, &dg));
}
#[test]
fn all_data_lost_but_recoverable() {
// 100 % and 200 % FEC: every data shard of a frame lost, rebuilt from parity alone.
let (fs, out, rec, dg) = scenario(31, 20, &[100, 200], |_, _, _, p| p.is_parity);
assert!(out.iter().all(|o| *o == Outcome::Deliver));
let r = run_with(false, &dg);
check(&fs, &out, Some(&rec), &r);
assert!(r.stats.shards_recovered > 0);
}
#[test]
fn last_packet_lost() {
// The last packet of each frame (its last parity packet, or the end-of-frame data packet without FEC).
let (fs, ..) = scenario(32, 30, MIXED, |_, _, _, _| true);
let mut datagrams = Vec::new();
let mut outcomes = Vec::new();
let mut recovered = Vec::new();
for (fi, f) in fs.iter().enumerate() {
let n = f.packets.len();
let arrived: Vec<&VPkt> =
f.packets.iter().take(if fi == 0 || fi + 1 == fs.len() { n } else { n - 1 }).collect();
outcomes.push(outcome(f, &arrived));
recovered.push(data_lost(f, &arrived));
datagrams.extend(arrived.iter().map(|p| p.bytes.clone()));
}
check(&fs, &outcomes, Some(&recovered), &run_with(false, &datagrams));
// The end-of-frame data packet itself (flags 0x02), with FEC to rebuild it.
let (fs, out, rec, dg) = scenario(33, 30, &[20, 50], |_, _, _, p| p.is_parity || p.bytes[24] & 0x02 == 0);
assert!(out.iter().all(|o| *o == Outcome::Deliver));
check(&fs, &out, Some(&rec), &run_with(false, &dg));
// ... and without FEC: lost.
let (fs, out, rec, dg) = scenario(34, 10, &[0], |_, _, _, p| p.bytes[24] & 0x02 == 0);
assert!(out[1..9].iter().all(|o| *o == Outcome::Lose));
check(&fs, &out, Some(&rec), &run_with(false, &dg));
}
#[test]
fn reordered() {
for seed in 40..46u64 {
let (fs, out, _, mut dg) = scenario(seed, 30, MIXED, move |rng, _, _, _| rng.below(100) >= 10);
// Shuffle within windows spanning about two frames.
let mut rng = SeqRng::new(seed);
let first_len = fs[0].packets.len();
let window = 24;
let mut i = first_len; // keep frame 0 first so the stream has a known start
while i < dg.len() {
let end = (i + window).min(dg.len());
rng.shuffle(&mut dg[i..end]);
i = end;
}
check(&fs, &out, None, &run_with(false, &dg));
}
}
#[test]
fn duplicated() {
for seed in 50..54u64 {
let (fs, out, _, dg) = scenario(seed, 30, MIXED, move |rng, _, _, _| rng.below(100) >= 10);
let mut rng = SeqRng::new(seed);
let mut with_dups = Vec::new();
let mut dups = 0u64;
for (i, g) in dg.iter().enumerate() {
with_dups.push(g.clone());
if i > 0 && rng.below(100) < 30 {
// Again now, and an earlier packet again later.
with_dups.push(g.clone());
with_dups.push(dg[rng.below(i)].clone());
dups += 2;
}
}
let r = run_with(false, &with_dups);
check(&fs, &out, None, &r);
assert!(
r.stats.packets_dropped >= dups / 2,
"duplicates are counted as dropped: {} of {dups}",
r.stats.packets_dropped
);
}
}
#[test]
fn reordered_and_duplicated_with_loss() {
for seed in 60..64u64 {
let (fs, out, _, dg) = scenario(seed, 40, MIXED, move |rng, _, _, _| rng.below(100) >= 20);
let mut rng = SeqRng::new(seed ^ 0xFF);
let mut mixed: Vec<Vec<u8>> = dg
.iter()
.flat_map(|g| if rng.below(5) == 0 { vec![g.clone(), g.clone()] } else { vec![g.clone()] })
.collect();
let start = fs[0].packets.len();
let mut i = start;
while i < mixed.len() {
let end = (i + 16).min(mixed.len());
rng.shuffle(&mut mixed[i..end]);
i = end;
}
check(&fs, &out, None, &run_with(false, &mixed));
}
}
// ================================================================================================ untrusted bytes 0-31
#[test]
fn recovered_shard_headers_are_not_trusted() {
// Parity computed over data shards whose bytes 0-31 were scrambled: a rebuilt shard's RTP and NV header bytes
// are guaranteed garbage (wrong frame index, flags, FEC fields). Only its payload and its place from the shard
// index may be used.
let mut rng = SeqRng::new(70);
let mut host = VideoHost::new(PACKET_SIZE);
host.scramble_parity_headers = true;
let fs = frames(&mut rng, &mut host, 0, 30, &[50, 100]);
let mut dg = Vec::new();
let mut out = Vec::new();
let mut rec = Vec::new();
for (fi, f) in fs.iter().enumerate() {
// Lose the first data shard of every block (often the start-of-frame packet) and, where the budget allows,
// the end-of-frame packet.
let arrived: Vec<&VPkt> = f
.packets
.iter()
.filter(|p| {
fi == 0 || p.is_parity || (p.shard_index != 0 && !(p.bytes[24] & 0x02 != 0 && p.parity_shards >= 2))
})
.collect();
out.push(outcome(f, &arrived));
rec.push(data_lost(f, &arrived));
dg.extend(arrived.iter().map(|p| p.bytes.clone()));
}
assert!(out.iter().all(|o| *o == Outcome::Deliver));
let r = run_with(false, &dg);
check(&fs, &out, Some(&rec), &r);
assert!(r.stats.shards_recovered >= 30);
}
// ================================================================================================ wraps and strays
#[test]
fn rtp_sequence_wraps_inside_frames() {
let mut rng = SeqRng::new(80);
let mut host = VideoHost::new(PACKET_SIZE);
host.next_sequence = 0xFFE0;
let fs = frames(&mut rng, &mut host, 0, 20, &[20, 50]);
assert!(host.next_sequence < 0xFFE0, "the stream passed 0xFFFF -> 0");
let mut dg = Vec::new();
let mut out = Vec::new();
for (fi, f) in fs.iter().enumerate() {
let arrived: Vec<&VPkt> =
f.packets.iter().enumerate().filter(|(pi, _)| fi == 0 || pi % 5 != 1).map(|(_, p)| p).collect();
out.push(outcome(f, &arrived));
dg.extend(arrived.iter().map(|p| p.bytes.clone()));
}
check(&fs, &out, None, &run_with(false, &dg));
}
#[test]
fn frame_index_wraps() {
let mut rng = SeqRng::new(81);
let mut host = VideoHost::new(PACKET_SIZE);
let fs = frames(&mut rng, &mut host, u32::MAX - 5, 12, &[50]);
assert_eq!(fs[6].expect.frame_index, 0);
let mut dg = Vec::new();
let mut out = Vec::new();
for (fi, f) in fs.iter().enumerate() {
// Frame 0 (the one after u32::MAX) is entirely lost; the others lose one packet.
let arrived: Vec<&VPkt> =
if f.expect.frame_index == 0 { vec![] } else { f.packets.iter().skip(usize::from(fi != 0)).collect() };
out.push(outcome(f, &arrived));
dg.extend(arrived.iter().map(|p| p.bytes.clone()));
}
assert_eq!(out[6], Outcome::Lose);
check(&fs, &out, None, &run_with(false, &dg));
}
#[test]
fn far_past_and_far_future_packets() {
let mut rng = SeqRng::new(82);
let mut host = VideoHost::new(PACKET_SIZE);
let fs = frames(&mut rng, &mut host, 5000, 10, &[50]);
let mut dg: Vec<Vec<u8>> = fs[..5].iter().flat_map(|f| f.packets.iter().map(|p| p.bytes.clone())).collect();
// A stray from long ago, a replay of an already delivered frame, and a lone packet from far ahead.
let mut stray = fs[0].packets[0].bytes.clone();
stray[20..24].copy_from_slice(&(5000u32 - 1000).to_le_bytes());
dg.push(stray);
dg.push(fs[1].packets[0].bytes.clone());
let mut future = fs[5].packets[0].bytes.clone();
future[20..24].copy_from_slice(&(5000u32 + 1_000_000).to_le_bytes());
dg.push(future);
dg.extend(fs[5..].iter().flat_map(|f| f.packets.iter().map(|p| p.bytes.clone())));
let r = run_with(false, &dg);
assert!(r.stats.packets_dropped >= 2, "the far-past stray and the replay are dropped: {:?}", r.stats);
// Whatever the far-future packet does, no frame comes out corrupt, none twice, and none out of order.
let pos: HashMap<u32, usize> = fs.iter().enumerate().map(|(i, f)| (f.expect.frame_index, i)).collect();
let mut seen = BTreeSet::new();
let mut prev = None;
for e in &r.events {
match e {
VideoEvent::Frame(f) => {
let &i = pos.get(&f.frame_index).unwrap_or_else(|| panic!("frame {} was never sent", f.frame_index));
assert_eq!(f.bitstream, fs[i].expect.bitstream);
assert!(seen.insert(i));
assert!(prev.is_none_or(|l| i > l));
prev = Some(i);
}
VideoEvent::FrameLost { first, last } => assert!(last.wrapping_sub(*first) < 1 << 31),
}
}
assert!((0..5).all(|i| seen.contains(&i)), "frames before the strays are delivered");
}
#[test]
fn bad_packets_inside_a_frame_are_dropped_not_used() {
let mut rng = SeqRng::new(83);
let mut host = VideoHost::new(PACKET_SIZE);
let fs = frames(&mut rng, &mut host, 0, 6, &[50]);
let mut dg = Vec::new();
for f in &fs {
for p in &f.packets {
dg.push(p.bytes.clone());
}
// Junk carrying the frame's own index: short, long, with impossible FEC fields.
let mut short = f.packets[0].bytes.clone();
short.truncate(50);
let mut long = f.packets[0].bytes.clone();
long.extend_from_slice(&[0xEE; 7]);
let bad_fec = video_packet_bytes(0, 0, f.expect.frame_index, 0x01, 0, fec_info(50, 900, 2), &[0xEE; 48]);
dg.extend([short, long, bad_fec, vec![], vec![0x90]]);
}
let r = run_with(false, &dg);
let out = vec![Outcome::Deliver; fs.len()];
check(&fs, &out, None, &r);
assert!(r.stats.packets_dropped >= 5 * fs.len() as u64);
}
// ================================================================================================ encryption
#[test]
fn encrypted_stream_with_loss_and_tampering() {
let mut rng = SeqRng::new(90);
let mut host = VideoHost::new(PACKET_SIZE);
let fs = frames(&mut rng, &mut host, 0, 30, &[50, 100]);
let mut counter = 0u64;
let mut dg = Vec::new();
let mut out = Vec::new();
let mut tampered = 0u64;
for (fi, f) in fs.iter().enumerate() {
let mut arrived = Vec::new();
for (pi, p) in f.packets.iter().enumerate() {
let mut e = common::video_encrypt(&KEY, counter, f.expect.frame_index, &p.bytes);
counter += 1;
if fi != 0 && pi == 1 {
// A flipped ciphertext byte: the tag fails, the packet counts as lost.
let last = e.len() - 1;
e[last] ^= 0x01;
tampered += 1;
} else if fi != 0 && rng.below(100) < 10 {
continue;
} else {
arrived.push(p);
}
dg.push(e);
}
out.push(outcome(f, &arrived));
}
let r = run_with(true, &dg);
check(&fs, &out, None, &r);
assert!(r.stats.packets_dropped >= tampered);
// The same plaintext packets fed to a receiver that expects encryption are refused, not decoded.
let plain: Vec<Vec<u8>> = fs.iter().flat_map(|f| f.packets.iter().map(|p| p.bytes.clone())).collect();
let r = run_with(true, &plain);
assert!(r.events.iter().all(|e| !matches!(e, VideoEvent::Frame(_))));
assert_eq!(r.stats.packets_dropped, plain.len() as u64);
}
// ================================================================================================ API edges
#[test]
fn config_bounds() {
for ps in [0u16, 1, 15] {
assert_err!(
VideoDepacketizer::new(VideoConfig { packet_size: ps, ..config(false) }),
Error::Malformed { .. },
"packet_size {ps}"
);
}
let max = (MAX_VIDEO_PACKET_BYTES - 16) as u16;
assert!(VideoDepacketizer::new(VideoConfig { packet_size: max, ..config(false) }).is_ok());
assert_err!(VideoDepacketizer::new(VideoConfig { packet_size: max + 1, ..config(false) }), Error::Malformed { .. });
assert_err!(
VideoDepacketizer::new(VideoConfig { packet_size: u16::MAX, ..config(false) }),
Error::Malformed { .. }
);
assert!(VideoDepacketizer::new(VideoConfig { packet_size: 1024, ..config(true) }).is_ok());
}
#[test]
fn push_sizes() {
let mut d = VideoDepacketizer::new(config(false)).unwrap();
assert_too_large!(
d.push(Instant::ZERO, &vec![0; MAX_VIDEO_PACKET_BYTES + 1]),
MAX_VIDEO_PACKET_BYTES,
MAX_VIDEO_PACKET_BYTES + 1
);
assert_too_large!(d.push(Instant::ZERO, &vec![0; 1 << 20]), MAX_VIDEO_PACKET_BYTES, 1 << 20);
for g in [vec![], vec![0x90], vec![0; 31], vec![0xFF; 80], vec![0; MAX_VIDEO_PACKET_BYTES]] {
assert_eq!(d.push(Instant::ZERO, &g), Ok(()));
}
assert_eq!(d.stats().packets_dropped, 5);
assert_eq!(d.poll_event(), None);
}
#[test]
fn incomplete_frame_times_out() {
let mut rng = SeqRng::new(100);
let mut host = VideoHost::new(PACKET_SIZE);
let fs = frames(&mut rng, &mut host, 0, 2, &[0]);
let mut d = VideoDepacketizer::new(config(false)).unwrap();
let t0 = Instant::from_micros(5_000_000);
for p in &fs[0].packets {
d.push(t0, &p.bytes).unwrap();
}
match d.poll_event() {
Some(VideoEvent::Frame(f)) => {
assert_eq!(f.first_packet_at, t0);
assert_eq!(f.completed_at, t0);
assert_eq!(f.frame_index, 0);
}
other => panic!("{other:?}"),
}
assert_eq!(d.poll_timeout(), None, "nothing pending");
// Frame 1 without its last packet (no FEC): pending until its timeout.
let n = fs[1].packets.len();
let t1 = Instant::from_micros(6_000_000);
for p in &fs[1].packets[..n - 1] {
d.push(t1, &p.bytes).unwrap();
}
if n == 1 {
return;
}
assert_eq!(d.poll_event(), None);
let deadline = d.poll_timeout().expect("a deadline for the incomplete frame");
assert!(deadline > t1 && deadline <= t1.saturating_add(TIMEOUT), "{deadline:?}");
d.handle_timeout(t1.saturating_add(TIMEOUT / 2)).unwrap();
assert_eq!(d.poll_event(), None, "not before the timeout");
d.handle_timeout(t1.saturating_add(TIMEOUT)).unwrap();
assert_eq!(d.poll_event(), Some(VideoEvent::FrameLost { first: 1, last: 1 }));
assert_eq!(d.stats().frames_lost, 1);
}
#[test]
fn frames_in_flight_are_capped() {
// One packet each of many incomplete frames: the oldest are declared lost before any timeout.
let mut rng = SeqRng::new(101);
let mut host = VideoHost::new(PACKET_SIZE);
let fs = frames(&mut rng, &mut host, 0, MAX_FRAMES_IN_FLIGHT + 5, &[0]);
let mut d = VideoDepacketizer::new(config(false)).unwrap();
for p in &fs[0].packets {
d.push(Instant::ZERO, &p.bytes).unwrap();
}
let mut lost = BTreeSet::new();
for f in &fs[1..] {
if f.packets.len() < 2 {
continue;
}
d.push(Instant::ZERO, &f.packets[0].bytes).unwrap();
}
while let Some(e) = d.poll_event() {
if let VideoEvent::FrameLost { first, last } = e {
lost.extend(first..=last);
}
}
assert!(!lost.is_empty(), "more than MAX_FRAMES_IN_FLIGHT incomplete frames: the oldest must be given up");
assert!(!lost.contains(&0));
}
proptest! {
#![proptest_config(ProptestConfig { cases: 48, ..ProptestConfig::default() })]
/// Random frames, random loss, random reordering: exact or reported lost, never corrupt.
#[test]
fn generated_patterns(seed in any::<u64>(), loss in 0usize..60, window in 1usize..30, dup in 0usize..30) {
let (fs, out, _, dg) = scenario(seed, 16, MIXED, move |rng, _, _, _| rng.below(100) >= loss);
let mut rng = SeqRng::new(seed.rotate_left(17));
let mut mixed: Vec<Vec<u8>> = dg.iter().flat_map(|g| if rng.below(100) < dup { vec![g.clone(), g.clone()] } else { vec![g.clone()] }).collect();
let mut i = fs[0].packets.len();
while i < mixed.len() {
let end = (i + window).min(mixed.len());
rng.shuffle(&mut mixed[i..end]);
i = end;
}
check(&fs, &out, None, &run_with(false, &mixed));
}
/// Arbitrary datagrams never panic, and nothing that comes out is larger than the frame cap.
#[test]
fn arbitrary_datagrams(datagrams in proptest::collection::vec(proptest::collection::vec(any::<u8>(), 0..120), 0..60)) {
let r = run_with(false, &datagrams);
for e in r.events {
match e {
VideoEvent::Frame(f) => prop_assert!(f.bitstream.len() <= domistream::video::MAX_FRAME_BYTES),
VideoEvent::FrameLost { first, last } => prop_assert!(last.wrapping_sub(first) < 1 << 31),
}
}
}
}
+6 -15
View File
@@ -12,20 +12,16 @@ GPL-licensed implementation. This file says what may be read, what may not, and
| [Moonshine](https://github.com/hgaiser/moonshine) | BSD-2-Clause | May be read. Facts taken are logged below. Code is not copied; if a snippet is ever borrowed, it keeps Moonshine's copyright line and licence text in the file that holds it. | | [Moonshine](https://github.com/hgaiser/moonshine) | BSD-2-Clause | May be read. Facts taken are logged below. Code is not copied; if a snippet is ever borrowed, it keeps Moonshine's copyright line and licence text in the file that holds it. |
| RFCs and standards (RTP RFC 3550, RTSP RFC 2326, SDP RFC 4566, Opus RFC 6716 / RFC 7845, AES FIPS 197, GCM/CBC NIST SP 800-38D/38A, PKCS #1 RFC 8017, X.509 RFC 5280) | open standards | Read freely. | | RFCs and standards (RTP RFC 3550, RTSP RFC 2326, SDP RFC 4566, Opus RFC 6716 / RFC 7845, AES FIPS 197, GCM/CBC NIST SP 800-38D/38A, PKCS #1 RFC 8017, X.509 RFC 5280) | open standards | Read freely. |
| Crate docs (docs.rs, crates.io, crate READMEs) | per crate | Read freely. | | Crate docs (docs.rs, crates.io, crate READMEs) | per crate | Read freely. |
| Our own measurements | ours | Captures through our own relay ([tools/lab-relay](../tools/lab-relay)). Mark allowed **one** capture on his PC (answer 16, 2026-11-25), done exactly as [LAB_CAPTURE.md](LAB_CAPTURE.md) says; never his TV, never 192.168.100.217. Recordings stay local (on E:, approved for Play remotely) under `E:\build\play-remotely\lab\`, out of git; only facts and test vectors derived from them go in, with the date and setup. | | Our own measurements | ours | Captures between our client and a host on a **lab machine** (never Mark's PC, never Mark's TV, never 192.168.100.217). Captures stay out of git; only the facts and test vectors derived from them go in, with the date and setup. |
| Official Sunshine and Moonlight PC **binaries** in that capture | GPL-3.0 (we only run them) | Black-box peers: run, observe their traffic, their `--help` output, their own logs and the files/registry keys they write. Never open their source, never disassemble or decompile them. |
| READMEs and wikis of forbidden projects | n/a | For facts only (licence, release notes, compatibility statements). Never their source files. | | READMEs and wikis of forbidden projects | n/a | For facts only (licence, release notes, compatibility statements). Never their source files. |
### Approved by Mark (answer 15, 2026-11-25): "Yes, with attribution" ### Proposed additions (need the build lead's yes before use)
Read for the wire format; anything borrowed beyond a fact is attributed in the file that holds it. GPL stays off
limits, and a value with GPL provenance stays out even when one of these sources carries it.
| Source | Licence | Why | | Source | Licence | Why |
| :-- | :-- | :-- | | :-- | :-- | :-- |
| [Stock ENet](https://github.com/lsalzman/enet) | MIT | The ENet 1.3 wire format is documented nowhere else. Read at v1.3.18 (S-17). | | [Stock ENet](https://github.com/lsalzman/enet) (`protocol.h`, `protocol.c`) | MIT | The ENet 1.3 wire format is not documented anywhere else in prose. The Wolf docs do not describe it. |
| [tokio-enet](https://github.com/hgaiser/tokio-enet) | BSD-2-Clause | Pure-Rust ENet 1.3 that Moonshine uses with Moonlight clients (S-10, now approved). | | [tokio-enet](https://github.com/hgaiser/tokio-enet) source | BSD-2-Clause | A pure-Rust ENet 1.3 used by Moonshine to talk to Moonlight clients. Its `src/protocol/` files were read for the command list (logged below, S-10). |
| [fec-rs](https://github.com/hgaiser/fec-rs) | BSD-2-Clause | Reed-Solomon whose README claims Moonlight compatibility; its matrix construction settles U14 (S-18). | | [fec-rs](https://github.com/hgaiser/fec-rs) source | BSD-2-Clause | Its README says its field setup is compatible with Moonlight. Reading its matrix construction would settle UNKNOWN U14 (video FEC). |
## Forbidden ## Forbidden
@@ -43,7 +39,6 @@ copied into DomiStream, and settled by our own measurement instead. Known cases:
| :-- | :-- | :-- | | :-- | :-- | :-- |
| `src/session/stream/audio/encoder.rs` | the fixed 2x4 Reed-Solomon parity matrix for audio FEC; the comment cites a moonlight-common-c file | Not taken. I saw the constant while reading the file; it is not in this repo. U16 in [PROTOCOL.md](PROTOCOL.md) says how to measure it ourselves. | | `src/session/stream/audio/encoder.rs` | the fixed 2x4 Reed-Solomon parity matrix for audio FEC; the comment cites a moonlight-common-c file | Not taken. I saw the constant while reading the file; it is not in this repo. U16 in [PROTOCOL.md](PROTOCOL.md) says how to measure it ourselves. |
| `src/session/stream/control/mod.rs` | HDR mode payload "matches Sunshine's" struct | Field layout logged as `[M*]`, confirm by measurement before relying on it | | `src/session/stream/control/mod.rs` | HDR mode payload "matches Sunshine's" struct | Field layout logged as `[M*]`, confirm by measurement before relying on it |
| fec-rs `src/reed_solomon.rs` tests (`test_partial_eq_reflects_parity_matrix_changes`) | the same audio parity matrix as Moonshine's encoder | Not taken, same rule. Seen while reading fec-rs on 2026-11-25. |
| `src/rtsp.rs` | `surround-params` digit packing "matching moonlight-common-c" | The Wolf example `surround-params=21101` gives the same packing independently, so we use the Wolf source | | `src/rtsp.rs` | `surround-params` digit packing "matching moonlight-common-c" | The Wolf example `surround-params=21101` gives the same packing independently, so we use the Wolf source |
## How code gets written ## How code gets written
@@ -69,14 +64,10 @@ All entries by the DomiStream protocol engineer. Pinned commits are the ones rea
| S-7 | 2026-11-25 | [Wolf: input](https://games-on-whales.github.io/wolf/stable/protocols/input-data.html) incl. bytefield sources | INPUT_DATA layout (size BE, type LE); input type codes; layouts and example bytes for mouse move rel/abs, buttons, keys, scroll, hscroll, controller arrival, controller multi; key code table; button flags; controller types and capability bits. | | S-7 | 2026-11-25 | [Wolf: input](https://games-on-whales.github.io/wolf/stable/protocols/input-data.html) incl. bytefield sources | INPUT_DATA layout (size BE, type LE); input type codes; layouts and example bytes for mouse move rel/abs, buttons, keys, scroll, hscroll, controller arrival, controller multi; key code table; button flags; controller types and capability bits. |
| S-8 | 2026-11-25 | GitHub API for [games-on-whales/wolf](https://github.com/games-on-whales/wolf) (`/repos`, `/git/trees/beta`, `LICENSE`, `docs/README.adoc`) | Repo licence MIT; the docs live in `docs/modules/protocols/pages/*.adoc` of the same repo; latest tag `v2026.11`. No source files of Wolf were read. | | S-8 | 2026-11-25 | GitHub API for [games-on-whales/wolf](https://github.com/games-on-whales/wolf) (`/repos`, `/git/trees/beta`, `LICENSE`, `docs/README.adoc`) | Repo licence MIT; the docs live in `docs/modules/protocols/pages/*.adoc` of the same repo; latest tag `v2026.11`. No source files of Wolf were read. |
| S-9 | 2026-11-25 | [Moonshine](https://github.com/hgaiser/moonshine) at `f184d5e3693e09c3a6ab1025bde6cdb67f36a6bc`: `LICENSE`, `README.md`, `Cargo.toml`, `src/clients.rs`, `src/crypto.rs`, `src/webserver/pairing.rs`, `src/webserver/mod.rs`, `src/rtsp.rs`, `src/session/stream/control/mod.rs`, `src/session/stream/audio/{mod,encoder}.rs`, `src/session/stream/video/{mod,packetizer,shard_batch}.rs` | Facts tagged `[M]` in PROTOCOL.md: pairing query names, AES-128-ECB, key = first 16 bytes of SHA-256(salt + PIN), 16-byte salt/challenge/secret, RSA PKCS#1 v1.5 SHA-256, "certificate signature" = X.509 signatureValue bytes; serverinfo, applist and launch XML and query fields; SDP attribute names, SETUP reply headers, encryption flag bits; control IV layout and direction bytes, START_B starts the streams, INVALIDATE_REF_FRAMES and termination layouts, ENet host settings; audio IV, payload types 97/127, millisecond timestamps; video RTP/NV header byte layout, FEC bit fields and block split, video encryption prefix and IV; `PING` payload. Moonshine depends on `tokio-enet` for the control channel. | | S-9 | 2026-11-25 | [Moonshine](https://github.com/hgaiser/moonshine) at `f184d5e3693e09c3a6ab1025bde6cdb67f36a6bc`: `LICENSE`, `README.md`, `Cargo.toml`, `src/clients.rs`, `src/crypto.rs`, `src/webserver/pairing.rs`, `src/webserver/mod.rs`, `src/rtsp.rs`, `src/session/stream/control/mod.rs`, `src/session/stream/audio/{mod,encoder}.rs`, `src/session/stream/video/{mod,packetizer,shard_batch}.rs` | Facts tagged `[M]` in PROTOCOL.md: pairing query names, AES-128-ECB, key = first 16 bytes of SHA-256(salt + PIN), 16-byte salt/challenge/secret, RSA PKCS#1 v1.5 SHA-256, "certificate signature" = X.509 signatureValue bytes; serverinfo, applist and launch XML and query fields; SDP attribute names, SETUP reply headers, encryption flag bits; control IV layout and direction bytes, START_B starts the streams, INVALIDATE_REF_FRAMES and termination layouts, ENet host settings; audio IV, payload types 97/127, millisecond timestamps; video RTP/NV header byte layout, FEC bit fields and block split, video encryption prefix and IV; `PING` payload. Moonshine depends on `tokio-enet` for the control channel. |
| S-10 | 2026-11-25 | [tokio-enet](https://github.com/hgaiser/tokio-enet) at `364628ed754760c99e0df7bcc88e479ad91475c4`: `README.md`, `CHANGELOG.md`, `src/protocol/{mod,header,commands}.rs` | Claims wire compatibility with C ENet 1.3.x, BSD-2; ENet command numbers 1-12, command sizes, header flags (compressed 1<<14, sent time 1<<15, session bits 12-13), 4-byte command header, big-endian fields. **Approved** (Mark, 2026-11-25, answer 15). | | S-10 | 2026-11-25 | [tokio-enet](https://github.com/hgaiser/tokio-enet) at `364628ed754760c99e0df7bcc88e479ad91475c4`: `README.md`, `CHANGELOG.md`, `src/protocol/{mod,header,commands}.rs` | Claims wire compatibility with C ENet 1.3.x, BSD-2; ENet command numbers 1-12, command sizes, header flags (compressed 1<<14, sent time 1<<15, session bits 12-13), 4-byte command header, big-endian fields. Pending approval as an allowed source (see above). |
| S-11 | 2026-11-25 | crates.io API for `enet`, `enet-rs`, `nsys-enet`, `rusty_enet`, `tokio-enet`, `enet-sys`, `henet`, `enet-cs-sys`, `fec-rs`, `reed-solomon-erasure` and the RustCrypto crates | Licences, versions, repositories (see research/open-point-2.md and the Cargo manifest). | | S-11 | 2026-11-25 | crates.io API for `enet`, `enet-rs`, `nsys-enet`, `rusty_enet`, `tokio-enet`, `enet-sys`, `henet`, `enet-cs-sys`, `fec-rs`, `reed-solomon-erasure` and the RustCrypto crates | Licences, versions, repositories (see research/open-point-2.md and the Cargo manifest). |
| S-12 | 2026-11-25 | [docs.rs: rusty_enet](https://docs.rs/rusty_enet/latest/rusty_enet/) | Transpiled from C ENet; caller-supplied `Socket` trait and `HostSettings::time`; optional crc32 checksum; MIT. | | S-12 | 2026-11-25 | [docs.rs: rusty_enet](https://docs.rs/rusty_enet/latest/rusty_enet/) | Transpiled from C ENet; caller-supplied `Socket` trait and `HostSettings::time`; optional crc32 checksum; MIT. |
| S-13 | 2026-11-25 | [fec-rs README](https://github.com/hgaiser/fec-rs) | GF(2^8) with polynomial 0x1D (0x11D), "compatible with the Moonlight streaming protocol", reconstruction supported, BSD-2. | | S-13 | 2026-11-25 | [fec-rs README](https://github.com/hgaiser/fec-rs) | GF(2^8) with polynomial 0x1D (0x11D), "compatible with the Moonlight streaming protocol", reconstruction supported, BSD-2. |
| S-14 | 2026-11-25 | [moonlight-common-c README](https://github.com/moonlight-stream/moonlight-common-c) (README only) | Needs its bundled ENet; other ENet versions are incompatible; GPL-3.0. | | S-14 | 2026-11-25 | [moonlight-common-c README](https://github.com/moonlight-stream/moonlight-common-c) (README only) | Needs its bundled ENet; other ENet versions are incompatible; GPL-3.0. |
| S-15 | 2026-11-25 | [cgutman/enet](https://github.com/cgutman/enet) repository page (description only) | Forked from lsalzman/enet, has a `moonlight` branch. No files opened. | | S-15 | 2026-11-25 | [cgutman/enet](https://github.com/cgutman/enet) repository page (description only) | Forked from lsalzman/enet, has a `moonlight` branch. No files opened. |
| S-16 | 2026-11-25 | Roadmap brief §3.2 ([moonlight-android releases](https://github.com/moonlight-stream/moonlight-android/releases)) | Moonlight Android 12.1 added end-to-end stream encryption with Sunshine. | | S-16 | 2026-11-25 | Roadmap brief §3.2 ([moonlight-android releases](https://github.com/moonlight-stream/moonlight-android/releases)) | Moonlight Android 12.1 added end-to-end stream encryption with Sunshine. |
| S-17 | 2026-11-25 | [Stock ENet](https://github.com/lsalzman/enet) v1.3.18 (`2662c0d`): `LICENSE`, `include/enet/protocol.h`, `include/enet/enet.h` (constants and peer states), `host.c` (`enet_host_connect`), `peer.c` (default ping and timeout setters), `protocol.c` (header and checksum handling, connect/verify connect session ids, retransmission timeout) | MIT. Wire structs and sizes; header flags; checksum is an optional host setting (4 bytes after the header, no flag on the wire, seeded with the connect id); connect sends session ids 0xFF and channel 0xFF; defaults: MTU 1392, ping interval 500 ms, timeout limit 32 / minimum 5000 ms / maximum 30000 ms, window 4096-65536 derived from bandwidth. |
| S-18 | 2026-11-25 | [fec-rs](https://github.com/hgaiser/fec-rs) at `402f41f970bb8c3ef7c88639821032e3b6460f63`: `LICENSE`, `README.md`, `build.rs` (field tables), `src/galois.rs` (`exp`), `src/matrix.rs` (`vandermonde`), `src/reed_solomon.rs` (`build_matrix`, `new`) | BSD-2. Field GF(2^8) with polynomial 0x11D, generator 2; systematic code whose parity rows are the Cauchy matrix `P[j][i] = 1 / ((m + i) XOR j)`. Its tests also contain the GPL-provenance audio matrix (not taken). |
| S-19 | 2026-11-25 | GitHub release API: [Moonlight PC v6.2.0](https://api.github.com/repos/moonlight-stream/moonlight-qt/releases/latest), [Sunshine v2026.914.233613](https://api.github.com/repos/SunshineStream/Sunshine/releases/tags/v2026.914.233613) | Asset names, sizes and sha256 digests for the lab capture pins. Release metadata only. |
| S-20 | 2026-11-25 | ArenaTV `docs/research/sunshine-api.md` and `docs/research/this-pc.md` (Domi's own research from LizardByte's docs) | Sunshine's API calls, `--creds`, `bind_address`, port offsets, first-run behaviour, this PC's adapters and old install. |
-269
View File
@@ -1,269 +0,0 @@
# Lab capture: one GameStream session on Mark's PC
Status: **plan, not run.** Mark allowed one capture (answer 16, 2026-11-25). Nothing below has been downloaded,
installed or started yet. The build lead relays the timeline (section 7) to Mark first.
Goal: settle the UNKNOWNs U1-U29 in [PROTOCOL.md](PROTOCOL.md) section 8 by watching **one** desktop stream between
the official Moonlight PC client and the pinned Sunshine, both on this PC, through **our own** logging relay.
Moonlight and Sunshine are black-box peers: we run them and watch their traffic, their `--help`, their own logs and
the files they write. We never open their source, never disassemble them ([CLEAN_ROOM.md](CLEAN_ROOM.md)).
Hard limits:
- One stream of the **Desktop** app, no game. Nothing touches the TV or 192.168.100.217.
- Every listening socket is on loopback: Sunshine on `127.0.0.2`, the relay on `127.0.0.1`.
- Lab keys and credentials live only under `E:\build\play-remotely\lab\`, are never printed, never on a command line that
survives, never in git, and are deleted at the end.
- Recordings stay under `E:\build\play-remotely\lab\captures\`, out of git. Only derived facts and test vectors go into
the docs.
- One UAC prompt in total.
## 0. Layout
```
E:\build\play-remotely\lab\
downloads\ Sunshine MSI and the Moonlight portable zip, as downloaded (untrusted until the sha256 matches)
moonlight\ the extracted Moonlight portable folder
keys\ lab-only TLS material (ACL: Mark's account + SYSTEM): Sunshine lab cert/key, Moonlight lab cert/key
secrets\ Sunshine API credentials, DPAPI-protected for Mark's account (ConvertFrom-SecureString)
captures\ relay recordings (*.dslr), Sunshine's log copy, the msiexec log, our notes
```
Our scripts and the relay come from this repo (`tools/lab-relay/`) and run from it, never from `downloads\`.
Built and checked on 2026-11-25 (Windows MSVC, stable 1.99, `-j 2`): `cargo test` 28 passed, `cargo clippy
--all-targets -- -D warnings` and `cargo fmt --check` clean. The relay has **not been run** yet. The two scripts
(`tools/lab-relay/scripts/lab-install.ps1`, `lab-api.ps1`) have been parse-checked only, never run; the build lead
reads them before anything goes to Mark.
The lab root is on E: (approved for Play remotely). The relay is built in `E:uild\play-remotely\DomiStream-wt-lab`
with `TEMP`/`TMP` set to `E:uild\play-remotely mp`, `-j 2`, and only while CPU, RAM, D: and E: are all below
90 % (DomiStream CLAUDE.md).
## 1. Step (a): the old Sunshine is gone (read-only)
Mark has uninstalled it himself. We only check, changing nothing:
| Check | Command (read-only) | Expected |
| :-- | :-- | :-- |
| Service | `Get-Service *sunshine* -ErrorAction SilentlyContinue` | nothing |
| Processes | `Get-Process sunshine*, sunshinesvc -ErrorAction SilentlyContinue` | nothing |
| Folder | `Test-Path 'C:\Program Files\Sunshine'` | `False` (or a folder without `sunshine.exe`; then we stop and ask, we do not delete it) |
| Uninstall entry | `Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*, HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* \| ? DisplayName -like '*Sunshine*'` | nothing |
| TCP ports | `Get-NetTCPConnection -State Listen \| ? LocalPort -in 47984,47989,47990,48010` | nothing |
| UDP ports | `Get-NetUDPEndpoint \| ? LocalPort -in 47998,47999,48000,48002` | nothing |
| Firewall leftovers | `Get-NetFirewallRule -DisplayName '*Sunshine*' -ErrorAction SilentlyContinue` | nothing (only noted if present) |
| Load | the CPU/RAM check from the build rule | both ≤ 90 %, else wait |
Anything unexpected: stop and report; no clean-up on our side.
## 2. Step (b): pinned Sunshine, one UAC prompt
**Pin** (release API, S-19): `v2026.914.233613`, `Sunshine-Windows-AMD64-installer.msi`, 33,710,080 bytes,
sha256 `1d7fed8beecd5889dc7ff14cf9f42d6d38f37c3066c13c6c2a5f4e91847e0ccf`,
`https://github.com/SunshineStream/Sunshine/releases/download/v2026.914.233613/Sunshine-Windows-AMD64-installer.msi`.
The same digest is checked twice: against this pin and against the release API's `digest` field fetched at download
time. A mismatch on either = delete the file and stop.
Download (not elevated): `Invoke-WebRequest -Uri <url> -OutFile E:\build\play-remotely\lab\downloads\Sunshine-Windows-AMD64-installer.msi`,
then `Get-FileHash -Algorithm SHA256`. Nothing is run from `downloads\` before the hash matches.
**Why one elevated script, not a bare `msiexec`:** Sunshine's first start must already be bound to loopback, and
`--creds` needs write access under `C:\Program Files\Sunshine\config`. A plain `msiexec /i` would start the service
on all interfaces with no credentials. So we start **one** elevated PowerShell (`Start-Process powershell -Verb RunAs`
with our script `tools/lab-relay/scripts/lab-install.ps1`). That is the one UAC prompt ("Windows PowerShell",
publisher Microsoft Windows). Inside it, without further prompts:
1. `msiexec /i <msi> /qn /norestart /l*v E:\build\play-remotely\lab\captures\msiexec.log` (quiet; elevated already).
2. `Stop-Service SunshineService` as soon as the MSI returns (the MSI starts it; until our config is in, it has no
credentials, so nobody can pair or call its API).
3. Write `C:\Program Files\Sunshine\config\sunshine.conf` with only these lines:
```
bind_address = 127.0.0.2
address_family = ipv4
origin_web_ui_allowed = pc
upnp = disabled
external_ip = 127.0.0.2
sunshine_name = DomiStream-lab
lan_encryption_mode = 1
wan_encryption_mode = 1
min_log_level = debug
pkey = E:/build/play-remotely/lab/keys/sunshine-lab-key.pem
cert = E:/build/play-remotely/lab/keys/sunshine-lab-cert.pem
```
Forward slashes in paths: how the config parser treats backslashes is not documented. Encryption mode 1 ("if the client supports it") rather than 2: if Moonlight PC lacks one kind of encryption, a
mandatory setting would refuse the only session we get. `pkey`/`cert` point at `keys\` so the lab key never has to
be copied out of Program Files (inferred: Sunshine creates the pair at the configured path when missing; if it does
not, the script removes the two lines, restarts, and copies the default pair from `config\credentials\` into
`keys\` instead, still inside the same elevation).
4. **First-run credentials, never on a surviving command line:** the script draws a throwaway username and password
(32 random bytes each, base64url), runs `sunshine.exe --creds <u> <p>` once (the documented non-interactive way,
sunshine-api.md §4; the arguments live only for that process's lifetime), and saves the throwaway pair to
`secrets\sunshine-throwaway.cred` with `ConvertFrom-SecureString` (DPAPI, Mark's account). It is rotated in step 5.
This needs Mark's account to be the one that elevates (consent prompt, not a password prompt); if UAC asks for a
different admin account, we stop.
5. `Start-Service SunshineService`; wait until `Get-NetTCPConnection` shows 127.0.0.2:47989/47984/47990/48010 and
nothing on 0.0.0.0; `icacls` `keys\` and `secrets\` down to Mark's account + SYSTEM. Exit.
After the elevated script, not elevated (`lab-api.ps1`, PowerShell, Basic auth built in memory, TLS pinned to
`keys\sunshine-lab-cert.pem` by thumbprint): `POST https://127.0.0.2:47990/api/password` from the throwaway pair to a
fresh random lab pair stored in `secrets\sunshine-lab.cred` (DPAPI); delete the throwaway file. Arena's Day 1
takeover rotates once more into Custos.
Firewall: if the MSI added inbound rules, we only note them (`Get-NetFirewallRule`); Sunshine listens on 127.0.0.2,
so they expose nothing. Changing them needs admin and is left to Arena Day 1.
## 3. Step (c): Moonlight PC portable, no install
**Pin** (release API, S-19): `v6.2.0` (2026-10-04), `MoonlightPortable-x64-6.2.0.zip`, 37,242,232 bytes,
sha256 `6f91d268b41ed5ca8066d9d7578dc403b8db190991ff48f00b1700465f8f7ebf`,
`https://github.com/moonlight-stream/moonlight-qt/releases/download/v6.2.0/MoonlightPortable-x64-6.2.0.zip`.
Download to `downloads\`, check the hash (pin and API digest), extract to `E:\build\play-remotely\lab\moonlight\`.
No installer, no admin.
Before its first start we snapshot (names only) the `moonlight\` folder tree and the key names under
`HKCU:\Software` so that afterwards we can see what Moonlight wrote (its settings and its client identity; where it
keeps them is not documented and we do not read its source to find out). We run `Moonlight.exe --help` first
(black-box) to see whether it can pair from the command line with a PIN we choose.
**Moonlight's lab client key:** the relay needs it to talk TLS to Sunshine on Moonlight's behalf (section 4). After
Moonlight's first start (or at the latest right after pairing step 1, which carries its certificate), a small script
finds the new value by name and length only, writes the key as PEM to `keys\moonlight-lab-key.pem` and the certificate
to `keys\moonlight-lab-cert.pem`, and prints neither. If the key is not readable (for example protected with DPAPI by
Moonlight), the relay passes HTTPS through untouched and we fall back to Sunshine's debug log for what HTTPS carries
(section 6 lists what that loses).
## 4. Step (d): the relay
### Addresses
```
Moonlight ──▶ 127.0.0.1:{47984,47989,48010}/tcp, {47998,47999,48000,48002}/udp (lab-relay, logs everything)
└──▶ 127.0.0.2: same ports (Sunshine, bind_address)
```
Moonlight is told the host is `127.0.0.1`. Because Sunshine sits on another loopback address with its **default**
ports, the relay copies the port numbers unchanged: no port rewriting in serverinfo, RTSP or SDP, which matters
because RTSP may be encrypted (U5) and could not be rewritten.
Address rewriting: Sunshine may write its own address (`127.0.0.2`) into answers, for example `sessionUrl0` in the
launch answer, which would send Moonlight around the relay. The relay replaces the 9 bytes `127.0.0.2` with
`127.0.0.1` in **host-to-client plaintext only** (HTTP, decrypted HTTPS, plain RTSP), logs the original and a note
per replacement. Same length, so `Content-Length` stays right.
Fallback if Sunshine refuses `bind_address = 127.0.0.2`: Sunshine on `127.0.0.1` with `port = 48989` (all ports
+1000), the relay on the default ports, and port rewriting of `HttpsPort`/`ExternalPort` (serverinfo), `sessionUrl0`
(launch) and `server_port=` (RTSP SETUP). That only works while RTSP is plaintext, so the fallback also sets the
encryption modes to 0 and gives up U17/U19 for this capture.
UDP: video, audio and control go to the address the client's first datagram (the PING, or the ENet connect) came
from (W5, W6). The relay keeps one upstream socket per client address and port, so Sunshine sees the relay's socket
and answers it; the relay sends the answers back to Moonlight's socket. ENet carries no addresses.
### What is encrypted, and how we see plaintext
| Traffic | Protection | How the relay sees it |
| :-- | :-- | :-- |
| HTTP 47989 (serverinfo, pairing steps 1-4) | none | plaintext |
| HTTPS 47984 (pairing step 5, applist, launch with `rikey`, cancel) | TLS, both sides pin certificates | **terminated in the relay**: towards Moonlight it presents Sunshine's own lab certificate (the one Moonlight pinned in pairing, so the pin holds); towards Sunshine it presents Moonlight's own lab client certificate and pins Sunshine's lab certificate |
| RTSP 48010 | plaintext, or encrypted when negotiated (U5) | as is; if encrypted, decrypted offline with `rikey` from the launch request |
| Control 47999 | AES-128-GCM with `rikey` (client-chosen) | ENet headers plaintext; message bodies decrypted offline with `rikey` |
| Audio 48000 | AES-128-CBC with `rikey`, if negotiated | decrypted offline |
| Video 47998 | AES-128-GCM with `rikey`, only if negotiated | headers plaintext unless encrypted; decrypted offline |
Why TLS termination and not just Sunshine's log: `rikey` and the launch parameters (U4) travel only inside HTTPS.
Without them, control, audio and possibly video stay opaque and U10, U11, U16, U17, U19, U20, U22 stay open. The debug
log's contents are not documented, and asking it to print keys is not something we can count on. Termination uses
only lab material that exists for this capture and is deleted after it; nothing outside this PC's loopback is
touched. Sunshine's debug log (`GET /api/logs`) is still copied into `captures\` as a cross-check.
The relay never changes a byte except the documented address rewrite, and never sends anything on its own.
### Which part of the capture settles which UNKNOWN
| U | Settled by |
| :-- | :-- |
| U1 | HTTP 47989 pairing requests (query names, order), then the first HTTPS request (`pairchallenge`) and its place in the order |
| U2 | partly: the certificate Moonlight sends in pairing step 1 shows one certificate Sunshine accepts (key size, validity, subject); our own certificate is tested on Day 1 |
| U4 | the decrypted HTTPS `/launch` request and answer |
| U5 | the RTSP TCP stream: framing, `Content-Length`, `X-GS-ClientVersion`, SETUP targets, `Transport`, `Session`, PLAY |
| U6 | the ANNOUNCE payload Sunshine accepted |
| U7 | headers of the three SETUP answers |
| U8 | the first client-to-host datagrams on 47998 and 48000, and their timing |
| U9 | control datagrams decoded with our ENet parser: connect/verify connect fields, flags, anything stock 1.3 lacks |
| U10 | decrypted control messages: START_A/B, PERIODIC_PING, LOSS/FRAME_STATS, IDR request, termination at the end, and their timing |
| U11 | control frame sequence numbers in both directions |
| U13 | the first 8 bytes of each reassembled video frame |
| U14 | confirmation: our Cauchy encoder must reproduce every captured video parity packet (offset 32 on) |
| U15 | the multi-FEC flags byte across all video packets |
| U16 | captured audio blocks: solve the 2 × 4 parity matrix over GF(2^8) from data and parity bytes |
| U17 | ANNOUNCE `encryptionEnabled` plus whether audio payloads decrypt |
| U19 | the video packet layout when video encryption was negotiated (if Moonlight PC does not negotiate it, U19 stays open) |
| U20 | keys typed during the stream into a scratch Notepad window |
| U22 | gamepad packets, only if Mark has a controller plugged in (optional) |
| U24 | the TLS handshakes on 47984 (versions, cipher suites), logged by the relay |
| U25 | `ServerCodecModeSupport` in serverinfo from a host whose GPU we know (RTX 3090) |
| U26 | the `surround-params` lines in DESCRIBE (all of them, if Sunshine lists every Opus configuration as Moonshine does) |
| U27 | only if a call is refused during the session; not provoked |
| U29 | video RTP timestamps against the 60 fps frame rate |
| U21, U23, U28 | **not** settled: no touch/pen device, no game to rumble, no wrong PIN in a one-session capture |
## 5. Step (e): what is recorded, analysis, clean-up
**Recorded** (`captures\`):
- `session-<UTC>.dslr`: the relay's record file. Each record: kind (open, data, close, note), protocol (HTTP,
HTTPS plaintext, RTSP, video, control, audio, mic, meta), direction, connection id, microseconds since the start,
and the bytes. Format and tests: `tools/lab-relay/src/record.rs`.
- `sunshine.log` (copied with `GET /api/logs`), `msiexec.log`.
- `notes.md`: what we did and when (times from the relay's clock).
**Privacy:** the video frames are Mark's desktop. Before the stream, Mark closes anything private; during it, only a
scratch Notepad and the desktop are on screen. After analysis the video payload bytes are deleted from the recording
(`lab-relay strip-video`), keeping only packet headers and parity checks.
**Analysis** (offline, no network): `lab-relay dump` lists records with secrets redacted (`rikey=`, `Authorization:`,
pairing values); per-protocol extraction feeds DomiStream's own parsers (Phase B) and small Python checks run with
`python -I` from the repo, never from `captures\`. Every fact that comes out goes into PROTOCOL.md with the tag
`[L1]` (lab capture 1, date, versions) and, where useful, into test vectors that contain **no** lab key (vectors are
re-encrypted with test keys generated in the test).
**Clean-up** (right after the stream, not elevated):
1. Quit Moonlight; stop the relay.
2. `POST /api/clients/unpair-all` (removes the Moonlight lab client from Sunshine).
3. `POST /api/config` without the `pkey`/`cert` lines and `POST /api/restart`, so Sunshine makes a fresh pair at its
default path (inferred; if it does not, the lab pair stays referenced and Arena's Day 1 takeover, which runs
elevated anyway, regenerates it). Then delete `keys\sunshine-lab-*.pem`.
4. Delete `keys\moonlight-lab-*.pem`, the whole `moonlight\` folder and the registry key Moonlight created (found by
the snapshot diff in step (c)).
5. Keep `secrets\sunshine-lab.cred` until Arena's Day 1 takeover rotates the credentials into Custos, then delete it.
6. Delete `downloads\Moonlight*.zip`. Keep the Sunshine MSI (Arena Day 1 pins the same version).
7. Sunshine **stays installed**, bound to 127.0.0.2, ready for Arena's Day 1 takeover.
8. The recordings stay on E: until the facts are in PROTOCOL.md and QA has its vectors; then they are deleted on the
build lead's word.
## 6. If something fails
| Failure | What we do |
| :-- | :-- |
| sha256 mismatch | delete the file, stop, report |
| Sunshine will not bind 127.0.0.2 | fallback of section 4 (port +1000, encryption off for this capture) |
| Moonlight refuses `127.0.0.1` as a host | relay on `127.0.0.3` instead (any loopback address works) |
| The relay's TLS handshake with Moonlight or Sunshine fails (for example a cipher suite rustls does not offer) | restart the relay with `--https-passthrough`: HTTPS is then recorded as raw TLS, with the same losses as the next row |
| Moonlight's key not readable | HTTPS passes through untouched; we lose U4 and `rikey`, so U10, U11, U16, U17, U19, U20, U22 stay open unless Sunshine's debug log shows them |
| Pairing needs a `pairing_id` we cannot find (sunshine-api.md gap) | we watch the network calls of Sunshine's own local PIN page in our browser pane (black-box) and submit the PIN there ourselves |
| CPU or RAM above 90 % | wait (the relay build and the stream are both heavy) |
## 7. Step (f): timeline for Mark
About 20 minutes; Mark's part is **one click**, plus closing private windows before the stream.
| When | What happens | Mark |
| :-- | :-- | :-- |
| 0:00 | We check that the old Sunshine is gone and that the PC is not busy. | nothing |
| 0:02 | We download the pinned Sunshine and Moonlight and check their fingerprints (about 70 MB). | nothing |
| 0:05 | **A UAC prompt appears: "Windows PowerShell – Do you want to allow this app to make changes to your device?" (publisher: Microsoft Windows).** | **click Yes** (the only click) |
| 0:05-0:08 | Sunshine installs quietly and starts, reachable only from this PC. | nothing |
| 0:08 | Moonlight opens in a window (portable, nothing installed). It may show a PIN; we enter it into Sunshine ourselves. If Windows Firewall asks about Moonlight, click **Cancel**: everything runs on this PC. | close private windows; Cancel on a firewall prompt if one appears |
| 0:10 | A one-minute desktop stream: Moonlight shows his own desktop in a window. We move the mouse and type a few letters into a scratch Notepad. If he has a gamepad plugged in, we may ask him to press a few buttons. | hands off the mouse and keyboard for that minute (optional: press gamepad buttons when asked) |
| 0:12 | We close the stream, unpair Moonlight, delete Moonlight and the lab keys. Sunshine stays installed for Arena's Day 1. | nothing |
| later | We analyse the recording offline and delete the desktop video from it. | nothing |
+21 -49
View File
@@ -2,8 +2,7 @@
The protocol between a GameStream host (Sunshine, later Lumen) and a client (Arena Domi TV). Written from the Wolf The protocol between a GameStream host (Sunshine, later Lumen) and a client (Arena Domi TV). Written from the Wolf
protocol docs in our own words, completed with facts read in Moonshine (BSD-2). Every fact has a tag; every gap is protocol docs in our own words, completed with facts read in Moonshine (BSD-2). Every fact has a tag; every gap is
marked **UNKNOWN Un** with what would settle it. Status: 2026-11-25, Phase A (docs + API, no logic yet). U9 narrowed and U14 settled from the approved sources the same marked **UNKNOWN Un** with what would settle it. Status: 2026-11-25, Phase A (docs + API, no logic yet).
day (sections 3.1, 5.3); the rest waits for the lab capture ([LAB_CAPTURE.md](LAB_CAPTURE.md)).
**Tags** (details in the source log, [CLEAN_ROOM.md](CLEAN_ROOM.md)): **Tags** (details in the source log, [CLEAN_ROOM.md](CLEAN_ROOM.md)):
@@ -12,9 +11,8 @@ day (sections 3.1, 5.3); the rest waits for the lab capture ([LAB_CAPTURE.md](LA
| [W1]-[W7] | Wolf docs: index, pairing, RTSP, control, RTP video, RTP Opus, input (S-1 to S-7) | | [W1]-[W7] | Wolf docs: index, pairing, RTSP, control, RTP video, RTP Opus, input (S-1 to S-7) |
| [M] | Moonshine `f184d5e` (S-9). A host implementation: we mirror its behaviour for the client. | | [M] | Moonshine `f184d5e` (S-9). A host implementation: we mirror its behaviour for the client. |
| [M*] | Moonshine, but the value has GPL provenance (Moonshine cites Sunshine or moonlight-common-c). Confirm by measurement before use. | | [M*] | Moonshine, but the value has GPL provenance (Moonshine cites Sunshine or moonlight-common-c). Confirm by measurement before use. |
| [T] | tokio-enet `364628e` (S-10), approved 2026-11-25 | | [T] | tokio-enet `364628e` (S-10), pending approval as a source |
| [E] | stock ENet v1.3.18 `2662c0d` (S-17), MIT, approved 2026-11-25 | | [F] | fec-rs README (S-13) |
| [F] | fec-rs README and source `402f41f` (S-13, S-18), BSD-2, approved 2026-11-25 |
| [RFC n] | the RFC | | [RFC n] | the RFC |
**Not in DomiStream:** sockets, TLS, the clock, video decoding and **Opus decoding**. DomiStream hands the platform **Not in DomiStream:** sockets, TLS, the clock, video decoding and **Opus decoding**. DomiStream hands the platform
@@ -228,46 +226,25 @@ Source: [Wolf: control](https://games-on-whales.github.io/wolf/stable/protocols/
### 3.1 ENet ### 3.1 ENet
The control stream runs over a custom fork of ENet supporting IPv4 and IPv6 [W4]. The wire is stock ENet 1.3 [E][T] The control stream runs over a custom fork of ENet supporting IPv4 and IPv6 [W4]. What is known about the wire,
(all multi-byte fields big-endian): from stock ENet 1.3 as tokio-enet implements it [T] (all multi-byte fields big-endian):
- **Datagram** = protocol header + up to 32 commands [E]. Header: `peer_id u16` whose bits 15 and 14 are flags (`1<<15` - Datagram = protocol header + up to 32 commands. Header: `peer_id u16` whose top bits are flags (`1<<15` sent time
sent time present, `1<<14` compressed) and bits 12-13 the session id; then `sent_time u16` (low 16 bits of the present, `1<<14` compressed) and bits 12-13 the session id; then `sent_time u16` if flagged.
sender's millisecond clock) if flagged [E]. Peer id `0xFFF` = "no peer yet" (the connect datagram) [E]. - Command header (4 bytes): `command u8` (low 4 bits type, `0x80` acknowledge wanted, `0x40` unsequenced),
- **Checksum** [E]: optional, a setting of the host on *both* ends; when on, 4 bytes follow the header (crc32 over the `channel_id u8`, `reliable_sequence u16`.
datagram with the field first set to the peer's connect id). **Nothing on the wire says whether it is on**, so both - Commands and total sizes: 1 acknowledge (8), 2 connect (48), 3 verify connect (44), 4 disconnect (8), 5 ping (4),
ends must agree. 6 send reliable (6 + data), 7 send unreliable (8 + data), 8 send fragment (24 + data), 9 send unsequenced (8 + data),
- **Command header** (4 bytes): `command u8` (low 4 bits type, `0x80` acknowledge wanted, `0x40` unsequenced), 10 bandwidth limit (12), 11 throttle configure (16), 12 send unreliable fragment (24 + data).
`channel_id u8` (`0xFF` for connection-level commands), `reliable_sequence u16` [E]. - MTU 576-4096, window 4096-65536, channels 1-255, peer id ≤ 0xFFF.
- **Commands and total sizes** [E]: 1 acknowledge (8: received reliable sequence, received sent time),
2 connect (48), 3 verify connect (44), 4 disconnect (8: data u32), 5 ping (4), 6 send reliable (6 + data),
7 send unreliable (8 + data), 8 send fragment (24 + data: start sequence, data length, fragment count, fragment
number, total length, fragment offset), 9 send unsequenced (8 + data: unsequenced group), 10 bandwidth limit (12),
11 throttle configure (16), 12 send unreliable fragment (24 + data).
- **Connect** fields [E]: outgoing peer id u16, incoming and outgoing session id u8 (a stock client sends `0xFF` for
both, "pick one"), MTU, window size, channel count, incoming and outgoing bandwidth, throttle interval, acceleration,
deceleration, connect id (random), data u32. Verify connect has the same fields without `data`; the connect id must
match [E].
- **Limits** [E]: MTU 576-4096, window 4096-65536, channels 1-255, peer id ≤ 0xFFF, at most 1024 × 1024 fragments.
- **Stock defaults** [E]: MTU 1392; window 65536 when bandwidth is unlimited; ping every 500 ms when idle;
retransmission timeout = RTT + 4 × RTT variance (initial RTT 500 ms), doubling per retry; a peer is dropped when
the oldest unacknowledged command is 30 s old, or once it has been sent 6 times (`2^(attempts-1) ≥ 32`, the
timeout limit) and is at least 5 s old.
How the host uses it [M]: one peer per session; host created with a channel limit of 0x30; every host message is sent How the host uses it [M]: one peer per session; host created with a channel limit of 0x30; every host message is sent
**reliable on channel 0**. Moonshine does this with stock-wire ENet and real Moonlight clients (see **reliable on channel 0**. Moonshine does this with stock-wire ENet and real Moonlight clients (see
[research/open-point-2.md](research/open-point-2.md)). [research/open-point-2.md](research/open-point-2.md)).
What follows without a capture (our reasoning on [E][T][M]): UNKNOWN U9: anything Sunshine's ENet sends that stock 1.3 does not (checksum, compression, header or connect field
- tokio-enet has no checksum and Moonlight clients work with it, so **Moonlight clients run without the checksum**. differences); the channel count, MTU and `connect data` the client should offer; ping interval and timeouts.
The checksum must match on both ends, and Sunshine works with the same clients, so **Sunshine runs without it too**. Settle: lab capture of one session, decoded with our parser.
Same reasoning for compression: a client that compressed would fail against tokio-enet without a compressor.
- So everything a Moonlight client *sends* parses as stock 1.3. What stays open is only what the fork might add on the
host's *sending* side, which the fork-aware client accepts and a stock parser might not.
UNKNOWN U9 (narrowed): anything Sunshine's ENet sends that stock 1.3 does not; the channel count, MTU and `connect
data` a client offers; whether the client sets non-default ping or timeout values. Settle: the lab capture's control
port datagrams, decoded with our parser (LAB_CAPTURE.md). Until then our client offers stock defaults.
### 3.2 Encrypted frame ### 3.2 Encrypted frame
@@ -455,14 +432,9 @@ Reed-Solomon erasure code over GF(2^8), polynomial `0x11D` [F] [W5]:
[W5] and their RTP and NV header fields are written **after** the parity is computed [M], so parity bytes 0-31 are [W5] and their RTP and NV header fields are written **after** the parity is computed [M], so parity bytes 0-31 are
not parity. Consequence for the receiver: a recovered data shard's bytes 0-31 are garbage; use only its payload not parity. Consequence for the receiver: a recovered data shard's bytes 0-31 are garbage; use only its payload
(offset 32 on) and take its place from the shard index. (offset 32 on) and take its place from the shard index.
- **Matrix (U14, settled from [F], to be confirmed by the capture):** systematic: the data shards pass through, and - UNKNOWN U14: the generator matrix (systematic construction). fec-rs (BSD-2) claims Moonlight compatibility [F].
parity shard `j` (0..m) is `Σ_i P[j][i] · data_i` with the Cauchy matrix `P[j][i] = 1 / ((m + i) XOR j)` over Settle: approve fec-rs as a source and read its construction, or measure: capture blocks with known losses and
GF(2^8), polynomial `0x11D`, generator 2 [F]. Nothing in the Wolf docs contradicts this: they only say Reed-Solomon check our decoder against them.
with parity blocks [W5]. Examples (our own arithmetic): `k = 4, m = 2`:
`P = [[8e f4 47 a7], [f4 8e a7 47]]`; `k = 3, m = 1`: `P = [[01 8e f4]]`.
The capture settles it without any loss: parity packets are always sent, so our encoder must reproduce the
captured parity bytes (offset 32 on) of every block.
- The audio code is **not** this matrix (section 6.4).
### 5.4 Feedback ### 5.4 Feedback
@@ -566,11 +538,11 @@ client and Sunshine on a lab machine, not Mark's PC, his Sunshine or his TV); th
| U6 | ANNOUNCE attributes and values Sunshine requires | B | capture, then vary one at a time | | U6 | ANNOUNCE attributes and values Sunshine requires | B | capture, then vary one at a time |
| U7 | Extra headers in SETUP replies | B | capture | | U7 | Extra headers in SETUP replies | B | capture |
| U8 | UDP ping payload and repeat interval | B | capture | | U8 | UDP ping payload and repeat interval | B | capture |
| U9 | Narrowed (3.1): only what Sunshine's ENet may add when *sending*; the client's channel count, MTU, connect data | B | capture, decode with our parser | | U9 | ENet differences from stock 1.3; client's channel count, MTU, connect data; ping/timeouts | B | capture, decode with our parser |
| U10 | Bodies of START_A, START_B, PERIODIC_PING, LOSS_STATS, FRAME_STATS, IDR request, TERMINATION; ping interval | B | capture, decrypted with the session's `rikey` | | U10 | Bodies of START_A, START_B, PERIODIC_PING, LOSS_STATS, FRAME_STATS, IDR request, TERMINATION; ping interval | B | capture, decrypted with the session's `rikey` |
| U11 | First control sequence number; host's replay rules | | capture | | U11 | First control sequence number; host's replay rules | | capture |
| U13 | Video frame header: Wolf's constant or Moonshine's fields | | capture | | U13 | Video frame header: Wolf's constant or Moonshine's fields | | capture |
| U14 | Video RS matrix: **settled** (5.3, Cauchy from fec-rs) | | capture confirms: our parity = captured parity | | U14 | Video RS generator matrix | B (for FEC; video plays without it at zero loss) | read fec-rs (approval) or capture with loss |
| U15 | Multi-FEC flags `0x10` | | capture | | U15 | Multi-FEC flags `0x10` | | capture |
| U16 | Audio RS parity matrix | (audio plays without it) | capture, solve over GF(2^8) | | U16 | Audio RS parity matrix | (audio plays without it) | capture, solve over GF(2^8) |
| U17 | Audio encryption always or only when negotiated | B | capture | | U17 | Audio encryption always or only when negotiated | B | capture |
+57 -1
View File
@@ -1,4 +1,4 @@
# Fuzz targets: one per DomiStream parser. Its own workspace, built only for fuzzing, never released. # Fuzz targets: one per DomiStream parser and state machine; each asserts invariants (round trips, caps). Its own workspace, built only for fuzzing, never released.
# #
# Linux, nightly, cargo-fuzz: # Linux, nightly, cargo-fuzz:
# cargo fuzz run <target> -- -max_total_time=600 # cargo fuzz run <target> -- -max_total_time=600
@@ -155,3 +155,59 @@ path = "fuzz_targets/audio_packet.rs"
test = false test = false
doc = false doc = false
bench = false bench = false
[[bin]]
name = "server_cert_der"
path = "fuzz_targets/server_cert_der.rs"
test = false
doc = false
bench = false
[[bin]]
name = "enet_client"
path = "fuzz_targets/enet_client.rs"
test = false
doc = false
bench = false
[[bin]]
name = "media_decrypt"
path = "fuzz_targets/media_decrypt.rs"
test = false
doc = false
bench = false
[[bin]]
name = "video_depacketizer"
path = "fuzz_targets/video_depacketizer.rs"
test = false
doc = false
bench = false
[[bin]]
name = "audio_depacketizer"
path = "fuzz_targets/audio_depacketizer.rs"
test = false
doc = false
bench = false
[[bin]]
name = "fec_reconstruct"
path = "fuzz_targets/fec_reconstruct.rs"
test = false
doc = false
bench = false
[[bin]]
name = "pairing_session"
path = "fuzz_targets/pairing_session.rs"
test = false
doc = false
bench = false
[[bin]]
name = "rtsp_client"
path = "fuzz_targets/rtsp_client.rs"
test = false
doc = false
bench = false
+16 -3
View File
@@ -1,11 +1,24 @@
//! Fuzzes `/applist` answers: never panics, whatever the bytes. //! Fuzzes `/applist` answers.
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic. //! Asserts invariants, not only "no panic": at most MAX_APPS apps, titles within the cap, ids unique.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`. //! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main] #![no_main]
use libfuzzer_sys::fuzz_target; use libfuzzer_sys::fuzz_target;
use domistream::http::applist::{MAX_APP_TITLE_BYTES, MAX_APPLIST_BYTES, MAX_APPS};
fuzz_target!(|data: &[u8]| { fuzz_target!(|data: &[u8]| {
let _ = domistream::http::parse_app_list(data); let r = domistream::http::parse_app_list(data);
if data.len() > MAX_APPLIST_BYTES {
assert!(matches!(r, Err(domistream::Error::TooLarge { .. })));
}
if let Ok(apps) = r {
assert!(apps.len() <= MAX_APPS);
let mut ids: Vec<u32> = apps.iter().map(|a| a.id).collect();
ids.sort_unstable();
ids.dedup();
assert_eq!(ids.len(), apps.len(), "duplicate ids accepted");
assert!(apps.iter().all(|a| a.title.len() <= MAX_APP_TITLE_BYTES));
}
}); });
+50
View File
@@ -0,0 +1,50 @@
//! Fuzzes the audio depacketizer with a sequence of datagrams (FEC on, a Cauchy test matrix).
//! Asserts invariants, not only "no panic": never two events for one sequence number in a short run; output stays bounded by the input.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main]
use libfuzzer_sys::fuzz_target;
use core::time::Duration;
use std::collections::HashSet;
use domistream::Instant;
use domistream::audio::{AudioConfig, AudioDepacketizer, AudioEvent, AudioFec};
// 1 / (x ^ y) over GF(2^8)/0x11D with x in {0, 1} and y in {2, 3, 4, 5}: a 2 x 4 Cauchy matrix, the same one
// tests/common builds with gf::cauchy(2, 4).
const MATRIX: [u8; 8] = [0x8e, 0xf4, 0x47, 0xa7, 0xf4, 0x8e, 0xa7, 0x47];
fuzz_target!(|data: &[u8]| {
let cfg = AudioConfig {
cipher: None,
packet_duration_ms: 5,
fec: AudioFec::ParityMatrix(MATRIX),
loss_timeout: Duration::from_millis(20),
};
let Ok(mut d) = AudioDepacketizer::new(cfg) else { return };
let mut rest = data;
let mut us = 0u64;
let mut seen = HashSet::new();
let mut out_bytes = 0usize;
while let Some((&len, tail)) = rest.split_first() {
let len = usize::from(len).min(tail.len());
let (g, tail) = tail.split_at(len);
rest = tail;
us += 1000;
let _ = d.push(Instant::from_micros(us), g);
let _ = d.handle_timeout(Instant::from_micros(us));
while let Some(e) = d.poll_event() {
let seq = match &e {
AudioEvent::Packet { sequence, opus, .. } => {
out_bytes += opus.len();
*sequence
}
AudioEvent::Lost { sequence } => *sequence,
};
assert!(seen.insert(seq), "two events for sequence {seq}");
}
}
assert!(out_bytes <= data.len() * 2, "FEC rebuilds packets, but not out of nothing");
});
+16 -3
View File
@@ -1,11 +1,24 @@
//! Fuzzes audio packets: never panics, whatever the bytes. //! Fuzzes audio packets.
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic. //! Asserts invariants, not only "no panic": payload types and shard indices are the ones PROTOCOL.md allows; payloads are never empty.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`. //! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main] #![no_main]
use libfuzzer_sys::fuzz_target; use libfuzzer_sys::fuzz_target;
use domistream::audio::AudioPacket;
use domistream::audio::packet::{AUDIO_FEC_PAYLOAD_TYPE, AUDIO_PAYLOAD_TYPE, MAX_AUDIO_PACKET_BYTES};
fuzz_target!(|data: &[u8]| { fuzz_target!(|data: &[u8]| {
let _ = domistream::audio::parse_audio_packet(data); match domistream::audio::parse_audio_packet(data) {
Ok(AudioPacket::Data { rtp, payload }) => {
assert_eq!(rtp.payload_type, AUDIO_PAYLOAD_TYPE);
assert!(!payload.is_empty() && data.len() <= MAX_AUDIO_PACKET_BYTES);
}
Ok(AudioPacket::Parity { rtp, fec, parity }) => {
assert_eq!(rtp.payload_type, AUDIO_FEC_PAYLOAD_TYPE);
assert!(fec.shard_index <= 1 && !parity.is_empty());
}
Err(_) => {}
}
}); });
+19 -3
View File
@@ -1,11 +1,27 @@
//! Fuzzes encrypted control frames (outer fields): never panics, whatever the bytes. //! Fuzzes encrypted control frames (outer fields), their opening, and seal/open round trips.
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic. //! Asserts invariants, not only "no panic": the length field matches the bytes, random frames never pass the GCM tag, and seal then open gives the plaintext back.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`. //! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main] #![no_main]
use libfuzzer_sys::fuzz_target; use libfuzzer_sys::fuzz_target;
use domistream::control::frame::{FRAME_HEADER_LEN, MAX_FRAME_BYTES, MIN_FRAME_BYTES};
use domistream::control::{ControlCipher, Direction, parse_encrypted_frame};
fuzz_target!(|data: &[u8]| { fuzz_target!(|data: &[u8]| {
let _ = domistream::control::parse_encrypted_frame(data); if let Ok(f) = parse_encrypted_frame(data) {
assert!(data.len() >= MIN_FRAME_BYTES && data.len() <= MAX_FRAME_BYTES);
assert_eq!(f.ciphertext.len() + FRAME_HEADER_LEN, data.len());
assert_eq!(&f.tag[..], &data[8..24]);
// A fuzzer forging a GCM tag would be a finding of its own.
assert_eq!(ControlCipher::new([0x42; 16]).open(Direction::HostToClient, data), Err(domistream::Error::Crypto));
}
if data.len() >= 4 && data.len() + FRAME_HEADER_LEN <= MAX_FRAME_BYTES {
let c = ControlCipher::new([0x24; 16]);
let seq = u32::from_le_bytes([data[0], data[1], data[2], data[3]]);
let sealed = c.seal(seq, Direction::ClientToHost, data).expect("seal");
assert_eq!(c.open(Direction::ClientToHost, &sealed), Ok((seq, data.to_vec())));
assert!(c.open(Direction::HostToClient, &sealed).is_err());
}
}); });
+15 -3
View File
@@ -1,11 +1,23 @@
//! Fuzzes decrypted control messages from the host: never panics, whatever the bytes. //! Fuzzes decrypted control messages from the host.
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic. //! Asserts invariants, not only "no panic": the split matches the length field; a host message always splits as a message; Other keeps the body length.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`. //! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main] #![no_main]
use libfuzzer_sys::fuzz_target; use libfuzzer_sys::fuzz_target;
use domistream::control::{HostMessage, parse_host_message, parse_message};
fuzz_target!(|data: &[u8]| { fuzz_target!(|data: &[u8]| {
let _ = domistream::control::parse_host_message(data); let raw = parse_message(data);
if let Ok(r) = raw {
assert_eq!(r.body.len() + 4, data.len());
assert_eq!(r.message_type, u16::from_le_bytes([data[0], data[1]]));
}
if let Ok(m) = parse_host_message(data) {
assert!(raw.is_ok(), "a host message must split as a message first");
if let HostMessage::Other { body_len, .. } = m {
assert_eq!(body_len + 4, data.len());
}
}
}); });
+52
View File
@@ -0,0 +1,52 @@
//! Fuzzes the ENet client peer: a connecting peer fed a sequence of datagrams.
//! Asserts invariants, not only "no panic": never panics; delivered packets are within MAX_PACKET_BYTES; outgoing datagrams parse and stay within the MTU.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main]
use libfuzzer_sys::fuzz_target;
use core::time::Duration;
use domistream::enet::protocol::parse_datagram;
use domistream::enet::{EnetClient, EnetConfig, EnetEvent, MAX_PACKET_BYTES};
use domistream::{Instant, RandomSource};
struct Fixed;
impl RandomSource for Fixed {
fn fill(&mut self, dest: &mut [u8]) {
dest.fill(0x5A);
}
}
fuzz_target!(|data: &[u8]| {
let cfg = EnetConfig {
channel_count: 2,
mtu: 1400,
connect_data: 0,
ping_interval: Duration::from_millis(500),
timeout: Duration::from_secs(10),
};
let Ok(mut c) = EnetClient::connect(cfg, Instant::ZERO, &mut Fixed) else { return };
// Datagrams separated by a 2-byte big-endian length; time advances 1 ms per datagram.
let mut rest = data;
let mut ms = 0u64;
while rest.len() >= 2 {
let len = usize::from(u16::from_be_bytes([rest[0], rest[1]])).min(rest.len() - 2);
let (d, tail) = rest[2..].split_at(len);
rest = tail;
ms += 1;
let now = Instant::from_micros(ms * 1000);
let _ = c.handle_datagram(now, d);
let _ = c.handle_timeout(now);
while let Some(out) = c.poll_transmit(now) {
assert!(out.len() <= usize::from(cfg.mtu));
parse_datagram(&out).expect("the client's own datagrams parse");
}
while let Some(e) = c.poll_event() {
if let EnetEvent::Received { data, .. } = e {
assert!(data.len() <= MAX_PACKET_BYTES);
}
}
}
});
+11 -3
View File
@@ -1,11 +1,19 @@
//! Fuzzes ENet datagrams: never panics, whatever the bytes. //! Fuzzes ENet datagrams.
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic. //! Asserts invariants, not only "no panic": parse -> encode -> parse is stable and within the datagram and command caps.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`. //! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main] #![no_main]
use libfuzzer_sys::fuzz_target; use libfuzzer_sys::fuzz_target;
use domistream::enet::protocol::{MAX_COMMANDS_PER_DATAGRAM, MAX_DATAGRAM_BYTES, encode_datagram, parse_datagram};
fuzz_target!(|data: &[u8]| { fuzz_target!(|data: &[u8]| {
let _ = domistream::enet::protocol::parse_datagram(data); if let Ok(d) = parse_datagram(data) {
assert!(data.len() <= MAX_DATAGRAM_BYTES);
assert!(d.commands.len() <= MAX_COMMANDS_PER_DATAGRAM);
let bytes = encode_datagram(&d).expect("a parsed datagram encodes");
assert!(bytes.len() <= MAX_DATAGRAM_BYTES);
assert_eq!(parse_datagram(&bytes), Ok(d));
}
}); });
+40
View File
@@ -0,0 +1,40 @@
//! Fuzzes Reed-Solomon reconstruction with fuzzer-chosen shapes and erasures.
//! Asserts invariants, not only "no panic": up to m erasures always rebuild the encoded data byte-exact; more are refused; hostile shard sets never panic.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main]
use libfuzzer_sys::fuzz_target;
use domistream::fec::ReedSolomon;
fuzz_target!(|data: &[u8]| {
if data.len() < 4 {
return;
}
let k = 1 + usize::from(data[0]) % 32;
let m = 1 + usize::from(data[1]) % 16;
let len = 1 + usize::from(data[2]) % 32;
let Ok(code) = ReedSolomon::new(k, m) else { return };
let body = &data[3..];
let mut shards: Vec<Vec<u8>> =
(0..k).map(|i| (0..len).map(|x| body[(i * len + x) % body.len()]).collect()).collect();
shards.extend((0..m).map(|_| vec![0; len]));
code.encode(&mut shards).expect("encode");
let mask = u32::from(body[body.len() - 1]);
let lost: Vec<usize> = (0..k + m).filter(|&i| (mask.rotate_left(i as u32) ^ (i as u32 * 7)) % 3 == 0).collect();
let mut s: Vec<Option<Vec<u8>>> =
shards.iter().enumerate().map(|(i, v)| (!lost.contains(&i)).then(|| v.clone())).collect();
let r = code.reconstruct(&mut s);
if lost.len() <= m {
r.expect("<= m erasures rebuild");
for (a, b) in s.iter().zip(&shards) {
assert_eq!(a.as_deref(), Some(b.as_slice()));
}
} else {
assert!(matches!(r, Err(domistream::Error::Truncated { .. })));
}
// The raw bytes as a hostile shard set.
let mut hostile: Vec<Option<Vec<u8>>> = body.chunks(len).map(|c| (c[0] & 1 == 0).then(|| c.to_vec())).collect();
let _ = code.reconstruct(&mut hostile);
});
+10 -3
View File
@@ -1,11 +1,18 @@
//! Fuzzes INPUT_DATA messages: never panics, whatever the bytes. //! Fuzzes INPUT_DATA messages.
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic. //! Asserts invariants, not only "no panic": parse -> encode -> parse is stable; an accepted message's length field matches.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`. //! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main] #![no_main]
use libfuzzer_sys::fuzz_target; use libfuzzer_sys::fuzz_target;
use domistream::input::{MAX_INPUT_MESSAGE_BYTES, encode_input, parse_input};
fuzz_target!(|data: &[u8]| { fuzz_target!(|data: &[u8]| {
let _ = domistream::input::parse_input(data); if let Ok(e) = parse_input(data) {
assert!(data.len() <= MAX_INPUT_MESSAGE_BYTES);
assert_eq!(usize::from(u16::from_le_bytes([data[2], data[3]])) + 4, data.len());
let bytes = encode_input(&e).expect("a parsed event encodes");
assert_eq!(parse_input(&bytes), Ok(e));
}
}); });
+15 -3
View File
@@ -1,11 +1,23 @@
//! Fuzzes `/launch` and `/resume` answers: never panics, whatever the bytes. //! Fuzzes `/launch` and `/resume` answers.
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic. //! Asserts invariants, not only "no panic": a session URL is within the cap, starts with rtsp:// and has no control characters.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`. //! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main] #![no_main]
use libfuzzer_sys::fuzz_target; use libfuzzer_sys::fuzz_target;
use domistream::http::launch::{MAX_LAUNCH_RESPONSE_BYTES, MAX_SESSION_URL_BYTES};
fuzz_target!(|data: &[u8]| { fuzz_target!(|data: &[u8]| {
let _ = domistream::http::parse_launch_response(data); let r = domistream::http::parse_launch_response(data);
if data.len() > MAX_LAUNCH_RESPONSE_BYTES {
assert!(matches!(r, Err(domistream::Error::TooLarge { .. })));
}
if let Ok(l) = r {
if let Some(url) = l.session_url {
assert!(url.len() <= MAX_SESSION_URL_BYTES);
assert!(url.starts_with("rtsp://"));
assert!(!url.chars().any(char::is_control));
}
}
}); });
+21
View File
@@ -0,0 +1,21 @@
//! Fuzzes the video (AES-GCM) and audio (AES-CBC) decryption of hostile packets.
//! Asserts invariants, not only "no panic": random video packets never pass the tag; audio output is shorter than its input, which is whole blocks.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main]
use libfuzzer_sys::fuzz_target;
use domistream::SessionKeys;
use domistream::audio::AudioCipher;
use domistream::video::VideoCipher;
fuzz_target!(|data: &[u8]| {
if let Ok(p) = VideoCipher::new([0x42; 16]).decrypt(data) {
panic!("forged video packet accepted: {} bytes", p.len());
}
let seq = data.first().map_or(0, |b| u16::from(*b));
if let Ok(p) = AudioCipher::new(&SessionKeys { rikey: [0x42; 16], rikeyid: 7 }).decrypt(seq, data) {
assert!(p.len() < data.len() && data.len() % 16 == 0);
}
});
+13 -3
View File
@@ -1,11 +1,21 @@
//! Fuzzes pairing answers: never panics, whatever the bytes. //! Fuzzes pairing answers.
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic. //! Asserts invariants, not only "no panic": decoded values are at most half the body (hex), oversize is TooLarge.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`. //! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main] #![no_main]
use libfuzzer_sys::fuzz_target; use libfuzzer_sys::fuzz_target;
use domistream::pairing::MAX_PAIR_RESPONSE_BYTES;
fuzz_target!(|data: &[u8]| { fuzz_target!(|data: &[u8]| {
let _ = domistream::pairing::parse_pair_response(data); let r = domistream::pairing::parse_pair_response(data);
if data.len() > MAX_PAIR_RESPONSE_BYTES {
assert!(matches!(r, Err(domistream::Error::TooLarge { .. })));
}
if let Ok(p) = r {
for v in [&p.plain_cert, &p.challenge_response, &p.pairing_secret].into_iter().flatten() {
assert!(v.len() * 2 <= data.len());
}
}
}); });
+42
View File
@@ -0,0 +1,42 @@
//! Fuzzes the pairing state machine: a session with the test-only identity fed fuzzer bodies at each step.
//! Asserts invariants, not only "no panic": a host that knows neither the PIN's key nor the host key never gets the session to Paired, and Failed is terminal.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main]
use libfuzzer_sys::fuzz_target;
use domistream::RandomSource;
use domistream::pairing::{ClientIdentity, PairingSession, PairingState, PairingStep, Pin};
const VECTORS: &str = include_str!("../../crates/domistream/tests/fixtures/pairing.txt");
fn value(name: &str) -> Vec<u8> {
let prefix = format!("{name} = ");
let line = VECTORS.lines().find(|l| l.starts_with(&prefix)).expect("fixture value");
let hex = &line[prefix.len()..];
(0..hex.len()).step_by(2).map(|i| u8::from_str_radix(&hex[i..i + 2], 16).expect("hex")).collect()
}
struct Fixed;
impl RandomSource for Fixed {
fn fill(&mut self, dest: &mut [u8]) {
dest.fill(0x33);
}
}
fuzz_target!(|data: &[u8]| {
let Ok(id) = ClientIdentity::from_der(&value("client_cert_der"), &value("client_key_pkcs8_der")) else { return };
let Ok(pin) = Pin::from_digits("4071") else { return };
let Ok((mut s, _)) = PairingSession::start(&id, "0123456789ABCDEF", "fuzz", pin, &mut Fixed) else { return };
// Bodies separated by 0xFF bytes (never valid in the XML); the HTTP status is always 200.
for body in data.split(|b| *b == 0xFF).take(6) {
let before = s.state();
let r = s.handle_response(&id, 200, body, &mut Fixed);
assert!(!matches!(r, Ok(PairingStep::Paired(_))), "paired with a host that cannot know the PIN key");
if let PairingState::Failed(_) = before {
assert!(r.is_err());
assert_eq!(s.state(), before, "Failed is terminal");
}
}
});
+9 -3
View File
@@ -1,5 +1,5 @@
//! Fuzzes the RTP header: never panics, whatever the bytes. //! Fuzzes the RTP header.
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic. //! Asserts invariants, not only "no panic": success means at least 12 bytes and version 2, with the fields read big-endian from the bytes.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`. //! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main] #![no_main]
@@ -7,5 +7,11 @@
use libfuzzer_sys::fuzz_target; use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: &[u8]| { fuzz_target!(|data: &[u8]| {
let _ = domistream::rtp::parse_rtp_header(data); if let Ok(h) = domistream::rtp::parse_rtp_header(data) {
assert!(data.len() >= domistream::rtp::RTP_HEADER_LEN);
assert_eq!(h.flags >> 6, 2);
assert_eq!(h.flags, data[0]);
assert_eq!(h.sequence, u16::from_be_bytes([data[2], data[3]]));
assert_eq!(h.timestamp, u32::from_be_bytes([data[4], data[5], data[6], data[7]]));
}
}); });
+38
View File
@@ -0,0 +1,38 @@
//! Fuzzes the RTSP client state machine with hostile answers.
//! Asserts invariants, not only "no panic": the requests it emits always parse, and it never reports Ready before a full exchange.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main]
use libfuzzer_sys::fuzz_target;
use domistream::http::launch::AudioLayout;
use domistream::rtsp::client::VideoCodec;
use domistream::rtsp::{EncryptionFlags, RtspClient, RtspProgress, StreamConfig, parse_request};
fuzz_target!(|data: &[u8]| {
let config = StreamConfig {
width: 1920,
height: 1080,
fps: 60,
bitrate_kbps: 20_000,
packet_size: 1024,
codec: VideoCodec::Hevc,
hdr: false,
audio: AudioLayout::Stereo,
audio_packet_duration_ms: 5,
min_fec_packets: 2,
reference_frame_invalidation: true,
encryption: EncryptionFlags(7),
};
let Ok(mut c) = RtspClient::new("rtsp://192.0.2.10:48010", config) else { return };
// Answers separated by NUL bytes.
for (answers, answer) in data.split(|b| *b == 0).take(8).enumerate() {
if let Some(req) = c.poll_request() {
parse_request(&req).expect("the client's requests parse");
}
if let Ok(RtspProgress::Ready(_)) = c.handle_response(answer) {
assert!(answers >= 6, "Ready after {} answers", answers + 1);
}
}
});
+26 -12
View File
@@ -1,23 +1,37 @@
//! Fuzzes the RTSP framer over a chunked byte stream: never panics, whatever the bytes. //! Fuzzes the RTSP framer over a chunked byte stream.
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic. //! Asserts invariants, not only "no panic": never buffers past the cap, and the messages do not depend on how the stream is chunked (chunked vs one push).
//! How to run: see the comment at the top of `fuzz/Cargo.toml`. //! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main] #![no_main]
use libfuzzer_sys::fuzz_target; use libfuzzer_sys::fuzz_target;
use domistream::rtsp::{MAX_RTSP_MESSAGE_BYTES, RtspFramer};
fn frame(stream: &[u8], chunk: usize) -> Option<Vec<Vec<u8>>> {
let mut f = RtspFramer::new();
let mut out = Vec::new();
for piece in stream.chunks(chunk) {
f.push(piece).ok()?;
assert!(f.buffered() <= MAX_RTSP_MESSAGE_BYTES);
while let Some(m) = f.next_message().ok()? {
let _ = domistream::rtsp::parse_response(&m);
out.push(m);
}
}
if let Some(last) = f.finish().ok()? {
out.push(last);
}
Some(out)
}
fuzz_target!(|data: &[u8]| { fuzz_target!(|data: &[u8]| {
// First byte picks the chunk size, so libFuzzer explores message boundaries across pushes. // First byte picks the chunk size, so libFuzzer explores message boundaries across pushes.
let Some((&chunk, rest)) = data.split_first() else { return }; let Some((&chunk, rest)) = data.split_first() else { return };
let chunk = usize::from(chunk).max(1); let chunked = frame(rest, usize::from(chunk).max(1));
let mut framer = domistream::rtsp::RtspFramer::new(); let whole = frame(rest, rest.len().max(1));
for piece in rest.chunks(chunk) { if let (Some(a), Some(b)) = (&chunked, &whole) {
if framer.push(piece).is_err() { assert_eq!(a, b, "framing depends on chunking");
return; assert!(a.iter().map(Vec::len).sum::<usize>() <= rest.len());
} }
while let Ok(Some(message)) = framer.next_message() {
let _ = domistream::rtsp::parse_response(&message);
}
}
let _ = framer.finish();
}); });
+6 -3
View File
@@ -1,5 +1,5 @@
//! Fuzzes RTSP requests: never panics, whatever the bytes. //! Fuzzes RTSP requests.
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic. //! Asserts invariants, not only "no panic": parse -> encode -> parse is stable.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`. //! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main] #![no_main]
@@ -7,5 +7,8 @@
use libfuzzer_sys::fuzz_target; use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: &[u8]| { fuzz_target!(|data: &[u8]| {
let _ = domistream::rtsp::parse_request(data); if let Ok(req) = domistream::rtsp::parse_request(data) {
let bytes = req.encode().expect("a parsed request encodes");
assert_eq!(domistream::rtsp::parse_request(&bytes), Ok(req));
}
}); });
+14 -3
View File
@@ -1,11 +1,22 @@
//! Fuzzes RTSP responses: never panics, whatever the bytes. //! Fuzzes RTSP responses.
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic. //! Asserts invariants, not only "no panic": header count, line length and body within the caps.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`. //! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main] #![no_main]
use libfuzzer_sys::fuzz_target; use libfuzzer_sys::fuzz_target;
use domistream::rtsp::{MAX_RTSP_HEADERS, MAX_RTSP_LINE_BYTES, MAX_RTSP_MESSAGE_BYTES};
fuzz_target!(|data: &[u8]| { fuzz_target!(|data: &[u8]| {
let _ = domistream::rtsp::parse_response(data); let r = domistream::rtsp::parse_response(data);
if data.len() > MAX_RTSP_MESSAGE_BYTES {
assert!(matches!(r, Err(domistream::Error::TooLarge { .. })));
}
if let Ok(m) = r {
assert!(m.headers.len() <= MAX_RTSP_HEADERS);
assert!(m.reason.len() <= MAX_RTSP_LINE_BYTES);
assert!(m.headers.iter().all(|(k, v)| k.len() + v.len() <= MAX_RTSP_LINE_BYTES));
assert!(m.body.len() <= data.len());
}
}); });
+23 -4
View File
@@ -1,13 +1,32 @@
//! Fuzzes SDP payloads and the host capabilities read from them: never panics, whatever the bytes. //! Fuzzes SDP payloads, the host capabilities read from them, and `surround-params` values.
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic. //! Asserts invariants, not only "no panic": line and config caps hold; every Opus config obeys RFC 7845's rules.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`. //! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main] #![no_main]
use libfuzzer_sys::fuzz_target; use libfuzzer_sys::fuzz_target;
use domistream::rtsp::sdp::{self, MAX_AUDIO_CHANNELS, MAX_OPUS_CONFIGS, MAX_SDP_LINES, OpusConfig};
fn valid(c: &OpusConfig) {
assert!(c.channels >= 1 && usize::from(c.channels) <= MAX_AUDIO_CHANNELS);
assert!(c.coupled_streams <= c.streams && c.streams >= 1);
assert_eq!(c.mapping.len(), usize::from(c.channels));
let total = u16::from(c.streams) + u16::from(c.coupled_streams);
assert!(c.mapping.iter().all(|&m| u16::from(m) < total));
}
fuzz_target!(|data: &[u8]| { fuzz_target!(|data: &[u8]| {
if let Ok(sdp) = domistream::rtsp::sdp::parse_sdp(data) { if let Ok(s) = sdp::parse_sdp(data) {
let _ = domistream::rtsp::HostCapabilities::from_sdp(&sdp); assert!(s.attributes.len() + s.other.len() <= MAX_SDP_LINES);
if let Ok(caps) = domistream::rtsp::HostCapabilities::from_sdp(&s) {
assert!(caps.opus_configs.len() <= MAX_OPUS_CONFIGS);
caps.opus_configs.iter().for_each(valid);
}
}
if let Ok(text) = core::str::from_utf8(data) {
if let Ok(c) = sdp::parse_surround_params(text) {
valid(&c);
}
} }
}); });
+24
View File
@@ -0,0 +1,24 @@
//! Fuzzes stored certificates and identities (`ServerCert::from_der`, `ClientIdentity::from_der`).
//! Asserts invariants, not only "no panic": accepted DER round-trips; an identity never loads from a cert and key that do not match (first byte splits the input).
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main]
use libfuzzer_sys::fuzz_target;
use domistream::pairing::{ClientIdentity, ServerCert};
fuzz_target!(|data: &[u8]| {
if let Ok(c) = ServerCert::from_der(data) {
assert_eq!(c.der(), data);
assert_eq!(c.matches(data), Ok(true));
}
let Some((&split, rest)) = data.split_first() else { return };
let at = (usize::from(split) * rest.len()) / 255;
let (cert, key) = rest.split_at(at.min(rest.len()));
if let Ok(id) = ClientIdentity::from_der(cert, key) {
assert_eq!(id.cert_der(), cert);
let sig = id.sign(b"fuzz").expect("a loaded identity signs");
ServerCert::from_der(cert).expect("its cert loads").verify(b"fuzz", &sig).expect("key matches cert");
}
});
+16 -3
View File
@@ -1,11 +1,24 @@
//! Fuzzes the host certificate PEM (`plaincert`): never panics, whatever the bytes. //! Fuzzes the host certificate PEM (`plaincert`).
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic. //! Asserts invariants, not only "no panic": an accepted PEM gives a DER that loads again, equals itself, pins itself, and has a signature.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`. //! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main] #![no_main]
use libfuzzer_sys::fuzz_target; use libfuzzer_sys::fuzz_target;
use domistream::pairing::ServerCert;
use domistream::pairing::identity::{MAX_CERT_DER_BYTES, MAX_CERT_PEM_BYTES};
fuzz_target!(|data: &[u8]| { fuzz_target!(|data: &[u8]| {
let _ = domistream::pairing::ServerCert::from_pem(data); let r = ServerCert::from_pem(data);
if data.len() > MAX_CERT_PEM_BYTES {
assert!(matches!(r, Err(domistream::Error::TooLarge { .. })));
}
if let Ok(c) = r {
assert!(c.der().len() <= MAX_CERT_DER_BYTES);
let again = ServerCert::from_der(c.der()).expect("the DER of an accepted PEM loads");
assert_eq!(again, c);
assert_eq!(c.matches(c.der()), Ok(true));
assert!(!c.signature().expect("signature").is_empty());
}
}); });
+18 -3
View File
@@ -1,11 +1,26 @@
//! Fuzzes `/serverinfo` answers: never panics, whatever the bytes. //! Fuzzes `/serverinfo` answers.
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic. //! Asserts invariants, not only "no panic": string fields within MAX_SERVERINFO_FIELD_BYTES, required fields non-empty, oversize is TooLarge.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`. //! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main] #![no_main]
use libfuzzer_sys::fuzz_target; use libfuzzer_sys::fuzz_target;
use domistream::http::serverinfo::{MAX_SERVERINFO_BYTES, MAX_SERVERINFO_FIELD_BYTES};
fuzz_target!(|data: &[u8]| { fuzz_target!(|data: &[u8]| {
let _ = domistream::http::parse_server_info(data); let r = domistream::http::parse_server_info(data);
if data.len() > MAX_SERVERINFO_BYTES {
assert!(matches!(r, Err(domistream::Error::TooLarge { .. })));
}
if let Ok(s) = r {
for f in [&s.hostname, &s.app_version, &s.unique_id, &s.state] {
assert!(f.len() <= MAX_SERVERINFO_FIELD_BYTES);
}
for f in [&s.gfe_version, &s.local_ip].into_iter().flatten() {
assert!(f.len() <= MAX_SERVERINFO_FIELD_BYTES);
}
assert!(!s.hostname.is_empty() && !s.unique_id.is_empty());
let _ = s.is_busy();
}
}); });
+41
View File
@@ -0,0 +1,41 @@
//! Fuzzes the video depacketizer with a sequence of datagrams.
//! Asserts invariants, not only "no panic": frames stay within MAX_FRAME_BYTES and come out in increasing frame order; lost ranges are forward ranges.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main]
use libfuzzer_sys::fuzz_target;
use core::time::Duration;
use domistream::Instant;
use domistream::video::{MAX_FRAME_BYTES, VideoConfig, VideoDepacketizer, VideoEvent};
fuzz_target!(|data: &[u8]| {
let cfg = VideoConfig { packet_size: 64, cipher: None, frame_timeout: Duration::from_millis(20) };
let Ok(mut d) = VideoDepacketizer::new(cfg) else { return };
let mut rest = data;
let mut us = 0u64;
let mut prev: Option<u32> = None;
// Datagrams separated by a 1-byte length; time advances 1 ms per datagram.
while let Some((&len, tail)) = rest.split_first() {
let len = usize::from(len).min(tail.len());
let (g, tail) = tail.split_at(len);
rest = tail;
us += 1000;
let _ = d.push(Instant::from_micros(us), g);
let _ = d.handle_timeout(Instant::from_micros(us));
while let Some(e) = d.poll_event() {
match e {
VideoEvent::Frame(f) => {
assert!(f.bitstream.len() <= MAX_FRAME_BYTES);
if let Some(p) = prev {
assert!(f.frame_index.wrapping_sub(p).wrapping_sub(1) < 1 << 31, "frame order");
}
prev = Some(f.frame_index);
}
VideoEvent::FrameLost { first, last } => assert!(last.wrapping_sub(first) < 1 << 31),
}
}
}
});
+17 -4
View File
@@ -1,12 +1,25 @@
//! Fuzzes video packets and the frame header: never panics, whatever the bytes. //! Fuzzes video packets and the frame header.
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic. //! Asserts invariants, not only "no panic": FEC fields are consistent on success, the payload is the rest of the packet, the frame header keeps its raw bytes.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`. //! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main] #![no_main]
use libfuzzer_sys::fuzz_target; use libfuzzer_sys::fuzz_target;
use domistream::video::packet::{FRAME_HEADER_LEN, MAX_VIDEO_PACKET_BYTES, PAYLOAD_OFFSET, parse_frame_header};
fuzz_target!(|data: &[u8]| { fuzz_target!(|data: &[u8]| {
let _ = domistream::video::parse_video_packet(data); if let Ok(p) = domistream::video::parse_video_packet(data) {
let _ = domistream::video::packet::parse_frame_header(data); assert!(data.len() >= PAYLOAD_OFFSET && data.len() <= MAX_VIDEO_PACKET_BYTES);
assert_eq!(p.payload.len() + PAYLOAD_OFFSET, data.len());
let f = p.nv.fec;
assert!(f.data_shards > 0 && f.block_index <= f.last_block_index && f.last_block_index < 4);
let m =
domistream::fec::parity_count(usize::from(f.data_shards), f.fec_percentage).expect("a consistent block");
assert!(usize::from(f.shard_index) < usize::from(f.data_shards) + m);
assert!(usize::from(f.data_shards) + m <= domistream::fec::MAX_SHARDS);
}
if let Ok(h) = parse_frame_header(data) {
assert_eq!(&h.raw[..], &data[..FRAME_HEADER_LEN]);
}
}); });
+35 -3
View File
@@ -1,11 +1,43 @@
//! Fuzzes the XML reader behind every HTTP answer: never panics, whatever the bytes. //! Fuzzes the XML reader behind every HTTP answer, and `parse_status_response` on the same bytes.
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic. //! Asserts invariants, not only "no panic": every cap holds on success, size over the cap is TooLarge, and the status parser agrees with the XML parser.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`. //! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main] #![no_main]
use libfuzzer_sys::fuzz_target; use libfuzzer_sys::fuzz_target;
use domistream::Error;
use domistream::http::xml::{
self, Element, MAX_XML_ATTRIBUTES, MAX_XML_BYTES, MAX_XML_DEPTH, MAX_XML_ELEMENTS, MAX_XML_TEXT_BYTES,
};
fn walk(e: &Element, depth: usize, count: &mut usize) {
*count += 1;
assert!(depth <= MAX_XML_DEPTH);
assert!(e.attributes.len() <= MAX_XML_ATTRIBUTES);
assert!(e.text.len() <= MAX_XML_TEXT_BYTES);
for c in &e.children {
walk(c, depth + 1, count);
}
}
fuzz_target!(|data: &[u8]| { fuzz_target!(|data: &[u8]| {
let _ = domistream::http::xml::parse(data); let parsed = xml::parse(data);
if data.len() > MAX_XML_BYTES {
assert!(matches!(parsed, Err(Error::TooLarge { .. })));
}
if let Ok(d) = &parsed {
assert_eq!(d.root.name, "root");
let mut count = 0;
walk(&d.root, 1, &mut count);
assert!(count <= MAX_XML_ELEMENTS);
}
let status = domistream::http::parse_status_response(data);
match (&parsed, &status) {
(Ok(d), Ok(())) => assert_eq!(d.status_code, 200),
(Ok(d), Err(Error::HostStatus { code })) => assert_eq!(d.status_code, *code),
(Ok(_), Err(e)) => panic!("xml parsed but status failed with {e:?}"),
(Err(_), Ok(())) => panic!("status accepted what xml refused"),
(Err(_), Err(_)) => {}
}
}); });
-208
View File
@@ -1,208 +0,0 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "cc"
version = "1.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69"
dependencies = [
"find-msvc-tools",
"shlex",
]
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "find-msvc-tools"
version = "0.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
[[package]]
name = "getrandom"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
dependencies = [
"cfg-if",
"libc",
"wasi",
]
[[package]]
name = "lab-relay"
version = "0.1.0"
dependencies = [
"ring",
"rustls",
"rustls-pki-types",
]
[[package]]
name = "libc"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "ring"
version = "0.17.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
dependencies = [
"cc",
"cfg-if",
"getrandom",
"libc",
"untrusted",
"windows-sys",
]
[[package]]
name = "rustls"
version = "0.23.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
dependencies = [
"once_cell",
"ring",
"rustls-pki-types",
"rustls-webpki",
"subtle",
"zeroize",
]
[[package]]
name = "rustls-pki-types"
version = "1.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb"
dependencies = [
"zeroize",
]
[[package]]
name = "rustls-webpki"
version = "0.103.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5"
dependencies = [
"ring",
"rustls-pki-types",
"untrusted",
]
[[package]]
name = "shlex"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[package]]
name = "subtle"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "untrusted"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
[[package]]
name = "windows-sys"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
dependencies = [
"windows-targets",
]
[[package]]
name = "windows-targets"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_gnullvm",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
[[package]]
name = "windows_i686_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
[[package]]
name = "windows_i686_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "zeroize"
version = "1.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa"
-21
View File
@@ -1,21 +0,0 @@
# lab-relay: our own logging relay for the one lab capture (docs/LAB_CAPTURE.md). A tool, never published, never part
# of the domistream crate. Its own workspace so it never joins the main build.
[package]
name = "lab-relay"
version = "0.1.0"
edition = "2024"
rust-version = "1.89"
license = "CPAL-1.0"
publish = false
[workspace]
members = ["."]
[dependencies]
# TLS termination on the HTTPS port with lab-only keys. ring backend: pure Rust + asm, builds with MSVC.
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
rustls-pki-types = { version = "1", features = ["std"] }
ring = "0.17"
[lints.rust]
unsafe_code = "forbid"
-183
View File
@@ -1,183 +0,0 @@
<#
.SYNOPSIS
Lab capture: talk to the lab Sunshine's local API (docs/LAB_CAPTURE.md sections 2, 3, 5). Not elevated.
.DESCRIPTION
Every call goes to https://127.0.0.2:47990 with Basic auth built in memory, no Origin/Referer header (the
documented non-browser path), TLS pinned to the lab certificate in keys\ byte for byte.
Credentials come only from DPAPI files in secrets\; they are never printed, logged or put on a command line.
-Action Rotate throwaway credentials (from lab-install.ps1) -> fresh lab credentials; deletes the throwaway
-Action Status lists paired clients and apps (names only)
-Action Pin submits the PIN Moonlight shows: -PinFile <file with 4 digits> (the file is deleted after
reading), optional -PairingId, -ClientName (default "DomiStream lab Moonlight")
-Action Logs saves GET /api/logs to captures\sunshine.log (not printed: it may hold secrets)
-Action Cleanup unpair all clients, drop the lab cert/key from the config (bind_address stays 127.0.0.2),
restart Sunshine
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[ValidateSet('Rotate', 'Status', 'Pin', 'Logs', 'Cleanup')]
[string] $Action,
[string] $LabRoot = 'E:\build\play-remotely\lab',
[string] $PinFile,
[string] $PairingId,
[string] $ClientName = 'DomiStream lab Moonlight'
)
Set-StrictMode -Version 2.0
$ErrorActionPreference = 'Stop'
$BaseUrl = 'https://127.0.0.2:47990'
$keys = Join-Path $LabRoot 'keys'
$secrets = Join-Path $LabRoot 'secrets'
$captures = Join-Path $LabRoot 'captures'
$throwawayFile = Join-Path $secrets 'sunshine-throwaway.cred'
$labFile = Join-Path $secrets 'sunshine-lab.cred'
$certFile = Join-Path $keys 'sunshine-lab-cert.pem'
function Fail([string] $Why) {
Write-Host "lab-api: STOPPED: $Why"
exit 1
}
# --- TLS pinning: accept exactly the lab certificate -------------------------------------------------------------
if (-not (Test-Path -LiteralPath $certFile)) { Fail "lab certificate not found: $certFile" }
$pem = Get-Content -LiteralPath $certFile -Raw
$m = [regex]::Match($pem, '-----BEGIN CERTIFICATE-----([A-Za-z0-9+/=\s]+)-----END CERTIFICATE-----')
if (-not $m.Success) { Fail 'lab certificate is not PEM' }
$pinnedDer = [Convert]::FromBase64String(($m.Groups[1].Value -replace '\s', ''))
if (-not ('DomiLabPin' -as [type])) {
Add-Type -TypeDefinition @'
using System;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
public static class DomiLabPin {
public static byte[] Pinned;
public static bool Check(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors) {
if (cert == null || Pinned == null) return false;
byte[] raw = cert.GetRawCertData();
if (raw.Length != Pinned.Length) return false;
int diff = 0;
for (int i = 0; i < raw.Length; i++) diff |= raw[i] ^ Pinned[i];
return diff == 0;
}
public static void Install() {
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(Check);
}
}
'@
}
[DomiLabPin]::Pinned = $pinnedDer
[DomiLabPin]::Install()
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
# --- Credentials -------------------------------------------------------------------------------------------------
function Read-Cred([string] $File) {
if (-not (Test-Path -LiteralPath $File)) { Fail "credentials file not found: $File" }
$j = Get-Content -LiteralPath $File -Raw | ConvertFrom-Json
$u = New-Object Management.Automation.PSCredential('x', ($j.user | ConvertTo-SecureString))
$p = New-Object Management.Automation.PSCredential('x', ($j.password | ConvertTo-SecureString))
return @{ User = $u.GetNetworkCredential().Password; Password = $p.GetNetworkCredential().Password }
}
function Save-Cred([string] $File, [string] $User, [string] $Password) {
@{
user = (ConvertTo-SecureString -String $User -AsPlainText -Force | ConvertFrom-SecureString)
password = (ConvertTo-SecureString -String $Password -AsPlainText -Force | ConvertFrom-SecureString)
} | ConvertTo-Json | Set-Content -LiteralPath $File -Encoding ASCII
}
function New-Secret {
$bytes = New-Object byte[] 32
$rng = [Security.Cryptography.RandomNumberGenerator]::Create()
$rng.GetBytes($bytes)
$rng.Dispose()
return ([Convert]::ToBase64String($bytes)).TrimEnd('=').Replace('+', '-').Replace('/', '_')
}
# --- One API call ------------------------------------------------------------------------------------------------
function Invoke-Sunshine([hashtable] $Cred, [string] $Method, [string] $Path, $Body, [string] $OutFile) {
$pair = [Text.Encoding]::UTF8.GetBytes($Cred.User + ':' + $Cred.Password)
$headers = @{ Authorization = 'Basic ' + [Convert]::ToBase64String($pair) }
$req = @{ Uri = $BaseUrl + $Path; Method = $Method; Headers = $headers; UseBasicParsing = $true; TimeoutSec = 30 }
if ($null -ne $Body) {
$req.Body = ($Body | ConvertTo-Json -Depth 5 -Compress)
$req.ContentType = 'application/json'
}
try {
if ($OutFile) {
Invoke-WebRequest @req -OutFile $OutFile | Out-Null
return $null
}
return Invoke-RestMethod @req
} catch {
# The message names the call only; the request, which holds the credentials, is never echoed.
Fail "$Method $Path failed: $($_.Exception.GetType().Name)"
}
}
# --- Actions -----------------------------------------------------------------------------------------------------
switch ($Action) {
'Rotate' {
$old = Read-Cred $throwawayFile
$newUser = 'lab' + (New-Secret).Substring(0, 12)
$newPass = New-Secret
$null = Invoke-Sunshine $old 'POST' '/api/password' @{
currentUsername = $old.User
currentPassword = $old.Password
newUsername = $newUser
newPassword = $newPass
confirmNewPassword = $newPass
}
Save-Cred $labFile $newUser $newPass
# Prove the new pair works before forgetting the old one.
$null = Invoke-Sunshine (Read-Cred $labFile) 'GET' '/api/clients/list' $null
Remove-Item -LiteralPath $throwawayFile -Force
Write-Host 'lab-api: credentials rotated; throwaway deleted'
}
'Status' {
$c = Read-Cred $labFile
$clients = Invoke-Sunshine $c 'GET' '/api/clients/list' $null
$apps = Invoke-Sunshine $c 'GET' '/api/apps' $null
Write-Host ('lab-api: clients: ' + (($clients | ConvertTo-Json -Depth 4 -Compress)))
Write-Host ('lab-api: apps: ' + ((@($apps.apps) | ForEach-Object { $_.name }) -join ', '))
}
'Pin' {
if (-not $PinFile) { Fail '-PinFile is required' }
$pin = (Get-Content -LiteralPath $PinFile -Raw).Trim()
Remove-Item -LiteralPath $PinFile -Force
if ($pin -notmatch '^[0-9]{4}$') { Fail 'the PIN file must hold exactly 4 digits' }
$body = @{ pin = $pin; name = $ClientName }
if ($PairingId) { $body.pairing_id = $PairingId }
$r = Invoke-Sunshine (Read-Cred $labFile) 'POST' '/api/pin' $body
Write-Host ('lab-api: PIN submitted, answer: ' + ($r | ConvertTo-Json -Compress))
}
'Logs' {
$out = Join-Path $captures 'sunshine.log'
$null = Invoke-Sunshine (Read-Cred $labFile) 'GET' '/api/logs' $null $out
Write-Host "lab-api: Sunshine log saved to $out (not shown: it may hold secrets)"
}
'Cleanup' {
$c = Read-Cred $labFile
$null = Invoke-Sunshine $c 'POST' '/api/clients/unpair-all' $null
# Same loopback-only config as lab-install.ps1, without the lab cert/key, so Sunshine makes a fresh pair.
$null = Invoke-Sunshine $c 'POST' '/api/config' @{
bind_address = '127.0.0.2'
address_family = 'ipv4'
origin_web_ui_allowed = 'pc'
upnp = 'disabled'
external_ip = '127.0.0.2'
sunshine_name = 'DomiStream-lab'
lan_encryption_mode = '1'
wan_encryption_mode = '1'
}
$null = Invoke-Sunshine $c 'POST' '/api/restart' $null
Write-Host 'lab-api: unpaired all clients, lab cert/key dropped from the config, Sunshine restarting'
Write-Host 'lab-api: next: delete keys\sunshine-lab-*.pem and keys\moonlight-lab-*.pem once Sunshine is back'
}
}
exit 0
-217
View File
@@ -1,217 +0,0 @@
<#
.SYNOPSIS
Lab capture step (b): install the pinned Sunshine bound to 127.0.0.2 only (docs/LAB_CAPTURE.md section 2).
.DESCRIPTION
Runs ELEVATED, once, started by the operator with:
Start-Process powershell -Verb RunAs -ArgumentList '-NoProfile','-ExecutionPolicy','Bypass','-File',
'<repo>\tools\lab-relay\scripts\lab-install.ps1'
That is the one UAC prompt of the lab capture.
What it does, in order, and nothing else:
1. Refuses unless elevated, unless the MSI's sha256 matches the pin, and unless no Sunshine is installed.
2. Creates keys\, secrets\, captures\ under the lab root, readable only by this account and SYSTEM.
3. msiexec /i (quiet, logged to captures\msiexec.log), then stops the service the MSI started.
4. Writes sunshine.conf: bind_address 127.0.0.2, web UI for this PC only, no UPnP, lab cert/key under keys\.
5. Sets throwaway web-UI credentials with `sunshine --creds` (they exist only in that one process's argv and
in a DPAPI-protected file; lab-api.ps1 -Action Rotate replaces them).
6. Starts the service and checks that every Sunshine listener is on 127.0.0.2. Anything else: stop, fail.
It does not touch Windows Defender, firewall rules (it only lists the ones the MSI added), or any other app.
It never prints, logs or writes a credential in plain text.
#>
[CmdletBinding()]
param(
[string] $LabRoot = 'E:\build\play-remotely\lab',
[string] $Msi = 'E:\build\play-remotely\lab\downloads\Sunshine-Windows-AMD64-installer.msi'
)
Set-StrictMode -Version 2.0
$ErrorActionPreference = 'Stop'
# --- Pins (release API, docs/LAB_CAPTURE.md section 2) ------------------------------------------------------------
$PinnedSha256 = '1d7fed8beecd5889dc7ff14cf9f42d6d38f37c3066c13c6c2a5f4e91847e0ccf'
$PinnedSize = 33710080
$BindAddress = '127.0.0.2'
$Ports = @(47984, 47989, 47990, 48010)
function Fail([string] $Why) {
Write-Host "lab-install: STOPPED: $Why"
exit 1
}
function Say([string] $What) {
Write-Host "lab-install: $What"
}
# --- 1. Preconditions --------------------------------------------------------------------------------------------
$principal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Fail 'not elevated; start it with Start-Process -Verb RunAs'
}
if (-not (Test-Path -LiteralPath $Msi -PathType Leaf)) { Fail "MSI not found: $Msi" }
$msiItem = Get-Item -LiteralPath $Msi
if ($msiItem.Length -ne $PinnedSize) { Fail "MSI size $($msiItem.Length) is not the pinned $PinnedSize" }
$hash = (Get-FileHash -LiteralPath $Msi -Algorithm SHA256).Hash.ToLowerInvariant()
if ($hash -ne $PinnedSha256) { Fail "MSI sha256 $hash does not match the pin; delete the file" }
Say 'MSI matches the pinned sha256'
if (Get-Service -Name '*sunshine*' -ErrorAction SilentlyContinue) { Fail 'a Sunshine service already exists' }
if (Test-Path -LiteralPath 'C:\Program Files\Sunshine\sunshine.exe') { Fail 'C:\Program Files\Sunshine\sunshine.exe already exists' }
$busy = Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue | Where-Object { $Ports -contains $_.LocalPort }
if ($busy) { Fail 'a GameStream port is already in use' }
# --- 2. Lab folders, this account + SYSTEM only ------------------------------------------------------------------
$account = [Security.Principal.WindowsIdentity]::GetCurrent().Name
$keys = Join-Path $LabRoot 'keys'
$secrets = Join-Path $LabRoot 'secrets'
$captures = Join-Path $LabRoot 'captures'
foreach ($dir in @($keys, $secrets, $captures)) {
New-Item -ItemType Directory -Force -Path $dir | Out-Null
& icacls.exe $dir /inheritance:r /grant:r "${account}:(OI)(CI)F" '*S-1-5-18:(OI)(CI)F' | Out-Null
if ($LASTEXITCODE -ne 0) { Fail "icacls failed on $dir" }
}
$hostKey = Join-Path $keys 'sunshine-lab-key.pem'
$hostCert = Join-Path $keys 'sunshine-lab-cert.pem'
foreach ($f in @($hostKey, $hostCert)) { if (Test-Path -LiteralPath $f) { Fail "$f already exists; clean up first" } }
Say "lab folders ready under $LabRoot"
# --- 3. Install ----------------------------------------------------------------------------------------------------
$msiLog = Join-Path $captures 'msiexec.log'
$p = Start-Process -FilePath 'msiexec.exe' -ArgumentList @('/i', "`"$Msi`"", '/qn', '/norestart', '/l*v', "`"$msiLog`"") -Wait -PassThru
if ($p.ExitCode -ne 0 -and $p.ExitCode -ne 3010) { Fail "msiexec exit code $($p.ExitCode); see $msiLog" }
Say "MSI installed (exit code $($p.ExitCode))"
$service = Get-CimInstance Win32_Service | Where-Object { $_.PathName -like '*Sunshine*' } | Select-Object -First 1
if (-not $service) { Fail 'no Sunshine service after the install' }
Stop-Service -Name $service.Name -Force
Say "service $($service.Name) stopped until the config is in"
$exe = 'C:\Program Files\Sunshine\sunshine.exe'
if (-not (Test-Path -LiteralPath $exe)) { Fail "$exe not found after the install" }
$installDir = Split-Path -Parent $exe
$configDir = Join-Path $installDir 'config'
New-Item -ItemType Directory -Force -Path $configDir | Out-Null
$conf = Join-Path $configDir 'sunshine.conf'
if (Test-Path -LiteralPath $conf) { Copy-Item -LiteralPath $conf -Destination (Join-Path $captures 'sunshine.conf.as-installed') -Force }
# --- 4. Config: loopback only ------------------------------------------------------------------------------------
function Write-Conf([bool] $WithLabKeys) {
$lines = @(
"bind_address = $BindAddress",
'address_family = ipv4',
'origin_web_ui_allowed = pc',
'upnp = disabled',
"external_ip = $BindAddress",
'sunshine_name = DomiStream-lab',
'lan_encryption_mode = 1',
'wan_encryption_mode = 1',
'min_log_level = debug'
)
if ($WithLabKeys) {
# Forward slashes: how the config parser treats backslashes is not documented.
$lines += 'pkey = ' + ($hostKey -replace '\\', '/')
$lines += 'cert = ' + ($hostCert -replace '\\', '/')
}
[IO.File]::WriteAllLines($conf, [string[]] $lines, (New-Object Text.UTF8Encoding($false)))
}
Write-Conf $true
Say 'sunshine.conf written (bind_address 127.0.0.2)'
# --- 5. Throwaway credentials ------------------------------------------------------------------------------------
function New-Secret {
$bytes = New-Object byte[] 32
$rng = [Security.Cryptography.RandomNumberGenerator]::Create()
$rng.GetBytes($bytes)
$rng.Dispose()
# base64url: only [A-Za-z0-9_-], so it needs no quoting on a command line.
return ([Convert]::ToBase64String($bytes)).TrimEnd('=').Replace('+', '-').Replace('/', '_')
}
$user = 'lab' + (New-Secret).Substring(0, 12)
$pass = New-Secret
# One child process; its argv dies with it. Output is read and discarded, never written anywhere.
$psi = New-Object Diagnostics.ProcessStartInfo
$psi.FileName = $exe
$psi.Arguments = "--creds $user $pass"
$psi.WorkingDirectory = $installDir
$psi.UseShellExecute = $false
$psi.CreateNoWindow = $true
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
$proc = [Diagnostics.Process]::Start($psi)
$null = $proc.StandardOutput.ReadToEnd()
$null = $proc.StandardError.ReadToEnd()
if (-not $proc.WaitForExit(60000)) { $proc.Kill(); Fail 'sunshine --creds did not finish' }
$credsExit = $proc.ExitCode
$psi = $null
$proc.Dispose()
if ($credsExit -ne 0) { Fail "sunshine --creds exit code $credsExit" }
# DPAPI (this account): readable only by this account on this PC; lab-api.ps1 -Action Rotate replaces it.
$throwaway = Join-Path $secrets 'sunshine-throwaway.cred'
@{
user = (ConvertTo-SecureString -String $user -AsPlainText -Force | ConvertFrom-SecureString)
password = (ConvertTo-SecureString -String $pass -AsPlainText -Force | ConvertFrom-SecureString)
} | ConvertTo-Json | Set-Content -LiteralPath $throwaway -Encoding ASCII
Remove-Variable -Name user, pass -ErrorAction SilentlyContinue
Say 'throwaway credentials set and stored (DPAPI)'
# --- 6. Start and check the binding ------------------------------------------------------------------------------
function Wait-Listeners([int] $Seconds) {
$deadline = (Get-Date).AddSeconds($Seconds)
while ((Get-Date) -lt $deadline) {
$l = Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue | Where-Object { $Ports -contains $_.LocalPort }
if ($l -and (@($l | Select-Object -ExpandProperty LocalPort -Unique).Count -eq $Ports.Count)) { return $l }
Start-Sleep -Milliseconds 500
}
return $null
}
function Assert-Loopback($Listeners) {
$wrong = @($Listeners | Where-Object { $_.LocalAddress -ne $BindAddress })
if ($wrong.Count -gt 0) {
Stop-Service -Name $service.Name -Force
Fail ('Sunshine listened on ' + (($wrong | ForEach-Object { "$($_.LocalAddress):$($_.LocalPort)" }) -join ', ') + '; service stopped')
}
}
Start-Service -Name $service.Name
$listeners = Wait-Listeners 60
if (-not $listeners) {
Stop-Service -Name $service.Name -Force
Fail 'Sunshine did not listen on all four TCP ports; service stopped (bind_address 127.0.0.2 refused? see LAB_CAPTURE.md section 4 fallback)'
}
Assert-Loopback $listeners
# Did Sunshine create its pair at the lab path? If not, fall back to its default pair and copy it for the relay.
$deadline = (Get-Date).AddSeconds(30)
while (-not ((Test-Path -LiteralPath $hostKey) -and (Test-Path -LiteralPath $hostCert)) -and (Get-Date) -lt $deadline) {
Start-Sleep -Milliseconds 500
}
if (-not ((Test-Path -LiteralPath $hostKey) -and (Test-Path -LiteralPath $hostCert))) {
Say 'Sunshine did not create the lab pair at keys\; using its default pair'
Stop-Service -Name $service.Name -Force
Write-Conf $false
Start-Service -Name $service.Name
$listeners = Wait-Listeners 60
if (-not $listeners) { Stop-Service -Name $service.Name -Force; Fail 'Sunshine did not come back after the fallback' }
Assert-Loopback $listeners
$defKey = Join-Path $configDir 'credentials\cakey.pem'
$defCert = Join-Path $configDir 'credentials\cacert.pem'
if (-not ((Test-Path -LiteralPath $defKey) -and (Test-Path -LiteralPath $defCert))) { Fail 'default pair not found either' }
Copy-Item -LiteralPath $defKey -Destination $hostKey
Copy-Item -LiteralPath $defCert -Destination $hostCert
}
Say 'Sunshine listens on 127.0.0.2 only; lab certificate pair in keys\'
# --- Report what the MSI did to the firewall (read only, nothing changed) ----------------------------------------
$rules = @(Get-NetFirewallRule -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -like '*Sunshine*' })
$notes = Join-Path $captures 'install-notes.txt'
@(
"installed: $(Get-Date -Format o)",
"service: $($service.Name)",
"msi sha256: $hash",
"listeners: " + (($listeners | ForEach-Object { "$($_.LocalAddress):$($_.LocalPort)" }) -join ', '),
"firewall rules named like Sunshine (not changed): " + (($rules | ForEach-Object { "$($_.DisplayName) [$($_.Direction) $($_.Action) $($_.Enabled)]" }) -join '; ')
) | Set-Content -LiteralPath $notes -Encoding ASCII
Say "done; notes in $notes. Next, not elevated: lab-api.ps1 -Action Rotate"
exit 0
-317
View File
@@ -1,317 +0,0 @@
//! Relay settings and the loopback-only rule.
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::path::PathBuf;
use std::time::Duration;
use crate::record::Protocol;
/// Where recordings go unless told otherwise.
pub const DEFAULT_CAPTURE_DIR: &str = r"E:\build\play-remotely\lab\captures";
/// Where lab keys live unless told otherwise.
pub const DEFAULT_KEY_DIR: &str = r"E:\build\play-remotely\lab\keys";
/// Transport of a relayed port.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Transport {
/// TCP, bytes copied (and rewritten host-to-client when the protocol is plaintext).
Tcp,
/// TCP with TLS terminated in the relay.
Tls,
/// UDP datagrams.
Udp,
}
/// One relayed port.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PortSpec {
/// Port the relay listens on.
pub listen_port: u16,
/// Port on the upstream (Sunshine) side.
pub upstream_port: u16,
/// Transport.
pub transport: Transport,
/// Protocol label for the records.
pub protocol: Protocol,
}
/// The GameStream default ports (PROTOCOL.md section 0, ArenaTV sunshine-api.md section 3).
pub const GAMESTREAM_PORTS: [(u16, Transport, Protocol); 7] = [
(47984, Transport::Tls, Protocol::HttpsPlain),
(47989, Transport::Tcp, Protocol::Http),
(48010, Transport::Tcp, Protocol::Rtsp),
(47998, Transport::Udp, Protocol::Video),
(47999, Transport::Udp, Protocol::Control),
(48000, Transport::Udp, Protocol::Audio),
(48002, Transport::Udp, Protocol::Mic),
];
/// TLS material, all lab-only PEM files.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TlsFiles {
/// Sunshine's lab certificate (presented to Moonlight, pinned towards Sunshine).
pub host_cert: PathBuf,
/// Sunshine's lab private key.
pub host_key: PathBuf,
/// Moonlight's lab client certificate (presented to Sunshine).
pub client_cert: PathBuf,
/// Moonlight's lab client key.
pub client_key: PathBuf,
}
impl TlsFiles {
/// The four default file names in `dir`.
pub fn in_dir(dir: &std::path::Path) -> Self {
Self {
host_cert: dir.join("sunshine-lab-cert.pem"),
host_key: dir.join("sunshine-lab-key.pem"),
client_cert: dir.join("moonlight-lab-cert.pem"),
client_key: dir.join("moonlight-lab-key.pem"),
}
}
}
/// An equal-length byte replacement applied to host-to-client plaintext.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Rewrite {
/// Bytes to find.
pub from: Vec<u8>,
/// Bytes to put instead, same length.
pub to: Vec<u8>,
}
/// Everything the relay needs.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Config {
/// Address the relay listens on (Moonlight's "host"). Loopback only.
pub listen: IpAddr,
/// Address Sunshine listens on. Loopback only.
pub upstream: IpAddr,
/// Added to each default port on the upstream side (0, or 1000 in the fallback of LAB_CAPTURE.md section 4).
pub upstream_port_offset: u16,
/// Directory for the record file.
pub capture_dir: PathBuf,
/// TLS files; `None` = HTTPS passes through as raw TLS.
pub tls: Option<TlsFiles>,
/// How long an HTTPS connection waits for the TLS files to appear (Moonlight's key may appear only after
/// pairing step 1).
pub wait_for_keys: Duration,
/// Rewrites, applied in order of position in the stream.
pub rewrites: Vec<Rewrite>,
}
/// Why a configuration is refused.
#[derive(Debug, PartialEq, Eq)]
pub enum ConfigError {
/// An address that is not loopback.
NotLoopback(IpAddr),
/// Listen and upstream are the same address with no port offset: the relay would talk to itself.
SelfLoop,
/// A rewrite whose two sides differ in length, or are empty.
BadRewrite(String),
/// Ports overflow with the offset.
PortOverflow(u16),
/// A command-line argument that is not understood.
BadArgument(String),
}
impl std::fmt::Display for ConfigError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::NotLoopback(ip) => {
write!(f, "{ip} is not a loopback address; the relay binds and connects only on loopback")
}
Self::SelfLoop => f.write_str("listen and upstream are the same address and ports"),
Self::BadRewrite(s) => write!(f, "rewrite {s:?}: both sides must be non-empty and the same length"),
Self::PortOverflow(p) => write!(f, "port {p} plus the offset is over 65535"),
Self::BadArgument(s) => write!(f, "bad argument: {s}"),
}
}
}
impl std::error::Error for ConfigError {}
impl Config {
/// The lab defaults: Moonlight sees 127.0.0.1, Sunshine sits on 127.0.0.2, `127.0.0.2` is rewritten to
/// `127.0.0.1` in host-to-client plaintext, TLS files from [`DEFAULT_KEY_DIR`].
pub fn lab_default() -> Self {
Self {
listen: IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)),
upstream: IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)),
upstream_port_offset: 0,
capture_dir: PathBuf::from(DEFAULT_CAPTURE_DIR),
tls: Some(TlsFiles::in_dir(std::path::Path::new(DEFAULT_KEY_DIR))),
wait_for_keys: Duration::from_secs(60),
rewrites: vec![Rewrite { from: b"127.0.0.2".to_vec(), to: b"127.0.0.1".to_vec() }],
}
}
/// Checks the rules: loopback only, no self-loop, sane rewrites, ports in range.
///
/// # Errors
/// The first rule broken.
pub fn validate(&self) -> Result<(), ConfigError> {
for ip in [self.listen, self.upstream] {
if !ip.is_loopback() {
return Err(ConfigError::NotLoopback(ip));
}
}
if self.listen == self.upstream && self.upstream_port_offset == 0 {
return Err(ConfigError::SelfLoop);
}
for r in &self.rewrites {
if r.from.is_empty() || r.from.len() != r.to.len() {
return Err(ConfigError::BadRewrite(String::from_utf8_lossy(&r.from).into_owned()));
}
}
self.ports().map(|_| ())
}
/// The relayed ports with the upstream offset applied.
///
/// # Errors
/// [`ConfigError::PortOverflow`].
pub fn ports(&self) -> Result<Vec<PortSpec>, ConfigError> {
GAMESTREAM_PORTS
.iter()
.map(|&(port, transport, protocol)| {
let upstream_port =
port.checked_add(self.upstream_port_offset).ok_or(ConfigError::PortOverflow(port))?;
let transport =
if transport == Transport::Tls && self.tls.is_none() { Transport::Tcp } else { transport };
let protocol = if transport == Transport::Tcp && protocol == Protocol::HttpsPlain {
Protocol::HttpsTls
} else {
protocol
};
Ok(PortSpec { listen_port: port, upstream_port, transport, protocol })
})
.collect()
}
/// Socket address the relay listens on for `spec`.
pub fn listen_addr(&self, spec: &PortSpec) -> SocketAddr {
SocketAddr::new(self.listen, spec.listen_port)
}
/// Upstream socket address for `spec`.
pub fn upstream_addr(&self, spec: &PortSpec) -> SocketAddr {
SocketAddr::new(self.upstream, spec.upstream_port)
}
/// Applies command-line options to the lab defaults:
/// `--listen <ip>`, `--upstream <ip>`, `--upstream-port-offset <n>`, `--capture-dir <dir>`, `--key-dir <dir>`,
/// `--https-passthrough`, `--wait-for-keys-secs <n>`, `--rewrite <from>=<to>` (repeatable; the first one
/// replaces the default rewrite), `--no-rewrite`.
///
/// # Errors
/// [`ConfigError::BadArgument`] for an unknown option or value, then [`Config::validate`].
pub fn from_args(args: &[String]) -> Result<Self, ConfigError> {
let mut c = Self::lab_default();
let mut custom_rewrites = false;
let mut it = args.iter();
let bad = |s: &str| ConfigError::BadArgument(s.to_owned());
while let Some(a) = it.next() {
let mut value = || it.next().ok_or_else(|| bad(a));
match a.as_str() {
"--listen" => c.listen = value()?.parse().map_err(|_| bad(a))?,
"--upstream" => c.upstream = value()?.parse().map_err(|_| bad(a))?,
"--upstream-port-offset" => c.upstream_port_offset = value()?.parse().map_err(|_| bad(a))?,
"--capture-dir" => c.capture_dir = PathBuf::from(value()?),
"--key-dir" => {
let dir = PathBuf::from(value()?);
if c.tls.is_some() {
c.tls = Some(TlsFiles::in_dir(&dir));
}
}
"--https-passthrough" => c.tls = None,
"--wait-for-keys-secs" => {
c.wait_for_keys = Duration::from_secs(value()?.parse().map_err(|_| bad(a))?);
}
"--rewrite" => {
let v = value()?;
let (from, to) = v.split_once('=').ok_or_else(|| bad(v))?;
if !custom_rewrites {
c.rewrites.clear();
custom_rewrites = true;
}
c.rewrites.push(Rewrite { from: from.as_bytes().to_vec(), to: to.as_bytes().to_vec() });
}
"--no-rewrite" => {
c.rewrites.clear();
custom_rewrites = true;
}
other => return Err(bad(other)),
}
}
c.validate()?;
Ok(c)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn args(s: &str) -> Vec<String> {
s.split_whitespace().map(str::to_owned).collect()
}
#[test]
fn lab_default_is_valid() {
assert_eq!(Config::lab_default().validate(), Ok(()));
}
#[test]
fn non_loopback_listen_or_upstream_is_refused() {
for a in [
"--listen 0.0.0.0",
"--listen 192.168.100.140",
"--upstream 192.168.100.217",
"--listen ::",
"--upstream 26.1.2.3",
] {
assert!(matches!(Config::from_args(&args(a)), Err(ConfigError::NotLoopback(_))), "{a}");
}
}
#[test]
fn other_loopback_addresses_are_accepted() {
let c = Config::from_args(&args("--listen 127.0.0.3 --upstream ::1")).unwrap();
assert!(c.listen.is_loopback() && c.upstream.is_loopback());
}
#[test]
fn self_loop_is_refused_unless_offset() {
assert_eq!(Config::from_args(&args("--upstream 127.0.0.1")), Err(ConfigError::SelfLoop));
let c = Config::from_args(&args("--upstream 127.0.0.1 --upstream-port-offset 1000")).unwrap();
let ports = c.ports().unwrap();
assert!(ports.iter().all(|p| p.upstream_port == p.listen_port + 1000));
}
#[test]
fn rewrites_must_keep_length() {
assert!(matches!(Config::from_args(&args("--rewrite 48984=7984")), Err(ConfigError::BadRewrite(_))));
assert!(matches!(Config::from_args(&args("--rewrite =")), Err(ConfigError::BadRewrite(_))));
let c = Config::from_args(&args("--rewrite 48984=47984 --rewrite 49010=48010")).unwrap();
assert_eq!(c.rewrites.len(), 2, "custom rewrites replace the default one");
}
#[test]
fn port_overflow_is_refused() {
assert!(matches!(Config::from_args(&args("--upstream-port-offset 20000")), Err(ConfigError::PortOverflow(_))));
}
#[test]
fn passthrough_turns_tls_into_raw_tcp() {
let c = Config::from_args(&args("--https-passthrough")).unwrap();
let https = c.ports().unwrap().into_iter().find(|p| p.listen_port == 47984).unwrap();
assert_eq!((https.transport, https.protocol), (Transport::Tcp, Protocol::HttpsTls));
}
#[test]
fn unknown_arguments_are_refused() {
assert!(matches!(Config::from_args(&args("--bind 0.0.0.0")), Err(ConfigError::BadArgument(_))));
assert!(matches!(Config::from_args(&args("--listen")), Err(ConfigError::BadArgument(_))));
}
}
-154
View File
@@ -1,154 +0,0 @@
//! lab-relay: our own logging relay for the one GameStream lab capture (`docs/LAB_CAPTURE.md`).
//!
//! ```text
//! lab-relay run [--listen 127.0.0.1] [--upstream 127.0.0.2] [--upstream-port-offset N] [--capture-dir DIR]
//! [--key-dir DIR] [--https-passthrough] [--wait-for-keys-secs N] [--rewrite FROM=TO]... [--no-rewrite]
//! lab-relay dump <file.dslr> list records, secrets redacted
//! lab-relay strip-video <in> <out> copy with video payloads cut to their 32 header bytes
//! ```
//!
//! Binds and connects only on loopback (refused otherwise). Never sends anything of its own.
mod config;
mod record;
mod recorder;
mod redact;
mod rewrite;
mod tcp;
mod tls;
mod udp;
use std::fs::File;
use std::io::{self, BufReader, BufWriter, Write};
use std::process::ExitCode;
use std::sync::Arc;
use std::thread;
use config::{Config, Transport};
use record::{Kind, Protocol, Record};
use recorder::Recorder;
/// Bytes of a video packet kept by `strip-video`: RTP header, reserved bytes and the NV header.
const VIDEO_HEADER_KEEP: usize = 32;
/// Text shown per record by `dump`.
const DUMP_TEXT_LIMIT: usize = 4000;
fn main() -> ExitCode {
let args: Vec<String> = std::env::args().skip(1).collect();
let result = match args.split_first() {
Some((cmd, rest)) if cmd == "run" => run(rest),
Some((cmd, [file])) if cmd == "dump" => dump(file),
Some((cmd, [input, output])) if cmd == "strip-video" => strip_video(input, output),
_ => Err("usage: lab-relay run [options] | dump <file> | strip-video <in> <out>".into()),
};
match result {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
eprintln!("lab-relay: {e}");
ExitCode::FAILURE
}
}
}
type AnyResult = Result<(), Box<dyn std::error::Error>>;
fn run(args: &[String]) -> AnyResult {
let config = Arc::new(Config::from_args(args)?);
let (rec, path) = Recorder::create(&config.capture_dir)?;
let rec = Arc::new(rec);
println!("lab-relay: recording to {}", path.display());
let mut threads = Vec::new();
for spec in config.ports()? {
let (config, rec) = (Arc::clone(&config), Arc::clone(&rec));
println!("lab-relay: {:?} {} -> {}", spec.protocol, config.listen_addr(&spec), config.upstream_addr(&spec));
threads.push(thread::spawn(move || {
let r = match spec.transport {
Transport::Tcp => tcp::serve(Arc::clone(&config), spec, Arc::clone(&rec)),
Transport::Tls => tls::serve(Arc::clone(&config), spec, Arc::clone(&rec)),
Transport::Udp => udp::serve(Arc::clone(&config), spec, Arc::clone(&rec)),
};
if let Err(e) = r {
eprintln!("lab-relay: port {} stopped: {e}", spec.listen_port);
rec.note(Protocol::Meta, 0, &format!("port {} stopped: {e}", spec.listen_port));
}
}));
}
rec.note(Protocol::Meta, 0, "relay started");
for t in threads {
let _ = t.join();
}
Ok(())
}
fn is_text(r: &Record) -> bool {
r.kind == Kind::Note
|| r.kind == Kind::Open
|| matches!(r.protocol, Protocol::Http | Protocol::HttpsPlain | Protocol::Rtsp)
}
fn dump(file: &str) -> AnyResult {
let mut input = BufReader::new(File::open(file)?);
let header = record::read_header(&mut input)?;
let stdout = io::stdout();
let mut out = stdout.lock();
writeln!(out, "capture started at unix {} us", header.start_unix_micros)?;
let mut index = 0u64;
loop {
let r = match record::read_record(&mut input) {
Ok(Some(r)) => r,
Ok(None) => break,
Err(e) => {
writeln!(out, "stopped at record {index}: {e}")?;
break;
}
};
writeln!(
out,
"#{index} t={}.{:06}s conn={} {:?} {:?} {:?} {} bytes",
r.time_micros / 1_000_000,
r.time_micros % 1_000_000,
r.connection,
r.kind,
r.protocol,
r.direction,
r.payload.len()
)?;
if is_text(&r) {
let text = redact::redact(&r.payload);
let shown = &text[..text.len().min(DUMP_TEXT_LIMIT)];
writeln!(out, " {}", String::from_utf8_lossy(shown).escape_debug())?;
} else {
let hex: String = r.payload.iter().take(32).map(|b| format!("{b:02x} ")).collect();
writeln!(out, " {hex}")?;
}
index += 1;
}
Ok(())
}
fn strip_video(input: &str, output: &str) -> AnyResult {
let mut reader = BufReader::new(File::open(input)?);
let header = record::read_header(&mut reader)?;
let mut writer = BufWriter::new(File::options().write(true).create_new(true).open(output)?);
record::write_header(&mut writer, header)?;
let mut stripped = 0u64;
while let Some(mut r) = record::read_record(&mut reader)? {
if r.kind == Kind::Data && r.protocol == Protocol::Video && r.payload.len() > VIDEO_HEADER_KEEP {
r.payload.truncate(VIDEO_HEADER_KEEP);
stripped += 1;
}
record::write_record(&mut writer, &r)?;
}
let note = Record {
kind: Kind::Note,
protocol: Protocol::Meta,
direction: record::Direction::None,
connection: 0,
time_micros: u64::MAX,
payload: format!("strip-video: {stripped} video payloads cut to {VIDEO_HEADER_KEEP} bytes").into_bytes(),
};
record::write_record(&mut writer, &note)?;
writer.flush()?;
println!("lab-relay: {stripped} video records stripped");
Ok(())
}
-387
View File
@@ -1,387 +0,0 @@
//! The record file: everything the relay sees, framed so it can be read back exactly.
//!
//! ```text
//! file = header record*
//! header = "DSLR" version:u8(=1) reserved:[u8;3](=0) start_unix_micros:u64le
//! record = kind:u8 protocol:u8 direction:u8 reserved:u8(=0) connection:u32le time_micros:u64le len:u32le bytes[len]
//! ```
//!
//! `time_micros` counts from the start of the capture. A record never holds more than [`MAX_PAYLOAD`] bytes.
use std::fmt;
use std::io::{self, Read, Write};
/// File magic.
pub const MAGIC: [u8; 4] = *b"DSLR";
/// Format version.
pub const VERSION: u8 = 1;
/// Header length in bytes.
pub const HEADER_LEN: usize = 16;
/// Record header length in bytes.
pub const RECORD_HEADER_LEN: usize = 20;
/// Largest payload of one record (a UDP datagram is at most 64 KiB; TCP reads are split to fit).
pub const MAX_PAYLOAD: usize = 1 << 20;
/// What a record says.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Kind {
/// A connection or UDP flow opened.
Open,
/// Bytes seen.
Data,
/// A connection or flow closed.
Close,
/// A UTF-8 note from the relay (TLS details, rewrites, errors).
Note,
}
/// Which protocol the bytes belong to.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Protocol {
/// Relay-level notes.
Meta,
/// HTTP, port 47989.
Http,
/// Raw TLS bytes on 47984 (when not terminated).
HttpsTls,
/// Decrypted HTTPS plaintext on 47984.
HttpsPlain,
/// RTSP, port 48010.
Rtsp,
/// Video RTP, port 47998.
Video,
/// Control ENet, port 47999.
Control,
/// Audio RTP, port 48000.
Audio,
/// Microphone, port 48002.
Mic,
}
/// Which way the bytes went.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Direction {
/// Not a transfer (notes, opens, closes).
None,
/// Moonlight to Sunshine.
ClientToHost,
/// Sunshine to Moonlight.
HostToClient,
}
macro_rules! codes {
($t:ty { $($v:ident = $c:literal),* $(,)? }) => {
impl $t {
/// Wire code.
pub const fn code(self) -> u8 {
match self { $(Self::$v => $c),* }
}
/// From a wire code.
pub const fn from_code(code: u8) -> Option<Self> {
match code { $($c => Some(Self::$v),)* _ => None }
}
}
};
}
codes!(Kind { Open = 1, Data = 2, Close = 3, Note = 4 });
codes!(Protocol {
Meta = 0, Http = 1, HttpsTls = 2, HttpsPlain = 3, Rtsp = 4, Video = 5, Control = 6, Audio = 7, Mic = 8,
});
codes!(Direction { None = 0, ClientToHost = 1, HostToClient = 2 });
/// The file header.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Header {
/// Wall-clock start of the capture, Unix microseconds.
pub start_unix_micros: u64,
}
/// One record.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Record {
/// What it is.
pub kind: Kind,
/// Protocol.
pub protocol: Protocol,
/// Direction.
pub direction: Direction,
/// Connection or flow id, unique per capture.
pub connection: u32,
/// Microseconds since the capture started.
pub time_micros: u64,
/// The bytes (UTF-8 text for notes).
pub payload: Vec<u8>,
}
/// Why a file could not be read.
#[derive(Debug)]
pub enum RecordError {
/// I/O failure.
Io(io::Error),
/// Not a record file, or another version.
BadHeader,
/// The file ends inside a record.
Truncated,
/// A field holds a value this version does not know.
BadField(&'static str, u64),
/// A payload over [`MAX_PAYLOAD`].
TooLarge(usize),
}
impl fmt::Display for RecordError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Io(e) => write!(f, "i/o: {e}"),
Self::BadHeader => f.write_str("not a DSLR v1 file"),
Self::Truncated => f.write_str("file ends inside a record"),
Self::BadField(name, v) => write!(f, "bad {name}: {v}"),
Self::TooLarge(n) => write!(f, "payload of {n} bytes is over the limit"),
}
}
}
impl std::error::Error for RecordError {}
impl From<io::Error> for RecordError {
fn from(e: io::Error) -> Self {
Self::Io(e)
}
}
/// Writes the file header.
///
/// # Errors
/// I/O errors.
pub fn write_header(out: &mut impl Write, header: Header) -> io::Result<()> {
let mut buf = [0u8; HEADER_LEN];
buf[..4].copy_from_slice(&MAGIC);
buf[4] = VERSION;
buf[8..16].copy_from_slice(&header.start_unix_micros.to_le_bytes());
out.write_all(&buf)
}
/// Writes one record.
///
/// # Errors
/// [`io::ErrorKind::InvalidInput`] for a payload over [`MAX_PAYLOAD`]; I/O errors.
pub fn write_record(out: &mut impl Write, record: &Record) -> io::Result<()> {
let len = record.payload.len();
if len > MAX_PAYLOAD {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "record payload over MAX_PAYLOAD"));
}
let mut head = [0u8; RECORD_HEADER_LEN];
head[0] = record.kind.code();
head[1] = record.protocol.code();
head[2] = record.direction.code();
head[4..8].copy_from_slice(&record.connection.to_le_bytes());
head[8..16].copy_from_slice(&record.time_micros.to_le_bytes());
// `len <= MAX_PAYLOAD < u32::MAX`, checked above.
head[16..20].copy_from_slice(&(len as u32).to_le_bytes());
out.write_all(&head)?;
out.write_all(&record.payload)
}
/// Reads exactly `buf.len()` bytes; `Ok(false)` at a clean end before the first byte.
fn read_full(input: &mut impl Read, buf: &mut [u8]) -> Result<bool, RecordError> {
let mut filled = 0;
while filled < buf.len() {
match input.read(&mut buf[filled..]) {
Ok(0) if filled == 0 => return Ok(false),
Ok(0) => return Err(RecordError::Truncated),
Ok(n) => filled += n,
Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
Err(e) => return Err(e.into()),
}
}
Ok(true)
}
/// Reads and checks the file header.
///
/// # Errors
/// [`RecordError::BadHeader`] for a wrong magic, version or reserved bytes; [`RecordError::Truncated`].
pub fn read_header(input: &mut impl Read) -> Result<Header, RecordError> {
let mut buf = [0u8; HEADER_LEN];
if !read_full(input, &mut buf)? {
return Err(RecordError::Truncated);
}
if buf[..4] != MAGIC || buf[4] != VERSION || buf[5..8] != [0, 0, 0] {
return Err(RecordError::BadHeader);
}
let mut start = [0u8; 8];
start.copy_from_slice(&buf[8..16]);
Ok(Header { start_unix_micros: u64::from_le_bytes(start) })
}
/// Reads the next record; `Ok(None)` at the end of the file.
///
/// # Errors
/// [`RecordError::Truncated`] inside a record, [`RecordError::BadField`] for unknown codes or a non-zero reserved
/// byte, [`RecordError::TooLarge`] before allocating an oversized payload.
pub fn read_record(input: &mut impl Read) -> Result<Option<Record>, RecordError> {
let mut head = [0u8; RECORD_HEADER_LEN];
if !read_full(input, &mut head)? {
return Ok(None);
}
let kind = Kind::from_code(head[0]).ok_or(RecordError::BadField("kind", head[0].into()))?;
let protocol = Protocol::from_code(head[1]).ok_or(RecordError::BadField("protocol", head[1].into()))?;
let direction = Direction::from_code(head[2]).ok_or(RecordError::BadField("direction", head[2].into()))?;
if head[3] != 0 {
return Err(RecordError::BadField("reserved", head[3].into()));
}
let word = |r: std::ops::Range<usize>| {
let mut b = [0u8; 8];
b[..r.len()].copy_from_slice(&head[r]);
u64::from_le_bytes(b)
};
let connection = word(4..8) as u32;
let time_micros = word(8..16);
let len = word(16..20) as usize;
if len > MAX_PAYLOAD {
return Err(RecordError::TooLarge(len));
}
let mut payload = vec![0u8; len];
if len > 0 && !read_full(input, &mut payload)? {
return Err(RecordError::Truncated);
}
Ok(Some(Record { kind, protocol, direction, connection, time_micros, payload }))
}
#[cfg(test)]
mod tests {
use super::*;
fn sample(payload: &[u8]) -> Record {
Record {
kind: Kind::Data,
protocol: Protocol::Control,
direction: Direction::HostToClient,
connection: 0x0102_0304,
time_micros: 0x1122_3344_5566_7788,
payload: payload.to_vec(),
}
}
fn file(records: &[Record]) -> Vec<u8> {
let mut out = Vec::new();
write_header(&mut out, Header { start_unix_micros: 42 }).unwrap();
for r in records {
write_record(&mut out, r).unwrap();
}
out
}
#[test]
fn header_layout_is_fixed() {
let mut out = Vec::new();
write_header(&mut out, Header { start_unix_micros: 0x0807_0605_0403_0201 }).unwrap();
assert_eq!(out, b"DSLR\x01\0\0\0\x01\x02\x03\x04\x05\x06\x07\x08");
}
#[test]
fn record_layout_is_fixed() {
let mut out = Vec::new();
write_record(&mut out, &sample(b"ab")).unwrap();
let mut want = vec![2, 6, 2, 0, 4, 3, 2, 1, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 2, 0, 0, 0];
want.extend_from_slice(b"ab");
assert_eq!(out, want);
}
#[test]
fn round_trip_of_every_code() {
let mut records = Vec::new();
for k in 1..=4 {
for p in 0..=8 {
for d in 0..=2 {
records.push(Record {
kind: Kind::from_code(k).unwrap(),
protocol: Protocol::from_code(p).unwrap(),
direction: Direction::from_code(d).unwrap(),
connection: u32::from(k) * 100 + u32::from(p),
time_micros: u64::from(d),
payload: vec![k, p, d],
});
}
}
}
records.push(sample(&[]));
records.push(sample(&vec![0xAB; MAX_PAYLOAD]));
let bytes = file(&records);
let mut input = bytes.as_slice();
assert_eq!(read_header(&mut input).unwrap(), Header { start_unix_micros: 42 });
for want in &records {
assert_eq!(read_record(&mut input).unwrap().as_ref(), Some(want));
}
assert!(read_record(&mut input).unwrap().is_none());
}
#[test]
fn oversized_payload_is_refused_on_write() {
let err = write_record(&mut Vec::new(), &sample(&vec![0; MAX_PAYLOAD + 1])).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
}
#[test]
fn oversized_length_is_refused_before_allocating() {
let mut bytes = Vec::new();
write_record(&mut bytes, &sample(b"")).unwrap();
bytes[16..20].copy_from_slice(&u32::MAX.to_le_bytes());
assert!(matches!(read_record(&mut bytes.as_slice()), Err(RecordError::TooLarge(_))));
}
#[test]
fn every_cut_inside_a_record_is_truncated() {
let mut bytes = Vec::new();
write_record(&mut bytes, &sample(b"payload")).unwrap();
for cut in 1..bytes.len() {
let r = read_record(&mut &bytes[..cut]);
assert!(matches!(r, Err(RecordError::Truncated)), "cut at {cut}");
}
}
#[test]
fn unknown_codes_and_reserved_bytes_are_refused() {
for (offset, value) in [(0, 0u8), (0, 5), (1, 9), (2, 3), (3, 1)] {
let mut bytes = Vec::new();
write_record(&mut bytes, &sample(b"x")).unwrap();
bytes[offset] = value;
assert!(matches!(read_record(&mut bytes.as_slice()), Err(RecordError::BadField(..))), "{offset}");
}
}
#[test]
fn bad_headers_are_refused() {
let good = file(&[]);
for (offset, value) in [(0, b'X'), (4, 2), (5, 1)] {
let mut bytes = good.clone();
bytes[offset] = value;
assert!(matches!(read_header(&mut bytes.as_slice()), Err(RecordError::BadHeader)));
}
assert!(matches!(read_header(&mut &good[..10]), Err(RecordError::Truncated)));
}
/// A reader that hands out one byte per call, like a slow pipe.
struct Trickle<'a>(&'a [u8]);
impl Read for Trickle<'_> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match (self.0.split_first(), buf.first_mut()) {
(Some((&b, rest)), Some(slot)) => {
*slot = b;
self.0 = rest;
Ok(1)
}
_ => Ok(0),
}
}
}
#[test]
fn short_reads_are_reassembled() {
let bytes = file(&[sample(b"one"), sample(b"two")]);
let mut input = Trickle(&bytes);
read_header(&mut input).unwrap();
assert_eq!(read_record(&mut input).unwrap().unwrap().payload, b"one");
assert_eq!(read_record(&mut input).unwrap().unwrap().payload, b"two");
assert!(read_record(&mut input).unwrap().is_none());
}
}
-73
View File
@@ -1,73 +0,0 @@
//! The shared, thread-safe writer of the record file. Every record is flushed at once, so a killed relay leaves a
//! file that reads cleanly up to its last whole record.
use std::fs::{File, OpenOptions};
use std::io::{self, BufWriter, Write};
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::time::{Instant, SystemTime, UNIX_EPOCH};
use crate::record::{self, Direction, Header, Kind, Protocol, Record};
/// Writes records for one capture.
pub struct Recorder {
out: Mutex<BufWriter<File>>,
start: Instant,
next_connection: AtomicU32,
failed: AtomicBool,
}
impl Recorder {
/// Creates `session-<unix seconds>.dslr` in `dir` (never overwrites) and writes the header.
///
/// # Errors
/// I/O errors, including an existing file of the same name.
pub fn create(dir: &Path) -> io::Result<(Self, PathBuf)> {
let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default();
let path = dir.join(format!("session-{}.dslr", now.as_secs()));
let file = OpenOptions::new().write(true).create_new(true).open(&path)?;
let mut out = BufWriter::new(file);
let start_unix_micros = u64::try_from(now.as_micros()).unwrap_or(u64::MAX);
record::write_header(&mut out, Header { start_unix_micros })?;
out.flush()?;
let rec = Self {
out: Mutex::new(out),
start: Instant::now(),
next_connection: AtomicU32::new(1),
failed: AtomicBool::new(false),
};
Ok((rec, path))
}
/// A fresh connection or flow id.
pub fn new_connection(&self) -> u32 {
self.next_connection.fetch_add(1, Ordering::Relaxed)
}
/// Records bytes (split into several records if over [`record::MAX_PAYLOAD`]).
pub fn log(&self, kind: Kind, protocol: Protocol, direction: Direction, connection: u32, payload: &[u8]) {
let time_micros = u64::try_from(self.start.elapsed().as_micros()).unwrap_or(u64::MAX);
let chunks: Vec<&[u8]> =
if payload.is_empty() { vec![payload] } else { payload.chunks(record::MAX_PAYLOAD).collect() };
let Ok(mut out) = self.out.lock() else { return self.fail("lock poisoned") };
for chunk in chunks {
let r = Record { kind, protocol, direction, connection, time_micros, payload: chunk.to_vec() };
if let Err(e) = record::write_record(&mut *out, &r).and_then(|()| out.flush()) {
return self.fail(&e.to_string());
}
}
}
/// Records a note (never pass key material here).
pub fn note(&self, protocol: Protocol, connection: u32, text: &str) {
self.log(Kind::Note, protocol, Direction::None, connection, text.as_bytes());
}
/// Reports the first write failure on stderr; later ones stay silent.
fn fail(&self, why: &str) {
if !self.failed.swap(true, Ordering::Relaxed) {
eprintln!("lab-relay: writing the record file failed: {why}");
}
}
}
-122
View File
@@ -1,122 +0,0 @@
//! Hides secrets when records are printed (`lab-relay dump`). The record file itself keeps everything; it never
//! leaves the lab folder.
/// Query parameters whose values are secret or let someone redo the pairing proofs.
pub const SECRET_PARAMS: [&str; 6] =
["rikey", "salt", "clientchallenge", "serverchallengeresp", "clientpairingsecret", "pin"];
/// XML elements whose text is secret.
pub const SECRET_ELEMENTS: [&str; 2] = ["challengeresponse", "pairingsecret"];
/// HTTP headers whose values are secret.
pub const SECRET_HEADERS: [&str; 2] = ["authorization", "cookie"];
/// What replaces a secret.
pub const MARK: &[u8] = b"<redacted>";
fn ends_param_value(b: u8) -> bool {
matches!(b, b'&' | b' ' | b'"' | b'\r' | b'\n' | b'<' | b'#')
}
/// Returns `text` with every secret value replaced by [`MARK`].
pub fn redact(text: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(text.len());
let mut i = 0;
let lower: Vec<u8> = text.to_ascii_lowercase();
'scan: while i < text.len() {
// `name=` at a parameter boundary.
if i == 0 || matches!(text[i - 1], b'?' | b'&' | b' ' | b'\n') {
for name in SECRET_PARAMS {
let key = [name.as_bytes(), b"="].concat();
if lower[i..].starts_with(&key) {
out.extend_from_slice(&text[i..i + key.len()]);
out.extend_from_slice(MARK);
i += key.len();
while i < text.len() && !ends_param_value(text[i]) {
i += 1;
}
continue 'scan;
}
}
}
// `<element>` … `</`.
if text[i] == b'<' {
for name in SECRET_ELEMENTS {
let open = [b"<", name.as_bytes(), b">"].concat();
if lower[i..].starts_with(&open) {
out.extend_from_slice(&text[i..i + open.len()]);
out.extend_from_slice(MARK);
i += open.len();
while i < text.len() && !text[i..].starts_with(b"</") {
i += 1;
}
continue 'scan;
}
}
}
// `Header:` at a line start, up to the end of the line.
if i == 0 || text[i - 1] == b'\n' {
for name in SECRET_HEADERS {
let key = [name.as_bytes(), b":"].concat();
if lower[i..].starts_with(&key) {
out.extend_from_slice(&text[i..i + key.len()]);
out.extend_from_slice(b" ");
out.extend_from_slice(MARK);
i += key.len();
while i < text.len() && text[i] != b'\r' && text[i] != b'\n' {
i += 1;
}
continue 'scan;
}
}
}
out.push(text[i]);
i += 1;
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn r(s: &str) -> String {
String::from_utf8(redact(s.as_bytes())).unwrap()
}
#[test]
fn launch_key_is_hidden() {
assert_eq!(
r("GET /launch?uniqueid=0123&appid=1&rikey=00112233445566778899aabbccddeeff&rikeyid=7 HTTP/1.1"),
"GET /launch?uniqueid=0123&appid=1&rikey=<redacted>&rikeyid=7 HTTP/1.1"
);
}
#[test]
fn pairing_values_are_hidden_but_names_and_certs_stay() {
assert_eq!(
r("GET /pair?uniqueid=1&phrase=getservercert&salt=ABCD&clientcert=2D2D HTTP/1.1"),
"GET /pair?uniqueid=1&phrase=getservercert&salt=<redacted>&clientcert=2D2D HTTP/1.1"
);
assert_eq!(
r("<root status_code=\"200\"><paired>1</paired><pairingsecret>ffee</pairingsecret></root>"),
"<root status_code=\"200\"><paired>1</paired><pairingsecret><redacted></pairingsecret></root>"
);
}
#[test]
fn auth_headers_are_hidden() {
assert_eq!(
r("POST /api/pin HTTP/1.1\r\nAuthorization: Basic dXNlcjpwYXNz\r\nHost: x\r\n"),
"POST /api/pin HTTP/1.1\r\nAuthorization: <redacted>\r\nHost: x\r\n"
);
}
#[test]
fn lookalike_names_are_not_touched() {
assert_eq!(r("GET /x?rikeyid=5&nosalt=1"), "GET /x?rikeyid=5&nosalt=1");
}
#[test]
fn value_at_end_of_input_is_hidden() {
assert_eq!(r("?rikey=abc"), "?rikey=<redacted>");
assert_eq!(r("<challengeresponse>abc"), "<challengeresponse><redacted>");
}
}
-150
View File
@@ -1,150 +0,0 @@
//! Equal-length byte replacement over a stream, safe across read boundaries.
//!
//! Bytes that could be the start of a pattern at the end of a chunk are held back until the next chunk (or
//! [`Rewriter::flush`]), so a pattern split over two reads is still found. Lengths never change, so HTTP
//! `Content-Length` stays right.
use crate::config::Rewrite;
/// A streaming rewriter.
#[derive(Debug)]
pub struct Rewriter {
rules: Vec<Rewrite>,
held: Vec<u8>,
}
impl Rewriter {
/// A rewriter for `rules` (each non-empty, `from.len() == to.len()`, checked by the config).
pub fn new(rules: Vec<Rewrite>) -> Self {
Self { rules, held: Vec::new() }
}
/// Feeds a chunk; returns the bytes that are safe to send and how many replacements were made.
pub fn push(&mut self, chunk: &[u8]) -> (Vec<u8>, usize) {
if self.rules.is_empty() {
return (chunk.to_vec(), 0);
}
let mut data = std::mem::take(&mut self.held);
data.extend_from_slice(chunk);
let mut out = Vec::with_capacity(data.len());
let mut count = 0;
let mut i = 0;
'scan: while i < data.len() {
for r in &self.rules {
if data[i..].starts_with(&r.from) {
out.extend_from_slice(&r.to);
i += r.from.len();
count += 1;
continue 'scan;
}
}
// Could `data[i..]` be the beginning of a pattern that the next chunk completes?
let rest = &data[i..];
if self.rules.iter().any(|r| rest.len() < r.from.len() && r.from.starts_with(rest)) {
self.held = rest.to_vec();
return (out, count);
}
out.push(data[i]);
i += 1;
}
(out, count)
}
/// Releases held bytes (end of stream, or a pause in it).
pub fn flush(&mut self) -> Vec<u8> {
std::mem::take(&mut self.held)
}
/// Whether there are no rules (the rewriter then passes bytes through and never holds any).
pub fn is_empty(&self) -> bool {
self.rules.is_empty()
}
/// Bytes currently held back.
#[cfg(test)]
pub fn held(&self) -> usize {
self.held.len()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn lab() -> Rewriter {
Rewriter::new(vec![Rewrite { from: b"127.0.0.2".to_vec(), to: b"127.0.0.1".to_vec() }])
}
fn run(r: &mut Rewriter, chunks: &[&[u8]]) -> (Vec<u8>, usize) {
let mut out = Vec::new();
let mut n = 0;
for c in chunks {
let (o, k) = r.push(c);
out.extend(o);
n += k;
}
out.extend(r.flush());
(out, n)
}
const ANSWER: &[u8] = b"<root status_code=\"200\"><sessionUrl0>rtsp://127.0.0.2:48010</sessionUrl0></root>";
#[test]
fn replaces_in_one_chunk() {
let (out, n) = run(&mut lab(), &[ANSWER]);
assert_eq!(n, 1);
assert_eq!(out, ANSWER.to_vec().replace_all_for_test());
}
#[test]
fn replaces_across_every_split_point() {
let want = ANSWER.to_vec().replace_all_for_test();
for cut in 0..=ANSWER.len() {
let (out, n) = run(&mut lab(), &[&ANSWER[..cut], &ANSWER[cut..]]);
assert_eq!(n, 1, "cut {cut}");
assert_eq!(out, want, "cut {cut}");
}
}
#[test]
fn byte_by_byte_works() {
let chunks: Vec<&[u8]> = ANSWER.chunks(1).collect();
let (out, n) = run(&mut lab(), &chunks);
assert_eq!((out, n), (ANSWER.to_vec().replace_all_for_test(), 1));
}
#[test]
fn length_never_changes_and_lookalikes_survive() {
let input = b"127.0.0.20 127.0.0.2127.0.0.2 127.0.0. 127.0.0.3";
let (out, n) = run(&mut lab(), &[input]);
assert_eq!(out.len(), input.len());
assert_eq!(out, b"127.0.0.10 127.0.0.1127.0.0.1 127.0.0. 127.0.0.3");
assert_eq!(n, 3);
}
#[test]
fn holds_only_a_possible_prefix() {
let mut r = lab();
let (out, _) = r.push(b"abc127.0.");
assert_eq!(out, b"abc");
assert_eq!(r.held(), 6);
let (out, n) = r.push(b"x");
assert_eq!((out, n), (b"127.0.x".to_vec(), 0));
assert_eq!(r.held(), 0);
}
#[test]
fn no_rules_is_a_pass_through() {
let mut r = Rewriter::new(Vec::new());
assert_eq!(r.push(b"127.0.0.2"), (b"127.0.0.2".to_vec(), 0));
}
trait ReplaceAll {
fn replace_all_for_test(self) -> Vec<u8>;
}
impl ReplaceAll for Vec<u8> {
fn replace_all_for_test(self) -> Vec<u8> {
String::from_utf8(self).unwrap().replace("127.0.0.2", "127.0.0.1").into_bytes()
}
}
}
-133
View File
@@ -1,133 +0,0 @@
//! Plain TCP relaying (HTTP, RTSP, and HTTPS in pass-through mode).
use std::io::{self, Read, Write};
use std::net::{Shutdown, TcpListener, TcpStream};
use std::sync::Arc;
use std::thread;
use std::time::Duration;
use crate::config::{Config, PortSpec, Rewrite};
use crate::record::{Direction, Kind, Protocol};
use crate::recorder::Recorder;
use crate::rewrite::Rewriter;
/// How long the host-to-client side waits for more bytes before releasing bytes held by the rewriter.
pub const HOLD_TIMEOUT: Duration = Duration::from_millis(50);
/// Timeout for connecting to Sunshine.
pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
/// Whether a protocol's bytes are plaintext the rewriter may touch.
pub fn rewritable(protocol: Protocol) -> bool {
matches!(protocol, Protocol::Http | Protocol::Rtsp | Protocol::HttpsPlain)
}
/// Accepts connections on `spec`'s port forever.
///
/// # Errors
/// Binding fails.
pub fn serve(config: Arc<Config>, spec: PortSpec, rec: Arc<Recorder>) -> io::Result<()> {
let listener = TcpListener::bind(config.listen_addr(&spec))?;
for client in listener.incoming() {
let client = match client {
Ok(c) => c,
Err(e) => {
rec.note(spec.protocol, 0, &format!("accept failed: {e}"));
continue;
}
};
let (config, rec) = (Arc::clone(&config), Arc::clone(&rec));
thread::spawn(move || {
let conn = rec.new_connection();
if let Err(e) = relay(client, &config, spec, &rec, conn) {
rec.note(spec.protocol, conn, &format!("connection ended with error: {e}"));
}
rec.log(Kind::Close, spec.protocol, Direction::None, conn, &[]);
});
}
Ok(())
}
fn relay(client: TcpStream, config: &Config, spec: PortSpec, rec: &Recorder, conn: u32) -> io::Result<()> {
let upstream_addr = config.upstream_addr(&spec);
let peer = client.peer_addr()?;
rec.log(Kind::Open, spec.protocol, Direction::None, conn, format!("{peer} -> {upstream_addr}").as_bytes());
let upstream = TcpStream::connect_timeout(&upstream_addr, CONNECT_TIMEOUT)?;
let _ = client.set_nodelay(true);
let _ = upstream.set_nodelay(true);
let rules = if rewritable(spec.protocol) { config.rewrites.clone() } else { Vec::new() };
pump_pair(client, upstream, spec.protocol, rec, conn, rules)
}
/// Copies both directions until both sides are closed; rewrites host-to-client bytes with `rules`.
///
/// # Errors
/// Socket errors.
pub fn pump_pair(
client: TcpStream,
upstream: TcpStream,
protocol: Protocol,
rec: &Recorder,
conn: u32,
rules: Vec<Rewrite>,
) -> io::Result<()> {
let (mut c_read, mut u_write) = (client.try_clone()?, upstream.try_clone()?);
thread::scope(|s| {
s.spawn(|| {
let mut buf = vec![0u8; 64 * 1024];
loop {
match c_read.read(&mut buf) {
Ok(0) | Err(_) => break,
Ok(n) => {
rec.log(Kind::Data, protocol, Direction::ClientToHost, conn, &buf[..n]);
if u_write.write_all(&buf[..n]).is_err() {
break;
}
}
}
}
let _ = u_write.shutdown(Shutdown::Write);
});
host_to_client(upstream, client, protocol, rec, conn, rules)
})
}
fn host_to_client(
mut upstream: TcpStream,
mut client: TcpStream,
protocol: Protocol,
rec: &Recorder,
conn: u32,
rules: Vec<Rewrite>,
) -> io::Result<()> {
let mut rewriter = Rewriter::new(rules);
if !rewriter.is_empty() {
upstream.set_read_timeout(Some(HOLD_TIMEOUT))?;
}
let mut buf = vec![0u8; 64 * 1024];
let result = loop {
match upstream.read(&mut buf) {
Ok(0) => break Ok(()),
Ok(n) => {
rec.log(Kind::Data, protocol, Direction::HostToClient, conn, &buf[..n]);
let (out, count) = rewriter.push(&buf[..n]);
if count > 0 {
rec.note(protocol, conn, &format!("rewrote {count} occurrence(s) in the bytes above"));
}
if let Err(e) = client.write_all(&out) {
break Err(e);
}
}
Err(e) if matches!(e.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut) => {
let held = rewriter.flush();
if let Err(e) = client.write_all(&held) {
break Err(e);
}
}
Err(e) => break Err(e),
}
};
let rest = rewriter.flush();
let _ = client.write_all(&rest);
let _ = client.shutdown(Shutdown::Write);
result
}
-396
View File
@@ -1,396 +0,0 @@
//! TLS termination on the HTTPS port (LAB_CAPTURE.md section 4).
//!
//! Towards Moonlight the relay presents Sunshine's own lab certificate, the one Moonlight pinned while pairing, and
//! asks for (but accepts any) client certificate. Towards Sunshine it presents Moonlight's own lab client
//! certificate and accepts only Sunshine's lab certificate. Both sides see the certificates they expect; the relay
//! records the plaintext in between. All key material is lab-only and is never written to the record file.
use std::io::{self, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::path::Path;
use std::sync::Arc;
use std::thread;
use std::time::{Duration, Instant};
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
use rustls::crypto::{CryptoProvider, WebPkiSupportedAlgorithms, verify_tls12_signature, verify_tls13_signature};
use rustls::pki_types::pem::PemObject;
use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime};
use rustls::server::danger::{ClientCertVerified, ClientCertVerifier};
use rustls::{ClientConfig, ClientConnection, Connection, DigitallySignedStruct, DistinguishedName, ServerConfig};
use rustls::{ServerConnection, SignatureScheme};
use crate::config::{Config, PortSpec, TlsFiles};
use crate::record::{Direction, Kind, Protocol};
use crate::recorder::Recorder;
use crate::rewrite::Rewriter;
use crate::tcp::{self, CONNECT_TIMEOUT};
/// Read timeout while pumping plaintext between the two TLS sessions.
const POLL: Duration = Duration::from_millis(20);
/// Accepts connections on the HTTPS port forever.
///
/// # Errors
/// Binding fails.
pub fn serve(config: Arc<Config>, spec: PortSpec, rec: Arc<Recorder>) -> io::Result<()> {
let listener = TcpListener::bind(config.listen_addr(&spec))?;
for client in listener.incoming() {
let client = match client {
Ok(c) => c,
Err(e) => {
rec.note(Protocol::HttpsPlain, 0, &format!("accept failed: {e}"));
continue;
}
};
let (config, rec) = (Arc::clone(&config), Arc::clone(&rec));
thread::spawn(move || {
let conn = rec.new_connection();
if let Err(e) = relay(client, &config, spec, &rec, conn) {
rec.note(Protocol::HttpsPlain, conn, &format!("connection ended with error: {e}"));
}
rec.log(Kind::Close, Protocol::HttpsPlain, Direction::None, conn, &[]);
});
}
Ok(())
}
/// The lab TLS material, loaded per connection (Moonlight's key may appear only after pairing step 1).
struct Material {
host_certs: Vec<CertificateDer<'static>>,
host_key: PrivateKeyDer<'static>,
client_certs: Vec<CertificateDer<'static>>,
client_key: PrivateKeyDer<'static>,
}
fn load(files: &TlsFiles) -> io::Result<Material> {
fn certs(path: &Path) -> io::Result<Vec<CertificateDer<'static>>> {
let certs = CertificateDer::pem_file_iter(path)
.map_err(|e| io::Error::other(format!("{}: {e:?}", path.display())))?
.collect::<Result<Vec<_>, _>>()
.map_err(|e| io::Error::other(format!("{}: {e:?}", path.display())))?;
if certs.is_empty() {
return Err(io::Error::other(format!("{}: no certificate", path.display())));
}
Ok(certs)
}
fn key(path: &Path) -> io::Result<PrivateKeyDer<'static>> {
// The error text names the file only; it never echoes key bytes.
PrivateKeyDer::from_pem_file(path).map_err(|_| io::Error::other(format!("{}: no usable key", path.display())))
}
Ok(Material {
host_certs: certs(&files.host_cert)?,
host_key: key(&files.host_key)?,
client_certs: certs(&files.client_cert)?,
client_key: key(&files.client_key)?,
})
}
/// Waits up to `wait` for all four files to load.
fn load_waiting(files: &TlsFiles, wait: Duration) -> io::Result<Material> {
let deadline = Instant::now() + wait;
loop {
match load(files) {
Ok(m) => return Ok(m),
Err(e) if Instant::now() >= deadline => return Err(e),
Err(_) => thread::sleep(Duration::from_millis(200)),
}
}
}
fn sha256_hex(bytes: &[u8]) -> String {
ring::digest::digest(&ring::digest::SHA256, bytes).as_ref().iter().map(|b| format!("{b:02x}")).collect()
}
fn relay(client: TcpStream, config: &Config, spec: PortSpec, rec: &Recorder, conn: u32) -> io::Result<()> {
let upstream_addr = config.upstream_addr(&spec);
let peer = client.peer_addr()?;
rec.log(
Kind::Open,
Protocol::HttpsPlain,
Direction::None,
conn,
format!("{peer} -> {upstream_addr} (TLS terminated)").as_bytes(),
);
let Some(files) = &config.tls else {
return Err(io::Error::other("TLS files not configured"));
};
let material = match load_waiting(files, config.wait_for_keys) {
Ok(m) => m,
Err(e) => {
// No keys: carry the raw TLS bytes, so the session still works and is still recorded.
rec.note(Protocol::HttpsTls, conn, &format!("lab keys not available ({e}); passing TLS through"));
let upstream = TcpStream::connect_timeout(&upstream_addr, CONNECT_TIMEOUT)?;
return tcp::pump_pair(client, upstream, Protocol::HttpsTls, rec, conn, Vec::new());
}
};
let provider = Arc::new(rustls::crypto::ring::default_provider());
let algs = provider.signature_verification_algorithms;
let server_config = ServerConfig::builder_with_provider(Arc::clone(&provider))
.with_safe_default_protocol_versions()
.map_err(io::Error::other)?
.with_client_cert_verifier(Arc::new(AnyClientCert { algs }))
.with_single_cert(material.host_certs.clone(), material.host_key)
.map_err(io::Error::other)?;
let pinned = material.host_certs[0].as_ref().to_vec();
let client_config = client_config(&provider, pinned, material.client_certs.clone(), material.client_key)?;
// Moonlight side first: it has already sent its ClientHello.
let mut moonlight = client;
let mut down = Connection::Server(ServerConnection::new(Arc::new(server_config)).map_err(io::Error::other)?);
while down.is_handshaking() {
down.complete_io(&mut moonlight)?;
}
let presented = down.peer_certificates().and_then(|c| c.first()).map(|c| sha256_hex(c.as_ref()));
let expected = sha256_hex(material.client_certs[0].as_ref());
rec.note(
Protocol::HttpsPlain,
conn,
&format!(
"client side: {:?}, {:?}, client certificate sha256 {} ({})",
down.protocol_version(),
down.negotiated_cipher_suite().map(|s| s.suite()),
presented.as_deref().unwrap_or("none"),
if presented.as_deref() == Some(expected.as_str()) {
"matches the lab client certificate"
} else {
"differs from the lab client certificate"
},
),
);
let mut sunshine = TcpStream::connect_timeout(&upstream_addr, CONNECT_TIMEOUT)?;
let name = ServerName::from(upstream_addr.ip());
let mut up = Connection::Client(ClientConnection::new(Arc::new(client_config), name).map_err(io::Error::other)?);
while up.is_handshaking() {
up.complete_io(&mut sunshine)?;
}
rec.note(
Protocol::HttpsPlain,
conn,
&format!("host side: {:?}, {:?}", up.protocol_version(), up.negotiated_cipher_suite().map(|s| s.suite())),
);
for s in [&moonlight, &sunshine] {
s.set_read_timeout(Some(POLL))?;
let _ = s.set_nodelay(true);
}
pump(&mut down, &mut moonlight, &mut up, &mut sunshine, rec, conn, Rewriter::new(config.rewrites.clone()))
}
fn client_config(
provider: &Arc<CryptoProvider>,
pinned: Vec<u8>,
certs: Vec<CertificateDer<'static>>,
key: PrivateKeyDer<'static>,
) -> io::Result<ClientConfig> {
let algs = provider.signature_verification_algorithms;
ClientConfig::builder_with_provider(Arc::clone(provider))
.with_safe_default_protocol_versions()
.map_err(io::Error::other)?
.dangerous()
.with_custom_certificate_verifier(Arc::new(PinnedHost { pinned, algs }))
.with_client_auth_cert(certs, key)
.map_err(io::Error::other)
}
/// Moves plaintext both ways until both sides are done.
fn pump(
down: &mut Connection,
moonlight: &mut TcpStream,
up: &mut Connection,
sunshine: &mut TcpStream,
rec: &Recorder,
conn: u32,
mut rewriter: Rewriter,
) -> io::Result<()> {
let (mut down_open, mut up_open) = (true, true);
while down_open || up_open {
if down_open {
let (data, eof) = pull(down, moonlight)?;
if !data.is_empty() {
rec.log(Kind::Data, Protocol::HttpsPlain, Direction::ClientToHost, conn, &data);
if up_open {
push(up, sunshine, &data)?;
}
}
if eof {
down_open = false;
if up_open {
up.send_close_notify();
flush(up, sunshine)?;
}
}
}
if up_open {
let (data, eof) = pull(up, sunshine)?;
if data.is_empty() {
let held = rewriter.flush();
if !held.is_empty() && down_open {
push(down, moonlight, &held)?;
}
} else {
rec.log(Kind::Data, Protocol::HttpsPlain, Direction::HostToClient, conn, &data);
let (out, count) = rewriter.push(&data);
if count > 0 {
rec.note(Protocol::HttpsPlain, conn, &format!("rewrote {count} occurrence(s) in the bytes above"));
}
if down_open {
push(down, moonlight, &out)?;
}
}
if eof {
up_open = false;
if down_open {
let held = rewriter.flush();
push(down, moonlight, &held)?;
down.send_close_notify();
flush(down, moonlight)?;
}
}
}
}
Ok(())
}
/// Reads what TLS bytes are there (or waits [`POLL`]) and returns the new plaintext and whether the peer is done.
fn pull(conn: &mut Connection, sock: &mut TcpStream) -> io::Result<(Vec<u8>, bool)> {
let mut eof = false;
match conn.read_tls(sock) {
Ok(0) => eof = true,
Ok(_) => {
conn.process_new_packets().map_err(io::Error::other)?;
}
Err(e) if matches!(e.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut) => {}
Err(e) => return Err(e),
}
let mut data = Vec::new();
let mut buf = [0u8; 16 * 1024];
loop {
match conn.reader().read(&mut buf) {
Ok(0) => {
eof = true;
break;
}
Ok(n) => data.extend_from_slice(&buf[..n]),
Err(e) if e.kind() == io::ErrorKind::WouldBlock => break,
Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => {
eof = true;
break;
}
Err(e) => return Err(e),
}
}
flush(conn, sock)?;
Ok((data, eof))
}
fn push(conn: &mut Connection, sock: &mut TcpStream, data: &[u8]) -> io::Result<()> {
conn.writer().write_all(data)?;
flush(conn, sock)
}
fn flush(conn: &mut Connection, sock: &mut TcpStream) -> io::Result<()> {
while conn.wants_write() {
conn.write_tls(sock)?;
}
Ok(())
}
/// Accepts any client certificate (it is recorded by fingerprint, and Sunshine checks the real one).
#[derive(Debug)]
struct AnyClientCert {
algs: WebPkiSupportedAlgorithms,
}
impl ClientCertVerifier for AnyClientCert {
fn offer_client_auth(&self) -> bool {
true
}
fn client_auth_mandatory(&self) -> bool {
false
}
fn root_hint_subjects(&self) -> &[DistinguishedName] {
&[]
}
fn verify_client_cert(
&self,
_end_entity: &CertificateDer<'_>,
_intermediates: &[CertificateDer<'_>],
_now: UnixTime,
) -> Result<ClientCertVerified, rustls::Error> {
Ok(ClientCertVerified::assertion())
}
fn verify_tls12_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
verify_tls12_signature(message, cert, dss, &self.algs)
}
fn verify_tls13_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
verify_tls13_signature(message, cert, dss, &self.algs)
}
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
self.algs.supported_schemes()
}
}
/// Accepts exactly Sunshine's lab certificate, byte for byte.
#[derive(Debug)]
struct PinnedHost {
pinned: Vec<u8>,
algs: WebPkiSupportedAlgorithms,
}
impl ServerCertVerifier for PinnedHost {
fn verify_server_cert(
&self,
end_entity: &CertificateDer<'_>,
_intermediates: &[CertificateDer<'_>],
_server_name: &ServerName<'_>,
_ocsp_response: &[u8],
_now: UnixTime,
) -> Result<ServerCertVerified, rustls::Error> {
if end_entity.as_ref() == self.pinned.as_slice() {
Ok(ServerCertVerified::assertion())
} else {
Err(rustls::Error::General("host certificate is not the pinned lab certificate".into()))
}
}
fn verify_tls12_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
verify_tls12_signature(message, cert, dss, &self.algs)
}
fn verify_tls13_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
verify_tls13_signature(message, cert, dss, &self.algs)
}
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
self.algs.supported_schemes()
}
}
-107
View File
@@ -1,107 +0,0 @@
//! UDP relaying (video, control, audio, mic).
//!
//! Each client address gets its own upstream socket on the listen address, so Sunshine sends the stream to the
//! relay (the address its PING or ENet connect came from) and the relay hands it to Moonlight.
use std::collections::HashMap;
use std::io;
use std::net::{SocketAddr, UdpSocket};
use std::sync::{Arc, Mutex};
use std::thread;
use crate::config::{Config, PortSpec};
use crate::record::{Direction, Kind};
use crate::recorder::Recorder;
/// Most client flows per port (one Moonlight uses one).
pub const MAX_FLOWS: usize = 16;
/// Largest datagram.
pub const MAX_DATAGRAM: usize = 64 * 1024;
/// Windows reports an ICMP "port unreachable" from an earlier send as a reset on the next receive; that is not
/// fatal for UDP.
fn transient(e: &io::Error) -> bool {
matches!(e.kind(), io::ErrorKind::ConnectionReset | io::ErrorKind::ConnectionRefused | io::ErrorKind::Interrupted)
}
/// Relays one UDP port forever.
///
/// # Errors
/// Binding fails.
pub fn serve(config: Arc<Config>, spec: PortSpec, rec: Arc<Recorder>) -> io::Result<()> {
let listen = Arc::new(UdpSocket::bind(config.listen_addr(&spec))?);
let upstream_addr = config.upstream_addr(&spec);
let flows: Mutex<HashMap<SocketAddr, (Arc<UdpSocket>, u32)>> = Mutex::new(HashMap::new());
let mut buf = vec![0u8; MAX_DATAGRAM];
loop {
let (n, from) = match listen.recv_from(&mut buf) {
Ok(v) => v,
Err(e) if transient(&e) => continue,
Err(e) => {
rec.note(spec.protocol, 0, &format!("receive failed: {e}"));
continue;
}
};
let flow = {
let Ok(mut map) = flows.lock() else { return Err(io::Error::other("flow table poisoned")) };
if let Some(f) = map.get(&from) {
Some(f.clone())
} else if map.len() >= MAX_FLOWS {
rec.note(spec.protocol, 0, &format!("dropping datagram from {from}: flow table full"));
None
} else {
let up = Arc::new(UdpSocket::bind(SocketAddr::new(config.listen, 0))?);
up.connect(upstream_addr)?;
let conn = rec.new_connection();
rec.log(
Kind::Open,
spec.protocol,
Direction::None,
conn,
format!("{from} -> {upstream_addr}").as_bytes(),
);
spawn_return_path(Arc::clone(&up), Arc::clone(&listen), from, spec, Arc::clone(&rec), conn);
map.insert(from, (Arc::clone(&up), conn));
Some((up, conn))
}
};
let Some((up, conn)) = flow else { continue };
rec.log(Kind::Data, spec.protocol, Direction::ClientToHost, conn, &buf[..n]);
if let Err(e) = up.send(&buf[..n])
&& !transient(&e)
{
rec.note(spec.protocol, conn, &format!("send to host failed: {e}"));
}
}
}
fn spawn_return_path(
up: Arc<UdpSocket>,
listen: Arc<UdpSocket>,
client: SocketAddr,
spec: PortSpec,
rec: Arc<Recorder>,
conn: u32,
) {
thread::spawn(move || {
let mut buf = vec![0u8; MAX_DATAGRAM];
loop {
match up.recv(&mut buf) {
Ok(n) => {
rec.log(Kind::Data, spec.protocol, Direction::HostToClient, conn, &buf[..n]);
if let Err(e) = listen.send_to(&buf[..n], client)
&& !transient(&e)
{
rec.note(spec.protocol, conn, &format!("send to client failed: {e}"));
}
}
Err(e) if transient(&e) => {}
Err(e) => {
rec.note(spec.protocol, conn, &format!("receive from host failed: {e}"));
break;
}
}
}
rec.log(Kind::Close, spec.protocol, Direction::None, conn, &[]);
});
}
+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()