use super::{Error, Result, put_be32};
use broadcast_core::error::BufferTooShort;
use broadcast_core::len::{need_in, need_out};
const S_FIXED: u8 = 0;
const V_FIXED: u8 = 1;
const PT_KEYING_MATERIAL: u8 = 2;
const SIGN_FIXED: u16 = 0x2029; const RESV1_FIXED: u8 = 0;
const RESV2_FIXED: u8 = 0;
const RESV3_FIXED: u16 = 0;
const FIXED_HEADER_LEN: usize = 16;
pub const ICV_LEN: usize = 8;
const KEY_BLOCK_LEN: usize = 4;
const KEY_COUNT_BOTH: usize = 2;
const KEKI_OFFSET: usize = 4;
const FLAGS_OFFSET: usize = 8;
const LENGTHS_OFFSET: usize = 12;
const S_SHIFT: u32 = 31;
const V_SHIFT: u32 = 28;
const V_MASK: u32 = 0b111;
const PT_SHIFT: u32 = 24;
const PT_MASK: u32 = 0b1111;
const SIGN_SHIFT: u32 = 8;
const SIGN_MASK: u32 = 0xFFFF;
const RESV1_SHIFT: u32 = 2;
const RESV1_MASK: u32 = 0b0011_1111;
const KK_MASK: u32 = 0b11;
const CIPHER_SHIFT: u32 = 24;
const AUTH_SHIFT: u32 = 16;
const SE_SHIFT: u32 = 8;
const RESV2_MASK: u32 = 0xFF;
const RESV3_SHIFT: u32 = 16;
const SLEN_SHIFT: u32 = 8;
const LEN_MASK: u32 = 0xFF;
const KK_FIELD_MASK: u8 = 0b11;
pub const KM_KK_NO_SEK: u8 = 0b00;
pub const KM_KK_EVEN: u8 = 0b01;
pub const KM_KK_ODD: u8 = 0b10;
pub const KM_KK_BOTH: u8 = 0b11;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum KmKeyFlag {
NoSek,
Even,
Odd,
Both,
}
impl KmKeyFlag {
pub fn from_bits(v: u8) -> Self {
match v & KK_FIELD_MASK {
KM_KK_EVEN => KmKeyFlag::Even,
KM_KK_ODD => KmKeyFlag::Odd,
KM_KK_BOTH => KmKeyFlag::Both,
_ => KmKeyFlag::NoSek,
}
}
pub fn to_bits(self) -> u8 {
match self {
KmKeyFlag::NoSek => KM_KK_NO_SEK,
KmKeyFlag::Even => KM_KK_EVEN,
KmKeyFlag::Odd => KM_KK_ODD,
KmKeyFlag::Both => KM_KK_BOTH,
}
}
pub fn key_count(self) -> u8 {
match self {
KmKeyFlag::NoSek => 0,
KmKeyFlag::Even | KmKeyFlag::Odd => 1,
KmKeyFlag::Both => 2,
}
}
pub fn name(&self) -> &'static str {
match self {
KmKeyFlag::NoSek => "no SEK",
KmKeyFlag::Even => "even key",
KmKeyFlag::Odd => "odd key",
KmKeyFlag::Both => "both keys",
}
}
}
broadcast_core::impl_spec_display!(KmKeyFlag);
pub const CIPHER_NONE: u8 = 0;
pub const CIPHER_AES_CTR: u8 = 2;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum Cipher {
None,
AesCtr,
Reserved(u8),
}
impl Cipher {
pub fn from_bits(v: u8) -> Self {
match v {
CIPHER_NONE => Cipher::None,
CIPHER_AES_CTR => Cipher::AesCtr,
other => Cipher::Reserved(other),
}
}
pub fn to_bits(self) -> u8 {
match self {
Cipher::None => CIPHER_NONE,
Cipher::AesCtr => CIPHER_AES_CTR,
Cipher::Reserved(v) => v,
}
}
pub fn name(&self) -> &'static str {
match self {
Cipher::None => "none / KEKI-indexed",
Cipher::AesCtr => "AES-CTR",
Cipher::Reserved(_) => "reserved",
}
}
}
broadcast_core::impl_spec_display!(Cipher, Reserved);
pub const KM_AUTH_NONE: u8 = 0;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum KmAuth {
None,
Reserved(u8),
}
impl KmAuth {
pub fn from_bits(v: u8) -> Self {
match v {
KM_AUTH_NONE => KmAuth::None,
other => KmAuth::Reserved(other),
}
}
pub fn to_bits(self) -> u8 {
match self {
KmAuth::None => KM_AUTH_NONE,
KmAuth::Reserved(v) => v,
}
}
pub fn name(&self) -> &'static str {
match self {
KmAuth::None => "none / KEKI-indexed",
KmAuth::Reserved(_) => "reserved",
}
}
}
broadcast_core::impl_spec_display!(KmAuth, Reserved);
pub const STREAM_ENCAP_UNSPECIFIED: u8 = 0;
pub const STREAM_ENCAP_MPEG_TS_UDP: u8 = 1;
pub const STREAM_ENCAP_MPEG_TS_SRT: u8 = 2;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum StreamEncapsulation {
Unspecified,
MpegTsUdp,
MpegTsSrt,
Reserved(u8),
}
impl StreamEncapsulation {
pub fn from_bits(v: u8) -> Self {
match v {
STREAM_ENCAP_UNSPECIFIED => StreamEncapsulation::Unspecified,
STREAM_ENCAP_MPEG_TS_UDP => StreamEncapsulation::MpegTsUdp,
STREAM_ENCAP_MPEG_TS_SRT => StreamEncapsulation::MpegTsSrt,
other => StreamEncapsulation::Reserved(other),
}
}
pub fn to_bits(self) -> u8 {
match self {
StreamEncapsulation::Unspecified => STREAM_ENCAP_UNSPECIFIED,
StreamEncapsulation::MpegTsUdp => STREAM_ENCAP_MPEG_TS_UDP,
StreamEncapsulation::MpegTsSrt => STREAM_ENCAP_MPEG_TS_SRT,
StreamEncapsulation::Reserved(v) => v,
}
}
pub fn name(&self) -> &'static str {
match self {
StreamEncapsulation::Unspecified => "unspecified / KEKI-indexed",
StreamEncapsulation::MpegTsUdp => "MPEG-TS/UDP",
StreamEncapsulation::MpegTsSrt => "MPEG-TS/SRT",
StreamEncapsulation::Reserved(_) => "reserved",
}
}
}
broadcast_core::impl_spec_display!(StreamEncapsulation, Reserved);
#[derive(Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct KeyMaterial<'a> {
pub kk: KmKeyFlag,
pub keki: u32,
pub cipher: Cipher,
pub auth: KmAuth,
pub se: StreamEncapsulation,
#[cfg_attr(feature = "serde", serde(skip))]
pub salt: &'a [u8],
#[cfg_attr(feature = "serde", serde(skip))]
pub icv: [u8; ICV_LEN],
#[cfg_attr(feature = "serde", serde(skip))]
pub x_sek: &'a [u8],
#[cfg_attr(feature = "serde", serde(skip))]
pub o_sek: Option<&'a [u8]>,
}
impl core::fmt::Debug for KeyMaterial<'_> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("KeyMaterial")
.field("kk", &self.kk)
.field("keki", &self.keki)
.field("cipher", &self.cipher)
.field("auth", &self.auth)
.field("se", &self.se)
.field(
"salt",
&format_args!("<redacted, {} bytes>", self.salt.len()),
)
.field("icv", &format_args!("<redacted, {} bytes>", self.icv.len()))
.field(
"x_sek",
&format_args!("<redacted, {} bytes>", self.x_sek.len()),
)
.field(
"o_sek",
&format_args!("<redacted, {} bytes>", self.o_sek.map_or(0, <[u8]>::len)),
)
.finish()
}
}
impl<'a> KeyMaterial<'a> {
pub fn parse(bytes: &'a [u8]) -> Result<Self> {
need_in(bytes, FIXED_HEADER_LEN, "key material fixed header")?;
let word0 = broadcast_core::wire::Reader::at(bytes, 0).u32("word0")?;
let s = (word0 >> S_SHIFT) as u8;
let v = ((word0 >> V_SHIFT) & V_MASK) as u8;
let pt = ((word0 >> PT_SHIFT) & PT_MASK) as u8;
let sign = ((word0 >> SIGN_SHIFT) & SIGN_MASK) as u16;
let resv1 = ((word0 >> RESV1_SHIFT) & RESV1_MASK) as u8;
let kk_bits = (word0 & KK_MASK) as u8;
if s != S_FIXED {
return Err(Error::InvalidKeyMaterial {
field: "S",
reason: "must be 0",
});
}
if v != V_FIXED {
return Err(Error::InvalidKeyMaterial {
field: "V",
reason: "must be 1",
});
}
if pt != PT_KEYING_MATERIAL {
return Err(Error::InvalidKeyMaterial {
field: "PT",
reason: "must be 2 (Keying Material Message)",
});
}
if sign != SIGN_FIXED {
return Err(Error::InvalidKeyMaterial {
field: "Sign",
reason: "must be 0x2029 ('HAI' PnP Vendor ID)",
});
}
if resv1 != RESV1_FIXED {
return Err(Error::InvalidKeyMaterial {
field: "Resv1",
reason: "must be 0",
});
}
let kk = KmKeyFlag::from_bits(kk_bits);
if kk == KmKeyFlag::NoSek {
return Err(Error::InvalidKeyMaterial {
field: "KK",
reason: "00b (no SEK provided) is an invalid Key Material message (§3.2.2)",
});
}
let keki = broadcast_core::wire::Reader::at(bytes, KEKI_OFFSET).u32("keki")?;
let word2 = broadcast_core::wire::Reader::at(bytes, FLAGS_OFFSET).u32("word2")?;
let cipher = Cipher::from_bits((word2 >> CIPHER_SHIFT) as u8);
let auth = KmAuth::from_bits((word2 >> AUTH_SHIFT) as u8);
let se = StreamEncapsulation::from_bits((word2 >> SE_SHIFT) as u8);
let resv2 = (word2 & RESV2_MASK) as u8;
if resv2 != RESV2_FIXED {
return Err(Error::InvalidKeyMaterial {
field: "Resv2",
reason: "must be 0",
});
}
let word3 = broadcast_core::wire::Reader::at(bytes, LENGTHS_OFFSET).u32("word3")?;
let resv3 = (word3 >> RESV3_SHIFT) as u16;
let slen4 = ((word3 >> SLEN_SHIFT) & LEN_MASK) as usize;
let klen4 = (word3 & LEN_MASK) as usize;
if resv3 != RESV3_FIXED {
return Err(Error::InvalidKeyMaterial {
field: "Resv3",
reason: "must be 0",
});
}
let slen = slen4 * KEY_BLOCK_LEN;
let klen = klen4 * KEY_BLOCK_LEN;
if !crate::AES_KEY_LENS.contains(&klen) {
return Err(Error::InvalidKeyMaterial {
field: "KLen",
reason: "must be 16, 24, or 32 bytes (AES-128/192/256)",
});
}
let mut offset = FIXED_HEADER_LEN;
let salt = bytes
.get(offset..offset + slen)
.ok_or(Error::BufferTooShort(BufferTooShort::new(
offset + slen,
bytes.len(),
"key material salt",
)))?;
offset += slen;
let n = usize::from(kk.key_count());
let wrap_len = ICV_LEN + n * klen;
let wrap = bytes
.get(offset..offset + wrap_len)
.ok_or(Error::BufferTooShort(BufferTooShort::new(
offset + wrap_len,
bytes.len(),
"key material wrap field",
)))?;
offset += wrap_len;
if offset != bytes.len() {
return Err(Error::UnexpectedTrailingBytes {
what: "key material message",
extra: bytes.len() - offset,
});
}
let mut icv = [0u8; ICV_LEN];
icv.copy_from_slice(&wrap[0..ICV_LEN]);
let x_sek = &wrap[ICV_LEN..ICV_LEN + klen];
let o_sek = if n == KEY_COUNT_BOTH {
Some(&wrap[ICV_LEN + klen..ICV_LEN + n * klen])
} else {
None
};
Ok(KeyMaterial {
kk,
keki,
cipher,
auth,
se,
salt,
icv,
x_sek,
o_sek,
})
}
pub fn serialized_len(&self) -> usize {
FIXED_HEADER_LEN
+ self.salt.len()
+ ICV_LEN
+ self.x_sek.len()
+ self.o_sek.map_or(0, <[u8]>::len)
}
pub fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
let len = self.serialized_len();
need_out(buf, len, "KeyMaterial")?;
if !self.salt.len().is_multiple_of(KEY_BLOCK_LEN) {
return Err(Error::InvalidKeyMaterial {
field: "Salt",
reason: "length must be a whole number of 4-byte words",
});
}
broadcast_core::len::fit_u8(self.salt.len() / KEY_BLOCK_LEN, "Salt length / 4 (SLen)")?;
if !crate::AES_KEY_LENS.contains(&self.x_sek.len()) {
return Err(Error::InvalidKeyMaterial {
field: "xSEK",
reason: "length must be 16, 24, or 32 bytes",
});
}
if self.kk == KmKeyFlag::NoSek {
return Err(Error::InvalidKeyMaterial {
field: "KK",
reason: "00b (no SEK provided) is an invalid Key Material message (§3.2.2)",
});
}
let expects_both = self.kk == KmKeyFlag::Both;
match (&self.o_sek, expects_both) {
(Some(o), true) if o.len() == self.x_sek.len() => {}
(None, false) => {}
_ => {
return Err(Error::InvalidKeyMaterial {
field: "KK/oSEK",
reason: "oSEK must be present with the same length as xSEK iff KK is Both",
});
}
}
let word0 = (u32::from(S_FIXED) << S_SHIFT)
| (u32::from(V_FIXED) << V_SHIFT)
| (u32::from(PT_KEYING_MATERIAL) << PT_SHIFT)
| (u32::from(SIGN_FIXED) << SIGN_SHIFT)
| (u32::from(RESV1_FIXED) << RESV1_SHIFT)
| u32::from(self.kk.to_bits());
put_be32(buf, 0, word0);
put_be32(buf, KEKI_OFFSET, self.keki);
let word2 = (u32::from(self.cipher.to_bits()) << CIPHER_SHIFT)
| (u32::from(self.auth.to_bits()) << AUTH_SHIFT)
| (u32::from(self.se.to_bits()) << SE_SHIFT)
| u32::from(RESV2_FIXED);
put_be32(buf, FLAGS_OFFSET, word2);
let slen4 = (self.salt.len() / KEY_BLOCK_LEN) as u32;
let klen4 = (self.x_sek.len() / KEY_BLOCK_LEN) as u32;
let word3 = (u32::from(RESV3_FIXED) << RESV3_SHIFT) | (slen4 << SLEN_SHIFT) | klen4;
put_be32(buf, LENGTHS_OFFSET, word3);
let mut off = FIXED_HEADER_LEN;
buf[off..off + self.salt.len()].copy_from_slice(self.salt);
off += self.salt.len();
buf[off..off + ICV_LEN].copy_from_slice(&self.icv);
off += ICV_LEN;
buf[off..off + self.x_sek.len()].copy_from_slice(self.x_sek);
off += self.x_sek.len();
if let Some(o) = self.o_sek {
buf[off..off + o.len()].copy_from_slice(o);
off += o.len();
}
debug_assert_eq!(off, len);
Ok(len)
}
}
impl<'a> broadcast_core::Parse<'a> for KeyMaterial<'a> {
type Error = crate::Error;
fn parse(bytes: &'a [u8]) -> core::result::Result<Self, Self::Error> {
KeyMaterial::parse(bytes)
}
}
impl broadcast_core::Serialize for KeyMaterial<'_> {
type Error = crate::Error;
fn serialized_len(&self) -> usize {
KeyMaterial::serialized_len(self)
}
fn serialize_into(&self, buf: &mut [u8]) -> core::result::Result<usize, Self::Error> {
KeyMaterial::serialize_into(self, buf)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn sample_even_only() -> KeyMaterial<'static> {
KeyMaterial {
kk: KmKeyFlag::Even,
keki: 0,
cipher: Cipher::AesCtr,
auth: KmAuth::None,
se: StreamEncapsulation::MpegTsSrt,
salt: &[0xAA; 16],
icv: [1, 2, 3, 4, 5, 6, 7, 8],
x_sek: &[0xEE; 16],
o_sek: None,
}
}
#[test]
fn round_trips_hand_computed_bytes() {
let km = sample_even_only();
let mut buf = alloc::vec![0u8; km.serialized_len()];
let n = km.serialize_into(&mut buf).unwrap();
assert_eq!(n, 16 + 16 + 8 + 16);
let expected_word0 = (1u32 << 28) | (2u32 << 24) | (0x2029u32 << 8) | 0b01u32;
assert_eq!(&buf[0..4], &expected_word0.to_be_bytes());
assert_eq!(&buf[12..16], &[0, 0, 4, 4]);
assert_eq!(&buf[16..32], &[0xAAu8; 16][..]);
assert_eq!(&buf[32..40], &[1, 2, 3, 4, 5, 6, 7, 8]);
assert_eq!(&buf[40..56], &[0xEEu8; 16][..]);
assert_eq!(KeyMaterial::parse(&buf).unwrap(), km);
}
#[test]
fn both_keys_round_trip() {
let km = KeyMaterial {
kk: KmKeyFlag::Both,
keki: 7,
cipher: Cipher::AesCtr,
auth: KmAuth::None,
se: StreamEncapsulation::MpegTsSrt,
salt: &[0; 16],
icv: [0; 8],
x_sek: &[1; 24],
o_sek: Some(&[2; 24]),
};
let mut buf = alloc::vec![0u8; km.serialized_len()];
km.serialize_into(&mut buf).unwrap();
assert_eq!(KeyMaterial::parse(&buf).unwrap(), km);
}
#[test]
fn no_salt_round_trips() {
let km = KeyMaterial {
kk: KmKeyFlag::Odd,
keki: 0,
cipher: Cipher::None,
auth: KmAuth::None,
se: StreamEncapsulation::Unspecified,
salt: &[],
icv: [9; 8],
x_sek: &[3; 32],
o_sek: None,
};
let mut buf = alloc::vec![0u8; km.serialized_len()];
km.serialize_into(&mut buf).unwrap();
assert_eq!(KeyMaterial::parse(&buf).unwrap(), km);
}
#[test]
fn bad_signature_errs_without_panic() {
let km = sample_even_only();
let mut buf = alloc::vec![0u8; km.serialized_len()];
km.serialize_into(&mut buf).unwrap();
buf[1] = 0x00; assert!(matches!(
KeyMaterial::parse(&buf),
Err(Error::InvalidKeyMaterial { field: "Sign", .. })
));
}
#[test]
fn inconsistent_kk_o_sek_errs() {
let mut km = sample_even_only();
km.o_sek = Some(&[0xEE; 16]); let mut buf = alloc::vec![0u8; 16 + 16 + 8 + 16 + 16];
assert!(matches!(
km.serialize_into(&mut buf),
Err(Error::InvalidKeyMaterial { .. })
));
}
#[test]
fn oversized_salt_length_errors() {
let salt = alloc::vec![0xAAu8; 1024];
let km = KeyMaterial {
kk: KmKeyFlag::Even,
keki: 0,
cipher: Cipher::AesCtr,
auth: KmAuth::None,
se: StreamEncapsulation::MpegTsSrt,
salt: &salt,
icv: [0; 8],
x_sek: &[0xEE; 16],
o_sek: None,
};
let mut buf = alloc::vec![0u8; km.serialized_len()];
let err = km.serialize_into(&mut buf).unwrap_err();
assert!(
matches!(err, Error::FieldOverflow(e) if e.max == u64::from(u8::MAX)),
"expected FieldOverflow(max=255) for SLen, got {err:?}"
);
}
#[test]
fn max_salt_length_round_trips() {
let salt = alloc::vec![0xAAu8; 1020];
let km = KeyMaterial {
kk: KmKeyFlag::Even,
keki: 0,
cipher: Cipher::AesCtr,
auth: KmAuth::None,
se: StreamEncapsulation::MpegTsSrt,
salt: &salt,
icv: [0; 8],
x_sek: &[0xEE; 16],
o_sek: None,
};
let mut buf = alloc::vec![0u8; km.serialized_len()];
km.serialize_into(&mut buf).unwrap();
let parsed = KeyMaterial::parse(&buf).unwrap();
assert_eq!(parsed.salt, salt.as_slice());
}
#[test]
fn kk_no_sek_is_refused_by_parse_and_serialize() {
let mut buf = alloc::vec![0u8; sample_even_only().serialized_len()];
sample_even_only().serialize_into(&mut buf).unwrap();
buf[3] &= !0b11;
assert!(matches!(
KeyMaterial::parse(&buf),
Err(Error::InvalidKeyMaterial { field: "KK", .. })
));
let short = &buf[..16 + 16 + 8];
assert!(matches!(
KeyMaterial::parse(short),
Err(Error::InvalidKeyMaterial { field: "KK", .. })
));
let mut km = sample_even_only();
km.kk = KmKeyFlag::NoSek;
let mut out = alloc::vec![0u8; km.serialized_len()];
assert!(matches!(
km.serialize_into(&mut out),
Err(Error::InvalidKeyMaterial { field: "KK", .. })
));
}
#[test]
fn every_accepted_message_reserializes_byte_identically() {
for kk in [KmKeyFlag::Even, KmKeyFlag::Odd, KmKeyFlag::Both] {
for klen in [16usize, 24, 32] {
let x = alloc::vec![0x5Au8; klen];
let o = alloc::vec![0xA5u8; klen];
let km = KeyMaterial {
kk,
keki: 3,
cipher: Cipher::AesCtr,
auth: KmAuth::None,
se: StreamEncapsulation::MpegTsSrt,
salt: &[7u8; 16],
icv: [9; 8],
x_sek: &x,
o_sek: (kk == KmKeyFlag::Both).then_some(o.as_slice()),
};
let mut wire = alloc::vec![0u8; km.serialized_len()];
km.serialize_into(&mut wire).unwrap();
let parsed = KeyMaterial::parse(&wire).unwrap();
let mut again = alloc::vec![0u8; parsed.serialized_len()];
parsed.serialize_into(&mut again).unwrap();
assert_eq!(again, wire, "kk={kk:?} klen={klen}");
}
}
}
#[test]
fn debug_output_redacts_wrapped_keys() {
let km = KeyMaterial {
kk: KmKeyFlag::Both,
keki: 0,
cipher: Cipher::AesCtr,
auth: KmAuth::None,
se: StreamEncapsulation::MpegTsSrt,
salt: &[0xAA; 16],
icv: [0xBB; 8],
x_sek: &[0xEE; 16],
o_sek: Some(&[0xDD; 16]),
};
for dump in [alloc::format!("{km:?}"), alloc::format!("{km:#?}")] {
for needle in ["238", "187", "221", "170", "0xee", "ee,"] {
assert!(!dump.contains(needle), "{needle:?} leaked: {dump}");
}
assert!(
dump.contains("x_sek: <redacted, 16 bytes>")
|| dump.contains("x_sek: <redacted, 16 bytes>,"),
"{dump}"
);
assert!(dump.contains("o_sek: <redacted, 16 bytes>"), "{dump}");
}
}
fn needles(bytes: &[u8]) -> alloc::vec::Vec<alloc::string::String> {
let head = &bytes[..6];
let join = |sep: &str| {
head.iter()
.map(|b| alloc::format!("{b}"))
.collect::<alloc::vec::Vec<_>>()
.join(sep)
};
alloc::vec![
join(", "),
join(","),
head.iter()
.map(|b| alloc::format!("{b:x}"))
.collect::<alloc::vec::Vec<_>>()
.join(", "),
head.iter().map(|b| alloc::format!("{b:02x}")).collect(),
]
}
fn distinctive(seed: u8, len: usize) -> alloc::vec::Vec<u8> {
let mut x = u32::from(seed)
.wrapping_mul(2_654_435_761)
.wrapping_add(12_345);
(0..len)
.map(|_| {
x = x.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
u8::try_from(x >> 24).unwrap()
})
.collect()
}
#[test]
fn debug_and_serde_output_carry_no_key_bytes() {
let salt = distinctive(1, 16);
let x = distinctive(2, 32);
let o = distinctive(3, 32);
let icv: [u8; 8] = distinctive(4, 8).try_into().unwrap();
let km = KeyMaterial {
kk: KmKeyFlag::Both,
keki: 0,
cipher: Cipher::AesCtr,
auth: KmAuth::None,
se: StreamEncapsulation::MpegTsSrt,
salt: &salt,
icv,
x_sek: &x,
o_sek: Some(&o),
};
#[cfg(feature = "serde")]
let json: Option<alloc::string::String> = {
let json = serde_json::to_string(&km).expect("serialize");
assert!(
json.contains("kk"),
"the non-secret fields are still serialized"
);
Some(json)
};
#[cfg(not(feature = "serde"))]
let json: Option<alloc::string::String> = None;
let dumps: alloc::vec::Vec<alloc::string::String> = [
alloc::format!("{km:?}"),
alloc::format!("{km:#?}"),
alloc::format!("{km:x?}"),
]
.into_iter()
.chain(json)
.collect();
for (name, secret) in [
("salt", &salt[..]),
("icv", &icv[..]),
("x_sek", &x[..]),
("o_sek", &o[..]),
] {
for needle in needles(secret) {
for dump in &dumps {
assert!(
!dump.contains(&needle),
"{name} leaked as {needle:?} in {dump}"
);
}
}
}
}
fn serialized(km: &KeyMaterial<'_>) -> alloc::vec::Vec<u8> {
let mut buf = alloc::vec![0u8; km.serialized_len()];
km.serialize_into(&mut buf).unwrap();
buf
}
#[test]
fn fixed_fields_are_checked_by_their_owned_bits() {
let km = sample_even_only();
let mut buf = serialized(&km);
buf[0] |= 0x80; assert!(matches!(
KeyMaterial::parse(&buf),
Err(Error::InvalidKeyMaterial { field: "S", .. })
));
let mut buf = serialized(&km);
buf[12] = 0x01; assert!(matches!(
KeyMaterial::parse(&buf),
Err(Error::InvalidKeyMaterial { field: "Resv3", .. })
));
}
#[test]
fn truncated_salt_reports_the_exact_need() {
let buf = serialized(&sample_even_only());
match KeyMaterial::parse(&buf[..20]) {
Err(Error::BufferTooShort(b)) => {
assert_eq!(b.need, 32);
assert_eq!(b.have, 20);
}
other => panic!("expected BufferTooShort, got {other:?}"),
}
}
#[test]
fn truncated_wrap_field_reports_the_exact_need() {
let buf = serialized(&sample_even_only());
match KeyMaterial::parse(&buf[..40]) {
Err(Error::BufferTooShort(b)) => {
assert_eq!(b.need, 56);
assert_eq!(b.have, 40);
}
other => panic!("expected BufferTooShort, got {other:?}"),
}
}
#[test]
fn trailing_bytes_report_the_exact_extra_count() {
let mut buf = serialized(&sample_even_only());
buf.extend_from_slice(&[0xAA, 0xBB]);
match KeyMaterial::parse(&buf) {
Err(Error::UnexpectedTrailingBytes { extra, .. }) => assert_eq!(extra, 2),
other => panic!("expected UnexpectedTrailingBytes, got {other:?}"),
}
}
}