Technical Article

PDF MAC Revision Chain Validation in Delphi (ISO 32004)

An encrypted PDF can carry an ISO/TS 32004 MAC on each of its incremental revisions and still be tampered with while the MAC in its active trailer checks out perfectly. Flip one byte inside revision 1 of a two-revision file, append a third revision with a freshly computed /AuthCode, and that newest MAC really is correct for the bytes it covers. A check that hashes the current byte range and compares it against the active trailer says yes. The edited bytes sit one revision below the active trailer, and the only test that catches them re-verifies each revision against the file exactly as it stood when that revision was written

Two calls, two questions: ValidatePDFMAC and ValidatePDFMACChain

HotPDF keeps the two questions apart because they have different answers on the same file. THotPDF.ValidatePDFMAC asks whether the current revision is authentic and fills a THPDFPDFMACValidationInfo record. THotPDF.ValidatePDFMACChain asks whether every MAC-protected revision in the file is authentic, and fills a THPDFPDFMACChainValidationInfo record with a per-revision array, a Failure code, the index of the revision that failed and that revision's cross-reference offset. On the tampered-then-re-MACed file from the opening, the first call returns True and the second returns False against revision index 1

The reason a single MAC cannot cover the history is built into the format. Incremental update is a first-class part of PDF: every save appends a new body, a new cross-reference section and a new trailer, while the older bytes stay exactly where they were. ISO/TS 32004 rides on that model, so each revision carries its own /AuthCode authenticating the file up to that point

var
  Pdf: THotPDF;
  Options: THPDFPDFMACOptions;
  Current: THPDFPDFMACValidationInfo;
  Chain: THPDFPDFMACChainValidationInfo;
  I: Integer;
begin
  // Validate with the profile the files were written with
  Options := THPDFPDFMACOptions.Modern;
  Pdf := THotPDF.Create(nil);
  try
    Pdf.ValidatePDFMAC('incoming.pdf', 'user', Options, Current);
    if not Pdf.ValidatePDFMACChain('incoming.pdf', 'user', Options, Chain) then
    begin
      Writeln('active trailer MAC valid: ', Current.Status = pmsValid);
      Writeln('chain rejected: ', Chain.Message);
      Writeln('revision ', Chain.FailureRevisionIndex,
              ' at xref offset ', Chain.FailureXRefOffset);
      Exit;
    end;
    Writeln(Chain.ValidatedRevisionCount, ' of ', Chain.RevisionCount,
            ' revisions verified, anchor at ', Chain.FirstMACRevisionIndex);
    for I := 0 to High(Chain.Revisions) do
      Writeln(I, ' len=', Chain.Revisions[I].RevisionLength,
              ' mac=', Chain.Revisions[I].HasPDFMAC,
              ' perms=', Chain.Revisions[I].PermissionsAuthenticated);
  finally
    Pdf.Free;
  end;
end;

Both methods have an overload without the options argument. It validates under THPDFPDFMACOptions.Default, the Compatibility profile, which accepts all six supported digests. If your system only writes Modern or HighAssurance files, pass that profile explicitly, or a SHA-256 file your own writer would never produce will pass

Each MAC verifies on its own prefix, never on the final file length

The expensive mistake when re-hashing an older revision is to use the final file size as the upper bound. That folds later bytes into every digest except the newest, so a perfectly sound file reports tampering on every historical revision. ValidatePDFMACChain instead treats each revision as the file truncated at that revision's own startxref value and %%EOF marker, and hashes only that prefix. The per-revision RevisionLength field reports where each cut was made

The literal %%EOF can appear inside a content stream or a string, so a candidate counts only when the startxref immediately before it parses to the cross-reference offset of the section being validated, with nothing but whitespace in between. Linearized files are the exception the format forces on you: their final footer points back at the first-page cross-reference section, and some writers mark the entry section's mid-file footer with startxref 0, so those anchors are accepted too without ever moving the boundary off the physical %%EOF

After the marker, a revision absorbs exactly one end-of-line sequence: a single CR, a single LF, or one CRLF pair. That rule bites in practice. A writer that emits an extra blank line between two revisions has produced bytes that belong to the next revision, and swallowing all trailing whitespace into the previous one changes both digests

HotPDF verifies each ISO 32004 PDF MAC against a prefix stream ending at that revision's own startxref and end-of-file marker, so a byte flipped inside revision 1 fails the chain even though the newest MAC still validates cleanly
Each revision's MAC is re-hashed over its own bounded prefix, so editing revision 1 and appending a freshly MACed revision still satisfies ValidatePDFMAC while ValidatePDFMACChain lands on revision 1

Section enumeration follows the same discipline. The cross-reference sections are walked oldest to newest exactly once, and each section's free, direct and object-stream entries overwrite the accumulated state, which is the opposite of the first-seen-wins rule a normal viewer applies when it only needs the current object graph. A /Prev pointer that loops back to a section already seen ends the walk with pmcfRevisionBoundary, and so does a chain that reaches 1000 sections, because a truncated history must never pass as a complete one

Where does the chain anchor, and what breaks it?

The first revision carrying a valid /AuthCode is the anchor, and FirstMACRevisionIndex reports where protection begins. Revisions before it are unprotected by construction, which is normal for a document that was edited before anyone MACed it. Everything after the anchor must carry its own MAC, so appending one plain incremental update to a protected file fails with pmcfRequiredRevisionMissing and the offending index. Tolerating that gap would let anyone strip protection simply by saving the file once more

Three more invariants hold across the chain, each with its own failure code and its own flag in the result record

  • pmcfKDFSaltChanged: the /KDFSalt must stay identical from the anchor onward, since a rotating salt would let a forger re-derive keys under parameters of their own choosing; KDFSaltStable goes False
  • pmcfDigestDowngrade: digest strength is compared against the last verified MAC, so a chain that starts at SHA-384 cannot continue with SHA-256; DigestStrengthMonotonic goes False
  • pmcfPermissionDowngrade: a revision may not clear a PDF MAC requirement that an earlier revision had authenticated through its permissions

Historical MACs are verified independently even after they stop being the active trailer. That is why the attack from the opening does not survive: the newest MAC checks out on its own, ValidatePDFMAC is satisfied, and the chain still lands on revision 1 with pmcfRevisionInvalid

What you do with a failure depends on which code came back, and lumping them together produces bad alerts. A wrong password, for example, also surfaces as pmcfRevisionInvalid on the anchor revision, with that revision's Status set to pmsInvalidPassword. Flagging that as tampering sends someone to investigate a typo. A file with no MAC at all returns pmcfNoPDFMAC, which means unprotected rather than modified

// A helper you would write yourself; it is not part of the library
function DescribeChain(const Chain: THPDFPDFMACChainValidationInfo): string;
var
  Idx: Integer;
begin
  Idx := Chain.FailureRevisionIndex;
  case Chain.Failure of
    pmcfNone:
      Result := 'all protected revisions verified';
    pmcfNoPDFMAC:
      Result := 'not MAC-protected';
    pmcfRevisionBoundary:
      Result := 'revision structure cannot be trusted: ' + Chain.Message;
    pmcfRevisionInvalid:
      if (Idx >= 0) and
         (Chain.Revisions[Idx].Status = pmsInvalidPassword) then
        Result := 'wrong password'
      else if (Idx >= 0) and
         (Chain.Revisions[Idx].Status = pmsPolicyRejected) then
        Result := Format('revision %d uses a digest outside the policy', [Idx])
      else
        Result := Format('revision %d modified: %s', [Idx, Chain.Message]);
    pmcfRequiredRevisionMissing, pmcfPermissionDowngrade:
      Result := Format('protection removed at revision %d', [Idx]);
    pmcfKDFSaltChanged, pmcfDigestDowngrade:
      Result := Format('key parameters weakened at revision %d', [Idx]);
  else
    Result := Chain.Message;
  end;
end;

Signature ordering: trailer keys first, signatureDigest last

When the MAC is attached to a CMS signature instead of standing alone, write order becomes a correctness question. /AuthCode, /KDFSalt, the ISO 32004 developer extension and /SigObjRef must be in the revision before the signature /ByteRange is measured. Append any of them afterward and those bytes land outside the range the signature covers, which produces a file whose signature verifies while the MAC binding is unsigned

The two digests then run in the opposite direction, and that looks circular until you trace it. The PDF MAC signatureDigest covers the raw content octets of the CMS SignerInfo.signature OCTET STRING, without the rest of the CMS DER and without the signed attributes. It is computed after the raw signature value exists and injected as an id-attr-pdfMacData unsigned attribute. Since /Contents is excluded from the signature ByteRange and unsigned attributes never feed the signature computation, the sequence produce signature, build MAC, wrap CMS closes with no cryptographic loop

Two practical consequences follow. The /ByteRange sentinel and the /Contents placeholder stay plaintext and outside object streams even in an encrypted file, because the fixed-width patcher has to find and overwrite them in place. And when the PDF MAC digest algorithm matches the signing digest, the byte-range digest is computed once and reused; otherwise the second digest is updated during the same read of the output, so a large file is not streamed twice

The HotPDF write order for a PDF MAC attached to a CMS signature: the MAC keys enter the revision before the ByteRange is measured, and the signature digest is built afterward from the raw SignerInfo signature octets
Writing AuthCode, KDFSalt, SigObjRef and the developer extension before the ByteRange is measured is what keeps the MAC binding inside the range the signature covers

THotPDF.SignPDFWithPFXAndAttachedPDFMAC does all of this in one call on an encrypted input that already has a reserved signature field. It needs Delphi 2009 or later and refuses an input encrypted without AES-GCM when the options demand it

var
  Pdf: THotPDF;
  Options: THPDFPDFMACOptions;
  Info: THPDFPDFMACValidationInfo;
begin
  Pdf := THotPDF.Create(nil);
  try
    Pdf.AutoLaunch := False;
    Pdf.FileName := 'unsigned.pdf';
    Pdf.ActivateProtection := True;
    Pdf.CryptKeyLength := aesgcm;
    Pdf.OwnerPassword := 'owner';
    Pdf.UserPassword := 'user';
    Pdf.ProtectOptions := [prPrint, prExtractContent];
    Pdf.BeginDoc;
    Pdf.CurrentPage.SetFont('Arial', [], 12);
    Pdf.CurrentPage.AddSignedSignatureField('Approval',
      Rect(72, 120, 280, 160), 16384);
    Pdf.EndDoc;

    Options := THPDFPDFMACOptions.Modern;      // SHA-384 document digest
    if THotPDF.SignPDFWithPFXAndAttachedPDFMAC('unsigned.pdf',
         'signed.pdf', 'signer.pfx', 'pfx-secret', 'user', Options) then
      if Pdf.ValidatePDFMAC('signed.pdf', 'user', Options, Info) then
      begin
        // Location = pmlAttachedToSignature; the two digests
        // are reported independently
        Writeln('signature object  : ', Info.SignatureObjectNumber);
        Writeln('signature digest  : ', Info.SignatureDigestMatched);
        Writeln('full file coverage: ', Info.FullFileCoverage);
        Writeln('perms authentic   : ', Info.PermissionsAuthenticated);
      end;
  finally
    Pdf.Free;
  end;
end;

Validation retraces the path from the other end. It reads the direct /AuthCode from the active classic cross-reference trailer, follows the generation-aware indirect /SigObjRef, confirms that it resolves to the value of exactly one signature field, and reports a document-digest failure (pmsDocumentModified) apart from a signature-binding failure (pmsSignatureBindingFailed). One means the page content changed; the other means the signature value was swapped. If you already do CMS work, this sits next to PAdES signing in Delphi and verifying signatures in loaded documents

Why is the /P permission integer not enough?

ISO/TS 32004 signals that a document requires a PDF MAC through permission bit 13, and the obvious place to read it is the wrong one. The /P integer in the encryption dictionary is plaintext and unauthenticated; anyone can flip that bit in a text editor and downgrade the requirement. ISO 32000-2 §7.6 provides the authenticated copy in /Perms, and that is where HotPDF reads it

The 16-byte /Perms string is decrypted with the file encryption key under AES-256 CBC, zero IV, no padding, and every field of the plaintext is checked before anything is believed. Bytes 1 to 4 hold the permission value in little-endian order and must equal /P exactly. Bytes 5 to 8 are 0xFF. Byte 9 is the T or F metadata-encryption flag, and bytes 10 to 12 are the literal marker adb. Only then does PermissionsAuthenticated become True and bit 13 get read, with inverted polarity: the MAC requirement is asserted when the 0x1000 bit is clear

HotPDF authenticates PDF permissions by decrypting the sixteen-byte Perms string with the file encryption key and checking the little-endian permission value, the FF filler bytes, the metadata flag and the adb marker before reading bit 13
The plaintext /P integer is unauthenticated, so the PDF MAC requirement is read only after every field of the decrypted /Perms has been checked

A mismatch between /P and the decrypted value is a forged permission set, and failing closed is the only sane response. In the chain result this shows up per revision through MACRequiredByPermissions and PermissionsAuthenticated, and a revision whose authenticated permissions demand a MAC but which has no /AuthCode fails with pmcfRequiredRevisionMissing even if it comes before the anchor

Algorithm agility stops at the digest

ISO/TS 32004 lets you choose the document digest, and only the document digest. Underneath a variable THPDFPDFMACDigestAlgorithm, which spans pmdaSHA256 through pmdaSHA3_512, HMAC-SHA-256 for authentication, HKDF-SHA-256 per RFC 5869 for key derivation and AES-256 key wrap per RFC 3394 stay fixed. Treating a SHA3-512 profile as license to swap the HMAC too yields a file that other ISO 32004 verifiers have no reason to accept

One detail is worth copying into your own verifier. Read the digest OID out of the CMS AuthenticatedData before hashing the byte range. Hardcoding SHA-256 and reconciling afterward turns agility into a label, and it lets a hostile file make you stream the whole document before you learn the algorithm was never supported. CMSAlgorithmProtection, the AuthenticatedData digest algorithm, the integrity-info messageDigest and the byte-range digest must all name one algorithm, and any disagreement fails closed

var
  Options: THPDFPDFMACOptions;
begin
  Options := THPDFPDFMACOptions.Compatibility;  // writes SHA-256, accepts all six
  Options := THPDFPDFMACOptions.Modern;         // writes SHA-384, rejects 256-bit digests
  Options := THPDFPDFMACOptions.HighAssurance;  // SHA3-512 only, requires AES-GCM

  // A custom profile is legal, but the algorithm it writes with must
  // also be in the validation allowlist, or the configuration is
  // rejected before a single byte is written
  Options.Profile := pmppCustom;
  Options.DigestAlgorithm := pmdaSHA512;
  Options.AllowedDigestAlgorithms := [pmdaSHA512, pmdaSHA3_512];
  Options.RequireAESGCM := True;
end;

The built-in profiles are fixed: a record labeled HighAssurance with AES-GCM switched off, or with a wider allowlist, is rejected. A different policy means pmppCustom, stated openly. For new documents Modern is the sensible starting point, since it keeps 256-bit digests out of both writing and validation without forcing every recipient onto AES-GCM

What a verified chain proves, and what it cannot

A verified chain proves that every protected revision is byte-identical to what was written by someone holding the file encryption key, that no protected revision was removed or reordered, and that no unprotected revision was appended after the anchor. Plain AES-256 encryption leaves exactly that class of attack open. Confidentiality says nothing about integrity, and an encrypted PDF with a spliced revision decrypts as happily as an intact one

Authorship is outside what a MAC can establish. The MAC key derives from the file encryption key, so anyone who can open the document can also produce a valid MAC over a modified version, every legitimate recipient included. To know who changed something you need a digital signature backed by a certificate, and the PDF MAC then protects the incremental structure around it. Report the two verdicts side by side in your UI instead of collapsing them into one status icon

The calls covered here, AddStandalonePDFMAC, SignPDFWithPFXAndAttachedPDFMAC, ValidatePDFMAC and ValidatePDFMACChain, are part of the HotPDF Delphi Component for Delphi and C++Builder; its product page lists the options record, the status and failure enumerations, and the fields of the per-revision result array