]> git.ipfire.org Git - thirdparty/openssl.git/commitdiff
fix potential memory leak in PKCS12_add_key_ex()
authorsashan <anedvedicky@gmail.com>
Wed, 22 May 2024 07:16:49 +0000 (09:16 +0200)
committerTodd Short <todd.short@me.com>
Tue, 18 Jun 2024 17:44:52 +0000 (13:44 -0400)
function must make sure memorry allocated for `p8`
gets freed in error path. Issue reported by LuMingYinDetect

Fixes #24453

Reviewed-by: Tomas Mraz <tomas@openssl.org>
Reviewed-by: Todd Short <todd.short@me.com>
(Merged from https://github.com/openssl/openssl/pull/24456)

crypto/pkcs12/p12_crt.c

index 26a444f868b0280524a55a6f042c3c7843fde3b7..6a7e97125fc4427a76f19b0f6ee06d7a07f2bb9f 100644 (file)
@@ -213,16 +213,19 @@ PKCS12_SAFEBAG *PKCS12_add_key_ex(STACK_OF(PKCS12_SAFEBAG) **pbags,
     if (key_usage && !PKCS8_add_keyusage(p8, key_usage))
         goto err;
     if (nid_key != -1) {
+        /* This call does not take ownership of p8 */
         bag = PKCS12_SAFEBAG_create_pkcs8_encrypt_ex(nid_key, pass, -1, NULL, 0,
                                                      iter, p8, ctx, propq);
-        PKCS8_PRIV_KEY_INFO_free(p8);
-    } else
+    } else {
         bag = PKCS12_SAFEBAG_create0_p8inf(p8);
+        if (bag != NULL)
+           p8 = NULL; /* bag takes ownership of p8 */
+    }
+    /* This does not need to be in the error path */
+    if (p8 != NULL)
+        PKCS8_PRIV_KEY_INFO_free(p8);
 
-    if (!bag)
-        goto err;
-
-    if (!pkcs12_add_bag(pbags, bag))
+    if (bag == NULL || !pkcs12_add_bag(pbags, bag))
         goto err;
 
     return bag;