Skip to main content

qualia_core_db/net/qdnf/link/
challenge.rs

1//! Discovery/reachability challenges bound to scope, peer, and observed locator.
2//!
3//! A challenge is not membership, application admission, or a handshake share.
4//! Pending challenges occupy a fixed table; hostile beacons cannot grow it.
5
6use crate::crypto::network::kdf::hmac_sha384;
7use crate::net::qdnf::errors::QdnfError;
8use crate::net::qdnf::types::{LinkId, ObservedLocator, ScopeEpoch};
9
10use super::adjacency::Adjacency;
11use super::budget::PreAuthBudget;
12use super::discovery::Beacon;
13use super::neighbor::NeighborTable;
14
15pub const CHALLENGE_TAG_LEN: usize = 16;
16pub const MAX_PENDING_CHALLENGES: usize = 32;
17
18#[repr(C)]
19#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20pub struct DiscoveryChallenge {
21    pub scope: ScopeEpoch,
22    pub peer: LinkId,
23    pub locator: ObservedLocator,
24    pub expiry_unix: u64,
25    pub nonce: [u8; 16],
26    pub tag: [u8; CHALLENGE_TAG_LEN],
27}
28
29pub struct ChallengeTable {
30    slots: [Option<DiscoveryChallenge>; MAX_PENDING_CHALLENGES],
31}
32
33impl ChallengeTable {
34    /// Creates a default `ChallengeTable`.
35    pub const fn new() -> Self {
36        Self {
37            slots: [None; MAX_PENDING_CHALLENGES],
38        }
39    }
40
41    /// Issue a challenge HMAC-bound to `(scope, peer, locator)`.
42    pub fn issue(
43        &mut self,
44        scope: ScopeEpoch,
45        peer: LinkId,
46        locator: ObservedLocator,
47        now_unix: u64,
48        ttl_secs: u64,
49        secret: &[u8],
50    ) -> Result<DiscoveryChallenge, QdnfError> {
51        let expiry_unix = now_unix.checked_add(ttl_secs).ok_or(QdnfError::Range)?;
52        let slot = self.free_slot(now_unix).ok_or(QdnfError::Capacity)?;
53        let mut nonce = [0u8; 16];
54        nonce[..8].copy_from_slice(&now_unix.to_be_bytes());
55        nonce[8..12].copy_from_slice(&(slot as u32).to_be_bytes());
56        nonce[12..16].copy_from_slice(&(expiry_unix as u32).to_be_bytes());
57        let tag = mint_challenge(scope, peer, &locator, expiry_unix, &nonce, secret)?;
58        let challenge = DiscoveryChallenge {
59            scope,
60            peer,
61            locator,
62            expiry_unix,
63            nonce,
64            tag,
65        };
66        self.slots[slot] = Some(challenge);
67        Ok(challenge)
68    }
69
70    /// Verifies integrity; fails closed on mismatch.
71    pub fn verify(
72        &self,
73        tag: &[u8; CHALLENGE_TAG_LEN],
74        scope: ScopeEpoch,
75        peer: LinkId,
76        locator: &ObservedLocator,
77        now_unix: u64,
78    ) -> Result<(), QdnfError> {
79        let stored = match self.find(tag) {
80            Some(c) => c,
81            None => return Err(QdnfError::Unauthorized),
82        };
83        stored.binds(scope, peer, locator, now_unix)
84    }
85
86    fn find(&self, tag: &[u8; CHALLENGE_TAG_LEN]) -> Option<&DiscoveryChallenge> {
87        self.slots.iter().flatten().find(|c| tag_eq(&c.tag, tag))
88    }
89
90    fn free_slot(&self, now_unix: u64) -> Option<usize> {
91        let mut expired = None;
92        let mut i = 0usize;
93        while i < MAX_PENDING_CHALLENGES {
94            match self.slots[i] {
95                None => return Some(i),
96                Some(c) if now_unix >= c.expiry_unix => {
97                    if expired.is_none() {
98                        expired = Some(i);
99                    }
100                }
101                Some(_) => {}
102            }
103            i += 1;
104        }
105        expired
106    }
107}
108
109impl Default for ChallengeTable {
110    fn default() -> Self {
111        Self::new()
112    }
113}
114
115impl DiscoveryChallenge {
116    /// Binding check: scope, peer, observed locator, and expiry.
117    pub fn binds(
118        &self,
119        scope: ScopeEpoch,
120        peer: LinkId,
121        locator: &ObservedLocator,
122        now_unix: u64,
123    ) -> Result<(), QdnfError> {
124        if now_unix >= self.expiry_unix {
125            return Err(QdnfError::Expired);
126        }
127        if self.scope != scope || self.peer != peer || self.locator != *locator {
128            return Err(QdnfError::Unauthorized);
129        }
130        Ok(())
131    }
132}
133
134/// Charge the pre-auth budget, then reject an expired beacon. No neighbor slot.
135pub fn accept_beacon(
136    beacon: &Beacon,
137    now_unix: u64,
138    budget: &mut PreAuthBudget,
139) -> Result<(), QdnfError> {
140    budget.charge(Beacon::WIRE_LEN as u64, 1)?;
141    beacon.accept(now_unix)
142}
143
144/// Insert adjacency only after the challenge binds the observed neighbor.
145pub fn insert_after_challenge(
146    table: &mut NeighborTable,
147    adj: Adjacency,
148    challenge: &DiscoveryChallenge,
149    scope: ScopeEpoch,
150    now_unix: u64,
151) -> Result<usize, QdnfError> {
152    challenge.binds(scope, adj.remote, &adj.observed_peer, now_unix)?;
153    table.insert(adj)
154}
155
156fn mint_challenge(
157    scope: ScopeEpoch,
158    peer: LinkId,
159    locator: &ObservedLocator,
160    expiry_unix: u64,
161    nonce: &[u8; 16],
162    secret: &[u8],
163) -> Result<[u8; CHALLENGE_TAG_LEN], QdnfError> {
164    let loc = locator.as_slice();
165    let mut info = [0u8; 96];
166    let label = b"qdnf-chal-v1";
167    let mut off = label.len();
168    info[..off].copy_from_slice(label);
169    info[off..off + 8].copy_from_slice(&scope.scope.to_be_bytes());
170    off += 8;
171    info[off..off + 8].copy_from_slice(&scope.epoch.to_be_bytes());
172    off += 8;
173    info[off..off + 16].copy_from_slice(&peer.0);
174    off += 16;
175    info[off] = locator.len;
176    off += 1;
177    info[off..off + loc.len()].copy_from_slice(loc);
178    off += loc.len();
179    info[off..off + 8].copy_from_slice(&expiry_unix.to_be_bytes());
180    off += 8;
181    info[off..off + 16].copy_from_slice(nonce);
182    off += 16;
183    let mut mac = [0u8; 48];
184    hmac_sha384(secret, &info[..off], &mut mac).map_err(|_| QdnfError::CryptoFailure)?;
185    let mut out = [0u8; CHALLENGE_TAG_LEN];
186    out.copy_from_slice(&mac[..CHALLENGE_TAG_LEN]);
187    Ok(out)
188}
189
190fn tag_eq(a: &[u8; CHALLENGE_TAG_LEN], b: &[u8; CHALLENGE_TAG_LEN]) -> bool {
191    let mut diff = 0u8;
192    let mut i = 0usize;
193    while i < CHALLENGE_TAG_LEN {
194        diff |= a[i] ^ b[i];
195        i += 1;
196    }
197    diff == 0
198}
199
200#[cfg(test)]
201mod tests {
202    use super::*;
203    use crate::net::qdnf::link::adjacency::AdjacencyState;
204    use crate::net::qdnf::link::discovery::DiscoveryMode;
205    use crate::net::qdnf::link::neighbor::MAX_NEIGHBORS;
206
207    const SECRET: &[u8] = b"qdnf-discovery-challenge-secret";
208
209    fn loc(byte: u8) -> ObservedLocator {
210        ObservedLocator::from_slice(&[byte]).unwrap()
211    }
212
213    fn scope() -> ScopeEpoch {
214        ScopeEpoch { scope: 7, epoch: 3 }
215    }
216
217    fn peer(b: u8) -> LinkId {
218        let mut id = LinkId::ZERO;
219        id.0[0] = b;
220        id
221    }
222
223    #[test]
224    fn challenge_binds_scope_peer_locator() {
225        let mut table = ChallengeTable::new();
226        let challenge = table
227            .issue(scope(), peer(1), loc(2), 1_000, 30, SECRET)
228            .unwrap();
229        assert_eq!(
230            table.verify(&challenge.tag, scope(), peer(1), &loc(2), 1_000),
231            Ok(())
232        );
233        assert_eq!(
234            table.verify(&challenge.tag, scope(), peer(9), &loc(2), 1_000),
235            Err(QdnfError::Unauthorized)
236        );
237        assert_eq!(
238            table.verify(&challenge.tag, scope(), peer(1), &loc(9), 1_000),
239            Err(QdnfError::Unauthorized)
240        );
241        let other_scope = ScopeEpoch { scope: 8, epoch: 3 };
242        assert_eq!(
243            table.verify(&challenge.tag, other_scope, peer(1), &loc(2), 1_000),
244            Err(QdnfError::Unauthorized)
245        );
246    }
247
248    #[test]
249    fn expired_beacon_is_expired() {
250        let beacon = Beacon {
251            mode: DiscoveryMode::PrivatePairwise,
252            tag: [1u8; 16],
253            link_id: peer(1),
254            epoch: 1,
255            expiry_unix: 10,
256            mtu: 1280,
257        };
258        let mut budget = PreAuthBudget::new();
259        assert_eq!(
260            accept_beacon(&beacon, 10, &mut budget),
261            Err(QdnfError::Expired)
262        );
263        assert_eq!(budget.used_bytes(), Beacon::WIRE_LEN as u64);
264    }
265
266    #[test]
267    fn expired_challenge_is_expired() {
268        let mut table = ChallengeTable::new();
269        let challenge = table
270            .issue(scope(), peer(1), loc(2), 1_000, 10, SECRET)
271            .unwrap();
272        assert_eq!(
273            table.verify(
274                &challenge.tag,
275                scope(),
276                peer(1),
277                &loc(2),
278                challenge.expiry_unix
279            ),
280            Err(QdnfError::Expired)
281        );
282    }
283
284    #[test]
285    fn thirty_third_challenge_is_capacity() {
286        let mut table = ChallengeTable::new();
287        for i in 0..MAX_PENDING_CHALLENGES {
288            table
289                .issue(
290                    scope(),
291                    peer(i as u8 + 1),
292                    loc(i as u8 + 1),
293                    1_000,
294                    30,
295                    SECRET,
296                )
297                .unwrap();
298        }
299        assert_eq!(
300            table.issue(scope(), peer(0xFF), loc(0xFF), 1_000, 30, SECRET),
301            Err(QdnfError::Capacity)
302        );
303    }
304
305    #[test]
306    fn neighbor_insert_requires_matching_challenge() {
307        let mut neighbors = NeighborTable::new();
308        let mut challenges = ChallengeTable::new();
309        let locator = loc(4);
310        let remote = peer(4);
311        let challenge = challenges
312            .issue(scope(), remote, locator, 1_000, 30, SECRET)
313            .unwrap();
314        let adj = Adjacency {
315            local: peer(0),
316            remote,
317            observed_peer: locator,
318            state: AdjacencyState::ChallengeReceived,
319            generation: 1,
320            mtu: 1280,
321        };
322        assert_eq!(
323            insert_after_challenge(&mut neighbors, adj, &challenge, scope(), 1_000),
324            Ok(0)
325        );
326        let wrong = Adjacency {
327            observed_peer: loc(9),
328            ..adj
329        };
330        assert_eq!(
331            insert_after_challenge(&mut neighbors, wrong, &challenge, scope(), 1_000),
332            Err(QdnfError::Unauthorized)
333        );
334        assert_eq!(neighbors.len(), 1);
335    }
336
337    #[test]
338    fn challenged_insert_still_caps_neighbor_table() {
339        let mut neighbors = NeighborTable::new();
340        let mut challenges = ChallengeTable::new();
341        for i in 0..MAX_NEIGHBORS {
342            let remote = peer(i as u8 + 1);
343            let locator = loc(i as u8 + 1);
344            let challenge = challenges
345                .issue(scope(), remote, locator, 1_000, 30, SECRET)
346                .unwrap();
347            insert_after_challenge(
348                &mut neighbors,
349                Adjacency {
350                    local: peer(0),
351                    remote,
352                    observed_peer: locator,
353                    state: AdjacencyState::Adjacent,
354                    generation: 1,
355                    mtu: 1280,
356                },
357                &challenge,
358                scope(),
359                1_000,
360            )
361            .unwrap();
362        }
363        let extra = peer(0xFE);
364        let extra_loc = loc(0xFE);
365        let mut extra_challenges = ChallengeTable::new();
366        let challenge = extra_challenges
367            .issue(scope(), extra, extra_loc, 1_000, 30, SECRET)
368            .unwrap();
369        assert_eq!(
370            insert_after_challenge(
371                &mut neighbors,
372                Adjacency {
373                    local: peer(0),
374                    remote: extra,
375                    observed_peer: extra_loc,
376                    state: AdjacencyState::Adjacent,
377                    generation: 1,
378                    mtu: 1280,
379                },
380                &challenge,
381                scope(),
382                1_000,
383            ),
384            Err(QdnfError::Capacity)
385        );
386        assert_eq!(neighbors.len(), MAX_NEIGHBORS);
387    }
388}