Skip to main content

qualia_core_db/net/qdnf/session/
packet_protection.rs

1//! Packet protection: directional keys, AEAD, packet numbers and replay (E02.3).
2//!
3//! Authenticate before updating the receive window or exposing plaintext.
4//! `install_update` retains the immediately previous generation (keys +
5//! packet space) so in-flight packets can open during overlap (E02.4 / E09.6).
6
7use crate::crypto::network::aead::{decrypt_in_place, encrypt_in_place};
8use crate::crypto::network::types::{AEAD_KEY_LEN, AEAD_TAG_LEN};
9use crate::net::qdnf::errors::QdnfError;
10use crate::net::qdnf::session::packet::{
11    nonce_from_packet_number, PacketNumber, PacketSpace, AEAD_NONCE_LEN,
12};
13use crate::net::qdnf::types::Generation;
14use zeroize::{Zeroize, Zeroizing};
15
16pub const PN_LEN: usize = 8;
17pub const OVERHEAD: usize = PN_LEN + AEAD_TAG_LEN;
18/// Bounded stack scratch for `open`. Caller still supplies `out`.
19pub const MAX_PROTECTED_BODY: usize = 4096;
20
21struct KeySpace {
22    send_key: [u8; AEAD_KEY_LEN],
23    recv_key: [u8; AEAD_KEY_LEN],
24    space: PacketSpace,
25    generation: Generation,
26}
27
28impl KeySpace {
29    fn empty() -> Self {
30        Self {
31            send_key: [0u8; AEAD_KEY_LEN],
32            recv_key: [0u8; AEAD_KEY_LEN],
33            space: PacketSpace::new(),
34            generation: Generation::ZERO,
35        }
36    }
37
38    fn occupied(&self) -> bool {
39        self.generation != Generation::ZERO
40    }
41
42    fn erase(&mut self) {
43        self.send_key.zeroize();
44        self.recv_key.zeroize();
45        self.space = PacketSpace::new();
46        self.generation = Generation::ZERO;
47    }
48}
49
50pub struct PacketProtection {
51    current: KeySpace,
52    previous: KeySpace,
53}
54
55impl PacketProtection {
56    /// Builds `PacketProtection` from `keys`.
57    pub fn from_keys(
58        send_key: [u8; AEAD_KEY_LEN],
59        recv_key: [u8; AEAD_KEY_LEN],
60        generation: Generation,
61    ) -> Result<Self, QdnfError> {
62        reject_key_pair(&send_key, &recv_key)?;
63        if generation == Generation::ZERO {
64            return Err(QdnfError::Unauthorized);
65        }
66        Ok(Self {
67            current: KeySpace {
68                send_key,
69                recv_key,
70                space: PacketSpace::new(),
71                generation,
72            },
73            previous: KeySpace::empty(),
74        })
75    }
76
77    #[inline]
78    /// Generation.
79    pub const fn generation(&self) -> Generation {
80        self.current.generation
81    }
82
83    /// Encrypt `plaintext` in place. `out` receives pn || ciphertext || tag.
84    pub fn seal(
85        &mut self,
86        aad: &[u8],
87        plaintext: &mut [u8],
88        out: &mut [u8],
89    ) -> Result<usize, QdnfError> {
90        if plaintext.len() > MAX_PROTECTED_BODY {
91            return Err(QdnfError::Capacity);
92        }
93        let need = plaintext
94            .len()
95            .checked_add(OVERHEAD)
96            .ok_or(QdnfError::Range)?;
97        if out.len() < need {
98            return Err(QdnfError::Capacity);
99        }
100        let pn = self.current.space.allocate_send()?;
101        let mut nonce = [0u8; AEAD_NONCE_LEN];
102        nonce_from_packet_number(pn, &mut nonce);
103        let mut tag = [0u8; AEAD_TAG_LEN];
104        encrypt_in_place(&self.current.send_key, &nonce, aad, plaintext, &mut tag)?;
105        out[..PN_LEN].copy_from_slice(&pn.0.to_be_bytes());
106        out[PN_LEN..PN_LEN + plaintext.len()].copy_from_slice(plaintext);
107        let tag_off = PN_LEN + plaintext.len();
108        out[tag_off..tag_off + AEAD_TAG_LEN].copy_from_slice(&tag);
109        Ok(need)
110    }
111
112    /// Encrypt `plaintext` in place with transmission pacing and idle-watch validation.
113    pub fn seal_paced(
114        &mut self,
115        aad: &[u8],
116        plaintext: &mut [u8],
117        out: &mut [u8],
118        pacer: &mut crate::net::qdnf::session::pacing::Pacer,
119        idle: &mut crate::net::qdnf::session::pacing::IdleWatch,
120        now_us: u64,
121    ) -> Result<usize, QdnfError> {
122        idle.on_send(now_us)?;
123        let need = plaintext
124            .len()
125            .checked_add(OVERHEAD)
126            .ok_or(QdnfError::Range)?;
127        crate::net::qdnf::session::pacing::on_paced_send(pacer, need as u64, now_us)?;
128        self.seal(aad, plaintext, out)
129    }
130
131    /// Decrypt into `out`. Replay/window updates happen only after AEAD success.
132    /// Tries current recv key first; on AEAD failure only, tries previous.
133    pub fn open(&mut self, aad: &[u8], sealed: &[u8], out: &mut [u8]) -> Result<usize, QdnfError> {
134        if sealed.len() < OVERHEAD {
135            return Err(QdnfError::Truncated);
136        }
137        let body_len = sealed.len() - OVERHEAD;
138        if body_len > MAX_PROTECTED_BODY {
139            return Err(QdnfError::Capacity);
140        }
141        if out.len() < body_len {
142            return Err(QdnfError::Capacity);
143        }
144        let pn_bytes: [u8; 8] = sealed[..PN_LEN].try_into().map_err(|_| QdnfError::Range)?;
145        let pn = PacketNumber(u64::from_be_bytes(pn_bytes));
146        let mut body = Zeroizing::new([0u8; MAX_PROTECTED_BODY]);
147        body[..body_len].copy_from_slice(&sealed[PN_LEN..PN_LEN + body_len]);
148        let mut tag = [0u8; AEAD_TAG_LEN];
149        tag.copy_from_slice(&sealed[PN_LEN + body_len..]);
150        match open_one(
151            &self.current.recv_key,
152            &mut self.current.space,
153            aad,
154            pn,
155            &mut body[..body_len],
156            &tag,
157            out,
158        ) {
159            Ok(n) => Ok(n),
160            Err(QdnfError::CryptoFailure) if self.previous.occupied() => {
161                body[..body_len].copy_from_slice(&sealed[PN_LEN..PN_LEN + body_len]);
162                open_one(
163                    &self.previous.recv_key,
164                    &mut self.previous.space,
165                    aad,
166                    pn,
167                    &mut body[..body_len],
168                    &tag,
169                    out,
170                )
171            }
172            Err(e) => Err(e),
173        }
174    }
175
176    /// Move current keys+space into previous (erasing any older previous) and
177    /// install new keys with a fresh packet-number space. Generations must
178    /// strictly increase. Nonce reuse is forbidden: spaces are not shared.
179    pub fn install_update(
180        &mut self,
181        send_key: [u8; AEAD_KEY_LEN],
182        recv_key: [u8; AEAD_KEY_LEN],
183        generation: Generation,
184    ) -> Result<(), QdnfError> {
185        reject_key_pair(&send_key, &recv_key)?;
186        if generation == Generation::ZERO || generation.0 <= self.current.generation.0 {
187            return Err(QdnfError::StaleGeneration);
188        }
189        self.previous.erase();
190        self.previous.send_key = self.current.send_key;
191        self.previous.recv_key = self.current.recv_key;
192        self.previous.space = self.current.space;
193        self.previous.generation = self.current.generation;
194        self.current.send_key = send_key;
195        self.current.recv_key = recv_key;
196        self.current.space = PacketSpace::new();
197        self.current.generation = generation;
198        Ok(())
199    }
200}
201
202fn reject_key_pair(
203    send_key: &[u8; AEAD_KEY_LEN],
204    recv_key: &[u8; AEAD_KEY_LEN],
205) -> Result<(), QdnfError> {
206    if *send_key == [0u8; AEAD_KEY_LEN] || *recv_key == [0u8; AEAD_KEY_LEN] || send_key == recv_key
207    {
208        return Err(QdnfError::CryptoFailure);
209    }
210    Ok(())
211}
212
213fn open_one(
214    recv_key: &[u8; AEAD_KEY_LEN],
215    space: &mut PacketSpace,
216    aad: &[u8],
217    pn: PacketNumber,
218    body: &mut [u8],
219    tag: &[u8; AEAD_TAG_LEN],
220    out: &mut [u8],
221) -> Result<usize, QdnfError> {
222    let mut nonce = [0u8; AEAD_NONCE_LEN];
223    nonce_from_packet_number(pn, &mut nonce);
224    decrypt_in_place(recv_key, &nonce, aad, body, tag)?;
225    space.accept_receive(pn)?;
226    out[..body.len()].copy_from_slice(body);
227    Ok(body.len())
228}
229
230impl Drop for PacketProtection {
231    fn drop(&mut self) {
232        self.current.erase();
233        self.previous.erase();
234    }
235}
236
237#[cfg(test)]
238mod tests {
239    use super::*;
240    use crate::net::qdnf::session::rekey::MAX_OLD_KEYS;
241
242    fn pair() -> (PacketProtection, PacketProtection) {
243        let a = PacketProtection::from_keys([1u8; 32], [2u8; 32], Generation(1)).unwrap();
244        let b = PacketProtection::from_keys([2u8; 32], [1u8; 32], Generation(1)).unwrap();
245        (a, b)
246    }
247
248    fn pn_of(sealed: &[u8]) -> u64 {
249        u64::from_be_bytes(sealed[..PN_LEN].try_into().unwrap())
250    }
251
252    #[test]
253    fn round_trip_hides_plaintext() {
254        let (mut a, mut b) = pair();
255        let app = b"hello-qpr";
256        let mut pt = *app;
257        let mut sealed = [0u8; 64];
258        let n = a.seal(b"aad", &mut pt, &mut sealed).unwrap();
259        assert_ne!(&sealed[PN_LEN..PN_LEN + app.len()], app.as_slice());
260        let mut out = [0u8; 16];
261        let got = b.open(b"aad", &sealed[..n], &mut out).unwrap();
262        assert_eq!(&out[..got], app);
263    }
264
265    #[test]
266    fn tamper_does_not_advance_replay_or_plaintext() {
267        let (mut a, mut b) = pair();
268        let mut pt = *b"hello-qpr";
269        let mut sealed = [0u8; 64];
270        let n = a.seal(b"aad", &mut pt, &mut sealed).unwrap();
271        sealed[PN_LEN] ^= 0xff;
272        let mut out = [0u8; 16];
273        assert!(b.open(b"aad", &sealed[..n], &mut out).is_err());
274        assert_ne!(&out[..9], b"hello-qpr");
275        sealed[PN_LEN] ^= 0xff;
276        let got = b.open(b"aad", &sealed[..n], &mut out).unwrap();
277        assert_eq!(&out[..got], b"hello-qpr");
278    }
279
280    #[test]
281    fn replay_is_rejected() {
282        let (mut a, mut b) = pair();
283        let mut pt = *b"hello-qpr";
284        let mut sealed = [0u8; 64];
285        let n = a.seal(b"aad", &mut pt, &mut sealed).unwrap();
286        let mut out = [0u8; 16];
287        assert!(b.open(b"aad", &sealed[..n], &mut out).is_ok());
288        assert_eq!(
289            b.open(b"aad", &sealed[..n], &mut out),
290            Err(QdnfError::Replay)
291        );
292    }
293
294    #[test]
295    fn wrong_aad_yields_no_plaintext() {
296        let (mut a, mut b) = pair();
297        let mut pt = *b"hello-qpr";
298        let mut sealed = [0u8; 64];
299        let n = a.seal(b"aad-1", &mut pt, &mut sealed).unwrap();
300        let mut out = [0u8; 16];
301        assert!(b.open(b"aad-2", &sealed[..n], &mut out).is_err());
302    }
303
304    #[test]
305    fn install_update_uses_new_keys_and_fresh_packet_space() {
306        let (mut a, mut b) = pair();
307        let mut pt = *b"hello-qpr";
308        let mut sealed_old = [0u8; 64];
309        let n_old = a.seal(b"aad", &mut pt, &mut sealed_old).unwrap();
310        a.install_update([3u8; 32], [4u8; 32], Generation(2))
311            .unwrap();
312        b.install_update([4u8; 32], [3u8; 32], Generation(2))
313            .unwrap();
314        let mut out = [0u8; 16];
315        let got_old = b.open(b"aad", &sealed_old[..n_old], &mut out).unwrap();
316        assert_eq!(&out[..got_old], b"hello-qpr");
317        let mut pt2 = *b"hello-qpr";
318        let mut sealed = [0u8; 64];
319        let n2 = a.seal(b"aad", &mut pt2, &mut sealed).unwrap();
320        assert_eq!(&sealed[..PN_LEN], &[0, 0, 0, 0, 0, 0, 0, 0]);
321        let got = b.open(b"aad", &sealed[..n2], &mut out).unwrap();
322        assert_eq!(&out[..got], b"hello-qpr");
323        assert_eq!(a.generation(), Generation(2));
324        assert_eq!(
325            a.install_update([5u8; 32], [6u8; 32], Generation(2)),
326            Err(QdnfError::StaleGeneration)
327        );
328    }
329
330    #[test]
331    fn open_rejects_body_over_max_protected_body() {
332        let (_a, mut b) = pair();
333        let sealed = [0u8; MAX_PROTECTED_BODY + OVERHEAD + 1];
334        let mut out = [0u8; MAX_PROTECTED_BODY + 1];
335        assert_eq!(b.open(b"aad", &sealed, &mut out), Err(QdnfError::Capacity));
336    }
337
338    #[test]
339    fn round_trip_4096_body() {
340        let (mut a, mut b) = pair();
341        let mut original = [0u8; MAX_PROTECTED_BODY];
342        let mut i = 0usize;
343        while i < MAX_PROTECTED_BODY {
344            original[i] = (i % 251) as u8;
345            i += 1;
346        }
347        let mut pt = original;
348        let mut sealed = [0u8; MAX_PROTECTED_BODY + OVERHEAD];
349        let n = a.seal(b"aad", &mut pt, &mut sealed).unwrap();
350        assert_eq!(n, MAX_PROTECTED_BODY + OVERHEAD);
351        assert_ne!(
352            &sealed[PN_LEN..PN_LEN + MAX_PROTECTED_BODY],
353            original.as_slice()
354        );
355        let mut out = [0u8; MAX_PROTECTED_BODY];
356        let got = b.open(b"aad", &sealed[..n], &mut out).unwrap();
357        assert_eq!(got, MAX_PROTECTED_BODY);
358        assert_eq!(&out[..got], original.as_slice());
359    }
360
361    #[test]
362    fn previous_generation_in_flight_opens_during_overlap() {
363        let (mut a, mut b) = pair();
364        let mut pt = *b"hello-qpr";
365        let mut sealed_old = [0u8; 64];
366        let n_old = a.seal(b"aad", &mut pt, &mut sealed_old).unwrap();
367        a.install_update([3u8; 32], [4u8; 32], Generation(2))
368            .unwrap();
369        b.install_update([4u8; 32], [3u8; 32], Generation(2))
370            .unwrap();
371        let mut out = [0u8; 16];
372        let got = b.open(b"aad", &sealed_old[..n_old], &mut out).unwrap();
373        assert_eq!(&out[..got], b"hello-qpr");
374        let mut gen = 2u64;
375        let mut k = 5u8;
376        while gen < 2 + MAX_OLD_KEYS as u64 {
377            gen += 1;
378            a.install_update([k; 32], [k.wrapping_add(1); 32], Generation(gen))
379                .unwrap();
380            b.install_update([k.wrapping_add(1); 32], [k; 32], Generation(gen))
381                .unwrap();
382            k = k.wrapping_add(2);
383        }
384        assert_eq!(
385            b.open(b"aad", &sealed_old[..n_old], &mut out),
386            Err(QdnfError::CryptoFailure)
387        );
388    }
389
390    #[test]
391    fn install_update_starts_new_pn_space() {
392        let (mut a, mut b) = pair();
393        let mut first = *b"hello-qpr";
394        let mut sealed1 = [0u8; 64];
395        let n1 = a.seal(b"aad", &mut first, &mut sealed1).unwrap();
396        let pn_gen1 = pn_of(&sealed1);
397        assert_eq!(pn_gen1, 0);
398        a.install_update([3u8; 32], [4u8; 32], Generation(2))
399            .unwrap();
400        b.install_update([4u8; 32], [3u8; 32], Generation(2))
401            .unwrap();
402        let mut second = *b"hello-qpr";
403        let mut sealed2 = [0u8; 64];
404        let n2 = a.seal(b"aad", &mut second, &mut sealed2).unwrap();
405        assert_eq!(pn_of(&sealed2), pn_gen1);
406        assert_ne!(&sealed1[..n1], &sealed2[..n2]);
407        let mut out = [0u8; 16];
408        let got2 = b.open(b"aad", &sealed2[..n2], &mut out).unwrap();
409        assert_eq!(&out[..got2], b"hello-qpr");
410        let got1 = b.open(b"aad", &sealed1[..n1], &mut out).unwrap();
411        assert_eq!(&out[..got1], b"hello-qpr");
412    }
413}