Installing and configuring the Cloud HSM PKCS#11 driver
Set up the Cloud HSM PKCS#11 driver with OVHcloud IAM authorisation and endpoint failover, and find supported functions, mechanisms, attributes and limits
Beta version — Cloud HSM is currently in beta. Features, interfaces and procedures may change until general availability (GA), and this guide will be updated along with them. To find out more about the beta or to request access, visit the Cloud HSM page on OVHcloud Labs.
Objective
Your applications use Cloud HSM through the OVHcloud PKCS#11 driver, a library that implements the PKCS#11 v2.40 standard (Cryptoki). Any PKCS#11-compatible application can load it, and the driver translates its calls into requests to the endpoints of your Cloud HSM cluster.
This guide explains how to install and configure the driver, how to authorise your applications with OVHcloud IAM, and what the driver supports.
Requirements
- A Cloud HSM cluster with the status
READY, its ID and the endpoints of its partitions. See Getting started with Cloud HSM. - An OVHcloud IAM token (Personal Access Token or service account OAuth2 access token) for an identity authorised on the cluster.
- A machine that can reach the endpoints of your cluster on TCP port 5697, running Linux on amd64 or arm64 with glibc 2.28 or later. These are the platforms for which the driver is provided during the beta. A Linux container or virtual machine is also suitable.
Instructions
Installing the driver
During the beta, the driver is provided directly to the participants, as a precompiled library for Linux on amd64 (x86_64) and arm64 (aarch64): libovhcloud_pkcs11_driver-<version>-linux-x86_64.so or libovhcloud_pkcs11_driver-<version>-linux-aarch64.so. Use the build that matches the architecture of your machine. It requires glibc 2.28 or later (for example RHEL 8, Debian 10, Ubuntu 20.04 or later).
- Copy the library to the machine that runs your application, for example to
/usr/local/lib/libovhcloud_pkcs11_driver.so. - Point your PKCS#11 application at this path. Depending on the application, this is a
module,libraryorprovidersetting, or a parameter of the function that loads the PKCS#11 library.
The driver needs no other component on the machine. The certificate presented by the Cloud HSM endpoints is issued by a public certification authority, so the system trust store is enough to validate it.
Configuring the driver
The driver reads its configuration once, when your application initialises it (C_Initialize), from one of two sources:
- a YAML file, whose path you set in the
PKCS_CONF_FILEenvironment variable. This is the recommended method: it lets you configure every endpoint of your cluster, for failover, and several slots. - environment variables, when
PKCS_CONF_FILEis not set. They configure a single slot (slot 0) with a single endpoint.
If the configuration is missing or invalid, C_Initialize returns CKR_ARGUMENTS_BAD and writes the reason to the standard error output, whatever the log level.
The driver exposes each slot as a token labelled OVHcloud Cloud HSM <slot number>, for example OVHcloud Cloud HSM 0.
Configuration with a YAML file (recommended)
The YAML file declares one or more slots. Each slot is an independent PKCS#11 token, with its own endpoints, credentials and login state.
Durations are written with a unit, for example 500ms, 30s or 1m.
If you store an IAM token in the Pin parameter, protect the configuration file like a password: restrict its permissions to the account that runs your application.
Configuration with environment variables
If PKCS_CONF_FILE is not set, the driver reads the following environment variables instead. This alternative configures a single slot (slot 0) with a single endpoint, without failover: use it for a quick test.
Configuring several endpoints
List every endpoint of your cluster in ServerUrl, starting with the one closest to your application. The driver connects to the first available endpoint. When the connection to an endpoint fails, the driver skips it for the duration of RetryTimeout and uses the next one. Once RetryTimeout has expired, new connections go back to the first endpoint. A refusal returned by Cloud HSM (for example an authorisation error) does not make the driver skip an endpoint.
If the connection to an endpoint is lost during a session, the driver reconnects to the next available endpoint without closing the session. It automatically re-sends, up to 3 times, the requests that change nothing: signature, verification, encryption, decryption, wrapping, search and attribute reads. A key creation, import, unwrap, deletion or attribute change interrupted this way fails with CKR_DEVICE_ERROR, because Cloud HSM may already have performed it. Your keys remain valid on every endpoint. See the "High availability and failover" section of the "Cloud HSM - Architecture and high availability" guide.
We recommend that your application:
- retries the operations that fail with
CKR_DEVICE_ERROR, with an increasing delay between attempts, after checking that an interrupted key creation did not take effect; - retries the operations that fail with
CKR_FUNCTION_FAILEDonly after checking the driver logs: an IAM refusal or an IP allowlist refusal also returnsCKR_FUNCTION_FAILED, and retrying them is useless; - closes the session and opens a new one if an endpoint keeps returning
CKR_DEVICE_ERRORorCKR_SESSION_HANDLE_INVALID; - does not retry the operations refused for a functional reason (for example
CKR_KEY_TYPE_INCONSISTENTorCKR_MECHANISM_INVALID).
When the last open session of a slot closes, the driver logs the slot out, and every object handle becomes invalid. After opening a new session, call C_Login again and find your keys again with C_FindObjects.
Connections and parallelism
Each open PKCS#11 session uses its own TLS connection to an endpoint, and the requests of a session run one at a time: open several sessions to run operations in parallel. The connections of closed sessions are kept for 60Â seconds to be reused. The driver does not keep the connection of an idle session alive, and endpoints close idle connections after 10Â minutes. If a firewall, a NAT gateway or a load balancer sits between your application and Cloud HSM, set its idle timeout above 10Â minutes.
If a key creation (C_GenerateKey, C_GenerateKeyPair, C_CreateObject or C_UnwrapKey) is interrupted by a timeout or a lost connection, your application cannot know whether the key was created. Give each new key a CKA_ID of your choice and, before retrying the creation, search for that CKA_ID with C_FindObjects: if the key exists, use it instead of creating a second one.
Authentication
The driver authenticates every request with an OVHcloud IAM token: a Personal Access Token (PAT) of an IAM local user, or an OAuth2 access token obtained with a service account.
The IAM token is the PIN of the PKCS#11 token: your application passes it to C_Login, and the driver sends it with every request until C_Logout. C_Login checks the token immediately with a search request, so the identity needs the cloudHSM:pkcs11:read action to log in. For applications that never call C_Login, set the token in the Pin parameter of the slot or in the PKCS11_HSMGW_TOKEN variable. A token passed to C_Login takes precedence over the configured one.
PIN management functions (C_InitToken, C_InitPIN, C_SetPIN) are not supported: tokens are managed in OVHcloud IAM.
Authorisation with OVHcloud IAM
Before running a request, Cloud HSM checks with OVHcloud IAM that the identity of the token is authorised to perform it on the cluster. The administrator of the OVHcloud account holds every right. For other identities, create IAM policies in the OVHcloud Console or with the IAM API.
Cloud HSM IAM actions
PKCS#11 operations (cloudHSM:pkcs11:*):
The driver also sends read requests on its own: a search at C_Login, and an attribute read the first time it uses a key. Every identity therefore needs cloudHSM:pkcs11:read.
Cluster management with the OVHcloud API v2 (cloudHSM:apiovh:*):
Example IAM policies
Apply these templates to your cluster. Its URN, in the form urn:v1:eu:resource:cloudHSM:<cluster ID>, is returned in the iam.urn field of GET /cloudHSM/resource/{cloudHSMId}. Replace <identity_urn> and <cluster_urn> with your values.
Full admin: manages the cluster and its keys, and uses the keys for every operation.
Read only: views the cluster, lists the keys and reads their public attributes, without creating, changing, deleting or using any key.
Crypto user: uses existing keys to encrypt, decrypt, sign and verify, without creating, changing or deleting keys.
Narrow the crypto user profile to what each application does: an application that only signs needs cloudHSM:pkcs11:read and cloudHSM:pkcs11:sign. Always keep cloudHSM:pkcs11:read: without it, C_Login fails.
Supported PKCS#11 functions
The driver implements Cryptoki v2.40. Unsupported functions return CKR_FUNCTION_NOT_SUPPORTED, except C_SeedRandom, which returns CKR_RANDOM_SEED_NOT_SUPPORTED.
Supported mechanisms
AES-GCM IV
For AES-GCM encryption and wrapping, the HSM generates the IV itself. The driver writes it back into the pIv buffer of your CK_GCM_PARAMS structure when the operation completes (C_Encrypt, C_EncryptFinal or C_WrapKey):
- size the
pIvbuffer to 16Â bytes; - keep the
CK_GCM_PARAMSstructure and itspIvbuffer allocated until the operation ends, not only untilC_EncryptInitreturns, otherwise the driver writes into freed memory; - store the IV with the ciphertext or the wrapped key: you need it to decrypt or unwrap.
Keys and attributes
Every object is a token object, stored in your cluster: CKA_TOKEN = CK_FALSE is refused. Key pairs are returned as two objects (CKO_PUBLIC_KEY and CKO_PRIVATE_KEY) that share the same CKA_ID.
Attributes accepted when creating a key
CKA_LABEL,CKA_ID,CKA_CLASS,CKA_KEY_TYPE;- the usages
CKA_ENCRYPT,CKA_DECRYPT,CKA_SIGN,CKA_VERIFY,CKA_WRAP,CKA_UNWRAP; CKA_VALUE_LEN(AES and generic secret keys),CKA_MODULUS_BITS(RSA),CKA_EC_PARAMS(EC, curve OID in DER);- to import a public key with
C_CreateObject:CKA_MODULUSandCKA_PUBLIC_EXPONENT(RSA), orCKA_EC_PARAMSandCKA_EC_POINT(EC, uncompressed point wrapped in a DER OCTET STRING: a compressed point or a bare point returnsCKR_ATTRIBUTE_VALUE_INVALID); CKA_SENSITIVE(CK_TRUEonly:CK_FALSEis refused withCKR_ATTRIBUTE_VALUE_INVALID),CKA_EXTRACTABLE.
Default values when the template does not state them:
CKA_ID is the identifier you choose for a key: it is stored, and you can search for the key with it. Choose one for every key you create: it lets your application find the key again, in particular after an interrupted creation. When you unwrap a secret key, state its CKA_VALUE_LEN in the template.
CKA_DERIVE is accepted in a template but ignored: no key gets the derive usage, since key derivation is not available.
Attributes you can change
With C_SetAttributeValue, in a read/write session:
CKA_DERIVE can only be set to CK_FALSE. Every other attribute is read-only (CKR_ATTRIBUTE_READ_ONLY). If one of the changes of a C_SetAttributeValue call is refused, the driver undoes the others, on a best-effort basis.
Attributes you can read
C_GetAttributeValue returns the label, the key type, the usages, CKA_ID, CKA_UNIQUE_ID, the size of the key (CKA_VALUE_LEN, CKA_MODULUS_BITS or CKA_EC_PARAMS), and the protection attributes CKA_SENSITIVE, CKA_EXTRACTABLE, CKA_ALWAYS_SENSITIVE and CKA_NEVER_EXTRACTABLE.
- Public keys:
CKA_MODULUSandCKA_PUBLIC_EXPONENT(RSA),CKA_EC_POINT(EC). Use them to export a public key, for example to build a certificate signing request. - Private and secret keys: the key material (
CKA_VALUE, private exponent, etc.) is never returned: reading it returnsCKR_ATTRIBUTE_SENSITIVE. CKA_UNIQUE_IDis the identifier that Cloud HSM gives the key. It differs between the two halves of a key pair.CKA_ALLOWED_MECHANISMSis not available, andCKA_KEY_GEN_MECHANISMreturnsCK_UNAVAILABLE_INFORMATION.
Searching for keys
C_FindObjects returns the keys that match every attribute of the template. You can search on the class, the key type, the label, CKA_ID, CKA_UNIQUE_ID, the key size, the curve, the usages and the protection attributes. A search on another attribute returns no result.
Wrapping and unwrapping keys
C_WrapKey exports a key encrypted under another key of your cluster, and C_UnwrapKey imports a wrapped key into your cluster. Unwrapping is the way to import your existing secret and private keys into Cloud HSM.
Limits:
- The wrapping key must have the
CKA_WRAPusage, and the unwrapping key theCKA_UNWRAPusage. Otherwise, the operation returnsCKR_KEY_TYPE_INCONSISTENT. - Only extractable keys (
CKA_EXTRACTABLE = CK_TRUE, which is not the default) can be wrapped. Otherwise,C_WrapKeyreturnsCKR_KEY_UNEXTRACTABLE. - The partitions do not export private keys: wrapping an RSA or EC private key is refused.
CKM_AES_KEY_WRAP(RFC 3394, without padding) is not supported: useCKM_AES_KEY_WRAP_KWP.- State
CKA_CLASS,CKA_KEY_TYPEand, for a secret key,CKA_VALUE_LENin the unwrap template. WithoutCKA_CLASS, the key is unwrapped as a secret key, and withoutCKA_KEY_TYPE, as an AES key. - A wrapped key larger than the size limit of an operation returns
CKR_WRAPPED_KEY_LEN_RANGE. - After you set
CKA_EXTRACTABLEtoCK_FALSE, the key can still be wrapped through another endpoint for about 30Â seconds. See the "Consistency of changes" section of the "Cloud HSM - Architecture and high availability" guide.
To import a secret key, retrieve an RSA public key of your cluster (with CKA_WRAP), wrap your key with it outside Cloud HSM using RSA-OAEP, then unwrap it in your cluster with the matching private key (with CKA_UNWRAP). RSA-OAEP can only wrap a small key (about 190Â bytes with an RSA 2048-bit key and SHA-256), and the partitions refuse the import of a secret or private key in plaintext.
To import an RSA or EC private key, which is too large for RSA-OAEP, proceed in two steps:
- Import an AES key as described above, with the
CKA_UNWRAPusage. - Outside Cloud HSM, wrap your private key, in PKCS#8 format (DER), with this AES key using AES-KWP (RFC 5649). Then unwrap it in your cluster with
CKM_AES_KEY_WRAP_KWP, statingCKA_CLASS = CKO_PRIVATE_KEYand the matchingCKA_KEY_TYPE(CKK_RSAorCKK_EC) in the template.
The imported private key, like any private key of your cluster, can never be exported.
Logs
Set the PKCS11_LOG_LEVEL variable (or LogLevel in the YAML file) to have the driver write its logs to the standard error output. At the error level, each error is logged with its context: session, mechanism, key, template (secret values masked) and, for errors returned by Cloud HSM, the request ID (req_id). Include this request ID when you report a problem.
Known limits
- No random number generation or key derivation:
C_GenerateRandomandC_DeriveKeyare not supported. - Size of an operation: an operation can process at most 1 MiB − 16 KiB (1,032,192 bytes) of data, AES-GCM additional data included. Beyond that, the driver returns, before sending anything,
CKR_DATA_LEN_RANGEfor the data of an encryption, a signature or a verification,CKR_ENCRYPTED_DATA_LEN_RANGEfor the ciphertext of a decryption and, atC_Verify,CKR_SIGNATURE_LEN_RANGEwhen the data and the signature together exceed the limit. Use envelope encryption for larger data. - Multi-part operations are not streamed: for encryption, decryption, HMAC and the raw signature mechanisms, the driver buffers the data,
C_EncryptUpdateandC_DecryptUpdatereturn no data, and the whole result is returned byC_EncryptFinalorC_DecryptFinal. The size limit applies to the whole data. Only the hash-and-sign mechanisms (CKM_SHA*_RSA_PKCS,CKM_SHA*_RSA_PKCS_PSS,CKM_ECDSA_SHA*) hash the data locally and accept any size. - Listing objects is slow on large partitions: reading the attributes of every object costs one request per object. On a partition with thousands of keys, search for keys by
CKA_IDor label instead of listing them all. fork(): callC_Finalize, or close every session, before your process forks. The child process must callC_Initializeitself.- AES-GCM IV: a 16-byte
pIvbuffer, kept allocated until the end of the operation. See AES-GCM IV. - RSA-OAEP: the OAEP hash and the MGF1 hash must be the same algorithm, and labels are not supported.
- RSA PKCS#1 v1.5 encryption (
CKM_RSA_PKCSfor encryption and decryption) is refused: useCKM_RSA_PKCS_OAEP. Signature withCKM_RSA_PKCSworks. - HMAC works only with generic secret keys (
CKM_GENERIC_SECRET_KEY_GEN), not with AES keys. - Consistency between endpoints: a deleted or modified key can keep its previous state on the other endpoints for about 30Â seconds. A new key is usable on every endpoint immediately. See the "Consistency of changes" section of the "Cloud HSM - Architecture and high availability" guide.
Go further
Cloud HSM - Architecture and high availability
Getting started with Cloud HSM
How to use IAM policies using the OVHcloud Console
Join our community of users.