2023-10-30 16:24:28 +00:00
|
|
|
// Copyright 2020 Signal Messenger, LLC
|
|
|
|
// SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
|
2024-05-20 19:29:20 +00:00
|
|
|
import { unlinkSync, createReadStream, createWriteStream } from 'fs';
|
2024-02-05 23:17:28 +00:00
|
|
|
import { open } from 'fs/promises';
|
2024-07-11 19:44:09 +00:00
|
|
|
import { createCipheriv, createHash, createHmac, randomBytes } from 'crypto';
|
|
|
|
import type { Hash } from 'crypto';
|
2024-05-20 19:29:20 +00:00
|
|
|
import { PassThrough, Transform, type Writable, Readable } from 'stream';
|
2023-10-30 16:24:28 +00:00
|
|
|
import { pipeline } from 'stream/promises';
|
2024-02-05 23:17:28 +00:00
|
|
|
import { ensureFile } from 'fs-extra';
|
2023-10-30 16:24:28 +00:00
|
|
|
import * as log from './logging/log';
|
2024-07-11 19:44:09 +00:00
|
|
|
import {
|
|
|
|
HashType,
|
|
|
|
CipherType,
|
|
|
|
IV_LENGTH,
|
|
|
|
KEY_LENGTH,
|
|
|
|
MAC_LENGTH,
|
|
|
|
} from './types/Crypto';
|
2024-04-15 20:54:21 +00:00
|
|
|
import { constantTimeEqual } from './Crypto';
|
2024-07-11 19:44:09 +00:00
|
|
|
import { createName, getRelativePath } from './util/attachmentPath';
|
2024-04-15 20:54:21 +00:00
|
|
|
import { appendPaddingStream, logPadSize } from './util/logPadding';
|
|
|
|
import { prependStream } from './util/prependStream';
|
|
|
|
import { appendMacStream } from './util/appendMacStream';
|
2024-07-20 02:17:02 +00:00
|
|
|
import { finalStream } from './util/finalStream';
|
2024-07-11 19:44:09 +00:00
|
|
|
import { getIvAndDecipher } from './util/getIvAndDecipher';
|
|
|
|
import { getMacAndUpdateHmac } from './util/getMacAndUpdateHmac';
|
|
|
|
import { trimPadding } from './util/trimPadding';
|
2024-02-05 23:17:28 +00:00
|
|
|
import { strictAssert } from './util/assert';
|
|
|
|
import * as Errors from './types/errors';
|
2024-05-02 17:11:34 +00:00
|
|
|
import { isNotNil } from './util/isNotNil';
|
2024-05-29 01:12:14 +00:00
|
|
|
import { missingCaseError } from './util/missingCaseError';
|
2024-07-11 19:44:09 +00:00
|
|
|
import { getEnvironment, Environment } from './environment';
|
2024-07-16 20:39:56 +00:00
|
|
|
import { toBase64 } from './Bytes';
|
2023-10-30 16:24:28 +00:00
|
|
|
|
|
|
|
// This file was split from ts/Crypto.ts because it pulls things in from node, and
|
|
|
|
// too many things pull in Crypto.ts, so it broke storybook.
|
|
|
|
|
2024-07-11 19:44:09 +00:00
|
|
|
const DIGEST_LENGTH = MAC_LENGTH;
|
2024-02-05 23:17:28 +00:00
|
|
|
const HEX_DIGEST_LENGTH = DIGEST_LENGTH * 2;
|
2024-07-11 19:44:09 +00:00
|
|
|
const ATTACHMENT_MAC_LENGTH = MAC_LENGTH;
|
2024-02-05 23:17:28 +00:00
|
|
|
|
2024-07-16 20:39:56 +00:00
|
|
|
export class ReencryptedDigestMismatchError extends Error {}
|
2024-05-29 23:46:43 +00:00
|
|
|
|
2024-02-05 23:17:28 +00:00
|
|
|
/** @private */
|
2024-07-11 19:44:09 +00:00
|
|
|
export const KEY_SET_LENGTH = KEY_LENGTH + MAC_LENGTH;
|
2024-02-05 23:17:28 +00:00
|
|
|
|
|
|
|
export function _generateAttachmentIv(): Uint8Array {
|
|
|
|
return randomBytes(IV_LENGTH);
|
|
|
|
}
|
2023-10-30 16:24:28 +00:00
|
|
|
|
2024-05-29 23:46:43 +00:00
|
|
|
export function generateAttachmentKeys(): Uint8Array {
|
|
|
|
return randomBytes(KEY_SET_LENGTH);
|
|
|
|
}
|
|
|
|
|
2023-10-30 16:24:28 +00:00
|
|
|
export type EncryptedAttachmentV2 = {
|
|
|
|
digest: Uint8Array;
|
2024-05-29 01:12:14 +00:00
|
|
|
iv: Uint8Array;
|
2023-11-17 20:02:02 +00:00
|
|
|
plaintextHash: string;
|
2024-05-20 19:29:20 +00:00
|
|
|
ciphertextSize: number;
|
2023-11-17 20:02:02 +00:00
|
|
|
};
|
|
|
|
|
2024-07-11 19:44:09 +00:00
|
|
|
export type ReencryptedAttachmentV2 = {
|
|
|
|
path: string;
|
2024-07-16 20:39:56 +00:00
|
|
|
iv: string;
|
2024-07-11 19:44:09 +00:00
|
|
|
plaintextHash: string;
|
2024-07-16 20:39:56 +00:00
|
|
|
localKey: string;
|
|
|
|
version: 2;
|
2024-07-11 19:44:09 +00:00
|
|
|
};
|
|
|
|
|
2023-11-17 20:02:02 +00:00
|
|
|
export type DecryptedAttachmentV2 = {
|
|
|
|
path: string;
|
2024-05-29 01:12:14 +00:00
|
|
|
iv: Uint8Array;
|
2023-11-17 20:02:02 +00:00
|
|
|
plaintextHash: string;
|
2023-10-30 16:24:28 +00:00
|
|
|
};
|
|
|
|
|
2024-05-20 19:29:20 +00:00
|
|
|
export type PlaintextSourceType =
|
|
|
|
| { data: Uint8Array }
|
2024-07-11 19:44:09 +00:00
|
|
|
| { stream: Readable }
|
2024-05-20 19:29:20 +00:00
|
|
|
| { absolutePath: string };
|
|
|
|
|
2024-05-29 01:12:14 +00:00
|
|
|
export type HardcodedIVForEncryptionType =
|
|
|
|
| {
|
|
|
|
reason: 'test';
|
|
|
|
iv: Uint8Array;
|
|
|
|
}
|
|
|
|
| {
|
|
|
|
reason: 'reencrypting-for-backup';
|
|
|
|
iv: Uint8Array;
|
|
|
|
digestToMatch: Uint8Array;
|
|
|
|
};
|
|
|
|
|
2024-05-15 14:55:20 +00:00
|
|
|
type EncryptAttachmentV2PropsType = {
|
2024-05-20 19:29:20 +00:00
|
|
|
plaintext: PlaintextSourceType;
|
2023-10-30 16:24:28 +00:00
|
|
|
keys: Readonly<Uint8Array>;
|
2024-05-29 01:12:14 +00:00
|
|
|
dangerousIv?: HardcodedIVForEncryptionType;
|
2024-05-02 17:11:34 +00:00
|
|
|
dangerousTestOnlySkipPadding?: boolean;
|
2024-07-11 19:44:09 +00:00
|
|
|
getAbsoluteAttachmentPath: (relativePath: string) => string;
|
2024-05-15 14:55:20 +00:00
|
|
|
};
|
2023-10-30 16:24:28 +00:00
|
|
|
|
2024-05-15 14:55:20 +00:00
|
|
|
export async function encryptAttachmentV2ToDisk(
|
|
|
|
args: EncryptAttachmentV2PropsType
|
|
|
|
): Promise<EncryptedAttachmentV2 & { path: string }> {
|
2023-10-30 16:24:28 +00:00
|
|
|
// Create random output file
|
|
|
|
const relativeTargetPath = getRelativePath(createName());
|
2024-07-11 19:44:09 +00:00
|
|
|
const absoluteTargetPath = args.getAbsoluteAttachmentPath(relativeTargetPath);
|
2023-10-30 16:24:28 +00:00
|
|
|
|
2024-05-20 19:29:20 +00:00
|
|
|
await ensureFile(absoluteTargetPath);
|
|
|
|
|
2024-05-15 14:55:20 +00:00
|
|
|
let encryptResult: EncryptedAttachmentV2;
|
|
|
|
|
|
|
|
try {
|
|
|
|
encryptResult = await encryptAttachmentV2({
|
|
|
|
...args,
|
2024-05-20 19:29:20 +00:00
|
|
|
sink: createWriteStream(absoluteTargetPath),
|
2024-05-15 14:55:20 +00:00
|
|
|
});
|
|
|
|
} catch (error) {
|
|
|
|
safeUnlinkSync(absoluteTargetPath);
|
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
...encryptResult,
|
|
|
|
path: relativeTargetPath,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
export async function encryptAttachmentV2({
|
|
|
|
keys,
|
2024-05-20 19:29:20 +00:00
|
|
|
plaintext,
|
2024-05-29 01:12:14 +00:00
|
|
|
dangerousIv,
|
2024-05-20 19:29:20 +00:00
|
|
|
dangerousTestOnlySkipPadding,
|
2024-05-15 14:55:20 +00:00
|
|
|
sink,
|
|
|
|
}: EncryptAttachmentV2PropsType & {
|
|
|
|
sink?: Writable;
|
|
|
|
}): Promise<EncryptedAttachmentV2> {
|
|
|
|
const logId = 'encryptAttachmentV2';
|
|
|
|
|
2024-02-05 23:17:28 +00:00
|
|
|
const { aesKey, macKey } = splitKeys(keys);
|
2023-10-30 16:24:28 +00:00
|
|
|
|
2024-05-29 01:12:14 +00:00
|
|
|
if (dangerousIv) {
|
|
|
|
if (dangerousIv.reason === 'test') {
|
2024-07-11 19:44:09 +00:00
|
|
|
if (getEnvironment() !== Environment.Test) {
|
2024-05-29 01:12:14 +00:00
|
|
|
throw new Error(
|
|
|
|
`${logId}: Used dangerousIv with reason test outside tests!`
|
|
|
|
);
|
|
|
|
}
|
|
|
|
} else if (dangerousIv.reason === 'reencrypting-for-backup') {
|
|
|
|
strictAssert(
|
|
|
|
dangerousIv.digestToMatch.byteLength === DIGEST_LENGTH,
|
|
|
|
`${logId}: Must provide valid digest to match if providing iv for re-encryption`
|
|
|
|
);
|
|
|
|
log.info(
|
|
|
|
`${logId}: using hardcoded iv because we are re-encrypting for backup`
|
|
|
|
);
|
|
|
|
} else {
|
|
|
|
throw missingCaseError(dangerousIv);
|
|
|
|
}
|
2023-10-30 16:24:28 +00:00
|
|
|
}
|
2024-05-29 01:12:14 +00:00
|
|
|
|
2024-07-11 19:44:09 +00:00
|
|
|
if (dangerousTestOnlySkipPadding && getEnvironment() !== Environment.Test) {
|
2024-05-02 17:11:34 +00:00
|
|
|
throw new Error(
|
|
|
|
`${logId}: Used dangerousTestOnlySkipPadding outside tests!`
|
|
|
|
);
|
|
|
|
}
|
2024-05-29 01:12:14 +00:00
|
|
|
|
|
|
|
const iv = dangerousIv?.iv || _generateAttachmentIv();
|
2024-02-05 23:17:28 +00:00
|
|
|
const plaintextHash = createHash(HashType.size256);
|
|
|
|
const digest = createHash(HashType.size256);
|
2023-10-30 16:24:28 +00:00
|
|
|
|
2024-05-20 19:29:20 +00:00
|
|
|
let ciphertextSize: number | undefined;
|
2024-07-11 19:44:09 +00:00
|
|
|
let mac: Uint8Array | undefined;
|
2024-05-20 19:29:20 +00:00
|
|
|
|
2023-10-30 16:24:28 +00:00
|
|
|
try {
|
2024-07-11 19:44:09 +00:00
|
|
|
let source: Readable;
|
|
|
|
if ('data' in plaintext) {
|
|
|
|
source = Readable.from([Buffer.from(plaintext.data)]);
|
|
|
|
} else if ('stream' in plaintext) {
|
|
|
|
source = plaintext.stream;
|
|
|
|
} else {
|
|
|
|
source = createReadStream(plaintext.absolutePath);
|
|
|
|
}
|
2023-10-30 16:24:28 +00:00
|
|
|
|
2024-02-05 23:17:28 +00:00
|
|
|
await pipeline(
|
2024-05-02 17:11:34 +00:00
|
|
|
[
|
2024-05-20 19:29:20 +00:00
|
|
|
source,
|
2024-05-02 17:11:34 +00:00
|
|
|
peekAndUpdateHash(plaintextHash),
|
|
|
|
dangerousTestOnlySkipPadding ? undefined : appendPaddingStream(),
|
|
|
|
createCipheriv(CipherType.AES256CBC, aesKey, iv),
|
|
|
|
prependIv(iv),
|
2024-07-11 19:44:09 +00:00
|
|
|
appendMacStream(macKey, macValue => {
|
|
|
|
mac = macValue;
|
|
|
|
}),
|
2024-05-02 17:11:34 +00:00
|
|
|
peekAndUpdateHash(digest),
|
2024-05-20 19:29:20 +00:00
|
|
|
measureSize(size => {
|
|
|
|
ciphertextSize = size;
|
|
|
|
}),
|
2024-05-15 14:55:20 +00:00
|
|
|
sink ?? new PassThrough().resume(),
|
2024-05-02 17:11:34 +00:00
|
|
|
].filter(isNotNil)
|
2024-02-05 23:17:28 +00:00
|
|
|
);
|
|
|
|
} catch (error) {
|
|
|
|
log.error(
|
|
|
|
`${logId}: Failed to encrypt attachment`,
|
|
|
|
Errors.toLogFormat(error)
|
|
|
|
);
|
2023-10-30 16:24:28 +00:00
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
|
2024-02-05 23:17:28 +00:00
|
|
|
const ourPlaintextHash = plaintextHash.digest('hex');
|
|
|
|
const ourDigest = digest.digest();
|
2023-11-17 20:02:02 +00:00
|
|
|
|
2024-02-05 23:17:28 +00:00
|
|
|
strictAssert(
|
|
|
|
ourPlaintextHash.length === HEX_DIGEST_LENGTH,
|
|
|
|
`${logId}: Failed to generate plaintext hash!`
|
|
|
|
);
|
2023-10-30 16:24:28 +00:00
|
|
|
|
2024-02-05 23:17:28 +00:00
|
|
|
strictAssert(
|
|
|
|
ourDigest.byteLength === DIGEST_LENGTH,
|
|
|
|
`${logId}: Failed to generate ourDigest!`
|
|
|
|
);
|
2023-10-30 16:24:28 +00:00
|
|
|
|
2024-05-20 19:29:20 +00:00
|
|
|
strictAssert(ciphertextSize != null, 'Failed to measure ciphertext size!');
|
2024-07-11 19:44:09 +00:00
|
|
|
strictAssert(mac != null, 'Failed to compute mac!');
|
2024-05-20 19:29:20 +00:00
|
|
|
|
2024-05-29 01:12:14 +00:00
|
|
|
if (dangerousIv?.reason === 'reencrypting-for-backup') {
|
|
|
|
if (!constantTimeEqual(ourDigest, dangerousIv.digestToMatch)) {
|
2024-07-16 20:39:56 +00:00
|
|
|
throw new ReencryptedDigestMismatchError(
|
2024-05-29 01:12:14 +00:00
|
|
|
`${logId}: iv was hardcoded for backup re-encryption, but digest does not match`
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
2024-05-29 23:46:43 +00:00
|
|
|
|
2023-10-30 16:24:28 +00:00
|
|
|
return {
|
|
|
|
digest: ourDigest,
|
2024-05-29 01:12:14 +00:00
|
|
|
iv,
|
2024-02-05 23:17:28 +00:00
|
|
|
plaintextHash: ourPlaintextHash,
|
2024-05-20 19:29:20 +00:00
|
|
|
ciphertextSize,
|
2023-10-30 16:24:28 +00:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2024-07-11 19:44:09 +00:00
|
|
|
type DecryptAttachmentToSinkOptionsType = Readonly<
|
|
|
|
{
|
|
|
|
ciphertextPath: string;
|
|
|
|
idForLogging: string;
|
|
|
|
size: number;
|
|
|
|
outerEncryption?: {
|
|
|
|
aesKey: Readonly<Uint8Array>;
|
|
|
|
macKey: Readonly<Uint8Array>;
|
|
|
|
};
|
|
|
|
} & (
|
|
|
|
| {
|
2024-07-16 20:39:56 +00:00
|
|
|
type: 'standard';
|
2024-07-11 19:44:09 +00:00
|
|
|
theirDigest: Readonly<Uint8Array>;
|
|
|
|
}
|
|
|
|
| {
|
2024-07-16 20:39:56 +00:00
|
|
|
// No need to check integrity for locally reencrypted attachments, or for backup
|
|
|
|
// thumbnails (since we created it)
|
|
|
|
type: 'local' | 'backupThumbnail';
|
2024-07-11 19:44:09 +00:00
|
|
|
theirDigest?: undefined;
|
|
|
|
}
|
|
|
|
) &
|
|
|
|
(
|
|
|
|
| {
|
|
|
|
aesKey: Readonly<Uint8Array>;
|
|
|
|
macKey: Readonly<Uint8Array>;
|
|
|
|
}
|
|
|
|
| {
|
|
|
|
// The format used by most stored attachments
|
|
|
|
keysBase64: string;
|
|
|
|
}
|
|
|
|
)
|
|
|
|
>;
|
|
|
|
|
|
|
|
export type DecryptAttachmentOptionsType = DecryptAttachmentToSinkOptionsType &
|
|
|
|
Readonly<{
|
|
|
|
getAbsoluteAttachmentPath: (relativePath: string) => string;
|
|
|
|
}>;
|
2024-05-02 17:11:34 +00:00
|
|
|
|
|
|
|
export async function decryptAttachmentV2(
|
|
|
|
options: DecryptAttachmentOptionsType
|
|
|
|
): Promise<DecryptedAttachmentV2> {
|
2024-07-11 19:44:09 +00:00
|
|
|
const logId = `decryptAttachmentV2(${options.idForLogging})`;
|
2023-10-30 16:24:28 +00:00
|
|
|
|
|
|
|
// Create random output file
|
|
|
|
const relativeTargetPath = getRelativePath(createName());
|
|
|
|
const absoluteTargetPath =
|
2024-07-11 19:44:09 +00:00
|
|
|
options.getAbsoluteAttachmentPath(relativeTargetPath);
|
|
|
|
|
|
|
|
let writeFd;
|
|
|
|
try {
|
|
|
|
try {
|
|
|
|
await ensureFile(absoluteTargetPath);
|
|
|
|
writeFd = await open(absoluteTargetPath, 'w');
|
|
|
|
} catch (cause) {
|
|
|
|
throw new Error(`${logId}: Failed to create write path`, { cause });
|
|
|
|
}
|
|
|
|
|
|
|
|
const result = await decryptAttachmentV2ToSink(
|
|
|
|
options,
|
|
|
|
writeFd.createWriteStream()
|
|
|
|
);
|
|
|
|
|
|
|
|
return {
|
|
|
|
...result,
|
|
|
|
path: relativeTargetPath,
|
|
|
|
};
|
|
|
|
} catch (error) {
|
|
|
|
log.error(
|
|
|
|
`${logId}: Failed to decrypt attachment to disk`,
|
|
|
|
Errors.toLogFormat(error)
|
|
|
|
);
|
|
|
|
safeUnlinkSync(absoluteTargetPath);
|
|
|
|
throw error;
|
|
|
|
} finally {
|
|
|
|
await writeFd?.close();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function decryptAttachmentV2ToSink(
|
|
|
|
options: DecryptAttachmentToSinkOptionsType,
|
|
|
|
sink: Writable
|
|
|
|
): Promise<Omit<DecryptedAttachmentV2, 'path'>> {
|
|
|
|
const { idForLogging, ciphertextPath, outerEncryption } = options;
|
|
|
|
|
|
|
|
let aesKey: Uint8Array;
|
|
|
|
let macKey: Uint8Array;
|
|
|
|
|
|
|
|
if ('aesKey' in options) {
|
|
|
|
({ aesKey, macKey } = options);
|
|
|
|
} else {
|
|
|
|
const { keysBase64 } = options;
|
|
|
|
const keys = Buffer.from(keysBase64, 'base64');
|
|
|
|
|
|
|
|
({ aesKey, macKey } = splitKeys(keys));
|
|
|
|
}
|
|
|
|
|
|
|
|
const logId = `decryptAttachmentV2(${idForLogging})`;
|
2023-10-30 16:24:28 +00:00
|
|
|
|
2024-02-05 23:17:28 +00:00
|
|
|
const digest = createHash(HashType.size256);
|
|
|
|
const hmac = createHmac(HashType.size256, macKey);
|
|
|
|
const plaintextHash = createHash(HashType.size256);
|
2024-05-02 17:11:34 +00:00
|
|
|
let theirMac: Uint8Array | undefined;
|
|
|
|
|
|
|
|
// When downloading from backup there is an outer encryption layer; in that case we
|
|
|
|
// need to decrypt the outer layer and check its MAC
|
|
|
|
let theirOuterMac: Uint8Array | undefined;
|
|
|
|
const outerHmac = outerEncryption
|
|
|
|
? createHmac(HashType.size256, outerEncryption.macKey)
|
|
|
|
: undefined;
|
|
|
|
|
|
|
|
const maybeOuterEncryptionGetIvAndDecipher = outerEncryption
|
|
|
|
? getIvAndDecipher(outerEncryption.aesKey)
|
|
|
|
: undefined;
|
|
|
|
|
|
|
|
const maybeOuterEncryptionGetMacAndUpdateMac = outerHmac
|
|
|
|
? getMacAndUpdateHmac(outerHmac, theirOuterMacValue => {
|
|
|
|
theirOuterMac = theirOuterMacValue;
|
|
|
|
})
|
|
|
|
: undefined;
|
2023-10-30 16:24:28 +00:00
|
|
|
|
2024-02-05 23:17:28 +00:00
|
|
|
let readFd;
|
2024-05-29 01:12:14 +00:00
|
|
|
let iv: Uint8Array | undefined;
|
2023-10-30 16:24:28 +00:00
|
|
|
try {
|
|
|
|
try {
|
2024-02-05 23:17:28 +00:00
|
|
|
readFd = await open(ciphertextPath, 'r');
|
|
|
|
} catch (cause) {
|
|
|
|
throw new Error(`${logId}: Read path doesn't exist`, { cause });
|
2023-10-30 16:24:28 +00:00
|
|
|
}
|
|
|
|
|
2024-02-05 23:17:28 +00:00
|
|
|
await pipeline(
|
2024-05-02 17:11:34 +00:00
|
|
|
[
|
|
|
|
readFd.createReadStream(),
|
|
|
|
maybeOuterEncryptionGetMacAndUpdateMac,
|
|
|
|
maybeOuterEncryptionGetIvAndDecipher,
|
|
|
|
peekAndUpdateHash(digest),
|
|
|
|
getMacAndUpdateHmac(hmac, theirMacValue => {
|
|
|
|
theirMac = theirMacValue;
|
|
|
|
}),
|
2024-05-29 01:12:14 +00:00
|
|
|
getIvAndDecipher(aesKey, theirIv => {
|
|
|
|
iv = theirIv;
|
|
|
|
}),
|
2024-05-02 17:11:34 +00:00
|
|
|
trimPadding(options.size),
|
|
|
|
peekAndUpdateHash(plaintextHash),
|
2024-07-20 02:17:02 +00:00
|
|
|
finalStream(() => {
|
|
|
|
const ourMac = hmac.digest();
|
|
|
|
const ourDigest = digest.digest();
|
|
|
|
|
|
|
|
strictAssert(
|
|
|
|
ourMac.byteLength === ATTACHMENT_MAC_LENGTH,
|
|
|
|
`${logId}: Failed to generate ourMac!`
|
|
|
|
);
|
|
|
|
strictAssert(
|
|
|
|
theirMac != null && theirMac.byteLength === ATTACHMENT_MAC_LENGTH,
|
|
|
|
`${logId}: Failed to find theirMac!`
|
|
|
|
);
|
|
|
|
strictAssert(
|
|
|
|
ourDigest.byteLength === DIGEST_LENGTH,
|
|
|
|
`${logId}: Failed to generate ourDigest!`
|
|
|
|
);
|
|
|
|
|
|
|
|
if (!constantTimeEqual(ourMac, theirMac)) {
|
|
|
|
throw new Error(`${logId}: Bad MAC`);
|
|
|
|
}
|
|
|
|
|
|
|
|
const { type } = options;
|
|
|
|
switch (type) {
|
|
|
|
case 'local':
|
|
|
|
case 'backupThumbnail':
|
2024-07-23 14:19:32 +00:00
|
|
|
// Skip digest check
|
2024-07-20 02:17:02 +00:00
|
|
|
break;
|
|
|
|
case 'standard':
|
|
|
|
if (!constantTimeEqual(ourDigest, options.theirDigest)) {
|
|
|
|
throw new Error(`${logId}: Bad digest`);
|
|
|
|
}
|
|
|
|
break;
|
|
|
|
default:
|
|
|
|
throw missingCaseError(type);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!outerEncryption) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
strictAssert(outerHmac, 'outerHmac must exist');
|
|
|
|
|
|
|
|
const ourOuterMac = outerHmac.digest();
|
|
|
|
strictAssert(
|
|
|
|
ourOuterMac.byteLength === ATTACHMENT_MAC_LENGTH,
|
|
|
|
`${logId}: Failed to generate ourOuterMac!`
|
|
|
|
);
|
|
|
|
strictAssert(
|
|
|
|
theirOuterMac != null &&
|
|
|
|
theirOuterMac.byteLength === ATTACHMENT_MAC_LENGTH,
|
|
|
|
`${logId}: Failed to find theirOuterMac!`
|
|
|
|
);
|
|
|
|
|
|
|
|
if (!constantTimeEqual(ourOuterMac, theirOuterMac)) {
|
|
|
|
throw new Error(`${logId}: Bad outer encryption MAC`);
|
|
|
|
}
|
|
|
|
}),
|
2024-07-11 19:44:09 +00:00
|
|
|
sink,
|
2024-05-02 17:11:34 +00:00
|
|
|
].filter(isNotNil)
|
2024-02-05 23:17:28 +00:00
|
|
|
);
|
|
|
|
} catch (error) {
|
2024-07-11 19:44:09 +00:00
|
|
|
// These errors happen when canceling fetch from `attachment://` urls,
|
|
|
|
// ignore them to avoid noise in the logs.
|
|
|
|
if (error.name === 'AbortError') {
|
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
|
2024-02-05 23:17:28 +00:00
|
|
|
log.error(
|
|
|
|
`${logId}: Failed to decrypt attachment`,
|
|
|
|
Errors.toLogFormat(error)
|
|
|
|
);
|
2023-10-30 16:24:28 +00:00
|
|
|
throw error;
|
2024-02-05 23:17:28 +00:00
|
|
|
} finally {
|
2024-07-11 19:44:09 +00:00
|
|
|
await readFd?.close();
|
2023-10-30 16:24:28 +00:00
|
|
|
}
|
|
|
|
|
2024-02-05 23:17:28 +00:00
|
|
|
const ourPlaintextHash = plaintextHash.digest('hex');
|
|
|
|
strictAssert(
|
|
|
|
ourPlaintextHash.length === HEX_DIGEST_LENGTH,
|
|
|
|
`${logId}: Failed to generate file hash!`
|
|
|
|
);
|
|
|
|
|
2024-05-29 01:12:14 +00:00
|
|
|
strictAssert(
|
|
|
|
iv != null && iv.byteLength === IV_LENGTH,
|
|
|
|
`${logId}: failed to find their iv`
|
|
|
|
);
|
|
|
|
|
2023-11-17 20:02:02 +00:00
|
|
|
return {
|
2024-05-29 01:12:14 +00:00
|
|
|
iv,
|
2024-02-05 23:17:28 +00:00
|
|
|
plaintextHash: ourPlaintextHash,
|
2023-11-17 20:02:02 +00:00
|
|
|
};
|
2023-10-30 16:24:28 +00:00
|
|
|
}
|
|
|
|
|
2024-07-16 20:39:56 +00:00
|
|
|
export async function decryptAndReencryptLocally(
|
2024-07-11 19:44:09 +00:00
|
|
|
options: DecryptAttachmentOptionsType
|
|
|
|
): Promise<ReencryptedAttachmentV2> {
|
|
|
|
const { idForLogging } = options;
|
|
|
|
|
|
|
|
const logId = `reencryptAttachmentV2(${idForLogging})`;
|
|
|
|
|
|
|
|
// Create random output file
|
|
|
|
const relativeTargetPath = getRelativePath(createName());
|
|
|
|
const absoluteTargetPath =
|
|
|
|
options.getAbsoluteAttachmentPath(relativeTargetPath);
|
|
|
|
|
|
|
|
let writeFd;
|
|
|
|
try {
|
|
|
|
try {
|
|
|
|
await ensureFile(absoluteTargetPath);
|
|
|
|
writeFd = await open(absoluteTargetPath, 'w');
|
|
|
|
} catch (cause) {
|
|
|
|
throw new Error(`${logId}: Failed to create write path`, { cause });
|
|
|
|
}
|
|
|
|
|
|
|
|
const keys = generateKeys();
|
|
|
|
|
|
|
|
const passthrough = new PassThrough();
|
|
|
|
const [result] = await Promise.all([
|
|
|
|
decryptAttachmentV2ToSink(options, passthrough),
|
|
|
|
await encryptAttachmentV2({
|
|
|
|
keys,
|
|
|
|
plaintext: {
|
|
|
|
stream: passthrough,
|
|
|
|
},
|
|
|
|
sink: createWriteStream(absoluteTargetPath),
|
|
|
|
getAbsoluteAttachmentPath: options.getAbsoluteAttachmentPath,
|
|
|
|
}),
|
|
|
|
]);
|
|
|
|
|
|
|
|
return {
|
|
|
|
...result,
|
2024-07-16 20:39:56 +00:00
|
|
|
localKey: toBase64(keys),
|
|
|
|
iv: toBase64(result.iv),
|
2024-07-11 19:44:09 +00:00
|
|
|
path: relativeTargetPath,
|
2024-07-16 20:39:56 +00:00
|
|
|
version: 2,
|
2024-07-11 19:44:09 +00:00
|
|
|
};
|
|
|
|
} catch (error) {
|
|
|
|
log.error(
|
|
|
|
`${logId}: Failed to decrypt attachment`,
|
|
|
|
Errors.toLogFormat(error)
|
|
|
|
);
|
|
|
|
safeUnlinkSync(absoluteTargetPath);
|
|
|
|
throw error;
|
|
|
|
} finally {
|
|
|
|
await writeFd?.close();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-02-05 23:17:28 +00:00
|
|
|
/**
|
|
|
|
* Splits the keys into aes and mac keys.
|
|
|
|
*/
|
2024-05-02 17:11:34 +00:00
|
|
|
|
|
|
|
type AttachmentEncryptionKeysType = {
|
|
|
|
aesKey: Uint8Array;
|
|
|
|
macKey: Uint8Array;
|
|
|
|
};
|
|
|
|
export function splitKeys(keys: Uint8Array): AttachmentEncryptionKeysType {
|
2024-02-05 23:17:28 +00:00
|
|
|
strictAssert(
|
|
|
|
keys.byteLength === KEY_SET_LENGTH,
|
|
|
|
`attachment keys must be ${KEY_SET_LENGTH} bytes, got ${keys.byteLength}`
|
|
|
|
);
|
|
|
|
const aesKey = keys.subarray(0, KEY_LENGTH);
|
|
|
|
const macKey = keys.subarray(KEY_LENGTH, KEY_SET_LENGTH);
|
|
|
|
return { aesKey, macKey };
|
2023-10-30 16:24:28 +00:00
|
|
|
}
|
|
|
|
|
2024-07-11 19:44:09 +00:00
|
|
|
export function generateKeys(): Uint8Array {
|
|
|
|
return randomBytes(KEY_SET_LENGTH);
|
|
|
|
}
|
|
|
|
|
2024-02-05 23:17:28 +00:00
|
|
|
/**
|
|
|
|
* Updates a hash of the stream without modifying it.
|
|
|
|
*/
|
|
|
|
function peekAndUpdateHash(hash: Hash) {
|
|
|
|
return new Transform({
|
|
|
|
transform(chunk, _encoding, callback) {
|
|
|
|
try {
|
|
|
|
hash.update(chunk);
|
|
|
|
callback(null, chunk);
|
|
|
|
} catch (error) {
|
|
|
|
callback(error);
|
2023-10-30 16:24:28 +00:00
|
|
|
}
|
2024-02-05 23:17:28 +00:00
|
|
|
},
|
|
|
|
});
|
2023-10-30 16:24:28 +00:00
|
|
|
}
|
|
|
|
|
2024-05-20 19:29:20 +00:00
|
|
|
export function measureSize(onComplete: (size: number) => void): Transform {
|
|
|
|
let totalBytes = 0;
|
|
|
|
const passthrough = new PassThrough();
|
|
|
|
passthrough.on('data', chunk => {
|
|
|
|
totalBytes += chunk.length;
|
|
|
|
});
|
|
|
|
passthrough.on('end', () => {
|
|
|
|
onComplete(totalBytes);
|
|
|
|
});
|
|
|
|
return passthrough;
|
|
|
|
}
|
|
|
|
|
2024-05-02 17:11:34 +00:00
|
|
|
export function getAttachmentCiphertextLength(plaintextLength: number): number {
|
|
|
|
const paddedPlaintextSize = logPadSize(plaintextLength);
|
|
|
|
|
|
|
|
return (
|
|
|
|
IV_LENGTH +
|
|
|
|
getAesCbcCiphertextLength(paddedPlaintextSize) +
|
|
|
|
ATTACHMENT_MAC_LENGTH
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
export function getAesCbcCiphertextLength(plaintextLength: number): number {
|
|
|
|
const AES_CBC_BLOCK_SIZE = 16;
|
2024-02-05 23:17:28 +00:00
|
|
|
return (
|
2024-05-02 17:11:34 +00:00
|
|
|
(1 + Math.floor(plaintextLength / AES_CBC_BLOCK_SIZE)) * AES_CBC_BLOCK_SIZE
|
2024-02-05 23:17:28 +00:00
|
|
|
);
|
2023-10-30 16:24:28 +00:00
|
|
|
}
|
|
|
|
|
2024-02-05 23:17:28 +00:00
|
|
|
/**
|
|
|
|
* Prepends the iv to the stream.
|
|
|
|
*/
|
|
|
|
function prependIv(iv: Uint8Array) {
|
|
|
|
strictAssert(
|
|
|
|
iv.byteLength === IV_LENGTH,
|
|
|
|
`prependIv: iv should be ${IV_LENGTH} bytes, got ${iv.byteLength} bytes`
|
|
|
|
);
|
2024-04-15 20:54:21 +00:00
|
|
|
return prependStream(iv);
|
2023-10-30 16:24:28 +00:00
|
|
|
}
|
2024-01-02 20:14:11 +00:00
|
|
|
|
|
|
|
export function getPlaintextHashForInMemoryAttachment(
|
|
|
|
data: Uint8Array
|
|
|
|
): string {
|
2024-02-05 23:17:28 +00:00
|
|
|
return createHash(HashType.size256).update(data).digest('hex');
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Unlinks a file without throwing an error if it doesn't exist.
|
|
|
|
* Throws an error if it fails to unlink for any other reason.
|
|
|
|
*/
|
|
|
|
export function safeUnlinkSync(filePath: string): void {
|
|
|
|
try {
|
|
|
|
unlinkSync(filePath);
|
|
|
|
} catch (error) {
|
|
|
|
// Ignore if file doesn't exist
|
|
|
|
if (error.code !== 'ENOENT') {
|
|
|
|
log.error('Failed to unlink', error);
|
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
}
|
2024-01-02 20:14:11 +00:00
|
|
|
}
|