1use std::collections::HashMap;
7use std::ops::Range;
8use std::sync::LazyLock;
9use std::time::SystemTime;
10
11use aes_gcm_siv::aead::AeadInOut as _;
12use aes_gcm_siv::aead::array::typenum::Unsigned;
13use aes_gcm_siv::{Aes256GcmSiv, KeyInit};
14use indexmap::IndexMap;
15use itertools::Itertools;
16use prost::Message;
17use proto::sealed_sender::unidentified_sender_message::message::Type as ProtoMessageType;
18use rand::{CryptoRng, Rng, TryRngCore as _};
19use subtle::{Choice, ConstantTimeEq};
20use zerocopy::{FromBytes, Immutable, KnownLayout};
21
22use crate::error::SessionNotFound;
23use crate::{
24 Aci, CiphertextMessageType, DeviceId, Direction, IdentityKey, IdentityKeyPair,
25 IdentityKeyStore, KeyPair, KyberPreKeyStore, PreKeySignalMessage, PreKeyStore, PrivateKey,
26 ProtocolAddress, PublicKey, Result, ServiceId, ServiceIdFixedWidthBinaryBytes, SessionRecord,
27 SessionStore, SignalMessage, SignalProtocolError, SignedPreKeyStore, Timestamp, crypto,
28 message_encrypt, proto, session_management,
29};
30
31#[derive(Debug, Clone)]
32pub struct ServerCertificate {
33 serialized: Vec<u8>,
34 key_id: u32,
35 key: PublicKey,
36 certificate: Vec<u8>,
37 signature: Vec<u8>,
38}
39
40const REVOKED_SERVER_CERTIFICATE_KEY_IDS: &[u32] = &[0xDEADC357];
49
50const KNOWN_SERVER_CERTIFICATES: &[(u32, [u8; 33], &[u8])] = &[
60 (
61 2,
62 data_encoding_macro::base64!("BYhU6tPjqP46KGZEzRs1OL4U39V5dlPJ/X09ha4rErkm"),
64 &const_str::hex!(
65 "0a25080212210539450d63ebd0752c0fd4038b9d07a916f5e174b756d409b5ca79f4c97400631e124064c5a38b1e927497d3d4786b101a623ab34a7da3954fae126b04dba9d7a3604ed88cdc8550950f0d4a9134ceb7e19b94139151d2c3d6e1c81e9d1128aafca806"
66 ),
67 ),
68 (
69 3,
70 data_encoding_macro::base64!("BUkY0I+9+oPgDCn4+Ac6Iu813yvqkDr/ga8DzLxFxuk6"),
72 &const_str::hex!(
73 "0a250803122105bc9d1d290be964810dfa7e94856480a3f7060d004c9762c24c575a1522353a5a1240c11ec3c401eb0107ab38f8600e8720a63169e0e2eb8a3fae24f63099f85ea319c3c1c46d3454706ae2a679d1fee690a488adda98a2290b66c906bb60295ed781"
74 ),
75 ),
76 (
77 0x7357C357,
79 data_encoding_macro::base64!("BS/lfaNHzWJDFSjarF+7KQcw//aEr8TPwu2QmV9Yyzt0"),
82 &const_str::hex!(
85 "0a2908d786df9a07122105847c0d2c375234f365e660955187a3735a0f7613d1609d3a6a4d8c53aeaa5a221240e0b9ebacdfc3aa2827f7924b697784d1c25e44ca05dd433e1a38dc6382eb2730d419ca9a250b1be9d5a9463e61efd6781777a91b83c97b844d014206e2829785"
86 ),
87 ),
88];
89
90const VALID_REGISTRATION_ID_MASK: u16 = 0x3FFF;
93
94impl ServerCertificate {
95 pub fn deserialize(data: &[u8]) -> Result<Self> {
96 let pb = proto::sealed_sender::ServerCertificate::decode(data)
97 .map_err(|_| SignalProtocolError::InvalidProtobufEncoding)?;
98
99 if pb.certificate.is_none() || pb.signature.is_none() {
100 return Err(SignalProtocolError::InvalidProtobufEncoding);
101 }
102
103 let certificate = pb
104 .certificate
105 .ok_or(SignalProtocolError::InvalidProtobufEncoding)?;
106 let signature = pb
107 .signature
108 .ok_or(SignalProtocolError::InvalidProtobufEncoding)?;
109 let certificate_data =
110 proto::sealed_sender::server_certificate::Certificate::decode(certificate.as_ref())
111 .map_err(|_| SignalProtocolError::InvalidProtobufEncoding)?;
112 let key = PublicKey::try_from(
113 &certificate_data
114 .key
115 .ok_or(SignalProtocolError::InvalidProtobufEncoding)?[..],
116 )?;
117 let key_id = certificate_data
118 .id
119 .ok_or(SignalProtocolError::InvalidProtobufEncoding)?;
120
121 Ok(Self {
122 serialized: data.to_vec(),
123 certificate,
124 signature,
125 key,
126 key_id,
127 })
128 }
129
130 pub fn new<R: Rng + CryptoRng>(
131 key_id: u32,
132 key: PublicKey,
133 trust_root: &PrivateKey,
134 rng: &mut R,
135 ) -> Result<Self> {
136 let certificate_pb = proto::sealed_sender::server_certificate::Certificate {
137 id: Some(key_id),
138 key: Some(key.serialize().to_vec()),
139 };
140
141 let certificate = certificate_pb.encode_to_vec();
142
143 let signature = trust_root.calculate_signature(&certificate, rng)?.to_vec();
144
145 let serialized = proto::sealed_sender::ServerCertificate {
146 certificate: Some(certificate.clone()),
147 signature: Some(signature.clone()),
148 }
149 .encode_to_vec();
150
151 Ok(Self {
152 serialized,
153 certificate,
154 signature,
155 key,
156 key_id,
157 })
158 }
159
160 pub fn validate(&self, trust_root: &PublicKey) -> Result<bool> {
161 if REVOKED_SERVER_CERTIFICATE_KEY_IDS.contains(&self.key_id()?) {
162 log::error!(
163 "received server certificate with revoked ID {:x}",
164 self.key_id()?
165 );
166 return Ok(false);
167 }
168 Ok(trust_root.verify_signature(&self.certificate, &self.signature))
169 }
170
171 pub fn key_id(&self) -> Result<u32> {
172 Ok(self.key_id)
173 }
174
175 pub fn public_key(&self) -> Result<PublicKey> {
176 Ok(self.key)
177 }
178
179 pub fn certificate(&self) -> Result<&[u8]> {
180 Ok(&self.certificate)
181 }
182
183 pub fn signature(&self) -> Result<&[u8]> {
184 Ok(&self.signature)
185 }
186
187 pub fn serialized(&self) -> Result<&[u8]> {
188 Ok(&self.serialized)
189 }
190}
191
192#[derive(Debug, Clone)]
193enum SenderCertificateSigner {
194 Embedded(ServerCertificate),
195 Reference(u32),
196}
197
198#[derive(Debug, Clone)]
199pub struct SenderCertificate {
200 signer: SenderCertificateSigner,
201 key: PublicKey,
202 sender_device_id: DeviceId,
203 sender_uuid: String,
204 sender_e164: Option<String>,
205 expiration: Timestamp,
206 serialized: Vec<u8>,
207 certificate: Vec<u8>,
208 signature: Vec<u8>,
209}
210
211impl SenderCertificate {
212 pub fn deserialize(data: &[u8]) -> Result<Self> {
213 let pb = proto::sealed_sender::SenderCertificate::decode(data)
214 .map_err(|_| SignalProtocolError::InvalidProtobufEncoding)?;
215 let certificate = pb
216 .certificate
217 .ok_or(SignalProtocolError::InvalidProtobufEncoding)?;
218 let signature = pb
219 .signature
220 .ok_or(SignalProtocolError::InvalidProtobufEncoding)?;
221 let certificate_data =
222 proto::sealed_sender::sender_certificate::Certificate::decode(certificate.as_ref())
223 .map_err(|_| SignalProtocolError::InvalidProtobufEncoding)?;
224
225 let sender_device_id: DeviceId = certificate_data
226 .sender_device
227 .and_then(|v| DeviceId::try_from(v).ok())
228 .ok_or(SignalProtocolError::InvalidProtobufEncoding)?;
229 let expiration = certificate_data
230 .expires
231 .map(Timestamp::from_epoch_millis)
232 .ok_or(SignalProtocolError::InvalidProtobufEncoding)?;
233 let signer = match certificate_data
234 .signer
235 .ok_or(SignalProtocolError::InvalidProtobufEncoding)?
236 {
237 proto::sealed_sender::sender_certificate::certificate::Signer::Certificate(encoded) => {
238 SenderCertificateSigner::Embedded(ServerCertificate::deserialize(&encoded)?)
239 }
240 proto::sealed_sender::sender_certificate::certificate::Signer::Id(id) => {
241 SenderCertificateSigner::Reference(id)
242 }
243 };
244 let sender_uuid = match certificate_data
245 .sender_uuid
246 .ok_or(SignalProtocolError::InvalidProtobufEncoding)?
247 {
248 proto::sealed_sender::sender_certificate::certificate::SenderUuid::UuidString(
249 uuid_str,
250 ) => uuid_str,
251 proto::sealed_sender::sender_certificate::certificate::SenderUuid::UuidBytes(raw) => {
252 uuid::Uuid::from_slice(&raw)
254 .map_err(|_| SignalProtocolError::InvalidProtobufEncoding)?
255 .to_string()
256 }
257 };
258 let sender_e164 = certificate_data.sender_e164;
259
260 let key = PublicKey::try_from(
261 &certificate_data
262 .identity_key
263 .ok_or(SignalProtocolError::InvalidProtobufEncoding)?[..],
264 )?;
265
266 Ok(Self {
267 signer,
268 key,
269 sender_device_id,
270 sender_uuid,
271 sender_e164,
272 expiration,
273 serialized: data.to_vec(),
274 certificate,
275 signature,
276 })
277 }
278
279 pub fn new<R: Rng + CryptoRng>(
280 sender_uuid: String,
281 sender_e164: Option<String>,
282 key: PublicKey,
283 sender_device_id: DeviceId,
284 expiration: Timestamp,
285 signer: ServerCertificate,
286 signer_key: &PrivateKey,
287 rng: &mut R,
288 ) -> Result<Self> {
289 let certificate_pb = proto::sealed_sender::sender_certificate::Certificate {
290 sender_uuid: Some(
291 proto::sealed_sender::sender_certificate::certificate::SenderUuid::UuidString(
292 sender_uuid.clone(),
293 ),
294 ),
295 sender_e164: sender_e164.clone(),
296 sender_device: Some(sender_device_id.into()),
297 expires: Some(expiration.epoch_millis()),
298 identity_key: Some(key.serialize().to_vec()),
299 signer: Some(
300 proto::sealed_sender::sender_certificate::certificate::Signer::Certificate(
301 signer.serialized()?.to_vec(),
302 ),
303 ),
304 };
305
306 let certificate = certificate_pb.encode_to_vec();
307
308 let signature = signer_key.calculate_signature(&certificate, rng)?.to_vec();
309
310 let serialized = proto::sealed_sender::SenderCertificate {
311 certificate: Some(certificate.clone()),
312 signature: Some(signature.clone()),
313 }
314 .encode_to_vec();
315
316 Ok(Self {
317 signer: SenderCertificateSigner::Embedded(signer),
318 key,
319 sender_device_id,
320 sender_uuid,
321 sender_e164,
322 expiration,
323 serialized,
324 certificate,
325 signature,
326 })
327 }
328
329 pub fn validate(&self, trust_root: &PublicKey, validation_time: Timestamp) -> Result<bool> {
330 self.validate_with_trust_roots(&[trust_root], validation_time)
331 }
332
333 pub fn validate_with_trust_roots(
334 &self,
335 trust_roots: &[impl AsRef<PublicKey>],
336 validation_time: Timestamp,
337 ) -> Result<bool> {
338 let signer = self.signer()?;
339
340 let mut any_valid = Choice::from(0u8);
342 for root in trust_roots {
343 let ok = signer.validate(root.as_ref())?;
344 any_valid |= Choice::from(u8::from(ok));
345 }
346 if !bool::from(any_valid) {
347 log::error!(
348 "sender certificate contained server certificate that wasn't signed by any trust root"
349 );
350 return Ok(false);
351 }
352
353 if !signer
354 .public_key()?
355 .verify_signature(&self.certificate, &self.signature)
356 {
357 log::error!("sender certificate not signed by server");
358 return Ok(false);
359 }
360
361 if validation_time > self.expiration {
362 log::error!(
363 "sender certificate is expired (expiration: {}, validation_time: {})",
364 self.expiration.epoch_millis(),
365 validation_time.epoch_millis()
366 );
367 return Ok(false);
368 }
369
370 Ok(true)
371 }
372
373 pub fn signer(&self) -> Result<&ServerCertificate> {
374 static CERT_MAP: LazyLock<HashMap<u32, (PublicKey, ServerCertificate)>> =
375 LazyLock::new(|| {
376 HashMap::from_iter(KNOWN_SERVER_CERTIFICATES.iter().map(
377 |(id, trust_root, cert)| {
378 (
379 *id,
380 (
381 PublicKey::deserialize(trust_root).expect("valid"),
382 ServerCertificate::deserialize(cert).expect("valid"),
383 ),
384 )
385 },
386 ))
387 });
388
389 match &self.signer {
390 SenderCertificateSigner::Embedded(cert) => Ok(cert),
391 SenderCertificateSigner::Reference(id) => CERT_MAP
392 .get(id)
393 .map(|(_trust_root, cert)| cert)
394 .ok_or_else(|| SignalProtocolError::UnknownSealedSenderServerCertificateId(*id)),
395 }
396 }
397
398 pub fn key(&self) -> Result<PublicKey> {
399 Ok(self.key)
400 }
401
402 pub fn sender_device_id(&self) -> Result<DeviceId> {
403 Ok(self.sender_device_id)
404 }
405
406 pub fn sender_uuid(&self) -> Result<&str> {
407 Ok(&self.sender_uuid)
408 }
409
410 pub fn sender_e164(&self) -> Result<Option<&str>> {
411 Ok(self.sender_e164.as_deref())
412 }
413
414 pub fn expiration(&self) -> Result<Timestamp> {
415 Ok(self.expiration)
416 }
417
418 pub fn serialized(&self) -> Result<&[u8]> {
419 Ok(&self.serialized)
420 }
421
422 pub fn certificate(&self) -> Result<&[u8]> {
423 Ok(&self.certificate)
424 }
425
426 pub fn signature(&self) -> Result<&[u8]> {
427 Ok(&self.signature)
428 }
429}
430
431impl From<ProtoMessageType> for CiphertextMessageType {
432 fn from(message_type: ProtoMessageType) -> Self {
433 let result = match message_type {
434 ProtoMessageType::Message => Self::Whisper,
435 ProtoMessageType::PrekeyMessage => Self::PreKey,
436 ProtoMessageType::SenderkeyMessage => Self::SenderKey,
437 ProtoMessageType::PlaintextContent => Self::Plaintext,
438 };
439 assert!(result == Self::PreKey || message_type as i32 == result as i32);
441 result
442 }
443}
444
445impl From<CiphertextMessageType> for ProtoMessageType {
446 fn from(message_type: CiphertextMessageType) -> Self {
447 let result = match message_type {
448 CiphertextMessageType::PreKey => Self::PrekeyMessage,
449 CiphertextMessageType::Whisper => Self::Message,
450 CiphertextMessageType::SenderKey => Self::SenderkeyMessage,
451 CiphertextMessageType::Plaintext => Self::PlaintextContent,
452 };
453 assert!(result == Self::PrekeyMessage || message_type as i32 == result as i32);
455 result
456 }
457}
458
459#[derive(Clone, Copy, PartialEq, Eq, Debug)]
460pub enum ContentHint {
461 Default,
462 Resendable,
463 Implicit,
464 Unknown(u32),
465}
466
467impl ContentHint {
468 fn to_proto(self) -> Option<i32> {
469 if self == ContentHint::Default {
470 None
471 } else {
472 Some(u32::from(self) as i32)
473 }
474 }
475
476 pub const fn to_u32(self) -> u32 {
477 use proto::sealed_sender::unidentified_sender_message::message::ContentHint as ProtoContentHint;
478 match self {
479 ContentHint::Default => 0,
480 ContentHint::Resendable => ProtoContentHint::Resendable as u32,
481 ContentHint::Implicit => ProtoContentHint::Implicit as u32,
482 ContentHint::Unknown(value) => value,
483 }
484 }
485}
486
487impl From<u32> for ContentHint {
488 fn from(raw_value: u32) -> Self {
489 use proto::sealed_sender::unidentified_sender_message::message::ContentHint as ProtoContentHint;
490 assert!(!ProtoContentHint::is_valid(0));
491 match ProtoContentHint::try_from(raw_value as i32) {
492 Err(_) if raw_value == 0 => ContentHint::Default,
493 Err(_) => ContentHint::Unknown(raw_value),
494 Ok(ProtoContentHint::Resendable) => ContentHint::Resendable,
495 Ok(ProtoContentHint::Implicit) => ContentHint::Implicit,
496 }
497 }
498}
499
500impl From<ContentHint> for u32 {
501 fn from(hint: ContentHint) -> Self {
502 hint.to_u32()
503 }
504}
505
506pub struct UnidentifiedSenderMessageContent {
507 serialized: Vec<u8>,
508 contents: Vec<u8>,
509 sender: SenderCertificate,
510 msg_type: CiphertextMessageType,
511 content_hint: ContentHint,
512 group_id: Option<Vec<u8>>,
513}
514
515impl UnidentifiedSenderMessageContent {
516 pub fn deserialize(data: &[u8]) -> Result<Self> {
517 let pb = proto::sealed_sender::unidentified_sender_message::Message::decode(data)
518 .map_err(|_| SignalProtocolError::InvalidProtobufEncoding)?;
519
520 let msg_type = pb
521 .r#type
522 .and_then(|t| ProtoMessageType::try_from(t).ok())
523 .map(CiphertextMessageType::from)
524 .ok_or(SignalProtocolError::InvalidProtobufEncoding)?;
525 let sender = pb
526 .sender_certificate
527 .ok_or(SignalProtocolError::InvalidProtobufEncoding)?;
528 let contents = pb
529 .content
530 .ok_or(SignalProtocolError::InvalidProtobufEncoding)?;
531 let content_hint = pb
532 .content_hint
533 .map(|raw| ContentHint::from(raw as u32))
534 .unwrap_or(ContentHint::Default);
535 let group_id = pb.group_id;
536
537 let sender = SenderCertificate::deserialize(&sender)?;
538
539 let serialized = data.to_vec();
540
541 log::info!(
542 "deserialized UnidentifiedSenderMessageContent from {}.{} with type {:?}",
543 sender.sender_uuid()?,
544 sender.sender_device_id()?,
545 msg_type,
546 );
547
548 Ok(Self {
549 serialized,
550 contents,
551 sender,
552 msg_type,
553 content_hint,
554 group_id,
555 })
556 }
557
558 pub fn new(
559 msg_type: CiphertextMessageType,
560 sender: SenderCertificate,
561 contents: Vec<u8>,
562 content_hint: ContentHint,
563 group_id: Option<Vec<u8>>,
564 ) -> Result<Self> {
565 let proto_msg_type = ProtoMessageType::from(msg_type);
566 let msg = proto::sealed_sender::unidentified_sender_message::Message {
567 content: Some(contents.clone()),
568 r#type: Some(proto_msg_type.into()),
569 sender_certificate: Some(sender.serialized()?.to_vec()),
570 content_hint: content_hint.to_proto(),
571 group_id: group_id.as_ref().and_then(|buf| {
572 if buf.is_empty() {
573 None
574 } else {
575 Some(buf.clone())
576 }
577 }),
578 };
579
580 let serialized = msg.encode_to_vec();
581
582 Ok(Self {
583 serialized,
584 msg_type,
585 sender,
586 contents,
587 content_hint,
588 group_id,
589 })
590 }
591
592 pub fn msg_type(&self) -> Result<CiphertextMessageType> {
593 Ok(self.msg_type)
594 }
595
596 pub fn sender(&self) -> Result<&SenderCertificate> {
597 Ok(&self.sender)
598 }
599
600 pub fn contents(&self) -> Result<&[u8]> {
601 Ok(&self.contents)
602 }
603
604 pub fn content_hint(&self) -> Result<ContentHint> {
605 Ok(self.content_hint)
606 }
607
608 pub fn group_id(&self) -> Result<Option<&[u8]>> {
609 Ok(self.group_id.as_deref())
610 }
611
612 pub fn serialized(&self) -> Result<&[u8]> {
613 Ok(&self.serialized)
614 }
615}
616
617enum UnidentifiedSenderMessage<'a> {
618 V1 {
619 ephemeral_public: PublicKey,
620 encrypted_static: Vec<u8>,
621 encrypted_message: Vec<u8>,
622 },
623 V2 {
624 ephemeral_public: PublicKey,
625 encrypted_message_key: &'a [u8; sealed_sender_v2::MESSAGE_KEY_LEN],
626 authentication_tag: &'a [u8; sealed_sender_v2::AUTH_TAG_LEN],
627 encrypted_message: &'a [u8],
628 },
629}
630
631const SEALED_SENDER_V1_MAJOR_VERSION: u8 = 1;
632const SEALED_SENDER_V1_FULL_VERSION: u8 = 0x11;
633const SEALED_SENDER_V2_MAJOR_VERSION: u8 = 2;
634const SEALED_SENDER_V2_UUID_FULL_VERSION: u8 = 0x22;
635const SEALED_SENDER_V2_SERVICE_ID_FULL_VERSION: u8 = 0x23;
636
637impl<'a> UnidentifiedSenderMessage<'a> {
638 fn deserialize(data: &'a [u8]) -> Result<Self> {
639 let (version_byte, remaining) = data.split_first().ok_or_else(|| {
640 SignalProtocolError::InvalidSealedSenderMessage("Message was empty".to_owned())
641 })?;
642 let version = version_byte >> 4;
643 log::debug!("deserializing UnidentifiedSenderMessage with version {version}");
644
645 match version {
646 0 | SEALED_SENDER_V1_MAJOR_VERSION => {
647 let pb = proto::sealed_sender::UnidentifiedSenderMessage::decode(remaining)
649 .map_err(|_| SignalProtocolError::InvalidProtobufEncoding)?;
650
651 let ephemeral_public = pb
652 .ephemeral_public
653 .ok_or(SignalProtocolError::InvalidProtobufEncoding)?;
654 let encrypted_static = pb
655 .encrypted_static
656 .ok_or(SignalProtocolError::InvalidProtobufEncoding)?;
657 let encrypted_message = pb
658 .encrypted_message
659 .ok_or(SignalProtocolError::InvalidProtobufEncoding)?;
660
661 let ephemeral_public = PublicKey::try_from(&ephemeral_public[..])?;
662
663 Ok(Self::V1 {
664 ephemeral_public,
665 encrypted_static,
666 encrypted_message,
667 })
668 }
669 SEALED_SENDER_V2_MAJOR_VERSION => {
670 #[derive(FromBytes, Immutable, KnownLayout)]
672 #[repr(C, packed)]
673 struct PrefixRepr {
674 encrypted_message_key: [u8; sealed_sender_v2::MESSAGE_KEY_LEN],
675 encrypted_authentication_tag: [u8; sealed_sender_v2::AUTH_TAG_LEN],
676 ephemeral_public: [u8; sealed_sender_v2::PUBLIC_KEY_LEN],
677 }
678 let (prefix, encrypted_message) =
679 zerocopy::Ref::<_, PrefixRepr>::from_prefix(remaining)
680 .map_err(|_| SignalProtocolError::InvalidProtobufEncoding)?;
681
682 let PrefixRepr {
683 encrypted_message_key,
684 encrypted_authentication_tag,
685 ephemeral_public,
686 } = zerocopy::Ref::into_ref(prefix);
687
688 Ok(Self::V2 {
689 ephemeral_public: PublicKey::from_djb_public_key_bytes(
690 ephemeral_public.as_slice(),
691 )?,
692 encrypted_message_key,
693 authentication_tag: encrypted_authentication_tag,
694 encrypted_message,
695 })
696 }
697 _ => Err(SignalProtocolError::UnknownSealedSenderVersion(version)),
698 }
699 }
700}
701
702mod sealed_sender_v1 {
703 #[cfg(test)]
704 use std::fmt;
705
706 use libsignal_core::derive_arrays;
707
708 use super::*;
709
710 pub(super) struct EphemeralKeys {
713 pub(super) chain_key: [u8; 32],
714 pub(super) cipher_key: [u8; 32],
715 pub(super) mac_key: [u8; 32],
716 }
717
718 const SALT_PREFIX: &[u8] = b"UnidentifiedDelivery";
719
720 impl EphemeralKeys {
721 pub(super) fn calculate(
724 our_keys: &KeyPair,
725 their_public: &PublicKey,
726 direction: Direction,
727 ) -> Result<Self> {
728 let our_pub_key = our_keys.public_key.serialize();
729 let their_pub_key = their_public.serialize();
730 let ephemeral_salt = match direction {
731 Direction::Sending => [SALT_PREFIX, &their_pub_key, &our_pub_key],
732 Direction::Receiving => [SALT_PREFIX, &our_pub_key, &their_pub_key],
733 }
734 .concat();
735
736 let shared_secret = our_keys.private_key.calculate_agreement(their_public)?;
737 let (chain_key, cipher_key, mac_key) = derive_arrays(|bytes| {
738 hkdf::Hkdf::<sha2::Sha256>::new(Some(&ephemeral_salt), &shared_secret)
739 .expand(&[], bytes)
740 .expect("valid output length")
741 });
742
743 Ok(Self {
744 chain_key,
745 cipher_key,
746 mac_key,
747 })
748 }
749 }
750
751 #[cfg(test)]
752 impl PartialEq for EphemeralKeys {
753 fn eq(&self, other: &Self) -> bool {
754 self.chain_key == other.chain_key
755 && self.cipher_key == other.cipher_key
756 && self.mac_key == other.mac_key
757 }
758 }
759
760 #[cfg(test)]
761 impl Eq for EphemeralKeys {}
762
763 #[cfg(test)]
764 impl fmt::Debug for EphemeralKeys {
765 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
766 write!(
767 f,
768 "EphemeralKeys {{ chain_key: {:?}, cipher_key: {:?}, mac_key: {:?} }}",
769 self.chain_key, self.cipher_key, self.mac_key
770 )
771 }
772 }
773
774 pub(super) struct StaticKeys {
776 pub(super) cipher_key: [u8; 32],
777 pub(super) mac_key: [u8; 32],
778 }
779
780 impl StaticKeys {
781 pub(super) fn calculate(
784 our_keys: &IdentityKeyPair,
785 their_key: &PublicKey,
786 chain_key: &[u8; 32],
787 ctext: &[u8],
788 ) -> Result<Self> {
789 let salt = [chain_key, ctext].concat();
790
791 let shared_secret = our_keys.private_key().calculate_agreement(their_key)?;
792 let (_, cipher_key, mac_key) = derive_arrays::<32, 32, 32>(|bytes| {
796 hkdf::Hkdf::<sha2::Sha256>::new(Some(&salt), &shared_secret)
797 .expand(&[], bytes)
798 .expect("valid output length")
799 });
800
801 Ok(Self {
802 cipher_key,
803 mac_key,
804 })
805 }
806 }
807
808 #[test]
809 fn test_agreement_and_authentication() -> Result<()> {
810 let sender_identity = IdentityKeyPair::generate(&mut rand::rng());
812 let recipient_identity = IdentityKeyPair::generate(&mut rand::rng());
813
814 let sender_ephemeral = KeyPair::generate(&mut rand::rng());
816 let ephemeral_public = sender_ephemeral.public_key;
817 let sender_eph_keys = EphemeralKeys::calculate(
819 &sender_ephemeral,
820 recipient_identity.public_key(),
821 Direction::Sending,
822 )?;
823
824 let sender_static_key_ctext = crypto::aes256_ctr_hmacsha256_encrypt(
826 &sender_identity.public_key().serialize(),
827 &sender_eph_keys.cipher_key,
828 &sender_eph_keys.mac_key,
829 )
830 .expect("just generated these keys, they should be correct");
831
832 let sender_static_keys = StaticKeys::calculate(
834 &sender_identity,
835 recipient_identity.public_key(),
836 &sender_eph_keys.chain_key,
837 &sender_static_key_ctext,
838 )?;
839
840 let sender_message_contents = b"this is a binary message";
841 let sender_message_data = crypto::aes256_ctr_hmacsha256_encrypt(
842 sender_message_contents,
843 &sender_static_keys.cipher_key,
844 &sender_static_keys.mac_key,
845 )
846 .expect("just generated these keys, they should be correct");
847
848 let recipient_eph_keys = EphemeralKeys::calculate(
850 &recipient_identity.into(),
851 &ephemeral_public,
852 Direction::Receiving,
853 )?;
854 assert_eq!(sender_eph_keys, recipient_eph_keys);
855
856 let recipient_message_key_bytes = crypto::aes256_ctr_hmacsha256_decrypt(
857 &sender_static_key_ctext,
858 &recipient_eph_keys.cipher_key,
859 &recipient_eph_keys.mac_key,
860 )
861 .expect("should decrypt successfully");
862 let sender_public_key: PublicKey = PublicKey::try_from(&recipient_message_key_bytes[..])?;
863 assert_eq!(sender_identity.public_key(), &sender_public_key);
864
865 let recipient_static_keys = StaticKeys::calculate(
866 &recipient_identity,
867 &sender_public_key,
868 &recipient_eph_keys.chain_key,
869 &sender_static_key_ctext,
870 )?;
871
872 let recipient_message_contents = crypto::aes256_ctr_hmacsha256_decrypt(
873 &sender_message_data,
874 &recipient_static_keys.cipher_key,
875 &recipient_static_keys.mac_key,
876 )
877 .expect("should decrypt successfully");
878 assert_eq!(recipient_message_contents, sender_message_contents);
879
880 Ok(())
881 }
882}
883
884pub async fn sealed_sender_encrypt<R: Rng + CryptoRng>(
891 destination: &ProtocolAddress,
892 sender_cert: &SenderCertificate,
893 ptext: &[u8],
894 session_store: &mut dyn SessionStore,
895 identity_store: &mut dyn IdentityKeyStore,
896 now: SystemTime,
897 rng: &mut R,
898) -> Result<Vec<u8>> {
899 let sender_address = ProtocolAddress::new(
900 sender_cert.sender_uuid()?.to_owned(),
901 sender_cert.sender_device_id()?,
902 );
903 let message = message_encrypt(
904 ptext,
905 destination,
906 &sender_address,
907 session_store,
908 identity_store,
909 now,
910 rng,
911 )
912 .await?;
913 let usmc = UnidentifiedSenderMessageContent::new(
914 message.message_type(),
915 sender_cert.clone(),
916 message.serialize().to_vec(),
917 ContentHint::Default,
918 None,
919 )?;
920 sealed_sender_encrypt_from_usmc(destination, &usmc, identity_store, rng).await
921}
922
923pub async fn sealed_sender_encrypt_from_usmc<R: Rng + CryptoRng>(
974 destination: &ProtocolAddress,
975 usmc: &UnidentifiedSenderMessageContent,
976 identity_store: &dyn IdentityKeyStore,
977 rng: &mut R,
978) -> Result<Vec<u8>> {
979 let our_identity = identity_store.get_identity_key_pair().await?;
980 let their_identity = identity_store
981 .get_identity(destination)
982 .await?
983 .ok_or_else(|| {
984 SignalProtocolError::SessionNotFound(SessionNotFound::new(
985 destination.clone(),
986 "sealed_sender_encrypt_from_usmc",
987 ))
988 })?;
989
990 let ephemeral = KeyPair::generate(rng);
991
992 let eph_keys = sealed_sender_v1::EphemeralKeys::calculate(
993 &ephemeral,
994 their_identity.public_key(),
995 Direction::Sending,
996 )?;
997
998 let static_key_ctext = crypto::aes256_ctr_hmacsha256_encrypt(
999 &our_identity.public_key().serialize(),
1000 &eph_keys.cipher_key,
1001 &eph_keys.mac_key,
1002 )
1003 .expect("just generated these keys, they should be correct");
1004
1005 let static_keys = sealed_sender_v1::StaticKeys::calculate(
1006 &our_identity,
1007 their_identity.public_key(),
1008 &eph_keys.chain_key,
1009 &static_key_ctext,
1010 )?;
1011
1012 let message_data = crypto::aes256_ctr_hmacsha256_encrypt(
1013 usmc.serialized()?,
1014 &static_keys.cipher_key,
1015 &static_keys.mac_key,
1016 )
1017 .expect("just generated these keys, they should be correct");
1018
1019 let mut serialized = vec![SEALED_SENDER_V1_FULL_VERSION];
1020 let pb = proto::sealed_sender::UnidentifiedSenderMessage {
1021 ephemeral_public: Some(ephemeral.public_key.serialize().to_vec()),
1022 encrypted_static: Some(static_key_ctext),
1023 encrypted_message: Some(message_data),
1024 };
1025 pb.encode(&mut serialized)
1026 .expect("can always append to Vec");
1027
1028 Ok(serialized)
1029}
1030
1031mod sealed_sender_v2 {
1032 use super::*;
1033
1034 const LABEL_R: &[u8] = b"Sealed Sender v2: r (2023-08)";
1036 const LABEL_K: &[u8] = b"Sealed Sender v2: K";
1037 const LABEL_DH: &[u8] = b"Sealed Sender v2: DH";
1038 const LABEL_DH_S: &[u8] = b"Sealed Sender v2: DH-sender";
1039
1040 pub const MESSAGE_KEY_LEN: usize = 32;
1041 pub const CIPHER_KEY_LEN: usize =
1042 <Aes256GcmSiv as aes_gcm_siv::aead::KeySizeUser>::KeySize::USIZE;
1043 pub const AUTH_TAG_LEN: usize = 16;
1044 pub const PUBLIC_KEY_LEN: usize = 32;
1046
1047 pub(super) struct DerivedKeys {
1049 kdf: hkdf::Hkdf<sha2::Sha256>,
1050 }
1051
1052 impl DerivedKeys {
1053 pub(super) fn new(m: &[u8]) -> DerivedKeys {
1055 Self {
1056 kdf: hkdf::Hkdf::<sha2::Sha256>::new(None, m),
1057 }
1058 }
1059
1060 pub(super) fn derive_e(&self) -> KeyPair {
1062 let mut r = [0; 32];
1063 self.kdf
1064 .expand(LABEL_R, &mut r)
1065 .expect("valid output length");
1066 let e = PrivateKey::try_from(&r[..]).expect("valid PrivateKey");
1067 KeyPair::try_from(e).expect("can derive public key")
1068 }
1069
1070 pub(super) fn derive_k(&self) -> [u8; CIPHER_KEY_LEN] {
1072 let mut k = [0; CIPHER_KEY_LEN];
1073 self.kdf
1074 .expand(LABEL_K, &mut k)
1075 .expect("valid output length");
1076 k
1077 }
1078 }
1079
1080 pub(super) fn apply_agreement_xor(
1087 our_keys: &KeyPair,
1088 their_key: &PublicKey,
1089 direction: Direction,
1090 input: &[u8; MESSAGE_KEY_LEN],
1091 ) -> Result<[u8; MESSAGE_KEY_LEN]> {
1092 let agreement = our_keys.calculate_agreement(their_key)?;
1093 let agreement_key_input = match direction {
1094 Direction::Sending => [
1095 agreement,
1096 our_keys.public_key.serialize(),
1097 their_key.serialize(),
1098 ],
1099 Direction::Receiving => [
1100 agreement,
1101 their_key.serialize(),
1102 our_keys.public_key.serialize(),
1103 ],
1104 }
1105 .concat();
1106
1107 let mut result = [0; MESSAGE_KEY_LEN];
1108 hkdf::Hkdf::<sha2::Sha256>::new(None, &agreement_key_input)
1109 .expand(LABEL_DH, &mut result)
1110 .expect("valid output length");
1111 result
1112 .iter_mut()
1113 .zip(input)
1114 .for_each(|(result_byte, input_byte)| *result_byte ^= input_byte);
1115 Ok(result)
1116 }
1117
1118 pub(super) fn compute_authentication_tag(
1127 our_keys: &IdentityKeyPair,
1128 their_key: &IdentityKey,
1129 direction: Direction,
1130 ephemeral_pub_key: &PublicKey,
1131 encrypted_message_key: &[u8; MESSAGE_KEY_LEN],
1132 ) -> Result<[u8; AUTH_TAG_LEN]> {
1133 let agreement = our_keys
1134 .private_key()
1135 .calculate_agreement(their_key.public_key())?;
1136 let mut agreement_key_input = agreement.into_vec();
1137 agreement_key_input.extend_from_slice(&ephemeral_pub_key.serialize());
1138 agreement_key_input.extend_from_slice(encrypted_message_key);
1139 match direction {
1140 Direction::Sending => {
1141 agreement_key_input.extend_from_slice(&our_keys.public_key().serialize());
1142 agreement_key_input.extend_from_slice(&their_key.serialize());
1143 }
1144 Direction::Receiving => {
1145 agreement_key_input.extend_from_slice(&their_key.serialize());
1146 agreement_key_input.extend_from_slice(&our_keys.public_key().serialize());
1147 }
1148 }
1149
1150 let mut result = [0; AUTH_TAG_LEN];
1151 hkdf::Hkdf::<sha2::Sha256>::new(None, &agreement_key_input)
1152 .expand(LABEL_DH_S, &mut result)
1153 .expect("valid output length");
1154 Ok(result)
1155 }
1156
1157 #[test]
1158 fn test_agreement_and_authentication() -> Result<()> {
1159 let sender_identity = IdentityKeyPair::generate(&mut rand::rng());
1161 let recipient_identity = IdentityKeyPair::generate(&mut rand::rng());
1162
1163 let m: [u8; MESSAGE_KEY_LEN] = rand::rng().random();
1165 let ephemeral_keys = DerivedKeys::new(&m);
1167 let e = ephemeral_keys.derive_e();
1168
1169 let sender_c_0: [u8; MESSAGE_KEY_LEN] =
1171 apply_agreement_xor(&e, recipient_identity.public_key(), Direction::Sending, &m)?;
1172 let sender_at_0 = compute_authentication_tag(
1174 &sender_identity,
1175 recipient_identity.identity_key(),
1176 Direction::Sending,
1177 &e.public_key,
1178 &sender_c_0,
1179 )?;
1180
1181 let recv_m = apply_agreement_xor(
1183 &recipient_identity.into(),
1184 &e.public_key,
1185 Direction::Receiving,
1186 &sender_c_0,
1187 )?;
1188 assert_eq!(&recv_m, &m);
1189
1190 let recv_at_0 = compute_authentication_tag(
1191 &recipient_identity,
1192 sender_identity.identity_key(),
1193 Direction::Receiving,
1194 &e.public_key,
1195 &sender_c_0,
1196 )?;
1197 assert_eq!(&recv_at_0, &sender_at_0);
1198
1199 Ok(())
1200 }
1201}
1202
1203pub async fn sealed_sender_multi_recipient_encrypt<
1364 R: Rng + CryptoRng,
1365 X: IntoIterator<Item = ServiceId>,
1366>(
1367 destinations: &[&ProtocolAddress],
1368 destination_sessions: &[&SessionRecord],
1369 excluded_recipients: X,
1370 usmc: &UnidentifiedSenderMessageContent,
1371 identity_store: &dyn IdentityKeyStore,
1372 rng: &mut R,
1373) -> Result<Vec<u8>>
1374where
1375 X::IntoIter: ExactSizeIterator,
1376{
1377 sealed_sender_multi_recipient_encrypt_impl(
1378 destinations,
1379 destination_sessions,
1380 excluded_recipients,
1381 usmc,
1382 identity_store,
1383 rng,
1384 )
1385 .await
1386}
1387
1388async fn sealed_sender_multi_recipient_encrypt_impl<
1389 R: Rng + CryptoRng,
1390 X: IntoIterator<Item = ServiceId>,
1391>(
1392 destinations: &[&ProtocolAddress],
1393 destination_sessions: &[&SessionRecord],
1394 excluded_recipients: X,
1395 usmc: &UnidentifiedSenderMessageContent,
1396 identity_store: &dyn IdentityKeyStore,
1397 rng: &mut R,
1398) -> Result<Vec<u8>>
1399where
1400 X::IntoIter: ExactSizeIterator,
1401{
1402 if destinations.len() != destination_sessions.len() {
1403 return Err(SignalProtocolError::InvalidArgument(
1404 "must have the same number of destination sessions as addresses".to_string(),
1405 ));
1406 }
1407
1408 let excluded_recipients = excluded_recipients.into_iter();
1409 let our_identity = identity_store.get_identity_key_pair().await?;
1410
1411 let m: [u8; sealed_sender_v2::MESSAGE_KEY_LEN] = rng.random();
1412 let keys = sealed_sender_v2::DerivedKeys::new(&m);
1413 let e = keys.derive_e();
1414 let e_pub = &e.public_key;
1415
1416 let ciphertext = {
1418 let mut ciphertext = usmc.serialized()?.to_vec();
1419 let symmetric_authentication_tag = Aes256GcmSiv::new(&keys.derive_k().into())
1420 .encrypt_inout_detached(
1421 &aes_gcm_siv::Nonce::default(),
1423 &[],
1425 (&mut ciphertext[..]).into(),
1426 )
1427 .expect("AES-GCM-SIV encryption should not fail with a just-computed key");
1428 ciphertext.extend_from_slice(&symmetric_authentication_tag);
1431 ciphertext
1432 };
1433
1434 let identity_keys_and_ranges: Vec<(IdentityKey, Range<usize>)> = {
1439 let mut identity_keys_and_ranges = vec![];
1440 for (_, mut next_group) in &destinations
1441 .iter()
1442 .enumerate()
1443 .chunk_by(|(_i, next)| next.name())
1444 {
1445 let (i, &destination) = next_group
1446 .next()
1447 .expect("at least one element in every group");
1448 let count = 1 + next_group.count();
1451 let their_identity =
1452 identity_store
1453 .get_identity(destination)
1454 .await?
1455 .ok_or_else(|| {
1456 log::error!("missing identity key for {destination}");
1457 SignalProtocolError::SessionNotFound(SessionNotFound::new(
1461 destination.clone(),
1462 "sealed_sender_multi_recipient_encrypt_impl",
1463 ))
1464 })?;
1465 identity_keys_and_ranges.push((their_identity, i..i + count));
1466 }
1467 identity_keys_and_ranges
1468 };
1469
1470 let serialize_recipient_destinations_into = |serialized: &mut Vec<u8>,
1476 destinations: &[&ProtocolAddress],
1477 sessions: &[&SessionRecord],
1478 their_identity: &IdentityKey|
1479 -> Result<()> {
1480 let their_service_id = ServiceId::parse_from_service_id_string(destinations[0].name())
1481 .ok_or_else(|| {
1482 SignalProtocolError::InvalidArgument(format!(
1483 "multi-recipient sealed sender requires recipients' ServiceId (not {})",
1484 destinations[0].name()
1485 ))
1486 })?;
1487
1488 serialized.extend_from_slice(&their_service_id.service_id_fixed_width_binary());
1489
1490 debug_assert_eq!(
1491 destinations.len(),
1492 sessions.len(),
1493 "should be sliced with the same range"
1494 );
1495 let mut destinations_and_sessions = destinations.iter().zip(sessions);
1496 while let Some((&destination, session)) = destinations_and_sessions.next() {
1497 let their_registration_id = session.remote_registration_id().map_err(|_| {
1498 SignalProtocolError::InvalidState(
1499 "sealed_sender_multi_recipient_encrypt",
1500 format!(
1501 concat!(
1502 "cannot get registration ID from session with {} ",
1503 "(maybe it was recently archived)"
1504 ),
1505 destination
1506 ),
1507 )
1508 })?;
1509 if their_registration_id & u32::from(VALID_REGISTRATION_ID_MASK)
1510 != their_registration_id
1511 {
1512 return Err(SignalProtocolError::InvalidRegistrationId(
1513 destination.clone(),
1514 their_registration_id,
1515 ));
1516 }
1517 let mut their_registration_id =
1518 u16::try_from(their_registration_id).expect("just checked range");
1519 if destinations_and_sessions.len() > 0 {
1520 their_registration_id |= 0x8000;
1521 }
1522
1523 let device_id = destination.device_id();
1524 serialized.push(device_id.into());
1525 serialized.extend_from_slice(&their_registration_id.to_be_bytes());
1526 }
1527
1528 let c_i = sealed_sender_v2::apply_agreement_xor(
1529 &e,
1530 their_identity.public_key(),
1531 Direction::Sending,
1532 &m,
1533 )?;
1534 serialized.extend_from_slice(&c_i);
1535
1536 let at_i = sealed_sender_v2::compute_authentication_tag(
1537 &our_identity,
1538 their_identity,
1539 Direction::Sending,
1540 e_pub,
1541 &c_i,
1542 )?;
1543 serialized.extend_from_slice(&at_i);
1544
1545 Ok(())
1546 };
1547
1548 let process_chunk =
1549 |serialized: &mut Vec<u8>, chunk: &[(IdentityKey, Range<usize>)]| -> Result<()> {
1550 for (their_identity, destination_range) in chunk {
1551 let these_destinations = &destinations[destination_range.clone()];
1552 let these_sessions = &destination_sessions[destination_range.clone()];
1553 serialize_recipient_destinations_into(
1554 serialized,
1555 these_destinations,
1556 these_sessions,
1557 their_identity,
1558 )?;
1559 }
1560 Ok(())
1561 };
1562
1563 let mut serialized: Vec<u8> = vec![SEALED_SENDER_V2_SERVICE_ID_FULL_VERSION];
1564
1565 let count_of_recipients = identity_keys_and_ranges.len() + excluded_recipients.len();
1566 prost::encode_length_delimiter(count_of_recipients, &mut serialized)
1567 .expect("can always resize a Vec");
1568
1569 let parallelism = std::thread::available_parallelism()
1571 .map(usize::from)
1572 .unwrap_or(1);
1573 let chunk_size = std::cmp::max(6, identity_keys_and_ranges.len().div_ceil(parallelism));
1574
1575 if parallelism == 1 || chunk_size >= identity_keys_and_ranges.len() {
1576 process_chunk(&mut serialized, &identity_keys_and_ranges)?;
1577 } else {
1578 let mut chunks = identity_keys_and_ranges.chunks(chunk_size);
1579 let first_chunk = chunks.next().expect("at least one chunk, tested above");
1581
1582 let mut all_outputs = Vec::new();
1583 all_outputs.resize_with(chunks.len(), || Ok(vec![]));
1584
1585 rayon::scope(|scope| -> Result<()> {
1586 let mut outputs = &mut all_outputs[..];
1587 for chunk in chunks {
1588 let (next_output, remaining_outputs) = outputs
1589 .split_first_mut()
1590 .expect("as many outputs as remaining chunks");
1591 scope.spawn(|_| {
1592 let mut serialized = vec![];
1593 *next_output = process_chunk(&mut serialized, chunk).map(|_| serialized);
1594 });
1595 outputs = remaining_outputs;
1596 }
1597
1598 process_chunk(&mut serialized, first_chunk)
1599 })?;
1600
1601 for output in all_outputs {
1602 serialized.extend(output?);
1603 }
1604 }
1605
1606 for excluded in excluded_recipients {
1607 serialized.extend_from_slice(&excluded.service_id_fixed_width_binary());
1608 serialized.push(0);
1609 }
1610
1611 serialized.extend_from_slice(e_pub.public_key_bytes());
1612 serialized.extend_from_slice(&ciphertext);
1613
1614 Ok(serialized)
1615}
1616
1617pub struct SealedSenderV2SentMessageRecipient<'a> {
1621 pub devices: Vec<(DeviceId, u16)>,
1623 c_and_at: &'a [u8],
1626}
1627
1628pub struct SealedSenderV2SentMessage<'a> {
1632 full_message: &'a [u8],
1634 pub version: u8,
1636 pub recipients: IndexMap<ServiceId, SealedSenderV2SentMessageRecipient<'a>>,
1642 shared_bytes: &'a [u8],
1644}
1645
1646impl<'a> SealedSenderV2SentMessage<'a> {
1647 pub fn parse(data: &'a [u8]) -> Result<Self> {
1649 if data.is_empty() {
1650 return Err(SignalProtocolError::InvalidSealedSenderMessage(
1651 "Message was empty".to_owned(),
1652 ));
1653 }
1654
1655 let version = data[0];
1656 if !matches!(
1657 version,
1658 SEALED_SENDER_V2_UUID_FULL_VERSION | SEALED_SENDER_V2_SERVICE_ID_FULL_VERSION
1659 ) {
1660 return Err(SignalProtocolError::UnknownSealedSenderVersion(version));
1661 }
1662
1663 fn advance<'a, const N: usize>(buf: &mut &'a [u8]) -> Result<&'a [u8; N]> {
1664 let (prefix, remaining) = buf
1665 .split_first_chunk()
1666 .ok_or(SignalProtocolError::InvalidProtobufEncoding)?;
1667 *buf = remaining;
1668 Ok(prefix)
1669 }
1670 fn decode_varint(buf: &mut &[u8]) -> Result<u32> {
1671 let result: usize = prost::decode_length_delimiter(*buf)
1672 .map_err(|_| SignalProtocolError::InvalidProtobufEncoding)?;
1673 *buf = &buf[prost::length_delimiter_len(result)..];
1674 result
1675 .try_into()
1676 .map_err(|_| SignalProtocolError::InvalidProtobufEncoding)
1677 }
1678
1679 let mut remaining = &data[1..];
1680 let recipient_count = decode_varint(&mut remaining)?
1681 .try_into()
1682 .unwrap_or(usize::MAX);
1683
1684 let mut recipients: IndexMap<ServiceId, SealedSenderV2SentMessageRecipient<'a>> =
1688 IndexMap::with_capacity(std::cmp::min(recipient_count as usize, 6000));
1689 for _ in 0..recipient_count {
1690 let service_id = if version == SEALED_SENDER_V2_UUID_FULL_VERSION {
1691 ServiceId::from(Aci::from_uuid_bytes(*advance::<
1693 { std::mem::size_of::<uuid::Bytes>() },
1694 >(&mut remaining)?))
1695 } else {
1696 ServiceId::parse_from_service_id_fixed_width_binary(advance::<
1697 { std::mem::size_of::<ServiceIdFixedWidthBinaryBytes>() },
1698 >(
1699 &mut remaining
1700 )?)
1701 .ok_or(SignalProtocolError::InvalidProtobufEncoding)?
1702 };
1703 let mut devices = Vec::new();
1704 loop {
1705 let device_id = advance::<1>(&mut remaining)?[0];
1706 if device_id == 0 {
1707 if !devices.is_empty() {
1708 return Err(SignalProtocolError::InvalidProtobufEncoding);
1709 }
1710 break;
1711 }
1712 let device_id = DeviceId::new(device_id)
1713 .map_err(|_| SignalProtocolError::InvalidProtobufEncoding)?;
1714 let registration_id_and_has_more =
1715 u16::from_be_bytes(*advance::<2>(&mut remaining)?);
1716 devices.push((
1717 device_id,
1718 registration_id_and_has_more & VALID_REGISTRATION_ID_MASK,
1719 ));
1720 let has_more = (registration_id_and_has_more & 0x8000) != 0;
1721 if !has_more {
1722 break;
1723 }
1724 }
1725
1726 let c_and_at: &[u8] = if devices.is_empty() {
1727 &[]
1728 } else {
1729 advance::<{ sealed_sender_v2::MESSAGE_KEY_LEN + sealed_sender_v2::AUTH_TAG_LEN }>(
1730 &mut remaining,
1731 )?
1732 };
1733
1734 match recipients.entry(service_id) {
1735 indexmap::map::Entry::Occupied(mut existing) => {
1736 if existing.get().devices.is_empty() || devices.is_empty() {
1737 return Err(SignalProtocolError::InvalidSealedSenderMessage(
1738 "recipient redundantly encoded as empty".to_owned(),
1739 ));
1740 }
1741 existing.get_mut().devices.extend(devices);
1744 }
1748 indexmap::map::Entry::Vacant(entry) => {
1749 entry.insert(SealedSenderV2SentMessageRecipient { devices, c_and_at });
1750 }
1751 };
1752 }
1753
1754 if remaining.len() < sealed_sender_v2::PUBLIC_KEY_LEN {
1755 return Err(SignalProtocolError::InvalidProtobufEncoding);
1756 }
1757
1758 Ok(Self {
1759 full_message: data,
1760 version,
1761 recipients,
1762 shared_bytes: remaining,
1763 })
1764 }
1765
1766 #[inline]
1772 pub fn received_message_parts_for_recipient(
1773 &self,
1774 recipient: &SealedSenderV2SentMessageRecipient<'a>,
1775 ) -> impl AsRef<[&[u8]]> {
1776 [
1781 &[SEALED_SENDER_V2_UUID_FULL_VERSION],
1782 recipient.c_and_at,
1783 self.shared_bytes,
1784 ]
1785 }
1786
1787 #[inline]
1793 fn offset_within_full_message(&self, addr: *const u8) -> Option<usize> {
1794 let offset = (addr as usize).wrapping_sub(self.full_message.as_ptr() as usize);
1798 if offset <= self.full_message.len() {
1801 debug_assert!(
1802 offset == self.full_message.len() || std::ptr::eq(&self.full_message[offset], addr)
1803 );
1804 Some(offset)
1805 } else {
1806 None
1807 }
1808 }
1809
1810 pub fn range_for_recipient_key_material(
1817 &self,
1818 recipient: &SealedSenderV2SentMessageRecipient<'a>,
1819 ) -> Range<usize> {
1820 if recipient.c_and_at.is_empty() {
1821 return 0..0;
1822 }
1823 let offset = self
1824 .offset_within_full_message(recipient.c_and_at.as_ptr())
1825 .expect("'recipient' is not one of the recipients in this SealedSenderV2SentMessage");
1826 let end_offset = offset.saturating_add(recipient.c_and_at.len());
1827 assert!(
1828 end_offset <= self.full_message.len(),
1829 "invalid 'recipient' passed to range_for_recipient_key_material"
1830 );
1831 offset..end_offset
1832 }
1833
1834 pub fn offset_of_shared_bytes(&self) -> usize {
1839 debug_assert_eq!(
1840 self.full_message.as_ptr_range().end,
1841 self.shared_bytes.as_ptr_range().end,
1842 "SealedSenderV2SentMessage parsed incorrectly"
1843 );
1844 self.offset_within_full_message(self.shared_bytes.as_ptr())
1845 .expect("constructed correctly")
1846 }
1847}
1848
1849pub async fn sealed_sender_decrypt_to_usmc(
1854 ciphertext: &[u8],
1855 identity_store: &dyn IdentityKeyStore,
1856) -> Result<UnidentifiedSenderMessageContent> {
1857 let our_identity = identity_store.get_identity_key_pair().await?;
1858
1859 match UnidentifiedSenderMessage::deserialize(ciphertext)? {
1860 UnidentifiedSenderMessage::V1 {
1861 ephemeral_public,
1862 encrypted_static,
1863 encrypted_message,
1864 } => {
1865 let eph_keys = sealed_sender_v1::EphemeralKeys::calculate(
1866 &our_identity.into(),
1867 &ephemeral_public,
1868 Direction::Receiving,
1869 )?;
1870
1871 let message_key_bytes = match crypto::aes256_ctr_hmacsha256_decrypt(
1872 &encrypted_static,
1873 &eph_keys.cipher_key,
1874 &eph_keys.mac_key,
1875 ) {
1876 Ok(plaintext) => plaintext,
1877 Err(crypto::DecryptionError::BadKeyOrIv) => {
1878 unreachable!("just derived these keys; they should be valid");
1879 }
1880 Err(crypto::DecryptionError::BadCiphertext(msg)) => {
1881 log::error!("failed to decrypt sealed sender v1 message key: {msg}");
1882 return Err(SignalProtocolError::InvalidSealedSenderMessage(
1883 "failed to decrypt sealed sender v1 message key".to_owned(),
1884 ));
1885 }
1886 };
1887
1888 let static_key = PublicKey::try_from(&message_key_bytes[..])?;
1889
1890 let static_keys = sealed_sender_v1::StaticKeys::calculate(
1891 &our_identity,
1892 &static_key,
1893 &eph_keys.chain_key,
1894 &encrypted_static,
1895 )?;
1896
1897 let message_bytes = match crypto::aes256_ctr_hmacsha256_decrypt(
1898 &encrypted_message,
1899 &static_keys.cipher_key,
1900 &static_keys.mac_key,
1901 ) {
1902 Ok(plaintext) => plaintext,
1903 Err(crypto::DecryptionError::BadKeyOrIv) => {
1904 unreachable!("just derived these keys; they should be valid");
1905 }
1906 Err(crypto::DecryptionError::BadCiphertext(msg)) => {
1907 log::error!("failed to decrypt sealed sender v1 message contents: {msg}");
1908 return Err(SignalProtocolError::InvalidSealedSenderMessage(
1909 "failed to decrypt sealed sender v1 message contents".to_owned(),
1910 ));
1911 }
1912 };
1913
1914 let usmc = UnidentifiedSenderMessageContent::deserialize(&message_bytes)?;
1915
1916 if !bool::from(message_key_bytes.ct_eq(&usmc.sender()?.key()?.serialize())) {
1917 return Err(SignalProtocolError::InvalidSealedSenderMessage(
1918 "sender certificate key does not match message key".to_string(),
1919 ));
1920 }
1921
1922 Ok(usmc)
1923 }
1924 UnidentifiedSenderMessage::V2 {
1925 ephemeral_public,
1926 encrypted_message_key,
1927 authentication_tag,
1928 encrypted_message,
1929 } => {
1930 let m = sealed_sender_v2::apply_agreement_xor(
1931 &our_identity.into(),
1932 &ephemeral_public,
1933 Direction::Receiving,
1934 encrypted_message_key,
1935 )?;
1936
1937 let keys = sealed_sender_v2::DerivedKeys::new(&m);
1938 if !bool::from(keys.derive_e().public_key.ct_eq(&ephemeral_public)) {
1939 return Err(SignalProtocolError::InvalidSealedSenderMessage(
1940 "derived ephemeral key did not match key provided in message".to_string(),
1941 ));
1942 }
1943
1944 let mut message_bytes = Vec::from(encrypted_message);
1945 Aes256GcmSiv::new(&keys.derive_k().into())
1946 .decrypt_in_place(
1947 &aes_gcm_siv::Nonce::default(),
1949 &[],
1951 &mut message_bytes,
1952 )
1953 .map_err(|err| {
1954 SignalProtocolError::InvalidSealedSenderMessage(format!(
1955 "failed to decrypt inner message: {err}"
1956 ))
1957 })?;
1958
1959 let usmc = UnidentifiedSenderMessageContent::deserialize(&message_bytes)?;
1960
1961 let at = sealed_sender_v2::compute_authentication_tag(
1962 &our_identity,
1963 &usmc.sender()?.key()?.into(),
1964 Direction::Receiving,
1965 &ephemeral_public,
1966 encrypted_message_key,
1967 )?;
1968 if !bool::from(authentication_tag.ct_eq(&at)) {
1969 return Err(SignalProtocolError::InvalidSealedSenderMessage(
1970 "sender certificate key does not match authentication tag".to_string(),
1971 ));
1972 }
1973
1974 Ok(usmc)
1975 }
1976 }
1977}
1978
1979#[derive(Debug)]
1980pub struct SealedSenderDecryptionResult {
1981 pub sender_uuid: String,
1982 pub sender_e164: Option<String>,
1983 pub device_id: DeviceId,
1984 pub message: Vec<u8>,
1985}
1986
1987impl SealedSenderDecryptionResult {
1988 pub fn sender_uuid(&self) -> Result<&str> {
1989 Ok(self.sender_uuid.as_ref())
1990 }
1991
1992 pub fn sender_e164(&self) -> Result<Option<&str>> {
1993 Ok(self.sender_e164.as_deref())
1994 }
1995
1996 pub fn device_id(&self) -> Result<DeviceId> {
1997 Ok(self.device_id)
1998 }
1999
2000 pub fn message(&self) -> Result<&[u8]> {
2001 Ok(self.message.as_ref())
2002 }
2003}
2004
2005#[expect(clippy::too_many_arguments)]
2013pub async fn sealed_sender_decrypt(
2014 ciphertext: &[u8],
2015 trust_root: &PublicKey,
2016 timestamp: Timestamp,
2017 local_e164: Option<String>,
2018 local_uuid: String,
2019 local_device_id: DeviceId,
2020 identity_store: &mut dyn IdentityKeyStore,
2021 session_store: &mut dyn SessionStore,
2022 pre_key_store: &mut dyn PreKeyStore,
2023 signed_pre_key_store: &dyn SignedPreKeyStore,
2024 kyber_pre_key_store: &mut dyn KyberPreKeyStore,
2025) -> Result<SealedSenderDecryptionResult> {
2026 let usmc = sealed_sender_decrypt_to_usmc(ciphertext, identity_store).await?;
2027
2028 if !usmc.sender()?.validate(trust_root, timestamp)? {
2029 return Err(SignalProtocolError::InvalidSealedSenderMessage(
2030 "trust root validation failed".to_string(),
2031 ));
2032 }
2033
2034 let is_local_uuid = local_uuid == usmc.sender()?.sender_uuid()?;
2035
2036 let is_local_e164 = match (local_e164, usmc.sender()?.sender_e164()?) {
2037 (Some(l), Some(s)) => l == s,
2038 (_, _) => false,
2039 };
2040
2041 if (is_local_e164 || is_local_uuid) && usmc.sender()?.sender_device_id()? == local_device_id {
2042 return Err(SignalProtocolError::SealedSenderSelfSend);
2043 }
2044
2045 let mut rng = rand::rngs::OsRng.unwrap_err();
2046
2047 let remote_address = ProtocolAddress::new(
2048 usmc.sender()?.sender_uuid()?.to_string(),
2049 usmc.sender()?.sender_device_id()?,
2050 );
2051 let local_address = ProtocolAddress::new(local_uuid, local_device_id);
2052
2053 let message = match usmc.msg_type()? {
2054 CiphertextMessageType::Whisper => {
2055 let ctext = SignalMessage::try_from(usmc.contents()?)?;
2056 session_management::message_decrypt_signal(
2057 &ctext,
2058 &remote_address,
2059 &local_address,
2060 session_store,
2061 identity_store,
2062 &mut rng,
2063 )
2064 .await?
2065 }
2066 CiphertextMessageType::PreKey => {
2067 let ctext = PreKeySignalMessage::try_from(usmc.contents()?)?;
2068 session_management::message_decrypt_prekey(
2069 &ctext,
2070 &remote_address,
2071 &local_address,
2072 session_store,
2073 identity_store,
2074 pre_key_store,
2075 signed_pre_key_store,
2076 kyber_pre_key_store,
2077 &mut rng,
2078 )
2079 .await?
2080 .plaintext
2081 }
2082 msg_type => {
2083 return Err(SignalProtocolError::InvalidMessage(
2084 msg_type,
2085 format!("unexpected message type for sealed_sender_decrypt: {msg_type:?}"),
2086 ));
2087 }
2088 };
2089
2090 Ok(SealedSenderDecryptionResult {
2091 sender_uuid: usmc.sender()?.sender_uuid()?.to_string(),
2092 sender_e164: usmc.sender()?.sender_e164()?.map(|s| s.to_string()),
2093 device_id: usmc.sender()?.sender_device_id()?,
2094 message,
2095 })
2096}
2097
2098#[test]
2099fn test_lossless_round_trip() -> Result<()> {
2100 let trust_root = PrivateKey::deserialize(&[0u8; 32])?;
2101
2102 let certificate_data = const_str::hex!(
2155 "100119697a0000000000002221056c9d1f8deb82b9a898f9c277a1b74989ec009afb5c0acb5e8e69e3d5ca29d6322a690a2508011221053b03ca070e6f6b2f271d32f27321689cdf4e59b106c10b58fbe15063ed868a5a124024bc92954e52ad1a105b5bda85c9db410dcfeb42a671b45a523b3a46e9594a8bde0efc671d8e8e046b32c67f59b80a46ffdf24071850779bc21325107902af89322461616161616161612d373030302d313165622d623332612d333362386138613438376136ba3e136372617368696e6720726967687420646f776e"
2156 );
2157 let certificate_signature = const_str::hex!(
2158 "a22d8f86f5d00794f319add821e342c6ffffb6b34f741e569f8b321ab0255f2d1757ecf648e53a3602cae8f09b3fc80dcf27534d67efd272b6739afc31f75c8c"
2159 );
2160
2161 let sender_certificate_data = proto::sealed_sender::SenderCertificate {
2162 certificate: Some(certificate_data.to_vec()),
2163 signature: Some(certificate_signature.to_vec()),
2164 };
2165
2166 let sender_certificate =
2167 SenderCertificate::deserialize(&sender_certificate_data.encode_to_vec())?;
2168 assert_eq!(
2169 sender_certificate.sender_uuid().expect("valid"),
2170 "aaaaaaaa-7000-11eb-b32a-33b8a8a487a6",
2171 );
2172 assert_eq!(sender_certificate.sender_e164().expect("valid"), None);
2173 assert_eq!(
2174 sender_certificate.sender_device_id().expect("valid"),
2175 DeviceId::new(1).expect("valid"),
2176 );
2177 assert_eq!(
2178 sender_certificate
2179 .expiration()
2180 .expect("valid")
2181 .epoch_millis(),
2182 31337
2183 );
2184 assert!(sender_certificate.validate(
2185 &trust_root.public_key()?,
2186 Timestamp::from_epoch_millis(31336)
2187 )?);
2188 Ok(())
2189}
2190
2191#[test]
2192fn test_uuid_bytes_representation() -> Result<()> {
2193 let trust_root = PrivateKey::deserialize(&[0u8; 32])?;
2194
2195 let certificate_data = const_str::hex!(
2197 "100119697a000000000000222105e083a8ce423d1c1955174107a85a6a7f3bcbf566723624077f75eafe8e0a07752a690a25080112210507a24397ae27d06fa76d2f02cfb5546e0b23a7e0c3670c1eb1e73b135a8e1e4d12407d127509ae1f5e9dcaa511793d3e94350dcb269e4ca54500da6e1f4dc13d95940c15badef019edfe8666315500c54e4489d4b83f6ce79c7f65c9772a1a83d88c3a10aaaaaaaa700011ebb32a33b8a8a487a6"
2198 );
2199 let certificate_signature = const_str::hex!(
2200 "755c428e9bf6ba367152f1e545834649b4e8f70df8383a352a953fdb774862af5d42fab573fc52b90ad47c331c36f93b1a4fa7a2504917d895452ffe7f44bd0e"
2201 );
2202
2203 let sender_certificate_data = proto::sealed_sender::SenderCertificate {
2204 certificate: Some(certificate_data.to_vec()),
2205 signature: Some(certificate_signature.to_vec()),
2206 };
2207
2208 let sender_certificate =
2209 SenderCertificate::deserialize(&sender_certificate_data.encode_to_vec())?;
2210 assert_eq!(
2211 sender_certificate.sender_uuid().expect("valid"),
2212 "aaaaaaaa-7000-11eb-b32a-33b8a8a487a6",
2213 );
2214 assert_eq!(sender_certificate.sender_e164().expect("valid"), None);
2215 assert_eq!(
2216 sender_certificate.sender_device_id().expect("valid"),
2217 DeviceId::new(1).expect("valid"),
2218 );
2219 assert_eq!(
2220 sender_certificate
2221 .expiration()
2222 .expect("valid")
2223 .epoch_millis(),
2224 31337
2225 );
2226 assert!(sender_certificate.validate(
2227 &trust_root.public_key()?,
2228 Timestamp::from_epoch_millis(31336)
2229 )?);
2230 Ok(())
2231}
2232
2233#[test]
2234fn test_known_server_cert() -> Result<()> {
2235 let trust_root = PrivateKey::deserialize(&[0u8; 32])?;
2246 let certificate_data = const_str::hex!(
2249 "100119697a000000000000222105d75b13e15c7700079dd226f51e5a790ba395e819e88a74d0cf5cedfad8b4334840d786df9a07322461616161616161612d373030302d313165622d623332612d333362386138613438376136"
2250 );
2251 let certificate_signature = const_str::hex!(
2252 "e62667bce627caed56ca2ab309b6ae7bc890a30a7482c0e1fd77ec9c3b7528abfd45c8c42b240509a71d973ef5e0f1dbd2685fe01410f0fdbaa8fb247a67e08f"
2253 );
2254
2255 let sender_certificate_data = proto::sealed_sender::SenderCertificate {
2256 certificate: Some(certificate_data.to_vec()),
2257 signature: Some(certificate_signature.to_vec()),
2258 };
2259
2260 let sender_certificate =
2261 SenderCertificate::deserialize(&sender_certificate_data.encode_to_vec())?;
2262 assert!(sender_certificate.validate(
2263 &trust_root.public_key()?,
2264 Timestamp::from_epoch_millis(31336)
2265 )?);
2266
2267 Ok(())
2268}
2269
2270#[test]
2271fn verify_known_certificates() {
2272 assert!(
2273 KNOWN_SERVER_CERTIFICATES
2274 .iter()
2275 .map(|(id, _trust_root, _cert)| id)
2276 .all_unique(),
2277 "all known certificate IDs must be unique"
2278 );
2279
2280 for (id, trust_root, cert) in KNOWN_SERVER_CERTIFICATES {
2281 let trust_root = PublicKey::deserialize(trust_root)
2282 .unwrap_or_else(|e| panic!("[{id:x}] has invalid trust root: {e}"));
2283 let cert = ServerCertificate::deserialize(cert)
2284 .unwrap_or_else(|e| panic!("[{id:x}] has invalid certificate data: {e}"));
2285 assert_eq!(*id, cert.key_id, "[{id:x}] mismatched certificate ID");
2286 assert!(
2287 cert.validate(&trust_root).expect("can validate"),
2288 "[{id:x}] has wrong trust root"
2289 );
2290 }
2291}