UNPKG

matrix-js-sdk

Version:
1,214 lines (1,080 loc) 152 kB
/* 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. */ /** * @module crypto */ import anotherjson from "another-json"; import { EventEmitter } from 'events'; import { ReEmitter } from '../ReEmitter'; import { logger } from '../logger'; import { IExportedDevice, OlmDevice } from "./OlmDevice"; import * as olmlib from "./olmlib"; import { DeviceInfoMap, DeviceList } from "./DeviceList"; import { DeviceInfo, IDevice } from "./deviceinfo"; import * as algorithms from "./algorithms"; import { createCryptoStoreCacheCallbacks, CrossSigningInfo, DeviceTrustLevel, UserTrustLevel } from './CrossSigning'; import { EncryptionSetupBuilder } from "./EncryptionSetup"; import { SECRET_STORAGE_ALGORITHM_V1_AES, SecretStorage, SecretStorageKeyTuple, ISecretRequest, SecretStorageKeyObject, } from './SecretStorage'; import { IAddSecretStorageKeyOpts, IImportRoomKeysOpts, ISecretStorageKeyInfo } from "./api"; import { OutgoingRoomKeyRequestManager } from './OutgoingRoomKeyRequestManager'; import { IndexedDBCryptoStore } from './store/indexeddb-crypto-store'; 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 } from "./verification/request/ToDeviceChannel"; import { IllegalMethod } from "./verification/IllegalMethod"; import { KeySignatureUploadError } from "../errors"; import { decryptAES, encryptAES, calculateKeyCheck } from './aes'; import { DehydrationManager, IDeviceKeys, IOneTimeKey } from './dehydration'; import { BackupManager } from "./backup"; import { IStore } from "../store"; import { Room } from "../models/room"; import { RoomMember } from "../models/room-member"; import { MatrixEvent, EventStatus } from "../models/event"; import { MatrixClient, IKeysUploadResponse, SessionStore, ISignedKey } from "../client"; import type { EncryptionAlgorithm, DecryptionAlgorithm } from "./algorithms/base"; import type { IRoomEncryption, RoomList } from "./RoomList"; import { IRecoveryKey, IEncryptedEventInfo } from "./api"; import { IKeyBackupInfo } from "./keybackup"; import { ISyncStateData } from "../sync"; import { CryptoStore } from "./store/base"; import { IVerificationChannel } from "./verification/request/Channel"; 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, }; /** * verification method names */ // legacy export identifier export const verificationMethods = { RECIPROCATE_QR_CODE: ReciprocateQRCode.NAME, SAS: SASVerification.NAME, }; 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 { setupNewCrossSigning?: boolean; authUploadDeviceSigningKeys?(makeRequest: (authData: any) => {}): Promise<void>; } interface IBootstrapSecretStorageOpts { keyBackupInfo?: any; // TODO types setupNewKeyBackup?: boolean; setupNewSecretStorage?: boolean; createSecretStorageKey?(): Promise<{ keyInfo?: any; // TODO types privateKey?: Uint8Array; }>; getKeyBackupPassphrase?(): Promise<Uint8Array | null>; } /* eslint-disable camelcase */ interface IRoomKey { room_id: string; algorithm: string; } export interface IRoomKeyRequestBody extends IRoomKey { session_id: string; sender_key: string; } export interface IMegolmSessionData { [key: string]: any; // extensible sender_key: string; forwarding_curve25519_key_chain: string[]; sender_claimed_keys: Record<string, string>; room_id: string; session_id: string; session_key: string; algorithm?: string; untrusted?: boolean; } /* eslint-enable camelcase */ interface IDeviceVerificationUpgrade { devices: DeviceInfo[]; crossSigningInfo: CrossSigningInfo; } export interface ICheckOwnCrossSigningTrustOpts { allowPrivateKeyRequests?: boolean; } /** * @typedef {Object} module:crypto~OlmSessionResult * @property {module:crypto/deviceinfo} device device info * @property {string?} sessionId base64 olm session id; null if no session * could be established */ interface IUserOlmSession { deviceIdKey: string; sessions: { sessionId: string; hasReceivedMessage: boolean; }[]; } interface ISyncDeviceLists { changed: string[]; left: string[]; } export interface IRoomKeyRequestRecipient { userId: string; deviceId: string; } interface ISignableObject { signatures?: object; unsigned?: object; } export interface IEventDecryptionResult { clearEvent: object; senderCurve25519Key?: string; claimedEd25519Key?: string; forwardingCurve25519KeyChain?: string[]; untrusted?: boolean; } export class Crypto extends EventEmitter { /** * @return {string} The version of Olm. */ 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: ReEmitter; private readonly verificationMethods: any; // TODO types 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; private oneTimeKeyCheckInProgress = false; // EncryptionAlgorithm instance for each room private roomEncryptors: Record<string, EncryptionAlgorithm> = {}; // map from algorithm to DecryptionAlgorithm instance, for each room private roomDecryptors: Record<string, Record<string, DecryptionAlgorithm>> = {}; private deviceKeys: Record<string, string> = {}; // type: key private globalBlacklistUnverifiedDevices = false; private 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: Record<string, Promise<void>> = {}; // roomId: 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; /** * Cryptography bits * * This module is internal to the js-sdk; the public API is via MatrixClient. * * @constructor * @alias module:crypto * * @internal * * @param {MatrixClient} baseApis base matrix api interface * * @param {module:store/session/webstorage~WebStorageSessionStore} sessionStore * Store to be used for end-to-end crypto session data * * @param {string} userId The user ID for the local user * * @param {string} deviceId The identifier for this device. * * @param {Object} clientStore the MatrixClient data store. * * @param {module:crypto/store/base~CryptoStore} cryptoStore * storage for the crypto layer. * * @param {RoomList} roomList An initialised RoomList object * * @param {Array} 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. */ constructor( public readonly baseApis: MatrixClient, public readonly sessionStore: SessionStore, public readonly userId: string, private readonly deviceId: string, private readonly clientStore: IStore, public readonly cryptoStore: CryptoStore, private readonly roomList: RoomList, verificationMethods: any[], // TODO types ) { super(); this.reEmitter = new ReEmitter(this); if (verificationMethods) { this.verificationMethods = new Map(); for (const method of verificationMethods) { if (typeof method === "string") { if (defaultVerificationMethods[method]) { this.verificationMethods.set( method, defaultVerificationMethods[method], ); } } else if (method.NAME) { this.verificationMethods.set( method.NAME, method, ); } else { logger.warn(`Excluding unknown verification method ${method}`); } } } else { this.verificationMethods = defaultVerificationMethods; } 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 [keyId] = await this.getSecretStorageKey(); await this.storeSecret("m.megolm_backup.v1", fixedKey, [keyId]); } return olmlib.decodeBase64(fixedKey || storedKey); } // try to get key from app if (this.baseApis.cryptoCallbacks && this.baseApis.cryptoCallbacks.getBackupKey) { return await 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('userCrossSigningUpdated', this.onDeviceListUserCrossSigningUpdated); this.reEmitter.reEmit(this.deviceList, ["crypto.devicesUpdated", "crypto.willUpdateDevices"]); this.supportedAlgorithms = Object.keys(algorithms.DECRYPTION_CLASSES); 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, 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) => { 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 {Object} opts keyword arguments. * @param {string} opts.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 * * @return {boolean} 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 {boolean} 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("deviceVerificationChanged", userId, deviceId, deviceObj); } } } } /** * Create a recovery key from a user-supplied passphrase. * * @param {string} password Passphrase string that can be entered by the user * when restoring the backup as an alternative to entering the recovery key. * Optional. * @returns {Promise<Object>} 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 { if (decryption) decryption.free(); } } /** * 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. * * @return {boolean} 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. * * @return {boolean} 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 {function} opts.authUploadDeviceSigningKeys Function * called to await an interactive auth flow when uploading device signing keys. * @param {boolean} [opts.setupNewCrossSigning] Optional. Reset even if keys * already exist. * Args: * {function} 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 () => { 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) as ISignedKey; 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); 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 {function} [opts.createSecretStorageKey] Optional. Function * called to await a secret storage key creation flow. * Returns: * {Promise<Object>} 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 {object} [opts.keyBackupInfo] The current key backup object. If passed, * the passphrase and recovery key from this backup will be used. * @param {boolean} [opts.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 {boolean} [opts.setupNewSecretStorage] Optional. Reset even if keys already exist. * @param {func} [opts.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: * {Promise} 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 () => ({ }), keyBackupInfo, setupNewKeyBackup, setupNewSecretStorage, getKeyBackupPassphrase, }: IBootstrapSecretStorageOpts = {}) { 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, ); // the ID of the new SSSS key, if we create one let newKeyId = null; // create a new SSSS key and set it as default const createSSSS = async (opts, privateKey: Uint8Array) => { opts = opts || {}; 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, keyInfo) => { 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) => { 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, 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: any = {}; // TODO types 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, }; } newKeyId = await createSSSS(opts, backupKey); // store the backup key in secret storage await secretStorage.store( "m.megolm_backup.v1", olmlib.encodeBase64(backupKey), [newKeyId], ); // The backup is trusted because the user provided the private key. // Sign the backup with the cross-signing key so the key backup can // be trusted via cross-signing. await signKeyBackupWithCrossSigning(keyBackupInfo.auth_data); builder.addSessionBackup(keyBackupInfo); } else { // 4S is already set up logger.log("Secret storage exists"); if (oldKeyInfo && oldKeyInfo.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) { // make sure that the default key has the information needed to // check the passphrase await ensureCanCheckPassphrase(oldKeyId, oldKeyInfo); } } // If we have cross-signing private keys cached, store them in secret // storage if they are not there already. if ( !this.baseApis.cryptoCallbacks.saveCrossSigningKeys && await this.isCrossSigningReady() && (newKeyId || !await this.crossSigningInfo.isStoredInSecretStorage(secretStorage)) ) { logger.log("Copying cross-signing private keys from cache to secret storage"); const crossSigningPrivateKeys = await this.crossSigningInfo.getCrossSigningKeysFromCache(); // This is writing to in-memory account data in // builder.accountDataClientAdapter so won't fail await CrossSigningInfo.storeInSecretStorage(crossSigningPrivateKeys, secretStorage); } if (setupNewKeyBackup && !keyBackupInfo) { logger.log("Creating new message key backup version"); const info = await this.baseApis.prepareKeyBackupVersion( null /* random key */, // don't write to secret storage, as it will write to this.secretStorage. // Here, we want to capture all the side-effects of bootstrapping, // and want to write to the local secretStorage object { secureSecretStorage: false }, ); // write the key ourselves to 4S const privateKey = decodeRecoveryKey(info.recovery_key); await secretStorage.store("m.megolm_backup.v1", olmlib.encodeBase64(privateKey)); // create keyBackupInfo object to add to builder const data: IKeyBackupInfo = { algorithm: info.algorithm, auth_data: info.auth_data, }; // Sign with cross-signing master key await signKeyBackupWithCrossSigning(data.auth_data); // sign with the device fingerprint await this.signObject(data.auth_data); builder.addSessionBackup(data); } // Cache the session backup key const sessionBackupKey = await secretStorage.get('m.megolm_backup.v1'); if (sessionBackupKey) { logger.info("Got session backup key from secret storage: caching"); // fix up the backup key if it's in the wrong format, and replace // in secret storage const fixedBackupKey = fixBackupKey(sessionBackupKey); if (fixedBackupKey) { await secretStorage.store("m.megolm_backup.v1", fixedBackupKey, [newKeyId || oldKeyId], ); } const decodedBackupKey = new Uint8Array(olmlib.decodeBase64( fixedBackupKey || sessionBackupKey, )); await builder.addSessionBackupPrivateKeyToCache(decodedBackupKey); } else if (this.backupManager.getKeyBackupEnabled()) { // key backup is enabled but we don't have a session backup key in SSSS: see if we have one in // the cache or the user can provide one, and if so, write it to SSSS const backupKey = await this.getSessionBackupPrivateKey() || await getKeyBackupPassphrase(); if (!backupKey) { // This will require user intervention to recover from since we don't have the key // backup key anywhere. The user should probably just set up a new key backup and // the key for the new backup will be stored. If we hit this scenario in the wild // with any frequency, we should do more than just log an error. logger.error("Key backup is enabled but couldn't get key backup key!"); return; } logger.info("Got session backup key from cache/user that wasn't in SSSS: saving to SSSS"); await secretStorage.store("m.megolm_backup.v1", olmlib.encodeBase64(backupKey)); } 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("Secure Secret Storage ready"); } public addSecretStorageKey( algorithm: string, opts: IAddSecretStorageKeyOpts, keyID: string, ): Promise<SecretStorageKeyObject> { return this.secretStorage.addKey(algorithm, opts, keyID); } public hasSecretStorageKey(keyID: string): Promise<boolean> { return this.secretStorage.hasKey(keyID); } public getSecretStorageKey(keyID?: string): Promise<SecretStorageKeyTuple> { return this.secretStorage.getKey(keyID); } public storeSecret(name: string, secret: string, keys?: string[]): Promise<void> { return this.secretStorage.store(name, secret, keys); } public getSecret(name: string): Promise<string> { return this.secretStorage.get(name); } public isSecretStored( name: string, checkKey?: boolean, ): Promise<Record<string, ISecretStorageKeyInfo>> { return this.secretStorage.isStored(name, checkKey); } public requestSecret(name: string, devices: string[]): ISecretRequest { if (!devices) { devices = Object.keys(this.deviceList.getRawStoredDevicesForUser(this.userId)); } return this.secretStorage.request(name, devices); } public getDefaultSecretStorageKeyId(): Promise<string> { return this.secretStorage.getDefaultKeyId(); } public setDefaultSecretStorageKeyId(k: string): Promise<void> { return this.secretStorage.setDefaultKeyId(k); } public checkSecretStorageKey(key: Uint8Array, info: ISecretStorageKeyInfo): Promise<boolean> { return this.secretStorage.checkKey(key, info); } /** * Checks that a given secret storage private key matches a given public key. * This can be used by the getSecretStorageKey callback to verify that the * private key it is about to supply is the one that was requested. * * @param {Uint8Array} privateKey The private key * @param {string} expectedPublicKey The public key * @returns {boolean} true if the key matches, otherwise false */ public checkSecretStoragePrivateKey(privateKey: Uint8Array, expectedPublicKey: string): boolean { let decryption = null; try { decryption = new global.Olm.PkDecryption(); const gotPubkey = decryption.init_with_private_key(privateKey); // make sure it agrees with the given pubkey return gotPubkey === expectedPublicKey; } finally { if (decryption) decryption.free(); } } /** * Fetches the backup private key, if cached * @returns {Promise} the key, if any, or null */ public async getSessionBackupPrivateKey(): Promise<Uint8Array | null> { let key = await new Promise<any>((resolve) => { // TODO types this.cryptoStore.doTxn( 'readonly', [IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => { this.cryptoStore.getSecretStorePrivateKey( txn, resolve, "m.megolm_backup.v1", ); }, ); }); // make sure we have a Uint8Array, rather than a string if (key && typeof key === "string") { key = new Uint8Array(olmlib.decodeBase64(fixBackupKey(key) || key)); await this.storeSessionBackupPrivateKey(key); } if (key && key.ciphertext) { const pickleKey = Buffer.from(this.olmDevice.pickleKey); const decrypted = await decryptAES(key, pickleKey, "m.megolm_backup.v1"); key = olmlib.decodeBase64(decrypted); } return key; } /** * Stores the session backup key to the cache * @param {Uint8Array} key the private key * @returns {Promise} so you can catch failures */ public async storeSessionBackupPrivateKey(key: ArrayLike<number>): Promise<void> { if (!(key instanceof Uint8Array)) { throw new Error(`storeSessionBackupPrivateKey expects Uint8Array, got ${key}`); } const pickleKey = Buffer.from(this.olmDevice.pickleKey); const encryptedKey = await encryptAES(olmlib.encodeBase64(key), pickleKey, "m.megolm_backup.v1"); return this.cryptoStore.doTxn( 'readwrite', [IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => { this.cryptoStore.storeSecretStorePrivateKey(txn, "m.megolm_backup.v1", encryptedKey); }, ); } /** * Checks that a given cross-signing private key matches a given public key. * This can be used by the getCrossSigningKey callback to verify that the * private key it is about to supply is the one that was requested. * * @param {Uint8Array} privateKey The private key * @param {string} expectedPublicKey The public key * @returns {boolean} true if the key matches, otherwise false */ public checkCrossSigningPrivateKey(privateKey: Uint8Array, expectedPublicKey: string): boolean { let signing = null; try { signing = new global.Olm.PkSigning(); const gotPubkey = signing.init_with_seed(privateKey); // make sure it agrees with the given pubkey return gotPubkey === expectedPublicKey; } finally { if (signing) signing.free(); } } /** * Run various follow-up actions after cross-signing keys have changed locally * (either by resetting the keys for the account or by getting them from secret * storage), such as signing the current device, upgrading device * verifications, etc. */ private async afterCrossSigningLocalKeyChange(): Promise<void> { logger.info("Starting cross-signing key change post-processing"); // sign the current device with the new key, and upload to the server const device = this.deviceList.getStoredDevice(this.userId, this.deviceId); const signedDevice = await this.crossSigningInfo.signDevice(this.userId, device); logger.info(`Starting background key sig upload for ${this.deviceId}`); const upload = ({ shouldEmit }) => { return this.baseApis.uploadKeySignatures({ [this.userId]: { [this.deviceId]: signedDevice, }, }).then((response) => { const { failures } = response || {}; if (Object.keys(failures || []).length > 0) { if (shouldEmit) { this.baseApis.emit( "crypto.keySignatureUploadFailure", failures, "afterCrossSigningLocalKeyChange", upload, // continuation ); } throw new KeySignatureUploadError("Key upload failed", { failures }); } logger.info(`Finished background key sig upload for ${this.deviceId}`); }).catch(e => { logger.error( `Error during background key sig upload for ${this.deviceId}`, e, ); }); }; upload({ shouldEmit: true }); const shouldUpgradeCb = ( this.baseApis.cryptoCallbacks.shouldUpgradeDeviceVerifications ); if (shouldUpgradeCb) { logger.info("Starting device verification upgrade"); // Check all users for signatures if upgrade callback present // FIXME: do this in batches const users = {}; for (const [userId, crossSigningInfo] of Object.entries(this.deviceList.crossSigningInfo)) { const upgradeInfo = await this.checkForDeviceVerificationUpgrade( userId, CrossSigningInfo.fromStorage(crossSigningInfo, userId), ); if (upgradeInfo) { users[userId] = upgradeInfo; } } if (Object.keys(users).length > 0) { logger.info(`Found ${Object.keys(users).length} verif users to upgrade`); try { const usersToUpgrade = await shouldUpgradeCb({