Skip to content

Remove node-specific crypto bits, use Node 16's WebCrypto #2762

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

Merged
merged 11 commits into from
Oct 17, 2022
Merged
Show file tree
Hide file tree
Changes from 5 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: 0 additions & 10 deletions spec/olm-loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ limitations under the License.
*/

import { logger } from '../src/logger';
import * as utils from "../src/utils";

// try to load the olm library.
try {
Expand All @@ -26,12 +25,3 @@ try {
} catch (e) {
logger.warn("unable to run crypto tests: libolm not available");
}

// also try to set node crypto
try {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const crypto = require('crypto');
utils.setCrypto(crypto);
} catch (err) {
logger.log('nodejs was compiled without crypto support: some tests will fail');
}
9 changes: 0 additions & 9 deletions spec/unit/crypto/secrets.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,19 +23,10 @@ import { makeTestClients } from './verification/util';
import { encryptAES } from "../../../src/crypto/aes";
import { resetCrossSigningKeys, createSecretStorageKey } from "./crypto-utils";
import { logger } from '../../../src/logger';
import * as utils from "../../../src/utils";
import { ICreateClientOpts } from '../../../src/client';
import { ISecretStorageKeyInfo } from '../../../src/crypto/api';
import { DeviceInfo } from '../../../src/crypto/deviceinfo';

try {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const crypto = require('crypto');
utils.setCrypto(crypto);
} catch (err) {
logger.log('nodejs was compiled without crypto support');
}

async function makeTestClient(userInfo: { userId: string, deviceId: string}, options: Partial<ICreateClientOpts> = {}) {
const client = (new TestClient(
userInfo.userId, userInfo.deviceId, undefined, undefined, options,
Expand Down
132 changes: 17 additions & 115 deletions src/crypto/aes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,137 +14,47 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

import type { BinaryLike } from "crypto";
import { getCrypto } from '../utils';
import { decodeBase64, encodeBase64 } from './olmlib';

const subtleCrypto = (typeof window !== "undefined" && window.crypto) ?
(window.crypto.subtle || window.crypto.webkitSubtle) : null;
import { subtleCrypto, crypto, TextEncoder } from "./crypto";

// salt for HKDF, with 8 bytes of zeros
const zeroSalt = new Uint8Array(8);

export interface IEncryptedPayload {
[key: string]: any; // extensible
iv?: string;
ciphertext?: string;
mac?: string;
iv: string;
ciphertext: string;
mac: string;
}

/**
* encrypt a string in Node.js
* encrypt a string
*
* @param {string} data the plaintext to encrypt
* @param {Uint8Array} key the encryption key to use
* @param {string} name the name of the secret
* @param {string} ivStr the initialization vector to use
*/
async function encryptNode(data: string, key: Uint8Array, name: string, ivStr?: string): Promise<IEncryptedPayload> {
const crypto = getCrypto();
if (!crypto) {
throw new Error("No usable crypto implementation");
}

let iv;
if (ivStr) {
iv = decodeBase64(ivStr);
} else {
iv = crypto.randomBytes(16);

// clear bit 63 of the IV to stop us hitting the 64-bit counter boundary
// (which would mean we wouldn't be able to decrypt on Android). The loss
// of a single bit of iv is a price we have to pay.
iv[8] &= 0x7f;
}

const [aesKey, hmacKey] = deriveKeysNode(key, name);

const cipher = crypto.createCipheriv("aes-256-ctr", aesKey, iv);
const ciphertext = Buffer.concat([
cipher.update(data, "utf8"),
cipher.final(),
]);

const hmac = crypto.createHmac("sha256", hmacKey)
.update(ciphertext).digest("base64");

return {
iv: encodeBase64(iv),
ciphertext: ciphertext.toString("base64"),
mac: hmac,
};
}

/**
* decrypt a string in Node.js
*
* @param {object} data the encrypted data
* @param {string} data.ciphertext the ciphertext in base64
* @param {string} data.iv the initialization vector in base64
* @param {string} data.mac the HMAC in base64
* @param {Uint8Array} key the encryption key to use
* @param {string} name the name of the secret
*/
async function decryptNode(data: IEncryptedPayload, key: Uint8Array, name: string): Promise<string> {
const crypto = getCrypto();
if (!crypto) {
throw new Error("No usable crypto implementation");
}

const [aesKey, hmacKey] = deriveKeysNode(key, name);

const hmac = crypto.createHmac("sha256", hmacKey)
.update(Buffer.from(data.ciphertext, "base64"))
.digest("base64").replace(/=+$/g, '');

if (hmac !== data.mac.replace(/=+$/g, '')) {
throw new Error(`Error decrypting secret ${name}: bad MAC`);
}

const decipher = crypto.createDecipheriv(
"aes-256-ctr", aesKey, decodeBase64(data.iv),
);
return decipher.update(data.ciphertext, "base64", "utf8")
+ decipher.final("utf8");
}

function deriveKeysNode(key: BinaryLike, name: string): [Buffer, Buffer] {
const crypto = getCrypto();
const prk = crypto.createHmac("sha256", zeroSalt).update(key).digest();

const b = Buffer.alloc(1, 1);
const aesKey = crypto.createHmac("sha256", prk)
.update(name, "utf8").update(b).digest();
b[0] = 2;
const hmacKey = crypto.createHmac("sha256", prk)
.update(aesKey).update(name, "utf8").update(b).digest();

return [aesKey, hmacKey];
}

/**
* encrypt a string in Node.js
*
* @param {string} data the plaintext to encrypt
* @param {Uint8Array} key the encryption key to use
* @param {string} name the name of the secret
* @param {string} ivStr the initialization vector to use
*/
async function encryptBrowser(data: string, key: Uint8Array, name: string, ivStr?: string): Promise<IEncryptedPayload> {
let iv;
export async function encryptAES(
data: string,
key: Uint8Array,
name: string,
ivStr?: string,
): Promise<IEncryptedPayload> {
let iv: Uint8Array;
if (ivStr) {
iv = decodeBase64(ivStr);
} else {
iv = new Uint8Array(16);
window.crypto.getRandomValues(iv);
crypto.getRandomValues(iv);

// clear bit 63 of the IV to stop us hitting the 64-bit counter boundary
// (which would mean we wouldn't be able to decrypt on Android). The loss
// of a single bit of iv is a price we have to pay.
iv[8] &= 0x7f;
}

const [aesKey, hmacKey] = await deriveKeysBrowser(key, name);
const [aesKey, hmacKey] = await deriveKeys(key, name);
const encodedData = new TextEncoder().encode(data);

const ciphertext = await subtleCrypto.encrypt(
Expand Down Expand Up @@ -180,8 +90,8 @@ async function encryptBrowser(data: string, key: Uint8Array, name: string, ivStr
* @param {Uint8Array} key the encryption key to use
* @param {string} name the name of the secret
*/
async function decryptBrowser(data: IEncryptedPayload, key: Uint8Array, name: string): Promise<string> {
const [aesKey, hmacKey] = await deriveKeysBrowser(key, name);
export async function decryptAES(data: IEncryptedPayload, key: Uint8Array, name: string): Promise<string> {
const [aesKey, hmacKey] = await deriveKeys(key, name);

const ciphertext = decodeBase64(data.ciphertext);

Expand All @@ -207,7 +117,7 @@ async function decryptBrowser(data: IEncryptedPayload, key: Uint8Array, name: st
return new TextDecoder().decode(new Uint8Array(plaintext));
}

async function deriveKeysBrowser(key: Uint8Array, name: string): Promise<[CryptoKey, CryptoKey]> {
async function deriveKeys(key: Uint8Array, name: string): Promise<[CryptoKey, CryptoKey]> {
const hkdfkey = await subtleCrypto.importKey(
'raw',
key,
Expand Down Expand Up @@ -253,14 +163,6 @@ async function deriveKeysBrowser(key: Uint8Array, name: string): Promise<[Crypto
return Promise.all([aesProm, hmacProm]);
}

export function encryptAES(data: string, key: Uint8Array, name: string, ivStr?: string): Promise<IEncryptedPayload> {
return subtleCrypto ? encryptBrowser(data, key, name, ivStr) : encryptNode(data, key, name, ivStr);
}

export function decryptAES(data: IEncryptedPayload, key: Uint8Array, name: string): Promise<string> {
return subtleCrypto ? decryptBrowser(data, key, name) : decryptNode(data, key, name);
}

// string of zeroes, for calculating the key check
const ZERO_STR = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";

Expand Down
38 changes: 20 additions & 18 deletions src/crypto/backup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,20 @@ import { MEGOLM_ALGORITHM, verifySignature } from "./olmlib";
import { DeviceInfo } from "./deviceinfo";
import { DeviceTrustLevel } from './CrossSigning';
import { keyFromPassphrase } from './key_passphrase';
import { getCrypto, sleep } from "../utils";
import { sleep } from "../utils";
import { IndexedDBCryptoStore } from './store/indexeddb-crypto-store';
import { encodeRecoveryKey } from './recoverykey';
import { calculateKeyCheck, decryptAES, encryptAES } from './aes';
import { IAes256AuthData, ICurve25519AuthData, IKeyBackupInfo, IKeyBackupSession } from "./keybackup";
import { calculateKeyCheck, decryptAES, encryptAES, IEncryptedPayload } from './aes';
import {
Curve25519SessionData,
IAes256AuthData,
ICurve25519AuthData,
IKeyBackupInfo,
IKeyBackupSession,
} from "./keybackup";
import { UnstableValue } from "../NamespacedValue";
import { CryptoEvent, IMegolmSessionData } from "./index";
import { crypto } from "./crypto";

const KEY_BACKUP_KEYS_PER_REQUEST = 200;
const KEY_BACKUP_CHECK_RATE_LIMIT = 5000; // ms
Expand Down Expand Up @@ -677,7 +684,9 @@ export class Curve25519 implements BackupAlgorithm {
return this.publicKey.encrypt(JSON.stringify(plainText));
}

public async decryptSessions(sessions: Record<string, IKeyBackupSession>): Promise<IMegolmSessionData[]> {
public async decryptSessions(
sessions: Record<string, IKeyBackupSession<Curve25519SessionData>>,
): Promise<IMegolmSessionData[]> {
const privKey = await this.getKey();
const decryption = new global.Olm.PkDecryption();
try {
Expand Down Expand Up @@ -711,7 +720,7 @@ export class Curve25519 implements BackupAlgorithm {

public async keyMatches(key: Uint8Array): Promise<boolean> {
const decryption = new global.Olm.PkDecryption();
let pubKey;
let pubKey: string;
try {
pubKey = decryption.init_with_private_key(key);
} finally {
Expand All @@ -727,18 +736,9 @@ export class Curve25519 implements BackupAlgorithm {
}

function randomBytes(size: number): Uint8Array {
const crypto: {randomBytes: (n: number) => Uint8Array} | undefined = getCrypto() as any;
if (crypto) {
// nodejs version
return crypto.randomBytes(size);
}
if (window?.crypto) {
// browser version
const buf = new Uint8Array(size);
window.crypto.getRandomValues(buf);
return buf;
}
throw new Error("No usable crypto implementation");
const buf = new Uint8Array(size);
crypto.getRandomValues(buf);
return buf;
}

const UNSTABLE_MSC3270_NAME = new UnstableValue(null, "org.matrix.msc3270.v1.aes-hmac-sha2");
Expand Down Expand Up @@ -807,7 +807,9 @@ export class Aes256 implements BackupAlgorithm {
return encryptAES(JSON.stringify(plainText), this.key, data.session_id);
}

public async decryptSessions(sessions: Record<string, IKeyBackupSession>): Promise<IMegolmSessionData[]> {
public async decryptSessions(
sessions: Record<string, IKeyBackupSession<IEncryptedPayload>>,
): Promise<IMegolmSessionData[]> {
const keys: IMegolmSessionData[] = [];

for (const [sessionId, sessionData] of Object.entries(sessions)) {
Expand Down
31 changes: 31 additions & 0 deletions src/crypto/crypto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
Copyright 2022 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.
*/

export let crypto = global.window?.crypto;
export let subtleCrypto = global.window?.crypto?.subtle ?? global.window?.crypto?.webkitSubtle;
export let TextEncoder = global.window?.TextEncoder;

/* eslint-disable @typescript-eslint/no-var-requires */
if (!crypto) {
crypto = require("crypto").webcrypto;
}
if (!subtleCrypto) {
subtleCrypto = crypto?.subtle;
}
if (!TextEncoder) {
TextEncoder = require("util").TextEncoder;
}
/* eslint-enable @typescript-eslint/no-var-requires */
34 changes: 2 additions & 32 deletions src/crypto/key_passphrase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,7 @@ limitations under the License.
*/

import { randomString } from '../randomstring';
import { getCrypto } from '../utils';

const subtleCrypto = (typeof window !== "undefined" && window.crypto) ?
(window.crypto.subtle || window.crypto.webkitSubtle) : null;
import { subtleCrypto, TextEncoder } from "./crypto";

const DEFAULT_ITERATIONS = 500000;

Expand Down Expand Up @@ -70,26 +67,13 @@ export async function keyFromPassphrase(password: string): Promise<IKey> {
}

export async function deriveKey(
password: string,
salt: string,
iterations: number,
numBits = DEFAULT_BITSIZE,
): Promise<Uint8Array> {
return subtleCrypto
? deriveKeyBrowser(password, salt, iterations, numBits)
: deriveKeyNode(password, salt, iterations, numBits);
}

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

const key = await subtleCrypto.importKey(
Expand All @@ -113,17 +97,3 @@ async function deriveKeyBrowser(

return new Uint8Array(keybits);
}

async function deriveKeyNode(
password: string,
salt: string,
iterations: number,
numBits: number,
): Promise<Uint8Array> {
const crypto = getCrypto();
if (!crypto) {
throw new Error("No usable crypto implementation");
}

return crypto.pbkdf2Sync(password, Buffer.from(salt, 'binary'), iterations, numBits, 'sha512');
}
Loading