1use alloc::string::String;
20use alloc::vec::Vec;
21#[cfg(feature = "crypto")]
22use subtle::ConstantTimeEq;
23#[cfg(feature = "crypto")]
24use zeroize::Zeroize;
25
26use crate::error::{Error, Result};
27#[cfg(feature = "crypto")]
28use crate::packet::KeyMaterial;
29use crate::packet::handshake::{HS_EXT_FLAG_CONFIG, HS_EXT_FLAG_HSREQ};
30#[cfg(feature = "crypto")]
31use crate::packet::{Cipher, KmAuth, KmKeyFlag, StreamEncapsulation};
32use crate::packet::{
33 ControlPacket, EncryptionField, GroupMembershipExtension, HandshakeExtensionMessageFlags,
34 HandshakePacket, HandshakeType, HsExtMessage,
35};
36
37pub const HANDSHAKE_VERSION_4: u32 = 4;
41pub const HANDSHAKE_VERSION_5: u32 = 5;
44
45pub const SRT_MAGIC_CODE: u16 = 0x4A17;
49
50pub const INDUCTION_LEGACY_SOCKET_TYPE: u16 = 2;
57
58pub const REJECTION_CODE_BASE: u32 = 1000;
62
63pub const REJECTION_CODE_LIMIT: u32 = 0x8000_0000;
68
69#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
73#[cfg_attr(feature = "serde", derive(serde::Serialize))]
74#[non_exhaustive]
75pub enum RejectionReason {
76 Unknown,
78 System,
80 Peer,
82 Resource,
84 Rogue,
86 Backlog,
88 Ipe,
90 Close,
92 Version,
94 RdvCookie,
96 BadSecret,
98 Unsecure,
100 MessageApi,
102 Congestion,
104 Filter,
106 Group,
108 Reserved(u32),
110}
111
112impl RejectionReason {
113 pub fn from_bits(v: u32) -> Self {
116 match v {
117 1000 => RejectionReason::Unknown,
118 1001 => RejectionReason::System,
119 1002 => RejectionReason::Peer,
120 1003 => RejectionReason::Resource,
121 1004 => RejectionReason::Rogue,
122 1005 => RejectionReason::Backlog,
123 1006 => RejectionReason::Ipe,
124 1007 => RejectionReason::Close,
125 1008 => RejectionReason::Version,
126 1009 => RejectionReason::RdvCookie,
127 1010 => RejectionReason::BadSecret,
128 1011 => RejectionReason::Unsecure,
129 1012 => RejectionReason::MessageApi,
130 1013 => RejectionReason::Congestion,
131 1014 => RejectionReason::Filter,
132 1015 => RejectionReason::Group,
133 other => RejectionReason::Reserved(other),
134 }
135 }
136
137 pub fn to_bits(self) -> u32 {
139 match self {
140 RejectionReason::Unknown => 1000,
141 RejectionReason::System => 1001,
142 RejectionReason::Peer => 1002,
143 RejectionReason::Resource => 1003,
144 RejectionReason::Rogue => 1004,
145 RejectionReason::Backlog => 1005,
146 RejectionReason::Ipe => 1006,
147 RejectionReason::Close => 1007,
148 RejectionReason::Version => 1008,
149 RejectionReason::RdvCookie => 1009,
150 RejectionReason::BadSecret => 1010,
151 RejectionReason::Unsecure => 1011,
152 RejectionReason::MessageApi => 1012,
153 RejectionReason::Congestion => 1013,
154 RejectionReason::Filter => 1014,
155 RejectionReason::Group => 1015,
156 RejectionReason::Reserved(v) => v,
157 }
158 }
159
160 pub fn name(&self) -> &'static str {
162 match self {
163 RejectionReason::Unknown => "REJ_UNKNOWN",
164 RejectionReason::System => "REJ_SYSTEM",
165 RejectionReason::Peer => "REJ_PEER",
166 RejectionReason::Resource => "REJ_RESOURCE",
167 RejectionReason::Rogue => "REJ_ROGUE",
168 RejectionReason::Backlog => "REJ_BACKLOG",
169 RejectionReason::Ipe => "REJ_IPE",
170 RejectionReason::Close => "REJ_CLOSE",
171 RejectionReason::Version => "REJ_VERSION",
172 RejectionReason::RdvCookie => "REJ_RDVCOOKIE",
173 RejectionReason::BadSecret => "REJ_BADSECRET",
174 RejectionReason::Unsecure => "REJ_UNSECURE",
175 RejectionReason::MessageApi => "REJ_MESSAGEAPI",
176 RejectionReason::Congestion => "REJ_CONGESTION",
177 RejectionReason::Filter => "REJ_FILTER",
178 RejectionReason::Group => "REJ_GROUP",
179 RejectionReason::Reserved(_) => "reserved",
180 }
181 }
182
183 pub fn from_handshake_type(ht: HandshakeType) -> Option<Self> {
192 match ht {
193 HandshakeType::Reserved(v)
194 if (REJECTION_CODE_BASE..REJECTION_CODE_LIMIT).contains(&v) =>
195 {
196 Some(RejectionReason::from_bits(v))
197 }
198 _ => None,
199 }
200 }
201
202 pub fn to_handshake_type(self) -> HandshakeType {
204 HandshakeType::from_bits(self.to_bits())
205 }
206}
207
208broadcast_common::impl_spec_display!(RejectionReason, Reserved);
209
210#[cfg(feature = "crypto")]
230#[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
231#[derive(Clone)]
232pub struct CryptoConfig {
233 pub passphrase: Vec<u8>,
238 pub salt: [u8; crate::crypto::SALT_LEN],
242 pub sek: Vec<u8>,
250}
251
252#[cfg(feature = "crypto")]
253impl core::fmt::Debug for CryptoConfig {
254 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
255 f.debug_struct("CryptoConfig")
256 .field(
257 "passphrase",
258 &format_args!("<redacted, {} bytes>", self.passphrase.len()),
259 )
260 .field(
261 "salt",
262 &format_args!("<redacted, {} bytes>", self.salt.len()),
263 )
264 .field("sek", &format_args!("<redacted, {} bytes>", self.sek.len()))
265 .finish()
266 }
267}
268
269#[cfg(feature = "crypto")]
270impl PartialEq for CryptoConfig {
271 fn eq(&self, other: &Self) -> bool {
273 let passphrase = self
274 .passphrase
275 .as_slice()
276 .ct_eq(other.passphrase.as_slice());
277 let salt = self.salt.as_slice().ct_eq(other.salt.as_slice());
278 let sek = self.sek.as_slice().ct_eq(other.sek.as_slice());
279 bool::from(passphrase & salt & sek)
280 }
281}
282
283#[cfg(feature = "crypto")]
284impl Zeroize for CryptoConfig {
285 fn zeroize(&mut self) {
286 self.passphrase.zeroize();
287 self.salt.zeroize();
288 self.sek.zeroize();
289 }
290}
291
292#[cfg(feature = "crypto")]
293impl Drop for CryptoConfig {
294 fn drop(&mut self) {
295 self.zeroize();
296 }
297}
298
299#[cfg(feature = "crypto")]
300impl zeroize::ZeroizeOnDrop for CryptoConfig {}
301
302#[cfg(feature = "crypto")]
309#[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
310#[derive(Clone)]
311pub struct SecretBytes(Vec<u8>);
312
313#[cfg(feature = "crypto")]
314impl SecretBytes {
315 pub fn new(bytes: Vec<u8>) -> Self {
317 SecretBytes(bytes)
318 }
319}
320
321#[cfg(feature = "crypto")]
322impl From<Vec<u8>> for SecretBytes {
323 fn from(bytes: Vec<u8>) -> Self {
324 SecretBytes(bytes)
325 }
326}
327
328#[cfg(feature = "crypto")]
329impl core::ops::Deref for SecretBytes {
330 type Target = [u8];
331 fn deref(&self) -> &[u8] {
332 &self.0
333 }
334}
335
336#[cfg(feature = "crypto")]
337impl core::fmt::Debug for SecretBytes {
338 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
339 write!(f, "SecretBytes(<redacted, {} bytes>)", self.0.len())
340 }
341}
342
343#[cfg(feature = "crypto")]
344impl PartialEq for SecretBytes {
345 fn eq(&self, other: &Self) -> bool {
347 bool::from(self.0.as_slice().ct_eq(other.0.as_slice()))
348 }
349}
350
351#[cfg(feature = "crypto")]
352impl Eq for SecretBytes {}
353
354#[cfg(feature = "crypto")]
355impl Zeroize for SecretBytes {
356 fn zeroize(&mut self) {
357 self.0.zeroize();
358 }
359}
360
361#[cfg(feature = "crypto")]
362impl Drop for SecretBytes {
363 fn drop(&mut self) {
364 self.zeroize();
365 }
366}
367
368#[cfg(feature = "crypto")]
369impl zeroize::ZeroizeOnDrop for SecretBytes {}
370
371#[derive(Debug, Clone, PartialEq)]
375pub struct HandshakeConfig {
376 pub latency_ms: u16,
381 pub mtu: u32,
383 pub max_flow_window_size: u32,
385 pub initial_seq_number: u32,
389 pub srt_version: u32,
392 pub flags: HandshakeExtensionMessageFlags,
394 pub encryption_field: EncryptionField,
398 pub stream_id: Option<String>,
401 pub group: Option<GroupMembershipExtension>,
404 pub local_ip: [u32; 4],
409 pub retransmit_after_ticks: u32,
414 pub max_retries: u32,
417 #[cfg(feature = "crypto")]
422 #[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
423 pub crypto: Option<CryptoConfig>,
424}
425
426pub const DEFAULT_MAX_RETRIES: u32 = 12;
431
432impl Default for HandshakeConfig {
433 fn default() -> Self {
434 HandshakeConfig {
435 latency_ms: 120,
436 mtu: 1500,
437 max_flow_window_size: 8192,
438 initial_seq_number: 0,
439 srt_version: 0x0105_0000,
440 flags: HandshakeExtensionMessageFlags(
441 crate::packet::handshake::HS_MSG_FLAG_TSBPDSND
442 | crate::packet::handshake::HS_MSG_FLAG_TSBPDRCV
443 | crate::packet::handshake::HS_MSG_FLAG_CRYPT
444 | crate::packet::handshake::HS_MSG_FLAG_TLPKTDROP
445 | crate::packet::handshake::HS_MSG_FLAG_PERIODICNAK
446 | crate::packet::handshake::HS_MSG_FLAG_REXMITFLG,
447 ),
448 encryption_field: EncryptionField::NoEncryption,
449 stream_id: None,
450 group: None,
451 local_ip: [0, 0, 0, 0],
452 retransmit_after_ticks: 3,
453 max_retries: DEFAULT_MAX_RETRIES,
454 #[cfg(feature = "crypto")]
455 crypto: None,
456 }
457 }
458}
459
460#[derive(Debug, Clone, PartialEq)]
465#[cfg_attr(feature = "serde", derive(serde::Serialize))]
466pub struct NegotiatedParams {
467 pub version: u32,
470 pub flags: HandshakeExtensionMessageFlags,
473 pub latency_ms: u16,
477 pub own_socket_id: u32,
479 pub peer_socket_id: u32,
481 pub mtu: u32,
485 pub max_flow_window_size: u32,
490 pub stream_id: Option<String>,
492 pub group: Option<GroupMembershipExtension>,
494 #[cfg(feature = "crypto")]
501 #[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
502 #[cfg_attr(feature = "serde", serde(skip))]
503 pub sek: Option<SecretBytes>,
504 #[cfg(feature = "crypto")]
508 #[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
509 pub salt: Option<[u8; crate::crypto::SALT_LEN]>,
510}
511
512#[derive(Debug, Clone, PartialEq)]
516#[cfg_attr(feature = "serde", derive(serde::Serialize))]
517#[non_exhaustive]
518pub enum HandshakeOutput {
519 Send(Vec<u8>),
522 Connected(NegotiatedParams),
524 Rejected(RejectionReason),
529 TimedOut,
532}
533
534pub(crate) fn build_bytes(hp: HandshakePacket<'_>) -> Result<Vec<u8>> {
537 let pkt = ControlPacket::Handshake(hp);
538 let mut buf = alloc::vec![0u8; pkt.serialized_len()];
539 pkt.serialize_into(&mut buf)?;
540 Ok(buf)
541}
542
543pub(crate) fn build_conclusion_extensions(
547 hs_ext_type: crate::packet::ExtensionType,
548 hs_msg: &HsExtMessage,
549 stream_id: Option<&str>,
550 group: Option<GroupMembershipExtension>,
551) -> Result<(Vec<u8>, u16)> {
552 use crate::packet::handshake::{build_extension_block, encode_stream_id};
553
554 let mut ext_bytes = Vec::new();
555 ext_bytes.extend(build_extension_block(hs_ext_type, &hs_msg.to_bytes())?);
556 let mut ext_flags = HS_EXT_FLAG_HSREQ;
557 if let Some(sid) = stream_id {
558 let sid_bytes = encode_stream_id(sid);
559 ext_bytes.extend(build_extension_block(
560 crate::packet::ExtensionType::Sid,
561 &sid_bytes,
562 )?);
563 ext_flags |= HS_EXT_FLAG_CONFIG;
564 }
565 if let Some(g) = group {
566 ext_bytes.extend(build_extension_block(
567 crate::packet::ExtensionType::Group,
568 &g.to_bytes(),
569 )?);
570 ext_flags |= HS_EXT_FLAG_CONFIG;
571 }
572 Ok((ext_bytes, ext_flags))
573}
574
575#[derive(Debug, Default)]
579pub(crate) struct ParsedPeerExtensions<'a> {
580 pub hs_msg: Option<HsExtMessage>,
581 pub stream_id: Option<String>,
582 pub group: Option<GroupMembershipExtension>,
583 #[cfg(feature = "crypto")]
590 pub km: Option<KeyMaterial<'a>>,
591 #[cfg(not(feature = "crypto"))]
594 _phantom: core::marker::PhantomData<&'a ()>,
595}
596
597pub(crate) fn parse_peer_extensions<'a>(
602 hp: &HandshakePacket<'a>,
603) -> Result<ParsedPeerExtensions<'a>> {
604 use crate::packet::ExtensionType;
605
606 let mut out = ParsedPeerExtensions::default();
607 for block in hp.extensions.iter() {
608 let block = block.map_err(|_| Error::InvalidField {
609 what: "handshake extensions",
610 reason: "malformed extension block",
611 })?;
612 match block.ext_type {
613 ExtensionType::HsReq | ExtensionType::HsRsp => {
614 let msg = block.as_hs_ext_message().map_err(|_| Error::InvalidField {
615 what: "handshake extension message",
616 reason: "malformed HSREQ/HSRSP contents",
617 })?;
618 out.hs_msg = Some(msg);
619 }
620 ExtensionType::Sid => {
621 let sid = block.as_stream_id().map_err(|_| Error::InvalidField {
622 what: "stream ID extension",
623 reason: "malformed or non-UTF-8 contents",
624 })?;
625 out.stream_id = Some(sid);
626 }
627 ExtensionType::Group => {
628 let g = block
629 .as_group_membership()
630 .map_err(|_| Error::InvalidField {
631 what: "group membership extension",
632 reason: "malformed contents",
633 })?;
634 out.group = Some(g);
635 }
636 #[cfg(feature = "crypto")]
637 ExtensionType::KmReq | ExtensionType::KmRsp => {
638 let km = block.as_key_material().map_err(|_| Error::InvalidField {
639 what: "key material extension",
640 reason: "malformed contents",
641 })?;
642 out.km = Some(km);
643 }
644 _ => {}
645 }
646 }
647 Ok(out)
648}
649
650#[cfg(feature = "crypto")]
663pub(crate) fn build_key_material_extension(crypto: &CryptoConfig) -> Result<Vec<u8>> {
664 let kek = crate::crypto::derive_kek(&crypto.passphrase, &crypto.salt, crypto.sek.len())?;
665 let (icv, wrapped) = crate::crypto::wrap_sek(&kek, &crypto.sek)?;
666 let km = KeyMaterial {
667 kk: KmKeyFlag::Even,
668 keki: 0,
669 cipher: Cipher::AesCtr,
670 auth: KmAuth::None,
671 se: StreamEncapsulation::MpegTsSrt,
672 salt: &crypto.salt,
673 icv,
674 x_sek: &wrapped,
675 o_sek: None,
676 };
677 let mut buf = alloc::vec![0u8; km.serialized_len()];
678 km.serialize_into(&mut buf)?;
679 crate::packet::handshake::build_extension_block(crate::packet::ExtensionType::KmReq, &buf)
680}
681
682#[cfg(feature = "crypto")]
684pub(crate) type RecoveredSek = (SecretBytes, [u8; crate::crypto::SALT_LEN]);
685
686#[cfg(feature = "crypto")]
698pub(crate) fn recover_sek(passphrase: &[u8], km: &KeyMaterial<'_>) -> Result<RecoveredSek> {
699 if km.salt.len() != crate::crypto::SALT_LEN {
700 return Err(Error::InvalidField {
701 what: "Key Material Salt",
702 reason: "must be 16 bytes (the only Salt length this crate's codec accepts)",
703 });
704 }
705 let mut salt = [0u8; crate::crypto::SALT_LEN];
706 salt.copy_from_slice(km.salt);
707 let kek = crate::crypto::derive_kek(passphrase, &salt, km.x_sek.len())?;
708 let sek = SecretBytes::new(crate::crypto::unwrap_sek(&kek, &km.icv, km.x_sek)?.to_vec());
709 Ok((sek, salt))
710}
711
712#[cfg(feature = "crypto")]
717pub(crate) fn echo_key_material_as_response(km: &KeyMaterial<'_>) -> Result<Vec<u8>> {
718 let mut buf = alloc::vec![0u8; km.serialized_len()];
719 km.serialize_into(&mut buf)?;
720 crate::packet::handshake::build_extension_block(crate::packet::ExtensionType::KmRsp, &buf)
721}
722
723#[cfg(feature = "crypto")]
728pub(crate) fn verify_km_echo(crypto: &CryptoConfig, echoed: &KeyMaterial<'_>) -> bool {
729 let kek = match crate::crypto::derive_kek(&crypto.passphrase, &crypto.salt, crypto.sek.len()) {
730 Ok(k) => k,
731 Err(_) => return false,
732 };
733 let (icv, wrapped) = match crate::crypto::wrap_sek(&kek, &crypto.sek) {
734 Ok(v) => v,
735 Err(_) => return false,
736 };
737 let salt = echoed.salt.ct_eq(crypto.salt.as_slice());
739 let icv = echoed.icv.as_slice().ct_eq(icv.as_slice());
740 let wrapped = echoed.x_sek.ct_eq(wrapped.as_slice());
741 bool::from(salt & icv & wrapped)
742}
743
744pub(crate) fn negotiate_latency_ms(local_latency_ms: u16, peer_msg: &HsExtMessage) -> u16 {
746 local_latency_ms
747 .max(peer_msg.receiver_tsbpd_delay_ms)
748 .max(peer_msg.sender_tsbpd_delay_ms)
749}
750
751fn siphash24(k0: u64, k1: u64, data: &[u8]) -> u64 {
757 const C_ROUNDS: usize = 2;
760 const D_ROUNDS: usize = 4;
761 const INIT_V0: u64 = 0x736f_6d65_7073_6575;
764 const INIT_V1: u64 = 0x646f_7261_6e64_6f6d;
765 const INIT_V2: u64 = 0x6c79_6765_6e65_7261;
766 const INIT_V3: u64 = 0x7465_6462_7974_6573;
767 const FINALIZATION_XOR: u64 = 0xFF;
769
770 let mut v0 = k0 ^ INIT_V0;
771 let mut v1 = k1 ^ INIT_V1;
772 let mut v2 = k0 ^ INIT_V2;
773 let mut v3 = k1 ^ INIT_V3;
774
775 fn round(v0: &mut u64, v1: &mut u64, v2: &mut u64, v3: &mut u64) {
776 *v0 = v0.wrapping_add(*v1);
777 *v1 = v1.rotate_left(13);
778 *v1 ^= *v0;
779 *v0 = v0.rotate_left(32);
780 *v2 = v2.wrapping_add(*v3);
781 *v3 = v3.rotate_left(16);
782 *v3 ^= *v2;
783 *v0 = v0.wrapping_add(*v3);
784 *v3 = v3.rotate_left(21);
785 *v3 ^= *v0;
786 *v2 = v2.wrapping_add(*v1);
787 *v1 = v1.rotate_left(17);
788 *v1 ^= *v2;
789 *v2 = v2.rotate_left(32);
790 }
791
792 let mut chunks = data.chunks_exact(8);
793 for chunk in chunks.by_ref() {
794 let mut word = [0u8; 8];
795 word.copy_from_slice(chunk);
796 let m = u64::from_le_bytes(word);
797 v3 ^= m;
798 for _ in 0..C_ROUNDS {
799 round(&mut v0, &mut v1, &mut v2, &mut v3);
800 }
801 v0 ^= m;
802 }
803 let mut last = [0u8; 8];
806 let rest = chunks.remainder();
807 last[..rest.len()].copy_from_slice(rest);
808 last[7] = u8::try_from(data.len() & 0xFF).unwrap_or(0);
809 let m = u64::from_le_bytes(last);
810 v3 ^= m;
811 for _ in 0..C_ROUNDS {
812 round(&mut v0, &mut v1, &mut v2, &mut v3);
813 }
814 v0 ^= m;
815 v2 ^= FINALIZATION_XOR;
816 for _ in 0..D_ROUNDS {
817 round(&mut v0, &mut v1, &mut v2, &mut v3);
818 }
819 v0 ^ v1 ^ v2 ^ v3
820}
821
822pub fn derive_cookie(peer_key: u64, time_bucket: u32, secret: u128) -> u32 {
839 let mut input = [0u8; 12];
840 input[..8].copy_from_slice(&peer_key.to_le_bytes());
841 input[8..].copy_from_slice(&time_bucket.to_le_bytes());
842 let k0 = u64::try_from(secret & u128::from(u64::MAX)).unwrap_or(0);
843 let k1 = u64::try_from(secret >> 64).unwrap_or(0);
844 let digest = siphash24(k0, k1, &input);
845 u32::try_from(digest & u64::from(u32::MAX)).unwrap_or(0) | 1
848}
849
850#[cfg(test)]
851mod tests {
852 use super::*;
853
854 #[test]
855 fn rejection_reason_round_trips_table_7() {
856 let all = [
857 RejectionReason::Unknown,
858 RejectionReason::System,
859 RejectionReason::Peer,
860 RejectionReason::Resource,
861 RejectionReason::Rogue,
862 RejectionReason::Backlog,
863 RejectionReason::Ipe,
864 RejectionReason::Close,
865 RejectionReason::Version,
866 RejectionReason::RdvCookie,
867 RejectionReason::BadSecret,
868 RejectionReason::Unsecure,
869 RejectionReason::MessageApi,
870 RejectionReason::Congestion,
871 RejectionReason::Filter,
872 RejectionReason::Group,
873 ];
874 for (i, r) in all.iter().enumerate() {
875 assert_eq!(r.to_bits(), 1000 + i as u32);
876 assert_eq!(RejectionReason::from_bits(r.to_bits()), *r);
877 assert_eq!(
878 RejectionReason::from_handshake_type(r.to_handshake_type()),
879 Some(*r)
880 );
881 }
882 }
883
884 #[test]
885 fn non_rejection_handshake_types_are_not_a_rejection() {
886 for ht in [
887 HandshakeType::Induction,
888 HandshakeType::Conclusion,
889 HandshakeType::Wavehand,
890 HandshakeType::Agreement,
891 HandshakeType::Done,
892 ] {
893 assert_eq!(RejectionReason::from_handshake_type(ht), None);
894 }
895 }
896
897 #[test]
898 fn derive_cookie_is_deterministic_and_nonzero() {
899 let a = derive_cookie(0x1234_5678_9ABC_DEF0, 12345, 0xDEAD_BEEF);
900 let b = derive_cookie(0x1234_5678_9ABC_DEF0, 12345, 0xDEAD_BEEF);
901 assert_eq!(a, b);
902 assert_ne!(a, 0);
903 let c = derive_cookie(0x1234_5678_9ABC_DEF1, 12345, 0xDEAD_BEEF);
904 assert_ne!(a, c);
905 }
906
907 #[test]
911 fn only_the_positive_rejection_range_counts_as_a_rejection() {
912 let is_rejection =
913 |v: u32| RejectionReason::from_handshake_type(HandshakeType::from_bits(v)).is_some();
914 assert!(!is_rejection(0xFFFF_FFFC));
915 assert!(!is_rejection(0xFFFF_FFFE)); assert!(!is_rejection(REJECTION_CODE_LIMIT));
917 assert!(!is_rejection(REJECTION_CODE_BASE - 1));
918 assert!(is_rejection(REJECTION_CODE_BASE));
919 assert!(is_rejection(REJECTION_CODE_LIMIT - 1));
920 assert_eq!(
923 RejectionReason::from_handshake_type(HandshakeType::from_bits(1010)),
924 Some(RejectionReason::BadSecret)
925 );
926 assert_eq!(
927 RejectionReason::from_handshake_type(HandshakeType::from_bits(1500)),
928 Some(RejectionReason::Reserved(1500))
929 );
930 assert_eq!(
931 RejectionReason::from_handshake_type(HandshakeType::from_bits(2001)),
932 Some(RejectionReason::Reserved(2001))
933 );
934 }
935
936 #[cfg(feature = "crypto")]
940 #[test]
941 fn caller_kmreq_declares_the_mpeg_ts_srt_encapsulation() {
942 let crypto = CryptoConfig {
943 passphrase: b"0123456789abcdef".to_vec(),
944 salt: [0x33; crate::crypto::SALT_LEN],
945 sek: alloc::vec![0x44; 16],
946 };
947 let ext = build_key_material_extension(&crypto).unwrap();
948 let km = KeyMaterial::parse(&ext[4..]).unwrap();
950 assert_eq!(km.se, StreamEncapsulation::MpegTsSrt);
951 assert_eq!(km.se.to_bits(), 2);
952 assert_eq!(ext[4 + 10], 2);
954 }
955
956 #[test]
959 fn siphash24_matches_the_reference_vector() {
960 let k0 = u64::from_le_bytes([0, 1, 2, 3, 4, 5, 6, 7]);
961 let k1 = u64::from_le_bytes([8, 9, 10, 11, 12, 13, 14, 15]);
962 let input: Vec<u8> = (0u8..15).collect();
963 assert_eq!(siphash24(k0, k1, &input), 0xa129_ca61_49be_45e5);
964 assert_eq!(siphash24(k0, k1, &[]), 0x726f_db47_dd0e_0e31);
966 }
967
968 #[test]
970 fn derive_cookie_depends_on_secret_peer_and_time() {
971 let base = derive_cookie(1, 2, 3);
972 assert_ne!(base, derive_cookie(1, 2, 4), "secret");
973 assert_ne!(base, derive_cookie(9, 2, 3), "peer");
974 assert_ne!(base, derive_cookie(1, 9, 3), "time bucket");
975 assert_eq!(base & 1, 1);
976 assert_eq!(
980 derive_cookie(0x1234_5678_9ABC_DEF0, 12345, 0xDEAD_BEEF),
981 0x5905_9ee9
982 );
983 assert_eq!(
984 derive_cookie(
985 0x1234_5678_9ABC_DEF0,
986 12345,
987 0x0123_4567_89AB_CDEF_FEDC_BA98_7654_3210
988 ),
989 0xec46_1e0b
990 );
991 assert_ne!(
993 derive_cookie(1, 2, 7),
994 derive_cookie(1, 2, 7 | (1u128 << 64)),
995 "the high key half must influence the cookie"
996 );
997 }
998
999 #[cfg(feature = "crypto")]
1005 fn distinctive(seed: u32, len: usize) -> Vec<u8> {
1006 let mut x = seed.wrapping_mul(2_654_435_761).wrapping_add(12_345);
1007 (0..len)
1008 .map(|_| {
1009 x = x.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
1010 u8::try_from(x >> 24).unwrap()
1011 })
1012 .collect()
1013 }
1014
1015 #[cfg(feature = "crypto")]
1017 fn needles(bytes: &[u8]) -> Vec<String> {
1018 let head = &bytes[..6];
1019 let dec = |sep: &str| {
1020 head.iter()
1021 .map(|b| alloc::format!("{b}"))
1022 .collect::<Vec<_>>()
1023 .join(sep)
1024 };
1025 alloc::vec![
1026 dec(", "),
1027 dec(","),
1028 head.iter()
1029 .map(|b| alloc::format!("{b:x}"))
1030 .collect::<Vec<_>>()
1031 .join(", "),
1032 head.iter().map(|b| alloc::format!("{b:02x}")).collect(),
1033 ]
1034 }
1035
1036 #[cfg(feature = "crypto")]
1037 fn secret_config() -> CryptoConfig {
1038 CryptoConfig {
1039 passphrase: distinctive(1, 15),
1040 salt: distinctive(2, crate::crypto::SALT_LEN).try_into().unwrap(),
1041 sek: distinctive(3, 16),
1042 }
1043 }
1044
1045 #[cfg(feature = "crypto")]
1048 #[test]
1049 fn crypto_config_debug_never_shows_secret_bytes() {
1050 let config = HandshakeConfig {
1051 crypto: Some(secret_config()),
1052 ..HandshakeConfig::default()
1053 };
1054 for dump in [
1055 alloc::format!("{:?}", secret_config()),
1056 alloc::format!("{:#?}", secret_config()),
1057 alloc::format!("{:?}", config),
1058 alloc::format!("{:#?}", config),
1059 alloc::format!("{:x?}", config),
1060 ] {
1061 let secret = secret_config();
1062 for (name, bytes) in [
1063 ("passphrase", &secret.passphrase[..]),
1064 ("salt", &secret.salt[..]),
1065 ("sek", &secret.sek[..]),
1066 ] {
1067 for needle in needles(bytes) {
1068 assert!(
1069 !dump.contains(&needle),
1070 "{name} leaked as {needle:?}: {dump}"
1071 );
1072 }
1073 }
1074 assert!(dump.contains("redacted"), "{dump}");
1075 }
1076 assert!(alloc::format!("{:?}", secret_config()).contains("15 bytes"));
1077 }
1078
1079 #[cfg(feature = "crypto")]
1082 #[test]
1083 fn negotiated_sek_is_redacted_in_debug_and_absent_from_serde() {
1084 let sek_bytes = distinctive(9, 16);
1085 let params = NegotiatedParams {
1086 version: HANDSHAKE_VERSION_5,
1087 flags: HandshakeExtensionMessageFlags(0),
1088 latency_ms: 120,
1089 own_socket_id: 1,
1090 peer_socket_id: 2,
1091 mtu: 1500,
1092 max_flow_window_size: 8192,
1093 stream_id: None,
1094 group: None,
1095 sek: Some(SecretBytes::new(sek_bytes.clone())),
1096 salt: Some([0x11; crate::crypto::SALT_LEN]),
1097 };
1098 for dump in [
1099 alloc::format!("{params:?}"),
1100 alloc::format!("{:#?}", HandshakeOutput::Connected(params.clone())),
1101 alloc::format!("{:x?}", HandshakeOutput::Connected(params.clone())),
1102 ] {
1103 for needle in needles(&sek_bytes) {
1104 assert!(!dump.contains(&needle), "SEK leaked as {needle:?}: {dump}");
1105 }
1106 assert!(dump.contains("redacted"), "{dump}");
1107 }
1108 #[cfg(feature = "serde")]
1109 {
1110 let json = serde_json::to_string(¶ms).expect("serialize");
1111 assert!(!json.contains("sek"), "the SEK was serialized: {json}");
1112 for needle in needles(&sek_bytes) {
1113 assert!(!json.contains(&needle), "SEK leaked as {needle:?}: {json}");
1114 }
1115 }
1116 }
1117
1118 #[cfg(feature = "crypto")]
1122 #[test]
1123 fn secrets_compare_correctly_and_wipe_on_zeroize() {
1124 let a = SecretBytes::new(alloc::vec![1, 2, 3, 4]);
1125 assert!(a == SecretBytes::new(alloc::vec![1, 2, 3, 4]));
1126 assert!(a != SecretBytes::new(alloc::vec![1, 2, 3, 5]));
1127 assert!(a != SecretBytes::new(alloc::vec![1, 2, 3]));
1128 assert_eq!(&*a, &[1u8, 2, 3, 4][..]);
1129
1130 let mut sek = SecretBytes::new(alloc::vec![9; 16]);
1131 sek.zeroize();
1132 assert!(sek.is_empty(), "zeroize must clear the key");
1133
1134 let mut config = secret_config();
1135 assert!(config == secret_config());
1136 let mut other = secret_config();
1137 other.sek[0] ^= 1;
1138 assert!(config != other);
1139 config.zeroize();
1140 assert!(config.passphrase.is_empty() && config.sek.is_empty());
1141 assert_eq!(config.salt, [0u8; crate::crypto::SALT_LEN]);
1142 }
1143
1144 #[cfg(feature = "crypto")]
1146 #[test]
1147 fn secret_holders_are_zeroize_on_drop() {
1148 fn assert_zeroize_on_drop<T: zeroize::ZeroizeOnDrop>() {}
1149 assert_zeroize_on_drop::<CryptoConfig>();
1150 assert_zeroize_on_drop::<SecretBytes>();
1151 }
1152}