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