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