1use crate::error::{Error, Result};
26use crate::traits::Table;
27use dvb_common::{Parse, Serialize};
28
29pub const TABLE_ID: u8 = 0x7B;
31pub const PID: u16 = 0x0000;
35
36pub const AUTH_EXTENSION_FIRST: u16 = 0x0000;
38pub const AUTH_EXTENSION_LAST: u16 = 0x00FF;
40pub const CERTIFICATE_COLLECTION_EXTENSION: u16 = 0x0100;
42
43const HEADER_LEN: usize = 8;
46const SECTION_LENGTH_PREFIX: usize = 3;
48const CRC_LEN: usize = 4;
50
51const AUTH_FIXED_PREFIX: usize = 5;
55
56#[derive(Debug, Clone, PartialEq, Eq)]
62#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
63pub struct SectionHashEntry<'a> {
64 pub reference_type: u8,
66 #[cfg_attr(feature = "serde", serde(borrow))]
68 pub reference: &'a [u8],
69 #[cfg_attr(feature = "serde", serde(borrow))]
71 pub hash: &'a [u8],
72}
73
74#[derive(Debug, Clone, PartialEq, Eq)]
76#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
77#[cfg_attr(feature = "serde", serde(bound(deserialize = "'de: 'a")))]
78pub enum ProtectionMessageBody<'a> {
79 AuthenticationMessage {
81 section_hash_algorithm_identifier: u8,
83 section_hash_length: u8,
85 signature_algorithm_identifier: u8,
87 #[cfg_attr(feature = "serde", serde(borrow))]
89 hashes: Vec<SectionHashEntry<'a>>,
90 #[cfg_attr(feature = "serde", serde(borrow))]
92 extension_bytes: &'a [u8],
93 #[cfg_attr(feature = "serde", serde(borrow))]
95 signature_key_identifier: &'a [u8],
96 #[cfg_attr(feature = "serde", serde(borrow))]
98 signature: &'a [u8],
99 },
100 CertificateCollection {
102 #[cfg_attr(feature = "serde", serde(borrow))]
104 certificates: Vec<&'a [u8]>,
105 },
106 Raw(#[cfg_attr(feature = "serde", serde(borrow))] &'a [u8]),
108}
109
110#[derive(Debug, Clone, PartialEq, Eq)]
115#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
116#[cfg_attr(feature = "serde", serde(bound(deserialize = "'de: 'a")))]
117pub struct ProtectionMessageSection<'a> {
118 pub table_id_extension: u16,
121 pub version_number: u8,
123 pub current_next_indicator: bool,
125 pub section_number: u8,
127 pub last_section_number: u8,
129 #[cfg_attr(feature = "serde", serde(borrow))]
131 pub body: ProtectionMessageBody<'a>,
132}
133
134impl<'a> Parse<'a> for ProtectionMessageSection<'a> {
135 type Error = crate::error::Error;
136 fn parse(bytes: &'a [u8]) -> Result<Self> {
137 let min_len = HEADER_LEN + CRC_LEN;
138 if bytes.len() < min_len {
139 return Err(Error::BufferTooShort {
140 need: min_len,
141 have: bytes.len(),
142 what: "ProtectionMessageSection",
143 });
144 }
145 if bytes[0] != TABLE_ID {
146 return Err(Error::UnexpectedTableId {
147 table_id: bytes[0],
148 what: "ProtectionMessageSection",
149 expected: &[TABLE_ID],
150 });
151 }
152 let section_length = (((bytes[1] & 0x0F) as usize) << 8) | bytes[2] as usize;
153 let total = SECTION_LENGTH_PREFIX + section_length;
154 if bytes.len() < total || total < HEADER_LEN + CRC_LEN {
155 return Err(Error::SectionLengthOverflow {
156 declared: section_length,
157 available: bytes.len().saturating_sub(SECTION_LENGTH_PREFIX),
158 });
159 }
160
161 let table_id_extension = u16::from_be_bytes([bytes[3], bytes[4]]);
162 let version_number = (bytes[5] >> 1) & 0x1F;
163 let current_next_indicator = bytes[5] & 0x01 != 0;
164 let section_number = bytes[6];
165 let last_section_number = bytes[7];
166
167 let body_bytes = &bytes[HEADER_LEN..total - CRC_LEN];
168 let body = match table_id_extension {
169 AUTH_EXTENSION_FIRST..=AUTH_EXTENSION_LAST => {
170 parse_authentication_message(body_bytes)?
171 }
172 CERTIFICATE_COLLECTION_EXTENSION => parse_certificate_collection(body_bytes)?,
173 _ => ProtectionMessageBody::Raw(body_bytes),
174 };
175
176 Ok(ProtectionMessageSection {
177 table_id_extension,
178 version_number,
179 current_next_indicator,
180 section_number,
181 last_section_number,
182 body,
183 })
184 }
185}
186
187fn parse_authentication_message(body: &[u8]) -> Result<ProtectionMessageBody<'_>> {
189 if body.len() < AUTH_FIXED_PREFIX {
190 return Err(Error::BufferTooShort {
191 need: AUTH_FIXED_PREFIX,
192 have: body.len(),
193 what: "ProtectionMessageSection::AuthenticationMessage",
194 });
195 }
196 let section_hash_algorithm_identifier = body[0];
197 let section_hash_length = body[1];
198 let signature_algorithm_identifier = body[2];
199 let section_hashes_loop_length = (((body[3] & 0x0F) as usize) << 8) | body[4] as usize;
201
202 let loop_start = AUTH_FIXED_PREFIX;
203 let loop_end = loop_start + section_hashes_loop_length;
204 if loop_end > body.len() {
205 return Err(Error::SectionLengthOverflow {
206 declared: section_hashes_loop_length,
207 available: body.len() - loop_start,
208 });
209 }
210
211 let hash_len = section_hash_length as usize;
212 let mut hashes = Vec::new();
213 let mut pos = loop_start;
214 while pos < loop_end {
215 let lead = body[pos];
217 let reference_type = lead >> 4;
218 let reference_length = (lead & 0x0F) as usize;
219 let ref_start = pos + 1;
220 let ref_end = ref_start + reference_length;
221 let hash_end = ref_end + hash_len;
222 if hash_end > loop_end {
223 return Err(Error::SectionLengthOverflow {
224 declared: reference_length + hash_len,
225 available: loop_end - ref_start,
226 });
227 }
228 hashes.push(SectionHashEntry {
229 reference_type,
230 reference: &body[ref_start..ref_end],
231 hash: &body[ref_end..hash_end],
232 });
233 pos = hash_end;
234 }
235
236 if loop_end >= body.len() {
238 return Err(Error::BufferTooShort {
239 need: loop_end + 1,
240 have: body.len(),
241 what: "ProtectionMessageSection::extension_bytes_length",
242 });
243 }
244 let extension_bytes_length = body[loop_end] as usize;
245 let ext_start = loop_end + 1;
246 let ext_end = ext_start + extension_bytes_length;
247 if ext_end > body.len() {
248 return Err(Error::SectionLengthOverflow {
249 declared: extension_bytes_length,
250 available: body.len() - ext_start,
251 });
252 }
253
254 if ext_end >= body.len() {
256 return Err(Error::BufferTooShort {
257 need: ext_end + 1,
258 have: body.len(),
259 what: "ProtectionMessageSection::signature_key_identifier_length",
260 });
261 }
262 let key_id_length = body[ext_end] as usize;
263 let key_start = ext_end + 1;
264 let key_end = key_start + key_id_length;
265 if key_end > body.len() {
266 return Err(Error::SectionLengthOverflow {
267 declared: key_id_length,
268 available: body.len() - key_start,
269 });
270 }
271
272 let signature = &body[key_end..];
274
275 Ok(ProtectionMessageBody::AuthenticationMessage {
276 section_hash_algorithm_identifier,
277 section_hash_length,
278 signature_algorithm_identifier,
279 hashes,
280 extension_bytes: &body[ext_start..ext_end],
281 signature_key_identifier: &body[key_start..key_end],
282 signature,
283 })
284}
285
286fn parse_certificate_collection(body: &[u8]) -> Result<ProtectionMessageBody<'_>> {
288 if body.is_empty() {
289 return Err(Error::BufferTooShort {
290 need: 1,
291 have: 0,
292 what: "ProtectionMessageSection::CertificateCollection",
293 });
294 }
295 let certificate_count = (body[0] & 0x0F) as usize;
297 let mut certificates = Vec::with_capacity(certificate_count);
298 let mut pos = 1;
299 for _ in 0..certificate_count {
300 if pos + 2 > body.len() {
301 return Err(Error::BufferTooShort {
302 need: pos + 2,
303 have: body.len(),
304 what: "ProtectionMessageSection::certificate_length",
305 });
306 }
307 let certificate_length = (((body[pos] & 0x0F) as usize) << 8) | body[pos + 1] as usize;
309 let cert_start = pos + 2;
310 let cert_end = cert_start + certificate_length;
311 if cert_end > body.len() {
312 return Err(Error::SectionLengthOverflow {
313 declared: certificate_length,
314 available: body.len() - cert_start,
315 });
316 }
317 certificates.push(&body[cert_start..cert_end]);
318 pos = cert_end;
319 }
320 Ok(ProtectionMessageBody::CertificateCollection { certificates })
321}
322
323impl ProtectionMessageBody<'_> {
324 fn body_len(&self) -> usize {
326 match self {
327 ProtectionMessageBody::AuthenticationMessage {
328 hashes,
329 extension_bytes,
330 signature_key_identifier,
331 signature,
332 ..
333 } => {
334 let loop_bytes: usize = hashes
335 .iter()
336 .map(|h| 1 + h.reference.len() + h.hash.len())
337 .sum();
338 AUTH_FIXED_PREFIX
339 + loop_bytes
340 + 1
341 + extension_bytes.len()
342 + 1
343 + signature_key_identifier.len()
344 + signature.len()
345 }
346 ProtectionMessageBody::CertificateCollection { certificates } => {
347 1 + certificates.iter().map(|c| 2 + c.len()).sum::<usize>()
348 }
349 ProtectionMessageBody::Raw(raw) => raw.len(),
350 }
351 }
352
353 fn write_into(&self, buf: &mut [u8]) -> Result<usize> {
357 match self {
358 ProtectionMessageBody::AuthenticationMessage {
359 section_hash_algorithm_identifier,
360 section_hash_length,
361 signature_algorithm_identifier,
362 hashes,
363 extension_bytes,
364 signature_key_identifier,
365 signature,
366 } => {
367 buf[0] = *section_hash_algorithm_identifier;
368 buf[1] = *section_hash_length;
369 buf[2] = *signature_algorithm_identifier;
370 let loop_bytes: usize = hashes
371 .iter()
372 .map(|h| 1 + h.reference.len() + h.hash.len())
373 .sum();
374 if loop_bytes > 0x0FFF {
375 return Err(Error::SectionLengthOverflow {
376 declared: loop_bytes,
377 available: 0x0FFF,
378 });
379 }
380 if extension_bytes.len() > u8::MAX as usize {
381 return Err(Error::SectionLengthOverflow {
382 declared: extension_bytes.len(),
383 available: u8::MAX as usize,
384 });
385 }
386 if signature_key_identifier.len() > u8::MAX as usize {
387 return Err(Error::SectionLengthOverflow {
388 declared: signature_key_identifier.len(),
389 available: u8::MAX as usize,
390 });
391 }
392 buf[3] = 0xF0 | ((loop_bytes >> 8) as u8 & 0x0F);
394 buf[4] = (loop_bytes & 0xFF) as u8;
395 let mut pos = AUTH_FIXED_PREFIX;
396 for h in hashes {
397 if h.reference.len() > 0x0F {
399 return Err(Error::SectionLengthOverflow {
400 declared: h.reference.len(),
401 available: 0x0F,
402 });
403 }
404 buf[pos] = (h.reference_type << 4) | (h.reference.len() as u8 & 0x0F);
405 pos += 1;
406 buf[pos..pos + h.reference.len()].copy_from_slice(h.reference);
407 pos += h.reference.len();
408 buf[pos..pos + h.hash.len()].copy_from_slice(h.hash);
409 pos += h.hash.len();
410 }
411 buf[pos] = extension_bytes.len() as u8;
412 pos += 1;
413 buf[pos..pos + extension_bytes.len()].copy_from_slice(extension_bytes);
414 pos += extension_bytes.len();
415 buf[pos] = signature_key_identifier.len() as u8;
416 pos += 1;
417 buf[pos..pos + signature_key_identifier.len()]
418 .copy_from_slice(signature_key_identifier);
419 pos += signature_key_identifier.len();
420 buf[pos..pos + signature.len()].copy_from_slice(signature);
421 pos += signature.len();
422 Ok(pos)
423 }
424 ProtectionMessageBody::CertificateCollection { certificates } => {
425 if certificates.len() > 0x0F {
427 return Err(Error::SectionLengthOverflow {
428 declared: certificates.len(),
429 available: 0x0F,
430 });
431 }
432 buf[0] = 0xF0 | (certificates.len() as u8 & 0x0F);
434 let mut pos = 1;
435 for c in certificates {
436 if c.len() > 0x0FFF {
438 return Err(Error::SectionLengthOverflow {
439 declared: c.len(),
440 available: 0x0FFF,
441 });
442 }
443 buf[pos] = 0xF0 | ((c.len() >> 8) as u8 & 0x0F);
445 buf[pos + 1] = (c.len() & 0xFF) as u8;
446 pos += 2;
447 buf[pos..pos + c.len()].copy_from_slice(c);
448 pos += c.len();
449 }
450 Ok(pos)
451 }
452 ProtectionMessageBody::Raw(raw) => {
453 buf[..raw.len()].copy_from_slice(raw);
454 Ok(raw.len())
455 }
456 }
457 }
458}
459
460impl Serialize for ProtectionMessageSection<'_> {
461 type Error = crate::error::Error;
462 fn serialized_len(&self) -> usize {
463 HEADER_LEN + self.body.body_len() + CRC_LEN
464 }
465 fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
466 let len = self.serialized_len();
467 if buf.len() < len {
468 return Err(Error::OutputBufferTooSmall {
469 need: len,
470 have: buf.len(),
471 });
472 }
473 let section_length = (len - SECTION_LENGTH_PREFIX) as u16;
474 buf[0] = TABLE_ID;
475 buf[1] = 0xB0 | ((section_length >> 8) as u8 & 0x0F);
477 buf[2] = (section_length & 0xFF) as u8;
478 buf[3..5].copy_from_slice(&self.table_id_extension.to_be_bytes());
479 buf[5] = 0xC0 | ((self.version_number & 0x1F) << 1) | u8::from(self.current_next_indicator);
481 buf[6] = self.section_number;
482 buf[7] = self.last_section_number;
483 let body_written = self.body.write_into(&mut buf[HEADER_LEN..])?;
484 let body_end = HEADER_LEN + body_written;
485 let crc = dvb_common::crc32_mpeg2::compute(&buf[..body_end]);
486 buf[body_end..len].copy_from_slice(&crc.to_be_bytes());
487 Ok(len)
488 }
489}
490
491impl<'a> Table<'a> for ProtectionMessageSection<'a> {
492 const TABLE_ID: u8 = TABLE_ID;
493 const PID: u16 = PID;
494}
495
496#[cfg(test)]
497mod tests {
498 use super::*;
499
500 fn build_section(extension: u16, version: u8, body: &[u8]) -> Vec<u8> {
502 let section_length =
503 (HEADER_LEN - SECTION_LENGTH_PREFIX + body.len() + CRC_LEN) as u16;
504 let mut v = vec![
505 TABLE_ID,
506 0xB0 | ((section_length >> 8) as u8 & 0x0F),
507 (section_length & 0xFF) as u8,
508 (extension >> 8) as u8,
509 (extension & 0xFF) as u8,
510 0xC0 | (version << 1) | 0x01,
511 0x00,
512 0x00,
513 ];
514 v.extend_from_slice(body);
515 v.extend_from_slice(&[0, 0, 0, 0]);
516 v
517 }
518
519 fn auth_body() -> Vec<u8> {
521 let reference = [0x01]; let hash = [0xAA, 0xBB, 0xCC, 0xDD]; let mut hashes_loop = vec![(1u8 << 4) | (reference.len() as u8)]; hashes_loop.extend_from_slice(&reference);
525 hashes_loop.extend_from_slice(&hash);
526 let loop_len = hashes_loop.len();
527
528 let mut b = vec![
529 0x00, hash.len() as u8, 0x01, 0xF0 | ((loop_len >> 8) as u8 & 0x0F), (loop_len & 0xFF) as u8, ];
535 b.extend_from_slice(&hashes_loop);
536 b.push(2);
538 b.extend_from_slice(&[0xDE, 0xAD]);
539 b.push(3);
541 b.extend_from_slice(&[0x11, 0x22, 0x33]);
542 b.extend_from_slice(&[0x90, 0x91, 0x92, 0x93, 0x94, 0x95]);
544 b
545 }
546
547 fn cert_body() -> Vec<u8> {
549 let c0: &[u8] = &[0x30, 0x82, 0x01, 0x02];
550 let c1: &[u8] = &[0xAB, 0xCD];
551 let mut b = vec![0xF0 | 0x02]; b.push(0xF0 | ((c0.len() >> 8) as u8 & 0x0F));
553 b.push((c0.len() & 0xFF) as u8);
554 b.extend_from_slice(c0);
555 b.push(0xF0 | ((c1.len() >> 8) as u8 & 0x0F));
556 b.push((c1.len() & 0xFF) as u8);
557 b.extend_from_slice(c1);
558 b
559 }
560
561 #[test]
562 fn parse_authentication_message() {
563 let bytes = build_section(0x0042, 5, &auth_body());
564 let sec = ProtectionMessageSection::parse(&bytes).unwrap();
565 assert_eq!(sec.table_id_extension, 0x0042);
566 assert_eq!(sec.version_number, 5);
567 assert!(sec.current_next_indicator);
568 match sec.body {
569 ProtectionMessageBody::AuthenticationMessage {
570 section_hash_algorithm_identifier,
571 section_hash_length,
572 signature_algorithm_identifier,
573 hashes,
574 extension_bytes,
575 signature_key_identifier,
576 signature,
577 } => {
578 assert_eq!(section_hash_algorithm_identifier, 0x00);
579 assert_eq!(section_hash_length, 4);
580 assert_eq!(signature_algorithm_identifier, 0x01);
581 assert_eq!(hashes.len(), 1);
582 assert_eq!(hashes[0].reference_type, 1);
583 assert_eq!(hashes[0].reference, &[0x01]);
584 assert_eq!(hashes[0].hash, &[0xAA, 0xBB, 0xCC, 0xDD]);
585 assert_eq!(extension_bytes, &[0xDE, 0xAD]);
586 assert_eq!(signature_key_identifier, &[0x11, 0x22, 0x33]);
587 assert_eq!(signature, &[0x90, 0x91, 0x92, 0x93, 0x94, 0x95]);
588 }
589 other => panic!("expected AuthenticationMessage, got {other:?}"),
590 }
591 }
592
593 #[test]
594 fn parse_certificate_collection() {
595 let bytes = build_section(CERTIFICATE_COLLECTION_EXTENSION, 0, &cert_body());
596 let sec = ProtectionMessageSection::parse(&bytes).unwrap();
597 assert_eq!(sec.table_id_extension, 0x0100);
598 match sec.body {
599 ProtectionMessageBody::CertificateCollection { certificates } => {
600 assert_eq!(certificates.len(), 2);
601 assert_eq!(certificates[0], &[0x30, 0x82, 0x01, 0x02]);
602 assert_eq!(certificates[1], &[0xAB, 0xCD]);
603 }
604 other => panic!("expected CertificateCollection, got {other:?}"),
605 }
606 }
607
608 #[test]
609 fn reserved_extension_kept_raw() {
610 let raw = [0x01, 0x02, 0x03, 0x04];
611 let bytes = build_section(0x0200, 0, &raw);
612 let sec = ProtectionMessageSection::parse(&bytes).unwrap();
613 assert!(matches!(sec.body, ProtectionMessageBody::Raw(b) if b == raw));
614 }
615
616 #[test]
617 fn parse_rejects_wrong_tag() {
618 let mut bytes = build_section(0x0000, 0, &auth_body());
619 bytes[0] = 0x4D;
620 assert!(matches!(
621 ProtectionMessageSection::parse(&bytes).unwrap_err(),
622 Error::UnexpectedTableId { table_id: 0x4D, .. }
623 ));
624 }
625
626 #[test]
627 fn rejects_short_buffer() {
628 assert!(matches!(
629 ProtectionMessageSection::parse(&[0x7B, 0xB0]).unwrap_err(),
630 Error::BufferTooShort {
631 what: "ProtectionMessageSection",
632 ..
633 }
634 ));
635 }
636
637 #[test]
638 fn auth_loop_overflow_rejected() {
639 let mut body = vec![0x00, 0x04, 0x01, 0xF0, 0xFF]; body.extend_from_slice(&[0x00]); let bytes = build_section(0x0000, 0, &body);
643 assert!(matches!(
644 ProtectionMessageSection::parse(&bytes).unwrap_err(),
645 Error::SectionLengthOverflow { .. }
646 ));
647 }
648
649 #[test]
650 fn cert_length_overflow_rejected() {
651 let body = vec![0xF0 | 0x01, 0x00, 0x10, 0x01]; let bytes = build_section(CERTIFICATE_COLLECTION_EXTENSION, 0, &body);
654 assert!(matches!(
655 ProtectionMessageSection::parse(&bytes).unwrap_err(),
656 Error::SectionLengthOverflow { .. }
657 ));
658 }
659
660 #[test]
661 fn round_trip_authentication_message() {
662 let bytes = build_section(0x0042, 7, &auth_body());
663 let sec = ProtectionMessageSection::parse(&bytes).unwrap();
664 let mut buf = vec![0u8; sec.serialized_len()];
665 sec.serialize_into(&mut buf).unwrap();
666 let re = ProtectionMessageSection::parse(&buf).unwrap();
667 assert_eq!(sec, re);
668 }
669
670 #[test]
671 fn round_trip_certificate_collection() {
672 let bytes = build_section(CERTIFICATE_COLLECTION_EXTENSION, 3, &cert_body());
673 let sec = ProtectionMessageSection::parse(&bytes).unwrap();
674 let mut buf = vec![0u8; sec.serialized_len()];
675 sec.serialize_into(&mut buf).unwrap();
676 let re = ProtectionMessageSection::parse(&buf).unwrap();
677 assert_eq!(sec, re);
678 }
679
680 #[test]
681 fn round_trip_raw_reserved() {
682 let bytes = build_section(0xABCD, 1, &[0xDE, 0xAD, 0xBE, 0xEF]);
683 let sec = ProtectionMessageSection::parse(&bytes).unwrap();
684 let mut buf = vec![0u8; sec.serialized_len()];
685 sec.serialize_into(&mut buf).unwrap();
686 let re = ProtectionMessageSection::parse(&buf).unwrap();
687 assert_eq!(sec, re);
688 }
689
690 #[test]
691 fn table_trait_constants() {
692 assert_eq!(<ProtectionMessageSection as Table>::TABLE_ID, 0x7B);
693 assert_eq!(<ProtectionMessageSection as Table>::PID, 0x0000);
694 }
695
696 #[test]
697 #[cfg(feature = "serde")]
698 fn serde_json_round_trip() {
699 let bytes = build_section(0x0042, 5, &auth_body());
700 let sec = ProtectionMessageSection::parse(&bytes).unwrap();
701 let j = serde_json::to_string(&sec).unwrap();
702 let reparsed = ProtectionMessageSection::parse(&bytes).unwrap();
709 assert_eq!(serde_json::to_string(&reparsed).unwrap(), j);
710 assert!(j.contains("\"signature_algorithm_identifier\":1"));
711 }
712}