Skip to main content

vodozemac/olm/session/
mod.rs

1// Copyright 2021 Damir Jelić
2// Copyright 2021 The Matrix.org Foundation C.I.C.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16mod chain_key;
17mod double_ratchet;
18pub(crate) mod message_key;
19pub(crate) mod ratchet;
20mod receiver_chain;
21mod root_key;
22
23use std::fmt::Debug;
24
25use aes::cipher::block_padding::Error as UnpadError;
26use arrayvec::ArrayVec;
27use chain_key::RemoteChainKey;
28use double_ratchet::DoubleRatchet;
29use hmac::digest::MacError;
30use ratchet::RemoteRatchetKey;
31use receiver_chain::ReceiverChain;
32use root_key::RemoteRootKey;
33use serde::{Deserialize, Serialize};
34use thiserror::Error;
35#[cfg(feature = "low-level-api")]
36use zeroize::Zeroize;
37
38use super::{
39    SessionConfig,
40    session_config::Version,
41    session_keys::SessionKeys,
42    shared_secret::{RemoteShared3DHSecret, Shared3DHSecret},
43};
44#[cfg(feature = "low-level-api")]
45use crate::hazmat::olm::MessageKey;
46use crate::{
47    Curve25519PublicKey, PickleError,
48    olm::{
49        messages::{Message, OlmMessage, PreKeyMessage},
50        session::double_ratchet::RatchetCount,
51    },
52    utilities::{pickle, unpickle},
53};
54
55const MAX_RECEIVING_CHAINS: usize = 5;
56
57/// Error type for Olm-based decryption failures.
58#[derive(Error, Debug)]
59pub enum DecryptionError {
60    /// The message authentication code of the message was invalid.
61    #[error("Failed decrypting Olm message, invalid MAC: {0}")]
62    InvalidMAC(#[from] MacError),
63    /// The length of the message authentication code of the message did not
64    /// match our expected length.
65    #[error("Failed decrypting Olm message, invalid MAC length: expected {0}, got {1}")]
66    InvalidMACLength(usize, usize),
67    /// The ciphertext of the message isn't padded correctly.
68    #[error("Failed decrypting Olm message, invalid padding")]
69    InvalidPadding(#[from] UnpadError),
70    /// One or more keys lacked contributory behavior in the Diffie-Hellman
71    /// operation, resulting in an insecure shared secret.
72    ///
73    /// For more details on contributory behavior please refer to the
74    /// [`x25519_dalek::SharedSecret::was_contributory()`] method.
75    #[error(
76        "One or more keys lacked contributory behavior in the Diffie-Hellman operation, \
77         resulting in an insecure shared secret"
78    )]
79    NonContributoryKey,
80    /// The session is missing the correct message key to decrypt the message,
81    /// either because it was already used up, or because the Session has been
82    /// ratcheted forwards and the message key has been discarded.
83    #[error("The message key with the given key can't be created, message index: {0}")]
84    MissingMessageKey(u64),
85    /// Too many messages have been skipped to attempt decrypting this message.
86    #[error("The message gap was too big, got {0}, max allowed {1}")]
87    TooBigMessageGap(u64, u64),
88}
89
90/// Error type for Olm-based encryption failures.
91#[derive(Error, Debug)]
92pub enum EncryptionError {
93    /// One or more keys lacked contributory behavior in the Diffie-Hellman
94    /// operation, resulting in an insecure shared secret.
95    ///
96    /// For more details on contributory behavior please refer to the
97    /// [`x25519_dalek::SharedSecret::was_contributory()`] method.
98    #[error(
99        "One or more keys lacked contributory behavior in the Diffie-Hellman operation, \
100         resulting in an insecure shared secret"
101    )]
102    NonContributoryKey,
103}
104
105#[derive(Serialize, Deserialize, Clone)]
106struct ChainStore {
107    inner: ArrayVec<ReceiverChain, MAX_RECEIVING_CHAINS>,
108}
109
110impl ChainStore {
111    fn new() -> Self {
112        Self { inner: ArrayVec::new() }
113    }
114
115    fn push(&mut self, ratchet: ReceiverChain) {
116        if self.inner.is_full() {
117            self.inner.pop_at(0);
118        }
119
120        self.inner.push(ratchet)
121    }
122
123    const fn is_empty(&self) -> bool {
124        self.inner.is_empty()
125    }
126
127    #[cfg(test)]
128    pub(crate) const fn len(&self) -> usize {
129        self.inner.len()
130    }
131
132    #[cfg(feature = "libolm-compat")]
133    pub(crate) fn get(&self, index: usize) -> Option<&ReceiverChain> {
134        self.inner.get(index)
135    }
136
137    fn find_ratchet(&mut self, ratchet_key: &RemoteRatchetKey) -> Option<&mut ReceiverChain> {
138        self.inner.iter_mut().find(|r| r.belongs_to(ratchet_key))
139    }
140}
141
142impl Default for ChainStore {
143    fn default() -> Self {
144        Self::new()
145    }
146}
147
148/// An Olm session represents one end of an encrypted communication channel
149/// between two participants.
150///
151/// A session enables enables the session owner to encrypt messages intended
152/// for, and decrypt messages sent by, the other participant of the channel.
153///
154/// Olm sessions have two important properties:
155///
156/// 1. They are based on a double ratchet algorithm which continuously
157///    introduces new entropy into the channel as messages are sent and
158///    received. This imbues the channel with *self-healing* properties,
159///    allowing it to recover from a momentary loss of confidentiality in the
160///    event of a key compromise.
161/// 2. They are *asynchronous*, allowing the participant to start sending
162///    messages to the other side even if the other participant is not online at
163///    the moment.
164///
165/// An Olm [`Session`] is acquired from an [`Account`], by calling either
166///
167/// - [`Account::create_outbound_session`], if you are the first participant to
168///   send a message in this channel, or
169/// - [`Account::create_inbound_session`], if the other participant initiated
170///   the channel by sending you a message.
171///
172/// [`Account`]: crate::olm::Account
173/// [`Account::create_outbound_session`]: crate::olm::Account::create_outbound_session
174/// [`Account::create_inbound_session`]: crate::olm::Account::create_inbound_session
175pub struct Session {
176    session_keys: SessionKeys,
177    sending_ratchet: DoubleRatchet,
178    receiving_chains: ChainStore,
179    config: SessionConfig,
180}
181
182impl Debug for Session {
183    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
184        let Self { session_keys: _, sending_ratchet, receiving_chains, config } = self;
185
186        f.debug_struct("Session")
187            .field("session_id", &self.session_id())
188            .field("sending_ratchet", &sending_ratchet)
189            .field("receiving_chains", &receiving_chains.inner)
190            .field("config", config)
191            .finish_non_exhaustive()
192    }
193}
194
195/// hazmat: a snapshot of the secret key material backing an active Olm sender
196/// chain.
197///
198/// This is the companion type to [`Session::from_root_key_material`] and is
199/// returned by [`Session::active_sending_state`]. It exists so that a
200/// [`Session`] bootstrapped from a non-Olm handshake can be compared for
201/// equivalence against an `Account`-derived [`Session`] — i.e. to assert that
202/// both sides agree on the root key, chain key and ratchet key once the
203/// handshake completes.
204///
205/// As with [`Session::from_root_key_material`], the only thing replaced here is
206/// the Olm 3DH handshake that normally seeds the root key; the Double Ratchet
207/// itself is untouched. See that constructor for the full rationale and an
208/// example.
209///
210/// The three 32-byte secrets are heap-allocated (boxed) and zeroized on drop,
211/// so moving the value around does not leave copies of the key material behind
212/// on the stack.
213#[cfg(feature = "low-level-api")]
214pub struct ActiveSendingState {
215    /// Current root key `R_i` of the active sender chain.
216    pub root_key: Box<[u8; 32]>,
217    /// Current chain key `C_{i,j}` of the active sender chain.
218    pub chain_key: Box<[u8; 32]>,
219    /// Index `j` within the current chain.
220    pub chain_index: u64,
221    /// Secret part of our local ratchet key `T_i`.
222    pub ratchet_key: Box<[u8; 32]>,
223}
224
225#[cfg(feature = "low-level-api")]
226impl Drop for ActiveSendingState {
227    fn drop(&mut self) {
228        self.root_key.zeroize();
229        self.chain_key.zeroize();
230        self.ratchet_key.zeroize();
231    }
232}
233
234#[cfg(feature = "low-level-api")]
235impl Session {
236    /// hazmat: build a [`Session`] directly from raw active-sender key material
237    /// derived outside of Olm.
238    ///
239    /// The supplied `root_key`, `chain_key` and `ratchet_key_secret` become the
240    /// active sending chain's keys *verbatim* — no key derivation, KDF or AEAD
241    /// step is performed here. The supplied [`SessionKeys`] is used solely to
242    /// compute the session ID and to populate the pre-key message envelope; its
243    /// contents are never used as key material.
244    ///
245    /// # When to use this
246    ///
247    /// This is for downstream protocols that run their own authenticated key
248    /// exchange and want to layer vodozemac's audited Double Ratchet on top,
249    /// rather than vendoring a separate ratchet implementation. Typical cases
250    /// are Noise handshakes (for example a Noise `KK` exchange carried over a
251    /// transport such as Tor v3 onion services) or alternative / post-quantum
252    /// KEMs.
253    ///
254    /// This constructor *replaces only the Olm 3DH handshake*: the bytes you
255    /// pass in stand in for the secret that 3DH would normally produce. From
256    /// that point on the Double Ratchet works exactly as it does in a regular
257    /// Olm session — the symmetric-key ratchet advances per message and the DH
258    /// ratchet advances on each received reply.
259    ///
260    /// Both peers must independently derive identical `root_key`, `chain_key`
261    /// and `ratchet_key_secret` material and agree on which side owns the
262    /// initial sending chain; the other side decrypts the first message and the
263    /// DH ratchet converges from there.
264    ///
265    /// # Examples
266    ///
267    /// ```
268    /// use vodozemac::{
269    ///     Curve25519PublicKey,
270    ///     olm::{Session, SessionConfig, SessionKeys},
271    /// };
272    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
273    /// // Secret material produced by your own (non-Olm) handshake. These bytes
274    /// // become the active sender chain's keys verbatim.
275    /// let root_key = [0u8; 32];
276    /// let chain_key = [0u8; 32];
277    /// let ratchet_key_secret = [0u8; 32];
278    ///
279    /// // `SessionKeys` only feeds the session ID and the pre-key message
280    /// // envelope; its contents are not used as key material.
281    /// let session_keys = SessionKeys {
282    ///     identity_key: Curve25519PublicKey::from_bytes([1u8; 32]),
283    ///     base_key: Curve25519PublicKey::from_bytes([2u8; 32]),
284    ///     one_time_key: Curve25519PublicKey::from_bytes([3u8; 32]),
285    /// };
286    ///
287    /// let mut session = Session::from_root_key_material(
288    ///     SessionConfig::version_1(),
289    ///     session_keys,
290    ///     root_key,
291    ///     chain_key,
292    ///     ratchet_key_secret,
293    /// );
294    ///
295    /// // `session` is now a ready-to-use Olm sender.
296    /// let message = session.encrypt("Hello from a non-Olm handshake")?;
297    /// # let _ = message;
298    /// # Ok(())
299    /// # }
300    /// ```
301    pub fn from_root_key_material(
302        config: SessionConfig,
303        session_keys: SessionKeys,
304        root_key: [u8; 32],
305        chain_key: [u8; 32],
306        ratchet_key_secret: [u8; 32],
307    ) -> Self {
308        let sending_ratchet = DoubleRatchet::active_from_root_key_material(
309            root_key::RootKey::new(Box::new(root_key)),
310            chain_key::ChainKey::new(Box::new(chain_key)),
311            ratchet::RatchetKey::from(crate::Curve25519SecretKey::from_slice(&ratchet_key_secret)),
312        );
313        Self { session_keys, sending_ratchet, receiving_chains: ChainStore::new(), config }
314    }
315
316    /// hazmat: read out the active sender chain's raw key material for
317    /// equivalence testing. Returns `None` if there is no active sender chain.
318    pub fn active_sending_state(&self) -> Option<ActiveSendingState> {
319        self.sending_ratchet.active_sending_state()
320    }
321}
322
323impl Session {
324    pub(super) fn new(
325        config: SessionConfig,
326        shared_secret: Shared3DHSecret,
327        session_keys: SessionKeys,
328    ) -> Self {
329        let local_ratchet = DoubleRatchet::active(shared_secret);
330
331        Self {
332            session_keys,
333            sending_ratchet: local_ratchet,
334            receiving_chains: Default::default(),
335            config,
336        }
337    }
338
339    pub(super) fn new_remote(
340        config: SessionConfig,
341        shared_secret: RemoteShared3DHSecret,
342        remote_ratchet_key: Curve25519PublicKey,
343        session_keys: SessionKeys,
344    ) -> Self {
345        let (root_key, remote_chain_key) = shared_secret.expand();
346
347        let remote_ratchet_key = RemoteRatchetKey::from(remote_ratchet_key);
348        let root_key = RemoteRootKey::new(root_key);
349        let remote_chain_key = RemoteChainKey::new(remote_chain_key);
350
351        let local_ratchet = DoubleRatchet::inactive_from_prekey_data(root_key, remote_ratchet_key);
352        let remote_ratchet =
353            ReceiverChain::new(remote_ratchet_key, remote_chain_key, RatchetCount::new());
354
355        let mut ratchet_store = ChainStore::new();
356        ratchet_store.push(remote_ratchet);
357
358        Self {
359            session_keys,
360            sending_ratchet: local_ratchet,
361            receiving_chains: ratchet_store,
362            config,
363        }
364    }
365
366    /// Returns the globally unique session ID, in base64-encoded form.
367    ///
368    /// This is a shorthand helper of the [`SessionKeys::session_id()`] method.
369    pub fn session_id(&self) -> String {
370        self.session_keys.session_id()
371    }
372
373    /// Have we ever received and decrypted a message from the other side?
374    ///
375    /// Used to decide if outgoing messages should be sent as normal or pre-key
376    /// messages.
377    pub const fn has_received_message(&self) -> bool {
378        !self.receiving_chains.is_empty()
379    }
380
381    /// Encrypt the `plaintext` and construct an [`OlmMessage`].
382    ///
383    /// The message will either be a pre-key message or a normal message,
384    /// depending on whether the session is fully established. A [`Session`] is
385    /// fully established once you receive (and decrypt) at least one
386    /// message from the other side.
387    pub fn encrypt(&mut self, plaintext: impl AsRef<[u8]>) -> Result<OlmMessage, EncryptionError> {
388        let message = match self.config.version {
389            Version::V1 => self.sending_ratchet.encrypt_truncated_mac(plaintext.as_ref()),
390            #[cfg(feature = "experimental-session-config")]
391            Version::V2 => self.sending_ratchet.encrypt(plaintext.as_ref()),
392        }?;
393
394        if self.has_received_message() {
395            Ok(OlmMessage::Normal(message))
396        } else {
397            let message = PreKeyMessage::new(self.session_keys, message);
398
399            Ok(OlmMessage::PreKey(message))
400        }
401    }
402
403    /// Get the keys associated with this session.
404    pub const fn session_keys(&self) -> SessionKeys {
405        self.session_keys
406    }
407
408    /// Get the [`SessionConfig`] that this [`Session`] is configured to use.
409    pub const fn session_config(&self) -> SessionConfig {
410        self.config
411    }
412
413    /// Get the [`MessageKey`] to encrypt the next message.
414    ///
415    /// **Note**: Each key obtained in this way should be used to encrypt
416    /// a message and the message must then be sent to the recipient.
417    ///
418    /// Failing to do so will increase the number of out-of-order messages on
419    /// the recipient side. Given that a `Session` can only support a limited
420    /// number of out-of-order messages, this will eventually lead to
421    /// undecryptable messages.
422    #[cfg(feature = "low-level-api")]
423    pub fn next_message_key(&mut self) -> Option<MessageKey> {
424        self.sending_ratchet.next_message_key()
425    }
426
427    /// Try to decrypt an Olm message, which will either return the plaintext or
428    /// result in a [`DecryptionError`].
429    pub fn decrypt(&mut self, message: &OlmMessage) -> Result<Vec<u8>, DecryptionError> {
430        let decrypted = match message {
431            OlmMessage::Normal(m) => self.decrypt_decoded(m)?,
432            OlmMessage::PreKey(m) => self.decrypt_decoded(&m.message)?,
433        };
434
435        Ok(decrypted)
436    }
437
438    pub(super) fn decrypt_decoded(
439        &mut self,
440        message: &Message,
441    ) -> Result<Vec<u8>, DecryptionError> {
442        let ratchet_key = RemoteRatchetKey::from(message.ratchet_key);
443
444        if let Some(ratchet) = self.receiving_chains.find_ratchet(&ratchet_key) {
445            ratchet.decrypt(message, &self.config)
446        } else {
447            let (sending_ratchet, mut remote_ratchet) =
448                self.sending_ratchet
449                    .advance(ratchet_key)
450                    .ok_or(DecryptionError::NonContributoryKey)?;
451
452            let plaintext = remote_ratchet.decrypt(message, &self.config)?;
453
454            self.sending_ratchet = sending_ratchet;
455            self.receiving_chains.push(remote_ratchet);
456
457            Ok(plaintext)
458        }
459    }
460
461    /// Convert the session into a struct which implements [`serde::Serialize`]
462    /// and [`serde::Deserialize`].
463    pub fn pickle(&self) -> SessionPickle {
464        SessionPickle {
465            session_keys: self.session_keys,
466            sending_ratchet: self.sending_ratchet.clone(),
467            receiving_chains: self.receiving_chains.clone(),
468            config: self.config,
469        }
470    }
471
472    /// Restore a [`Session`] from a previously saved [`SessionPickle`].
473    pub fn from_pickle(pickle: SessionPickle) -> Self {
474        pickle.into()
475    }
476
477    /// Create a [`Session`] object by unpickling a session pickle in libolm
478    /// legacy pickle format.
479    ///
480    /// Such pickles are encrypted and need to first be decrypted using
481    /// `pickle_key`.
482    #[cfg(feature = "libolm-compat")]
483    pub fn from_libolm_pickle(
484        pickle: &str,
485        pickle_key: &[u8],
486    ) -> Result<Self, crate::LibolmPickleError> {
487        use crate::{olm::session::libolm_compat::Pickle, utilities::unpickle_libolm};
488
489        const PICKLE_VERSION: u32 = 1;
490        unpickle_libolm::<Pickle, _>(pickle, pickle_key, PICKLE_VERSION)
491    }
492}
493
494#[cfg(feature = "libolm-compat")]
495mod libolm_compat {
496    use matrix_pickle::Decode;
497    use zeroize::{Zeroize, ZeroizeOnDrop};
498
499    use super::{
500        ChainStore, Session,
501        chain_key::{ChainKey, RemoteChainKey},
502        double_ratchet::{DoubleRatchet, RatchetCount},
503        message_key::RemoteMessageKey,
504        ratchet::{Ratchet, RatchetKey, RemoteRatchetKey},
505        receiver_chain::ReceiverChain,
506        root_key::{RemoteRootKey, RootKey},
507    };
508    use crate::{
509        Curve25519PublicKey,
510        olm::{SessionConfig, SessionKeys},
511        types::Curve25519SecretKey,
512    };
513
514    #[derive(Decode, Zeroize, ZeroizeOnDrop)]
515    struct SenderChain {
516        public_ratchet_key: [u8; 32],
517        #[secret]
518        secret_ratchet_key: Box<[u8; 32]>,
519        chain_key: Box<[u8; 32]>,
520        chain_key_index: u32,
521    }
522
523    #[derive(Decode, Zeroize, ZeroizeOnDrop)]
524    struct ReceivingChain {
525        public_ratchet_key: [u8; 32],
526        #[secret]
527        chain_key: Box<[u8; 32]>,
528        chain_key_index: u32,
529    }
530
531    impl From<&ReceivingChain> for ReceiverChain {
532        fn from(chain: &ReceivingChain) -> Self {
533            let ratchet_key = RemoteRatchetKey::from(chain.public_ratchet_key);
534            let chain_key = RemoteChainKey::from_bytes_and_index(
535                chain.chain_key.clone(),
536                chain.chain_key_index,
537            );
538
539            ReceiverChain::new(ratchet_key, chain_key, RatchetCount::unknown())
540        }
541    }
542
543    #[derive(Decode, Zeroize, ZeroizeOnDrop)]
544    struct MessageKey {
545        ratchet_key: [u8; 32],
546        #[secret]
547        message_key: Box<[u8; 32]>,
548        index: u32,
549    }
550
551    impl From<&MessageKey> for RemoteMessageKey {
552        fn from(key: &MessageKey) -> Self {
553            RemoteMessageKey { key: key.message_key.clone(), index: key.index.into() }
554        }
555    }
556
557    #[derive(Decode)]
558    pub(super) struct Pickle {
559        #[expect(
560            dead_code,
561            reason = "part of the libolm pickle format but not needed by vodozemac"
562        )]
563        version: u32,
564        #[expect(
565            dead_code,
566            reason = "part of the libolm pickle format but not needed by vodozemac"
567        )]
568        received_message: bool,
569        session_keys: SessionKeys,
570        #[secret]
571        root_key: Box<[u8; 32]>,
572        sender_chains: Vec<SenderChain>,
573        receiver_chains: Vec<ReceivingChain>,
574        message_keys: Vec<MessageKey>,
575    }
576
577    impl Drop for Pickle {
578        fn drop(&mut self) {
579            self.root_key.zeroize();
580            self.sender_chains.zeroize();
581            self.receiver_chains.zeroize();
582            self.message_keys.zeroize();
583        }
584    }
585
586    impl TryFrom<Pickle> for Session {
587        type Error = crate::LibolmPickleError;
588
589        fn try_from(pickle: Pickle) -> Result<Self, Self::Error> {
590            let mut receiving_chains = ChainStore::new();
591
592            for chain in &pickle.receiver_chains {
593                receiving_chains.push(chain.into())
594            }
595
596            for key in &pickle.message_keys {
597                let ratchet_key =
598                    RemoteRatchetKey::from(Curve25519PublicKey::from(key.ratchet_key));
599
600                if let Some(receiving_chain) = receiving_chains.find_ratchet(&ratchet_key) {
601                    receiving_chain.insert_message_key(key.into())
602                }
603            }
604
605            if let Some(chain) = pickle.sender_chains.first() {
606                // XXX: Passing in secret array as value.
607                let ratchet_key = RatchetKey::from(Curve25519SecretKey::from_slice(
608                    chain.secret_ratchet_key.as_ref(),
609                ));
610                let chain_key =
611                    ChainKey::from_bytes_and_index(chain.chain_key.clone(), chain.chain_key_index);
612
613                let root_key = RootKey::new(pickle.root_key.clone());
614
615                let ratchet = Ratchet::new_with_ratchet_key(root_key, ratchet_key);
616                let sending_ratchet = DoubleRatchet::from_ratchet_and_chain_key(ratchet, chain_key);
617
618                Ok(Self {
619                    session_keys: pickle.session_keys,
620                    sending_ratchet,
621                    receiving_chains,
622                    config: SessionConfig::version_1(),
623                })
624            } else if let Some(chain) = receiving_chains.get(0) {
625                let sending_ratchet = DoubleRatchet::inactive_from_libolm_pickle(
626                    RemoteRootKey::new(pickle.root_key.clone()),
627                    chain.ratchet_key(),
628                );
629
630                Ok(Self {
631                    session_keys: pickle.session_keys,
632                    sending_ratchet,
633                    receiving_chains,
634                    config: SessionConfig::version_1(),
635                })
636            } else {
637                Err(crate::LibolmPickleError::InvalidSession)
638            }
639        }
640    }
641}
642
643/// A format suitable for serialization which implements [`serde::Serialize`]
644/// and [`serde::Deserialize`]. Obtainable by calling [`Session::pickle`].
645#[derive(Deserialize, Serialize)]
646pub struct SessionPickle {
647    session_keys: SessionKeys,
648    sending_ratchet: DoubleRatchet,
649    receiving_chains: ChainStore,
650    #[serde(default = "default_config")]
651    config: SessionConfig,
652}
653
654const fn default_config() -> SessionConfig {
655    SessionConfig::version_1()
656}
657
658impl SessionPickle {
659    /// Serialize and encrypt the pickle using the given key.
660    ///
661    /// This is the inverse of [`SessionPickle::from_encrypted`].
662    pub fn encrypt(self, pickle_key: &[u8; 32]) -> String {
663        pickle(&self, pickle_key)
664    }
665
666    /// Obtain a pickle from a ciphertext by decrypting and deserializing using
667    /// the given key.
668    ///
669    /// This is the inverse of [`SessionPickle::encrypt`].
670    pub fn from_encrypted(ciphertext: &str, pickle_key: &[u8; 32]) -> Result<Self, PickleError> {
671        unpickle(ciphertext, pickle_key)
672    }
673}
674
675impl From<SessionPickle> for Session {
676    fn from(pickle: SessionPickle) -> Self {
677        Self {
678            session_keys: pickle.session_keys,
679            sending_ratchet: pickle.sending_ratchet,
680            receiving_chains: pickle.receiving_chains,
681            config: pickle.config,
682        }
683    }
684}
685
686#[cfg(test)]
687mod test {
688    use std::assert_matches;
689
690    use anyhow::{Result, bail};
691    use olm_rs::{
692        account::OlmAccount,
693        session::{OlmMessage, OlmSession},
694    };
695
696    use super::{DecryptionError, Session};
697    use crate::{
698        Curve25519PublicKey,
699        olm::{
700            Account, SessionConfig, SessionPickle, messages,
701            session::receiver_chain::{MAX_MESSAGE_GAP, MAX_MESSAGE_KEYS},
702        },
703    };
704
705    const PICKLE_KEY: [u8; 32] = [0u8; 32];
706
707    /// Create a pair of accounts, one using vodozemac and one libolm.
708    ///
709    /// Then, create a pair of sessions between the two.
710    pub(crate) fn session_and_libolm_pair() -> Result<(Account, OlmAccount, Session, OlmSession)> {
711        let alice = Account::new();
712        let bob = OlmAccount::new();
713        bob.generate_one_time_keys(1);
714
715        let one_time_key = bob
716            .parsed_one_time_keys()
717            .curve25519()
718            .values()
719            .next()
720            .cloned()
721            .expect("Couldn't find a one-time key");
722
723        let identity_keys = bob.parsed_identity_keys();
724        let curve25519_key = Curve25519PublicKey::from_base64(identity_keys.curve25519())?;
725        let one_time_key = Curve25519PublicKey::from_base64(&one_time_key)?;
726        let mut alice_session = alice
727            .create_outbound_session(SessionConfig::version_1(), curve25519_key, one_time_key)
728            .unwrap();
729
730        let message = "It's a secret to everybody";
731
732        let olm_message = alice_session.encrypt(message).unwrap();
733        bob.mark_keys_as_published();
734
735        if let OlmMessage::PreKey(m) = olm_message.into() {
736            let session =
737                bob.create_inbound_session_from(&alice.curve25519_key().to_base64(), m)?;
738
739            Ok((alice, bob, alice_session, session))
740        } else {
741            bail!("Invalid message type");
742        }
743    }
744
745    #[test]
746    fn session_config() {
747        let (_, _, alice_session, _) = session_and_libolm_pair().unwrap();
748        assert_eq!(alice_session.session_config(), SessionConfig::version_1());
749    }
750
751    #[test]
752    fn has_received_message() {
753        let (_, _, mut alice_session, bob_session) = session_and_libolm_pair().unwrap();
754        assert!(!alice_session.has_received_message());
755        assert!(!bob_session.has_received_message());
756        let message = bob_session.encrypt("Message").into();
757        assert_eq!(
758            "Message".as_bytes(),
759            alice_session.decrypt(&message).expect("Should be able to decrypt message")
760        );
761        assert!(alice_session.has_received_message());
762        assert!(!bob_session.has_received_message());
763    }
764
765    #[test]
766    fn out_of_order_decryption() {
767        let (_, _, mut alice_session, bob_session) = session_and_libolm_pair().unwrap();
768
769        let message_1 = bob_session.encrypt("Message 1").into();
770        let message_2 = bob_session.encrypt("Message 2").into();
771        let message_3 = bob_session.encrypt("Message 3").into();
772
773        assert_eq!(
774            "Message 3".as_bytes(),
775            alice_session.decrypt(&message_3).expect("Should be able to decrypt message 3")
776        );
777        assert_eq!(
778            "Message 2".as_bytes(),
779            alice_session.decrypt(&message_2).expect("Should be able to decrypt message 2")
780        );
781        assert_eq!(
782            "Message 1".as_bytes(),
783            alice_session.decrypt(&message_1).expect("Should be able to decrypt message 1")
784        );
785    }
786
787    #[test]
788    fn more_out_of_order_decryption() {
789        let (_, _, mut alice_session, bob_session) = session_and_libolm_pair().unwrap();
790
791        let message_1 = bob_session.encrypt("Message 1").into();
792        let message_2 = bob_session.encrypt("Message 2").into();
793        let message_3 = bob_session.encrypt("Message 3").into();
794
795        assert_eq!(
796            "Message 1".as_bytes(),
797            alice_session.decrypt(&message_1).expect("Should be able to decrypt message 1")
798        );
799
800        assert_eq!(alice_session.receiving_chains.len(), 1);
801
802        let message_4 = alice_session.encrypt("Message 4").unwrap().into();
803        assert_eq!(
804            "Message 4",
805            bob_session.decrypt(message_4).expect("Should be able to decrypt message 4")
806        );
807
808        let message_5 = bob_session.encrypt("Message 5").into();
809        assert_eq!(
810            "Message 5".as_bytes(),
811            alice_session.decrypt(&message_5).expect("Should be able to decrypt message 5")
812        );
813        assert_eq!(
814            "Message 3".as_bytes(),
815            alice_session.decrypt(&message_3).expect("Should be able to decrypt message 3")
816        );
817        assert_eq!(
818            "Message 2".as_bytes(),
819            alice_session.decrypt(&message_2).expect("Should be able to decrypt message 2")
820        );
821
822        assert_eq!(alice_session.receiving_chains.len(), 2);
823    }
824
825    #[test]
826    fn max_keys_out_of_order_decryption() {
827        let (_, _, mut alice_session, bob_session) = session_and_libolm_pair().unwrap();
828
829        let mut messages: Vec<messages::OlmMessage> = Vec::new();
830        for i in 0..(MAX_MESSAGE_KEYS + 2) {
831            messages.push(bob_session.encrypt(format!("Message {i}").as_str()).into());
832        }
833
834        // Decrypt last message
835        assert_eq!(
836            format!("Message {}", MAX_MESSAGE_KEYS + 1).as_bytes(),
837            alice_session
838                .decrypt(&messages[MAX_MESSAGE_KEYS + 1])
839                .expect("Should be able to decrypt last message")
840        );
841
842        // Cannot decrypt first message because it is more than MAX_MESSAGE_KEYS
843        // ago
844        assert_matches!(
845            alice_session.decrypt(&messages[0]),
846            Err(DecryptionError::MissingMessageKey(_))
847        );
848
849        // Can decrypt all other messages
850        for (i, message) in messages.iter().enumerate().skip(1).take(MAX_MESSAGE_KEYS) {
851            assert_eq!(
852                format!("Message {i}").as_bytes(),
853                alice_session
854                    .decrypt(message)
855                    .expect("Should be able to decrypt remaining messages")
856            );
857        }
858    }
859
860    #[test]
861    fn max_gap_out_of_order_decryption() {
862        let (_, _, mut alice_session, bob_session) = session_and_libolm_pair().unwrap();
863
864        for i in 0..(MAX_MESSAGE_GAP + 1) {
865            bob_session.encrypt(format!("Message {i}").as_str());
866        }
867
868        let message = bob_session.encrypt("Message").into();
869        assert_matches!(
870            alice_session.decrypt(&message),
871            Err(DecryptionError::TooBigMessageGap(_, _))
872        );
873    }
874
875    #[test]
876    fn pickle_default_config() {
877        let json = r#"
878            {
879                "receiving_chains": {
880                    "inner": []
881                },
882                "sending_ratchet": {
883                    "active_ratchet": {
884                        "ratchet_key": [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
885                        "root_key": [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
886                    },
887                    "parent_ratchet_key": null,
888                    "ratchet_count": {
889                        "Known": 1
890                    },
891                    "symmetric_key_ratchet": {
892                        "index": 1,
893                        "key": [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]
894                    },
895                    "type": "active"
896                },
897                "session_keys": {
898                    "base_key": [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4],
899                    "identity_key": [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5],
900                    "one_time_key": [6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6]
901                }
902            }
903        "#;
904        let pickle: SessionPickle =
905            serde_json::from_str(json).expect("Should be able to deserialize JSON");
906        assert_eq!(pickle.config, SessionConfig::version_1());
907    }
908
909    #[test]
910    #[cfg(feature = "libolm-compat")]
911    fn libolm_unpickling() {
912        let (_, _, mut session, olm) = session_and_libolm_pair().unwrap();
913
914        let plaintext = "It's a secret to everybody";
915        let old_message = session.encrypt(plaintext).unwrap();
916
917        for _ in 0..9 {
918            session.encrypt("Hello").unwrap();
919        }
920
921        let message = session.encrypt("Hello").unwrap();
922        olm.decrypt(message.into()).expect("Should be able to decrypt message");
923
924        let key = b"DEFAULT_PICKLE_KEY";
925        let pickle = olm.pickle(olm_rs::PicklingMode::Encrypted { key: key.to_vec() });
926
927        let mut unpickled =
928            Session::from_libolm_pickle(&pickle, key).expect("Should be able to unpickle session");
929
930        assert_eq!(olm.session_id(), unpickled.session_id());
931
932        assert_eq!(
933            unpickled
934                .decrypt(&old_message)
935                .expect("Should be able to decrypt old message with unpickled session"),
936            plaintext.as_bytes()
937        );
938
939        let message = unpickled.encrypt(plaintext).unwrap();
940
941        assert_eq!(
942            session.decrypt(&message).expect("Should be able to decrypt re-encrypted message"),
943            plaintext.as_bytes()
944        );
945    }
946
947    #[test]
948    fn session_pickling_roundtrip_is_identity() {
949        let (_, _, session, _) = session_and_libolm_pair().unwrap();
950
951        let pickle = session.pickle().encrypt(&PICKLE_KEY);
952
953        let decrypted_pickle = SessionPickle::from_encrypted(&pickle, &PICKLE_KEY)
954            .expect("Should be able to decrypt encrypted pickle");
955        let unpickled_group_session = Session::from_pickle(decrypted_pickle);
956        let repickle = unpickled_group_session.pickle();
957
958        assert_eq!(session.session_id(), unpickled_group_session.session_id());
959
960        let decrypted_pickle = SessionPickle::from_encrypted(&pickle, &PICKLE_KEY)
961            .expect("Should be able to decrypt encrypted pickle");
962        let pickle = serde_json::to_value(decrypted_pickle).unwrap();
963        let repickle = serde_json::to_value(repickle).unwrap();
964
965        assert_eq!(pickle, repickle);
966    }
967
968    #[test]
969    #[cfg(feature = "low-level-api")]
970    fn next_message_key_returns_a_key() {
971        let plaintext = "It's a secret to everybody";
972        let (_, _, mut session, _) = session_and_libolm_pair().unwrap();
973
974        let message_key =
975            session.next_message_key().expect("We should be able to get a message key");
976
977        let message = message_key.encrypt_truncated_mac(plaintext.as_bytes());
978        assert_ne!(message.ciphertext, plaintext.as_bytes());
979    }
980
981    #[test]
982    #[cfg(feature = "low-level-api")]
983    fn from_root_key_material_exposes_active_sending_state() {
984        use crate::{Curve25519SecretKey, olm::SessionKeys};
985
986        let session_keys = SessionKeys {
987            identity_key: Curve25519PublicKey::from_bytes([0xAA; 32]),
988            base_key: Curve25519PublicKey::from_bytes([0xBB; 32]),
989            one_time_key: Curve25519PublicKey::from_bytes([0xCC; 32]),
990        };
991
992        let root_key = [0x11u8; 32];
993        let chain_key = [0x22u8; 32];
994        let ratchet_key_secret = [0x33u8; 32];
995
996        let session = Session::from_root_key_material(
997            SessionConfig::version_1(),
998            session_keys,
999            root_key,
1000            chain_key,
1001            ratchet_key_secret,
1002        );
1003
1004        let state = session
1005            .active_sending_state()
1006            .expect("a freshly constructed Session must have an active sending chain");
1007
1008        assert_eq!(*state.root_key, root_key);
1009        assert_eq!(*state.chain_key, chain_key);
1010        assert_eq!(state.chain_index, 0);
1011        let expected_ratchet_key = *Curve25519SecretKey::from_slice(&ratchet_key_secret).to_bytes();
1012        assert_eq!(*state.ratchet_key, expected_ratchet_key);
1013    }
1014}