Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
38 changes: 36 additions & 2 deletions modules/sdk-api/src/encrypt.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,36 @@
import * as sjcl from '@bitgo/sjcl';
import { randomBytes } from 'crypto';

import { decryptV1 } from './decryptV1';
import { decryptV1, V1_MAX_ITER } from './decryptV1';
import { decryptV2, encryptV2 } from './encryptV2';

/**
* True when running in a bundled browser build. `browserify-aes` -- the AES
* polyfill webpack substitutes for `node:crypto` in browser bundles -- has no
* AES-CCM mode at all, so native v1 decrypt fails on literally every call
* there. There's no point paying for the doomed native attempt (a full
* PBKDF2 run) before falling back; go straight to SJCL.
*/
const isBrowserRuntime = typeof window !== 'undefined';

/**
* SJCL has no upper bound on `iter`, so a hostile v1 envelope could burn CPU
* running an inflated PBKDF2. Native decrypt's codec normally catches this
* before any KDF work runs; the browser path skips native entirely, so it
* needs this narrow check to preserve the same DoS protection.
*/
function assertIterWithinCap(ciphertext: string): void {
let iter: unknown;
try {
iter = JSON.parse(ciphertext)?.iter;
} catch {
return; // malformed JSON -- let sjcl.decrypt raise its own error
}
if (typeof iter === 'number' && iter > V1_MAX_ITER) {
throw new Error(`v1 decrypt: iter ${iter} exceeds cap of ${V1_MAX_ITER}`);
}
}

/**
* convert a 4 element Uint8Array to a 4 byte Number
*
Expand Down Expand Up @@ -92,12 +119,19 @@ function isIterCapViolation(err: unknown): boolean {
*
* `native` defaults to the module's `decryptV1` but is exposed as a parameter
* so tests can inject a throwing version to exercise the fallback path.
* `isBrowser` defaults to a real runtime check but is exposed so tests can
* exercise the browser-only branch under Node.
*/
export async function decryptV1WithFallback(
password: string,
ciphertext: string,
native: (pw: string, ct: string) => Promise<string> = decryptV1
native: (pw: string, ct: string) => Promise<string> = decryptV1,
isBrowser: boolean = isBrowserRuntime
): Promise<string> {
if (isBrowser) {
assertIterWithinCap(ciphertext);
return sjcl.decrypt(password, ciphertext);
}
try {
return await native(password, ciphertext);
} catch (nativeErr) {
Expand Down
37 changes: 37 additions & 0 deletions modules/sdk-api/test/unit/decryptV1.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,4 +185,41 @@ describe('decryptV1 (native, SJCL-free)', () => {
assert.ok(warnings[0].includes('SJCL fallback succeeded'));
});
});

describe('browser runtime (isBrowser = true)', () => {
it('skips native and decrypts via SJCL without warning', async () => {
const ct = await encrypt(password, plaintext, { encryptionVersion: 1 });
const neverCalled = async (): Promise<string> => {
throw new Error('native should not be attempted in the browser');
};
// eslint-disable-next-line no-console
const originalWarn = console.warn;
const warnings: string[] = [];
// eslint-disable-next-line no-console
console.warn = (...args: unknown[]) => {
warnings.push(args.join(' '));
};
try {
const result = await decryptV1WithFallback(password, ct, neverCalled, true);
assert.strictEqual(result, plaintext);
assert.deepStrictEqual(warnings, []);
} finally {
// eslint-disable-next-line no-console
console.warn = originalWarn;
}
});

it('still enforces the iter cap before running PBKDF2', async () => {
const envelope = JSON.parse(await encrypt(password, plaintext, { encryptionVersion: 1 }));
envelope.iter = V1_MAX_ITER + 1;
const start = Date.now();
await assert.rejects(() => decryptV1WithFallback(password, JSON.stringify(envelope), decryptV1, true), /iter/);
assert.ok(Date.now() - start < 100, 'must reject before any KDF work');
});

it('rejects wrong password via SJCL auth failure', async () => {
const ct = await encrypt(password, plaintext, { encryptionVersion: 1 });
await assert.rejects(() => decryptV1WithFallback('wrongPassword', ct, decryptV1, true));
});
});
});
Loading