Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 78 additions & 0 deletions src/Library/Core/Util/OKPKey.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -21,12 +23,16 @@
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 function strrev;
use const PHP_VERSION_ID;

/**
Expand Down Expand Up @@ -61,6 +67,20 @@
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
];

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.
Expand Down Expand Up @@ -98,6 +118,59 @@ 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);
}

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.
*/
Expand Down Expand Up @@ -175,6 +248,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.');
Expand Down
30 changes: 25 additions & 5 deletions src/Library/KeyManagement/Analyzer/OKPKeyAnalyzer.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,27 +45,47 @@ 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) {
$this->checkEd25519Point($x, $bag);
}
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 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.'));
}
}

Expand Down
97 changes: 97 additions & 0 deletions tests/Component/Core/Util/OKPKeyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,103 @@ public function ed25519SignedWithOpenSSLMatchesTheRfc8037Vector(): void
static::assertFalse(OKPKey::verifyWithOpenSSL($key->toPublic(), $input, substr($signature, 0, 63)));
}

/**
* @return iterable<string, array{string}>
*/
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 theRfc8037Ed25519PublicKeyIsAPoint(): void
{
$x = Base64UrlSafe::decodeNoPadding(self::rfc8037Key()->getString('x'));

static::assertTrue(OKPKey::isEd25519Point($x));
}

/**
* @return iterable<string, array{string, bool}>
*/
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
{
$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
{
Expand Down
66 changes: 65 additions & 1 deletion tests/Component/KeyManagement/OKPKeyAnalyzerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
use function sprintf;
use function str_repeat;

/**
* @internal
Expand Down Expand Up @@ -109,6 +110,64 @@ public function aNonStringComponentIsReported(): void
);
}

/**
* @return iterable<string, array{string}>
*/
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)
);
}

#[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<string, array{string, string, list<string>}>
*/
Expand Down Expand Up @@ -206,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)),
]);
}
Expand Down
15 changes: 15 additions & 0 deletions tests/SignatureAlgorithm/EdDSA/FullySpecifiedEdDSATest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down