From 86863f2ddc4200e5048e28c40ed6521495010699 Mon Sep 17 00:00:00 2001
From: Matt Caswell <matt@openssl.org>
Date: Wed, 27 May 2020 11:37:39 +0100
Subject: [PATCH 023/147] Ensure we never use a partially initialised CMAC_CTX

If the CMAC_CTX is partially initialised then we make a note of this so
that future operations will fail if the initialisation has not been
completed.

Reviewed-by: Tomas Mraz <tmraz@fedoraproject.org>
(Merged from https://github.com/openssl/openssl/pull/12107)
---
 crypto/cmac/cmac.c | 13 ++++++++++---
 1 file changed, 10 insertions(+), 3 deletions(-)

diff --git a/crypto/cmac/cmac.c b/crypto/cmac/cmac.c
index 6989c32..dbcc436 100644
--- a/crypto/cmac/cmac.c
+++ b/crypto/cmac/cmac.c
@@ -116,11 +116,18 @@ int CMAC_Init(CMAC_CTX *ctx, const void *key, size_t keylen,
         return 1;
     }
     /* Initialise context */
-    if (cipher && !EVP_EncryptInit_ex(ctx->cctx, cipher, impl, NULL, NULL))
-        return 0;
+    if (cipher != NULL) {
+        /* Ensure we can't use this ctx until we also have a key */
+        ctx->nlast_block = -1;
+        if (!EVP_EncryptInit_ex(ctx->cctx, cipher, impl, NULL, NULL))
+            return 0;
+    }
     /* Non-NULL key means initialisation complete */
-    if (key) {
+    if (key != NULL) {
         int bl;
+
+        /* If anything fails then ensure we can't use this ctx */
+        ctx->nlast_block = -1;
         if (!EVP_CIPHER_CTX_cipher(ctx->cctx))
             return 0;
         if (!EVP_CIPHER_CTX_set_key_length(ctx->cctx, keylen))
-- 
1.8.3.1

