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