-
Notifications
You must be signed in to change notification settings - Fork 246
/
account.rs
1710 lines (1485 loc) · 61.5 KB
/
account.rs
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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2020 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::{
collections::{BTreeMap, HashMap},
fmt,
ops::{Deref, Not as _},
sync::Arc,
time::Duration,
};
use js_option::JsOption;
use ruma::{
api::client::{
dehydrated_device::{DehydratedDeviceData, DehydratedDeviceV1},
keys::{
upload_keys,
upload_signatures::v3::{Request as SignatureUploadRequest, SignedKeys},
},
},
events::AnyToDeviceEvent,
serde::Raw,
DeviceId, DeviceKeyAlgorithm, DeviceKeyId, MilliSecondsSinceUnixEpoch, OwnedDeviceId,
OwnedDeviceKeyId, OwnedUserId, RoomId, SecondsSinceUnixEpoch, UInt, UserId,
};
use serde::{de::Error, Deserialize, Serialize};
use serde_json::{
value::{to_raw_value, RawValue as RawJsonValue},
Value,
};
use sha2::{Digest, Sha256};
use tokio::sync::Mutex;
use tracing::{debug, field::debug, info, instrument, trace, warn, Span};
use vodozemac::{
base64_encode,
olm::{
Account as InnerAccount, AccountPickle, IdentityKeys, OlmMessage,
OneTimeKeyGenerationResult, PreKeyMessage, SessionConfig,
},
Curve25519PublicKey, Ed25519Signature, KeyId, PickleError,
};
use super::{
utility::SignJson, EncryptionSettings, InboundGroupSession, OutboundGroupSession,
PrivateCrossSigningIdentity, Session, SessionCreationError as MegolmSessionCreationError,
};
#[cfg(feature = "experimental-algorithms")]
use crate::types::events::room::encrypted::OlmV2Curve25519AesSha2Content;
use crate::{
dehydrated_devices::DehydrationError,
error::{EventError, OlmResult, SessionCreationError},
identities::DeviceData,
olm::SenderData,
requests::UploadSigningKeysRequest,
store::{Changes, DeviceChanges, Store},
types::{
events::{
olm_v1::AnyDecryptedOlmEvent,
room::encrypted::{
EncryptedToDeviceEvent, OlmV1Curve25519AesSha2Content,
ToDeviceEncryptedEventContent,
},
},
CrossSigningKey, DeviceKeys, EventEncryptionAlgorithm, MasterPubkey, OneTimeKey, SignedKey,
},
OlmError, SignatureError,
};
#[derive(Debug)]
enum PrekeyBundle {
Olm3DH { key: SignedKey },
}
#[derive(Debug, Clone)]
pub(crate) enum SessionType {
New(Session),
Existing(Session),
}
#[derive(Debug)]
pub struct InboundCreationResult {
pub session: Session,
pub plaintext: String,
}
impl SessionType {
#[cfg(test)]
pub fn session(self) -> Session {
match self {
SessionType::New(s) => s,
SessionType::Existing(s) => s,
}
}
}
/// A struct witnessing a successful decryption of an Olm-encrypted to-device
/// event.
///
/// Contains the decrypted event plaintext along with some associated metadata,
/// such as the identity (Curve25519) key of the to-device event sender.
#[derive(Debug)]
pub(crate) struct OlmDecryptionInfo {
pub session: SessionType,
pub message_hash: OlmMessageHash,
pub inbound_group_session: Option<InboundGroupSession>,
pub result: DecryptionResult,
}
#[derive(Debug)]
pub(crate) struct DecryptionResult {
// AnyDecryptedOlmEvent is pretty big at 512 bytes, box it to reduce stack size
pub event: Box<AnyDecryptedOlmEvent>,
pub raw_event: Raw<AnyToDeviceEvent>,
pub sender_key: Curve25519PublicKey,
}
/// A hash of a successfully decrypted Olm message.
///
/// Can be used to check if a message has been replayed to us.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OlmMessageHash {
/// The curve25519 key of the sender that sent us the Olm message.
pub sender_key: String,
/// The hash of the message.
pub hash: String,
}
impl OlmMessageHash {
fn new(sender_key: Curve25519PublicKey, ciphertext: &OlmMessage) -> Self {
let (message_type, ciphertext) = ciphertext.clone().to_parts();
let sender_key = sender_key.to_base64();
let sha = Sha256::new()
.chain_update(sender_key.as_bytes())
.chain_update([message_type as u8])
.chain_update(ciphertext)
.finalize();
Self { sender_key, hash: base64_encode(sha.as_slice()) }
}
}
/// Account data that's static for the lifetime of a Client.
///
/// This data never changes once it's set, so it can be freely passed and cloned
/// everywhere.
#[derive(Clone)]
#[cfg_attr(not(tarpaulin_include), derive(Debug))]
pub struct StaticAccountData {
/// The user_id this account belongs to.
pub user_id: OwnedUserId,
/// The device_id of this entry.
pub device_id: OwnedDeviceId,
/// The associated identity keys.
pub identity_keys: Arc<IdentityKeys>,
/// Whether the account is for a dehydrated device.
pub dehydrated: bool,
// The creation time of the account in milliseconds since epoch.
creation_local_time: MilliSecondsSinceUnixEpoch,
}
impl StaticAccountData {
const ALGORITHMS: &'static [&'static EventEncryptionAlgorithm] = &[
&EventEncryptionAlgorithm::OlmV1Curve25519AesSha2,
#[cfg(feature = "experimental-algorithms")]
&EventEncryptionAlgorithm::OlmV2Curve25519AesSha2,
&EventEncryptionAlgorithm::MegolmV1AesSha2,
#[cfg(feature = "experimental-algorithms")]
&EventEncryptionAlgorithm::MegolmV2AesSha2,
];
/// Create a group session pair.
///
/// This session pair can be used to encrypt and decrypt messages meant for
/// a large group of participants.
///
/// The outbound session is used to encrypt messages while the inbound one
/// is used to decrypt messages encrypted by the outbound one.
///
/// # Arguments
///
/// * `room_id` - The ID of the room where the group session will be used.
///
/// * `settings` - Settings determining the algorithm and rotation period of
/// the outbound group session.
pub async fn create_group_session_pair(
&self,
room_id: &RoomId,
settings: EncryptionSettings,
own_sender_data: SenderData,
) -> Result<(OutboundGroupSession, InboundGroupSession), MegolmSessionCreationError> {
trace!(?room_id, algorithm = settings.algorithm.as_str(), "Creating a new room key");
let visibility = settings.history_visibility.clone();
let algorithm = settings.algorithm.to_owned();
let outbound = OutboundGroupSession::new(
self.device_id.clone(),
self.identity_keys.clone(),
room_id,
settings,
)?;
let identity_keys = &self.identity_keys;
let sender_key = identity_keys.curve25519;
let signing_key = identity_keys.ed25519;
let inbound = InboundGroupSession::new(
sender_key,
signing_key,
room_id,
&outbound.session_key().await,
own_sender_data,
algorithm,
Some(visibility),
)?;
Ok((outbound, inbound))
}
#[cfg(any(test, feature = "testing"))]
#[allow(dead_code)]
/// Testing only facility to create a group session pair with default
/// settings.
pub async fn create_group_session_pair_with_defaults(
&self,
room_id: &RoomId,
) -> (OutboundGroupSession, InboundGroupSession) {
self.create_group_session_pair(
room_id,
EncryptionSettings::default(),
SenderData::unknown(),
)
.await
.expect("Can't create default group session pair")
}
/// Get the key ID of our Ed25519 signing key.
pub fn signing_key_id(&self) -> OwnedDeviceKeyId {
DeviceKeyId::from_parts(DeviceKeyAlgorithm::Ed25519, self.device_id())
}
/// Check if the given JSON is signed by this Account key.
///
/// This method should only be used if an object's signature needs to be
/// checked multiple times, and you'd like to avoid performing the
/// canonicalization step each time.
///
/// **Note**: Use this method with caution, the `canonical_json` needs to be
/// correctly canonicalized and make sure that the object you are checking
/// the signature for is allowed to be signed by our own device.
pub fn has_signed_raw(
&self,
signatures: &crate::types::Signatures,
canonical_json: &str,
) -> Result<(), SignatureError> {
use crate::olm::utility::VerifyJson;
let signing_key = self.identity_keys.ed25519;
signing_key.verify_canonicalized_json(
&self.user_id,
&DeviceKeyId::from_parts(DeviceKeyAlgorithm::Ed25519, self.device_id()),
signatures,
canonical_json,
)
}
/// Generate the unsigned `DeviceKeys` from this `StaticAccountData`.
pub fn unsigned_device_keys(&self) -> DeviceKeys {
let identity_keys = self.identity_keys();
let keys = BTreeMap::from([
(
DeviceKeyId::from_parts(DeviceKeyAlgorithm::Curve25519, &self.device_id),
identity_keys.curve25519.into(),
),
(
DeviceKeyId::from_parts(DeviceKeyAlgorithm::Ed25519, &self.device_id),
identity_keys.ed25519.into(),
),
]);
let mut ret = DeviceKeys::new(
(*self.user_id).to_owned(),
(*self.device_id).to_owned(),
Self::ALGORITHMS.iter().map(|a| (**a).clone()).collect(),
keys,
Default::default(),
);
if self.dehydrated {
ret.dehydrated = JsOption::Some(true);
}
ret
}
/// Get the user id of the owner of the account.
pub fn user_id(&self) -> &UserId {
&self.user_id
}
/// Get the device ID that owns this account.
pub fn device_id(&self) -> &DeviceId {
&self.device_id
}
/// Get the public parts of the identity keys for the account.
pub fn identity_keys(&self) -> IdentityKeys {
*self.identity_keys
}
/// Get the local timestamp creation of the account in secs since epoch.
pub fn creation_local_time(&self) -> MilliSecondsSinceUnixEpoch {
self.creation_local_time
}
}
/// Account holding identity keys for which sessions can be created.
///
/// An account is the central identity for encrypted communication between two
/// devices.
pub struct Account {
pub(crate) static_data: StaticAccountData,
/// `vodozemac` account.
inner: Box<InnerAccount>,
/// Is this account ready to encrypt messages? (i.e. has it shared keys with
/// a homeserver)
shared: bool,
/// The number of signed one-time keys we have uploaded to the server. If
/// this is None, no action will be taken. After a sync request the client
/// needs to set this for us, depending on the count we will suggest the
/// client to upload new keys.
uploaded_signed_key_count: u64,
/// The timestamp of the last time we generated a fallback key. Fallback
/// keys are rotated in a time-based manner. This field records when we
/// either generated our first fallback key or rotated one.
///
/// Will be `None` if we never created a fallback key, or if we're migrating
/// from a `AccountPickle` that didn't use time-based fallback key
/// rotation.
fallback_creation_timestamp: Option<MilliSecondsSinceUnixEpoch>,
}
impl Deref for Account {
type Target = StaticAccountData;
fn deref(&self) -> &Self::Target {
&self.static_data
}
}
/// A pickled version of an `Account`.
///
/// Holds all the information that needs to be stored in a database to restore
/// an account.
#[derive(Serialize, Deserialize)]
#[allow(missing_debug_implementations)]
pub struct PickledAccount {
/// The user id of the account owner.
pub user_id: OwnedUserId,
/// The device ID of the account owner.
pub device_id: OwnedDeviceId,
/// The pickled version of the Olm account.
pub pickle: AccountPickle,
/// Was the account shared.
pub shared: bool,
/// Whether this is for a dehydrated device
#[serde(default)]
pub dehydrated: bool,
/// The number of uploaded one-time keys we have on the server.
pub uploaded_signed_key_count: u64,
/// The local time creation of this account (milliseconds since epoch), used
/// as creation time of own device
#[serde(default = "default_account_creation_time")]
pub creation_local_time: MilliSecondsSinceUnixEpoch,
/// The timestamp of the last time we generated a fallback key.
#[serde(default)]
pub fallback_key_creation_timestamp: Option<MilliSecondsSinceUnixEpoch>,
}
fn default_account_creation_time() -> MilliSecondsSinceUnixEpoch {
MilliSecondsSinceUnixEpoch(UInt::default())
}
#[cfg(not(tarpaulin_include))]
impl fmt::Debug for Account {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Account")
.field("identity_keys", &self.identity_keys())
.field("shared", &self.shared())
.finish()
}
}
pub type OneTimeKeys = BTreeMap<OwnedDeviceKeyId, Raw<ruma::encryption::OneTimeKey>>;
pub type FallbackKeys = OneTimeKeys;
impl Account {
pub(crate) fn new_helper(
mut account: InnerAccount,
user_id: &UserId,
device_id: &DeviceId,
) -> Self {
let identity_keys = account.identity_keys();
// Let's generate some initial one-time keys while we're here. Since we know
// that this is a completely new [`Account`] we're certain that the
// server does not yet have any one-time keys of ours.
//
// This ensures we upload one-time keys along with our device keys right
// away, rather than waiting for the key counts to be echoed back to us
// from the server.
//
// It would be nice to do this for the fallback key as well but we can't assume
// that the server supports fallback keys. Maybe one of these days we
// will be able to do so.
account.generate_one_time_keys(account.max_number_of_one_time_keys());
Self {
static_data: StaticAccountData {
user_id: user_id.into(),
device_id: device_id.into(),
identity_keys: Arc::new(identity_keys),
dehydrated: false,
creation_local_time: MilliSecondsSinceUnixEpoch::now(),
},
inner: Box::new(account),
shared: false,
uploaded_signed_key_count: 0,
fallback_creation_timestamp: None,
}
}
/// Create a fresh new account, this will generate the identity key-pair.
pub fn with_device_id(user_id: &UserId, device_id: &DeviceId) -> Self {
let account = InnerAccount::new();
Self::new_helper(account, user_id, device_id)
}
/// Create a new random Olm Account, the long-term Curve25519 identity key
/// encoded as base64 will be used for the device ID.
pub fn new(user_id: &UserId) -> Self {
let account = InnerAccount::new();
let device_id: OwnedDeviceId =
base64_encode(account.identity_keys().curve25519.as_bytes()).into();
Self::new_helper(account, user_id, &device_id)
}
/// Create a new random Olm Account for a dehydrated device
pub fn new_dehydrated(user_id: &UserId) -> Self {
let account = InnerAccount::new();
let device_id: OwnedDeviceId =
base64_encode(account.identity_keys().curve25519.as_bytes()).into();
let mut ret = Self::new_helper(account, user_id, &device_id);
ret.static_data.dehydrated = true;
ret
}
/// Get the immutable data for this account.
pub fn static_data(&self) -> &StaticAccountData {
&self.static_data
}
/// Update the uploaded key count.
///
/// # Arguments
///
/// * `new_count` - The new count that was reported by the server.
pub fn update_uploaded_key_count(&mut self, new_count: u64) {
self.uploaded_signed_key_count = new_count;
}
/// Get the currently known uploaded key count.
pub fn uploaded_key_count(&self) -> u64 {
self.uploaded_signed_key_count
}
/// Has the account been shared with the server.
pub fn shared(&self) -> bool {
self.shared
}
/// Mark the account as shared.
///
/// Messages shouldn't be encrypted with the session before it has been
/// shared.
pub fn mark_as_shared(&mut self) {
self.shared = true;
}
/// Get the one-time keys of the account.
///
/// This can be empty, keys need to be generated first.
pub fn one_time_keys(&self) -> HashMap<KeyId, Curve25519PublicKey> {
self.inner.one_time_keys()
}
/// Generate count number of one-time keys.
pub fn generate_one_time_keys(&mut self, count: usize) -> OneTimeKeyGenerationResult {
self.inner.generate_one_time_keys(count)
}
/// Get the maximum number of one-time keys the account can hold.
pub fn max_one_time_keys(&self) -> usize {
self.inner.max_number_of_one_time_keys()
}
pub(crate) fn update_key_counts(
&mut self,
one_time_key_counts: &BTreeMap<DeviceKeyAlgorithm, UInt>,
unused_fallback_keys: Option<&[DeviceKeyAlgorithm]>,
) {
if let Some(count) = one_time_key_counts.get(&DeviceKeyAlgorithm::SignedCurve25519) {
let count: u64 = (*count).into();
let old_count = self.uploaded_key_count();
// Some servers might always return the key counts in the sync
// response, we don't want to the logs with noop changes if they do
// so.
if count != old_count {
debug!(
"Updated uploaded one-time key count {} -> {count}.",
self.uploaded_key_count(),
);
}
self.update_uploaded_key_count(count);
self.generate_one_time_keys_if_needed();
}
// If the server supports fallback keys or if it did so in the past, shown by
// the existence of a fallback creation timestamp, generate a new one if
// we don't have one, or if the current fallback key expired.
if unused_fallback_keys.is_some() || self.fallback_creation_timestamp.is_some() {
self.generate_fallback_key_if_needed();
}
}
/// Generate new one-time keys that need to be uploaded to the server.
///
/// Returns None if no keys need to be uploaded, otherwise the number of
/// newly generated one-time keys. May return 0 if some one-time keys are
/// already generated but weren't uploaded.
///
/// Generally `Some` means that keys should be uploaded, while `None` means
/// that keys should not be uploaded.
#[instrument(skip_all)]
pub fn generate_one_time_keys_if_needed(&mut self) -> Option<u64> {
// Only generate one-time keys if there aren't any, otherwise the caller
// might have failed to upload them the last time this method was
// called.
if !self.one_time_keys().is_empty() {
return Some(0);
}
let count = self.uploaded_key_count();
let max_keys = self.max_one_time_keys();
if count >= max_keys as u64 {
return None;
}
let key_count = (max_keys as u64) - count;
let key_count: usize = key_count.try_into().unwrap_or(max_keys);
let result = self.generate_one_time_keys(key_count);
debug!(
count = key_count,
discarded_keys = ?result.removed,
created_keys = ?result.created,
"Generated new one-time keys"
);
Some(key_count as u64)
}
/// Generate a new fallback key iff a unpublished one isn't already inside
/// of vodozemac and if the currently active one expired.
///
/// The former is checked using [`Account::fallback_key().is_empty()`],
/// which is a hashmap that gets cleared by the
/// [`Account::mark_keys_as_published()`] call.
pub(crate) fn generate_fallback_key_if_needed(&mut self) {
if self.inner.fallback_key().is_empty() && self.fallback_key_expired() {
let removed_fallback_key = self.inner.generate_fallback_key();
self.fallback_creation_timestamp = Some(MilliSecondsSinceUnixEpoch::now());
debug!(
?removed_fallback_key,
"The fallback key either expired or we didn't have one: generated a new fallback key.",
);
}
}
/// Check if our most recent fallback key has expired.
///
/// We consider the fallback key to be expired if it's older than a week.
/// This is the lower bound for the recommended signed pre-key bundle
/// rotation interval in the X3DH spec[1].
///
/// [1]: https://signal.org/docs/specifications/x3dh/#publishing-keys
fn fallback_key_expired(&self) -> bool {
const FALLBACK_KEY_MAX_AGE: Duration = Duration::from_secs(3600 * 24 * 7);
if let Some(time) = self.fallback_creation_timestamp {
// `to_system_time()` returns `None` if the the UNIX_EPOCH + `time` doesn't fit
// into a i64. This will likely never happen, but let's rotate the
// key in case the values are messed up for some other reason.
let Some(system_time) = time.to_system_time() else {
return true;
};
// `elapsed()` errors if the `system_time` is in the future, this should mean
// that our clock has changed to the past, let's rotate just in case
// and then we'll get to a normal time.
let Ok(elapsed) = system_time.elapsed() else {
return true;
};
// Alright, our times are normal and we know how much time elapsed since the
// last time we created/rotated a fallback key.
//
// If the key is older than a week, then we rotate it.
elapsed > FALLBACK_KEY_MAX_AGE
} else {
// We never created a fallback key, or we're migrating to the time-based
// fallback key rotation, so let's generate a new fallback key.
true
}
}
fn fallback_key(&self) -> HashMap<KeyId, Curve25519PublicKey> {
self.inner.fallback_key()
}
/// Get a tuple of device, one-time, and fallback keys that need to be
/// uploaded.
///
/// If no keys need to be uploaded the `DeviceKeys` will be `None` and the
/// one-time and fallback keys maps will be empty.
pub fn keys_for_upload(&self) -> (Option<DeviceKeys>, OneTimeKeys, FallbackKeys) {
let device_keys = self.shared().not().then(|| self.device_keys());
let one_time_keys = self.signed_one_time_keys();
let fallback_keys = self.signed_fallback_keys();
(device_keys, one_time_keys, fallback_keys)
}
/// Mark the current set of one-time keys as being published.
pub fn mark_keys_as_published(&mut self) {
self.inner.mark_keys_as_published();
}
/// Sign the given string using the accounts signing key.
///
/// Returns the signature as a base64 encoded string.
pub fn sign(&self, string: &str) -> Ed25519Signature {
self.inner.sign(string)
}
/// Get a serializable version of the `Account` so it can be persisted.
pub fn pickle(&self) -> PickledAccount {
let pickle = self.inner.pickle();
PickledAccount {
user_id: self.user_id().to_owned(),
device_id: self.device_id().to_owned(),
pickle,
shared: self.shared(),
dehydrated: self.static_data.dehydrated,
uploaded_signed_key_count: self.uploaded_key_count(),
creation_local_time: self.static_data.creation_local_time,
fallback_key_creation_timestamp: self.fallback_creation_timestamp,
}
}
pub(crate) fn dehydrate(&self, pickle_key: &[u8; 32]) -> Raw<DehydratedDeviceData> {
let device_pickle = self
.inner
.to_libolm_pickle(pickle_key)
.expect("We should be able to convert a freshly created Account into a libolm pickle");
let data = DehydratedDeviceData::V1(DehydratedDeviceV1::new(device_pickle));
Raw::from_json(to_raw_value(&data).expect("Couldn't serialize our dehydrated device data"))
}
pub(crate) fn rehydrate(
pickle_key: &[u8; 32],
user_id: &UserId,
device_id: &DeviceId,
device_data: Raw<DehydratedDeviceData>,
) -> Result<Self, DehydrationError> {
let data = device_data.deserialize()?;
match data {
DehydratedDeviceData::V1(d) => {
let account = InnerAccount::from_libolm_pickle(&d.device_pickle, pickle_key)?;
Ok(Self::new_helper(account, user_id, device_id))
}
_ => Err(DehydrationError::Json(serde_json::Error::custom(format!(
"Unsupported dehydrated device algorithm {:?}",
data.algorithm()
)))),
}
}
/// Restore an account from a previously pickled one.
///
/// # Arguments
///
/// * `pickle` - The pickled version of the Account.
///
/// * `pickle_mode` - The mode that was used to pickle the account, either
/// an unencrypted mode or an encrypted using passphrase.
pub fn from_pickle(pickle: PickledAccount) -> Result<Self, PickleError> {
let account: vodozemac::olm::Account = pickle.pickle.into();
let identity_keys = account.identity_keys();
Ok(Self {
static_data: StaticAccountData {
user_id: (*pickle.user_id).into(),
device_id: (*pickle.device_id).into(),
identity_keys: Arc::new(identity_keys),
dehydrated: pickle.dehydrated,
creation_local_time: pickle.creation_local_time,
},
inner: Box::new(account),
shared: pickle.shared,
uploaded_signed_key_count: pickle.uploaded_signed_key_count,
fallback_creation_timestamp: pickle.fallback_key_creation_timestamp,
})
}
/// Sign the device keys of the account and return them so they can be
/// uploaded.
pub fn device_keys(&self) -> DeviceKeys {
let mut device_keys = self.unsigned_device_keys();
// Create a copy of the device keys containing only fields that will
// get signed.
let json_device_keys =
serde_json::to_value(&device_keys).expect("device key is always safe to serialize");
let signature = self
.sign_json(json_device_keys)
.expect("Newly created device keys can always be signed");
device_keys.signatures.add_signature(
self.user_id().to_owned(),
DeviceKeyId::from_parts(DeviceKeyAlgorithm::Ed25519, &self.static_data.device_id),
signature,
);
device_keys
}
/// Bootstrap Cross-Signing
pub async fn bootstrap_cross_signing(
&self,
) -> (PrivateCrossSigningIdentity, UploadSigningKeysRequest, SignatureUploadRequest) {
PrivateCrossSigningIdentity::with_account(self).await
}
/// Sign the given CrossSigning Key in place
pub fn sign_cross_signing_key(
&self,
cross_signing_key: &mut CrossSigningKey,
) -> Result<(), SignatureError> {
#[allow(clippy::needless_borrows_for_generic_args)]
// XXX: false positive, see https://github.com/rust-lang/rust-clippy/issues/12856
let signature = self.sign_json(serde_json::to_value(&cross_signing_key)?)?;
cross_signing_key.signatures.add_signature(
self.user_id().to_owned(),
DeviceKeyId::from_parts(DeviceKeyAlgorithm::Ed25519, self.device_id()),
signature,
);
Ok(())
}
/// Sign the given Master Key
pub fn sign_master_key(
&self,
master_key: &MasterPubkey,
) -> Result<SignatureUploadRequest, SignatureError> {
let public_key =
master_key.get_first_key().ok_or(SignatureError::MissingSigningKey)?.to_base64().into();
let mut cross_signing_key: CrossSigningKey = master_key.as_ref().clone();
cross_signing_key.signatures.clear();
self.sign_cross_signing_key(&mut cross_signing_key)?;
let mut user_signed_keys = SignedKeys::new();
user_signed_keys.add_cross_signing_keys(public_key, cross_signing_key.to_raw());
let signed_keys = [(self.user_id().to_owned(), user_signed_keys)].into();
Ok(SignatureUploadRequest::new(signed_keys))
}
/// Convert a JSON value to the canonical representation and sign the JSON
/// string.
///
/// # Arguments
///
/// * `json` - The value that should be converted into a canonical JSON
/// string.
pub fn sign_json(&self, json: Value) -> Result<Ed25519Signature, SignatureError> {
self.inner.sign_json(json)
}
/// Sign and prepare one-time keys to be uploaded.
///
/// If no one-time keys need to be uploaded, returns an empty `BTreeMap`.
pub fn signed_one_time_keys(
&self,
) -> BTreeMap<OwnedDeviceKeyId, Raw<ruma::encryption::OneTimeKey>> {
let one_time_keys = self.one_time_keys();
if one_time_keys.is_empty() {
BTreeMap::new()
} else {
self.signed_keys(one_time_keys, false)
}
}
/// Sign and prepare fallback keys to be uploaded.
///
/// If no fallback keys need to be uploaded returns an empty BTreeMap.
pub fn signed_fallback_keys(
&self,
) -> BTreeMap<OwnedDeviceKeyId, Raw<ruma::encryption::OneTimeKey>> {
let fallback_key = self.fallback_key();
if fallback_key.is_empty() {
BTreeMap::new()
} else {
self.signed_keys(fallback_key, true)
}
}
fn signed_keys(
&self,
keys: HashMap<KeyId, Curve25519PublicKey>,
fallback: bool,
) -> BTreeMap<OwnedDeviceKeyId, Raw<ruma::encryption::OneTimeKey>> {
let mut keys_map = BTreeMap::new();
for (key_id, key) in keys {
let signed_key = self.sign_key(key, fallback);
keys_map.insert(
DeviceKeyId::from_parts(
DeviceKeyAlgorithm::SignedCurve25519,
key_id.to_base64().as_str().into(),
),
signed_key.into_raw(),
);
}
keys_map
}
fn sign_key(&self, key: Curve25519PublicKey, fallback: bool) -> SignedKey {
let mut key = if fallback {
SignedKey::new_fallback(key.to_owned())
} else {
SignedKey::new(key.to_owned())
};
let signature = self
.sign_json(serde_json::to_value(&key).expect("Can't serialize a signed key"))
.expect("Newly created one-time keys can always be signed");
key.signatures_mut().add_signature(
self.user_id().to_owned(),
DeviceKeyId::from_parts(DeviceKeyAlgorithm::Ed25519, self.device_id()),
signature,
);
key
}
/// Create a new session with another account given a one-time key.
///
/// Returns the newly created session or a `OlmSessionError` if creating a
/// session failed.
///
/// # Arguments
///
/// * `config` - The session config that should be used when creating the
/// Session.
///
/// * `identity_key` - The other account's identity/curve25519 key.
///
/// * `one_time_key` - A signed one-time key that the other account created
/// and shared with us.
///
/// * `fallback_used` - Was the one-time key a fallback key.
///
/// * `our_device_keys` - Our own `DeviceKeys`, including cross-signing
/// signatures if applicable, for embedding in encrypted messages.
pub fn create_outbound_session_helper(
&self,
config: SessionConfig,
identity_key: Curve25519PublicKey,
one_time_key: Curve25519PublicKey,
fallback_used: bool,
our_device_keys: DeviceKeys,
) -> Session {
let session = self.inner.create_outbound_session(config, identity_key, one_time_key);
let now = SecondsSinceUnixEpoch::now();
let session_id = session.session_id();
Session {
inner: Arc::new(Mutex::new(session)),
session_id: session_id.into(),
sender_key: identity_key,
our_device_keys,
created_using_fallback_key: fallback_used,
creation_time: now,
last_use_time: now,
}
}
#[instrument(
skip_all,
fields(
user_id = ?device.user_id(),
device_id = ?device.device_id(),
algorithms = ?device.algorithms()
)
)]
fn find_pre_key_bundle(
device: &DeviceData,
key_map: &BTreeMap<OwnedDeviceKeyId, Raw<ruma::encryption::OneTimeKey>>,
) -> Result<PrekeyBundle, SessionCreationError> {
let mut keys = key_map.iter();
let first_key = keys.next().ok_or_else(|| {
SessionCreationError::OneTimeKeyMissing(
device.user_id().to_owned(),
device.device_id().into(),
)
})?;
let first_key_id = first_key.0.to_owned();
let first_key = OneTimeKey::deserialize(first_key_id.algorithm(), first_key.1)?;
let result = match first_key {
OneTimeKey::SignedKey(key) => Ok(PrekeyBundle::Olm3DH { key }),
_ => Err(SessionCreationError::OneTimeKeyUnknown(
device.user_id().to_owned(),
device.device_id().into(),
)),
};
trace!(?result, "Finished searching for a valid pre-key bundle");
result
}
/// Create a new session with another account given a one-time key and a
/// device.
///
/// Returns the newly created session or a `OlmSessionError` if creating a
/// session failed.
///
/// # Arguments
/// * `device` - The other account's device.
///
/// * `key_map` - A map from the algorithm and device ID to the one-time key
/// that the other account created and shared with us.
///
/// * `our_device_keys` - Our own `DeviceKeys`, including cross-signing
/// signatures if applicable, for embedding in encrypted messages.
#[allow(clippy::result_large_err)]
pub fn create_outbound_session(
&self,
device: &DeviceData,
key_map: &BTreeMap<OwnedDeviceKeyId, Raw<ruma::encryption::OneTimeKey>>,
our_device_keys: DeviceKeys,
) -> Result<Session, SessionCreationError> {
let pre_key_bundle = Self::find_pre_key_bundle(device, key_map)?;