zaun_community_protocol/crypto/voice/
sender.rs1use 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
56pub struct SenderKey(Zeroizing<[u8; BASE_KEY_LEN]>);
58
59impl SenderKey {
60 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 #[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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
165pub struct WrapContext {
166 pub community_id: CommunityId,
168 pub channel_id: ChannelId,
170 pub sender_member: MemberId,
172 pub sender_session: VoiceSessionId,
174 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#[derive(Clone, PartialEq, Eq)]
196pub struct WrappedKey([u8; WRAPPED_KEY_LEN]);
197
198impl WrappedKey {
199 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 #[must_use]
212 pub const fn as_bytes(&self) -> &[u8; WRAPPED_KEY_LEN] {
213 &self.0
214 }
215
216 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
235pub struct RecipientEntry {
236 pub member_id: MemberId,
238 pub voice_session: VoiceSessionId,
240 pub wrapped_hash: [u8; 32],
242}
243
244#[derive(Debug, Clone, PartialEq, Eq)]
246pub struct SenderKeys {
247 pub suite: u8,
249 pub community_id: CommunityId,
251 pub channel_id: ChannelId,
253 pub sender_member: MemberId,
255 pub sender_session: VoiceSessionId,
257 pub epoch: u32,
259 pub kid: u64,
261 pub recipients: Vec<RecipientEntry>,
263 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#[derive(Debug, Clone, PartialEq, Eq)]
342pub struct SenderKeysExpectation {
343 pub community_id: CommunityId,
345 pub channel_id: ChannelId,
347 pub sender_member: MemberId,
349 pub min_suite: u8,
351}
352
353#[derive(Debug, Clone, PartialEq, Eq)]
355pub struct SignedSenderKeys(Signed<SenderKeys>);
356
357impl SenderKeys {
358 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 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 #[must_use]
422 pub const fn keys(&self) -> &SenderKeys {
423 self.0.object()
424 }
425
426 #[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 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 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}