Skip to main content

qualia_core_db/net/qdnf/link/
cookies.rs

1//! Reachability cookies for QLink anti-amplification.
2//!
3//! A cookie proves **reachability of an observed locator only**. It is not a
4//! handshake share, not a membership grant, and not application admission.
5
6use crate::crypto::network::kdf::hmac_sha384;
7use crate::net::qdnf::errors::QdnfError;
8use crate::net::qdnf::types::{LinkId, ObservedLocator, ScopeEpoch};
9
10pub const COOKIE_LEN: usize = 16;
11pub const MAX_PENDING: usize = 32;
12pub const MAX_PER_LOCATOR: usize = 2;
13/// Replies per cookie before [`QdnfError::Denied`].
14pub const REPLY_CAP: u8 = 3;
15
16#[repr(C)]
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18pub struct ReachabilityCookie {
19    pub bytes: [u8; COOKIE_LEN],
20    pub locator: ObservedLocator,
21    pub scope: ScopeEpoch,
22    pub peer: LinkId,
23    pub expiry_unix: u64,
24    replies: u8,
25}
26
27pub struct CookieJar {
28    slots: [Option<ReachabilityCookie>; MAX_PENDING],
29}
30
31impl CookieJar {
32    /// Creates a default `CookieJar`.
33    pub const fn new() -> Self {
34        Self {
35            slots: [None; MAX_PENDING],
36        }
37    }
38
39    /// Issue a 16-byte HMAC cookie bound to `locator`. Does not open a session.
40    pub fn issue(
41        &mut self,
42        locator: ObservedLocator,
43        now_unix: u64,
44        ttl_secs: u64,
45        secret: &[u8],
46    ) -> Result<ReachabilityCookie, QdnfError> {
47        let expiry_unix = now_unix.checked_add(ttl_secs).ok_or(QdnfError::Range)?;
48        if self.live_for_locator(&locator, now_unix) >= MAX_PER_LOCATOR {
49            return Err(QdnfError::Capacity);
50        }
51        let slot = self.free_slot(now_unix).ok_or(QdnfError::Capacity)?;
52        let bytes = mint_cookie(
53            &locator,
54            ScopeEpoch { scope: 0, epoch: 0 },
55            LinkId::ZERO,
56            expiry_unix,
57            secret,
58        )?;
59        let cookie = ReachabilityCookie {
60            bytes,
61            locator,
62            scope: ScopeEpoch { scope: 0, epoch: 0 },
63            peer: LinkId::ZERO,
64            expiry_unix,
65            replies: 0,
66        };
67        self.slots[slot] = Some(cookie);
68        Ok(cookie)
69    }
70
71    /// Issue a cookie HMAC-bound to scope, peer, and observed locator.
72    pub fn issue_bound(
73        &mut self,
74        locator: ObservedLocator,
75        scope: ScopeEpoch,
76        peer: LinkId,
77        now_unix: u64,
78        ttl_secs: u64,
79        secret: &[u8],
80    ) -> Result<ReachabilityCookie, QdnfError> {
81        let expiry_unix = now_unix.checked_add(ttl_secs).ok_or(QdnfError::Range)?;
82        if self.live_for_locator(&locator, now_unix) >= MAX_PER_LOCATOR {
83            return Err(QdnfError::Capacity);
84        }
85        let slot = self.free_slot(now_unix).ok_or(QdnfError::Capacity)?;
86        let bytes = mint_cookie(&locator, scope, peer, expiry_unix, secret)?;
87        let cookie = ReachabilityCookie {
88            bytes,
89            locator,
90            scope,
91            peer,
92            expiry_unix,
93            replies: 0,
94        };
95        self.slots[slot] = Some(cookie);
96        Ok(cookie)
97    }
98
99    /// Record a reply from the same observed locator. Still not membership.
100    pub fn accept_reply(
101        &mut self,
102        cookie: &[u8; COOKIE_LEN],
103        locator: &ObservedLocator,
104        now_unix: u64,
105    ) -> Result<(), QdnfError> {
106        self.accept_bound_reply(
107            cookie,
108            locator,
109            &ScopeEpoch { scope: 0, epoch: 0 },
110            &LinkId::ZERO,
111            now_unix,
112        )
113    }
114
115    /// Accepts a stateless-retry cookie bound to the connection.
116    pub fn accept_bound_reply(
117        &mut self,
118        cookie: &[u8; COOKIE_LEN],
119        locator: &ObservedLocator,
120        scope: &ScopeEpoch,
121        peer: &LinkId,
122        now_unix: u64,
123    ) -> Result<(), QdnfError> {
124        let stored = match self.find_mut(cookie) {
125            Some(slot) => slot,
126            None => return Err(QdnfError::Unauthorized),
127        };
128        if now_unix >= stored.expiry_unix {
129            return Err(QdnfError::Expired);
130        }
131        if stored.locator != *locator || stored.scope != *scope || stored.peer != *peer {
132            return Err(QdnfError::Unauthorized);
133        }
134        if stored.replies >= REPLY_CAP {
135            return Err(QdnfError::Denied);
136        }
137        stored.replies = stored.replies.saturating_add(1);
138        Ok(())
139    }
140
141    /// `true` when the cookie grants membership.
142    pub fn grants_membership() -> bool {
143        false
144    }
145
146    /// `true` when the cookie grants application access.
147    pub fn grants_application() -> bool {
148        false
149    }
150
151    fn live_for_locator(&self, locator: &ObservedLocator, now_unix: u64) -> usize {
152        let mut n = 0usize;
153        let mut i = 0usize;
154        while i < MAX_PENDING {
155            if let Some(c) = self.slots[i] {
156                if c.locator == *locator && now_unix < c.expiry_unix {
157                    n += 1;
158                }
159            }
160            i += 1;
161        }
162        n
163    }
164
165    fn free_slot(&self, now_unix: u64) -> Option<usize> {
166        let mut expired = None;
167        let mut i = 0usize;
168        while i < MAX_PENDING {
169            match self.slots[i] {
170                None => return Some(i),
171                Some(c) if now_unix >= c.expiry_unix => {
172                    if expired.is_none() {
173                        expired = Some(i);
174                    }
175                }
176                Some(_) => {}
177            }
178            i += 1;
179        }
180        expired
181    }
182
183    fn find_mut(&mut self, cookie: &[u8; COOKIE_LEN]) -> Option<&mut ReachabilityCookie> {
184        self.slots
185            .iter_mut()
186            .find_map(|slot| slot.as_mut().filter(|c| cookie_eq(&c.bytes, cookie)))
187    }
188}
189
190impl Default for CookieJar {
191    fn default() -> Self {
192        Self::new()
193    }
194}
195
196fn mint_cookie(
197    locator: &ObservedLocator,
198    scope: ScopeEpoch,
199    peer: LinkId,
200    expiry_unix: u64,
201    secret: &[u8],
202) -> Result<[u8; COOKIE_LEN], QdnfError> {
203    let loc = locator.as_slice();
204    let mut info = [0u8; 80];
205    let n = loc.len();
206    info[..n].copy_from_slice(loc);
207    let mut off = n;
208    info[off..off + 8].copy_from_slice(&expiry_unix.to_be_bytes());
209    off += 8;
210    info[off..off + 8].copy_from_slice(&scope.scope.to_be_bytes());
211    off += 8;
212    info[off..off + 8].copy_from_slice(&scope.epoch.to_be_bytes());
213    off += 8;
214    info[off..off + 16].copy_from_slice(&peer.0);
215    off += 16;
216    let mut mac = [0u8; 48];
217    hmac_sha384(secret, &info[..off], &mut mac).map_err(|_| QdnfError::CryptoFailure)?;
218    let mut out = [0u8; COOKIE_LEN];
219    out.copy_from_slice(&mac[..COOKIE_LEN]);
220    Ok(out)
221}
222
223fn cookie_eq(a: &[u8; COOKIE_LEN], b: &[u8; COOKIE_LEN]) -> bool {
224    let mut diff = 0u8;
225    let mut i = 0usize;
226    while i < COOKIE_LEN {
227        diff |= a[i] ^ b[i];
228        i += 1;
229    }
230    diff == 0
231}
232
233#[cfg(test)]
234mod tests {
235    use super::*;
236
237    const SECRET: &[u8] = b"qdnf-reachability-cookie-secret";
238
239    fn loc(byte: u8) -> ObservedLocator {
240        ObservedLocator::from_slice(&[byte]).unwrap()
241    }
242
243    #[test]
244    fn issue_then_accept_same_locator() {
245        let mut jar = CookieJar::new();
246        let locator = loc(1);
247        let cookie = jar.issue(locator, 1_000, 30, SECRET).unwrap();
248        assert_eq!(jar.accept_reply(&cookie.bytes, &locator, 1_000), Ok(()));
249    }
250
251    #[test]
252    fn wrong_locator_is_unauthorized() {
253        let mut jar = CookieJar::new();
254        let cookie = jar.issue(loc(1), 1_000, 30, SECRET).unwrap();
255        assert_eq!(
256            jar.accept_reply(&cookie.bytes, &loc(2), 1_000),
257            Err(QdnfError::Unauthorized)
258        );
259    }
260
261    #[test]
262    fn expired_cookie_is_expired() {
263        let mut jar = CookieJar::new();
264        let locator = loc(1);
265        let cookie = jar.issue(locator, 1_000, 10, SECRET).unwrap();
266        assert_eq!(
267            jar.accept_reply(&cookie.bytes, &locator, cookie.expiry_unix),
268            Err(QdnfError::Expired)
269        );
270    }
271
272    #[test]
273    fn fourth_reply_is_denied() {
274        let mut jar = CookieJar::new();
275        let locator = loc(1);
276        let cookie = jar.issue(locator, 1_000, 30, SECRET).unwrap();
277        for _ in 0..REPLY_CAP {
278            assert_eq!(jar.accept_reply(&cookie.bytes, &locator, 1_000), Ok(()));
279        }
280        assert_eq!(
281            jar.accept_reply(&cookie.bytes, &locator, 1_000),
282            Err(QdnfError::Denied)
283        );
284    }
285
286    #[test]
287    fn third_pending_same_locator_is_capacity() {
288        let mut jar = CookieJar::new();
289        let locator = loc(7);
290        jar.issue(locator, 1_000, 30, SECRET).unwrap();
291        jar.issue(locator, 1_000, 31, SECRET).unwrap();
292        assert_eq!(
293            jar.issue(locator, 1_000, 32, SECRET),
294            Err(QdnfError::Capacity)
295        );
296    }
297
298    #[test]
299    fn cookie_does_not_grant_membership_or_application() {
300        assert!(!CookieJar::grants_membership());
301        assert!(!CookieJar::grants_application());
302    }
303
304    #[test]
305    fn thirty_third_distinct_locator_is_capacity() {
306        let mut jar = CookieJar::new();
307        for i in 0..MAX_PENDING {
308            let locator = loc(i as u8 + 1);
309            jar.issue(locator, 1_000, 30, SECRET).unwrap();
310        }
311        assert_eq!(
312            jar.issue(loc(0xFF), 1_000, 30, SECRET),
313            Err(QdnfError::Capacity)
314        );
315    }
316
317    #[test]
318    fn unknown_cookie_is_unauthorized() {
319        let mut jar = CookieJar::new();
320        assert_eq!(
321            jar.accept_reply(&[0u8; COOKIE_LEN], &loc(1), 1_000),
322            Err(QdnfError::Unauthorized)
323        );
324    }
325
326    #[test]
327    fn bound_cookie_rejects_wrong_scope_or_peer() {
328        let mut jar = CookieJar::new();
329        let locator = loc(3);
330        let scope = ScopeEpoch { scope: 1, epoch: 2 };
331        let peer = LinkId([9u8; 16]);
332        let cookie = jar
333            .issue_bound(locator, scope, peer, 1_000, 30, SECRET)
334            .unwrap();
335        assert_eq!(
336            jar.accept_bound_reply(&cookie.bytes, &locator, &scope, &peer, 1_000),
337            Ok(())
338        );
339        let other_scope = ScopeEpoch { scope: 2, epoch: 2 };
340        assert_eq!(
341            jar.accept_bound_reply(&cookie.bytes, &locator, &other_scope, &peer, 1_000),
342            Err(QdnfError::Unauthorized)
343        );
344        let other_peer = LinkId([8u8; 16]);
345        assert_eq!(
346            jar.accept_bound_reply(&cookie.bytes, &locator, &scope, &other_peer, 1_000),
347            Err(QdnfError::Unauthorized)
348        );
349    }
350}