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
mod pk_signing;
use std::sync::{
atomic::{AtomicBool, Ordering},
Arc,
};
use matrix_sdk_common::locks::Mutex;
use pk_signing::{MasterSigning, PickledSignings, SelfSigning, Signing, SigningError, UserSigning};
use ruma::{
api::client::keys::upload_signatures::v3::{Request as SignatureUploadRequest, SignedKeys},
encryption::KeyUsage,
events::secret::request::SecretName,
DeviceKeyAlgorithm, DeviceKeyId, OwnedDeviceId, OwnedDeviceKeyId, OwnedUserId, UserId,
};
use serde::{Deserialize, Serialize};
use serde_json::Error as JsonError;
use vodozemac::Ed25519Signature;
use crate::{
error::SignatureError,
identities::{MasterPubkey, SelfSigningPubkey, UserSigningPubkey},
requests::UploadSigningKeysRequest,
store::SecretImportError,
types::DeviceKeys,
OwnUserIdentity, ReadOnlyAccount, ReadOnlyDevice, ReadOnlyOwnUserIdentity,
ReadOnlyUserIdentity,
};
#[derive(Clone, Debug)]
pub struct PrivateCrossSigningIdentity {
user_id: Arc<UserId>,
shared: Arc<AtomicBool>,
pub(crate) master_key: Arc<Mutex<Option<MasterSigning>>>,
pub(crate) user_signing_key: Arc<Mutex<Option<UserSigning>>>,
pub(crate) self_signing_key: Arc<Mutex<Option<SelfSigning>>>,
}
#[derive(Debug, Clone)]
pub struct ClearResult {
master_cleared: bool,
self_signing_cleared: bool,
user_signing_cleared: bool,
}
impl ClearResult {
pub fn any_cleared(&self) -> bool {
self.master_cleared || self.self_signing_cleared || self.user_signing_cleared
}
}
#[derive(Serialize, Deserialize)]
#[allow(missing_debug_implementations)]
pub struct PickledCrossSigningIdentity {
pub user_id: OwnedUserId,
pub shared: bool,
pub keys: PickledSignings,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CrossSigningStatus {
pub has_master: bool,
pub has_self_signing: bool,
pub has_user_signing: bool,
}
impl PrivateCrossSigningIdentity {
pub fn user_id(&self) -> &UserId {
&self.user_id
}
pub async fn is_empty(&self) -> bool {
let has_master = self.master_key.lock().await.is_some();
let has_user = self.user_signing_key.lock().await.is_some();
let has_self = self.self_signing_key.lock().await.is_some();
!(has_master && has_user && has_self)
}
pub async fn master_key_id(&self) -> Option<OwnedDeviceKeyId> {
let master_key = self.master_public_key().await?.get_first_key()?.to_base64();
let master_key = OwnedDeviceId::from(master_key);
Some(DeviceKeyId::from_parts(DeviceKeyAlgorithm::Ed25519, &master_key))
}
pub async fn can_sign_devices(&self) -> bool {
self.self_signing_key.lock().await.is_some()
}
pub async fn can_sign_users(&self) -> bool {
self.user_signing_key.lock().await.is_some()
}
pub async fn has_master_key(&self) -> bool {
self.master_key.lock().await.is_some()
}
pub async fn status(&self) -> CrossSigningStatus {
CrossSigningStatus {
has_master: self.has_master_key().await,
has_self_signing: self.can_sign_devices().await,
has_user_signing: self.can_sign_users().await,
}
}
pub async fn master_public_key(&self) -> Option<MasterPubkey> {
self.master_key.lock().await.as_ref().map(|m| m.public_key.to_owned())
}
pub async fn self_signing_public_key(&self) -> Option<SelfSigningPubkey> {
self.self_signing_key.lock().await.as_ref().map(|k| k.public_key.to_owned())
}
pub async fn user_signing_public_key(&self) -> Option<UserSigningPubkey> {
self.user_signing_key.lock().await.as_ref().map(|k| k.public_key.to_owned())
}
pub async fn export_secret(&self, secret_name: &SecretName) -> Option<String> {
match secret_name {
SecretName::CrossSigningMasterKey => {
self.master_key.lock().await.as_ref().map(|m| m.export_seed())
}
SecretName::CrossSigningUserSigningKey => {
self.user_signing_key.lock().await.as_ref().map(|m| m.export_seed())
}
SecretName::CrossSigningSelfSigningKey => {
self.self_signing_key.lock().await.as_ref().map(|m| m.export_seed())
}
_ => None,
}
}
pub(crate) async fn import_secret(
&self,
public_identity: OwnUserIdentity,
secret_name: &SecretName,
seed: &str,
) -> Result<(), SecretImportError> {
let (master, self_signing, user_signing) = match secret_name {
SecretName::CrossSigningMasterKey => (Some(seed), None, None),
SecretName::CrossSigningSelfSigningKey => (None, Some(seed), None),
SecretName::CrossSigningUserSigningKey => (None, None, Some(seed)),
_ => return Ok(()),
};
self.import_secrets(public_identity, master, self_signing, user_signing).await
}
pub(crate) async fn import_secrets(
&self,
public_identity: OwnUserIdentity,
master_key: Option<&str>,
self_signing_key: Option<&str>,
user_signing_key: Option<&str>,
) -> Result<(), SecretImportError> {
let master = if let Some(master_key) = master_key {
let master = MasterSigning::from_base64(self.user_id().to_owned(), master_key)?;
if public_identity.master_key() == &master.public_key {
Ok(Some(master))
} else {
Err(SecretImportError::MismatchedPublicKeys)
}
} else {
Ok(None)
}?;
let user_signing = if let Some(user_signing_key) = user_signing_key {
let subkey = UserSigning::from_base64(self.user_id().to_owned(), user_signing_key)?;
if public_identity.user_signing_key() == &subkey.public_key {
Ok(Some(subkey))
} else {
Err(SecretImportError::MismatchedPublicKeys)
}
} else {
Ok(None)
}?;
let self_signing = if let Some(self_signing_key) = self_signing_key {
let subkey = SelfSigning::from_base64(self.user_id().to_owned(), self_signing_key)?;
if public_identity.self_signing_key() == &subkey.public_key {
Ok(Some(subkey))
} else {
Err(SecretImportError::MismatchedPublicKeys)
}
} else {
Ok(None)
}?;
if let Some(master) = master {
*self.master_key.lock().await = Some(master);
}
if let Some(self_signing) = self_signing {
*self.self_signing_key.lock().await = Some(self_signing);
}
if let Some(user_signing) = user_signing {
*self.user_signing_key.lock().await = Some(user_signing);
}
Ok(())
}
pub async fn import_secrets_unchecked(
&self,
master_key: Option<&str>,
self_signing_key: Option<&str>,
user_signing_key: Option<&str>,
) -> Result<(), SecretImportError> {
if let Some(master_key) = master_key {
let master = MasterSigning::from_base64(self.user_id().to_owned(), master_key)?;
*self.master_key.lock().await = Some(master);
}
if let Some(user_signing_key) = user_signing_key {
let subkey = UserSigning::from_base64(self.user_id().to_owned(), user_signing_key)?;
*self.user_signing_key.lock().await = Some(subkey);
};
if let Some(self_signing_key) = self_signing_key {
let subkey = SelfSigning::from_base64(self.user_id().to_owned(), self_signing_key)?;
*self.self_signing_key.lock().await = Some(subkey);
}
Ok(())
}
pub(crate) async fn clear_if_differs(
&self,
public_identity: &ReadOnlyOwnUserIdentity,
) -> ClearResult {
let result = self.get_public_identity_diff(public_identity).await;
if result.master_cleared {
*self.master_key.lock().await = None;
}
if result.user_signing_cleared {
*self.user_signing_key.lock().await = None;
}
if result.self_signing_cleared {
*self.self_signing_key.lock().await = None;
}
result
}
async fn get_public_identity_diff(
&self,
public_identity: &ReadOnlyOwnUserIdentity,
) -> ClearResult {
let master_differs = self
.master_public_key()
.await
.map(|master| &master != public_identity.master_key())
.unwrap_or(false);
let user_signing_differs = self
.user_signing_public_key()
.await
.map(|subkey| &subkey != public_identity.user_signing_key())
.unwrap_or(false);
let self_signing_differs = self
.self_signing_public_key()
.await
.map(|subkey| &subkey != public_identity.self_signing_key())
.unwrap_or(false);
ClearResult {
master_cleared: master_differs,
user_signing_cleared: user_signing_differs,
self_signing_cleared: self_signing_differs,
}
}
pub(crate) async fn get_missing_secrets(&self) -> Vec<SecretName> {
let mut missing = Vec::new();
if !self.has_master_key().await {
missing.push(SecretName::CrossSigningMasterKey);
}
if !self.can_sign_devices().await {
missing.push(SecretName::CrossSigningSelfSigningKey);
}
if !self.can_sign_users().await {
missing.push(SecretName::CrossSigningUserSigningKey);
}
missing
}
pub fn empty(user_id: &UserId) -> Self {
Self {
user_id: user_id.into(),
shared: Arc::new(AtomicBool::new(false)),
master_key: Arc::new(Mutex::new(None)),
self_signing_key: Arc::new(Mutex::new(None)),
user_signing_key: Arc::new(Mutex::new(None)),
}
}
pub(crate) async fn to_public_identity(
&self,
) -> Result<ReadOnlyOwnUserIdentity, SignatureError> {
let master = self
.master_key
.lock()
.await
.as_ref()
.ok_or(SignatureError::MissingSigningKey)?
.public_key
.clone();
let self_signing = self
.self_signing_key
.lock()
.await
.as_ref()
.ok_or(SignatureError::MissingSigningKey)?
.public_key
.clone();
let user_signing = self
.user_signing_key
.lock()
.await
.as_ref()
.ok_or(SignatureError::MissingSigningKey)?
.public_key
.clone();
let identity = ReadOnlyOwnUserIdentity::new(master, self_signing, user_signing)?;
identity.mark_as_verified();
Ok(identity)
}
pub(crate) async fn sign_user(
&self,
user_identity: &ReadOnlyUserIdentity,
) -> Result<SignatureUploadRequest, SignatureError> {
let master_key = self
.user_signing_key
.lock()
.await
.as_ref()
.ok_or(SignatureError::MissingSigningKey)?
.sign_user(user_identity)?;
let mut user_signed_keys = SignedKeys::new();
user_signed_keys.add_cross_signing_keys(
user_identity
.master_key()
.get_first_key()
.ok_or(SignatureError::MissingSigningKey)?
.to_base64()
.into(),
master_key.to_raw(),
);
let signed_keys = [(user_identity.user_id().to_owned(), user_signed_keys)].into();
Ok(SignatureUploadRequest::new(signed_keys))
}
pub(crate) async fn sign_device(
&self,
device: &ReadOnlyDevice,
) -> Result<SignatureUploadRequest, SignatureError> {
let mut device_keys = device.as_device_keys().to_owned();
device_keys.signatures.clear();
self.sign_device_keys(&mut device_keys).await
}
pub(crate) async fn sign_account(
&self,
account: &ReadOnlyAccount,
) -> Result<SignatureUploadRequest, SignatureError> {
let mut device_keys = account.unsigned_device_keys();
self.sign_device_keys(&mut device_keys).await
}
pub(crate) async fn sign_device_keys(
&self,
device_keys: &mut DeviceKeys,
) -> Result<SignatureUploadRequest, SignatureError> {
self.self_signing_key
.lock()
.await
.as_ref()
.ok_or(SignatureError::MissingSigningKey)?
.sign_device(device_keys)?;
let mut user_signed_keys = SignedKeys::new();
user_signed_keys.add_device_keys(device_keys.device_id.clone(), device_keys.to_raw());
let signed_keys = [((*self.user_id).to_owned(), user_signed_keys)].into();
Ok(SignatureUploadRequest::new(signed_keys))
}
pub(crate) async fn sign(&self, message: &str) -> Result<Ed25519Signature, SignatureError> {
Ok(self
.master_key
.lock()
.await
.as_ref()
.ok_or(SignatureError::MissingSigningKey)?
.sign(message))
}
pub(crate) async fn with_account(
account: &ReadOnlyAccount,
) -> (Self, UploadSigningKeysRequest, SignatureUploadRequest) {
let master = Signing::new();
let mut public_key =
master.cross_signing_key(account.user_id().to_owned(), KeyUsage::Master);
account
.sign_cross_signing_key(&mut public_key)
.await
.expect("Can't sign our freshly created master key with our account");
let master = MasterSigning { inner: master, public_key: public_key.into() };
let identity = Self::new_helper(account.user_id(), master).await;
let signature_request = identity
.sign_account(account)
.await
.expect("Can't sign own device with new cross signing keys");
let request = identity.as_upload_request().await;
(identity, request, signature_request)
}
async fn new_helper(user_id: &UserId, master: MasterSigning) -> Self {
let user = Signing::new();
let mut public_key = user.cross_signing_key(user_id.to_owned(), KeyUsage::UserSigning);
master.sign_subkey(&mut public_key);
let user = UserSigning { inner: user, public_key: public_key.into() };
let self_signing = Signing::new();
let mut public_key =
self_signing.cross_signing_key(user_id.to_owned(), KeyUsage::SelfSigning);
master.sign_subkey(&mut public_key);
let self_signing = SelfSigning { inner: self_signing, public_key: public_key.into() };
Self {
user_id: user_id.into(),
shared: Arc::new(AtomicBool::new(false)),
master_key: Arc::new(Mutex::new(Some(master))),
self_signing_key: Arc::new(Mutex::new(Some(self_signing))),
user_signing_key: Arc::new(Mutex::new(Some(user))),
}
}
#[cfg(any(test, feature = "testing"))]
#[allow(dead_code)]
pub async fn new(user_id: OwnedUserId) -> Self {
let master = Signing::new();
let public_key = master.cross_signing_key(user_id.clone(), KeyUsage::Master);
let master = MasterSigning { inner: master, public_key: public_key.into() };
Self::new_helper(&user_id, master).await
}
#[cfg(any(test, feature = "testing"))]
#[allow(dead_code)]
pub async fn reset(&mut self) {
let new = Self::new(self.user_id().to_owned()).await;
*self = new
}
pub fn mark_as_shared(&self) {
self.shared.store(true, Ordering::SeqCst)
}
pub fn shared(&self) -> bool {
self.shared.load(Ordering::SeqCst)
}
pub async fn pickle(&self) -> Result<PickledCrossSigningIdentity, JsonError> {
let master_key = self.master_key.lock().await.as_ref().map(|m| m.pickle());
let self_signing_key = self.self_signing_key.lock().await.as_ref().map(|m| m.pickle());
let user_signing_key = self.user_signing_key.lock().await.as_ref().map(|m| m.pickle());
let keys = PickledSignings { master_key, user_signing_key, self_signing_key };
Ok(PickledCrossSigningIdentity {
user_id: self.user_id.as_ref().to_owned(),
shared: self.shared(),
keys,
})
}
pub async fn from_pickle(pickle: PickledCrossSigningIdentity) -> Result<Self, SigningError> {
let keys = pickle.keys;
let master = keys.master_key.map(MasterSigning::from_pickle).transpose()?;
let self_signing = keys.self_signing_key.map(SelfSigning::from_pickle).transpose()?;
let user_signing = keys.user_signing_key.map(UserSigning::from_pickle).transpose()?;
Ok(Self {
user_id: (&*pickle.user_id).into(),
shared: Arc::new(AtomicBool::from(pickle.shared)),
master_key: Arc::new(Mutex::new(master)),
self_signing_key: Arc::new(Mutex::new(self_signing)),
user_signing_key: Arc::new(Mutex::new(user_signing)),
})
}
pub(crate) async fn as_upload_request(&self) -> UploadSigningKeysRequest {
let master_key =
self.master_key.lock().await.as_ref().map(|k| k.public_key.as_ref().clone());
let user_signing_key =
self.user_signing_key.lock().await.as_ref().map(|k| k.public_key.as_ref().clone());
let self_signing_key =
self.self_signing_key.lock().await.as_ref().map(|k| k.public_key.as_ref().clone());
UploadSigningKeysRequest { master_key, self_signing_key, user_signing_key }
}
}
#[cfg(test)]
mod tests {
use matrix_sdk_test::async_test;
use ruma::{
device_id, signatures::CanonicalJsonValue, user_id, DeviceKeyAlgorithm, DeviceKeyId, UserId,
};
use serde_json::json;
use super::{PrivateCrossSigningIdentity, Signing};
use crate::{
identities::{ReadOnlyDevice, ReadOnlyUserIdentity},
olm::{ReadOnlyAccount, VerifyJson},
types::Signatures,
};
fn user_id() -> &'static UserId {
user_id!("@example:localhost")
}
#[test]
fn signature_verification() {
let signing = Signing::new();
let user_id = user_id();
let key_id = DeviceKeyId::from_parts(DeviceKeyAlgorithm::Ed25519, "DEVICEID".into());
let json = json!({
"hello": "world"
});
let canonicalized: CanonicalJsonValue = json.try_into().unwrap();
let canonicalized = canonicalized.to_string();
let signature = signing.sign(&canonicalized);
let mut signatures = Signatures::new();
signatures.add_signature(user_id.to_owned(), key_id.clone(), signature);
let public_key = signing.public_key();
public_key
.verify_canonicalized_json(user_id, &key_id, &signatures, &canonicalized)
.expect("The signature can be verified");
}
#[test]
fn pickling_signing() {
let signing = Signing::new();
let pickled = signing.pickle();
let unpickled = Signing::from_pickle(pickled).unwrap();
assert_eq!(signing.public_key(), unpickled.public_key());
}
#[async_test]
async fn private_identity_creation() {
let identity = PrivateCrossSigningIdentity::new(user_id().to_owned()).await;
let master_key = identity.master_key.lock().await;
let master_key = master_key.as_ref().unwrap();
assert!(master_key
.public_key
.verify_subkey(&identity.self_signing_key.lock().await.as_ref().unwrap().public_key,)
.is_ok());
assert!(master_key
.public_key
.verify_subkey(&identity.user_signing_key.lock().await.as_ref().unwrap().public_key,)
.is_ok());
}
#[async_test]
async fn identity_pickling() {
let identity = PrivateCrossSigningIdentity::new(user_id().to_owned()).await;
let pickled = identity.pickle().await.unwrap();
let unpickled = PrivateCrossSigningIdentity::from_pickle(pickled).await.unwrap();
assert_eq!(identity.user_id, unpickled.user_id);
assert_eq!(&*identity.master_key.lock().await, &*unpickled.master_key.lock().await);
assert_eq!(
&*identity.user_signing_key.lock().await,
&*unpickled.user_signing_key.lock().await
);
assert_eq!(
&*identity.self_signing_key.lock().await,
&*unpickled.self_signing_key.lock().await
);
}
#[async_test]
async fn private_identity_signed_by_account() {
let account = ReadOnlyAccount::new(user_id(), device_id!("DEVICEID"));
let (identity, _, _) = PrivateCrossSigningIdentity::with_account(&account).await;
let master = identity.master_key.lock().await;
let master = master.as_ref().unwrap();
assert!(!master.public_key.signatures().is_empty());
}
#[async_test]
async fn sign_device() {
let account = ReadOnlyAccount::new(user_id(), device_id!("DEVICEID"));
let (identity, _, _) = PrivateCrossSigningIdentity::with_account(&account).await;
let mut device = ReadOnlyDevice::from_account(&account).await;
let self_signing = identity.self_signing_key.lock().await;
let self_signing = self_signing.as_ref().unwrap();
let mut device_keys = device.as_device_keys().to_owned();
self_signing.sign_device(&mut device_keys).unwrap();
device.update_device(&device_keys).unwrap();
let public_key = &self_signing.public_key;
public_key.verify_device(&device).unwrap()
}
#[async_test]
async fn sign_user_identity() {
let account = ReadOnlyAccount::new(user_id(), device_id!("DEVICEID"));
let (identity, _, _) = PrivateCrossSigningIdentity::with_account(&account).await;
let bob_account = ReadOnlyAccount::new(user_id!("@bob:localhost"), device_id!("DEVICEID"));
let (bob_private, _, _) = PrivateCrossSigningIdentity::with_account(&bob_account).await;
let mut bob_public = ReadOnlyUserIdentity::from_private(&bob_private).await;
let user_signing = identity.user_signing_key.lock().await;
let user_signing = user_signing.as_ref().unwrap();
let master = user_signing.sign_user(&bob_public).unwrap();
assert_eq!(
master.signatures.signature_count(),
1,
"We're only uploading our own signature"
);
bob_public.master_key = master.into();
user_signing.public_key.verify_master_key(bob_public.master_key()).unwrap();
}
}