libsignal_protocol/
ratchet.rs

1//
2// Copyright 2020 Signal Messenger, LLC.
3// SPDX-License-Identifier: AGPL-3.0-only
4//
5
6mod keys;
7mod params;
8
9use rand::{CryptoRng, Rng};
10
11pub(crate) use self::keys::{ChainKey, MessageKeyGenerator, RootKey};
12pub use self::params::{AliceSignalProtocolParameters, BobSignalProtocolParameters};
13use crate::protocol::CIPHERTEXT_MESSAGE_CURRENT_VERSION;
14use crate::state::SessionState;
15use crate::{KeyPair, Result, SessionRecord, SignalProtocolError, consts};
16
17type InitialPQRKey = [u8; 32];
18
19fn derive_keys(secret_input: &[u8]) -> (RootKey, ChainKey, InitialPQRKey) {
20    derive_keys_with_label(
21        b"WhisperText_X25519_SHA-256_CRYSTALS-KYBER-1024",
22        secret_input,
23    )
24}
25
26fn derive_keys_with_label(label: &[u8], secret_input: &[u8]) -> (RootKey, ChainKey, InitialPQRKey) {
27    let mut secrets = [0; 96];
28    hkdf::Hkdf::<sha2::Sha256>::new(None, secret_input)
29        .expand(label, &mut secrets)
30        .expect("valid length");
31    let (root_key_bytes, chain_key_bytes, pqr_bytes) =
32        (&secrets[0..32], &secrets[32..64], &secrets[64..96]);
33
34    let root_key = RootKey::new(root_key_bytes.try_into().expect("correct length"));
35    let chain_key = ChainKey::new(chain_key_bytes.try_into().expect("correct length"), 0);
36    let pqr_key: InitialPQRKey = pqr_bytes.try_into().expect("correct length");
37
38    (root_key, chain_key, pqr_key)
39}
40
41fn spqr_chain_params(self_connection: bool) -> spqr::ChainParams {
42    #[allow(clippy::needless_update)]
43    spqr::ChainParams {
44        max_jump: if self_connection {
45            u32::MAX
46        } else {
47            consts::MAX_FORWARD_JUMPS.try_into().expect("should be <4B")
48        },
49        max_ooo_keys: consts::MAX_MESSAGE_KEYS.try_into().expect("should be <4B"),
50        ..Default::default()
51    }
52}
53
54pub(crate) fn initialize_alice_session<R: Rng + CryptoRng>(
55    parameters: &AliceSignalProtocolParameters,
56    mut csprng: &mut R,
57) -> Result<SessionState> {
58    let local_identity = parameters.our_identity_key_pair().identity_key();
59
60    let mut secrets = Vec::with_capacity(32 * 6);
61
62    secrets.extend_from_slice(&[0xFFu8; 32]); // "discontinuity bytes"
63
64    let our_base_private_key = parameters.our_base_key_pair().private_key;
65
66    secrets.extend_from_slice(
67        &parameters
68            .our_identity_key_pair()
69            .private_key()
70            .calculate_agreement(parameters.their_signed_pre_key())?,
71    );
72
73    secrets.extend_from_slice(
74        &our_base_private_key.calculate_agreement(parameters.their_identity_key().public_key())?,
75    );
76
77    secrets.extend_from_slice(
78        &our_base_private_key.calculate_agreement(parameters.their_signed_pre_key())?,
79    );
80
81    if let Some(their_one_time_prekey) = parameters.their_one_time_pre_key() {
82        secrets
83            .extend_from_slice(&our_base_private_key.calculate_agreement(their_one_time_prekey)?);
84    }
85
86    let kyber_ciphertext = {
87        let (ss, ct) = parameters.their_kyber_pre_key().encapsulate(&mut csprng)?;
88        secrets.extend_from_slice(ss.as_ref());
89        ct
90    };
91
92    let (root_key, chain_key, pqr_key) = derive_keys(&secrets);
93
94    let sending_ratchet_key = KeyPair::generate(&mut csprng);
95    let (sending_chain_root_key, sending_chain_chain_key) = root_key.create_chain(
96        parameters.their_ratchet_key(),
97        &sending_ratchet_key.private_key,
98    )?;
99
100    let self_session = local_identity == parameters.their_identity_key();
101    let pqr_state = spqr::initial_state(spqr::Params {
102        auth_key: &pqr_key,
103        version: spqr::Version::V1,
104        direction: spqr::Direction::A2B,
105        // Set min_version to V0 (allow fallback to no PQR at all) while
106        // there are clients that don't speak PQR.  Once all clients speak
107        // PQR, we can up this to V1 to require that all subsequent sessions
108        // use at least V1.
109        min_version: spqr::Version::V0,
110        chain_params: spqr_chain_params(self_session),
111    })
112    .map_err(|e| {
113        // Since this is an error associated with the initial creation of the state,
114        // it must be a problem with the arguments provided.
115        SignalProtocolError::InvalidArgument(format!(
116            "post-quantum ratchet: error creating initial A2B state: {e}"
117        ))
118    })?;
119
120    let mut session = SessionState::new(
121        CIPHERTEXT_MESSAGE_CURRENT_VERSION,
122        local_identity,
123        parameters.their_identity_key(),
124        &sending_chain_root_key,
125        &parameters.our_base_key_pair().public_key,
126        pqr_state,
127    )
128    .with_receiver_chain(parameters.their_ratchet_key(), &chain_key)
129    .with_sender_chain(&sending_ratchet_key, &sending_chain_chain_key);
130
131    session.set_kyber_ciphertext(kyber_ciphertext);
132
133    Ok(session)
134}
135
136pub(crate) fn initialize_bob_session(
137    parameters: &BobSignalProtocolParameters,
138) -> Result<SessionState> {
139    // validate their base key
140    if !parameters.their_base_key().is_canonical() {
141        return Err(SignalProtocolError::InvalidMessage(
142            crate::CiphertextMessageType::PreKey,
143            "incoming base key is invalid",
144        ));
145    }
146
147    let local_identity = parameters.our_identity_key_pair().identity_key();
148
149    let mut secrets = Vec::with_capacity(32 * 6);
150
151    secrets.extend_from_slice(&[0xFFu8; 32]); // "discontinuity bytes"
152
153    secrets.extend_from_slice(
154        &parameters
155            .our_signed_pre_key_pair()
156            .private_key
157            .calculate_agreement(parameters.their_identity_key().public_key())?,
158    );
159
160    secrets.extend_from_slice(
161        &parameters
162            .our_identity_key_pair()
163            .private_key()
164            .calculate_agreement(parameters.their_base_key())?,
165    );
166
167    secrets.extend_from_slice(
168        &parameters
169            .our_signed_pre_key_pair()
170            .private_key
171            .calculate_agreement(parameters.their_base_key())?,
172    );
173
174    if let Some(our_one_time_pre_key_pair) = parameters.our_one_time_pre_key_pair() {
175        secrets.extend_from_slice(
176            &our_one_time_pre_key_pair
177                .private_key
178                .calculate_agreement(parameters.their_base_key())?,
179        );
180    }
181
182    secrets.extend_from_slice(
183        &parameters
184            .our_kyber_pre_key_pair()
185            .secret_key
186            .decapsulate(parameters.their_kyber_ciphertext())?,
187    );
188
189    let (root_key, chain_key, pqr_key) = derive_keys(&secrets);
190
191    let self_session = local_identity == parameters.their_identity_key();
192    let pqr_state = spqr::initial_state(spqr::Params {
193        auth_key: &pqr_key,
194        version: spqr::Version::V1,
195        direction: spqr::Direction::B2A,
196        // Set min_version to V0 (allow fallback to no PQR at all) while
197        // there are clients that don't speak PQR.  Once all clients speak
198        // PQR, we can up this to V1 to require that all subsequent sessions
199        // use at least V1.
200        min_version: spqr::Version::V0,
201        chain_params: spqr_chain_params(self_session),
202    })
203    .map_err(|e| {
204        // Since this is an error associated with the initial creation of the state,
205        // it must be a problem with the arguments provided.
206        SignalProtocolError::InvalidArgument(format!(
207            "post-quantum ratchet: error creating initial B2A state: {e}"
208        ))
209    })?;
210    let session = SessionState::new(
211        CIPHERTEXT_MESSAGE_CURRENT_VERSION,
212        local_identity,
213        parameters.their_identity_key(),
214        &root_key,
215        parameters.their_base_key(),
216        pqr_state,
217    )
218    .with_sender_chain(parameters.our_ratchet_key_pair(), &chain_key);
219
220    Ok(session)
221}
222
223pub fn initialize_alice_session_record<R: Rng + CryptoRng>(
224    parameters: &AliceSignalProtocolParameters,
225    csprng: &mut R,
226) -> Result<SessionRecord> {
227    Ok(SessionRecord::new(initialize_alice_session(
228        parameters, csprng,
229    )?))
230}
231
232pub fn initialize_bob_session_record(
233    parameters: &BobSignalProtocolParameters,
234) -> Result<SessionRecord> {
235    Ok(SessionRecord::new(initialize_bob_session(parameters)?))
236}