Merge pull request #3578 from gilles-peskine-arm/md_setup-leak-development

Fix memory leak in mbedtls_md_setup with HMAC
diff --git a/ChangeLog.d/md_setup-leak.txt b/ChangeLog.d/md_setup-leak.txt
new file mode 100644
index 0000000..5111d8e
--- /dev/null
+++ b/ChangeLog.d/md_setup-leak.txt
@@ -0,0 +1,3 @@
+Bugfix
+   * Fix a memory leak in mbedtls_md_setup() when using HMAC under low memory
+     conditions. Reported and fix suggested by Guido Vranken in #3486.
diff --git a/library/md.c b/library/md.c
index 430ba5d..de77b16 100644
--- a/library/md.c
+++ b/library/md.c
@@ -411,6 +411,10 @@
     if( md_info == NULL || ctx == NULL )
         return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
 
+    ctx->md_info = md_info;
+    ctx->md_ctx = NULL;
+    ctx->hmac_ctx = NULL;
+
     switch( md_info->type )
     {
 #if defined(MBEDTLS_MD2_C)
@@ -466,8 +470,6 @@
         }
     }
 
-    ctx->md_info = md_info;
-
     return( 0 );
 }
 #undef ALLOC