Skip to main content

rtci_sframe/
sender_key.rs

1//! The sender-keys scheme of RFC 9605 section 5.1: each sender distributes its own `base_key`
2//! over an end-to-end secure channel, and ratchets it forward for forward secrecy.
3
4use std::collections::VecDeque;
5use std::sync::Arc;
6
7use crypto::{RTCCryptoProvider, SecretVec};
8
9use crate::cipher_suite::CipherSuite;
10use crate::context::{KeyContext, SFrameConfig, SFrameContext};
11use crate::error::{Error, Result};
12use crate::header::Header;
13use crate::kdf::ratchet_base_key;
14use crate::key_id::SenderKeyIdLayout;
15
16/// How many ratchet steps a [`SenderKeyReceiver`] follows for one ciphertext unless told
17/// otherwise.
18pub const DEFAULT_MAX_RATCHET_STEPS: u64 = 8;
19
20/// How many keys older than the current one a [`SenderKeyReceiver`] keeps unless told
21/// otherwise.
22pub const DEFAULT_RETAINED_OLD_KEYS: usize = 2;
23
24/// One sender's key at a point of its ratchet: the key generation, the ratchet step and the
25/// `base_key` there.
26///
27/// The sender holds one and [`advance`](Self::advance)s it, installing each new `base_key`
28/// under the new KID as its encryption key and removing the previous one. A receiver gets the
29/// sender's current `base_key` and KID over the secure channel and follows with a
30/// [`SenderKeyReceiver`].
31pub struct SenderKeyRatchet {
32    suite: CipherSuite,
33    provider: Arc<dyn RTCCryptoProvider>,
34    layout: SenderKeyIdLayout,
35    key_generation: u64,
36    ratchet_step: u64,
37    base_key: SecretVec,
38}
39
40impl SenderKeyRatchet {
41    /// A freshly distributed key: generation `key_generation`, ratchet step 0.
42    pub fn new(
43        suite: CipherSuite,
44        provider: Arc<dyn RTCCryptoProvider>,
45        layout: SenderKeyIdLayout,
46        key_generation: u64,
47        base_key: &[u8],
48    ) -> Result<Self> {
49        let kid = layout.key_id(key_generation, 0)?;
50        Self::at_key_id(suite, provider, layout, kid, base_key)
51    }
52
53    /// The key a sender is at when it uses `kid`, as a participant joining mid-session learns
54    /// it: the sender's current `base_key` together with its current KID.
55    ///
56    /// The KID carries only the low bits of the ratchet step; they are all a receiver needs to
57    /// follow.
58    pub fn at_key_id(
59        suite: CipherSuite,
60        provider: Arc<dyn RTCCryptoProvider>,
61        layout: SenderKeyIdLayout,
62        kid: u64,
63        base_key: &[u8],
64    ) -> Result<Self> {
65        if base_key.is_empty() {
66            return Err(Error::EmptyBaseKey);
67        }
68        let parts = layout.split(kid);
69        Ok(Self {
70            suite,
71            provider,
72            layout,
73            key_generation: parts.key_generation,
74            ratchet_step: parts.ratchet_step,
75            base_key: SecretVec::new(base_key.to_vec()),
76        })
77    }
78
79    /// The KID layout.
80    #[must_use]
81    pub fn layout(&self) -> SenderKeyIdLayout {
82        self.layout
83    }
84
85    /// The key generation.
86    #[must_use]
87    pub fn key_generation(&self) -> u64 {
88        self.key_generation
89    }
90
91    /// The ratchet step. After [`at_key_id`](Self::at_key_id) it counts from the low bits the
92    /// KID carried.
93    #[must_use]
94    pub fn ratchet_step(&self) -> u64 {
95        self.ratchet_step
96    }
97
98    /// The KID of the current key.
99    #[must_use]
100    pub fn key_id(&self) -> u64 {
101        // The generation came out of a KID of this layout, so it fits its field.
102        self.layout.compose(self.key_generation, self.ratchet_step)
103    }
104
105    /// The current `base_key`: what goes into the SFrame context under
106    /// [`key_id`](Self::key_id), and what a new participant is sent.
107    #[must_use]
108    pub fn base_key(&self) -> &[u8] {
109        self.base_key.as_ref()
110    }
111
112    /// Ratchets one step forward and returns the new KID. The previous `base_key` is erased.
113    pub fn advance(&mut self) -> Result<u64> {
114        let Some(next_step) = self.ratchet_step.checked_add(1) else {
115            return Err(Error::RatchetExhausted);
116        };
117        self.base_key =
118            ratchet_base_key(self.provider.crypto(), self.suite, self.base_key.as_ref())?;
119        self.ratchet_step = next_step;
120        Ok(self.key_id())
121    }
122
123    /// How many steps forward `kid` is from the current key, or `None` when it belongs to
124    /// another key generation (the sender distributed, or will distribute, a new key).
125    ///
126    /// The count is modulo `1 << R`: a KID from before the current step reads as far ahead. A
127    /// receiver therefore keeps its recent keys installed and bounds how far it follows.
128    #[must_use]
129    pub fn steps_to(&self, kid: u64) -> Option<u64> {
130        let parts = self.layout.split(kid);
131        (parts.key_generation == self.key_generation).then(|| {
132            self.layout
133                .steps_between(self.ratchet_step, parts.ratchet_step)
134        })
135    }
136}
137
138impl std::fmt::Debug for SenderKeyRatchet {
139    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
140        formatter
141            .debug_struct("SenderKeyRatchet")
142            .field("suite", &self.suite)
143            .field("layout", &self.layout)
144            .field("key_generation", &self.key_generation)
145            .field("ratchet_step", &self.ratchet_step)
146            .finish_non_exhaustive()
147    }
148}
149
150/// The receiving side of one sender in the sender-keys scheme.
151///
152/// It decrypts with the keys it holds, and when the sender signals a ratchet step by a KID with
153/// a higher step, derives the keys up to it. The KID is not authenticated until a key has been
154/// derived from it, so the ratchet moves only once a ciphertext has authenticated under the new
155/// key: a forged KID costs a bounded number of derivations and changes nothing.
156///
157/// Old keys stay for out-of-order delivery, a bounded number of them; an application that
158/// wants them gone sooner calls [`forget_old_keys`](Self::forget_old_keys).
159pub struct SenderKeyReceiver {
160    context: SFrameContext,
161    layout: SenderKeyIdLayout,
162    ratchet: Option<SenderKeyRatchet>,
163    /// The KIDs installed, oldest first; the last one is the current key's.
164    installed: VecDeque<u64>,
165    max_ratchet_steps: u64,
166    retained_old_keys: usize,
167}
168
169impl SenderKeyReceiver {
170    /// A receiver for one sender whose KIDs follow `layout`, with no key yet.
171    #[must_use]
172    pub fn new(
173        suite: CipherSuite,
174        provider: Arc<dyn RTCCryptoProvider>,
175        layout: SenderKeyIdLayout,
176    ) -> Self {
177        Self::with_config(suite, provider, layout, SFrameConfig::default())
178    }
179
180    /// [`new`](Self::new) with explicit options for the underlying [`SFrameContext`].
181    #[must_use]
182    pub fn with_config(
183        suite: CipherSuite,
184        provider: Arc<dyn RTCCryptoProvider>,
185        layout: SenderKeyIdLayout,
186        config: SFrameConfig,
187    ) -> Self {
188        Self {
189            context: SFrameContext::with_config(suite, provider, config),
190            layout,
191            ratchet: None,
192            installed: VecDeque::new(),
193            max_ratchet_steps: DEFAULT_MAX_RATCHET_STEPS,
194            retained_old_keys: DEFAULT_RETAINED_OLD_KEYS,
195        }
196    }
197
198    /// Sets how many ratchet steps one ciphertext may make the receiver follow. A KID further
199    /// ahead is treated as unknown.
200    pub fn set_max_ratchet_steps(&mut self, steps: u64) {
201        self.max_ratchet_steps = steps;
202    }
203
204    /// Sets how many keys older than the current one are kept for late ciphertexts.
205    pub fn set_retained_old_keys(&mut self, keys: usize) {
206        self.retained_old_keys = keys;
207        self.prune();
208    }
209
210    /// The underlying context: its cipher suite, statistics and stored keys.
211    #[must_use]
212    pub fn context(&self) -> &SFrameContext {
213        &self.context
214    }
215
216    /// The KID of the newest key held, if any.
217    #[must_use]
218    pub fn current_key_id(&self) -> Option<u64> {
219        self.ratchet.as_ref().map(SenderKeyRatchet::key_id)
220    }
221
222    /// Installs the `base_key` the sender distributed, for the KID it is used under: the first
223    /// key, a new key generation, or the current key of a session joined midway.
224    pub fn set_key(&mut self, kid: u64, base_key: &[u8]) -> Result<()> {
225        let ratchet = SenderKeyRatchet::at_key_id(
226            self.context.cipher_suite(),
227            self.context.provider().clone(),
228            self.layout,
229            kid,
230            base_key,
231        )?;
232        self.context.add_recv_key(kid, base_key)?;
233        self.ratchet = Some(ratchet);
234        self.note_installed(kid);
235        Ok(())
236    }
237
238    /// Removes every key but the current one.
239    pub fn forget_old_keys(&mut self) {
240        while self.installed.len() > 1 {
241            if let Some(kid) = self.installed.pop_front() {
242                self.context.remove_key(kid);
243            }
244        }
245    }
246
247    fn note_installed(&mut self, kid: u64) {
248        self.installed.retain(|installed| *installed != kid);
249        self.installed.push_back(kid);
250        self.prune();
251    }
252
253    fn prune(&mut self) {
254        while self.installed.len() > self.retained_old_keys.saturating_add(1) {
255            if let Some(kid) = self.installed.pop_front() {
256                self.context.remove_key(kid);
257            }
258        }
259    }
260
261    /// Decrypts an SFrame ciphertext from this sender and returns the plaintext.
262    pub fn decrypt(&mut self, metadata: &[u8], ciphertext: &[u8]) -> Result<Vec<u8>> {
263        let mut out = Vec::with_capacity(ciphertext.len());
264        self.decrypt_into(metadata, ciphertext, &mut out)?;
265        Ok(out)
266    }
267
268    /// [`decrypt`](Self::decrypt), appending the plaintext to `out`. On an error `out` is as it
269    /// was.
270    pub fn decrypt_into(
271        &mut self,
272        metadata: &[u8],
273        ciphertext: &[u8],
274        out: &mut Vec<u8>,
275    ) -> Result<Header> {
276        let result = self.decrypt_uncounted(metadata, ciphertext, out);
277        self.context.count(&result);
278        result
279    }
280
281    fn decrypt_uncounted(
282        &mut self,
283        metadata: &[u8],
284        ciphertext: &[u8],
285        out: &mut Vec<u8>,
286    ) -> Result<Header> {
287        let (header, _) = self.context.decode_header(ciphertext)?;
288        if self.context.key_usage(header.kid).is_some() {
289            let result = self.context.decrypt_uncounted(metadata, ciphertext, out);
290            // KIDs repeat every `1 << R` steps: a key that fails to authenticate may be an old
291            // one whose KID the sender has come round to again.
292            if result != Err(Error::AuthenticationFailed) || !self.is_ahead(header.kid) {
293                return result;
294            }
295        }
296        self.decrypt_ratcheting(metadata, ciphertext, out)
297    }
298
299    /// Whether `kid` is a step the receiver would follow the ratchet to.
300    fn is_ahead(&self, kid: u64) -> bool {
301        self.ratchet
302            .as_ref()
303            .and_then(|ratchet| ratchet.steps_to(kid))
304            .is_some_and(|steps| (1..=self.max_ratchet_steps).contains(&steps))
305    }
306
307    /// Decrypts a ciphertext whose KID is ahead of the current key, and moves the ratchet there
308    /// if it authenticated.
309    fn decrypt_ratcheting(
310        &mut self,
311        metadata: &[u8],
312        ciphertext: &[u8],
313        out: &mut Vec<u8>,
314    ) -> Result<Header> {
315        let (header, header_len) = self.context.decode_header(ciphertext)?;
316        let unknown = Error::UnknownKeyId(header.kid);
317        if !self.is_ahead(header.kid) {
318            return Err(unknown);
319        }
320        let Some(ratchet) = &self.ratchet else {
321            return Err(unknown);
322        };
323        let Some(steps) = ratchet.steps_to(header.kid) else {
324            return Err(unknown);
325        };
326
327        // Derive ahead on a copy: the ratchet itself moves only on success.
328        let mut ahead = SenderKeyRatchet::at_key_id(
329            ratchet.suite,
330            ratchet.provider.clone(),
331            ratchet.layout,
332            ratchet.key_id(),
333            ratchet.base_key(),
334        )?;
335        let mut passed: Vec<(u64, SecretVec)> = Vec::new();
336        for step in 1..=steps {
337            let kid = ahead.advance()?;
338            if step < steps {
339                passed.push((kid, SecretVec::new(ahead.base_key().to_vec())));
340            }
341        }
342        if ahead.key_id() != header.kid {
343            return Err(unknown);
344        }
345
346        let mut key = KeyContext::derive_recv(
347            self.context.provider().crypto(),
348            self.context.cipher_suite(),
349            header.kid,
350            ahead.base_key(),
351            self.context.config().replay_window,
352        )?;
353        self.context
354            .decrypt_with(&mut key, header, header_len, metadata, ciphertext, out)?;
355
356        // Authentic: the sender is at this step. Keep the keys of the steps passed over too,
357        // for ciphertexts of theirs still on the way. The plaintext is already in `out`, so a
358        // key that cannot be installed is left out rather than reported.
359        for (kid, base_key) in passed {
360            if self.context.add_recv_key(kid, base_key.as_ref()).is_ok() {
361                self.note_installed(kid);
362            }
363        }
364        self.context.insert_key(header.kid, key);
365        self.note_installed(header.kid);
366        self.ratchet = Some(ahead);
367        Ok(header)
368    }
369}
370
371impl std::fmt::Debug for SenderKeyReceiver {
372    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
373        formatter
374            .debug_struct("SenderKeyReceiver")
375            .field("context", &self.context)
376            .field("layout", &self.layout)
377            .field("ratchet", &self.ratchet)
378            .finish_non_exhaustive()
379    }
380}