This review documents security checks performed on the PHP generator and its locked dependencies: code review, regression tests, dependency audit and PDF validation by independent readers. It covers PDF value serialization, inline images, binary resources, graphs, numeric limits and file writing. The results below concern the verified surfaces and scenarios; they are not a guarantee of the absence of every vulnerability.
TrueType and PNG/JPEG converter checks are now maintained in the optional pdf-fonts and pdf-images modules. PDF objects and their invariants remain in the core. The pdf-reader module has its own security documentation for reading external files; this generator review does not replace it.
The source manifest pins versions and revisions: core 0.12.4, Reader 0.8.1, PDF-to-HTML 0.8.4, Images 0.2.3, Fonts 0.2.1, OpenType 0.4.1, Codecs 0.1.1 and HTML-to-PDF 0.4.0. These libraries use 64-bit PHP 8.3+; qualification covers PHP 8.3/8.4/8.5. PDF 2.0 companion mechanisms retain their own scope. Definitions and conformance declarations are not security certificates. OpenType and Codecs have format controls and limits separate from the writer.
The 0.8.4 PDF-to-HTML module with the selected reader 0.8.1 retains its own security checks and explicit policies. Independent tests verify HTML/CSS/URL filtering, associations and IDs, cumulative budgets, inline images and runtime confinement to bound controls. PDF scripts, remote resources and ResetForm/SubmitForm actions are disabled by default. Enabling the library-owned reset does not enable source scripts. HTML 0.8 separates the explicit local-stylesheet capability from script permission: its bounded filter rejects remote resource functions and imports, preserves ordered declarations, and accepts the documented subset of nested conditions. The demo selects that capability explicitly; the library default remains unchanged. Rendering remains application-supplied. Native password or certificate authentication is an explicit reader selection; the HTML authentication guide shows its construction. The receiving HTML viewer must enforce verified permissions. A wrong native password does not fall back to another provider.
PDF-to-HTML 0.6 accepts an explicit SignatureValidationProvider. Its supplied
SignatureOutputValidation adapter binds results to the exact source request,
requires a physical Contents span and complete signed revision, then verifies
the covered bytes with the selected certificate. integrity-verified does not
mean trusted identity, revocation checks or permission for later PDF changes.
The signature guide
explains independent states and the native escaped status popover. Derived HTML
is a new unsigned artifact. Appearance rendering reuses the explicitly supplied
content engine with verified raster bytes and cumulative document budgets.
Reader 0.3.1 limits the EncryptMetadata=false exemption to the actual catalog
metadata object; page and Form metadata remain encrypted unless they explicitly
select Identity. It resolves indirect stream types before selecting EFF, uses
the fixed 128-bit V4 file key and ignores attempts to redefine the standard
Identity filter. Its seven additional regression cases
use qpdf and cryptography with the specific oracle boundaries explained in the
authentication guide.
Reader 0.4.1 preserves terminal object numbers and generations through Encrypt,
Root and catalog Metadata reference chains. Re-reading O/U credentials does
not decrypt them, and only the actual correctly typed catalog metadata receives
the implicit cleartext exemption. Four additional encrypted-alias cases use
pyHanko's unchanged strict parser and Standard handler with cryptography.
The high-level qpdf/pypdf/pyHanko decryptors do not follow these Encrypt chains;
their earlier independent checks remain intact. The module guide states those
oracle limits without extending the exemption to page or object metadata.
Bounded mechanisms and explicit capabilities
- Core dictionary rules execute source-linked domains and entry relationships; they do not sanitize arbitrary graphs or certify every normative condition.
- Native redaction deletes affected content, shared payloads and ancillary channels before writing a fresh file. Default preservation requires normalized device samples and trusted resource semantics; unsupported content is rejected, and retained complex resources need an explicit sanitizer. The process intentionally permits excess deletion. Reverse Mask/SMask/Form dependencies are excluded globally; font descriptor metadata is stripped, and retained values require validated types and context. Rotation/shear bounds use four rectangle corners, and unpainted source paths crossing a region are removed as recoverable geometry.
- The optional WTPDF XML parser forbids DTDs, external entities, remote resources and active content and applies byte/node/depth budgets. Unsupported rich text remains pending; XML comparison does not establish accessibility.
- Reader 0.3 authenticates explicit R=2–7 credentials and decrypts each payload
once. Named crypt filters, object streams and AES-GCM tags have independent
fixtures. Retained plaintext shares cumulative budgets; original ciphertext is
separately available. Reader 0.4 additionally verifies indicated source PDF
MACs before protected content is interpreted.
RequirePdfMacrejects unprotected or stripped input; the compatible default also accepts ordinary unprotected PDFs. Exact lexical token identity, full-current-file byte coverage and CMS framing are checked. This does not verify signature mathematics or certificate trust; a holder of the file key can construct a new MAC. The source MAC guide explains policies, budgets and rejection boundaries. Reader 0.5 adds explicit Adobe.PubSec authentication. CMS packet, identity and attempt budgets cover independent filters and deferred attachment access. Permissions are authenticated recipient facts; bit 2 does not imply a Standard owner login, and bit 13 cannot bypass required MAC checks. The application supplies certificate/key bytes and enforces effective rights. Certificate decryption grants neither signature trust nor revocation status. - Barcode preparation compresses the whole explicit value before ordered
partitioning and checks cumulative budgets before invoking the next supplied
encoder. The core constructs native full-rectangle
AP.Nimages; symbology, quiet zones and the encoder's own execution remain its explicit capability. - WTPDF Type 3 inspection follows actual selected glyph programs and bounded nested resources. Contextual deprecation checks distinguish recommendations from failures; opaque programs and missing file context stay pending.
- Reader 0.6 exposes physical revision history separately. Prefixes, xrefs and
objects retain source bytes, including ciphertext; this inspection does not
authenticate them or verify signatures. Interpreting a prefix requires its
own credentials and MAC policy. This history does not confer the authority
of a native
FileRevision. - OpenType 0.3 bounds offsets, records, bytes, points, operations and recursion. TrueType/CFF/CFF2 geometry, gvar/cvar and variable metrics are compared with fontTools; substitutions and positioning are compared with HarfBuzz. Type 2 programs execute to produce unhinted outlines. Preserved TrueType instructions do not constitute an executed VM. No rasterizer or complete Unicode shaping engine is claimed.
Results and protections
| Surface | Review result |
|---|---|
| Names, strings, numbers, header | Separators and bytes are escaped, literal strings preserve data, numbers are finite and header versions are limited by an enum. Payloads attempting to close a string or introduce other objects remain data. |
| PDF streams | /Length is calculated from encoded bytes. endstream markers within data do not change this length. StreamObject rejects external /F, /FFilter and /FDecodeParms entries. |
| Inline images | An EI ambiguity was corrected: a tolerant reader may recognize the terminator without preceding whitespace. Bytes could then be read as content operators. Such sequences are now rejected; an image XObject provides a separate representation with an explicit length. |
| Image dimensions | Checked integer calculation of row bytes and the total. Overflow is rejected rather than passing through a float and an incorrect length. |
| PNG/JPEG import — pdf-images module | Explicitly supplied bytes, without path/URL loading. Limits on bytes, pixels, dimensions and segments; PNG CRC/order/filters/bounded zlib; JPEG markers, tables and colors inspected. A separate rendering reader decodes JPEG coefficients. |
| Font programs — pdf-fonts | Explicit bytes; bounded tables, glyph references and cycles. Static TrueType/CFF1 and selected collection faces feed explicit layout/embedding. Variable/CFF2 embedding remains rejected. OS/2 permissions follow their source version; font licensing remains an application responsibility. |
| Shared operands | Validation visits each identity once, with a separate set for active ancestors. It preserves cycle rejection without exponentially revisiting a shared subgraph. |
| Cross-references | Initial gaps receive free records as required by the standard. CrossReferenceLimits bounds cumulative capacity before allocation. Incremental sections remain partial; additions for /Size and the xref stream number are checked. |
| Revisions | Old-number reservations, preserved generations and aliases; structural-container replacement rejected even through a new object stream. Catalog and page-tree metadata are checked against effective values. Old bytes remain in the file: an update cannot erase a secret. |
| File output | Path validation before serialization, rejection of stream URIs, write exception without path disclosure. A graph validation error occurs before opening an existing destination. |
| Dependencies | No known advisory or abandoned package reported by composer audit --locked during the review. This check runs in every CI build. |
| Historical Adobe R=5 encryption | Official AES vectors, qpdf fixtures and independent string/stream decryption, with user/owner passwords and incorrect-password rejection. Checks of lengths after filtering and encryption, absence of double encryption and structural exceptions. |
| Password preparation | Fixed Unicode 3.2 SASLprep/NFKC, compared with an independent oracle: mappings, prohibited and unassigned characters, bidirectional rules and truncation after normalization. |
| ISO R=2/3/4 encryption | Algorithms 1–7, user/owner credentials, RC4 and AESV2, 40–128-bit keys, implicit and explicit filters and incremental revisions. Explicit Crypt filters use their key directly according to 7.4.10; implicit streams use per-object derivation. |
| Certificate encryption | CMS messages, recipient grouping, s3/s4/s5 formats and distinct document and attachment keys. Independent verification of CMS data, keys and decryption. Permission byte order is an explicit choice. |
| Encrypted-writer boundary | Direct trailer strings outside ID rejected; Encrypt dictionary and xref remain clear. Only catalog metadata may be exempted; replacement follows the revision's effective binding. A new PHP identity cannot replace Encrypt inside an object stream. |
| Signatures | ByteRange fixed before signing, Contents reservation with explicit capacity, delimiter checking and filling without shifting offsets. The three ISO formats undergo independent verification of digests, CMS messages and RSA signatures. |
Explicit stream-URI rejection hardens the writeTo() contract rather than correcting demonstrated PHP execution: LOCK_EX already blocked common wrappers on the verified PHP 8.5 runtime. A native destination may still follow a symbolic link or point to a network share depending on the system. The application must control its location and permissions.
Using data in the right place
ShowText(new LiteralString($text)) escapes string syntax. NameType($name) escapes name syntax. However, StreamObject($rawContent) writes supplied bytes: when used as /Contents, they are PDF drawing code. Use ContentStreams and its typed operators to compose content from external text.
A PDF can represent a JavaScript action, launch action or URI. The library does not execute them in PHP and retains these definitions because they belong to the format. A reader may interpret them later. An application accepting user choices must allowlist action types and destinations rather than freely accepting an arbitrary graph or entries.
EncodedData passes already-encoded bytes. It does not analyze or decompress an incoming PNG, JPEG or PDF. The PngImageDecoder and JpegImageReader in pdftoolkit/pdf-images perform their dedicated validations and receive explicit limits; they do not replace an upload service's quotas or access controls. The core's DCTImage accepts an explicitly declared DCT representation without inspecting its markers. Font programs are also binary data; their analysis belongs to pdftoolkit/pdf-fonts. Hinting engines and DCT decoding remain executed by the reader opening the document.
Writing or serving a document
The application must choose the writeTo() path in a controlled location. The method overwrites an existing destination and does not create its parent directory. It is neither a path sandbox nor an atomic write: a hardware failure during writing may leave an incomplete file.
For an HTTP response, the application can send toPdf() bytes with its own access controls and appropriate headers:
$bytes = $document->toPdf();
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="document.pdf"');
header('X-Content-Type-Options: nosniff');
echo $bytes;
The download filename is fixed here. Request data must not be interpolated directly into headers or paths. Repository examples are CLI scripts; their first argument is a path selected by the person running the command.
Availability and coverage
Numeric checks prevent identified overflows; operand validation avoids unnecessary revisits. They do not replace service quotas. A shared direct graph can represent very large output when expanded into PDF syntax. A filter chain can also greatly increase byte counts. An input-size limit alone therefore does not bound all serialization.
SecuritySerializationTest, SecurityLimitsTest and FileOutputTest cover injection payloads, all 256 byte values, inline terminators, numeric bounds, shared graphs and output. ImageObjectsTest, CrossReferenceSectionTest and IncrementalUpdateTest cover core PDF invariants. Image-decoding regressions are in the module's ImageImportTest. TrueType validation remains in font module tests. Independent pypdf reads confirmed binary vectors and reproduction of the inline ambiguity. qpdf checks every example in CI.
This review is not an audit of PDF readers, PHP, the HTTP server or a future layout library. Generated definition files express standard constraints; they are not a general document-sanitization policy.
Cross-review of new mechanisms identified two defects in development versions: a metadata exemption attached to an old identity and replacement of Encrypt by an object-stream member. EncryptedRevisionInvariantTest checks their corrections, including actually written XML content.
The ISO, certificate and signature validators are development dependencies with locked versions and hashes. Every oracle states its reader's limitations: qpdf 12.4.2 also derives a per-object key for explicit Crypt; pyHanko verifies the ISO rule without modifying its algorithms. For some older RC4 variants, pypdf uses its own general provider to accept every permitted integer length.
A mathematical signature does not establish trust in its signer. Certificate policy, revocation, timestamping and interpretation of permitted changes require separate checks. Private keys in fixtures are public and exclusively intended for tests.
The native backend checks table 257 algorithms and key sizes against the
effective PDF version. The historical CMS backend uses SHA-256;
ModernCmsSignatureBackend provides its own explicit digest/curve selection
and independently checked PDF 2.0 operations. SignatureFieldSigning
orchestration applies actually written seeds, locks, certificates and
appearances, then mathematically verifies the result before filling the
reservation. An unavailable digest or evidence requirement remains rejected.
Simple signing rejects policies that require this dedicated contract.
A certificate chain declared for a PKCS#1 signature must start with the
certificate actually used by this backend.
The output verification, field-policy and historical-permission tests cover altered output, mismatched certificates, replayed facts, locks and permissions. The policy oracle verifies eight PDFs and nine RSA/DSA signatures without modifying readers. General comparison of MDP/UR-permitted modifications remains separate.
The common native incremental boundary applies DocMDP/FieldMDP and compares
the complete frozen delta, even without PreparedSignature. Core 0.11 extends
Tx/Ch/Btn filling to exclusively owned indirect values and bounded XML rich
text, with fully regenerated normal appearances. It permits limited historical
page-template instantiation without annotations and retains the explicit P3
annotation list. These operations cannot change shared resources or unrelated
objects.
UR3 requires explicit authority over verified signature facts and a per-update
operation scope. Encrypted histories require PasswordUsageRightsAuthentication
or CertificateUsageRightsAuthentication: credentials recover the actual keys,
including every named filter, and CMS recipient permissions are not inferred
from Encrypt.P. An owner login overrides neither UR, DocMDP/FieldMDP nor the
application scope. Adding a signature field separately requires AddField.
The historically signed PDF version selects UR3 semantics: PDF 2.0 with
P=false or absent ignores UR restrictions without removing the other proofs;
with P=true, filling requires FullSave. Legacy UR handlers remain refused.
Terminal signing and DSS/timestamp maintenance retain separate proofs;
unsupported combinations of operations are refused. The
protected-revisions guide explains contracts and
pyHanko classification differences; the migration guide
explains new objects and edition choices. Tutorial 37
shows native form filling.
Use the original native FileRevision emitted in the current runtime. Supplied
snapshots, clones and PHP serialization cannot preserve its emission authority.
Completed historical signatures must have actual verification bound to the final
bytes, ByteRange, Contents, signature dictionary and signing credential,
including the final CMS/MAC when applicable. Opaque finalize() bytes alone do
not establish this evidence. The checks establish mathematical integrity, not
PKI trust or arbitrary external-PDF change classification. The
incremental-permission regressions
and independent permission oracle
exercise both permitted native operations and rejected unrelated changes.
The retained-source guide
records exact source pages, supported operations and migration choices.
AdobeEncryptionTest and validate_adobe_encryption.py cover historical R=5. This protocol is explicitly selected for interoperability: its password derivation is old and AES-CBC does not authenticate content. SASLprep preparation does not strengthen a weak password. The Adobe guide states the mechanisms actually available and their limits.
PDF 2.0 cryptography, metadata and audit boundaries
ModernStandardSecurityHandler keeps R=6 AES-CBC separate from TS 32003
R=7 AES-GCM. The latter authenticates encrypted values and uses an explicit
per-key nonce sequence, rejecting duplicates and bounding invocations. The
application must preserve that allocation for the lifetime of the key, including
across processes. TS 32004 PDF MAC authenticates the covered serialized revision,
including structural bytes. Native writers compute a fresh standalone or
signature-attached MAC for initial, incremental and linearized output. Altered
ciphertext, wrong passwords, tampered MAC data and inconsistent key/salt/permission
relationships are regression cases. AES-CBC alone does not authenticate content,
and historical Adobe R=5 is rejected for effective PDF 2.0.
SHA3-256/384/512, fixed-output SHAKE256 and supported modern curve/digest pairs are explicit selections with separate ISO extension declarations. RSA/ECDSA uses PHP OpenSSL. Ed25519/Ed448 requires an explicitly selected executable provider with an explicit key and executable; other operations do not launch a process. The tests' certificates and private keys are public fixtures, not production credentials. Independent pyHanko, cryptography, ASN.1 and OpenSSL checks validate actual output; see the crypto oracle.
RFC 3161 document timestamps require a caller-selected token provider and authority verifier. DSS/VRI objects store supplied certificate, CRL and OCSP evidence; storage alone does not establish freshness, revocation status or trust. The timestamp-maintenance policy compares the frozen incremental delta before allowing the narrow DocMDP timestamp/DSS exception. It does not permit arbitrary page/content changes, override FieldMDP or replace general authenticated revision analysis. Network retrieval, trusted roots and validation policy remain explicit application decisions; no URL in metadata triggers a fetch. The timestamp/DSS tutorial shows the actual revisions and the evidence-validation boundary.
Native XMP objects validate UTF-8/XML characters and escape RDF/XML values. Metadata owners, marked-content resource scopes, associated files, flat DParts arrays, explicit parents, XMP on DPartRoot and encrypted-wrapper discovery are checked against the effective graph. Caller-supplied opaque XML/content and embedded payload bytes are not parsed or trusted by this model. Declarations state an author's claim at the chosen scope; they do not prove that claim. The metadata oracle uses independent XML/PDF readers and decrypts the example's inner PDF separately.
WtPdfAudit is a partial mechanical audit, not certification. Malformed
references, unresolved roles and invalid structures become failed findings;
legitimate indirect booleans are resolved. Traversals reject cycles, and explicit
budgets bound structure/font inspection, cumulative Unicode mappings, operations
and text bytes. A budget exhaustion aborts the audit rather than returning a
successful report. An absence of detected failures does not discharge pending
checks for reading order, useful descriptions, Unicode meaning or external
font-program evidence. The namespace tutorial
shows both failures and remaining evidence requirements.
Policy and private reporting · Architecture · Standard coverage
Reader image decoding has separate ImageLimits: native header inspection, metadata/index retention, output planes and work are budgeted before invoking the bounded Ghostscript process. Only unavailable capabilities trigger PHP fallback; malformed inputs and limits remain errors. Native execution sanitizes inherited Ghostscript configuration, uses no shell and receives image bytes on stdin. These controls are not a general OS sandbox. The image codec guide records exact profiles and tests. Importing a graph preserves source bytes and rejects transfer of signature/encryption authority; it does not certify its semantics or grant reuse rights.