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 `specs/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::Vec;
21#[cfg(feature = "crypto")]
22use subtle::ConstantTimeEq;
23#[cfg(feature = "crypto")]
24use zeroize::Zeroize;
25
26use crate::error::{Error, Result};
27#[cfg(feature = "crypto")]
28use crate::packet::KeyMaterial;
29use crate::packet::handshake::{HS_EXT_FLAG_CONFIG, HS_EXT_FLAG_HSREQ};
30#[cfg(feature = "crypto")]
31use crate::packet::{Cipher, KmAuth, KmKeyFlag, StreamEncapsulation};
32use crate::packet::{
33    ControlPacket, EncryptionField, GroupMembershipExtension, HandshakeExtensionMessageFlags,
34    HandshakePacket, HandshakeType, HsExtMessage,
35};
36
37/// A base protocol version number of `4` — the value the Caller's INDUCTION
38/// handshake MUST always carry (`draft-sharabayko-srt-01` §4.3.1.1), kept for
39/// UDT compatibility.
40pub const HANDSHAKE_VERSION_4: u32 = 4;
41/// A base protocol version number of `5` — HSv5, used by every handshake
42/// message from the Listener's INDUCTION response onward (§4.3.1.1/§4.3.1.2).
43pub const HANDSHAKE_VERSION_5: u32 = 5;
44
45/// The `Extension Field` value the Listener echoes on its INDUCTION response
46/// so the Caller can recognise it as an SRT (not legacy UDT) party
47/// (`draft-sharabayko-srt-01` §4.3.1.1: "SRT magic code 0x4A17").
48pub const SRT_MAGIC_CODE: u16 = 0x4A17;
49
50/// The `Extension Field` value the Caller sets on its very first INDUCTION
51/// handshake (§4.3.1.1: "Extension Field: 2"). This is *not* the §3.2.1
52/// Table 3 `Extension Flags` bitmask (whose `KMREQ` bit happens to share the
53/// same numeric value) — it is a legacy UDT socket-type field (`UDT_DGRAM`)
54/// carried over because the INDUCTION handshake is version-4-shaped for UDT
55/// compatibility.
56pub const INDUCTION_LEGACY_SOCKET_TYPE: u16 = 2;
57
58/// The base wire value of the Handshake Rejection Reason codes
59/// (`draft-sharabayko-srt-01` §4.3, Table 7): a rejected connection's
60/// `Handshake Type` field carries `1000 + <code>`.
61pub const REJECTION_CODE_BASE: u32 = 1000;
62
63/// One past the largest `Handshake Type` value read as a rejection: libsrt's
64/// request type is a signed 32-bit integer, so everything from `2^31` up is
65/// the negative `URQ_*` range, never a rejection reason (see
66/// [`RejectionReason::from_handshake_type`]).
67pub const REJECTION_CODE_LIMIT: u32 = 0x8000_0000;
68
69/// Handshake Rejection Reason (`draft-sharabayko-srt-01` §4.3, Table 7). Sent
70/// in place of a normal `Handshake Type` value (`1000 + code`, decoded via
71/// [`HandshakeType::Reserved`]) when a connection attempt is refused.
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
73#[cfg_attr(feature = "serde", derive(serde::Serialize))]
74#[non_exhaustive]
75pub enum RejectionReason {
76    /// `1000`: unknown reason.
77    Unknown,
78    /// `1001`: system function error.
79    System,
80    /// `1002`: rejected by peer.
81    Peer,
82    /// `1003`: resource allocation problem.
83    Resource,
84    /// `1004`: incorrect data in handshake.
85    Rogue,
86    /// `1005`: listener's backlog exceeded.
87    Backlog,
88    /// `1006`: internal program error.
89    Ipe,
90    /// `1007`: socket is closing.
91    Close,
92    /// `1008`: peer is an older version than the agent's minimum.
93    Version,
94    /// `1009`: rendezvous cookie collision.
95    RdvCookie,
96    /// `1010`: wrong password.
97    BadSecret,
98    /// `1011`: password required or unexpected.
99    Unsecure,
100    /// `1012`: stream flag collision.
101    MessageApi,
102    /// `1013`: incompatible congestion-controller type.
103    Congestion,
104    /// `1014`: incompatible packet filter.
105    Filter,
106    /// `1015`: incompatible group.
107    Group,
108    /// A `1000 + code` value Table 7 does not define.
109    Reserved(u32),
110}
111
112impl RejectionReason {
113    /// Decode a Table 7 wire code (the value carried in `Handshake Type`,
114    /// i.e. already `1000 + code`).
115    pub fn from_bits(v: u32) -> Self {
116        match v {
117            1000 => RejectionReason::Unknown,
118            1001 => RejectionReason::System,
119            1002 => RejectionReason::Peer,
120            1003 => RejectionReason::Resource,
121            1004 => RejectionReason::Rogue,
122            1005 => RejectionReason::Backlog,
123            1006 => RejectionReason::Ipe,
124            1007 => RejectionReason::Close,
125            1008 => RejectionReason::Version,
126            1009 => RejectionReason::RdvCookie,
127            1010 => RejectionReason::BadSecret,
128            1011 => RejectionReason::Unsecure,
129            1012 => RejectionReason::MessageApi,
130            1013 => RejectionReason::Congestion,
131            1014 => RejectionReason::Filter,
132            1015 => RejectionReason::Group,
133            other => RejectionReason::Reserved(other),
134        }
135    }
136
137    /// The wire code (`1000 + code`), as carried in `Handshake Type`.
138    pub fn to_bits(self) -> u32 {
139        match self {
140            RejectionReason::Unknown => 1000,
141            RejectionReason::System => 1001,
142            RejectionReason::Peer => 1002,
143            RejectionReason::Resource => 1003,
144            RejectionReason::Rogue => 1004,
145            RejectionReason::Backlog => 1005,
146            RejectionReason::Ipe => 1006,
147            RejectionReason::Close => 1007,
148            RejectionReason::Version => 1008,
149            RejectionReason::RdvCookie => 1009,
150            RejectionReason::BadSecret => 1010,
151            RejectionReason::Unsecure => 1011,
152            RejectionReason::MessageApi => 1012,
153            RejectionReason::Congestion => 1013,
154            RejectionReason::Filter => 1014,
155            RejectionReason::Group => 1015,
156            RejectionReason::Reserved(v) => v,
157        }
158    }
159
160    /// Spec label (Table 7).
161    pub fn name(&self) -> &'static str {
162        match self {
163            RejectionReason::Unknown => "REJ_UNKNOWN",
164            RejectionReason::System => "REJ_SYSTEM",
165            RejectionReason::Peer => "REJ_PEER",
166            RejectionReason::Resource => "REJ_RESOURCE",
167            RejectionReason::Rogue => "REJ_ROGUE",
168            RejectionReason::Backlog => "REJ_BACKLOG",
169            RejectionReason::Ipe => "REJ_IPE",
170            RejectionReason::Close => "REJ_CLOSE",
171            RejectionReason::Version => "REJ_VERSION",
172            RejectionReason::RdvCookie => "REJ_RDVCOOKIE",
173            RejectionReason::BadSecret => "REJ_BADSECRET",
174            RejectionReason::Unsecure => "REJ_UNSECURE",
175            RejectionReason::MessageApi => "REJ_MESSAGEAPI",
176            RejectionReason::Congestion => "REJ_CONGESTION",
177            RejectionReason::Filter => "REJ_FILTER",
178            RejectionReason::Group => "REJ_GROUP",
179            RejectionReason::Reserved(_) => "reserved",
180        }
181    }
182
183    /// Recover the [`RejectionReason`] a peer sent back as a `Handshake
184    /// Type`, or `None` if `ht` is a normal (non-rejection) handshake type.
185    ///
186    /// Only `1000..`[`REJECTION_CODE_LIMIT`] is a rejection: libsrt carries the
187    /// handshake request type as a *signed* 32-bit integer whose negative
188    /// values (the `URQ_*` family, e.g. `CONCLUSION` = -1 = `0xFFFF_FFFF`)
189    /// are handshake types, not reasons, so an undefined value such as
190    /// `0xFFFF_FFFC` is not a rejection.
191    pub fn from_handshake_type(ht: HandshakeType) -> Option<Self> {
192        match ht {
193            HandshakeType::Reserved(v)
194                if (REJECTION_CODE_BASE..REJECTION_CODE_LIMIT).contains(&v) =>
195            {
196                Some(RejectionReason::from_bits(v))
197            }
198            _ => None,
199        }
200    }
201
202    /// Encode as the `Handshake Type` value a rejection packet carries.
203    pub fn to_handshake_type(self) -> HandshakeType {
204        HandshakeType::from_bits(self.to_bits())
205    }
206}
207
208broadcast_common::impl_spec_display!(RejectionReason, Reserved);
209
210/// Opt-in §6 payload-encryption config for one side of a Caller-Listener
211/// handshake (`draft-sharabayko-srt-01` §6.1.5, Key Material Exchange —
212/// curated at `specs/rules/srt-crypto.md`). `None` on
213/// [`HandshakeConfig::crypto`] (the default) disables the encryption path
214/// entirely: no Key Material extension is sent, and a peer that sends one
215/// unexpectedly is rejected ([`RejectionReason::Unsecure`]).
216///
217/// This crate's sans-IO core never reads OS randomness — the same design
218/// choice as [`derive_cookie`]'s caller-supplied `time_bucket`/`secret`
219/// inputs, or [`crate::io`]'s OS-random SYN Cookie key.
220/// [`Self::salt`] and, on the initiator, [`Self::sek`] must be freshly
221/// generated by the caller/driver (e.g. a `tokio` adapter with access to a
222/// real CSPRNG) for **every new connection** (§6.2.1: `Salt = PRNG(128)`,
223/// `SEK = PRNG(KLen)`) and never reused across connections.
224///
225/// # Secret hygiene (issue #1142)
226/// The passphrase and SEK never appear in [`core::fmt::Debug`] output (it
227/// prints only their lengths), [`PartialEq`] compares them in constant time,
228/// and dropping a `CryptoConfig` (or calling [`Zeroize::zeroize`]) wipes them.
229#[cfg(feature = "crypto")]
230#[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
231#[derive(Clone)]
232pub struct CryptoConfig {
233    /// The pre-shared secret (§6.1.4). Must be identical on both peers, or
234    /// the responder's KEK derivation recovers the wrong SEK and the RFC
235    /// 3394 wrap's integrity check fails
236    /// ([`RejectionReason::BadSecret`] on the Listener side).
237    pub passphrase: Vec<u8>,
238    /// A fresh, cryptographically random 128-bit Salt for **this
239    /// connection** (§6.2.1: `Salt = PRNG(128)`). See the struct doc for why
240    /// this crate does not generate it internally.
241    pub salt: [u8; crate::crypto::SALT_LEN],
242    /// This side's plaintext Stream Encrypting Key. **Only meaningful on the
243    /// connection initiator** (the Caller — §6.1.5: "sent by the connection
244    /// initiator ... to the responder"). Must be a fresh, cryptographically
245    /// random 16/24/32-byte value (§6.2.1: `SEK = PRNG(KLen)`) matching
246    /// [`HandshakeConfig::encryption_field`]'s advertised cipher. Ignored on
247    /// the Listener/responder side (which instead recovers the SEK by
248    /// unwrapping the initiator's Key Material) — may be left empty there.
249    pub sek: Vec<u8>,
250}
251
252#[cfg(feature = "crypto")]
253impl core::fmt::Debug for CryptoConfig {
254    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
255        f.debug_struct("CryptoConfig")
256            .field(
257                "passphrase",
258                &format_args!("<redacted, {} bytes>", self.passphrase.len()),
259            )
260            .field(
261                "salt",
262                &format_args!("<redacted, {} bytes>", self.salt.len()),
263            )
264            .field("sek", &format_args!("<redacted, {} bytes>", self.sek.len()))
265            .finish()
266    }
267}
268
269#[cfg(feature = "crypto")]
270impl PartialEq for CryptoConfig {
271    /// Constant-time in the secret contents (the lengths are not secret).
272    fn eq(&self, other: &Self) -> bool {
273        let passphrase = self
274            .passphrase
275            .as_slice()
276            .ct_eq(other.passphrase.as_slice());
277        let salt = self.salt.as_slice().ct_eq(other.salt.as_slice());
278        let sek = self.sek.as_slice().ct_eq(other.sek.as_slice());
279        bool::from(passphrase & salt & sek)
280    }
281}
282
283#[cfg(feature = "crypto")]
284impl Zeroize for CryptoConfig {
285    fn zeroize(&mut self) {
286        self.passphrase.zeroize();
287        self.salt.zeroize();
288        self.sek.zeroize();
289    }
290}
291
292#[cfg(feature = "crypto")]
293impl Drop for CryptoConfig {
294    fn drop(&mut self) {
295        self.zeroize();
296    }
297}
298
299#[cfg(feature = "crypto")]
300impl zeroize::ZeroizeOnDrop for CryptoConfig {}
301
302/// Secret key bytes — a negotiated Stream Encrypting Key.
303///
304/// Derefs to `&[u8]` for use with [`crate::crypto::aes_ctr_apply`], but is
305/// deliberately not a plain `Vec<u8>`: [`core::fmt::Debug`] prints only the
306/// length, serde never serializes it (it is skipped where it is a field),
307/// [`PartialEq`] is constant-time, and it is wiped when dropped (issue #1142).
308#[cfg(feature = "crypto")]
309#[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
310#[derive(Clone)]
311pub struct SecretBytes(Vec<u8>);
312
313#[cfg(feature = "crypto")]
314impl SecretBytes {
315    /// Wrap `bytes`.
316    pub fn new(bytes: Vec<u8>) -> Self {
317        SecretBytes(bytes)
318    }
319}
320
321#[cfg(feature = "crypto")]
322impl From<Vec<u8>> for SecretBytes {
323    fn from(bytes: Vec<u8>) -> Self {
324        SecretBytes(bytes)
325    }
326}
327
328#[cfg(feature = "crypto")]
329impl core::ops::Deref for SecretBytes {
330    type Target = [u8];
331    fn deref(&self) -> &[u8] {
332        &self.0
333    }
334}
335
336#[cfg(feature = "crypto")]
337impl core::fmt::Debug for SecretBytes {
338    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
339        write!(f, "SecretBytes(<redacted, {} bytes>)", self.0.len())
340    }
341}
342
343#[cfg(feature = "crypto")]
344impl PartialEq for SecretBytes {
345    /// Constant-time in the contents (the length is not secret).
346    fn eq(&self, other: &Self) -> bool {
347        bool::from(self.0.as_slice().ct_eq(other.0.as_slice()))
348    }
349}
350
351#[cfg(feature = "crypto")]
352impl Eq for SecretBytes {}
353
354#[cfg(feature = "crypto")]
355impl Zeroize for SecretBytes {
356    fn zeroize(&mut self) {
357        self.0.zeroize();
358    }
359}
360
361#[cfg(feature = "crypto")]
362impl Drop for SecretBytes {
363    fn drop(&mut self) {
364        self.zeroize();
365    }
366}
367
368#[cfg(feature = "crypto")]
369impl zeroize::ZeroizeOnDrop for SecretBytes {}
370
371/// Local configuration for one side of a Caller-Listener handshake — the
372/// values *this* engine advertises (`draft-sharabayko-srt-01` §3.2.1,
373/// §3.2.1.1, §3.2.1.3, §3.2.1.4).
374#[derive(Debug, Clone, PartialEq)]
375pub struct HandshakeConfig {
376    /// TSBPD delay in milliseconds this side requests, sent as both the
377    /// Receiver and Sender TSBPD Delay of its Handshake Extension Message
378    /// (§3.2.1.1, Figure 6). The negotiated value is the greater of the two
379    /// parties' requests (§4.3.1.2).
380    pub latency_ms: u16,
381    /// Maximum Transmission Unit Size (§3.2.1).
382    pub mtu: u32,
383    /// Maximum Flow Window Size (§3.2.1).
384    pub max_flow_window_size: u32,
385    /// Initial Packet Sequence Number this side will use for its first data
386    /// packet (§3.2.1). No data plane exists yet in this crate; callers of a
387    /// later data-plane PR are expected to set this to a real ISN.
388    pub initial_seq_number: u32,
389    /// The `SRT Version` this side reports in its Handshake Extension
390    /// Message (`major * 0x10000 + minor * 0x100 + patch`, §3.2.1.1).
391    pub srt_version: u32,
392    /// `SRT Flags` this side advertises (§3.2.1.1.1, Table 6).
393    pub flags: HandshakeExtensionMessageFlags,
394    /// Advertised cipher family and block size (§3.2.1, Table 2). Actual
395    /// key-wrap/unwrap crypto is an explicit follow-up; this field is
396    /// negotiated but not acted on in this release.
397    pub encryption_field: EncryptionField,
398    /// Stream ID to advertise (Caller only — §3.2.1.3); `None` sends no
399    /// Stream ID extension.
400    pub stream_id: Option<String>,
401    /// Group Membership to advertise (§3.2.1.4); `None` sends no Group
402    /// extension.
403    pub group: Option<GroupMembershipExtension>,
404    /// This side's own IP address, reported in every outgoing handshake
405    /// packet's `Peer IP Address` field (§3.2.1: "IPv4 or IPv6 address of
406    /// the packet's *sender*" — despite the field's name, each party reports
407    /// its own address, not its peer's).
408    pub local_ip: [u32; 4],
409    /// Number of [`crate::caller::CallerHandshake::tick`] /
410    /// [`crate::listener::ListenerHandshake::tick`] calls with no reply
411    /// before the last-sent handshake packet is retransmitted. Timeouts are
412    /// modeled as caller-driven ticks — no wall-clock lives in this crate.
413    pub retransmit_after_ticks: u32,
414    /// Maximum number of retransmissions before the handshake gives up
415    /// ([`HandshakeOutput::TimedOut`]).
416    pub max_retries: u32,
417    /// Opt-in §6 payload-encryption negotiation (`crypto` feature only).
418    /// `None` (the default) means this side neither offers nor requires
419    /// encryption. See [`CryptoConfig`] for the caller-supplied Salt/SEK
420    /// contract.
421    #[cfg(feature = "crypto")]
422    #[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
423    pub crypto: Option<CryptoConfig>,
424}
425
426/// Default [`HandshakeConfig::max_retries`]: twelve retransmissions at the
427/// adapter's 250 ms retransmit period is libsrt's 3 s connect timeout
428/// (`SRTO_CONNTIMEO`) — the previous 5 gave up after 1.25 s of a 250 ms
429/// retransmit period.
430pub const DEFAULT_MAX_RETRIES: u32 = 12;
431
432impl Default for HandshakeConfig {
433    fn default() -> Self {
434        HandshakeConfig {
435            latency_ms: 120,
436            mtu: 1500,
437            max_flow_window_size: 8192,
438            initial_seq_number: 0,
439            srt_version: 0x0105_0000,
440            flags: HandshakeExtensionMessageFlags(
441                crate::packet::handshake::HS_MSG_FLAG_TSBPDSND
442                    | crate::packet::handshake::HS_MSG_FLAG_TSBPDRCV
443                    | crate::packet::handshake::HS_MSG_FLAG_CRYPT
444                    | crate::packet::handshake::HS_MSG_FLAG_TLPKTDROP
445                    | crate::packet::handshake::HS_MSG_FLAG_PERIODICNAK
446                    | crate::packet::handshake::HS_MSG_FLAG_REXMITFLG,
447            ),
448            encryption_field: EncryptionField::NoEncryption,
449            stream_id: None,
450            group: None,
451            local_ip: [0, 0, 0, 0],
452            retransmit_after_ticks: 3,
453            max_retries: DEFAULT_MAX_RETRIES,
454            #[cfg(feature = "crypto")]
455            crypto: None,
456        }
457    }
458}
459
460/// The outcome of a Caller-Listener handshake, once both TSBPD delays and
461/// flags have been reconciled per `draft-sharabayko-srt-01` §4.3.1.2 ("The
462/// value for latency is always agreed to be the greater of those reported by
463/// each party").
464#[derive(Debug, Clone, PartialEq)]
465#[cfg_attr(feature = "serde", derive(serde::Serialize))]
466pub struct NegotiatedParams {
467    /// The negotiated base protocol version — always `5` (HSv5) for a
468    /// completed handshake in this crate.
469    pub version: u32,
470    /// The flags both sides advertised, ANDed together (only mutually
471    /// supported capabilities are considered agreed).
472    pub flags: HandshakeExtensionMessageFlags,
473    /// The agreed TSBPD latency in milliseconds: the greater of this side's
474    /// configured [`HandshakeConfig::latency_ms`] and the peer's reported
475    /// Receiver/Sender TSBPD Delay (§4.3.1.2).
476    pub latency_ms: u16,
477    /// This side's own SRT Socket ID.
478    pub own_socket_id: u32,
479    /// The peer's SRT Socket ID.
480    pub peer_socket_id: u32,
481    /// The agreed Maximum Transmission Unit Size (§3.2.1): the smaller of the
482    /// two parties' advertised values, so neither is sent a datagram larger
483    /// than it said it could carry.
484    pub mtu: u32,
485    /// The agreed Maximum Flow Window Size (§3.2.1): the smaller of the two
486    /// parties' advertised values — how many packets may be unacknowledged in
487    /// flight (the sender's window) and how far ahead of its ack point a
488    /// receiver tracks (the receiver's window).
489    pub max_flow_window_size: u32,
490    /// The negotiated Stream ID (§3.2.1.3), if one was advertised.
491    pub stream_id: Option<String>,
492    /// The negotiated Group Membership (§3.2.1.4), if one was advertised.
493    pub group: Option<GroupMembershipExtension>,
494    /// The negotiated Stream Encrypting Key (§6.1.5), if
495    /// [`HandshakeConfig::crypto`] was set on this side and the Key Material
496    /// exchange succeeded. `None` if encryption was not negotiated.
497    ///
498    /// A [`SecretBytes`]: redacted in `Debug`, constant-time in `==`, wiped on
499    /// drop, and never serialized.
500    #[cfg(feature = "crypto")]
501    #[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
502    #[cfg_attr(feature = "serde", serde(skip))]
503    pub sek: Option<SecretBytes>,
504    /// The Salt paired with [`Self::sek`] — both are required by
505    /// [`crate::crypto::aes_ctr_apply`] to encrypt/decrypt a data packet's
506    /// payload (§6.1.2/§6.2.2/§6.3.2).
507    #[cfg(feature = "crypto")]
508    #[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
509    pub salt: Option<[u8; crate::crypto::SALT_LEN]>,
510}
511
512/// An event produced by [`crate::caller::CallerHandshake::feed`] /
513/// [`crate::caller::CallerHandshake::start`] /
514/// [`crate::listener::ListenerHandshake::feed`] / either engine's `tick`.
515#[derive(Debug, Clone, PartialEq)]
516#[cfg_attr(feature = "serde", derive(serde::Serialize))]
517#[non_exhaustive]
518pub enum HandshakeOutput {
519    /// Send these bytes (one serialized Handshake control packet, built from
520    /// the existing [`crate::packet`] codecs) to the peer.
521    Send(Vec<u8>),
522    /// The handshake completed; here are the negotiated parameters.
523    Connected(NegotiatedParams),
524    /// The handshake was rejected — either the peer sent back an explicit
525    /// [`RejectionReason`], or a local validation check failed (in which
526    /// case a matching `Send` rejection packet is also emitted, in the same
527    /// output batch, for the Listener side).
528    Rejected(RejectionReason),
529    /// No reply arrived after [`HandshakeConfig::max_retries`]
530    /// retransmissions.
531    TimedOut,
532}
533
534/// Serializes one [`HandshakePacket`] using the existing [`ControlPacket`]
535/// codec — never hand-rolled.
536pub(crate) fn build_bytes(hp: HandshakePacket<'_>) -> Result<Vec<u8>> {
537    let pkt = ControlPacket::Handshake(hp);
538    let mut buf = alloc::vec![0u8; pkt.serialized_len()];
539    pkt.serialize_into(&mut buf)?;
540    Ok(buf)
541}
542
543/// Builds the extensions payload for a CONCLUSION-phase handshake carrying a
544/// Handshake Extension Message plus optional Stream ID / Group Membership,
545/// returning `(bytes, Extension Field flags)`.
546pub(crate) fn build_conclusion_extensions(
547    hs_ext_type: crate::packet::ExtensionType,
548    hs_msg: &HsExtMessage,
549    stream_id: Option<&str>,
550    group: Option<GroupMembershipExtension>,
551) -> Result<(Vec<u8>, u16)> {
552    use crate::packet::handshake::{build_extension_block, encode_stream_id};
553
554    let mut ext_bytes = Vec::new();
555    ext_bytes.extend(build_extension_block(hs_ext_type, &hs_msg.to_bytes())?);
556    let mut ext_flags = HS_EXT_FLAG_HSREQ;
557    if let Some(sid) = stream_id {
558        let sid_bytes = encode_stream_id(sid);
559        ext_bytes.extend(build_extension_block(
560            crate::packet::ExtensionType::Sid,
561            &sid_bytes,
562        )?);
563        ext_flags |= HS_EXT_FLAG_CONFIG;
564    }
565    if let Some(g) = group {
566        ext_bytes.extend(build_extension_block(
567            crate::packet::ExtensionType::Group,
568            &g.to_bytes(),
569        )?);
570        ext_flags |= HS_EXT_FLAG_CONFIG;
571    }
572    Ok((ext_bytes, ext_flags))
573}
574
575/// A parsed peer extension payload relevant to the Caller-Listener handshake:
576/// the mandatory Handshake Extension Message plus any optional Stream ID /
577/// Group Membership / Key Material.
578#[derive(Debug, Default)]
579pub(crate) struct ParsedPeerExtensions<'a> {
580    pub hs_msg: Option<HsExtMessage>,
581    pub stream_id: Option<String>,
582    pub group: Option<GroupMembershipExtension>,
583    /// The Key Material extension (§3.2.1.2/§3.2.2, `SRT_CMD_KMREQ` on the
584    /// Caller's CONCLUSION / `SRT_CMD_KMRSP` on the Listener's) — decoded
585    /// regardless of the `crypto` feature (wire-structure decode only,
586    /// [`KeyMaterial`] has no crypto dependency); only *acted on*
587    /// (KEK derive/unwrap/wrap) when `crypto` is enabled, see
588    /// [`crate::caller::CallerHandshake`]/[`crate::listener::ListenerHandshake`].
589    #[cfg(feature = "crypto")]
590    pub km: Option<KeyMaterial<'a>>,
591    /// Keeps the `'a` lifetime parameter meaningful when the `crypto`
592    /// feature (and with it, [`Self::km`]) is compiled out.
593    #[cfg(not(feature = "crypto"))]
594    _phantom: core::marker::PhantomData<&'a ()>,
595}
596
597/// Walks a handshake packet's extension blocks, decoding the ones this crate
598/// understands. Returns [`Error::InvalidField`] (mapped by the caller to a
599/// [`RejectionReason::Rogue`] rejection) on any decode failure, rather than
600/// panicking — extension content is untrusted peer input.
601pub(crate) fn parse_peer_extensions<'a>(
602    hp: &HandshakePacket<'a>,
603) -> Result<ParsedPeerExtensions<'a>> {
604    use crate::packet::ExtensionType;
605
606    let mut out = ParsedPeerExtensions::default();
607    for block in hp.extensions.iter() {
608        let block = block.map_err(|_| Error::InvalidField {
609            what: "handshake extensions",
610            reason: "malformed extension block",
611        })?;
612        match block.ext_type {
613            ExtensionType::HsReq | ExtensionType::HsRsp => {
614                let msg = block.as_hs_ext_message().map_err(|_| Error::InvalidField {
615                    what: "handshake extension message",
616                    reason: "malformed HSREQ/HSRSP contents",
617                })?;
618                out.hs_msg = Some(msg);
619            }
620            ExtensionType::Sid => {
621                let sid = block.as_stream_id().map_err(|_| Error::InvalidField {
622                    what: "stream ID extension",
623                    reason: "malformed or non-UTF-8 contents",
624                })?;
625                out.stream_id = Some(sid);
626            }
627            ExtensionType::Group => {
628                let g = block
629                    .as_group_membership()
630                    .map_err(|_| Error::InvalidField {
631                        what: "group membership extension",
632                        reason: "malformed contents",
633                    })?;
634                out.group = Some(g);
635            }
636            #[cfg(feature = "crypto")]
637            ExtensionType::KmReq | ExtensionType::KmRsp => {
638                let km = block.as_key_material().map_err(|_| Error::InvalidField {
639                    what: "key material extension",
640                    reason: "malformed contents",
641                })?;
642                out.km = Some(km);
643            }
644            _ => {}
645        }
646    }
647    Ok(out)
648}
649
650// ---------------------------------------------------------------------------
651// §6.1.5 Key Material Exchange — piggybacked on the CONCLUSION extensions.
652// ---------------------------------------------------------------------------
653
654/// Build the Key Material handshake extension block (`Extension Type` +
655/// `Extension Length` + contents — ready to append after the mandatory
656/// HSREQ block) offering `crypto.sek`, wrapped under a KEK derived from
657/// `crypto.passphrase`/`crypto.salt` (`draft-sharabayko-srt-01` §6.1.5 "sent
658/// by the connection initiator ... to the responder", §6.2.1's `Wrap =
659/// AESkw(KEK, SEK)`). Always encodes `KK = Even` — this crate's convention
660/// for the handshake-negotiated initial SEK; §6.1.6's odd/even alternation
661/// only matters from the first KM Refresh onward (see [`crate::km_refresh`]).
662#[cfg(feature = "crypto")]
663pub(crate) fn build_key_material_extension(crypto: &CryptoConfig) -> Result<Vec<u8>> {
664    let kek = crate::crypto::derive_kek(&crypto.passphrase, &crypto.salt, crypto.sek.len())?;
665    let (icv, wrapped) = crate::crypto::wrap_sek(&kek, &crypto.sek)?;
666    let km = KeyMaterial {
667        kk: KmKeyFlag::Even,
668        keki: 0,
669        cipher: Cipher::AesCtr,
670        auth: KmAuth::None,
671        se: StreamEncapsulation::MpegTsSrt,
672        salt: &crypto.salt,
673        icv,
674        x_sek: &wrapped,
675        o_sek: None,
676    };
677    let mut buf = alloc::vec![0u8; km.serialized_len()];
678    km.serialize_into(&mut buf)?;
679    crate::packet::handshake::build_extension_block(crate::packet::ExtensionType::KmReq, &buf)
680}
681
682/// A recovered/negotiated `(SEK, Salt)` pair.
683#[cfg(feature = "crypto")]
684pub(crate) type RecoveredSek = (SecretBytes, [u8; crate::crypto::SALT_LEN]);
685
686/// Recover the SEK a peer's Key Material offered, given this side's shared
687/// passphrase (§6.1.5/§6.3.1: "the responder MUST know the passphrase ...
688/// everything else needed is extracted from the Keying Material message").
689/// Returns the recovered SEK bytes and the 16-byte Salt — both required by
690/// [`crate::crypto::aes_ctr_apply`].
691///
692/// # Errors
693/// [`Error::InvalidField`] if the Salt is not 16 bytes (the only Salt length
694/// this crate's Key Material codec accepts); otherwise propagates
695/// [`crate::crypto::unwrap_sek`]'s error (RFC 3394 wrap-integrity failure —
696/// wrong passphrase, §6.1.5's "it does not have the SEK" case).
697#[cfg(feature = "crypto")]
698pub(crate) fn recover_sek(passphrase: &[u8], km: &KeyMaterial<'_>) -> Result<RecoveredSek> {
699    if km.salt.len() != crate::crypto::SALT_LEN {
700        return Err(Error::InvalidField {
701            what: "Key Material Salt",
702            reason: "must be 16 bytes (the only Salt length this crate's codec accepts)",
703        });
704    }
705    let mut salt = [0u8; crate::crypto::SALT_LEN];
706    salt.copy_from_slice(km.salt);
707    let kek = crate::crypto::derive_kek(passphrase, &salt, km.x_sek.len())?;
708    let sek = SecretBytes::new(crate::crypto::unwrap_sek(&kek, &km.icv, km.x_sek)?.to_vec());
709    Ok((sek, salt))
710}
711
712/// Re-serialize a parsed Key Material message and wrap it as a `KmRsp`
713/// extension block — the responder's confirmation echo (§6.1.5: "the
714/// responder ... echoes the same KM message back to prove it derived the
715/// same SEK").
716#[cfg(feature = "crypto")]
717pub(crate) fn echo_key_material_as_response(km: &KeyMaterial<'_>) -> Result<Vec<u8>> {
718    let mut buf = alloc::vec![0u8; km.serialized_len()];
719    km.serialize_into(&mut buf)?;
720    crate::packet::handshake::build_extension_block(crate::packet::ExtensionType::KmRsp, &buf)
721}
722
723/// Verify a Listener's echoed Key Material matches what this Caller sent.
724/// Recomputed deterministically from `crypto` (the same passphrase/salt/sek
725/// always wraps to the same bytes, §6.2.1) rather than requiring the Caller
726/// to keep the original wrap bytes around.
727#[cfg(feature = "crypto")]
728pub(crate) fn verify_km_echo(crypto: &CryptoConfig, echoed: &KeyMaterial<'_>) -> bool {
729    let kek = match crate::crypto::derive_kek(&crypto.passphrase, &crypto.salt, crypto.sek.len()) {
730        Ok(k) => k,
731        Err(_) => return false,
732    };
733    let (icv, wrapped) = match crate::crypto::wrap_sek(&kek, &crypto.sek) {
734        Ok(v) => v,
735        Err(_) => return false,
736    };
737    // The wrapped key is derived from the secret: compare it in constant time.
738    let salt = echoed.salt.ct_eq(crypto.salt.as_slice());
739    let icv = echoed.icv.as_slice().ct_eq(icv.as_slice());
740    let wrapped = echoed.x_sek.ct_eq(wrapped.as_slice());
741    bool::from(salt & icv & wrapped)
742}
743
744/// The greater-of-both-parties TSBPD latency rule (§4.3.1.2).
745pub(crate) fn negotiate_latency_ms(local_latency_ms: u16, peer_msg: &HsExtMessage) -> u16 {
746    local_latency_ms
747        .max(peer_msg.receiver_tsbpd_delay_ms)
748        .max(peer_msg.sender_tsbpd_delay_ms)
749}
750
751/// SipHash-2-4 (Aumasson & Bernstein, "SipHash: a fast short-input PRF",
752/// 2012): a keyed 64-bit pseudorandom function designed for exactly this use —
753/// short inputs, an unpredictable key, an attacker who must not be able to
754/// forge outputs. Verified against the paper's reference test vector in this
755/// module's tests.
756fn siphash24(k0: u64, k1: u64, data: &[u8]) -> u64 {
757    // Compression rounds per message block and finalisation rounds: the "2-4"
758    // of SipHash-2-4.
759    const C_ROUNDS: usize = 2;
760    const D_ROUNDS: usize = 4;
761    // The four state words' initialisation constants (ASCII of
762    // "somepseudorandomlygeneratedbytes"), per the SipHash paper.
763    const INIT_V0: u64 = 0x736f_6d65_7073_6575;
764    const INIT_V1: u64 = 0x646f_7261_6e64_6f6d;
765    const INIT_V2: u64 = 0x6c79_6765_6e65_7261;
766    const INIT_V3: u64 = 0x7465_6462_7974_6573;
767    // XORed into `v2` before the finalisation rounds.
768    const FINALIZATION_XOR: u64 = 0xFF;
769
770    let mut v0 = k0 ^ INIT_V0;
771    let mut v1 = k1 ^ INIT_V1;
772    let mut v2 = k0 ^ INIT_V2;
773    let mut v3 = k1 ^ INIT_V3;
774
775    fn round(v0: &mut u64, v1: &mut u64, v2: &mut u64, v3: &mut u64) {
776        *v0 = v0.wrapping_add(*v1);
777        *v1 = v1.rotate_left(13);
778        *v1 ^= *v0;
779        *v0 = v0.rotate_left(32);
780        *v2 = v2.wrapping_add(*v3);
781        *v3 = v3.rotate_left(16);
782        *v3 ^= *v2;
783        *v0 = v0.wrapping_add(*v3);
784        *v3 = v3.rotate_left(21);
785        *v3 ^= *v0;
786        *v2 = v2.wrapping_add(*v1);
787        *v1 = v1.rotate_left(17);
788        *v1 ^= *v2;
789        *v2 = v2.rotate_left(32);
790    }
791
792    let mut chunks = data.chunks_exact(8);
793    for chunk in chunks.by_ref() {
794        let mut word = [0u8; 8];
795        word.copy_from_slice(chunk);
796        let m = u64::from_le_bytes(word);
797        v3 ^= m;
798        for _ in 0..C_ROUNDS {
799            round(&mut v0, &mut v1, &mut v2, &mut v3);
800        }
801        v0 ^= m;
802    }
803    // Final block: the remaining 0..=7 bytes, with the input length in the
804    // top byte (modulo 256, as the reference does).
805    let mut last = [0u8; 8];
806    let rest = chunks.remainder();
807    last[..rest.len()].copy_from_slice(rest);
808    last[7] = u8::try_from(data.len() & 0xFF).unwrap_or(0);
809    let m = u64::from_le_bytes(last);
810    v3 ^= m;
811    for _ in 0..C_ROUNDS {
812        round(&mut v0, &mut v1, &mut v2, &mut v3);
813    }
814    v0 ^= m;
815    v2 ^= FINALIZATION_XOR;
816    for _ in 0..D_ROUNDS {
817        round(&mut v0, &mut v1, &mut v2, &mut v3);
818    }
819    v0 ^ v1 ^ v2 ^ v3
820}
821
822/// Derives a SYN Cookie from caller-supplied inputs (`draft-sharabayko-srt-01`
823/// §4.3.1.1: "a cookie that is crafted based on host, port and current time
824/// with 1 minute accuracy"). The draft specifies the semantic inputs, not a
825/// wire algorithm; this crate's core never reads a clock, so `time_bucket`
826/// (e.g. UNIX time / 60) must come from the caller/driver.
827///
828/// The cookie is the low 32 bits of **SipHash-2-4** over `peer_key ‖
829/// time_bucket`, keyed by the 128-bit `secret` (SipHash's whole key, low half
830/// as `k0`): a real keyed PRF, so a peer that sees cookies cannot predict or
831/// forge the cookie for another `(peer, minute)` without the secret. It is
832/// still *not* a message-authentication code of the handshake packet: the
833/// cookie only proves the Caller received the INDUCTION response sent to its
834/// address, and its 32 bits are a flood-protection token, not a long-lived
835/// credential. `secret` must come from a CSPRNG and should be replaced
836/// periodically (the tokio adapter's listener draws it from the OS and
837/// rotates it every minute).
838pub fn derive_cookie(peer_key: u64, time_bucket: u32, secret: u128) -> u32 {
839    let mut input = [0u8; 12];
840    input[..8].copy_from_slice(&peer_key.to_le_bytes());
841    input[8..].copy_from_slice(&time_bucket.to_le_bytes());
842    let k0 = u64::try_from(secret & u128::from(u64::MAX)).unwrap_or(0);
843    let k1 = u64::try_from(secret >> 64).unwrap_or(0);
844    let digest = siphash24(k0, k1, &input);
845    // Keep the low 32 bits; `| 1` so it is never 0, never confused with "no
846    // cookie yet".
847    u32::try_from(digest & u64::from(u32::MAX)).unwrap_or(0) | 1
848}
849
850#[cfg(test)]
851mod tests {
852    use super::*;
853
854    #[test]
855    fn rejection_reason_round_trips_table_7() {
856        let all = [
857            RejectionReason::Unknown,
858            RejectionReason::System,
859            RejectionReason::Peer,
860            RejectionReason::Resource,
861            RejectionReason::Rogue,
862            RejectionReason::Backlog,
863            RejectionReason::Ipe,
864            RejectionReason::Close,
865            RejectionReason::Version,
866            RejectionReason::RdvCookie,
867            RejectionReason::BadSecret,
868            RejectionReason::Unsecure,
869            RejectionReason::MessageApi,
870            RejectionReason::Congestion,
871            RejectionReason::Filter,
872            RejectionReason::Group,
873        ];
874        for (i, r) in all.iter().enumerate() {
875            assert_eq!(r.to_bits(), 1000 + i as u32);
876            assert_eq!(RejectionReason::from_bits(r.to_bits()), *r);
877            assert_eq!(
878                RejectionReason::from_handshake_type(r.to_handshake_type()),
879                Some(*r)
880            );
881        }
882    }
883
884    #[test]
885    fn non_rejection_handshake_types_are_not_a_rejection() {
886        for ht in [
887            HandshakeType::Induction,
888            HandshakeType::Conclusion,
889            HandshakeType::Wavehand,
890            HandshakeType::Agreement,
891            HandshakeType::Done,
892        ] {
893            assert_eq!(RejectionReason::from_handshake_type(ht), None);
894        }
895    }
896
897    #[test]
898    fn derive_cookie_is_deterministic_and_nonzero() {
899        let a = derive_cookie(0x1234_5678_9ABC_DEF0, 12345, 0xDEAD_BEEF);
900        let b = derive_cookie(0x1234_5678_9ABC_DEF0, 12345, 0xDEAD_BEEF);
901        assert_eq!(a, b);
902        assert_ne!(a, 0);
903        let c = derive_cookie(0x1234_5678_9ABC_DEF1, 12345, 0xDEAD_BEEF);
904        assert_ne!(a, c);
905    }
906
907    /// r08-SRT-W14: only `1000..2^31` is a rejection. `0xFFFF_FFFC` (libsrt's
908    /// negative URQ range) and `2^31` itself used to be reported as
909    /// `Rejected(Reserved(..))`.
910    #[test]
911    fn only_the_positive_rejection_range_counts_as_a_rejection() {
912        let is_rejection =
913            |v: u32| RejectionReason::from_handshake_type(HandshakeType::from_bits(v)).is_some();
914        assert!(!is_rejection(0xFFFF_FFFC));
915        assert!(!is_rejection(0xFFFF_FFFE)); // AGREEMENT is its own type
916        assert!(!is_rejection(REJECTION_CODE_LIMIT));
917        assert!(!is_rejection(REJECTION_CODE_BASE - 1));
918        assert!(is_rejection(REJECTION_CODE_BASE));
919        assert!(is_rejection(REJECTION_CODE_LIMIT - 1));
920        // A predefined reason, a reason the table does not define, and a
921        // user-defined (2000+) reason all decode.
922        assert_eq!(
923            RejectionReason::from_handshake_type(HandshakeType::from_bits(1010)),
924            Some(RejectionReason::BadSecret)
925        );
926        assert_eq!(
927            RejectionReason::from_handshake_type(HandshakeType::from_bits(1500)),
928            Some(RejectionReason::Reserved(1500))
929        );
930        assert_eq!(
931            RejectionReason::from_handshake_type(HandshakeType::from_bits(2001)),
932            Some(RejectionReason::Reserved(2001))
933        );
934    }
935
936    /// r08-SRT-W7: the Caller's KMREQ carries `SE` = 2 (MPEG-TS/SRT), the
937    /// value libsrt's `hcryptCtx_Rx_ParseKM` requires (`km_msg[SE] ==
938    /// crypto->se`, `HCRYPT_SE_TSSRT`); `SE` = 0 is rejected as a bad KM.
939    #[cfg(feature = "crypto")]
940    #[test]
941    fn caller_kmreq_declares_the_mpeg_ts_srt_encapsulation() {
942        let crypto = CryptoConfig {
943            passphrase: b"0123456789abcdef".to_vec(),
944            salt: [0x33; crate::crypto::SALT_LEN],
945            sek: alloc::vec![0x44; 16],
946        };
947        let ext = build_key_material_extension(&crypto).unwrap();
948        // Extension block: type(16) length(16, words) then the KM message.
949        let km = KeyMaterial::parse(&ext[4..]).unwrap();
950        assert_eq!(km.se, StreamEncapsulation::MpegTsSrt);
951        assert_eq!(km.se.to_bits(), 2);
952        // Wire byte: word 2 of the KM is Cipher(8) Auth(8) SE(8) Resv2(8).
953        assert_eq!(ext[4 + 10], 2);
954    }
955
956    /// The SipHash-2-4 reference vector from the paper's appendix: key
957    /// `00 01 .. 0f`, input `00 01 .. 0e` (15 bytes), output `a129ca6149be45e5`.
958    #[test]
959    fn siphash24_matches_the_reference_vector() {
960        let k0 = u64::from_le_bytes([0, 1, 2, 3, 4, 5, 6, 7]);
961        let k1 = u64::from_le_bytes([8, 9, 10, 11, 12, 13, 14, 15]);
962        let input: Vec<u8> = (0u8..15).collect();
963        assert_eq!(siphash24(k0, k1, &input), 0xa129_ca61_49be_45e5);
964        // And the empty input (a second reference value from the same table).
965        assert_eq!(siphash24(k0, k1, &[]), 0x726f_db47_dd0e_0e31);
966    }
967
968    /// The cookie depends on every input, including the secret.
969    #[test]
970    fn derive_cookie_depends_on_secret_peer_and_time() {
971        let base = derive_cookie(1, 2, 3);
972        assert_ne!(base, derive_cookie(1, 2, 4), "secret");
973        assert_ne!(base, derive_cookie(9, 2, 3), "peer");
974        assert_ne!(base, derive_cookie(1, 9, 3), "time bucket");
975        assert_eq!(base & 1, 1);
976        // Pinned against an independent SipHash-2-4 implementation (Python,
977        // checked against the same reference vector): fixes the input layout
978        // (`peer_key` LE ‖ `time_bucket` LE) and the key split (low half k0).
979        assert_eq!(
980            derive_cookie(0x1234_5678_9ABC_DEF0, 12345, 0xDEAD_BEEF),
981            0x5905_9ee9
982        );
983        assert_eq!(
984            derive_cookie(
985                0x1234_5678_9ABC_DEF0,
986                12345,
987                0x0123_4567_89AB_CDEF_FEDC_BA98_7654_3210
988            ),
989            0xec46_1e0b
990        );
991        // Both halves of the key matter.
992        assert_ne!(
993            derive_cookie(1, 2, 7),
994            derive_cookie(1, 2, 7 | (1u128 << 64)),
995            "the high key half must influence the cookie"
996        );
997    }
998
999    // ---- #1142: secrets stay out of Debug / serde, are compared in constant
1000    // time and wiped on drop ------------------------------------------------
1001
1002    /// A non-repeating pseudo-random run, so a needle cut from it cannot occur
1003    /// by chance in unrelated numbers.
1004    #[cfg(feature = "crypto")]
1005    fn distinctive(seed: u32, len: usize) -> Vec<u8> {
1006        let mut x = seed.wrapping_mul(2_654_435_761).wrapping_add(12_345);
1007        (0..len)
1008            .map(|_| {
1009                x = x.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
1010                u8::try_from(x >> 24).unwrap()
1011            })
1012            .collect()
1013    }
1014
1015    /// Every spelling a leak of the first six bytes of `bytes` could take.
1016    #[cfg(feature = "crypto")]
1017    fn needles(bytes: &[u8]) -> Vec<String> {
1018        let head = &bytes[..6];
1019        let dec = |sep: &str| {
1020            head.iter()
1021                .map(|b| alloc::format!("{b}"))
1022                .collect::<Vec<_>>()
1023                .join(sep)
1024        };
1025        alloc::vec![
1026            dec(", "),
1027            dec(","),
1028            head.iter()
1029                .map(|b| alloc::format!("{b:x}"))
1030                .collect::<Vec<_>>()
1031                .join(", "),
1032            head.iter().map(|b| alloc::format!("{b:02x}")).collect(),
1033        ]
1034    }
1035
1036    #[cfg(feature = "crypto")]
1037    fn secret_config() -> CryptoConfig {
1038        CryptoConfig {
1039            passphrase: distinctive(1, 15),
1040            salt: distinctive(2, crate::crypto::SALT_LEN).try_into().unwrap(),
1041            sek: distinctive(3, 16),
1042        }
1043    }
1044
1045    /// `{:?}` and `{:#?}` of a config (alone or inside a `HandshakeConfig`)
1046    /// carry no passphrase, salt or key bytes — only their lengths.
1047    #[cfg(feature = "crypto")]
1048    #[test]
1049    fn crypto_config_debug_never_shows_secret_bytes() {
1050        let config = HandshakeConfig {
1051            crypto: Some(secret_config()),
1052            ..HandshakeConfig::default()
1053        };
1054        for dump in [
1055            alloc::format!("{:?}", secret_config()),
1056            alloc::format!("{:#?}", secret_config()),
1057            alloc::format!("{:?}", config),
1058            alloc::format!("{:#?}", config),
1059            alloc::format!("{:x?}", config),
1060        ] {
1061            let secret = secret_config();
1062            for (name, bytes) in [
1063                ("passphrase", &secret.passphrase[..]),
1064                ("salt", &secret.salt[..]),
1065                ("sek", &secret.sek[..]),
1066            ] {
1067                for needle in needles(bytes) {
1068                    assert!(
1069                        !dump.contains(&needle),
1070                        "{name} leaked as {needle:?}: {dump}"
1071                    );
1072                }
1073            }
1074            assert!(dump.contains("redacted"), "{dump}");
1075        }
1076        assert!(alloc::format!("{:?}", secret_config()).contains("15 bytes"));
1077    }
1078
1079    /// A negotiated key is redacted in `Debug` — also when it rides inside a
1080    /// [`HandshakeOutput`] — and is not serialized.
1081    #[cfg(feature = "crypto")]
1082    #[test]
1083    fn negotiated_sek_is_redacted_in_debug_and_absent_from_serde() {
1084        let sek_bytes = distinctive(9, 16);
1085        let params = NegotiatedParams {
1086            version: HANDSHAKE_VERSION_5,
1087            flags: HandshakeExtensionMessageFlags(0),
1088            latency_ms: 120,
1089            own_socket_id: 1,
1090            peer_socket_id: 2,
1091            mtu: 1500,
1092            max_flow_window_size: 8192,
1093            stream_id: None,
1094            group: None,
1095            sek: Some(SecretBytes::new(sek_bytes.clone())),
1096            salt: Some([0x11; crate::crypto::SALT_LEN]),
1097        };
1098        for dump in [
1099            alloc::format!("{params:?}"),
1100            alloc::format!("{:#?}", HandshakeOutput::Connected(params.clone())),
1101            alloc::format!("{:x?}", HandshakeOutput::Connected(params.clone())),
1102        ] {
1103            for needle in needles(&sek_bytes) {
1104                assert!(!dump.contains(&needle), "SEK leaked as {needle:?}: {dump}");
1105            }
1106            assert!(dump.contains("redacted"), "{dump}");
1107        }
1108        #[cfg(feature = "serde")]
1109        {
1110            let json = serde_json::to_string(&params).expect("serialize");
1111            assert!(!json.contains("sek"), "the SEK was serialized: {json}");
1112            for needle in needles(&sek_bytes) {
1113                assert!(!json.contains(&needle), "SEK leaked as {needle:?}: {json}");
1114            }
1115        }
1116    }
1117
1118    /// Secret comparison and wiping: `==` distinguishes contents (and
1119    /// lengths) correctly through the constant-time path, and `zeroize`
1120    /// clears the key and the passphrase.
1121    #[cfg(feature = "crypto")]
1122    #[test]
1123    fn secrets_compare_correctly_and_wipe_on_zeroize() {
1124        let a = SecretBytes::new(alloc::vec![1, 2, 3, 4]);
1125        assert!(a == SecretBytes::new(alloc::vec![1, 2, 3, 4]));
1126        assert!(a != SecretBytes::new(alloc::vec![1, 2, 3, 5]));
1127        assert!(a != SecretBytes::new(alloc::vec![1, 2, 3]));
1128        assert_eq!(&*a, &[1u8, 2, 3, 4][..]);
1129
1130        let mut sek = SecretBytes::new(alloc::vec![9; 16]);
1131        sek.zeroize();
1132        assert!(sek.is_empty(), "zeroize must clear the key");
1133
1134        let mut config = secret_config();
1135        assert!(config == secret_config());
1136        let mut other = secret_config();
1137        other.sek[0] ^= 1;
1138        assert!(config != other);
1139        config.zeroize();
1140        assert!(config.passphrase.is_empty() && config.sek.is_empty());
1141        assert_eq!(config.salt, [0u8; crate::crypto::SALT_LEN]);
1142    }
1143
1144    /// Compile-time guard: both secret holders wipe themselves on drop.
1145    #[cfg(feature = "crypto")]
1146    #[test]
1147    fn secret_holders_are_zeroize_on_drop() {
1148        fn assert_zeroize_on_drop<T: zeroize::ZeroizeOnDrop>() {}
1149        assert_zeroize_on_drop::<CryptoConfig>();
1150        assert_zeroize_on_drop::<SecretBytes>();
1151    }
1152}