From 91ffe5b87187e45a0d58cf0510d773ebe804508d Mon Sep 17 00:00:00 2001 From: Ryan Everett Date: Tue, 23 Jan 2024 20:05:42 +0000 Subject: [PATCH] Make psa_finish_key_creation thread safe Hold mutex for the entirety of the call. We are writing to storage and writing to the slot state here. If we didn't keep the mutex for the whole duration then we may end up with another thread seeing that a persistent key is in storage before our slot is set to FULL; this would be unlinearizable behaviour. Signed-off-by: Ryan Everett --- library/psa_crypto.c | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/library/psa_crypto.c b/library/psa_crypto.c index 4a0666bb8..d53a09da3 100644 --- a/library/psa_crypto.c +++ b/library/psa_crypto.c @@ -1799,6 +1799,11 @@ static psa_status_t psa_finish_key_creation( (void) slot; (void) driver; +#if defined(MBEDTLS_THREADING_C) + PSA_THREADING_CHK_RET(mbedtls_mutex_lock( + &mbedtls_threading_key_slot_mutex)); +#endif + #if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) if (!PSA_KEY_LIFETIME_IS_VOLATILE(slot->attr.lifetime)) { #if defined(MBEDTLS_PSA_CRYPTO_SE_C) @@ -1838,6 +1843,11 @@ static psa_status_t psa_finish_key_creation( status = psa_save_se_persistent_data(driver); if (status != PSA_SUCCESS) { psa_destroy_persistent_key(slot->attr.id); + +#if defined(MBEDTLS_THREADING_C) + PSA_THREADING_CHK_RET(mbedtls_mutex_unlock( + &mbedtls_threading_key_slot_mutex)); +#endif return status; } status = psa_crypto_stop_transaction(); @@ -1853,6 +1863,10 @@ static psa_status_t psa_finish_key_creation( } } +#if defined(MBEDTLS_THREADING_C) + PSA_THREADING_CHK_RET(mbedtls_mutex_unlock( + &mbedtls_threading_key_slot_mutex)); +#endif return status; }