Repository navigation
feat(reader): decrypt on read — PdfReader.Open takes a password - #212
Merged
Merged
Conversation
Parts 1 (#203) and 2 (#207) built the RC4/MD5 primitives and the decrypt side of the Standard security handler with no reader wiring at all. This is the third and final part: PdfReader.Open(bytes, password) resolves /Encrypt, authenticates owner-then-user, and decrypts strings at Resolve (using the containing indirect object's identity per Algorithm 1 step (a)) and streams at the decode path, leaving ParsedStream.RawBody verbatim for the byte-level conformance rules that depend on it. A wrong password throws PdfPasswordException rather than UnsupportedPdfFeatureException, since vellum-preflight already catches NotSupportedException to report an unsupported feature and a bad password is a different failure. PdfDocumentReader.Encryption exposes /V, /R, cipher, key length, /P, /EncryptMetadata, and owner-vs-user access, with no key material. Object streams are decrypted once as a whole, never per member (ISO 32000-2 7.5.7); cross-reference streams and the /Encrypt dictionary's own strings are never decrypted; a signature dictionary's /Contents is exempted from string decryption since the spec is silent and a conformant signer patches those bytes in after encryption regardless. PdfFilters gained a /Crypt filter, and a /StmF, /StrF, or /Crypt /Name naming an undefined /CF entry now fails loudly instead of returning ciphertext as plaintext. Verified against the committed corpus, plus three new fixtures: an empty user password (the shape most real encrypted PDFs use), an object stream and cross-reference stream in RC4 (AES double-decryption throws, so only RC4 can catch a decryptor that wrongly re-decrypts an object-stream member), and a nested array-of-strings pin for the containing-object-identity rule.
Mutation testing on the decrypt-wiring tests turned up three that passed under a mutation they were meant to catch: - CryptIdentityFilter_onAStream_bypassesDecryption_endToEnd patched a stream's /Filter down to just /Crypt to fit a same-length byte patch, dropping /FlateDecode from the chain. Missing decompression alone made the output not match baseline, so the assertion passed whether or not the /Crypt /Identity override actually fired. Fixed by keeping /FlateDecode in the patched filter array and catching the InvalidDataException FlateDecode throws on raw ciphertext. - StmFNamingUndefinedCfEntry_opensButThrowsOnDecode asserted only the exception TYPE. Falling back to Identity instead of Unsupported for an undefined /CF name also throws InvalidDataException, just from FlateDecode rejecting the still-ciphertext bytes rather than from the intended "/CFM ... does not exist" check. Now asserts the message too. - PublicKeySecurityHandler_throwsUnsupportedPdfFeatureException passed even with the /Adobe.PubSec-specific guard removed, because the general "/Filter is not /Standard" guard right after it throws the same exception type for the same input. Now asserts the message names "public-key" specifically. Also adds the one fixture #97 shipped without: a JPXDecode image XObject on an encrypted document, to pin Jpeg2000Rule reading decrypted bytes rather than stream.RawBody. No prior fixture combined encryption with a JPX image, so that line was unpinned.
The table was written from recollection and the comment cited ISO 32000-2 Annex D.2 without anyone having read it. Checked it entry by entry against the PDF column of ISO 32000-1 Annex D: 36 of 39 match, and the three that resist extraction from the two-column layout fill exactly the gaps in the run that does extract. No value changed; only the provenance is now true.
The decrypt walk skipped /Contents only when the containing dictionary declared /Type /Sig. ISO 32000-1 Table 252 lists /Type as optional in a signature dictionary, and an archive timestamp declares /DocTimeStamp instead - the type ArchiveTimestampBuilder writes for PAdES B-LTA. Both shapes had their signature bytes decrypted into garbage, which breaks /ByteRange verification on exactly the documents this issue exists to make readable: encrypted, signed PDFs. A /Type-less dictionary is now recognised the way NumericLimitsRule already recognises one, by /ByteRange (required of approval and certification signatures by ISO 32000-1 12.8.1) alongside a string /Contents. Requiring both halves keeps the exemption off the many dictionaries that carry an unrelated /Contents. The theory rows for the /Type-less and /DocTimeStamp shapes fail against the old predicate and pass against the new one; the /Type /Sig row and the negative case (a /Contents with no /ByteRange still decrypts) hold under both.
Three objects came out of the decrypt path corrupted, all found by probing the wiring rather than by a failing test. A cross-reference stream resolved as an ordinary object was decrypted, body and dictionary strings alike, though ISO 32000-1 7.5.8.2 says both shall not be. XrefParser never hit this - it reads the stream before a decryptor exists - but a preflight rule walking every object does, and the body then fails to inflate. The /ID in that dictionary is exactly the string 7.5.5 wants readable without decrypting the file. A stream whose data is in an external file was decrypted too, against 7.6.1. Under RC4 that silently turns the in-file bytes into noise; under AES it throws, so a legal document becomes unreadable. /F only exempts the stream when it is a file specification - a string or a dictionary - so a producer using the key for something else still gets its content decrypted. An object whose header generation disagreed with the cross-reference table's had its dictionary decrypted under the table's generation and its body under the header's. Algorithm 1 has one identity per object; the table is the authority both halves now use, matching #192. Each of the six new tests fails against the code as it was.
ResolveStream parsed a stream, cached its dictionary, and never ran the decrypt walk. Resolve did. Both populate the same cache and Resolve returns early on a hit, so whichever ran first decided for the reader's lifetime whether that dictionary's strings were plaintext or ciphertext - and the Conformance package resolves streams before objects, so ciphertext was the usual outcome. Adversarial review found it; two reviewers found it independently. The cross-reference stream exemption keyed on /Type /XRef, a key the document's author writes. A page's content stream mislabelled that way was handed to every content rule as ciphertext while a conforming viewer decrypted and rendered it. XrefParser now reports the object numbers it actually consumed as cross-reference streams, and that set decides. The same sniff also fired on nested dictionaries and returned the whole subtree unwalked, which hid arbitrarily much of an object from the decrypt walk. The object-stream loader skipped the generation re-stamp, so a container whose header disagreed with the table decoded correctly through ResolveStream and to noise through the loader, in one reader. An /Encrypt that only an older revision declares is no longer read as a plaintext document. Only the newest trailer is consulted, which is right, but an incremental update over an encrypted document has to repeat /Encrypt; one that drops it left every stream decoding to ciphertext with no error at all.
Four defects in the decrypt core, all found by adversarial review against the ISO text rather than by a failing test - every fixture in the corpus carries redundant parameters that agree, so none of them could tell a reader that reads the wrong one from a reader that reads the right one. The key length for /V 4 came from the top-level /Length, which Table 20 scopes to "only if V is 2 or 3". The length that applies is the crypt filter's own, and a conformant file may omit the top-level entry entirely - which derived a 5-byte key and rejected the CORRECT password on a file qpdf opens and fully decrypts. /R 2 ignored Algorithm 2 step (i), "n shall always be 5 for security handlers of revision 2": a spec-conformant /V 2 /R 2 /Length 128 file was rejected and a non-conformant one accepted. /Perms was implemented and never called. At R<=4 /P feeds Algorithm 2, so editing it breaks authentication by itself; at R>=5 the file key is random and /P is protected only by /Perms. A two-byte edit silently granted every permission, and this library reported the attacker's bits as the document's. Algorithm 13 now runs, and a mismatch is rejected. An empty string or zero-length stream under AES threw: there is no IV to write for one, so its encrypted form is empty too, and demanding an IV made a legal document unreadable. /O and /U longer than 48 bytes at R>=5 are now tolerated, reading the first 48 - Acrobat 9-era producers pad them out. PdfEncryptionInfo's constructor becomes internal. The Reader is its only producer and already has the friend grant; public would freeze a seven-parameter list in a Stable package at the next release.
vellum-preflight crashed with an unhandled exception on any encrypted file in its default invocation. The password catch added with the decrypt wiring sat around Validate, but profile auto-detection opens the document first, with no password, so an encrypted file never reached it. Both paths now report the same line. ISO 19005-2 6.1.3 forbids /Encrypt, and that had been enforced by the reader refusing to open encrypted documents at all - an error line, never a verdict. Since the reader reads them, an AES-encrypted file was reported as passing 6.1.3 along with every other check. FileTrailerRule checks it now, which is what its own remark claimed was covered elsewhere. /V 3 is a value ISO 32000-1 Table 20 defines and leaves unpublished, so a file using it is valid and merely beyond a clean-room implementation. Reporting it as "not a valid PDF" told users their good file was corrupt. Four documentation claims did not match the code: Open's four overloads promised UnsupportedPdfFeatureException for an unsupported crypt filter (it is an InvalidDataException, and not at Open), DetectClaimedProfiles never documented the password exception it now throws, KeyLengthBits named three values the code does not enforce, and the changelog asserted a retry order matching another tool's internals.
A /StrF that resolved to no usable crypt filter was completely silent: the document opened, every string came back as ciphertext, and no API said so. It now fails at Open. An unresolvable /StmF still fails lazily at the first decode - the asymmetry is deliberate, since a document whose streams cannot be decrypted still has readable strings while the converse has nothing to offer at all. PdfEncryptionInfo gains StringCipher. ISO 32000-2 Table 20 lets a document use different crypt filters for strings and streams, so one reported cipher could not describe both, and /StrF resolving to something unsupported had no public expression. PdfPreflight now reports a document whose streams cannot be decoded as unevaluable rather than non-conformant. Each rule used to hit the failure separately and report it against whatever clause it happened to cover, so a crypt-filter problem came out as a FAIL stamped with output-intent and transparency clauses the file never violated.
An adversarial pass mutated the decrypt wiring and found 18 changes no test objected to. The ones that mattered: The generation was dead weight. Every fixture object is generation 0, so zeroing the generation in the object key passed the whole suite - including the test whose entire subject is generation handling, which only pins that the dictionary and the body AGREE. There is now an object at generation 5 in both its header and the table, and its ciphertext is produced from ISO 32000-1 Algorithm 1 against the platform's MD5 rather than through the library's own derivation, since a helper built on the code under test cancels that error out on both sides. /EncryptMetadata was decoration: both cleartext-metadata fixtures existed and were verified byte-for-byte, but nothing read that stream back through the reader, so hardcoding the flag true passed while making the document unreadable. The metadata stream now decodes to the same XMP whether the fixture encrypts it or not. The /Crypt passthrough test tolerated an exception as a pass, so it could not tell "/Crypt handled, Flate rejected ciphertext" from "/Crypt not handled at all" - it still passed with the passthrough removed. Replaced by an unencrypted document where the no-op is observable by value. Also pinned: /CFM /None, a present-but-broken /CF entry, and PdfDocEncoding, which shipped as 122 lines with no tests at all. Writing its known-answer table against Annex D turned up a real defect - the encoding puts Euro at 0xA0 where Latin-1 has NO-BREAK SPACE, so a password containing a Euro sign could not be encoded and one containing U+00A0 was encoded as a Euro sign. A document that encrypts only its embedded files (/EFF) is now refused instead of returning each attachment's ciphertext as the attachment. ExternalSignerChainTests and DssBuilderTests wait for the CA they just installed to become visible to the chain engine. A certificate added to CurrentUser\CA is not immediately visible to an in-process chain build, and this assembly keeps that cache hot, so the signer intermittently embedded a one-element chain - about one full-suite run in four, which also corrupts mutation-testing verdicts. Eight consecutive runs are clean.
Seven behaviours the eight-fixture corpus could not distinguish from their opposites, whatever it asserted. Four need a document no existing fixture could be, three need arrangements no producer emits. Every other fixture's password is the one ASCII character "u", which hides three rules at once. A 40-character password fixes Algorithm 2 step (a)'s truncation point by value: its first 32 characters open the document and its first 31 do not. One password serving as both owner and user pins the owner-first trial order, whose whole justification is what to report in that case. And "passwoerd" spelled with umlauts pins the PDFDocEncoding retry - qpdf derives /U for an R<=4 document from PDFDocEncoding bytes, so the file does not open on the UTF-8 attempt, which is the gap CandidatePasswordEncodings names in its own comment. The fourth is an incremental update over an encrypted document - the shape any encrypted file acquires the moment it is annotated or signed, and the only one where revision chaining and decryption meet. qpdf cannot produce it (it rewrites whole files); poppler's pdfattach appends, at the cost of an empty user password since it takes no password argument. The synthetic three: which trailer's /Encrypt wins when a hybrid file declares two, the /Crypt filter written the way ISO 32000-1 7.6.5's own example writes it, and the key-length rules that only bite when /Length disagrees with /V or /R. The /Crypt test needs both of its rows - a reader that cannot read a dictionary-shaped /DecodeParms falls back to a missing /Name, whose default is Identity, so the Identity row alone passes for the wrong reason. It did, until the second row was added. Each of the seven fails against a mutant of the rule it covers.
Round two of adversarial review, on the round-one fixes. Three reviewers,
eighteen findings; the ones that changed behaviour:
/EncryptMetadata false exempted every stream claiming /Type /Metadata.
Table 20 scopes it to the DOCUMENT's metadata stream, and qpdf's
--cleartext-metadata encrypts a page's while exempting the catalog's - so a
page-level XMP stream came back as ciphertext under RC4 and threw under AES.
It is now the object the catalog names, decided by the reader rather than
sniffed from an author-controlled key, the way the cross-reference exemption
already worked.
That cross-reference exemption had the same defect one level down: it
collected object numbers from every revision walked, including superseded
ones, so an update reusing the number an older revision gave its
cross-reference stream had that object silently skip decryption. It is keyed
on the offset the stream was actually read at now, checked against the
merged table.
Three refusals are withdrawn. /EFF is no longer refused - nothing in this
library extracts an embedded file, so there is no caller to hand the wrong
bytes to, and refusing threw away a readable document to avoid mishandling a
part no API exposes. A /Perms that disagrees with /P no longer throws
either: the sealed copy is the authenticated permission set and is now what
gets reported, where refusing made this the only library that cannot open a
file qpdf, poppler and pdfium all read. Byte 8 of that block carries
/EncryptMetadata and is not part of Algorithm 13's verification, so it no
longer denies the document.
The V=4 key length now falls back to the length the cipher implies rather
than Table 20's 40-bit default, which rejected the correct password on a
conformant file carrying neither /Length entry; /StmF /Identity falls
through to /StrF for the same reason. A /StrF naming a defined filter with
an unimplemented /CFM is UnsupportedPdfFeatureException, not "malformed".
A stream whose stale /Length lands on ')', '{', '}' or a lone '>' is
recovered by the scan instead of failing the parse - ordinary on an
encrypted document, where the body is high-entropy. Seen on poppler
pdfattach output over AES-256.
Dispose now zeroes the file key. Three tests were reading it after disposal.
Three reviewers again; two found the same blocker independently. IsDocumentMetadataStream dereferenced Catalog, which the constructor assigns LAST - and reaching it decodes a stream when /Root lives in an object stream, the layout nearly every producer emits. PdfReader.Open threw NullReferenceException on those files, out of a public API, on documents qpdf reads without complaint. No fixture could catch it: qpdf writes the catalog uncompressed whenever it encrypts, so the shape had to be hand-built, and it is now a test. /EFF is implemented rather than argued about. The previous round withdrew the refusal on the grounds that nothing here extracts an embedded file - which was wrong: EmbeddedFilePdfaRule decodes every /EF stream, and one of this branch's own tests reads an attachment and asserts its plaintext. An embedded file stream now takes the crypt filter /EFF names, so Acrobat's "encrypt only file attachments" shape reads correctly instead of returning ciphertext as the attachment. Dispose zeroing the key left the reader dangerous rather than useless: resolving afterwards decrypted against sixteen zero bytes, which under RC4 is plausible-looking garbage that reports nothing. It throws ObjectDisposedException now, and the behaviour change is in the CHANGELOG, where it was missing. PdfEncryptionInfo.Cipher becomes StreamCipher. It was named when it was the only one; StringCipher now sits beside it, and its own documentation already called it the /StmF cipher. The Kernel is Stable, so this is free now and permanent after the next release. Table 20's /V 3 row ends "This value shall not appear in a conforming PDF file" - the sentence the comment justifying that branch had truncated. The behaviour stands and the reason is now the true one. /V 0 is handled too: undocumented, no algorithm to apply, malformed. AES-128 and AES-256 each have exactly one legal key size, so a crypt filter declaring another loses to the cipher rather than rejecting the correct password. PDFDocEncoding treats 0x7F and 0xAD as unencodable, which Annex D marks Undefined alongside 0x9F - the class comment claimed one byte of divergence from Latin-1 where there are four. Tests: thirteen mutants survived round three's sweep. Every one is dead, including three where the assertion coincided with the value another code path would have produced anyway - the /StrF length fallback needed a length that is not 128 bits to be observable at all. Three shipped documents still said the reader opens unencrypted PDFs only. One of them is packed into the NuGet package.
Two reviewers found the same regression from round three, independently. The /EFF branch sat above the /Crypt check. Table 20 says the opposite in as many words: a writer respects /EFF "except for embedded file streams that have their own crypt filter specifier". Leaving one attachment in the clear inside an encrypted document is written exactly that way, and taking /EFF over it returned the attachment as noise under RC4 and threw under AES - on files qpdf and poppler both read, and that this library read one commit earlier. The check order is reversed, and /EFF is null below /V 4, where Table 20 makes the entry meaningless, rather than defaulting to the stream filter and firing on documents that never mentioned it. /EncryptMetadata is gated on /V 4 too, for the same reason and from the same table: the key-derivation half was already gated on the revision, so reading it ungated was the two halves disagreeing. A /V 2 document carrying a stray copy had its metadata stream handed back as ciphertext. PDFDocEncoding stops refusing 0x7F and 0xAD. Round three added them as Undefined-per-Annex-D, which was true and beside the point: refusing a character drops the whole password candidate rather than substituting for it, so a document whose /U came from the byte 0xAD stopped opening under its correct password. Annex D marks two dozen more code points Undefined, so naming three was arbitrary as well as harmful. Documentation, all of it checkable and checked: - The NuGet package description still told nuget.org the reader does not support encryption. Three other capability docs were corrected last round; this is the one that ships on the package page. - The qpdf verification claim covered four signature shapes. qpdf agrees on one - /Type /Sig referenced from a field - and encrypts /Contents on the other three. The exemption is the reading that cannot corrupt a signature, which is a different claim and now the one being made. - "ISO 32000-1 and ISO 32000-2 are both silent" is now only what was verified: ISO 32000-1's text is in the tree, ISO 32000-2's is not. - DecryptObjectGraph named one of its two callers; Dispose claimed to release the only thing there is to release, past two live caches. Recorded as known gaps rather than half-built: an attachment omitting the optional /Type /EmbeddedFile is read under /StmF, since identifying it from the /EF entries needs the catalog before the first stream decodes - the ordering that produced a null dereference last round - and /AuthEvent is read past entirely.
Thirteen mutants lived through round four's sweep and five tests could not fail. All of them are dead now, and three were the same shape the last two rounds kept finding: an assertion whose expected value is also what another code path produces, so deleting the path under test changed nothing. The three /Perms guard tests each dodged the clause they named. Two passed a key the LENGTH clause rejects, so neither ever reached the revision check; the third passed a 16-byte key at R6 and said in its comment that the AES setter would otherwise have thrown, which it would not - 16 bytes is a legal AES-128 key. The revision clause now gets a /Perms block that would really decrypt, so only that clause can refuse it. V0_isMalformed asserted on a string the decryptor's own fallback message also contains, and passed with the guard deleted. The rest were untested behaviour rather than untestable tests. An annotation's /Contents is a text string (Table 168) and every commented PDF has one, so exempting on any /Type at all would have returned reviewer notes as ciphertext. The cross-reference exemption was pinned only through Resolve, never through ResolveStream - the order the code comment calls the dangerous one. Dispose zeroing the key, and the decode path's own disposal guard, were both unpinned; so was the resolver's dereference callback, which exists for an indirect /Filter and had no test at all. Every /CFM /V2 length row declared 5 or 16, so neither the bytes-or-bits reading nor RC4's own 128-bit limit was ever reached with a value that could tell them apart. Two needed documents nothing here could build. Over-long /O and /U at R6 - Acrobat 9-era padding the constructor deliberately tolerates - had a test for the rejecting direction only, so hashing the padding along with the value went unnoticed. And the Catalog-is-null guard is observable only when /EncryptMetadata is false, which needs a catalog inside an object stream in a cleartext-metadata document: built by appending a revision to the fixture that already has the right file key.
Round five of review on the decryption branch. ResolveStreamMethod applied the /EncryptMetadata exemption before reading a stream's own /Crypt entry, and read that entry at every /V. Both are wrong in the same direction. Table 20's /StmF row excepts "streams that have a Crypt entry in their Filter array" from the document-wide routing and its /EFF row excepts them again, so the specifier is the most specific thing a document says about a stream and outranks a flag Table 21 only asks a reader to respect. Below /V 4 the opposite holds: Table 20 marks /CF, /StmF, /StrF and /EFF "meaningful only when the value of V is 4", so there is no /CF for a /Name to resolve against and honouring the specifier left an RC4 embedded file undecrypted on a document qpdf reads. The spec's two "shall not be encrypted" cases keep their place above both. Also here: - Encode U+009F rather than refuse it. The guard excluded 0x80-0x9F where Annex D assigns glyphs only through 0x9E, contradicting the comment beside it that named 0x9F among the Undefined code points this table encodes byte-identically alongside 0x7F and 0xAD. - Widen the Unsupported crypt filter message, which named /StmF and /StrF but also fires for /EFF and for a /Crypt specifier's /Name. - Pin the two ordering rules, the /V gate, and /EFF's scoping to embedded file streams. Deleting that scoping check made /EFF the document-wide filter and weakening it to "has a /Type" caught object streams, both silently under the previous suite.
Algorithm 2 step (e) appends /ID[0] to the MD5 input, and appending nothing is well defined: a producer that wrote no /ID hashed exactly the bytes this derivation hashes, so it lands on that producer's file key. Table 15 does require /ID once /Encrypt is present, but qpdf opens such a file — silently where the array is [<><>], with a warning where it is absent entirely — and so does poppler, so refusing it made a document readable everywhere but here. The constructor now takes an empty element at every revision. The rest of this commit is documentation the branch had outrun: - The PDFDocEncoding CHANGELOG entry still described the behaviour of a round-three fix that was reverted: the Undefined code points encode as themselves, they are not dropped. - SECURITY.md's failure contract listed NotSupportedException for encrypted documents, which is what this branch changed, and never mentioned PdfPasswordException. - The qpdf comparison overstated its result. qpdf keys on /Type /Sig alone, not on reachability from a signature field; measured across five signature shapes, it leaves /Contents alone on all three /Type /Sig ones. - The 7.16-1 coverage note, which ships inside ConformanceCatalog.All, said PDF/UA-1's permission check needs reader decryption. It has that now; what it lacks is a way to give a preflight run a password. - PdfPasswordException now documents the one case that reaches it with the right password: an R6 file whose password needs SASLprep normalisation. - The /EFF known gap ran in one direction only. A cleartext attachment under /StmF with /EFF /Identity is decrypted into noise by the same ambiguity. - The key-length commentary in EncryptionSetup had been merged into the comment on the method below it during an earlier round.
A mutation sweep over the decrypt path found fourteen clauses no test could distinguish from its fallback, and five theory rows that cannot fail at all. Both come from the same coincidence: at /V 4 a document with no usable /Length is 128-bit, and 128 bits is also what every AESV2 and V2 crypt filter implies — so a row asserting 16 bytes passes whether or not the clause under test ever answered. Every /V 4 row now declares a top-level /Length of 40, which the fallback would read as a five-byte key. With that, deleting the cipher-implied length, either per-cipher clamp, the bits-vs-bytes divisibility test, or the unknown-/CFM case each fails a row that used to pass. Newly pinned, each verified by reverting the clause and watching a test go red: - /Perms recovery at R5. Algorithm 13 arrived with R5, not R6, and the whole /Perms suite was written at R6, so the revision comparison could be moved a revision either way unnoticed. - Algorithm 2 step (f) at /R 3. The 0xFFFFFFFF extension is scoped to revision 4 and up; applying it at 3 derives a different key from the producer's. Reachable only from /V 4 /R 3 /EncryptMetadata false. - /OE and /UE lengths. The constructor rejected null but accepted 16 or 48 bytes, which reach Algorithm 2.A and unwrap to a wrongly-sized file key. - An /Encrypt dictionary with no /Filter, which was read as /Standard. - Each byte of the "adb" marker separately; corrupting all three at once only ever reached the first comparison. - A /Type-less dictionary with a /ByteRange but a non-string /Contents, which is an annotation, not a signature. - A hybrid file's own /XRefStm object, resolved after opening. Also fixed: an indirect /CFM was unresolvable, because BuildCfTable's dereference callback was always passed null and the copy above it stops at the per-filter dictionary. That one is a bug, not a coverage gap, and it has its own CHANGELOG entry. Two things the sweep showed were untrue rather than untested: - The 16-byte short-circuit in the AES path claimed that demanding a block after the IV rejects the document. It does not: decrypting zero blocks returns zero bytes. Removed, with the length guard below it left to do the work the test actually exercises. - SignAsync_withExternalSigner_awaitsSignerWithoutBlocking timed a Task.Delay(200) with a stopwatch and failed roughly one run in twenty-five on Windows timer granularity — enough to report four surviving mutants as killed. It now holds the signer open on a signal the test controls and asserts no document comes back while it is outstanding.
Two rows, both built from the same baseline with the same u/o pair as the rest of the corpus: - enc-aes-128-linearized.pdf. Every other fixture is one ordinary cross-reference section. A linearized file has a first-page section ahead of the body and a second at the end, plus a hint stream that is ordinary encrypted content, so the reader follows /Prev backwards to the first section before it can resolve anything — with /Encrypt on a trailer it may reach in either order. It is also what Acrobat writes by default. - enc-256-linearized-objstm-cleartextmd.pdf. Linearization, object streams and /EncryptMetadata false in one file, which is where the null-catalog guard and the metadata exemption meet: reaching the catalog decodes an object stream, and that asks whether the object stream is the document's metadata before a catalog exists to answer from. Both decrypt to the baseline's page content under either password, and both carry a value-level assertion of the layout they claim, so a regenerated fixture qpdf declined to linearize does not silently stop testing anything. Also: pin /V 1's key-length rule with the top-level /Length renamed away. enc-rc4-40.pdf declares 40 bits, which is what the rule produces anyway and what the fallback defaults to below /V 4 — so the rule was invisible on the only fixture that reaches it, and deleting it passed the whole suite. The fixture README now records the corpus's largest remaining gap plainly: every file in it is qpdf's output, and producers differ in exactly the places this code decides.
Authentication runs with no decryptor, deliberately: that is what keeps /O, /U, /OE and /UE from ever being run through string decryption. But ISO 32000-1 §7.6.1 lets every non-string entry of the encryption dictionary be an indirect reference, and following one goes through Resolve, which caches what it returns. A document whose /Encrypt pointed at an object the document also used got that object back as ciphertext from then on — no exception, and nothing downstream that could tell a cached value from a decrypted one. The cache is dropped once the decryptor exists. The encryption dictionary itself is kept, because its own strings are exempt and that cached copy is what stops a later resolve from decrypting them; a test already covered that direction and catches the mistake. Two more places where an indirect value was not followed: - The crypt filter's /CFM and /Length. The dereferenced copy stops at the per-filter dictionary, and the key-length reader was never given the resolver the cipher reader got last round. An unresolved /Length disables the cipher-implied size and both clamps, so the correct password is reported as wrong. - /Filter itself, read twenty lines above the dereference that the comment below it correctly describes. An indirect one was reported as a handler named /(missing). And the CLI crash the password fix did not cover: auto-detection opens the document before the validation loop, so a public-key handler or an unimplementable /V escaped as an unhandled exception on the plainest invocation there is. Each fix has a test that fails without it, including two rows built so the key-length answers cannot coincide — the first attempt at them passed with the dereference removed, because 128 bits and AES-128's implied length are the same sixteen bytes.
Twelve clauses across the decrypt path could be deleted or moved with the whole suite still green. Each now has a test that fails without it, and each was verified by reverting the clause and watching the right test go red — including four whose first attempt did NOT discriminate, because the two answers coincided: - Algorithm 2.B's termination boundary. Every existing test round-trips through a re-implementation of the same clause, so a boundary written one round low cancels on both sides. Three known answers computed outside the repository from the clause text fix it; the first row's password is one whose last byte of E lands exactly on the bound, which happens for about one password in 256 and for none of the committed fixtures. - The AES whole-blocks guard. Asserting the exception type alone passed either way, because the cipher raises its own exception and the catch folds it into the same type. The absent inner exception is the tell. - /Perms of the wrong length, the one malformed input on that path that escaped as a bare CryptographicException. - /Perms byte 8, documented as deliberately not compared and unpinned: with the dictionary /P left at -4 both answers were -4. - The reader's own /V 4 gate on a stream's /Crypt specifier. The resolver's parameter was pinned; what the reader passes was not. - A present /Type settling IsSignatureDictionary. An annotation carrying a /ByteRange and a string /Contents would otherwise be exempted. - A one-element trailer /ID, where the rows already there had an empty /ID[0] either way and could not see the difference. - R>=5 forcing a 32-byte key, which R6 alone cannot place. - /V 1's key length. Renaming /Length away proves nothing below /V 4, since the fallback answers 40 bits too; the value has to contradict. - The crypt filter's 32-byte upper bound. - The parser's int.MaxValue bound. A wrapped cast has to land on a marker that is really there for the guard to matter, which needs a body carrying a literal endstream at exactly the truncated offset. - Open(Stream, string?), the only public entry point carrying a password that nothing called. Also corrects eleven documentation claims, four of which ship: the §7.6.3.3 citation on PdfPasswordException (Algorithms 4-7 are §7.6.3.4), /EncryptMetadata attributed to Table 20 in six places when it is Table 21, a comment saying no fixture pins the PDFDocEncoding retry when enc-aes-128-pdfdocpassword.pdf opens only through it, and the 7.16-1 coverage note, whose stated blocker was disproved by running preflight on an encrypted file. SECURITY.md no longer claims nothing in the encryption dictionary is trusted before authentication — /O, /P and /ID are inputs to the derivation; what is true is that none of it is acted on unvalidated.
CLAUDE.md forbids a disallowed reference library's name anywhere in the tree — code, comments, docs and commit messages alike — but the check only read working-tree files. A commit message on this very branch named several, and CI passed it: the file scan saw nothing, and nothing else looked. That asymmetry is the point. A name in a file is a follow-up commit away from being fixed. A name in a merged commit message is in public history and cannot be corrected without rewriting it, which after a merge is no longer a local decision. The branch's own message has been rewritten. The check now also scans the commits between the base ref and HEAD, and CI checks out full history so it has something to scan — the default depth-1 checkout would give it one commit and it would skip. It skips silently where no base resolves, because this backs up the file scan rather than replacing it, and a shallow clone is not a finding. The failure prints a count and not the line, so a CI log does not become the next place the name appears.
Three mutations of ISO 32000-2 Algorithm 9 survived every test in the solution: dropping /U as the udata argument to either of the two Hash2B calls that build /O and /OE, and swapping the validation and key salts inside /O. The mirror mutations on Algorithm 8 are all caught, because /U and /UE have a round trip and /O and /OE had none. Nothing joined the two halves. The write side derives /O and /OE and no test ever opened the result with the owner password; the read side's owner path is exercised only against committed fixtures, which come from another producer and so can never see a defect in ours. A file written under any of those three mutations opens nowhere — not here, not anywhere else — and the suite would have stayed green. The new test drives a handler with distinct passwords into a decryptor and asserts both passwords reach the SAME file key, then decrypts under it. All three mutations now fail it. A negative sibling pins that the wrong password is refused and that neither password authenticates through the other's path. Four more clauses on the write side had nothing depending on them, each now pinned and each verified by reverting it: /Perms bytes 4-7, which Algorithm 10 fixes at 0xFF and which only a validator elsewhere would ever read; the 127-byte password truncation, invisible because both sides call the same helper and R<=4 pads to 32 first; and /P's reserved low bits, reachable because PdfEncryptionSettings.Permissions is unvalidated. Also here, from the same round: - The handler check goes back above DereferenceValues, reading /Filter through the single-value dereference helper. Moving it below meant an /Encrypt with an unresolvable entry reported a public-key document as malformed — and the CLI prints one of those and swallows the other. - Both preflight entry points now refuse a document whose /StmF names an undefined crypt filter. Only Validate did; auto-detection is the one the default CLI invocation reaches first, and it surfaced the decryptor's own exception, which the CLI discarded in silence. - ParsedStream's identity parameters are required. They defaulted to (0, 0) so the old three-argument call sites kept compiling while decryption was wired in; a stream built that way decrypts under the wrong per-object key, and under RC4 that returns plausible bytes with no error. - Both arms of the AESV3 and AESV2 key-length ternaries were the same constant, so no test could ever distinguish a mutation of the comparison. - Two Table 20 citations for /EncryptMetadata that should say Table 21, and a summary an earlier insertion separated from the method it documents.
Everything the handler reads out of /Encrypt runs before the password is checked, on a file anyone can send, and PdfDictionary is a linear-scan list — so copying an /CF entry-by-entry is quadratic in the entry count. Measured here: 4000 entries 174 ms, 8000 442 ms, 16000 1401 ms on a 521 KB file. Table 20 describes /CF as the crypt filters used in the document, and /StmF, /StrF and /EFF can select three between them; 64 is far above any producer and far below where the work starts to matter. This bounds the part the handler adds, not the whole cost — parsing the same dictionary is quadratic too and happens before this code sees it, which is why SECURITY.md now states that limit outright instead of implying the reader cannot be made to spend time. The underlying lookup cost is worth its own change. Also from this round: - The object-stream cache joins the two the purge already cleared. Nothing reachable depends on it — a document whose /Encrypt value lives in an object stream cannot be opened by anything, since decoding the container needs the key that entry helps derive — but leaving one cache out contradicted the purge's own reasoning. - The AOT gate exercises encryption. It opened an unencrypted document only, so the branch's headline feature sat outside the gate meant to prove the library AOT-safe. It now writes an AES-256 document, reads it back through Algorithm 2.A, and checks a wrong password is refused. - DssBuilder and ArchiveTimestampBuilder say why they open a document with no password and no encryption check. It is safe today only because both are internal and fed bytes this library just signed; a public "add LTV to an existing PDF" entry point would reach them with someone else's file. - PdfEncryptionInfo.Permissions documents that at R5 and R6 it reports the sealed /Perms copy, that other tools report the dictionary's /P, and that where they disagree this one is deliberately the permissive answer. - StringCipher documents that it is never Unsupported: an unusable /StrF is refused at open, because a string that cannot be decrypted would otherwise reach the caller as ciphertext. - The cross-reference-stream exemption test read its rows back and checked them against the file instead of asserting the body merely inflated. - Three README-family claims that the reader exposes decoded stream data. It does not: stream decoding is internal, and the public surface reads structure and signatures.
Each was checked by executing it rather than reading it. - The crypt-filter cost in SECURITY.md and the CHANGELOG quoted 0.45 s for sixteen thousand keys. That is the eight-thousand figure, one row up in the same measurement the commit that added the cap recorded; sixteen thousand is 1.4 s. Understating a denial-of-service cost in a security policy is the wrong direction to be wrong in, and the CHANGELOG section becomes the release notes verbatim. - Eight per-package READMEs still described the reader as exposing streams. The previous commit claimed to have removed that claim and removed three of eleven occurrences; seven of the eight remaining ship inside their nupkgs, and the eighth sits thirty-nine lines below the corrected sentence in the same file. The public surface is Catalog, Encryption, Signatures and Dispose; stream decoding is internal. - The fixture regeneration procedure said to read the encryption dictionary with --show-object=8. It is object 8 in the original eight fixtures and object 6 or 9 in four of the nine this branch adds, and asking for the wrong number prints a different dictionary and exits 0 — a verification step that reports success while looking at something else, in the step whose stated purpose is proving the fixture carries the feature. The --json --json-key=encrypt form is object-number independent and is now the instruction. - The CHANGELOG said all eleven baseline rows open under both passwords. Ten did: enc-rc4-objstm.pdf is excluded from the shared theory because its object graph differs, and that exclusion silently took the owner-password assertion with it, leaving the corpus's only object-stream document opened under the user password alone. Adding the missing test makes the sentence true, which is the better of the two ways to fix it — Algorithm 7 reaches the container's decryption by a different route than Algorithm 2 does.
A mutation sweep found the layer nothing tested. The algorithm tests feed handler.O/U/OE/UE straight into a decryptor; the corpus tests read files another producer wrote. Between them sits BuildEncryptDictionary, which decides which of those values goes under which key and what /StmF, /StrF, /V, /R and /Length say about them — and eight separate mutations of it passed every test in the solution. The worst writes /StrF as /Identity. Strings are encrypted on the way out whenever an encryptor is set, whatever /StrF claims, so the file declares its strings to be in the clear over strings that are not, and a reader that believes the declaration hands the caller ciphertext with no error at all. Two more swap /O with /U and /OE with /UE, producing files that open nowhere or decrypt to noise. The rest weaken /Length, /CFM and /Perms in ways only another implementation would see. One test now saves an encrypted Document and opens the bytes with PdfReader, asserting a decrypted STRING as well as a decoded stream — the string is what catches the /StrF mutation, since content streams decrypt correctly under it. A second asserts what the dictionary declares, for the two entries a round trip cannot see. Two more clauses had nothing depending on them, both security-relevant: - The owner-password fallback. With it removed, a document written without an explicit owner password derives /O from the EMPTY string and opens to anyone supplying nothing, at owner privilege. One token, whole suite green. - The per-encryption random IV. At /V 5 the file key is used directly for every string and stream, so a fixed IV makes identical plaintext produce identical ciphertext across the document. A round trip decrypts either way. And three corrections to the previous round's own work: - The /Filter ordering test did not discriminate. A dangling reference resolves to null quietly, so both orderings reached the handler check; it takes an out-of-range cross-reference offset, which throws. Reverting the fix now fails two rows instead of none. - The preflight guard was gating auto-detection on the document-wide /StmF, which refuses a /EncryptMetadata false document whose metadata is exempt from decryption and perfectly readable. It now lets the decode of that one stream decide, and still answers honestly when there is no metadata at all. - The AOT block claimed to decrypt a stream and did not — it passed with the decryption path stubbed to return zeroes. It now decrypts /Perms, and says plainly that a decoded stream is out of reach because those APIs are internal. The crypt-filter cap comment claimed to bound what the handler adds. It bounds one of three quadratic terms: 128 thousand entries directly in /Encrypt still cost about fifty seconds, and no cap on /CF changes that. The comment now says which term it closes and which it does not, and the cap's boundary is tested at 64 rather than well below it.
The test added last round to close the /Perms mutant closed only the omission variant. Its one assertion was that the entry is sixteen bytes long, so writing sixteen ZERO bytes there passed all 5049 tests — and qpdf warns on the result: "/Perms field in encryption dictionary doesn't match expected value". The reader cannot see it by design, because a /Perms that fails its marker check falls back to /P and reaches the same answer. Editing /P in the written bytes is what separates the two sources. The document is written granting print alone; the edit declares everything over a seal that says otherwise, and a reader that reads the seal still reports print. Both the zeroed-/Perms mutant and a /P written as -1 now fail. The same defect, and the same fix, in two more places: - The /P assertion in the declares-the-dictionary test was a tautology. SaveEncrypted never set Permissions, so both sides of the comparison reduced to All whichever source the reader used. That is the second tautology I have written in this file; the comment beside it described a detection nothing performed. - The AOT smoke checked Permissions on an untouched document, which is insensitive for the same reason — it passed with the /Perms decryption stubbed to return zeroes, which is exactly the stub the previous round said it had closed. It now edits /P before reopening, and fails on that stub. And the preflight test written last round asserted nothing at all. It looked for /EncryptMetadata false in a fixture that has no such entry, hit an early return, and reported Passed — a guard that reports success is how it got past review. The document is now written here rather than hunted for, and reverting the guard it covers fails it. Also: the /Filter ordering helper corrupts whatever row happens to be last, with nothing tying that to the object /Length points at, so a later edit adding an object would have silently returned the test to passing for the wrong reason. It now asserts the subsection size it depends on. The CHANGELOG's "four times the work for twice the entries" was 3.1x by its own figures. The preflight comment claimed the decode decides "exactly"; it decides the outcome exactly and the exception's NAME imprecisely, in a case no producer emits.
A routing sweep — sixty-two mutations applied at the joints between types rather than inside them — found four places where both sides were tested and the joint was not. The code is correct at all four; nothing would have noticed if it stopped being. - The decrypt walk has two copies, one in Resolve and one in the object-stream load path, and the suite crossed each on a different axis. The non-zero-generation test resolves the dictionary first, so the second copy never runs; the test that does take that path has an authoritative generation of 0, where the real value and a hardcoded 0 are the same thing. Hardcoding 0 there passed everything. Stream-first with a generation of 5 is the ordering PreflightContext actually uses, and getting it wrong keys the dictionary on one identity and the body on another — which under RC4 returns plausible bytes and reports nothing. - The writer clears its encryptor before writing the trailer, because §7.6.5 says the /ID strings are never encrypted. Deleting that line passed every test: at /V 5 the /ID is not an input to key derivation, so this library reads its own output back perfectly. Encrypted, each element becomes an IV plus ciphertext — three times the length and no longer equal to its twin. Only another implementation would ever see it. - The stale-/Encrypt guard accumulates across revisions, and the chain is walked newest to oldest, so a guard that keeps only the last value it saw keeps the OLDEST revision's. With two revisions that is the same answer. With three, a declaration in the middle one disappears and the document opens as plaintext — the outcome the guard's own comment says must not happen, on a file an attacker can shape. - The authentication purge drops two caches and only the object cache was pinned. An /Encrypt entry may point at a stream (§7.6.1 constrains only the strings), and that stream is cached with no decryptor; dropping the object cache alone leaves ResolveStream handing back a dictionary whose strings are still ciphertext. Each test was verified by applying the mutation that survived the full solution and confirming it now fails, and by nothing else in the suite changing. Left alone deliberately: swapping the /StmF-before-/StrF lookup order in the key-length path also survives, but it is observable only on a document whose two filters name different /CF entries with different lengths, where the failure is a rejected password rather than wrong bytes.
A 53-mutation sweep of the write path found nine clauses nothing depended on. Three are cryptographic, and all three produce a file that qpdf and poppler read without a word: - The file encryption key was not required to be random. Replacing the call that fills it with a constant passed everything: every round trip recovers the key from /UE rather than checking it is fresh, and the different-ciphertext test still passes because the per-string IV varies. Two documents written under the same password must now reach different keys. - /U's validation salt and key salt were not required to differ. If they are equal, the hash that unwraps /UE is byte-identical to the validation hash the file publishes in the clear — so the file key falls out of the document with no password at all. That is a total break, not a weakening. The same on the owner side, via /O and /OE. Both are asserted in the form that matters: not "the salts differ" but "the published hash does not unwrap the wrapped key", which a merely-correlated pair would still fail. Then four places where the writer's encryption was unpinned because no test encrypted a document of the right shape: - Passthrough image streams. RawPdfStream carries every JPEG, JPEG 2000, CCITT and JBIG2 image, and skipping its encryption writes the image into the file verbatim. Its two sibling stream classes were pinned; this one needed a fixture nobody had. - The same stream's /Length, which must count the ciphertext. Stating the plaintext length is the stale-/Length shape this library's own reader papers over by scanning for endstream, and qpdf reports as a recovery. - The /Encrypt exemption's restore, and its narrowness. The objects written after that slot are the outline entries, so a bookmark title went into the file in the clear under either mutation — and no test encrypted a document with bookmarks. - /Perms bytes 12-15, the random padding Algorithm 10 calls for. And one real defect rather than a test gap: a DocumentId that is not 16 bytes was written as no /ID at all, silently. Table 15 requires /ID once /Encrypt is present, so that produced a document qpdf rejects outright. The setter now refuses it. Two harness notes the sweep surfaced, both worth knowing before repeating it: qpdf must be on PATH or four oracle-backed encryption tests pass having asserted nothing, and a two-second mtime bump is not enough to defeat MSBuild's up-to-date check when restoring a mutated file.
DocumentId.set is in PublicAPI.Shipped.txt, so refusing a wrong-length value changes behaviour a caller of the Stable surface could depend on: previously any length was accepted and silently written as no /ID. On an encrypted document that produced a file qpdf rejects, which is why the throw is right — but on an unencrypted one it only omitted an optional entry, so the entry belongs under Breaking changes, not Fixed.
A tenth review round found the Breaking changes section listing the smaller of the branch's two breaks and not the larger one. PdfPreflight.Validate and DetectClaimedProfiles are shipped API in the Stable Conformance package. Every prior version threw UnsupportedPdfFeatureException, and so NotSupportedException, for any /Encrypt at all, so that is what a caller wrote to detect an encrypted file. PdfPasswordException derives from Exception directly and deliberately, so that catch no longer covers it; the CLI needed exactly this fix in 9886419. It was recorded mid-paragraph under Changed, in an entry titled about PdfReader.Open, which is Preview. Someone reading Breaking changes to find out what an upgrade costs them would have missed it. The kernel guide is the only prose that teaches DocumentId, and it never said the value must be 16 bytes, so the new ArgumentException arrived undocumented for anyone following the guide.
_xrefType sat with the decrypt walk's other well-known keys, under a comment saying they are used only by that walk, and was read by nothing. Cross-reference streams are identified positionally, from the offsets XrefParser actually read them at. CryptFilterResolver spells out why a /Type /XRef entry must not decide it: the document's author controls that key and could put it on a page's content stream to have ciphertext handed to a preflight rule. Leaving the name declared reads as if the rejected approach is still live somewhere.
Round 10 ran three independent sweeps. None found a defect in the shipped behaviour. All three found clauses nothing depended on, and two found the same seam from opposite directions. - /F as a file-specification DICTIONARY. Both external-file tests use a string and the only dictionary row was the rejecting direction, so dropping `or PdfDictionary` passed the whole solution while turning every attachment whose /F is a full file specification (ISO 32000-1 §7.11.3) into a stream the reader decrypts. Under AES that is a throw on a legal document. - Both ends of the top-level /Length range. 60 and int.MaxValue are refused by the multiple-of-8 test beside it and 0 by the lower bound, so neither bound was load-bearing: widening the upper one to 100000 passed, and a /V 2 /Length 256 document then derived a 32-byte RC4 key. 32 and 136 are the tight boundaries. - The object stream container's identity, in both directions. The uncompressed half of #192's rule was covered and the object-stream half was not, because the existing container document is generation 0 throughout and the header value and the table value are the same answer. Gutting the restamp passed, and so did forcing the parser to stamp every stream generation 0 -- the fallback for a cross-reference row that cannot express a generation at all. The row that reaches it needs /W [1 4 3], since the shape only exists above the 65535 a two-byte field can hold. - Two of the three ThrowIfNoStreamCanBeDecoded gates in DetectClaimedProfiles. The fixture both existing tests use always has a /Metadata that resolves, so they land in the decode path every time and only the third gate was joined to anything. Without the other two, a document in which nothing can be decoded answers "no conformance claim found" and sends the caller to -p, which then fails for the real reason. Also the limit of /Perms, which the sentence above it invited the opposite reading of: the entry is optional, so deleting it or corrupting one byte of its ciphertext leaves the dictionary's /P as the only answer, and an editor needs no key for either. Both shapes pinned. And three claims the suite made about itself. CryptFilterResolverTests carried two consecutive <summary> blocks on one theory, the first describing a /Type-keyed /EncryptMetadata exemption that the design deliberately rejects in favour of identifying that stream positionally -- so it credited coverage that does not exist, for behaviour the library does not have. EmbeddedFileStream_withNoEff_takesTheDocumentWideStreamFilter claimed reaching for a filter that was never named "would decrypt it twice"; it would not, since both spellings resolve to the stream filter and decrypt once. And EncryptionStructureTests.Build had no callers.
Permissions was documented in four places as the copy sealed inside /Perms at R5 and R6. It is that where there is a /Perms to recover; ISO 32000-2 Table 21 does not require the entry, and Algorithm 13 refuses one whose adb marker does not check out. Renaming /Perms to /Xerms and editing /P -4 to /P -8 on enc-aes-256-r6.pdf makes the reader report the edited value, print bit cleared, and corrupting a single hex digit of the ciphertext does the same. Neither needs the file key. Falling back is still right, and is what qpdf, poppler and pdfium do: refusing the document over an optional entry would make this the only library that cannot open a file every other reader opens. What was wrong was telling a caller enforcing restrictions on an untrusted document to treat the value as what the author granted, since on that path it is what the last editor wrote. Two further limits recorded rather than changed, both measured this round: - At /V 4 with /CFM /V2 this reader honours the crypt filter's own /Length (Table 25) and qpdf 12.3.2 ignores both /Length entries and always uses 16 bytes, so over the full matrix the two open disjoint sets. Neither reading is obviously right, this one is the more literal, and no producer known to emit the shape is available to settle it. Its failure mode is a rejected password, not wrong bytes. - At R5 and R6 nothing authenticates /EncryptMetadata: the flag stops feeding key derivation above R4, so an editor can flip it with no key and change whether the metadata stream is decrypted. Byte 8 of the /Perms block seals the writer's answer and is deliberately not compared, for the same reason Permissions falls back. The result is a corrupted stream, not access.
This was referenced Aug 28, 2026
Tim81
added a commit
that referenced
this pull request
Aug 28, 2026
XrefRevision.StartXrefOffset was assigned on every revision and read by nothing. It was not merely unused but redundant: startxrefForCurrent was initialised alongside currentOffset and reassigned alongside it, so the two were equal at every call site. StandardSecurityDecryptor.TryComputeFileKey was written for PdfReader.Open to lean on, but #212 shipped calling TryComputeFileKeyFromUserPassword and TryComputeFileKeyFromOwnerPassword directly instead, in the opposite order so it can report which one matched. That left the combinator held alive by its own test. Review found that the deleted test also carried the only assertion that an owner password must be rejected as a user password — coverage of a surviving method. That assertion is restored into UserPassword_derivesFileKey_wrongPassword_failsCleanly, verified by mutation. Both removed members are internal, so no PublicAPI baseline moves and no behaviour a consumer can observe changes. No CHANGELOG entry, deliberately. Closes #210 Closes #209
This was referenced Aug 28, 2026
Tim81
added a commit
that referenced
this pull request
Sep 6, 2026
Third and last PR for #97, after the RC4/MD5 primitives (#203) and the decrypt algorithms (#207). Wires them into the reader and ships the public surface. PdfReader.Open(bytes, password) opens Standard-security-handler documents at /V 1, 2, 4 and 5 and /R 2 through 6 — RC4-40 through RC4-128, AES-128 and AES-256 — plus the /Crypt filter and crypt filters naming different methods for strings and streams. Strings are decrypted in Resolve under the identity of the indirect object containing them (ISO 32000-1 §7.6.2, Algorithm 1) and stream bodies on the decode path; ParsedStream.RawBody still holds the verbatim file bytes, which StreamRule and HexStringRule need for byte offsets. Two behavioural breaks, both under Breaking changes in the CHANGELOG. A password-protected document now reaches PdfPreflight as PdfPasswordException, which does not derive from NotSupportedException, so a caller that caught the old UnsupportedPdfFeatureException to detect an encrypted file no longer catches it. And PdfDocument.DocumentId refuses a value that is not 16 bytes, where any other length was previously written as no /ID at all, silently — which produced an encrypted document qpdf rejects outright. A signature dictionary's /Contents is never decrypted. ISO 32000-1 says nothing either way; a signer patches those hex digits into already-serialized bytes, so decrypting them corrupts /ByteRange verification. Measured against qpdf across five signature shapes, and stated in full in the CHANGELOG. Reviewed over ten adversarial rounds. The ninth and earlier each found real defects, among them a cache-poisoning bug that left an object cached as ciphertext, a file key not required to be random, and /U's two salts not required to differ. The tenth found none: three independent reviewers ran 107 mutations, one built a reference implementation of §7.6 from the spec and a 312-file differential corpus, and all 312 open and decrypt correctly. What that round found was five places where the suite was green for the wrong reason, all now joined and each verified to kill its own mutation. Closes #97.
Tim81
added a commit
that referenced
this pull request
Sep 6, 2026
XrefRevision.StartXrefOffset was assigned on every revision and read by nothing. It was not merely unused but redundant: startxrefForCurrent was initialised alongside currentOffset and reassigned alongside it, so the two were equal at every call site. StandardSecurityDecryptor.TryComputeFileKey was written for PdfReader.Open to lean on, but #212 shipped calling TryComputeFileKeyFromUserPassword and TryComputeFileKeyFromOwnerPassword directly instead, in the opposite order so it can report which one matched. That left the combinator held alive by its own test. Review found that the deleted test also carried the only assertion that an owner password must be rejected as a user password — coverage of a surviving method. That assertion is restored into UserPassword_derivesFileKey_wrongPassword_failsCleanly, verified by mutation. Both removed members are internal, so no PublicAPI baseline moves and no behaviour a consumer can observe changes. No CHANGELOG entry, deliberately. Closes #210 Closes #209
Tim81
added a commit
that referenced
this pull request
Sep 6, 2026
Third and last PR for #97, after the RC4/MD5 primitives (#203) and the decrypt algorithms (#207). Wires them into the reader and ships the public surface. PdfReader.Open(bytes, password) opens Standard-security-handler documents at /V 1, 2, 4 and 5 and /R 2 through 6 — RC4-40 through RC4-128, AES-128 and AES-256 — plus the /Crypt filter and crypt filters naming different methods for strings and streams. Strings are decrypted in Resolve under the identity of the indirect object containing them (ISO 32000-1 §7.6.2, Algorithm 1) and stream bodies on the decode path; ParsedStream.RawBody still holds the verbatim file bytes, which StreamRule and HexStringRule need for byte offsets. Two behavioural breaks, both under Breaking changes in the CHANGELOG. A password-protected document now reaches PdfPreflight as PdfPasswordException, which does not derive from NotSupportedException, so a caller that caught the old UnsupportedPdfFeatureException to detect an encrypted file no longer catches it. And PdfDocument.DocumentId refuses a value that is not 16 bytes, where any other length was previously written as no /ID at all, silently — which produced an encrypted document qpdf rejects outright. A signature dictionary's /Contents is never decrypted. ISO 32000-1 says nothing either way; a signer patches those hex digits into already-serialized bytes, so decrypting them corrupts /ByteRange verification. Measured against qpdf across five signature shapes, and stated in full in the CHANGELOG. Reviewed over ten adversarial rounds. The ninth and earlier each found real defects, among them a cache-poisoning bug that left an object cached as ciphertext, a file key not required to be random, and /U's two salts not required to differ. The tenth found none: three independent reviewers ran 107 mutations, one built a reference implementation of §7.6 from the spec and a 312-file differential corpus, and all 312 open and decrypt correctly. What that round found was five places where the suite was green for the wrong reason, all now joined and each verified to kill its own mutation. Closes #97.
Tim81
added a commit
that referenced
this pull request
Sep 6, 2026
XrefRevision.StartXrefOffset was assigned on every revision and read by nothing. It was not merely unused but redundant: startxrefForCurrent was initialised alongside currentOffset and reassigned alongside it, so the two were equal at every call site. StandardSecurityDecryptor.TryComputeFileKey was written for PdfReader.Open to lean on, but #212 shipped calling TryComputeFileKeyFromUserPassword and TryComputeFileKeyFromOwnerPassword directly instead, in the opposite order so it can report which one matched. That left the combinator held alive by its own test. Review found that the deleted test also carried the only assertion that an owner password must be rejected as a user password — coverage of a surviving method. That assertion is restored into UserPassword_derivesFileKey_wrongPassword_failsCleanly, verified by mutation. Both removed members are internal, so no PublicAPI baseline moves and no behaviour a consumer can observe changes. No CHANGELOG entry, deliberately. Closes #210 Closes #209
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Third and last PR for #97. The first two landed the RC4/MD5 primitives (#203) and the decrypt
algorithms (#207); this one wires them into the reader and ships the public surface.
PdfReader.Open(bytes, password)opens encrypted documents: the Standard security handler at/V1,2, 4 and 5 and
/R2 through 6 — RC4-40 through RC4-128, AES-128 and AES-256 — plus the/Cryptfilter (ISO 32000-2 §7.4.10) and crypt filters naming different methods for strings and streams.
Strings are decrypted in
Resolveunder the identity of the indirect object containing them(ISO 32000-1 §7.6.2, Algorithm 1) and stream bodies on the decode path;
ParsedStream.RawBodystillholds the verbatim file bytes, which
StreamRuleandHexStringRuleneed for byte offsets.Closes #97.
Two behavioural breaks, both under Breaking changes in the CHANGELOG
A password-protected document now reaches
PdfPreflightasPdfPasswordException. Every priorversion threw
UnsupportedPdfFeatureException— and soNotSupportedException— for any/Encryptat all, so that is what a caller of
PdfPreflight.ValidateorDetectClaimedProfileswrote to detectan encrypted file. Both are Stable API in a Stable package.
PdfPasswordExceptionderives fromExceptiondirectly, deliberately, so an existingcatch (NotSupportedException)lets it through.The CLI needed exactly this fix during the work.
PdfDocument.DocumentIdnow throws for a value that is not 16 bytes. Any other length waspreviously written as no
/IDat all, silently, and ISO 32000-2 Table 15 requires/IDonce/Encryptis present — so an encrypted document came out that qpdf rejects with "invalid /ID intrailer dictionary", with nothing telling the caller which value did it.
DocumentId.setis inPublicAPI.Shipped.txt, so this is a break on Stable API. Still reversible before merge if youwould rather validate in
Saveonly when encrypting; the setter is a four-line change.What is deliberately left in the clear
Per the spec: the trailer
/ID, the/Encryptdictionary's own strings, cross-reference streams(§7.5.8.2), streams whose data lives in an external file (§7.6.1), and the document metadata stream
under
/EncryptMetadata false(Table 21 — a page's or an XObject's metadata is not exempt).One decision the spec does not settle: a signature dictionary's
/Contentsis never decrypted.A signer patches those hex digits into already-serialized bytes, so decrypting them corrupts
/ByteRangeverification. Measured against qpdf across five signature shapes — it keys on/Type /Sigalone and leaves those
/Contentsbyte-identical while encrypting the other two, so a document anothertool encrypted after signing can hand back an archive timestamp's ciphertext. Stated in full in the
CHANGELOG. Encrypt-then-sign is handled correctly in all shapes.
How this was reviewed
Ten adversarial rounds, agents in separate worktrees. Every round through the ninth found real
defects, and eight of nine found that the previous round's fixes had introduced a new one, left one
half-fixed, or added a test that did not discriminate. The worst finds were a cache poisoning bug
(an indirect
/Encryptvalue left its target cached as ciphertext, silently), a file key notrequired to be random, and
/U's two salts not required to differ — which is a total break, thekey falling out of the document with no password.
Round ten is the first that found no defect in shipped behaviour. Three independent reviewers ran 107
mutations between them; one wrote a reference implementation of §7.6 from the spec and built a
312-file differential corpus, and all 312 open and decrypt correctly here. What they found was five
places where the suite was green for the wrong reason, all now joined, each verified to kill its own
mutation.
Mutation testing is the standard throughout: a test that passes with its clause deleted is not a test.
Verification
Gates, run with qpdf on
PATHandVERAPDF_HOME+REQUIRE_VERAPDFset, because a green local runwithout them means four oracle-backed encryption tests passed having asserted nothing and 278
conformance tests silently skipped:
dotnet builddotnet testdotnet format --verify-no-changeseng/clean-room-check.ps1eng/aot/run-aot-smoke.ps118 encrypted fixtures under
tests/VellumPdf.Reader.Tests/Fixtures/Encrypted/, whose README recordsthe corpus's known gaps — including two divergences from qpdf measured during review, where neither
reading is obviously right and no third producer is available to settle it.
PublicAPI.Shipped.txtis untouched in every project; 21 new symbols, all inUnshipped.txt.Follow-ups filed, not fixed here
#208 (
PdfDictionaryis O(n²) on the pre-authentication path), #209 and #210 (dead internal surface),#211 (an empty-string owner password opens to anyone at owner privilege). #185's first item — the
Openoverloads' stale<exception>docs — is fixed by this PR; its other two are in files this PRdoes not touch, so that issue stays open.