Skip to content

Commit ec013c9

Browse files
committed
Allow users to lock their app into an algorithm.
1 parent 724b1fc commit ec013c9

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

Authentication/JWT.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@
1515
*/
1616
class JWT
1717
{
18+
public static $only_method = 'HS256';
19+
1820
public static $methods = array(
1921
'HS256' => array('hash_hmac', 'SHA256'),
2022
'HS512' => array('hash_hmac', 'SHA512'),
@@ -173,6 +175,11 @@ public static function verify($msg, $signature, $key, $method = 'HS256')
173175
if (empty(self::$methods[$method])) {
174176
throw new DomainException('Algorithm not supported');
175177
}
178+
if (self::$only_method === null) {
179+
throw new DomainException('Algorithm not specified');
180+
} elseif ($method !== self::$only_method) {
181+
throw new DomainException('Incorrect algorithm error');
182+
}
176183
list($function, $algo) = self::$methods[$method];
177184
switch($function) {
178185
case 'openssl':
@@ -299,4 +306,22 @@ private static function handleJsonError($errno)
299306
: 'Unknown JSON error: ' . $errno
300307
);
301308
}
309+
310+
/**
311+
* Set the only allowed method for this server.
312+
*
313+
* @ref https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/
314+
*
315+
* @param string $method array index in self::$methods
316+
*
317+
* @return boolean
318+
*/
319+
public static function setOnlyAllowedMethod($method)
320+
{
321+
if (!empty(self::$methods[$method])) {
322+
self::$only_method = $method;
323+
return true;
324+
}
325+
return false;
326+
}
302327
}

tests/JWTTest.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,7 @@ public function testRSEncodeDecode()
102102
$privKey = openssl_pkey_new(array('digest_alg' => 'sha256',
103103
'private_key_bits' => 1024,
104104
'private_key_type' => OPENSSL_KEYTYPE_RSA));
105+
JWT::setOnlyAllowedMethod('RS256');
105106
$msg = JWT::encode('abc', $privKey, 'RS256');
106107
$pubKey = openssl_pkey_get_details($privKey);
107108
$pubKey = $pubKey['key'];
@@ -112,6 +113,7 @@ public function testRSEncodeDecode()
112113
public function testKIDChooser()
113114
{
114115
$keys = array('1' => 'my_key', '2' => 'my_key2');
116+
JWT::setOnlyAllowedMethod('HS256');
115117
$msg = JWT::encode('abc', $keys['1'], 'HS256', '1');
116118
$decoded = JWT::decode($msg, $keys, true);
117119
$this->assertEquals($decoded, 'abc');

0 commit comments

Comments
 (0)