Skip to main content

rtci_sframe/
mls.rs

1//! SFrame keyed from MLS (RFC 9605 section 5.2). No MLS here: the application runs MLS and
2//! hands over each epoch's exported secret.
3
4use std::collections::HashMap;
5use std::sync::Arc;
6
7use crypto::{RTCCryptoProvider, SecretVec, constant_time_eq};
8
9use crate::cipher_suite::CipherSuite;
10use crate::context::{KeyContext, SFrameConfig, SFrameContext};
11use crate::error::{Error, Result};
12use crate::header::Header;
13use crate::key_id::MlsKeyIdLayout;
14
15/// The label of the MLS exporter call that yields an epoch's SFrame `base_key`:
16/// `base_key = MLS-Exporter("SFrame 1.0 Base Key", "", AEAD.Nk)`, with `AEAD.Nk` being
17/// [`CipherSuite::key_len`].
18pub const MLS_EXPORTER_LABEL: &str = "SFrame 1.0 Base Key";
19
20/// The number of derived keys an [`MlsContext`] holds unless told otherwise.
21pub const DEFAULT_MAX_MLS_KEYS: usize = 4096;
22
23/// What a KID's low epoch bits currently stand for.
24struct EpochSlot {
25    /// The newest epoch introduced with these low bits.
26    epoch: u64,
27    /// Its exported secret; `None` once the epoch has been removed.
28    base_key: Option<SecretVec>,
29}
30
31/// An SFrame context keyed by MLS epochs.
32///
33/// Every member derives its keys from the epoch's exported secret and its own KIDs
34/// ([`MlsKeyIdLayout`]): the KIDs with this member's index encrypt, all the others decrypt.
35/// Keys are derived on demand. A decryption key is kept only once a ciphertext has
36/// authenticated with it, so forged KIDs do not fill the store.
37///
38/// A new epoch whose low `E` bits equal an older one's replaces it, with every key derived
39/// from the older one (RFC 9605 section 5.2). An epoch at or below one already introduced with
40/// the same low bits is refused, so a removed epoch cannot come back with its counters at 0.
41pub struct MlsContext {
42    context: SFrameContext,
43    layout: MlsKeyIdLayout,
44    sender_index: u64,
45    slots: HashMap<u64, EpochSlot>,
46    max_keys: usize,
47}
48
49impl MlsContext {
50    /// A context for the member at `sender_index` of the MLS group, with no epoch yet.
51    ///
52    /// Fails with [`Error::KeyIdLayout`] when the index does not fit the layout's `S` bits.
53    pub fn new(
54        suite: CipherSuite,
55        provider: Arc<dyn RTCCryptoProvider>,
56        layout: MlsKeyIdLayout,
57        sender_index: u64,
58    ) -> Result<Self> {
59        Self::with_config(
60            suite,
61            provider,
62            layout,
63            sender_index,
64            SFrameConfig::default(),
65        )
66    }
67
68    /// [`new`](Self::new) with explicit options for the underlying [`SFrameContext`].
69    pub fn with_config(
70        suite: CipherSuite,
71        provider: Arc<dyn RTCCryptoProvider>,
72        layout: MlsKeyIdLayout,
73        sender_index: u64,
74        config: SFrameConfig,
75    ) -> Result<Self> {
76        // Validates the index against the layout.
77        layout.key_id(0, sender_index, 0)?;
78        Ok(Self {
79            context: SFrameContext::with_config(suite, provider, config),
80            layout,
81            sender_index,
82            slots: HashMap::new(),
83            max_keys: DEFAULT_MAX_MLS_KEYS,
84        })
85    }
86
87    /// Sets how many derived keys the context holds at most. Beyond it, a KID that needs a new
88    /// key fails with [`Error::TooManyKeys`] until an epoch is replaced or removed.
89    pub fn set_max_keys(&mut self, max_keys: usize) {
90        self.max_keys = max_keys;
91    }
92
93    /// The KID layout.
94    #[must_use]
95    pub fn layout(&self) -> MlsKeyIdLayout {
96        self.layout
97    }
98
99    /// This member's index in the MLS group.
100    #[must_use]
101    pub fn sender_index(&self) -> u64 {
102        self.sender_index
103    }
104
105    /// The underlying context: its cipher suite, statistics and stored keys.
106    #[must_use]
107    pub fn context(&self) -> &SFrameContext {
108        &self.context
109    }
110
111    /// Whether `epoch` has been introduced and not removed or replaced.
112    #[must_use]
113    pub fn has_epoch(&self, epoch: u64) -> bool {
114        self.secret(epoch).is_some()
115    }
116
117    fn secret(&self, epoch: u64) -> Option<&SecretVec> {
118        let slot = self.slots.get(&self.layout.epoch_slot(epoch))?;
119        if slot.epoch == epoch {
120            slot.base_key.as_ref()
121        } else {
122            None
123        }
124    }
125
126    /// Removes every key derived for the epoch that `slot` stood for.
127    fn purge(&mut self, slot: u64) {
128        let layout = self.layout;
129        self.context
130            .retain_keys(|kid| layout.epoch_slot(kid) != slot);
131    }
132
133    /// Introduces `epoch` with its exported secret (see [`MLS_EXPORTER_LABEL`]).
134    ///
135    /// An older epoch with the same low `E` bits is removed, with all its keys. Introducing an
136    /// epoch again with the same secret changes nothing. Fails with [`Error::StaleEpoch`] when
137    /// `epoch` is older than the one its low bits already stand for, was removed, or comes with
138    /// another secret than before.
139    pub fn add_epoch(&mut self, epoch: u64, base_key: &[u8]) -> Result<()> {
140        if base_key.is_empty() {
141            return Err(Error::EmptyBaseKey);
142        }
143        let slot = self.layout.epoch_slot(epoch);
144        if let Some(current) = self.slots.get(&slot) {
145            if current.epoch > epoch {
146                return Err(Error::StaleEpoch(epoch));
147            }
148            if current.epoch == epoch {
149                return match &current.base_key {
150                    Some(known) if constant_time_eq(known.as_ref(), base_key) => Ok(()),
151                    _ => Err(Error::StaleEpoch(epoch)),
152                };
153            }
154            self.purge(slot);
155        }
156        self.slots.insert(
157            slot,
158            EpochSlot {
159                epoch,
160                base_key: Some(SecretVec::new(base_key.to_vec())),
161            },
162        );
163        Ok(())
164    }
165
166    /// Removes `epoch`, its secret and every key derived from it. Returns whether it was
167    /// there. The epoch cannot be introduced again.
168    pub fn remove_epoch(&mut self, epoch: u64) -> bool {
169        let slot = self.layout.epoch_slot(epoch);
170        match self.slots.get_mut(&slot) {
171            Some(current) if current.epoch == epoch && current.base_key.is_some() => {
172                current.base_key = None;
173                self.purge(slot);
174                true
175            }
176            _ => false,
177        }
178    }
179
180    /// The KID this member sends with in `epoch` for its `context` value.
181    pub fn key_id(&self, epoch: u64, context: u64) -> Result<u64> {
182        self.layout.key_id(epoch, self.sender_index, context)
183    }
184
185    /// Encrypts `plaintext` as this member in `epoch`, under the KID of `context`, and returns
186    /// the SFrame ciphertext. Fails with [`Error::UnknownEpoch`] when the epoch is not held.
187    pub fn encrypt(
188        &mut self,
189        epoch: u64,
190        context: u64,
191        metadata: &[u8],
192        plaintext: &[u8],
193    ) -> Result<Vec<u8>> {
194        let mut out = Vec::with_capacity(plaintext.len() + self.context.max_overhead());
195        self.encrypt_into(epoch, context, metadata, plaintext, &mut out)?;
196        Ok(out)
197    }
198
199    /// [`encrypt`](Self::encrypt), appending the ciphertext to `out`.
200    pub fn encrypt_into(
201        &mut self,
202        epoch: u64,
203        context: u64,
204        metadata: &[u8],
205        plaintext: &[u8],
206        out: &mut Vec<u8>,
207    ) -> Result<Header> {
208        let kid = self.key_id(epoch, context)?;
209        if self.context.key_usage(kid).is_none() {
210            let slot = self.slots.get(&self.layout.epoch_slot(epoch));
211            let Some(base_key) = slot
212                .filter(|slot| slot.epoch == epoch)
213                .and_then(|slot| slot.base_key.as_ref())
214            else {
215                return Err(Error::UnknownEpoch(epoch));
216            };
217            if self.context.key_count() >= self.max_keys {
218                return Err(Error::TooManyKeys);
219            }
220            self.context.add_send_key(kid, base_key.as_ref())?;
221        } else if !self.has_epoch(epoch) {
222            // The KID's low bits now stand for another epoch.
223            return Err(Error::UnknownEpoch(epoch));
224        }
225        self.context.encrypt_into(kid, metadata, plaintext, out)
226    }
227
228    /// Decrypts an SFrame ciphertext from another member and returns the plaintext.
229    ///
230    /// The key is found by the KID in the header: the epoch by its low `E` bits, the sender by
231    /// its index. A KID with this member's own index is refused
232    /// ([`Error::KeyRoleConflict`]): its keys encrypt only.
233    pub fn decrypt(&mut self, metadata: &[u8], ciphertext: &[u8]) -> Result<Vec<u8>> {
234        let mut out = Vec::with_capacity(ciphertext.len());
235        self.decrypt_into(metadata, ciphertext, &mut out)?;
236        Ok(out)
237    }
238
239    /// [`decrypt`](Self::decrypt), appending the plaintext to `out`. On an error `out` is as it
240    /// was.
241    pub fn decrypt_into(
242        &mut self,
243        metadata: &[u8],
244        ciphertext: &[u8],
245        out: &mut Vec<u8>,
246    ) -> Result<Header> {
247        if let Ok((header, _)) = self.context.decode_header(ciphertext)
248            && self.context.key_usage(header.kid).is_some()
249        {
250            return self.context.decrypt_into(metadata, ciphertext, out);
251        }
252        let result = self.decrypt_on_demand(metadata, ciphertext, out);
253        self.context.count(&result);
254        result
255    }
256
257    /// Decrypts with a key derived for the occasion, and stores the key if the ciphertext
258    /// authenticated.
259    fn decrypt_on_demand(
260        &mut self,
261        metadata: &[u8],
262        ciphertext: &[u8],
263        out: &mut Vec<u8>,
264    ) -> Result<Header> {
265        let (header, header_len) = self.context.decode_header(ciphertext)?;
266        let parts = self.layout.split(header.kid);
267        if parts.sender_index == self.sender_index {
268            return Err(Error::KeyRoleConflict(header.kid));
269        }
270        let Some(base_key) = self
271            .slots
272            .get(&parts.epoch)
273            .and_then(|slot| slot.base_key.as_ref())
274        else {
275            return Err(Error::UnknownKeyId(header.kid));
276        };
277        if self.context.key_count() >= self.max_keys {
278            return Err(Error::TooManyKeys);
279        }
280        let mut key = KeyContext::derive_recv(
281            self.context.provider().crypto(),
282            self.context.cipher_suite(),
283            header.kid,
284            base_key.as_ref(),
285            self.context.config().replay_window,
286        )?;
287        self.context
288            .decrypt_with(&mut key, header, header_len, metadata, ciphertext, out)?;
289        self.context.insert_key(header.kid, key);
290        Ok(header)
291    }
292}
293
294impl std::fmt::Debug for MlsContext {
295    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
296        formatter
297            .debug_struct("MlsContext")
298            .field("context", &self.context)
299            .field("layout", &self.layout)
300            .field("sender_index", &self.sender_index)
301            .field("epochs", &self.slots.len())
302            .finish_non_exhaustive()
303    }
304}