From: terrafrost <terrafrost@gmail.com>
Date: Sat, 24 Feb 2024 08:38:47 -0600
Subject: BigInteger: put guardrails on isPrime() and randomPrime()

Origin: upstream, https://github.com/phpseclib/phpseclib/commit/0358eb163c55a9fd7b3848b9ecc83f6b9e49dbf5
Bug-Debian: https://security-tracker.debian.org/tracker/CVE-2024-27354
---
 phpseclib/Math/BigInteger/Engines/Engine.php | 14 ++++++++++++++
 1 file changed, 14 insertions(+)

diff --git a/phpseclib/Math/BigInteger/Engines/Engine.php b/phpseclib/Math/BigInteger/Engines/Engine.php
index 2b00bc3..3a735e7 100644
--- a/phpseclib/Math/BigInteger/Engines/Engine.php
+++ b/phpseclib/Math/BigInteger/Engines/Engine.php
@@ -781,6 +781,11 @@ abstract class Engine implements \JsonSerializable
             $min = $temp;
         }
 
+        $length = $max->getLength();
+        if ($length > 8196) {
+            throw new \RuntimeException("Generation of random prime numbers larger than 8196 has been disabled ($length)");
+        }
+
         $x = static::randomRange($min, $max);
 
         return static::randomRangePrimeInner($x, $min, $max);
@@ -985,6 +990,15 @@ abstract class Engine implements \JsonSerializable
      */
     public function isPrime($t = false)
     {
+        // OpenSSL limits RSA keys to 16384 bits. The length of an RSA key is equal to the length of the modulo, which is
+        // produced by multiplying the primes p and q by one another. The largest number two 8196 bit primes can produce is
+        // a 16384 bit number so, basically, 8196 bit primes are the largest OpenSSL will generate and if that's the largest
+        // that it'll generate it also stands to reason that that's the largest you'll be able to test primality on
+        $length = $this->getLength();
+        if ($length > 8196) {
+            throw new \RuntimeException("Primality testing is not supported for numbers larger than 8196 bits ($length)");
+        }
+
         if (!$t) {
             $t = $this->setupIsPrime();
         }
