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
18 changes: 18 additions & 0 deletions .ci-tools/phpstan-baseline.neon
Original file line number Diff line number Diff line change
Expand Up @@ -5154,6 +5154,12 @@ parameters:
count: 1
path: ../src/Library/Encryption/Serializer/JSONFlattenedSerializer.php

-
rawMessage: 'Only booleans are allowed in a ternary operator condition, mixed given.'
identifier: ternary.condNotBoolean
count: 1
path: ../src/Library/Encryption/Serializer/JSONFlattenedSerializer.php

-
rawMessage: 'Parameter #1 $encodedString of static method Jose\Component\Core\Util\Base64UrlSafe::decodeNoPadding() expects string, mixed given.'
identifier: argument.type
Expand Down Expand Up @@ -5220,6 +5226,12 @@ parameters:
count: 1
path: ../src/Library/Encryption/Serializer/JSONGeneralSerializer.php

-
rawMessage: 'Only booleans are allowed in a ternary operator condition, mixed given.'
identifier: ternary.condNotBoolean
count: 1
path: ../src/Library/Encryption/Serializer/JSONGeneralSerializer.php

-
rawMessage: 'Parameter #1 $encodedString of static method Jose\Component\Core\Util\Base64UrlSafe::decodeNoPadding() expects string, mixed given.'
identifier: argument.type
Expand Down Expand Up @@ -5298,6 +5310,12 @@ parameters:
count: 1
path: ../src/Library/KeyManagement/Analyzer/MixedPublicAndPrivateKeys.php

-
rawMessage: 'Only booleans are allowed in an if condition, mixed given.'
identifier: if.condNotBoolean
count: 1
path: ../src/Library/KeyManagement/Analyzer/MixedPublicAndPrivateKeys.php

-
rawMessage: 'Parameter #2 ...$values of function sprintf expects bool|float|int|string|null, mixed given.'
identifier: argument.type
Expand Down
12 changes: 5 additions & 7 deletions src/Library/Core/Util/RSAKey.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
use function array_key_exists;
use function count;
use function ltrim;
use function min;
use function ord;
use function sprintf;
use function strlen;
Expand All @@ -28,14 +29,12 @@
final class RSAKey
{
/**
* The limits of OpenSSL, in bytes: a modulus of 16384 bits at most, and a public exponent no longer than the
* modulus and of 64 bits at most above 3072 bits. RSA-PSS and RSAES compute the public operation in PHP, at a cost
* set by these lengths.
* In bytes: a modulus of 16384 bits at most, the limit of OpenSSL, and a public exponent no longer than the modulus
* and of 64 bits at most whatever the modulus, a limit OpenSSL applies above 3072 bits only. RSA-PSS and RSAES
* compute the public operation in PHP, at a cost set by these lengths.
*/
private const MAX_MODULUS_LENGTH = 2048;

private const SMALL_MODULUS_LENGTH = 384;

private const MAX_PUBLIC_EXPONENT_LENGTH = 8;

private null|Sequence $sequence = null;
Expand Down Expand Up @@ -71,8 +70,7 @@ private function __construct(JWK $data)
if ($modulusLength > self::MAX_MODULUS_LENGTH) {
throw new InvalidArgumentException('The key parameter "n" is too long.');
}
$limit = $modulusLength > self::SMALL_MODULUS_LENGTH ? self::MAX_PUBLIC_EXPONENT_LENGTH : $modulusLength;
if ($this->getMemberLength('e') > $limit) {
if ($this->getMemberLength('e') > min($modulusLength, self::MAX_PUBLIC_EXPONENT_LENGTH)) {
throw new InvalidArgumentException('The key parameter "e" is too long.');
}
$this->modulusLength = $modulusLength;
Expand Down
15 changes: 14 additions & 1 deletion src/Library/KeyManagement/Analyzer/ESKeyAnalyzer.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@

abstract readonly class ESKeyAnalyzer implements KeyAnalyzer
{
/**
* Coordinates of the wrong size are reported and not converted into integers: the analyzed keys may come from a
* third party, and converting coordinates of any length costs seconds without GMP.
*/
#[Override]
public function analyze(JWK $jwk, MessageBag $bag): void
{
Expand Down Expand Up @@ -57,10 +61,19 @@ public function analyze(JWK $jwk, MessageBag $bag): void
$this->getKeySize()
))
);

return;
}
$xBI = BigInteger::fromBase(bin2hex($x), 16);
$yBI = BigInteger::fromBase(bin2hex($y), 16);
if (! $this->getCurve()->contains($xBI, $yBI)) {
$curve = $this->getCurve();
$prime = $curve->getPrime();
if ($xBI->isGreaterThanOrEqualTo($prime) || $yBI->isGreaterThanOrEqualTo($prime)) {
$bag->add(Message::high('Invalid key. The components "x" and "y" shall be lower than the field prime.'));

return;
}
if (! $curve->contains($xBI, $yBI)) {
$bag->add(Message::high('Invalid key. The point is not on the curve.'));
}
}
Expand Down
43 changes: 34 additions & 9 deletions src/Library/KeyManagement/Analyzer/RsaAnalyzer.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,12 @@

namespace Jose\Component\KeyManagement\Analyzer;

use InvalidArgumentException;
use Jose\Component\Core\JWK;
use Jose\Component\Core\Util\Base64UrlSafe;
use Override;
use function is_array;
use function is_string;
use function ord;
use function strlen;
use const STR_PAD_RIGHT;

final readonly class RsaAnalyzer implements KeyAnalyzer
{
Expand All @@ -26,6 +24,10 @@ public function analyze(JWK $jwk, MessageBag $bag): void
$this->checkModulus($jwk, $bag);
}

/**
* The exponent is compared on its octets, without its leading zero octets: a value longer than three octets is at
* least 2^24, so only a value of three octets or less is converted into an integer.
*/
private function checkExponent(JWK $jwk, MessageBag $bag): void
{
$e = $jwk->get('e');
Expand All @@ -34,11 +36,14 @@ private function checkExponent(JWK $jwk, MessageBag $bag): void

return;
}
$exponent = unpack('l', str_pad(Base64UrlSafe::decodeNoPadding($e), 4, "\0", STR_PAD_RIGHT));
if (! is_array($exponent) || ! isset($exponent[1])) {
throw new InvalidArgumentException('Unable to get the private key');
$e = Base64UrlSafe::decodeNoPadding($e);
if ($e === '') {
$bag->add(Message::high('The exponent is not valid.'));

return;
}
if ($exponent[1] < 65537) {
$e = ltrim($e, "\0");
if (strlen($e) <= 3 && hexdec(bin2hex($e)) < 65537) {
$bag->add(Message::high('The exponent is too low. It should be at least 65537.'));
}
}
Expand All @@ -51,8 +56,13 @@ private function checkModulus(JWK $jwk, MessageBag $bag): void

return;
}
$n = 8 * strlen(Base64UrlSafe::decodeNoPadding($n));
if ($n < 2048) {
$n = Base64UrlSafe::decodeNoPadding($n);
if ($n === '') {
$bag->add(Message::high('The modulus is not valid.'));

return;
}
if (self::getBitLength($n) < 2048) {
$bag->add(Message::high('The key length is less than 2048 bits.'));
}
if ($jwk->has('d') && (! $jwk->has('p') || ! $jwk->has('q') || ! $jwk->has('dp') || ! $jwk->has(
Expand All @@ -65,4 +75,19 @@ private function checkModulus(JWK $jwk, MessageBag $bag): void
);
}
}

/**
* Returns the bit length of a Base64urlUInt value (RFC 7518, section 2) from its octets, leading zero octets
* ignored. The analyzed keys may come from a third party with a modulus of any length: converting it into a big
* integer costs seconds to minutes without GMP, while this costs nothing.
*/
private static function getBitLength(string $value): int
{
$value = ltrim($value, "\0");
if ($value === '') {
return 0;
}

return 8 * (strlen($value) - 1) + strlen(decbin(ord($value[0])));
}
}
15 changes: 9 additions & 6 deletions tests/Component/Core/Util/RSAKeyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,17 +32,18 @@ protected function tearDown(): void
}

#[Test]
public function theLimitsOfOpenSSLAreAccepted(): void
public function theLargestKeysAreAccepted(): void
{
static::assertSame(2048, RSAKey::createFromJWK(self::key(2048, 8))->getModulusLength());
static::assertSame(385, RSAKey::createFromJWK(self::key(385, 8))->getModulusLength());
static::assertSame(384, RSAKey::createFromJWK(self::key(384, 384))->getModulusLength());
static::assertSame(256, RSAKey::createFromJWK(self::key(256, 9))->getModulusLength());
static::assertSame(384, RSAKey::createFromJWK(self::key(384, 8))->getModulusLength());
static::assertSame(256, RSAKey::createFromJWK(self::key(256, 8))->getModulusLength());
static::assertSame(4, RSAKey::createFromJWK(self::key(4, 4))->getModulusLength());
}

#[Test]
#[DataProvider('oversizedKeys')]
public function aKeyBeyondTheLimitsOfOpenSSLIsRejected(
public function aKeyBeyondTheLimitsIsRejected(
int $modulusLength,
int $exponentLength,
string $member
Expand All @@ -61,8 +62,10 @@ public static function oversizedKeys(): iterable
yield 'modulus of 16392 bits' => [2049, 3, 'n'];
yield 'exponent of 72 bits, modulus of 16384 bits' => [2048, 9, 'e'];
yield 'exponent of 72 bits, modulus of 3080 bits' => [385, 9, 'e'];
yield 'exponent longer than a modulus of 3072 bits' => [384, 385, 'e'];
yield 'exponent longer than a modulus of 2048 bits' => [256, 257, 'e'];
yield 'exponent of 72 bits, modulus of 3072 bits' => [384, 9, 'e'];
yield 'exponent of 72 bits, modulus of 2048 bits' => [256, 9, 'e'];
yield 'exponent as long as a modulus of 3072 bits' => [384, 384, 'e'];
yield 'exponent longer than a modulus of 32 bits' => [4, 5, 'e'];
}

#[Test]
Expand Down
131 changes: 131 additions & 0 deletions tests/Component/KeyManagement/JWKAnalyzerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@

namespace Jose\Tests\Component\KeyManagement;

use Brick\Math\BigInteger;
use Jose\Component\Core\JWK;
use Jose\Component\Core\Util\Base64UrlSafe;
use Jose\Component\Core\Util\Ecc\NistCurve;
use Jose\Component\KeyManagement\Analyzer\AlgorithmAnalyzer;
use Jose\Component\KeyManagement\Analyzer\ES256KeyAnalyzer;
use Jose\Component\KeyManagement\Analyzer\ES384KeyAnalyzer;
Expand All @@ -14,15 +17,19 @@
use Jose\Component\KeyManagement\Analyzer\HS512KeyAnalyzer;
use Jose\Component\KeyManagement\Analyzer\KeyAnalyzerManager;
use Jose\Component\KeyManagement\Analyzer\KeyIdentifierAnalyzer;
use Jose\Component\KeyManagement\Analyzer\Message;
use Jose\Component\KeyManagement\Analyzer\NoneAnalyzer;
use Jose\Component\KeyManagement\Analyzer\OctAnalyzer;
use Jose\Component\KeyManagement\Analyzer\RsaAnalyzer;
use Jose\Component\KeyManagement\Analyzer\UsageAnalyzer;
use Jose\Component\KeyManagement\Analyzer\ZxcvbnKeyAnalyzer;
use Jose\Component\KeyManagement\JWKFactory;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\DoesNotPerformAssertions;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
use function in_array;
use const STR_PAD_LEFT;

/**
* @internal
Expand Down Expand Up @@ -74,6 +81,130 @@ public function theRsaKeyHasALowExponent(): void
static::fail('The low exponent should be catched');
}

#[Test]
public function theRsaKeyWithLeadingZeroOctetsIsAnalyzedByItsValue(): void
{
$key = new JWK([
'kty' => 'RSA',
'n' => Base64UrlSafe::encodeUnpadded(str_repeat("\0", 255) . "\x0f"),
'e' => Base64UrlSafe::encodeUnpadded("\0\0\0\1"),
]);
$messages = $this->getKeyAnalyzer()
->analyze($key);

$texts = array_map(static fn (Message $message): string => $message->getMessage(), $messages->all());
static::assertContains('The key length is less than 2048 bits.', $texts);
static::assertContains('The exponent is too low. It should be at least 65537.', $texts);
}

#[Test]
public function theEcKeyWithACoordinateAboveTheFieldPrimeIsRejected(): void
{
$key = JWKFactory::createECKey('P-521');
$prime = NistCurve::curve521()->getPrime();
$y = BigInteger::fromBase(bin2hex(Base64UrlSafe::decodeNoPadding($key->get('y'))), 16)->plus($prime);
$y = str_pad(hex2bin(str_pad($y->toBase(16), 132, '0', STR_PAD_LEFT)), 66, "\0", STR_PAD_LEFT);
$key = new JWK([
'kty' => 'EC',
'crv' => 'P-521',
'x' => $key->get('x'),
'y' => Base64UrlSafe::encodeUnpadded($y),
]);
$messages = $this->getKeyAnalyzer()
->analyze($key);

$texts = array_map(static fn (Message $message): string => $message->getMessage(), $messages->all());
static::assertContains(
'Invalid key. The components "x" and "y" shall be lower than the field prime.',
$texts
);
}

#[Test]
public function theEcKeyWithCoordinatesOfTheWrongSizeIsNotAnalyzedFurther(): void
{
$key = new JWK([
'kty' => 'EC',
'crv' => 'P-256',
'x' => Base64UrlSafe::encodeUnpadded(str_repeat("\xff", 33)),
'y' => Base64UrlSafe::encodeUnpadded(str_repeat("\xff", 33)),
]);
$messages = $this->getKeyAnalyzer()
->analyze($key);

$texts = array_map(static fn (Message $message): string => $message->getMessage(), $messages->all());
static::assertContains('Invalid key. The components "x" and "y" size shall be 256 bits.', $texts);
static::assertNotContains(
'Invalid key. The components "x" and "y" shall be lower than the field prime.',
$texts
);
static::assertNotContains('Invalid key. The point is not on the curve.', $texts);
}

#[Test]
#[DataProvider('rsaModuli')]
public function theRsaKeyLengthIsTheBitLengthOfTheModulus(string $n, bool $tooShort): void
{
$key = new JWK([
'kty' => 'RSA',
'n' => Base64UrlSafe::encodeUnpadded($n),
'e' => 'AQAB',
]);
$messages = $this->getKeyAnalyzer()
->analyze($key);

$texts = array_map(static fn (Message $message): string => $message->getMessage(), $messages->all());
static::assertSame($tooShort, in_array('The key length is less than 2048 bits.', $texts, true));
}

/**
* @return iterable<string, array{string, bool}>
*/
public static function rsaModuli(): iterable
{
yield '2048 bits' => ["\x80" . str_repeat("\xff", 255), false];
yield '2048 bits with a leading zero octet' => ["\0\x80" . str_repeat("\xff", 255), false];
yield '2049 bits' => ["\x01" . str_repeat("\xff", 256), false];
yield '2047 bits on 256 octets' => ["\x7f" . str_repeat("\xff", 255), true];
yield '2041 bits on 256 octets' => ["\x01" . str_repeat("\xff", 255), true];
yield '2040 bits' => [str_repeat("\xff", 255), true];
}

#[Test]
#[DataProvider('rsaExponents')]
public function theRsaExponentIsComparedByItsValue(string $e, bool $tooLow): void
{
$key = new JWK([
'kty' => 'RSA',
'n' => Base64UrlSafe::encodeUnpadded("\x80" . str_repeat("\xff", 255)),
'e' => Base64UrlSafe::encodeUnpadded($e),
]);
$messages = $this->getKeyAnalyzer()
->analyze($key);

$texts = array_map(static fn (Message $message): string => $message->getMessage(), $messages->all());
static::assertSame(
$tooLow,
in_array('The exponent is too low. It should be at least 65537.', $texts, true)
);
}

/**
* @return iterable<string, array{string, bool}>
*/
public static function rsaExponents(): iterable
{
yield '65537' => ["\x01\x00\x01", false];
yield '65537 with leading zero octets' => ["\0\0\x01\x00\x01", false];
yield '65536' => ["\x01\x00\x00", true];
yield '3' => ["\x03", true];
yield 'zero' => ["\0", true];
yield '2^24 - 1' => ["\xff\xff\xff", false];
yield '2^24' => ["\x01\x00\x00\x00", false];
yield '2^32 + 1' => ["\x01\x00\x00\x00\x01", false];
yield '2^32 - 1' => ["\xff\xff\xff\xff", false];
}

#[Test]
public function iCanAnalyzeAnOctKeyAndGetMessages(): void
{
Expand Down
Loading