From 40b2fc553e056f2e8b08e63dc1e14337d31df6c9 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 7 Oct 2026 19:12:14 +0000 Subject: [PATCH] Fix PDF unlock aborting on streams the producer left unencrypted MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Some producers write AES-encrypted PDFs in which a few small streams (seen with font /CIDSet streams) are stored unencrypted and declare their filter as a one-element array, /Filter [ /FlateDecode ]. qpdf does not recognise such a stream as already compressed, so when writing it decrypts the stream, tries to inflate it to compress it again, and aborts the whole write on the resulting "incorrect header check". The user saw "file is corrupt or could not be read" although the password was right. qpdf now runs with --stream-data=preserve for both decryption and the re-encryption that keeps restrictions: stream data is only decrypted and otherwise written as it is. The affected streams end up exactly as a conforming reader sees them in the original; page rendering is unchanged. Adds a fixture that reproduces the failure, with a regression test covering the decrypt and the keep-restrictions path. Docs-Impact: none – supported protections and results are unchanged; the fix only makes qpdf stop re-compressing stream data, which no document describes Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DBSwp8dMkpVxCSR4ArHAU5 --- scripts/gen-fixtures.py | 50 ++++++++++++++++++ web/src/core/pdf/qpdf.ts | 11 +++- web/tests/fixtures/README.md | 1 + .../pdf/unencrypted-stream-aes256.pdf | Bin 0 -> 1738 bytes web/tests/pdf.test.ts | 12 +++++ 5 files changed, 73 insertions(+), 1 deletion(-) create mode 100644 web/tests/fixtures/pdf/unencrypted-stream-aes256.pdf 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 0000000000000000000000000000000000000000..6f40a9ec092e88ac71fe89e9c6a25877f8a4f2c1 GIT binary patch literal 1738 zcmah~JBVCW7&dB?iC9=!D4b@iu-@~2;JA>TM_iJ1mziV>=HXLz zbHuG;GO7?k*_DAGqkY8d%wL@6K83S1P1{S;5wKN_k*IC5?cfJ?vp4}S7(NtFzu;@v zmY_Iir5DD9^wYT)ctsU60y92`|eiR3h3f09=XbKY#m!Up{&2{LkM% zH~HqyN9Auf{1am|T)+6TW|5E z)bvtg!@Z)C2&RcQQK&qRo;u?MVM0b?b8c;5PI_n!$|KPpLm^rZZ6z&qRLmWTm>L3Y zW^*s0J1A3;tK1mKVF&sh+R8>ErI5MBA`%r~+lDB>qjgSs<5bSHj2QDE2zJ`!4r@U< z6I6tlrT|)J1nNKA4do%!x#Buk8bWxgWYFGYCb%Ii&jr_3P%!C1RcHO`u$z7phwvzu zFV|5MLt8tof+tEy1Kn3y1O@~oaUI|@Obj6sAam)I(njVY$|wb}3`m91+&b?RkybKHWwgN?3VcaP zEcMCF9*l%#9iEgSHZU>`ytt4Qf(aDSLPnq^(}hM08BDt~GAf{|Pw6oNeRE1C{=*+6 zct%fgm}sYLHHY~;msO=53}Ggu3AHtf1xm9UMtiR)(%7um{lQBC8Q5>5{U#%vK%q#$ xr;Rd { 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']) {