Skip to content

Commit 0893d6f

Browse files
authored
Merge pull request #825 from web-token/fix/key-analyzers-integer-encoding
fix(key-mgmt): analyze RSA n and e and EC coordinates by their integer value
2 parents d321578 + dafe074 commit 0893d6f

3 files changed

Lines changed: 179 additions & 10 deletions

File tree

‎src/Library/KeyManagement/Analyzer/ESKeyAnalyzer.php‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,10 @@
1515

1616
abstract readonly class ESKeyAnalyzer implements KeyAnalyzer
1717
{
18+
/**
19+
* Coordinates of the wrong size are reported and not converted into integers: the analyzed keys may come from a
20+
* third party, and converting coordinates of any length costs seconds without GMP.
21+
*/
1822
#[Override]
1923
public function analyze(JWK $jwk, MessageBag $bag): void
2024
{
@@ -57,10 +61,19 @@ public function analyze(JWK $jwk, MessageBag $bag): void
5761
$this->getKeySize()
5862
))
5963
);
64+
65+
return;
6066
}
6167
$xBI = BigInteger::fromBase(bin2hex($x), 16);
6268
$yBI = BigInteger::fromBase(bin2hex($y), 16);
63-
if (! $this->getCurve()->contains($xBI, $yBI)) {
69+
$curve = $this->getCurve();
70+
$prime = $curve->getPrime();
71+
if ($xBI->isGreaterThanOrEqualTo($prime) || $yBI->isGreaterThanOrEqualTo($prime)) {
72+
$bag->add(Message::high('Invalid key. The components "x" and "y" shall be lower than the field prime.'));
73+
74+
return;
75+
}
76+
if (! $curve->contains($xBI, $yBI)) {
6477
$bag->add(Message::high('Invalid key. The point is not on the curve.'));
6578
}
6679
}

‎src/Library/KeyManagement/Analyzer/RsaAnalyzer.php‎

Lines changed: 34 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,12 @@
44

55
namespace Jose\Component\KeyManagement\Analyzer;
66

7-
use InvalidArgumentException;
87
use Jose\Component\Core\JWK;
98
use Jose\Component\Core\Util\Base64UrlSafe;
109
use Override;
11-
use function is_array;
1210
use function is_string;
11+
use function ord;
1312
use function strlen;
14-
use const STR_PAD_RIGHT;
1513

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

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

3537
return;
3638
}
37-
$exponent = unpack('l', str_pad(Base64UrlSafe::decodeNoPadding($e), 4, "\0", STR_PAD_RIGHT));
38-
if (! is_array($exponent) || ! isset($exponent[1])) {
39-
throw new InvalidArgumentException('Unable to get the private key');
39+
$e = Base64UrlSafe::decodeNoPadding($e);
40+
if ($e === '') {
41+
$bag->add(Message::high('The exponent is not valid.'));
42+
43+
return;
4044
}
41-
if ($exponent[1] < 65537) {
45+
$e = ltrim($e, "\0");
46+
if (strlen($e) <= 3 && hexdec(bin2hex($e)) < 65537) {
4247
$bag->add(Message::high('The exponent is too low. It should be at least 65537.'));
4348
}
4449
}
@@ -51,8 +56,13 @@ private function checkModulus(JWK $jwk, MessageBag $bag): void
5156

5257
return;
5358
}
54-
$n = 8 * strlen(Base64UrlSafe::decodeNoPadding($n));
55-
if ($n < 2048) {
59+
$n = Base64UrlSafe::decodeNoPadding($n);
60+
if ($n === '') {
61+
$bag->add(Message::high('The modulus is not valid.'));
62+
63+
return;
64+
}
65+
if (self::getBitLength($n) < 2048) {
5666
$bag->add(Message::high('The key length is less than 2048 bits.'));
5767
}
5868
if ($jwk->has('d') && (! $jwk->has('p') || ! $jwk->has('q') || ! $jwk->has('dp') || ! $jwk->has(
@@ -65,4 +75,19 @@ private function checkModulus(JWK $jwk, MessageBag $bag): void
6575
);
6676
}
6777
}
78+
79+
/**
80+
* Returns the bit length of a Base64urlUInt value (RFC 7518, section 2) from its octets, leading zero octets
81+
* ignored. The analyzed keys may come from a third party with a modulus of any length: converting it into a big
82+
* integer costs seconds to minutes without GMP, while this costs nothing.
83+
*/
84+
private static function getBitLength(string $value): int
85+
{
86+
$value = ltrim($value, "\0");
87+
if ($value === '') {
88+
return 0;
89+
}
90+
91+
return 8 * (strlen($value) - 1) + strlen(decbin(ord($value[0])));
92+
}
6893
}

‎tests/Component/KeyManagement/JWKAnalyzerTest.php‎

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@
44

55
namespace Jose\Tests\Component\KeyManagement;
66

7+
use Brick\Math\BigInteger;
78
use Jose\Component\Core\JWK;
9+
use Jose\Component\Core\Util\Base64UrlSafe;
10+
use Jose\Component\Core\Util\Ecc\NistCurve;
811
use Jose\Component\KeyManagement\Analyzer\AlgorithmAnalyzer;
912
use Jose\Component\KeyManagement\Analyzer\ES256KeyAnalyzer;
1013
use Jose\Component\KeyManagement\Analyzer\ES384KeyAnalyzer;
@@ -14,15 +17,19 @@
1417
use Jose\Component\KeyManagement\Analyzer\HS512KeyAnalyzer;
1518
use Jose\Component\KeyManagement\Analyzer\KeyAnalyzerManager;
1619
use Jose\Component\KeyManagement\Analyzer\KeyIdentifierAnalyzer;
20+
use Jose\Component\KeyManagement\Analyzer\Message;
1721
use Jose\Component\KeyManagement\Analyzer\NoneAnalyzer;
1822
use Jose\Component\KeyManagement\Analyzer\OctAnalyzer;
1923
use Jose\Component\KeyManagement\Analyzer\RsaAnalyzer;
2024
use Jose\Component\KeyManagement\Analyzer\UsageAnalyzer;
2125
use Jose\Component\KeyManagement\Analyzer\ZxcvbnKeyAnalyzer;
2226
use Jose\Component\KeyManagement\JWKFactory;
27+
use PHPUnit\Framework\Attributes\DataProvider;
2328
use PHPUnit\Framework\Attributes\DoesNotPerformAssertions;
2429
use PHPUnit\Framework\Attributes\Test;
2530
use PHPUnit\Framework\TestCase;
31+
use function in_array;
32+
use const STR_PAD_LEFT;
2633

2734
/**
2835
* @internal
@@ -74,6 +81,130 @@ public function theRsaKeyHasALowExponent(): void
7481
static::fail('The low exponent should be catched');
7582
}
7683

84+
#[Test]
85+
public function theRsaKeyWithLeadingZeroOctetsIsAnalyzedByItsValue(): void
86+
{
87+
$key = new JWK([
88+
'kty' => 'RSA',
89+
'n' => Base64UrlSafe::encodeUnpadded(str_repeat("\0", 255) . "\x0f"),
90+
'e' => Base64UrlSafe::encodeUnpadded("\0\0\0\1"),
91+
]);
92+
$messages = $this->getKeyAnalyzer()
93+
->analyze($key);
94+
95+
$texts = array_map(static fn (Message $message): string => $message->getMessage(), $messages->all());
96+
static::assertContains('The key length is less than 2048 bits.', $texts);
97+
static::assertContains('The exponent is too low. It should be at least 65537.', $texts);
98+
}
99+
100+
#[Test]
101+
public function theEcKeyWithACoordinateAboveTheFieldPrimeIsRejected(): void
102+
{
103+
$key = JWKFactory::createECKey('P-521');
104+
$prime = NistCurve::curve521()->getPrime();
105+
$y = BigInteger::fromBase(bin2hex(Base64UrlSafe::decodeNoPadding($key->get('y'))), 16)->plus($prime);
106+
$y = str_pad(hex2bin(str_pad($y->toBase(16), 132, '0', STR_PAD_LEFT)), 66, "\0", STR_PAD_LEFT);
107+
$key = new JWK([
108+
'kty' => 'EC',
109+
'crv' => 'P-521',
110+
'x' => $key->get('x'),
111+
'y' => Base64UrlSafe::encodeUnpadded($y),
112+
]);
113+
$messages = $this->getKeyAnalyzer()
114+
->analyze($key);
115+
116+
$texts = array_map(static fn (Message $message): string => $message->getMessage(), $messages->all());
117+
static::assertContains(
118+
'Invalid key. The components "x" and "y" shall be lower than the field prime.',
119+
$texts
120+
);
121+
}
122+
123+
#[Test]
124+
public function theEcKeyWithCoordinatesOfTheWrongSizeIsNotAnalyzedFurther(): void
125+
{
126+
$key = new JWK([
127+
'kty' => 'EC',
128+
'crv' => 'P-256',
129+
'x' => Base64UrlSafe::encodeUnpadded(str_repeat("\xff", 33)),
130+
'y' => Base64UrlSafe::encodeUnpadded(str_repeat("\xff", 33)),
131+
]);
132+
$messages = $this->getKeyAnalyzer()
133+
->analyze($key);
134+
135+
$texts = array_map(static fn (Message $message): string => $message->getMessage(), $messages->all());
136+
static::assertContains('Invalid key. The components "x" and "y" size shall be 256 bits.', $texts);
137+
static::assertNotContains(
138+
'Invalid key. The components "x" and "y" shall be lower than the field prime.',
139+
$texts
140+
);
141+
static::assertNotContains('Invalid key. The point is not on the curve.', $texts);
142+
}
143+
144+
#[Test]
145+
#[DataProvider('rsaModuli')]
146+
public function theRsaKeyLengthIsTheBitLengthOfTheModulus(string $n, bool $tooShort): void
147+
{
148+
$key = new JWK([
149+
'kty' => 'RSA',
150+
'n' => Base64UrlSafe::encodeUnpadded($n),
151+
'e' => 'AQAB',
152+
]);
153+
$messages = $this->getKeyAnalyzer()
154+
->analyze($key);
155+
156+
$texts = array_map(static fn (Message $message): string => $message->getMessage(), $messages->all());
157+
static::assertSame($tooShort, in_array('The key length is less than 2048 bits.', $texts, true));
158+
}
159+
160+
/**
161+
* @return iterable<string, array{string, bool}>
162+
*/
163+
public static function rsaModuli(): iterable
164+
{
165+
yield '2048 bits' => ["\x80" . str_repeat("\xff", 255), false];
166+
yield '2048 bits with a leading zero octet' => ["\0\x80" . str_repeat("\xff", 255), false];
167+
yield '2049 bits' => ["\x01" . str_repeat("\xff", 256), false];
168+
yield '2047 bits on 256 octets' => ["\x7f" . str_repeat("\xff", 255), true];
169+
yield '2041 bits on 256 octets' => ["\x01" . str_repeat("\xff", 255), true];
170+
yield '2040 bits' => [str_repeat("\xff", 255), true];
171+
}
172+
173+
#[Test]
174+
#[DataProvider('rsaExponents')]
175+
public function theRsaExponentIsComparedByItsValue(string $e, bool $tooLow): void
176+
{
177+
$key = new JWK([
178+
'kty' => 'RSA',
179+
'n' => Base64UrlSafe::encodeUnpadded("\x80" . str_repeat("\xff", 255)),
180+
'e' => Base64UrlSafe::encodeUnpadded($e),
181+
]);
182+
$messages = $this->getKeyAnalyzer()
183+
->analyze($key);
184+
185+
$texts = array_map(static fn (Message $message): string => $message->getMessage(), $messages->all());
186+
static::assertSame(
187+
$tooLow,
188+
in_array('The exponent is too low. It should be at least 65537.', $texts, true)
189+
);
190+
}
191+
192+
/**
193+
* @return iterable<string, array{string, bool}>
194+
*/
195+
public static function rsaExponents(): iterable
196+
{
197+
yield '65537' => ["\x01\x00\x01", false];
198+
yield '65537 with leading zero octets' => ["\0\0\x01\x00\x01", false];
199+
yield '65536' => ["\x01\x00\x00", true];
200+
yield '3' => ["\x03", true];
201+
yield 'zero' => ["\0", true];
202+
yield '2^24 - 1' => ["\xff\xff\xff", false];
203+
yield '2^24' => ["\x01\x00\x00\x00", false];
204+
yield '2^32 + 1' => ["\x01\x00\x00\x00\x01", false];
205+
yield '2^32 - 1' => ["\xff\xff\xff\xff", false];
206+
}
207+
77208
#[Test]
78209
public function iCanAnalyzeAnOctKeyAndGetMessages(): void
79210
{

0 commit comments

Comments
 (0)