Open History to see the last commit
1import { cbc } from "@noble/ciphers/aes.js";
2import { sha1 } from "@noble/hashes/legacy.js";
3import { sha256 } from "@noble/hashes/sha2.js";
4import { pbkdf2 } from "@noble/hashes/pbkdf2.js";
5import type JSZip from "jszip";
6
7import { officeXmlDecoder } from "./officeArchive";
8import { find, parseXml } from "./documentPreviewXml";
9import { OFFICE_PREVIEW_MAX_BYTES } from "./officePreviewProtocol";
10import { PreviewError } from "./previewFailure";
11
12const manifest = "{urn:oasis:names:tc:opendocument:xmlns:manifest:1.0}";
13const manifestAlgorithm = "urn:oasis:names:tc:opendocument:xmlns:manifest:1.0#";
14
15function unsupported(): never {
16 throw new PreviewError({ code: "encryption-unsupported" });
17}
18
19function invalid(): never {
20 throw new PreviewError({ code: "office-invalid" });
21}
22
23function decode(value: string | undefined) {
24 if (!value) invalid();
25 try {
26 return Uint8Array.from(atob(value), (char) => char.charCodeAt(0));
27 } catch {
28 invalid();
29 }
30}
31
32async function inflate(compressed: Uint8Array<ArrayBuffer>, size: number) {
33 const stream = new Blob([compressed])
34 .stream()
35 .pipeThrough(new DecompressionStream("deflate-raw"));
36 const reader = stream.getReader();
37 const output = new Uint8Array(size);
38 let length = 0;
39 try {
40 while (true) {
41 const { value, done } = await reader.read();
42 if (done) break;
43 if (length + value.length > size) invalid();
44 output.set(value, length);
45 length += value.length;
46 }
47 if (length !== size) invalid();
48 return output;
49 } finally {
50 void reader.cancel().catch(() => undefined);
51 }
52}
53
54export async function unlockOpenDocument(archive: JSZip, password?: string) {
55 const source = await archive.file("META-INF/manifest.xml")?.async("uint8array");
56 if (!source?.length) return;
57 const xml = parseXml(officeXmlDecoder(source).decode(source));
58 const parts = find(xml, manifest + "file-entry").flatMap((entry) => {
59 const encryption = find(entry, manifest + "encryption-data")[0];
60 if (!encryption) return [];
61 const path = entry.attrs[manifest + "full-path"];
62 const size = Number(entry.attrs[manifest + "size"]);
63 const key = find(encryption, manifest + "key-derivation")[0]?.attrs;
64 const algorithm = find(encryption, manifest + "algorithm")[0]?.attrs;
65 const start = find(encryption, manifest + "start-key-generation")[0]?.attrs;
66 const cipher = algorithm?.[manifest + "algorithm-name"];
67 const keyBytes =
68 Number(
69 /^http:\/\/www\.w3\.org\/2001\/04\/xmlenc#aes(128|192|256)-cbc$/.exec(cipher ?? "")?.[1],
70 ) / 8;
71 const derivation = key?.[manifest + "key-derivation-name"];
72 const startName = start?.[manifest + "start-key-generation-name"];
73 const check = encryption.attrs[manifest + "checksum-type"];
74 if (
75 !key ||
76 !algorithm ||
77 !Number.isFinite(keyBytes) ||
78 (derivation !== "PBKDF2" && derivation !== manifestAlgorithm + "pbkdf2") ||
79 (startName &&
80 startName !== "SHA1" &&
81 startName !== "http://www.w3.org/2000/09/xmldsig#sha1" &&
82 startName !== "http://www.w3.org/2000/09/xmldsig#sha256" &&
83 startName !== "http://www.w3.org/2001/04/xmlenc#sha256") ||
84 (check !== "SHA1/1K" &&
85 check !== manifestAlgorithm + "sha1-1k" &&
86 check !== manifestAlgorithm + "sha256-1k")
87 )
88 unsupported();
89 const iterations = Number(key[manifest + "iteration-count"]);
90 if (!Number.isSafeInteger(iterations) || iterations < 1) invalid();
91 if (!path || !Number.isSafeInteger(size) || size < 0) invalid();
92 return [
93 {
94 path,
95 size,
96 iterations,
97 keyBytes,
98 iv: decode(algorithm[manifest + "initialisation-vector"]),
99 salt: decode(key[manifest + "salt"]),
100 expected: decode(encryption.attrs[manifest + "checksum"]),
101 startHash: startName?.endsWith("sha256") ? sha256 : sha1,
102 checksum: check.endsWith("sha256-1k") ? sha256 : sha1,
103 },
104 ];
105 });
106 if (parts.length === 0) return;
107 if (parts.some((part) => part.path === "encrypted-package")) unsupported();
108 if (password === undefined) throw new PreviewError({ code: "password-required" });
109 const total = parts.reduce((sum, part) => sum + part.size, 0);
110 const rounds = parts.reduce(
111 (sum, part) => sum + part.iterations * Math.ceil(part.keyBytes / 20),
112 0,
113 );
114 if (rounds > 4_000_000 || parts.some((part) => part.iterations > 1_000_000))
115 throw new PreviewError({ code: "office-decryption-limit" });
116 if (
117 total > OFFICE_PREVIEW_MAX_BYTES ||
118 parts.some((part) => part.path.toLowerCase().endsWith(".xml") && part.size > 8 * 1024 * 1024)
119 )
120 throw new PreviewError({ code: "office-too-large-expanded" });
121 const utf8 = new TextEncoder().encode(password);
122 for (const part of parts) {
123 const encrypted = await archive.file(part.path)?.async("uint8array");
124 if (
125 !encrypted?.length ||
126 encrypted.length % 16 !== 0 ||
127 part.iv.length !== 16 ||
128 part.salt.length > 64
129 )
130 invalid();
131 const key = pbkdf2(sha1, part.startHash(utf8), part.salt, {
132 c: part.iterations,
133 dkLen: part.keyBytes,
134 });
135 const padded = new Uint8Array(encrypted.length);
136 cbc(key, part.iv, { disablePadding: true }).decrypt(encrypted, padded);
137 const padding = padded.at(-1)!;
138 const compressed = padded.subarray(0, padded.length - padding);
139 const hash = part.checksum(compressed.subarray(0, 1024));
140 if (
141 padding < 1 ||
142 padding > 16 ||
143 hash.length !== part.expected.length ||
144 hash.some((value, index) => value !== part.expected[index])
145 )
146 throw new PreviewError({ code: "password-incorrect" });
147 archive.file(part.path, await inflate(compressed, part.size), { createFolders: false });
148 }
149}