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
use std::{
collections::{BTreeMap, HashMap},
convert::{TryFrom, TryInto},
ops::Deref,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
};
use atomic::Atomic;
use matrix_sdk_common::locks::Mutex;
use ruma::{
api::client::keys::upload_signatures::v3::Request as SignatureUploadRequest,
events::{
forwarded_room_key::ToDeviceForwardedRoomKeyEventContent,
key::verification::VerificationMethod, room::encrypted::ToDeviceRoomEncryptedEventContent,
AnyToDeviceEventContent,
},
DeviceId, DeviceKeyAlgorithm, DeviceKeyId, EventEncryptionAlgorithm, OwnedDeviceId,
OwnedDeviceKeyId, UserId,
};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use tracing::warn;
use vodozemac::{Curve25519PublicKey, Ed25519PublicKey};
use super::{atomic_bool_deserializer, atomic_bool_serializer};
#[cfg(any(test, feature = "testing"))]
use crate::OlmMachine;
use crate::{
error::{EventError, OlmError, OlmResult, SignatureError},
identities::{ReadOnlyOwnUserIdentity, ReadOnlyUserIdentities},
olm::{InboundGroupSession, Session, SignedJsonObject, VerifyJson},
store::{Changes, CryptoStore, DeviceChanges, Result as StoreResult},
types::{DeviceKey, DeviceKeys, Signatures, SignedKey},
verification::VerificationMachine,
OutgoingVerificationRequest, ReadOnlyAccount, Sas, ToDeviceRequest, VerificationRequest,
};
#[derive(Clone, Serialize, Deserialize)]
pub struct ReadOnlyDevice {
pub(crate) inner: Arc<DeviceKeys>,
#[serde(
serialize_with = "atomic_bool_serializer",
deserialize_with = "atomic_bool_deserializer"
)]
deleted: Arc<AtomicBool>,
#[serde(
serialize_with = "local_trust_serializer",
deserialize_with = "local_trust_deserializer"
)]
trust_state: Arc<Atomic<LocalTrust>>,
}
impl std::fmt::Debug for ReadOnlyDevice {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ReadOnlyDevice")
.field("user_id", &self.user_id())
.field("device_id", &self.device_id())
.field("display_name", &self.display_name())
.field("keys", self.keys())
.field("deleted", &self.deleted.load(Ordering::SeqCst))
.field("trust_state", &self.trust_state)
.finish()
}
}
fn local_trust_serializer<S>(x: &Atomic<LocalTrust>, s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let value = x.load(Ordering::SeqCst);
s.serialize_some(&value)
}
fn local_trust_deserializer<'de, D>(deserializer: D) -> Result<Arc<Atomic<LocalTrust>>, D::Error>
where
D: Deserializer<'de>,
{
let value = LocalTrust::deserialize(deserializer)?;
Ok(Arc::new(Atomic::new(value)))
}
#[derive(Clone)]
pub struct Device {
pub(crate) inner: ReadOnlyDevice,
pub(crate) verification_machine: VerificationMachine,
pub(crate) own_identity: Option<ReadOnlyOwnUserIdentity>,
pub(crate) device_owner_identity: Option<ReadOnlyUserIdentities>,
}
impl std::fmt::Debug for Device {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Device").field("device", &self.inner).finish()
}
}
impl Deref for Device {
type Target = ReadOnlyDevice;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl Device {
pub async fn start_verification(&self) -> StoreResult<(Sas, ToDeviceRequest)> {
let (sas, request) = self.verification_machine.start_sas(self.inner.clone()).await?;
if let OutgoingVerificationRequest::ToDevice(r) = request {
Ok((sas, r))
} else {
panic!("Invalid verification request type");
}
}
pub async fn request_verification(&self) -> (VerificationRequest, OutgoingVerificationRequest) {
self.request_verification_helper(None).await
}
pub async fn request_verification_with_methods(
&self,
methods: Vec<VerificationMethod>,
) -> (VerificationRequest, OutgoingVerificationRequest) {
self.request_verification_helper(Some(methods)).await
}
async fn request_verification_helper(
&self,
methods: Option<Vec<VerificationMethod>>,
) -> (VerificationRequest, OutgoingVerificationRequest) {
self.verification_machine
.request_to_device_verification(
self.user_id(),
vec![self.device_id().to_owned()],
methods,
)
.await
}
pub(crate) async fn get_sessions(&self) -> StoreResult<Option<Arc<Mutex<Vec<Session>>>>> {
if let Some(k) = self.curve25519_key() {
self.verification_machine.store.get_sessions(&k.to_base64()).await
} else {
Ok(None)
}
}
pub fn verified(&self) -> bool {
self.inner.verified(&self.own_identity, &self.device_owner_identity)
}
pub fn is_cross_signing_trusted(&self) -> bool {
self.inner.is_cross_signing_trusted(&self.own_identity, &self.device_owner_identity)
}
pub async fn verify(&self) -> Result<SignatureUploadRequest, SignatureError> {
if self.user_id() == self.verification_machine.own_user_id() {
Ok(self
.verification_machine
.store
.private_identity
.lock()
.await
.sign_device(&self.inner)
.await?)
} else {
Err(SignatureError::UserIdMismatch)
}
}
pub async fn set_local_trust(&self, trust_state: LocalTrust) -> StoreResult<()> {
self.inner.set_trust_state(trust_state);
let changes = Changes {
devices: DeviceChanges { changed: vec![self.inner.clone()], ..Default::default() },
..Default::default()
};
self.verification_machine.store.save_changes(changes).await
}
pub(crate) async fn encrypt(
&self,
content: AnyToDeviceEventContent,
) -> OlmResult<(Session, ToDeviceRoomEncryptedEventContent)> {
self.inner.encrypt(self.verification_machine.store.inner(), content).await
}
pub async fn encrypt_session(
&self,
session: InboundGroupSession,
message_index: Option<u32>,
) -> OlmResult<(Session, ToDeviceRoomEncryptedEventContent)> {
let export = if let Some(index) = message_index {
session.export_at_index(index).await
} else {
session.export().await
};
let content: ToDeviceForwardedRoomKeyEventContent = if let Ok(c) = export.try_into() {
c
} else {
panic!(
"Can't share session {} with device {} {}, key export can't \
be converted to a forwarded room key content",
session.session_id(),
self.user_id(),
self.device_id()
);
};
self.encrypt(AnyToDeviceEventContent::ForwardedRoomKey(content)).await
}
}
#[derive(Debug)]
pub struct UserDevices {
pub(crate) inner: HashMap<OwnedDeviceId, ReadOnlyDevice>,
pub(crate) verification_machine: VerificationMachine,
pub(crate) own_identity: Option<ReadOnlyOwnUserIdentity>,
pub(crate) device_owner_identity: Option<ReadOnlyUserIdentities>,
}
impl UserDevices {
pub fn get(&self, device_id: &DeviceId) -> Option<Device> {
self.inner.get(device_id).map(|d| Device {
inner: d.clone(),
verification_machine: self.verification_machine.clone(),
own_identity: self.own_identity.clone(),
device_owner_identity: self.device_owner_identity.clone(),
})
}
fn own_user_id(&self) -> &UserId {
self.verification_machine.own_user_id()
}
fn own_device_id(&self) -> &DeviceId {
self.verification_machine.own_device_id()
}
pub fn is_any_verified(&self) -> bool {
self.inner
.values()
.filter(|d| {
!(d.user_id() == self.own_user_id() && d.device_id() == self.own_device_id())
})
.any(|d| d.verified(&self.own_identity, &self.device_owner_identity))
}
pub fn keys(&self) -> impl Iterator<Item = &DeviceId> {
self.inner.keys().map(Deref::deref)
}
pub fn devices(&self) -> impl Iterator<Item = Device> + '_ {
self.inner.values().map(move |d| Device {
inner: d.clone(),
verification_machine: self.verification_machine.clone(),
own_identity: self.own_identity.clone(),
device_owner_identity: self.device_owner_identity.clone(),
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum LocalTrust {
Verified = 0,
BlackListed = 1,
Ignored = 2,
Unset = 3,
}
impl From<i64> for LocalTrust {
fn from(state: i64) -> Self {
match state {
0 => LocalTrust::Verified,
1 => LocalTrust::BlackListed,
2 => LocalTrust::Ignored,
3 => LocalTrust::Unset,
_ => LocalTrust::Unset,
}
}
}
impl ReadOnlyDevice {
pub fn new(device_keys: DeviceKeys, trust_state: LocalTrust) -> Self {
Self {
inner: device_keys.into(),
trust_state: Arc::new(Atomic::new(trust_state)),
deleted: Arc::new(AtomicBool::new(false)),
}
}
pub fn user_id(&self) -> &UserId {
&self.inner.user_id
}
pub fn device_id(&self) -> &DeviceId {
&self.inner.device_id
}
pub fn display_name(&self) -> Option<&str> {
self.inner.unsigned.device_display_name.as_deref()
}
pub fn get_key(&self, algorithm: DeviceKeyAlgorithm) -> Option<&DeviceKey> {
self.inner.keys.get(&DeviceKeyId::from_parts(algorithm, self.device_id()))
}
pub fn curve25519_key(&self) -> Option<Curve25519PublicKey> {
self.get_key(DeviceKeyAlgorithm::Curve25519).and_then(|k| {
if let DeviceKey::Curve25519(k) = k {
Some(*k)
} else {
None
}
})
}
pub fn ed25519_key(&self) -> Option<Ed25519PublicKey> {
self.get_key(DeviceKeyAlgorithm::Ed25519).and_then(|k| {
if let DeviceKey::Ed25519(k) = k {
Some(*k)
} else {
None
}
})
}
pub fn keys(&self) -> &BTreeMap<OwnedDeviceKeyId, DeviceKey> {
&self.inner.keys
}
pub fn signatures(&self) -> &Signatures {
&self.inner.signatures
}
pub fn local_trust_state(&self) -> LocalTrust {
self.trust_state.load(Ordering::Relaxed)
}
pub fn is_locally_trusted(&self) -> bool {
self.local_trust_state() == LocalTrust::Verified
}
pub fn is_blacklisted(&self) -> bool {
self.local_trust_state() == LocalTrust::BlackListed
}
pub(crate) fn set_trust_state(&self, state: LocalTrust) {
self.trust_state.store(state, Ordering::Relaxed)
}
pub fn algorithms(&self) -> &[EventEncryptionAlgorithm] {
&self.inner.algorithms
}
pub fn deleted(&self) -> bool {
self.deleted.load(Ordering::Relaxed)
}
pub(crate) fn verified(
&self,
own_identity: &Option<ReadOnlyOwnUserIdentity>,
device_owner: &Option<ReadOnlyUserIdentities>,
) -> bool {
self.is_locally_trusted() || self.is_cross_signing_trusted(own_identity, device_owner)
}
pub(crate) fn is_cross_signing_trusted(
&self,
own_identity: &Option<ReadOnlyOwnUserIdentity>,
device_owner: &Option<ReadOnlyUserIdentities>,
) -> bool {
own_identity.as_ref().map_or(false, |own_identity| {
own_identity.is_verified()
&& device_owner
.as_ref()
.map(|device_identity| match device_identity {
ReadOnlyUserIdentities::Own(_) => {
own_identity.is_device_signed(self).map_or(false, |_| true)
}
ReadOnlyUserIdentities::Other(device_identity) => {
own_identity.is_identity_signed(device_identity).map_or(false, |_| true)
&& device_identity.is_device_signed(self).map_or(false, |_| true)
}
})
.unwrap_or(false)
})
}
pub(crate) async fn encrypt(
&self,
store: &dyn CryptoStore,
content: AnyToDeviceEventContent,
) -> OlmResult<(Session, ToDeviceRoomEncryptedEventContent)> {
let sender_key = if let Some(k) = self.curve25519_key() {
k
} else {
warn!(
user_id = %self.user_id(),
device_id = %self.device_id(),
"Trying to encrypt a Megolm session, but the device doesn't \
have a curve25519 key",
);
return Err(EventError::MissingSenderKey.into());
};
let session = if let Some(s) = store.get_sessions(&sender_key.to_base64()).await? {
let mut sessions = s.lock().await;
sessions.sort_by_key(|s| s.last_use_time);
sessions.get(0).cloned()
} else {
None
};
let mut session = if let Some(s) = session {
s
} else {
warn!(
"Trying to encrypt a Megolm session for user {} on device {}, \
but no Olm session is found",
self.user_id(),
self.device_id()
);
return Err(OlmError::MissingSession);
};
let message = session.encrypt(self, content).await?;
Ok((session, message))
}
pub(crate) fn update_device(&mut self, device_keys: &DeviceKeys) -> Result<(), SignatureError> {
self.verify_device_keys(device_keys)?;
self.inner = device_keys.clone().into();
Ok(())
}
pub(crate) fn as_device_keys(&self) -> &DeviceKeys {
&self.inner
}
#[cfg(feature = "backups_v1")]
pub(crate) fn has_signed_raw(
&self,
signatures: &Signatures,
canonical_json: &str,
) -> Result<(), SignatureError> {
let key = self.ed25519_key().ok_or(SignatureError::MissingSigningKey)?;
let user_id = self.user_id();
let key_id = &DeviceKeyId::from_parts(DeviceKeyAlgorithm::Ed25519, self.device_id());
key.verify_canonicalized_json(user_id, key_id, signatures, canonical_json)
}
fn has_signed(&self, signed_object: &impl SignedJsonObject) -> Result<(), SignatureError> {
let key = self.ed25519_key().ok_or(SignatureError::MissingSigningKey)?;
let user_id = self.user_id();
let key_id = &DeviceKeyId::from_parts(DeviceKeyAlgorithm::Ed25519, self.device_id());
key.verify_json(user_id, key_id, signed_object)
}
pub(crate) fn verify_device_keys(
&self,
device_keys: &DeviceKeys,
) -> Result<(), SignatureError> {
self.has_signed(device_keys)
}
pub(crate) fn verify_one_time_key(
&self,
one_time_key: &SignedKey,
) -> Result<(), SignatureError> {
self.has_signed(one_time_key)
}
pub(crate) fn mark_as_deleted(&self) {
self.deleted.store(true, Ordering::Relaxed);
}
#[cfg(any(test, feature = "testing"))]
#[allow(dead_code)]
pub async fn from_machine(machine: &OlmMachine) -> ReadOnlyDevice {
ReadOnlyDevice::from_account(machine.account()).await
}
pub async fn from_account(account: &ReadOnlyAccount) -> ReadOnlyDevice {
let device_keys = account.device_keys().await;
ReadOnlyDevice::try_from(&device_keys)
.expect("Creating a device from our own account should always succeed")
}
}
impl TryFrom<&DeviceKeys> for ReadOnlyDevice {
type Error = SignatureError;
fn try_from(device_keys: &DeviceKeys) -> Result<Self, Self::Error> {
let device = Self {
inner: device_keys.clone().into(),
deleted: Arc::new(AtomicBool::new(false)),
trust_state: Arc::new(Atomic::new(LocalTrust::Unset)),
};
device.verify_device_keys(device_keys)?;
Ok(device)
}
}
impl PartialEq for ReadOnlyDevice {
fn eq(&self, other: &Self) -> bool {
self.user_id() == other.user_id() && self.device_id() == other.device_id()
}
}
#[cfg(any(test, feature = "testing"))]
pub(crate) mod testing {
#![allow(dead_code)]
use serde_json::json;
use crate::{identities::ReadOnlyDevice, types::DeviceKeys};
pub fn device_keys() -> DeviceKeys {
let device_keys = json!({
"algorithms": vec![
"m.olm.v1.curve25519-aes-sha2",
"m.megolm.v1.aes-sha2"
],
"device_id": "BNYQQWUMXO",
"user_id": "@example:localhost",
"keys": {
"curve25519:BNYQQWUMXO": "xfgbLIC5WAl1OIkpOzoxpCe8FsRDT6nch7NQsOb15nc",
"ed25519:BNYQQWUMXO": "2/5LWJMow5zhJqakV88SIc7q/1pa8fmkfgAzx72w9G4"
},
"signatures": {
"@example:localhost": {
"ed25519:BNYQQWUMXO": "kTwMrbsLJJM/uFGOj/oqlCaRuw7i9p/6eGrTlXjo8UJMCFAetoyWzoMcF35vSe4S6FTx8RJmqX6rM7ep53MHDQ"
}
},
"unsigned": {
"device_display_name": "Alice's mobile phone"
}
});
serde_json::from_value(device_keys).unwrap()
}
pub fn get_device() -> ReadOnlyDevice {
let device_keys = device_keys();
ReadOnlyDevice::try_from(&device_keys).unwrap()
}
}
#[cfg(test)]
pub(crate) mod tests {
use ruma::user_id;
use vodozemac::{Curve25519PublicKey, Ed25519PublicKey};
use super::testing::{device_keys, get_device};
use crate::identities::LocalTrust;
#[test]
fn create_a_device() {
let user_id = user_id!("@example:localhost");
let device_id = "BNYQQWUMXO";
let device = get_device();
assert_eq!(user_id, device.user_id());
assert_eq!(device_id, device.device_id());
assert_eq!(device.algorithms().len(), 2);
assert_eq!(LocalTrust::Unset, device.local_trust_state());
assert_eq!("Alice's mobile phone", device.display_name().unwrap());
assert_eq!(
device.curve25519_key().unwrap(),
Curve25519PublicKey::from_base64("xfgbLIC5WAl1OIkpOzoxpCe8FsRDT6nch7NQsOb15nc")
.unwrap(),
);
assert_eq!(
device.ed25519_key().unwrap(),
Ed25519PublicKey::from_base64("2/5LWJMow5zhJqakV88SIc7q/1pa8fmkfgAzx72w9G4").unwrap(),
);
}
#[test]
fn update_a_device() {
let mut device = get_device();
assert_eq!("Alice's mobile phone", device.display_name().unwrap());
let display_name = "Alice's work computer".to_owned();
let mut device_keys = device_keys();
device_keys.unsigned.device_display_name = Some(display_name.clone());
device.update_device(&device_keys).unwrap();
assert_eq!(&display_name, device.display_name().as_ref().unwrap());
}
#[test]
fn delete_a_device() {
let device = get_device();
assert!(!device.deleted());
let device_clone = device.clone();
device.mark_as_deleted();
assert!(device.deleted());
assert!(device_clone.deleted());
}
}