Skip to main content

libsignal_protocol/
sealed_sender.rs

1//
2// Copyright 2020-2022 Signal Messenger, LLC.
3// SPDX-License-Identifier: AGPL-3.0-only
4//
5
6use 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
40/*
410xDEADC357 is a server certificate ID which is used to test the
42revocation logic. As of this writing, no prod server certificates have
43been revoked. If one ever does, add its key ID here.
44
45If a production server certificate is ever generated which collides
46with this test certificate ID, Bad Things will happen.
47*/
48const REVOKED_SERVER_CERTIFICATE_KEY_IDS: &[u32] = &[0xDEADC357];
49
50/// A set of server certificates that can be omitted from sender certificates for space savings,
51/// keyed by ID.
52///
53/// The middle item is the trust root for the signature in the certificate, used to check integrity
54/// and potentially to filter out irrelevant certificates during validation. This is the serialized
55/// bytes of an XEd25519 public key, without the leading "type byte" used by the PublicKey type.
56///
57/// Technically the ID is also stored in the certificate data, but listing it here makes it easier
58/// for maintainers to tell which certificates are present.
59const KNOWN_SERVER_CERTIFICATES: &[(u32, [u8; 33], &[u8])] = &[
60    (
61        2,
62        // A trust root used in Staging (but this crate doesn't care about staging / production)
63        data_encoding_macro::base64!("BYhU6tPjqP46KGZEzRs1OL4U39V5dlPJ/X09ha4rErkm"),
64        &const_str::hex!(
65            "0a25080212210539450d63ebd0752c0fd4038b9d07a916f5e174b756d409b5ca79f4c97400631e124064c5a38b1e927497d3d4786b101a623ab34a7da3954fae126b04dba9d7a3604ed88cdc8550950f0d4a9134ceb7e19b94139151d2c3d6e1c81e9d1128aafca806"
66        ),
67    ),
68    (
69        3,
70        // A trust root used in Production (but this crate doesn't care about staging / production)
71        data_encoding_macro::base64!("BUkY0I+9+oPgDCn4+Ac6Iu813yvqkDr/ga8DzLxFxuk6"),
72        &const_str::hex!(
73            "0a250803122105bc9d1d290be964810dfa7e94856480a3f7060d004c9762c24c575a1522353a5a1240c11ec3c401eb0107ab38f8600e8720a63169e0e2eb8a3fae24f63099f85ea319c3c1c46d3454706ae2a679d1fee690a488adda98a2290b66c906bb60295ed781"
74        ),
75    ),
76    (
77        // "Test cert"
78        0x7357C357,
79        // This is the public key that corresponds to a private key of all zeros, which will never
80        // be used in a real service or trusted by a real app.
81        data_encoding_macro::base64!("BS/lfaNHzWJDFSjarF+7KQcw//aEr8TPwu2QmV9Yyzt0"),
82        // And we use it to sign a server certificate for a private key of all 0xFF bytes, also
83        // never used in a real service.
84        &const_str::hex!(
85            "0a2908d786df9a07122105847c0d2c375234f365e660955187a3735a0f7613d1609d3a6a4d8c53aeaa5a221240e0b9ebacdfc3aa2827f7924b697784d1c25e44ca05dd433e1a38dc6382eb2730d419ca9a250b1be9d5a9463e61efd6781777a91b83c97b844d014206e2829785"
86        ),
87    ),
88];
89
90// Valid registration IDs fit in 14 bits.
91// TODO: move this into a RegistrationId strong type.
92const 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                // For now, map this back to a string locally.
253                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        // Check the signer against every trust root to hide which one was the correct one.
341        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        // Keep raw values in sync from now on, for efficient codegen.
440        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        // Keep raw values in sync from now on, for efficient codegen.
454        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                // XXX should we really be accepted version == 0 here?
648                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                /// Uses a flat representation: C || AT || E.pub || ciphertext
671                #[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    /// A symmetric cipher key and a MAC key, along with a "chain key" consumed in
711    /// [`StaticKeys::calculate`].
712    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        /// Derive a set of symmetric keys from the key agreement between the sender and
722        /// recipient's identities.
723        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    /// A symmetric cipher key and a MAC key.
775    pub(super) struct StaticKeys {
776        pub(super) cipher_key: [u8; 32],
777        pub(super) mac_key: [u8; 32],
778    }
779
780    impl StaticKeys {
781        /// Derive a set of symmetric keys from the agreement between the sender and
782        /// recipient's identities, as well as [`EphemeralKeys::chain_key`].
783        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            // 96 bytes are derived, but the first 32 are discarded/unused. This is intended to
793            // mirror the way the EphemeralKeys are derived, even though StaticKeys does not end up
794            // requiring a third "chain key".
795            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        // The sender and recipient each have a long-term identity key pair.
811        let sender_identity = IdentityKeyPair::generate(&mut rand::rng());
812        let recipient_identity = IdentityKeyPair::generate(&mut rand::rng());
813
814        // Generate an ephemeral key pair.
815        let sender_ephemeral = KeyPair::generate(&mut rand::rng());
816        let ephemeral_public = sender_ephemeral.public_key;
817        // Generate ephemeral cipher, chain, and MAC keys.
818        let sender_eph_keys = EphemeralKeys::calculate(
819            &sender_ephemeral,
820            recipient_identity.public_key(),
821            Direction::Sending,
822        )?;
823
824        // Encrypt the sender's public key with AES-256 CTR and a MAC.
825        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        // Generate another cipher and MAC key.
833        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        // The message recipient calculates the ephemeral key and the sender's public key.
849        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
884/// Encrypt the plaintext message `ptext`, generate an [`UnidentifiedSenderMessageContent`], then
885/// pass the result to [`sealed_sender_encrypt_from_usmc`].
886///
887/// This is a simple way to encrypt a message in a 1:1 using [Sealed Sender v1].
888///
889/// [Sealed Sender v1]: sealed_sender_encrypt_from_usmc
890pub 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
923/// This method implements the single-key single-recipient [KEM] described in [this Signal blog
924/// post], a.k.a. Sealed Sender v1.
925///
926/// [KEM]: https://en.wikipedia.org/wiki/Key_encapsulation
927/// [this Signal blog post]: https://signal.org/blog/sealed-sender/
928///
929/// [`sealed_sender_decrypt`] is used in the client to decrypt the Sealed Sender message produced by
930/// this method.
931///
932/// # Contrast with Sealed Sender v2
933/// The *single-recipient* KEM scheme implemented by this method partially derives the encryption
934/// key from the recipient's identity key, which would then require re-encrypting the same message
935/// multiple times to send to multiple recipients. In contrast,
936/// [Sealed Sender v2](sealed_sender_multi_recipient_encrypt) uses a *multi-recipient* KEM scheme
937/// which avoids this repeated work, but makes a few additional design tradeoffs.
938///
939/// # High-level algorithmic overview
940/// The KEM scheme implemented by this method is described in [this Signal blog post]. The
941/// high-level steps of this process are listed below:
942/// 1. Generate a random key pair.
943/// 2. Derive a symmetric chain key, cipher key, and MAC key from the recipient's public key and the
944///    sender's public/private key pair.
945/// 3. Symmetrically encrypt the sender's public key using the cipher key and MAC key from (2) with
946///    AES-256 in CTR mode.
947/// 4. Derive a second symmetric cipher key and MAC key from the sender's private key, the
948///    recipient's public key, and the chain key from (2).
949/// 5. Symmetrically encrypt the underlying [`UnidentifiedSenderMessageContent`] using the cipher key
950///    and MAC key from (4) with AES-256 in CTR mode.
951/// 6. Send the ephemeral public key from (1) and the encrypted public key from (3) to the
952///    recipient, along with the encrypted message (5).
953///
954/// ## Pseudocode
955///```text
956/// e_pub, e_priv                  = X25519.generateEphemeral()
957/// e_chain, e_cipherKey, e_macKey = HKDF(salt="UnidentifiedDelivery" || recipientIdentityPublic || e_pub, ikm=ECDH(recipientIdentityPublic, e_priv), info="")
958/// e_ciphertext                   = AES_CTR(key=e_cipherKey, input=senderIdentityPublic)
959/// e_mac                          = Hmac256(key=e_macKey, input=e_ciphertext)
960///
961/// s_cipherKey, s_macKey = HKDF(salt=e_chain || e_ciphertext || e_mac, ikm=ECDH(recipientIdentityPublic, senderIdentityPrivate), info="")
962/// s_ciphertext          = AES_CTR(key=s_cipherKey, input=sender_certificate || message_ciphertext)
963/// s_mac                 = Hmac256(key=s_macKey, input=s_ciphertext)
964///
965/// message_to_send = s_ciphertext || s_mac
966///```
967///
968/// # Wire Format
969/// The output of this method is encoded as an `UnidentifiedSenderMessage.Message` from
970/// `sealed_sender.proto`, prepended with an additional byte to indicate the version of Sealed
971/// Sender in use (see [further documentation on the version
972/// byte](sealed_sender_multi_recipient_encrypt#the-version-byte)).
973pub 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    // Static byte strings used as part of a MAC in HKDF.
1035    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    /// SSv2 hardcodes that its keys are Curve25519 public keys.
1045    pub const PUBLIC_KEY_LEN: usize = 32;
1046
1047    /// An asymmetric and a symmetric cipher key.
1048    pub(super) struct DerivedKeys {
1049        kdf: hkdf::Hkdf<sha2::Sha256>,
1050    }
1051
1052    impl DerivedKeys {
1053        /// Initialize from a slice of random bytes `m`.
1054        pub(super) fn new(m: &[u8]) -> DerivedKeys {
1055            Self {
1056                kdf: hkdf::Hkdf::<sha2::Sha256>::new(None, m),
1057            }
1058        }
1059
1060        /// Derive the ephemeral asymmetric keys.
1061        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        /// Derive the symmetric cipher key.
1071        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    /// Encrypt or decrypt a slice of random bytes `input` using a shared secret derived from
1081    /// `our_keys` and `their_key`.
1082    ///
1083    /// The output of this method when called with [`Direction::Sending`] can be inverted to produce
1084    /// the original `input` bytes if called with [`Direction::Receiving`] with `our_keys` and
1085    /// `their_key` swapped.
1086    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    /// Compute an [authentication tag] for the bytes `encrypted_message_key` using a shared secret
1119    /// derived from `our_keys` and `their_key`.
1120    ///
1121    /// [authentication tag]: https://en.wikipedia.org/wiki/Message_authentication_code
1122    ///
1123    /// The output of this method with [`Direction::Sending`] should be the same bytes produced by
1124    /// calling this method with [`Direction::Receiving`] with `our_keys` and `their_key`
1125    /// swapped, if `ephemeral_pub_key` and `encrypted_message_key` are the same.
1126    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        // The sender and recipient each have a long-term identity key pair.
1160        let sender_identity = IdentityKeyPair::generate(&mut rand::rng());
1161        let recipient_identity = IdentityKeyPair::generate(&mut rand::rng());
1162
1163        // Generate random bytes used for our multi-recipient encoding scheme.
1164        let m: [u8; MESSAGE_KEY_LEN] = rand::rng().random();
1165        // Derive an ephemeral key pair from those random bytes.
1166        let ephemeral_keys = DerivedKeys::new(&m);
1167        let e = ephemeral_keys.derive_e();
1168
1169        // Encrypt the ephemeral key pair.
1170        let sender_c_0: [u8; MESSAGE_KEY_LEN] =
1171            apply_agreement_xor(&e, recipient_identity.public_key(), Direction::Sending, &m)?;
1172        // Compute an authentication tag for the encrypted key pair.
1173        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        // The message recipient calculates the original random bytes and authenticates the result.
1182        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
1203/// This method implements a single-key multi-recipient [KEM] as defined in Manuel Barbosa's
1204/// ["Randomness Reuse: Extensions and Improvements"], a.k.a. Sealed Sender v2.
1205///
1206/// [KEM]: https://en.wikipedia.org/wiki/Key_encapsulation
1207/// ["Randomness Reuse: Extensions and Improvements"]: https://haslab.uminho.pt/mbb/files/reuse.pdf
1208///
1209/// # Contrast with Sealed Sender v1
1210/// The KEM scheme implemented by this method uses the "Generic Construction" in `4.1` of [Barbosa's
1211/// paper]["Randomness Reuse: Extensions and Improvements"], instantiated with [ElGamal encryption].
1212/// This technique enables reusing a single sequence of random bytes across multiple messages with
1213/// the same content, which reduces computation time for clients sending the same message to
1214/// multiple recipients (without compromising the message security).
1215///
1216/// There are a few additional design tradeoffs this method makes vs [Sealed Sender v1] which may
1217/// make it comparatively unwieldy for certain scenarios:
1218/// 1. it requires a [`SessionRecord`] to exist already for the recipient, i.e. that a Double
1219///    Ratchet message chain has previously been established in the [`SessionStore`] via
1220///    [`process_prekey_bundle`][crate::process_prekey_bundle] after an initial
1221///    [`PreKeySignalMessage`] is received.
1222/// 2. it ferries a lot of additional information in its encoding which makes the resulting message
1223///    bulkier than the message produced by [Sealed Sender v1]. For sending, this will generally
1224///    still be more compact than sending the same message N times, but on the receiver side the
1225///    message is slightly larger.
1226/// 3. unlike other message types sent over the wire, the encoded message returned by this method
1227///    does not use protobuf, in order to avoid inefficiencies produced by protobuf's packing (see
1228///    **[Wire Format]**).
1229///
1230/// [ElGamal encryption]: https://en.wikipedia.org/wiki/ElGamal_encryption
1231/// [Sealed Sender v1]: sealed_sender_encrypt_from_usmc
1232/// [Wire Format]: #wire-format
1233///
1234/// # High-level algorithmic overview
1235/// The high-level steps of this process are summarized below:
1236/// 1. Generate a series of random bytes.
1237/// 2. Derive an ephemeral key pair from (1).
1238/// 3. *Once per recipient:* Encrypt (1) using a shared secret derived from the private ephemeral
1239///    key (2) and the recipient's public identity key.
1240/// 4. *Once per recipient:* Add an authentication tag for (3) using a secret derived from the
1241///    sender's private identity key and the recipient's public identity key.
1242/// 5. Generate a symmetric key from (1) and use it to symmetrically encrypt the underlying
1243///    [`UnidentifiedSenderMessageContent`] via [AEAD encryption]. *This step is only performed once
1244///    per message, regardless of the number of recipients.*
1245/// 6. Send the public ephemeral key (2) to the server, along with the sequence of encrypted random
1246///    bytes (3) and authentication tags (4), and the single encrypted message (5).
1247///
1248/// [AEAD encryption]:
1249///    https://en.wikipedia.org/wiki/Authenticated_encryption#Authenticated_encryption_with_associated_data_(AEAD)
1250///
1251/// ## Pseudocode
1252///```text
1253/// ENCRYPT(message, R_i):
1254///     M = Random(32)
1255///     r = KDF(label_r, M, len=32)
1256///     K = KDF(label_K, M, len=32)
1257///     E = DeriveKeyPair(r)
1258///     for i in num_recipients:
1259///         C_i = KDF(label_DH, DH(E, R_i) || E.public || R_i.public, len=32) XOR M
1260///         AT_i = KDF(label_DH_s, DH(S, R_i) || E.public || C_i || S.public || R_i.public, len=16)
1261///     ciphertext = AEAD_Encrypt(K, message)
1262///     return E.public, C_i, AT_i, ciphertext
1263///
1264/// DECRYPT(E.public, C, AT, ciphertext):
1265///     M = KDF(label_DH, DH(E, R) || E.public || R.public, len=32) xor C
1266///     r = KDF(label_r, M, len=32)
1267///     K = KDF(label_K, M, len=32)
1268///     E' = DeriveKeyPair(r)
1269///     if E.public != E'.public:
1270///         return DecryptionError
1271///     message = AEAD_Decrypt(K, ciphertext) // includes S.public
1272///     AT' = KDF(label_DH_s, DH(S, R) || E.public || C || S.public || R.public, len=16)
1273///     if AT != AT':
1274///         return DecryptionError
1275///     return message
1276///```
1277///
1278/// # Routing messages to recipients
1279///
1280/// The server will split up the set of messages and securely route each individual [received
1281/// message][receiving] to its intended recipient. [`SealedSenderV2SentMessage`] can perform this
1282/// fan-out operation.
1283///
1284/// # Wire Format
1285/// Multi-recipient sealed-sender does not use protobufs for its payload format. Instead, it uses a
1286/// flat format marked with a [version byte](#the-version-byte). The format is different for
1287/// [sending] and [receiving]. The decrypted content is a protobuf-encoded
1288/// `UnidentifiedSenderMessage.Message` from `sealed_sender.proto`.
1289///
1290/// The public key used in Sealed Sender v2 is always a Curve25519 DJB key.
1291///
1292/// [sending]: #sent-messages
1293/// [receiving]: #received-messages
1294///
1295/// ## The version byte
1296///
1297/// Sealed sender messages (v1 and v2) in serialized form begin with a version [byte][u8]. This byte
1298/// has the form:
1299///
1300/// ```text
1301/// (requiredVersion << 4) | currentVersion
1302/// ```
1303///
1304/// v1 messages thus have a version byte of `0x11`. v2 messages have a version byte of `0x22` or
1305/// `0x23`. A hypothetical version byte `0x34` would indicate a message encoded as Sealed Sender v4,
1306/// but decodable by any client that supports Sealed Sender v3.
1307///
1308/// ## Received messages
1309///
1310/// ```text
1311/// ReceivedMessage {
1312///     version_byte: u8,
1313///     c: [u8; 32],
1314///     at: [u8; 16],
1315///     e_pub: [u8; 32],
1316///     message: [u8] // remaining bytes
1317/// }
1318/// ```
1319///
1320/// Each individual Sealed Sender message received from the server is decoded in the Signal client
1321/// by calling [`sealed_sender_decrypt`].
1322///
1323/// ## Sent messages
1324///
1325/// ```text
1326/// SentMessage {
1327///     version_byte: u8,
1328///     count: varint,
1329///     recipients: [PerRecipientData | ExcludedRecipient; count],
1330///     e_pub: [u8; 32],
1331///     message: [u8] // remaining bytes
1332/// }
1333///
1334/// PerRecipientData {
1335///     recipient: Recipient,
1336///     devices: [DeviceList], // last element's has_more = 0
1337///     c: [u8; 32],
1338///     at: [u8; 16],
1339/// }
1340///
1341/// ExcludedRecipient {
1342///     recipient: Recipient,
1343///     no_devices_marker: u8 = 0, // never a valid device ID
1344/// }
1345///
1346/// DeviceList {
1347///     device_id: u8,
1348///     has_more: u1, // high bit of following field
1349///     unused: u1,   // high bit of following field
1350///     registration_id: u14,
1351/// }
1352///
1353/// Recipient {
1354///     service_id_fixed_width_binary: [u8; 17],
1355/// }
1356/// ```
1357///
1358/// The varint encoding used is the same as [protobuf's][varint]. Values are unsigned.
1359/// Fixed-width-binary encoding is used for the [ServiceId] values.
1360/// Fixed-width integers are unaligned and in network byte order (big-endian).
1361///
1362/// [varint]: https://developers.google.com/protocol-buffers/docs/encoding#varints
1363pub 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    // Encrypt the shared ciphertext using AES-GCM-SIV.
1417    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                // There's no nonce because the key is already one-use.
1422                &aes_gcm_siv::Nonce::default(),
1423                // And there's no associated data.
1424                &[],
1425                (&mut ciphertext[..]).into(),
1426            )
1427            .expect("AES-GCM-SIV encryption should not fail with a just-computed key");
1428        // AES-GCM-SIV expects the authentication tag to be at the end of the ciphertext
1429        // when decrypting.
1430        ciphertext.extend_from_slice(&symmetric_authentication_tag);
1431        ciphertext
1432    };
1433
1434    // Group the destinations by name, and fetch identity keys once for each name. This optimizes
1435    // for the common case where all of a recipient's devices are included contiguously in the
1436    // destination list. (If the caller *doesn't* do this, that's on them; the message will still be
1437    // valid but some key material will be redundantly computed and encoded in the output.)
1438    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            // We can't put this before the call to `next()` because `count` consumes the rest of
1449            // the iterator.
1450            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                        // Returned as a SessionNotFound error because (a) we don't have an identity
1458                        // error that includes the address, and (b) re-establishing the session should
1459                        // re-fetch the identity.
1460                        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    // Next, fan out the work of generating the per-recipient to multiple cores, since we do two key
1471    // agreements per recipient (though not per device) and those are CPU-bound.
1472
1473    // I know this looks complicated enough to pull out into a separate function altogether, but it
1474    // also depends on a bunch of local state: our identity, E and E_pub, and M.
1475    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    // Fan out to N threads, like Rayon would. But don't bother for less than 6 items.
1570    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        // We'll process the first chunk on the current thread once we've spawned all the others.
1580        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
1617/// Represents a single recipient in an SSv2 SentMessage.
1618///
1619/// See [`SealedSenderV2SentMessage`].
1620pub struct SealedSenderV2SentMessageRecipient<'a> {
1621    /// The recipient's devices and their registration IDs. May be empty.
1622    pub devices: Vec<(DeviceId, u16)>,
1623    /// A concatenation of the `C_i` and `AT_i` SSv2 fields for this recipient, or an empty slice if
1624    /// the recipient has no devices.
1625    c_and_at: &'a [u8],
1626}
1627
1628/// A parsed representation of a Sealed Sender v2 SentMessage.
1629///
1630/// This only parses enough to fan out the message as a series of ReceivedMessages.
1631pub struct SealedSenderV2SentMessage<'a> {
1632    /// The full message, for calculating offsets.
1633    full_message: &'a [u8],
1634    /// The version byte at the head of the message.
1635    pub version: u8,
1636    /// The parsed list of recipients, grouped by ServiceId.
1637    ///
1638    /// The map is ordered by when a recipient first appears in the full message, even if they
1639    /// appear again later with more devices. This makes iteration over the full set of recipients
1640    /// deterministic.
1641    pub recipients: IndexMap<ServiceId, SealedSenderV2SentMessageRecipient<'a>>,
1642    /// A concatenation of the `e_pub` and `message` SSv2 fields for this recipient.
1643    shared_bytes: &'a [u8],
1644}
1645
1646impl<'a> SealedSenderV2SentMessage<'a> {
1647    /// Parses the message, or produces an error if the message is invalid.
1648    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        // Cap our preallocated capacity; anything higher than this is *probably* a mistake, but
1685        // could just be a very large message.
1686        // (Callers can of course refuse to process messages with too many recipients.)
1687        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                // The original version of SSv2 assumed ACIs here, and only encoded the raw UUID.
1692                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                    // We don't unique the recipient devices; the server is going to check this
1742                    // against the account's canonical list of devices anyway.
1743                    existing.get_mut().devices.extend(devices);
1744                    // Note that we don't check that c_and_at matches. Any case where it doesn't
1745                    // match would already result in a decryption error for at least one of the
1746                    // recipient's devices, though.
1747                }
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    /// Returns a slice of slices that, when concatenated, form the ReceivedMessage appropriate for
1767    /// `recipient`.
1768    ///
1769    /// If `recipient` is not one of the recipients in `self`, the resulting message will not be
1770    /// decryptable.
1771    #[inline]
1772    pub fn received_message_parts_for_recipient(
1773        &self,
1774        recipient: &SealedSenderV2SentMessageRecipient<'a>,
1775    ) -> impl AsRef<[&[u8]]> {
1776        // Why not use `IntoIterator<Item = &[u8]>` as the result? Because the `concat` method on
1777        // slices is more efficient when the caller just wants a `Vec<u8>`.
1778        // Why use SEALED_SENDER_V2_UUID_FULL_VERSION as the version? Because the ReceivedMessage
1779        // format hasn't changed since then.
1780        [
1781            &[SEALED_SENDER_V2_UUID_FULL_VERSION],
1782            recipient.c_and_at,
1783            self.shared_bytes,
1784        ]
1785    }
1786
1787    /// Returns the offset of `addr` within `self.full_message`, or `None` if `addr` does not lie
1788    /// within `self.full_message`.
1789    ///
1790    /// TODO: replace with slice::element_offset at MSRV 1.94. That API doesn't accept
1791    /// "one-past-the-end" addresses, but we don't make use of that anyway in either caller.
1792    #[inline]
1793    fn offset_within_full_message(&self, addr: *const u8) -> Option<usize> {
1794        // Arithmetic on addresses is valid for offsets within a byte array.
1795        // If addr < start, we'll wrap around to a very large value, which will be out of range just
1796        // like if addr > end.
1797        let offset = (addr as usize).wrapping_sub(self.full_message.as_ptr() as usize);
1798        // We *do* want to allow the "one-past-the-end" offset here, because the offset might be
1799        // used as part of a range (e.g. 0..end).
1800        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    /// Returns the range within the full message of `recipient`'s user-specific key material.
1811    ///
1812    /// This can be concatenated as `[version, recipient_key_material, shared_bytes]` to produce a
1813    /// valid SSv2 ReceivedMessage, the payload delivered to recipients.
1814    ///
1815    /// **Panics** if `recipient` is not one of the recipients in `self`.
1816    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    /// Returns the offset of the shared bytes within the full message.
1835    ///
1836    /// This can be concatenated as `[version, recipient_key_material, shared_bytes]` to produce a
1837    /// valid SSv2 ReceivedMessage, the payload delivered to recipients.
1838    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
1849/// Decrypt the payload of a sealed-sender message in either the v1 or v2 format.
1850///
1851/// [`sealed_sender_decrypt`] consumes the output of this method to validate the sender's identity
1852/// before decrypting the underlying message.
1853pub 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                    // There's no nonce because the key is already one-use.
1948                    &aes_gcm_siv::Nonce::default(),
1949                    // And there's no associated data.
1950                    &[],
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/// Decrypt a Sealed Sender message `ciphertext` in either the v1 or v2 format, validate its sender
2006/// certificate, and then decrypt the inner message payload.
2007///
2008/// This method calls [`sealed_sender_decrypt_to_usmc`] to extract the sender information, including
2009/// the embedded [`SenderCertificate`]. The sender certificate (signed by the [`ServerCertificate`])
2010/// is then validated against the `trust_root` baked into the client to ensure that the sender's
2011/// identity was not forged.
2012#[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    // To test a hypothetical addition of a new field:
2103    //
2104    // Step 1: temporarily add a new field to the .proto.
2105    //
2106    //    --- a/rust/protocol/src/proto/sealed_sender.proto
2107    //    +++ b/rust/protocol/src/proto/sealed_sender.proto
2108    //    @@ -26,3 +26,4 @@ message SenderCertificate {
2109    //             optional bytes             identityKey   = 4;
2110    //             optional ServerCertificate signer        = 5;
2111    //    +        optional string someFakeField = 999;
2112    //     }
2113    //
2114    // Step 2: Add `some_fake_field: None` to the above construction of
2115    // proto::sealed_sender::sender_certificate::Certificate.
2116    //
2117    // Step 3: Serialize and print out the new fixture data (uncomment the following)
2118    //
2119    // let mut rng = rand::rngs::OsRng.unwrap_err();
2120    // let server_key = KeyPair::generate(&mut rng);
2121    // let sender_key = KeyPair::generate(&mut rng);
2122    //
2123    // let server_cert =
2124    //     ServerCertificate::new(1, server_key.public_key, &trust_root, &mut rng)?;
2125    //
2126    // let sender_cert = proto::sealed_sender::sender_certificate::Certificate {
2127    //     sender_uuid: Some(
2128    //         proto::sealed_sender::sender_certificate::certificate::SenderUuid::UuidString(
2129    //             "aaaaaaaa-7000-11eb-b32a-33b8a8a487a6".to_string(),
2130    //         ),
2131    //     ),
2132    //     sender_e164: None,
2133    //     sender_device: Some(1),
2134    //     expires: Some(31337),
2135    //     identity_key: Some(sender_key.public_key.serialize().to_vec()),
2136    //     signer: Some(
2137    //         proto::sealed_sender::sender_certificate::certificate::Signer::Certificate(
2138    //             server_cert.serialized()?.to_vec(),
2139    //         ),
2140    //     ),
2141    //     some_fake_field: Some("crashing right down".to_string()),
2142    // };
2143    //
2144    // eprintln!("<SNIP>");
2145    // let serialized_certificate_data = sender_cert.encode_to_vec();
2146    // let certificate_data_encoded = hex::encode(&serialized_certificate_data);
2147    // eprintln!("let certificate_data = const_str::hex!(\"{}\");", certificate_data_encoded);
2148    //
2149    // let certificate_signature = server_key.calculate_signature(&serialized_certificate_data, &mut rng)?;
2150    // let certificate_signature_encoded = hex::encode(certificate_signature);
2151    // eprintln!("let certificate_signature = const_str::hex!(\"{}\");", certificate_signature_encoded);
2152
2153    // Step 4: update the following fixture data with the new values from above.
2154    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    // Same structure as above, but using the uuidBytes representation instead of uuidString.
2196    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    // Same structure as test_lossless_round_trip, but using the fixed server key from the 7357c357
2236    // certificate, and a reference to it rather than embedding it.
2237    //
2238    // % pbpaste | xxd -r -p | protoscope
2239    // 2: 1
2240    // 3: 31337i64
2241    // 4: {`05d75b13e15c7700079dd226f51e5a790ba395e819e88a74d0cf5cedfad8b43348`}
2242    // 8: 1935131479
2243    // 6: {"aaaaaaaa-7000-11eb-b32a-33b8a8a487a6"}
2244
2245    let trust_root = PrivateKey::deserialize(&[0u8; 32])?;
2246    // let server_key = PrivateKey::deserialize(&[0xff; 32])?;
2247
2248    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}