Skip to content

Commit 1b26594

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 1b26594

1 file changed

Lines changed: 39 additions & 3 deletions

File tree

wolfcrypt/src/wc_pkcs11.c

Lines changed: 39 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6535,10 +6535,46 @@ 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+
/* Sign ops are session-scoped; cache the session across
6541+
* multi-call HMAC dispatches. */
6542+
if (hmac != NULL && hmac->devCtx != NULL) {
6543+
session.func = token->func;
6544+
session.slotId = token->slotId;
6545+
session.version = token->version;
6546+
session.handle =
6547+
(CK_SESSION_HANDLE)(wc_ptr_t)hmac->devCtx;
65406548
ret = Pkcs11Hmac(&session, info);
6541-
Pkcs11CloseSession(token, &session);
6549+
if (ret != 0 ||
6550+
hmac->innerHashKeyed
6551+
!= WC_HMAC_INNER_HASH_KEYED_DEV) {
6552+
Pkcs11CloseSession(token, &session);
6553+
hmac->devCtx = NULL;
6554+
/* Don't leave stale DEV state past session close;
6555+
* leave SW state (owned by software fallback). */
6556+
if (hmac->innerHashKeyed
6557+
== WC_HMAC_INNER_HASH_KEYED_DEV)
6558+
hmac->innerHashKeyed = 0;
6559+
}
6560+
}
6561+
else {
6562+
ret = Pkcs11OpenSession(token, &session, readWrite);
6563+
if (ret == 0) {
6564+
ret = Pkcs11Hmac(&session, info);
6565+
if (ret == 0 && hmac != NULL &&
6566+
hmac->innerHashKeyed
6567+
== WC_HMAC_INNER_HASH_KEYED_DEV) {
6568+
hmac->devCtx =
6569+
(void*)(wc_ptr_t)session.handle;
6570+
}
6571+
else {
6572+
Pkcs11CloseSession(token, &session);
6573+
if (hmac != NULL && hmac->innerHashKeyed
6574+
== WC_HMAC_INNER_HASH_KEYED_DEV)
6575+
hmac->innerHashKeyed = 0;
6576+
}
6577+
}
65426578
}
65436579
#else
65446580
ret = NOT_COMPILED_IN;

0 commit comments

Comments
 (0)