1use 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; const RESV1_FIXED: u8 = 0;
35const RESV2_FIXED: u8 = 0;
36const RESV3_FIXED: u16 = 0;
37
38const FIXED_HEADER_LEN: usize = 16;
41pub const ICV_LEN: usize = 8;
44const KEY_BLOCK_LEN: usize = 4;
45
46const KEY_COUNT_BOTH: usize = 2;
48
49const KEKI_OFFSET: usize = 4;
51const FLAGS_OFFSET: usize = 8;
52const LENGTHS_OFFSET: usize = 12;
53
54const 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
66const 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
75const KK_FIELD_MASK: u8 = 0b11;
77
78pub const KM_KK_NO_SEK: u8 = 0b00;
82pub const KM_KK_EVEN: u8 = 0b01;
84pub const KM_KK_ODD: u8 = 0b10;
86pub const KM_KK_BOTH: u8 = 0b11;
88
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
92#[cfg_attr(feature = "serde", derive(serde::Serialize))]
93#[non_exhaustive]
94pub enum KmKeyFlag {
95 NoSek,
99 Even,
101 Odd,
103 Both,
105}
106
107impl KmKeyFlag {
108 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 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 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 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
151pub const CIPHER_NONE: u8 = 0;
153pub const CIPHER_AES_CTR: u8 = 2;
155
156#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
158#[cfg_attr(feature = "serde", derive(serde::Serialize))]
159#[non_exhaustive]
160pub enum Cipher {
161 None,
163 AesCtr,
165 Reserved(u8),
167}
168
169impl Cipher {
170 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 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 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
200pub const KM_AUTH_NONE: u8 = 0;
202
203#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
206#[cfg_attr(feature = "serde", derive(serde::Serialize))]
207#[non_exhaustive]
208pub enum KmAuth {
209 None,
211 Reserved(u8),
213}
214
215impl KmAuth {
216 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 pub fn to_bits(self) -> u8 {
226 match self {
227 KmAuth::None => KM_AUTH_NONE,
228 KmAuth::Reserved(v) => v,
229 }
230 }
231
232 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
243pub const STREAM_ENCAP_UNSPECIFIED: u8 = 0;
245pub const STREAM_ENCAP_MPEG_TS_UDP: u8 = 1;
247pub const STREAM_ENCAP_MPEG_TS_SRT: u8 = 2;
249
250#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
252#[cfg_attr(feature = "serde", derive(serde::Serialize))]
253#[non_exhaustive]
254pub enum StreamEncapsulation {
255 Unspecified,
257 MpegTsUdp,
259 MpegTsSrt,
261 Reserved(u8),
263}
264
265impl StreamEncapsulation {
266 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 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 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#[derive(Clone, PartialEq, Eq, Hash)]
306#[cfg_attr(feature = "serde", derive(serde::Serialize))]
307pub struct KeyMaterial<'a> {
308 pub kk: KmKeyFlag,
310 pub keki: u32,
312 pub cipher: Cipher,
314 pub auth: KmAuth,
316 pub se: StreamEncapsulation,
318 #[cfg_attr(feature = "serde", serde(skip))]
323 pub salt: &'a [u8],
324 #[cfg_attr(feature = "serde", serde(skip))]
326 pub icv: [u8; ICV_LEN],
327 #[cfg_attr(feature = "serde", serde(skip))]
331 pub x_sek: &'a [u8],
332 #[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 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 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 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 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 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 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 let expected_word0 = (1u32 << 28) | (2u32 << 24) | (0x2029u32 << 8) | 0b01u32;
635 assert_eq!(&buf[0..4], &expected_word0.to_be_bytes());
636 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; 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]); 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 #[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 #[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 #[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 buf[3] &= !0b11;
763 assert!(matches!(
764 KeyMaterial::parse(&buf),
765 Err(Error::InvalidKeyMaterial { field: "KK", .. })
766 ));
767 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 #[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 #[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 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 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 #[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 #[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; assert!(matches!(
947 KeyMaterial::parse(&buf),
948 Err(Error::InvalidKeyMaterial { field: "S", .. })
949 ));
950
951 let mut buf = serialized(&km);
952 buf[12] = 0x01; assert!(matches!(
954 KeyMaterial::parse(&buf),
955 Err(Error::InvalidKeyMaterial { field: "Resv3", .. })
956 ));
957 }
958
959 #[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 #[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 #[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}