Commit 7f503e882b for openssl.org

commit 7f503e882bfb6a56186fb54e4d2476df51578f07
Author: Dr. David von Oheimb <dev@ddvo.net>
Date:   Sun Jun 1 08:35:28 2025 +0200

    ASN1_item_sign_ctx(): prevent crash due to wrong memory deallocation on d2i_X509_ALGOR() failure

    Reviewed-by: Matt Caswell <matt@openssl.org>
    Reviewed-by: Dmitry Belyavskiy <beldmit@gmail.com>
    (Merged from https://github.com/openssl/openssl/pull/27737)

diff --git a/crypto/asn1/a_sign.c b/crypto/asn1/a_sign.c
index 7659cf8703..18368b8e3f 100644
--- a/crypto/asn1/a_sign.c
+++ b/crypto/asn1/a_sign.c
@@ -143,6 +143,21 @@ err:
     return rv;
 }

+static int replace_algor_contents_from_DER(X509_ALGOR *algor, const unsigned char *aid, size_t len)
+{
+    /* as a workaround for d2i_*() freeing its first argument, using NULL instead: */
+    X509_ALGOR *alg = d2i_X509_ALGOR(NULL, &aid, (long)len);
+    int ret;
+
+    if (alg == NULL) {
+        ERR_raise(ERR_LIB_ASN1, ASN1_R_DECODE_ERROR);
+        return 0;
+    }
+    ret = X509_ALGOR_copy(algor, alg);
+    X509_ALGOR_free(alg);
+    return ret;
+}
+
 int ASN1_item_sign_ctx(const ASN1_ITEM *it, X509_ALGOR *algor1,
     X509_ALGOR *algor2, ASN1_BIT_STRING *signature,
     const void *data, EVP_MD_CTX *ctx)
@@ -186,23 +201,10 @@ int ASN1_item_sign_ctx(const ASN1_ITEM *it, X509_ALGOR *algor1,
             goto err;
         }

-        if (algor1 != NULL) {
-            const unsigned char *pp = aid;
-
-            if (d2i_X509_ALGOR(&algor1, &pp, (long)aid_len) == NULL) {
-                ERR_raise(ERR_LIB_ASN1, ERR_R_INTERNAL_ERROR);
-                goto err;
-            }
-        }
-
-        if (algor2 != NULL) {
-            const unsigned char *pp = aid;
-
-            if (d2i_X509_ALGOR(&algor2, &pp, (long)aid_len) == NULL) {
-                ERR_raise(ERR_LIB_ASN1, ERR_R_INTERNAL_ERROR);
-                goto err;
-            }
-        }
+        if (algor1 != NULL && !replace_algor_contents_from_DER(algor1, aid, aid_len))
+            goto err;
+        if (algor2 != NULL && !replace_algor_contents_from_DER(algor2, aid, aid_len))
+            goto err;

         rv = 3;
     } else if (pkey->ameth->item_sign) {