1use super::{Error, Result, be32, put_be32};
27use broadcast_common::error::BufferTooShort;
28use broadcast_common::len::{need_in, need_out};
29
30const S_FIXED: u8 = 0;
31const V_FIXED: u8 = 1;
32const PT_KEYING_MATERIAL: u8 = 2;
33const SIGN_FIXED: u16 = 0x2029; const RESV1_FIXED: u8 = 0;
35const RESV2_FIXED: u8 = 0;
36const RESV3_FIXED: u16 = 0;
37
38pub const KM_KK_NO_SEK: u8 = 0b00;
42pub const KM_KK_EVEN: u8 = 0b01;
44pub const KM_KK_ODD: u8 = 0b10;
46pub const KM_KK_BOTH: u8 = 0b11;
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
52#[cfg_attr(feature = "serde", derive(serde::Serialize))]
53#[non_exhaustive]
54pub enum KmKeyFlag {
55 NoSek,
59 Even,
61 Odd,
63 Both,
65}
66
67impl KmKeyFlag {
68 pub fn from_bits(v: u8) -> Self {
70 match v & 0b11 {
71 KM_KK_EVEN => KmKeyFlag::Even,
72 KM_KK_ODD => KmKeyFlag::Odd,
73 KM_KK_BOTH => KmKeyFlag::Both,
74 _ => KmKeyFlag::NoSek,
75 }
76 }
77
78 pub fn to_bits(self) -> u8 {
80 match self {
81 KmKeyFlag::NoSek => KM_KK_NO_SEK,
82 KmKeyFlag::Even => KM_KK_EVEN,
83 KmKeyFlag::Odd => KM_KK_ODD,
84 KmKeyFlag::Both => KM_KK_BOTH,
85 }
86 }
87
88 pub fn key_count(self) -> u8 {
91 match self {
92 KmKeyFlag::NoSek => 0,
93 KmKeyFlag::Even | KmKeyFlag::Odd => 1,
94 KmKeyFlag::Both => 2,
95 }
96 }
97
98 pub fn name(&self) -> &'static str {
100 match self {
101 KmKeyFlag::NoSek => "no SEK",
102 KmKeyFlag::Even => "even key",
103 KmKeyFlag::Odd => "odd key",
104 KmKeyFlag::Both => "both keys",
105 }
106 }
107}
108
109broadcast_common::impl_spec_display!(KmKeyFlag);
110
111pub const CIPHER_NONE: u8 = 0;
113pub const CIPHER_AES_CTR: u8 = 2;
115
116#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
118#[cfg_attr(feature = "serde", derive(serde::Serialize))]
119#[non_exhaustive]
120pub enum Cipher {
121 None,
123 AesCtr,
125 Reserved(u8),
127}
128
129impl Cipher {
130 pub fn from_bits(v: u8) -> Self {
132 match v {
133 CIPHER_NONE => Cipher::None,
134 CIPHER_AES_CTR => Cipher::AesCtr,
135 other => Cipher::Reserved(other),
136 }
137 }
138
139 pub fn to_bits(self) -> u8 {
141 match self {
142 Cipher::None => CIPHER_NONE,
143 Cipher::AesCtr => CIPHER_AES_CTR,
144 Cipher::Reserved(v) => v,
145 }
146 }
147
148 pub fn name(&self) -> &'static str {
150 match self {
151 Cipher::None => "none / KEKI-indexed",
152 Cipher::AesCtr => "AES-CTR",
153 Cipher::Reserved(_) => "reserved",
154 }
155 }
156}
157
158broadcast_common::impl_spec_display!(Cipher, Reserved);
159
160pub const KM_AUTH_NONE: u8 = 0;
162
163#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
166#[cfg_attr(feature = "serde", derive(serde::Serialize))]
167#[non_exhaustive]
168pub enum KmAuth {
169 None,
171 Reserved(u8),
173}
174
175impl KmAuth {
176 pub fn from_bits(v: u8) -> Self {
178 match v {
179 KM_AUTH_NONE => KmAuth::None,
180 other => KmAuth::Reserved(other),
181 }
182 }
183
184 pub fn to_bits(self) -> u8 {
186 match self {
187 KmAuth::None => KM_AUTH_NONE,
188 KmAuth::Reserved(v) => v,
189 }
190 }
191
192 pub fn name(&self) -> &'static str {
194 match self {
195 KmAuth::None => "none / KEKI-indexed",
196 KmAuth::Reserved(_) => "reserved",
197 }
198 }
199}
200
201broadcast_common::impl_spec_display!(KmAuth, Reserved);
202
203pub const STREAM_ENCAP_UNSPECIFIED: u8 = 0;
205pub const STREAM_ENCAP_MPEG_TS_UDP: u8 = 1;
207pub const STREAM_ENCAP_MPEG_TS_SRT: u8 = 2;
209
210#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
212#[cfg_attr(feature = "serde", derive(serde::Serialize))]
213#[non_exhaustive]
214pub enum StreamEncapsulation {
215 Unspecified,
217 MpegTsUdp,
219 MpegTsSrt,
221 Reserved(u8),
223}
224
225impl StreamEncapsulation {
226 pub fn from_bits(v: u8) -> Self {
228 match v {
229 STREAM_ENCAP_UNSPECIFIED => StreamEncapsulation::Unspecified,
230 STREAM_ENCAP_MPEG_TS_UDP => StreamEncapsulation::MpegTsUdp,
231 STREAM_ENCAP_MPEG_TS_SRT => StreamEncapsulation::MpegTsSrt,
232 other => StreamEncapsulation::Reserved(other),
233 }
234 }
235
236 pub fn to_bits(self) -> u8 {
238 match self {
239 StreamEncapsulation::Unspecified => STREAM_ENCAP_UNSPECIFIED,
240 StreamEncapsulation::MpegTsUdp => STREAM_ENCAP_MPEG_TS_UDP,
241 StreamEncapsulation::MpegTsSrt => STREAM_ENCAP_MPEG_TS_SRT,
242 StreamEncapsulation::Reserved(v) => v,
243 }
244 }
245
246 pub fn name(&self) -> &'static str {
248 match self {
249 StreamEncapsulation::Unspecified => "unspecified / KEKI-indexed",
250 StreamEncapsulation::MpegTsUdp => "MPEG-TS/UDP",
251 StreamEncapsulation::MpegTsSrt => "MPEG-TS/SRT",
252 StreamEncapsulation::Reserved(_) => "reserved",
253 }
254 }
255}
256
257broadcast_common::impl_spec_display!(StreamEncapsulation, Reserved);
258
259#[derive(Clone, PartialEq, Eq, Hash)]
266#[cfg_attr(feature = "serde", derive(serde::Serialize))]
267pub struct KeyMaterial<'a> {
268 pub kk: KmKeyFlag,
270 pub keki: u32,
272 pub cipher: Cipher,
274 pub auth: KmAuth,
276 pub se: StreamEncapsulation,
278 #[cfg_attr(feature = "serde", serde(skip))]
283 pub salt: &'a [u8],
284 #[cfg_attr(feature = "serde", serde(skip))]
286 pub icv: [u8; 8],
287 #[cfg_attr(feature = "serde", serde(skip))]
291 pub x_sek: &'a [u8],
292 #[cfg_attr(feature = "serde", serde(skip))]
296 pub o_sek: Option<&'a [u8]>,
297}
298
299impl core::fmt::Debug for KeyMaterial<'_> {
300 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
301 f.debug_struct("KeyMaterial")
302 .field("kk", &self.kk)
303 .field("keki", &self.keki)
304 .field("cipher", &self.cipher)
305 .field("auth", &self.auth)
306 .field("se", &self.se)
307 .field(
308 "salt",
309 &format_args!("<redacted, {} bytes>", self.salt.len()),
310 )
311 .field("icv", &format_args!("<redacted, {} bytes>", self.icv.len()))
312 .field(
313 "x_sek",
314 &format_args!("<redacted, {} bytes>", self.x_sek.len()),
315 )
316 .field(
317 "o_sek",
318 &format_args!("<redacted, {} bytes>", self.o_sek.map_or(0, <[u8]>::len)),
319 )
320 .finish()
321 }
322}
323
324impl<'a> KeyMaterial<'a> {
325 pub fn parse(bytes: &'a [u8]) -> Result<Self> {
329 need_in(bytes, 16, "key material fixed header")?;
330 let word0 = be32(bytes, 0);
331 let s = (word0 >> 31) as u8;
332 let v = ((word0 >> 28) & 0b111) as u8;
333 let pt = ((word0 >> 24) & 0b1111) as u8;
334 let sign = ((word0 >> 8) & 0xFFFF) as u16;
335 let resv1 = ((word0 >> 2) & 0b0011_1111) as u8;
336 let kk_bits = (word0 & 0b11) as u8;
337
338 if s != S_FIXED {
339 return Err(Error::InvalidKeyMaterial {
340 field: "S",
341 reason: "must be 0",
342 });
343 }
344 if v != V_FIXED {
345 return Err(Error::InvalidKeyMaterial {
346 field: "V",
347 reason: "must be 1",
348 });
349 }
350 if pt != PT_KEYING_MATERIAL {
351 return Err(Error::InvalidKeyMaterial {
352 field: "PT",
353 reason: "must be 2 (Keying Material Message)",
354 });
355 }
356 if sign != SIGN_FIXED {
357 return Err(Error::InvalidKeyMaterial {
358 field: "Sign",
359 reason: "must be 0x2029 ('HAI' PnP Vendor ID)",
360 });
361 }
362 if resv1 != RESV1_FIXED {
363 return Err(Error::InvalidKeyMaterial {
364 field: "Resv1",
365 reason: "must be 0",
366 });
367 }
368 let kk = KmKeyFlag::from_bits(kk_bits);
369 if kk == KmKeyFlag::NoSek {
370 return Err(Error::InvalidKeyMaterial {
376 field: "KK",
377 reason: "00b (no SEK provided) is an invalid Key Material message (§3.2.2)",
378 });
379 }
380
381 let keki = be32(bytes, 4);
382
383 let word2 = be32(bytes, 8);
384 let cipher = Cipher::from_bits((word2 >> 24) as u8);
385 let auth = KmAuth::from_bits((word2 >> 16) as u8);
386 let se = StreamEncapsulation::from_bits((word2 >> 8) as u8);
387 let resv2 = (word2 & 0xFF) as u8;
388 if resv2 != RESV2_FIXED {
389 return Err(Error::InvalidKeyMaterial {
390 field: "Resv2",
391 reason: "must be 0",
392 });
393 }
394
395 let word3 = be32(bytes, 12);
396 let resv3 = (word3 >> 16) as u16;
397 let slen4 = ((word3 >> 8) & 0xFF) as usize;
398 let klen4 = (word3 & 0xFF) as usize;
399 if resv3 != RESV3_FIXED {
400 return Err(Error::InvalidKeyMaterial {
401 field: "Resv3",
402 reason: "must be 0",
403 });
404 }
405
406 let slen = slen4 * 4;
407 let klen = klen4 * 4;
408 if !matches!(klen, 16 | 24 | 32) {
409 return Err(Error::InvalidKeyMaterial {
410 field: "KLen",
411 reason: "must be 16, 24, or 32 bytes (AES-128/192/256)",
412 });
413 }
414
415 let mut offset = 16usize;
416 let salt = bytes
417 .get(offset..offset + slen)
418 .ok_or(Error::BufferTooShort(BufferTooShort {
419 need: offset + slen,
420 have: bytes.len(),
421 what: "key material salt",
422 }))?;
423 offset += slen;
424
425 let n = usize::from(kk.key_count());
426 let wrap_len = 8 + n * klen;
427 let wrap = bytes
428 .get(offset..offset + wrap_len)
429 .ok_or(Error::BufferTooShort(BufferTooShort {
430 need: offset + wrap_len,
431 have: bytes.len(),
432 what: "key material wrap field",
433 }))?;
434 offset += wrap_len;
435
436 if offset != bytes.len() {
437 return Err(Error::UnexpectedTrailingBytes {
438 what: "key material message",
439 extra: bytes.len() - offset,
440 });
441 }
442
443 let mut icv = [0u8; 8];
444 icv.copy_from_slice(&wrap[0..8]);
445 let x_sek = &wrap[8..8 + klen];
447 let o_sek = if n == 2 {
448 Some(&wrap[8 + klen..8 + 2 * klen])
449 } else {
450 None
451 };
452
453 Ok(KeyMaterial {
454 kk,
455 keki,
456 cipher,
457 auth,
458 se,
459 salt,
460 icv,
461 x_sek,
462 o_sek,
463 })
464 }
465
466 pub fn serialized_len(&self) -> usize {
468 16 + self.salt.len() + 8 + self.x_sek.len() + self.o_sek.map_or(0, <[u8]>::len)
469 }
470
471 pub fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
473 let len = self.serialized_len();
474 need_out(buf, len)?;
475 if !self.salt.len().is_multiple_of(4) {
476 return Err(Error::InvalidKeyMaterial {
477 field: "Salt",
478 reason: "length must be a whole number of 4-byte words",
479 });
480 }
481 broadcast_common::len::fit_u8(self.salt.len() / 4, "Salt length / 4 (SLen)")?;
486 if !matches!(self.x_sek.len(), 16 | 24 | 32) {
487 return Err(Error::InvalidKeyMaterial {
488 field: "xSEK",
489 reason: "length must be 16, 24, or 32 bytes",
490 });
491 }
492 if self.kk == KmKeyFlag::NoSek {
493 return Err(Error::InvalidKeyMaterial {
494 field: "KK",
495 reason: "00b (no SEK provided) is an invalid Key Material message (§3.2.2)",
496 });
497 }
498 let expects_both = self.kk == KmKeyFlag::Both;
499 match (&self.o_sek, expects_both) {
500 (Some(o), true) if o.len() == self.x_sek.len() => {}
501 (None, false) => {}
502 _ => {
503 return Err(Error::InvalidKeyMaterial {
504 field: "KK/oSEK",
505 reason: "oSEK must be present with the same length as xSEK iff KK is Both",
506 });
507 }
508 }
509
510 let word0 = (u32::from(S_FIXED) << 31)
511 | (u32::from(V_FIXED) << 28)
512 | (u32::from(PT_KEYING_MATERIAL) << 24)
513 | (u32::from(SIGN_FIXED) << 8)
514 | (u32::from(RESV1_FIXED) << 2)
515 | u32::from(self.kk.to_bits());
516 put_be32(buf, 0, word0);
517 put_be32(buf, 4, self.keki);
518 let word2 = (u32::from(self.cipher.to_bits()) << 24)
519 | (u32::from(self.auth.to_bits()) << 16)
520 | (u32::from(self.se.to_bits()) << 8)
521 | u32::from(RESV2_FIXED);
522 put_be32(buf, 8, word2);
523 let slen4 = (self.salt.len() / 4) as u32;
524 let klen4 = (self.x_sek.len() / 4) as u32;
525 let word3 = (u32::from(RESV3_FIXED) << 16) | (slen4 << 8) | klen4;
526 put_be32(buf, 12, word3);
527
528 let mut off = 16;
529 buf[off..off + self.salt.len()].copy_from_slice(self.salt);
530 off += self.salt.len();
531 buf[off..off + 8].copy_from_slice(&self.icv);
532 off += 8;
533 buf[off..off + self.x_sek.len()].copy_from_slice(self.x_sek);
534 off += self.x_sek.len();
535 if let Some(o) = self.o_sek {
536 buf[off..off + o.len()].copy_from_slice(o);
537 off += o.len();
538 }
539 debug_assert_eq!(off, len);
540 Ok(len)
541 }
542}
543
544impl<'a> broadcast_common::Parse<'a> for KeyMaterial<'a> {
545 type Error = crate::Error;
546
547 fn parse(bytes: &'a [u8]) -> core::result::Result<Self, Self::Error> {
548 KeyMaterial::parse(bytes)
549 }
550}
551
552impl broadcast_common::Serialize for KeyMaterial<'_> {
553 type Error = crate::Error;
554
555 fn serialized_len(&self) -> usize {
556 KeyMaterial::serialized_len(self)
557 }
558
559 fn serialize_into(&self, buf: &mut [u8]) -> core::result::Result<usize, Self::Error> {
560 KeyMaterial::serialize_into(self, buf)
561 }
562}
563
564#[cfg(test)]
565mod tests {
566 use super::*;
567
568 fn sample_even_only() -> KeyMaterial<'static> {
569 KeyMaterial {
570 kk: KmKeyFlag::Even,
571 keki: 0,
572 cipher: Cipher::AesCtr,
573 auth: KmAuth::None,
574 se: StreamEncapsulation::MpegTsSrt,
575 salt: &[0xAA; 16],
576 icv: [1, 2, 3, 4, 5, 6, 7, 8],
577 x_sek: &[0xEE; 16],
578 o_sek: None,
579 }
580 }
581
582 #[test]
583 fn round_trips_hand_computed_bytes() {
584 let km = sample_even_only();
585 let mut buf = alloc::vec![0u8; km.serialized_len()];
586 let n = km.serialize_into(&mut buf).unwrap();
587 assert_eq!(n, 16 + 16 + 8 + 16);
588
589 let expected_word0 = (1u32 << 28) | (2u32 << 24) | (0x2029u32 << 8) | 0b01u32;
591 assert_eq!(&buf[0..4], &expected_word0.to_be_bytes());
592 assert_eq!(&buf[12..16], &[0, 0, 4, 4]);
594 assert_eq!(&buf[16..32], &[0xAAu8; 16][..]);
595 assert_eq!(&buf[32..40], &[1, 2, 3, 4, 5, 6, 7, 8]);
596 assert_eq!(&buf[40..56], &[0xEEu8; 16][..]);
597
598 assert_eq!(KeyMaterial::parse(&buf).unwrap(), km);
599 }
600
601 #[test]
602 fn both_keys_round_trip() {
603 let km = KeyMaterial {
604 kk: KmKeyFlag::Both,
605 keki: 7,
606 cipher: Cipher::AesCtr,
607 auth: KmAuth::None,
608 se: StreamEncapsulation::MpegTsSrt,
609 salt: &[0; 16],
610 icv: [0; 8],
611 x_sek: &[1; 24],
612 o_sek: Some(&[2; 24]),
613 };
614 let mut buf = alloc::vec![0u8; km.serialized_len()];
615 km.serialize_into(&mut buf).unwrap();
616 assert_eq!(KeyMaterial::parse(&buf).unwrap(), km);
617 }
618
619 #[test]
620 fn no_salt_round_trips() {
621 let km = KeyMaterial {
622 kk: KmKeyFlag::Odd,
623 keki: 0,
624 cipher: Cipher::None,
625 auth: KmAuth::None,
626 se: StreamEncapsulation::Unspecified,
627 salt: &[],
628 icv: [9; 8],
629 x_sek: &[3; 32],
630 o_sek: None,
631 };
632 let mut buf = alloc::vec![0u8; km.serialized_len()];
633 km.serialize_into(&mut buf).unwrap();
634 assert_eq!(KeyMaterial::parse(&buf).unwrap(), km);
635 }
636
637 #[test]
638 fn bad_signature_errs_without_panic() {
639 let km = sample_even_only();
640 let mut buf = alloc::vec![0u8; km.serialized_len()];
641 km.serialize_into(&mut buf).unwrap();
642 buf[1] = 0x00; assert!(matches!(
644 KeyMaterial::parse(&buf),
645 Err(Error::InvalidKeyMaterial { field: "Sign", .. })
646 ));
647 }
648
649 #[test]
650 fn inconsistent_kk_o_sek_errs() {
651 let mut km = sample_even_only();
652 km.o_sek = Some(&[0xEE; 16]); let mut buf = alloc::vec![0u8; 16 + 16 + 8 + 16 + 16];
654 assert!(matches!(
655 km.serialize_into(&mut buf),
656 Err(Error::InvalidKeyMaterial { .. })
657 ));
658 }
659
660 #[test]
665 fn oversized_salt_length_errors() {
666 let salt = alloc::vec![0xAAu8; 1024];
667 let km = KeyMaterial {
668 kk: KmKeyFlag::Even,
669 keki: 0,
670 cipher: Cipher::AesCtr,
671 auth: KmAuth::None,
672 se: StreamEncapsulation::MpegTsSrt,
673 salt: &salt,
674 icv: [0; 8],
675 x_sek: &[0xEE; 16],
676 o_sek: None,
677 };
678 let mut buf = alloc::vec![0u8; km.serialized_len()];
679 let err = km.serialize_into(&mut buf).unwrap_err();
680 assert!(
681 matches!(err, Error::FieldOverflow(e) if e.max == u64::from(u8::MAX)),
682 "expected FieldOverflow(max=255) for SLen, got {err:?}"
683 );
684 }
685
686 #[test]
689 fn max_salt_length_round_trips() {
690 let salt = alloc::vec![0xAAu8; 1020];
691 let km = KeyMaterial {
692 kk: KmKeyFlag::Even,
693 keki: 0,
694 cipher: Cipher::AesCtr,
695 auth: KmAuth::None,
696 se: StreamEncapsulation::MpegTsSrt,
697 salt: &salt,
698 icv: [0; 8],
699 x_sek: &[0xEE; 16],
700 o_sek: None,
701 };
702 let mut buf = alloc::vec![0u8; km.serialized_len()];
703 km.serialize_into(&mut buf).unwrap();
704 let parsed = KeyMaterial::parse(&buf).unwrap();
705 assert_eq!(parsed.salt, salt.as_slice());
706 }
707
708 #[test]
713 fn kk_no_sek_is_refused_by_parse_and_serialize() {
714 let mut buf = alloc::vec![0u8; sample_even_only().serialized_len()];
715 sample_even_only().serialize_into(&mut buf).unwrap();
716 buf[3] &= !0b11;
719 assert!(matches!(
720 KeyMaterial::parse(&buf),
721 Err(Error::InvalidKeyMaterial { field: "KK", .. })
722 ));
723 let short = &buf[..16 + 16 + 8];
726 assert!(matches!(
727 KeyMaterial::parse(short),
728 Err(Error::InvalidKeyMaterial { field: "KK", .. })
729 ));
730
731 let mut km = sample_even_only();
732 km.kk = KmKeyFlag::NoSek;
733 let mut out = alloc::vec![0u8; km.serialized_len()];
734 assert!(matches!(
735 km.serialize_into(&mut out),
736 Err(Error::InvalidKeyMaterial { field: "KK", .. })
737 ));
738 }
739
740 #[test]
743 fn every_accepted_message_reserializes_byte_identically() {
744 for kk in [KmKeyFlag::Even, KmKeyFlag::Odd, KmKeyFlag::Both] {
745 for klen in [16usize, 24, 32] {
746 let x = alloc::vec![0x5Au8; klen];
747 let o = alloc::vec![0xA5u8; klen];
748 let km = KeyMaterial {
749 kk,
750 keki: 3,
751 cipher: Cipher::AesCtr,
752 auth: KmAuth::None,
753 se: StreamEncapsulation::MpegTsSrt,
754 salt: &[7u8; 16],
755 icv: [9; 8],
756 x_sek: &x,
757 o_sek: (kk == KmKeyFlag::Both).then_some(o.as_slice()),
758 };
759 let mut wire = alloc::vec![0u8; km.serialized_len()];
760 km.serialize_into(&mut wire).unwrap();
761 let parsed = KeyMaterial::parse(&wire).unwrap();
762 let mut again = alloc::vec![0u8; parsed.serialized_len()];
763 parsed.serialize_into(&mut again).unwrap();
764 assert_eq!(again, wire, "kk={kk:?} klen={klen}");
765 }
766 }
767 }
768
769 #[test]
773 fn debug_output_redacts_wrapped_keys() {
774 let km = KeyMaterial {
775 kk: KmKeyFlag::Both,
776 keki: 0,
777 cipher: Cipher::AesCtr,
778 auth: KmAuth::None,
779 se: StreamEncapsulation::MpegTsSrt,
780 salt: &[0xAA; 16],
781 icv: [0xBB; 8],
782 x_sek: &[0xEE; 16],
783 o_sek: Some(&[0xDD; 16]),
784 };
785 for dump in [alloc::format!("{km:?}"), alloc::format!("{km:#?}")] {
786 for needle in ["238", "187", "221", "170", "0xee", "ee,"] {
787 assert!(!dump.contains(needle), "{needle:?} leaked: {dump}");
788 }
789 assert!(
790 dump.contains("x_sek: <redacted, 16 bytes>")
791 || dump.contains("x_sek: <redacted, 16 bytes>,"),
792 "{dump}"
793 );
794 assert!(dump.contains("o_sek: <redacted, 16 bytes>"), "{dump}");
795 }
796 }
797
798 fn needles(bytes: &[u8]) -> alloc::vec::Vec<alloc::string::String> {
802 let head = &bytes[..6];
803 let join = |sep: &str| {
804 head.iter()
805 .map(|b| alloc::format!("{b}"))
806 .collect::<alloc::vec::Vec<_>>()
807 .join(sep)
808 };
809 alloc::vec![
810 join(", "),
811 join(","),
812 head.iter()
813 .map(|b| alloc::format!("{b:x}"))
814 .collect::<alloc::vec::Vec<_>>()
815 .join(", "),
816 head.iter().map(|b| alloc::format!("{b:02x}")).collect(),
817 ]
818 }
819
820 fn distinctive(seed: u8, len: usize) -> alloc::vec::Vec<u8> {
823 let mut x = u32::from(seed)
824 .wrapping_mul(2_654_435_761)
825 .wrapping_add(12_345);
826 (0..len)
827 .map(|_| {
828 x = x.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
829 u8::try_from(x >> 24).unwrap()
830 })
831 .collect()
832 }
833
834 #[test]
837 fn debug_and_serde_output_carry_no_key_bytes() {
838 let salt = distinctive(1, 16);
839 let x = distinctive(2, 32);
840 let o = distinctive(3, 32);
841 let icv: [u8; 8] = distinctive(4, 8).try_into().unwrap();
842 let km = KeyMaterial {
843 kk: KmKeyFlag::Both,
844 keki: 0,
845 cipher: Cipher::AesCtr,
846 auth: KmAuth::None,
847 se: StreamEncapsulation::MpegTsSrt,
848 salt: &salt,
849 icv,
850 x_sek: &x,
851 o_sek: Some(&o),
852 };
853 #[cfg(feature = "serde")]
854 let json: Option<alloc::string::String> = {
855 let json = serde_json::to_string(&km).expect("serialize");
856 assert!(
857 json.contains("kk"),
858 "the non-secret fields are still serialized"
859 );
860 Some(json)
861 };
862 #[cfg(not(feature = "serde"))]
863 let json: Option<alloc::string::String> = None;
864 let dumps: alloc::vec::Vec<alloc::string::String> = [
865 alloc::format!("{km:?}"),
866 alloc::format!("{km:#?}"),
867 alloc::format!("{km:x?}"),
868 ]
869 .into_iter()
870 .chain(json)
871 .collect();
872 for (name, secret) in [
873 ("salt", &salt[..]),
874 ("icv", &icv[..]),
875 ("x_sek", &x[..]),
876 ("o_sek", &o[..]),
877 ] {
878 for needle in needles(secret) {
879 for dump in &dumps {
880 assert!(
881 !dump.contains(&needle),
882 "{name} leaked as {needle:?} in {dump}"
883 );
884 }
885 }
886 }
887 }
888}