Technical Article

PKCS#11 in Delphi: CK_ULONG and the Packing Trap

A Pascal PKCS#11 binding that signs happily against a token on Windows can be recompiled with Free Pascal for Linux and fail on its first object search: C_FindObjectsInit with a one-entry CKA_CLASS template comes back with something like CKR_ATTRIBUTE_VALUE_INVALID (0x13), although the template asks for nothing more exotic than certificates. The token is fine. The record declarations are wrong, and two facts from the PKCS#11 headers explain why: CK_ULONG is the C unsigned long, so 4 bytes on Windows and 8 on Linux and macOS, and the headers byte-pack their structures on Windows only, which moves every pointer in the CK_FUNCTION_LIST table

No linker ever gets a chance to complain. A PKCS#11 module is a .dll, .so or .dylib opened by path at run time, the one exported symbol you look up is C_GetFunctionList, and everything else is a pointer pulled out of the record that call hands back. The Pascal compiler has no view of the C header on the other side, so a width or packing mismatch only shows up as wrong numbers, wrong return codes or an access violation somewhere downstream. A packing mistake tends to produce the access violation, because the slot you read as C_GetSlotList holds six bytes of one pointer and two of the next. A width mistake tends to produce believable-looking error codes, because every address is right and only the data is shifted

CK_ULONG follows the C data model, and almost every PKCS#11 scalar is one

The PKCS#11 v2.40 and 3.x headers define CK_ULONG as unsigned long and build nearly everything else on top of it: slot IDs, session handles, object handles, object classes, key types, attribute types, mechanism types, flags, buffer lengths and the CK_RV return code. Windows is LLP64, so unsigned long stays 32-bit even in a 64-bit process. Linux and macOS are LP64, where it grows to pointer width. A binding that declares CK_ULONG = Cardinal because "unsigned long is 32 bits" is right on exactly one family of platforms

CK_ULONG width map for the PDFium Component PKCS#11 binding in Delphi showing the C unsigned long following the platform data model, 4 bytes as LongWord on Windows LLP64 and 8 bytes as PtrUInt on Linux and macOS LP64, with slot IDs, session handles, object classes, key types, mechanism types and CK_RV all inheriting that width
CK_ULONG is defined as the C unsigned long, so its width follows the data model rather than the specification, and every scalar PKCS#11 passes across the ABI inherits whatever width the build resolves

The PKCS#11 backend in PDFium Component makes that decision once and derives every other scalar type from it. The declarations below are the ones the unit uses, and they are also the shape a hand-written binding should take:

type
{$IFDEF MSWINDOWS}
  // Windows is LLP64: a C unsigned long stays 32-bit there
  CK_ULONG = LongWord;
{$ELSE}
  // Linux and macOS are LP64: unsigned long follows the pointer width
  CK_ULONG = PtrUInt;
{$ENDIF}
  CK_RV = CK_ULONG;
  CK_FLAGS = CK_ULONG;
  CK_SLOT_ID = CK_ULONG;
  CK_SESSION_HANDLE = CK_ULONG;
  CK_OBJECT_HANDLE = CK_ULONG;
  CK_OBJECT_CLASS = CK_ULONG;
  CK_KEY_TYPE = CK_ULONG;
  CK_ATTRIBUTE_TYPE = CK_ULONG;
  CK_MECHANISM_TYPE = CK_ULONG;
  CK_USER_TYPE = CK_ULONG;
  PCK_ULONG = ^CK_ULONG;

Spelling any of those aliases out as LongWord or UInt64 directly is the mistake to avoid. The conditional should exist in one place, because the failures it prevents are scattered. A var Count: CK_ULONG out-parameter of C_GetSlotList declared 4 bytes wide receives 8 bytes from an LP64 module and overwrites whatever local variable sits next to it. A CKA_CLASS template whose value is a 4-byte Cardinal passes ValueLen = 4 where an LP64 module expects sizeof(CK_OBJECT_CLASS), which is 8. And C_GetAttributeValue reports an unreadable attribute by setting the length to CK_UNAVAILABLE_INFORMATION, which is ~0UL: compare against $FFFFFFFF on Linux and you will try to allocate 18 exabytes. The unit tests Attr.ValueLen = CK_ULONG(-1), which is correct on both widths

Why does #pragma pack(1) shift the whole function table?

Because CK_FUNCTION_LIST starts with a two-byte CK_VERSION, and the conventional PKCS#11 headers wrap their declarations in #pragma pack(push, cryptoki, 1) on Windows and leave natural alignment everywhere else. On a 64-bit LP64 build the compiler pads six bytes after the version, so C_Initialize sits at offset 8. On Windows there is no padding and it sits at offset 2. Every later entry inherits that displacement, so a packing error never breaks just one call; it breaks the table

CK_FUNCTION_LIST memory layout in the Delphi PKCS#11 header translation comparing natural alignment where a six byte gap follows the two byte CK_VERSION and C_Initialize lands at offset 8, against byte packing where the pointer lands at offset 2 and every later entry inherits the displacement
The two byte CK_VERSION at the head of CK_FUNCTION_LIST makes packing a whole table problem, because natural alignment pads to offset 8 while pragma pack on Windows puts the first pointer at offset 2

The trap inside the trap is that most PKCS#11 structures do not care. CK_SLOT_INFO is two byte arrays of 64 and 32 bytes followed by CK_ULONG and CK_VERSION fields that land on aligned offsets either way, so a smoke test that reads a slot description passes with the wrong packing. On Windows x64 the structure that does notice is CK_ATTRIBUTE: packed, it is 4 + 8 + 4 = 16 bytes, while natural alignment would pad it to 24, so a two-entry template built with the wrong packing has the module reading its second entry from the middle of the first. Here is how the unit brackets its record declarations:

{$IFDEF FPC}
  {$IFDEF MSWINDOWS}{$PACKRECORDS 1}{$ELSE}{$PACKRECORDS C}{$ENDIF}
{$ELSE}
  {$A1}
{$ENDIF}

  CK_VERSION = record
    Major: Byte;
    Minor: Byte;
  end;

  CK_ATTRIBUTE = record
    AttrType: CK_ATTRIBUTE_TYPE;
    Value: Pointer;
    ValueLen: CK_ULONG;
  end;

  CK_FUNCTION_LIST = record
    Version: CK_VERSION;     // two bytes: the reason the table moves
    C_Initialize: Pointer;   // offset 2 packed, 8 on LP64
    C_Finalize: Pointer;
    C_GetInfo: Pointer;
    C_GetFunctionList: Pointer;
    C_GetSlotList: Pointer;
    // ... the table has a fixed order, so declaring the prefix
    // up to C_Sign reaches every entry a signing backend calls
    C_SignInit: Pointer;
    C_Sign: Pointer;
  end;

{$IFDEF FPC}{$PACKRECORDS DEFAULT}{$ELSE}{$A8}{$ENDIF}

type
  // Every Cryptoki entry point uses the C calling convention
  TfnSign = function(Session: CK_SESSION_HANDLE; Data: Pointer;
    DataLen: CK_ULONG; Signature: Pointer;
    var SignatureLen: CK_ULONG): CK_RV; cdecl;

{$PACKRECORDS C} is a real instruction rather than a no-op: it tells Free Pascal to lay records out the way the platform C compiler would, which is the contract the Linux and macOS headers assume. The Delphi branch is plain {$A1} because the product's Delphi builds of this unit target Windows, and Free Pascal carries the Linux and macOS builds. The restore line at the end matters as much as the opening one, since a unit left packed changes the layout of every record declared after it, which is exactly the kind of action-at-a-distance fault covered in hardening a PDFium component binding against ABI and memory-safety faults. The cdecl on the function types is the remaining piece of the ABI: on Win32 a stdcall declaration would leave the stack unbalanced after every call

Pkcs11AbiLayout turns the record layout into a test assertion

Pkcs11AbiLayout returns the layout the current build resolved, as one string of the form ulong=4 attr=16 pss=12 table=2. The four values are SizeOf(CK_ULONG), SizeOf(CK_ATTRIBUTE), SizeOf(CK_RSA_PKCS_PSS_PARAMS) and the offset of C_Initialize inside the function table. Win32 reports 4/12/12/2, Win64 reports 4/16/12/2, and a 64-bit Linux or macOS build reports 8/24/24/8. Those numbers follow directly from the header rules: CK_ATTRIBUTE is CK_ULONG + pointer + CK_ULONG, and the PSS parameter block is three CK_ULONG fields

Pkcs11AbiLayout fingerprints for the two PDFium Component build branches reporting ulong, CK_ATTRIBUTE size, CK_RSA_PKCS_PSS_PARAMS size and the table offset as one assertable string, with the load time version and nil entry point check that refuses a module whose record was laid out wrong
One string turns the ABI layout into an assertion: a 64 bit Windows build must report table offset 2 while an LP64 target reports 8, and a module whose version or entry points look implausible is dropped instead of called

A comment saying a record matches its C header proves nothing, while an equality check in a test run on each target proves the thing you care about. Put the check in your own suite for every platform you ship:

uses
  SysUtils, FPdfPkcs11;

// A check you add to your own test suite; Pkcs11AbiLayout is the library call
procedure CheckPkcs11Abi;
var
  Expected: string;
begin
{$IFDEF MSWINDOWS}
  if SizeOf(Pointer) = 8 then
    Expected := 'ulong=4 attr=16 pss=12 table=2'
  else
    Expected := 'ulong=4 attr=12 pss=12 table=2';
{$ELSE}
  // 64-bit Linux and macOS (LP64)
  Expected := 'ulong=8 attr=24 pss=24 table=8';
{$ENDIF}
  if Pkcs11AbiLayout <> Expected then
    raise Exception.CreateFmt('PKCS#11 ABI mismatch: got %s, expected %s',
      [Pkcs11AbiLayout, Expected]);
end;

The same idea runs at load time, against the module rather than the build. The unit resolves only C_GetFunctionList by name, through GetProcAddress on Delphi and GetProcedureAddress on Free Pascal, and takes every other entry point from the returned table, which is how the PKCS#11 base specification expects a module to be reached and which avoids per-vendor symbol naming quirks. It then checks what came back: a major version outside 2 to 3, or a nil C_Initialize, C_GetSlotList or C_Sign, means the table was read through the wrong layout, and the module is reported as unavailable instead of being called. Pkcs11ModuleAvailable returns False in that case, and Pkcs11ModuleVersion returns the version pair the table reports when it loads

Mechanism parameters and the two-pass C_Sign

Width bugs do not stop at templates. CK_MECHANISM carries a pointer to a parameter block plus its length, and for CKM_RSA_PKCS_PSS that block is CK_RSA_PKCS_PSS_PARAMS: hash mechanism, MGF and salt length, all CK_ULONG. The unit fills it with CKM_SHA256, CKG_MGF1_SHA256 and a 32-byte salt and passes SizeOf(PssParams) as the length, which is 12 on Windows and 24 on LP64. A binding that hard-codes 12 works on Windows and can expect CKR_MECHANISM_PARAM_INVALID from an LP64 module

Three mechanism rules decide whether the resulting PDF signature verifies. CKM_RSA_PKCS applies PKCS#1 v1.5 padding but does not build the DigestInfo, so the caller prepends the 19-byte SHA-256 DigestInfo prefix from RFC 8017; hand the bare digest over and you get a valid RSA operation over the wrong input. CKM_RSA_PKCS_PSS and CKM_ECDSA take the digest as is, but CKM_ECDSA returns the raw r||s concatenation, and CMS needs the DER ECDSA-Sig-Value SEQUENCE from RFC 3279 §2.2.3, so the unit converts it. C_Sign itself is called twice: once with a nil buffer to learn the signature length, then with a buffer of that size. The same ask-for-length, then ask-for-value pattern applies to C_GetAttributeValue when reading a certificate's CKA_VALUE

Two constants are worth checking against the header rather than memory. CKO_CERTIFICATE is 1; 0 is CKO_DATA and 2 is CKO_PUBLIC_KEY, so a misremembered value produces an empty search with CKR_OK. And CKR_CRYPTOKI_ALREADY_INITIALIZED (0x190) from C_Initialize means another part of the process got there first. The unit caches modules by path, because C_Initialize is once per process per module, and treats 0x190 as success

Signing a PDF through a token from Delphi

With the layout settled, signing is configuration. ConfigurePkcs11SignerProvider builds a provider from TPdfPkcs11Options and installs it as the PAdES signer backend, so the regular SignPadesBytes call signs with the token key. The private key stays inside the token; the library computes the signed-attributes digest and the token performs C_Sign on it. The backend lives in FPdfPkcs11, which ships with the Enterprise edition, and the same unit works on Windows, Linux and macOS. Bring it up against SoftHSM2 before a hardware token, so an ABI question and a token-configuration question never arrive together:

uses
  Classes, SysUtils, FPdfCrypto, FPdfPades, FPdfPkcs11;

procedure SignWithToken(const InFile, OutFile, Pin: string);
var
  Pkcs11: TPdfPkcs11Options;
  Provider: IPdfPkcs11SignerProvider;
  Slot: TPdfPkcs11Slot;
  Options: TPadesSignOptions;
  Src, Dst: TFileStream;
begin
  Pkcs11 := TPdfPkcs11Options.Default;
  Pkcs11.ModulePath := '/usr/lib/softhsm/libsofthsm2.so';
  Pkcs11.Pin := Pin;
  Pkcs11.CertificateLabel := 'Signing Certificate';

  if not Pkcs11ModuleAvailable(Pkcs11.ModulePath) then
    raise Exception.CreateFmt('No usable PKCS#11 module at %s (layout %s)',
      [Pkcs11.ModulePath, Pkcs11AbiLayout]);
  Writeln('Cryptoki version ', Pkcs11ModuleVersion(Pkcs11.ModulePath));

  Provider := ConfigurePkcs11SignerProvider(Pkcs11);
  for Slot in Provider.EnumerateSlots do
    if Slot.TokenPresent then
      Writeln(Slot.SlotID, ': ', Slot.TokenLabel);

  Options := TPadesSignOptions.Default;
  Options.PaddingScheme := psRsaPss;  // an EC certificate switches this to ECDSA
  Options.Reason := 'Approved';
  Src := TFileStream.Create(InFile, fmOpenRead or fmShareDenyWrite);
  try
    Dst := TFileStream.Create(OutFile, fmCreate);
    try
      SignPadesBytes(Src, Dst, Options);
    finally
      Dst.Free;
    end;
  finally
    Src.Free;
  end;
end;

Certificate selection follows a fixed order. A non-empty CertificateThumbprint in the sign options wins; otherwise CertificateLabel is matched against CKA_LABEL; with neither set, the first certificate on the token is used. That last fallback is fine on a SoftHSM2 slot holding one test certificate and wrong for production, where a token often carries an authentication certificate next to the signing one. Set the thumbprint in production. The private key is matched to the certificate through CKA_ID, and the certificate's key algorithm decides between RSA and ECDSA

A few smaller rules come from the specification itself. The PIN is sent to C_Login as UTF-8, and the provider clears its own copy once the token has consumed it. Labels are UTF-8 as well, while CK_SLOT_INFO and CK_TOKEN_INFO text fields are blank-padded fixed-width arrays with no terminating NUL, so EnumerateSlots trims them from the tail. Leave UseSpecificSlot False and the provider takes the first slot that reports a token present; set it with SlotId when a reader has more than one

Where the signature gets verified

Verification is configured separately from signing, and each platform has its own CMS verifier. Windows uses the system crypto stack by default. On Linux, ConfigureSslCmsVerifier from FPdfCryptoSsl installs an OpenSSL-based verifier; on macOS, ConfigureKeychainCmsVerifier from FPdfCryptoMac uses Security.framework. A non-Windows build that installs no verifier reports the cryptographic checks as pcsUnsupported rather than guessing, so a Linux service that produces a PAdES B-B signature over a token-held key should configure one before it validates its own output

The OpenSSL binding meets the same C type the token binding does. Its error codes and store flags are C unsigned long too, and SslAbiLayout reports the assumed widths as ulong=<n> long=<n>, which belongs in the same per-platform test as Pkcs11AbiLayout. When the key lives in a remote HSM or a cloud key service instead of a local token, the signer seam is the same one used by remote PAdES signing sessions against an HSM or a cloud key service

The PKCS#11 backend, the OpenSSL and Keychain verifiers and the rest of the PAdES stack are part of the PDFium Component for Delphi, C++Builder and Lazarus, with the width and packing conditionals already in place on each target, so your own code deals with slots, labels and PINs rather than struct offsets