Skip to main content

rtci_sframe/
context.rs

1//! The SFrame context: a key store with a role per key, and the encryption and decryption of
2//! RFC 9605 sections 4.4.3 and 4.4.4.
3
4use std::collections::HashMap;
5use std::sync::Arc;
6
7use crypto::{RTCCrypto, RTCCryptoProvider, constant_time_eq};
8use zeroize::{Zeroize, Zeroizing};
9
10use crate::aead::SuiteAead;
11use crate::cipher_suite::{CipherSuite, NONCE_LEN};
12use crate::error::{Error, Result};
13use crate::header::{Header, MAX_HEADER_LEN};
14use crate::kdf::derive_key_salt;
15use crate::replay::{DEFAULT_REPLAY_WINDOW, ReplayWindow};
16
17/// What a stored key may be used for. A key has one role for as long as it is stored
18/// (RFC 9605 section 4.4.1).
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20pub enum KeyUsage {
21    /// The key encrypts; this endpoint is its one sender.
22    Encrypt,
23    /// The key decrypts what another sender encrypted.
24    Decrypt,
25}
26
27/// Options of an [`SFrameContext`].
28#[non_exhaustive]
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct SFrameConfig {
31    /// The anti-replay window of each decryption key, in counter values, or `None` for no
32    /// replay protection (RFC 9605 section 9.3 leaves it to the receiver). With a window, an
33    /// authentic ciphertext is accepted once per counter, and refused when its counter is older
34    /// than the window. Rounded up to a multiple of 64, at most
35    /// [`MAX_REPLAY_WINDOW`](crate::MAX_REPLAY_WINDOW). It applies to keys added afterwards.
36    ///
37    /// Default: [`DEFAULT_REPLAY_WINDOW`].
38    pub replay_window: Option<usize>,
39    /// Accept a header whose KID or CTR is longer than it needs to be. RFC 9605 section 4.3
40    /// requires the shortest form of a sender; this admits senders that do not follow it.
41    ///
42    /// Default: `false`.
43    pub allow_non_minimal_headers: bool,
44}
45
46impl Default for SFrameConfig {
47    fn default() -> Self {
48        Self {
49            replay_window: Some(DEFAULT_REPLAY_WINDOW),
50            allow_non_minimal_headers: false,
51        }
52    }
53}
54
55/// Counts of what a context has done, for an application that watches for the brute-force
56/// signal of RFC 9605 section 7.5 (an elevated rate of failures against a short tag).
57#[non_exhaustive]
58#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
59pub struct SFrameStats {
60    /// Plaintexts encrypted.
61    pub encrypted: u64,
62    /// Ciphertexts decrypted and released.
63    pub decrypted: u64,
64    /// Ciphertexts refused because the header or the length is malformed.
65    pub syntax_errors: u64,
66    /// Ciphertexts refused because no decryption key is stored for their KID.
67    pub unknown_key_ids: u64,
68    /// Ciphertexts refused because the authentication tag did not validate.
69    pub authentication_failures: u64,
70    /// Authentic ciphertexts refused as replays.
71    pub replays: u64,
72}
73
74/// The base key of the decoy: any fixed bytes do, nothing is ever encrypted with it.
75const DECOY_BASE_KEY: &[u8] = b"rtc-sframe decoy";
76
77enum Role {
78    /// The next CTR to encrypt with; `None` once the last one (2^64 - 1) has been used.
79    Send {
80        next_ctr: Option<u64>,
81    },
82    Recv {
83        replay: Option<ReplayWindow>,
84    },
85}
86
87/// A parsed SFrame ciphertext and the metadata it is to be decrypted with.
88pub(crate) struct Frame<'a> {
89    header: Header,
90    /// The header as it was received: it is authenticated byte for byte.
91    encoded_header: &'a [u8],
92    /// What follows the header: the encrypted data, then the tag.
93    body: &'a [u8],
94    metadata: &'a [u8],
95}
96
97impl<'a> Frame<'a> {
98    /// `ciphertext` divided after its `header_len`-byte header.
99    fn new(header: Header, header_len: usize, ciphertext: &'a [u8], metadata: &'a [u8]) -> Self {
100        let (encoded_header, body) = ciphertext.split_at(header_len);
101        Self {
102            header,
103            encoded_header,
104            body,
105            metadata,
106        }
107    }
108}
109
110/// One stored key: the keyed AEAD, the salt, and what the role needs.
111pub(crate) struct KeyContext {
112    aead: SuiteAead,
113    salt: Zeroizing<[u8; NONCE_LEN]>,
114    role: Role,
115}
116
117impl KeyContext {
118    fn derive(
119        crypto: &dyn RTCCrypto,
120        suite: CipherSuite,
121        kid: u64,
122        base_key: &[u8],
123        role: Role,
124    ) -> Result<Box<Self>> {
125        // A key context lives in a heap block of its own (the store holds the box), so that
126        // moving it, in or out of the store or when the store grows, copies a pointer and not
127        // the salt: a `HashMap` that moves a value leaves its bytes in the bucket and frees the
128        // table without erasing it. It is derived and built in frames below this one over stack
129        // that has just been overwritten (so the bytes of the new value that no field writes,
130        // padding and the room of a smaller variant, carry nothing from earlier key work), and
131        // the stack is overwritten again afterwards (so no copy of the key or the salt is left
132        // in a dead frame, to be carried into a later heap value the same way; docs/key-erasure.md).
133        crypto::scrub_stack();
134        crypto::on_erased_stack(|| {
135            let derived = derive_key_salt(crypto, suite, kid, base_key)?;
136            Ok(Box::new(Self {
137                aead: SuiteAead::new(crypto, suite, &derived.key)?,
138                salt: derived.salt,
139                role,
140            }))
141        })
142    }
143
144    /// A decryption key for `kid`, not stored anywhere yet.
145    pub(crate) fn derive_recv(
146        crypto: &dyn RTCCrypto,
147        suite: CipherSuite,
148        kid: u64,
149        base_key: &[u8],
150        replay_window: Option<usize>,
151    ) -> Result<Box<Self>> {
152        let replay = replay_window.map(ReplayWindow::new);
153        Self::derive(crypto, suite, kid, base_key, Role::Recv { replay })
154    }
155
156    /// The nonce of RFC 9605 section 4.4.3: the salt XOR the CTR as an `Nn`-byte big-endian
157    /// integer.
158    fn nonce(&self, ctr: u64) -> Zeroizing<[u8; NONCE_LEN]> {
159        let mut nonce = Zeroizing::new(*self.salt);
160        for (byte, ctr_byte) in nonce[NONCE_LEN - 8..].iter_mut().zip(ctr.to_be_bytes()) {
161            *byte ^= ctr_byte;
162        }
163        nonce
164    }
165
166    fn usage(&self) -> KeyUsage {
167        match self.role {
168            Role::Send { .. } => KeyUsage::Encrypt,
169            Role::Recv { .. } => KeyUsage::Decrypt,
170        }
171    }
172
173    /// Decrypts one ciphertext with this key, appending the plaintext to `out`.
174    ///
175    /// On any error `out` is as it was, and the bytes written meanwhile are erased.
176    pub(crate) fn open(
177        &mut self,
178        suite: CipherSuite,
179        frame: Frame<'_>,
180        scratch: &mut Vec<u8>,
181        out: &mut Vec<u8>,
182    ) -> Result<()> {
183        let Frame {
184            header,
185            encoded_header,
186            body,
187            metadata,
188        } = frame;
189        let nonce = self.nonce(header.ctr);
190        let Role::Recv { replay } = &mut self.role else {
191            return Err(Error::KeyRoleConflict(header.kid));
192        };
193        let Some(data_len) = body.len().checked_sub(suite.tag_len()) else {
194            return Err(Error::TruncatedCiphertext);
195        };
196        let (data, tag) = body.split_at(data_len);
197
198        let start = out.len();
199        out.extend_from_slice(data);
200        let mut result = self.aead.open(
201            &nonce,
202            encoded_header,
203            metadata,
204            scratch,
205            &mut out[start..],
206            tag,
207        );
208        // The replay check comes after authentication: only an authentic ciphertext can be a
209        // replay, and a replayed one costs what a fresh one does.
210        if result.is_ok()
211            && let Some(window) = replay
212        {
213            if window.is_fresh(header.ctr) {
214                window.accept(header.ctr);
215            } else {
216                result = Err(Error::Replayed {
217                    kid: header.kid,
218                    ctr: header.ctr,
219                });
220            }
221        }
222        if result.is_err() {
223            out[start..].zeroize();
224            out.truncate(start);
225        }
226        result
227    }
228}
229
230/// An SFrame context (RFC 9605 Appendix A): one cipher suite, and the keys known for each KID.
231///
232/// A key is added for sending or for receiving and keeps that role. Encryption takes the KID to
233/// use and draws the CTR from the key's own counter, so a (key, nonce) pair is never used
234/// twice; decryption finds the key by the KID in the SFrame header.
235///
236/// ```
237/// use rtci_sframe::{CipherSuite, SFrameContext};
238///
239/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
240/// let suite = CipherSuite::Aes128GcmSha256_128;
241/// let base_key = [0x2a; 16]; // from the application's key management
242///
243/// let mut sender = SFrameContext::with_default_provider(suite)?;
244/// sender.add_send_key(7, &base_key)?;
245/// let mut receiver = SFrameContext::with_default_provider(suite)?;
246/// receiver.add_recv_key(7, &base_key)?;
247///
248/// let metadata = b"what the application authenticates but sends elsewhere";
249/// let ciphertext = sender.encrypt(7, metadata, b"an encoded frame")?;
250/// assert_eq!(receiver.decrypt(metadata, &ciphertext)?, b"an encoded frame");
251/// # Ok(())
252/// # }
253/// ```
254pub struct SFrameContext {
255    suite: CipherSuite,
256    provider: Arc<dyn RTCCryptoProvider>,
257    config: SFrameConfig,
258    keys: HashMap<u64, Box<KeyContext>>,
259    /// A decryption key that belongs to no sender, for ciphertexts that have none: see
260    /// [`decrypt_uncounted`](Self::decrypt_uncounted). Made with the first decryption key.
261    decoy: Option<Box<KeyContext>>,
262    /// Reused to join header and metadata for a native AEAD.
263    scratch: Vec<u8>,
264    stats: SFrameStats,
265}
266
267impl SFrameContext {
268    /// A context for `suite` with no keys and the default [`SFrameConfig`].
269    #[must_use]
270    pub fn new(suite: CipherSuite, provider: Arc<dyn RTCCryptoProvider>) -> Self {
271        Self::with_config(suite, provider, SFrameConfig::default())
272    }
273
274    /// A context for `suite` with no keys.
275    #[must_use]
276    pub fn with_config(
277        suite: CipherSuite,
278        provider: Arc<dyn RTCCryptoProvider>,
279        config: SFrameConfig,
280    ) -> Self {
281        Self {
282            suite,
283            provider,
284            config,
285            keys: HashMap::new(),
286            decoy: None,
287            scratch: Vec::new(),
288            stats: SFrameStats::default(),
289        }
290    }
291
292    /// A context for `suite` on the built-in crypto provider. Fails when the crate was built
293    /// without one.
294    pub fn with_default_provider(suite: CipherSuite) -> Result<Self> {
295        Ok(Self::new(
296            suite,
297            crypto::default_provider().map_err(Error::Crypto)?,
298        ))
299    }
300
301    /// The context's cipher suite.
302    #[must_use]
303    pub fn cipher_suite(&self) -> CipherSuite {
304        self.suite
305    }
306
307    /// The context's options.
308    #[must_use]
309    pub fn config(&self) -> &SFrameConfig {
310        &self.config
311    }
312
313    /// The crypto provider the context was built with.
314    #[must_use]
315    pub fn provider(&self) -> &Arc<dyn RTCCryptoProvider> {
316        &self.provider
317    }
318
319    /// What the context has done so far.
320    #[must_use]
321    pub fn stats(&self) -> SFrameStats {
322        self.stats
323    }
324
325    /// The most bytes encryption adds to a plaintext: the longest header and the suite's tag.
326    #[must_use]
327    pub fn max_overhead(&self) -> usize {
328        MAX_HEADER_LEN + self.suite.tag_len()
329    }
330
331    /// Adds `base_key` under `kid` for encryption, with its counter at 0.
332    ///
333    /// The caller is the key's one sender (RFC 9605 section 4.4.1). Fails with
334    /// [`Error::KeyRoleConflict`] when `kid` holds a decryption key, and with
335    /// [`Error::KeyReuse`] when `kid` already sends with this very key, since starting its
336    /// counter again would repeat nonces. Another key under the same KID replaces the old one.
337    pub fn add_send_key(&mut self, kid: u64, base_key: &[u8]) -> Result<()> {
338        self.add_send_key_at(kid, base_key, 0)
339    }
340
341    /// Adds `base_key` under `kid` for encryption, with its counter at `next_ctr`.
342    ///
343    /// For a context restored from storage (RFC 9605 section 9.1): store
344    /// [`next_counter`](Self::next_counter) before using it, and resume from the stored value,
345    /// so that a failure never leads to a counter being used twice.
346    pub fn add_send_key_at(&mut self, kid: u64, base_key: &[u8], next_ctr: u64) -> Result<()> {
347        let role = Role::Send {
348            next_ctr: Some(next_ctr),
349        };
350        let key = KeyContext::derive(self.provider.crypto(), self.suite, kid, base_key, role)?;
351        match self.keys.get(&kid) {
352            Some(existing) if existing.usage() != KeyUsage::Encrypt => {
353                Err(Error::KeyRoleConflict(kid))
354            }
355            Some(existing) if constant_time_eq(&existing.salt[..], &key.salt[..]) => {
356                Err(Error::KeyReuse(kid))
357            }
358            _ => {
359                self.keys.insert(kid, key);
360                Ok(())
361            }
362        }
363    }
364
365    /// Adds `base_key` under `kid` for decryption.
366    ///
367    /// Fails with [`Error::KeyRoleConflict`] when `kid` holds an encryption key. Adding the key
368    /// `kid` already decrypts with changes nothing (its replay window is kept); another key
369    /// under the same KID replaces the old one.
370    pub fn add_recv_key(&mut self, kid: u64, base_key: &[u8]) -> Result<()> {
371        let key = KeyContext::derive_recv(
372            self.provider.crypto(),
373            self.suite,
374            kid,
375            base_key,
376            self.config.replay_window,
377        )?;
378        match self.keys.get(&kid) {
379            Some(existing) if existing.usage() != KeyUsage::Decrypt => {
380                return Err(Error::KeyRoleConflict(kid));
381            }
382            Some(existing) if constant_time_eq(&existing.salt[..], &key.salt[..]) => {
383                return Ok(());
384            }
385            _ => {}
386        }
387        if self.decoy.is_none() {
388            self.decoy = Some(KeyContext::derive_recv(
389                self.provider.crypto(),
390                self.suite,
391                0,
392                DECOY_BASE_KEY,
393                None,
394            )?);
395        }
396        self.keys.insert(kid, key);
397        Ok(())
398    }
399
400    /// Stores a decryption key derived elsewhere in this crate, replacing what `kid` held.
401    pub(crate) fn insert_key(&mut self, kid: u64, key: Box<KeyContext>) {
402        self.keys.insert(kid, key);
403    }
404
405    /// Removes the key stored under `kid`. Returns whether there was one.
406    ///
407    /// A removed encryption key takes its counter with it: adding the same `base_key` under the
408    /// same KID again would repeat nonces, and it is the application that must not do so
409    /// (RFC 9605 section 9.1).
410    pub fn remove_key(&mut self, kid: u64) -> bool {
411        self.keys.remove(&kid).is_some()
412    }
413
414    /// Removes every key whose KID `keep` returns `false` for.
415    pub fn retain_keys(&mut self, mut keep: impl FnMut(u64) -> bool) {
416        self.keys.retain(|kid, _| keep(*kid));
417    }
418
419    /// What the key stored under `kid` is for, if there is one.
420    #[must_use]
421    pub fn key_usage(&self, kid: u64) -> Option<KeyUsage> {
422        self.keys.get(&kid).map(|key| key.usage())
423    }
424
425    /// The number of keys stored.
426    #[must_use]
427    pub fn key_count(&self) -> usize {
428        self.keys.len()
429    }
430
431    /// The CTR the next encryption under `kid` will use. `None` when `kid` holds no encryption
432    /// key, or one that has used every counter.
433    #[must_use]
434    pub fn next_counter(&self, kid: u64) -> Option<u64> {
435        match self.keys.get(&kid)?.role {
436            Role::Send { next_ctr } => next_ctr,
437            Role::Recv { .. } => None,
438        }
439    }
440
441    /// Encrypts `plaintext` with the key stored under `kid` and returns the SFrame ciphertext:
442    /// header, encrypted data, authentication tag (RFC 9605 section 4.4.3).
443    ///
444    /// `metadata` is authenticated with the header but is not part of the output; the receiver
445    /// must supply the same bytes.
446    pub fn encrypt(&mut self, kid: u64, metadata: &[u8], plaintext: &[u8]) -> Result<Vec<u8>> {
447        let mut out = Vec::with_capacity(plaintext.len() + self.max_overhead());
448        self.encrypt_into(kid, metadata, plaintext, &mut out)?;
449        Ok(out)
450    }
451
452    /// [`encrypt`](Self::encrypt), appending the ciphertext to `out` so that a caller can reuse
453    /// one buffer. Returns the header that was written. On an error `out` is as it was.
454    ///
455    /// The key's counter advances before the cipher runs, so a counter is never used twice,
456    /// whatever happens. After 2^64 encryptions the key is exhausted
457    /// ([`Error::CounterExhausted`]).
458    pub fn encrypt_into(
459        &mut self,
460        kid: u64,
461        metadata: &[u8],
462        plaintext: &[u8],
463        out: &mut Vec<u8>,
464    ) -> Result<Header> {
465        let Some(key) = self.keys.get_mut(&kid) else {
466            return Err(Error::UnknownKeyId(kid));
467        };
468        let Role::Send { next_ctr } = &mut key.role else {
469            return Err(Error::KeyRoleConflict(kid));
470        };
471        let Some(ctr) = *next_ctr else {
472            return Err(Error::CounterExhausted(kid));
473        };
474        *next_ctr = ctr.checked_add(1);
475
476        let header = Header::new(kid, ctr);
477        let mut encoded_header = [0u8; MAX_HEADER_LEN];
478        let header_len = header.encode(&mut encoded_header);
479        let nonce = key.nonce(ctr);
480
481        let start = out.len();
482        out.reserve(header_len + plaintext.len() + self.suite.tag_len());
483        out.extend_from_slice(&encoded_header[..header_len]);
484        out.extend_from_slice(plaintext);
485        out.resize(out.len() + self.suite.tag_len(), 0);
486        let (data, tag) = out[start + header_len..].split_at_mut(plaintext.len());
487        let sealed = key.aead.seal(
488            &nonce,
489            &encoded_header[..header_len],
490            metadata,
491            &mut self.scratch,
492            data,
493            tag,
494        );
495        if let Err(error) = sealed {
496            out[start..].zeroize();
497            out.truncate(start);
498            return Err(error);
499        }
500        self.stats.encrypted = self.stats.encrypted.saturating_add(1);
501        Ok(header)
502    }
503
504    /// Decrypts an SFrame ciphertext and returns the plaintext (RFC 9605 section 4.4.4).
505    ///
506    /// `metadata` must be the bytes the sender authenticated. Nothing of an unauthenticated
507    /// ciphertext is returned. A ciphertext that fails authentication, is a replay or names a
508    /// KID without a decryption key costs the cipher and MAC work of a valid one of its length,
509    /// so that the outcome does not show in the time taken; only a malformed one, which has
510    /// nothing to process, returns at once.
511    ///
512    /// The ciphertext is not consumed: when the failure is
513    /// [`Error::UnknownKeyId`], the application may keep it (see
514    /// [`PendingCiphertexts`](crate::PendingCiphertexts)) and decrypt again once the key has
515    /// arrived. Any other failure means the ciphertext is to be discarded.
516    pub fn decrypt(&mut self, metadata: &[u8], ciphertext: &[u8]) -> Result<Vec<u8>> {
517        let mut out = Vec::with_capacity(ciphertext.len());
518        self.decrypt_into(metadata, ciphertext, &mut out)?;
519        Ok(out)
520    }
521
522    /// [`decrypt`](Self::decrypt), appending the plaintext to `out` so that a caller can reuse
523    /// one buffer. Returns the header of the ciphertext. On an error `out` is as it was.
524    pub fn decrypt_into(
525        &mut self,
526        metadata: &[u8],
527        ciphertext: &[u8],
528        out: &mut Vec<u8>,
529    ) -> Result<Header> {
530        let result = self.decrypt_uncounted(metadata, ciphertext, out);
531        self.count(&result);
532        result
533    }
534
535    /// [`decrypt_into`](Self::decrypt_into) without the statistics, for the key-management
536    /// helpers that may try a second key before the outcome is known.
537    pub(crate) fn decrypt_uncounted(
538        &mut self,
539        metadata: &[u8],
540        ciphertext: &[u8],
541        out: &mut Vec<u8>,
542    ) -> Result<Header> {
543        let (header, header_len) = self.decode_header(ciphertext)?;
544        let frame = Frame::new(header, header_len, ciphertext, metadata);
545        let refusal = match self.keys.get_mut(&header.kid) {
546            Some(key) if key.usage() == KeyUsage::Decrypt => {
547                key.open(self.suite, frame, &mut self.scratch, out)?;
548                return Ok(header);
549            }
550            Some(_) => Error::KeyRoleConflict(header.kid),
551            None => Error::UnknownKeyId(header.kid),
552        };
553        // No key to decrypt with. The decoy does the work a key would have done, so that this
554        // ciphertext is discarded like one that fails authentication (RFC 9605 section 4.4.4).
555        if let Some(decoy) = &mut self.decoy {
556            let start = out.len();
557            let _ = decoy.open(self.suite, frame, &mut self.scratch, out);
558            out[start..].zeroize();
559            out.truncate(start);
560        }
561        Err(refusal)
562    }
563
564    /// Parses the header of `ciphertext` as this context's configuration admits it.
565    pub(crate) fn decode_header(&self, ciphertext: &[u8]) -> Result<(Header, usize)> {
566        if self.config.allow_non_minimal_headers {
567            Header::decode_lenient(ciphertext)
568        } else {
569            Header::decode(ciphertext)
570        }
571    }
572
573    /// Decrypts with a key that is not in the store (yet), for the key-management helpers that
574    /// derive a key on demand and keep it only once a ciphertext has authenticated with it.
575    pub(crate) fn decrypt_with(
576        &mut self,
577        key: &mut KeyContext,
578        header: Header,
579        header_len: usize,
580        metadata: &[u8],
581        ciphertext: &[u8],
582        out: &mut Vec<u8>,
583    ) -> Result<()> {
584        key.open(
585            self.suite,
586            Frame::new(header, header_len, ciphertext, metadata),
587            &mut self.scratch,
588            out,
589        )
590    }
591
592    /// Adds the outcome of one decryption to the statistics.
593    pub(crate) fn count<T>(&mut self, result: &Result<T>) {
594        let counter = match result {
595            Ok(_) => &mut self.stats.decrypted,
596            Err(Error::TruncatedHeader | Error::NonMinimalHeader | Error::TruncatedCiphertext) => {
597                &mut self.stats.syntax_errors
598            }
599            Err(Error::UnknownKeyId(_) | Error::KeyRoleConflict(_)) => {
600                &mut self.stats.unknown_key_ids
601            }
602            Err(Error::AuthenticationFailed) => &mut self.stats.authentication_failures,
603            Err(Error::Replayed { .. }) => &mut self.stats.replays,
604            Err(_) => return,
605        };
606        *counter = counter.saturating_add(1);
607    }
608}
609
610impl std::fmt::Debug for SFrameContext {
611    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
612        formatter
613            .debug_struct("SFrameContext")
614            .field("suite", &self.suite)
615            .field("config", &self.config)
616            .field("keys", &self.keys.len())
617            .field("stats", &self.stats)
618            .finish_non_exhaustive()
619    }
620}