From 0e71fa20fc31391f7c4a67106cfe42e1c044207c Mon Sep 17 00:00:00 2001 From: Richard van der Hoff Date: Thu, 16 May 2024 23:15:59 +0100 Subject: [PATCH] Element-R: pass pickleKey in as raw key for indexeddb encryption Currently, we pass the `pickleKey` to the rust library for use as a passphrase for encrypting its crypto store. The Rust libary then passes that passphrase through 200000 rounds of PBKDF2 to generate an encryption key, which is (deliberately) slow. However, the pickleKey is actually 32 bytes of random data (base64-encoded). By passing the raw key into the rust library, we can therefore save the PBKDF operation. Backwards-compatibility with existing sessions is maintained, because if the rust library discovers that the store was previously encrypted with a key based on a PBKDF, it will re-base64 and PBKDF the key we provide, thus reconstructing the right key. --- src/Lifecycle.ts | 23 +++++++++++++++------- src/MatrixClientPeg.ts | 38 ++++++++++++++++++++++++++---------- test/MatrixClientPeg-test.ts | 7 ++++--- 3 files changed, 48 insertions(+), 20 deletions(-) diff --git a/src/Lifecycle.ts b/src/Lifecycle.ts index 8b04f74afcb..a42787655d3 100644 --- a/src/Lifecycle.ts +++ b/src/Lifecycle.ts @@ -18,7 +18,7 @@ limitations under the License. */ import { ReactNode } from "react"; -import { createClient, MatrixClient, SSOAction, OidcTokenRefresher } from "matrix-js-sdk/src/matrix"; +import { createClient, MatrixClient, SSOAction, OidcTokenRefresher, decodeBase64 } from "matrix-js-sdk/src/matrix"; import { IEncryptedPayload } from "matrix-js-sdk/src/crypto/aes"; import { QueryDict } from "matrix-js-sdk/src/utils"; import { logger } from "matrix-js-sdk/src/logger"; @@ -821,7 +821,10 @@ async function doSetLoggedIn(credentials: IMatrixClientCreds, clearStorageEnable checkSessionLock(); dis.fire(Action.OnLoggedIn); - await startMatrixClient(client, /*startSyncing=*/ !softLogout); + // The pickleKey, if provided, is a base64-encoded 256-bit key, so can be used for the crypto store. + const storageKey = credentials.pickleKey ? decodeBase64(credentials.pickleKey) : undefined; + await startMatrixClient(client, /*startSyncing=*/ !softLogout, storageKey); + storageKey?.fill(0); return client; } @@ -955,11 +958,17 @@ export function isLoggingOut(): boolean { /** * Starts the matrix client and all other react-sdk services that * listen for events while a session is logged in. + * * @param client the matrix client to start - * @param {boolean} startSyncing True (default) to actually start - * syncing the client. + * @param startSyncing True to actually start syncing the client. + * @param rustCryptoStoreKey - If we are using Rust Crypto, a key to encrypt the store with. + * If undefined, the store will be unencrypted. */ -async function startMatrixClient(client: MatrixClient, startSyncing = true): Promise { +async function startMatrixClient( + client: MatrixClient, + startSyncing: boolean, + rustCryptoStoreKey?: Uint8Array, +): Promise { logger.log(`Lifecycle: Starting MatrixClient`); // dispatch this before starting the matrix client: it's used @@ -990,10 +999,10 @@ async function startMatrixClient(client: MatrixClient, startSyncing = true): Pro // index (e.g. the FilePanel), therefore initialize the event index // before the client. await EventIndexPeg.init(); - await MatrixClientPeg.start(); + await MatrixClientPeg.start(rustCryptoStoreKey); } else { logger.warn("Caller requested only auxiliary services be started"); - await MatrixClientPeg.assign(); + await MatrixClientPeg.assign(rustCryptoStoreKey); } checkSessionLock(); diff --git a/src/MatrixClientPeg.ts b/src/MatrixClientPeg.ts index d14003dbfac..3a2da727713 100644 --- a/src/MatrixClientPeg.ts +++ b/src/MatrixClientPeg.ts @@ -103,14 +103,20 @@ export interface IMatrixClientPeg { unset(): void; /** - * Prepare the MatrixClient for use, including initialising the store and crypto, but do not start it + * Prepare the MatrixClient for use, including initialising the store and crypto, but do not start it. + * + * @param rustCryptoStoreKey - If we are using Rust crypto, a key with which to encrypt the indexeddb. + * If undefined, the store will be unencrypted. */ - assign(): Promise; + assign(rustCryptoStoreKey?: Uint8Array): Promise; /** - * Prepare the MatrixClient for use, including initialising the store and crypto, and start it + * Prepare the MatrixClient for use, including initialising the store and crypto, and start it. + * + * @param rustCryptoStoreKey - If we are using Rust crypto, a key with which to encrypt the indexeddb. + * If undefined, the store will be unencrypted. */ - start(): Promise; + start(rustCryptoStoreKey?: Uint8Array): Promise; /** * If we've registered a user ID we set this to the ID of the @@ -257,7 +263,10 @@ class MatrixClientPegClass implements IMatrixClientPeg { PlatformPeg.get()?.reload(); }; - public async assign(): Promise { + /** + * Implementation of {@link IMatrixClientPeg.assign}. + */ + public async assign(rustCryptoStoreKey?: Uint8Array): Promise { if (!this.matrixClient) { throw new Error("createClient must be called first"); } @@ -284,7 +293,7 @@ class MatrixClientPegClass implements IMatrixClientPeg { // try to initialise e2e on the new client if (!SettingsStore.getValue("lowBandwidth")) { - await this.initClientCrypto(); + await this.initClientCrypto(rustCryptoStoreKey); } const opts = utils.deepCopy(this.opts); @@ -310,8 +319,11 @@ class MatrixClientPegClass implements IMatrixClientPeg { /** * Attempt to initialize the crypto layer on a newly-created MatrixClient + * + * @param rustCryptoStoreKey - If we are using Rust crypto, a key with which to encrypt the indexeddb. + * If undefined, the store will be unencrypted. */ - private async initClientCrypto(): Promise { + private async initClientCrypto(rustCryptoStoreKey?: Uint8Array): Promise { if (!this.matrixClient) { throw new Error("createClient must be called first"); } @@ -347,7 +359,10 @@ class MatrixClientPegClass implements IMatrixClientPeg { // Now we can initialise the right crypto impl. if (useRustCrypto) { - await this.matrixClient.initRustCrypto(); + if (!rustCryptoStoreKey) { + logger.error("Warning! Not using an encryption key for rust crypto store."); + } + await this.matrixClient.initRustCrypto({ storageKey: rustCryptoStoreKey }); StorageManager.setCryptoInitialised(true); // TODO: device dehydration and whathaveyou @@ -376,8 +391,11 @@ class MatrixClientPegClass implements IMatrixClientPeg { } } - public async start(): Promise { - const opts = await this.assign(); + /** + * Implementation of {@link IMatrixClientPeg.start}. + */ + public async start(rustCryptoStoreKey?: Uint8Array): Promise { + const opts = await this.assign(rustCryptoStoreKey); logger.log(`MatrixClientPeg: really starting MatrixClient`); await this.matrixClient!.startClient(opts); diff --git a/test/MatrixClientPeg-test.ts b/test/MatrixClientPeg-test.ts index 2ed08e0a21f..d0bf0ed6686 100644 --- a/test/MatrixClientPeg-test.ts +++ b/test/MatrixClientPeg-test.ts @@ -243,9 +243,10 @@ describe("MatrixClientPeg", () => { const mockInitCrypto = jest.spyOn(testPeg.safeGet(), "initCrypto").mockResolvedValue(undefined); const mockInitRustCrypto = jest.spyOn(testPeg.safeGet(), "initRustCrypto").mockResolvedValue(undefined); - await testPeg.start(); + const cryptoStoreKey = new Uint8Array([1, 2, 3, 4]); + await testPeg.start(cryptoStoreKey); expect(mockInitCrypto).not.toHaveBeenCalled(); - expect(mockInitRustCrypto).toHaveBeenCalledTimes(1); + expect(mockInitRustCrypto).toHaveBeenCalledWith({ storageKey: cryptoStoreKey }); // we should have stashed the setting in the settings store expect(mockSetValue).toHaveBeenCalledWith("feature_rust_crypto", null, SettingLevel.DEVICE, true); @@ -271,7 +272,7 @@ describe("MatrixClientPeg", () => { await testPeg.start(); expect(mockInitCrypto).toHaveBeenCalled(); - expect(mockInitRustCrypto).not.toHaveBeenCalledTimes(1); + expect(mockInitRustCrypto).not.toHaveBeenCalled(); // we should have stashed the setting in the settings store expect(mockSetValue).toHaveBeenCalledWith("feature_rust_crypto", null, SettingLevel.DEVICE, false);