From 8780a896543a654e757db1b9396383f9d8095528 Mon Sep 17 00:00:00 2001
From: Matt Caswell <matt@openssl.org>
Date: Thu, 6 Jul 2023 16:36:35 +0100
Subject: [PATCH] Fix DH_check() excessive time with over sized modulus

The DH_check() function checks numerous aspects of the key or parameters
that have been supplied. Some of those checks use the supplied modulus
value even if it is excessively large.

There is already a maximum DH modulus size (10,000 bits) over which
OpenSSL will not generate or derive keys. DH_check() will however still
perform various tests for validity on such a large modulus. We introduce
a
new maximum (32,768) over which DH_check() will just fail.

An application that calls DH_check() and supplies a key or parameters
obtained from an untrusted source could be vulnerable to a Denial of
Service attack.

The function DH_check() is itself called by a number of other OpenSSL
functions. An application calling any of those other functions may
similarly be affected. The other functions affected by this are
DH_check_ex() and EVP_PKEY_param_check().

CVE-2023-3446

Reviewed-by: Paul Dale <pauli@openssl.org>
Reviewed-by: Tom Cosgrove <tom.cosgrove@arm.com>
Reviewed-by: Bernd Edlinger <bernd.edlinger@hotmail.de>
Reviewed-by: Tomas Mraz <tomas@openssl.org>
(Merged from https://github.com/openssl/openssl/pull/21452)
---
 Cryptlib/Include/openssl/dh.h         | 5 +++++
 Cryptlib/OpenSSL/crypto/dh/dh_check.c | 4 ++++
 2 files changed, 9 insertions(+)

diff --git a/Cryptlib/Include/openssl/dh.h b/Cryptlib/Include/openssl/dh.h
index 6488879..06142df 100644
--- a/Cryptlib/Include/openssl/dh.h
+++ b/Cryptlib/Include/openssl/dh.h
@@ -77,6 +77,10 @@
 #  define OPENSSL_DH_MAX_MODULUS_BITS    10000
 # endif
 
+# ifndef OPENSSL_DH_CHECK_MAX_MODULUS_BITS
+#  define OPENSSL_DH_CHECK_MAX_MODULUS_BITS 32768
+# endif
+
 # define DH_FLAG_CACHE_MONT_P     0x01
 
 /*
@@ -356,6 +360,7 @@ void ERR_load_DH_strings(void);
 # define DH_F_COMPUTE_KEY                                 102
 # define DH_F_DHPARAMS_PRINT_FP                           101
 # define DH_F_DH_BUILTIN_GENPARAMS                        106
+# define DH_F_DH_CHECK                                    126
 # define DH_F_DH_CMS_DECRYPT                              117
 # define DH_F_DH_CMS_SET_PEERKEY                          118
 # define DH_F_DH_CMS_SET_SHARED_INFO                      119
diff --git a/Cryptlib/OpenSSL/crypto/dh/dh_check.c b/Cryptlib/OpenSSL/crypto/dh/dh_check.c
index 9f3b174..9c62da4 100644
--- a/Cryptlib/OpenSSL/crypto/dh/dh_check.c
+++ b/Cryptlib/OpenSSL/crypto/dh/dh_check.c
@@ -78,6 +78,10 @@ int DH_check(const DH *dh, int *ret)
     BN_ULONG l;
     BIGNUM *t1 = NULL, *t2 = NULL;
 
+    /* Don't do any check at all with an excessively large modulus */
+    if (BN_num_bits(dh->p) > OPENSSL_DH_CHECK_MAX_MODULUS_BITS) {
+        return 0;
+    }
     *ret = 0;
     ctx = BN_CTX_new();
     if (ctx == NULL)
-- 
2.27.0

