-
-
Notifications
You must be signed in to change notification settings - Fork 617
/
Copy pathrust-crypto.ts
2212 lines (1943 loc) · 88.6 KB
/
rust-crypto.ts
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 2022-2023 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.
*/
import anotherjson from "another-json";
import * as RustSdkCryptoJs from "@matrix-org/matrix-sdk-crypto-wasm";
import type { IEventDecryptionResult, IMegolmSessionData } from "../@types/crypto.ts";
import { KnownMembership } from "../@types/membership.ts";
import type { IDeviceLists, IToDeviceEvent } from "../sync-accumulator.ts";
import type { IEncryptedEventInfo } from "../crypto/api.ts";
import type { ToDevicePayload, ToDeviceBatch } from "../models/ToDeviceMessage.ts";
import { MatrixEvent, MatrixEventEvent } from "../models/event.ts";
import { Room } from "../models/room.ts";
import { RoomMember } from "../models/room-member.ts";
import {
BackupDecryptor,
CryptoBackend,
DecryptionError,
OnSyncCompletedData,
} from "../common-crypto/CryptoBackend.ts";
import { logger, Logger, LogSpan } from "../logger.ts";
import { IHttpOpts, MatrixHttpApi, Method } from "../http-api/index.ts";
import { RoomEncryptor } from "./RoomEncryptor.ts";
import { OutgoingRequestProcessor } from "./OutgoingRequestProcessor.ts";
import { KeyClaimManager } from "./KeyClaimManager.ts";
import { logDuration, MapWithDefault } from "../utils.ts";
import {
BackupTrustInfo,
BootstrapCrossSigningOpts,
CreateSecretStorageOpts,
CrossSigningKey,
CrossSigningKeyInfo,
CrossSigningStatus,
CryptoApi,
CryptoCallbacks,
DecryptionFailureCode,
DeviceVerificationStatus,
EventEncryptionInfo,
EventShieldColour,
EventShieldReason,
GeneratedSecretStorageKey,
ImportRoomKeysOpts,
KeyBackupCheck,
KeyBackupInfo,
OwnDeviceKeys,
UserVerificationStatus,
VerificationRequest,
encodeRecoveryKey,
deriveRecoveryKeyFromPassphrase,
DeviceIsolationMode,
AllDevicesIsolationMode,
DeviceIsolationModeKind,
CryptoEvent,
CryptoEventHandlerMap,
KeyBackupRestoreOpts,
KeyBackupRestoreResult,
} from "../crypto-api/index.ts";
import { deviceKeysToDeviceMap, rustDeviceToJsDevice } from "./device-converter.ts";
import { IDownloadKeyResult, IQueryKeysRequest } from "../client.ts";
import { Device, DeviceMap } from "../models/device.ts";
import { SECRET_STORAGE_ALGORITHM_V1_AES, ServerSideSecretStorage } from "../secret-storage.ts";
import { CrossSigningIdentity } from "./CrossSigningIdentity.ts";
import { secretStorageCanAccessSecrets, secretStorageContainsCrossSigningKeys } from "./secret-storage.ts";
import { isVerificationEvent, RustVerificationRequest, verificationMethodIdentifierToMethod } from "./verification.ts";
import { EventType, MsgType } from "../@types/event.ts";
import { TypedEventEmitter } from "../models/typed-event-emitter.ts";
import { decryptionKeyMatchesKeyBackupInfo, RustBackupManager } from "./backup.ts";
import { TypedReEmitter } from "../ReEmitter.ts";
import { randomString } from "../randomstring.ts";
import { ClientStoppedError } from "../errors.ts";
import { ISignatures } from "../@types/signed.ts";
import { decodeBase64, encodeBase64 } from "../base64.ts";
import { OutgoingRequestsManager } from "./OutgoingRequestsManager.ts";
import { PerSessionKeyBackupDownloader } from "./PerSessionKeyBackupDownloader.ts";
import { DehydratedDeviceManager } from "./DehydratedDeviceManager.ts";
import { VerificationMethod } from "../types.ts";
import { keyFromAuthData } from "../common-crypto/key-passphrase.ts";
const ALL_VERIFICATION_METHODS = [
VerificationMethod.Sas,
VerificationMethod.ScanQrCode,
VerificationMethod.ShowQrCode,
VerificationMethod.Reciprocate,
];
interface ISignableObject {
signatures?: ISignatures;
unsigned?: object;
}
/**
* An implementation of {@link CryptoBackend} using the Rust matrix-sdk-crypto.
*
* @internal
*/
export class RustCrypto extends TypedEventEmitter<RustCryptoEvents, CryptoEventHandlerMap> implements CryptoBackend {
/**
* The number of iterations to use when deriving a recovery key from a passphrase.
*/
private readonly RECOVERY_KEY_DERIVATION_ITERATIONS = 500000;
private _trustCrossSignedDevices = true;
private deviceIsolationMode: DeviceIsolationMode = new AllDevicesIsolationMode(false);
/** whether {@link stop} has been called */
private stopped = false;
/** mapping of roomId → encryptor class */
private roomEncryptors: Record<string, RoomEncryptor> = {};
private eventDecryptor: EventDecryptor;
private keyClaimManager: KeyClaimManager;
private outgoingRequestProcessor: OutgoingRequestProcessor;
private crossSigningIdentity: CrossSigningIdentity;
private readonly backupManager: RustBackupManager;
private outgoingRequestsManager: OutgoingRequestsManager;
private readonly perSessionBackupDownloader: PerSessionKeyBackupDownloader;
private readonly dehydratedDeviceManager: DehydratedDeviceManager;
private readonly reemitter = new TypedReEmitter<RustCryptoEvents, CryptoEventHandlerMap>(this);
public constructor(
private readonly logger: Logger,
/** The `OlmMachine` from the underlying rust crypto sdk. */
private readonly olmMachine: RustSdkCryptoJs.OlmMachine,
/**
* Low-level HTTP interface: used to make outgoing requests required by the rust SDK.
*
* We expect it to set the access token, etc.
*/
private readonly http: MatrixHttpApi<IHttpOpts & { onlyData: true }>,
/** The local user's User ID. */
private readonly userId: string,
/** The local user's Device ID. */
_deviceId: string,
/** Interface to server-side secret storage */
private readonly secretStorage: ServerSideSecretStorage,
/** Crypto callbacks provided by the application */
private readonly cryptoCallbacks: CryptoCallbacks,
) {
super();
this.outgoingRequestProcessor = new OutgoingRequestProcessor(olmMachine, http);
this.outgoingRequestsManager = new OutgoingRequestsManager(
this.logger,
olmMachine,
this.outgoingRequestProcessor,
);
this.keyClaimManager = new KeyClaimManager(olmMachine, this.outgoingRequestProcessor);
this.backupManager = new RustBackupManager(olmMachine, http, this.outgoingRequestProcessor);
this.perSessionBackupDownloader = new PerSessionKeyBackupDownloader(
this.logger,
this.olmMachine,
this.http,
this.backupManager,
);
this.dehydratedDeviceManager = new DehydratedDeviceManager(
this.logger,
olmMachine,
http,
this.outgoingRequestProcessor,
secretStorage,
);
this.eventDecryptor = new EventDecryptor(this.logger, olmMachine, this.perSessionBackupDownloader);
this.reemitter.reEmit(this.backupManager, [
CryptoEvent.KeyBackupStatus,
CryptoEvent.KeyBackupSessionsRemaining,
CryptoEvent.KeyBackupFailed,
CryptoEvent.KeyBackupDecryptionKeyCached,
]);
this.crossSigningIdentity = new CrossSigningIdentity(olmMachine, this.outgoingRequestProcessor, secretStorage);
// Check and start in background the key backup connection
this.checkKeyBackupAndEnable();
}
/**
* Return the OlmMachine only if {@link RustCrypto#stop} has not been called.
*
* This allows us to better handle race conditions where the client is stopped before or during a crypto API call.
*
* @throws ClientStoppedError if {@link RustCrypto#stop} has been called.
*/
private getOlmMachineOrThrow(): RustSdkCryptoJs.OlmMachine {
if (this.stopped) {
throw new ClientStoppedError();
}
return this.olmMachine;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// CryptoBackend implementation
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public set globalErrorOnUnknownDevices(_v: boolean) {
// Not implemented for rust crypto.
}
public get globalErrorOnUnknownDevices(): boolean {
// Not implemented for rust crypto.
return false;
}
public stop(): void {
// stop() may be called multiple times, but attempting to close() the OlmMachine twice
// will cause an error.
if (this.stopped) {
return;
}
this.stopped = true;
this.keyClaimManager.stop();
this.backupManager.stop();
this.outgoingRequestsManager.stop();
this.perSessionBackupDownloader.stop();
this.dehydratedDeviceManager.stop();
// make sure we close() the OlmMachine; doing so means that all the Rust objects will be
// cleaned up; in particular, the indexeddb connections will be closed, which means they
// can then be deleted.
this.olmMachine.close();
}
public async encryptEvent(event: MatrixEvent, _room: Room): Promise<void> {
const roomId = event.getRoomId()!;
const encryptor = this.roomEncryptors[roomId];
if (!encryptor) {
throw new Error(`Cannot encrypt event in unconfigured room ${roomId}`);
}
await encryptor.encryptEvent(event, this.globalBlacklistUnverifiedDevices, this.deviceIsolationMode);
}
public async decryptEvent(event: MatrixEvent): Promise<IEventDecryptionResult> {
const roomId = event.getRoomId();
if (!roomId) {
// presumably, a to-device message. These are normally decrypted in preprocessToDeviceMessages
// so the fact it has come back here suggests that decryption failed.
//
// once we drop support for the libolm crypto implementation, we can stop passing to-device messages
// through decryptEvent and hence get rid of this case.
throw new Error("to-device event was not decrypted in preprocessToDeviceMessages");
}
return await this.eventDecryptor.attemptEventDecryption(event, this.deviceIsolationMode);
}
/**
* Implementation of (deprecated) {@link MatrixClient#getEventEncryptionInfo}.
*
* @param event - event to inspect
*/
public getEventEncryptionInfo(event: MatrixEvent): IEncryptedEventInfo {
const ret: Partial<IEncryptedEventInfo> = {};
ret.senderKey = event.getSenderKey() ?? undefined;
ret.algorithm = event.getWireContent().algorithm;
if (!ret.senderKey || !ret.algorithm) {
ret.encrypted = false;
return ret as IEncryptedEventInfo;
}
ret.encrypted = true;
ret.authenticated = true;
ret.mismatchedSender = true;
return ret as IEncryptedEventInfo;
}
/**
* Implementation of {@link CryptoBackend#checkUserTrust}.
*
* Stub for backwards compatibility.
*
*/
public checkUserTrust(userId: string): UserVerificationStatus {
return new UserVerificationStatus(false, false, false);
}
/**
* Get the cross signing information for a given user.
*
* The cross-signing API is currently UNSTABLE and may change without notice.
*
* @param userId - the user ID to get the cross-signing info for.
*
* @returns the cross signing information for the user.
*/
public getStoredCrossSigningForUser(userId: string): null {
// TODO
return null;
}
/**
* This function is unneeded for the rust-crypto.
* The cross signing key import and the device verification are done in {@link CryptoApi#bootstrapCrossSigning}
*
* The function is stub to keep the compatibility with the old crypto.
* More information: https://github.com/vector-im/element-web/issues/25648
*
* Implementation of {@link CryptoBackend#checkOwnCrossSigningTrust}
*/
public async checkOwnCrossSigningTrust(): Promise<void> {
return;
}
/**
* Implementation of {@link CryptoBackend#getBackupDecryptor}.
*/
public async getBackupDecryptor(backupInfo: KeyBackupInfo, privKey: ArrayLike<number>): Promise<BackupDecryptor> {
if (!(privKey instanceof Uint8Array)) {
throw new Error(`getBackupDecryptor: expects Uint8Array`);
}
if (backupInfo.algorithm != "m.megolm_backup.v1.curve25519-aes-sha2") {
throw new Error(`getBackupDecryptor: Unsupported algorithm ${backupInfo.algorithm}`);
}
const backupDecryptionKey = RustSdkCryptoJs.BackupDecryptionKey.fromBase64(encodeBase64(privKey));
if (!decryptionKeyMatchesKeyBackupInfo(backupDecryptionKey, backupInfo)) {
throw new Error(`getBackupDecryptor: key backup on server does not match the decryption key`);
}
return this.backupManager.createBackupDecryptor(backupDecryptionKey);
}
/**
* Implementation of {@link CryptoBackend#importBackedUpRoomKeys}.
*/
public async importBackedUpRoomKeys(
keys: IMegolmSessionData[],
backupVersion: string,
opts?: ImportRoomKeysOpts,
): Promise<void> {
return await this.backupManager.importBackedUpRoomKeys(keys, backupVersion, opts);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// CryptoApi implementation
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public globalBlacklistUnverifiedDevices = false;
/**
* Implementation of {@link CryptoApi#getVersion}.
*/
public getVersion(): string {
const versions = RustSdkCryptoJs.getVersions();
return `Rust SDK ${versions.matrix_sdk_crypto} (${versions.git_sha}), Vodozemac ${versions.vodozemac}`;
}
/**
* Implementation of {@link CryptoApi#setDeviceIsolationMode}.
*/
public setDeviceIsolationMode(isolationMode: DeviceIsolationMode): void {
this.deviceIsolationMode = isolationMode;
}
/**
* Implementation of {@link CryptoApi#isEncryptionEnabledInRoom}.
*/
public async isEncryptionEnabledInRoom(roomId: string): Promise<boolean> {
const roomSettings: RustSdkCryptoJs.RoomSettings | undefined = await this.olmMachine.getRoomSettings(
new RustSdkCryptoJs.RoomId(roomId),
);
return Boolean(roomSettings?.algorithm);
}
/**
* Implementation of {@link CryptoApi#getOwnDeviceKeys}.
*/
public async getOwnDeviceKeys(): Promise<OwnDeviceKeys> {
const keys = this.olmMachine.identityKeys;
return { ed25519: keys.ed25519.toBase64(), curve25519: keys.curve25519.toBase64() };
}
public prepareToEncrypt(room: Room): void {
const encryptor = this.roomEncryptors[room.roomId];
if (encryptor) {
encryptor.prepareForEncryption(this.globalBlacklistUnverifiedDevices, this.deviceIsolationMode);
}
}
public forceDiscardSession(roomId: string): Promise<void> {
return this.roomEncryptors[roomId]?.forceDiscardSession();
}
public async exportRoomKeys(): Promise<IMegolmSessionData[]> {
const raw = await this.olmMachine.exportRoomKeys(() => true);
return JSON.parse(raw);
}
public async exportRoomKeysAsJson(): Promise<string> {
return await this.olmMachine.exportRoomKeys(() => true);
}
public async importRoomKeys(keys: IMegolmSessionData[], opts?: ImportRoomKeysOpts): Promise<void> {
return await this.backupManager.importRoomKeys(keys, opts);
}
public async importRoomKeysAsJson(keys: string, opts?: ImportRoomKeysOpts): Promise<void> {
return await this.backupManager.importRoomKeysAsJson(keys, opts);
}
/**
* Implementation of {@link CryptoApi.userHasCrossSigningKeys}.
*/
public async userHasCrossSigningKeys(userId = this.userId, downloadUncached = false): Promise<boolean> {
// TODO: could probably do with a more efficient way of doing this than returning the whole set and searching
const rustTrackedUsers: Set<RustSdkCryptoJs.UserId> = await this.olmMachine.trackedUsers();
let rustTrackedUser: RustSdkCryptoJs.UserId | undefined;
for (const u of rustTrackedUsers) {
if (userId === u.toString()) {
rustTrackedUser = u;
break;
}
}
if (rustTrackedUser !== undefined) {
if (userId === this.userId) {
/* make sure we have an *up-to-date* idea of the user's cross-signing keys. This is important, because if we
* return "false" here, we will end up generating new cross-signing keys and replacing the existing ones.
*/
const request = this.olmMachine.queryKeysForUsers(
// clone as rust layer will take ownership and it's reused later
[rustTrackedUser.clone()],
);
await this.outgoingRequestProcessor.makeOutgoingRequest(request);
}
const userIdentity = await this.olmMachine.getIdentity(rustTrackedUser);
userIdentity?.free();
return userIdentity !== undefined;
} else if (downloadUncached) {
// Download the cross signing keys and check if the master key is available
const keyResult = await this.downloadDeviceList(new Set([userId]));
const keys = keyResult.master_keys?.[userId];
// No master key
if (!keys) return false;
// `keys` is an object with { [`ed25519:${pubKey}`]: pubKey }
// We assume only a single key, and we want the bare form without type
// prefix, so we select the values.
return Boolean(Object.values(keys.keys)[0]);
} else {
return false;
}
}
/**
* Get the device information for the given list of users.
*
* @param userIds - The users to fetch.
* @param downloadUncached - If true, download the device list for users whose device list we are not
* currently tracking. Defaults to false, in which case such users will not appear at all in the result map.
*
* @returns A map `{@link DeviceMap}`.
*/
public async getUserDeviceInfo(userIds: string[], downloadUncached = false): Promise<DeviceMap> {
const deviceMapByUserId = new Map<string, Map<string, Device>>();
const rustTrackedUsers: Set<RustSdkCryptoJs.UserId> = await this.getOlmMachineOrThrow().trackedUsers();
// Convert RustSdkCryptoJs.UserId to a `Set<string>`
const trackedUsers = new Set<string>();
rustTrackedUsers.forEach((rustUserId) => trackedUsers.add(rustUserId.toString()));
// Keep untracked user to download their keys after
const untrackedUsers: Set<string> = new Set();
for (const userId of userIds) {
// if this is a tracked user, we can just fetch the device list from the rust-sdk
// (NB: this is probably ok even if we race with a leave event such that we stop tracking the user's
// devices: the rust-sdk will return the last-known device list, which will be good enough.)
if (trackedUsers.has(userId)) {
deviceMapByUserId.set(userId, await this.getUserDevices(userId));
} else {
untrackedUsers.add(userId);
}
}
// for any users whose device lists we are not tracking, fall back to downloading the device list
// over HTTP.
if (downloadUncached && untrackedUsers.size >= 1) {
const queryResult = await this.downloadDeviceList(untrackedUsers);
Object.entries(queryResult.device_keys).forEach(([userId, deviceKeys]) =>
deviceMapByUserId.set(userId, deviceKeysToDeviceMap(deviceKeys)),
);
}
return deviceMapByUserId;
}
/**
* Get the device list for the given user from the olm machine
* @param userId - Rust SDK UserId
*/
private async getUserDevices(userId: string): Promise<Map<string, Device>> {
const rustUserId = new RustSdkCryptoJs.UserId(userId);
// For reasons I don't really understand, the Javascript FinalizationRegistry doesn't seem to run the
// registered callbacks when `userDevices` goes out of scope, nor when the individual devices in the array
// returned by `userDevices.devices` do so.
//
// This is particularly problematic, because each of those structures holds a reference to the
// VerificationMachine, which in turn holds a reference to the IndexeddbCryptoStore. Hence, we end up leaking
// open connections to the crypto store, which means the store can't be deleted on logout.
//
// To fix this, we explicitly call `.free` on each of the objects, which tells the rust code to drop the
// allocated memory and decrement the refcounts for the crypto store.
// Wait for up to a second for any in-flight device list requests to complete.
// The reason for this isn't so much to avoid races (some level of raciness is
// inevitable for this method) but to make testing easier.
const userDevices: RustSdkCryptoJs.UserDevices = await this.olmMachine.getUserDevices(rustUserId, 1);
try {
const deviceArray: RustSdkCryptoJs.Device[] = userDevices.devices();
try {
return new Map(
deviceArray.map((device) => [device.deviceId.toString(), rustDeviceToJsDevice(device, rustUserId)]),
);
} finally {
deviceArray.forEach((d) => d.free());
}
} finally {
userDevices.free();
}
}
/**
* Download the given user keys by calling `/keys/query` request
* @param untrackedUsers - download keys of these users
*/
private async downloadDeviceList(untrackedUsers: Set<string>): Promise<IDownloadKeyResult> {
const queryBody: IQueryKeysRequest = { device_keys: {} };
untrackedUsers.forEach((user) => (queryBody.device_keys[user] = []));
return await this.http.authedRequest(Method.Post, "/_matrix/client/v3/keys/query", undefined, queryBody, {
prefix: "",
});
}
/**
* Implementation of {@link CryptoApi#getTrustCrossSignedDevices}.
*/
public getTrustCrossSignedDevices(): boolean {
return this._trustCrossSignedDevices;
}
/**
* Implementation of {@link CryptoApi#setTrustCrossSignedDevices}.
*/
public setTrustCrossSignedDevices(val: boolean): void {
this._trustCrossSignedDevices = val;
// TODO: legacy crypto goes through the list of known devices and emits DeviceVerificationChanged
// events. Maybe we need to do the same?
}
/**
* Mark the given device as locally verified.
*
* Implementation of {@link CryptoApi#setDeviceVerified}.
*/
public async setDeviceVerified(userId: string, deviceId: string, verified = true): Promise<void> {
const device: RustSdkCryptoJs.Device | undefined = await this.olmMachine.getDevice(
new RustSdkCryptoJs.UserId(userId),
new RustSdkCryptoJs.DeviceId(deviceId),
);
if (!device) {
throw new Error(`Unknown device ${userId}|${deviceId}`);
}
try {
await device.setLocalTrust(
verified ? RustSdkCryptoJs.LocalTrust.Verified : RustSdkCryptoJs.LocalTrust.Unset,
);
} finally {
device.free();
}
}
/**
* Blindly cross-sign one of our other devices.
*
* Implementation of {@link CryptoApi#crossSignDevice}.
*/
public async crossSignDevice(deviceId: string): Promise<void> {
const device: RustSdkCryptoJs.Device | undefined = await this.olmMachine.getDevice(
new RustSdkCryptoJs.UserId(this.userId),
new RustSdkCryptoJs.DeviceId(deviceId),
);
if (!device) {
throw new Error(`Unknown device ${deviceId}`);
}
try {
const outgoingRequest: RustSdkCryptoJs.SignatureUploadRequest = await device.verify();
await this.outgoingRequestProcessor.makeOutgoingRequest(outgoingRequest);
} finally {
device.free();
}
}
/**
* Implementation of {@link CryptoApi#getDeviceVerificationStatus}.
*/
public async getDeviceVerificationStatus(
userId: string,
deviceId: string,
): Promise<DeviceVerificationStatus | null> {
const device: RustSdkCryptoJs.Device | undefined = await this.olmMachine.getDevice(
new RustSdkCryptoJs.UserId(userId),
new RustSdkCryptoJs.DeviceId(deviceId),
);
if (!device) return null;
try {
return new DeviceVerificationStatus({
signedByOwner: device.isCrossSignedByOwner(),
crossSigningVerified: device.isCrossSigningTrusted(),
localVerified: device.isLocallyTrusted(),
trustCrossSignedDevices: this._trustCrossSignedDevices,
});
} finally {
device.free();
}
}
/**
* Implementation of {@link CryptoApi#getUserVerificationStatus}.
*/
public async getUserVerificationStatus(userId: string): Promise<UserVerificationStatus> {
const userIdentity: RustSdkCryptoJs.UserIdentity | RustSdkCryptoJs.OwnUserIdentity | undefined =
await this.getOlmMachineOrThrow().getIdentity(new RustSdkCryptoJs.UserId(userId));
if (userIdentity === undefined) {
return new UserVerificationStatus(false, false, false);
}
const verified = userIdentity.isVerified();
const wasVerified = userIdentity.wasPreviouslyVerified();
const needsUserApproval =
userIdentity instanceof RustSdkCryptoJs.UserIdentity ? userIdentity.identityNeedsUserApproval() : false;
userIdentity.free();
return new UserVerificationStatus(verified, wasVerified, false, needsUserApproval);
}
/**
* Implementation of {@link CryptoApi#pinCurrentUserIdentity}.
*/
public async pinCurrentUserIdentity(userId: string): Promise<void> {
const userIdentity: RustSdkCryptoJs.UserIdentity | RustSdkCryptoJs.OwnUserIdentity | undefined =
await this.getOlmMachineOrThrow().getIdentity(new RustSdkCryptoJs.UserId(userId));
if (userIdentity === undefined) {
throw new Error("Cannot pin identity of unknown user");
}
if (userIdentity instanceof RustSdkCryptoJs.OwnUserIdentity) {
throw new Error("Cannot pin identity of own user");
}
await userIdentity.pinCurrentMasterKey();
}
/**
* Implementation of {@link CryptoApi#isCrossSigningReady}
*/
public async isCrossSigningReady(): Promise<boolean> {
const { privateKeysInSecretStorage, privateKeysCachedLocally } = await this.getCrossSigningStatus();
const hasKeysInCache =
Boolean(privateKeysCachedLocally.masterKey) &&
Boolean(privateKeysCachedLocally.selfSigningKey) &&
Boolean(privateKeysCachedLocally.userSigningKey);
const identity = await this.getOwnIdentity();
// Cross-signing is ready if the public identity is trusted, and the private keys
// are either cached, or accessible via secret-storage.
return !!identity?.isVerified() && (hasKeysInCache || privateKeysInSecretStorage);
}
/**
* Implementation of {@link CryptoApi#getCrossSigningKeyId}
*/
public async getCrossSigningKeyId(type: CrossSigningKey = CrossSigningKey.Master): Promise<string | null> {
const userIdentity: RustSdkCryptoJs.OwnUserIdentity | undefined = await this.olmMachine.getIdentity(
new RustSdkCryptoJs.UserId(this.userId),
);
if (!userIdentity) {
// The public keys are not available on this device
return null;
}
try {
const crossSigningStatus: RustSdkCryptoJs.CrossSigningStatus = await this.olmMachine.crossSigningStatus();
const privateKeysOnDevice =
crossSigningStatus.hasMaster && crossSigningStatus.hasUserSigning && crossSigningStatus.hasSelfSigning;
if (!privateKeysOnDevice) {
// The private keys are not available on this device
return null;
}
if (!userIdentity.isVerified()) {
// We have both public and private keys, but they don't match!
return null;
}
let key: string;
switch (type) {
case CrossSigningKey.Master:
key = userIdentity.masterKey;
break;
case CrossSigningKey.SelfSigning:
key = userIdentity.selfSigningKey;
break;
case CrossSigningKey.UserSigning:
key = userIdentity.userSigningKey;
break;
default:
// Unknown type
return null;
}
const parsedKey: CrossSigningKeyInfo = JSON.parse(key);
// `keys` is an object with { [`ed25519:${pubKey}`]: pubKey }
// We assume only a single key, and we want the bare form without type
// prefix, so we select the values.
return Object.values(parsedKey.keys)[0];
} finally {
userIdentity.free();
}
}
/**
* Implementation of {@link CryptoApi#bootstrapCrossSigning}
*/
public async bootstrapCrossSigning(opts: BootstrapCrossSigningOpts): Promise<void> {
await this.crossSigningIdentity.bootstrapCrossSigning(opts);
}
/**
* Implementation of {@link CryptoApi#isSecretStorageReady}
*/
public async isSecretStorageReady(): Promise<boolean> {
// make sure that the cross-signing keys are stored
const secretsToCheck = [
"m.cross_signing.master",
"m.cross_signing.user_signing",
"m.cross_signing.self_signing",
];
// if key backup is active, we also need to check that the backup decryption key is stored
const keyBackupEnabled = (await this.backupManager.getActiveBackupVersion()) != null;
if (keyBackupEnabled) {
secretsToCheck.push("m.megolm_backup.v1");
}
return secretStorageCanAccessSecrets(this.secretStorage, secretsToCheck);
}
/**
* Implementation of {@link CryptoApi#bootstrapSecretStorage}
*/
public async bootstrapSecretStorage({
createSecretStorageKey,
setupNewSecretStorage,
setupNewKeyBackup,
}: CreateSecretStorageOpts = {}): Promise<void> {
// If an AES Key is already stored in the secret storage and setupNewSecretStorage is not set
// we don't want to create a new key
const isNewSecretStorageKeyNeeded = setupNewSecretStorage || !(await this.secretStorageHasAESKey());
if (isNewSecretStorageKeyNeeded) {
if (!createSecretStorageKey) {
throw new Error("unable to create a new secret storage key, createSecretStorageKey is not set");
}
// Create a new storage key and add it to secret storage
this.logger.info("bootstrapSecretStorage: creating new secret storage key");
const recoveryKey = await createSecretStorageKey();
if (!recoveryKey) {
throw new Error("createSecretStorageKey() callback did not return a secret storage key");
}
await this.addSecretStorageKeyToSecretStorage(recoveryKey);
}
const crossSigningStatus: RustSdkCryptoJs.CrossSigningStatus = await this.olmMachine.crossSigningStatus();
const hasPrivateKeys =
crossSigningStatus.hasMaster && crossSigningStatus.hasSelfSigning && crossSigningStatus.hasUserSigning;
// If we have cross-signing private keys cached, store them in secret
// storage if they are not there already.
if (
hasPrivateKeys &&
(isNewSecretStorageKeyNeeded || !(await secretStorageContainsCrossSigningKeys(this.secretStorage)))
) {
this.logger.info("bootstrapSecretStorage: cross-signing keys not yet exported; doing so now.");
const crossSigningPrivateKeys: RustSdkCryptoJs.CrossSigningKeyExport =
await this.olmMachine.exportCrossSigningKeys();
if (!crossSigningPrivateKeys.masterKey) {
throw new Error("missing master key in cross signing private keys");
}
if (!crossSigningPrivateKeys.userSigningKey) {
throw new Error("missing user signing key in cross signing private keys");
}
if (!crossSigningPrivateKeys.self_signing_key) {
throw new Error("missing self signing key in cross signing private keys");
}
await this.secretStorage.store("m.cross_signing.master", crossSigningPrivateKeys.masterKey);
await this.secretStorage.store("m.cross_signing.user_signing", crossSigningPrivateKeys.userSigningKey);
await this.secretStorage.store("m.cross_signing.self_signing", crossSigningPrivateKeys.self_signing_key);
}
if (setupNewKeyBackup) {
await this.resetKeyBackup();
}
}
/**
* Add the secretStorage key to the secret storage
* - The secret storage key must have the `keyInfo` field filled
* - The secret storage key is set as the default key of the secret storage
* - Call `cryptoCallbacks.cacheSecretStorageKey` when done
*
* @param secretStorageKey - The secret storage key to add in the secret storage.
*/
private async addSecretStorageKeyToSecretStorage(secretStorageKey: GeneratedSecretStorageKey): Promise<void> {
const secretStorageKeyObject = await this.secretStorage.addKey(SECRET_STORAGE_ALGORITHM_V1_AES, {
passphrase: secretStorageKey.keyInfo?.passphrase,
name: secretStorageKey.keyInfo?.name,
key: secretStorageKey.privateKey,
});
await this.secretStorage.setDefaultKeyId(secretStorageKeyObject.keyId);
this.cryptoCallbacks.cacheSecretStorageKey?.(
secretStorageKeyObject.keyId,
secretStorageKeyObject.keyInfo,
secretStorageKey.privateKey,
);
}
/**
* Check if a secret storage AES Key is already added in secret storage
*
* @returns True if an AES key is in the secret storage
*/
private async secretStorageHasAESKey(): Promise<boolean> {
// See if we already have an AES secret-storage key.
const secretStorageKeyTuple = await this.secretStorage.getKey();
if (!secretStorageKeyTuple) return false;
const [, keyInfo] = secretStorageKeyTuple;
// Check if the key is an AES key
return keyInfo.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES;
}
/**
* Implementation of {@link CryptoApi#getCrossSigningStatus}
*/
public async getCrossSigningStatus(): Promise<CrossSigningStatus> {
const userIdentity: RustSdkCryptoJs.OwnUserIdentity | null = await this.getOlmMachineOrThrow().getIdentity(
new RustSdkCryptoJs.UserId(this.userId),
);
const publicKeysOnDevice =
Boolean(userIdentity?.masterKey) &&
Boolean(userIdentity?.selfSigningKey) &&
Boolean(userIdentity?.userSigningKey);
userIdentity?.free();
const privateKeysInSecretStorage = await secretStorageContainsCrossSigningKeys(this.secretStorage);
const crossSigningStatus: RustSdkCryptoJs.CrossSigningStatus | null =
await this.getOlmMachineOrThrow().crossSigningStatus();
return {
publicKeysOnDevice,
privateKeysInSecretStorage,
privateKeysCachedLocally: {
masterKey: Boolean(crossSigningStatus?.hasMaster),
userSigningKey: Boolean(crossSigningStatus?.hasUserSigning),
selfSigningKey: Boolean(crossSigningStatus?.hasSelfSigning),
},
};
}
/**
* Implementation of {@link CryptoApi#createRecoveryKeyFromPassphrase}
*/
public async createRecoveryKeyFromPassphrase(password?: string): Promise<GeneratedSecretStorageKey> {
if (password) {
// Generate the key from the passphrase
// first we generate a random salt
const salt = randomString(32);
// then we derive the key from the passphrase
const recoveryKey = await deriveRecoveryKeyFromPassphrase(
password,
salt,
this.RECOVERY_KEY_DERIVATION_ITERATIONS,
);
return {
keyInfo: {
passphrase: {
algorithm: "m.pbkdf2",
iterations: this.RECOVERY_KEY_DERIVATION_ITERATIONS,
salt,
},
},
privateKey: recoveryKey,
encodedPrivateKey: encodeRecoveryKey(recoveryKey),
};
} else {
// Using the navigator crypto API to generate the private key
const key = new Uint8Array(32);
globalThis.crypto.getRandomValues(key);
return {
privateKey: key,
encodedPrivateKey: encodeRecoveryKey(key),
};
}
}
/**
* Implementation of {@link CryptoApi#getEncryptionInfoForEvent}.
*/
public async getEncryptionInfoForEvent(event: MatrixEvent): Promise<EventEncryptionInfo | null> {
return this.eventDecryptor.getEncryptionInfoForEvent(event);
}
/**
* Returns to-device verification requests that are already in progress for the given user id.
*
* Implementation of {@link CryptoApi#getVerificationRequestsToDeviceInProgress}
*
* @param userId - the ID of the user to query
*
* @returns the VerificationRequests that are in progress
*/
public getVerificationRequestsToDeviceInProgress(userId: string): VerificationRequest[] {
const requests: RustSdkCryptoJs.VerificationRequest[] = this.olmMachine.getVerificationRequests(
new RustSdkCryptoJs.UserId(userId),
);
return requests
.filter((request) => request.roomId === undefined)
.map(
(request) =>
new RustVerificationRequest(
this.olmMachine,
request,
this.outgoingRequestProcessor,
this._supportedVerificationMethods,
),
);
}
/**
* Finds a DM verification request that is already in progress for the given room id
*
* Implementation of {@link CryptoApi#findVerificationRequestDMInProgress}
*
* @param roomId - the room to use for verification
* @param userId - search the verification request for the given user
*
* @returns the VerificationRequest that is in progress, if any
*
*/
public findVerificationRequestDMInProgress(roomId: string, userId?: string): VerificationRequest | undefined {
if (!userId) throw new Error("missing userId");