Merge pull request #6189 from Kxuan/fix-ctr_drbg-uninit

ctr_drbg: fix free uninitialized aes context
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 0000000..fe62c28
--- /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 43f490e..8919c78 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;
@@ -448,8 +449,6 @@
     mbedtls_mutex_init( &ctx->mutex );
 #endif
 
-    mbedtls_aes_init( &ctx->aes_ctx );
-
     ctx->f_entropy = f_entropy;
     ctx->p_entropy = p_entropy;