Skip to main content

srt_runtime/
handshake_sm.rs

1//! Shared types for the sans-IO HSv5 handshake state machine —
2//! `draft-sharabayko-srt-01` §4.3 (Handshake Messages) / §4.3.1
3//! (Caller-Listener Handshake).
4//!
5//! This module holds the pieces [`crate::caller::CallerHandshake`] and
6//! [`crate::listener::ListenerHandshake`] share: the negotiation input
7//! ([`HandshakeConfig`]), the negotiation output ([`NegotiatedParams`]), the
8//! event type both engines emit ([`HandshakeOutput`]), and the Handshake
9//! Rejection Reason codes (§4.3, Table 7) as a typed [`RejectionReason`].
10//!
11//! This module also holds the `crypto`-feature-gated §6.1.5 Key Material
12//! Exchange helpers ([`CryptoConfig`], `build_key_material_extension`,
13//! `recover_sek`, `echo_key_material_as_response`, `verify_km_echo`) shared
14//! by [`crate::caller::CallerHandshake`] / [`crate::listener::ListenerHandshake`]
15//! — see [`CryptoConfig`]'s doc and `private/specs-verified/rules/srt-crypto.md`. Congestion
16//! control beyond LiveCC packet pacing is an explicit follow-up — see the
17//! crate root docs.
18
19use 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
39/// A base protocol version number of `4` — the value the Caller's INDUCTION
40/// handshake MUST always carry (`draft-sharabayko-srt-01` §4.3.1.1), kept for
41/// UDT compatibility.
42pub const HANDSHAKE_VERSION_4: u32 = 4;
43/// A base protocol version number of `5` — HSv5, used by every handshake
44/// message from the Listener's INDUCTION response onward (§4.3.1.1/§4.3.1.2).
45pub const HANDSHAKE_VERSION_5: u32 = 5;
46
47/// The `Extension Field` value the Listener echoes on its INDUCTION response
48/// so the Caller can recognise it as an SRT (not legacy UDT) party
49/// (`draft-sharabayko-srt-01` §4.3.1.1: "SRT magic code 0x4A17").
50pub const SRT_MAGIC_CODE: u16 = 0x4A17;
51
52/// The `Extension Field` value the Caller sets on its very first INDUCTION
53/// handshake (§4.3.1.1: "Extension Field: 2"). This is *not* the §3.2.1
54/// Table 3 `Extension Flags` bitmask (whose `KMREQ` bit happens to share the
55/// same numeric value) — it is a legacy UDT socket-type field (`UDT_DGRAM`)
56/// carried over because the INDUCTION handshake is version-4-shaped for UDT
57/// compatibility.
58pub const INDUCTION_LEGACY_SOCKET_TYPE: u16 = 2;
59
60/// The base wire value of the Handshake Rejection Reason codes
61/// (`draft-sharabayko-srt-01` §4.3, Table 7): a rejected connection's
62/// `Handshake Type` field carries `1000 + <code>`.
63pub const REJECTION_CODE_BASE: u32 = 1000;
64
65/// One past the largest `Handshake Type` value read as a rejection: libsrt's
66/// request type is a signed 32-bit integer, so everything from `2^31` up is
67/// the negative `URQ_*` range, never a rejection reason (see
68/// [`RejectionReason::from_handshake_type`]).
69pub const REJECTION_CODE_LIMIT: u32 = 0x8000_0000;
70
71/// Handshake Rejection Reason (`draft-sharabayko-srt-01` §4.3, Table 7). Sent
72/// in place of a normal `Handshake Type` value (`1000 + code`, decoded via
73/// [`HandshakeType::Reserved`]) when a connection attempt is refused.
74#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
75#[cfg_attr(feature = "serde", derive(serde::Serialize))]
76#[non_exhaustive]
77pub enum RejectionReason {
78    /// `1000`: unknown reason.
79    Unknown,
80    /// `1001`: system function error.
81    System,
82    /// `1002`: rejected by peer.
83    Peer,
84    /// `1003`: resource allocation problem.
85    Resource,
86    /// `1004`: incorrect data in handshake.
87    Rogue,
88    /// `1005`: listener's backlog exceeded.
89    Backlog,
90    /// `1006`: internal program error.
91    Ipe,
92    /// `1007`: socket is closing.
93    Close,
94    /// `1008`: peer is an older version than the agent's minimum.
95    Version,
96    /// `1009`: rendezvous cookie collision.
97    RdvCookie,
98    /// `1010`: wrong password.
99    BadSecret,
100    /// `1011`: password required or unexpected.
101    Unsecure,
102    /// `1012`: stream flag collision.
103    MessageApi,
104    /// `1013`: incompatible congestion-controller type.
105    Congestion,
106    /// `1014`: incompatible packet filter.
107    Filter,
108    /// `1015`: incompatible group.
109    Group,
110    /// A `1000 + code` value Table 7 does not define.
111    Reserved(u32),
112}
113
114impl RejectionReason {
115    /// Decode a Table 7 wire code (the value carried in `Handshake Type`,
116    /// i.e. already `1000 + code`).
117    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    /// The wire code (`1000 + code`), as carried in `Handshake Type`.
140    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    /// Spec label (Table 7).
163    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    /// Recover the [`RejectionReason`] a peer sent back as a `Handshake
186    /// Type`, or `None` if `ht` is a normal (non-rejection) handshake type.
187    ///
188    /// Only `1000..`[`REJECTION_CODE_LIMIT`] is a rejection: libsrt carries the
189    /// handshake request type as a *signed* 32-bit integer whose negative
190    /// values (the `URQ_*` family, e.g. `CONCLUSION` = -1 = `0xFFFF_FFFF`)
191    /// are handshake types, not reasons, so an undefined value such as
192    /// `0xFFFF_FFFC` is not a rejection.
193    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    /// Encode as the `Handshake Type` value a rejection packet carries.
205    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/// Opt-in §6 payload-encryption config for one side of a Caller-Listener
213/// handshake (`draft-sharabayko-srt-01` §6.1.5, Key Material Exchange —
214/// curated at `private/specs-verified/rules/srt-crypto.md`). `None` on
215/// [`HandshakeConfig::crypto`] (the default) disables the encryption path
216/// entirely: no Key Material extension is sent, and a peer that sends one
217/// unexpectedly is rejected ([`RejectionReason::Unsecure`]).
218///
219/// This crate's sans-IO core never reads OS randomness — the same design
220/// choice as [`derive_cookie`]'s caller-supplied `time_bucket`/`secret`
221/// inputs, or [`crate::io`]'s OS-random SYN Cookie key.
222/// [`Self::salt`] and, on the initiator, [`Self::sek`] must be freshly
223/// generated by the caller/driver (e.g. a `tokio` adapter with access to a
224/// real CSPRNG) for **every new connection** (§6.2.1: `Salt = PRNG(128)`,
225/// `SEK = PRNG(KLen)`) and never reused across connections.
226///
227/// # Secret hygiene (issue #1142)
228/// The passphrase and SEK never appear in [`core::fmt::Debug`] output (it
229/// prints only their lengths), [`PartialEq`] compares them in constant time,
230/// and dropping a `CryptoConfig` (or calling [`Zeroize::zeroize`]) wipes them.
231#[cfg(feature = "crypto")]
232#[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
233#[derive(Clone)]
234pub struct CryptoConfig {
235    /// The pre-shared secret (§6.1.4). Must be identical on both peers, or
236    /// the responder's KEK derivation recovers the wrong SEK and the RFC
237    /// 3394 wrap's integrity check fails
238    /// ([`RejectionReason::BadSecret`] on the Listener side).
239    pub passphrase: Vec<u8>,
240    /// A fresh, cryptographically random 128-bit Salt for **this
241    /// connection** (§6.2.1: `Salt = PRNG(128)`). See the struct doc for why
242    /// this crate does not generate it internally.
243    pub salt: [u8; crate::crypto::SALT_LEN],
244    /// This side's plaintext Stream Encrypting Key. **Only meaningful on the
245    /// connection initiator** (the Caller — §6.1.5: "sent by the connection
246    /// initiator ... to the responder"). Must be a fresh, cryptographically
247    /// random 16/24/32-byte value (§6.2.1: `SEK = PRNG(KLen)`) matching
248    /// [`HandshakeConfig::encryption_field`]'s advertised cipher. Ignored on
249    /// the Listener/responder side (which instead recovers the SEK by
250    /// unwrapping the initiator's Key Material) — may be left empty there.
251    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    /// Constant-time in the secret contents (the lengths are not secret).
274    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/// Secret key bytes — a negotiated Stream Encrypting Key.
305///
306/// Derefs to `&[u8]` for use with [`crate::crypto::aes_ctr_apply`], but is
307/// deliberately not a plain `Vec<u8>`: [`core::fmt::Debug`] prints only the
308/// length, serde never serializes it (it is skipped where it is a field),
309/// [`PartialEq`] is constant-time, and it is wiped when dropped (issue #1142).
310#[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    /// Wrap `bytes`.
318    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    /// Constant-time in the contents (the length is not secret).
348    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/// Local configuration for one side of a Caller-Listener handshake — the
374/// values *this* engine advertises (`draft-sharabayko-srt-01` §3.2.1,
375/// §3.2.1.1, §3.2.1.3, §3.2.1.4).
376#[derive(Debug, Clone, PartialEq)]
377#[non_exhaustive]
378pub struct HandshakeConfig {
379    /// TSBPD delay in milliseconds this side requests, sent as both the
380    /// Receiver and Sender TSBPD Delay of its Handshake Extension Message
381    /// (§3.2.1.1, Figure 6). The negotiated value is the greater of the two
382    /// parties' requests (§4.3.1.2).
383    pub latency_ms: u16,
384    /// Maximum Transmission Unit Size (§3.2.1).
385    pub mtu: u32,
386    /// Maximum Flow Window Size (§3.2.1).
387    pub max_flow_window_size: u32,
388    /// Initial Packet Sequence Number this side will use for its first data
389    /// packet (§3.2.1). No data plane exists yet in this crate; callers of a
390    /// later data-plane PR are expected to set this to a real ISN.
391    pub initial_seq_number: u32,
392    /// The `SRT Version` this side reports in its Handshake Extension
393    /// Message (`major * 0x10000 + minor * 0x100 + patch`, §3.2.1.1).
394    pub srt_version: u32,
395    /// `SRT Flags` this side advertises (§3.2.1.1.1, Table 6).
396    pub flags: HandshakeExtensionMessageFlags,
397    /// Advertised cipher family and block size (§3.2.1, Table 2). Actual
398    /// key-wrap/unwrap crypto is an explicit follow-up; this field is
399    /// negotiated but not acted on in this release.
400    pub encryption_field: EncryptionField,
401    /// Stream ID to advertise (Caller only — §3.2.1.3); `None` sends no
402    /// Stream ID extension.
403    pub stream_id: Option<String>,
404    /// Group Membership to advertise (§3.2.1.4); `None` sends no Group
405    /// extension.
406    pub group: Option<GroupMembershipExtension>,
407    /// This side's own IP address, reported in every outgoing handshake
408    /// packet's `Peer IP Address` field (§3.2.1: "IPv4 or IPv6 address of
409    /// the packet's *sender*" — despite the field's name, each party reports
410    /// its own address, not its peer's).
411    pub local_ip: [u32; 4],
412    /// Number of [`crate::caller::CallerHandshake::tick`] /
413    /// [`crate::listener::ListenerHandshake::tick`] calls with no reply
414    /// before the last-sent handshake packet is retransmitted. Timeouts are
415    /// modeled as caller-driven ticks — no wall-clock lives in this crate.
416    pub retransmit_after_ticks: u32,
417    /// Maximum number of retransmissions before the handshake gives up
418    /// ([`HandshakeOutput::TimedOut`]).
419    pub max_retries: u32,
420    /// Opt-in §6 payload-encryption negotiation (`crypto` feature only).
421    /// `None` (the default) means this side neither offers nor requires
422    /// encryption. See [`CryptoConfig`] for the caller-supplied Salt/SEK
423    /// contract.
424    #[cfg(feature = "crypto")]
425    #[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
426    pub crypto: Option<CryptoConfig>,
427}
428
429impl HandshakeConfig {
430    /// Sets [`latency_ms`](Self::latency_ms).
431    #[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    /// Sets [`mtu`](Self::mtu).
438    #[must_use]
439    pub fn with_mtu(mut self, mtu: u32) -> Self {
440        self.mtu = mtu;
441        self
442    }
443
444    /// Sets [`max_flow_window_size`](Self::max_flow_window_size).
445    #[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    /// Sets [`initial_seq_number`](Self::initial_seq_number).
452    #[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    /// Sets [`srt_version`](Self::srt_version).
459    #[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    /// Sets [`flags`](Self::flags).
466    #[must_use]
467    pub fn with_flags(mut self, flags: HandshakeExtensionMessageFlags) -> Self {
468        self.flags = flags;
469        self
470    }
471
472    /// Sets [`encryption_field`](Self::encryption_field).
473    #[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    /// Sets [`stream_id`](Self::stream_id).
480    #[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    /// Sets [`group`](Self::group).
487    #[must_use]
488    pub fn with_group(mut self, group: Option<GroupMembershipExtension>) -> Self {
489        self.group = group;
490        self
491    }
492
493    /// Sets [`local_ip`](Self::local_ip).
494    #[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    /// Sets [`retransmit_after_ticks`](Self::retransmit_after_ticks).
501    #[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    /// Sets [`max_retries`](Self::max_retries).
508    #[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    /// Sets [`crypto`](Self::crypto).
515    #[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
524/// Default [`HandshakeConfig::max_retries`]: twelve retransmissions at the
525/// adapter's 250 ms retransmit period is libsrt's 3 s connect timeout
526/// (`SRTO_CONNTIMEO`) — the previous 5 gave up after 1.25 s of a 250 ms
527/// retransmit period.
528pub 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/// The outcome of a Caller-Listener handshake, once both TSBPD delays and
559/// flags have been reconciled per `draft-sharabayko-srt-01` §4.3.1.2 ("The
560/// value for latency is always agreed to be the greater of those reported by
561/// each party").
562#[derive(Debug, Clone, PartialEq)]
563#[cfg_attr(feature = "serde", derive(serde::Serialize))]
564pub struct NegotiatedParams {
565    /// The negotiated base protocol version — always `5` (HSv5) for a
566    /// completed handshake in this crate.
567    pub version: u32,
568    /// The flags both sides advertised, ANDed together (only mutually
569    /// supported capabilities are considered agreed).
570    pub flags: HandshakeExtensionMessageFlags,
571    /// The agreed TSBPD latency in milliseconds: the greater of this side's
572    /// configured [`HandshakeConfig::latency_ms`] and the peer's reported
573    /// Receiver/Sender TSBPD Delay (§4.3.1.2).
574    pub latency_ms: u16,
575    /// This side's own SRT Socket ID.
576    pub own_socket_id: u32,
577    /// The peer's SRT Socket ID.
578    pub peer_socket_id: u32,
579    /// The agreed Maximum Transmission Unit Size (§3.2.1): the smaller of the
580    /// two parties' advertised values, so neither is sent a datagram larger
581    /// than it said it could carry.
582    pub mtu: u32,
583    /// The agreed Maximum Flow Window Size (§3.2.1): the smaller of the two
584    /// parties' advertised values — how many packets may be unacknowledged in
585    /// flight (the sender's window) and how far ahead of its ack point a
586    /// receiver tracks (the receiver's window).
587    pub max_flow_window_size: u32,
588    /// The negotiated Stream ID (§3.2.1.3), if one was advertised.
589    pub stream_id: Option<String>,
590    /// The negotiated Group Membership (§3.2.1.4), if one was advertised.
591    pub group: Option<GroupMembershipExtension>,
592    /// The negotiated Stream Encrypting Key (§6.1.5), if
593    /// [`HandshakeConfig::crypto`] was set on this side and the Key Material
594    /// exchange succeeded. `None` if encryption was not negotiated.
595    ///
596    /// A [`SecretBytes`]: redacted in `Debug`, constant-time in `==`, wiped on
597    /// drop, and never serialized.
598    #[cfg(feature = "crypto")]
599    #[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
600    #[cfg_attr(feature = "serde", serde(skip))]
601    pub sek: Option<SecretBytes>,
602    /// The Salt paired with [`Self::sek`] — both are required by
603    /// [`crate::crypto::aes_ctr_apply`] to encrypt/decrypt a data packet's
604    /// payload (§6.1.2/§6.2.2/§6.3.2).
605    #[cfg(feature = "crypto")]
606    #[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
607    pub salt: Option<[u8; crate::crypto::SALT_LEN]>,
608}
609
610/// An event produced by [`crate::caller::CallerHandshake::feed`] /
611/// [`crate::caller::CallerHandshake::start`] /
612/// [`crate::listener::ListenerHandshake::feed`] / either engine's `tick`.
613#[derive(Debug, Clone, PartialEq)]
614#[cfg_attr(feature = "serde", derive(serde::Serialize))]
615#[non_exhaustive]
616pub enum HandshakeOutput {
617    /// Send these bytes (one serialized Handshake control packet, built from
618    /// the existing [`crate::packet`] codecs) to the peer.
619    Send(Vec<u8>),
620    /// The handshake completed; here are the negotiated parameters.
621    Connected(NegotiatedParams),
622    /// The handshake was rejected — either the peer sent back an explicit
623    /// [`RejectionReason`], or a local validation check failed (in which
624    /// case a matching `Send` rejection packet is also emitted, in the same
625    /// output batch, for the Listener side).
626    Rejected(RejectionReason),
627    /// No reply arrived after [`HandshakeConfig::max_retries`]
628    /// retransmissions.
629    TimedOut,
630}
631
632/// What a retransmit tick asks of the handshake machine that owns it.
633pub(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/// The connection-relative wire timestamp (§3.2.1, microseconds since the
650/// connection started) the handshake machines stamp on every packet they build.
651/// The machines read no clock: the driver feeds the elapsed time in.
652#[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/// The retransmit bookkeeping every handshake machine (caller, listener,
668/// rendezvous) shares: the last packet sent, ticks since it was sent, and the
669/// retransmissions spent on it.
670#[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    /// One caller-defined tick: after [`HandshakeConfig::retransmit_after_ticks`]
697    /// ticks the last packet is resent, and once
698    /// [`HandshakeConfig::max_retries`] resends are spent the handshake times out.
699    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
715/// Serializes one [`HandshakePacket`] using the existing [`ControlPacket`]
716/// codec — never hand-rolled.
717pub(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
724/// Builds the extensions payload for a CONCLUSION-phase handshake carrying a
725/// Handshake Extension Message plus optional Stream ID / Group Membership,
726/// returning `(bytes, Extension Field flags)`.
727pub(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/// A parsed peer extension payload relevant to the Caller-Listener handshake:
757/// the mandatory Handshake Extension Message plus any optional Stream ID /
758/// Group Membership / Key Material.
759#[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    /// The Key Material extension (§3.2.1.2/§3.2.2, `SRT_CMD_KMREQ` on the
765    /// Caller's CONCLUSION / `SRT_CMD_KMRSP` on the Listener's) — decoded
766    /// regardless of the `crypto` feature (wire-structure decode only,
767    /// [`KeyMaterial`] has no crypto dependency); only *acted on*
768    /// (KEK derive/unwrap/wrap) when `crypto` is enabled, see
769    /// [`crate::caller::CallerHandshake`]/[`crate::listener::ListenerHandshake`].
770    #[cfg(feature = "crypto")]
771    pub km: Option<KeyMaterial<'a>>,
772    /// Keeps the `'a` lifetime parameter meaningful when the `crypto`
773    /// feature (and with it, [`Self::km`]) is compiled out.
774    #[cfg(not(feature = "crypto"))]
775    _phantom: core::marker::PhantomData<&'a ()>,
776}
777
778/// Walks a handshake packet's extension blocks, decoding the ones this crate
779/// understands. Returns [`Error::InvalidField`] (mapped by the caller to a
780/// [`RejectionReason::Rogue`] rejection) on any decode failure, rather than
781/// panicking — extension content is untrusted peer input.
782pub(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// ---------------------------------------------------------------------------
840// §6.1.5 Key Material Exchange — piggybacked on the CONCLUSION extensions.
841// ---------------------------------------------------------------------------
842
843/// Build the Key Material handshake extension block (`Extension Type` +
844/// `Extension Length` + contents — ready to append after the mandatory
845/// HSREQ block) offering `crypto.sek`, wrapped under a KEK derived from
846/// `crypto.passphrase`/`crypto.salt` (`draft-sharabayko-srt-01` §6.1.5 "sent
847/// by the connection initiator ... to the responder", §6.2.1's `Wrap =
848/// AESkw(KEK, SEK)`). Always encodes `KK = Even` — this crate's convention
849/// for the handshake-negotiated initial SEK; §6.1.6's odd/even alternation
850/// only matters from the first KM Refresh onward (see [`crate::km_refresh`]).
851#[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/// A recovered/negotiated `(SEK, Salt)` pair.
872#[cfg(feature = "crypto")]
873pub(crate) type RecoveredSek = (SecretBytes, [u8; crate::crypto::SALT_LEN]);
874
875/// Recover the SEK a peer's Key Material offered, given this side's shared
876/// passphrase (§6.1.5/§6.3.1: "the responder MUST know the passphrase ...
877/// everything else needed is extracted from the Keying Material message").
878/// Returns the recovered SEK bytes and the 16-byte Salt — both required by
879/// [`crate::crypto::aes_ctr_apply`].
880///
881/// # Errors
882/// [`Error::InvalidField`] if the Salt is not 16 bytes (the only Salt length
883/// this crate's Key Material codec accepts); otherwise propagates
884/// [`crate::crypto::unwrap_sek`]'s error (RFC 3394 wrap-integrity failure —
885/// wrong passphrase, §6.1.5's "it does not have the SEK" case).
886#[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/// Recover the `(even, odd, salt)` triple a `KK = Both` Key Material message
902/// carries: §6.1.6 wraps `even SEK || odd SEK` as one RFC 3394 block under a
903/// single ICV.
904///
905/// # Errors
906/// [`Error::InvalidField`] if the message is not `KK = Both`, the Salt is not
907/// 16 bytes, or the RFC 3394 integrity check fails.
908#[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/// Re-serialize a parsed Key Material message and wrap it as a `KmRsp`
941/// extension block — the responder's confirmation echo (§6.1.5: "the
942/// responder ... echoes the same KM message back to prove it derived the
943/// same SEK").
944#[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/// Verify a Listener's echoed Key Material matches what this Caller sent.
952/// Recomputed deterministically from `crypto` (the same passphrase/salt/sek
953/// always wraps to the same bytes, §6.2.1) rather than requiring the Caller
954/// to keep the original wrap bytes around.
955#[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    // The wrapped key is derived from the secret: compare it in constant time.
966    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
972/// The greater-of-both-parties TSBPD latency rule (§4.3.1.2).
973pub(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
979/// SipHash-2-4 (Aumasson & Bernstein, "SipHash: a fast short-input PRF",
980/// 2012): a keyed 64-bit pseudorandom function designed for exactly this use —
981/// short inputs, an unpredictable key, an attacker who must not be able to
982/// forge outputs. Verified against the paper's reference test vector in this
983/// module's tests.
984fn siphash24(k0: u64, k1: u64, data: &[u8]) -> u64 {
985    // Compression rounds per message block and finalisation rounds: the "2-4"
986    // of SipHash-2-4.
987    const C_ROUNDS: usize = 2;
988    const D_ROUNDS: usize = 4;
989    // The four state words' initialisation constants (ASCII of
990    // "somepseudorandomlygeneratedbytes"), per the SipHash paper.
991    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    // XORed into `v2` before the finalisation rounds.
996    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    // Final block: the remaining 0..=7 bytes, with the input length in the
1032    // top byte (modulo 256, as the reference does).
1033    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
1050/// Derives a SYN Cookie from caller-supplied inputs (`draft-sharabayko-srt-01`
1051/// §4.3.1.1: "a cookie that is crafted based on host, port and current time
1052/// with 1 minute accuracy"). The draft specifies the semantic inputs, not a
1053/// wire algorithm; this crate's core never reads a clock, so `time_bucket`
1054/// (e.g. UNIX time / 60) must come from the caller/driver.
1055///
1056/// The cookie is the low 32 bits of **SipHash-2-4** over `peer_key ‖
1057/// time_bucket`, keyed by the 128-bit `secret` (SipHash's whole key, low half
1058/// as `k0`): a real keyed PRF, so a peer that sees cookies cannot predict or
1059/// forge the cookie for another `(peer, minute)` without the secret. It is
1060/// still *not* a message-authentication code of the handshake packet: the
1061/// cookie only proves the Caller received the INDUCTION response sent to its
1062/// address, and its 32 bits are a flood-protection token, not a long-lived
1063/// credential. `secret` must come from a CSPRNG and should be replaced
1064/// periodically (the tokio adapter's listener draws it from the OS and
1065/// rotates it every minute).
1066pub 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    // Keep the low 32 bits; `| 1` so it is never 0, never confused with "no
1074    // cookie yet".
1075    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    /// r08-SRT-W14: only `1000..2^31` is a rejection. `0xFFFF_FFFC` (libsrt's
1136    /// negative URQ range) and `2^31` itself used to be reported as
1137    /// `Rejected(Reserved(..))`.
1138    #[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)); // AGREEMENT is its own type
1144        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        // A predefined reason, a reason the table does not define, and a
1149        // user-defined (2000+) reason all decode.
1150        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    /// r08-SRT-W7: the Caller's KMREQ carries `SE` = 2 (MPEG-TS/SRT), the
1165    /// value libsrt's `hcryptCtx_Rx_ParseKM` requires (`km_msg[SE] ==
1166    /// crypto->se`, `HCRYPT_SE_TSSRT`); `SE` = 0 is rejected as a bad KM.
1167    #[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        // Extension block: type(16) length(16, words) then the KM message.
1177        let km = KeyMaterial::parse(&ext[4..]).unwrap();
1178        assert_eq!(km.se, StreamEncapsulation::MpegTsSrt);
1179        assert_eq!(km.se.to_bits(), 2);
1180        // Wire byte: word 2 of the KM is Cipher(8) Auth(8) SE(8) Resv2(8).
1181        assert_eq!(ext[4 + 10], 2);
1182    }
1183
1184    /// The SipHash-2-4 reference vector from the paper's appendix: key
1185    /// `00 01 .. 0f`, input `00 01 .. 0e` (15 bytes), output `a129ca6149be45e5`.
1186    #[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        // And the empty input (a second reference value from the same table).
1193        assert_eq!(siphash24(k0, k1, &[]), 0x726f_db47_dd0e_0e31);
1194    }
1195
1196    /// The cookie depends on every input, including the secret.
1197    #[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        // Pinned against an independent SipHash-2-4 implementation (Python,
1205        // checked against the same reference vector): fixes the input layout
1206        // (`peer_key` LE ‖ `time_bucket` LE) and the key split (low half k0).
1207        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        // Both halves of the key matter.
1220        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    // ---- #1142: secrets stay out of Debug / serde, are compared in constant
1228    // time and wiped on drop ------------------------------------------------
1229
1230    /// A non-repeating pseudo-random run, so a needle cut from it cannot occur
1231    /// by chance in unrelated numbers.
1232    #[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    /// Every spelling a leak of the first six bytes of `bytes` could take.
1244    #[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    /// `{:?}` and `{:#?}` of a config (alone or inside a `HandshakeConfig`)
1274    /// carry no passphrase, salt or key bytes — only their lengths.
1275    #[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    /// A negotiated key is redacted in `Debug` — also when it rides inside a
1308    /// [`HandshakeOutput`] — and is not serialized.
1309    #[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(&params).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    /// Secret comparison and wiping: `==` distinguishes contents (and
1347    /// lengths) correctly through the constant-time path, and `zeroize`
1348    /// clears the key and the passphrase.
1349    #[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    /// Compile-time guard: both secret holders wipe themselves on drop.
1373    #[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}