Skip to main content

zaun_community_protocol/crypto/voice/
sender.rs

1//! Sender keys: a fresh SFrame base key per epoch, wrapped to each other participant with HPKE
2//! (RFC 9180 base mode; X-Wing, HKDF-SHA256, AES-256-GCM), and one `VoiceSenderKeys` message
3//! (ctx `zaun/v1/voice-sender-keys`) that binds the wrapped keys to the sender's member key.
4//!
5//! HPKE base mode does not authenticate the sender, and X-Wing has no authenticated mode, so
6//! anyone holding a recipient's public key (the relaying host included) could wrap a key of its
7//! own. The sender therefore signs, once per epoch, `SHA3-256` of every wrapped key it made,
8//! with the recipient it was made for. A recipient opens only a wrapped key whose hash the
9//! sender signed for it. One signature per epoch, not per recipient, keeps a rekey small.
10//!
11//! `VoiceSenderKeys`:
12//!
13//! | # | Field | Encoding |
14//! |---|---|---|
15//! | 1 | format | `u8` = `0x01` |
16//! | 2 | suite | `u8` = [`SUITE_V1`] |
17//! | 3 | `community_id` | `bytes[32]` |
18//! | 4 | `channel_id` | `bytes[16]` |
19//! | 5 | `sender_member` | `bytes[16]` |
20//! | 6 | `sender_session` | `bytes[16]` |
21//! | 7 | `epoch` | `u32` |
22//! | 8 | `kid` | `u64`, [`kid_for`] of fields 6 and 7 |
23//! | 9 | `recipients` | `list<member bytes[16] ‖ session bytes[16] ‖ sha3 bytes[32]>`, ≤ [`MAX_RECIPIENTS`] |
24//! | 10 | `created_at` | `u64`, ms since the epoch |
25//!
26//! HPKE `info` = `"zaun/v1/voice-sender-key"` ‖ suite ‖ community ‖ channel ‖ sender member ‖
27//! sender session ‖ epoch ‖ recipient member ‖ recipient session; `aad` = `SHA3-256` of the
28//! recipient's key package bytes, so a key opens only for the exact package it was made for.
29
30use std::collections::BTreeSet;
31use std::fmt;
32
33use hpke::aead::AesGcm256;
34use hpke::kdf::HkdfSha256;
35use hpke::kem::XWing;
36use hpke::{Deserializable, Kem, OpModeR, OpModeS, Serializable};
37use zeroize::Zeroizing;
38
39use super::identity::VoiceIdentity;
40use super::package::SignedKeyPackage;
41use super::rng::Predrawn;
42use super::session::VoiceSessionId;
43use super::sframe::kid_for;
44use super::{
45    BASE_KEY_LEN, KEM_CIPHERTEXT_LEN, MAX_RECIPIENTS, SENDER_KEYS_BYTES_MAX, SENDER_KEYS_WIRE_MAX,
46    SUITE_V1, VoiceError, WRAPPED_KEY_LEN,
47};
48use crate::crypto::{Context, SecretKey, content_hash};
49use crate::encoding::{Decode, DecodeError, Encode, EncodeError, Reader, Writer};
50use crate::ids::{ChannelId, CommunityId, MemberId, fill_random};
51use crate::keys::{PublicKey, SIGNATURE_LEN, Signature};
52use crate::signed::{FORMAT_V1, Signed, SignedObject};
53
54const WRAP_LABEL: &[u8] = b"zaun/v1/voice-sender-key";
55
56/// An SFrame base key (32 bytes). Zeroized on drop, never printed, never on the wire unwrapped.
57pub struct SenderKey(Zeroizing<[u8; BASE_KEY_LEN]>);
58
59impl SenderKey {
60    /// A fresh base key from the OS CSPRNG.
61    ///
62    /// # Errors
63    /// [`VoiceError::Rng`] when the CSPRNG fails.
64    pub fn generate() -> Result<Self, VoiceError> {
65        let mut key = Zeroizing::new([0u8; BASE_KEY_LEN]);
66        fill_random(key.as_mut())?;
67        Ok(Self(key))
68    }
69
70    /// Wraps raw bytes. Tests only; real keys come from [`Self::generate`] or [`Self::unwrap`].
71    #[must_use]
72    pub fn from_bytes(bytes: &[u8; BASE_KEY_LEN]) -> Self {
73        Self(Zeroizing::new(*bytes))
74    }
75
76    pub(super) fn expose(&self) -> &[u8; BASE_KEY_LEN] {
77        &self.0
78    }
79
80    /// Wraps this key to `recipient`'s verified key package.
81    ///
82    /// # Errors
83    /// [`VoiceError::Mismatch`] when the package is for another community or channel,
84    /// [`VoiceError::Rng`], or [`VoiceError::Unwrap`] if HPKE fails.
85    pub fn wrap_for(
86        &self,
87        ctx: &WrapContext,
88        recipient: &SignedKeyPackage,
89    ) -> Result<WrappedKey, VoiceError> {
90        let p = recipient.package();
91        if p.community_id != ctx.community_id {
92            return Err(VoiceError::Mismatch("community_id"));
93        }
94        if p.channel_id != ctx.channel_id {
95            return Err(VoiceError::Mismatch("channel_id"));
96        }
97        let info = ctx.info(p.member_id, p.voice_session);
98        let aad = recipient.hash();
99        let mut rng = Predrawn::new()?;
100        let (enc, ct) = hpke::single_shot_seal_with_rng::<AesGcm256, HkdfSha256, XWing>(
101            &OpModeS::Base,
102            p.kem_public.key(),
103            &info,
104            self.expose(),
105            &aad,
106            &mut rng,
107        )
108        .map_err(|_| VoiceError::Unwrap)?;
109        let mut out = [0u8; WRAPPED_KEY_LEN];
110        out[..KEM_CIPHERTEXT_LEN].copy_from_slice(&enc.to_bytes());
111        if ct.len() != WRAPPED_KEY_LEN - KEM_CIPHERTEXT_LEN {
112            return Err(VoiceError::Length("wrapped key"));
113        }
114        out[KEM_CIPHERTEXT_LEN..].copy_from_slice(&ct);
115        Ok(WrappedKey(out))
116    }
117
118    /// Opens a key wrapped to `own` (this participant's package) with `identity`.
119    ///
120    /// The caller must already have checked the wrapped key against a verified
121    /// [`SignedSenderKeys`] ([`SignedSenderKeys::entry_for`]); [`super::GroupKeys`] does both.
122    ///
123    /// # Errors
124    /// [`VoiceError::Unwrap`] when the key was not made for this package and context.
125    pub fn unwrap(
126        identity: &VoiceIdentity,
127        ctx: &WrapContext,
128        own: &SignedKeyPackage,
129        wrapped: &WrappedKey,
130    ) -> Result<Self, VoiceError> {
131        let p = own.package();
132        if p.kem_public != *identity.public_key() {
133            return Err(VoiceError::Mismatch("kem_public"));
134        }
135        let (enc, ct) = wrapped.0.split_at(KEM_CIPHERTEXT_LEN);
136        let enc = <XWing as Kem>::EncappedKey::from_bytes(enc).map_err(|_| VoiceError::Unwrap)?;
137        let info = ctx.info(p.member_id, p.voice_session);
138        let plain = Zeroizing::new(
139            hpke::single_shot_open::<AesGcm256, HkdfSha256, XWing>(
140                &OpModeR::Base,
141                identity.secret(),
142                &enc,
143                &info,
144                ct,
145                &own.hash(),
146            )
147            .map_err(|_| VoiceError::Unwrap)?,
148        );
149        let key: [u8; BASE_KEY_LEN] = plain
150            .as_slice()
151            .try_into()
152            .map_err(|_| VoiceError::Unwrap)?;
153        Ok(Self(Zeroizing::new(key)))
154    }
155}
156
157impl fmt::Debug for SenderKey {
158    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159        f.write_str("SenderKey(<redacted>)")
160    }
161}
162
163/// Who wraps, for which channel and epoch: bound into the HPKE `info`.
164#[derive(Debug, Clone, Copy, PartialEq, Eq)]
165pub struct WrapContext {
166    /// The community.
167    pub community_id: CommunityId,
168    /// The voice channel.
169    pub channel_id: ChannelId,
170    /// The sender.
171    pub sender_member: MemberId,
172    /// The sender's voice session.
173    pub sender_session: VoiceSessionId,
174    /// The sender's epoch.
175    pub epoch: u32,
176}
177
178impl WrapContext {
179    fn info(&self, recipient: MemberId, recipient_session: VoiceSessionId) -> Vec<u8> {
180        let mut out = Vec::with_capacity(WRAP_LABEL.len() + 1 + 32 + 16 * 5 + 4);
181        out.extend_from_slice(WRAP_LABEL);
182        out.push(SUITE_V1);
183        out.extend_from_slice(self.community_id.as_bytes());
184        out.extend_from_slice(self.channel_id.as_bytes());
185        out.extend_from_slice(self.sender_member.as_bytes());
186        out.extend_from_slice(self.sender_session.as_bytes());
187        out.extend_from_slice(&self.epoch.to_be_bytes());
188        out.extend_from_slice(recipient.as_bytes());
189        out.extend_from_slice(recipient_session.as_bytes());
190        out
191    }
192}
193
194/// A base key wrapped to one recipient: X-Wing `enc` ‖ AES-256-GCM ciphertext ‖ tag.
195#[derive(Clone, PartialEq, Eq)]
196pub struct WrappedKey([u8; WRAPPED_KEY_LEN]);
197
198impl WrappedKey {
199    /// Parses the wire form.
200    ///
201    /// # Errors
202    /// [`VoiceError::Length`] unless exactly [`WRAPPED_KEY_LEN`] bytes.
203    pub fn from_bytes(bytes: &[u8]) -> Result<Self, VoiceError> {
204        bytes
205            .try_into()
206            .map(Self)
207            .map_err(|_| VoiceError::Length("wrapped key"))
208    }
209
210    /// The wire form.
211    #[must_use]
212    pub const fn as_bytes(&self) -> &[u8; WRAPPED_KEY_LEN] {
213        &self.0
214    }
215
216    /// `SHA3-256` of the wire form, as signed in [`SenderKeys`].
217    #[must_use]
218    pub fn hash(&self) -> [u8; 32] {
219        content_hash(&self.0)
220    }
221}
222
223impl fmt::Debug for WrappedKey {
224    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
225        write!(
226            f,
227            "WrappedKey(sha3:{})",
228            crate::b64::encode(&self.hash()[..8])
229        )
230    }
231}
232
233/// One recipient of a sender's epoch key.
234#[derive(Debug, Clone, Copy, PartialEq, Eq)]
235pub struct RecipientEntry {
236    /// The recipient.
237    pub member_id: MemberId,
238    /// The recipient's voice session.
239    pub voice_session: VoiceSessionId,
240    /// `SHA3-256` of the [`WrappedKey`] made for it.
241    pub wrapped_hash: [u8; 32],
242}
243
244/// The signed statement of one sender's epoch (see the module table).
245#[derive(Debug, Clone, PartialEq, Eq)]
246pub struct SenderKeys {
247    /// 2: the voice suite.
248    pub suite: u8,
249    /// 3: the community.
250    pub community_id: CommunityId,
251    /// 4: the voice channel.
252    pub channel_id: ChannelId,
253    /// 5: the sender; its member key signs.
254    pub sender_member: MemberId,
255    /// 6: the sender's voice session.
256    pub sender_session: VoiceSessionId,
257    /// 7: the epoch.
258    pub epoch: u32,
259    /// 8: the SFrame KID of this epoch.
260    pub kid: u64,
261    /// 9: the recipients, at most [`MAX_RECIPIENTS`], each once.
262    pub recipients: Vec<RecipientEntry>,
263    /// 10: ms since the epoch.
264    pub created_at: u64,
265}
266
267impl Encode for SenderKeys {
268    fn encode(&self, w: &mut Writer) -> Result<(), EncodeError> {
269        w.u8(FORMAT_V1);
270        w.u8(self.suite);
271        w.put(&self.community_id)?;
272        w.fixed(self.channel_id.as_bytes());
273        w.fixed(self.sender_member.as_bytes());
274        w.fixed(self.sender_session.as_bytes());
275        w.u32(self.epoch);
276        w.u64(self.kid);
277        w.list(&self.recipients, MAX_RECIPIENTS, |w, r| {
278            w.fixed(r.member_id.as_bytes());
279            w.fixed(r.voice_session.as_bytes());
280            w.fixed(&r.wrapped_hash);
281            Ok(())
282        })?;
283        w.u64(self.created_at);
284        Ok(())
285    }
286}
287
288impl Decode for SenderKeys {
289    fn decode(r: &mut Reader<'_>) -> Result<Self, DecodeError> {
290        let format = r.u8()?;
291        if format != FORMAT_V1 {
292            return Err(DecodeError::UnknownFormat(format));
293        }
294        let suite = r.u8()?;
295        if suite != SUITE_V1 {
296            return Err(DecodeError::Invalid("suite"));
297        }
298        let community_id = r.get()?;
299        let channel_id = ChannelId::from_bytes(r.array()?);
300        let sender_member = MemberId::from_bytes(r.array()?);
301        let sender_session = VoiceSessionId::from_bytes(r.array()?);
302        let epoch = r.u32()?;
303        let kid = r.u64()?;
304        let recipients = r.list(MAX_RECIPIENTS, |r| {
305            Ok(RecipientEntry {
306                member_id: MemberId::from_bytes(r.array()?),
307                voice_session: VoiceSessionId::from_bytes(r.array()?),
308                wrapped_hash: r.array()?,
309            })
310        })?;
311        if kid != kid_for(&sender_session, epoch) {
312            return Err(DecodeError::Invalid("kid"));
313        }
314        if !distinct(&recipients) {
315            return Err(DecodeError::Invalid("recipients"));
316        }
317        Ok(Self {
318            suite,
319            community_id,
320            channel_id,
321            sender_member,
322            sender_session,
323            epoch,
324            kid,
325            recipients,
326            created_at: r.u64()?,
327        })
328    }
329}
330
331fn distinct(recipients: &[RecipientEntry]) -> bool {
332    let mut seen = BTreeSet::new();
333    recipients.iter().all(|r| seen.insert(r.voice_session))
334}
335
336impl SignedObject for SenderKeys {
337    const CONTEXT: Context = Context::VoiceSenderKeys;
338}
339
340/// What a recipient expects of a sender-keys message.
341#[derive(Debug, Clone, PartialEq, Eq)]
342pub struct SenderKeysExpectation {
343    /// The community.
344    pub community_id: CommunityId,
345    /// The voice channel.
346    pub channel_id: ChannelId,
347    /// The sender the roster names; its member key verifies.
348    pub sender_member: MemberId,
349    /// The community's minimum signature suite (`0x01` today).
350    pub min_suite: u8,
351}
352
353/// A sender-keys message whose signature was made here or verified.
354#[derive(Debug, Clone, PartialEq, Eq)]
355pub struct SignedSenderKeys(Signed<SenderKeys>);
356
357impl SenderKeys {
358    /// Signs a sender's epoch over the wrapped keys it made.
359    ///
360    /// # Errors
361    /// [`VoiceError::Recipients`] for too many or repeated recipients; [`VoiceError::Signed`].
362    pub fn sign_epoch(
363        member_key: &SecretKey,
364        ctx: &WrapContext,
365        recipients: Vec<RecipientEntry>,
366        created_at: u64,
367    ) -> Result<SignedSenderKeys, VoiceError> {
368        if recipients.len() > MAX_RECIPIENTS || !distinct(&recipients) {
369            return Err(VoiceError::Recipients);
370        }
371        let keys = Self {
372            suite: SUITE_V1,
373            community_id: ctx.community_id,
374            channel_id: ctx.channel_id,
375            sender_member: ctx.sender_member,
376            sender_session: ctx.sender_session,
377            epoch: ctx.epoch,
378            kid: kid_for(&ctx.sender_session, ctx.epoch),
379            recipients,
380            created_at,
381        };
382        Ok(SignedSenderKeys(keys.sign(member_key)?))
383    }
384
385    /// Verifies a sender-keys message from the wire under the sender's member key.
386    ///
387    /// # Errors
388    /// [`VoiceError::Length`], [`VoiceError::Decode`], [`VoiceError::Signed`] (checked
389    /// before the body is decoded) or [`VoiceError::Mismatch`].
390    pub fn verify(
391        wire: &[u8],
392        sender_key: &PublicKey,
393        expected: &SenderKeysExpectation,
394    ) -> Result<SignedSenderKeys, VoiceError> {
395        if wire.len() > SENDER_KEYS_WIRE_MAX {
396            return Err(VoiceError::Length("sender keys"));
397        }
398        let mut r = Reader::new(wire);
399        let bytes = r.bytes(SENDER_KEYS_BYTES_MAX)?;
400        let sig = r.fixed(SIGNATURE_LEN)?;
401        r.finish()?;
402        let sig = Signature::from_bytes(sig).map_err(|e| VoiceError::Signed(e.into()))?;
403        let signed =
404            Signed::<Self>::verify_and_decode(bytes, &sig, sender_key, expected.min_suite)?;
405        let k = signed.object();
406        if k.community_id != expected.community_id {
407            return Err(VoiceError::Mismatch("community_id"));
408        }
409        if k.channel_id != expected.channel_id {
410            return Err(VoiceError::Mismatch("channel_id"));
411        }
412        if k.sender_member != expected.sender_member {
413            return Err(VoiceError::Mismatch("sender_member"));
414        }
415        Ok(SignedSenderKeys(signed))
416    }
417}
418
419impl SignedSenderKeys {
420    /// The statement.
421    #[must_use]
422    pub const fn keys(&self) -> &SenderKeys {
423        self.0.object()
424    }
425
426    /// The HPKE context of this epoch.
427    #[must_use]
428    pub const fn wrap_context(&self) -> WrapContext {
429        let k = self.0.object();
430        WrapContext {
431            community_id: k.community_id,
432            channel_id: k.channel_id,
433            sender_member: k.sender_member,
434            sender_session: k.sender_session,
435            epoch: k.epoch,
436        }
437    }
438
439    /// The entry for `own`, after checking that `wrapped` is the key the sender signed for it.
440    ///
441    /// # Errors
442    /// [`VoiceError::NotARecipient`] or [`VoiceError::WrappedHash`].
443    pub fn entry_for(
444        &self,
445        own: &SignedKeyPackage,
446        wrapped: &WrappedKey,
447    ) -> Result<&RecipientEntry, VoiceError> {
448        let p = own.package();
449        let entry = self
450            .0
451            .object()
452            .recipients
453            .iter()
454            .find(|r| r.voice_session == p.voice_session && r.member_id == p.member_id)
455            .ok_or(VoiceError::NotARecipient)?;
456        if entry.wrapped_hash != wrapped.hash() {
457            return Err(VoiceError::WrappedHash);
458        }
459        Ok(entry)
460    }
461
462    /// The wire form: `u32` length ‖ canonical bytes ‖ signature.
463    ///
464    /// # Errors
465    /// [`VoiceError::Encode`] (never expected: the bytes were checked when made).
466    pub fn to_wire(&self) -> Result<Vec<u8>, VoiceError> {
467        let mut w = Writer::new();
468        w.bytes(self.0.bytes(), SENDER_KEYS_BYTES_MAX)?;
469        w.fixed(self.0.signature().as_bytes());
470        Ok(w.into_bytes())
471    }
472}