Technical Article

Signature Wrapping in PDFs: ByteRange Gaps and Countersigns

A signed PDF can carry a forged page, pass a CMS digest check and claim that its signature covers the whole document, all at once. Every signed byte remains exactly as the signer left it, the /ByteRange still runs from 0 to the file size, and the extra objects sit in the one stretch of the file that a PDF signature deliberately keeps out of the digest: the space reserved for the /Contents hex string

That stretch is larger than most people imagine. Reserve 8,192 bytes for the CMS container and you get 16,384 hex digits on disk, with every digit the real signature leaves unused padded out using 0. A verifier that asks only whether the gap between the two ranges is non-empty never inspects what the gap actually holds. The same layout question arises from the opposite direction when a contract needs a countersignature: the approver's signature must be appended without disturbing a single byte the vendor signed, and its placeholder has to land in precisely the shape a strict verifier will accept

What the ByteRange gap has to contain

The gap has to hold the complete /Contents value and nothing besides. ISO 32000-1 §12.8.3.3 states that the hexadecimal string, delimiters < and > included, fits exactly into the space between the two byte ranges, and ISO 32000-2 §12.8.1 carries the rule forward unchanged. Table 252 and the PAdES documents put it more loosely, saying merely that the digest excludes the Contents value. Skimmed quickly, that reads like "exclude the hex digits", and a signer following the loose reading hashes the two angle brackets along with everything else. Validators that compare the gap against the signature value then flag the byte range as invalid

HotPDF follows the §12.8.3.3 wording on both of its signing routes. THotPDF.PreparePDFForSigning ends the first range immediately before < and starts the second immediately after >, and the streaming preparation within the CMS signing pipeline computes the same offsets. The /ByteRange placeholder in the signature dictionary is a fixed-width literal string, so patching in the real numbers never moves a byte and the cross-reference table remains valid. Each of the four values sits right-aligned in a ten-character field, which is why a file signed this way shows /ByteRange [ followed by runs of spaces. We paid for that padding once whilst driving a standalone verifier of our own: our first cut split the four numbers on single spaces and found nothing, and the /Contents hex yielded the real CMS bytes only once its trailing zero padding had been stripped

Two bytes suffice to check any signed file yourself, whoever produced it. The byte at offset ByteRange[1] must be <, and the byte at offset ByteRange[2] - 1 must be >. The helper below forms no part of the library; it is a dozen lines you can drop into an audit tool, fed with the ByteRange array from GetLoadedSignatureInfo

// Suggested helper for your own audit code, not a HotPDF API
function GapIsSpecLayout(const FileName: string;
  const BR: array of Int64): Boolean;
var
  FS: TFileStream;
  B: AnsiChar;
begin
  Result := False;
  if Length(BR) <> 4 then Exit;
  FS := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
  try
    FS.Position := BR[1];               // first byte of the gap
    if (FS.Read(B, 1) <> 1) or (B <> '<') then Exit;
    FS.Position := BR[2] - 1;           // last byte of the gap
    if (FS.Read(B, 1) <> 1) or (B <> '>') then Exit;
    Result := True;
  finally
    FS.Free;
  end;
end;

// Usage, after Pdf.LoadFromFile('Signed.pdf'):
//   if not GapIsSpecLayout('Signed.pdf',
//     Pdf.GetLoadedSignatureInfo(0).ByteRange) then
//     Writeln('Brackets sit inside the signed ranges');

For the cryptographic half, OpenSSL verifies the CMS on its own: concatenate the two ranges into one file and pass that as external content, for instance openssl cms -verify -binary -inform DER -in contents.der -content signed-ranges.bin -noverify. That command checks the digest and the signature over exactly the bytes you hand it. It never claps eyes on the gap, so the two-byte check above remains your job

Anatomy of a correctly filled PDF signature ByteRange in HotPDF: the first range covers the file from byte zero, the gap holds the complete /Contents hex string with the less-than and greater-than delimiters included, the second range covers the trailer through to the end, and two one-byte checks at ByteRange[1] and ByteRange[2] - 1 confirm the layout on any signed file
The delimiters sit outside the signed ranges, so the digest covers the digits alone and the gap can be validated byte by byte

Why does a non-empty gap check overlook signature wrapping?

A non-empty gap proves that something was left out of the digest and says nothing whatsoever about what. That is the entire attack surface. The /Contents placeholder is reserved with thousands of zero digits, and a real CMS container rarely fills it. An attacker closes the hex string early inside that padding with a >, writes new objects, or a whole forged revision, into the rest of the reserved space and leaves the byte ranges untouched. The CMS still verifies, because every signed byte is unchanged. The ranges still run from 0 to the file size. A verifier that stops at "the gap is non-empty" reports svValid with CoversWholeDocument set to True, whilst any PDF parser opening the file follows whatever objects sit in the unsigned hole

THotPDF.VerifyLoadedSignatureEx treats the gap as data worth validating. Once the CMS check passes, the verifier reads the gap, strips the delimiters and accepts only hex digits together with the five PDF whitespace bytes (tab, line feed, form feed, carriage return, space). The decoded digits must then equal the signature dictionary's own /Contents byte for byte. A stray >, a single binary byte, or a decoded value one byte too long or too short turns the result into svInvalidByteRange, as does a gap larger than 64 MiB. The same check runs in ValidateLoadedSignatureBatch; VerifyAllLoadedSignatures and VerifyLoadedSignatureWithTrust travel the single-signature path and so inherit it too

One layout is deliberately waved through: files whose signer kept the brackets inside the signed ranges, so that the gap holds only the digits. For those, the verifier confirms the byte immediately before the gap is < and the byte immediately after it is >, then applies the same digit-and-whitespace test. Rejecting that layout would buy no safety, since the gap still contains nothing beyond the signature value, and it would fail archived contracts that are perfectly intact. Accepting it is the sensible default

How signature wrapping exploits a loosely checked PDF ByteRange in Delphi: the attacker closes the hex string early inside thousands of reserved zero digits, writes a forged revision into the unsigned gap without touching any covered byte, and a non-empty gap check still reports svValid with CoversWholeDocument true; hence HotPDF validates the gap byte by byte
A non-empty gap only proves something was left out of the digest, not what — the padded hole is the entire attack surface
var
  Pdf: THotPDF;
  Info: THPDFSignatureInfo;
  Status: THPDFSignatureVerifyStatus;
  I: Integer;
begin
  Pdf := THotPDF.Create(nil);
  try
    Pdf.LoadFromFile('SignedTwice.pdf');
    for I := 0 to Pdf.GetLoadedSignatureFieldCount - 1 do
    begin
      Status := Pdf.VerifyLoadedSignatureEx(I, Info);
      case Status of
        svValid:
          if Info.CoversWholeDocument then
            Writeln(Info.FieldName, ': valid, covers the whole file')
          else
            Writeln(Info.FieldName, ': valid, ',
              Info.UnsignedTrailingBytes, ' bytes appended later');
        svInvalidByteRange:
          Writeln(Info.FieldName, ': ByteRange gap rejected (wrapping?)');
        svSourceUnavailable:
          Writeln('Loaded from a stream: use the TStream overload');
      else
        Writeln(Info.FieldName, ': failed, status ', Ord(Status));
      end;
    end;
  finally
    Pdf.Free;
  end;
end;

Both GetLoadedSignatureFieldCount and the index handed to VerifyLoadedSignatureEx count signature fields in form-field order, beginning at 0. In a countersigned file the vendor's signature falls into the first branch with CoversWholeDocument = False and a positive UnsignedTrailingBytes: everything appended after it, the approver's revision included. Should the basics of this API be new to you, the guide to verifying PDF digital signatures with HotPDF covers the status values and the info record in greater depth

Countersigning via AddLoadedSignedSignatureField

A countersignature takes four calls: open the signed file with BeginIncrementalUpdate, add the field with AddLoadedSignedSignatureField, write the new revision with SaveIncrementalUpdate, then sign the prepared file with the class function THotPDF.SignPDFWithPFX. The page-level THPDFPage.AddSignedSignatureField has no role here, because CurrentPage is nil during an incremental update; the document is loaded rather than being laid out. The loaded-document method creates the widget on an existing page and hangs beneath /V the very same placeholder signature dictionary the new-document path builds, so both signing routes see identical bytes. For the first signature itself, the article on creating PAdES digital signatures in Delphi walks through the PFX pipeline

var
  Pdf: THotPDF;
  FieldIndex: Integer;
begin
  Pdf := THotPDF.Create(nil);
  try
    Pdf.BeginIncrementalUpdate('Signed.pdf');
    // Page 0, widget rectangle in points, 8192 bytes reserved for the CMS
    FieldIndex := Pdf.AddLoadedSignedSignatureField(0, 320, 60, 520, 120,
      'ApproverSignature', 8192, 'adbe.pkcs7.detached',
      'Approved for payment', 'Head office');
    if FieldIndex < 0 then
      raise Exception.Create('Page index out of range');
    Pdf.SaveIncrementalUpdate('Prepared.pdf');
  finally
    Pdf.Free;
  end;

  // Signs the first unfilled placeholder; raises on PFX or crypto errors
  if not THotPDF.SignPDFWithPFX('Prepared.pdf', 'SignedTwice.pdf',
    'approver.pfx', 'pfx-password') then
    raise Exception.Create('Second signature failed');
end;

The parameter list is short, yet each value has a visible effect. ContentsBytes defaults to 8192 and sizes the decoded CMS container; the placeholder on disk holds twice that many hex digits, floored at 64 bytes. SubFilter defaults to adbe.pkcs7.detached, and Reason, Location and ContactName end up in the signature dictionary as /Reason, /Location and /ContactInfo, beside a /M timestamp taken when the field is created. The return value is the new field index, or -1 when the page index falls outside range. An empty field name or a rectangle of zero width or height raises an exception before anything gets written

What the appended revision carries, and what it leaves untouched

AddLoadedSignedSignatureField is deliberately quieter than its siblings. The other AddLoaded* field creators set /NeedAppearances true on the AcroForm, asking a viewer to regenerate field appearances when it opens the file. On a signed document that regeneration can rewrite content the first signer covered. The new method therefore removes the flag again whenever the source file did not already carry it, and a file that arrived with /NeedAppearances keeps it exactly as it was. /SigFlags retains its existing bits and gains 3, being SignaturesExist (1) plus AppendOnly (2) from ISO 32000-1 §12.7.2, Table 219

Leave MarkDirty alone where the page is concerned. In incremental mode, newly created objects are written automatically, whilst loaded objects are written only when something marks them. Adding the widget to the page's /Annots and to the AcroForm /Fields already pulls whatever indirect objects own those arrays into the new revision. An explicit page mark drags the page dictionary along even where its /Annots array lives in a separate object, and revision analysis then reports a page modification in a revision that ought to contain nothing beyond a signature field

The placeholder dictionary writes /ByteRange ahead of /Contents. That ordering matters should you post-process the prepared file with tools of your own: PreparePDFForSigning finds the /ByteRange sentinel first and then searches forward for the next /Contents <. A dictionary with the keys swapped would send that forward search straight past its own hex string and into whatever comes next in the file

Where the first signer applied a DocMDP or FieldMDP restriction, SaveIncrementalUpdateAuthenticated is the stricter route to revision 2. It saves to a candidate file in the same directory, authenticates every signature carrying a transform policy, evaluates all revisions after each of them and publishes the candidate only when every policy permits the change. On an unrestricted contract, plain SaveIncrementalUpdate does the job with less ceremony

The HotPDF Delphi workflow for countersigning an already signed PDF: BeginIncrementalUpdate opens the file, AddLoadedSignedSignatureField creates the widget and reserves the /Contents placeholder, SaveIncrementalUpdate appends a second revision, and SignPDFWithPFX fills it, leaving the first signature valid with UnsignedTrailingBytes whilst the new ByteRange spans the whole grown file
One placeholder per revision, prepared and patched by the same serialisation on both signing routes — the clean layout the strict verifier expects

Handing the digest to an outside signer or HSM

Nothing in the workflow alters when the CMS comes from a smart card, an HSM or a remote signing service; only the final step does. THotPDF.PreparePDFForSigning patches the /ByteRange in the prepared bytes and returns two 0-based ranges whose gap is the whole /Contents string, plus ContentsHexStart, the 1-based index of the first hex digit in the AnsiString, and ContentsHexLen. Mixing 0-based file offsets with 1-based string indexes is the classic off-by-one at this step. The sample asserts both delimiter positions before hashing anything

var
  Bytes, ToSign, CmsHex: AnsiString;
  R1Start, R1Len, R2Start, R2Len, HexStart, HexLen: Integer;
begin
  Bytes := LoadFileAsAnsiString('Prepared.pdf');   // your helper
  if not THotPDF.PreparePDFForSigning(Bytes, R1Start, R1Len,
    R2Start, R2Len, HexStart, HexLen) then
    raise Exception.Create('No signature placeholder found');

  // Suggested sanity checks (your own, not library calls):
  // '<' ends range 1, '>' sits just before range 2
  Assert(Bytes[R1Start + R1Len + 1] = '<');
  Assert(Bytes[R2Start] = '>');

  ToSign := Copy(Bytes, R1Start + 1, R1Len) + Copy(Bytes, R2Start + 1, R2Len);
  CmsHex := SignDetachedWithHsm(ToSign);           // your CMS signer, hex DER
  if not THotPDF.InsertSignatureHexAt(Bytes, HexStart, HexLen, CmsHex) then
    raise Exception.Create('CMS does not fit the reserved space');
  SaveAnsiStringToFile(Bytes, 'SignedTwice.pdf');  // your helper
end;

Prepare exactly one placeholder per revision. PreparePDFForSigning patches the first unpatched /ByteRange sentinel it comes across, and a second placeholder left within the same revision sits inside the bytes the first signature covers, so filling it later breaks that signature. For writing the CMS back, InsertSignatureHexAt with the returned offsets is the call to reach for. InsertSignatureHex hunts for the first /Contents string whose digits are all zero, which works on a file with a single empty placeholder; with offsets to hand there is nothing to search for and nothing to mismatch. A shorter CMS is padded with 0 at the end, ahead of the closing >. A longer one makes InsertSignatureHexAt return False without touching the file bytes

What does the gap check prove, and what does it not?

The gap check closes one specific hole. svValid still means byte integrity plus a signature matching the certificate embedded in the CMS; whether that certificate chains to a trust anchor you accept is a question for VerifyLoadedSignatureWithTrust, given your trust anchors and revocation evidence. Without source bytes nothing reaches svValid at all. VerifyLoadedSignatureEx reads them from the file the document was loaded from, returning svSourceUnavailable for a stream-loaded document, where the TStream overload of VerifyLoadedSignature takes them from you

For the first signature in a countersigned file, CoversWholeDocument is rightly False. Whether the appended revision merely added a signature or also changed pages is a matter for AnalyzeLoadedSignatureRevisions, explained in DocMDP, FieldMDP and revision analysis in HotPDF

The bracket layout also seeps into the attached PDF MAC defined by ISO TS 32004 (/MACLocation /AttachedToSig), whose check compares offsets against the exact positions of < and > in the file. HotPDF accepts both layouts there too. A home-grown tool that hard-codes bracket-inclusive offsets is usually the first thing to fall over when it meets a file signed to the §12.8.3.3 layout, and running the two-byte helper from the first section over your own tool's output takes a minute

Most signature trouble in this area begins when the tool that signs, the tool that countersigns and the tool that audits disagree about where the brackets belong. HotPDF, the native PDF component for Delphi and C++Builder writes the §12.8.3.3 layout on every signing route, checks the gap byte by byte on every verification path, and appends countersignatures as clean incremental revisions from a single API