diff --git a/scripts/gen-fixtures.py b/scripts/gen-fixtures.py index cc313b1..5d92cd8 100644 --- a/scripts/gen-fixtures.py +++ b/scripts/gen-fixtures.py @@ -12,10 +12,12 @@ regenerated files differ byte-wise while remaining equivalent. """ import io +import re import shutil import subprocess import tempfile import zipfile +import zlib from pathlib import Path import msoffcrypto @@ -97,6 +99,54 @@ def gen_pdf(): save_pdf("restricted-rc4-40.pdf", user=USER_PW, owner=OWNER_PW, R=2, aes=False, metadata=False, allow=RESTRICTED) # no open password, only owner restrictions save_pdf("owner-only.pdf", user="", owner=OWNER_PW, R=6, allow=RESTRICTED) + save_unencrypted_stream_pdf("unencrypted-stream-aes256.pdf") + + +def save_unencrypted_stream_pdf(name: str): + """AES-256 file in which one small font stream (a /CIDSet) was left unencrypted. + + Some producers write files like this. Decrypting such a stream yields bytes that + no longer inflate, which must not abort the whole unlock. + """ + pdf = pdf_doc() + # stored deflate, 23 bytes: longer than one AES block, like the streams seen in the wild + plain = zlib.compress(b"\xff" * 12, 0) + descriptor = pdf.make_indirect( + pikepdf.Dictionary( + Type=pikepdf.Name.FontDescriptor, + FontName=pikepdf.Name.Helvetica, + CIDSet=pdf.make_stream(plain, Filter=pikepdf.Name.FlateDecode), + ) + ) + pdf.pages[0].obj.Resources.Font.F1.FontDescriptor = descriptor + path = OUT / "pdf" / name + pdf.save( + path, + static_id=True, + deterministic_id=False, + object_stream_mode=pikepdf.ObjectStreamMode.disable, + encryption=pikepdf.Encryption(user=USER_PW, owner=OWNER_PW, R=6, allow=RESTRICTED), + ) + with pikepdf.open(path, password=USER_PW) as enc: + num = enc.pages[0].obj.Resources.Font.F1.FontDescriptor.CIDSet.objgen[0] + + # Put the plaintext back in place of the encrypted stream data, then rebuild the xref. + data = path.read_bytes() + obj = re.compile(rb"(?m)^%d 0 obj\b.*?/Length (\d+).*?stream\r?\n" % num, re.S).search(data) + start = obj.end() + end = start + int(obj.group(1)) + # The filter as a one-element array, as the producer wrote it: qpdf then does not + # recognise the stream as already compressed and tries to inflate it. + head = data[: obj.start(1)] + str(len(plain)).encode() + data[obj.end(1) : start] + head = head[: obj.start()] + head[obj.start() :].replace(b"/Filter /FlateDecode", b"/Filter [ /FlateDecode ]") + data = head + plain + data[end:] + body = data[: data.rindex(b"\nxref\n") + 1] + offsets = {int(m.group(1)): m.start() for m in re.finditer(rb"(?m)^(\d+) 0 obj\b", body)} + size = max(offsets) + 1 + xref = b"xref\n0 %d\n0000000000 65535 f \n" % size + xref += b"".join(b"%010d 00000 n \n" % offsets[i] for i in range(1, size)) + trailer = data[data.index(b"trailer", len(body)) : data.rindex(b"startxref")] + path.write_bytes(body + xref + trailer + b"startxref\n%d\n%%%%EOF\n" % len(body)) def minimal_docx() -> bytes: diff --git a/web/src/core/pdf/qpdf.ts b/web/src/core/pdf/qpdf.ts index 95f7048..a911946 100644 --- a/web/src/core/pdf/qpdf.ts +++ b/web/src/core/pdf/qpdf.ts @@ -160,8 +160,16 @@ function finish(run: QpdfRun): Uint8Array { return run.output; } +/** + * Write stream data as it is, only decrypted. Without this qpdf re-compresses + * streams it does not recognise as compressed (e.g. `/Filter [/FlateDecode]`) + * and aborts the whole write when one of them does not inflate, as happens + * when a producer left a stream unencrypted in an encrypted file. + */ +const PRESERVE_STREAMS = '--stream-data=preserve'; + export async function decryptPdf(input: Uint8Array, password: PasswordBytes): Promise { - return finish(await runQpdf(input, (i, o) => [...passwordArgs(password), '--decrypt', i, o])); + return finish(await runQpdf(input, (i, o) => [...passwordArgs(password), PRESERVE_STREAMS, '--decrypt', i, o])); } function yn(v: boolean): string { @@ -197,6 +205,7 @@ export async function removeOpenPasswordKeepRestrictions( return finish( await runQpdf(input, (i, o) => [ ...passwordArgs(password), + PRESERVE_STREAMS, i, '--encrypt', '--user-password=', diff --git a/web/tests/fixtures/README.md b/web/tests/fixtures/README.md index 6f68759..11846f2 100644 --- a/web/tests/fixtures/README.md +++ b/web/tests/fixtures/README.md @@ -13,6 +13,7 @@ All passwords are test values and intentionally public. | `pdf/restricted-rc4-noaccess.pdf` | same | RC4-128 (R3), same restrictions plus accessibility denied | | `pdf/restricted-rc4-40.pdf` | same | RC4-40 (R2), same restrictions; R2 ties accessibility to extract | | `pdf/owner-only.pdf` | owner `owner-Pässwort2` (empty user password) | opens without password, restrictions only | +| `pdf/unencrypted-stream-aes256.pdf` | user `user-Pässwort1`, owner `owner-Pässwort2` | AES-256 (R6), restrictions as above; one `/CIDSet` stream left unencrypted with `/Filter [ /FlateDecode ]`, as some producers write it | | `office/plain.docx` | – | minimal unencrypted DOCX | | `office/agile.docx` | `Büro-Geheim 42` | ECMA-376 Agile (msoffcrypto-tool) | | `office/standard.docx` | `Password1234_` | ECMA-376 Standard; taken from the msoffcrypto-tool test suite (MIT) | diff --git a/web/tests/fixtures/pdf/unencrypted-stream-aes256.pdf b/web/tests/fixtures/pdf/unencrypted-stream-aes256.pdf new file mode 100644 index 0000000..6f40a9e Binary files /dev/null and b/web/tests/fixtures/pdf/unencrypted-stream-aes256.pdf differ diff --git a/web/tests/pdf.test.ts b/web/tests/pdf.test.ts index 173d6ef..83ff93c 100644 --- a/web/tests/pdf.test.ts +++ b/web/tests/pdf.test.ts @@ -72,6 +72,18 @@ describe('unlockPdf', () => { expect((await inspectEncryption(r.data, ''))?.encrypted).toBe(false); }); + it('unlocks a file in which the producer left a stream unencrypted', async () => { + // that stream does not inflate after decryption; it must not abort the unlock + const file = fixture('pdf/unencrypted-stream-aes256.pdf'); + const restricted = await unlockPdf(file, PW.pdfUser); + expect(restricted.mode).toBe('open-password-removed'); + expect((await inspectEncryption(restricted.data, ''))?.capabilities.extract).toBe(false); + const full = await unlockPdf(file, PW.pdfOwner); + expect(full.mode).toBe('decrypted'); + expect((await inspectEncryption(full.data, ''))?.encrypted).toBe(false); + expect(new TextDecoder('latin1').decode(full.data)).toContain('(unpassword fixture)'); + }); + it('accepts the password regardless of how the producer encoded it', async () => { // R3/R4 fixtures store PDFDocEncoding bytes, R6 stores UTF-8 for (const f of ['restricted-rc4.pdf', 'restricted-aes128.pdf', 'restricted-aes256.pdf']) {