UNPKG

matrix-js-sdk

Version:
1,096 lines (1,028 loc) 152 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.IncomingRoomKeyRequest = exports.CryptoEvent = exports.Crypto = void 0; exports.fixBackupKey = fixBackupKey; exports.isCryptoAvailable = isCryptoAvailable; exports.verificationMethods = void 0; var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); var _anotherJson = _interopRequireDefault(require("another-json")); var _uuid = require("uuid"); var _event = require("../@types/event"); var _ReEmitter = require("../ReEmitter"); var _logger = require("../logger"); var _OlmDevice = require("./OlmDevice"); var olmlib = _interopRequireWildcard(require("./olmlib")); var _DeviceList = require("./DeviceList"); var _deviceinfo = require("./deviceinfo"); var algorithms = _interopRequireWildcard(require("./algorithms")); var _CrossSigning = require("./CrossSigning"); var _EncryptionSetup = require("./EncryptionSetup"); var _SecretStorage = require("./SecretStorage"); var _api = require("./api"); var _OutgoingRoomKeyRequestManager = require("./OutgoingRoomKeyRequestManager"); var _indexeddbCryptoStore = require("./store/indexeddb-crypto-store"); var _QRCode = require("./verification/QRCode"); var _SAS = require("./verification/SAS"); var _key_passphrase = require("./key_passphrase"); var _recoverykey = require("./recoverykey"); var _VerificationRequest = require("./verification/request/VerificationRequest"); var _InRoomChannel = require("./verification/request/InRoomChannel"); var _ToDeviceChannel = require("./verification/request/ToDeviceChannel"); var _IllegalMethod = require("./verification/IllegalMethod"); var _errors = require("../errors"); var _aes = require("./aes"); var _dehydration = require("./dehydration"); var _backup = require("./backup"); var _room = require("../models/room"); var _roomMember = require("../models/room-member"); var _event2 = require("../models/event"); var _client = require("../client"); var _RoomList = require("./RoomList"); var _typedEventEmitter = require("../models/typed-event-emitter"); var _CryptoBackend = require("../common-crypto/CryptoBackend"); var _roomState = require("../models/room-state"); var _utils = require("../utils"); var _secretStorage = require("../secret-storage"); var _cryptoApi = require("../crypto-api"); var _deviceConverter = require("./device-converter"); var _httpApi = require("../http-api"); var _base = require("../base64"); var _membership = require("../@types/membership"); function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } /* 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. */ /* re-exports for backwards compatibility */ const DeviceVerification = _deviceinfo.DeviceInfo.DeviceVerification; const defaultVerificationMethods = { [_QRCode.ReciprocateQRCode.NAME]: _QRCode.ReciprocateQRCode, [_SAS.SAS.NAME]: _SAS.SAS, // 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. [_QRCode.SHOW_QR_CODE_METHOD]: _IllegalMethod.IllegalMethod, [_QRCode.SCAN_QR_CODE_METHOD]: _IllegalMethod.IllegalMethod }; /** * verification method names */ // legacy export identifier const verificationMethods = exports.verificationMethods = { RECIPROCATE_QR_CODE: _QRCode.ReciprocateQRCode.NAME, SAS: _SAS.SAS.NAME }; function isCryptoAvailable() { return Boolean(globalThis.Olm); } // minimum time between attempting to unwedge an Olm session, if we succeeded // in creating a new session const MIN_FORCE_SESSION_INTERVAL_MS = 60 * 60 * 1000; // 1 hour // minimum time between attempting to unwedge an Olm session, if we failed // to create a new session const FORCE_SESSION_RETRY_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes /* eslint-disable camelcase */ /** * 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. */ /* eslint-enable camelcase */ /* eslint-disable camelcase */ /* eslint-enable camelcase */ let CryptoEvent = exports.CryptoEvent = /*#__PURE__*/function (CryptoEvent) { CryptoEvent["DeviceVerificationChanged"] = "deviceVerificationChanged"; CryptoEvent["UserTrustStatusChanged"] = "userTrustStatusChanged"; CryptoEvent["UserCrossSigningUpdated"] = "userCrossSigningUpdated"; CryptoEvent["RoomKeyRequest"] = "crypto.roomKeyRequest"; CryptoEvent["RoomKeyRequestCancellation"] = "crypto.roomKeyRequestCancellation"; CryptoEvent["KeyBackupStatus"] = "crypto.keyBackupStatus"; CryptoEvent["KeyBackupFailed"] = "crypto.keyBackupFailed"; CryptoEvent["KeyBackupSessionsRemaining"] = "crypto.keyBackupSessionsRemaining"; CryptoEvent["KeyBackupDecryptionKeyCached"] = "crypto.keyBackupDecryptionKeyCached"; CryptoEvent["KeySignatureUploadFailure"] = "crypto.keySignatureUploadFailure"; CryptoEvent["VerificationRequest"] = "crypto.verification.request"; CryptoEvent["VerificationRequestReceived"] = "crypto.verificationRequestReceived"; CryptoEvent["Warning"] = "crypto.warning"; CryptoEvent["WillUpdateDevices"] = "crypto.willUpdateDevices"; CryptoEvent["DevicesUpdated"] = "crypto.devicesUpdated"; CryptoEvent["KeysChanged"] = "crossSigning.keysChanged"; CryptoEvent["LegacyCryptoStoreMigrationProgress"] = "crypto.legacyCryptoStoreMigrationProgress"; return CryptoEvent; }({}); class Crypto extends _typedEventEmitter.TypedEventEmitter { /** * @returns The version of Olm. */ static getOlmVersion() { return _OlmDevice.OlmDevice.getOlmVersion(); } /** * 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 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(baseApis, _userId, deviceId, clientStore, cryptoStore, verificationMethods) { super(); (0, _defineProperty2.default)(this, "trustCrossSignedDevices", true); // the last time we did a check for the number of one-time-keys on the server. (0, _defineProperty2.default)(this, "lastOneTimeKeyCheck", null); (0, _defineProperty2.default)(this, "oneTimeKeyCheckInProgress", false); // EncryptionAlgorithm instance for each room (0, _defineProperty2.default)(this, "roomEncryptors", new Map()); // map from algorithm to DecryptionAlgorithm instance, for each room (0, _defineProperty2.default)(this, "roomDecryptors", new Map()); (0, _defineProperty2.default)(this, "deviceKeys", {}); // type: key (0, _defineProperty2.default)(this, "globalBlacklistUnverifiedDevices", false); (0, _defineProperty2.default)(this, "globalErrorOnUnknownDevices", true); // list of IncomingRoomKeyRequests/IncomingRoomKeyRequestCancellations // we received in the current sync. (0, _defineProperty2.default)(this, "receivedRoomKeyRequests", []); (0, _defineProperty2.default)(this, "receivedRoomKeyRequestCancellations", []); // true if we are currently processing received room key requests (0, _defineProperty2.default)(this, "processingRoomKeyRequests", false); // controls whether device tracking is delayed // until calling encryptEvent or trackRoomDevices, // or done immediately upon enabling room encryption. (0, _defineProperty2.default)(this, "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. (0, _defineProperty2.default)(this, "roomDeviceTrackingState", {}); // The timestamp of the minimum time at which we will retry forcing establishment // of a new session for each device, in milliseconds. // { // userId: { // deviceId: 1234567890000, // }, // } // Map: user Id → device Id → timestamp (0, _defineProperty2.default)(this, "forceNewSessionRetryTime", new _utils.MapWithDefault(() => new _utils.MapWithDefault(() => 0))); // 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. (0, _defineProperty2.default)(this, "sendKeyRequestsImmediately", false); /* * Event handler for DeviceList's userNewDevices event */ (0, _defineProperty2.default)(this, "onDeviceListUserCrossSigningUpdated", async userId => { if (userId === this.userId) { // An update to our own cross-signing key. // Get the new key first: const newCrossSigning = this.deviceList.getStoredCrossSigningForUser(userId); const seenPubkey = newCrossSigning ? newCrossSigning.getId() : null; const currentPubkey = this.crossSigningInfo.getId(); const changed = currentPubkey !== seenPubkey; if (currentPubkey && seenPubkey && !changed) { // If it's not changed, just make sure everything is up to date await this.checkOwnCrossSigningTrust(); } else { // We'll now be in a state where cross-signing on the account is not trusted // because our locally stored cross-signing keys will not match the ones // on the server for our account. So we clear our own stored cross-signing keys, // effectively disabling cross-signing until the user gets verified by the device // that reset the keys this.storeTrustedSelfKeys(null); // emit cross-signing has been disabled this.emit(CryptoEvent.KeysChanged, {}); // as the trust for our own user has changed, // also emit an event for this this.emit(CryptoEvent.UserTrustStatusChanged, this.userId, this.checkUserTrust(userId)); } } else { await this.checkDeviceVerifications(userId); // Update verified before latch using the current state and save the new // latch value in the device list store. const crossSigning = this.deviceList.getStoredCrossSigningForUser(userId); if (crossSigning) { crossSigning.updateCrossSigningVerifiedBefore(this.checkUserTrust(userId).isCrossSigningVerified()); this.deviceList.setRawStoredCrossSigningForUser(userId, crossSigning.toStorage()); } this.emit(CryptoEvent.UserTrustStatusChanged, userId, this.checkUserTrust(userId)); } }); (0, _defineProperty2.default)(this, "onMembership", (event, member, oldMembership) => { try { this.onRoomMembership(event, member, oldMembership); } catch (e) { _logger.logger.error("Error handling membership change:", e); } }); (0, _defineProperty2.default)(this, "onToDeviceEvent", event => { try { _logger.logger.log(`received to-device ${event.getType()} from: ` + `${event.getSender()} id: ${event.getContent()[_event.ToDeviceMessageId]}`); if (event.getType() == "m.room_key" || event.getType() == "m.forwarded_room_key") { this.onRoomKeyEvent(event); } else if (event.getType() == "m.room_key_request") { this.onRoomKeyRequestEvent(event); } else if (event.getType() === "m.secret.request") { this.secretStorage.onRequestReceived(event); } else if (event.getType() === "m.secret.send") { this.secretStorage.onSecretReceived(event); } else if (event.getType() === "m.room_key.withheld") { this.onRoomKeyWithheldEvent(event); } else if (event.getContent().transaction_id) { this.onKeyVerificationMessage(event); } else if (event.getContent().msgtype === "m.bad.encrypted") { this.onToDeviceBadEncrypted(event); } else if (event.isBeingDecrypted() || event.shouldAttemptDecryption()) { if (!event.isBeingDecrypted()) { event.attemptDecryption(this); } // once the event has been decrypted, try again event.once(_event2.MatrixEventEvent.Decrypted, ev => { this.onToDeviceEvent(ev); }); } } catch (e) { _logger.logger.error("Error handling toDeviceEvent:", e); } }); /** * Handle key verification requests sent as timeline events * * @internal * @param event - the timeline event * @param room - not used * @param atStart - not used * @param removed - not used * @param whether - this is a live event */ (0, _defineProperty2.default)(this, "onTimelineEvent", (event, room, atStart, removed, { liveEvent = true } = {}) => { if (!_InRoomChannel.InRoomChannel.validateEvent(event, this.baseApis)) { return; } const createRequest = event => { const channel = new _InRoomChannel.InRoomChannel(this.baseApis, event.getRoomId()); return new _VerificationRequest.VerificationRequest(channel, this.verificationMethods, this.baseApis); }; this.handleVerificationEvent(event, this.inRoomVerificationRequests, createRequest, liveEvent); }); this.baseApis = baseApis; this.userId = _userId; this.deviceId = deviceId; this.clientStore = clientStore; this.cryptoStore = cryptoStore; _logger.logger.debug("Crypto: initialising roomlist..."); this.roomList = new _RoomList.RoomList(cryptoStore); this.reEmitter = new _ReEmitter.TypedReEmitter(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.logger.warn(`Excluding unknown verification method ${method}`); } } } else { this.verificationMethods = new Map(Object.entries(defaultVerificationMethods)); } this.backupManager = new _backup.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.secretStorage.get("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.secretStorage.getKey(); await this.secretStorage.store("m.megolm_backup.v1", fixedKey, [keys[0]]); } return (0, _base.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.OlmDevice(cryptoStore); this.deviceList = new _DeviceList.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.OutgoingRoomKeyRequestManager(baseApis, this.deviceId, this.cryptoStore); this.toDeviceVerificationRequests = new _ToDeviceChannel.ToDeviceRequests(); this.inRoomVerificationRequests = new _InRoomChannel.InRoomRequests(); const cryptoCallbacks = this.baseApis.cryptoCallbacks || {}; const cacheCallbacks = (0, _CrossSigning.createCryptoStoreCacheCallbacks)(cryptoStore, this.olmDevice); this.crossSigningInfo = new _CrossSigning.CrossSigningInfo(_userId, cryptoCallbacks, cacheCallbacks); // Yes, we pass the client twice here: see SecretStorage this.secretStorage = new _SecretStorage.SecretStorage(baseApis, cryptoCallbacks, baseApis); this.dehydrationManager = new _dehydration.DehydrationManager(this); // Assuming no app-supplied callback, default to getting from SSSS. if (!cryptoCallbacks.getCrossSigningKey && cryptoCallbacks.getSecretStorageKey) { cryptoCallbacks.getCrossSigningKey = async type => { return _CrossSigning.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. */ async init({ exportedOlmDevice, pickleKey } = {}) { _logger.logger.log("Crypto: initialising Olm..."); await global.Olm.init(); _logger.logger.log(exportedOlmDevice ? "Crypto: initialising Olm device from exported device..." : "Crypto: initialising Olm device..."); await this.olmDevice.init({ fromExportedDevice: exportedOlmDevice, pickleKey }); _logger.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.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.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.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.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.logger.debug("Crypto: initialising roomlist..."); await this.roomList.init(); _logger.logger.log("Crypto: checking for key backup..."); this.backupManager.checkAndStart(); } /** * Implementation of {@link CryptoApi#getVersion}. */ getVersion() { const olmVersionTuple = Crypto.getOlmVersion(); return `Olm ${olmVersionTuple[0]}.${olmVersionTuple[1]}.${olmVersionTuple[2]}`; } /** * 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 */ getTrustCrossSignedDevices() { return this.trustCrossSignedDevices; } /** * @deprecated Use {@link Crypto.CryptoApi#getTrustCrossSignedDevices}. */ getCryptoTrustCrossSignedDevices() { return this.trustCrossSignedDevices; } /** * See getCryptoTrustCrossSignedDevices * * @param val - True to trust cross-signed devices */ setTrustCrossSignedDevices(val) { 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); } } } } /** * @deprecated Use {@link Crypto.CryptoApi#setTrustCrossSignedDevices}. */ setCryptoTrustCrossSignedDevices(val) { this.setTrustCrossSignedDevices(val); } /** * 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. */ async createRecoveryKeyFromPassphrase(password) { const decryption = new global.Olm.PkDecryption(); try { if (password) { const derivation = await (0, _key_passphrase.keyFromPassphrase)(password); decryption.init_with_private_key(derivation.key); const privateKey = decryption.get_private_key(); return { keyInfo: { passphrase: { algorithm: "m.pbkdf2", iterations: derivation.iterations, salt: derivation.salt } }, privateKey: privateKey, encodedPrivateKey: (0, _recoverykey.encodeRecoveryKey)(privateKey) }; } else { decryption.generate_key(); const privateKey = decryption.get_private_key(); return { privateKey: privateKey, encodedPrivateKey: (0, _recoverykey.encodeRecoveryKey)(privateKey) }; } } finally { decryption === null || decryption === void 0 || 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 */ async userHasCrossSigningKeys(userId = this.userId) { await this.downloadKeys([userId]); return this.deviceList.getStoredCrossSigningForUser(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 */ async isCrossSigningReady() { 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 */ async isSecretStorageReady() { 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); } /** * Implementation of {@link CryptoApi#getCrossSigningStatus} */ async getCrossSigningStatus() { var _cacheCallbacks$getCr, _cacheCallbacks$getCr2, _cacheCallbacks$getCr3; const publicKeysOnDevice = Boolean(this.crossSigningInfo.getId()); const privateKeysInSecretStorage = Boolean(await this.crossSigningInfo.isStoredInSecretStorage(this.secretStorage)); const cacheCallbacks = this.crossSigningInfo.getCacheCallbacks(); const masterKey = Boolean(await ((_cacheCallbacks$getCr = cacheCallbacks.getCrossSigningKeyCache) === null || _cacheCallbacks$getCr === void 0 ? void 0 : _cacheCallbacks$getCr.call(cacheCallbacks, "master"))); const selfSigningKey = Boolean(await ((_cacheCallbacks$getCr2 = cacheCallbacks.getCrossSigningKeyCache) === null || _cacheCallbacks$getCr2 === void 0 ? void 0 : _cacheCallbacks$getCr2.call(cacheCallbacks, "self_signing"))); const userSigningKey = Boolean(await ((_cacheCallbacks$getCr3 = cacheCallbacks.getCrossSigningKeyCache) === null || _cacheCallbacks$getCr3 === void 0 ? void 0 : _cacheCallbacks$getCr3.call(cacheCallbacks, "user_signing"))); return { publicKeysOnDevice, privateKeysInSecretStorage, privateKeysCachedLocally: { masterKey, selfSigningKey, userSigningKey } }; } /** * 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. */ async bootstrapCrossSigning({ authUploadDeviceSigningKeys, setupNewCrossSigning } = {}) { _logger.logger.log("Bootstrapping cross-signing"); const delegateCryptoCallbacks = this.baseApis.cryptoCallbacks; const builder = new _EncryptionSetup.EncryptionSetupBuilder(this.baseApis.store.accountData, delegateCryptoCallbacks); const crossSigningInfo = new _CrossSigning.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); 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.logger.log({ setupNewCrossSigning, publicKeysOnDevice, privateKeysInCache, privateKeysInStorage, privateKeysExistSomewhere }); if (!privateKeysExistSomewhere || setupNewCrossSigning) { _logger.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.logger.log("Cross-signing public keys trusted and private keys found locally"); } else if (privateKeysInStorage) { _logger.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.ServerSideSecretStorageImpl(builder.accountDataClientAdapter, builder.ssssCryptoCallbacks); if (await secretStorage.hasKey()) { _logger.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 _CrossSigning.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.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. * * 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 async bootstrapSecretStorage({ createSecretStorageKey = async () => ({}), keyBackupInfo, setupNewKeyBackup, setupNewSecretStorage, getKeyBackupPassphrase } = {}) { _logger.logger.log("Bootstrapping Secure Secret Storage"); const delegateCryptoCallbacks = this.baseApis.cryptoCallbacks; const builder = new _EncryptionSetup.EncryptionSetupBuilder(this.baseApis.store.accountData, delegateCryptoCallbacks); const secretStorage = new _secretStorage.ServerSideSecretStorageImpl(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 => { const { keyId, keyInfo } = await secretStorage.addKey(_secretStorage.SECRET_STORAGE_ALGORITHM_V1_AES, opts); // make the private key available to encrypt 4S secrets builder.ssssCryptoCallbacks.addPrivateKey(keyId, keyInfo, opts.key); await secretStorage.setDefaultKeyId(keyId); return keyId; }; const ensureCanCheckPassphrase = async (keyId, keyInfo) => { if (!keyInfo.mac) { var _this$baseApis$crypto, _this$baseApis$crypto2; const key = await ((_this$baseApis$crypto = (_this$baseApis$crypto2 = this.baseApis.cryptoCallbacks).getSecretStorageKey) === null || _this$baseApis$crypto === void 0 ? void 0 : _this$baseApis$crypto.call(_this$baseApis$crypto2, { keys: { [keyId]: keyInfo } }, "")); if (key) { const privateKey = key[1]; builder.ssssCryptoCallbacks.addPrivateKey(keyId, keyInfo, privateKey); const { iv, mac } = await (0, _aes.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.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.logger.error("Signing key backup with cross-signing keys failed", e); } } else { _logger.logger.warn("Cross-signing keys not available, skipping signature on key backup"); } }; const oldSSSSKey = await this.secretStorage.getKey(); const [oldKeyId, oldKeyInfo] = oldSSSSKey || [null, null]; const storageExists = !setupNewSecretStorage && oldKeyInfo && oldKeyInfo.algorithm === _secretStorage.SECRET_STORAGE_ALGORITHM_V1_AES; // Log all relevant state for easier parsing of debug logs. _logger.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.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({ passphrase: keyInfo === null || keyInfo === void 0 ? void 0 : keyInfo.passphrase, key: privateKey, name: keyInfo === null || keyInfo === void 0 ? void 0 : keyInfo.name }); } else if (!storageExists && keyBackupInfo) { // we have an existing backup, but no SSSS _logger.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 === null || getKeyBackupPassphrase === void 0 ? void 0 : getKeyBackupPassphrase())); // create a new SSSS key and use the backup key as the new SSSS key const opts = { key: backupKey }; 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); // store the backup key in secret storage await secretStorage.store("m.megolm_backup.v1", (0, _base.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.logger.log("Secret storage exists"); if (oldKeyInfo && oldKeyInfo.algorithm === _secretStorage.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.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 _CrossSigning.CrossSigningInfo.storeInSecretStorage(crossSigningPrivateKeys, secretStorage); } if (setupNewKeyBackup && !keyBackupInfo) { _logger.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 to 4S const privateKey = (0, _recoverykey.decodeRecoveryKey)(info.recovery_key); await secretStorage.store("m.megolm_backup.v1", (0, _base.encodeBase64)(privateKey)); // create keyBackupInfo object to add to builder const data = { 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.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) { const keyId = newKeyId || oldKeyId; await secretStorage.store("m.megolm_backup.v1", fixedBackupKey, keyId ? [keyId] : null); } const decodedBackupKey = new Uint8Array((0, _base.decodeBase64)(fixedBackupKey || sessionBackupKey)); 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 === null || getKeyBackupPassphrase === void 0 ? void 0 : 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.logger.error("Key backup is enabled but couldn't get key backup key!"); return; } _logger.logger.info("Got session backup key from cache/user that wasn't in SSSS: saving to SSSS"); await secretStorage.store("m.megolm_backup.v1", (0, _base.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.logger.log("Secure Secret Storage ready"); } /** * Implementation of {@link CryptoApi#resetKeyBackup}. */ async resetKeyBackup() { // Delete existing ones // There is no use case for having several key backup version live server side. // Even if not deleted it would be lost as the key to restore is lost. // There should be only one backup at a time. await this.backupManager.deleteAllKeyBackupVersions(); const info = await this.backupManager.prepareKeyBackupVersion(); await this.signObject(info.auth_data); // add new key backup const { version } = await this.baseApis.http.authedRequest(_httpApi.Method.Post, "/room_keys/version", undefined, info, { prefix: _httpApi.ClientPrefix.V3 }); _logger.logger.log(`Created backup version ${version}`); // write the key to 4S const privateKey = info.privateKey; await this.secretStorage.store("m.megolm_backup.v1", (0, _base.encodeBase64)(privateKey)); await this.storeSessionBackupPrivateKey(privateKey); await this.backupManager.checkAndStart(); await this.backupManager.scheduleAllGroupSessionsForBackup(); } /** * Implementation of {@link CryptoApi#deleteKeyBackupVersion}. */ async deleteKeyBackupVersion(version) { await this.backupManager.deleteKeyBackupVersion(version); } /** * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#addKey}. */ addSecretStorageKey(algorithm, opts, keyID) { return this.secretStorage.addKey(algorithm, opts, keyID); } /** * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#hasKey}. */ hasSecretStorageKey(keyID) { return this.secretStorage.hasKey(keyID); } /** * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#getKey}. */ getSecretStorageKey(keyID) { return this.secretStorage.getKey(keyID); } /** * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#store}. */ storeSecret(name, secret, keys) { return this.secretStorage.store(name, secret, keys); } /** * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#get}. */ getSecret(name) { return this.secretStorage.get(name); } /** * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#isStored}. */ isSecretStored(name) { return this.secretStorage.isStored(name); } requestSecret(name, devices) { if (!devices) { devices = Object.keys(this.deviceList.getRawStoredDevicesForUser(this.userId)); } return this.secretStorage.request(name, devices); } /** * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#getDefaultKeyId}. */ getDefaultSecretStorageKeyId() { return this.secretStorage.getDefaultKeyId(); } /** * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#setDefaultKeyId}. */ setDefaultSecretStorageKeyId(k) { return this.secretStorage.setDefaultKeyId(k); } /** * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#checkKey}. */ checkSecretStorageKey(key, info) { 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 privateKey - The private key * @param expectedPublicKey - The public key * @returns true if the key matches, otherwise false */ checkSecretStoragePrivateKey(privateKey, expectedPublicKey) { 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 { var _decryption; (_decryption = decryption) === null || _decryption === void 0 || _decryption.free(); } } /** * Fetches the backup private key, if cached * @returns the key, if any, or null */ async getSessionBackupPrivateKey() { const encodedKey = await new Promise(resolve => { this.cryptoStore.doTxn("readonly", [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_ACCOUNT], txn => { this.cryptoStore.getSecretStorePrivateKey(txn, resolve, "m.megolm_backup.v1"); }); }); let key = null; // make sure we have a Uint8Array, rather than a string if (typeof encodedKey === "string") { key = new Uint8Array((0, _base.decodeBase64)(fixBackupKey(encodedKey) || encodedKey)); await this.storeSessionBackupPrivateKey(key); } if (encodedKey && typeof encodedKey === "object" && "ciphertext" in encodedKey) { const pickleKey = Buffer.from(this.olmDevice.pickleKey); const decrypted = await (0, _aes.decryptAES)(encodedKey, pickleKey, "m.megolm_backup.v1"); key = (0, _base.decodeBase64)(decrypted); } return key; } /** * Stores the session backup key to the cache * @param key - the private key * @returns a promise so you c