Skip to main content

srt_runtime/
cookie.rs

1//! The SYN Cookie and the Listener's stateless identifiers โ€” `draft-sharabayko-srt-01` ยง4.3.1.1
2//! ("a cookie that is crafted based on host, port and current time with 1 minute accuracy";
3//! `private/specs-verified/rules/srt-rules.md`).
4//!
5//! The draft names the cookie's inputs, not an algorithm. Here the cookie is a keyed MAC โ€”
6//! HMAC-SHA-256 under the listener's secret โ€” over the peer's full address (family, IP, port),
7//! the Caller's Socket ID and a coarse time bucket, so a cookie obtained from one source proves
8//! nothing for another, and it expires once its bucket is two old. This crate never reads a
9//! clock: the caller supplies the bucket (UNIX time / 60) and the secret (from a CSPRNG, replaced
10//! periodically).
11
12use core::net::{IpAddr, SocketAddr};
13
14use hmac::digest::Key;
15use hmac::{Hmac, KeyInit, Mac};
16use sha2::Sha256;
17use subtle::ConstantTimeEq;
18
19const COOKIE_DOMAIN: u8 = 0;
20const SOCKET_ID_DOMAIN: u8 = 1;
21const ISN_DOMAIN: u8 = 2;
22const FAMILY_V4: u8 = 4;
23const FAMILY_V6: u8 = 6;
24const SECRET_LEN: usize = core::mem::size_of::<u128>();
25const WORD_LEN: usize = core::mem::size_of::<u32>();
26
27/// The key and the bucket a validated cookie was issued under.
28#[derive(Clone, Copy, PartialEq, Eq)]
29pub struct CookieOrigin {
30    /// The time bucket the cookie was derived for.
31    pub time_bucket: u32,
32    /// The secret it was derived under.
33    pub secret: u128,
34}
35
36impl core::fmt::Debug for CookieOrigin {
37    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
38        f.debug_struct("CookieOrigin")
39            .field("time_bucket", &self.time_bucket)
40            .finish_non_exhaustive()
41    }
42}
43
44fn tag(
45    domain: u8,
46    peer: &SocketAddr,
47    caller_socket_id: u32,
48    time_bucket: u32,
49    secret: u128,
50) -> u32 {
51    let mut key = Key::<Hmac<Sha256>>::default();
52    key[..SECRET_LEN].copy_from_slice(&secret.to_le_bytes());
53    let mut mac = Hmac::<Sha256>::new(&key);
54    mac.update(&[domain]);
55    match peer.ip() {
56        IpAddr::V4(ip) => {
57            mac.update(&[FAMILY_V4]);
58            mac.update(&ip.octets());
59        }
60        IpAddr::V6(ip) => {
61            mac.update(&[FAMILY_V6]);
62            mac.update(&ip.octets());
63        }
64    }
65    mac.update(&peer.port().to_be_bytes());
66    mac.update(&caller_socket_id.to_be_bytes());
67    mac.update(&time_bucket.to_be_bytes());
68    let digest = mac.finalize().into_bytes();
69    let mut word = [0u8; WORD_LEN];
70    word.copy_from_slice(&digest[..WORD_LEN]);
71    u32::from_be_bytes(word)
72}
73
74/// The SYN Cookie for `peer` and the Caller's `caller_socket_id` in `time_bucket`, under
75/// `secret`. Never `0` (that value means "no cookie yet").
76#[must_use]
77pub fn derive_cookie(
78    peer: &SocketAddr,
79    caller_socket_id: u32,
80    time_bucket: u32,
81    secret: u128,
82) -> u32 {
83    tag(COOKIE_DOMAIN, peer, caller_socket_id, time_bucket, secret) | 1
84}
85
86/// Whether `cookie` was issued to `peer` and `caller_socket_id` under one of `secrets`, in
87/// `now_bucket` or the bucket before it, compared in constant time. A cookie two buckets old is
88/// refused.
89#[must_use]
90pub fn validate_cookie(
91    peer: &SocketAddr,
92    caller_socket_id: u32,
93    cookie: u32,
94    now_bucket: u32,
95    secrets: impl IntoIterator<Item = u128> + Clone,
96) -> Option<CookieOrigin> {
97    let mut found = None;
98    for time_bucket in [now_bucket, now_bucket.wrapping_sub(1)] {
99        for secret in secrets.clone() {
100            let derived = derive_cookie(peer, caller_socket_id, time_bucket, secret);
101            if bool::from(derived.ct_eq(&cookie)) && found.is_none() {
102                found = Some(CookieOrigin {
103                    time_bucket,
104                    secret,
105                });
106            }
107        }
108    }
109    found
110}
111
112/// The Listener's per-connection Socket ID and Initial Sequence Number for a cookie issued over
113/// the same inputs: a stateless Listener has nowhere to keep what its INDUCTION answer carried,
114/// so the CONCLUSION recomputes it. Domain-separated from the cookie, so a Caller that has seen
115/// its cookie cannot compute them. The Socket ID is never `0` (no socket assigned).
116#[must_use]
117pub fn derive_listener_ids(
118    peer: &SocketAddr,
119    caller_socket_id: u32,
120    time_bucket: u32,
121    secret: u128,
122) -> (u32, u32) {
123    let socket_id = tag(
124        SOCKET_ID_DOMAIN,
125        peer,
126        caller_socket_id,
127        time_bucket,
128        secret,
129    ) | 1;
130    let initial_seq = tag(ISN_DOMAIN, peer, caller_socket_id, time_bucket, secret)
131        & crate::packet::SEQ_NUMBER_MASK;
132    (socket_id, initial_seq)
133}
134
135#[cfg(test)]
136mod tests {
137    use super::*;
138
139    const SECRET: u128 = 0x0123_4567_89AB_CDEF_FEDC_BA98_7654_3210;
140    const BUCKET: u32 = 29_000_000;
141
142    fn addr(s: &str) -> SocketAddr {
143        s.parse().unwrap()
144    }
145
146    #[test]
147    fn a_cookie_is_refused_from_another_address_port_or_socket_id() {
148        let a = addr("198.51.100.1:4000");
149        let cookie = derive_cookie(&a, 7, BUCKET, SECRET);
150        let ok = |p: &SocketAddr, id| validate_cookie(p, id, cookie, BUCKET, [SECRET]).is_some();
151        assert!(ok(&a, 7));
152        assert!(!ok(&addr("198.51.100.2:4000"), 7));
153        assert!(!ok(&addr("198.51.100.1:4001"), 7));
154        assert!(!ok(&a, 8));
155        assert!(!ok(&addr("[::ffff:198.51.100.1]:4000"), 7));
156    }
157
158    #[test]
159    fn a_cookie_older_than_two_buckets_is_refused_and_one_rolls_over() {
160        let a = addr("198.51.100.1:4000");
161        let cookie = derive_cookie(&a, 7, BUCKET, SECRET);
162        let at = |now| validate_cookie(&a, 7, cookie, now, [SECRET]);
163        assert!(at(BUCKET).is_some());
164        assert_eq!(at(BUCKET + 1).map(|o| o.time_bucket), Some(BUCKET));
165        assert!(at(BUCKET + 2).is_none());
166        assert!(at(BUCKET - 1).is_none());
167    }
168
169    #[test]
170    fn a_cookie_under_another_secret_is_refused() {
171        let a = addr("198.51.100.1:4000");
172        let cookie = derive_cookie(&a, 7, BUCKET, SECRET);
173        assert!(validate_cookie(&a, 7, cookie, BUCKET, [SECRET ^ 1]).is_none());
174        assert_eq!(
175            validate_cookie(&a, 7, cookie, BUCKET, [SECRET ^ 1, SECRET]).map(|o| o.secret),
176            Some(SECRET)
177        );
178    }
179
180    /// The old peer key folded the address hash with the Socket ID by XOR, so two sources
181    /// could be made to share a cookie by choosing Socket IDs; no such pair collides now.
182    #[test]
183    fn distinct_sources_never_share_a_cookie_by_choice_of_socket_id() {
184        let a = addr("198.51.100.1:4000");
185        let b = addr("198.51.100.1:4001");
186        let wanted = derive_cookie(&a, 0, BUCKET, SECRET);
187        let collides = (0..=u16::MAX)
188            .map(u32::from)
189            .any(|id| derive_cookie(&b, id, BUCKET, SECRET) == wanted);
190        assert!(!collides);
191    }
192
193    #[test]
194    fn identifiers_are_stable_in_range_and_not_the_cookie() {
195        let a = addr("198.51.100.1:4000");
196        let first = derive_listener_ids(&a, 7, BUCKET, SECRET);
197        assert_eq!(first, derive_listener_ids(&a, 7, BUCKET, SECRET));
198        assert_ne!(first.0, 0);
199        assert!(first.1 <= crate::packet::SEQ_NUMBER_MASK);
200        assert_ne!(first.0, derive_cookie(&a, 7, BUCKET, SECRET));
201        assert_ne!(first, derive_listener_ids(&a, 7, BUCKET + 1, SECRET));
202        assert_ne!(first, derive_listener_ids(&a, 7, BUCKET, SECRET ^ 1));
203    }
204
205    /// Pinned against an independent HMAC-SHA-256 (Python `hmac`): fixes the message layout
206    /// and the key placement.
207    #[test]
208    fn the_cookie_matches_an_independent_hmac() {
209        let a = addr("198.51.100.1:4000");
210        assert_eq!(derive_cookie(&a, 7, BUCKET, SECRET), 0x131f_6c61);
211    }
212
213    #[test]
214    fn both_halves_of_the_secret_feed_the_cookie_and_the_identifiers() {
215        let a = addr("198.51.100.1:4000");
216        let high = SECRET ^ (1u128 << 100);
217        let low = SECRET ^ 1;
218        for other in [high, low] {
219            assert_ne!(
220                derive_cookie(&a, 7, BUCKET, SECRET),
221                derive_cookie(&a, 7, BUCKET, other)
222            );
223            assert_ne!(
224                derive_listener_ids(&a, 7, BUCKET, SECRET),
225                derive_listener_ids(&a, 7, BUCKET, other)
226            );
227        }
228    }
229
230    #[test]
231    fn the_cookie_is_never_zero() {
232        let a = addr("198.51.100.1:4000");
233        assert!((0..1000).all(|id| derive_cookie(&a, id, BUCKET, SECRET) != 0));
234    }
235}