Craton HSM

Components

Components

This page describes each internal module of the craton_hsm crate and its responsibilities. Consumer surfaces (cratond, craton-hsm-admin) are covered separately in gRPC Daemon and Admin CLI.

pkcs11_abi

The C ABI layer. Source: src/pkcs11_abi/.

Responsibilities

  • Expose 70+ #[no_mangle] pub extern "C" functions matching the PKCS#11 v3.0 specification.
  • Marshal between PKCS#11 C types (CK_*) and the internal Rust types in HsmCore.
  • Translate HsmError values to CK_RV return codes.
  • Contain every unsafe block in the crate. All other modules compile with #![deny(unsafe_code)].

Submodules

  • types.rs -- CK_* type aliases and C-compatible structs.
  • constants.rs -- CKR_*, CKM_*, CKO_*, CKA_* constants.
  • functions.rs -- the exported entry points.

Every exported function wraps its body in catch_unwind. A panic that would otherwise cross the FFI boundary (undefined behaviour under the C ABI) is converted into CKR_GENERAL_ERROR. unsafe usage is restricted to four documented patterns: dereferencing caller-provided output pointers, constructing slices from (ptr, len) pairs, reading CK_MECHANISM through a raw pointer, and casting CK_C_INITIALIZE_ARGS.

session

Session state and handle allocation. Source: src/session/.

Responsibilities

  • Track each open session's flavour (RO or RW), login state, active cryptographic operation, and FindObjects cursor.
  • Allocate unique CK_SESSION_HANDLE values via an atomic counter.
  • Provide a SessionManager backed by DashMap for lock-free concurrent access from many threads.

Key types

  • Session -- per-session state machine; enforces that C_Login, C_OpenSession, and mechanism-init calls occur only from legal states.
  • SessionManager -- owns the DashMap<CK_SESSION_HANDLE, Session> and exposes create / close / lookup APIs.
  • SessionHandleAllocator, ObjectHandleAllocator -- atomic counters used by session/handle.rs.

token

Token metadata, slot bookkeeping, and PIN authentication. Source: src/token/.

Responsibilities

  • Maintain slot-to-token mapping via SlotManager.
  • Store token labels, serials, and PIN hashes.
  • Enforce PIN policy: PBKDF2-HMAC-SHA256 with 600,000 iterations, per-token random salt, constant-time comparison via subtle.
  • Implement the PIN-retry lockout state machine. The Security Officer can unlock a locked user PIN.

Key types

  • Token -- token state including PIN hashes and login status.
  • SlotManager -- slot-to-token assignment.

See Security Model for PIN policy details.

store

The PKCS#11 object model and its persistence backends. Source: src/store/.

Responsibilities

  • Maintain the authoritative map of CK_OBJECT_HANDLE to StoredObject.
  • Enforce attribute semantics: CKA_SENSITIVE, CKA_EXTRACTABLE, CKA_PRIVATE, usage flags (CKA_SIGN, CKA_ENCRYPT, etc.), CKA_TOKEN, and CKA_START_DATE / CKA_END_DATE.
  • Track key lifecycle state (SP 800-57): PreActivation, Active, Deactivated, Compromised, Destroyed.
  • Persist token objects to an encrypted redb database when configured.
  • Produce and restore encrypted backups.

Submodules

  • object.rs -- StoredObject, KeyLifecycleState, attribute holders.
  • attributes.rs -- the in-memory ObjectStore (DashMap-backed).
  • encrypted_store.rs -- EncryptedStore: redb database with AES-256-GCM per-record encryption under a PIN-derived key, plus an exclusive fs2 file lock.
  • backup.rs -- encrypted backup blobs with magic header, PBKDF2 salt, AES-GCM nonce, and AES-256-GCM ciphertext of a serialised payload.
  • key_material.rs -- RawKeyMaterial, a ZeroizeOnDrop wrapper that mlocks its buffer and prints [REDACTED] in Debug.
  • lifecycle.rs -- date-based lifecycle transition helpers.
  • lockout_store.rs -- persistent PIN retry counters.

See Storage for on-disk layout and encryption details.

crypto

Cryptographic operations, backend abstraction, DRBG, and self-tests. Source: src/crypto/.

Responsibilities

  • Define the CryptoBackend trait that pluggable backends implement.
  • Route mechanism calls (C_SignInit / C_Sign, C_Encrypt, etc.) to the appropriate backend method, including multi-part (C_SignUpdate, C_EncryptUpdate) dispatch.
  • Implement the SP 800-90A HMAC-SHA256 DRBG used for all key generation and nonce production.
  • Run FIPS 140-3 Power-On Self-Tests.
  • Enforce memory hardening: mlock / VirtualLock on key buffers, zeroize on drop.

Submodules

  • backend.rs -- the CryptoBackend trait (classical primitives).
  • rustcrypto_backend.rs -- default pure-Rust implementation.
  • awslc_backend.rs -- optional aws-lc-rs FIPS-validated backend.
  • keygen.rs, sign.rs, encrypt.rs, digest.rs, derive.rs, wrap.rs -- mechanism implementations.
  • pqc.rs -- post-quantum mechanisms: ML-DSA, ML-KEM, SLH-DSA, hybrid X25519+ML-KEM-768.
  • mechanisms.rs -- mechanism dispatch and feature gating.
  • drbg.rs -- HmacDrbg with prediction resistance and continuous health tests.
  • self_test.rs -- 17 POST self-tests (software integrity + 16 KATs).
  • pairwise_test.rs -- SP 800-56B pairwise consistency tests run on newly generated asymmetric keys.
  • integrity.rs -- module-binary HMAC-SHA256 verification.
  • mlock.rs -- cross-platform memory locking (mlock on Unix, VirtualLock on Windows).

audit

Tamper-evident event logging. Source: src/audit/.

Responsibilities

  • Record every security-relevant PKCS#11 operation as an AuditEvent.
  • Chain entries with SHA-256 so that any modification, deletion, or reordering invalidates the chain.
  • Serialise writes through a Mutex and fsync before returning from the originating PKCS#11 call.
  • Expose readers for the admin CLI (craton-hsm-admin audit dump, export-json, export-ndjson, export-syslog, verify-chain).

Key types

  • AuditEvent -- { timestamp, session_handle, operation, key_id, result, previous_hash }.
  • AuditOperation -- enum covering initialize, finalize, open/close session, login/logout, create/destroy object, sign, verify, encrypt, decrypt, digest, derive, wrap/unwrap, and administrative actions.
  • AuditLog -- holds the append-only file and the last hash.

selftests

Implemented within crypto/self_test.rs and crypto/integrity.rs. Not a separate top-level module, but called out here because it is the gate between initialisation and any cryptographic service.

Responsibilities

  • Verify the module binary's embedded HMAC-SHA256 against a sidecar .hmac file (software integrity check).
  • Execute 16 algorithm Known-Answer Tests covering the approved-mode primitives: SHA-256/384/512, SHA3-256, HMAC-SHA256/384/512, AES-256-GCM/CBC/CTR, RSA-2048 PKCS#1 v1.5, ECDSA P-256, ML-DSA-44, ML-KEM-768, RNG health per SP 800-90B, and the HMAC_DRBG KAT.
  • Latch a global POST_FAILED flag on any failure; subsequent PKCS#11 calls return CKR_GENERAL_ERROR until re-initialisation.

See Operations -- Self-Tests for invocation procedures and Security Model for the approved-mode contract.

Module Boundaries

  • pkcs11_abi is the only module allowed to use unsafe. All other modules are compiled with #![deny(unsafe_code)].
  • crypto depends on store::key_material for zeroising key buffers but does not reach into the object store directly; the C ABI layer resolves handles to keys before calling crypto routines.
  • audit has no dependency on crypto except for SHA-256 digest computation of log entries.
  • config (src/config/) holds the HsmConfig and AlgorithmConfig types parsed from craton_hsm.toml. See Configuration Reference.