From 11e9310fd17808e69c0fc590697e8445997b251c Mon Sep 17 00:00:00 2001 From: kXuan Date: Wed, 10 Aug 2022 16:32:06 +0800 Subject: [PATCH 1/2] ctr_drbg: fix free uninitialized aes context Application may enabled AES_ALT and define mbedtls_aes_context by its own. The initial state of user-defined mbedtls_aes_context may not all byte zero. In mbedtls_ctr_drbg_init, the code set all byte to zero, including the AES context nested in the ctr_drbg context. And in mbedtls_ctr_drbg_free, the code calls mbedtls_aes_free on an AES context without calling mbedtls_aes_init. If user-defined AES context requires an non-zero init, the mbedtls_aes_free call in mbedtls_ctr_drbg_free is illegal. This patch fix this issue by add mbedtls_aes_init in mbedtls_ctr_drbg_init. So aes context will always be initialized to correct state. Signed-off-by: kXuan --- library/ctr_drbg.c | 1 + 1 file changed, 1 insertion(+) diff --git a/library/ctr_drbg.c b/library/ctr_drbg.c index 43f490e831..75103a3992 100644 --- a/library/ctr_drbg.c +++ b/library/ctr_drbg.c @@ -51,6 +51,7 @@ void mbedtls_ctr_drbg_init( mbedtls_ctr_drbg_context *ctx ) { memset( ctx, 0, sizeof( mbedtls_ctr_drbg_context ) ); + mbedtls_aes_init( &ctx->aes_ctx ); /* Indicate that the entropy nonce length is not set explicitly. * See mbedtls_ctr_drbg_set_nonce_len(). */ ctx->reseed_counter = -1; From 9ac6b28e279321d8ad1b816288e70cf3a745aed0 Mon Sep 17 00:00:00 2001 From: kXuan Date: Thu, 11 Aug 2022 09:52:18 +0800 Subject: [PATCH 2/2] ctr_drbg: remove mbedtls_aes_init call from mbedtls_ctr_drbg_seed Since 11e9310 add mbedtls_aes_init call in mbedtls_ctr_drbg_init, it should not init aes_ctx again in mbedtls_ctr_drbg_seed. Signed-off-by: kXuan --- ChangeLog.d/fix-ctr-drbg-may-free-invalid-aes-context.txt | 4 ++++ library/ctr_drbg.c | 2 -- 2 files changed, 4 insertions(+), 2 deletions(-) create mode 100644 ChangeLog.d/fix-ctr-drbg-may-free-invalid-aes-context.txt diff --git a/ChangeLog.d/fix-ctr-drbg-may-free-invalid-aes-context.txt b/ChangeLog.d/fix-ctr-drbg-may-free-invalid-aes-context.txt new file mode 100644 index 0000000000..fe62c28edc --- /dev/null +++ b/ChangeLog.d/fix-ctr-drbg-may-free-invalid-aes-context.txt @@ -0,0 +1,4 @@ +Bugfix + * Fix mbedtls_ctr_drbg_free() on an initialized but unseeded context. When + MBEDTLS_AES_ALT is enabled, it could call mbedtls_aes_free() on an + uninitialized context. diff --git a/library/ctr_drbg.c b/library/ctr_drbg.c index 75103a3992..8919c78a10 100644 --- a/library/ctr_drbg.c +++ b/library/ctr_drbg.c @@ -449,8 +449,6 @@ int mbedtls_ctr_drbg_seed( mbedtls_ctr_drbg_context *ctx, mbedtls_mutex_init( &ctx->mutex ); #endif - mbedtls_aes_init( &ctx->aes_ctx ); - ctx->f_entropy = f_entropy; ctx->p_entropy = p_entropy;