1#[cfg(feature = "crypto")]
20use alloc::borrow::Cow;
21use alloc::string::String;
22use alloc::vec;
23use alloc::vec::Vec;
24use broadcast_core::error::InvalidField;
25use core::time::Duration;
26#[cfg(feature = "crypto")]
27use subtle::ConstantTimeEq;
28#[cfg(feature = "crypto")]
29use zeroize::Zeroize;
30
31use crate::error::{Error, Result};
32use crate::packet::KeyMaterial;
33use crate::packet::handshake::{HS_EXT_FLAG_CONFIG, HS_EXT_FLAG_HSREQ};
34#[cfg(feature = "crypto")]
35use crate::packet::{Cipher, KmAuth, KmKeyFlag, StreamEncapsulation};
36use crate::packet::{
37 ControlPacket, EncryptionField, GroupMembershipExtension, HandshakeExtensionBlock,
38 HandshakeExtensionMessageFlags, HandshakeExtensions, HandshakePacket, HandshakeType,
39 HsExtMessage,
40};
41
42pub const HANDSHAKE_VERSION_4: u32 = 4;
46pub const HANDSHAKE_VERSION_5: u32 = 5;
49
50pub const SRT_MAGIC_CODE: u16 = 0x4A17;
54
55pub const INDUCTION_LEGACY_SOCKET_TYPE: u16 = 2;
62
63pub const REJECTION_CODE_BASE: u32 = 1000;
67
68pub const REJECTION_CODE_LIMIT: u32 = 0x8000_0000;
73
74#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
78#[cfg_attr(feature = "serde", derive(serde::Serialize))]
79#[non_exhaustive]
80pub enum RejectionReason {
81 Unknown,
83 System,
85 Peer,
87 Resource,
89 Rogue,
91 Backlog,
93 Ipe,
95 Close,
97 Version,
99 RdvCookie,
101 BadSecret,
103 Unsecure,
105 MessageApi,
107 Congestion,
109 Filter,
111 Group,
113 Reserved(u32),
115}
116
117impl RejectionReason {
118 pub fn from_bits(v: u32) -> Self {
121 match v {
122 1000 => RejectionReason::Unknown,
123 1001 => RejectionReason::System,
124 1002 => RejectionReason::Peer,
125 1003 => RejectionReason::Resource,
126 1004 => RejectionReason::Rogue,
127 1005 => RejectionReason::Backlog,
128 1006 => RejectionReason::Ipe,
129 1007 => RejectionReason::Close,
130 1008 => RejectionReason::Version,
131 1009 => RejectionReason::RdvCookie,
132 1010 => RejectionReason::BadSecret,
133 1011 => RejectionReason::Unsecure,
134 1012 => RejectionReason::MessageApi,
135 1013 => RejectionReason::Congestion,
136 1014 => RejectionReason::Filter,
137 1015 => RejectionReason::Group,
138 other => RejectionReason::Reserved(other),
139 }
140 }
141
142 pub fn to_bits(self) -> u32 {
144 match self {
145 RejectionReason::Unknown => 1000,
146 RejectionReason::System => 1001,
147 RejectionReason::Peer => 1002,
148 RejectionReason::Resource => 1003,
149 RejectionReason::Rogue => 1004,
150 RejectionReason::Backlog => 1005,
151 RejectionReason::Ipe => 1006,
152 RejectionReason::Close => 1007,
153 RejectionReason::Version => 1008,
154 RejectionReason::RdvCookie => 1009,
155 RejectionReason::BadSecret => 1010,
156 RejectionReason::Unsecure => 1011,
157 RejectionReason::MessageApi => 1012,
158 RejectionReason::Congestion => 1013,
159 RejectionReason::Filter => 1014,
160 RejectionReason::Group => 1015,
161 RejectionReason::Reserved(v) => v,
162 }
163 }
164
165 pub fn name(&self) -> &'static str {
167 match self {
168 RejectionReason::Unknown => "REJ_UNKNOWN",
169 RejectionReason::System => "REJ_SYSTEM",
170 RejectionReason::Peer => "REJ_PEER",
171 RejectionReason::Resource => "REJ_RESOURCE",
172 RejectionReason::Rogue => "REJ_ROGUE",
173 RejectionReason::Backlog => "REJ_BACKLOG",
174 RejectionReason::Ipe => "REJ_IPE",
175 RejectionReason::Close => "REJ_CLOSE",
176 RejectionReason::Version => "REJ_VERSION",
177 RejectionReason::RdvCookie => "REJ_RDVCOOKIE",
178 RejectionReason::BadSecret => "REJ_BADSECRET",
179 RejectionReason::Unsecure => "REJ_UNSECURE",
180 RejectionReason::MessageApi => "REJ_MESSAGEAPI",
181 RejectionReason::Congestion => "REJ_CONGESTION",
182 RejectionReason::Filter => "REJ_FILTER",
183 RejectionReason::Group => "REJ_GROUP",
184 RejectionReason::Reserved(_) => "reserved",
185 }
186 }
187
188 pub fn from_handshake_type(ht: HandshakeType) -> Option<Self> {
197 match ht {
198 HandshakeType::Reserved(v)
199 if (REJECTION_CODE_BASE..REJECTION_CODE_LIMIT).contains(&v) =>
200 {
201 Some(RejectionReason::from_bits(v))
202 }
203 _ => None,
204 }
205 }
206
207 pub fn to_handshake_type(self) -> HandshakeType {
209 HandshakeType::from_bits(self.to_bits())
210 }
211}
212
213broadcast_core::impl_spec_display!(RejectionReason, Reserved);
214
215#[cfg(feature = "crypto")]
235#[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
236#[derive(Clone)]
237#[non_exhaustive]
238pub struct CryptoConfig {
239 pub passphrase: Vec<u8>,
244 pub salt: [u8; crate::crypto::SALT_LEN],
248 pub sek: Vec<u8>,
256}
257
258#[cfg(feature = "crypto")]
259impl core::fmt::Debug for CryptoConfig {
260 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
261 f.debug_struct("CryptoConfig")
262 .field(
263 "passphrase",
264 &format_args!("<redacted, {} bytes>", self.passphrase.len()),
265 )
266 .field(
267 "salt",
268 &format_args!("<redacted, {} bytes>", self.salt.len()),
269 )
270 .field("sek", &format_args!("<redacted, {} bytes>", self.sek.len()))
271 .finish()
272 }
273}
274
275#[cfg(feature = "crypto")]
276impl PartialEq for CryptoConfig {
277 fn eq(&self, other: &Self) -> bool {
279 let passphrase = self
280 .passphrase
281 .as_slice()
282 .ct_eq(other.passphrase.as_slice());
283 let salt = self.salt.as_slice().ct_eq(other.salt.as_slice());
284 let sek = self.sek.as_slice().ct_eq(other.sek.as_slice());
285 bool::from(passphrase & salt & sek)
286 }
287}
288
289#[cfg(feature = "crypto")]
290impl Zeroize for CryptoConfig {
291 fn zeroize(&mut self) {
292 self.passphrase.zeroize();
293 self.salt.zeroize();
294 self.sek.zeroize();
295 }
296}
297
298#[cfg(feature = "crypto")]
299impl Drop for CryptoConfig {
300 fn drop(&mut self) {
301 self.zeroize();
302 }
303}
304
305#[cfg(feature = "crypto")]
306impl zeroize::ZeroizeOnDrop for CryptoConfig {}
307
308#[cfg(feature = "crypto")]
309impl CryptoConfig {
310 #[must_use]
314 pub fn new(passphrase: Vec<u8>, salt: [u8; crate::crypto::SALT_LEN], sek: Vec<u8>) -> Self {
315 Self {
316 passphrase,
317 salt,
318 sek,
319 }
320 }
321}
322
323#[cfg(feature = "crypto")]
330#[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
331#[derive(Clone)]
332pub struct SecretBytes(Vec<u8>);
333
334#[cfg(feature = "crypto")]
335impl SecretBytes {
336 pub fn new(bytes: Vec<u8>) -> Self {
338 SecretBytes(bytes)
339 }
340}
341
342#[cfg(feature = "crypto")]
343impl From<Vec<u8>> for SecretBytes {
344 fn from(bytes: Vec<u8>) -> Self {
345 SecretBytes(bytes)
346 }
347}
348
349#[cfg(feature = "crypto")]
350impl core::ops::Deref for SecretBytes {
351 type Target = [u8];
352 fn deref(&self) -> &[u8] {
353 &self.0
354 }
355}
356
357#[cfg(feature = "crypto")]
358impl core::fmt::Debug for SecretBytes {
359 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
360 write!(f, "SecretBytes(<redacted, {} bytes>)", self.0.len())
361 }
362}
363
364#[cfg(feature = "crypto")]
365impl PartialEq for SecretBytes {
366 fn eq(&self, other: &Self) -> bool {
368 bool::from(self.0.as_slice().ct_eq(other.0.as_slice()))
369 }
370}
371
372#[cfg(feature = "crypto")]
373impl Eq for SecretBytes {}
374
375#[cfg(feature = "crypto")]
376impl Zeroize for SecretBytes {
377 fn zeroize(&mut self) {
378 self.0.zeroize();
379 }
380}
381
382#[cfg(feature = "crypto")]
383impl Drop for SecretBytes {
384 fn drop(&mut self) {
385 self.zeroize();
386 }
387}
388
389#[cfg(feature = "crypto")]
390impl zeroize::ZeroizeOnDrop for SecretBytes {}
391
392#[derive(Debug, Clone, PartialEq)]
396#[non_exhaustive]
397pub struct HandshakeConfig {
398 pub latency: Duration,
403 pub mtu: u32,
405 pub max_flow_window_size: u32,
407 pub initial_seq_number: u32,
411 pub srt_version: u32,
414 pub flags: HandshakeExtensionMessageFlags,
416 pub encryption_field: EncryptionField,
420 pub stream_id: Option<String>,
423 pub group: Option<GroupMembershipExtension>,
426 pub local_ip: [u32; IPV4_ADDR_WORDS],
431 pub retransmit_after: Duration,
437 pub max_retries: u32,
440 #[cfg(feature = "crypto")]
445 #[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
446 pub crypto: Option<CryptoConfig>,
447}
448
449impl HandshakeConfig {
450 #[must_use]
452 pub fn with_latency(mut self, latency: Duration) -> Self {
453 self.latency = latency;
454 self
455 }
456
457 #[must_use]
459 pub fn with_mtu(mut self, mtu: u32) -> Self {
460 self.mtu = mtu;
461 self
462 }
463
464 #[must_use]
466 pub fn with_max_flow_window_size(mut self, max_flow_window_size: u32) -> Self {
467 self.max_flow_window_size = max_flow_window_size;
468 self
469 }
470
471 #[must_use]
473 pub fn with_initial_seq_number(mut self, initial_seq_number: u32) -> Self {
474 self.initial_seq_number = initial_seq_number;
475 self
476 }
477
478 #[must_use]
480 pub fn with_srt_version(mut self, srt_version: u32) -> Self {
481 self.srt_version = srt_version;
482 self
483 }
484
485 #[must_use]
487 pub fn with_flags(mut self, flags: HandshakeExtensionMessageFlags) -> Self {
488 self.flags = flags;
489 self
490 }
491
492 #[must_use]
494 pub fn with_encryption_field(mut self, encryption_field: EncryptionField) -> Self {
495 self.encryption_field = encryption_field;
496 self
497 }
498
499 #[must_use]
501 pub fn with_stream_id(mut self, stream_id: Option<String>) -> Self {
502 self.stream_id = stream_id;
503 self
504 }
505
506 #[must_use]
508 pub fn with_group(mut self, group: Option<GroupMembershipExtension>) -> Self {
509 self.group = group;
510 self
511 }
512
513 #[must_use]
515 pub fn with_local_ip(mut self, local_ip: [u32; IPV4_ADDR_WORDS]) -> Self {
516 self.local_ip = local_ip;
517 self
518 }
519
520 #[must_use]
522 pub fn with_retransmit_after(mut self, retransmit_after: Duration) -> Self {
523 self.retransmit_after = retransmit_after;
524 self
525 }
526
527 #[must_use]
529 pub fn with_max_retries(mut self, max_retries: u32) -> Self {
530 self.max_retries = max_retries;
531 self
532 }
533
534 #[cfg(feature = "crypto")]
536 #[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
537 #[must_use]
538 pub fn with_crypto(mut self, crypto: Option<CryptoConfig>) -> Self {
539 self.crypto = crypto;
540 self
541 }
542}
543
544const SRT_VERSION: u32 = 0x0105_0000;
547
548pub const IPV4_ADDR_WORDS: usize = 4;
550
551impl HandshakeConfig {
552 #[must_use]
557 pub fn new(
558 latency: Duration,
559 mtu: u32,
560 max_flow_window_size: u32,
561 retransmit_after: Duration,
562 max_retries: u32,
563 ) -> Self {
564 HandshakeConfig {
565 latency,
566 mtu,
567 max_flow_window_size,
568 initial_seq_number: 0,
569 srt_version: SRT_VERSION,
570 flags: HandshakeExtensionMessageFlags::new(
571 crate::packet::handshake::HS_MSG_FLAG_TSBPDSND
572 | crate::packet::handshake::HS_MSG_FLAG_TSBPDRCV
573 | crate::packet::handshake::HS_MSG_FLAG_CRYPT
574 | crate::packet::handshake::HS_MSG_FLAG_TLPKTDROP
575 | crate::packet::handshake::HS_MSG_FLAG_PERIODICNAK
576 | crate::packet::handshake::HS_MSG_FLAG_REXMITFLG,
577 ),
578 encryption_field: EncryptionField::NoEncryption,
579 stream_id: None,
580 group: None,
581 local_ip: [0, 0, 0, 0],
582 retransmit_after,
583 max_retries,
584 #[cfg(feature = "crypto")]
585 crypto: None,
586 }
587 }
588}
589
590#[derive(Debug, Clone, PartialEq)]
595#[cfg_attr(feature = "serde", derive(serde::Serialize))]
596#[non_exhaustive]
597pub struct NegotiatedParams {
598 pub version: u32,
601 pub flags: HandshakeExtensionMessageFlags,
604 pub latency: Duration,
609 pub own_socket_id: u32,
611 pub peer_socket_id: u32,
613 pub mtu: u32,
617 pub max_flow_window_size: u32,
622 pub stream_id: Option<String>,
624 pub group: Option<GroupMembershipExtension>,
626 #[cfg(feature = "crypto")]
633 #[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
634 #[cfg_attr(feature = "serde", serde(skip))]
635 pub sek: Option<SecretBytes>,
636 #[cfg(feature = "crypto")]
640 #[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
641 pub salt: Option<[u8; crate::crypto::SALT_LEN]>,
642}
643
644#[derive(Debug, Clone, PartialEq)]
648#[cfg_attr(feature = "serde", derive(serde::Serialize))]
649#[non_exhaustive]
650pub enum HandshakeOutput {
651 Send(Vec<u8>),
654 Connected(NegotiatedParams),
656 Rejected(RejectionReason),
661 TimedOut,
664}
665
666pub(crate) enum RetransmitStep {
668 Idle,
669 Resend(Vec<u8>),
670 TimedOut,
671}
672
673impl RetransmitStep {
674 pub(crate) fn into_outputs(self) -> Vec<HandshakeOutput> {
675 match self {
676 Self::Idle => Vec::new(),
677 Self::Resend(bytes) => vec![HandshakeOutput::Send(bytes)],
678 Self::TimedOut => vec![HandshakeOutput::TimedOut],
679 }
680 }
681}
682
683#[derive(Debug, Default, Clone, Copy)]
687pub(crate) struct WireClock {
688 us: u32,
689}
690
691impl WireClock {
692 pub(crate) fn set(&mut self, elapsed: core::time::Duration) {
693 self.us = crate::arq::duration_to_wire_us(elapsed);
694 }
695
696 pub(crate) fn now(&self) -> u32 {
697 self.us
698 }
699}
700
701#[derive(Debug, Default)]
705pub(crate) struct Retransmit {
706 last_sent: Option<Vec<u8>>,
707 silent: Duration,
708 retries: u32,
709}
710
711impl Retransmit {
712 pub(crate) fn remember(&mut self, bytes: &[u8]) {
713 self.last_sent = Some(bytes.to_vec());
714 }
715
716 pub(crate) fn arm(&mut self, bytes: &[u8]) {
717 self.remember(bytes);
718 self.silent = Duration::ZERO;
719 }
720
721 pub(crate) fn arm_fresh(&mut self, bytes: &[u8]) {
722 self.arm(bytes);
723 self.retries = 0;
724 }
725
726 pub(crate) fn last_sent(&self) -> Option<&[u8]> {
727 self.last_sent.as_deref()
728 }
729
730 pub(crate) fn tick(&mut self, elapsed: Duration, config: &HandshakeConfig) -> RetransmitStep {
735 self.silent = self.silent.saturating_add(elapsed);
736 if self.silent < config.retransmit_after {
737 return RetransmitStep::Idle;
738 }
739 self.silent = Duration::ZERO;
740 self.retries += 1;
741 if self.retries > config.max_retries {
742 return RetransmitStep::TimedOut;
743 }
744 self.last_sent
745 .clone()
746 .map_or(RetransmitStep::Idle, RetransmitStep::Resend)
747 }
748}
749
750pub(crate) fn build_bytes(hp: HandshakePacket<'_>) -> Result<Vec<u8>> {
753 let pkt = ControlPacket::Handshake(hp);
754 let mut buf = alloc::vec![0u8; pkt.serialized_len()];
755 pkt.serialize_into(&mut buf)?;
756 Ok(buf)
757}
758
759pub(crate) fn build_conclusion_extensions<'a>(
763 hs_ext_type: crate::packet::ExtensionType,
764 contents: &'a ConclusionExtensionContents,
765) -> (HandshakeExtensions<'a>, u16) {
766 let mut blocks = alloc::vec![HandshakeExtensionBlock {
767 ext_type: hs_ext_type,
768 contents: &contents.hs_msg,
769 }];
770 let mut ext_flags = HS_EXT_FLAG_HSREQ;
771 if let Some(sid) = contents.stream_id.as_ref() {
772 blocks.push(HandshakeExtensionBlock {
773 ext_type: crate::packet::ExtensionType::Sid,
774 contents: sid,
775 });
776 ext_flags |= HS_EXT_FLAG_CONFIG;
777 }
778 if let Some(group) = contents.group.as_ref() {
779 blocks.push(HandshakeExtensionBlock {
780 ext_type: crate::packet::ExtensionType::Group,
781 contents: group,
782 });
783 ext_flags |= HS_EXT_FLAG_CONFIG;
784 }
785 if let Some((ext_type, km)) = contents.km.as_ref() {
786 blocks.push(HandshakeExtensionBlock {
787 ext_type: *ext_type,
788 contents: km,
789 });
790 ext_flags |= crate::packet::handshake::HS_EXT_FLAG_KMREQ;
791 }
792 (HandshakeExtensions(blocks), ext_flags)
793}
794
795pub(crate) struct ConclusionExtensionContents {
798 hs_msg: Vec<u8>,
799 stream_id: Option<Vec<u8>>,
800 group: Option<Vec<u8>>,
801 km: Option<(crate::packet::ExtensionType, Vec<u8>)>,
802}
803
804impl ConclusionExtensionContents {
805 pub(crate) fn new(
808 hs_msg: HsExtMessage,
809 stream_id: Option<&str>,
810 group: Option<GroupMembershipExtension>,
811 ) -> Self {
812 use crate::packet::handshake::encode_stream_id;
813 ConclusionExtensionContents {
814 hs_msg: Vec::from(hs_msg.to_bytes()),
815 stream_id: stream_id.map(encode_stream_id),
816 group: group.map(|g| Vec::from(g.to_bytes())),
817 km: None,
818 }
819 }
820
821 #[cfg(feature = "crypto")]
824 pub(crate) fn set_key_material(
825 &mut self,
826 ext_type: crate::packet::ExtensionType,
827 contents: Vec<u8>,
828 ) {
829 self.km = Some((ext_type, contents));
830 }
831}
832
833#[derive(Debug, Default)]
837pub(crate) struct ParsedPeerExtensions<'a> {
838 pub hs_msg: Option<HsExtMessage>,
839 pub stream_id: Option<String>,
840 pub group: Option<GroupMembershipExtension>,
841 pub(crate) km: Option<KeyMaterial<'a>>,
848}
849
850pub(crate) fn parse_peer_extensions<'a>(
855 hp: &HandshakePacket<'a>,
856) -> Result<ParsedPeerExtensions<'a>> {
857 use crate::packet::ExtensionType;
858
859 let mut out = ParsedPeerExtensions::default();
860 for block in hp.extensions.iter() {
861 match block.ext_type {
862 ExtensionType::HsReq | ExtensionType::HsRsp => {
863 let msg = block.as_hs_ext_message().map_err(|_| {
864 Error::InvalidField(InvalidField::new(
865 "handshake extension message",
866 "malformed HSREQ/HSRSP contents",
867 ))
868 })?;
869 out.hs_msg = Some(msg);
870 }
871 ExtensionType::Sid => {
872 let sid = block.as_stream_id().map_err(|_| {
873 Error::InvalidField(InvalidField::new(
874 "stream ID extension",
875 "malformed or non-UTF-8 contents",
876 ))
877 })?;
878 out.stream_id = Some(sid);
879 }
880 ExtensionType::Group => {
881 let g = block.as_group_membership().map_err(|_| {
882 Error::InvalidField(InvalidField::new(
883 "group membership extension",
884 "malformed contents",
885 ))
886 })?;
887 out.group = Some(g);
888 }
889 ExtensionType::KmReq | ExtensionType::KmRsp => {
890 let km = block.as_key_material().map_err(|_| {
891 Error::InvalidField(InvalidField::new(
892 "key material extension",
893 "malformed contents",
894 ))
895 })?;
896 out.km = Some(km);
897 }
898 _ => {}
899 }
900 }
901 Ok(out)
902}
903
904#[cfg(feature = "crypto")]
917pub(crate) fn build_key_material_extension(crypto: &CryptoConfig) -> Result<Vec<u8>> {
918 let kek = crate::crypto::derive_kek(&crypto.passphrase, &crypto.salt, crypto.sek.len())?;
919 let (icv, wrapped) = crate::crypto::wrap_sek(&kek, &crypto.sek)?;
920 let km = KeyMaterial {
921 kk: KmKeyFlag::Even,
922 keki: 0,
923 cipher: Cipher::AesCtr,
924 auth: KmAuth::None,
925 se: StreamEncapsulation::MpegTsSrt,
926 salt: &crypto.salt,
927 icv,
928 x_sek: &wrapped,
929 o_sek: None,
930 };
931 let mut buf = alloc::vec![0u8; km.serialized_len()];
932 km.serialize_into(&mut buf)?;
933 crate::packet::handshake::build_extension_block(crate::packet::ExtensionType::KmReq, &buf)
934}
935
936#[cfg(feature = "crypto")]
940pub(crate) fn build_key_material_contents(crypto: &CryptoConfig) -> Result<Vec<u8>> {
941 let block = build_key_material_extension(crypto)?;
942 Ok(block[crate::packet::handshake::HANDSHAKE_EXT_BLOCK_HEADER_LEN..].to_vec())
943}
944
945#[cfg(feature = "crypto")]
949pub(crate) fn echo_key_material_contents<'a>(
950 hp: &'a HandshakePacket<'a>,
951 km: &KeyMaterial<'_>,
952) -> Result<Cow<'a, [u8]>> {
953 for block in hp.extensions.iter() {
954 if matches!(
955 block.ext_type,
956 crate::packet::ExtensionType::KmReq | crate::packet::ExtensionType::KmRsp
957 ) {
958 return Ok(Cow::Borrowed(block.contents));
959 }
960 }
961 let mut contents = alloc::vec![0u8; km.serialized_len()];
962 km.serialize_into(&mut contents)?;
963 Ok(Cow::Owned(contents))
964}
965
966#[cfg(feature = "crypto")]
968pub(crate) type RecoveredSek = (SecretBytes, [u8; crate::crypto::SALT_LEN]);
969
970#[cfg(feature = "crypto")]
982pub(crate) fn recover_sek(
983 passphrase: &[u8],
984 km: &KeyMaterial<'_>,
985 kek_cache: &mut crate::crypto::KekCache,
986) -> Result<RecoveredSek> {
987 if km.salt.len() != crate::crypto::SALT_LEN {
988 return Err(Error::InvalidField(InvalidField::new(
989 "Key Material Salt",
990 "must be 16 bytes (the only Salt length this crate's codec accepts)",
991 )));
992 }
993 let mut salt = [0u8; crate::crypto::SALT_LEN];
994 salt.copy_from_slice(km.salt);
995 let kek = kek_cache.derive(passphrase, &salt, km.x_sek.len())?;
996 let sek = SecretBytes::new(crate::crypto::unwrap_sek(&kek, &km.icv, km.x_sek)?.to_vec());
997 Ok((sek, salt))
998}
999
1000#[cfg(feature = "link")]
1008pub(crate) fn recover_both_seks(
1009 passphrase: &[u8],
1010 km: &KeyMaterial<'_>,
1011 kek_cache: &mut crate::crypto::KekCache,
1012) -> Result<(SecretBytes, SecretBytes, [u8; crate::crypto::SALT_LEN])> {
1013 let Some(o_sek) = km.o_sek.filter(|_| km.kk == KmKeyFlag::Both) else {
1014 return Err(Error::InvalidField(InvalidField::new(
1015 "Key Material KK",
1016 "expected both an even and an odd SEK",
1017 )));
1018 };
1019 if km.salt.len() != crate::crypto::SALT_LEN {
1020 return Err(Error::InvalidField(InvalidField::new(
1021 "Key Material Salt",
1022 "must be 16 bytes (the only Salt length this crate's codec accepts)",
1023 )));
1024 }
1025 let mut salt = [0u8; crate::crypto::SALT_LEN];
1026 salt.copy_from_slice(km.salt);
1027 let kek = kek_cache.derive(passphrase, &salt, km.x_sek.len())?;
1028 let mut wrapped = Vec::with_capacity(km.x_sek.len() + o_sek.len());
1029 wrapped.extend_from_slice(km.x_sek);
1030 wrapped.extend_from_slice(o_sek);
1031 let keys = crate::crypto::unwrap_sek(&kek, &km.icv, &wrapped)?;
1032 let (even, odd) = keys.split_at(km.x_sek.len());
1033 Ok((
1034 SecretBytes::new(even.to_vec()),
1035 SecretBytes::new(odd.to_vec()),
1036 salt,
1037 ))
1038}
1039
1040#[cfg(feature = "crypto")]
1045pub(crate) fn verify_km_echo(crypto: &CryptoConfig, echoed: &KeyMaterial<'_>) -> bool {
1046 let kek = match crate::crypto::derive_kek(&crypto.passphrase, &crypto.salt, crypto.sek.len()) {
1047 Ok(k) => k,
1048 Err(_) => return false,
1049 };
1050 let (icv, wrapped) = match crate::crypto::wrap_sek(&kek, &crypto.sek) {
1051 Ok(v) => v,
1052 Err(_) => return false,
1053 };
1054 let salt = echoed.salt.ct_eq(crypto.salt.as_slice());
1056 let icv = echoed.icv.as_slice().ct_eq(icv.as_slice());
1057 let wrapped = echoed.x_sek.ct_eq(wrapped.as_slice());
1058 bool::from(salt & icv & wrapped)
1059}
1060
1061pub(crate) fn negotiate_latency(local: Duration, peer_msg: &HsExtMessage) -> Duration {
1064 local
1065 .max(peer_msg.receiver_tsbpd_delay)
1066 .max(peer_msg.sender_tsbpd_delay)
1067}
1068
1069#[cfg(test)]
1070mod tests {
1071 use super::*;
1072
1073 #[test]
1074 fn rejection_reason_round_trips_table_7() {
1075 let all = [
1076 RejectionReason::Unknown,
1077 RejectionReason::System,
1078 RejectionReason::Peer,
1079 RejectionReason::Resource,
1080 RejectionReason::Rogue,
1081 RejectionReason::Backlog,
1082 RejectionReason::Ipe,
1083 RejectionReason::Close,
1084 RejectionReason::Version,
1085 RejectionReason::RdvCookie,
1086 RejectionReason::BadSecret,
1087 RejectionReason::Unsecure,
1088 RejectionReason::MessageApi,
1089 RejectionReason::Congestion,
1090 RejectionReason::Filter,
1091 RejectionReason::Group,
1092 ];
1093 for (i, r) in all.iter().enumerate() {
1094 assert_eq!(r.to_bits(), 1000 + i as u32);
1095 assert_eq!(RejectionReason::from_bits(r.to_bits()), *r);
1096 assert_eq!(
1097 RejectionReason::from_handshake_type(r.to_handshake_type()),
1098 Some(*r)
1099 );
1100 }
1101 }
1102
1103 #[test]
1104 fn non_rejection_handshake_types_are_not_a_rejection() {
1105 for ht in [
1106 HandshakeType::Induction,
1107 HandshakeType::Conclusion,
1108 HandshakeType::Wavehand,
1109 HandshakeType::Agreement,
1110 HandshakeType::Done,
1111 ] {
1112 assert_eq!(RejectionReason::from_handshake_type(ht), None);
1113 }
1114 }
1115
1116 #[test]
1120 fn only_the_positive_rejection_range_counts_as_a_rejection() {
1121 let is_rejection =
1122 |v: u32| RejectionReason::from_handshake_type(HandshakeType::from_bits(v)).is_some();
1123 assert!(!is_rejection(0xFFFF_FFFC));
1124 assert!(!is_rejection(0xFFFF_FFFE)); assert!(!is_rejection(REJECTION_CODE_LIMIT));
1126 assert!(!is_rejection(REJECTION_CODE_BASE - 1));
1127 assert!(is_rejection(REJECTION_CODE_BASE));
1128 assert!(is_rejection(REJECTION_CODE_LIMIT - 1));
1129 assert_eq!(
1132 RejectionReason::from_handshake_type(HandshakeType::from_bits(1010)),
1133 Some(RejectionReason::BadSecret)
1134 );
1135 assert_eq!(
1136 RejectionReason::from_handshake_type(HandshakeType::from_bits(1500)),
1137 Some(RejectionReason::Reserved(1500))
1138 );
1139 assert_eq!(
1140 RejectionReason::from_handshake_type(HandshakeType::from_bits(2001)),
1141 Some(RejectionReason::Reserved(2001))
1142 );
1143 }
1144
1145 #[cfg(feature = "crypto")]
1149 #[test]
1150 fn caller_kmreq_declares_the_mpeg_ts_srt_encapsulation() {
1151 let crypto = CryptoConfig {
1152 passphrase: b"0123456789abcdef".to_vec(),
1153 salt: [0x33; crate::crypto::SALT_LEN],
1154 sek: alloc::vec![0x44; 16],
1155 };
1156 let ext = build_key_material_extension(&crypto).unwrap();
1157 let km = KeyMaterial::parse(&ext[4..]).unwrap();
1159 assert_eq!(km.se, StreamEncapsulation::MpegTsSrt);
1160 assert_eq!(km.se.to_bits(), 2);
1161 assert_eq!(ext[4 + 10], 2);
1163 }
1164
1165 #[cfg(feature = "crypto")]
1171 fn distinctive(seed: u32, len: usize) -> Vec<u8> {
1172 let mut x = seed.wrapping_mul(2_654_435_761).wrapping_add(12_345);
1173 (0..len)
1174 .map(|_| {
1175 x = x.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
1176 u8::try_from(x >> 24).unwrap()
1177 })
1178 .collect()
1179 }
1180
1181 #[cfg(feature = "crypto")]
1183 fn needles(bytes: &[u8]) -> Vec<String> {
1184 let head = &bytes[..6];
1185 let dec = |sep: &str| {
1186 head.iter()
1187 .map(|b| alloc::format!("{b}"))
1188 .collect::<Vec<_>>()
1189 .join(sep)
1190 };
1191 alloc::vec![
1192 dec(", "),
1193 dec(","),
1194 head.iter()
1195 .map(|b| alloc::format!("{b:x}"))
1196 .collect::<Vec<_>>()
1197 .join(", "),
1198 head.iter().map(|b| alloc::format!("{b:02x}")).collect(),
1199 ]
1200 }
1201
1202 #[cfg(feature = "crypto")]
1203 fn secret_config() -> CryptoConfig {
1204 CryptoConfig {
1205 passphrase: distinctive(1, 15),
1206 salt: distinctive(2, crate::crypto::SALT_LEN).try_into().unwrap(),
1207 sek: distinctive(3, 16),
1208 }
1209 }
1210
1211 #[cfg(feature = "crypto")]
1214 #[test]
1215 fn crypto_config_debug_never_shows_secret_bytes() {
1216 let config = HandshakeConfig {
1217 crypto: Some(secret_config()),
1218 ..HandshakeConfig::for_profile(broadcast_core::Profile::Server)
1219 };
1220 for dump in [
1221 alloc::format!("{:?}", secret_config()),
1222 alloc::format!("{:#?}", secret_config()),
1223 alloc::format!("{:?}", config),
1224 alloc::format!("{:#?}", config),
1225 alloc::format!("{:x?}", config),
1226 ] {
1227 let secret = secret_config();
1228 for (name, bytes) in [
1229 ("passphrase", &secret.passphrase[..]),
1230 ("salt", &secret.salt[..]),
1231 ("sek", &secret.sek[..]),
1232 ] {
1233 for needle in needles(bytes) {
1234 assert!(
1235 !dump.contains(&needle),
1236 "{name} leaked as {needle:?}: {dump}"
1237 );
1238 }
1239 }
1240 assert!(dump.contains("redacted"), "{dump}");
1241 }
1242 assert!(alloc::format!("{:?}", secret_config()).contains("15 bytes"));
1243 }
1244
1245 #[cfg(feature = "crypto")]
1248 #[test]
1249 fn negotiated_sek_is_redacted_in_debug_and_absent_from_serde() {
1250 let sek_bytes = distinctive(9, 16);
1251 let params = NegotiatedParams {
1252 version: HANDSHAKE_VERSION_5,
1253 flags: HandshakeExtensionMessageFlags::new(0),
1254 latency: Duration::from_millis(120),
1255 own_socket_id: 1,
1256 peer_socket_id: 2,
1257 mtu: 1500,
1258 max_flow_window_size: 8192,
1259 stream_id: None,
1260 group: None,
1261 sek: Some(SecretBytes::new(sek_bytes.clone())),
1262 salt: Some([0x11; crate::crypto::SALT_LEN]),
1263 };
1264 for dump in [
1265 alloc::format!("{params:?}"),
1266 alloc::format!("{:#?}", HandshakeOutput::Connected(params.clone())),
1267 alloc::format!("{:x?}", HandshakeOutput::Connected(params.clone())),
1268 ] {
1269 for needle in needles(&sek_bytes) {
1270 assert!(!dump.contains(&needle), "SEK leaked as {needle:?}: {dump}");
1271 }
1272 assert!(dump.contains("redacted"), "{dump}");
1273 }
1274 #[cfg(feature = "serde")]
1275 {
1276 let json = serde_json::to_string(¶ms).expect("serialize");
1277 assert!(!json.contains("sek"), "the SEK was serialized: {json}");
1278 for needle in needles(&sek_bytes) {
1279 assert!(!json.contains(&needle), "SEK leaked as {needle:?}: {json}");
1280 }
1281 }
1282 }
1283
1284 #[cfg(feature = "crypto")]
1288 #[test]
1289 fn secrets_compare_correctly_and_wipe_on_zeroize() {
1290 let a = SecretBytes::new(alloc::vec![1, 2, 3, 4]);
1291 assert!(a == SecretBytes::new(alloc::vec![1, 2, 3, 4]));
1292 assert!(a != SecretBytes::new(alloc::vec![1, 2, 3, 5]));
1293 assert!(a != SecretBytes::new(alloc::vec![1, 2, 3]));
1294 assert_eq!(&*a, &[1u8, 2, 3, 4][..]);
1295
1296 let mut sek = SecretBytes::new(alloc::vec![9; 16]);
1297 sek.zeroize();
1298 assert!(sek.is_empty(), "zeroize must clear the key");
1299
1300 let mut config = secret_config();
1301 assert!(config == secret_config());
1302 let mut other = secret_config();
1303 other.sek[0] ^= 1;
1304 assert!(config != other);
1305 config.zeroize();
1306 assert!(config.passphrase.is_empty() && config.sek.is_empty());
1307 assert_eq!(config.salt, [0u8; crate::crypto::SALT_LEN]);
1308 }
1309
1310 #[cfg(feature = "crypto")]
1312 #[test]
1313 fn secret_holders_are_zeroize_on_drop() {
1314 fn assert_zeroize_on_drop<T: zeroize::ZeroizeOnDrop>() {}
1315 assert_zeroize_on_drop::<CryptoConfig>();
1316 assert_zeroize_on_drop::<SecretBytes>();
1317 }
1318
1319 #[test]
1320 fn config_builders_store_each_field() {
1321 use crate::packet::HandshakeExtensionMessageFlags;
1322 let flags = HandshakeExtensionMessageFlags::new(0x0000_0023);
1323 let config = HandshakeConfig::for_profile(broadcast_core::Profile::Server)
1324 .with_srt_version(0x0105_0003)
1325 .with_flags(flags)
1326 .with_local_ip([1, 2, 3, 4])
1327 .with_retransmit_after(Duration::from_millis(7))
1328 .with_max_retries(3);
1329 assert_eq!(config.srt_version, 0x0105_0003);
1330 assert_eq!(config.flags, flags);
1331 assert_eq!(config.local_ip, [1, 2, 3, 4]);
1332 assert_eq!(config.retransmit_after, Duration::from_millis(7));
1333 assert_eq!(config.max_retries, 3);
1334 }
1335
1336 fn example_hs_msg() -> HsExtMessage {
1337 HsExtMessage {
1338 srt_version: 0x0105_0000,
1339 srt_flags: crate::packet::HandshakeExtensionMessageFlags::new(0),
1340 receiver_tsbpd_delay: Duration::from_millis(120),
1341 sender_tsbpd_delay: Duration::from_millis(120),
1342 }
1343 }
1344
1345 #[test]
1346 fn conclusion_extension_flags_advertise_a_present_stream_id() {
1347 use crate::packet::handshake::HS_EXT_FLAG_CONFIG;
1348 let contents = ConclusionExtensionContents::new(example_hs_msg(), Some("sid"), None);
1349 let (_, flags) =
1350 build_conclusion_extensions(crate::packet::ExtensionType::HsReq, &contents);
1351 assert_eq!(flags & HS_EXT_FLAG_CONFIG, HS_EXT_FLAG_CONFIG);
1352 }
1353
1354 #[test]
1355 fn conclusion_extension_flags_advertise_a_present_group() {
1356 use crate::packet::handshake::HS_EXT_FLAG_CONFIG;
1357 use crate::packet::{GroupFlags, GroupMembershipExtension, GroupType};
1358 let group = GroupMembershipExtension {
1359 group_id: 7,
1360 group_type: GroupType::from_bits(0),
1361 flags: GroupFlags::new(0),
1362 weight: 0,
1363 };
1364 let contents = ConclusionExtensionContents::new(example_hs_msg(), None, Some(group));
1365 let (_, flags) =
1366 build_conclusion_extensions(crate::packet::ExtensionType::HsReq, &contents);
1367 assert_eq!(flags & HS_EXT_FLAG_CONFIG, HS_EXT_FLAG_CONFIG);
1368 }
1369
1370 #[test]
1371 fn arm_fresh_resets_the_retry_budget_and_the_silence() {
1372 let config = HandshakeConfig::for_profile(broadcast_core::Profile::Server);
1373 let mut retransmit = Retransmit::default();
1374 retransmit.arm_fresh(b"packet");
1375 assert!(matches!(
1376 retransmit.tick(config.retransmit_after - Duration::from_micros(1), &config),
1377 RetransmitStep::Idle
1378 ));
1379 for _ in 0..=config.max_retries {
1380 let _ = retransmit.tick(config.retransmit_after, &config);
1381 }
1382 assert!(matches!(
1383 retransmit.tick(config.retransmit_after, &config),
1384 RetransmitStep::TimedOut
1385 ));
1386 retransmit.arm_fresh(b"packet");
1387 assert!(
1388 matches!(
1389 retransmit.tick(config.retransmit_after, &config),
1390 RetransmitStep::Resend(ref bytes) if bytes.as_slice() == b"packet"
1391 ),
1392 "arm_fresh must restore the retry budget and resend"
1393 );
1394 }
1395
1396 #[test]
1397 fn rejection_reason_labels_match_table_7() {
1398 let cases: &[(RejectionReason, &str)] = &[
1399 (RejectionReason::Unknown, "REJ_UNKNOWN"),
1400 (RejectionReason::System, "REJ_SYSTEM"),
1401 (RejectionReason::Peer, "REJ_PEER"),
1402 (RejectionReason::Resource, "REJ_RESOURCE"),
1403 (RejectionReason::Rogue, "REJ_ROGUE"),
1404 (RejectionReason::Backlog, "REJ_BACKLOG"),
1405 (RejectionReason::Ipe, "REJ_IPE"),
1406 (RejectionReason::Close, "REJ_CLOSE"),
1407 (RejectionReason::Version, "REJ_VERSION"),
1408 (RejectionReason::RdvCookie, "REJ_RDVCOOKIE"),
1409 (RejectionReason::BadSecret, "REJ_BADSECRET"),
1410 (RejectionReason::Unsecure, "REJ_UNSECURE"),
1411 (RejectionReason::MessageApi, "REJ_MESSAGEAPI"),
1412 (RejectionReason::Congestion, "REJ_CONGESTION"),
1413 (RejectionReason::Filter, "REJ_FILTER"),
1414 (RejectionReason::Group, "REJ_GROUP"),
1415 ];
1416 for &(reason, label) in cases {
1417 assert_eq!(reason.name(), label);
1418 }
1419 assert_eq!(RejectionReason::Reserved(1500).name(), "reserved");
1420 }
1421}