Fix a possible memory leak in CMS_add_simple_smimecap
authorBernd Edlinger <bernd.edlinger@hotmail.de>
Wed, 15 Nov 2023 18:14:54 +0000 (19:14 +0100)
committerBernd Edlinger <bernd.edlinger@hotmail.de>
Mon, 4 Dec 2023 11:54:08 +0000 (12:54 +0100)
The return code of X509_ALGOR_set0 was not checked,
and if it fails the key will be leaked.

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

crypto/cms/cms_sd.c

index cfac556957df9a97356cc8a0b1d30fdae5489d3f..9788322f8d4e3a574bd5bae05f05493e839eb833 100644 (file)
@@ -1068,31 +1068,32 @@ int CMS_add_smimecap(CMS_SignerInfo *si, STACK_OF(X509_ALGOR) *algs)
 int CMS_add_simple_smimecap(STACK_OF(X509_ALGOR) **algs,
                             int algnid, int keysize)
 {
-    X509_ALGOR *alg;
+    X509_ALGOR *alg = NULL;
     ASN1_INTEGER *key = NULL;
 
     if (keysize > 0) {
         key = ASN1_INTEGER_new();
-        if (key == NULL || !ASN1_INTEGER_set(key, keysize)) {
-            ASN1_INTEGER_free(key);
-            return 0;
-        }
+        if (key == NULL || !ASN1_INTEGER_set(key, keysize))
+            goto err;
     }
     alg = X509_ALGOR_new();
-    if (alg == NULL) {
-        ASN1_INTEGER_free(key);
-        return 0;
-    }
+    if (alg == NULL)
+        goto err;
 
-    X509_ALGOR_set0(alg, OBJ_nid2obj(algnid),
-                    key ? V_ASN1_INTEGER : V_ASN1_UNDEF, key);
+    if (!X509_ALGOR_set0(alg, OBJ_nid2obj(algnid),
+                         key ? V_ASN1_INTEGER : V_ASN1_UNDEF, key))
+        goto err;
+    key = NULL;
     if (*algs == NULL)
         *algs = sk_X509_ALGOR_new_null();
-    if (*algs == NULL || !sk_X509_ALGOR_push(*algs, alg)) {
-        X509_ALGOR_free(alg);
-        return 0;
-    }
+    if (*algs == NULL || !sk_X509_ALGOR_push(*algs, alg))
+        goto err;
     return 1;
+
+ err:
+    ASN1_INTEGER_free(key);
+    X509_ALGOR_free(alg);
+    return 0;
 }
 
 /* Check to see if a cipher exists and if so add S/MIME capabilities */