From bdb229da3af51e369c97095a445d0d2139ce1b07 Mon Sep 17 00:00:00 2001
From: Matt Caswell <matt@openssl.org>
Date: Wed, 18 Aug 2021 17:58:23 +0100
Subject: [PATCH 6/9] Fix append_ia5 function to not assume NUL terminated
 strings

ASN.1 strings may not be NUL terminated. Don't assume they are.

CVE-2021-3712

Reviewed-by: Viktor Dukhovni <viktor@openssl.org>
Reviewed-by: Paul Dale <pauli@openssl.org>
---
 .../OpensslLib/openssl/crypto/x509v3/v3_utl.c  | 18 +++++++++++++-----
 1 file changed, 13 insertions(+), 5 deletions(-)

diff --git a/CryptoPkg/Library/OpensslLib/openssl/crypto/x509v3/v3_utl.c b/CryptoPkg/Library/OpensslLib/openssl/crypto/x509v3/v3_utl.c
index 004ef55..513dc68 100644
--- a/CryptoPkg/Library/OpensslLib/openssl/crypto/x509v3/v3_utl.c
+++ b/CryptoPkg/Library/OpensslLib/openssl/crypto/x509v3/v3_utl.c
@@ -528,18 +528,26 @@ static int append_ia5(STACK_OF(OPENSSL_STRING) **sk, const ASN1_IA5STRING *email
     /* First some sanity checks */
     if (email->type != V_ASN1_IA5STRING)
         return 1;
-    if (!email->data || !email->length)
+    if (email->data == NULL || email->length == 0)
+        return 1;
+    if (memchr(email->data, 0, email->length) != NULL)
         return 1;
     if (*sk == NULL)
         *sk = sk_OPENSSL_STRING_new(sk_strcmp);
     if (*sk == NULL)
         return 0;
+
+    emtmp = OPENSSL_strndup((char *)email->data, email->length);
+    if (emtmp == NULL)
+        return 0;
+
     /* Don't add duplicates */
-    if (sk_OPENSSL_STRING_find(*sk, (char *)email->data) != -1)
+    if (sk_OPENSSL_STRING_find(*sk, emtmp) != -1) {
+        OPENSSL_free(emtmp);
         return 1;
-    emtmp = OPENSSL_strdup((char *)email->data);
-    if (emtmp == NULL || !sk_OPENSSL_STRING_push(*sk, emtmp)) {
-        OPENSSL_free(emtmp);    /* free on push failure */
+    }
+    if (!sk_OPENSSL_STRING_push(*sk, emtmp)) {
+        OPENSSL_free(emtmp); /* free on push failure */
         X509_email_free(*sk);
         *sk = NULL;
         return 0;
-- 
2.33.0

