Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move crypto/key_passphrase.ts to crypto-api/key-passphrase.ts #4401

Merged
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,6 @@ import {
} from "./crypto/index.ts";
import { DeviceInfo } from "./crypto/deviceinfo.ts";
import { decodeRecoveryKey } from "./crypto/recoverykey.ts";
import { keyFromAuthData } from "./crypto/key_passphrase.ts";
import { User, UserEvent, UserEventHandlerMap } from "./models/user.ts";
import { getHttpUriForMxc } from "./content-repo.ts";
import { SearchResult } from "./models/search-result.ts";
Expand Down Expand Up @@ -223,7 +222,13 @@ import { LocalNotificationSettings } from "./@types/local_notifications.ts";
import { buildFeatureSupportMap, Feature, ServerSupport } from "./feature.ts";
import { BackupDecryptor, CryptoBackend } from "./common-crypto/CryptoBackend.ts";
import { RUST_SDK_STORE_PREFIX } from "./rust-crypto/constants.ts";
import { BootstrapCrossSigningOpts, CrossSigningKeyInfo, CryptoApi, ImportRoomKeysOpts } from "./crypto-api/index.ts";
import {
BootstrapCrossSigningOpts,
CrossSigningKeyInfo,
CryptoApi,
ImportRoomKeysOpts,
keyFromAuthData,
} from "./crypto-api/index.ts";
import { DeviceInfoMap } from "./crypto/DeviceList.ts";
import {
AddSecretStorageKeyOpts,
Expand Down Expand Up @@ -3645,6 +3650,7 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
* @param password - Passphrase
* @param backupInfo - Backup metadata from `checkKeyBackup`
* @returns key backup key
* @deprecated Use {@link keyFromAuthData} directly.
florianduros marked this conversation as resolved.
Show resolved Hide resolved
*/
public keyBackupKeyFromPassword(password: string, backupInfo: IKeyBackupInfo): Promise<Uint8Array> {
return keyFromAuthData(backupInfo.auth_data, password);
Expand Down
1 change: 1 addition & 0 deletions src/crypto-api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -967,3 +967,4 @@ export interface OwnDeviceKeys {

export * from "./verification.ts";
export * from "./keybackup.ts";
export * from "./key-passphrase.ts";
104 changes: 104 additions & 0 deletions src/crypto-api/key-passphrase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
/*
* Copyright 2024 The Matrix.org Foundation C.I.C.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { randomString } from "../randomstring.ts";

const DEFAULT_ITERATIONS = 500000;

const DEFAULT_BITSIZE = 256;

/* eslint-disable camelcase */
interface IAuthData {
private_key_salt?: string;
private_key_iterations?: number;
private_key_bits?: number;
}
/* eslint-enable camelcase */

interface IKey {
key: Uint8Array;
salt: string;
iterations: number;
}

/**
* Derive a key from a passphrase using the salt and iterations from the auth data.
florianduros marked this conversation as resolved.
Show resolved Hide resolved
* @param authData
* @param password
*/
export function keyFromAuthData(authData: IAuthData, password: string): Promise<Uint8Array> {
if (!authData.private_key_salt || !authData.private_key_iterations) {
throw new Error("Salt and/or iterations not found: " + "this backup cannot be restored with a passphrase");
}

return deriveKey(
password,
authData.private_key_salt,
authData.private_key_iterations,
authData.private_key_bits || DEFAULT_BITSIZE,
);
}
florianduros marked this conversation as resolved.
Show resolved Hide resolved

/**
* Derive a key from a passphrase.
florianduros marked this conversation as resolved.
Show resolved Hide resolved
* @param password
*/
export async function keyFromPassphrase(password: string): Promise<IKey> {
const salt = randomString(32);

const key = await deriveKey(password, salt, DEFAULT_ITERATIONS, DEFAULT_BITSIZE);

return { key, salt, iterations: DEFAULT_ITERATIONS };
}
florianduros marked this conversation as resolved.
Show resolved Hide resolved

/**
* Derive a key from a passphrase using PBKDF2.
florianduros marked this conversation as resolved.
Show resolved Hide resolved
* @param password
* @param salt
* @param iterations
* @param numBits
florianduros marked this conversation as resolved.
Show resolved Hide resolved
*/
export async function deriveKey(
florianduros marked this conversation as resolved.
Show resolved Hide resolved
password: string,
florianduros marked this conversation as resolved.
Show resolved Hide resolved
salt: string,
iterations: number,
numBits = DEFAULT_BITSIZE,
): Promise<Uint8Array> {
if (!globalThis.crypto.subtle || !TextEncoder) {
throw new Error("Password-based backup is not available on this platform");
}

const key = await globalThis.crypto.subtle.importKey(
"raw",
new TextEncoder().encode(password),
{ name: "PBKDF2" },
false,
["deriveBits"],
);

const keybits = await globalThis.crypto.subtle.deriveBits(
{
name: "PBKDF2",
salt: new TextEncoder().encode(salt),
iterations: iterations,
hash: "SHA-512",
},
key,
numBits,
);

return new Uint8Array(keybits);
}
2 changes: 1 addition & 1 deletion src/crypto/backup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import { logger } from "../logger.ts";
import { MEGOLM_ALGORITHM, verifySignature } from "./olmlib.ts";
import { DeviceInfo } from "./deviceinfo.ts";
import { DeviceTrustLevel } from "./CrossSigning.ts";
import { keyFromPassphrase } from "./key_passphrase.ts";
import { encodeUri, safeSet, sleep } from "../utils.ts";
import { IndexedDBCryptoStore } from "./store/indexeddb-crypto-store.ts";
import { encodeRecoveryKey } from "./recoverykey.ts";
Expand All @@ -41,6 +40,7 @@ import { CryptoEvent } from "./index.ts";
import { ClientPrefix, HTTPError, MatrixError, Method } from "../http-api/index.ts";
import { BackupTrustInfo } from "../crypto-api/keybackup.ts";
import { BackupDecryptor } from "../common-crypto/CryptoBackend.ts";
import { keyFromPassphrase } from "../crypto-api/index.ts";

const KEY_BACKUP_KEYS_PER_REQUEST = 200;
const KEY_BACKUP_CHECK_RATE_LIMIT = 5000; // ms
Expand Down
2 changes: 1 addition & 1 deletion src/crypto/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ import { IndexedDBCryptoStore } from "./store/indexeddb-crypto-store.ts";
import { VerificationBase } from "./verification/Base.ts";
import { ReciprocateQRCode, SCAN_QR_CODE_METHOD, SHOW_QR_CODE_METHOD } from "./verification/QRCode.ts";
import { SAS as SASVerification } from "./verification/SAS.ts";
import { keyFromPassphrase } from "./key_passphrase.ts";
import { decodeRecoveryKey, encodeRecoveryKey } from "./recoverykey.ts";
import { VerificationRequest } from "./verification/request/VerificationRequest.ts";
import { InRoomChannel, InRoomRequests } from "./verification/request/InRoomChannel.ts";
Expand Down Expand Up @@ -97,6 +96,7 @@ import {
ImportRoomKeysOpts,
KeyBackupCheck,
KeyBackupInfo,
keyFromPassphrase,
OwnDeviceKeys,
VerificationRequest as CryptoApiVerificationRequest,
} from "../crypto-api/index.ts";
Expand Down
74 changes: 2 additions & 72 deletions src/crypto/key_passphrase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,75 +14,5 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

import { randomString } from "../randomstring.ts";

const DEFAULT_ITERATIONS = 500000;

const DEFAULT_BITSIZE = 256;

/* eslint-disable camelcase */
interface IAuthData {
private_key_salt?: string;
private_key_iterations?: number;
private_key_bits?: number;
}
/* eslint-enable camelcase */

interface IKey {
key: Uint8Array;
salt: string;
iterations: number;
}

export function keyFromAuthData(authData: IAuthData, password: string): Promise<Uint8Array> {
if (!authData.private_key_salt || !authData.private_key_iterations) {
throw new Error("Salt and/or iterations not found: " + "this backup cannot be restored with a passphrase");
}

return deriveKey(
password,
authData.private_key_salt,
authData.private_key_iterations,
authData.private_key_bits || DEFAULT_BITSIZE,
);
}

export async function keyFromPassphrase(password: string): Promise<IKey> {
const salt = randomString(32);

const key = await deriveKey(password, salt, DEFAULT_ITERATIONS, DEFAULT_BITSIZE);

return { key, salt, iterations: DEFAULT_ITERATIONS };
}

export async function deriveKey(
password: string,
salt: string,
iterations: number,
numBits = DEFAULT_BITSIZE,
): Promise<Uint8Array> {
if (!globalThis.crypto.subtle || !TextEncoder) {
throw new Error("Password-based backup is not available on this platform");
}

const key = await globalThis.crypto.subtle.importKey(
"raw",
new TextEncoder().encode(password),
{ name: "PBKDF2" },
false,
["deriveBits"],
);

const keybits = await globalThis.crypto.subtle.deriveBits(
{
name: "PBKDF2",
salt: new TextEncoder().encode(salt),
iterations: iterations,
hash: "SHA-512",
},
key,
numBits,
);

return new Uint8Array(keybits);
}
// Re-export the key passphrase functions to avoid breaking changes
export * from "../crypto-api/key-passphrase.ts";
2 changes: 1 addition & 1 deletion src/rust-crypto/rust-crypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ import {
ImportRoomKeysOpts,
KeyBackupCheck,
KeyBackupInfo,
keyFromPassphrase,
OwnDeviceKeys,
UserVerificationStatus,
VerificationRequest,
Expand All @@ -65,7 +66,6 @@ import { Device, DeviceMap } from "../models/device.ts";
import { SECRET_STORAGE_ALGORITHM_V1_AES, ServerSideSecretStorage } from "../secret-storage.ts";
import { CrossSigningIdentity } from "./CrossSigningIdentity.ts";
import { secretStorageCanAccessSecrets, secretStorageContainsCrossSigningKeys } from "./secret-storage.ts";
import { keyFromPassphrase } from "../crypto/key_passphrase.ts";
import { encodeRecoveryKey } from "../crypto/recoverykey.ts";
import { isVerificationEvent, RustVerificationRequest, verificationMethodIdentifierToMethod } from "./verification.ts";
import { EventType, MsgType } from "../@types/event.ts";
Expand Down