From 81a0110a56c37330bb3f68cfce6e559591daab56 Mon Sep 17 00:00:00 2001 From: lav45 Date: Tue, 10 Nov 2026 19:17:45 +0300 Subject: [PATCH 1/2] fix(okp): refuse the Ed25519 public keys of small order without sodium OpenSSL loads an Ed25519 public key whose point is of small order, and with the neutral point as key it verifies the signature R = the neutral point, S = 0 for any input. Without ext-sodium, AbstractEdDSA::verify() goes through OKPKey::verifyWithOpenSSL(), so Ed25519 and EdDSA accepted such a forged signature. With sodium, sodium_crypto_sign_verify_detached() refuses it. OKPKey::isSmallOrderEd25519Point() compares "x", sign bit cleared, with the 7 encodings libsodium refuses (ge25519_has_small_order()): the 8 points of order 1, 2, 4 and 8 and the non-canonical encodings of y = 0 and y = 1. It needs no extension. verifyWithOpenSSL() returns false for such a key, and OKPKeyAnalyzer reports it whichever backend is loaded. --- src/Library/Core/Util/OKPKey.php | 28 +++++++++++ .../KeyManagement/Analyzer/OKPKeyAnalyzer.php | 18 +++++-- tests/Component/Core/Util/OKPKeyTest.php | 47 +++++++++++++++++++ .../KeyManagement/OKPKeyAnalyzerTest.php | 27 +++++++++++ .../EdDSA/FullySpecifiedEdDSATest.php | 15 ++++++ 5 files changed, 130 insertions(+), 5 deletions(-) diff --git a/src/Library/Core/Util/OKPKey.php b/src/Library/Core/Util/OKPKey.php index a025dd64..9a02d78f 100644 --- a/src/Library/Core/Util/OKPKey.php +++ b/src/Library/Core/Util/OKPKey.php @@ -21,10 +21,13 @@ use SpomkyLabs\Pki\CryptoTypes\Asymmetric\RFC8410\Curve448\Ed448PublicKey; use SpomkyLabs\Pki\CryptoTypes\Asymmetric\RFC8410\Curve448\X448PrivateKey; use SpomkyLabs\Pki\CryptoTypes\Asymmetric\RFC8410\Curve448\X448PublicKey; +use function bin2hex; +use function chr; use function extension_loaded; use function in_array; use function is_array; use function is_string; +use function ord; use function sprintf; use function strlen; use const PHP_VERSION_ID; @@ -61,6 +64,16 @@ self::CURVE_X448 => 56, ]; + private const ED25519_SMALL_ORDER_POINTS = [ + '0000000000000000000000000000000000000000000000000000000000000000', // y = 0, order 4 + '0100000000000000000000000000000000000000000000000000000000000000', // y = 1, order 1 + '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05', // order 8 + 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a', // order 8 + 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f', // y = p - 1, order 2 + 'edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f', // y = p, order 4 + 'eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f', // y = p + 1, order 1 + ]; + /** * The OpenSSL key type of each curve, as numbered by ext-openssl. The OPENSSL_KEYTYPE_* constants only exist * since PHP 8.4, which is also the first version able to use them. @@ -98,6 +111,16 @@ public static function supportsSodium(string $curve): bool return extension_loaded('sodium') && in_array($curve, [self::CURVE_ED25519, self::CURVE_X25519], true); } + public static function isSmallOrderEd25519Point(string $x): bool + { + if (strlen($x) !== self::KEY_SIZES[self::CURVE_ED25519]) { + return false; + } + $x[31] = chr(ord($x[31]) & 0x7F); + + return in_array(bin2hex($x), self::ED25519_SMALL_ORDER_POINTS, true); + } + /** * Tells whether the given curve can be used on this platform, with either backend. */ @@ -175,6 +198,11 @@ public static function signWithOpenSSL(JWK $privateKey, string $input): string */ public static function verifyWithOpenSSL(JWK $publicKey, #[SensitiveParameter] string $input, string $signature): bool { + $curve = self::getParameter($publicKey, 'crv'); + $x = Base64UrlSafe::decodeNoPadding(self::getParameter($publicKey, 'x')); + if ($curve === self::CURVE_ED25519 && self::isSmallOrderEd25519Point($x)) { + return false; + } $key = openssl_pkey_get_public(self::convertPublicKeyToPEM($publicKey)); if ($key === false) { throw new InvalidKeyException('Unable to load the public key.'); diff --git a/src/Library/KeyManagement/Analyzer/OKPKeyAnalyzer.php b/src/Library/KeyManagement/Analyzer/OKPKeyAnalyzer.php index 4b0a4306..4d21289d 100644 --- a/src/Library/KeyManagement/Analyzer/OKPKeyAnalyzer.php +++ b/src/Library/KeyManagement/Analyzer/OKPKeyAnalyzer.php @@ -45,28 +45,36 @@ public function analyze(JWK $jwk, MessageBag $bag): void return; } - $this->checkComponentSize($jwk, 'x', OKPKey::KEY_SIZES[$crv], $bag); + $x = $this->decodeComponent($jwk, 'x', OKPKey::KEY_SIZES[$crv], $bag); + if ($x !== null && $crv === OKPKey::CURVE_ED25519 && OKPKey::isSmallOrderEd25519Point($x)) { + $bag->add(Message::high('Invalid key. The point of the Ed25519 public key is of small order.')); + } if ($jwk->has('d')) { - $this->checkComponentSize($jwk, 'd', OKPKey::KEY_SIZES[$crv], $bag); + $this->decodeComponent($jwk, 'd', OKPKey::KEY_SIZES[$crv], $bag); } $this->checkAlgorithm($jwk, $crv, $bag); } - private function checkComponentSize(JWK $jwk, string $component, int $size, MessageBag $bag): void + private function decodeComponent(JWK $jwk, string $component, int $size, MessageBag $bag): ?string { $value = $jwk->find($component); if (! is_string($value)) { $bag->add(Message::high(sprintf('Invalid key. The component "%s" shall be a string.', $component))); - return; + return null; } - if (strlen(Base64UrlSafe::decodeNoPadding($value)) !== $size) { + $value = Base64UrlSafe::decodeNoPadding($value); + if (strlen($value) !== $size) { $bag->add(Message::high(sprintf( 'Invalid key. The component "%s" size shall be %d bytes.', $component, $size ))); + + return null; } + + return $value; } private function checkAlgorithm(JWK $jwk, string $crv, MessageBag $bag): void diff --git a/tests/Component/Core/Util/OKPKeyTest.php b/tests/Component/Core/Util/OKPKeyTest.php index 51438503..bbe716d0 100644 --- a/tests/Component/Core/Util/OKPKeyTest.php +++ b/tests/Component/Core/Util/OKPKeyTest.php @@ -116,6 +116,53 @@ public function ed25519SignedWithOpenSSLMatchesTheRfc8037Vector(): void static::assertFalse(OKPKey::verifyWithOpenSSL($key->toPublic(), $input, substr($signature, 0, 63))); } + /** + * @return iterable + */ + public static function ed25519PointsOfSmallOrder(): iterable + { + yield 'y = 0, order 4' => ['0000000000000000000000000000000000000000000000000000000000000000']; + yield 'y = 1, order 1' => ['0100000000000000000000000000000000000000000000000000000000000000']; + yield 'order 8' => ['26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05']; + yield 'order 8, other y' => ['c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a']; + yield 'y = p - 1, order 2' => ['ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f']; + yield 'y = p, order 4' => ['edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f']; + yield 'y = p + 1, order 1' => ['eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f']; + yield 'order 8, sign bit set' => ['26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85']; + yield 'y = 1, sign bit set' => ['0100000000000000000000000000000000000000000000000000000000000080']; + } + + #[Test] + #[DataProvider('ed25519PointsOfSmallOrder')] + public function anEd25519PointOfSmallOrderIsRecognized(string $x): void + { + static::assertTrue(OKPKey::isSmallOrderEd25519Point(hex2bin($x))); + } + + #[Test] + public function theRfc8037Ed25519PublicKeyIsNotOfSmallOrder(): void + { + $x = Base64UrlSafe::decodeNoPadding(self::rfc8037Key()->getString('x')); + + static::assertFalse(OKPKey::isSmallOrderEd25519Point($x)); + static::assertFalse(OKPKey::isSmallOrderEd25519Point("\x01" . str_repeat("\0", 30))); + } + + #[Test] + public function aSignatureWithAnEd25519KeyOfSmallOrderIsNotVerifiedWithOpenSSL(): void + { + $this->requireOpenSSL(); + $neutralPoint = "\x01" . str_repeat("\0", 31); + $key = new JWK([ + 'kty' => 'OKP', + 'crv' => 'Ed25519', + 'x' => Base64UrlSafe::encodeUnpadded($neutralPoint), + ]); + $signature = $neutralPoint . str_repeat("\0", 32); + + static::assertFalse(OKPKey::verifyWithOpenSSL($key, 'any input', $signature)); + } + #[Test] public function ed25519SignaturesMadeWithOpenSSLAndSodiumAreInterchangeable(): void { diff --git a/tests/Component/KeyManagement/OKPKeyAnalyzerTest.php b/tests/Component/KeyManagement/OKPKeyAnalyzerTest.php index 9847ae10..d0da4c4b 100644 --- a/tests/Component/KeyManagement/OKPKeyAnalyzerTest.php +++ b/tests/Component/KeyManagement/OKPKeyAnalyzerTest.php @@ -15,6 +15,7 @@ use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use function sprintf; +use function str_repeat; /** * @internal @@ -109,6 +110,32 @@ public function aNonStringComponentIsReported(): void ); } + /** + * @return iterable + */ + public static function ed25519PointsOfSmallOrder(): iterable + { + yield 'neutral point, order 1' => ["\x01" . str_repeat("\0", 31)]; + yield 'y = 0, order 4' => [str_repeat("\0", 32)]; + yield 'y = -1, order 2' => ["\xec" . str_repeat("\xff", 30) . "\x7f"]; + } + + #[Test] + #[DataProvider('ed25519PointsOfSmallOrder')] + public function anEd25519KeyOfSmallOrderIsReported(string $x): void + { + $key = new JWK([ + 'kty' => 'OKP', + 'crv' => 'Ed25519', + 'x' => Base64UrlSafe::encodeUnpadded($x), + ]); + + static::assertSame( + ['high: Invalid key. The point of the Ed25519 public key is of small order.'], + self::analyze(new OKPKeyAnalyzer(), $key) + ); + } + /** * @return iterable}> */ diff --git a/tests/SignatureAlgorithm/EdDSA/FullySpecifiedEdDSATest.php b/tests/SignatureAlgorithm/EdDSA/FullySpecifiedEdDSATest.php index eb0c7a2f..ff68416e 100644 --- a/tests/SignatureAlgorithm/EdDSA/FullySpecifiedEdDSATest.php +++ b/tests/SignatureAlgorithm/EdDSA/FullySpecifiedEdDSATest.php @@ -167,6 +167,21 @@ public function aTruncatedOrTamperedEd25519SignatureIsFalse(): void static::assertFalse($algorithm->verify($key, 'payload', $tampered)); } + #[Test] + #[DataProvider('ed25519Algorithms')] + public function aSignatureWithAnEd25519KeyOfSmallOrderIsFalse(SignatureAlgorithm $algorithm): void + { + $neutralPoint = "\x01" . str_repeat("\0", 31); + $key = new JWK([ + 'kty' => 'OKP', + 'crv' => 'Ed25519', + 'x' => Base64UrlSafe::encodeUnpadded($neutralPoint), + ]); + $signature = $neutralPoint . str_repeat("\0", 32); + + static::assertFalse($algorithm->verify($key, 'payload', $signature)); + } + #[Test] public function ed25519RefusesAnEd448Key(): void { From bd58fa8cd5b5ccaaf08a36743db3d448446476b8 Mon Sep 17 00:00:00 2001 From: lav45 Date: Tue, 10 Nov 2026 19:51:48 +0300 Subject: [PATCH 2/2] fix(key-mgmt): report an Ed25519 key whose "x" is no valid public key OKPKeyAnalyzer only checked the size of "x" and the points of small order, so an Ed25519 key whose "x" decodes to no point of the curve raised no message, while every signature verification with it fails. OKPKey::isValidEd25519PublicKey() uses sodium when it is loaded: sodium_crypto_sign_ed25519_pk_to_curve25519() also requires the point to be in the prime-order subgroup. Without sodium, OKPKey::isEd25519Point() decodes "x" as RFC 8032 section 5.1.3 does, with brick/math: y lower than p and (y^2 - 1) / (d y^2 + 1) a square modulo p. A point outside the prime-order subgroup is then only reported with sodium. The tests build the "x" of a well-formed Ed25519 key from the RFC 8037 key, as random bytes are a point of the curve only half of the time. --- src/Library/Core/Util/OKPKey.php | 50 +++++++++++++++++++ .../KeyManagement/Analyzer/OKPKeyAnalyzer.php | 16 +++++- tests/Component/Core/Util/OKPKeyTest.php | 50 +++++++++++++++++++ .../KeyManagement/OKPKeyAnalyzerTest.php | 39 ++++++++++++++- 4 files changed, 152 insertions(+), 3 deletions(-) diff --git a/src/Library/Core/Util/OKPKey.php b/src/Library/Core/Util/OKPKey.php index 9a02d78f..26268da5 100644 --- a/src/Library/Core/Util/OKPKey.php +++ b/src/Library/Core/Util/OKPKey.php @@ -4,12 +4,14 @@ namespace Jose\Component\Core\Util; +use Brick\Math\BigInteger; use Jose\Component\Core\Exception\InvalidKeyException; use Jose\Component\Core\Exception\MissingDependencyException; use Jose\Component\Core\Exception\RuntimeException; use Jose\Component\Core\Exception\UnsupportedCurveException; use Jose\Component\Core\JWK; use SensitiveParameter; +use SodiumException; use SpomkyLabs\Pki\CryptoTypes\Asymmetric\PrivateKey; use SpomkyLabs\Pki\CryptoTypes\Asymmetric\PrivateKeyInfo; use SpomkyLabs\Pki\CryptoTypes\Asymmetric\PublicKey; @@ -30,6 +32,7 @@ use function ord; use function sprintf; use function strlen; +use function strrev; use const PHP_VERSION_ID; /** @@ -74,6 +77,10 @@ 'eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f', // y = p + 1, order 1 ]; + private const ED25519_PRIME = '57896044618658097711785492504343953926634992332820282019728792003956564819949'; // 2^255 - 19 + + private const ED25519_D = '37095705934669439343138083508754565189542113879843219016388785533085940283555'; // -121665 / 121666 + /** * The OpenSSL key type of each curve, as numbered by ext-openssl. The OPENSSL_KEYTYPE_* constants only exist * since PHP 8.4, which is also the first version able to use them. @@ -121,6 +128,49 @@ public static function isSmallOrderEd25519Point(string $x): bool return in_array(bin2hex($x), self::ED25519_SMALL_ORDER_POINTS, true); } + public static function isEd25519Point(string $x): bool + { + if (strlen($x) !== self::KEY_SIZES[self::CURVE_ED25519]) { + return false; + } + $isXOdd = (ord($x[31]) & 0x80) !== 0; + $x[31] = chr(ord($x[31]) & 0x7F); + $p = BigInteger::of(self::ED25519_PRIME); + $y = BigInteger::fromBase(bin2hex(strrev($x)), 16); + if ($y->isGreaterThanOrEqualTo($p)) { + return false; + } + $ySquare = $y->power(2) + ->mod($p); + $u = $ySquare->minus(1) + ->mod($p); + $v = BigInteger::of(self::ED25519_D)->multipliedBy($ySquare) + ->plus(1) + ->mod($p); + $xSquare = $u->multipliedBy($v->modPow($p->minus(2), $p)) + ->mod($p); + if ($xSquare->isZero()) { + return ! $isXOdd; + } + + return $xSquare->modPow($p->minus(1)->dividedBy(2), $p) + ->isEqualTo(1); + } + + public static function isValidEd25519PublicKey(string $x): bool + { + if (! self::supportsSodium(self::CURVE_ED25519)) { + return self::isEd25519Point($x) && ! self::isSmallOrderEd25519Point($x); + } + try { + sodium_crypto_sign_ed25519_pk_to_curve25519($x); + } catch (SodiumException) { + return false; + } + + return true; + } + /** * Tells whether the given curve can be used on this platform, with either backend. */ diff --git a/src/Library/KeyManagement/Analyzer/OKPKeyAnalyzer.php b/src/Library/KeyManagement/Analyzer/OKPKeyAnalyzer.php index 4d21289d..1693ad2a 100644 --- a/src/Library/KeyManagement/Analyzer/OKPKeyAnalyzer.php +++ b/src/Library/KeyManagement/Analyzer/OKPKeyAnalyzer.php @@ -46,8 +46,8 @@ public function analyze(JWK $jwk, MessageBag $bag): void return; } $x = $this->decodeComponent($jwk, 'x', OKPKey::KEY_SIZES[$crv], $bag); - if ($x !== null && $crv === OKPKey::CURVE_ED25519 && OKPKey::isSmallOrderEd25519Point($x)) { - $bag->add(Message::high('Invalid key. The point of the Ed25519 public key is of small order.')); + if ($x !== null && $crv === OKPKey::CURVE_ED25519) { + $this->checkEd25519Point($x, $bag); } if ($jwk->has('d')) { $this->decodeComponent($jwk, 'd', OKPKey::KEY_SIZES[$crv], $bag); @@ -77,6 +77,18 @@ private function decodeComponent(JWK $jwk, string $component, int $size, Message return $value; } + private function checkEd25519Point(string $x, MessageBag $bag): void + { + if (OKPKey::isSmallOrderEd25519Point($x)) { + $bag->add(Message::high('Invalid key. The point of the Ed25519 public key is of small order.')); + + return; + } + if (! OKPKey::isValidEd25519PublicKey($x)) { + $bag->add(Message::high('Invalid key. The point is not a valid Ed25519 public key.')); + } + } + private function checkAlgorithm(JWK $jwk, string $crv, MessageBag $bag): void { $alg = $jwk->find('alg'); diff --git a/tests/Component/Core/Util/OKPKeyTest.php b/tests/Component/Core/Util/OKPKeyTest.php index bbe716d0..ff1b0829 100644 --- a/tests/Component/Core/Util/OKPKeyTest.php +++ b/tests/Component/Core/Util/OKPKeyTest.php @@ -148,6 +148,56 @@ public function theRfc8037Ed25519PublicKeyIsNotOfSmallOrder(): void static::assertFalse(OKPKey::isSmallOrderEd25519Point("\x01" . str_repeat("\0", 30))); } + #[Test] + public function theRfc8037Ed25519PublicKeyIsAPoint(): void + { + $x = Base64UrlSafe::decodeNoPadding(self::rfc8037Key()->getString('x')); + + static::assertTrue(OKPKey::isEd25519Point($x)); + } + + /** + * @return iterable + */ + public static function ed25519Encodings(): iterable + { + yield 'y = 1, x = 0' => ['0100000000000000000000000000000000000000000000000000000000000000', true]; + yield 'y = 0' => ['0000000000000000000000000000000000000000000000000000000000000000', true]; + yield 'y = p - 1, x = 0' => ['ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f', true]; + yield 'order 8, sign bit set' => ['26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85', true]; + yield 'y = 2' => ['0200000000000000000000000000000000000000000000000000000000000000', false]; + yield 'y = p' => ['edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f', false]; + yield 'y = 1, x = 0 with the sign bit set' => [ + '0100000000000000000000000000000000000000000000000000000000000080', + false, + ]; + yield 'too short' => ['01000000000000000000000000000000000000000000000000000000000000', false]; + } + + #[Test] + #[DataProvider('ed25519Encodings')] + public function anEd25519EncodingIsAPointOnlyWhenItDecodes(string $x, bool $expected): void + { + static::assertSame($expected, OKPKey::isEd25519Point(hex2bin($x))); + } + + #[Test] + public function anEd25519PublicKeyIsValidWhenItIsAPointNotOfSmallOrder(): void + { + $rfc8037 = Base64UrlSafe::decodeNoPadding(self::rfc8037Key()->getString('x')); + $mixedOrder = hex2bin('9c94cb2663e2140be35aafbbcc90981dc72785ea5e9046d19a3e770c3b8fba79'); + + static::assertTrue(OKPKey::isEd25519Point($mixedOrder)); + static::assertTrue(OKPKey::isValidEd25519PublicKey($rfc8037)); + static::assertFalse(OKPKey::isValidEd25519PublicKey("\x01" . str_repeat("\0", 31))); + static::assertFalse(OKPKey::isValidEd25519PublicKey("\x02" . str_repeat("\0", 31))); + static::assertFalse(OKPKey::isValidEd25519PublicKey("\x01" . str_repeat("\0", 30))); + static::assertSame( + ! OKPKey::supportsSodium(OKPKey::CURVE_ED25519), + OKPKey::isValidEd25519PublicKey($mixedOrder) + ); + } + #[Test] public function aSignatureWithAnEd25519KeyOfSmallOrderIsNotVerifiedWithOpenSSL(): void { diff --git a/tests/Component/KeyManagement/OKPKeyAnalyzerTest.php b/tests/Component/KeyManagement/OKPKeyAnalyzerTest.php index d0da4c4b..b61389cd 100644 --- a/tests/Component/KeyManagement/OKPKeyAnalyzerTest.php +++ b/tests/Component/KeyManagement/OKPKeyAnalyzerTest.php @@ -136,6 +136,38 @@ public function anEd25519KeyOfSmallOrderIsReported(string $x): void ); } + #[Test] + public function anEd25519KeyThatIsNoPointIsReported(): void + { + $key = new JWK([ + 'kty' => 'OKP', + 'crv' => 'Ed25519', + 'x' => Base64UrlSafe::encodeUnpadded("\x02" . str_repeat("\0", 31)), + ]); + + static::assertSame( + ['high: Invalid key. The point is not a valid Ed25519 public key.'], + self::analyze(new OKPKeyAnalyzer(), $key) + ); + } + + #[Test] + public function anEd25519KeyOutsideThePrimeOrderSubgroupIsReportedWithSodiumOnly(): void + { + $key = new JWK([ + 'kty' => 'OKP', + 'crv' => 'Ed25519', + 'x' => Base64UrlSafe::encodeUnpadded( + hex2bin('9c94cb2663e2140be35aafbbcc90981dc72785ea5e9046d19a3e770c3b8fba79') + ), + ]); + $expected = OKPKey::supportsSodium(OKPKey::CURVE_ED25519) + ? ['high: Invalid key. The point is not a valid Ed25519 public key.'] + : []; + + static::assertSame($expected, self::analyze(new OKPKeyAnalyzer(), $key)); + } + /** * @return iterable}> */ @@ -233,10 +265,15 @@ private static function analyze(KeyAnalyzer $analyzer, JWK $key): array private static function key(string $curve, int $xSize, int $dSize): JWK { + $x = Base64UrlSafe::encodeUnpadded(random_bytes($xSize)); + if ($curve === OKPKey::CURVE_ED25519 && $xSize === OKPKey::KEY_SIZES[$curve]) { + $x = '11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo'; // RFC 8037 appendix A.1 + } + return new JWK([ 'kty' => 'OKP', 'crv' => $curve, - 'x' => Base64UrlSafe::encodeUnpadded(random_bytes($xSize)), + 'x' => $x, 'd' => Base64UrlSafe::encodeUnpadded(random_bytes($dSize)), ]); }