Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

officeEncryption.ts

222 lines8.4 KB

1import { cbc, ecb } from "@noble/ciphers/aes.js";
2import { sha1 } from "@noble/hashes/legacy.js";
3import { sha256, sha384, sha512 } from "@noble/hashes/sha2.js";
4import { hmac } from "@noble/hashes/hmac.js";
5import { concatBytes } from "@noble/hashes/utils.js";
6import { SaxesParser } from "saxes";
7​
8import { readOfficeEncryptedStreams } from "./officeEncryptedStreams";
9import { PreviewError } from "./previewFailure";
10​
11const CBC = { disablePadding: true };
12const ENCRYPTION_NS = "http://schemas.microsoft.com/office/2006/encryption";
13const PASSWORD_NS = "http://schemas.microsoft.com/office/2006/keyEncryptor/password";
14const AGILE_HASHES = { SHA1: sha1, SHA256: sha256, SHA384: sha384, SHA512: sha512 };
15type Hash = typeof sha256;
16​
17function invalid(): never {
18 throw new PreviewError({ code: "office-invalid" });
20​
21function unsupported(): never {
22 throw new PreviewError({ code: "encryption-unsupported" });
24​
25function wrongPassword(): never {
26 throw new PreviewError({ code: "password-incorrect" });
28​
29function uint32(number: number) {
30 const bytes = new Uint8Array(4);
31 new DataView(bytes.buffer).setUint32(0, number, true);
32 return bytes;
34​
35function equal(left: Uint8Array, right: Uint8Array) {
36 if (left.length !== right.length) return false;
37 let difference = 0;
38 for (let i = 0; i < left.length; i++) difference |= left[i]! ^ right[i]!;
39 return difference === 0;
41​
42function pad(bytes: Uint8Array, length: number) {
43 const output = new Uint8Array(length).fill(0x36);
44 output.set(bytes.subarray(0, length));
45 return output;
47​
48function passwordHash(hash: Hash, salt: Uint8Array, password: string, spins: number) {
49 const utf16 = new Uint8Array(password.length * 2);
50 const view = new DataView(utf16.buffer);
51 for (let i = 0; i < password.length; i++) view.setUint16(i * 2, password.charCodeAt(i), true);
52 const block = new Uint8Array(4 + hash.outputLen);
53 const counter = new DataView(block.buffer);
54 block.set(hash(concatBytes(salt, utf16)), 4);
55 for (let i = 0; i < spins; i++) {
56 counter.setUint32(0, i, true);
57 block.set(hash(block), 4);
58 }
59 return block.subarray(4);
61​
62function base64(value: string | undefined) {
63 if (!value) invalid();
64 try {
65 return Uint8Array.from(atob(value), (char) => char.charCodeAt(0));
66 } catch {
67 invalid();
68 }
70​
71function agileParameters(attrs: Record<string, string>) {
72 const algorithm = attrs.hashAlgorithm as keyof typeof AGILE_HASHES;
73 if (!Object.hasOwn(AGILE_HASHES, algorithm)) unsupported();
74 const hash = AGILE_HASHES[algorithm];
75 const keyBytes = Number(attrs.keyBits) / 8;
76 if (
77 attrs.cipherAlgorithm !== "AES" ||
78 attrs.cipherChaining !== "ChainingModeCBC" ||
79 Number(attrs.blockSize) !== 16 ||
80 ![16, 24, 32].includes(keyBytes)
81 )
82 unsupported();
83 const salt = base64(attrs.saltValue);
84 if (salt.length !== Number(attrs.saltSize) || salt.length > 64 || salt.length === 0) invalid();
85 return { hash, keyBytes, salt };
87​
88function agileDecrypt(info: Uint8Array, pkg: Uint8Array, size: number, password?: string) {
89 let data: Record<string, string> | undefined;
90 let key: Record<string, string> | undefined;
91 let integrity: Record<string, string> | undefined;
92 const parser = new SaxesParser({ xmlns: true });
93 parser.on("doctype", invalid);
94 parser.on("error", invalid);
95 parser.on("opentag", (tag) => {
96 if (tag.uri === ENCRYPTION_NS && tag.local === "keyData")
97 data = Object.fromEntries(
98 Object.values(tag.attributes).map((attr) => [attr.local, attr.value]),
99 );
100 if (tag.uri === PASSWORD_NS && tag.local === "encryptedKey")
101 key = Object.fromEntries(
102 Object.values(tag.attributes).map((attr) => [attr.local, attr.value]),
103 );
104 if (tag.uri === ENCRYPTION_NS && tag.local === "dataIntegrity")
105 integrity = Object.fromEntries(
106 Object.values(tag.attributes).map((attr) => [attr.local, attr.value]),
107 );
108 });
109 parser.write(new TextDecoder().decode(info.subarray(8))).close();
110 if (!data) invalid();
111 if (!key) unsupported();
112 const dataParams = agileParameters(data);
113 const keyParams = agileParameters(key);
114 const spins = Number(key.spinCount);
115 if (!Number.isSafeInteger(spins) || spins < 0 || spins > 1_000_000) unsupported();
116 if (password === undefined) throw new PreviewError({ code: "password-required" });
117​
118 const secret = passwordHash(keyParams.hash, keyParams.salt, password, spins);
119 const decryptKeyValue = (value: string | undefined, block: number[]) => {
120 const aesKey = pad(
121 keyParams.hash(concatBytes(secret, new Uint8Array(block))),
122 keyParams.keyBytes,
123 );
124 return cbc(aesKey, pad(keyParams.salt, 16), CBC).decrypt(base64(value));
125 };
126 const verifier = decryptKeyValue(
127 key.encryptedVerifierHashInput,
128 [0xfe, 0xa7, 0xd2, 0x76, 0x3b, 0x4b, 0x9e, 0x79],
129 );
130 const expected = decryptKeyValue(
131 key.encryptedVerifierHashValue,
132 [0xd7, 0xaa, 0x0f, 0x6d, 0x30, 0x61, 0x34, 0x4e],
133 );
134 const actual = keyParams.hash(verifier.subarray(0, keyParams.salt.length));
135 if (!equal(actual, expected.subarray(0, actual.length))) wrongPassword();
136​
137 const dataKey = decryptKeyValue(
138 key.encryptedKeyValue,
139 [0x14, 0x6e, 0x0b, 0xe7, 0xab, 0xac, 0xd0, 0xd6],
140 ).subarray(0, dataParams.keyBytes);
141 const decrypt = (block: Uint8Array, value: Uint8Array) =>
142 cbc(dataKey, pad(dataParams.hash(concatBytes(dataParams.salt, block)), 16), CBC).decrypt(value);
143 if (integrity) {
144 const digestSize = dataParams.hash.outputLen;
145 const hmacKey = decrypt(
146 new Uint8Array([0x5f, 0xb2, 0xad, 0x01, 0x0c, 0xb9, 0xe1, 0xf6]),
147 base64(integrity.encryptedHmacKey),
148 );
149 const digest = decrypt(
150 new Uint8Array([0xa0, 0x67, 0x7f, 0x02, 0xb2, 0x2c, 0x84, 0x33]),
151 base64(integrity.encryptedHmacValue),
152 );
153 if (
154 !equal(
155 hmac(dataParams.hash, hmacKey.subarray(0, digestSize), pkg),
156 digest.subarray(0, digestSize),
157 )
158 )
159 invalid();
160 }
161 const output = new Uint8Array(size);
162 for (let offset = 0; offset < size; offset += 4096) {
163 const length = Math.min(size - offset, 4096);
164 const chunk = decrypt(
165 uint32(offset / 4096),
166 pkg.subarray(8 + offset, 8 + offset + Math.ceil(length / 16) * 16),
167 );
168 output.set(chunk.subarray(0, length), offset);
169 }
170 return output.buffer;
172​
173function standardDecrypt(info: Uint8Array, pkg: Uint8Array, size: number, password?: string) {
174 if (info.length < 44) invalid();
175 const view = new DataView(info.buffer, info.byteOffset, info.byteLength);
176 const verifierOffset = 12 + view.getUint32(8, true);
177 const keyBits = view.getUint32(28, true);
178 const algorithm = view.getUint32(20, true);
179 if (
180 ![128, 192, 256].includes(keyBits) ||
181 algorithm !== 0x660e + (keyBits - 128) / 64 ||
182 view.getUint32(24, true) !== 0x8004
183 )
184 unsupported();
185 if (
186 verifierOffset < 44 ||
187 verifierOffset + 72 > info.length ||
188 view.getUint32(verifierOffset, true) !== 16 ||
189 view.getUint32(verifierOffset + 36, true) !== 20
190 )
191 invalid();
192 if (password === undefined) throw new PreviewError({ code: "password-required" });
193 const salt = info.subarray(verifierOffset + 4, verifierOffset + 20);
194 const secret = passwordHash(sha1, salt, password, 50_000);
195 const hash = sha1(concatBytes(secret, uint32(0)));
196 const key = concatBytes(
197 ...[0x36, 0x5c].map((byte) => {
198 const block = new Uint8Array(64).fill(byte);
199 hash.forEach((value, i) => {
200 block[i] = value ^ byte;
201 });
202 return sha1(block);
203 }),
204 ).subarray(0, keyBits / 8);
205 const verifier = ecb(key, CBC).decrypt(info.subarray(verifierOffset + 20, verifierOffset + 36));
206 const digest = ecb(key, CBC).decrypt(info.subarray(verifierOffset + 40, verifierOffset + 72));
207 if (!equal(sha1(verifier), digest.subarray(0, 20))) wrongPassword();
208 return ecb(key, CBC).decrypt(pkg.subarray(8)).slice(0, size).buffer;
210​
211export function decryptOffice(bytes: ArrayBuffer, password?: string) {
212 const { info, package: pkg } = readOfficeEncryptedStreams(bytes);
213 const size = Number(new DataView(pkg.buffer, pkg.byteOffset).getBigUint64(0, true));
214 if (size < 22 || Math.ceil(size / 16) * 16 !== pkg.length - 8) invalid();
215 const header = new DataView(info.buffer, info.byteOffset);
216 const major = header.getUint16(0, true);
217 const minor = header.getUint16(2, true);
218 if (major === 4 && minor === 4) return agileDecrypt(info, pkg, size, password);
219 if ((major === 2 || major === 3 || major === 4) && minor === 2)
220 return standardDecrypt(info, pkg, size, password);
221 unsupported();