Technical Article

CMS Signature Parsing in Delphi: DER Bounds and OID Arcs

Encode the OID 2.999.3 the way a quick DER helper often does, with the first two arcs packed into one byte, and the decoder hands back 1.15.3. Two other CMS-reading mistakes behave the same way: a certificate count that swallows a neighbor's bytes, and a signer matched on a serial number read from the wrong field. In PDF Library for Delphi (PDFlibPas), the signature reader walks the CMS in /Contents as pure DER, bounds every nested read by its parent element, trims the padding at the length the CMS declares, and base-128 encodes the combined first OID arc

Plenty of code needs the read side of a signature. Long-term validation has to pull the signer certificate and its issuers out of an existing signature before it can fetch any revocation data. An audit report has to say who signed. A Lazarus build on Linux has no Windows message functions to fall back on, because the platform CMS calls are stubbed to failure off Windows, which is why PDFlibPas does this walk in plain Pascal and uses no CryptoAPI at all

Reading the signer certificates out of a signed PDF

Five TPDFlib methods cover the whole read side, and each takes InputFile, Password, FieldName. Every call opens the file read-only, answers, and closes it again, so there is no document state to manage. GetSignatureEmbeddedCertificateCount and GetSignatureEmbeddedCertificateDER enumerate the CMS certificates set in encoding order. GetSignatureSignerCertificateDER returns the certificate that produced a given SignerInfo. GetSignatureCertificateChainLength and GetSignatureCertificateChainDER walk from that signer toward the furthest issuer the signature carries. All indexes are zero-based

The results come back as AnsiString, and you should keep them that way. A DER blob pushed through string or a TStrings goes through a character set conversion, and the bytes that come out the other side no longer parse. That is also why the library keeps certificate lists as arrays of AnsiString and returns URL lists as one-per-line text: addresses are plain ASCII and survive the conversion, certificate bytes do not

uses
  SysUtils, Classes, PDFlibrary, PDFlibEnterprise;

procedure SaveDer(const FileName: string; const Der: AnsiString);
var
  Fs: TFileStream;
begin
  Fs := TFileStream.Create(FileName, fmCreate);
  try
    if Der <> '' then
      Fs.WriteBuffer(Der[1], Length(Der));
  finally
    Fs.Free;
  end;
end;

const
  Src = 'contract-signed.pdf';
  Field = 'Signature1';
var
  Pdf: TPDFlibEnterprise;
  Count, ChainLen, I: Integer;
  SignerDer, LastDer: AnsiString;
begin
  Pdf := TPDFlibEnterprise.Create;
  try
    Count := Pdf.GetSignatureEmbeddedCertificateCount(Src, '', Field);
    WriteLn(Field, ': ', Count, ' certificate(s) in the CMS');
    for I := 0 to Count - 1 do
      SaveDer(Format('embedded-%d.cer', [I]),
        Pdf.GetSignatureEmbeddedCertificateDER(Src, '', Field, I));

    SignerDer := Pdf.GetSignatureSignerCertificateDER(Src, '', Field, 0);
    if SignerDer = '' then
      raise Exception.CreateFmt('%s: signer certificate missing or not matched', [Field]);
    SaveDer('signer.cer', SignerDer);

    ChainLen := Pdf.GetSignatureCertificateChainLength(Src, '', Field, 0);
    for I := 0 to ChainLen - 1 do
      SaveDer(Format('chain-%d.cer', [I]),
        Pdf.GetSignatureCertificateChainDER(Src, '', Field, 0, I));
    if ChainLen > 0 then
    begin
      // the last link may still have an issuer the signature did not embed
      LastDer := Pdf.GetSignatureCertificateChainDER(Src, '', Field, 0, ChainLen - 1);
      WriteLn('Issuer locations: ', Pdf.GetCertificateIssuerURLs(LastDer));
    end;
  finally
    Pdf.Free;
  end;
end;

Two results in that program are easy to misread. A count of 0 tells you very little on its own: a missing field, a wrong password, a blob that is not DER, and a SignedData that simply omits the optional certificates set all come back as 0 or an empty string. Log the field name next to the number, as the example does, or you will end up debugging the wrong file. The second one is chain length. The chain builder uses only certificates embedded in the signature, so a chain that stops before a self-issued root is normal. Sign a file with our demo certificate, which a test root issues, and GetSignatureCertificateChainLength returns 1 because that root is not in the CMS. The next hop comes from the addresses GetCertificateIssuerURLs reports, a call that belongs to the Enterprise edition along with the rest of the long-term validation API

The signer match itself handles both forms of SignerIdentifier that RFC 5652 §5.3 allows. issuerAndSerialNumber is the one everyone tests. The [0] subjectKeyIdentifier form, an implicitly tagged OCTET STRING with tag $80, is the branch hand-written readers most often forget, and signers that identify themselves by key identifier do emit it. When the issuer-and-serial form is used, both halves have to match: a serial number is unique only within one issuer, so matching on serial alone can land on a certificate from a different CA

How much of /Contents is actually the CMS?

Only the prefix covered by the outer SEQUENCE, and PLTrimCMSPadding in unit PDFlibCMSRead cuts everything after it. The reason is ordering. ISO 32000-1 §12.8.1 requires the /ByteRange to be fixed before the signature value exists, so a signer reserves the /Contents hex string up front, sizes it generously, and fills the unused tail with zeros once the CMS is known. A typical signed file therefore carries a run of trailing zeros after the CMS, as long as whatever the signer over-reserved

PLTrimCMSPadding reads the first TLV, requires tag $30, and returns the bytes up to the end of that element. Feed it 30 03 02 01 00 00 00 00 and you get the first five bytes back; feed it 'not der' and you get an empty string. This top level is the only place where trailing bytes are legal. A strict rule that the element must consume the whole buffer would reject ordinary signed files, while a lax "anything left over is fine" rule applied at every depth is exactly how nested fields end up reading bytes they do not own

PDFlibPas PLTrimCMSPadding reads the first TLV of the reserved /Contents hex string, requires tag $30 and cuts the zero padding at the length the outer SEQUENCE declares, and it returns an empty result when the buffer does not start with a well-formed SEQUENCE
Trailing bytes are legal only at the top level, where the reserved slot must stay fixed for /ByteRange — deeper reads get the parent-bounded rule instead

Why does a DER reader need the parent's end offset?

Because a nested element is valid only if it ends inside its parent, and checking it against the end of the buffer does not prove that. DERReadTLV in PDFlibASN1 bounds each element against the whole string, rejects lengths that would run past the end, and does the arithmetic as a subtraction so a crafted four-byte length of $7FFFFFFF cannot wrap the check negative. That is memory safety. It says nothing about whether the element belongs where it was found

Picture a SignerInfo whose issuerAndSerialNumber declares 40 bytes while the issuer Name inside it claims 60. Every byte is still in the buffer, so a buffer-bounded reader accepts the Name, then reads the "serial number" out of the digest algorithm that follows, then compares that pair against the embedded certificates. Nothing fails. Sometimes the comparison even succeeds against the wrong certificate

PDFlibPas bounds every nested DER read by its parent element: a 60-byte issuer Name inside a 40-byte issuerAndSerialNumber is accepted by a buffer-bounded read, which then reads the serial number out of digestAlgorithm, while ReadTLVWithin refuses any element ending past ParentEnd
Inside the buffer is memory safety, inside the parent is correctness — PDFlibPas threads the parent end offset through every CMS level so a hostile length cannot borrow a neighbor's bytes

The PDFlibPas CMS walker carries the parent's end position into every read, from ContentInfo (RFC 5652 §3) through the [0] EXPLICIT wrapper, the SignedData fields (§5.1), each SignerInfo and its identifier, down to the tbsCertificate fields it reads when matching a signer. If you write your own walker on top of the public DERReadTLV, for a timestamp token or an OCSP response, the same pattern is a dozen lines:

uses
  PDFlibASN1;

// One child read, refused if the child would end past its parent.
function ReadChild(const Data: AnsiString; ParentEnd: Integer;
  var Offset: Integer; out Tag: Byte; out Start, Len: Integer): Boolean;
begin
  Result := False;
  if (Offset < 1) or (Offset >= ParentEnd) then
    Exit;                          // nothing left inside the parent
  if not DERReadTLV(Data, Offset, Tag, Start, Len) then
    Exit;
  Result := Offset <= ParentEnd;  // Offset now sits one past the child
end;

// Counts the SEQUENCE members of a SET OF whose content spans
// Data[SetStart .. SetEnd - 1]. Stops at the first member that overruns.
function CountSequences(const Data: AnsiString; SetStart, SetEnd: Integer): Integer;
var
  Offset, Start, Len: Integer;
  Tag: Byte;
begin
  Result := 0;
  Offset := SetStart;
  while Offset < SetEnd do
  begin
    if not ReadChild(Data, SetEnd, Offset, Tag, Start, Len) then
      Break;                       // no resync: the alignment is gone
    if Tag = $30 then
      Inc(Result);
  end;
end;

Note the Break. Inside the certificates set and the signerInfos set, PLExtractCMSCertificates does the same thing: an element that runs past the set's end stops the loop, and the function returns the certificates it had already accepted. It never glues the following crls or signerInfos bytes onto the last certificate. Skipping the bad element and carrying on is tempting, and it is the wrong call. Once one declared length is wrong, the reader no longer knows where the next element starts, and any "recovery" is a guess about which byte looks like a tag. With the loop stopped, a set whose second certificate overruns by a single byte yields a count of 1 and the first certificate's bytes exactly as encoded

How can 2.999.3 come out as 1.15.3?

The first two arcs of an OID combine into one subidentifier, and that subidentifier is base-128 encoded like every other arc — it is not a single byte. X.690 §8.19.4 defines the value as 40 * arc1 + arc2. An encoder that writes it with Byte(...) is correct up to 127, which is 2.47. For 2.999 the sum is 1079, a byte cast keeps 55, and 55 decodes as 1.15. The identifier now names a different branch of the tree and nothing complains. Values from 128 to 255 break differently: the cast emits one byte with the continuation bit set, and the decoder swallows the next arc into it

The shortcut survives so long in real code because most PKI identifiers never reach the boundary. Everything under 1.2.840, 2.5.29 and 0.4.0 has a combined first value well below 128, so a test suite built only from common signature OIDs never exercises the second byte. Only the joint-iso-itu-t arcs from 2.48 upward cross the line. In PDFlibPas a single function, DER_OID, serves the encoder for signed attributes, the lookup inside DERFindExtensionByOID, and the SignedData content-type check, so writing and matching cannot drift apart. Test vectors belong on both sides of the boundary:

uses
  SysUtils, PDFlibASN1;

function Hex(const S: AnsiString): string;
var
  I: Integer;
begin
  Result := '';
  for I := 1 to Length(S) do
    Result := Result + IntToHex(Byte(S[I]), 2) + ' ';
  Result := Trim(Result);
end;

procedure Check(const Oid, Expected: AnsiString);
begin
  if Hex(DER_OID(Oid)) <> Expected then
    WriteLn('MISMATCH ', Oid, ': ', Hex(DER_OID(Oid)), ' expected ', Expected)
  else
    WriteLn('ok       ', Oid);
end;

begin
  Check('2.47.1',               '06 02 7F 01');     // last one-byte value
  Check('2.48.1',               '06 03 81 00 01');  // first two-byte value
  Check('2.999.3',              '06 03 88 37 03');  // a Byte cast gives 1.15.3
  Check('2.5.29.14',            '06 03 55 1D 0E');
  Check('1.2.840.113549.1.7.2', '06 09 2A 86 48 86 F7 0D 01 07 02');
end.
PDFlibPas DER_OID combines the first two OID arcs as 40 * arc1 + arc2 and base-128 encodes the sum in a UInt64, so 2.999.3 becomes 06 03 88 37 03, while a Byte cast would keep 55 and silently decode the identifier as 1.15.3
Most PKI arcs never reach the boundary, which is why a byte-sized shortcut goes unnoticed — the joint-iso-itu-t arcs from 2.48 up need two bytes, so test vectors belong on both sides of that line

There is one more overflow hiding in the same line of arithmetic. DER_OID parses arcs into Int64, so a legal second arc can be as large as Int64.MaxValue, and adding 80 for arc1 = 2 overflows a signed 64-bit integer. The combined value is therefore held in a UInt64, which carries Int64.MaxValue + 80 without wrapping, Nobody issues OIDs that large, but a crafted string can still ask for one. The ten-byte scratch buffer in DER_OID holds the ten 7-bit groups a 64-bit value can need, so even 2.9223372036854775807 encodes to a ten-byte subidentifier instead of wrapping

What the CMS walker accepts, and where verification lives

PDFlibCMSRead returns bytes that sit where RFC 5652 says they should, and that is its whole job. It checks no signature value, no digest and no validity period. The walker accepts DER only: DERReadTLV refuses indefinite lengths and multi-byte tag numbers, so a BER-encoded CMS from a nonconforming signer reports zero certificates. We prefer that to a partial parse of BER. In practice the giveaway is a length byte of $80 right after the outer $30 tag, which is what an indefinite-length SEQUENCE starts with

Attribute certificates and the other CertificateChoices alternatives are skipped while walking the certificates set, since only the plain Certificate alternative is an X.509 certificate that chain building and revocation lookups can use. Everything cryptographic stays with the code that owns it, which starts with the byte coverage checks in PAdES signing and ByteRange validation in Delphi and continues with classifying what changed after a PDF was signed. The same habit of distrusting declared lengths runs through hardening a Pascal PDF parser against malicious files

Certificate extraction, chain building and the long-term validation calls shown above are part of losLab PDF Library for Delphi, which runs on Delphi, C++Builder and Lazarus, so the same signature-reading code works in a Windows service and in a Linux build