Fix a mem leak in evp_pkey_copy_downgraded()
authorMatt Caswell <matt@openssl.org>
Fri, 3 Jun 2022 13:01:22 +0000 (14:01 +0100)
committerMatt Caswell <matt@openssl.org>
Wed, 8 Jun 2022 14:28:07 +0000 (15:28 +0100)
If we get a failure during evp_pkey_copy_downgraded() and on entry *dest
was NULL then we leak the EVP_PKEY that was automatically allocated and
stored in *dest.

Found due to this comment:
https://github.com/openssl/openssl/pull/18355#issuecomment-1145028315

Reviewed-by: Tomas Mraz <tomas@openssl.org>
Reviewed-by: David von Oheimb <david.von.oheimb@siemens.com>
(Merged from https://github.com/openssl/openssl/pull/18470)

crypto/evp/p_lib.c

index 46883255c6e4a6cc19e6850d057513b24f02da49..ed228a1bd43650c6b5ed03b683405d9d2f9ddae3 100644 (file)
@@ -1973,6 +1973,8 @@ void *evp_pkey_export_to_provider(EVP_PKEY *pk, OSSL_LIB_CTX *libctx,
 #ifndef FIPS_MODULE
 int evp_pkey_copy_downgraded(EVP_PKEY **dest, const EVP_PKEY *src)
 {
+    EVP_PKEY *allocpkey = NULL;
+
     if (!ossl_assert(dest != NULL))
         return 0;
 
@@ -2003,7 +2005,7 @@ int evp_pkey_copy_downgraded(EVP_PKEY **dest, const EVP_PKEY *src)
 
         /* Make sure we have a clean slate to copy into */
         if (*dest == NULL) {
-            *dest = EVP_PKEY_new();
+            allocpkey = *dest = EVP_PKEY_new();
             if (*dest == NULL) {
                 ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
                 return 0;
@@ -2052,6 +2054,10 @@ int evp_pkey_copy_downgraded(EVP_PKEY **dest, const EVP_PKEY *src)
         }
     }
 
+    if (allocpkey != NULL) {
+        EVP_PKEY_free(allocpkey);
+        *dest = NULL;
+    }
     return 0;
 }