1use alloc::string::String;
20use alloc::vec;
21use alloc::vec::Vec;
22use broadcast_common::error::InvalidField;
23#[cfg(feature = "crypto")]
24use subtle::ConstantTimeEq;
25#[cfg(feature = "crypto")]
26use zeroize::Zeroize;
27
28use crate::error::{Error, Result};
29#[cfg(feature = "crypto")]
30use crate::packet::KeyMaterial;
31use crate::packet::handshake::{HS_EXT_FLAG_CONFIG, HS_EXT_FLAG_HSREQ};
32#[cfg(feature = "crypto")]
33use crate::packet::{Cipher, KmAuth, KmKeyFlag, StreamEncapsulation};
34use crate::packet::{
35 ControlPacket, EncryptionField, GroupMembershipExtension, HandshakeExtensionMessageFlags,
36 HandshakePacket, HandshakeType, HsExtMessage,
37};
38
39pub const HANDSHAKE_VERSION_4: u32 = 4;
43pub const HANDSHAKE_VERSION_5: u32 = 5;
46
47pub const SRT_MAGIC_CODE: u16 = 0x4A17;
51
52pub const INDUCTION_LEGACY_SOCKET_TYPE: u16 = 2;
59
60pub const REJECTION_CODE_BASE: u32 = 1000;
64
65pub const REJECTION_CODE_LIMIT: u32 = 0x8000_0000;
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
75#[cfg_attr(feature = "serde", derive(serde::Serialize))]
76#[non_exhaustive]
77pub enum RejectionReason {
78 Unknown,
80 System,
82 Peer,
84 Resource,
86 Rogue,
88 Backlog,
90 Ipe,
92 Close,
94 Version,
96 RdvCookie,
98 BadSecret,
100 Unsecure,
102 MessageApi,
104 Congestion,
106 Filter,
108 Group,
110 Reserved(u32),
112}
113
114impl RejectionReason {
115 pub fn from_bits(v: u32) -> Self {
118 match v {
119 1000 => RejectionReason::Unknown,
120 1001 => RejectionReason::System,
121 1002 => RejectionReason::Peer,
122 1003 => RejectionReason::Resource,
123 1004 => RejectionReason::Rogue,
124 1005 => RejectionReason::Backlog,
125 1006 => RejectionReason::Ipe,
126 1007 => RejectionReason::Close,
127 1008 => RejectionReason::Version,
128 1009 => RejectionReason::RdvCookie,
129 1010 => RejectionReason::BadSecret,
130 1011 => RejectionReason::Unsecure,
131 1012 => RejectionReason::MessageApi,
132 1013 => RejectionReason::Congestion,
133 1014 => RejectionReason::Filter,
134 1015 => RejectionReason::Group,
135 other => RejectionReason::Reserved(other),
136 }
137 }
138
139 pub fn to_bits(self) -> u32 {
141 match self {
142 RejectionReason::Unknown => 1000,
143 RejectionReason::System => 1001,
144 RejectionReason::Peer => 1002,
145 RejectionReason::Resource => 1003,
146 RejectionReason::Rogue => 1004,
147 RejectionReason::Backlog => 1005,
148 RejectionReason::Ipe => 1006,
149 RejectionReason::Close => 1007,
150 RejectionReason::Version => 1008,
151 RejectionReason::RdvCookie => 1009,
152 RejectionReason::BadSecret => 1010,
153 RejectionReason::Unsecure => 1011,
154 RejectionReason::MessageApi => 1012,
155 RejectionReason::Congestion => 1013,
156 RejectionReason::Filter => 1014,
157 RejectionReason::Group => 1015,
158 RejectionReason::Reserved(v) => v,
159 }
160 }
161
162 pub fn name(&self) -> &'static str {
164 match self {
165 RejectionReason::Unknown => "REJ_UNKNOWN",
166 RejectionReason::System => "REJ_SYSTEM",
167 RejectionReason::Peer => "REJ_PEER",
168 RejectionReason::Resource => "REJ_RESOURCE",
169 RejectionReason::Rogue => "REJ_ROGUE",
170 RejectionReason::Backlog => "REJ_BACKLOG",
171 RejectionReason::Ipe => "REJ_IPE",
172 RejectionReason::Close => "REJ_CLOSE",
173 RejectionReason::Version => "REJ_VERSION",
174 RejectionReason::RdvCookie => "REJ_RDVCOOKIE",
175 RejectionReason::BadSecret => "REJ_BADSECRET",
176 RejectionReason::Unsecure => "REJ_UNSECURE",
177 RejectionReason::MessageApi => "REJ_MESSAGEAPI",
178 RejectionReason::Congestion => "REJ_CONGESTION",
179 RejectionReason::Filter => "REJ_FILTER",
180 RejectionReason::Group => "REJ_GROUP",
181 RejectionReason::Reserved(_) => "reserved",
182 }
183 }
184
185 pub fn from_handshake_type(ht: HandshakeType) -> Option<Self> {
194 match ht {
195 HandshakeType::Reserved(v)
196 if (REJECTION_CODE_BASE..REJECTION_CODE_LIMIT).contains(&v) =>
197 {
198 Some(RejectionReason::from_bits(v))
199 }
200 _ => None,
201 }
202 }
203
204 pub fn to_handshake_type(self) -> HandshakeType {
206 HandshakeType::from_bits(self.to_bits())
207 }
208}
209
210broadcast_common::impl_spec_display!(RejectionReason, Reserved);
211
212#[cfg(feature = "crypto")]
232#[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
233#[derive(Clone)]
234pub struct CryptoConfig {
235 pub passphrase: Vec<u8>,
240 pub salt: [u8; crate::crypto::SALT_LEN],
244 pub sek: Vec<u8>,
252}
253
254#[cfg(feature = "crypto")]
255impl core::fmt::Debug for CryptoConfig {
256 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
257 f.debug_struct("CryptoConfig")
258 .field(
259 "passphrase",
260 &format_args!("<redacted, {} bytes>", self.passphrase.len()),
261 )
262 .field(
263 "salt",
264 &format_args!("<redacted, {} bytes>", self.salt.len()),
265 )
266 .field("sek", &format_args!("<redacted, {} bytes>", self.sek.len()))
267 .finish()
268 }
269}
270
271#[cfg(feature = "crypto")]
272impl PartialEq for CryptoConfig {
273 fn eq(&self, other: &Self) -> bool {
275 let passphrase = self
276 .passphrase
277 .as_slice()
278 .ct_eq(other.passphrase.as_slice());
279 let salt = self.salt.as_slice().ct_eq(other.salt.as_slice());
280 let sek = self.sek.as_slice().ct_eq(other.sek.as_slice());
281 bool::from(passphrase & salt & sek)
282 }
283}
284
285#[cfg(feature = "crypto")]
286impl Zeroize for CryptoConfig {
287 fn zeroize(&mut self) {
288 self.passphrase.zeroize();
289 self.salt.zeroize();
290 self.sek.zeroize();
291 }
292}
293
294#[cfg(feature = "crypto")]
295impl Drop for CryptoConfig {
296 fn drop(&mut self) {
297 self.zeroize();
298 }
299}
300
301#[cfg(feature = "crypto")]
302impl zeroize::ZeroizeOnDrop for CryptoConfig {}
303
304#[cfg(feature = "crypto")]
311#[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
312#[derive(Clone)]
313pub struct SecretBytes(Vec<u8>);
314
315#[cfg(feature = "crypto")]
316impl SecretBytes {
317 pub fn new(bytes: Vec<u8>) -> Self {
319 SecretBytes(bytes)
320 }
321}
322
323#[cfg(feature = "crypto")]
324impl From<Vec<u8>> for SecretBytes {
325 fn from(bytes: Vec<u8>) -> Self {
326 SecretBytes(bytes)
327 }
328}
329
330#[cfg(feature = "crypto")]
331impl core::ops::Deref for SecretBytes {
332 type Target = [u8];
333 fn deref(&self) -> &[u8] {
334 &self.0
335 }
336}
337
338#[cfg(feature = "crypto")]
339impl core::fmt::Debug for SecretBytes {
340 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
341 write!(f, "SecretBytes(<redacted, {} bytes>)", self.0.len())
342 }
343}
344
345#[cfg(feature = "crypto")]
346impl PartialEq for SecretBytes {
347 fn eq(&self, other: &Self) -> bool {
349 bool::from(self.0.as_slice().ct_eq(other.0.as_slice()))
350 }
351}
352
353#[cfg(feature = "crypto")]
354impl Eq for SecretBytes {}
355
356#[cfg(feature = "crypto")]
357impl Zeroize for SecretBytes {
358 fn zeroize(&mut self) {
359 self.0.zeroize();
360 }
361}
362
363#[cfg(feature = "crypto")]
364impl Drop for SecretBytes {
365 fn drop(&mut self) {
366 self.zeroize();
367 }
368}
369
370#[cfg(feature = "crypto")]
371impl zeroize::ZeroizeOnDrop for SecretBytes {}
372
373#[derive(Debug, Clone, PartialEq)]
377#[non_exhaustive]
378pub struct HandshakeConfig {
379 pub latency_ms: u16,
384 pub mtu: u32,
386 pub max_flow_window_size: u32,
388 pub initial_seq_number: u32,
392 pub srt_version: u32,
395 pub flags: HandshakeExtensionMessageFlags,
397 pub encryption_field: EncryptionField,
401 pub stream_id: Option<String>,
404 pub group: Option<GroupMembershipExtension>,
407 pub local_ip: [u32; 4],
412 pub retransmit_after_ticks: u32,
417 pub max_retries: u32,
420 #[cfg(feature = "crypto")]
425 #[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
426 pub crypto: Option<CryptoConfig>,
427}
428
429impl HandshakeConfig {
430 #[must_use]
432 pub fn with_latency_ms(mut self, latency_ms: u16) -> Self {
433 self.latency_ms = latency_ms;
434 self
435 }
436
437 #[must_use]
439 pub fn with_mtu(mut self, mtu: u32) -> Self {
440 self.mtu = mtu;
441 self
442 }
443
444 #[must_use]
446 pub fn with_max_flow_window_size(mut self, max_flow_window_size: u32) -> Self {
447 self.max_flow_window_size = max_flow_window_size;
448 self
449 }
450
451 #[must_use]
453 pub fn with_initial_seq_number(mut self, initial_seq_number: u32) -> Self {
454 self.initial_seq_number = initial_seq_number;
455 self
456 }
457
458 #[must_use]
460 pub fn with_srt_version(mut self, srt_version: u32) -> Self {
461 self.srt_version = srt_version;
462 self
463 }
464
465 #[must_use]
467 pub fn with_flags(mut self, flags: HandshakeExtensionMessageFlags) -> Self {
468 self.flags = flags;
469 self
470 }
471
472 #[must_use]
474 pub fn with_encryption_field(mut self, encryption_field: EncryptionField) -> Self {
475 self.encryption_field = encryption_field;
476 self
477 }
478
479 #[must_use]
481 pub fn with_stream_id(mut self, stream_id: Option<String>) -> Self {
482 self.stream_id = stream_id;
483 self
484 }
485
486 #[must_use]
488 pub fn with_group(mut self, group: Option<GroupMembershipExtension>) -> Self {
489 self.group = group;
490 self
491 }
492
493 #[must_use]
495 pub fn with_local_ip(mut self, local_ip: [u32; 4]) -> Self {
496 self.local_ip = local_ip;
497 self
498 }
499
500 #[must_use]
502 pub fn with_retransmit_after_ticks(mut self, retransmit_after_ticks: u32) -> Self {
503 self.retransmit_after_ticks = retransmit_after_ticks;
504 self
505 }
506
507 #[must_use]
509 pub fn with_max_retries(mut self, max_retries: u32) -> Self {
510 self.max_retries = max_retries;
511 self
512 }
513
514 #[cfg(feature = "crypto")]
516 #[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
517 #[must_use]
518 pub fn with_crypto(mut self, crypto: Option<CryptoConfig>) -> Self {
519 self.crypto = crypto;
520 self
521 }
522}
523
524pub const DEFAULT_MAX_RETRIES: u32 = 12;
529
530impl Default for HandshakeConfig {
531 fn default() -> Self {
532 HandshakeConfig {
533 latency_ms: 120,
534 mtu: 1500,
535 max_flow_window_size: 8192,
536 initial_seq_number: 0,
537 srt_version: 0x0105_0000,
538 flags: HandshakeExtensionMessageFlags(
539 crate::packet::handshake::HS_MSG_FLAG_TSBPDSND
540 | crate::packet::handshake::HS_MSG_FLAG_TSBPDRCV
541 | crate::packet::handshake::HS_MSG_FLAG_CRYPT
542 | crate::packet::handshake::HS_MSG_FLAG_TLPKTDROP
543 | crate::packet::handshake::HS_MSG_FLAG_PERIODICNAK
544 | crate::packet::handshake::HS_MSG_FLAG_REXMITFLG,
545 ),
546 encryption_field: EncryptionField::NoEncryption,
547 stream_id: None,
548 group: None,
549 local_ip: [0, 0, 0, 0],
550 retransmit_after_ticks: 3,
551 max_retries: DEFAULT_MAX_RETRIES,
552 #[cfg(feature = "crypto")]
553 crypto: None,
554 }
555 }
556}
557
558#[derive(Debug, Clone, PartialEq)]
563#[cfg_attr(feature = "serde", derive(serde::Serialize))]
564pub struct NegotiatedParams {
565 pub version: u32,
568 pub flags: HandshakeExtensionMessageFlags,
571 pub latency_ms: u16,
575 pub own_socket_id: u32,
577 pub peer_socket_id: u32,
579 pub mtu: u32,
583 pub max_flow_window_size: u32,
588 pub stream_id: Option<String>,
590 pub group: Option<GroupMembershipExtension>,
592 #[cfg(feature = "crypto")]
599 #[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
600 #[cfg_attr(feature = "serde", serde(skip))]
601 pub sek: Option<SecretBytes>,
602 #[cfg(feature = "crypto")]
606 #[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
607 pub salt: Option<[u8; crate::crypto::SALT_LEN]>,
608}
609
610#[derive(Debug, Clone, PartialEq)]
614#[cfg_attr(feature = "serde", derive(serde::Serialize))]
615#[non_exhaustive]
616pub enum HandshakeOutput {
617 Send(Vec<u8>),
620 Connected(NegotiatedParams),
622 Rejected(RejectionReason),
627 TimedOut,
630}
631
632pub(crate) enum RetransmitStep {
634 Idle,
635 Resend(Vec<u8>),
636 TimedOut,
637}
638
639impl RetransmitStep {
640 pub(crate) fn into_outputs(self) -> Vec<HandshakeOutput> {
641 match self {
642 Self::Idle => Vec::new(),
643 Self::Resend(bytes) => vec![HandshakeOutput::Send(bytes)],
644 Self::TimedOut => vec![HandshakeOutput::TimedOut],
645 }
646 }
647}
648
649#[derive(Debug, Default, Clone, Copy)]
653pub(crate) struct WireClock {
654 us: u32,
655}
656
657impl WireClock {
658 pub(crate) fn set(&mut self, elapsed: core::time::Duration) {
659 self.us = crate::arq::duration_to_wire_us(elapsed);
660 }
661
662 pub(crate) fn now(&self) -> u32 {
663 self.us
664 }
665}
666
667#[derive(Debug, Default)]
671pub(crate) struct Retransmit {
672 last_sent: Option<Vec<u8>>,
673 ticks_since_send: u32,
674 retries: u32,
675}
676
677impl Retransmit {
678 pub(crate) fn remember(&mut self, bytes: &[u8]) {
679 self.last_sent = Some(bytes.to_vec());
680 }
681
682 pub(crate) fn arm(&mut self, bytes: &[u8]) {
683 self.remember(bytes);
684 self.ticks_since_send = 0;
685 }
686
687 pub(crate) fn arm_fresh(&mut self, bytes: &[u8]) {
688 self.arm(bytes);
689 self.retries = 0;
690 }
691
692 pub(crate) fn last_sent(&self) -> Option<&[u8]> {
693 self.last_sent.as_deref()
694 }
695
696 pub(crate) fn tick(&mut self, config: &HandshakeConfig) -> RetransmitStep {
700 self.ticks_since_send += 1;
701 if self.ticks_since_send < config.retransmit_after_ticks {
702 return RetransmitStep::Idle;
703 }
704 self.ticks_since_send = 0;
705 self.retries += 1;
706 if self.retries > config.max_retries {
707 return RetransmitStep::TimedOut;
708 }
709 self.last_sent
710 .clone()
711 .map_or(RetransmitStep::Idle, RetransmitStep::Resend)
712 }
713}
714
715pub(crate) fn build_bytes(hp: HandshakePacket<'_>) -> Result<Vec<u8>> {
718 let pkt = ControlPacket::Handshake(hp);
719 let mut buf = alloc::vec![0u8; pkt.serialized_len()];
720 pkt.serialize_into(&mut buf)?;
721 Ok(buf)
722}
723
724pub(crate) fn build_conclusion_extensions(
728 hs_ext_type: crate::packet::ExtensionType,
729 hs_msg: &HsExtMessage,
730 stream_id: Option<&str>,
731 group: Option<GroupMembershipExtension>,
732) -> Result<(Vec<u8>, u16)> {
733 use crate::packet::handshake::{build_extension_block, encode_stream_id};
734
735 let mut ext_bytes = Vec::new();
736 ext_bytes.extend(build_extension_block(hs_ext_type, &hs_msg.to_bytes())?);
737 let mut ext_flags = HS_EXT_FLAG_HSREQ;
738 if let Some(sid) = stream_id {
739 let sid_bytes = encode_stream_id(sid);
740 ext_bytes.extend(build_extension_block(
741 crate::packet::ExtensionType::Sid,
742 &sid_bytes,
743 )?);
744 ext_flags |= HS_EXT_FLAG_CONFIG;
745 }
746 if let Some(g) = group {
747 ext_bytes.extend(build_extension_block(
748 crate::packet::ExtensionType::Group,
749 &g.to_bytes(),
750 )?);
751 ext_flags |= HS_EXT_FLAG_CONFIG;
752 }
753 Ok((ext_bytes, ext_flags))
754}
755
756#[derive(Debug, Default)]
760pub(crate) struct ParsedPeerExtensions<'a> {
761 pub hs_msg: Option<HsExtMessage>,
762 pub stream_id: Option<String>,
763 pub group: Option<GroupMembershipExtension>,
764 #[cfg(feature = "crypto")]
771 pub km: Option<KeyMaterial<'a>>,
772 #[cfg(not(feature = "crypto"))]
775 _phantom: core::marker::PhantomData<&'a ()>,
776}
777
778pub(crate) fn parse_peer_extensions<'a>(
783 hp: &HandshakePacket<'a>,
784) -> Result<ParsedPeerExtensions<'a>> {
785 use crate::packet::ExtensionType;
786
787 let mut out = ParsedPeerExtensions::default();
788 for block in hp.extensions.iter() {
789 let block = block.map_err(|_| {
790 Error::InvalidField(InvalidField {
791 field: "handshake extensions",
792 reason: "malformed extension block",
793 })
794 })?;
795 match block.ext_type {
796 ExtensionType::HsReq | ExtensionType::HsRsp => {
797 let msg = block.as_hs_ext_message().map_err(|_| {
798 Error::InvalidField(InvalidField {
799 field: "handshake extension message",
800 reason: "malformed HSREQ/HSRSP contents",
801 })
802 })?;
803 out.hs_msg = Some(msg);
804 }
805 ExtensionType::Sid => {
806 let sid = block.as_stream_id().map_err(|_| {
807 Error::InvalidField(InvalidField {
808 field: "stream ID extension",
809 reason: "malformed or non-UTF-8 contents",
810 })
811 })?;
812 out.stream_id = Some(sid);
813 }
814 ExtensionType::Group => {
815 let g = block.as_group_membership().map_err(|_| {
816 Error::InvalidField(InvalidField {
817 field: "group membership extension",
818 reason: "malformed contents",
819 })
820 })?;
821 out.group = Some(g);
822 }
823 #[cfg(feature = "crypto")]
824 ExtensionType::KmReq | ExtensionType::KmRsp => {
825 let km = block.as_key_material().map_err(|_| {
826 Error::InvalidField(InvalidField {
827 field: "key material extension",
828 reason: "malformed contents",
829 })
830 })?;
831 out.km = Some(km);
832 }
833 _ => {}
834 }
835 }
836 Ok(out)
837}
838
839#[cfg(feature = "crypto")]
852pub(crate) fn build_key_material_extension(crypto: &CryptoConfig) -> Result<Vec<u8>> {
853 let kek = crate::crypto::derive_kek(&crypto.passphrase, &crypto.salt, crypto.sek.len())?;
854 let (icv, wrapped) = crate::crypto::wrap_sek(&kek, &crypto.sek)?;
855 let km = KeyMaterial {
856 kk: KmKeyFlag::Even,
857 keki: 0,
858 cipher: Cipher::AesCtr,
859 auth: KmAuth::None,
860 se: StreamEncapsulation::MpegTsSrt,
861 salt: &crypto.salt,
862 icv,
863 x_sek: &wrapped,
864 o_sek: None,
865 };
866 let mut buf = alloc::vec![0u8; km.serialized_len()];
867 km.serialize_into(&mut buf)?;
868 crate::packet::handshake::build_extension_block(crate::packet::ExtensionType::KmReq, &buf)
869}
870
871#[cfg(feature = "crypto")]
873pub(crate) type RecoveredSek = (SecretBytes, [u8; crate::crypto::SALT_LEN]);
874
875#[cfg(feature = "crypto")]
887pub(crate) fn recover_sek(passphrase: &[u8], km: &KeyMaterial<'_>) -> Result<RecoveredSek> {
888 if km.salt.len() != crate::crypto::SALT_LEN {
889 return Err(Error::InvalidField(InvalidField {
890 field: "Key Material Salt",
891 reason: "must be 16 bytes (the only Salt length this crate's codec accepts)",
892 }));
893 }
894 let mut salt = [0u8; crate::crypto::SALT_LEN];
895 salt.copy_from_slice(km.salt);
896 let kek = crate::crypto::derive_kek(passphrase, &salt, km.x_sek.len())?;
897 let sek = SecretBytes::new(crate::crypto::unwrap_sek(&kek, &km.icv, km.x_sek)?.to_vec());
898 Ok((sek, salt))
899}
900
901#[cfg(all(feature = "crypto", feature = "tokio"))]
909pub(crate) fn recover_both_seks(
910 passphrase: &[u8],
911 km: &KeyMaterial<'_>,
912) -> Result<(SecretBytes, SecretBytes, [u8; crate::crypto::SALT_LEN])> {
913 let Some(o_sek) = km.o_sek.filter(|_| km.kk == KmKeyFlag::Both) else {
914 return Err(Error::InvalidField(InvalidField {
915 field: "Key Material KK",
916 reason: "expected both an even and an odd SEK",
917 }));
918 };
919 if km.salt.len() != crate::crypto::SALT_LEN {
920 return Err(Error::InvalidField(InvalidField {
921 field: "Key Material Salt",
922 reason: "must be 16 bytes (the only Salt length this crate's codec accepts)",
923 }));
924 }
925 let mut salt = [0u8; crate::crypto::SALT_LEN];
926 salt.copy_from_slice(km.salt);
927 let kek = crate::crypto::derive_kek(passphrase, &salt, km.x_sek.len())?;
928 let mut wrapped = Vec::with_capacity(km.x_sek.len() + o_sek.len());
929 wrapped.extend_from_slice(km.x_sek);
930 wrapped.extend_from_slice(o_sek);
931 let keys = crate::crypto::unwrap_sek(&kek, &km.icv, &wrapped)?;
932 let (even, odd) = keys.split_at(km.x_sek.len());
933 Ok((
934 SecretBytes::new(even.to_vec()),
935 SecretBytes::new(odd.to_vec()),
936 salt,
937 ))
938}
939
940#[cfg(feature = "crypto")]
945pub(crate) fn echo_key_material_as_response(km: &KeyMaterial<'_>) -> Result<Vec<u8>> {
946 let mut buf = alloc::vec![0u8; km.serialized_len()];
947 km.serialize_into(&mut buf)?;
948 crate::packet::handshake::build_extension_block(crate::packet::ExtensionType::KmRsp, &buf)
949}
950
951#[cfg(feature = "crypto")]
956pub(crate) fn verify_km_echo(crypto: &CryptoConfig, echoed: &KeyMaterial<'_>) -> bool {
957 let kek = match crate::crypto::derive_kek(&crypto.passphrase, &crypto.salt, crypto.sek.len()) {
958 Ok(k) => k,
959 Err(_) => return false,
960 };
961 let (icv, wrapped) = match crate::crypto::wrap_sek(&kek, &crypto.sek) {
962 Ok(v) => v,
963 Err(_) => return false,
964 };
965 let salt = echoed.salt.ct_eq(crypto.salt.as_slice());
967 let icv = echoed.icv.as_slice().ct_eq(icv.as_slice());
968 let wrapped = echoed.x_sek.ct_eq(wrapped.as_slice());
969 bool::from(salt & icv & wrapped)
970}
971
972pub(crate) fn negotiate_latency_ms(local_latency_ms: u16, peer_msg: &HsExtMessage) -> u16 {
974 local_latency_ms
975 .max(peer_msg.receiver_tsbpd_delay_ms)
976 .max(peer_msg.sender_tsbpd_delay_ms)
977}
978
979fn siphash24(k0: u64, k1: u64, data: &[u8]) -> u64 {
985 const C_ROUNDS: usize = 2;
988 const D_ROUNDS: usize = 4;
989 const INIT_V0: u64 = 0x736f_6d65_7073_6575;
992 const INIT_V1: u64 = 0x646f_7261_6e64_6f6d;
993 const INIT_V2: u64 = 0x6c79_6765_6e65_7261;
994 const INIT_V3: u64 = 0x7465_6462_7974_6573;
995 const FINALIZATION_XOR: u64 = 0xFF;
997
998 let mut v0 = k0 ^ INIT_V0;
999 let mut v1 = k1 ^ INIT_V1;
1000 let mut v2 = k0 ^ INIT_V2;
1001 let mut v3 = k1 ^ INIT_V3;
1002
1003 fn round(v0: &mut u64, v1: &mut u64, v2: &mut u64, v3: &mut u64) {
1004 *v0 = v0.wrapping_add(*v1);
1005 *v1 = v1.rotate_left(13);
1006 *v1 ^= *v0;
1007 *v0 = v0.rotate_left(32);
1008 *v2 = v2.wrapping_add(*v3);
1009 *v3 = v3.rotate_left(16);
1010 *v3 ^= *v2;
1011 *v0 = v0.wrapping_add(*v3);
1012 *v3 = v3.rotate_left(21);
1013 *v3 ^= *v0;
1014 *v2 = v2.wrapping_add(*v1);
1015 *v1 = v1.rotate_left(17);
1016 *v1 ^= *v2;
1017 *v2 = v2.rotate_left(32);
1018 }
1019
1020 let mut chunks = data.chunks_exact(8);
1021 for chunk in chunks.by_ref() {
1022 let mut word = [0u8; 8];
1023 word.copy_from_slice(chunk);
1024 let m = u64::from_le_bytes(word);
1025 v3 ^= m;
1026 for _ in 0..C_ROUNDS {
1027 round(&mut v0, &mut v1, &mut v2, &mut v3);
1028 }
1029 v0 ^= m;
1030 }
1031 let mut last = [0u8; 8];
1034 let rest = chunks.remainder();
1035 last[..rest.len()].copy_from_slice(rest);
1036 last[7] = u8::try_from(data.len() & 0xFF).unwrap_or(0);
1037 let m = u64::from_le_bytes(last);
1038 v3 ^= m;
1039 for _ in 0..C_ROUNDS {
1040 round(&mut v0, &mut v1, &mut v2, &mut v3);
1041 }
1042 v0 ^= m;
1043 v2 ^= FINALIZATION_XOR;
1044 for _ in 0..D_ROUNDS {
1045 round(&mut v0, &mut v1, &mut v2, &mut v3);
1046 }
1047 v0 ^ v1 ^ v2 ^ v3
1048}
1049
1050pub fn derive_cookie(peer_key: u64, time_bucket: u32, secret: u128) -> u32 {
1067 let mut input = [0u8; 12];
1068 input[..8].copy_from_slice(&peer_key.to_le_bytes());
1069 input[8..].copy_from_slice(&time_bucket.to_le_bytes());
1070 let k0 = u64::try_from(secret & u128::from(u64::MAX)).unwrap_or(0);
1071 let k1 = u64::try_from(secret >> 64).unwrap_or(0);
1072 let digest = siphash24(k0, k1, &input);
1073 u32::try_from(digest & u64::from(u32::MAX)).unwrap_or(0) | 1
1076}
1077
1078#[cfg(test)]
1079mod tests {
1080 use super::*;
1081
1082 #[test]
1083 fn rejection_reason_round_trips_table_7() {
1084 let all = [
1085 RejectionReason::Unknown,
1086 RejectionReason::System,
1087 RejectionReason::Peer,
1088 RejectionReason::Resource,
1089 RejectionReason::Rogue,
1090 RejectionReason::Backlog,
1091 RejectionReason::Ipe,
1092 RejectionReason::Close,
1093 RejectionReason::Version,
1094 RejectionReason::RdvCookie,
1095 RejectionReason::BadSecret,
1096 RejectionReason::Unsecure,
1097 RejectionReason::MessageApi,
1098 RejectionReason::Congestion,
1099 RejectionReason::Filter,
1100 RejectionReason::Group,
1101 ];
1102 for (i, r) in all.iter().enumerate() {
1103 assert_eq!(r.to_bits(), 1000 + i as u32);
1104 assert_eq!(RejectionReason::from_bits(r.to_bits()), *r);
1105 assert_eq!(
1106 RejectionReason::from_handshake_type(r.to_handshake_type()),
1107 Some(*r)
1108 );
1109 }
1110 }
1111
1112 #[test]
1113 fn non_rejection_handshake_types_are_not_a_rejection() {
1114 for ht in [
1115 HandshakeType::Induction,
1116 HandshakeType::Conclusion,
1117 HandshakeType::Wavehand,
1118 HandshakeType::Agreement,
1119 HandshakeType::Done,
1120 ] {
1121 assert_eq!(RejectionReason::from_handshake_type(ht), None);
1122 }
1123 }
1124
1125 #[test]
1126 fn derive_cookie_is_deterministic_and_nonzero() {
1127 let a = derive_cookie(0x1234_5678_9ABC_DEF0, 12345, 0xDEAD_BEEF);
1128 let b = derive_cookie(0x1234_5678_9ABC_DEF0, 12345, 0xDEAD_BEEF);
1129 assert_eq!(a, b);
1130 assert_ne!(a, 0);
1131 let c = derive_cookie(0x1234_5678_9ABC_DEF1, 12345, 0xDEAD_BEEF);
1132 assert_ne!(a, c);
1133 }
1134
1135 #[test]
1139 fn only_the_positive_rejection_range_counts_as_a_rejection() {
1140 let is_rejection =
1141 |v: u32| RejectionReason::from_handshake_type(HandshakeType::from_bits(v)).is_some();
1142 assert!(!is_rejection(0xFFFF_FFFC));
1143 assert!(!is_rejection(0xFFFF_FFFE)); assert!(!is_rejection(REJECTION_CODE_LIMIT));
1145 assert!(!is_rejection(REJECTION_CODE_BASE - 1));
1146 assert!(is_rejection(REJECTION_CODE_BASE));
1147 assert!(is_rejection(REJECTION_CODE_LIMIT - 1));
1148 assert_eq!(
1151 RejectionReason::from_handshake_type(HandshakeType::from_bits(1010)),
1152 Some(RejectionReason::BadSecret)
1153 );
1154 assert_eq!(
1155 RejectionReason::from_handshake_type(HandshakeType::from_bits(1500)),
1156 Some(RejectionReason::Reserved(1500))
1157 );
1158 assert_eq!(
1159 RejectionReason::from_handshake_type(HandshakeType::from_bits(2001)),
1160 Some(RejectionReason::Reserved(2001))
1161 );
1162 }
1163
1164 #[cfg(feature = "crypto")]
1168 #[test]
1169 fn caller_kmreq_declares_the_mpeg_ts_srt_encapsulation() {
1170 let crypto = CryptoConfig {
1171 passphrase: b"0123456789abcdef".to_vec(),
1172 salt: [0x33; crate::crypto::SALT_LEN],
1173 sek: alloc::vec![0x44; 16],
1174 };
1175 let ext = build_key_material_extension(&crypto).unwrap();
1176 let km = KeyMaterial::parse(&ext[4..]).unwrap();
1178 assert_eq!(km.se, StreamEncapsulation::MpegTsSrt);
1179 assert_eq!(km.se.to_bits(), 2);
1180 assert_eq!(ext[4 + 10], 2);
1182 }
1183
1184 #[test]
1187 fn siphash24_matches_the_reference_vector() {
1188 let k0 = u64::from_le_bytes([0, 1, 2, 3, 4, 5, 6, 7]);
1189 let k1 = u64::from_le_bytes([8, 9, 10, 11, 12, 13, 14, 15]);
1190 let input: Vec<u8> = (0u8..15).collect();
1191 assert_eq!(siphash24(k0, k1, &input), 0xa129_ca61_49be_45e5);
1192 assert_eq!(siphash24(k0, k1, &[]), 0x726f_db47_dd0e_0e31);
1194 }
1195
1196 #[test]
1198 fn derive_cookie_depends_on_secret_peer_and_time() {
1199 let base = derive_cookie(1, 2, 3);
1200 assert_ne!(base, derive_cookie(1, 2, 4), "secret");
1201 assert_ne!(base, derive_cookie(9, 2, 3), "peer");
1202 assert_ne!(base, derive_cookie(1, 9, 3), "time bucket");
1203 assert_eq!(base & 1, 1);
1204 assert_eq!(
1208 derive_cookie(0x1234_5678_9ABC_DEF0, 12345, 0xDEAD_BEEF),
1209 0x5905_9ee9
1210 );
1211 assert_eq!(
1212 derive_cookie(
1213 0x1234_5678_9ABC_DEF0,
1214 12345,
1215 0x0123_4567_89AB_CDEF_FEDC_BA98_7654_3210
1216 ),
1217 0xec46_1e0b
1218 );
1219 assert_ne!(
1221 derive_cookie(1, 2, 7),
1222 derive_cookie(1, 2, 7 | (1u128 << 64)),
1223 "the high key half must influence the cookie"
1224 );
1225 }
1226
1227 #[cfg(feature = "crypto")]
1233 fn distinctive(seed: u32, len: usize) -> Vec<u8> {
1234 let mut x = seed.wrapping_mul(2_654_435_761).wrapping_add(12_345);
1235 (0..len)
1236 .map(|_| {
1237 x = x.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
1238 u8::try_from(x >> 24).unwrap()
1239 })
1240 .collect()
1241 }
1242
1243 #[cfg(feature = "crypto")]
1245 fn needles(bytes: &[u8]) -> Vec<String> {
1246 let head = &bytes[..6];
1247 let dec = |sep: &str| {
1248 head.iter()
1249 .map(|b| alloc::format!("{b}"))
1250 .collect::<Vec<_>>()
1251 .join(sep)
1252 };
1253 alloc::vec![
1254 dec(", "),
1255 dec(","),
1256 head.iter()
1257 .map(|b| alloc::format!("{b:x}"))
1258 .collect::<Vec<_>>()
1259 .join(", "),
1260 head.iter().map(|b| alloc::format!("{b:02x}")).collect(),
1261 ]
1262 }
1263
1264 #[cfg(feature = "crypto")]
1265 fn secret_config() -> CryptoConfig {
1266 CryptoConfig {
1267 passphrase: distinctive(1, 15),
1268 salt: distinctive(2, crate::crypto::SALT_LEN).try_into().unwrap(),
1269 sek: distinctive(3, 16),
1270 }
1271 }
1272
1273 #[cfg(feature = "crypto")]
1276 #[test]
1277 fn crypto_config_debug_never_shows_secret_bytes() {
1278 let config = HandshakeConfig {
1279 crypto: Some(secret_config()),
1280 ..HandshakeConfig::default()
1281 };
1282 for dump in [
1283 alloc::format!("{:?}", secret_config()),
1284 alloc::format!("{:#?}", secret_config()),
1285 alloc::format!("{:?}", config),
1286 alloc::format!("{:#?}", config),
1287 alloc::format!("{:x?}", config),
1288 ] {
1289 let secret = secret_config();
1290 for (name, bytes) in [
1291 ("passphrase", &secret.passphrase[..]),
1292 ("salt", &secret.salt[..]),
1293 ("sek", &secret.sek[..]),
1294 ] {
1295 for needle in needles(bytes) {
1296 assert!(
1297 !dump.contains(&needle),
1298 "{name} leaked as {needle:?}: {dump}"
1299 );
1300 }
1301 }
1302 assert!(dump.contains("redacted"), "{dump}");
1303 }
1304 assert!(alloc::format!("{:?}", secret_config()).contains("15 bytes"));
1305 }
1306
1307 #[cfg(feature = "crypto")]
1310 #[test]
1311 fn negotiated_sek_is_redacted_in_debug_and_absent_from_serde() {
1312 let sek_bytes = distinctive(9, 16);
1313 let params = NegotiatedParams {
1314 version: HANDSHAKE_VERSION_5,
1315 flags: HandshakeExtensionMessageFlags(0),
1316 latency_ms: 120,
1317 own_socket_id: 1,
1318 peer_socket_id: 2,
1319 mtu: 1500,
1320 max_flow_window_size: 8192,
1321 stream_id: None,
1322 group: None,
1323 sek: Some(SecretBytes::new(sek_bytes.clone())),
1324 salt: Some([0x11; crate::crypto::SALT_LEN]),
1325 };
1326 for dump in [
1327 alloc::format!("{params:?}"),
1328 alloc::format!("{:#?}", HandshakeOutput::Connected(params.clone())),
1329 alloc::format!("{:x?}", HandshakeOutput::Connected(params.clone())),
1330 ] {
1331 for needle in needles(&sek_bytes) {
1332 assert!(!dump.contains(&needle), "SEK leaked as {needle:?}: {dump}");
1333 }
1334 assert!(dump.contains("redacted"), "{dump}");
1335 }
1336 #[cfg(feature = "serde")]
1337 {
1338 let json = serde_json::to_string(¶ms).expect("serialize");
1339 assert!(!json.contains("sek"), "the SEK was serialized: {json}");
1340 for needle in needles(&sek_bytes) {
1341 assert!(!json.contains(&needle), "SEK leaked as {needle:?}: {json}");
1342 }
1343 }
1344 }
1345
1346 #[cfg(feature = "crypto")]
1350 #[test]
1351 fn secrets_compare_correctly_and_wipe_on_zeroize() {
1352 let a = SecretBytes::new(alloc::vec![1, 2, 3, 4]);
1353 assert!(a == SecretBytes::new(alloc::vec![1, 2, 3, 4]));
1354 assert!(a != SecretBytes::new(alloc::vec![1, 2, 3, 5]));
1355 assert!(a != SecretBytes::new(alloc::vec![1, 2, 3]));
1356 assert_eq!(&*a, &[1u8, 2, 3, 4][..]);
1357
1358 let mut sek = SecretBytes::new(alloc::vec![9; 16]);
1359 sek.zeroize();
1360 assert!(sek.is_empty(), "zeroize must clear the key");
1361
1362 let mut config = secret_config();
1363 assert!(config == secret_config());
1364 let mut other = secret_config();
1365 other.sek[0] ^= 1;
1366 assert!(config != other);
1367 config.zeroize();
1368 assert!(config.passphrase.is_empty() && config.sek.is_empty());
1369 assert_eq!(config.salt, [0u8; crate::crypto::SALT_LEN]);
1370 }
1371
1372 #[cfg(feature = "crypto")]
1374 #[test]
1375 fn secret_holders_are_zeroize_on_drop() {
1376 fn assert_zeroize_on_drop<T: zeroize::ZeroizeOnDrop>() {}
1377 assert_zeroize_on_drop::<CryptoConfig>();
1378 assert_zeroize_on_drop::<SecretBytes>();
1379 }
1380}