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(passphrase: &[u8], km: &KeyMaterial<'_>) -> Result<RecoveredSek> {
982 if km.salt.len() != crate::crypto::SALT_LEN {
983 return Err(Error::InvalidField(InvalidField {
984 field: "Key Material Salt",
985 reason: "must be 16 bytes (the only Salt length this crate's codec accepts)",
986 }));
987 }
988 let mut salt = [0u8; crate::crypto::SALT_LEN];
989 salt.copy_from_slice(km.salt);
990 let kek = crate::crypto::derive_kek(passphrase, &salt, km.x_sek.len())?;
991 let sek = SecretBytes::new(crate::crypto::unwrap_sek(&kek, &km.icv, km.x_sek)?.to_vec());
992 Ok((sek, salt))
993}
994
995#[cfg(all(feature = "crypto", feature = "tokio"))]
1003pub(crate) fn recover_both_seks(
1004 passphrase: &[u8],
1005 km: &KeyMaterial<'_>,
1006) -> Result<(SecretBytes, SecretBytes, [u8; crate::crypto::SALT_LEN])> {
1007 let Some(o_sek) = km.o_sek.filter(|_| km.kk == KmKeyFlag::Both) else {
1008 return Err(Error::InvalidField(InvalidField {
1009 field: "Key Material KK",
1010 reason: "expected both an even and an odd SEK",
1011 }));
1012 };
1013 if km.salt.len() != crate::crypto::SALT_LEN {
1014 return Err(Error::InvalidField(InvalidField {
1015 field: "Key Material Salt",
1016 reason: "must be 16 bytes (the only Salt length this crate's codec accepts)",
1017 }));
1018 }
1019 let mut salt = [0u8; crate::crypto::SALT_LEN];
1020 salt.copy_from_slice(km.salt);
1021 let kek = crate::crypto::derive_kek(passphrase, &salt, km.x_sek.len())?;
1022 let mut wrapped = Vec::with_capacity(km.x_sek.len() + o_sek.len());
1023 wrapped.extend_from_slice(km.x_sek);
1024 wrapped.extend_from_slice(o_sek);
1025 let keys = crate::crypto::unwrap_sek(&kek, &km.icv, &wrapped)?;
1026 let (even, odd) = keys.split_at(km.x_sek.len());
1027 Ok((
1028 SecretBytes::new(even.to_vec()),
1029 SecretBytes::new(odd.to_vec()),
1030 salt,
1031 ))
1032}
1033
1034#[cfg(feature = "crypto")]
1039pub(crate) fn verify_km_echo(crypto: &CryptoConfig, echoed: &KeyMaterial<'_>) -> bool {
1040 let kek = match crate::crypto::derive_kek(&crypto.passphrase, &crypto.salt, crypto.sek.len()) {
1041 Ok(k) => k,
1042 Err(_) => return false,
1043 };
1044 let (icv, wrapped) = match crate::crypto::wrap_sek(&kek, &crypto.sek) {
1045 Ok(v) => v,
1046 Err(_) => return false,
1047 };
1048 let salt = echoed.salt.ct_eq(crypto.salt.as_slice());
1050 let icv = echoed.icv.as_slice().ct_eq(icv.as_slice());
1051 let wrapped = echoed.x_sek.ct_eq(wrapped.as_slice());
1052 bool::from(salt & icv & wrapped)
1053}
1054
1055pub(crate) fn negotiate_latency(local: Duration, peer_msg: &HsExtMessage) -> Duration {
1058 local
1059 .max(peer_msg.receiver_tsbpd_delay)
1060 .max(peer_msg.sender_tsbpd_delay)
1061}
1062
1063fn siphash24(k0: u64, k1: u64, data: &[u8]) -> u64 {
1069 const C_ROUNDS: usize = 2;
1072 const D_ROUNDS: usize = 4;
1073 const INIT_V0: u64 = 0x736f_6d65_7073_6575;
1076 const INIT_V1: u64 = 0x646f_7261_6e64_6f6d;
1077 const INIT_V2: u64 = 0x6c79_6765_6e65_7261;
1078 const INIT_V3: u64 = 0x7465_6462_7974_6573;
1079 const FINALIZATION_XOR: u64 = 0xFF;
1081
1082 let mut v0 = k0 ^ INIT_V0;
1083 let mut v1 = k1 ^ INIT_V1;
1084 let mut v2 = k0 ^ INIT_V2;
1085 let mut v3 = k1 ^ INIT_V3;
1086
1087 fn round(v0: &mut u64, v1: &mut u64, v2: &mut u64, v3: &mut u64) {
1088 *v0 = v0.wrapping_add(*v1);
1089 *v1 = v1.rotate_left(13);
1090 *v1 ^= *v0;
1091 *v0 = v0.rotate_left(32);
1092 *v2 = v2.wrapping_add(*v3);
1093 *v3 = v3.rotate_left(16);
1094 *v3 ^= *v2;
1095 *v0 = v0.wrapping_add(*v3);
1096 *v3 = v3.rotate_left(21);
1097 *v3 ^= *v0;
1098 *v2 = v2.wrapping_add(*v1);
1099 *v1 = v1.rotate_left(17);
1100 *v1 ^= *v2;
1101 *v2 = v2.rotate_left(32);
1102 }
1103
1104 let mut chunks = data.chunks_exact(8);
1105 for chunk in chunks.by_ref() {
1106 let mut word = [0u8; 8];
1107 word.copy_from_slice(chunk);
1108 let m = u64::from_le_bytes(word);
1109 v3 ^= m;
1110 for _ in 0..C_ROUNDS {
1111 round(&mut v0, &mut v1, &mut v2, &mut v3);
1112 }
1113 v0 ^= m;
1114 }
1115 let mut last = [0u8; 8];
1118 let rest = chunks.remainder();
1119 last[..rest.len()].copy_from_slice(rest);
1120 last[7] = u8::try_from(data.len() & 0xFF).unwrap_or(0);
1121 let m = u64::from_le_bytes(last);
1122 v3 ^= m;
1123 for _ in 0..C_ROUNDS {
1124 round(&mut v0, &mut v1, &mut v2, &mut v3);
1125 }
1126 v0 ^= m;
1127 v2 ^= FINALIZATION_XOR;
1128 for _ in 0..D_ROUNDS {
1129 round(&mut v0, &mut v1, &mut v2, &mut v3);
1130 }
1131 v0 ^ v1 ^ v2 ^ v3
1132}
1133
1134pub fn derive_cookie(peer_key: u64, time_bucket: u32, secret: u128) -> u32 {
1151 let mut input = [0u8; 12];
1152 input[..8].copy_from_slice(&peer_key.to_le_bytes());
1153 input[8..].copy_from_slice(&time_bucket.to_le_bytes());
1154 let k0 = u64::try_from(secret & u128::from(u64::MAX)).unwrap_or(0);
1155 let k1 = u64::try_from(secret >> 64).unwrap_or(0);
1156 let digest = siphash24(k0, k1, &input);
1157 u32::try_from(digest & u64::from(u32::MAX)).unwrap_or(0) | 1
1160}
1161
1162#[cfg(test)]
1163mod tests {
1164 use super::*;
1165
1166 #[test]
1167 fn rejection_reason_round_trips_table_7() {
1168 let all = [
1169 RejectionReason::Unknown,
1170 RejectionReason::System,
1171 RejectionReason::Peer,
1172 RejectionReason::Resource,
1173 RejectionReason::Rogue,
1174 RejectionReason::Backlog,
1175 RejectionReason::Ipe,
1176 RejectionReason::Close,
1177 RejectionReason::Version,
1178 RejectionReason::RdvCookie,
1179 RejectionReason::BadSecret,
1180 RejectionReason::Unsecure,
1181 RejectionReason::MessageApi,
1182 RejectionReason::Congestion,
1183 RejectionReason::Filter,
1184 RejectionReason::Group,
1185 ];
1186 for (i, r) in all.iter().enumerate() {
1187 assert_eq!(r.to_bits(), 1000 + i as u32);
1188 assert_eq!(RejectionReason::from_bits(r.to_bits()), *r);
1189 assert_eq!(
1190 RejectionReason::from_handshake_type(r.to_handshake_type()),
1191 Some(*r)
1192 );
1193 }
1194 }
1195
1196 #[test]
1197 fn non_rejection_handshake_types_are_not_a_rejection() {
1198 for ht in [
1199 HandshakeType::Induction,
1200 HandshakeType::Conclusion,
1201 HandshakeType::Wavehand,
1202 HandshakeType::Agreement,
1203 HandshakeType::Done,
1204 ] {
1205 assert_eq!(RejectionReason::from_handshake_type(ht), None);
1206 }
1207 }
1208
1209 #[test]
1210 fn derive_cookie_is_deterministic_and_nonzero() {
1211 let a = derive_cookie(0x1234_5678_9ABC_DEF0, 12345, 0xDEAD_BEEF);
1212 let b = derive_cookie(0x1234_5678_9ABC_DEF0, 12345, 0xDEAD_BEEF);
1213 assert_eq!(a, b);
1214 assert_ne!(a, 0);
1215 let c = derive_cookie(0x1234_5678_9ABC_DEF1, 12345, 0xDEAD_BEEF);
1216 assert_ne!(a, c);
1217 }
1218
1219 #[test]
1223 fn only_the_positive_rejection_range_counts_as_a_rejection() {
1224 let is_rejection =
1225 |v: u32| RejectionReason::from_handshake_type(HandshakeType::from_bits(v)).is_some();
1226 assert!(!is_rejection(0xFFFF_FFFC));
1227 assert!(!is_rejection(0xFFFF_FFFE)); assert!(!is_rejection(REJECTION_CODE_LIMIT));
1229 assert!(!is_rejection(REJECTION_CODE_BASE - 1));
1230 assert!(is_rejection(REJECTION_CODE_BASE));
1231 assert!(is_rejection(REJECTION_CODE_LIMIT - 1));
1232 assert_eq!(
1235 RejectionReason::from_handshake_type(HandshakeType::from_bits(1010)),
1236 Some(RejectionReason::BadSecret)
1237 );
1238 assert_eq!(
1239 RejectionReason::from_handshake_type(HandshakeType::from_bits(1500)),
1240 Some(RejectionReason::Reserved(1500))
1241 );
1242 assert_eq!(
1243 RejectionReason::from_handshake_type(HandshakeType::from_bits(2001)),
1244 Some(RejectionReason::Reserved(2001))
1245 );
1246 }
1247
1248 #[cfg(feature = "crypto")]
1252 #[test]
1253 fn caller_kmreq_declares_the_mpeg_ts_srt_encapsulation() {
1254 let crypto = CryptoConfig {
1255 passphrase: b"0123456789abcdef".to_vec(),
1256 salt: [0x33; crate::crypto::SALT_LEN],
1257 sek: alloc::vec![0x44; 16],
1258 };
1259 let ext = build_key_material_extension(&crypto).unwrap();
1260 let km = KeyMaterial::parse(&ext[4..]).unwrap();
1262 assert_eq!(km.se, StreamEncapsulation::MpegTsSrt);
1263 assert_eq!(km.se.to_bits(), 2);
1264 assert_eq!(ext[4 + 10], 2);
1266 }
1267
1268 #[test]
1271 fn siphash24_matches_the_reference_vector() {
1272 let k0 = u64::from_le_bytes([0, 1, 2, 3, 4, 5, 6, 7]);
1273 let k1 = u64::from_le_bytes([8, 9, 10, 11, 12, 13, 14, 15]);
1274 let input: Vec<u8> = (0u8..15).collect();
1275 assert_eq!(siphash24(k0, k1, &input), 0xa129_ca61_49be_45e5);
1276 assert_eq!(siphash24(k0, k1, &[]), 0x726f_db47_dd0e_0e31);
1278 }
1279
1280 #[test]
1282 fn derive_cookie_depends_on_secret_peer_and_time() {
1283 let base = derive_cookie(1, 2, 3);
1284 assert_ne!(base, derive_cookie(1, 2, 4), "secret");
1285 assert_ne!(base, derive_cookie(9, 2, 3), "peer");
1286 assert_ne!(base, derive_cookie(1, 9, 3), "time bucket");
1287 assert_eq!(base & 1, 1);
1288 assert_eq!(
1292 derive_cookie(0x1234_5678_9ABC_DEF0, 12345, 0xDEAD_BEEF),
1293 0x5905_9ee9
1294 );
1295 assert_eq!(
1296 derive_cookie(
1297 0x1234_5678_9ABC_DEF0,
1298 12345,
1299 0x0123_4567_89AB_CDEF_FEDC_BA98_7654_3210
1300 ),
1301 0xec46_1e0b
1302 );
1303 assert_ne!(
1305 derive_cookie(1, 2, 7),
1306 derive_cookie(1, 2, 7 | (1u128 << 64)),
1307 "the high key half must influence the cookie"
1308 );
1309 }
1310
1311 #[cfg(feature = "crypto")]
1317 fn distinctive(seed: u32, len: usize) -> Vec<u8> {
1318 let mut x = seed.wrapping_mul(2_654_435_761).wrapping_add(12_345);
1319 (0..len)
1320 .map(|_| {
1321 x = x.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
1322 u8::try_from(x >> 24).unwrap()
1323 })
1324 .collect()
1325 }
1326
1327 #[cfg(feature = "crypto")]
1329 fn needles(bytes: &[u8]) -> Vec<String> {
1330 let head = &bytes[..6];
1331 let dec = |sep: &str| {
1332 head.iter()
1333 .map(|b| alloc::format!("{b}"))
1334 .collect::<Vec<_>>()
1335 .join(sep)
1336 };
1337 alloc::vec![
1338 dec(", "),
1339 dec(","),
1340 head.iter()
1341 .map(|b| alloc::format!("{b:x}"))
1342 .collect::<Vec<_>>()
1343 .join(", "),
1344 head.iter().map(|b| alloc::format!("{b:02x}")).collect(),
1345 ]
1346 }
1347
1348 #[cfg(feature = "crypto")]
1349 fn secret_config() -> CryptoConfig {
1350 CryptoConfig {
1351 passphrase: distinctive(1, 15),
1352 salt: distinctive(2, crate::crypto::SALT_LEN).try_into().unwrap(),
1353 sek: distinctive(3, 16),
1354 }
1355 }
1356
1357 #[cfg(feature = "crypto")]
1360 #[test]
1361 fn crypto_config_debug_never_shows_secret_bytes() {
1362 let config = HandshakeConfig {
1363 crypto: Some(secret_config()),
1364 ..HandshakeConfig::default()
1365 };
1366 for dump in [
1367 alloc::format!("{:?}", secret_config()),
1368 alloc::format!("{:#?}", secret_config()),
1369 alloc::format!("{:?}", config),
1370 alloc::format!("{:#?}", config),
1371 alloc::format!("{:x?}", config),
1372 ] {
1373 let secret = secret_config();
1374 for (name, bytes) in [
1375 ("passphrase", &secret.passphrase[..]),
1376 ("salt", &secret.salt[..]),
1377 ("sek", &secret.sek[..]),
1378 ] {
1379 for needle in needles(bytes) {
1380 assert!(
1381 !dump.contains(&needle),
1382 "{name} leaked as {needle:?}: {dump}"
1383 );
1384 }
1385 }
1386 assert!(dump.contains("redacted"), "{dump}");
1387 }
1388 assert!(alloc::format!("{:?}", secret_config()).contains("15 bytes"));
1389 }
1390
1391 #[cfg(feature = "crypto")]
1394 #[test]
1395 fn negotiated_sek_is_redacted_in_debug_and_absent_from_serde() {
1396 let sek_bytes = distinctive(9, 16);
1397 let params = NegotiatedParams {
1398 version: HANDSHAKE_VERSION_5,
1399 flags: HandshakeExtensionMessageFlags(0),
1400 latency: Duration::from_millis(120),
1401 own_socket_id: 1,
1402 peer_socket_id: 2,
1403 mtu: 1500,
1404 max_flow_window_size: 8192,
1405 stream_id: None,
1406 group: None,
1407 sek: Some(SecretBytes::new(sek_bytes.clone())),
1408 salt: Some([0x11; crate::crypto::SALT_LEN]),
1409 };
1410 for dump in [
1411 alloc::format!("{params:?}"),
1412 alloc::format!("{:#?}", HandshakeOutput::Connected(params.clone())),
1413 alloc::format!("{:x?}", HandshakeOutput::Connected(params.clone())),
1414 ] {
1415 for needle in needles(&sek_bytes) {
1416 assert!(!dump.contains(&needle), "SEK leaked as {needle:?}: {dump}");
1417 }
1418 assert!(dump.contains("redacted"), "{dump}");
1419 }
1420 #[cfg(feature = "serde")]
1421 {
1422 let json = serde_json::to_string(¶ms).expect("serialize");
1423 assert!(!json.contains("sek"), "the SEK was serialized: {json}");
1424 for needle in needles(&sek_bytes) {
1425 assert!(!json.contains(&needle), "SEK leaked as {needle:?}: {json}");
1426 }
1427 }
1428 }
1429
1430 #[cfg(feature = "crypto")]
1434 #[test]
1435 fn secrets_compare_correctly_and_wipe_on_zeroize() {
1436 let a = SecretBytes::new(alloc::vec![1, 2, 3, 4]);
1437 assert!(a == SecretBytes::new(alloc::vec![1, 2, 3, 4]));
1438 assert!(a != SecretBytes::new(alloc::vec![1, 2, 3, 5]));
1439 assert!(a != SecretBytes::new(alloc::vec![1, 2, 3]));
1440 assert_eq!(&*a, &[1u8, 2, 3, 4][..]);
1441
1442 let mut sek = SecretBytes::new(alloc::vec![9; 16]);
1443 sek.zeroize();
1444 assert!(sek.is_empty(), "zeroize must clear the key");
1445
1446 let mut config = secret_config();
1447 assert!(config == secret_config());
1448 let mut other = secret_config();
1449 other.sek[0] ^= 1;
1450 assert!(config != other);
1451 config.zeroize();
1452 assert!(config.passphrase.is_empty() && config.sek.is_empty());
1453 assert_eq!(config.salt, [0u8; crate::crypto::SALT_LEN]);
1454 }
1455
1456 #[cfg(feature = "crypto")]
1458 #[test]
1459 fn secret_holders_are_zeroize_on_drop() {
1460 fn assert_zeroize_on_drop<T: zeroize::ZeroizeOnDrop>() {}
1461 assert_zeroize_on_drop::<CryptoConfig>();
1462 assert_zeroize_on_drop::<SecretBytes>();
1463 }
1464}