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