Fix memory leak in mbedtls_md_setup with HMAC

mbedtls_md_setup() allocates a hash-specific context and then, if
requested, an extra HMAC context. If the second allocation failed, the
hash context was not freed.

Fix this by ensuring that the mbedtls_md_context_t object is always in
a consistent state, in particular, that the md_info field is always
set. For robustness, ensure that the object is in a consistent state
even on errors (other than BAD_INPUT_DATA if the object was not in a
consistent state on entry).

Fix #3486

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
diff --git a/library/md.c b/library/md.c
index 3eb0fe3..0b9f3da 100644
--- a/library/md.c
+++ b/library/md.c
@@ -413,6 +413,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)
@@ -468,8 +472,6 @@
         }
     }
 
-    ctx->md_info = md_info;
-
     return( 0 );
 }
 #undef ALLOC