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)]
377pub struct HandshakeConfig {
378 pub latency_ms: u16,
383 pub mtu: u32,
385 pub max_flow_window_size: u32,
387 pub initial_seq_number: u32,
391 pub srt_version: u32,
394 pub flags: HandshakeExtensionMessageFlags,
396 pub encryption_field: EncryptionField,
400 pub stream_id: Option<String>,
403 pub group: Option<GroupMembershipExtension>,
406 pub local_ip: [u32; 4],
411 pub retransmit_after_ticks: u32,
416 pub max_retries: u32,
419 #[cfg(feature = "crypto")]
424 #[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
425 pub crypto: Option<CryptoConfig>,
426}
427
428pub const DEFAULT_MAX_RETRIES: u32 = 12;
433
434impl Default for HandshakeConfig {
435 fn default() -> Self {
436 HandshakeConfig {
437 latency_ms: 120,
438 mtu: 1500,
439 max_flow_window_size: 8192,
440 initial_seq_number: 0,
441 srt_version: 0x0105_0000,
442 flags: HandshakeExtensionMessageFlags(
443 crate::packet::handshake::HS_MSG_FLAG_TSBPDSND
444 | crate::packet::handshake::HS_MSG_FLAG_TSBPDRCV
445 | crate::packet::handshake::HS_MSG_FLAG_CRYPT
446 | crate::packet::handshake::HS_MSG_FLAG_TLPKTDROP
447 | crate::packet::handshake::HS_MSG_FLAG_PERIODICNAK
448 | crate::packet::handshake::HS_MSG_FLAG_REXMITFLG,
449 ),
450 encryption_field: EncryptionField::NoEncryption,
451 stream_id: None,
452 group: None,
453 local_ip: [0, 0, 0, 0],
454 retransmit_after_ticks: 3,
455 max_retries: DEFAULT_MAX_RETRIES,
456 #[cfg(feature = "crypto")]
457 crypto: None,
458 }
459 }
460}
461
462#[derive(Debug, Clone, PartialEq)]
467#[cfg_attr(feature = "serde", derive(serde::Serialize))]
468pub struct NegotiatedParams {
469 pub version: u32,
472 pub flags: HandshakeExtensionMessageFlags,
475 pub latency_ms: u16,
479 pub own_socket_id: u32,
481 pub peer_socket_id: u32,
483 pub mtu: u32,
487 pub max_flow_window_size: u32,
492 pub stream_id: Option<String>,
494 pub group: Option<GroupMembershipExtension>,
496 #[cfg(feature = "crypto")]
503 #[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
504 #[cfg_attr(feature = "serde", serde(skip))]
505 pub sek: Option<SecretBytes>,
506 #[cfg(feature = "crypto")]
510 #[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
511 pub salt: Option<[u8; crate::crypto::SALT_LEN]>,
512}
513
514#[derive(Debug, Clone, PartialEq)]
518#[cfg_attr(feature = "serde", derive(serde::Serialize))]
519#[non_exhaustive]
520pub enum HandshakeOutput {
521 Send(Vec<u8>),
524 Connected(NegotiatedParams),
526 Rejected(RejectionReason),
531 TimedOut,
534}
535
536pub(crate) enum RetransmitStep {
538 Idle,
539 Resend(Vec<u8>),
540 TimedOut,
541}
542
543impl RetransmitStep {
544 pub(crate) fn into_outputs(self) -> Vec<HandshakeOutput> {
545 match self {
546 Self::Idle => Vec::new(),
547 Self::Resend(bytes) => vec![HandshakeOutput::Send(bytes)],
548 Self::TimedOut => vec![HandshakeOutput::TimedOut],
549 }
550 }
551}
552
553#[derive(Debug, Default)]
557pub(crate) struct Retransmit {
558 last_sent: Option<Vec<u8>>,
559 ticks_since_send: u32,
560 retries: u32,
561}
562
563impl Retransmit {
564 pub(crate) fn remember(&mut self, bytes: &[u8]) {
565 self.last_sent = Some(bytes.to_vec());
566 }
567
568 pub(crate) fn arm(&mut self, bytes: &[u8]) {
569 self.remember(bytes);
570 self.ticks_since_send = 0;
571 }
572
573 pub(crate) fn arm_fresh(&mut self, bytes: &[u8]) {
574 self.arm(bytes);
575 self.retries = 0;
576 }
577
578 pub(crate) fn last_sent(&self) -> Option<&[u8]> {
579 self.last_sent.as_deref()
580 }
581
582 pub(crate) fn tick(&mut self, config: &HandshakeConfig) -> RetransmitStep {
586 self.ticks_since_send += 1;
587 if self.ticks_since_send < config.retransmit_after_ticks {
588 return RetransmitStep::Idle;
589 }
590 self.ticks_since_send = 0;
591 self.retries += 1;
592 if self.retries > config.max_retries {
593 return RetransmitStep::TimedOut;
594 }
595 self.last_sent
596 .clone()
597 .map_or(RetransmitStep::Idle, RetransmitStep::Resend)
598 }
599}
600
601pub(crate) fn build_bytes(hp: HandshakePacket<'_>) -> Result<Vec<u8>> {
604 let pkt = ControlPacket::Handshake(hp);
605 let mut buf = alloc::vec![0u8; pkt.serialized_len()];
606 pkt.serialize_into(&mut buf)?;
607 Ok(buf)
608}
609
610pub(crate) fn build_conclusion_extensions(
614 hs_ext_type: crate::packet::ExtensionType,
615 hs_msg: &HsExtMessage,
616 stream_id: Option<&str>,
617 group: Option<GroupMembershipExtension>,
618) -> Result<(Vec<u8>, u16)> {
619 use crate::packet::handshake::{build_extension_block, encode_stream_id};
620
621 let mut ext_bytes = Vec::new();
622 ext_bytes.extend(build_extension_block(hs_ext_type, &hs_msg.to_bytes())?);
623 let mut ext_flags = HS_EXT_FLAG_HSREQ;
624 if let Some(sid) = stream_id {
625 let sid_bytes = encode_stream_id(sid);
626 ext_bytes.extend(build_extension_block(
627 crate::packet::ExtensionType::Sid,
628 &sid_bytes,
629 )?);
630 ext_flags |= HS_EXT_FLAG_CONFIG;
631 }
632 if let Some(g) = group {
633 ext_bytes.extend(build_extension_block(
634 crate::packet::ExtensionType::Group,
635 &g.to_bytes(),
636 )?);
637 ext_flags |= HS_EXT_FLAG_CONFIG;
638 }
639 Ok((ext_bytes, ext_flags))
640}
641
642#[derive(Debug, Default)]
646pub(crate) struct ParsedPeerExtensions<'a> {
647 pub hs_msg: Option<HsExtMessage>,
648 pub stream_id: Option<String>,
649 pub group: Option<GroupMembershipExtension>,
650 #[cfg(feature = "crypto")]
657 pub km: Option<KeyMaterial<'a>>,
658 #[cfg(not(feature = "crypto"))]
661 _phantom: core::marker::PhantomData<&'a ()>,
662}
663
664pub(crate) fn parse_peer_extensions<'a>(
669 hp: &HandshakePacket<'a>,
670) -> Result<ParsedPeerExtensions<'a>> {
671 use crate::packet::ExtensionType;
672
673 let mut out = ParsedPeerExtensions::default();
674 for block in hp.extensions.iter() {
675 let block = block.map_err(|_| {
676 Error::InvalidField(InvalidField {
677 field: "handshake extensions",
678 reason: "malformed extension block",
679 })
680 })?;
681 match block.ext_type {
682 ExtensionType::HsReq | ExtensionType::HsRsp => {
683 let msg = block.as_hs_ext_message().map_err(|_| {
684 Error::InvalidField(InvalidField {
685 field: "handshake extension message",
686 reason: "malformed HSREQ/HSRSP contents",
687 })
688 })?;
689 out.hs_msg = Some(msg);
690 }
691 ExtensionType::Sid => {
692 let sid = block.as_stream_id().map_err(|_| {
693 Error::InvalidField(InvalidField {
694 field: "stream ID extension",
695 reason: "malformed or non-UTF-8 contents",
696 })
697 })?;
698 out.stream_id = Some(sid);
699 }
700 ExtensionType::Group => {
701 let g = block.as_group_membership().map_err(|_| {
702 Error::InvalidField(InvalidField {
703 field: "group membership extension",
704 reason: "malformed contents",
705 })
706 })?;
707 out.group = Some(g);
708 }
709 #[cfg(feature = "crypto")]
710 ExtensionType::KmReq | ExtensionType::KmRsp => {
711 let km = block.as_key_material().map_err(|_| {
712 Error::InvalidField(InvalidField {
713 field: "key material extension",
714 reason: "malformed contents",
715 })
716 })?;
717 out.km = Some(km);
718 }
719 _ => {}
720 }
721 }
722 Ok(out)
723}
724
725#[cfg(feature = "crypto")]
738pub(crate) fn build_key_material_extension(crypto: &CryptoConfig) -> Result<Vec<u8>> {
739 let kek = crate::crypto::derive_kek(&crypto.passphrase, &crypto.salt, crypto.sek.len())?;
740 let (icv, wrapped) = crate::crypto::wrap_sek(&kek, &crypto.sek)?;
741 let km = KeyMaterial {
742 kk: KmKeyFlag::Even,
743 keki: 0,
744 cipher: Cipher::AesCtr,
745 auth: KmAuth::None,
746 se: StreamEncapsulation::MpegTsSrt,
747 salt: &crypto.salt,
748 icv,
749 x_sek: &wrapped,
750 o_sek: None,
751 };
752 let mut buf = alloc::vec![0u8; km.serialized_len()];
753 km.serialize_into(&mut buf)?;
754 crate::packet::handshake::build_extension_block(crate::packet::ExtensionType::KmReq, &buf)
755}
756
757#[cfg(feature = "crypto")]
759pub(crate) type RecoveredSek = (SecretBytes, [u8; crate::crypto::SALT_LEN]);
760
761#[cfg(feature = "crypto")]
773pub(crate) fn recover_sek(passphrase: &[u8], km: &KeyMaterial<'_>) -> Result<RecoveredSek> {
774 if km.salt.len() != crate::crypto::SALT_LEN {
775 return Err(Error::InvalidField(InvalidField {
776 field: "Key Material Salt",
777 reason: "must be 16 bytes (the only Salt length this crate's codec accepts)",
778 }));
779 }
780 let mut salt = [0u8; crate::crypto::SALT_LEN];
781 salt.copy_from_slice(km.salt);
782 let kek = crate::crypto::derive_kek(passphrase, &salt, km.x_sek.len())?;
783 let sek = SecretBytes::new(crate::crypto::unwrap_sek(&kek, &km.icv, km.x_sek)?.to_vec());
784 Ok((sek, salt))
785}
786
787#[cfg(feature = "crypto")]
792pub(crate) fn echo_key_material_as_response(km: &KeyMaterial<'_>) -> Result<Vec<u8>> {
793 let mut buf = alloc::vec![0u8; km.serialized_len()];
794 km.serialize_into(&mut buf)?;
795 crate::packet::handshake::build_extension_block(crate::packet::ExtensionType::KmRsp, &buf)
796}
797
798#[cfg(feature = "crypto")]
803pub(crate) fn verify_km_echo(crypto: &CryptoConfig, echoed: &KeyMaterial<'_>) -> bool {
804 let kek = match crate::crypto::derive_kek(&crypto.passphrase, &crypto.salt, crypto.sek.len()) {
805 Ok(k) => k,
806 Err(_) => return false,
807 };
808 let (icv, wrapped) = match crate::crypto::wrap_sek(&kek, &crypto.sek) {
809 Ok(v) => v,
810 Err(_) => return false,
811 };
812 let salt = echoed.salt.ct_eq(crypto.salt.as_slice());
814 let icv = echoed.icv.as_slice().ct_eq(icv.as_slice());
815 let wrapped = echoed.x_sek.ct_eq(wrapped.as_slice());
816 bool::from(salt & icv & wrapped)
817}
818
819pub(crate) fn negotiate_latency_ms(local_latency_ms: u16, peer_msg: &HsExtMessage) -> u16 {
821 local_latency_ms
822 .max(peer_msg.receiver_tsbpd_delay_ms)
823 .max(peer_msg.sender_tsbpd_delay_ms)
824}
825
826fn siphash24(k0: u64, k1: u64, data: &[u8]) -> u64 {
832 const C_ROUNDS: usize = 2;
835 const D_ROUNDS: usize = 4;
836 const INIT_V0: u64 = 0x736f_6d65_7073_6575;
839 const INIT_V1: u64 = 0x646f_7261_6e64_6f6d;
840 const INIT_V2: u64 = 0x6c79_6765_6e65_7261;
841 const INIT_V3: u64 = 0x7465_6462_7974_6573;
842 const FINALIZATION_XOR: u64 = 0xFF;
844
845 let mut v0 = k0 ^ INIT_V0;
846 let mut v1 = k1 ^ INIT_V1;
847 let mut v2 = k0 ^ INIT_V2;
848 let mut v3 = k1 ^ INIT_V3;
849
850 fn round(v0: &mut u64, v1: &mut u64, v2: &mut u64, v3: &mut u64) {
851 *v0 = v0.wrapping_add(*v1);
852 *v1 = v1.rotate_left(13);
853 *v1 ^= *v0;
854 *v0 = v0.rotate_left(32);
855 *v2 = v2.wrapping_add(*v3);
856 *v3 = v3.rotate_left(16);
857 *v3 ^= *v2;
858 *v0 = v0.wrapping_add(*v3);
859 *v3 = v3.rotate_left(21);
860 *v3 ^= *v0;
861 *v2 = v2.wrapping_add(*v1);
862 *v1 = v1.rotate_left(17);
863 *v1 ^= *v2;
864 *v2 = v2.rotate_left(32);
865 }
866
867 let mut chunks = data.chunks_exact(8);
868 for chunk in chunks.by_ref() {
869 let mut word = [0u8; 8];
870 word.copy_from_slice(chunk);
871 let m = u64::from_le_bytes(word);
872 v3 ^= m;
873 for _ in 0..C_ROUNDS {
874 round(&mut v0, &mut v1, &mut v2, &mut v3);
875 }
876 v0 ^= m;
877 }
878 let mut last = [0u8; 8];
881 let rest = chunks.remainder();
882 last[..rest.len()].copy_from_slice(rest);
883 last[7] = u8::try_from(data.len() & 0xFF).unwrap_or(0);
884 let m = u64::from_le_bytes(last);
885 v3 ^= m;
886 for _ in 0..C_ROUNDS {
887 round(&mut v0, &mut v1, &mut v2, &mut v3);
888 }
889 v0 ^= m;
890 v2 ^= FINALIZATION_XOR;
891 for _ in 0..D_ROUNDS {
892 round(&mut v0, &mut v1, &mut v2, &mut v3);
893 }
894 v0 ^ v1 ^ v2 ^ v3
895}
896
897pub fn derive_cookie(peer_key: u64, time_bucket: u32, secret: u128) -> u32 {
914 let mut input = [0u8; 12];
915 input[..8].copy_from_slice(&peer_key.to_le_bytes());
916 input[8..].copy_from_slice(&time_bucket.to_le_bytes());
917 let k0 = u64::try_from(secret & u128::from(u64::MAX)).unwrap_or(0);
918 let k1 = u64::try_from(secret >> 64).unwrap_or(0);
919 let digest = siphash24(k0, k1, &input);
920 u32::try_from(digest & u64::from(u32::MAX)).unwrap_or(0) | 1
923}
924
925#[cfg(test)]
926mod tests {
927 use super::*;
928
929 #[test]
930 fn rejection_reason_round_trips_table_7() {
931 let all = [
932 RejectionReason::Unknown,
933 RejectionReason::System,
934 RejectionReason::Peer,
935 RejectionReason::Resource,
936 RejectionReason::Rogue,
937 RejectionReason::Backlog,
938 RejectionReason::Ipe,
939 RejectionReason::Close,
940 RejectionReason::Version,
941 RejectionReason::RdvCookie,
942 RejectionReason::BadSecret,
943 RejectionReason::Unsecure,
944 RejectionReason::MessageApi,
945 RejectionReason::Congestion,
946 RejectionReason::Filter,
947 RejectionReason::Group,
948 ];
949 for (i, r) in all.iter().enumerate() {
950 assert_eq!(r.to_bits(), 1000 + i as u32);
951 assert_eq!(RejectionReason::from_bits(r.to_bits()), *r);
952 assert_eq!(
953 RejectionReason::from_handshake_type(r.to_handshake_type()),
954 Some(*r)
955 );
956 }
957 }
958
959 #[test]
960 fn non_rejection_handshake_types_are_not_a_rejection() {
961 for ht in [
962 HandshakeType::Induction,
963 HandshakeType::Conclusion,
964 HandshakeType::Wavehand,
965 HandshakeType::Agreement,
966 HandshakeType::Done,
967 ] {
968 assert_eq!(RejectionReason::from_handshake_type(ht), None);
969 }
970 }
971
972 #[test]
973 fn derive_cookie_is_deterministic_and_nonzero() {
974 let a = derive_cookie(0x1234_5678_9ABC_DEF0, 12345, 0xDEAD_BEEF);
975 let b = derive_cookie(0x1234_5678_9ABC_DEF0, 12345, 0xDEAD_BEEF);
976 assert_eq!(a, b);
977 assert_ne!(a, 0);
978 let c = derive_cookie(0x1234_5678_9ABC_DEF1, 12345, 0xDEAD_BEEF);
979 assert_ne!(a, c);
980 }
981
982 #[test]
986 fn only_the_positive_rejection_range_counts_as_a_rejection() {
987 let is_rejection =
988 |v: u32| RejectionReason::from_handshake_type(HandshakeType::from_bits(v)).is_some();
989 assert!(!is_rejection(0xFFFF_FFFC));
990 assert!(!is_rejection(0xFFFF_FFFE)); assert!(!is_rejection(REJECTION_CODE_LIMIT));
992 assert!(!is_rejection(REJECTION_CODE_BASE - 1));
993 assert!(is_rejection(REJECTION_CODE_BASE));
994 assert!(is_rejection(REJECTION_CODE_LIMIT - 1));
995 assert_eq!(
998 RejectionReason::from_handshake_type(HandshakeType::from_bits(1010)),
999 Some(RejectionReason::BadSecret)
1000 );
1001 assert_eq!(
1002 RejectionReason::from_handshake_type(HandshakeType::from_bits(1500)),
1003 Some(RejectionReason::Reserved(1500))
1004 );
1005 assert_eq!(
1006 RejectionReason::from_handshake_type(HandshakeType::from_bits(2001)),
1007 Some(RejectionReason::Reserved(2001))
1008 );
1009 }
1010
1011 #[cfg(feature = "crypto")]
1015 #[test]
1016 fn caller_kmreq_declares_the_mpeg_ts_srt_encapsulation() {
1017 let crypto = CryptoConfig {
1018 passphrase: b"0123456789abcdef".to_vec(),
1019 salt: [0x33; crate::crypto::SALT_LEN],
1020 sek: alloc::vec![0x44; 16],
1021 };
1022 let ext = build_key_material_extension(&crypto).unwrap();
1023 let km = KeyMaterial::parse(&ext[4..]).unwrap();
1025 assert_eq!(km.se, StreamEncapsulation::MpegTsSrt);
1026 assert_eq!(km.se.to_bits(), 2);
1027 assert_eq!(ext[4 + 10], 2);
1029 }
1030
1031 #[test]
1034 fn siphash24_matches_the_reference_vector() {
1035 let k0 = u64::from_le_bytes([0, 1, 2, 3, 4, 5, 6, 7]);
1036 let k1 = u64::from_le_bytes([8, 9, 10, 11, 12, 13, 14, 15]);
1037 let input: Vec<u8> = (0u8..15).collect();
1038 assert_eq!(siphash24(k0, k1, &input), 0xa129_ca61_49be_45e5);
1039 assert_eq!(siphash24(k0, k1, &[]), 0x726f_db47_dd0e_0e31);
1041 }
1042
1043 #[test]
1045 fn derive_cookie_depends_on_secret_peer_and_time() {
1046 let base = derive_cookie(1, 2, 3);
1047 assert_ne!(base, derive_cookie(1, 2, 4), "secret");
1048 assert_ne!(base, derive_cookie(9, 2, 3), "peer");
1049 assert_ne!(base, derive_cookie(1, 9, 3), "time bucket");
1050 assert_eq!(base & 1, 1);
1051 assert_eq!(
1055 derive_cookie(0x1234_5678_9ABC_DEF0, 12345, 0xDEAD_BEEF),
1056 0x5905_9ee9
1057 );
1058 assert_eq!(
1059 derive_cookie(
1060 0x1234_5678_9ABC_DEF0,
1061 12345,
1062 0x0123_4567_89AB_CDEF_FEDC_BA98_7654_3210
1063 ),
1064 0xec46_1e0b
1065 );
1066 assert_ne!(
1068 derive_cookie(1, 2, 7),
1069 derive_cookie(1, 2, 7 | (1u128 << 64)),
1070 "the high key half must influence the cookie"
1071 );
1072 }
1073
1074 #[cfg(feature = "crypto")]
1080 fn distinctive(seed: u32, len: usize) -> Vec<u8> {
1081 let mut x = seed.wrapping_mul(2_654_435_761).wrapping_add(12_345);
1082 (0..len)
1083 .map(|_| {
1084 x = x.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
1085 u8::try_from(x >> 24).unwrap()
1086 })
1087 .collect()
1088 }
1089
1090 #[cfg(feature = "crypto")]
1092 fn needles(bytes: &[u8]) -> Vec<String> {
1093 let head = &bytes[..6];
1094 let dec = |sep: &str| {
1095 head.iter()
1096 .map(|b| alloc::format!("{b}"))
1097 .collect::<Vec<_>>()
1098 .join(sep)
1099 };
1100 alloc::vec![
1101 dec(", "),
1102 dec(","),
1103 head.iter()
1104 .map(|b| alloc::format!("{b:x}"))
1105 .collect::<Vec<_>>()
1106 .join(", "),
1107 head.iter().map(|b| alloc::format!("{b:02x}")).collect(),
1108 ]
1109 }
1110
1111 #[cfg(feature = "crypto")]
1112 fn secret_config() -> CryptoConfig {
1113 CryptoConfig {
1114 passphrase: distinctive(1, 15),
1115 salt: distinctive(2, crate::crypto::SALT_LEN).try_into().unwrap(),
1116 sek: distinctive(3, 16),
1117 }
1118 }
1119
1120 #[cfg(feature = "crypto")]
1123 #[test]
1124 fn crypto_config_debug_never_shows_secret_bytes() {
1125 let config = HandshakeConfig {
1126 crypto: Some(secret_config()),
1127 ..HandshakeConfig::default()
1128 };
1129 for dump in [
1130 alloc::format!("{:?}", secret_config()),
1131 alloc::format!("{:#?}", secret_config()),
1132 alloc::format!("{:?}", config),
1133 alloc::format!("{:#?}", config),
1134 alloc::format!("{:x?}", config),
1135 ] {
1136 let secret = secret_config();
1137 for (name, bytes) in [
1138 ("passphrase", &secret.passphrase[..]),
1139 ("salt", &secret.salt[..]),
1140 ("sek", &secret.sek[..]),
1141 ] {
1142 for needle in needles(bytes) {
1143 assert!(
1144 !dump.contains(&needle),
1145 "{name} leaked as {needle:?}: {dump}"
1146 );
1147 }
1148 }
1149 assert!(dump.contains("redacted"), "{dump}");
1150 }
1151 assert!(alloc::format!("{:?}", secret_config()).contains("15 bytes"));
1152 }
1153
1154 #[cfg(feature = "crypto")]
1157 #[test]
1158 fn negotiated_sek_is_redacted_in_debug_and_absent_from_serde() {
1159 let sek_bytes = distinctive(9, 16);
1160 let params = NegotiatedParams {
1161 version: HANDSHAKE_VERSION_5,
1162 flags: HandshakeExtensionMessageFlags(0),
1163 latency_ms: 120,
1164 own_socket_id: 1,
1165 peer_socket_id: 2,
1166 mtu: 1500,
1167 max_flow_window_size: 8192,
1168 stream_id: None,
1169 group: None,
1170 sek: Some(SecretBytes::new(sek_bytes.clone())),
1171 salt: Some([0x11; crate::crypto::SALT_LEN]),
1172 };
1173 for dump in [
1174 alloc::format!("{params:?}"),
1175 alloc::format!("{:#?}", HandshakeOutput::Connected(params.clone())),
1176 alloc::format!("{:x?}", HandshakeOutput::Connected(params.clone())),
1177 ] {
1178 for needle in needles(&sek_bytes) {
1179 assert!(!dump.contains(&needle), "SEK leaked as {needle:?}: {dump}");
1180 }
1181 assert!(dump.contains("redacted"), "{dump}");
1182 }
1183 #[cfg(feature = "serde")]
1184 {
1185 let json = serde_json::to_string(¶ms).expect("serialize");
1186 assert!(!json.contains("sek"), "the SEK was serialized: {json}");
1187 for needle in needles(&sek_bytes) {
1188 assert!(!json.contains(&needle), "SEK leaked as {needle:?}: {json}");
1189 }
1190 }
1191 }
1192
1193 #[cfg(feature = "crypto")]
1197 #[test]
1198 fn secrets_compare_correctly_and_wipe_on_zeroize() {
1199 let a = SecretBytes::new(alloc::vec![1, 2, 3, 4]);
1200 assert!(a == SecretBytes::new(alloc::vec![1, 2, 3, 4]));
1201 assert!(a != SecretBytes::new(alloc::vec![1, 2, 3, 5]));
1202 assert!(a != SecretBytes::new(alloc::vec![1, 2, 3]));
1203 assert_eq!(&*a, &[1u8, 2, 3, 4][..]);
1204
1205 let mut sek = SecretBytes::new(alloc::vec![9; 16]);
1206 sek.zeroize();
1207 assert!(sek.is_empty(), "zeroize must clear the key");
1208
1209 let mut config = secret_config();
1210 assert!(config == secret_config());
1211 let mut other = secret_config();
1212 other.sek[0] ^= 1;
1213 assert!(config != other);
1214 config.zeroize();
1215 assert!(config.passphrase.is_empty() && config.sek.is_empty());
1216 assert_eq!(config.salt, [0u8; crate::crypto::SALT_LEN]);
1217 }
1218
1219 #[cfg(feature = "crypto")]
1221 #[test]
1222 fn secret_holders_are_zeroize_on_drop() {
1223 fn assert_zeroize_on_drop<T: zeroize::ZeroizeOnDrop>() {}
1224 assert_zeroize_on_drop::<CryptoConfig>();
1225 assert_zeroize_on_drop::<SecretBytes>();
1226 }
1227}