-
-
Notifications
You must be signed in to change notification settings - Fork 577
/
index.ts
3912 lines (3529 loc) · 160 KB
/
index.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 2016 OpenMarket Ltd
Copyright 2017 Vector Creations Ltd
Copyright 2018-2019 New Vector Ltd
Copyright 2019-2021 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 { v4 as uuidv4 } from "uuid";
import type { IDeviceKeys, IEventDecryptionResult, IMegolmSessionData, IOneTimeKey } from "../@types/crypto";
import type { PkDecryption, PkSigning } from "@matrix-org/olm";
import { EventType, ToDeviceMessageId } from "../@types/event";
import { TypedReEmitter } from "../ReEmitter";
import { logger } from "../logger";
import { IExportedDevice, OlmDevice } from "./OlmDevice";
import { IOlmDevice } from "./algorithms/megolm";
import * as olmlib from "./olmlib";
import { DeviceInfoMap, DeviceList } from "./DeviceList";
import { DeviceInfo, IDevice } from "./deviceinfo";
import type { DecryptionAlgorithm, EncryptionAlgorithm } from "./algorithms";
import * as algorithms from "./algorithms";
import { createCryptoStoreCacheCallbacks, CrossSigningInfo, DeviceTrustLevel, UserTrustLevel } from "./CrossSigning";
import { EncryptionSetupBuilder } from "./EncryptionSetup";
import {
IAccountDataClient,
ISecretRequest,
SECRET_STORAGE_ALGORITHM_V1_AES,
SecretStorage,
SecretStorageKeyObject,
SecretStorageKeyTuple,
} from "./SecretStorage";
import {
IAddSecretStorageKeyOpts,
ICreateSecretStorageOpts,
IEncryptedEventInfo,
IImportRoomKeysOpts,
IRecoveryKey,
ISecretStorageKeyInfo,
} from "./api";
import { OutgoingRoomKeyRequestManager } from "./OutgoingRoomKeyRequestManager";
import { IndexedDBCryptoStore } from "./store/indexeddb-crypto-store";
import { VerificationBase } from "./verification/Base";
import { ReciprocateQRCode, SCAN_QR_CODE_METHOD, SHOW_QR_CODE_METHOD } from "./verification/QRCode";
import { SAS as SASVerification } from "./verification/SAS";
import { keyFromPassphrase } from "./key_passphrase";
import { decodeRecoveryKey, encodeRecoveryKey } from "./recoverykey";
import { VerificationRequest } from "./verification/request/VerificationRequest";
import { InRoomChannel, InRoomRequests } from "./verification/request/InRoomChannel";
import { ToDeviceChannel, ToDeviceRequests, Request } from "./verification/request/ToDeviceChannel";
import { IllegalMethod } from "./verification/IllegalMethod";
import { KeySignatureUploadError } from "../errors";
import { calculateKeyCheck, decryptAES, encryptAES } from "./aes";
import { DehydrationManager } from "./dehydration";
import { BackupManager } from "./backup";
import { IStore } from "../store";
import { Room, RoomEvent } from "../models/room";
import { RoomMember, RoomMemberEvent } from "../models/room-member";
import { EventStatus, IEvent, MatrixEvent, MatrixEventEvent } from "../models/event";
import { ToDeviceBatch } from "../models/ToDeviceMessage";
import {
ClientEvent,
ICrossSigningKey,
IKeysUploadResponse,
ISignedKey,
IUploadKeySignaturesResponse,
MatrixClient,
} from "../client";
import type { IRoomEncryption, RoomList } from "./RoomList";
import { IKeyBackupInfo } from "./keybackup";
import { ISyncStateData } from "../sync";
import { CryptoStore } from "./store/base";
import { IVerificationChannel } from "./verification/request/Channel";
import { TypedEventEmitter } from "../models/typed-event-emitter";
import { IContent } from "../models/event";
import { ISyncResponse, IToDeviceEvent } from "../sync-accumulator";
import { ISignatures } from "../@types/signed";
import { IMessage } from "./algorithms/olm";
import { CryptoBackend, OnSyncCompletedData } from "../common-crypto/CryptoBackend";
import { RoomState, RoomStateEvent } from "../models/room-state";
const DeviceVerification = DeviceInfo.DeviceVerification;
const defaultVerificationMethods = {
[ReciprocateQRCode.NAME]: ReciprocateQRCode,
[SASVerification.NAME]: SASVerification,
// These two can't be used for actual verification, but we do
// need to be able to define them here for the verification flows
// to start.
[SHOW_QR_CODE_METHOD]: IllegalMethod,
[SCAN_QR_CODE_METHOD]: IllegalMethod,
} as const;
/**
* verification method names
*/
// legacy export identifier
export const verificationMethods = {
RECIPROCATE_QR_CODE: ReciprocateQRCode.NAME,
SAS: SASVerification.NAME,
} as const;
export type VerificationMethod = keyof typeof verificationMethods | string;
export function isCryptoAvailable(): boolean {
return Boolean(global.Olm);
}
const MIN_FORCE_SESSION_INTERVAL_MS = 60 * 60 * 1000;
interface IInitOpts {
exportedOlmDevice?: IExportedDevice;
pickleKey?: string;
}
export interface IBootstrapCrossSigningOpts {
/** Optional. Reset even if keys already exist. */
setupNewCrossSigning?: boolean;
/**
* A function that makes the request requiring auth. Receives the auth data as an object.
* Can be called multiple times, first with an empty authDict, to obtain the flows.
*/
authUploadDeviceSigningKeys?(makeRequest: (authData: any) => Promise<{}>): Promise<void>;
}
export interface ICryptoCallbacks {
getCrossSigningKey?: (keyType: string, pubKey: string) => Promise<Uint8Array | null>;
saveCrossSigningKeys?: (keys: Record<string, Uint8Array>) => void;
shouldUpgradeDeviceVerifications?: (users: Record<string, any>) => Promise<string[]>;
getSecretStorageKey?: (
keys: { keys: Record<string, ISecretStorageKeyInfo> },
name: string,
) => Promise<[string, Uint8Array] | null>;
cacheSecretStorageKey?: (keyId: string, keyInfo: ISecretStorageKeyInfo, key: Uint8Array) => void;
onSecretRequested?: (
userId: string,
deviceId: string,
requestId: string,
secretName: string,
deviceTrust: DeviceTrustLevel,
) => Promise<string | undefined>;
getDehydrationKey?: (keyInfo: ISecretStorageKeyInfo, checkFunc: (key: Uint8Array) => void) => Promise<Uint8Array>;
getBackupKey?: () => Promise<Uint8Array>;
}
/* eslint-disable camelcase */
interface IRoomKey {
room_id: string;
algorithm: string;
}
/**
* The parameters of a room key request. The details of the request may
* vary with the crypto algorithm, but the management and storage layers for
* outgoing requests expect it to have 'room_id' and 'session_id' properties.
*/
export interface IRoomKeyRequestBody extends IRoomKey {
session_id: string;
sender_key: string;
}
/* eslint-enable camelcase */
interface IDeviceVerificationUpgrade {
devices: DeviceInfo[];
crossSigningInfo: CrossSigningInfo;
}
export interface ICheckOwnCrossSigningTrustOpts {
allowPrivateKeyRequests?: boolean;
}
interface IUserOlmSession {
deviceIdKey: string;
sessions: {
sessionId: string;
hasReceivedMessage: boolean;
}[];
}
export interface IRoomKeyRequestRecipient {
userId: string;
deviceId: string;
}
interface ISignableObject {
signatures?: ISignatures;
unsigned?: object;
}
export interface IRequestsMap {
getRequest(event: MatrixEvent): VerificationRequest | undefined;
getRequestByChannel(channel: IVerificationChannel): VerificationRequest | undefined;
setRequest(event: MatrixEvent, request: VerificationRequest): void;
setRequestByChannel(channel: IVerificationChannel, request: VerificationRequest): void;
}
/* eslint-disable camelcase */
export interface IOlmEncryptedContent {
algorithm: typeof olmlib.OLM_ALGORITHM;
sender_key: string;
ciphertext: Record<string, IMessage>;
[ToDeviceMessageId]?: string;
}
export interface IMegolmEncryptedContent {
algorithm: typeof olmlib.MEGOLM_ALGORITHM;
sender_key: string;
session_id: string;
device_id: string;
ciphertext: string;
[ToDeviceMessageId]?: string;
}
/* eslint-enable camelcase */
export type IEncryptedContent = IOlmEncryptedContent | IMegolmEncryptedContent;
export enum CryptoEvent {
DeviceVerificationChanged = "deviceVerificationChanged",
UserTrustStatusChanged = "userTrustStatusChanged",
UserCrossSigningUpdated = "userCrossSigningUpdated",
RoomKeyRequest = "crypto.roomKeyRequest",
RoomKeyRequestCancellation = "crypto.roomKeyRequestCancellation",
KeyBackupStatus = "crypto.keyBackupStatus",
KeyBackupFailed = "crypto.keyBackupFailed",
KeyBackupSessionsRemaining = "crypto.keyBackupSessionsRemaining",
KeySignatureUploadFailure = "crypto.keySignatureUploadFailure",
VerificationRequest = "crypto.verification.request",
Warning = "crypto.warning",
WillUpdateDevices = "crypto.willUpdateDevices",
DevicesUpdated = "crypto.devicesUpdated",
KeysChanged = "crossSigning.keysChanged",
}
export type CryptoEventHandlerMap = {
/**
* Fires when a device is marked as verified/unverified/blocked/unblocked by
* {@link MatrixClient#setDeviceVerified|MatrixClient.setDeviceVerified} or
* {@link MatrixClient#setDeviceBlocked|MatrixClient.setDeviceBlocked}.
*
* @param userId - the owner of the verified device
* @param deviceId - the id of the verified device
* @param deviceInfo - updated device information
*/
[CryptoEvent.DeviceVerificationChanged]: (userId: string, deviceId: string, device: DeviceInfo) => void;
/**
* Fires when the trust status of a user changes
* If userId is the userId of the logged-in user, this indicated a change
* in the trust status of the cross-signing data on the account.
*
* The cross-signing API is currently UNSTABLE and may change without notice.
* @experimental
*
* @param userId - the userId of the user in question
* @param trustLevel - The new trust level of the user
*/
[CryptoEvent.UserTrustStatusChanged]: (userId: string, trustLevel: UserTrustLevel) => void;
/**
* Fires when we receive a room key request
*
* @param req - request details
*/
[CryptoEvent.RoomKeyRequest]: (request: IncomingRoomKeyRequest) => void;
/**
* Fires when we receive a room key request cancellation
*/
[CryptoEvent.RoomKeyRequestCancellation]: (request: IncomingRoomKeyRequestCancellation) => void;
/**
* Fires whenever the status of e2e key backup changes, as returned by getKeyBackupEnabled()
* @param enabled - true if key backup has been enabled, otherwise false
* @example
* ```
* matrixClient.on("crypto.keyBackupStatus", function(enabled){
* if (enabled) {
* [...]
* }
* });
* ```
*/
[CryptoEvent.KeyBackupStatus]: (enabled: boolean) => void;
[CryptoEvent.KeyBackupFailed]: (errcode: string) => void;
[CryptoEvent.KeyBackupSessionsRemaining]: (remaining: number) => void;
[CryptoEvent.KeySignatureUploadFailure]: (
failures: IUploadKeySignaturesResponse["failures"],
source: "checkOwnCrossSigningTrust" | "afterCrossSigningLocalKeyChange" | "setDeviceVerification",
upload: (opts: { shouldEmit: boolean }) => Promise<void>,
) => void;
/**
* Fires when a key verification is requested.
*/
[CryptoEvent.VerificationRequest]: (request: VerificationRequest<any>) => void;
/**
* Fires when the app may wish to warn the user about something related
* the end-to-end crypto.
*
* @param type - One of the strings listed above
*/
[CryptoEvent.Warning]: (type: string) => void;
/**
* Fires when the user's cross-signing keys have changed or cross-signing
* has been enabled/disabled. The client can use getStoredCrossSigningForUser
* with the user ID of the logged in user to check if cross-signing is
* enabled on the account. If enabled, it can test whether the current key
* is trusted using with checkUserTrust with the user ID of the logged
* in user. The checkOwnCrossSigningTrust function may be used to reconcile
* the trust in the account key.
*
* The cross-signing API is currently UNSTABLE and may change without notice.
* @experimental
*/
[CryptoEvent.KeysChanged]: (data: {}) => void;
/**
* Fires whenever the stored devices for a user will be updated
* @param users - A list of user IDs that will be updated
* @param initialFetch - If true, the store is empty (apart
* from our own device) and is being seeded.
*/
[CryptoEvent.WillUpdateDevices]: (users: string[], initialFetch: boolean) => void;
/**
* Fires whenever the stored devices for a user have changed
* @param users - A list of user IDs that were updated
* @param initialFetch - If true, the store was empty (apart
* from our own device) and has been seeded.
*/
[CryptoEvent.DevicesUpdated]: (users: string[], initialFetch: boolean) => void;
[CryptoEvent.UserCrossSigningUpdated]: (userId: string) => void;
};
export class Crypto extends TypedEventEmitter<CryptoEvent, CryptoEventHandlerMap> implements CryptoBackend {
/**
* @returns The version of Olm.
*/
public static getOlmVersion(): [number, number, number] {
return OlmDevice.getOlmVersion();
}
public readonly backupManager: BackupManager;
public readonly crossSigningInfo: CrossSigningInfo;
public readonly olmDevice: OlmDevice;
public readonly deviceList: DeviceList;
public readonly dehydrationManager: DehydrationManager;
public readonly secretStorage: SecretStorage;
private readonly reEmitter: TypedReEmitter<CryptoEvent, CryptoEventHandlerMap>;
private readonly verificationMethods: Map<VerificationMethod, typeof VerificationBase>;
public readonly supportedAlgorithms: string[];
private readonly outgoingRoomKeyRequestManager: OutgoingRoomKeyRequestManager;
private readonly toDeviceVerificationRequests: ToDeviceRequests;
public readonly inRoomVerificationRequests: InRoomRequests;
private trustCrossSignedDevices = true;
// the last time we did a check for the number of one-time-keys on the server.
private lastOneTimeKeyCheck: number | null = null;
private oneTimeKeyCheckInProgress = false;
// EncryptionAlgorithm instance for each room
private roomEncryptors = new Map<string, EncryptionAlgorithm>();
// map from algorithm to DecryptionAlgorithm instance, for each room
private roomDecryptors = new Map<string, Map<string, DecryptionAlgorithm>>();
private deviceKeys: Record<string, string> = {}; // type: key
public globalBlacklistUnverifiedDevices = false;
public globalErrorOnUnknownDevices = true;
// list of IncomingRoomKeyRequests/IncomingRoomKeyRequestCancellations
// we received in the current sync.
private receivedRoomKeyRequests: IncomingRoomKeyRequest[] = [];
private receivedRoomKeyRequestCancellations: IncomingRoomKeyRequestCancellation[] = [];
// true if we are currently processing received room key requests
private processingRoomKeyRequests = false;
// controls whether device tracking is delayed
// until calling encryptEvent or trackRoomDevices,
// or done immediately upon enabling room encryption.
private lazyLoadMembers = false;
// in case lazyLoadMembers is true,
// track if an initial tracking of all the room members
// has happened for a given room. This is delayed
// to avoid loading room members as long as possible.
private roomDeviceTrackingState: { [roomId: string]: Promise<void> } = {};
// The timestamp of the last time we forced establishment
// of a new session for each device, in milliseconds.
// {
// userId: {
// deviceId: 1234567890000,
// },
// }
private lastNewSessionForced: Record<string, Record<string, number>> = {};
// This flag will be unset whilst the client processes a sync response
// so that we don't start requesting keys until we've actually finished
// processing the response.
private sendKeyRequestsImmediately = false;
private oneTimeKeyCount?: number;
private needsNewFallback?: boolean;
private fallbackCleanup?: ReturnType<typeof setTimeout>;
/**
* Cryptography bits
*
* This module is internal to the js-sdk; the public API is via MatrixClient.
*
* @internal
*
* @param baseApis - base matrix api interface
*
* @param userId - The user ID for the local user
*
* @param deviceId - The identifier for this device.
*
* @param clientStore - the MatrixClient data store.
*
* @param cryptoStore - storage for the crypto layer.
*
* @param roomList - An initialised RoomList object
*
* @param verificationMethods - Array of verification methods to use.
* Each element can either be a string from MatrixClient.verificationMethods
* or a class that implements a verification method.
*/
public constructor(
public readonly baseApis: MatrixClient,
public readonly userId: string,
private readonly deviceId: string,
private readonly clientStore: IStore,
public readonly cryptoStore: CryptoStore,
private readonly roomList: RoomList,
verificationMethods: Array<VerificationMethod | (typeof VerificationBase & { NAME: string })>,
) {
super();
this.reEmitter = new TypedReEmitter(this);
if (verificationMethods) {
this.verificationMethods = new Map();
for (const method of verificationMethods) {
if (typeof method === "string") {
if (defaultVerificationMethods[method]) {
this.verificationMethods.set(
method,
<typeof VerificationBase>defaultVerificationMethods[method],
);
}
} else if (method["NAME"]) {
this.verificationMethods.set(method["NAME"], method as typeof VerificationBase);
} else {
logger.warn(`Excluding unknown verification method ${method}`);
}
}
} else {
this.verificationMethods = new Map(Object.entries(defaultVerificationMethods)) as Map<
VerificationMethod,
typeof VerificationBase
>;
}
this.backupManager = new BackupManager(baseApis, async () => {
// try to get key from cache
const cachedKey = await this.getSessionBackupPrivateKey();
if (cachedKey) {
return cachedKey;
}
// try to get key from secret storage
const storedKey = await this.getSecret("m.megolm_backup.v1");
if (storedKey) {
// ensure that the key is in the right format. If not, fix the key and
// store the fixed version
const fixedKey = fixBackupKey(storedKey);
if (fixedKey) {
const keys = await this.getSecretStorageKey();
await this.storeSecret("m.megolm_backup.v1", fixedKey, [keys![0]]);
}
return olmlib.decodeBase64(fixedKey || storedKey);
}
// try to get key from app
if (this.baseApis.cryptoCallbacks && this.baseApis.cryptoCallbacks.getBackupKey) {
return this.baseApis.cryptoCallbacks.getBackupKey();
}
throw new Error("Unable to get private key");
});
this.olmDevice = new OlmDevice(cryptoStore);
this.deviceList = new DeviceList(baseApis, cryptoStore, this.olmDevice);
// XXX: This isn't removed at any point, but then none of the event listeners
// this class sets seem to be removed at any point... :/
this.deviceList.on(CryptoEvent.UserCrossSigningUpdated, this.onDeviceListUserCrossSigningUpdated);
this.reEmitter.reEmit(this.deviceList, [CryptoEvent.DevicesUpdated, CryptoEvent.WillUpdateDevices]);
this.supportedAlgorithms = Array.from(algorithms.DECRYPTION_CLASSES.keys());
this.outgoingRoomKeyRequestManager = new OutgoingRoomKeyRequestManager(
baseApis,
this.deviceId,
this.cryptoStore,
);
this.toDeviceVerificationRequests = new ToDeviceRequests();
this.inRoomVerificationRequests = new InRoomRequests();
const cryptoCallbacks = this.baseApis.cryptoCallbacks || {};
const cacheCallbacks = createCryptoStoreCacheCallbacks(cryptoStore, this.olmDevice);
this.crossSigningInfo = new CrossSigningInfo(userId, cryptoCallbacks, cacheCallbacks);
// Yes, we pass the client twice here: see SecretStorage
this.secretStorage = new SecretStorage(baseApis as IAccountDataClient, cryptoCallbacks, baseApis);
this.dehydrationManager = new DehydrationManager(this);
// Assuming no app-supplied callback, default to getting from SSSS.
if (!cryptoCallbacks.getCrossSigningKey && cryptoCallbacks.getSecretStorageKey) {
cryptoCallbacks.getCrossSigningKey = async (type): Promise<Uint8Array | null> => {
return CrossSigningInfo.getFromSecretStorage(type, this.secretStorage);
};
}
}
/**
* Initialise the crypto module so that it is ready for use
*
* Returns a promise which resolves once the crypto module is ready for use.
*
* @param exportedOlmDevice - (Optional) data from exported device
* that must be re-created.
*/
public async init({ exportedOlmDevice, pickleKey }: IInitOpts = {}): Promise<void> {
logger.log("Crypto: initialising Olm...");
await global.Olm.init();
logger.log(
exportedOlmDevice
? "Crypto: initialising Olm device from exported device..."
: "Crypto: initialising Olm device...",
);
await this.olmDevice.init({ fromExportedDevice: exportedOlmDevice, pickleKey });
logger.log("Crypto: loading device list...");
await this.deviceList.load();
// build our device keys: these will later be uploaded
this.deviceKeys["ed25519:" + this.deviceId] = this.olmDevice.deviceEd25519Key!;
this.deviceKeys["curve25519:" + this.deviceId] = this.olmDevice.deviceCurve25519Key!;
logger.log("Crypto: fetching own devices...");
let myDevices = this.deviceList.getRawStoredDevicesForUser(this.userId);
if (!myDevices) {
myDevices = {};
}
if (!myDevices[this.deviceId]) {
// add our own deviceinfo to the cryptoStore
logger.log("Crypto: adding this device to the store...");
const deviceInfo = {
keys: this.deviceKeys,
algorithms: this.supportedAlgorithms,
verified: DeviceVerification.VERIFIED,
known: true,
};
myDevices[this.deviceId] = deviceInfo;
this.deviceList.storeDevicesForUser(this.userId, myDevices);
this.deviceList.saveIfDirty();
}
await this.cryptoStore.doTxn("readonly", [IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {
this.cryptoStore.getCrossSigningKeys(txn, (keys) => {
// can be an empty object after resetting cross-signing keys, see storeTrustedSelfKeys
if (keys && Object.keys(keys).length !== 0) {
logger.log("Loaded cross-signing public keys from crypto store");
this.crossSigningInfo.setKeys(keys);
}
});
});
// make sure we are keeping track of our own devices
// (this is important for key backups & things)
this.deviceList.startTrackingDeviceList(this.userId);
logger.log("Crypto: checking for key backup...");
this.backupManager.checkAndStart();
}
/**
* Whether to trust a others users signatures of their devices.
* If false, devices will only be considered 'verified' if we have
* verified that device individually (effectively disabling cross-signing).
*
* Default: true
*
* @returns True if trusting cross-signed devices
*/
public getCryptoTrustCrossSignedDevices(): boolean {
return this.trustCrossSignedDevices;
}
/**
* See getCryptoTrustCrossSignedDevices
* This may be set before initCrypto() is called to ensure no races occur.
*
* @param val - True to trust cross-signed devices
*/
public setCryptoTrustCrossSignedDevices(val: boolean): void {
this.trustCrossSignedDevices = val;
for (const userId of this.deviceList.getKnownUserIds()) {
const devices = this.deviceList.getRawStoredDevicesForUser(userId);
for (const deviceId of Object.keys(devices)) {
const deviceTrust = this.checkDeviceTrust(userId, deviceId);
// If the device is locally verified then isVerified() is always true,
// so this will only have caused the value to change if the device is
// cross-signing verified but not locally verified
if (!deviceTrust.isLocallyVerified() && deviceTrust.isCrossSigningVerified()) {
const deviceObj = this.deviceList.getStoredDevice(userId, deviceId)!;
this.emit(CryptoEvent.DeviceVerificationChanged, userId, deviceId, deviceObj);
}
}
}
}
/**
* Create a recovery key from a user-supplied passphrase.
*
* @param password - Passphrase string that can be entered by the user
* when restoring the backup as an alternative to entering the recovery key.
* Optional.
* @returns Object with public key metadata, encoded private
* recovery key which should be disposed of after displaying to the user,
* and raw private key to avoid round tripping if needed.
*/
public async createRecoveryKeyFromPassphrase(password?: string): Promise<IRecoveryKey> {
const decryption = new global.Olm.PkDecryption();
try {
const keyInfo: Partial<IRecoveryKey["keyInfo"]> = {};
if (password) {
const derivation = await keyFromPassphrase(password);
keyInfo.passphrase = {
algorithm: "m.pbkdf2",
iterations: derivation.iterations,
salt: derivation.salt,
};
keyInfo.pubkey = decryption.init_with_private_key(derivation.key);
} else {
keyInfo.pubkey = decryption.generate_key();
}
const privateKey = decryption.get_private_key();
const encodedPrivateKey = encodeRecoveryKey(privateKey);
return {
keyInfo: keyInfo as IRecoveryKey["keyInfo"],
encodedPrivateKey,
privateKey,
};
} finally {
decryption?.free();
}
}
/**
* Checks if the user has previously published cross-signing keys
*
* This means downloading the devicelist for the user and checking if the list includes
* the cross-signing pseudo-device.
*
* @internal
*/
public async userHasCrossSigningKeys(): Promise<boolean> {
await this.downloadKeys([this.userId]);
return this.deviceList.getStoredCrossSigningForUser(this.userId) !== null;
}
/**
* Checks whether cross signing:
* - is enabled on this account and trusted by this device
* - has private keys either cached locally or stored in secret storage
*
* If this function returns false, bootstrapCrossSigning() can be used
* to fix things such that it returns true. That is to say, after
* bootstrapCrossSigning() completes successfully, this function should
* return true.
*
* The cross-signing API is currently UNSTABLE and may change without notice.
*
* @returns True if cross-signing is ready to be used on this device
*/
public async isCrossSigningReady(): Promise<boolean> {
const publicKeysOnDevice = this.crossSigningInfo.getId();
const privateKeysExistSomewhere =
(await this.crossSigningInfo.isStoredInKeyCache()) ||
(await this.crossSigningInfo.isStoredInSecretStorage(this.secretStorage));
return !!(publicKeysOnDevice && privateKeysExistSomewhere);
}
/**
* Checks whether secret storage:
* - is enabled on this account
* - is storing cross-signing private keys
* - is storing session backup key (if enabled)
*
* If this function returns false, bootstrapSecretStorage() can be used
* to fix things such that it returns true. That is to say, after
* bootstrapSecretStorage() completes successfully, this function should
* return true.
*
* The Secure Secret Storage API is currently UNSTABLE and may change without notice.
*
* @returns True if secret storage is ready to be used on this device
*/
public async isSecretStorageReady(): Promise<boolean> {
const secretStorageKeyInAccount = await this.secretStorage.hasKey();
const privateKeysInStorage = await this.crossSigningInfo.isStoredInSecretStorage(this.secretStorage);
const sessionBackupInStorage =
!this.backupManager.getKeyBackupEnabled() || (await this.baseApis.isKeyBackupKeyStored());
return !!(secretStorageKeyInAccount && privateKeysInStorage && sessionBackupInStorage);
}
/**
* Bootstrap cross-signing by creating keys if needed. If everything is already
* set up, then no changes are made, so this is safe to run to ensure
* cross-signing is ready for use.
*
* This function:
* - creates new cross-signing keys if they are not found locally cached nor in
* secret storage (if it has been setup)
*
* The cross-signing API is currently UNSTABLE and may change without notice.
*
* @param authUploadDeviceSigningKeys - Function
* called to await an interactive auth flow when uploading device signing keys.
* @param setupNewCrossSigning - Optional. Reset even if keys
* already exist.
* Args:
* A function that makes the request requiring auth. Receives the
* auth data as an object. Can be called multiple times, first with an empty
* authDict, to obtain the flows.
*/
public async bootstrapCrossSigning({
authUploadDeviceSigningKeys,
setupNewCrossSigning,
}: IBootstrapCrossSigningOpts = {}): Promise<void> {
logger.log("Bootstrapping cross-signing");
const delegateCryptoCallbacks = this.baseApis.cryptoCallbacks;
const builder = new EncryptionSetupBuilder(this.baseApis.store.accountData, delegateCryptoCallbacks);
const crossSigningInfo = new CrossSigningInfo(
this.userId,
builder.crossSigningCallbacks,
builder.crossSigningCallbacks,
);
// Reset the cross-signing keys
const resetCrossSigning = async (): Promise<void> => {
crossSigningInfo.resetKeys();
// Sign master key with device key
await this.signObject(crossSigningInfo.keys.master);
// Store auth flow helper function, as we need to call it when uploading
// to ensure we handle auth errors properly.
builder.addCrossSigningKeys(authUploadDeviceSigningKeys, crossSigningInfo.keys);
// Cross-sign own device
const device = this.deviceList.getStoredDevice(this.userId, this.deviceId)!;
const deviceSignature = await crossSigningInfo.signDevice(this.userId, device);
builder.addKeySignature(this.userId, this.deviceId, deviceSignature!);
// Sign message key backup with cross-signing master key
if (this.backupManager.backupInfo) {
await crossSigningInfo.signObject(this.backupManager.backupInfo.auth_data, "master");
builder.addSessionBackup(this.backupManager.backupInfo);
}
};
const publicKeysOnDevice = this.crossSigningInfo.getId();
const privateKeysInCache = await this.crossSigningInfo.isStoredInKeyCache();
const privateKeysInStorage = await this.crossSigningInfo.isStoredInSecretStorage(this.secretStorage);
const privateKeysExistSomewhere = privateKeysInCache || privateKeysInStorage;
// Log all relevant state for easier parsing of debug logs.
logger.log({
setupNewCrossSigning,
publicKeysOnDevice,
privateKeysInCache,
privateKeysInStorage,
privateKeysExistSomewhere,
});
if (!privateKeysExistSomewhere || setupNewCrossSigning) {
logger.log("Cross-signing private keys not found locally or in secret storage, " + "creating new keys");
// If a user has multiple devices, it important to only call bootstrap
// as part of some UI flow (and not silently during startup), as they
// may have setup cross-signing on a platform which has not saved keys
// to secret storage, and this would reset them. In such a case, you
// should prompt the user to verify any existing devices first (and
// request private keys from those devices) before calling bootstrap.
await resetCrossSigning();
} else if (publicKeysOnDevice && privateKeysInCache) {
logger.log("Cross-signing public keys trusted and private keys found locally");
} else if (privateKeysInStorage) {
logger.log(
"Cross-signing private keys not found locally, but they are available " +
"in secret storage, reading storage and caching locally",
);
await this.checkOwnCrossSigningTrust({
allowPrivateKeyRequests: true,
});
}
// Assuming no app-supplied callback, default to storing new private keys in
// secret storage if it exists. If it does not, it is assumed this will be
// done as part of setting up secret storage later.
const crossSigningPrivateKeys = builder.crossSigningCallbacks.privateKeys;
if (crossSigningPrivateKeys.size && !this.baseApis.cryptoCallbacks.saveCrossSigningKeys) {
const secretStorage = new SecretStorage(
builder.accountDataClientAdapter,
builder.ssssCryptoCallbacks,
undefined,
);
if (await secretStorage.hasKey()) {
logger.log("Storing new cross-signing private keys in secret storage");
// This is writing to in-memory account data in
// builder.accountDataClientAdapter so won't fail
await CrossSigningInfo.storeInSecretStorage(crossSigningPrivateKeys, secretStorage);
}
}
const operation = builder.buildOperation();
await operation.apply(this);
// This persists private keys and public keys as trusted,
// only do this if apply succeeded for now as retry isn't in place yet
await builder.persist(this);
logger.log("Cross-signing ready");
}
/**
* Bootstrap Secure Secret Storage if needed by creating a default key. If everything is
* already set up, then no changes are made, so this is safe to run to ensure secret
* storage is ready for use.
*
* This function
* - creates a new Secure Secret Storage key if no default key exists
* - if a key backup exists, it is migrated to store the key in the Secret
* Storage
* - creates a backup if none exists, and one is requested
* - migrates Secure Secret Storage to use the latest algorithm, if an outdated
* algorithm is found
*
* The Secure Secret Storage API is currently UNSTABLE and may change without notice.
*
* @param createSecretStorageKey - Optional. Function
* called to await a secret storage key creation flow.
* Returns a Promise which resolves to an object with public key metadata, encoded private
* recovery key which should be disposed of after displaying to the user,
* and raw private key to avoid round tripping if needed.
* @param keyBackupInfo - The current key backup object. If passed,
* the passphrase and recovery key from this backup will be used.
* @param setupNewKeyBackup - If true, a new key backup version will be
* created and the private key stored in the new SSSS store. Ignored if keyBackupInfo
* is supplied.
* @param setupNewSecretStorage - Optional. Reset even if keys already exist.
* @param getKeyBackupPassphrase - Optional. Function called to get the user's
* current key backup passphrase. Should return a promise that resolves with a Buffer
* containing the key, or rejects if the key cannot be obtained.
* Returns:
* A promise which resolves to key creation data for
* SecretStorage#addKey: an object with `passphrase` etc fields.
*/
// TODO this does not resolve with what it says it does
public async bootstrapSecretStorage({
createSecretStorageKey = async (): Promise<IRecoveryKey> => ({} as IRecoveryKey),
keyBackupInfo,
setupNewKeyBackup,
setupNewSecretStorage,
getKeyBackupPassphrase,
}: ICreateSecretStorageOpts = {}): Promise<void> {
logger.log("Bootstrapping Secure Secret Storage");
const delegateCryptoCallbacks = this.baseApis.cryptoCallbacks;
const builder = new EncryptionSetupBuilder(this.baseApis.store.accountData, delegateCryptoCallbacks);
const secretStorage = new SecretStorage(
builder.accountDataClientAdapter,
builder.ssssCryptoCallbacks,
undefined,
);
// the ID of the new SSSS key, if we create one
let newKeyId: string | null = null;
// create a new SSSS key and set it as default
const createSSSS = async (opts: IAddSecretStorageKeyOpts, privateKey?: Uint8Array): Promise<string> => {
if (privateKey) {
opts.key = privateKey;
}
const { keyId, keyInfo } = await secretStorage.addKey(SECRET_STORAGE_ALGORITHM_V1_AES, opts);
if (privateKey) {
// make the private key available to encrypt 4S secrets
builder.ssssCryptoCallbacks.addPrivateKey(keyId, keyInfo, privateKey);
}
await secretStorage.setDefaultKeyId(keyId);
return keyId;
};
const ensureCanCheckPassphrase = async (keyId: string, keyInfo: ISecretStorageKeyInfo): Promise<void> => {
if (!keyInfo.mac) {
const key = await this.baseApis.cryptoCallbacks.getSecretStorageKey?.(
{ keys: { [keyId]: keyInfo } },
"",
);
if (key) {
const privateKey = key[1];
builder.ssssCryptoCallbacks.addPrivateKey(keyId, keyInfo, privateKey);
const { iv, mac } = await calculateKeyCheck(privateKey);
keyInfo.iv = iv;
keyInfo.mac = mac;
await builder.setAccountData(`m.secret_storage.key.${keyId}`, keyInfo);
}
}
};
const signKeyBackupWithCrossSigning = async (keyBackupAuthData: IKeyBackupInfo["auth_data"]): Promise<void> => {
if (this.crossSigningInfo.getId() && (await this.crossSigningInfo.isStoredInKeyCache("master"))) {
try {
logger.log("Adding cross-signing signature to key backup");
await this.crossSigningInfo.signObject(keyBackupAuthData, "master");
} catch (e) {
// This step is not critical (just helpful), so we catch here
// and continue if it fails.
logger.error("Signing key backup with cross-signing keys failed", e);
}
} else {
logger.warn("Cross-signing keys not available, skipping signature on key backup");
}
};
const oldSSSSKey = await this.getSecretStorageKey();
const [oldKeyId, oldKeyInfo] = oldSSSSKey || [null, null];
const storageExists =
!setupNewSecretStorage && oldKeyInfo && oldKeyInfo.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES;
// Log all relevant state for easier parsing of debug logs.
logger.log({
keyBackupInfo,
setupNewKeyBackup,
setupNewSecretStorage,
storageExists,
oldKeyInfo,
});
if (!storageExists && !keyBackupInfo) {
// either we don't have anything, or we've been asked to restart
// from scratch
logger.log("Secret storage does not exist, creating new storage key");
// if we already have a usable default SSSS key and aren't resetting
// SSSS just use it. otherwise, create a new one
// Note: we leave the old SSSS key in place: there could be other
// secrets using it, in theory. We could move them to the new key but a)
// that would mean we'd need to prompt for the old passphrase, and b)
// it's not clear that would be the right thing to do anyway.
const { keyInfo = {} as IAddSecretStorageKeyOpts, privateKey } = await createSecretStorageKey();
newKeyId = await createSSSS(keyInfo, privateKey);
} else if (!storageExists && keyBackupInfo) {
// we have an existing backup, but no SSSS
logger.log("Secret storage does not exist, using key backup key");
// if we have the backup key already cached, use it; otherwise use the
// callback to prompt for the key
const backupKey = (await this.getSessionBackupPrivateKey()) || (await getKeyBackupPassphrase?.());
// create a new SSSS key and use the backup key as the new SSSS key
const opts = {} as IAddSecretStorageKeyOpts;
if (keyBackupInfo.auth_data.private_key_salt && keyBackupInfo.auth_data.private_key_iterations) {
// FIXME: ???
opts.passphrase = {
algorithm: "m.pbkdf2",
iterations: keyBackupInfo.auth_data.private_key_iterations,
salt: keyBackupInfo.auth_data.private_key_salt,
bits: 256,
};