Skip to main content

srt_runtime/packet/
key_material.rs

1//! Key Material message — `draft-sharabayko-srt-01` §3.2.2, Figures 10-11.
2//!
3//! Carried either as a Handshake Extension (§3.2.1.2, `Extension Type`
4//! `SRT_CMD_KMREQ`/`SRT_CMD_KMRSP`) or as the CIF of a User-Defined control
5//! packet (`Subtype` `SRT_CMD_KMREQ`/`SRT_CMD_KMRSP`, §3.2.2).
6//!
7//! ```text
8//! word0   S(1) V(3) PT(4) | Sign(16) | Resv1(6) KK(2)
9//! word1   KEKI(32)
10//! word2   Cipher(8) Auth(8) SE(8) Resv2(8)
11//! word3   Resv3(16) SLen/4(8) KLen/4(8)
12//! ..      Salt (SLen bytes)
13//! ..      ICV (8 bytes) | xSEK (KLen bytes) | [oSEK (KLen bytes)]
14//! ```
15//!
16//! `S`, `V`, `PT`, `Sign`, `Resv1`, `Resv2`, `Resv3` are fixed-value fields
17//! (the spec gives each a mandated `value = {..}`); they are validated on
18//! parse and not stored (matching the crate's reserved-bit policy — see the
19//! crate root docs), except `PT`, which acts as this struct's discriminating
20//! magic number (must be `2`, "Keying Material Message").
21//!
22//! This module only carries the wrapped-key *bytes* — it performs no AES
23//! key-wrap/unwrap. Actual encryption/decryption is an explicit follow-up
24//! (see the crate root docs).
25
26use super::{Error, Result, be32, put_be32};
27use broadcast_common::error::BufferTooShort;
28use broadcast_common::len::{need_in, need_out};
29
30const S_FIXED: u8 = 0;
31const V_FIXED: u8 = 1;
32const PT_KEYING_MATERIAL: u8 = 2;
33const SIGN_FIXED: u16 = 0x2029; // 'HAI' PnP Vendor ID, big-endian.
34const RESV1_FIXED: u8 = 0;
35const RESV2_FIXED: u8 = 0;
36const RESV3_FIXED: u16 = 0;
37
38/// `KK` wire values of the Key Material message (§3.2.2). Distinct from the
39/// data-packet `KK` field ([`super::EncryptionKeyField`]) — same 2-bit shape,
40/// different meaning.
41pub const KM_KK_NO_SEK: u8 = 0b00;
42/// Even key provided.
43pub const KM_KK_EVEN: u8 = 0b01;
44/// Odd key provided.
45pub const KM_KK_ODD: u8 = 0b10;
46/// Both keys provided.
47pub const KM_KK_BOTH: u8 = 0b11;
48
49/// `KK`: which SEK(s) (odd/even) this Key Material message provides
50/// (`draft-sharabayko-srt-01` §3.2.2).
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
52#[cfg_attr(feature = "serde", derive(serde::Serialize))]
53#[non_exhaustive]
54pub enum KmKeyFlag {
55    /// `00b`: no SEK provided (spec: "invalid extension format") — decodable
56    /// from the 2-bit field, but [`KeyMaterial::parse`] and
57    /// [`KeyMaterial::serialize_into`] both refuse a message carrying it.
58    NoSek,
59    /// `01b`: even key provided.
60    Even,
61    /// `10b`: odd key provided.
62    Odd,
63    /// `11b`: both even and odd keys provided.
64    Both,
65}
66
67impl KmKeyFlag {
68    /// Decode the 2-bit `KK` field.
69    pub fn from_bits(v: u8) -> Self {
70        match v & 0b11 {
71            KM_KK_EVEN => KmKeyFlag::Even,
72            KM_KK_ODD => KmKeyFlag::Odd,
73            KM_KK_BOTH => KmKeyFlag::Both,
74            _ => KmKeyFlag::NoSek,
75        }
76    }
77
78    /// The 2-bit wire value.
79    pub fn to_bits(self) -> u8 {
80        match self {
81            KmKeyFlag::NoSek => KM_KK_NO_SEK,
82            KmKeyFlag::Even => KM_KK_EVEN,
83            KmKeyFlag::Odd => KM_KK_ODD,
84            KmKeyFlag::Both => KM_KK_BOTH,
85        }
86    }
87
88    /// Number of SEKs this flag indicates (`n` in the Wrap-field length
89    /// formula, §3.2.2: `n = (KK + 1) / 2`).
90    pub fn key_count(self) -> u8 {
91        match self {
92            KmKeyFlag::NoSek => 0,
93            KmKeyFlag::Even | KmKeyFlag::Odd => 1,
94            KmKeyFlag::Both => 2,
95        }
96    }
97
98    /// Spec label.
99    pub fn name(&self) -> &'static str {
100        match self {
101            KmKeyFlag::NoSek => "no SEK",
102            KmKeyFlag::Even => "even key",
103            KmKeyFlag::Odd => "odd key",
104            KmKeyFlag::Both => "both keys",
105        }
106    }
107}
108
109broadcast_common::impl_spec_display!(KmKeyFlag);
110
111/// `Cipher` wire values (§3.2.2).
112pub const CIPHER_NONE: u8 = 0;
113/// AES-CTR.
114pub const CIPHER_AES_CTR: u8 = 2;
115
116/// `Cipher`: encryption cipher and mode (`draft-sharabayko-srt-01` §3.2.2).
117#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
118#[cfg_attr(feature = "serde", derive(serde::Serialize))]
119#[non_exhaustive]
120pub enum Cipher {
121    /// `0`: none, or a KEKI-indexed crypto context.
122    None,
123    /// `2`: AES-CTR (SP800-38A).
124    AesCtr,
125    /// A value not defined above (includes `1`).
126    Reserved(u8),
127}
128
129impl Cipher {
130    /// Decode the 8-bit `Cipher` field.
131    pub fn from_bits(v: u8) -> Self {
132        match v {
133            CIPHER_NONE => Cipher::None,
134            CIPHER_AES_CTR => Cipher::AesCtr,
135            other => Cipher::Reserved(other),
136        }
137    }
138
139    /// The wire value.
140    pub fn to_bits(self) -> u8 {
141        match self {
142            Cipher::None => CIPHER_NONE,
143            Cipher::AesCtr => CIPHER_AES_CTR,
144            Cipher::Reserved(v) => v,
145        }
146    }
147
148    /// Spec label.
149    pub fn name(&self) -> &'static str {
150        match self {
151            Cipher::None => "none / KEKI-indexed",
152            Cipher::AesCtr => "AES-CTR",
153            Cipher::Reserved(_) => "reserved",
154        }
155    }
156}
157
158broadcast_common::impl_spec_display!(Cipher, Reserved);
159
160/// `Authentication` wire values (§3.2.2).
161pub const KM_AUTH_NONE: u8 = 0;
162
163/// `Authentication`: message authentication code algorithm
164/// (`draft-sharabayko-srt-01` §3.2.2).
165#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
166#[cfg_attr(feature = "serde", derive(serde::Serialize))]
167#[non_exhaustive]
168pub enum KmAuth {
169    /// `0`: none, or a KEKI-indexed crypto context (the only defined value).
170    None,
171    /// A value not defined above.
172    Reserved(u8),
173}
174
175impl KmAuth {
176    /// Decode the 8-bit `Auth` field.
177    pub fn from_bits(v: u8) -> Self {
178        match v {
179            KM_AUTH_NONE => KmAuth::None,
180            other => KmAuth::Reserved(other),
181        }
182    }
183
184    /// The wire value.
185    pub fn to_bits(self) -> u8 {
186        match self {
187            KmAuth::None => KM_AUTH_NONE,
188            KmAuth::Reserved(v) => v,
189        }
190    }
191
192    /// Spec label.
193    pub fn name(&self) -> &'static str {
194        match self {
195            KmAuth::None => "none / KEKI-indexed",
196            KmAuth::Reserved(_) => "reserved",
197        }
198    }
199}
200
201broadcast_common::impl_spec_display!(KmAuth, Reserved);
202
203/// `SE` (Stream Encapsulation) wire values (§3.2.2).
204pub const STREAM_ENCAP_UNSPECIFIED: u8 = 0;
205/// MPEG-TS/UDP.
206pub const STREAM_ENCAP_MPEG_TS_UDP: u8 = 1;
207/// MPEG-TS/SRT.
208pub const STREAM_ENCAP_MPEG_TS_SRT: u8 = 2;
209
210/// `SE`: stream encapsulation (`draft-sharabayko-srt-01` §3.2.2).
211#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
212#[cfg_attr(feature = "serde", derive(serde::Serialize))]
213#[non_exhaustive]
214pub enum StreamEncapsulation {
215    /// `0`: unspecified, or a KEKI-indexed crypto context.
216    Unspecified,
217    /// `1`: MPEG-TS/UDP.
218    MpegTsUdp,
219    /// `2`: MPEG-TS/SRT.
220    MpegTsSrt,
221    /// A value not defined above.
222    Reserved(u8),
223}
224
225impl StreamEncapsulation {
226    /// Decode the 8-bit `SE` field.
227    pub fn from_bits(v: u8) -> Self {
228        match v {
229            STREAM_ENCAP_UNSPECIFIED => StreamEncapsulation::Unspecified,
230            STREAM_ENCAP_MPEG_TS_UDP => StreamEncapsulation::MpegTsUdp,
231            STREAM_ENCAP_MPEG_TS_SRT => StreamEncapsulation::MpegTsSrt,
232            other => StreamEncapsulation::Reserved(other),
233        }
234    }
235
236    /// The wire value.
237    pub fn to_bits(self) -> u8 {
238        match self {
239            StreamEncapsulation::Unspecified => STREAM_ENCAP_UNSPECIFIED,
240            StreamEncapsulation::MpegTsUdp => STREAM_ENCAP_MPEG_TS_UDP,
241            StreamEncapsulation::MpegTsSrt => STREAM_ENCAP_MPEG_TS_SRT,
242            StreamEncapsulation::Reserved(v) => v,
243        }
244    }
245
246    /// Spec label.
247    pub fn name(&self) -> &'static str {
248        match self {
249            StreamEncapsulation::Unspecified => "unspecified / KEKI-indexed",
250            StreamEncapsulation::MpegTsUdp => "MPEG-TS/UDP",
251            StreamEncapsulation::MpegTsSrt => "MPEG-TS/SRT",
252            StreamEncapsulation::Reserved(_) => "reserved",
253        }
254    }
255}
256
257broadcast_common::impl_spec_display!(StreamEncapsulation, Reserved);
258
259/// Key Material message (`draft-sharabayko-srt-01` §3.2.2, Figures 10-11).
260///
261/// [`core::fmt::Debug`] prints only the lengths of the wrapped keys and the
262/// ICV: with the Salt they are exactly what an offline attack on the
263/// passphrase needs, so they must not reach a log by way of `{:?}`
264/// (issue #1142).
265#[derive(Clone, PartialEq, Eq, Hash)]
266#[cfg_attr(feature = "serde", derive(serde::Serialize))]
267pub struct KeyMaterial<'a> {
268    /// Which SEK(s) [`Self::x_sek`] / [`Self::o_sek`] carry.
269    pub kk: KmKeyFlag,
270    /// Key Encryption Key Index (big-endian; `0` = default stream key).
271    pub keki: u32,
272    /// Encryption cipher and mode.
273    pub cipher: Cipher,
274    /// Message authentication code algorithm.
275    pub auth: KmAuth,
276    /// Stream encapsulation.
277    pub se: StreamEncapsulation,
278    /// Salt / IV (`SLen` bytes; `0` if absent, else 16 bytes / 128 bits per
279    /// the only length the spec defines). Not serialized by the `serde`
280    /// feature (with the wrapped keys it permits an offline passphrase
281    /// attack), nor shown by `Debug`.
282    #[cfg_attr(feature = "serde", serde(skip))]
283    pub salt: &'a [u8],
284    /// 64-bit AES key-wrap Integrity Check Vector. Not serialized by `serde`.
285    #[cfg_attr(feature = "serde", serde(skip))]
286    pub icv: [u8; 8],
287    /// The (even or odd, per [`Self::kk`]) SEK, wrapped. `KLen` bytes
288    /// (16/24/32, matching the handshake's `Encryption Field`). Not serialized
289    /// by `serde`.
290    #[cfg_attr(feature = "serde", serde(skip))]
291    pub x_sek: &'a [u8],
292    /// The odd SEK, wrapped, present only when [`Self::kk`] is
293    /// [`KmKeyFlag::Both`] (same length as [`Self::x_sek`]). Not serialized by
294    /// `serde`.
295    #[cfg_attr(feature = "serde", serde(skip))]
296    pub o_sek: Option<&'a [u8]>,
297}
298
299impl core::fmt::Debug for KeyMaterial<'_> {
300    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
301        f.debug_struct("KeyMaterial")
302            .field("kk", &self.kk)
303            .field("keki", &self.keki)
304            .field("cipher", &self.cipher)
305            .field("auth", &self.auth)
306            .field("se", &self.se)
307            .field(
308                "salt",
309                &format_args!("<redacted, {} bytes>", self.salt.len()),
310            )
311            .field("icv", &format_args!("<redacted, {} bytes>", self.icv.len()))
312            .field(
313                "x_sek",
314                &format_args!("<redacted, {} bytes>", self.x_sek.len()),
315            )
316            .field(
317                "o_sek",
318                &format_args!("<redacted, {} bytes>", self.o_sek.map_or(0, <[u8]>::len)),
319            )
320            .finish()
321    }
322}
323
324impl<'a> KeyMaterial<'a> {
325    /// Parse a Key Material message from `bytes` (exactly the message —
326    /// either a handshake extension's contents or a User-Defined control
327    /// packet's CIF).
328    pub fn parse(bytes: &'a [u8]) -> Result<Self> {
329        need_in(bytes, 16, "key material fixed header")?;
330        let word0 = be32(bytes, 0);
331        let s = (word0 >> 31) as u8;
332        let v = ((word0 >> 28) & 0b111) as u8;
333        let pt = ((word0 >> 24) & 0b1111) as u8;
334        let sign = ((word0 >> 8) & 0xFFFF) as u16;
335        let resv1 = ((word0 >> 2) & 0b0011_1111) as u8;
336        let kk_bits = (word0 & 0b11) as u8;
337
338        if s != S_FIXED {
339            return Err(Error::InvalidKeyMaterial {
340                field: "S",
341                reason: "must be 0",
342            });
343        }
344        if v != V_FIXED {
345            return Err(Error::InvalidKeyMaterial {
346                field: "V",
347                reason: "must be 1",
348            });
349        }
350        if pt != PT_KEYING_MATERIAL {
351            return Err(Error::InvalidKeyMaterial {
352                field: "PT",
353                reason: "must be 2 (Keying Material Message)",
354            });
355        }
356        if sign != SIGN_FIXED {
357            return Err(Error::InvalidKeyMaterial {
358                field: "Sign",
359                reason: "must be 0x2029 ('HAI' PnP Vendor ID)",
360            });
361        }
362        if resv1 != RESV1_FIXED {
363            return Err(Error::InvalidKeyMaterial {
364                field: "Resv1",
365                reason: "must be 0",
366            });
367        }
368        let kk = KmKeyFlag::from_bits(kk_bits);
369        if kk == KmKeyFlag::NoSek {
370            // §3.2.2: `KK` = `00b` "No SEK is provided", which the draft
371            // itself calls an invalid extension format. Accepting it would
372            // admit a value `serialize_into` (which needs a `KLen`-sized
373            // xSEK) cannot reproduce — a parse the round-trip invariant
374            // cannot honour — so it is refused here and in serialize.
375            return Err(Error::InvalidKeyMaterial {
376                field: "KK",
377                reason: "00b (no SEK provided) is an invalid Key Material message (§3.2.2)",
378            });
379        }
380
381        let keki = be32(bytes, 4);
382
383        let word2 = be32(bytes, 8);
384        let cipher = Cipher::from_bits((word2 >> 24) as u8);
385        let auth = KmAuth::from_bits((word2 >> 16) as u8);
386        let se = StreamEncapsulation::from_bits((word2 >> 8) as u8);
387        let resv2 = (word2 & 0xFF) as u8;
388        if resv2 != RESV2_FIXED {
389            return Err(Error::InvalidKeyMaterial {
390                field: "Resv2",
391                reason: "must be 0",
392            });
393        }
394
395        let word3 = be32(bytes, 12);
396        let resv3 = (word3 >> 16) as u16;
397        let slen4 = ((word3 >> 8) & 0xFF) as usize;
398        let klen4 = (word3 & 0xFF) as usize;
399        if resv3 != RESV3_FIXED {
400            return Err(Error::InvalidKeyMaterial {
401                field: "Resv3",
402                reason: "must be 0",
403            });
404        }
405
406        let slen = slen4 * 4;
407        let klen = klen4 * 4;
408        if !matches!(klen, 16 | 24 | 32) {
409            return Err(Error::InvalidKeyMaterial {
410                field: "KLen",
411                reason: "must be 16, 24, or 32 bytes (AES-128/192/256)",
412            });
413        }
414
415        let mut offset = 16usize;
416        let salt = bytes
417            .get(offset..offset + slen)
418            .ok_or(Error::BufferTooShort(BufferTooShort {
419                need: offset + slen,
420                have: bytes.len(),
421                what: "key material salt",
422            }))?;
423        offset += slen;
424
425        let n = usize::from(kk.key_count());
426        let wrap_len = 8 + n * klen;
427        let wrap = bytes
428            .get(offset..offset + wrap_len)
429            .ok_or(Error::BufferTooShort(BufferTooShort {
430                need: offset + wrap_len,
431                have: bytes.len(),
432                what: "key material wrap field",
433            }))?;
434        offset += wrap_len;
435
436        if offset != bytes.len() {
437            return Err(Error::UnexpectedTrailingBytes {
438                what: "key material message",
439                extra: bytes.len() - offset,
440            });
441        }
442
443        let mut icv = [0u8; 8];
444        icv.copy_from_slice(&wrap[0..8]);
445        // `KK` is not `NoSek` (refused above), so there is always an xSEK.
446        let x_sek = &wrap[8..8 + klen];
447        let o_sek = if n == 2 {
448            Some(&wrap[8 + klen..8 + 2 * klen])
449        } else {
450            None
451        };
452
453        Ok(KeyMaterial {
454            kk,
455            keki,
456            cipher,
457            auth,
458            se,
459            salt,
460            icv,
461            x_sek,
462            o_sek,
463        })
464    }
465
466    /// Number of bytes [`Self::serialize_into`] will write.
467    pub fn serialized_len(&self) -> usize {
468        16 + self.salt.len() + 8 + self.x_sek.len() + self.o_sek.map_or(0, <[u8]>::len)
469    }
470
471    /// Serialize this Key Material message into `buf`.
472    pub fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
473        let len = self.serialized_len();
474        need_out(buf, len)?;
475        if !self.salt.len().is_multiple_of(4) {
476            return Err(Error::InvalidKeyMaterial {
477                field: "Salt",
478                reason: "length must be a whole number of 4-byte words",
479            });
480        }
481        // `SLen/4` is an 8-bit wire field (§3.2.2): a salt over 1020 bytes
482        // would otherwise shift into the reserved `Resv3` bits, misframing
483        // the message with `Ok` (#1129). Checked in `usize` before the
484        // 8-bit field is packed below.
485        broadcast_common::len::fit_u8(self.salt.len() / 4, "Salt length / 4 (SLen)")?;
486        if !matches!(self.x_sek.len(), 16 | 24 | 32) {
487            return Err(Error::InvalidKeyMaterial {
488                field: "xSEK",
489                reason: "length must be 16, 24, or 32 bytes",
490            });
491        }
492        if self.kk == KmKeyFlag::NoSek {
493            return Err(Error::InvalidKeyMaterial {
494                field: "KK",
495                reason: "00b (no SEK provided) is an invalid Key Material message (§3.2.2)",
496            });
497        }
498        let expects_both = self.kk == KmKeyFlag::Both;
499        match (&self.o_sek, expects_both) {
500            (Some(o), true) if o.len() == self.x_sek.len() => {}
501            (None, false) => {}
502            _ => {
503                return Err(Error::InvalidKeyMaterial {
504                    field: "KK/oSEK",
505                    reason: "oSEK must be present with the same length as xSEK iff KK is Both",
506                });
507            }
508        }
509
510        let word0 = (u32::from(S_FIXED) << 31)
511            | (u32::from(V_FIXED) << 28)
512            | (u32::from(PT_KEYING_MATERIAL) << 24)
513            | (u32::from(SIGN_FIXED) << 8)
514            | (u32::from(RESV1_FIXED) << 2)
515            | u32::from(self.kk.to_bits());
516        put_be32(buf, 0, word0);
517        put_be32(buf, 4, self.keki);
518        let word2 = (u32::from(self.cipher.to_bits()) << 24)
519            | (u32::from(self.auth.to_bits()) << 16)
520            | (u32::from(self.se.to_bits()) << 8)
521            | u32::from(RESV2_FIXED);
522        put_be32(buf, 8, word2);
523        let slen4 = (self.salt.len() / 4) as u32;
524        let klen4 = (self.x_sek.len() / 4) as u32;
525        let word3 = (u32::from(RESV3_FIXED) << 16) | (slen4 << 8) | klen4;
526        put_be32(buf, 12, word3);
527
528        let mut off = 16;
529        buf[off..off + self.salt.len()].copy_from_slice(self.salt);
530        off += self.salt.len();
531        buf[off..off + 8].copy_from_slice(&self.icv);
532        off += 8;
533        buf[off..off + self.x_sek.len()].copy_from_slice(self.x_sek);
534        off += self.x_sek.len();
535        if let Some(o) = self.o_sek {
536            buf[off..off + o.len()].copy_from_slice(o);
537            off += o.len();
538        }
539        debug_assert_eq!(off, len);
540        Ok(len)
541    }
542}
543
544impl<'a> broadcast_common::Parse<'a> for KeyMaterial<'a> {
545    type Error = crate::Error;
546
547    fn parse(bytes: &'a [u8]) -> core::result::Result<Self, Self::Error> {
548        KeyMaterial::parse(bytes)
549    }
550}
551
552impl broadcast_common::Serialize for KeyMaterial<'_> {
553    type Error = crate::Error;
554
555    fn serialized_len(&self) -> usize {
556        KeyMaterial::serialized_len(self)
557    }
558
559    fn serialize_into(&self, buf: &mut [u8]) -> core::result::Result<usize, Self::Error> {
560        KeyMaterial::serialize_into(self, buf)
561    }
562}
563
564#[cfg(test)]
565mod tests {
566    use super::*;
567
568    fn sample_even_only() -> KeyMaterial<'static> {
569        KeyMaterial {
570            kk: KmKeyFlag::Even,
571            keki: 0,
572            cipher: Cipher::AesCtr,
573            auth: KmAuth::None,
574            se: StreamEncapsulation::MpegTsSrt,
575            salt: &[0xAA; 16],
576            icv: [1, 2, 3, 4, 5, 6, 7, 8],
577            x_sek: &[0xEE; 16],
578            o_sek: None,
579        }
580    }
581
582    #[test]
583    fn round_trips_hand_computed_bytes() {
584        let km = sample_even_only();
585        let mut buf = alloc::vec![0u8; km.serialized_len()];
586        let n = km.serialize_into(&mut buf).unwrap();
587        assert_eq!(n, 16 + 16 + 8 + 16);
588
589        // word0: S=0,V=1,PT=2,Sign=0x2029,Resv1=0,KK=01
590        let expected_word0 = (1u32 << 28) | (2u32 << 24) | (0x2029u32 << 8) | 0b01u32;
591        assert_eq!(&buf[0..4], &expected_word0.to_be_bytes());
592        // word3: Resv3=0, SLen/4=4, KLen/4=4
593        assert_eq!(&buf[12..16], &[0, 0, 4, 4]);
594        assert_eq!(&buf[16..32], &[0xAAu8; 16][..]);
595        assert_eq!(&buf[32..40], &[1, 2, 3, 4, 5, 6, 7, 8]);
596        assert_eq!(&buf[40..56], &[0xEEu8; 16][..]);
597
598        assert_eq!(KeyMaterial::parse(&buf).unwrap(), km);
599    }
600
601    #[test]
602    fn both_keys_round_trip() {
603        let km = KeyMaterial {
604            kk: KmKeyFlag::Both,
605            keki: 7,
606            cipher: Cipher::AesCtr,
607            auth: KmAuth::None,
608            se: StreamEncapsulation::MpegTsSrt,
609            salt: &[0; 16],
610            icv: [0; 8],
611            x_sek: &[1; 24],
612            o_sek: Some(&[2; 24]),
613        };
614        let mut buf = alloc::vec![0u8; km.serialized_len()];
615        km.serialize_into(&mut buf).unwrap();
616        assert_eq!(KeyMaterial::parse(&buf).unwrap(), km);
617    }
618
619    #[test]
620    fn no_salt_round_trips() {
621        let km = KeyMaterial {
622            kk: KmKeyFlag::Odd,
623            keki: 0,
624            cipher: Cipher::None,
625            auth: KmAuth::None,
626            se: StreamEncapsulation::Unspecified,
627            salt: &[],
628            icv: [9; 8],
629            x_sek: &[3; 32],
630            o_sek: None,
631        };
632        let mut buf = alloc::vec![0u8; km.serialized_len()];
633        km.serialize_into(&mut buf).unwrap();
634        assert_eq!(KeyMaterial::parse(&buf).unwrap(), km);
635    }
636
637    #[test]
638    fn bad_signature_errs_without_panic() {
639        let km = sample_even_only();
640        let mut buf = alloc::vec![0u8; km.serialized_len()];
641        km.serialize_into(&mut buf).unwrap();
642        buf[1] = 0x00; // corrupt the Sign field
643        assert!(matches!(
644            KeyMaterial::parse(&buf),
645            Err(Error::InvalidKeyMaterial { field: "Sign", .. })
646        ));
647    }
648
649    #[test]
650    fn inconsistent_kk_o_sek_errs() {
651        let mut km = sample_even_only();
652        km.o_sek = Some(&[0xEE; 16]); // KK=Even must not carry oSEK
653        let mut buf = alloc::vec![0u8; 16 + 16 + 8 + 16 + 16];
654        assert!(matches!(
655            km.serialize_into(&mut buf),
656            Err(Error::InvalidKeyMaterial { .. })
657        ));
658    }
659
660    /// A salt of 1024 bytes (`SLen/4` = 256) cannot fit the 8-bit `SLen`
661    /// wire field (max 255, i.e. 1020 bytes; #1129): unfixed, `(slen4 as u8)`
662    /// (well, the packed `u32` word) wraps 256 to 0 and shifts into the
663    /// reserved `Resv3` bits, misframing the message with `Ok`.
664    #[test]
665    fn oversized_salt_length_errors() {
666        let salt = alloc::vec![0xAAu8; 1024];
667        let km = KeyMaterial {
668            kk: KmKeyFlag::Even,
669            keki: 0,
670            cipher: Cipher::AesCtr,
671            auth: KmAuth::None,
672            se: StreamEncapsulation::MpegTsSrt,
673            salt: &salt,
674            icv: [0; 8],
675            x_sek: &[0xEE; 16],
676            o_sek: None,
677        };
678        let mut buf = alloc::vec![0u8; km.serialized_len()];
679        let err = km.serialize_into(&mut buf).unwrap_err();
680        assert!(
681            matches!(err, Error::FieldOverflow(e) if e.max == u64::from(u8::MAX)),
682            "expected FieldOverflow(max=255) for SLen, got {err:?}"
683        );
684    }
685
686    /// The boundary: exactly 1020 bytes (`SLen/4` = 255, the 8-bit max)
687    /// still serializes and round-trips.
688    #[test]
689    fn max_salt_length_round_trips() {
690        let salt = alloc::vec![0xAAu8; 1020];
691        let km = KeyMaterial {
692            kk: KmKeyFlag::Even,
693            keki: 0,
694            cipher: Cipher::AesCtr,
695            auth: KmAuth::None,
696            se: StreamEncapsulation::MpegTsSrt,
697            salt: &salt,
698            icv: [0; 8],
699            x_sek: &[0xEE; 16],
700            o_sek: None,
701        };
702        let mut buf = alloc::vec![0u8; km.serialized_len()];
703        km.serialize_into(&mut buf).unwrap();
704        let parsed = KeyMaterial::parse(&buf).unwrap();
705        assert_eq!(parsed.salt, salt.as_slice());
706    }
707
708    /// r08-SRT-W13: `KK = 00b` ("no SEK provided", which §3.2.2 calls an
709    /// invalid format) used to parse to an empty xSEK that `serialize_into`
710    /// then refused — a parsed value that could not be re-serialized. It is
711    /// now refused at both ends, so no such value exists.
712    #[test]
713    fn kk_no_sek_is_refused_by_parse_and_serialize() {
714        let mut buf = alloc::vec![0u8; sample_even_only().serialized_len()];
715        sample_even_only().serialize_into(&mut buf).unwrap();
716        // Rewrite `KK` (low 2 bits of word 0) to 00b; keep the 16-byte xSEK so
717        // only the flag is wrong.
718        buf[3] &= !0b11;
719        assert!(matches!(
720            KeyMaterial::parse(&buf),
721            Err(Error::InvalidKeyMaterial { field: "KK", .. })
722        ));
723        // The same, with no xSEK bytes at all (the shape the old parser
724        // accepted): truncate to header + salt + ICV.
725        let short = &buf[..16 + 16 + 8];
726        assert!(matches!(
727            KeyMaterial::parse(short),
728            Err(Error::InvalidKeyMaterial { field: "KK", .. })
729        ));
730
731        let mut km = sample_even_only();
732        km.kk = KmKeyFlag::NoSek;
733        let mut out = alloc::vec![0u8; km.serialized_len()];
734        assert!(matches!(
735            km.serialize_into(&mut out),
736            Err(Error::InvalidKeyMaterial { field: "KK", .. })
737        ));
738    }
739
740    /// Every message `parse` accepts re-serializes byte-identically (the
741    /// symmetry the NoSek case broke), over all `KK` values and key lengths.
742    #[test]
743    fn every_accepted_message_reserializes_byte_identically() {
744        for kk in [KmKeyFlag::Even, KmKeyFlag::Odd, KmKeyFlag::Both] {
745            for klen in [16usize, 24, 32] {
746                let x = alloc::vec![0x5Au8; klen];
747                let o = alloc::vec![0xA5u8; klen];
748                let km = KeyMaterial {
749                    kk,
750                    keki: 3,
751                    cipher: Cipher::AesCtr,
752                    auth: KmAuth::None,
753                    se: StreamEncapsulation::MpegTsSrt,
754                    salt: &[7u8; 16],
755                    icv: [9; 8],
756                    x_sek: &x,
757                    o_sek: (kk == KmKeyFlag::Both).then_some(o.as_slice()),
758                };
759                let mut wire = alloc::vec![0u8; km.serialized_len()];
760                km.serialize_into(&mut wire).unwrap();
761                let parsed = KeyMaterial::parse(&wire).unwrap();
762                let mut again = alloc::vec![0u8; parsed.serialized_len()];
763                parsed.serialize_into(&mut again).unwrap();
764                assert_eq!(again, wire, "kk={kk:?} klen={klen}");
765            }
766        }
767    }
768
769    /// #1142: `{:?}` of a Key Material message shows the lengths of the wrapped
770    /// keys and ICV, never their bytes (with the salt they permit an offline
771    /// passphrase attack).
772    #[test]
773    fn debug_output_redacts_wrapped_keys() {
774        let km = KeyMaterial {
775            kk: KmKeyFlag::Both,
776            keki: 0,
777            cipher: Cipher::AesCtr,
778            auth: KmAuth::None,
779            se: StreamEncapsulation::MpegTsSrt,
780            salt: &[0xAA; 16],
781            icv: [0xBB; 8],
782            x_sek: &[0xEE; 16],
783            o_sek: Some(&[0xDD; 16]),
784        };
785        for dump in [alloc::format!("{km:?}"), alloc::format!("{km:#?}")] {
786            for needle in ["238", "187", "221", "170", "0xee", "ee,"] {
787                assert!(!dump.contains(needle), "{needle:?} leaked: {dump}");
788            }
789            assert!(
790                dump.contains("x_sek: <redacted, 16 bytes>")
791                    || dump.contains("x_sek: <redacted, 16 bytes>,"),
792                "{dump}"
793            );
794            assert!(dump.contains("o_sek: <redacted, 16 bytes>"), "{dump}");
795        }
796    }
797
798    /// Strings a leak of `bytes` would contain, in every form a `Debug` dump,
799    /// `{:x?}` dump or JSON array would print them (the first six bytes are a
800    /// long enough run to be unambiguous).
801    fn needles(bytes: &[u8]) -> alloc::vec::Vec<alloc::string::String> {
802        let head = &bytes[..6];
803        let join = |sep: &str| {
804            head.iter()
805                .map(|b| alloc::format!("{b}"))
806                .collect::<alloc::vec::Vec<_>>()
807                .join(sep)
808        };
809        alloc::vec![
810            join(", "),
811            join(","),
812            head.iter()
813                .map(|b| alloc::format!("{b:x}"))
814                .collect::<alloc::vec::Vec<_>>()
815                .join(", "),
816            head.iter().map(|b| alloc::format!("{b:02x}")).collect(),
817        ]
818    }
819
820    /// Distinctive, non-repeating key material (a fixed pseudo-random run, so
821    /// the needle cannot occur by chance in unrelated numbers).
822    fn distinctive(seed: u8, len: usize) -> alloc::vec::Vec<u8> {
823        let mut x = u32::from(seed)
824            .wrapping_mul(2_654_435_761)
825            .wrapping_add(12_345);
826        (0..len)
827            .map(|_| {
828                x = x.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
829                u8::try_from(x >> 24).unwrap()
830            })
831            .collect()
832    }
833
834    /// #1142: neither `Debug` nor serde output carries the salt, the ICV or
835    /// either wrapped key.
836    #[test]
837    fn debug_and_serde_output_carry_no_key_bytes() {
838        let salt = distinctive(1, 16);
839        let x = distinctive(2, 32);
840        let o = distinctive(3, 32);
841        let icv: [u8; 8] = distinctive(4, 8).try_into().unwrap();
842        let km = KeyMaterial {
843            kk: KmKeyFlag::Both,
844            keki: 0,
845            cipher: Cipher::AesCtr,
846            auth: KmAuth::None,
847            se: StreamEncapsulation::MpegTsSrt,
848            salt: &salt,
849            icv,
850            x_sek: &x,
851            o_sek: Some(&o),
852        };
853        #[cfg(feature = "serde")]
854        let json: Option<alloc::string::String> = {
855            let json = serde_json::to_string(&km).expect("serialize");
856            assert!(
857                json.contains("kk"),
858                "the non-secret fields are still serialized"
859            );
860            Some(json)
861        };
862        #[cfg(not(feature = "serde"))]
863        let json: Option<alloc::string::String> = None;
864        let dumps: alloc::vec::Vec<alloc::string::String> = [
865            alloc::format!("{km:?}"),
866            alloc::format!("{km:#?}"),
867            alloc::format!("{km:x?}"),
868        ]
869        .into_iter()
870        .chain(json)
871        .collect();
872        for (name, secret) in [
873            ("salt", &salt[..]),
874            ("icv", &icv[..]),
875            ("x_sek", &x[..]),
876            ("o_sek", &o[..]),
877        ] {
878            for needle in needles(secret) {
879                for dump in &dumps {
880                    assert!(
881                        !dump.contains(&needle),
882                        "{name} leaked as {needle:?} in {dump}"
883                    );
884                }
885            }
886        }
887    }
888
889    fn serialized(km: &KeyMaterial<'_>) -> alloc::vec::Vec<u8> {
890        let mut buf = alloc::vec![0u8; km.serialized_len()];
891        km.serialize_into(&mut buf).unwrap();
892        buf
893    }
894
895    /// Each fixed-value field is checked by its own shift: a set `S` or
896    /// `Resv3` bit must be rejected naming that field.
897    #[test]
898    fn fixed_fields_are_checked_by_their_owned_bits() {
899        let km = sample_even_only();
900        let mut buf = serialized(&km);
901        buf[0] |= 0x80; // S = 1
902        assert!(matches!(
903            KeyMaterial::parse(&buf),
904            Err(Error::InvalidKeyMaterial { field: "S", .. })
905        ));
906
907        let mut buf = serialized(&km);
908        buf[12] = 0x01; // Resv3 = 1
909        assert!(matches!(
910            KeyMaterial::parse(&buf),
911            Err(Error::InvalidKeyMaterial { field: "Resv3", .. })
912        ));
913    }
914
915    /// A truncated salt reports the exact byte count it needs (header + the
916    /// announced salt), not a product of the two.
917    #[test]
918    fn truncated_salt_reports_the_exact_need() {
919        let buf = serialized(&sample_even_only());
920        match KeyMaterial::parse(&buf[..20]) {
921            Err(Error::BufferTooShort(b)) => {
922                assert_eq!(b.need, 32);
923                assert_eq!(b.have, 20);
924            }
925            other => panic!("expected BufferTooShort, got {other:?}"),
926        }
927    }
928
929    /// A truncated wrap field reports the exact byte count it needs.
930    #[test]
931    fn truncated_wrap_field_reports_the_exact_need() {
932        let buf = serialized(&sample_even_only());
933        match KeyMaterial::parse(&buf[..40]) {
934            Err(Error::BufferTooShort(b)) => {
935                assert_eq!(b.need, 56);
936                assert_eq!(b.have, 40);
937            }
938            other => panic!("expected BufferTooShort, got {other:?}"),
939        }
940    }
941
942    /// Trailing bytes report the exact number left past the message.
943    #[test]
944    fn trailing_bytes_report_the_exact_extra_count() {
945        let mut buf = serialized(&sample_even_only());
946        buf.extend_from_slice(&[0xAA, 0xBB]);
947        match KeyMaterial::parse(&buf) {
948            Err(Error::UnexpectedTrailingBytes { extra, .. }) => assert_eq!(extra, 2),
949            other => panic!("expected UnexpectedTrailingBytes, got {other:?}"),
950        }
951    }
952}