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