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<Self> {
125        let derived = derive_key_salt(crypto, suite, kid, base_key)?;
126        Ok(Self {
127            aead: SuiteAead::new(crypto, suite, &derived.key)?,
128            salt: derived.salt,
129            role,
130        })
131    }
132
133    /// A decryption key for `kid`, not stored anywhere yet.
134    pub(crate) fn derive_recv(
135        crypto: &dyn RTCCrypto,
136        suite: CipherSuite,
137        kid: u64,
138        base_key: &[u8],
139        replay_window: Option<usize>,
140    ) -> Result<Self> {
141        let replay = replay_window.map(ReplayWindow::new);
142        Self::derive(crypto, suite, kid, base_key, Role::Recv { replay })
143    }
144
145    /// The nonce of RFC 9605 section 4.4.3: the salt XOR the CTR as an `Nn`-byte big-endian
146    /// integer.
147    fn nonce(&self, ctr: u64) -> Zeroizing<[u8; NONCE_LEN]> {
148        let mut nonce = Zeroizing::new(*self.salt);
149        for (byte, ctr_byte) in nonce[NONCE_LEN - 8..].iter_mut().zip(ctr.to_be_bytes()) {
150            *byte ^= ctr_byte;
151        }
152        nonce
153    }
154
155    fn usage(&self) -> KeyUsage {
156        match self.role {
157            Role::Send { .. } => KeyUsage::Encrypt,
158            Role::Recv { .. } => KeyUsage::Decrypt,
159        }
160    }
161
162    /// Decrypts one ciphertext with this key, appending the plaintext to `out`.
163    ///
164    /// On any error `out` is as it was, and the bytes written meanwhile are erased.
165    pub(crate) fn open(
166        &mut self,
167        suite: CipherSuite,
168        frame: Frame<'_>,
169        scratch: &mut Vec<u8>,
170        out: &mut Vec<u8>,
171    ) -> Result<()> {
172        let Frame {
173            header,
174            encoded_header,
175            body,
176            metadata,
177        } = frame;
178        let nonce = self.nonce(header.ctr);
179        let Role::Recv { replay } = &mut self.role else {
180            return Err(Error::KeyRoleConflict(header.kid));
181        };
182        let Some(data_len) = body.len().checked_sub(suite.tag_len()) else {
183            return Err(Error::TruncatedCiphertext);
184        };
185        let (data, tag) = body.split_at(data_len);
186
187        let start = out.len();
188        out.extend_from_slice(data);
189        let mut result = self.aead.open(
190            &nonce,
191            encoded_header,
192            metadata,
193            scratch,
194            &mut out[start..],
195            tag,
196        );
197        // The replay check comes after authentication: only an authentic ciphertext can be a
198        // replay, and a replayed one costs what a fresh one does.
199        if result.is_ok()
200            && let Some(window) = replay
201        {
202            if window.is_fresh(header.ctr) {
203                window.accept(header.ctr);
204            } else {
205                result = Err(Error::Replayed {
206                    kid: header.kid,
207                    ctr: header.ctr,
208                });
209            }
210        }
211        if result.is_err() {
212            out[start..].zeroize();
213            out.truncate(start);
214        }
215        result
216    }
217}
218
219/// An SFrame context (RFC 9605 Appendix A): one cipher suite, and the keys known for each KID.
220///
221/// A key is added for sending or for receiving and keeps that role. Encryption takes the KID to
222/// use and draws the CTR from the key's own counter, so a (key, nonce) pair is never used
223/// twice; decryption finds the key by the KID in the SFrame header.
224///
225/// ```
226/// use rtci_sframe::{CipherSuite, SFrameContext};
227///
228/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
229/// let suite = CipherSuite::Aes128GcmSha256_128;
230/// let base_key = [0x2a; 16]; // from the application's key management
231///
232/// let mut sender = SFrameContext::with_default_provider(suite)?;
233/// sender.add_send_key(7, &base_key)?;
234/// let mut receiver = SFrameContext::with_default_provider(suite)?;
235/// receiver.add_recv_key(7, &base_key)?;
236///
237/// let metadata = b"what the application authenticates but sends elsewhere";
238/// let ciphertext = sender.encrypt(7, metadata, b"an encoded frame")?;
239/// assert_eq!(receiver.decrypt(metadata, &ciphertext)?, b"an encoded frame");
240/// # Ok(())
241/// # }
242/// ```
243pub struct SFrameContext {
244    suite: CipherSuite,
245    provider: Arc<dyn RTCCryptoProvider>,
246    config: SFrameConfig,
247    keys: HashMap<u64, KeyContext>,
248    /// A decryption key that belongs to no sender, for ciphertexts that have none: see
249    /// [`decrypt_uncounted`](Self::decrypt_uncounted). Made with the first decryption key.
250    decoy: Option<KeyContext>,
251    /// Reused to join header and metadata for a native AEAD.
252    scratch: Vec<u8>,
253    stats: SFrameStats,
254}
255
256impl SFrameContext {
257    /// A context for `suite` with no keys and the default [`SFrameConfig`].
258    #[must_use]
259    pub fn new(suite: CipherSuite, provider: Arc<dyn RTCCryptoProvider>) -> Self {
260        Self::with_config(suite, provider, SFrameConfig::default())
261    }
262
263    /// A context for `suite` with no keys.
264    #[must_use]
265    pub fn with_config(
266        suite: CipherSuite,
267        provider: Arc<dyn RTCCryptoProvider>,
268        config: SFrameConfig,
269    ) -> Self {
270        Self {
271            suite,
272            provider,
273            config,
274            keys: HashMap::new(),
275            decoy: None,
276            scratch: Vec::new(),
277            stats: SFrameStats::default(),
278        }
279    }
280
281    /// A context for `suite` on the built-in crypto provider. Fails when the crate was built
282    /// without one.
283    pub fn with_default_provider(suite: CipherSuite) -> Result<Self> {
284        Ok(Self::new(
285            suite,
286            crypto::default_provider().map_err(Error::Crypto)?,
287        ))
288    }
289
290    /// The context's cipher suite.
291    #[must_use]
292    pub fn cipher_suite(&self) -> CipherSuite {
293        self.suite
294    }
295
296    /// The context's options.
297    #[must_use]
298    pub fn config(&self) -> &SFrameConfig {
299        &self.config
300    }
301
302    /// The crypto provider the context was built with.
303    #[must_use]
304    pub fn provider(&self) -> &Arc<dyn RTCCryptoProvider> {
305        &self.provider
306    }
307
308    /// What the context has done so far.
309    #[must_use]
310    pub fn stats(&self) -> SFrameStats {
311        self.stats
312    }
313
314    /// The most bytes encryption adds to a plaintext: the longest header and the suite's tag.
315    #[must_use]
316    pub fn max_overhead(&self) -> usize {
317        MAX_HEADER_LEN + self.suite.tag_len()
318    }
319
320    /// Adds `base_key` under `kid` for encryption, with its counter at 0.
321    ///
322    /// The caller is the key's one sender (RFC 9605 section 4.4.1). Fails with
323    /// [`Error::KeyRoleConflict`] when `kid` holds a decryption key, and with
324    /// [`Error::KeyReuse`] when `kid` already sends with this very key, since starting its
325    /// counter again would repeat nonces. Another key under the same KID replaces the old one.
326    pub fn add_send_key(&mut self, kid: u64, base_key: &[u8]) -> Result<()> {
327        self.add_send_key_at(kid, base_key, 0)
328    }
329
330    /// Adds `base_key` under `kid` for encryption, with its counter at `next_ctr`.
331    ///
332    /// For a context restored from storage (RFC 9605 section 9.1): store
333    /// [`next_counter`](Self::next_counter) before using it, and resume from the stored value,
334    /// so that a failure never leads to a counter being used twice.
335    pub fn add_send_key_at(&mut self, kid: u64, base_key: &[u8], next_ctr: u64) -> Result<()> {
336        let role = Role::Send {
337            next_ctr: Some(next_ctr),
338        };
339        let key = KeyContext::derive(self.provider.crypto(), self.suite, kid, base_key, role)?;
340        match self.keys.get(&kid) {
341            Some(existing) if existing.usage() != KeyUsage::Encrypt => {
342                Err(Error::KeyRoleConflict(kid))
343            }
344            Some(existing) if constant_time_eq(&existing.salt[..], &key.salt[..]) => {
345                Err(Error::KeyReuse(kid))
346            }
347            _ => {
348                self.keys.insert(kid, key);
349                Ok(())
350            }
351        }
352    }
353
354    /// Adds `base_key` under `kid` for decryption.
355    ///
356    /// Fails with [`Error::KeyRoleConflict`] when `kid` holds an encryption key. Adding the key
357    /// `kid` already decrypts with changes nothing (its replay window is kept); another key
358    /// under the same KID replaces the old one.
359    pub fn add_recv_key(&mut self, kid: u64, base_key: &[u8]) -> Result<()> {
360        let key = KeyContext::derive_recv(
361            self.provider.crypto(),
362            self.suite,
363            kid,
364            base_key,
365            self.config.replay_window,
366        )?;
367        match self.keys.get(&kid) {
368            Some(existing) if existing.usage() != KeyUsage::Decrypt => {
369                return Err(Error::KeyRoleConflict(kid));
370            }
371            Some(existing) if constant_time_eq(&existing.salt[..], &key.salt[..]) => {
372                return Ok(());
373            }
374            _ => {}
375        }
376        if self.decoy.is_none() {
377            self.decoy = Some(KeyContext::derive_recv(
378                self.provider.crypto(),
379                self.suite,
380                0,
381                DECOY_BASE_KEY,
382                None,
383            )?);
384        }
385        self.keys.insert(kid, key);
386        Ok(())
387    }
388
389    /// Stores a decryption key derived elsewhere in this crate, replacing what `kid` held.
390    pub(crate) fn insert_key(&mut self, kid: u64, key: KeyContext) {
391        self.keys.insert(kid, key);
392    }
393
394    /// Removes the key stored under `kid`. Returns whether there was one.
395    ///
396    /// A removed encryption key takes its counter with it: adding the same `base_key` under the
397    /// same KID again would repeat nonces, and it is the application that must not do so
398    /// (RFC 9605 section 9.1).
399    pub fn remove_key(&mut self, kid: u64) -> bool {
400        self.keys.remove(&kid).is_some()
401    }
402
403    /// Removes every key whose KID `keep` returns `false` for.
404    pub fn retain_keys(&mut self, mut keep: impl FnMut(u64) -> bool) {
405        self.keys.retain(|kid, _| keep(*kid));
406    }
407
408    /// What the key stored under `kid` is for, if there is one.
409    #[must_use]
410    pub fn key_usage(&self, kid: u64) -> Option<KeyUsage> {
411        self.keys.get(&kid).map(KeyContext::usage)
412    }
413
414    /// The number of keys stored.
415    #[must_use]
416    pub fn key_count(&self) -> usize {
417        self.keys.len()
418    }
419
420    /// The CTR the next encryption under `kid` will use. `None` when `kid` holds no encryption
421    /// key, or one that has used every counter.
422    #[must_use]
423    pub fn next_counter(&self, kid: u64) -> Option<u64> {
424        match self.keys.get(&kid)?.role {
425            Role::Send { next_ctr } => next_ctr,
426            Role::Recv { .. } => None,
427        }
428    }
429
430    /// Encrypts `plaintext` with the key stored under `kid` and returns the SFrame ciphertext:
431    /// header, encrypted data, authentication tag (RFC 9605 section 4.4.3).
432    ///
433    /// `metadata` is authenticated with the header but is not part of the output; the receiver
434    /// must supply the same bytes.
435    pub fn encrypt(&mut self, kid: u64, metadata: &[u8], plaintext: &[u8]) -> Result<Vec<u8>> {
436        let mut out = Vec::with_capacity(plaintext.len() + self.max_overhead());
437        self.encrypt_into(kid, metadata, plaintext, &mut out)?;
438        Ok(out)
439    }
440
441    /// [`encrypt`](Self::encrypt), appending the ciphertext to `out` so that a caller can reuse
442    /// one buffer. Returns the header that was written. On an error `out` is as it was.
443    ///
444    /// The key's counter advances before the cipher runs, so a counter is never used twice,
445    /// whatever happens. After 2^64 encryptions the key is exhausted
446    /// ([`Error::CounterExhausted`]).
447    pub fn encrypt_into(
448        &mut self,
449        kid: u64,
450        metadata: &[u8],
451        plaintext: &[u8],
452        out: &mut Vec<u8>,
453    ) -> Result<Header> {
454        let Some(key) = self.keys.get_mut(&kid) else {
455            return Err(Error::UnknownKeyId(kid));
456        };
457        let Role::Send { next_ctr } = &mut key.role else {
458            return Err(Error::KeyRoleConflict(kid));
459        };
460        let Some(ctr) = *next_ctr else {
461            return Err(Error::CounterExhausted(kid));
462        };
463        *next_ctr = ctr.checked_add(1);
464
465        let header = Header::new(kid, ctr);
466        let mut encoded_header = [0u8; MAX_HEADER_LEN];
467        let header_len = header.encode(&mut encoded_header);
468        let nonce = key.nonce(ctr);
469
470        let start = out.len();
471        out.reserve(header_len + plaintext.len() + self.suite.tag_len());
472        out.extend_from_slice(&encoded_header[..header_len]);
473        out.extend_from_slice(plaintext);
474        out.resize(out.len() + self.suite.tag_len(), 0);
475        let (data, tag) = out[start + header_len..].split_at_mut(plaintext.len());
476        let sealed = key.aead.seal(
477            &nonce,
478            &encoded_header[..header_len],
479            metadata,
480            &mut self.scratch,
481            data,
482            tag,
483        );
484        if let Err(error) = sealed {
485            out[start..].zeroize();
486            out.truncate(start);
487            return Err(error);
488        }
489        self.stats.encrypted = self.stats.encrypted.saturating_add(1);
490        Ok(header)
491    }
492
493    /// Decrypts an SFrame ciphertext and returns the plaintext (RFC 9605 section 4.4.4).
494    ///
495    /// `metadata` must be the bytes the sender authenticated. Nothing of an unauthenticated
496    /// ciphertext is returned. A ciphertext that fails authentication, is a replay or names a
497    /// KID without a decryption key costs the cipher and MAC work of a valid one of its length,
498    /// so that the outcome does not show in the time taken; only a malformed one, which has
499    /// nothing to process, returns at once.
500    ///
501    /// The ciphertext is not consumed: when the failure is
502    /// [`Error::UnknownKeyId`], the application may keep it (see
503    /// [`PendingCiphertexts`](crate::PendingCiphertexts)) and decrypt again once the key has
504    /// arrived. Any other failure means the ciphertext is to be discarded.
505    pub fn decrypt(&mut self, metadata: &[u8], ciphertext: &[u8]) -> Result<Vec<u8>> {
506        let mut out = Vec::with_capacity(ciphertext.len());
507        self.decrypt_into(metadata, ciphertext, &mut out)?;
508        Ok(out)
509    }
510
511    /// [`decrypt`](Self::decrypt), appending the plaintext to `out` so that a caller can reuse
512    /// one buffer. Returns the header of the ciphertext. On an error `out` is as it was.
513    pub fn decrypt_into(
514        &mut self,
515        metadata: &[u8],
516        ciphertext: &[u8],
517        out: &mut Vec<u8>,
518    ) -> Result<Header> {
519        let result = self.decrypt_uncounted(metadata, ciphertext, out);
520        self.count(&result);
521        result
522    }
523
524    /// [`decrypt_into`](Self::decrypt_into) without the statistics, for the key-management
525    /// helpers that may try a second key before the outcome is known.
526    pub(crate) fn decrypt_uncounted(
527        &mut self,
528        metadata: &[u8],
529        ciphertext: &[u8],
530        out: &mut Vec<u8>,
531    ) -> Result<Header> {
532        let (header, header_len) = self.decode_header(ciphertext)?;
533        let frame = Frame::new(header, header_len, ciphertext, metadata);
534        let refusal = match self.keys.get_mut(&header.kid) {
535            Some(key) if key.usage() == KeyUsage::Decrypt => {
536                key.open(self.suite, frame, &mut self.scratch, out)?;
537                return Ok(header);
538            }
539            Some(_) => Error::KeyRoleConflict(header.kid),
540            None => Error::UnknownKeyId(header.kid),
541        };
542        // No key to decrypt with. The decoy does the work a key would have done, so that this
543        // ciphertext is discarded like one that fails authentication (RFC 9605 section 4.4.4).
544        if let Some(decoy) = &mut self.decoy {
545            let start = out.len();
546            let _ = decoy.open(self.suite, frame, &mut self.scratch, out);
547            out[start..].zeroize();
548            out.truncate(start);
549        }
550        Err(refusal)
551    }
552
553    /// Parses the header of `ciphertext` as this context's configuration admits it.
554    pub(crate) fn decode_header(&self, ciphertext: &[u8]) -> Result<(Header, usize)> {
555        if self.config.allow_non_minimal_headers {
556            Header::decode_lenient(ciphertext)
557        } else {
558            Header::decode(ciphertext)
559        }
560    }
561
562    /// Decrypts with a key that is not in the store (yet), for the key-management helpers that
563    /// derive a key on demand and keep it only once a ciphertext has authenticated with it.
564    pub(crate) fn decrypt_with(
565        &mut self,
566        key: &mut KeyContext,
567        header: Header,
568        header_len: usize,
569        metadata: &[u8],
570        ciphertext: &[u8],
571        out: &mut Vec<u8>,
572    ) -> Result<()> {
573        key.open(
574            self.suite,
575            Frame::new(header, header_len, ciphertext, metadata),
576            &mut self.scratch,
577            out,
578        )
579    }
580
581    /// Adds the outcome of one decryption to the statistics.
582    pub(crate) fn count<T>(&mut self, result: &Result<T>) {
583        let counter = match result {
584            Ok(_) => &mut self.stats.decrypted,
585            Err(Error::TruncatedHeader | Error::NonMinimalHeader | Error::TruncatedCiphertext) => {
586                &mut self.stats.syntax_errors
587            }
588            Err(Error::UnknownKeyId(_) | Error::KeyRoleConflict(_)) => {
589                &mut self.stats.unknown_key_ids
590            }
591            Err(Error::AuthenticationFailed) => &mut self.stats.authentication_failures,
592            Err(Error::Replayed { .. }) => &mut self.stats.replays,
593            Err(_) => return,
594        };
595        *counter = counter.saturating_add(1);
596    }
597}
598
599impl std::fmt::Debug for SFrameContext {
600    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
601        formatter
602            .debug_struct("SFrameContext")
603            .field("suite", &self.suite)
604            .field("config", &self.config)
605            .field("keys", &self.keys.len())
606            .field("stats", &self.stats)
607            .finish_non_exhaustive()
608    }
609}