1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
mod chain_key;
mod double_ratchet;
pub mod message_key;
pub mod ratchet;
mod receiver_chain;
mod root_key;
use aes::cipher::block_padding::UnpadError;
use arrayvec::ArrayVec;
use chain_key::RemoteChainKey;
use double_ratchet::DoubleRatchet;
use hmac::digest::MacError;
use ratchet::RemoteRatchetKey;
use receiver_chain::ReceiverChain;
use root_key::RemoteRootKey;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use thiserror::Error;
use zeroize::Zeroize;
use super::{
session_keys::SessionKeys,
shared_secret::{RemoteShared3DHSecret, Shared3DHSecret},
};
#[cfg(feature = "low-level-api")]
use crate::hazmat::olm::MessageKey;
use crate::{
olm::messages::{Message, OlmMessage, PreKeyMessage},
utilities::{base64_encode, pickle, unpickle, DecodeSecret},
Curve25519PublicKey, PickleError,
};
const MAX_RECEIVING_CHAINS: usize = 5;
#[derive(Error, Debug)]
pub enum DecryptionError {
#[error("Failed decrypting Olm message, invalid MAC: {0}")]
InvalidMAC(#[from] MacError),
#[error("Failed decrypting Olm message, invalid padding")]
InvalidPadding(#[from] UnpadError),
#[error("The message key with the given key can't be created, message index: {0}")]
MissingMessageKey(u64),
#[error("The message gap was too big, got {0}, max allowed {}")]
TooBigMessageGap(u64, u64),
}
#[derive(Serialize, Deserialize, Clone)]
struct ChainStore {
inner: ArrayVec<ReceiverChain, MAX_RECEIVING_CHAINS>,
}
impl ChainStore {
fn new() -> Self {
Self { inner: ArrayVec::new() }
}
fn push(&mut self, ratchet: ReceiverChain) {
if self.inner.is_full() {
self.inner.pop_at(0);
}
self.inner.push(ratchet)
}
fn is_empty(&self) -> bool {
self.inner.is_empty()
}
#[cfg(test)]
pub fn len(&self) -> usize {
self.inner.len()
}
#[cfg(feature = "libolm-compat")]
pub fn get(&self, index: usize) -> Option<&ReceiverChain> {
self.inner.get(index)
}
fn find_ratchet(&mut self, ratchet_key: &RemoteRatchetKey) -> Option<&mut ReceiverChain> {
self.inner.iter_mut().find(|r| r.belongs_to(ratchet_key))
}
}
impl Default for ChainStore {
fn default() -> Self {
Self::new()
}
}
pub struct Session {
session_keys: SessionKeys,
sending_ratchet: DoubleRatchet,
receiving_chains: ChainStore,
}
impl std::fmt::Debug for Session {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Session").field("session_id", &self.session_id()).finish_non_exhaustive()
}
}
impl Session {
pub(super) fn new(shared_secret: Shared3DHSecret, session_keys: SessionKeys) -> Self {
let local_ratchet = DoubleRatchet::active(shared_secret);
Self { session_keys, sending_ratchet: local_ratchet, receiving_chains: Default::default() }
}
pub(super) fn new_remote(
shared_secret: RemoteShared3DHSecret,
remote_ratchet_key: Curve25519PublicKey,
session_keys: SessionKeys,
) -> Self {
let (root_key, remote_chain_key) = shared_secret.expand();
let remote_ratchet_key = RemoteRatchetKey::from(remote_ratchet_key);
let root_key = RemoteRootKey::new(root_key);
let remote_chain_key = RemoteChainKey::new(remote_chain_key);
let local_ratchet = DoubleRatchet::inactive(root_key, remote_ratchet_key);
let remote_ratchet = ReceiverChain::new(remote_ratchet_key, remote_chain_key);
let mut ratchet_store = ChainStore::new();
ratchet_store.push(remote_ratchet);
Self { session_keys, sending_ratchet: local_ratchet, receiving_chains: ratchet_store }
}
pub fn session_id(&self) -> String {
let sha = Sha256::new();
let digest = sha
.chain_update(self.session_keys.identity_key.as_bytes())
.chain_update(self.session_keys.base_key.as_bytes())
.chain_update(self.session_keys.one_time_key.as_bytes())
.finalize();
base64_encode(digest)
}
pub fn has_received_message(&self) -> bool {
!self.receiving_chains.is_empty()
}
pub fn encrypt(&mut self, plaintext: &str) -> OlmMessage {
let message = self.sending_ratchet.encrypt(plaintext);
if self.has_received_message() {
OlmMessage::Normal(message)
} else {
let message = PreKeyMessage::new(self.session_keys, message);
OlmMessage::PreKey(message)
}
}
pub fn session_keys(&self) -> SessionKeys {
self.session_keys
}
#[cfg(feature = "low-level-api")]
pub fn next_message_key(&mut self) -> MessageKey {
self.sending_ratchet.next_message_key()
}
pub fn decrypt(&mut self, message: &OlmMessage) -> Result<String, DecryptionError> {
let decrypted = match message {
OlmMessage::Normal(m) => self.decrypt_decoded(m)?,
OlmMessage::PreKey(m) => self.decrypt_decoded(&m.message)?,
};
Ok(String::from_utf8_lossy(&decrypted).to_string())
}
pub(super) fn decrypt_decoded(
&mut self,
message: &Message,
) -> Result<Vec<u8>, DecryptionError> {
let ratchet_key = RemoteRatchetKey::from(message.ratchet_key);
if let Some(ratchet) = self.receiving_chains.find_ratchet(&ratchet_key) {
Ok(ratchet.decrypt(message)?)
} else {
let (sending_ratchet, mut remote_ratchet) = self.sending_ratchet.advance(ratchet_key);
let plaintext = remote_ratchet.decrypt(message)?;
self.sending_ratchet = sending_ratchet;
self.receiving_chains.push(remote_ratchet);
Ok(plaintext)
}
}
pub fn pickle(&self) -> SessionPickle {
SessionPickle {
session_keys: self.session_keys,
sending_ratchet: self.sending_ratchet.clone(),
receiving_chains: self.receiving_chains.clone(),
}
}
pub fn from_pickle(pickle: SessionPickle) -> Self {
pickle.into()
}
#[cfg(feature = "libolm-compat")]
pub fn from_libolm_pickle(
pickle: &str,
pickle_key: &[u8],
) -> Result<Self, crate::LibolmPickleError> {
use chain_key::ChainKey;
use message_key::RemoteMessageKey;
use ratchet::{Ratchet, RatchetKey};
use root_key::RootKey;
use crate::{
types::Curve25519SecretKey,
utilities::{unpickle_libolm, Decode},
};
#[derive(Debug, Zeroize)]
#[zeroize(drop)]
struct SenderChain {
public_ratchet_key: [u8; 32],
secret_ratchet_key: Box<[u8; 32]>,
chain_key: Box<[u8; 32]>,
chain_key_index: u32,
}
impl Decode for SenderChain {
fn decode(
reader: &mut impl std::io::Read,
) -> Result<Self, crate::utilities::LibolmDecodeError> {
Ok(Self {
public_ratchet_key: <[u8; 32]>::decode(reader)?,
secret_ratchet_key: <[u8; 32]>::decode_secret(reader)?,
chain_key: <[u8; 32]>::decode_secret(reader)?,
chain_key_index: u32::decode(reader)?,
})
}
}
#[derive(Debug, Zeroize)]
#[zeroize(drop)]
struct ReceivingChain {
public_ratchet_key: [u8; 32],
chain_key: Box<[u8; 32]>,
chain_key_index: u32,
}
impl Decode for ReceivingChain {
fn decode(
reader: &mut impl std::io::Read,
) -> Result<Self, crate::utilities::LibolmDecodeError> {
Ok(Self {
public_ratchet_key: <[u8; 32]>::decode(reader)?,
chain_key: <[u8; 32]>::decode_secret(reader)?,
chain_key_index: u32::decode(reader)?,
})
}
}
impl From<&ReceivingChain> for ReceiverChain {
fn from(chain: &ReceivingChain) -> Self {
let ratchet_key = RemoteRatchetKey::from(chain.public_ratchet_key);
let chain_key = RemoteChainKey::from_bytes_and_index(
chain.chain_key.clone(),
chain.chain_key_index,
);
ReceiverChain::new(ratchet_key, chain_key)
}
}
#[derive(Debug, Zeroize)]
#[zeroize(drop)]
struct MessageKey {
ratchet_key: [u8; 32],
message_key: Box<[u8; 32]>,
index: u32,
}
impl Decode for MessageKey {
fn decode(
reader: &mut impl std::io::Read,
) -> Result<Self, crate::utilities::LibolmDecodeError> {
Ok(Self {
ratchet_key: <[u8; 32]>::decode(reader)?,
message_key: <[u8; 32]>::decode_secret(reader)?,
index: u32::decode(reader)?,
})
}
}
impl From<&MessageKey> for RemoteMessageKey {
fn from(key: &MessageKey) -> Self {
RemoteMessageKey { key: key.message_key.clone(), index: key.index.into() }
}
}
struct Pickle {
#[allow(dead_code)]
version: u32,
#[allow(dead_code)]
received_message: bool,
session_keys: SessionKeys,
root_key: Box<[u8; 32]>,
sender_chains: Vec<SenderChain>,
receiver_chains: Vec<ReceivingChain>,
message_keys: Vec<MessageKey>,
}
impl Decode for Pickle {
fn decode(
reader: &mut impl std::io::Read,
) -> Result<Self, crate::utilities::LibolmDecodeError> {
Ok(Self {
version: u32::decode(reader)?,
received_message: bool::decode(reader)?,
session_keys: SessionKeys::decode(reader)?,
root_key: <[u8; 32]>::decode_secret(reader)?,
sender_chains: Vec::decode(reader)?,
receiver_chains: Vec::decode(reader)?,
message_keys: Vec::decode(reader)?,
})
}
}
impl Drop for Pickle {
fn drop(&mut self) {
self.root_key.zeroize();
self.sender_chains.zeroize();
self.receiver_chains.zeroize();
self.message_keys.zeroize();
}
}
impl TryFrom<Pickle> for Session {
type Error = crate::LibolmPickleError;
fn try_from(pickle: Pickle) -> Result<Self, Self::Error> {
let mut receiving_chains = ChainStore::new();
for chain in &pickle.receiver_chains {
receiving_chains.push(chain.into())
}
for key in &pickle.message_keys {
let ratchet_key =
RemoteRatchetKey::from(Curve25519PublicKey::from(key.ratchet_key));
if let Some(receiving_chain) = receiving_chains.find_ratchet(&ratchet_key) {
receiving_chain.insert_message_key(key.into())
}
}
if let Some(chain) = pickle.sender_chains.get(0) {
let ratchet_key = RatchetKey::from(Curve25519SecretKey::from_slice(
chain.secret_ratchet_key.as_ref(),
));
let chain_key = ChainKey::from_bytes_and_index(
chain.chain_key.clone(),
chain.chain_key_index,
);
let root_key = RootKey::new(pickle.root_key.clone());
let ratchet = Ratchet::new_with_ratchet_key(root_key, ratchet_key);
let sending_ratchet =
DoubleRatchet::from_ratchet_and_chain_key(ratchet, chain_key);
Ok(Self {
session_keys: pickle.session_keys,
sending_ratchet,
receiving_chains,
})
} else if let Some(chain) = receiving_chains.get(0) {
let sending_ratchet = DoubleRatchet::inactive(
RemoteRootKey::new(pickle.root_key.clone()),
chain.ratchet_key(),
);
Ok(Self {
session_keys: pickle.session_keys,
sending_ratchet,
receiving_chains,
})
} else {
Err(crate::LibolmPickleError::InvalidSession)
}
}
}
const PICKLE_VERSION: u32 = 1;
unpickle_libolm::<Pickle, _>(pickle, pickle_key, PICKLE_VERSION)
}
}
#[derive(Deserialize, Serialize)]
pub struct SessionPickle {
session_keys: SessionKeys,
sending_ratchet: DoubleRatchet,
receiving_chains: ChainStore,
}
impl SessionPickle {
pub fn encrypt(self, pickle_key: &[u8; 32]) -> String {
pickle(&self, pickle_key)
}
pub fn from_encrypted(ciphertext: &str, pickle_key: &[u8; 32]) -> Result<Self, PickleError> {
unpickle(ciphertext, pickle_key)
}
}
impl From<SessionPickle> for Session {
fn from(pickle: SessionPickle) -> Self {
Self {
session_keys: pickle.session_keys,
sending_ratchet: pickle.sending_ratchet,
receiving_chains: pickle.receiving_chains,
}
}
}
#[cfg(test)]
mod test {
use anyhow::{bail, Result};
use olm_rs::{
account::OlmAccount,
session::{OlmMessage, OlmSession},
};
use super::Session;
use crate::{
olm::{Account, SessionPickle},
Curve25519PublicKey,
};
const PICKLE_KEY: [u8; 32] = [0u8; 32];
fn sessions() -> Result<(Account, OlmAccount, Session, OlmSession)> {
let alice = Account::new();
let bob = OlmAccount::new();
bob.generate_one_time_keys(1);
let one_time_key = bob
.parsed_one_time_keys()
.curve25519()
.values()
.next()
.cloned()
.expect("Couldn't find a one-time key");
let identity_keys = bob.parsed_identity_keys();
let curve25519_key = Curve25519PublicKey::from_base64(identity_keys.curve25519())?;
let one_time_key = Curve25519PublicKey::from_base64(&one_time_key)?;
let mut alice_session = alice.create_outbound_session(curve25519_key, one_time_key);
let message = "It's a secret to everybody";
let olm_message = alice_session.encrypt(message);
bob.mark_keys_as_published();
if let OlmMessage::PreKey(m) = olm_message.into() {
let session =
bob.create_inbound_session_from(&alice.curve25519_key().to_base64(), m)?;
Ok((alice, bob, alice_session, session))
} else {
bail!("Invalid message type");
}
}
#[test]
fn out_of_order_decryption() -> Result<()> {
let (_, _, mut alice_session, bob_session) = sessions()?;
let message_1 = bob_session.encrypt("Message 1").into();
let message_2 = bob_session.encrypt("Message 2").into();
let message_3 = bob_session.encrypt("Message 3").into();
assert_eq!("Message 3", alice_session.decrypt(&message_3)?);
assert_eq!("Message 2", alice_session.decrypt(&message_2)?);
assert_eq!("Message 1", alice_session.decrypt(&message_1)?);
Ok(())
}
#[test]
fn more_out_of_order_decryption() -> Result<()> {
let (_, _, mut alice_session, bob_session) = sessions()?;
let message_1 = bob_session.encrypt("Message 1").into();
let message_2 = bob_session.encrypt("Message 2").into();
let message_3 = bob_session.encrypt("Message 3").into();
assert_eq!("Message 1", alice_session.decrypt(&message_1)?);
assert_eq!(alice_session.receiving_chains.len(), 1);
let message_4 = alice_session.encrypt("Message 4").into();
assert_eq!("Message 4", bob_session.decrypt(message_4)?);
let message_5 = bob_session.encrypt("Message 5").into();
assert_eq!("Message 5", alice_session.decrypt(&message_5)?);
assert_eq!("Message 3", alice_session.decrypt(&message_3)?);
assert_eq!("Message 2", alice_session.decrypt(&message_2)?);
assert_eq!(alice_session.receiving_chains.len(), 2);
Ok(())
}
#[test]
#[cfg(feature = "libolm-compat")]
fn libolm_unpickling() -> Result<()> {
let (_, _, mut session, olm) = sessions()?;
let plaintext = "It's a secret to everybody";
let old_message = session.encrypt(plaintext);
for _ in 0..9 {
session.encrypt("Hello");
}
let message = session.encrypt("Hello");
olm.decrypt(message.into())?;
let key = b"DEFAULT_PICKLE_KEY";
let pickle = olm.pickle(olm_rs::PicklingMode::Encrypted { key: key.to_vec() });
let mut unpickled = Session::from_libolm_pickle(&pickle, key)?;
assert_eq!(olm.session_id(), unpickled.session_id());
assert_eq!(unpickled.decrypt(&old_message)?, plaintext);
let message = unpickled.encrypt(plaintext);
assert_eq!(session.decrypt(&message)?, plaintext);
Ok(())
}
#[test]
fn session_pickling_roundtrip_is_identity() -> Result<()> {
let (_, _, session, _) = sessions()?;
let pickle = session.pickle().encrypt(&PICKLE_KEY);
let decrypted_pickle = SessionPickle::from_encrypted(&pickle, &PICKLE_KEY)?;
let unpickled_group_session = Session::from_pickle(decrypted_pickle);
let repickle = unpickled_group_session.pickle();
assert_eq!(session.session_id(), unpickled_group_session.session_id());
let decrypted_pickle = SessionPickle::from_encrypted(&pickle, &PICKLE_KEY)?;
let pickle = serde_json::to_value(decrypted_pickle)?;
let repickle = serde_json::to_value(repickle)?;
assert_eq!(pickle, repickle);
Ok(())
}
}