A signed PDF can carry a forged page, pass a CMS digest check and report that its signature covers the whole document, all at the same time. Every signed byte stays exactly as the signer left it, the /ByteRange still starts at 0 and ends at the file size, and the extra objects sit in the one stretch of the file that a PDF signature deliberately leaves out of the digest: the space reserved for the /Contents hex string
That stretch is bigger than most people picture. Reserving 8,192 bytes for the CMS container puts 16,384 hex digits on disk, and whatever part of them the real signature does not use is padded with the digit 0. A verifier that only asks whether the gap between the two ranges is non-empty never looks at what the gap holds. The same layout question turns up from the opposite direction when a contract needs a countersignature: the approver's signature has to be appended without touching a single byte the vendor signed, and its placeholder has to end up in exactly the shape a strict verifier accepts
What the ByteRange gap must contain
The gap must hold the complete /Contents value and nothing else. ISO 32000-1 §12.8.3.3 says the hexadecimal string, with its < and > delimiters, fits precisely in the space between the two byte ranges, and ISO 32000-2 §12.8.1 carries the same rule forward. Table 252 and the PAdES documents phrase it more loosely, saying only that the digest excludes the Contents value. Read quickly, that sounds like "exclude the hex digits", and a signer that follows 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 inside 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 shifts a byte and the cross-reference table stays valid. Each of the four values is 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 while driving a standalone verifier of our own: the first cut split the four numbers on single spaces and found nothing, and the /Contents hex only produced the real CMS bytes after its trailing zero padding was stripped
Two bytes are enough 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 is not 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 independently: concatenate the two ranges into one file and pass it as external content, for example 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 sees the gap, so the two-byte check above is still your job
Why does a non-empty gap check miss signature wrapping?
A non-empty gap proves that something was left out of the digest and says nothing 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, while any PDF parser that opens the file follows whatever objects sit in the unsigned hole
THotPDF.VerifyLoadedSignatureEx treats the gap as data to validate. Once the CMS check passes, the verifier reads the gap, strips the delimiters and accepts only hex digits plus 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 >, one binary byte, or a decoded value one byte too long or too short turns the result into svInvalidByteRange, and so does a gap larger than 64 MiB. The same check runs in ValidateLoadedSignatureBatch; VerifyAllLoadedSignatures and VerifyLoadedSignatureWithTrust go through the single-signature path, so they inherit it as well
One layout is deliberately let through: files whose signer kept the brackets inside the signed ranges, so the gap holds only the digits. For those, the verifier confirms that the byte just before the gap is < and the byte just after it is >, then applies the same digit-and-whitespace test. Rejecting that layout would buy no safety, since the gap still contains nothing but the signature value, and it would fail archived contracts that are perfectly intact. Accepting it is the right default
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 passed to VerifyLoadedSignatureEx count signature fields in form-field order, starting at 0. In a countersigned file the vendor's signature lands in the first branch with CoversWholeDocument = False and a positive UnsignedTrailingBytes: everything appended after it, the approver's revision included. If the basics of this API are new to you, the guide to verifying PDF digital signatures with HotPDF covers the status values and the info record in more depth
Countersigning with 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 does not apply here, because CurrentPage is nil during an incremental update; the document is loaded, not being laid out. The loaded-document method creates the widget on an existing page and hangs under /V the same placeholder signature dictionary that 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 but 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, with a floor of 64 bytes. SubFilter defaults to adbe.pkcs7.detached, and Reason, Location and ContactName end up in the signature dictionary as /Reason, /Location and /ContactInfo, next to a /M timestamp taken when the field is created. The return value is the new field index, or -1 when the page index is out of range. An empty field name or a rectangle with zero width or height raises an exception before anything is written
What the appended revision carries, and what it leaves alone
AddLoadedSignedSignatureField is deliberately quieter than its siblings. The other AddLoaded* field creators set /NeedAppearances true on the AcroForm, which asks a viewer to regenerate field appearances when it opens the file. On a signed document that regeneration can rewrite content the first signer covered. So the new method 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 keeps its existing bits and gains 3, which is SignaturesExist (1) plus AppendOnly (2) from ISO 32000-1 §12.7.2, Table 219
Leave MarkDirty alone for the page. In incremental mode, newly created objects are written automatically, and loaded objects are written only when something marks them. Adding the widget to the page's /Annots and to the AcroForm /Fields already puts whatever indirect objects own those arrays into the new revision. An explicit page mark drags the page dictionary along even when its /Annots array lives in a separate object, and revision analysis then reports a page modification in a revision that should contain nothing but a signature field
The placeholder dictionary writes /ByteRange before /Contents. That order matters if you post-process the prepared file with your own tools: 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 past its own hex string and into whatever comes next in the file
When the first signer applied a DocMDP or FieldMDP restriction, SaveIncrementalUpdateAuthenticated is the stricter way to write revision 2. It saves to a candidate file in the same directory, authenticates every signature that carries 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
Handing the digest to an external signer or HSM
Nothing in the workflow changes when the CMS comes from a smart card, an HSM or a remote signing service; only the last 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 in this step. The sample asserts both delimiter positions before it hashes 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 finds, and a second placeholder left in 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 use. InsertSignatureHex searches for the first /Contents string whose digits are all zero, which works on a file with a single empty placeholder; with offsets in hand there is nothing to search for and nothing to mismatch. A shorter CMS is padded with 0 at the end, before the closing >. A longer one makes InsertSignatureHexAt return False without touching the file bytes
What does the gap check prove, and what not?
The gap check closes one specific hole. svValid still means byte integrity plus a signature that matches the certificate embedded in the CMS; whether that certificate chains to a trust anchor you accept is answered by 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 and returns 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 correctly False. Whether the appended revision only added a signature or also changed pages is a question for AnalyzeLoadedSignatureRevisions, explained in DocMDP, FieldMDP and revision analysis in HotPDF
The bracket layout also leaks 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 break 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 starts when the tool that signs, the tool that countersigns and the tool that audits disagree about where the brackets go. 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 one API