Skip to main content

fips_core/noise/
session.rs

1use super::{CipherState, HandshakeRole, NoiseError, ReplayWindow};
2use ring::aead::LessSafeKey;
3use secp256k1::{PublicKey, XOnlyPublicKey};
4#[cfg(test)]
5use std::ops::Range;
6use std::{
7    fmt,
8    sync::{
9        Arc,
10        atomic::{AtomicU64, Ordering},
11    },
12};
13
14/// Shared send-side counter authority for one Noise transport session.
15///
16/// AEAD keys can be rebuilt for worker threads, but nonce uniqueness must stay
17/// single-owner. This authority is the small clonable object that lets a future
18/// packet mover reserve counters without borrowing the whole `NoiseSession`.
19#[derive(Clone, Debug)]
20pub(crate) struct SendCounterAuthority {
21    next: Arc<AtomicU64>,
22}
23
24impl SendCounterAuthority {
25    fn new(next: u64) -> Self {
26        Self {
27            next: Arc::new(AtomicU64::new(next)),
28        }
29    }
30
31    pub(crate) fn current(&self) -> u64 {
32        self.next.load(Ordering::Relaxed)
33    }
34
35    pub(crate) fn reserve(&self) -> Result<u64, NoiseError> {
36        self.next
37            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |next| {
38                if next == u64::MAX {
39                    None
40                } else {
41                    Some(next + 1)
42                }
43            })
44            .map_err(|_| NoiseError::NonceOverflow)
45    }
46
47    #[cfg(test)]
48    pub(crate) fn reserve_range(&self, count: usize) -> Result<Range<u64>, NoiseError> {
49        let count = u64::try_from(count).map_err(|_| NoiseError::NonceOverflow)?;
50        if count == 0 {
51            let current = self.current();
52            return Ok(current..current);
53        }
54
55        let first = self
56            .next
57            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |next| {
58                if next <= u64::MAX - count {
59                    Some(next + count)
60                } else {
61                    None
62                }
63            })
64            .map_err(|_| NoiseError::NonceOverflow)?;
65        Ok(first..first + count)
66    }
67}
68
69/// Completed Noise session for transport encryption.
70///
71/// Provides bidirectional authenticated encryption with replay protection.
72/// The send counter is monotonically incremented; received counters are
73/// validated against a sliding window to prevent replay attacks.
74pub struct NoiseSession {
75    /// Our role in the original handshake.
76    role: HandshakeRole,
77    /// Cipher for sending.
78    send_cipher: CipherState,
79    /// Monotonic send counter authority for transport nonces.
80    send_counter: SendCounterAuthority,
81    /// Cipher for receiving.
82    recv_cipher: CipherState,
83    /// Handshake hash for channel binding.
84    handshake_hash: [u8; 32],
85    /// Remote peer's static public key.
86    remote_static: PublicKey,
87    /// Replay window for received packets.
88    replay_window: ReplayWindow,
89}
90
91impl NoiseSession {
92    /// Create a new session from completed handshake data.
93    pub(super) fn from_handshake(
94        role: HandshakeRole,
95        send_cipher: CipherState,
96        recv_cipher: CipherState,
97        handshake_hash: [u8; 32],
98        remote_static: PublicKey,
99    ) -> Self {
100        let send_counter = SendCounterAuthority::new(send_cipher.nonce());
101        Self {
102            role,
103            send_cipher,
104            send_counter,
105            recv_cipher,
106            handshake_hash,
107            remote_static,
108            replay_window: ReplayWindow::new(),
109        }
110    }
111
112    /// Encrypt a message for sending (using internal counter).
113    ///
114    /// Returns the ciphertext. The current send counter should be included
115    /// in the wire format before calling this method.
116    pub fn encrypt(&mut self, plaintext: &[u8]) -> Result<Vec<u8>, NoiseError> {
117        let counter = self.take_send_counter()?;
118        self.send_cipher.encrypt_with_counter(plaintext, counter)
119    }
120
121    /// Get the current send counter (before incrementing).
122    ///
123    /// Use this to get the counter to include in the wire format.
124    /// The counter will be incremented when `encrypt` is called.
125    pub fn current_send_counter(&self) -> u64 {
126        self.send_counter.current()
127    }
128
129    /// Decrypt a received message (using internal counter).
130    ///
131    /// This is for handshake-phase decryption. For transport phase with
132    /// explicit counters, use `decrypt_with_replay_check` instead.
133    pub fn decrypt(&mut self, ciphertext: &[u8]) -> Result<Vec<u8>, NoiseError> {
134        self.recv_cipher.decrypt(ciphertext)
135    }
136
137    /// Check if a counter passes the replay window.
138    ///
139    /// Returns Ok(()) if the counter is acceptable, Err if it should be rejected.
140    /// Call this before attempting decryption to avoid wasting CPU on replay attacks.
141    pub fn check_replay(&self, counter: u64) -> Result<(), NoiseError> {
142        if self.replay_window.check(counter) {
143            Ok(())
144        } else {
145            Err(NoiseError::ReplayDetected(counter))
146        }
147    }
148
149    /// Decrypt with explicit counter and replay protection.
150    ///
151    /// This is the primary decryption method for transport phase.
152    /// The counter comes from the wire format and is validated against
153    /// the replay window before and after decryption.
154    ///
155    /// On success, the counter is accepted into the replay window.
156    pub fn decrypt_with_replay_check(
157        &mut self,
158        ciphertext: &[u8],
159        counter: u64,
160    ) -> Result<Vec<u8>, NoiseError> {
161        // Check replay window first (cheap)
162        if !self.replay_window.check(counter) {
163            return Err(NoiseError::ReplayDetected(counter));
164        }
165
166        // Attempt decryption (expensive)
167        let plaintext = self.recv_cipher.decrypt_with_counter(ciphertext, counter)?;
168
169        // Only accept into window after successful decryption
170        // This prevents DoS attacks that exhaust the window
171        self.replay_window.accept(counter);
172
173        Ok(plaintext)
174    }
175
176    /// Encrypt a message with Additional Authenticated Data (AAD).
177    ///
178    /// Returns the ciphertext. The current send counter should be included
179    /// in the wire format before calling this method.
180    pub fn encrypt_with_aad(
181        &mut self,
182        plaintext: &[u8],
183        aad: &[u8],
184    ) -> Result<Vec<u8>, NoiseError> {
185        let counter = self.take_send_counter()?;
186        self.send_cipher
187            .encrypt_with_counter_and_aad(plaintext, counter, aad)
188    }
189
190    /// Decrypt with explicit counter, replay protection, and AAD.
191    ///
192    /// This is the primary decryption method for the FMP transport phase
193    /// with AAD binding. The AAD (typically the 16-byte outer header) must
194    /// match what was used during encryption.
195    pub fn decrypt_with_replay_check_and_aad(
196        &mut self,
197        ciphertext: &[u8],
198        counter: u64,
199        aad: &[u8],
200    ) -> Result<Vec<u8>, NoiseError> {
201        // Check replay window first (cheap)
202        if !self.replay_window.check(counter) {
203            return Err(NoiseError::ReplayDetected(counter));
204        }
205
206        // Attempt decryption with AAD (expensive)
207        let plaintext = self
208            .recv_cipher
209            .decrypt_with_counter_and_aad(ciphertext, counter, aad)?;
210
211        // Only accept into window after successful decryption
212        self.replay_window.accept(counter);
213
214        Ok(plaintext)
215    }
216
217    /// In-place variant of [`Self::decrypt_with_replay_check_and_aad`].
218    ///
219    /// On entry, `buf` holds `ciphertext + 16-byte AEAD tag`. On
220    /// successful return, `buf[..returned_len]` holds the plaintext.
221    /// The caller can then slice into `buf` without paying for an
222    /// extra heap allocation + memcpy per packet — at multi-Gbps
223    /// single-stream the by-value variant's `ciphertext.to_vec()`
224    /// alone is a measurable fraction of the rx_loop's per-packet
225    /// cost.
226    pub fn decrypt_with_replay_check_and_aad_in_place(
227        &mut self,
228        buf: &mut [u8],
229        counter: u64,
230        aad: &[u8],
231    ) -> Result<usize, NoiseError> {
232        if !self.replay_window.check(counter) {
233            return Err(NoiseError::ReplayDetected(counter));
234        }
235        let plaintext_len = self
236            .recv_cipher
237            .decrypt_with_counter_and_aad_in_place(buf, counter, aad)?;
238        self.replay_window.accept(counter);
239        Ok(plaintext_len)
240    }
241
242    /// Get the highest received counter.
243    pub fn highest_received_counter(&self) -> u64 {
244        self.replay_window.highest()
245    }
246
247    /// Clone the recv-side AEAD instance, for off-task decrypt.
248    ///
249    /// Returns `None` if the recv cipher has no key (transport phase has
250    /// not begun). The cloned cipher pairs with `decrypt_with_counter[_and_aad]`
251    /// on `CipherState`: a dispatcher can `check_replay` here, fan the
252    /// AEAD work out to a worker holding the clone + counter + aad, then
253    /// call `accept_replay` here once the worker reports success.
254    pub fn recv_cipher_clone(&self) -> Option<LessSafeKey> {
255        self.recv_cipher.cipher_clone()
256    }
257
258    /// Snapshot the current replay-window state as an **owned**
259    /// `ReplayWindow` value, for hand-off to a shard-owning decrypt
260    /// worker.
261    ///
262    /// **The worker becomes the sole authority for replay protection
263    /// on this session after this snapshot.** The local
264    /// `self.replay_window` is no longer the source of truth — it
265    /// only matters for rare-slow-path uses (rekey, drain-window
266    /// fallback). The worker keeps its copy in its own
267    /// thread-local `HashMap`, so there's no Mutex / no Arc / no
268    /// sharing — direct `&mut` access on every packet.
269    ///
270    /// (Previously this returned an `Arc<Mutex<ReplayWindow>>` for
271    /// concurrent access; the data-plane shard restructure now hands
272    /// the worker exclusive ownership instead.)
273    pub fn recv_replay_snapshot_owned(&self) -> crate::noise::ReplayWindow {
274        self.replay_window.clone()
275    }
276
277    /// Clone the send-side AEAD instance, for off-task encrypt.
278    ///
279    /// Returns `None` if the send cipher has no key. Pairs with
280    /// `encrypt_with_counter[_and_aad]` on `CipherState`. The caller must
281    /// reserve counters through this session's shared counter authority before
282    /// worker-side encryption.
283    pub fn send_cipher_clone(&self) -> Option<LessSafeKey> {
284        self.send_cipher.cipher_clone()
285    }
286
287    /// Clone the send-side counter authority for an owned packet mover.
288    pub(crate) fn send_counter_authority(&self) -> SendCounterAuthority {
289        self.send_counter.clone()
290    }
291
292    /// Whether the send-side cipher is keyed for worker-side encryption.
293    pub fn has_send_cipher(&self) -> bool {
294        self.send_cipher.has_key()
295    }
296
297    /// Reserve and return the next send counter, advancing the internal
298    /// nonce. For pipelined encrypt paths that call `encrypt_with_counter`
299    /// on a cloned cipher: the dispatcher pre-assigns the counter here
300    /// through the session's shared authority and the worker performs the
301    /// AEAD with no further mutation of session state.
302    pub fn take_send_counter(&self) -> Result<u64, NoiseError> {
303        self.send_counter.reserve()
304    }
305
306    /// Accept a counter into the replay window after a successful out-of-task
307    /// decrypt. Caller is responsible for verifying decrypt success first.
308    pub fn accept_replay(&mut self, counter: u64) {
309        self.replay_window.accept(counter);
310    }
311
312    /// Reset the replay window (use when rekeying).
313    pub fn reset_replay_window(&mut self) {
314        self.replay_window.reset();
315    }
316
317    /// Get the handshake hash for channel binding.
318    pub fn handshake_hash(&self) -> &[u8; 32] {
319        &self.handshake_hash
320    }
321
322    /// Get the remote peer's static public key.
323    pub fn remote_static(&self) -> &PublicKey {
324        &self.remote_static
325    }
326
327    /// Get the remote peer's x-only public key.
328    pub fn remote_static_xonly(&self) -> XOnlyPublicKey {
329        self.remote_static.x_only_public_key().0
330    }
331
332    /// Get our role in the handshake.
333    pub fn role(&self) -> HandshakeRole {
334        self.role
335    }
336
337    /// Get the send nonce (for debugging).
338    pub fn send_nonce(&self) -> u64 {
339        self.send_counter.current()
340    }
341
342    /// Get the receive nonce (for debugging).
343    pub fn recv_nonce(&self) -> u64 {
344        self.recv_cipher.nonce()
345    }
346}
347
348impl fmt::Debug for NoiseSession {
349    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
350        f.debug_struct("NoiseSession")
351            .field("role", &self.role)
352            .field("send_nonce", &self.send_counter.current())
353            .field("recv_nonce", &self.recv_cipher.nonce())
354            .field("handshake_hash", &hex::encode(&self.handshake_hash[..8]))
355            .finish()
356    }
357}