1#[cfg(feature = "crypto")]
20use alloc::borrow::Cow;
21use alloc::string::String;
22use alloc::vec;
23use alloc::vec::Vec;
24use broadcast_common::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_common::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; 4],
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; 4]) -> 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
545pub const DEFAULT_MAX_RETRIES: u32 = 12;
550
551pub const DEFAULT_RETRANSMIT_AFTER: Duration = Duration::from_micros(83_333);
554
555impl Default for HandshakeConfig {
556 fn default() -> Self {
557 HandshakeConfig {
558 latency: Duration::from_millis(120),
559 mtu: 1500,
560 max_flow_window_size: 8192,
561 initial_seq_number: 0,
562 srt_version: 0x0105_0000,
563 flags: HandshakeExtensionMessageFlags(
564 crate::packet::handshake::HS_MSG_FLAG_TSBPDSND
565 | crate::packet::handshake::HS_MSG_FLAG_TSBPDRCV
566 | crate::packet::handshake::HS_MSG_FLAG_CRYPT
567 | crate::packet::handshake::HS_MSG_FLAG_TLPKTDROP
568 | crate::packet::handshake::HS_MSG_FLAG_PERIODICNAK
569 | crate::packet::handshake::HS_MSG_FLAG_REXMITFLG,
570 ),
571 encryption_field: EncryptionField::NoEncryption,
572 stream_id: None,
573 group: None,
574 local_ip: [0, 0, 0, 0],
575 retransmit_after: DEFAULT_RETRANSMIT_AFTER,
576 max_retries: DEFAULT_MAX_RETRIES,
577 #[cfg(feature = "crypto")]
578 crypto: None,
579 }
580 }
581}
582
583#[derive(Debug, Clone, PartialEq)]
588#[cfg_attr(feature = "serde", derive(serde::Serialize))]
589#[non_exhaustive]
590pub struct NegotiatedParams {
591 pub version: u32,
594 pub flags: HandshakeExtensionMessageFlags,
597 pub latency: Duration,
602 pub own_socket_id: u32,
604 pub peer_socket_id: u32,
606 pub mtu: u32,
610 pub max_flow_window_size: u32,
615 pub stream_id: Option<String>,
617 pub group: Option<GroupMembershipExtension>,
619 #[cfg(feature = "crypto")]
626 #[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
627 #[cfg_attr(feature = "serde", serde(skip))]
628 pub sek: Option<SecretBytes>,
629 #[cfg(feature = "crypto")]
633 #[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
634 pub salt: Option<[u8; crate::crypto::SALT_LEN]>,
635}
636
637#[derive(Debug, Clone, PartialEq)]
641#[cfg_attr(feature = "serde", derive(serde::Serialize))]
642#[non_exhaustive]
643pub enum HandshakeOutput {
644 Send(Vec<u8>),
647 Connected(NegotiatedParams),
649 Rejected(RejectionReason),
654 TimedOut,
657}
658
659pub(crate) enum RetransmitStep {
661 Idle,
662 Resend(Vec<u8>),
663 TimedOut,
664}
665
666impl RetransmitStep {
667 pub(crate) fn into_outputs(self) -> Vec<HandshakeOutput> {
668 match self {
669 Self::Idle => Vec::new(),
670 Self::Resend(bytes) => vec![HandshakeOutput::Send(bytes)],
671 Self::TimedOut => vec![HandshakeOutput::TimedOut],
672 }
673 }
674}
675
676#[derive(Debug, Default, Clone, Copy)]
680pub(crate) struct WireClock {
681 us: u32,
682}
683
684impl WireClock {
685 pub(crate) fn set(&mut self, elapsed: core::time::Duration) {
686 self.us = crate::arq::duration_to_wire_us(elapsed);
687 }
688
689 pub(crate) fn now(&self) -> u32 {
690 self.us
691 }
692}
693
694#[derive(Debug, Default)]
698pub(crate) struct Retransmit {
699 last_sent: Option<Vec<u8>>,
700 silent: Duration,
701 retries: u32,
702}
703
704impl Retransmit {
705 pub(crate) fn remember(&mut self, bytes: &[u8]) {
706 self.last_sent = Some(bytes.to_vec());
707 }
708
709 pub(crate) fn arm(&mut self, bytes: &[u8]) {
710 self.remember(bytes);
711 self.silent = Duration::ZERO;
712 }
713
714 pub(crate) fn arm_fresh(&mut self, bytes: &[u8]) {
715 self.arm(bytes);
716 self.retries = 0;
717 }
718
719 pub(crate) fn last_sent(&self) -> Option<&[u8]> {
720 self.last_sent.as_deref()
721 }
722
723 pub(crate) fn tick(&mut self, elapsed: Duration, config: &HandshakeConfig) -> RetransmitStep {
728 self.silent = self.silent.saturating_add(elapsed);
729 if self.silent < config.retransmit_after {
730 return RetransmitStep::Idle;
731 }
732 self.silent = Duration::ZERO;
733 self.retries += 1;
734 if self.retries > config.max_retries {
735 return RetransmitStep::TimedOut;
736 }
737 self.last_sent
738 .clone()
739 .map_or(RetransmitStep::Idle, RetransmitStep::Resend)
740 }
741}
742
743pub(crate) fn build_bytes(hp: HandshakePacket<'_>) -> Result<Vec<u8>> {
746 let pkt = ControlPacket::Handshake(hp);
747 let mut buf = alloc::vec![0u8; pkt.serialized_len()];
748 pkt.serialize_into(&mut buf)?;
749 Ok(buf)
750}
751
752pub(crate) fn build_conclusion_extensions<'a>(
756 hs_ext_type: crate::packet::ExtensionType,
757 contents: &'a ConclusionExtensionContents,
758) -> (HandshakeExtensions<'a>, u16) {
759 let mut blocks = alloc::vec![HandshakeExtensionBlock {
760 ext_type: hs_ext_type,
761 contents: &contents.hs_msg,
762 }];
763 let mut ext_flags = HS_EXT_FLAG_HSREQ;
764 if let Some(sid) = contents.stream_id.as_ref() {
765 blocks.push(HandshakeExtensionBlock {
766 ext_type: crate::packet::ExtensionType::Sid,
767 contents: sid,
768 });
769 ext_flags |= HS_EXT_FLAG_CONFIG;
770 }
771 if let Some(group) = contents.group.as_ref() {
772 blocks.push(HandshakeExtensionBlock {
773 ext_type: crate::packet::ExtensionType::Group,
774 contents: group,
775 });
776 ext_flags |= HS_EXT_FLAG_CONFIG;
777 }
778 if let Some((ext_type, km)) = contents.km.as_ref() {
779 blocks.push(HandshakeExtensionBlock {
780 ext_type: *ext_type,
781 contents: km,
782 });
783 ext_flags |= crate::packet::handshake::HS_EXT_FLAG_KMREQ;
784 }
785 (HandshakeExtensions(blocks), ext_flags)
786}
787
788pub(crate) struct ConclusionExtensionContents {
791 hs_msg: Vec<u8>,
792 stream_id: Option<Vec<u8>>,
793 group: Option<Vec<u8>>,
794 km: Option<(crate::packet::ExtensionType, Vec<u8>)>,
795}
796
797impl ConclusionExtensionContents {
798 pub(crate) fn new(
801 hs_msg: HsExtMessage,
802 stream_id: Option<&str>,
803 group: Option<GroupMembershipExtension>,
804 ) -> Self {
805 use crate::packet::handshake::encode_stream_id;
806 ConclusionExtensionContents {
807 hs_msg: Vec::from(hs_msg.to_bytes()),
808 stream_id: stream_id.map(encode_stream_id),
809 group: group.map(|g| Vec::from(g.to_bytes())),
810 km: None,
811 }
812 }
813
814 #[cfg(feature = "crypto")]
817 pub(crate) fn set_key_material(
818 &mut self,
819 ext_type: crate::packet::ExtensionType,
820 contents: Vec<u8>,
821 ) {
822 self.km = Some((ext_type, contents));
823 }
824}
825
826#[derive(Debug, Default)]
830pub(crate) struct ParsedPeerExtensions<'a> {
831 pub hs_msg: Option<HsExtMessage>,
832 pub stream_id: Option<String>,
833 pub group: Option<GroupMembershipExtension>,
834 #[cfg(feature = "crypto")]
841 pub km: Option<KeyMaterial<'a>>,
842 #[cfg(not(feature = "crypto"))]
845 _phantom: core::marker::PhantomData<&'a ()>,
846}
847
848pub(crate) fn parse_peer_extensions<'a>(
853 hp: &HandshakePacket<'a>,
854) -> Result<ParsedPeerExtensions<'a>> {
855 use crate::packet::ExtensionType;
856
857 let mut out = ParsedPeerExtensions::default();
858 for block in hp.extensions.iter() {
859 match block.ext_type {
860 ExtensionType::HsReq | ExtensionType::HsRsp => {
861 let msg = block.as_hs_ext_message().map_err(|_| {
862 Error::InvalidField(InvalidField {
863 field: "handshake extension message",
864 reason: "malformed HSREQ/HSRSP contents",
865 })
866 })?;
867 out.hs_msg = Some(msg);
868 }
869 ExtensionType::Sid => {
870 let sid = block.as_stream_id().map_err(|_| {
871 Error::InvalidField(InvalidField {
872 field: "stream ID extension",
873 reason: "malformed or non-UTF-8 contents",
874 })
875 })?;
876 out.stream_id = Some(sid);
877 }
878 ExtensionType::Group => {
879 let g = block.as_group_membership().map_err(|_| {
880 Error::InvalidField(InvalidField {
881 field: "group membership extension",
882 reason: "malformed contents",
883 })
884 })?;
885 out.group = Some(g);
886 }
887 #[cfg(feature = "crypto")]
888 ExtensionType::KmReq | ExtensionType::KmRsp => {
889 let km = block.as_key_material().map_err(|_| {
890 Error::InvalidField(InvalidField {
891 field: "key material extension",
892 reason: "malformed contents",
893 })
894 })?;
895 out.km = Some(km);
896 }
897 _ => {}
898 }
899 }
900 Ok(out)
901}
902
903#[cfg(feature = "crypto")]
916pub(crate) fn build_key_material_extension(crypto: &CryptoConfig) -> Result<Vec<u8>> {
917 let kek = crate::crypto::derive_kek(&crypto.passphrase, &crypto.salt, crypto.sek.len())?;
918 let (icv, wrapped) = crate::crypto::wrap_sek(&kek, &crypto.sek)?;
919 let km = KeyMaterial {
920 kk: KmKeyFlag::Even,
921 keki: 0,
922 cipher: Cipher::AesCtr,
923 auth: KmAuth::None,
924 se: StreamEncapsulation::MpegTsSrt,
925 salt: &crypto.salt,
926 icv,
927 x_sek: &wrapped,
928 o_sek: None,
929 };
930 let mut buf = alloc::vec![0u8; km.serialized_len()];
931 km.serialize_into(&mut buf)?;
932 crate::packet::handshake::build_extension_block(crate::packet::ExtensionType::KmReq, &buf)
933}
934
935#[cfg(feature = "crypto")]
939pub(crate) fn build_key_material_contents(crypto: &CryptoConfig) -> Result<Vec<u8>> {
940 let block = build_key_material_extension(crypto)?;
941 Ok(block[crate::packet::handshake::HANDSHAKE_EXT_BLOCK_HEADER_LEN..].to_vec())
942}
943
944#[cfg(feature = "crypto")]
948pub(crate) fn echo_key_material_contents<'a>(
949 hp: &'a HandshakePacket<'a>,
950 km: &KeyMaterial<'_>,
951) -> Result<Cow<'a, [u8]>> {
952 for block in hp.extensions.iter() {
953 if matches!(
954 block.ext_type,
955 crate::packet::ExtensionType::KmReq | crate::packet::ExtensionType::KmRsp
956 ) {
957 return Ok(Cow::Borrowed(block.contents));
958 }
959 }
960 let mut contents = alloc::vec![0u8; km.serialized_len()];
961 km.serialize_into(&mut contents)?;
962 Ok(Cow::Owned(contents))
963}
964
965#[cfg(feature = "crypto")]
967pub(crate) type RecoveredSek = (SecretBytes, [u8; crate::crypto::SALT_LEN]);
968
969#[cfg(feature = "crypto")]
981pub(crate) fn recover_sek(
982 passphrase: &[u8],
983 km: &KeyMaterial<'_>,
984 kek_cache: &mut crate::crypto::KekCache,
985) -> Result<RecoveredSek> {
986 if km.salt.len() != crate::crypto::SALT_LEN {
987 return Err(Error::InvalidField(InvalidField {
988 field: "Key Material Salt",
989 reason: "must be 16 bytes (the only Salt length this crate's codec accepts)",
990 }));
991 }
992 let mut salt = [0u8; crate::crypto::SALT_LEN];
993 salt.copy_from_slice(km.salt);
994 let kek = kek_cache.derive(passphrase, &salt, km.x_sek.len())?;
995 let sek = SecretBytes::new(crate::crypto::unwrap_sek(&kek, &km.icv, km.x_sek)?.to_vec());
996 Ok((sek, salt))
997}
998
999#[cfg(all(feature = "crypto", feature = "tokio"))]
1007pub(crate) fn recover_both_seks(
1008 passphrase: &[u8],
1009 km: &KeyMaterial<'_>,
1010 kek_cache: &mut crate::crypto::KekCache,
1011) -> Result<(SecretBytes, SecretBytes, [u8; crate::crypto::SALT_LEN])> {
1012 let Some(o_sek) = km.o_sek.filter(|_| km.kk == KmKeyFlag::Both) else {
1013 return Err(Error::InvalidField(InvalidField {
1014 field: "Key Material KK",
1015 reason: "expected both an even and an odd SEK",
1016 }));
1017 };
1018 if km.salt.len() != crate::crypto::SALT_LEN {
1019 return Err(Error::InvalidField(InvalidField {
1020 field: "Key Material Salt",
1021 reason: "must be 16 bytes (the only Salt length this crate's codec accepts)",
1022 }));
1023 }
1024 let mut salt = [0u8; crate::crypto::SALT_LEN];
1025 salt.copy_from_slice(km.salt);
1026 let kek = kek_cache.derive(passphrase, &salt, km.x_sek.len())?;
1027 let mut wrapped = Vec::with_capacity(km.x_sek.len() + o_sek.len());
1028 wrapped.extend_from_slice(km.x_sek);
1029 wrapped.extend_from_slice(o_sek);
1030 let keys = crate::crypto::unwrap_sek(&kek, &km.icv, &wrapped)?;
1031 let (even, odd) = keys.split_at(km.x_sek.len());
1032 Ok((
1033 SecretBytes::new(even.to_vec()),
1034 SecretBytes::new(odd.to_vec()),
1035 salt,
1036 ))
1037}
1038
1039#[cfg(feature = "crypto")]
1044pub(crate) fn verify_km_echo(crypto: &CryptoConfig, echoed: &KeyMaterial<'_>) -> bool {
1045 let kek = match crate::crypto::derive_kek(&crypto.passphrase, &crypto.salt, crypto.sek.len()) {
1046 Ok(k) => k,
1047 Err(_) => return false,
1048 };
1049 let (icv, wrapped) = match crate::crypto::wrap_sek(&kek, &crypto.sek) {
1050 Ok(v) => v,
1051 Err(_) => return false,
1052 };
1053 let salt = echoed.salt.ct_eq(crypto.salt.as_slice());
1055 let icv = echoed.icv.as_slice().ct_eq(icv.as_slice());
1056 let wrapped = echoed.x_sek.ct_eq(wrapped.as_slice());
1057 bool::from(salt & icv & wrapped)
1058}
1059
1060pub(crate) fn negotiate_latency(local: Duration, peer_msg: &HsExtMessage) -> Duration {
1063 local
1064 .max(peer_msg.receiver_tsbpd_delay)
1065 .max(peer_msg.sender_tsbpd_delay)
1066}
1067
1068fn siphash24(k0: u64, k1: u64, data: &[u8]) -> u64 {
1074 const C_ROUNDS: usize = 2;
1077 const D_ROUNDS: usize = 4;
1078 const INIT_V0: u64 = 0x736f_6d65_7073_6575;
1081 const INIT_V1: u64 = 0x646f_7261_6e64_6f6d;
1082 const INIT_V2: u64 = 0x6c79_6765_6e65_7261;
1083 const INIT_V3: u64 = 0x7465_6462_7974_6573;
1084 const FINALIZATION_XOR: u64 = 0xFF;
1086
1087 let mut v0 = k0 ^ INIT_V0;
1088 let mut v1 = k1 ^ INIT_V1;
1089 let mut v2 = k0 ^ INIT_V2;
1090 let mut v3 = k1 ^ INIT_V3;
1091
1092 fn round(v0: &mut u64, v1: &mut u64, v2: &mut u64, v3: &mut u64) {
1093 *v0 = v0.wrapping_add(*v1);
1094 *v1 = v1.rotate_left(13);
1095 *v1 ^= *v0;
1096 *v0 = v0.rotate_left(32);
1097 *v2 = v2.wrapping_add(*v3);
1098 *v3 = v3.rotate_left(16);
1099 *v3 ^= *v2;
1100 *v0 = v0.wrapping_add(*v3);
1101 *v3 = v3.rotate_left(21);
1102 *v3 ^= *v0;
1103 *v2 = v2.wrapping_add(*v1);
1104 *v1 = v1.rotate_left(17);
1105 *v1 ^= *v2;
1106 *v2 = v2.rotate_left(32);
1107 }
1108
1109 let mut chunks = data.chunks_exact(8);
1110 for chunk in chunks.by_ref() {
1111 let mut word = [0u8; 8];
1112 word.copy_from_slice(chunk);
1113 let m = u64::from_le_bytes(word);
1114 v3 ^= m;
1115 for _ in 0..C_ROUNDS {
1116 round(&mut v0, &mut v1, &mut v2, &mut v3);
1117 }
1118 v0 ^= m;
1119 }
1120 let mut last = [0u8; 8];
1123 let rest = chunks.remainder();
1124 last[..rest.len()].copy_from_slice(rest);
1125 last[7] = u8::try_from(data.len() & 0xFF).unwrap_or(0);
1126 let m = u64::from_le_bytes(last);
1127 v3 ^= m;
1128 for _ in 0..C_ROUNDS {
1129 round(&mut v0, &mut v1, &mut v2, &mut v3);
1130 }
1131 v0 ^= m;
1132 v2 ^= FINALIZATION_XOR;
1133 for _ in 0..D_ROUNDS {
1134 round(&mut v0, &mut v1, &mut v2, &mut v3);
1135 }
1136 v0 ^ v1 ^ v2 ^ v3
1137}
1138
1139pub fn derive_cookie(peer_key: u64, time_bucket: u32, secret: u128) -> u32 {
1156 let mut input = [0u8; 12];
1157 input[..8].copy_from_slice(&peer_key.to_le_bytes());
1158 input[8..].copy_from_slice(&time_bucket.to_le_bytes());
1159 let k0 = u64::try_from(secret & u128::from(u64::MAX)).unwrap_or(0);
1160 let k1 = u64::try_from(secret >> 64).unwrap_or(0);
1161 let digest = siphash24(k0, k1, &input);
1162 u32::try_from(digest & u64::from(u32::MAX)).unwrap_or(0) | 1
1165}
1166
1167const SOCKET_ID_DOMAIN: u8 = 1;
1171const ISN_DOMAIN: u8 = 2;
1172
1173pub fn derive_listener_ids(peer_key: u64, time_bucket: u32, secret: u128) -> (u32, u32) {
1185 let k0 = u64::try_from(secret & u128::from(u64::MAX)).unwrap_or(0);
1186 let k1 = u64::try_from(secret >> 64).unwrap_or(0);
1187 let keyed = |domain: u8| {
1188 let mut input = [0u8; 13];
1189 input[0] = domain;
1190 input[1..9].copy_from_slice(&peer_key.to_le_bytes());
1191 input[9..].copy_from_slice(&time_bucket.to_le_bytes());
1192 u32::try_from(siphash24(k0, k1, &input) & u64::from(u32::MAX)).unwrap_or(0)
1193 };
1194 let socket_id = keyed(SOCKET_ID_DOMAIN) | 1;
1196 let initial_seq = keyed(ISN_DOMAIN) & crate::packet::SEQ_NUMBER_MASK;
1197 (socket_id, initial_seq)
1198}
1199
1200#[cfg(test)]
1201mod tests {
1202 use super::*;
1203
1204 #[test]
1205 fn rejection_reason_round_trips_table_7() {
1206 let all = [
1207 RejectionReason::Unknown,
1208 RejectionReason::System,
1209 RejectionReason::Peer,
1210 RejectionReason::Resource,
1211 RejectionReason::Rogue,
1212 RejectionReason::Backlog,
1213 RejectionReason::Ipe,
1214 RejectionReason::Close,
1215 RejectionReason::Version,
1216 RejectionReason::RdvCookie,
1217 RejectionReason::BadSecret,
1218 RejectionReason::Unsecure,
1219 RejectionReason::MessageApi,
1220 RejectionReason::Congestion,
1221 RejectionReason::Filter,
1222 RejectionReason::Group,
1223 ];
1224 for (i, r) in all.iter().enumerate() {
1225 assert_eq!(r.to_bits(), 1000 + i as u32);
1226 assert_eq!(RejectionReason::from_bits(r.to_bits()), *r);
1227 assert_eq!(
1228 RejectionReason::from_handshake_type(r.to_handshake_type()),
1229 Some(*r)
1230 );
1231 }
1232 }
1233
1234 #[test]
1235 fn non_rejection_handshake_types_are_not_a_rejection() {
1236 for ht in [
1237 HandshakeType::Induction,
1238 HandshakeType::Conclusion,
1239 HandshakeType::Wavehand,
1240 HandshakeType::Agreement,
1241 HandshakeType::Done,
1242 ] {
1243 assert_eq!(RejectionReason::from_handshake_type(ht), None);
1244 }
1245 }
1246
1247 #[test]
1248 fn derive_cookie_is_deterministic_and_nonzero() {
1249 let a = derive_cookie(0x1234_5678_9ABC_DEF0, 12345, 0xDEAD_BEEF);
1250 let b = derive_cookie(0x1234_5678_9ABC_DEF0, 12345, 0xDEAD_BEEF);
1251 assert_eq!(a, b);
1252 assert_ne!(a, 0);
1253 let c = derive_cookie(0x1234_5678_9ABC_DEF1, 12345, 0xDEAD_BEEF);
1254 assert_ne!(a, c);
1255 }
1256
1257 #[test]
1261 fn derive_listener_ids_is_stable_in_range_and_distinct_from_the_cookie() {
1262 let first = derive_listener_ids(0x1234_5678_9ABC_DEF0, 12345, 0xDEAD_BEEF);
1263 let again = derive_listener_ids(0x1234_5678_9ABC_DEF0, 12345, 0xDEAD_BEEF);
1264 assert_eq!(first, again);
1265 let (socket_id, initial_seq) = first;
1266 assert_ne!(socket_id, 0);
1267 assert!(initial_seq <= crate::packet::SEQ_NUMBER_MASK);
1268 assert_ne!(
1269 socket_id,
1270 derive_cookie(0x1234_5678_9ABC_DEF0, 12345, 0xDEAD_BEEF)
1271 );
1272 assert_ne!(
1273 first,
1274 derive_listener_ids(0x1234_5678_9ABC_DEF1, 12345, 0xDEAD_BEEF),
1275 "peer"
1276 );
1277 assert_ne!(
1278 first,
1279 derive_listener_ids(0x1234_5678_9ABC_DEF0, 12346, 0xDEAD_BEEF),
1280 "time bucket"
1281 );
1282 assert_ne!(
1283 first,
1284 derive_listener_ids(0x1234_5678_9ABC_DEF0, 12345, 0xDEAD_BEE0),
1285 "secret"
1286 );
1287 }
1288
1289 #[test]
1293 fn only_the_positive_rejection_range_counts_as_a_rejection() {
1294 let is_rejection =
1295 |v: u32| RejectionReason::from_handshake_type(HandshakeType::from_bits(v)).is_some();
1296 assert!(!is_rejection(0xFFFF_FFFC));
1297 assert!(!is_rejection(0xFFFF_FFFE)); assert!(!is_rejection(REJECTION_CODE_LIMIT));
1299 assert!(!is_rejection(REJECTION_CODE_BASE - 1));
1300 assert!(is_rejection(REJECTION_CODE_BASE));
1301 assert!(is_rejection(REJECTION_CODE_LIMIT - 1));
1302 assert_eq!(
1305 RejectionReason::from_handshake_type(HandshakeType::from_bits(1010)),
1306 Some(RejectionReason::BadSecret)
1307 );
1308 assert_eq!(
1309 RejectionReason::from_handshake_type(HandshakeType::from_bits(1500)),
1310 Some(RejectionReason::Reserved(1500))
1311 );
1312 assert_eq!(
1313 RejectionReason::from_handshake_type(HandshakeType::from_bits(2001)),
1314 Some(RejectionReason::Reserved(2001))
1315 );
1316 }
1317
1318 #[cfg(feature = "crypto")]
1322 #[test]
1323 fn caller_kmreq_declares_the_mpeg_ts_srt_encapsulation() {
1324 let crypto = CryptoConfig {
1325 passphrase: b"0123456789abcdef".to_vec(),
1326 salt: [0x33; crate::crypto::SALT_LEN],
1327 sek: alloc::vec![0x44; 16],
1328 };
1329 let ext = build_key_material_extension(&crypto).unwrap();
1330 let km = KeyMaterial::parse(&ext[4..]).unwrap();
1332 assert_eq!(km.se, StreamEncapsulation::MpegTsSrt);
1333 assert_eq!(km.se.to_bits(), 2);
1334 assert_eq!(ext[4 + 10], 2);
1336 }
1337
1338 #[test]
1341 fn siphash24_matches_the_reference_vector() {
1342 let k0 = u64::from_le_bytes([0, 1, 2, 3, 4, 5, 6, 7]);
1343 let k1 = u64::from_le_bytes([8, 9, 10, 11, 12, 13, 14, 15]);
1344 let input: Vec<u8> = (0u8..15).collect();
1345 assert_eq!(siphash24(k0, k1, &input), 0xa129_ca61_49be_45e5);
1346 assert_eq!(siphash24(k0, k1, &[]), 0x726f_db47_dd0e_0e31);
1348 }
1349
1350 #[test]
1352 fn derive_cookie_depends_on_secret_peer_and_time() {
1353 let base = derive_cookie(1, 2, 3);
1354 assert_ne!(base, derive_cookie(1, 2, 4), "secret");
1355 assert_ne!(base, derive_cookie(9, 2, 3), "peer");
1356 assert_ne!(base, derive_cookie(1, 9, 3), "time bucket");
1357 assert_eq!(base & 1, 1);
1358 assert_eq!(
1362 derive_cookie(0x1234_5678_9ABC_DEF0, 12345, 0xDEAD_BEEF),
1363 0x5905_9ee9
1364 );
1365 assert_eq!(
1366 derive_cookie(
1367 0x1234_5678_9ABC_DEF0,
1368 12345,
1369 0x0123_4567_89AB_CDEF_FEDC_BA98_7654_3210
1370 ),
1371 0xec46_1e0b
1372 );
1373 assert_ne!(
1375 derive_cookie(1, 2, 7),
1376 derive_cookie(1, 2, 7 | (1u128 << 64)),
1377 "the high key half must influence the cookie"
1378 );
1379 }
1380
1381 #[cfg(feature = "crypto")]
1387 fn distinctive(seed: u32, len: usize) -> Vec<u8> {
1388 let mut x = seed.wrapping_mul(2_654_435_761).wrapping_add(12_345);
1389 (0..len)
1390 .map(|_| {
1391 x = x.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
1392 u8::try_from(x >> 24).unwrap()
1393 })
1394 .collect()
1395 }
1396
1397 #[cfg(feature = "crypto")]
1399 fn needles(bytes: &[u8]) -> Vec<String> {
1400 let head = &bytes[..6];
1401 let dec = |sep: &str| {
1402 head.iter()
1403 .map(|b| alloc::format!("{b}"))
1404 .collect::<Vec<_>>()
1405 .join(sep)
1406 };
1407 alloc::vec![
1408 dec(", "),
1409 dec(","),
1410 head.iter()
1411 .map(|b| alloc::format!("{b:x}"))
1412 .collect::<Vec<_>>()
1413 .join(", "),
1414 head.iter().map(|b| alloc::format!("{b:02x}")).collect(),
1415 ]
1416 }
1417
1418 #[cfg(feature = "crypto")]
1419 fn secret_config() -> CryptoConfig {
1420 CryptoConfig {
1421 passphrase: distinctive(1, 15),
1422 salt: distinctive(2, crate::crypto::SALT_LEN).try_into().unwrap(),
1423 sek: distinctive(3, 16),
1424 }
1425 }
1426
1427 #[cfg(feature = "crypto")]
1430 #[test]
1431 fn crypto_config_debug_never_shows_secret_bytes() {
1432 let config = HandshakeConfig {
1433 crypto: Some(secret_config()),
1434 ..HandshakeConfig::default()
1435 };
1436 for dump in [
1437 alloc::format!("{:?}", secret_config()),
1438 alloc::format!("{:#?}", secret_config()),
1439 alloc::format!("{:?}", config),
1440 alloc::format!("{:#?}", config),
1441 alloc::format!("{:x?}", config),
1442 ] {
1443 let secret = secret_config();
1444 for (name, bytes) in [
1445 ("passphrase", &secret.passphrase[..]),
1446 ("salt", &secret.salt[..]),
1447 ("sek", &secret.sek[..]),
1448 ] {
1449 for needle in needles(bytes) {
1450 assert!(
1451 !dump.contains(&needle),
1452 "{name} leaked as {needle:?}: {dump}"
1453 );
1454 }
1455 }
1456 assert!(dump.contains("redacted"), "{dump}");
1457 }
1458 assert!(alloc::format!("{:?}", secret_config()).contains("15 bytes"));
1459 }
1460
1461 #[cfg(feature = "crypto")]
1464 #[test]
1465 fn negotiated_sek_is_redacted_in_debug_and_absent_from_serde() {
1466 let sek_bytes = distinctive(9, 16);
1467 let params = NegotiatedParams {
1468 version: HANDSHAKE_VERSION_5,
1469 flags: HandshakeExtensionMessageFlags(0),
1470 latency: Duration::from_millis(120),
1471 own_socket_id: 1,
1472 peer_socket_id: 2,
1473 mtu: 1500,
1474 max_flow_window_size: 8192,
1475 stream_id: None,
1476 group: None,
1477 sek: Some(SecretBytes::new(sek_bytes.clone())),
1478 salt: Some([0x11; crate::crypto::SALT_LEN]),
1479 };
1480 for dump in [
1481 alloc::format!("{params:?}"),
1482 alloc::format!("{:#?}", HandshakeOutput::Connected(params.clone())),
1483 alloc::format!("{:x?}", HandshakeOutput::Connected(params.clone())),
1484 ] {
1485 for needle in needles(&sek_bytes) {
1486 assert!(!dump.contains(&needle), "SEK leaked as {needle:?}: {dump}");
1487 }
1488 assert!(dump.contains("redacted"), "{dump}");
1489 }
1490 #[cfg(feature = "serde")]
1491 {
1492 let json = serde_json::to_string(¶ms).expect("serialize");
1493 assert!(!json.contains("sek"), "the SEK was serialized: {json}");
1494 for needle in needles(&sek_bytes) {
1495 assert!(!json.contains(&needle), "SEK leaked as {needle:?}: {json}");
1496 }
1497 }
1498 }
1499
1500 #[cfg(feature = "crypto")]
1504 #[test]
1505 fn secrets_compare_correctly_and_wipe_on_zeroize() {
1506 let a = SecretBytes::new(alloc::vec![1, 2, 3, 4]);
1507 assert!(a == SecretBytes::new(alloc::vec![1, 2, 3, 4]));
1508 assert!(a != SecretBytes::new(alloc::vec![1, 2, 3, 5]));
1509 assert!(a != SecretBytes::new(alloc::vec![1, 2, 3]));
1510 assert_eq!(&*a, &[1u8, 2, 3, 4][..]);
1511
1512 let mut sek = SecretBytes::new(alloc::vec![9; 16]);
1513 sek.zeroize();
1514 assert!(sek.is_empty(), "zeroize must clear the key");
1515
1516 let mut config = secret_config();
1517 assert!(config == secret_config());
1518 let mut other = secret_config();
1519 other.sek[0] ^= 1;
1520 assert!(config != other);
1521 config.zeroize();
1522 assert!(config.passphrase.is_empty() && config.sek.is_empty());
1523 assert_eq!(config.salt, [0u8; crate::crypto::SALT_LEN]);
1524 }
1525
1526 #[cfg(feature = "crypto")]
1528 #[test]
1529 fn secret_holders_are_zeroize_on_drop() {
1530 fn assert_zeroize_on_drop<T: zeroize::ZeroizeOnDrop>() {}
1531 assert_zeroize_on_drop::<CryptoConfig>();
1532 assert_zeroize_on_drop::<SecretBytes>();
1533 }
1534}