Skip to main content

sew_e2ee/
recorder.rs

1//! The recorder key handoff.
2//!
3//! A consenting device seals its **own** frame IKM of an epoch to the recorder's per-recording
4//! X25519 key:
5//!
6//! ```text
7//! info = "sew call recorder release v1" ‖ TLS(ReleaseInfo{ call_id, recording_id, group_id,
8//!                                                     epoch, uint32 leaf_index, uint8 slot,
9//!                                                     sender_identity })
10//! (enc, ct) = HPKE.SealBase(pkR = hpke_pub, info, aad = "", pt = ikm_self(e))   // 32 + 48 bytes
11//! ```
12//!
13//! The recorder rebuilds `info` from its **own** `call_id` and `recording_id` and the
14//! release's other fields, so a release for another call, recording, group, epoch, leaf, slot or
15//! sender fails AEAD.
16
17use std::fmt;
18
19use openmls_traits::crypto::OpenMlsCrypto;
20use openmls_traits::types::{HpkeAeadType, HpkeCiphertext, HpkeConfig, HpkeKdfType, HpkeKemType};
21use rand::{CryptoRng, RngCore};
22use sew_mls_crypto::MlsCrypto;
23use sew_proto::e2ee::Release;
24use sew_proto::e2ee::tls::{RecorderCert, RecorderCertTbs, ReleaseInfo, TlsCodec};
25use zeroize::Zeroizing;
26
27use crate::config::caps;
28use crate::error::ReleaseError;
29use crate::identity::cert::verify_recorder_cert_sig;
30use crate::ids::{Epoch, LkIdentity, RoomName, Slot, UnixMs, install_id_bytes};
31use crate::keys::FrameIkm;
32
33/// DHKEM(X25519), HKDF-SHA256, AES-128-GCM.
34pub const RELEASE_HPKE: HpkeConfig = HpkeConfig(
35    HpkeKemType::DhKem25519,
36    HpkeKdfType::HkdfSha256,
37    HpkeAeadType::AesGcm128,
38);
39
40/// The longest a recorder certificate may be valid (24 h).
41pub const RECORDER_CERT_MAX_S: u64 = 24 * 3600;
42
43/// Why a recorder announcement was refused (no release is ever sent for it).
44#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
45#[non_exhaustive]
46pub enum RecorderCertError {
47    /// Malformed or over the size cap.
48    #[error("recorder certificate: decode")]
49    Decode,
50    /// The CA signature does not verify under the pin.
51    #[error("recorder certificate: signature")]
52    Signature,
53    /// Another install, call, recording or HPKE key than announced.
54    #[error("recorder certificate: binding ({0})")]
55    Binding(&'static str),
56    /// Outside its validity (or valid for more than 24 h).
57    #[error("recorder certificate: validity")]
58    Validity,
59}
60
61/// Verifies a recorder certificate against the announcement (the certificate's first condition).
62pub fn verify_recorder_cert(
63    bytes: &[u8],
64    ca_public: &[u8; 32],
65    install_id: u64,
66    call_id: &RoomName,
67    recording_id: u64,
68    hpke_pub: &[u8; 32],
69    now: UnixMs,
70) -> Result<RecorderCertTbs, RecorderCertError> {
71    if bytes.len() > caps::RECORDER_CERT {
72        return Err(RecorderCertError::Decode);
73    }
74    let cert = RecorderCert::from_bytes(bytes).map_err(|_| RecorderCertError::Decode)?;
75    if !verify_recorder_cert_sig(ca_public, &cert) {
76        return Err(RecorderCertError::Signature);
77    }
78    let t = cert.tbs;
79    if t.install_id != install_id_bytes(install_id) {
80        return Err(RecorderCertError::Binding("install"));
81    }
82    if t.call_id != call_id.as_str().as_bytes() {
83        return Err(RecorderCertError::Binding("call_id"));
84    }
85    if t.recording_id != recording_id {
86        return Err(RecorderCertError::Binding("recording_id"));
87    }
88    if &t.hpke_pub != hpke_pub {
89        return Err(RecorderCertError::Binding("hpke_pub"));
90    }
91    let now_s = now / 1000;
92    if now_s < t.not_before
93        || now_s > t.not_after
94        || t.not_after.saturating_sub(t.not_before) > RECORDER_CERT_MAX_S
95    {
96        return Err(RecorderCertError::Validity);
97    }
98    Ok(t)
99}
100
101/// Seals `ikm` for a recorder: `(enc, ct)` (32 and 48 bytes). `None` if HPKE fails.
102pub fn seal_release(
103    hpke_pub: &[u8; 32],
104    info: &ReleaseInfo,
105    ikm: &FrameIkm,
106) -> Option<(Vec<u8>, Vec<u8>)> {
107    let info = info.info().ok()?;
108    let ct = MlsCrypto::default()
109        .hpke_seal(RELEASE_HPKE, hpke_pub, &info, b"", ikm.expose())
110        .ok()?;
111    let enc = ct.kem_output.as_slice().to_vec();
112    let ct = ct.ciphertext.as_slice().to_vec();
113    if enc.len() != caps::RELEASE_ENC || ct.len() != caps::RELEASE_CT {
114        return None;
115    }
116    Some((enc, ct))
117}
118
119/// An opened release.
120#[derive(Debug)]
121pub struct Released {
122    /// The sender's engine identity.
123    pub identity: LkIdentity,
124    /// The sender's leaf index in `epoch`.
125    pub leaf: u32,
126    /// The epoch.
127    pub epoch: Epoch,
128    /// `slot(epoch)`.
129    pub slot: Slot,
130    /// The sender's frame IKM.
131    pub ikm: FrameIkm,
132}
133
134/// The recorder's side: opens relayed releases with the per-recording key.
135pub struct ReleaseOpener {
136    sk: Zeroizing<[u8; 32]>,
137    call_id: RoomName,
138    recording_id: u64,
139}
140
141impl fmt::Debug for ReleaseOpener {
142    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143        f.debug_struct("ReleaseOpener")
144            .field("call_id", &self.call_id)
145            .field("recording_id", &self.recording_id)
146            .finish_non_exhaustive()
147    }
148}
149
150impl ReleaseOpener {
151    /// An opener for one recording of one call.
152    pub fn new(call_id: RoomName, recording_id: u64, hpke_sk: Zeroizing<[u8; 32]>) -> Self {
153        ReleaseOpener {
154            sk: hpke_sk,
155            call_id,
156            recording_id,
157        }
158    }
159
160    /// Opens `r` (the server's relayed `Release`). The `info` is rebuilt from the opener's own
161    /// `call_id` and `recording_id` and the release's `group_id`, `epoch`, `leaf`, `slot` and
162    /// `sender_identity`; sizes are checked first.
163    pub fn open(&self, r: &Release) -> Result<Released, ReleaseError> {
164        if r.enc.len() != caps::RELEASE_ENC || r.ct.len() != caps::RELEASE_CT {
165            return Err(ReleaseError::Sizes);
166        }
167        let slot = Slot::new(r.slot).ok_or(ReleaseError::Malformed("slot"))?;
168        let info = ReleaseInfo {
169            call_id: self.call_id.as_str().as_bytes().to_vec(),
170            recording_id: self.recording_id,
171            group_id: r.group_id.as_bytes().to_vec(),
172            epoch: r.epoch,
173            leaf_index: r.leaf,
174            slot: r.slot,
175            sender_identity: r.sender_identity.as_str().as_bytes().to_vec(),
176        };
177        let info = info.info().map_err(|_| ReleaseError::Malformed("info"))?;
178        let input = HpkeCiphertext {
179            kem_output: r.enc.as_bytes().to_vec().into(),
180            ciphertext: r.ct.as_bytes().to_vec().into(),
181        };
182        let pt = MlsCrypto::default()
183            .hpke_open(RELEASE_HPKE, &input, self.sk.as_slice(), &info, b"")
184            .map_err(|_| ReleaseError::Aead)?;
185        let pt = Zeroizing::new(pt);
186        let ikm = FrameIkm::from_bytes(
187            <[u8; 32]>::try_from(pt.as_slice()).map_err(|_| ReleaseError::Aead)?,
188        );
189        Ok(Released {
190            identity: r.sender_identity.clone(),
191            leaf: r.leaf,
192            epoch: r.epoch,
193            slot,
194            ikm,
195        })
196    }
197
198    /// The call.
199    pub fn call_id(&self) -> &RoomName {
200        &self.call_id
201    }
202
203    /// The recording.
204    pub fn recording_id(&self) -> u64 {
205        self.recording_id
206    }
207}
208
209/// The recorder's per-recording X25519 key pair. The public key goes into the
210/// `RecorderCert` through the server.
211pub struct RecorderKeyPair {
212    sk: Zeroizing<[u8; 32]>,
213    pk: [u8; 32],
214    call_id: RoomName,
215    recording_id: u64,
216}
217
218impl fmt::Debug for RecorderKeyPair {
219    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220        f.debug_struct("RecorderKeyPair")
221            .field("call_id", &self.call_id)
222            .field("recording_id", &self.recording_id)
223            .finish_non_exhaustive()
224    }
225}
226
227impl RecorderKeyPair {
228    /// A fresh key pair (HPKE `DeriveKeyPair` from 32 random bytes).
229    pub fn generate<R: RngCore + CryptoRng>(
230        call_id: RoomName,
231        recording_id: u64,
232        rng: &mut R,
233    ) -> RecorderKeyPair {
234        loop {
235            let mut ikm = Zeroizing::new([0u8; 32]);
236            rng.fill_bytes(ikm.as_mut());
237            if let Ok(kp) = MlsCrypto::default().derive_hpke_keypair(RELEASE_HPKE, ikm.as_slice())
238                && kp.public.len() == 32
239                && kp.private.len() == 32
240            {
241                let mut sk = Zeroizing::new([0u8; 32]);
242                sk.copy_from_slice(&kp.private);
243                let mut pk = [0u8; 32];
244                pk.copy_from_slice(&kp.public);
245                return RecorderKeyPair {
246                    sk,
247                    pk,
248                    call_id,
249                    recording_id,
250                };
251            }
252        }
253    }
254
255    /// The public key (`RecorderCert.hpke_pub`).
256    pub fn public_key(&self) -> [u8; 32] {
257        self.pk
258    }
259
260    /// Test hook: the secret key (tests search logs for it).
261    #[cfg(feature = "testing")]
262    pub fn secret_for_test(&self) -> [u8; 32] {
263        *self.sk
264    }
265
266    /// The opener for this recording.
267    pub fn into_opener(self) -> ReleaseOpener {
268        ReleaseOpener::new(self.call_id, self.recording_id, self.sk)
269    }
270}