From 3bd976551e549c030bdbd150c7aa8a1980cb00fe Mon Sep 17 00:00:00 2001
From: Tomas Mraz <tomas@openssl.org>
Date: Tue, 29 Mar 2022 13:31:34 +0200
Subject: [PATCH] Fix strict client chain check with TLS-1.3

When TLS-1.3 is used and the server does not send any CA names
the ca_dn will be NULL. sk_X509_NAME_num() returns -1 on null
argument.

Reviewed-by: Todd Short <todd.short@me.com>
Reviewed-by: Matt Caswell <matt@openssl.org>
(Merged from https://github.com/openssl/openssl/pull/17986)

(cherry picked from commit 89dd85430770d39cbfb15eb586c921958ca7687f)
---
 ssl/t1_lib.c | 14 ++++++--------
 1 file changed, 6 insertions(+), 8 deletions(-)

diff --git a/ssl/t1_lib.c b/ssl/t1_lib.c
index 4de4623a49..5fcb40eaff 100644
--- a/ssl/t1_lib.c
+++ b/ssl/t1_lib.c
@@ -2369,22 +2369,20 @@ int tls1_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain,
 
         ca_dn = s->s3->tmp.peer_ca_names;
 
-        if (!sk_X509_NAME_num(ca_dn))
+        if (ca_dn == NULL
+            || sk_X509_NAME_num(ca_dn) == 0
+            || ssl_check_ca_name(ca_dn, x))
             rv |= CERT_PKEY_ISSUER_NAME;
-
-        if (!(rv & CERT_PKEY_ISSUER_NAME)) {
-            if (ssl_check_ca_name(ca_dn, x))
-                rv |= CERT_PKEY_ISSUER_NAME;
-        }
-        if (!(rv & CERT_PKEY_ISSUER_NAME)) {
+        else
             for (i = 0; i < sk_X509_num(chain); i++) {
                 X509 *xtmp = sk_X509_value(chain, i);
+
                 if (ssl_check_ca_name(ca_dn, xtmp)) {
                     rv |= CERT_PKEY_ISSUER_NAME;
                     break;
                 }
             }
-        }
+
         if (!check_flags && !(rv & CERT_PKEY_ISSUER_NAME))
             goto end;
     } else
-- 
2.17.1

