From da51d6901342a7f4fd9ce61219f9c92d351c971c Mon Sep 17 00:00:00 2001 From: Mike Szczys Date: Fri, 26 Jun 2026 13:16:01 -0500 Subject: [PATCH] fix(esp-tls): only destroy volatile keys in DS/ECDSA cleanup The DS/ECDSA cleanup added in 8cb64703 is intended for volatile PSA keys created internally by the DS and ECDSA peripheral paths. Ensure that during the cleanup, PSA_KEY_LIFETIME_IS_VOLATILE() is checked to avoid destroying keys the user has added persistently to PSA. This resolves an issue in the next commit (adding support for clientkey_psa_id) where a user passes a PSA key id that is then silently destroyed if CONFIG_ESP_TLS_USE_DS_PERIPHERAL or CONFIG_MBEDTLS_HARDWARE_ECDSA_SIGN happen to be defined. Signed-off-by: Mike Szczys --- components/esp-tls/esp_tls_mbedtls.c | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/components/esp-tls/esp_tls_mbedtls.c b/components/esp-tls/esp_tls_mbedtls.c index 901d4ba713b..22c2dd5659b 100644 --- a/components/esp-tls/esp_tls_mbedtls.c +++ b/components/esp-tls/esp_tls_mbedtls.c @@ -498,11 +498,22 @@ void esp_mbedtls_cleanup(esp_tls_t *tls) * before calling mbedtls_pk_free(). mbedtls_pk_wrap_psa() sets the pk_info * to mbedtls_{rsa,ecdsa}_opaque_info, both of which have type * MBEDTLS_PK_OPAQUE — so a single check covers both DS and ECDSA paths. - * clientkey and serverkey share storage via union, so one branch suffices. */ + * clientkey and serverkey share storage via union, so one branch suffices. + * + * Only destroy volatile keys created internally by the DS/ECDSA peripheral + * paths. Keys wrapped from an external clientkey_psa_id are caller-owned + * (typically persistent) and must not be destroyed here. */ #if defined(CONFIG_ESP_TLS_USE_DS_PERIPHERAL) || defined(CONFIG_MBEDTLS_HARDWARE_ECDSA_SIGN) if (mbedtls_pk_get_type(&tls->clientkey) == MBEDTLS_PK_OPAQUE) { if (tls->clientkey.MBEDTLS_PRIVATE(priv_id) != PSA_KEY_ID_NULL) { - psa_destroy_key(tls->clientkey.MBEDTLS_PRIVATE(priv_id)); + psa_key_attributes_t attrs = PSA_KEY_ATTRIBUTES_INIT; + if (psa_get_key_attributes(tls->clientkey.MBEDTLS_PRIVATE(priv_id), + &attrs) == PSA_SUCCESS) { + if (PSA_KEY_LIFETIME_IS_VOLATILE(psa_get_key_lifetime(&attrs))) { + psa_destroy_key(tls->clientkey.MBEDTLS_PRIVATE(priv_id)); + } + psa_reset_key_attributes(&attrs); + } tls->clientkey.MBEDTLS_PRIVATE(priv_id) = PSA_KEY_ID_NULL; } }