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 inHsmCore. - Translate
HsmErrorvalues toCK_RVreturn codes. - Contain every
unsafeblock 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
FindObjectscursor. - Allocate unique
CK_SESSION_HANDLEvalues via an atomic counter. - Provide a
SessionManagerbacked byDashMapfor lock-free concurrent access from many threads.
Key types
Session-- per-session state machine; enforces thatC_Login,C_OpenSession, and mechanism-init calls occur only from legal states.SessionManager-- owns theDashMap<CK_SESSION_HANDLE, Session>and exposes create / close / lookup APIs.SessionHandleAllocator,ObjectHandleAllocator-- atomic counters used bysession/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_HANDLEtoStoredObject. - Enforce attribute semantics:
CKA_SENSITIVE,CKA_EXTRACTABLE,CKA_PRIVATE, usage flags (CKA_SIGN,CKA_ENCRYPT, etc.),CKA_TOKEN, andCKA_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-memoryObjectStore(DashMap-backed).encrypted_store.rs--EncryptedStore: redb database with AES-256-GCM per-record encryption under a PIN-derived key, plus an exclusivefs2file 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, aZeroizeOnDropwrapper that mlocks its buffer and prints[REDACTED]inDebug.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
CryptoBackendtrait 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-- theCryptoBackendtrait (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--HmacDrbgwith 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 (mlockon Unix,VirtualLockon 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
Mutexand 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
.hmacfile (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_FAILEDflag on any failure; subsequent PKCS#11 calls returnCKR_GENERAL_ERRORuntil re-initialisation.
See Operations -- Self-Tests for invocation procedures and Security Model for the approved-mode contract.
Module Boundaries
pkcs11_abiis the only module allowed to useunsafe. All other modules are compiled with#![deny(unsafe_code)].cryptodepends onstore::key_materialfor zeroising key buffers but does not reach into the object store directly; the C ABI layer resolves handles to keys before calling crypto routines.audithas no dependency oncryptoexcept for SHA-256 digest computation of log entries.config(src/config/) holds theHsmConfigandAlgorithmConfigtypes parsed fromcraton_hsm.toml. See Configuration Reference.