[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).
This commit is contained in:
@@ -21,3 +21,9 @@ rsa = "0.10" # client key, PKCS#1 v1.5 SHA-256 sign/verify (crypto-bigin
|
||||
x509-cert = { version = "0.3", features = ["builder", "pem"] } # client certificate, host certificate parsing
|
||||
rand_core = "0.10" # adapter from our RandomSource to the RustCrypto RNG traits
|
||||
zeroize = "1.8" # wipe keys on drop
|
||||
|
||||
# Tests only. proptest without fork/timeout (no subprocesses, no threads); peak_alloc (MIT) is a counting global
|
||||
# allocator, so tests can check that parsers never allocate past their caps without any unsafe code of ours.
|
||||
[dev-dependencies]
|
||||
proptest = { version = "1.12", default-features = false, features = ["std"] }
|
||||
peak_alloc = "0.3"
|
||||
|
||||
@@ -0,0 +1,717 @@
|
||||
//! Helpers shared by the integration tests: deterministic randomness, fixture loading, an independent GF(2^8)
|
||||
//! reference, and builders for video and audio streams. Test code: panics are the way a test fails.
|
||||
|
||||
#![allow(dead_code, unreachable_pub, clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing)]
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use domistream::RandomSource;
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ assertions
|
||||
|
||||
/// Asserts that `$e` is `Err` matching `$p` (an `Error` pattern), printing the actual value otherwise.
|
||||
#[macro_export]
|
||||
macro_rules! assert_err {
|
||||
($e:expr, $p:pat) => {
|
||||
match $e {
|
||||
Err($p) => {}
|
||||
other => panic!("expected Err({}), got {:?}", stringify!($p), other),
|
||||
}
|
||||
};
|
||||
($e:expr, $p:pat, $($ctx:tt)+) => {
|
||||
match $e {
|
||||
Err($p) => {}
|
||||
other => panic!("expected Err({}), got {:?}: {}", stringify!($p), other, format!($($ctx)+)),
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// Asserts `Err(TooLarge { max, actual, .. })` with the given numbers.
|
||||
#[macro_export]
|
||||
macro_rules! assert_too_large {
|
||||
($e:expr, $max:expr, $actual:expr) => {
|
||||
match $e {
|
||||
Err(domistream::Error::TooLarge { max, actual, .. }) => {
|
||||
assert_eq!(max, $max, "TooLarge.max");
|
||||
assert_eq!(actual, $actual, "TooLarge.actual");
|
||||
}
|
||||
other => panic!("expected Err(TooLarge {{ max: {}, actual: {} }}), got {:?}", $max, $actual, other),
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ randomness
|
||||
|
||||
/// A seeded, deterministic random source (splitmix64). Never for production.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SeqRng(u64);
|
||||
|
||||
impl SeqRng {
|
||||
pub fn new(seed: u64) -> Self {
|
||||
Self(seed)
|
||||
}
|
||||
|
||||
pub fn next_u64(&mut self) -> u64 {
|
||||
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
|
||||
let mut z = self.0;
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
||||
z ^ (z >> 31)
|
||||
}
|
||||
|
||||
/// Uniform in `0..n` (n > 0); bias is irrelevant for test data.
|
||||
pub fn below(&mut self, n: usize) -> usize {
|
||||
(self.next_u64() % n as u64) as usize
|
||||
}
|
||||
|
||||
pub fn bytes(&mut self, n: usize) -> Vec<u8> {
|
||||
let mut v = vec![0; n];
|
||||
self.fill(&mut v);
|
||||
v
|
||||
}
|
||||
|
||||
/// `count` distinct indices from `0..n`, sorted.
|
||||
pub fn subset(&mut self, n: usize, count: usize) -> Vec<usize> {
|
||||
let mut all: Vec<usize> = (0..n).collect();
|
||||
for i in 0..count.min(n) {
|
||||
let j = i + self.below(n - i);
|
||||
all.swap(i, j);
|
||||
}
|
||||
let mut chosen = all[..count.min(n)].to_vec();
|
||||
chosen.sort_unstable();
|
||||
chosen
|
||||
}
|
||||
|
||||
pub fn shuffle<T>(&mut self, items: &mut [T]) {
|
||||
for i in (1..items.len()).rev() {
|
||||
let j = self.below(i + 1);
|
||||
items.swap(i, j);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RandomSource for SeqRng {
|
||||
fn fill(&mut self, dest: &mut [u8]) {
|
||||
for chunk in dest.chunks_mut(8) {
|
||||
let word = self.next_u64().to_le_bytes();
|
||||
chunk.copy_from_slice(&word[..chunk.len()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Hands out a fixed byte stream (a recorded transcript's randomness) and fails the test when the code under
|
||||
/// test draws more than was recorded.
|
||||
#[derive(Debug)]
|
||||
pub struct ScriptedRng {
|
||||
bytes: Vec<u8>,
|
||||
pos: usize,
|
||||
}
|
||||
|
||||
impl ScriptedRng {
|
||||
pub fn new(bytes: Vec<u8>) -> Self {
|
||||
Self { bytes, pos: 0 }
|
||||
}
|
||||
|
||||
pub fn drawn(&self) -> usize {
|
||||
self.pos
|
||||
}
|
||||
}
|
||||
|
||||
impl RandomSource for ScriptedRng {
|
||||
fn fill(&mut self, dest: &mut [u8]) {
|
||||
let end = self.pos + dest.len();
|
||||
assert!(
|
||||
end <= self.bytes.len(),
|
||||
"the code drew {} random bytes but the recorded transcript holds only {} \
|
||||
(fixture assumption: salt, then C, then secret_c, 16 bytes each)",
|
||||
end,
|
||||
self.bytes.len()
|
||||
);
|
||||
dest.copy_from_slice(&self.bytes[self.pos..end]);
|
||||
self.pos = end;
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ fixtures
|
||||
|
||||
pub fn hex(s: &str) -> Vec<u8> {
|
||||
let s: String = s.chars().filter(|c| !c.is_whitespace()).collect();
|
||||
if s == "-" {
|
||||
return Vec::new();
|
||||
}
|
||||
assert!(s.len() % 2 == 0, "odd hex length");
|
||||
(0..s.len()).step_by(2).map(|i| u8::from_str_radix(&s[i..i + 2], 16).expect("hex digit")).collect()
|
||||
}
|
||||
|
||||
pub fn to_hex(b: &[u8]) -> String {
|
||||
b.iter().map(|x| format!("{x:02x}")).collect()
|
||||
}
|
||||
|
||||
pub fn to_hex_upper(b: &[u8]) -> String {
|
||||
b.iter().map(|x| format!("{x:02X}")).collect()
|
||||
}
|
||||
|
||||
/// A `name = value` fixture file written by `tools/vectors/gen_vectors.py`.
|
||||
pub struct Vectors(HashMap<String, String>);
|
||||
|
||||
impl Vectors {
|
||||
pub fn parse(text: &str) -> Self {
|
||||
let mut map = HashMap::new();
|
||||
for line in text.lines() {
|
||||
let line = line.trim();
|
||||
if line.is_empty() || line.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
let (k, v) = line.split_once(" = ").expect("fixture line `name = value`");
|
||||
map.insert(k.to_string(), v.to_string());
|
||||
}
|
||||
Self(map)
|
||||
}
|
||||
|
||||
pub fn str(&self, name: &str) -> &str {
|
||||
self.0.get(name).unwrap_or_else(|| panic!("fixture value `{name}` missing"))
|
||||
}
|
||||
|
||||
pub fn bytes(&self, name: &str) -> Vec<u8> {
|
||||
hex(self.str(name))
|
||||
}
|
||||
|
||||
pub fn arr16(&self, name: &str) -> [u8; 16] {
|
||||
self.bytes(name).try_into().unwrap_or_else(|_| panic!("`{name}` is not 16 bytes"))
|
||||
}
|
||||
|
||||
pub fn u32_hex(&self, name: &str) -> u32 {
|
||||
u32::from_str_radix(self.str(name), 16).expect("hex u32")
|
||||
}
|
||||
}
|
||||
|
||||
pub fn pairing_vectors() -> Vectors {
|
||||
Vectors::parse(include_str!("../fixtures/pairing.txt"))
|
||||
}
|
||||
|
||||
pub fn control_vectors() -> Vectors {
|
||||
Vectors::parse(include_str!("../fixtures/control_gcm.txt"))
|
||||
}
|
||||
|
||||
pub fn video_vectors() -> Vectors {
|
||||
Vectors::parse(include_str!("../fixtures/video_gcm.txt"))
|
||||
}
|
||||
|
||||
pub fn audio_vectors() -> Vectors {
|
||||
Vectors::parse(include_str!("../fixtures/audio_cbc.txt"))
|
||||
}
|
||||
|
||||
pub const HOST_CERT_PEM: &str = include_str!("../fixtures/test-only-host-cert.pem");
|
||||
pub const CLIENT_CERT_PEM: &str = include_str!("../fixtures/test-only-client-cert.pem");
|
||||
pub const ROGUE_CERT_PEM: &str = include_str!("../fixtures/test-only-rogue-cert.pem");
|
||||
pub const EC_CERT_PEM: &str = include_str!("../fixtures/test-only-ec-cert.pem");
|
||||
pub const CLIENT_KEY_PEM: &str = include_str!("../fixtures/test-only-client-key.pem");
|
||||
|
||||
/// Base64 (RFC 4648, standard alphabet, padding allowed) to bytes; panics on anything else.
|
||||
pub fn base64_decode(s: &str) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
let mut acc = 0u32;
|
||||
let mut bits = 0;
|
||||
for c in s.bytes().filter(|c| !c.is_ascii_whitespace()) {
|
||||
let v = match c {
|
||||
b'A'..=b'Z' => c - b'A',
|
||||
b'a'..=b'z' => c - b'a' + 26,
|
||||
b'0'..=b'9' => c - b'0' + 52,
|
||||
b'+' => 62,
|
||||
b'/' => 63,
|
||||
b'=' => break,
|
||||
_ => panic!("not base64: {c:#x}"),
|
||||
};
|
||||
acc = (acc << 6) | u32::from(v);
|
||||
bits += 6;
|
||||
if bits >= 8 {
|
||||
bits -= 8;
|
||||
out.push((acc >> bits) as u8);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The DER inside every `-----BEGIN <label>-----` block of a PEM text.
|
||||
pub fn pem_blocks(pem: &str, label: &str) -> Vec<Vec<u8>> {
|
||||
let begin = format!("-----BEGIN {label}-----");
|
||||
let end = format!("-----END {label}-----");
|
||||
let mut out = Vec::new();
|
||||
let mut rest = pem;
|
||||
while let Some(start) = rest.find(&begin) {
|
||||
let after = &rest[start + begin.len()..];
|
||||
let stop = after.find(&end).expect("PEM end line");
|
||||
out.push(base64_decode(&after[..stop]));
|
||||
rest = &after[stop + end.len()..];
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ HTTP helpers
|
||||
|
||||
/// Splits a `path?query` into the path and its decoded parameters, in order.
|
||||
pub fn parse_query(path_and_query: &str) -> (String, Vec<(String, String)>) {
|
||||
let (path, query) = path_and_query.split_once('?').unwrap_or((path_and_query, ""));
|
||||
let params = query
|
||||
.split('&')
|
||||
.filter(|p| !p.is_empty())
|
||||
.map(|p| {
|
||||
let (k, v) = p.split_once('=').unwrap_or((p, ""));
|
||||
(percent_decode(k), percent_decode(v))
|
||||
})
|
||||
.collect();
|
||||
(path.to_string(), params)
|
||||
}
|
||||
|
||||
pub fn percent_decode(s: &str) -> String {
|
||||
let b = s.as_bytes();
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < b.len() {
|
||||
if b[i] == b'%' && i + 2 < b.len() {
|
||||
let h = std::str::from_utf8(&b[i + 1..i + 3]).expect("utf8");
|
||||
out.push(u8::from_str_radix(h, 16).expect("percent escape"));
|
||||
i += 3;
|
||||
} else if b[i] == b'+' {
|
||||
out.push(b' ');
|
||||
i += 1;
|
||||
} else {
|
||||
out.push(b[i]);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
String::from_utf8(out).expect("decoded query is UTF-8")
|
||||
}
|
||||
|
||||
/// The single value of `name`; fails when it is missing or repeated (parameter injection).
|
||||
pub fn param<'a>(params: &'a [(String, String)], name: &str) -> &'a str {
|
||||
let found: Vec<&(String, String)> = params.iter().filter(|(k, _)| k == name).collect();
|
||||
assert_eq!(found.len(), 1, "query parameter `{name}` must appear exactly once in {params:?}");
|
||||
&found[0].1
|
||||
}
|
||||
|
||||
/// `<root status_code="200">` + elements + `</root>`.
|
||||
pub fn xml_root(status: u32, inner: &str) -> Vec<u8> {
|
||||
format!("<root status_code=\"{status}\">{inner}</root>").into_bytes()
|
||||
}
|
||||
|
||||
/// A child element sequence of exactly `len` bytes (`len >= 7`): `<x>aaa…</x>` pieces of at most 207 bytes, so no
|
||||
/// single text is long and the element count stays small.
|
||||
pub fn xml_filler(len: usize) -> String {
|
||||
assert!(len >= 7, "filler needs at least 7 bytes");
|
||||
let mut out = String::with_capacity(len);
|
||||
let mut remaining = len;
|
||||
while remaining > 0 {
|
||||
let piece = if remaining <= 207 {
|
||||
remaining
|
||||
} else if remaining - 207 >= 7 {
|
||||
207
|
||||
} else {
|
||||
remaining - 7
|
||||
};
|
||||
out.push_str("<x>");
|
||||
out.extend(std::iter::repeat_n('a', piece - 7));
|
||||
out.push_str("</x>");
|
||||
remaining -= piece;
|
||||
}
|
||||
assert_eq!(out.len(), len);
|
||||
out
|
||||
}
|
||||
|
||||
/// A document `<root status_code="200">{inner}{filler}</root>` of exactly `total` bytes.
|
||||
pub fn xml_padded_to(inner: &str, total: usize) -> Vec<u8> {
|
||||
let bare = xml_root(200, inner).len();
|
||||
assert!(total >= bare + 7, "target {total} too small for {bare} + filler");
|
||||
let doc = xml_root(200, &format!("{inner}{}", xml_filler(total - bare)));
|
||||
assert_eq!(doc.len(), total);
|
||||
doc
|
||||
}
|
||||
|
||||
/// All subsets of `0..n` with exactly `size` elements, in lexicographic order.
|
||||
pub fn subsets_of(n: usize, size: usize) -> Vec<Vec<usize>> {
|
||||
fn go(start: usize, n: usize, size: usize, cur: &mut Vec<usize>, out: &mut Vec<Vec<usize>>) {
|
||||
if cur.len() == size {
|
||||
out.push(cur.clone());
|
||||
return;
|
||||
}
|
||||
for i in start..n {
|
||||
cur.push(i);
|
||||
go(i + 1, n, size, cur, out);
|
||||
cur.pop();
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
go(0, n, size, &mut Vec::new(), &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ GF(2^8)
|
||||
|
||||
/// An independent GF(2^8) reference with polynomial 0x11D (`docs/PROTOCOL.md` 5.3), from the field definition.
|
||||
pub mod gf {
|
||||
pub fn mul(mut a: u8, mut b: u8) -> u8 {
|
||||
let mut p = 0u8;
|
||||
while b != 0 {
|
||||
if b & 1 != 0 {
|
||||
p ^= a;
|
||||
}
|
||||
let carry = a & 0x80 != 0;
|
||||
a <<= 1;
|
||||
if carry {
|
||||
a ^= 0x1D;
|
||||
}
|
||||
b >>= 1;
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
pub fn inv(a: u8) -> u8 {
|
||||
assert!(a != 0, "no inverse of 0");
|
||||
(1..=255u8).find(|&b| mul(a, b) == 1).expect("field inverse")
|
||||
}
|
||||
|
||||
/// A `rows × cols` Cauchy matrix `1 / (x_i + y_j)` with `x_i = i`, `y_j = rows + j`: every square submatrix is
|
||||
/// invertible, so `[I; C]` is MDS.
|
||||
pub fn cauchy(rows: usize, cols: usize) -> Vec<u8> {
|
||||
assert!(rows + cols <= 256);
|
||||
let mut m = Vec::with_capacity(rows * cols);
|
||||
for i in 0..rows {
|
||||
for j in 0..cols {
|
||||
m.push(inv((i as u8) ^ ((rows + j) as u8)));
|
||||
}
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
/// Parity shards for `data` with a row-major `parity × data` matrix.
|
||||
pub fn encode(matrix: &[u8], data: &[Vec<u8>], parity: usize) -> Vec<Vec<u8>> {
|
||||
let k = data.len();
|
||||
let len = data[0].len();
|
||||
(0..parity)
|
||||
.map(|r| {
|
||||
(0..len)
|
||||
.map(|x| (0..k).fold(0u8, |acc, c| acc ^ mul(matrix[r * k + c], data[c][x])))
|
||||
.collect()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ video
|
||||
|
||||
/// One video packet as the test host built it.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct VPkt {
|
||||
pub bytes: Vec<u8>,
|
||||
pub frame_index: u32,
|
||||
pub block: u8,
|
||||
pub shard_index: u16,
|
||||
pub data_shards: u16,
|
||||
pub parity_shards: u16,
|
||||
pub is_parity: bool,
|
||||
}
|
||||
|
||||
/// What a frame should come out as.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct VExpect {
|
||||
pub frame_index: u32,
|
||||
pub header: [u8; 8],
|
||||
pub bitstream: Vec<u8>,
|
||||
pub rtp_timestamp: u32,
|
||||
}
|
||||
|
||||
/// A test host that packetizes frames as `docs/PROTOCOL.md` 5.2-5.3 describe (Moonshine-style frame header).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct VideoHost {
|
||||
pub packet_size: u16,
|
||||
pub next_sequence: u16,
|
||||
pub timestamp: u32,
|
||||
/// When set, parity is computed over data shards whose bytes 0-31 are replaced by this pattern (a host may
|
||||
/// compute parity before writing headers), so a recovered shard's header is guaranteed garbage.
|
||||
pub scramble_parity_headers: bool,
|
||||
}
|
||||
|
||||
impl VideoHost {
|
||||
pub fn new(packet_size: u16) -> Self {
|
||||
Self { packet_size, next_sequence: 0, timestamp: 90_000, scramble_parity_headers: false }
|
||||
}
|
||||
|
||||
pub fn payload_len(&self) -> usize {
|
||||
usize::from(self.packet_size) - 16
|
||||
}
|
||||
|
||||
/// An Annex-B bitstream of about `len` bytes that ends in a nonzero byte (so trimming the zero padding by
|
||||
/// either the frame header's length or the content gives the same answer: UNKNOWN U13).
|
||||
pub fn bitstream(rng: &mut SeqRng, len: usize) -> Vec<u8> {
|
||||
let mut b = vec![0, 0, 0, 1, 0x65];
|
||||
b.extend(rng.bytes(len.saturating_sub(6)));
|
||||
b.push(0x80 | rng.bytes(1)[0]);
|
||||
b
|
||||
}
|
||||
|
||||
/// Packetizes one frame into `blocks` FEC blocks at `fec_percentage`.
|
||||
pub fn frame(
|
||||
&mut self,
|
||||
frame_index: u32,
|
||||
bitstream: &[u8],
|
||||
fec_percentage: u8,
|
||||
blocks: usize,
|
||||
) -> (Vec<VPkt>, VExpect) {
|
||||
let payload_len = self.payload_len();
|
||||
let total_len = 8 + bitstream.len();
|
||||
let shards_total = total_len.div_ceil(payload_len);
|
||||
let last_payload_len = total_len - (shards_total - 1) * payload_len;
|
||||
let mut header = [0u8; 8];
|
||||
header[0] = 0x01;
|
||||
header[1..3].copy_from_slice(&7u16.to_le_bytes());
|
||||
header[3] = 2; // key frame
|
||||
header[4..8].copy_from_slice(&(last_payload_len as u32).to_le_bytes());
|
||||
let mut data = header.to_vec();
|
||||
data.extend_from_slice(bitstream);
|
||||
data.resize(shards_total * payload_len, 0);
|
||||
|
||||
let blocks = blocks.clamp(1, 4).min(shards_total);
|
||||
let base = shards_total / blocks;
|
||||
let extra = shards_total % blocks;
|
||||
let last_block = (blocks - 1) as u8;
|
||||
let mut packets = Vec::new();
|
||||
let mut shard_offset = 0;
|
||||
for b in 0..blocks {
|
||||
let k = base + usize::from(b < extra);
|
||||
let m = (k * usize::from(fec_percentage)).div_ceil(100);
|
||||
assert!(k + m <= 255, "test frame needs k + m <= 255");
|
||||
let mut shards: Vec<Vec<u8>> = Vec::with_capacity(k + m);
|
||||
for i in 0..k {
|
||||
let global = shard_offset + i;
|
||||
let mut flags = 0x01;
|
||||
if global == 0 {
|
||||
flags |= 0x04;
|
||||
}
|
||||
if global == shards_total - 1 {
|
||||
flags |= 0x02;
|
||||
}
|
||||
let mut p = self.header(frame_index, flags, b as u8, last_block, i, k, fec_percentage);
|
||||
p.extend_from_slice(&data[global * payload_len..(global + 1) * payload_len]);
|
||||
shards.push(p);
|
||||
}
|
||||
if m > 0 {
|
||||
let code = domistream::fec::ReedSolomon::new(k, m)
|
||||
.expect("ReedSolomon::new for the test host (Phase A: Unimplemented)");
|
||||
let shard_len = shards[0].len();
|
||||
let mut work: Vec<Vec<u8>> = shards.clone();
|
||||
if self.scramble_parity_headers {
|
||||
for (i, s) in work.iter_mut().enumerate() {
|
||||
for (x, byte) in s[..32].iter_mut().enumerate() {
|
||||
*byte = (0xA5 ^ (i as u8).wrapping_mul(31) ^ (x as u8).wrapping_mul(7)) | 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
work.extend((0..m).map(|_| vec![0u8; shard_len]));
|
||||
code.encode(&mut work).expect("ReedSolomon::encode for the test host");
|
||||
for j in 0..m {
|
||||
let mut p = self.header(frame_index, 0, b as u8, last_block, k + j, k, fec_percentage);
|
||||
p.extend_from_slice(&work[k + j][32..]);
|
||||
shards.push(p);
|
||||
}
|
||||
}
|
||||
for (i, bytes) in shards.into_iter().enumerate() {
|
||||
packets.push(VPkt {
|
||||
bytes,
|
||||
frame_index,
|
||||
block: b as u8,
|
||||
shard_index: i as u16,
|
||||
data_shards: k as u16,
|
||||
parity_shards: m as u16,
|
||||
is_parity: i >= k,
|
||||
});
|
||||
}
|
||||
shard_offset += k;
|
||||
}
|
||||
let expect = VExpect { frame_index, header, bitstream: bitstream.to_vec(), rtp_timestamp: self.timestamp };
|
||||
self.timestamp = self.timestamp.wrapping_add(1500);
|
||||
(packets, expect)
|
||||
}
|
||||
|
||||
/// RTP header + 4 reserved + NV header for the next sequence number (all packets of a frame share the
|
||||
/// timestamp).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn header(
|
||||
&mut self,
|
||||
frame_index: u32,
|
||||
flags: u8,
|
||||
block: u8,
|
||||
last_block: u8,
|
||||
shard_index: usize,
|
||||
data_shards: usize,
|
||||
fec_percentage: u8,
|
||||
) -> Vec<u8> {
|
||||
let seq = self.next_sequence;
|
||||
self.next_sequence = self.next_sequence.wrapping_add(1);
|
||||
let mut p = Vec::with_capacity(usize::from(self.packet_size) + 16);
|
||||
p.extend_from_slice(&[0x90, 0x00]);
|
||||
p.extend_from_slice(&seq.to_be_bytes());
|
||||
p.extend_from_slice(&self.timestamp.to_be_bytes());
|
||||
p.extend_from_slice(&0u32.to_be_bytes());
|
||||
p.extend_from_slice(&[0; 4]);
|
||||
p.extend_from_slice(&(u32::from(seq) << 8).to_le_bytes());
|
||||
p.extend_from_slice(&frame_index.to_le_bytes());
|
||||
p.push(flags);
|
||||
p.push(0);
|
||||
p.push(0x10);
|
||||
p.push((block << 4) | (last_block << 6));
|
||||
let fec_info =
|
||||
(u32::from(fec_percentage) << 4) | ((shard_index as u32) << 12) | ((data_shards as u32) << 22);
|
||||
p.extend_from_slice(&fec_info.to_le_bytes());
|
||||
p
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds one NV video packet by hand from the field table (`docs/PROTOCOL.md` 5.2).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn video_packet_bytes(
|
||||
seq: u16,
|
||||
timestamp: u32,
|
||||
frame_index: u32,
|
||||
flags: u8,
|
||||
multi_fec_blocks: u8,
|
||||
fec_info: u32,
|
||||
payload: &[u8],
|
||||
) -> Vec<u8> {
|
||||
let mut p = vec![0x90, 0x00];
|
||||
p.extend_from_slice(&seq.to_be_bytes());
|
||||
p.extend_from_slice(×tamp.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")
|
||||
}
|
||||
@@ -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());
|
||||
@@ -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()
|
||||
Reference in New Issue
Block a user