Skip to content

Commit 82c3883

Browse files
committed
wolfcrypt/src/wc_pkcs11.c: cache PKCS#11 session across multi-call HMAC
The cryptocb dispatcher opened and closed a fresh PKCS#11 session around each HMAC invocation. PKCS#11 sign operations are session-scoped, so a multi-call HMAC (wc_HmacUpdate then wc_HmacFinal, which arrive as separate cryptocb dispatches) had its C_SignFinal land on a session that never saw a C_SignInit, returning CKR_OPERATION_NOT_INITIALIZED and surfacing as WC_HW_E. This broke any code path that drives Update and Final separately under PKCS#11 routing. Cache the PKCS#11 session handle on Hmac.devCtx (cast through wc_ptr_t, matching the existing pattern for cached PKCS#11 object handles) and rebuild the Pkcs11Session on the stack. The session is opened on the first dispatch when the operation enters WC_HMAC_INNER_HASH_KEYED_DEV state and released when it leaves that state (Final completed or hard error).
1 parent 1c9555c commit 82c3883

1 file changed

Lines changed: 32 additions & 3 deletions

File tree

wolfcrypt/src/wc_pkcs11.c

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6535,10 +6535,39 @@ int wc_Pkcs11_CryptoDevCb(int devId, wc_CryptoInfo* info, void* ctx)
65356535
}
65366536
else if (info->algo_type == WC_ALGO_TYPE_HMAC) {
65376537
#ifndef NO_HMAC
6538-
ret = Pkcs11OpenSession(token, &session, readWrite);
6539-
if (ret == 0) {
6538+
Hmac* hmac = info->hmac.hmac;
6539+
6540+
/* PKCS#11 Sign{Init,Update,Final} are session-scoped, so a
6541+
* multi-call HMAC must run on the same session. Cache the
6542+
* session handle on hmac->devCtx between dispatches. */
6543+
if (hmac != NULL && hmac->devCtx != NULL) {
6544+
session.func = token->func;
6545+
session.slotId = token->slotId;
6546+
session.version = token->version;
6547+
session.handle =
6548+
(CK_SESSION_HANDLE)(wc_ptr_t)hmac->devCtx;
65406549
ret = Pkcs11Hmac(&session, info);
6541-
Pkcs11CloseSession(token, &session);
6550+
if (ret != 0 ||
6551+
hmac->innerHashKeyed
6552+
!= WC_HMAC_INNER_HASH_KEYED_DEV) {
6553+
Pkcs11CloseSession(token, &session);
6554+
hmac->devCtx = NULL;
6555+
}
6556+
}
6557+
else {
6558+
ret = Pkcs11OpenSession(token, &session, readWrite);
6559+
if (ret == 0) {
6560+
ret = Pkcs11Hmac(&session, info);
6561+
if (ret == 0 && hmac != NULL &&
6562+
hmac->innerHashKeyed
6563+
== WC_HMAC_INNER_HASH_KEYED_DEV) {
6564+
hmac->devCtx =
6565+
(void*)(wc_ptr_t)session.handle;
6566+
}
6567+
else {
6568+
Pkcs11CloseSession(token, &session);
6569+
}
6570+
}
65426571
}
65436572
#else
65446573
ret = NOT_COMPILED_IN;

0 commit comments

Comments
 (0)