Commit a21fdfc89a for openssl.org

commit a21fdfc89aa07c62ca642bc729ef0c42e7cb0f7d
Author: Ingo Franzki <ifranzki@linux.ibm.com>
Date:   Mon Jul 6 08:24:42 2026 +0200

    Fix crash in EVP_MD_CTX_copy_ex on inconsistent context

    EVP_MD_CTX_copy_ex() might crash on an NULL pointer access when an
    inconsistent context is copied. This happens when a context is copied
    where digest is set but algctx is NULL, i.e. due to an incomplete
    initialization.

    The copyctx shortcut for cases where the in and out contexts use the
    exact same digest call the copyctx function attempting to copy
    the algctx, but it does not check if algctx is NULL on the in or out
    contexts.

    Fix this by only taking the copyctx shortcut if algctx is non-NULL on
    both, in and out. Otherwise use the full copy path which will only
    duplicate the algctx if it is non-NULL.

    Closes: https://github.com/openssl/openssl/issues/31831

    Signed-off-by: Ingo Franzki <ifranzki@linux.ibm.com>

    Reviewed-by: Neil Horman <nhorman@openssl.org>
    Reviewed-by: Paul Dale <paul.dale@oracle.com>
    (Merged from https://github.com/openssl/openssl/pull/31867)

diff --git a/crypto/evp/digest.c b/crypto/evp/digest.c
index 2cb490b279..61e7dbc4ec 100644
--- a/crypto/evp/digest.c
+++ b/crypto/evp/digest.c
@@ -494,7 +494,8 @@ int EVP_MD_CTX_copy_ex(EVP_MD_CTX *out, const EVP_MD_CTX *in)
         return 0;
     }

-    if (out->digest == in->digest && in->digest->copyctx != NULL) {
+    if (out->digest == in->digest && in->digest->copyctx != NULL
+        && out->algctx != NULL && in->algctx != NULL) {

         in->digest->copyctx(out->algctx, in->algctx);