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)]
377pub struct HandshakeConfig {
378    /// TSBPD delay in milliseconds this side requests, sent as both the
379    /// Receiver and Sender TSBPD Delay of its Handshake Extension Message
380    /// (§3.2.1.1, Figure 6). The negotiated value is the greater of the two
381    /// parties' requests (§4.3.1.2).
382    pub latency_ms: u16,
383    /// Maximum Transmission Unit Size (§3.2.1).
384    pub mtu: u32,
385    /// Maximum Flow Window Size (§3.2.1).
386    pub max_flow_window_size: u32,
387    /// Initial Packet Sequence Number this side will use for its first data
388    /// packet (§3.2.1). No data plane exists yet in this crate; callers of a
389    /// later data-plane PR are expected to set this to a real ISN.
390    pub initial_seq_number: u32,
391    /// The `SRT Version` this side reports in its Handshake Extension
392    /// Message (`major * 0x10000 + minor * 0x100 + patch`, §3.2.1.1).
393    pub srt_version: u32,
394    /// `SRT Flags` this side advertises (§3.2.1.1.1, Table 6).
395    pub flags: HandshakeExtensionMessageFlags,
396    /// Advertised cipher family and block size (§3.2.1, Table 2). Actual
397    /// key-wrap/unwrap crypto is an explicit follow-up; this field is
398    /// negotiated but not acted on in this release.
399    pub encryption_field: EncryptionField,
400    /// Stream ID to advertise (Caller only — §3.2.1.3); `None` sends no
401    /// Stream ID extension.
402    pub stream_id: Option<String>,
403    /// Group Membership to advertise (§3.2.1.4); `None` sends no Group
404    /// extension.
405    pub group: Option<GroupMembershipExtension>,
406    /// This side's own IP address, reported in every outgoing handshake
407    /// packet's `Peer IP Address` field (§3.2.1: "IPv4 or IPv6 address of
408    /// the packet's *sender*" — despite the field's name, each party reports
409    /// its own address, not its peer's).
410    pub local_ip: [u32; 4],
411    /// Number of [`crate::caller::CallerHandshake::tick`] /
412    /// [`crate::listener::ListenerHandshake::tick`] calls with no reply
413    /// before the last-sent handshake packet is retransmitted. Timeouts are
414    /// modeled as caller-driven ticks — no wall-clock lives in this crate.
415    pub retransmit_after_ticks: u32,
416    /// Maximum number of retransmissions before the handshake gives up
417    /// ([`HandshakeOutput::TimedOut`]).
418    pub max_retries: u32,
419    /// Opt-in §6 payload-encryption negotiation (`crypto` feature only).
420    /// `None` (the default) means this side neither offers nor requires
421    /// encryption. See [`CryptoConfig`] for the caller-supplied Salt/SEK
422    /// contract.
423    #[cfg(feature = "crypto")]
424    #[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
425    pub crypto: Option<CryptoConfig>,
426}
427
428/// Default [`HandshakeConfig::max_retries`]: twelve retransmissions at the
429/// adapter's 250 ms retransmit period is libsrt's 3 s connect timeout
430/// (`SRTO_CONNTIMEO`) — the previous 5 gave up after 1.25 s of a 250 ms
431/// retransmit period.
432pub 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/// The outcome of a Caller-Listener handshake, once both TSBPD delays and
463/// flags have been reconciled per `draft-sharabayko-srt-01` §4.3.1.2 ("The
464/// value for latency is always agreed to be the greater of those reported by
465/// each party").
466#[derive(Debug, Clone, PartialEq)]
467#[cfg_attr(feature = "serde", derive(serde::Serialize))]
468pub struct NegotiatedParams {
469    /// The negotiated base protocol version — always `5` (HSv5) for a
470    /// completed handshake in this crate.
471    pub version: u32,
472    /// The flags both sides advertised, ANDed together (only mutually
473    /// supported capabilities are considered agreed).
474    pub flags: HandshakeExtensionMessageFlags,
475    /// The agreed TSBPD latency in milliseconds: the greater of this side's
476    /// configured [`HandshakeConfig::latency_ms`] and the peer's reported
477    /// Receiver/Sender TSBPD Delay (§4.3.1.2).
478    pub latency_ms: u16,
479    /// This side's own SRT Socket ID.
480    pub own_socket_id: u32,
481    /// The peer's SRT Socket ID.
482    pub peer_socket_id: u32,
483    /// The agreed Maximum Transmission Unit Size (§3.2.1): the smaller of the
484    /// two parties' advertised values, so neither is sent a datagram larger
485    /// than it said it could carry.
486    pub mtu: u32,
487    /// The agreed Maximum Flow Window Size (§3.2.1): the smaller of the two
488    /// parties' advertised values — how many packets may be unacknowledged in
489    /// flight (the sender's window) and how far ahead of its ack point a
490    /// receiver tracks (the receiver's window).
491    pub max_flow_window_size: u32,
492    /// The negotiated Stream ID (§3.2.1.3), if one was advertised.
493    pub stream_id: Option<String>,
494    /// The negotiated Group Membership (§3.2.1.4), if one was advertised.
495    pub group: Option<GroupMembershipExtension>,
496    /// The negotiated Stream Encrypting Key (§6.1.5), if
497    /// [`HandshakeConfig::crypto`] was set on this side and the Key Material
498    /// exchange succeeded. `None` if encryption was not negotiated.
499    ///
500    /// A [`SecretBytes`]: redacted in `Debug`, constant-time in `==`, wiped on
501    /// drop, and never serialized.
502    #[cfg(feature = "crypto")]
503    #[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
504    #[cfg_attr(feature = "serde", serde(skip))]
505    pub sek: Option<SecretBytes>,
506    /// The Salt paired with [`Self::sek`] — both are required by
507    /// [`crate::crypto::aes_ctr_apply`] to encrypt/decrypt a data packet's
508    /// payload (§6.1.2/§6.2.2/§6.3.2).
509    #[cfg(feature = "crypto")]
510    #[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
511    pub salt: Option<[u8; crate::crypto::SALT_LEN]>,
512}
513
514/// An event produced by [`crate::caller::CallerHandshake::feed`] /
515/// [`crate::caller::CallerHandshake::start`] /
516/// [`crate::listener::ListenerHandshake::feed`] / either engine's `tick`.
517#[derive(Debug, Clone, PartialEq)]
518#[cfg_attr(feature = "serde", derive(serde::Serialize))]
519#[non_exhaustive]
520pub enum HandshakeOutput {
521    /// Send these bytes (one serialized Handshake control packet, built from
522    /// the existing [`crate::packet`] codecs) to the peer.
523    Send(Vec<u8>),
524    /// The handshake completed; here are the negotiated parameters.
525    Connected(NegotiatedParams),
526    /// The handshake was rejected — either the peer sent back an explicit
527    /// [`RejectionReason`], or a local validation check failed (in which
528    /// case a matching `Send` rejection packet is also emitted, in the same
529    /// output batch, for the Listener side).
530    Rejected(RejectionReason),
531    /// No reply arrived after [`HandshakeConfig::max_retries`]
532    /// retransmissions.
533    TimedOut,
534}
535
536/// What a retransmit tick asks of the handshake machine that owns it.
537pub(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/// The retransmit bookkeeping every handshake machine (caller, listener,
554/// rendezvous) shares: the last packet sent, ticks since it was sent, and the
555/// retransmissions spent on it.
556#[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    /// One caller-defined tick: after [`HandshakeConfig::retransmit_after_ticks`]
583    /// ticks the last packet is resent, and once
584    /// [`HandshakeConfig::max_retries`] resends are spent the handshake times out.
585    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
601/// Serializes one [`HandshakePacket`] using the existing [`ControlPacket`]
602/// codec — never hand-rolled.
603pub(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
610/// Builds the extensions payload for a CONCLUSION-phase handshake carrying a
611/// Handshake Extension Message plus optional Stream ID / Group Membership,
612/// returning `(bytes, Extension Field flags)`.
613pub(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/// A parsed peer extension payload relevant to the Caller-Listener handshake:
643/// the mandatory Handshake Extension Message plus any optional Stream ID /
644/// Group Membership / Key Material.
645#[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    /// The Key Material extension (§3.2.1.2/§3.2.2, `SRT_CMD_KMREQ` on the
651    /// Caller's CONCLUSION / `SRT_CMD_KMRSP` on the Listener's) — decoded
652    /// regardless of the `crypto` feature (wire-structure decode only,
653    /// [`KeyMaterial`] has no crypto dependency); only *acted on*
654    /// (KEK derive/unwrap/wrap) when `crypto` is enabled, see
655    /// [`crate::caller::CallerHandshake`]/[`crate::listener::ListenerHandshake`].
656    #[cfg(feature = "crypto")]
657    pub km: Option<KeyMaterial<'a>>,
658    /// Keeps the `'a` lifetime parameter meaningful when the `crypto`
659    /// feature (and with it, [`Self::km`]) is compiled out.
660    #[cfg(not(feature = "crypto"))]
661    _phantom: core::marker::PhantomData<&'a ()>,
662}
663
664/// Walks a handshake packet's extension blocks, decoding the ones this crate
665/// understands. Returns [`Error::InvalidField`] (mapped by the caller to a
666/// [`RejectionReason::Rogue`] rejection) on any decode failure, rather than
667/// panicking — extension content is untrusted peer input.
668pub(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// ---------------------------------------------------------------------------
726// §6.1.5 Key Material Exchange — piggybacked on the CONCLUSION extensions.
727// ---------------------------------------------------------------------------
728
729/// Build the Key Material handshake extension block (`Extension Type` +
730/// `Extension Length` + contents — ready to append after the mandatory
731/// HSREQ block) offering `crypto.sek`, wrapped under a KEK derived from
732/// `crypto.passphrase`/`crypto.salt` (`draft-sharabayko-srt-01` §6.1.5 "sent
733/// by the connection initiator ... to the responder", §6.2.1's `Wrap =
734/// AESkw(KEK, SEK)`). Always encodes `KK = Even` — this crate's convention
735/// for the handshake-negotiated initial SEK; §6.1.6's odd/even alternation
736/// only matters from the first KM Refresh onward (see [`crate::km_refresh`]).
737#[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/// A recovered/negotiated `(SEK, Salt)` pair.
758#[cfg(feature = "crypto")]
759pub(crate) type RecoveredSek = (SecretBytes, [u8; crate::crypto::SALT_LEN]);
760
761/// Recover the SEK a peer's Key Material offered, given this side's shared
762/// passphrase (§6.1.5/§6.3.1: "the responder MUST know the passphrase ...
763/// everything else needed is extracted from the Keying Material message").
764/// Returns the recovered SEK bytes and the 16-byte Salt — both required by
765/// [`crate::crypto::aes_ctr_apply`].
766///
767/// # Errors
768/// [`Error::InvalidField`] if the Salt is not 16 bytes (the only Salt length
769/// this crate's Key Material codec accepts); otherwise propagates
770/// [`crate::crypto::unwrap_sek`]'s error (RFC 3394 wrap-integrity failure —
771/// wrong passphrase, §6.1.5's "it does not have the SEK" case).
772#[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/// Re-serialize a parsed Key Material message and wrap it as a `KmRsp`
788/// extension block — the responder's confirmation echo (§6.1.5: "the
789/// responder ... echoes the same KM message back to prove it derived the
790/// same SEK").
791#[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/// Verify a Listener's echoed Key Material matches what this Caller sent.
799/// Recomputed deterministically from `crypto` (the same passphrase/salt/sek
800/// always wraps to the same bytes, §6.2.1) rather than requiring the Caller
801/// to keep the original wrap bytes around.
802#[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    // The wrapped key is derived from the secret: compare it in constant time.
813    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
819/// The greater-of-both-parties TSBPD latency rule (§4.3.1.2).
820pub(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
826/// SipHash-2-4 (Aumasson & Bernstein, "SipHash: a fast short-input PRF",
827/// 2012): a keyed 64-bit pseudorandom function designed for exactly this use —
828/// short inputs, an unpredictable key, an attacker who must not be able to
829/// forge outputs. Verified against the paper's reference test vector in this
830/// module's tests.
831fn siphash24(k0: u64, k1: u64, data: &[u8]) -> u64 {
832    // Compression rounds per message block and finalisation rounds: the "2-4"
833    // of SipHash-2-4.
834    const C_ROUNDS: usize = 2;
835    const D_ROUNDS: usize = 4;
836    // The four state words' initialisation constants (ASCII of
837    // "somepseudorandomlygeneratedbytes"), per the SipHash paper.
838    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    // XORed into `v2` before the finalisation rounds.
843    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    // Final block: the remaining 0..=7 bytes, with the input length in the
879    // top byte (modulo 256, as the reference does).
880    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
897/// Derives a SYN Cookie from caller-supplied inputs (`draft-sharabayko-srt-01`
898/// §4.3.1.1: "a cookie that is crafted based on host, port and current time
899/// with 1 minute accuracy"). The draft specifies the semantic inputs, not a
900/// wire algorithm; this crate's core never reads a clock, so `time_bucket`
901/// (e.g. UNIX time / 60) must come from the caller/driver.
902///
903/// The cookie is the low 32 bits of **SipHash-2-4** over `peer_key ‖
904/// time_bucket`, keyed by the 128-bit `secret` (SipHash's whole key, low half
905/// as `k0`): a real keyed PRF, so a peer that sees cookies cannot predict or
906/// forge the cookie for another `(peer, minute)` without the secret. It is
907/// still *not* a message-authentication code of the handshake packet: the
908/// cookie only proves the Caller received the INDUCTION response sent to its
909/// address, and its 32 bits are a flood-protection token, not a long-lived
910/// credential. `secret` must come from a CSPRNG and should be replaced
911/// periodically (the tokio adapter's listener draws it from the OS and
912/// rotates it every minute).
913pub 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    // Keep the low 32 bits; `| 1` so it is never 0, never confused with "no
921    // cookie yet".
922    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    /// r08-SRT-W14: only `1000..2^31` is a rejection. `0xFFFF_FFFC` (libsrt's
983    /// negative URQ range) and `2^31` itself used to be reported as
984    /// `Rejected(Reserved(..))`.
985    #[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)); // AGREEMENT is its own type
991        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        // A predefined reason, a reason the table does not define, and a
996        // user-defined (2000+) reason all decode.
997        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    /// r08-SRT-W7: the Caller's KMREQ carries `SE` = 2 (MPEG-TS/SRT), the
1012    /// value libsrt's `hcryptCtx_Rx_ParseKM` requires (`km_msg[SE] ==
1013    /// crypto->se`, `HCRYPT_SE_TSSRT`); `SE` = 0 is rejected as a bad KM.
1014    #[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        // Extension block: type(16) length(16, words) then the KM message.
1024        let km = KeyMaterial::parse(&ext[4..]).unwrap();
1025        assert_eq!(km.se, StreamEncapsulation::MpegTsSrt);
1026        assert_eq!(km.se.to_bits(), 2);
1027        // Wire byte: word 2 of the KM is Cipher(8) Auth(8) SE(8) Resv2(8).
1028        assert_eq!(ext[4 + 10], 2);
1029    }
1030
1031    /// The SipHash-2-4 reference vector from the paper's appendix: key
1032    /// `00 01 .. 0f`, input `00 01 .. 0e` (15 bytes), output `a129ca6149be45e5`.
1033    #[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        // And the empty input (a second reference value from the same table).
1040        assert_eq!(siphash24(k0, k1, &[]), 0x726f_db47_dd0e_0e31);
1041    }
1042
1043    /// The cookie depends on every input, including the secret.
1044    #[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        // Pinned against an independent SipHash-2-4 implementation (Python,
1052        // checked against the same reference vector): fixes the input layout
1053        // (`peer_key` LE ‖ `time_bucket` LE) and the key split (low half k0).
1054        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        // Both halves of the key matter.
1067        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    // ---- #1142: secrets stay out of Debug / serde, are compared in constant
1075    // time and wiped on drop ------------------------------------------------
1076
1077    /// A non-repeating pseudo-random run, so a needle cut from it cannot occur
1078    /// by chance in unrelated numbers.
1079    #[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    /// Every spelling a leak of the first six bytes of `bytes` could take.
1091    #[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    /// `{:?}` and `{:#?}` of a config (alone or inside a `HandshakeConfig`)
1121    /// carry no passphrase, salt or key bytes — only their lengths.
1122    #[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    /// A negotiated key is redacted in `Debug` — also when it rides inside a
1155    /// [`HandshakeOutput`] — and is not serialized.
1156    #[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(&params).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    /// Secret comparison and wiping: `==` distinguishes contents (and
1194    /// lengths) correctly through the constant-time path, and `zeroize`
1195    /// clears the key and the passphrase.
1196    #[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    /// Compile-time guard: both secret holders wipe themselves on drop.
1220    #[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}