Skip to content

Commit cd51786

Browse files
committed
Fix PKCS11 object leak in Pkcs11ECDH
1 parent 4fe05d7 commit cd51786

1 file changed

Lines changed: 22 additions & 1 deletion

File tree

wolfcrypt/src/wc_pkcs11.c

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2994,6 +2994,7 @@ static int Pkcs11ECDH(Pkcs11Session* session, wc_CryptoInfo* info)
29942994
{
29952995
int ret = 0;
29962996
int sessionKey = 0;
2997+
int destroyPrivKey = 0;
29972998
unsigned char* point = NULL;
29982999
word32 pointLen;
29993000
CK_RV rv;
@@ -3038,6 +3039,11 @@ static int Pkcs11ECDH(Pkcs11Session* session, wc_CryptoInfo* info)
30383039
else {
30393040
ret = Pkcs11FindEccKey(&privateKey, CKO_PRIVATE_KEY, session,
30403041
info->pk.ecdh.public_key, CKA_DERIVE);
3042+
if (ret == 0) {
3043+
/* Key found by public key match is likely ephemeral (e.g. from
3044+
* Pkcs11EcKeyGen for ECDHE), clean it up after use. */
3045+
destroyPrivKey = 1;
3046+
}
30413047
}
30423048
}
30433049
if (ret == 0) {
@@ -3085,8 +3091,23 @@ static int Pkcs11ECDH(Pkcs11Session* session, wc_CryptoInfo* info)
30853091
info->pk.ecdh.outlen);
30863092
}
30873093

3088-
if (sessionKey)
3094+
if (secret != CK_INVALID_HANDLE)
3095+
session->func->C_DestroyObject(session->handle, secret);
3096+
3097+
if (sessionKey) {
30893098
session->func->C_DestroyObject(session->handle, privateKey);
3099+
}
3100+
else if (destroyPrivKey && privateKey != NULL_PTR) {
3101+
/* Only destroy if the key is a non-persistent session object */
3102+
CK_BBOOL isToken = CK_FALSE;
3103+
CK_ATTRIBUTE tokenTmpl[] = {
3104+
{ CKA_TOKEN, &isToken, sizeof(isToken) },
3105+
};
3106+
if (session->func->C_GetAttributeValue(session->handle, privateKey,
3107+
tokenTmpl, 1) == CKR_OK && isToken == CK_FALSE) {
3108+
session->func->C_DestroyObject(session->handle, privateKey);
3109+
}
3110+
}
30903111

30913112
if (point != NULL)
30923113
XFREE(point, info->pk.ecdh.public_key->heap, DYNAMIC_TYPE_ECC_BUFFER);

0 commit comments

Comments
 (0)