From ce61a32e6a68c2ab0f97dfd1a8c075f24d078459 Mon Sep 17 00:00:00 2001 From: Hanno Becker Date: Sat, 17 Nov 2018 22:11:16 +0000 Subject: [PATCH] Use enum for slot state in PSA-based cipher context --- include/mbedtls/cipher_internal.h | 20 ++++++++++++++++---- library/cipher.c | 8 +++++--- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/include/mbedtls/cipher_internal.h b/include/mbedtls/cipher_internal.h index f1f0e2bde..cecad9a8d 100644 --- a/include/mbedtls/cipher_internal.h +++ b/include/mbedtls/cipher_internal.h @@ -119,14 +119,26 @@ typedef struct } mbedtls_cipher_definition_t; #if defined(MBEDTLS_USE_PSA_CRYPTO) +typedef enum +{ + MBEDTLS_CIPHER_PSA_KEY_UNSET = 0, + MBEDTLS_CIPHER_PSA_KEY_OWNED, /* Used for PSA-based cipher contexts + * which use raw key material internally + * imported into a freshly allocated key slot, + * and which hence need to destroy that key + * slot when they are no longer needed. */ + MBEDTLS_CIPHER_PSA_KEY_NOT_OWNED, /* Used for PSA-based cipher contexts + * which use a key from a key slot + * provided by the user, and which hence + * should not be destroyed when the + * context is no longer needed. */ +} mbedtls_cipher_psa_key_ownership; + typedef struct { psa_algorithm_t alg; psa_key_slot_t slot; - unsigned char slot_state; /*!< 0: The slot is unset. - * 1: The slot is set and we own it. - * 2: The slot is set but we don't own it. */ - + mbedtls_cipher_psa_key_ownership slot_state; } mbedtls_cipher_context_psa; #endif /* MBEDTLS_USE_PSA_CRYPTO */ diff --git a/library/cipher.c b/library/cipher.c index e9a1a07a0..95146ac63 100644 --- a/library/cipher.c +++ b/library/cipher.c @@ -175,7 +175,7 @@ void mbedtls_cipher_free( mbedtls_cipher_context_t *ctx ) mbedtls_cipher_context_psa * const cipher_psa = (mbedtls_cipher_context_psa *) ctx->cipher_ctx; - if( cipher_psa->slot_state == 1 ) + if( cipher_psa->slot_state == MBEDTLS_CIPHER_PSA_KEY_OWNED ) { /* xxx_free() doesn't allow to return failures. */ (void) psa_destroy_key( cipher_psa->slot ); @@ -299,14 +299,16 @@ int mbedtls_cipher_setkey( mbedtls_cipher_context_t *ctx, return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); /* Don't allow keys to be set multiple times. */ - if( cipher_psa->slot_state != 0 ) + if( cipher_psa->slot_state != MBEDTLS_CIPHER_PSA_KEY_UNSET ) return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); /* Find a fresh key slot to use. */ status = mbedtls_psa_get_free_key_slot( &cipher_psa->slot ); if( status != PSA_SUCCESS ) return( MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED ); - cipher_psa->slot_state = 1; /* Indicate that we own the key slot. */ + /* Indicate that we own the key slot and need to + * destroy it in mbedtls_cipher_free(). */ + cipher_psa->slot_state = MBEDTLS_CIPHER_PSA_KEY_OWNED; /* From that point on, the responsibility for destroying the * key slot is on mbedtls_cipher_free(). This includes the case