diff --git a/ChangeLog.d/fix-concurrently-loading-non-existent-keys.txt b/ChangeLog.d/fix-concurrently-loading-non-existent-keys.txt new file mode 100644 index 0000000000..8a406a12e8 --- /dev/null +++ b/ChangeLog.d/fix-concurrently-loading-non-existent-keys.txt @@ -0,0 +1,4 @@ +Bugfix + * Fix rare concurrent access bug where attempting to operate on a + non-existent key while concurrently creating a new key could potentially + corrupt the key store. diff --git a/library/psa_crypto_slot_management.c b/library/psa_crypto_slot_management.c index b184ed08c9..9986a44969 100644 --- a/library/psa_crypto_slot_management.c +++ b/library/psa_crypto_slot_management.c @@ -424,6 +424,8 @@ psa_status_t psa_get_and_lock_key_slot(mbedtls_svc_key_id_t key, if (status != PSA_SUCCESS) { psa_wipe_key_slot(*p_slot); + /* If the key does not exist, we need to return + * PSA_ERROR_INVALID_HANDLE. */ if (status == PSA_ERROR_DOES_NOT_EXIST) { status = PSA_ERROR_INVALID_HANDLE; } @@ -440,6 +442,9 @@ psa_status_t psa_get_and_lock_key_slot(mbedtls_svc_key_id_t key, status = PSA_ERROR_INVALID_HANDLE; #endif /* MBEDTLS_PSA_CRYPTO_STORAGE_C || MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS */ + if (status != PSA_SUCCESS) { + *p_slot = NULL; + } #if defined(MBEDTLS_THREADING_C) PSA_THREADING_CHK_RET(mbedtls_mutex_unlock( &mbedtls_threading_key_slot_mutex)); diff --git a/library/psa_crypto_slot_management.h b/library/psa_crypto_slot_management.h index bcfc9d8adc..a84be7d837 100644 --- a/library/psa_crypto_slot_management.h +++ b/library/psa_crypto_slot_management.h @@ -58,6 +58,9 @@ static inline int psa_key_id_is_volatile(psa_key_id_t key_id) * It is the responsibility of the caller to call psa_unregister_read(slot) * when they have finished reading the contents of the slot. * + * On failure, `*p_slot` is set to NULL. This ensures that it is always valid + * to call psa_unregister_read on the returned slot. + * * \param key Key identifier to query. * \param[out] p_slot On success, `*p_slot` contains a pointer to the * key slot containing the description of the key