From 31a7c1692907a10dfdb2ea88115ac7164fe53d58 Mon Sep 17 00:00:00 2001 From: Paragon Initiative Enterprises Date: Wed, 4 Aug 2021 05:42:09 -0400 Subject: [PATCH 1/7] Proposed Fix for #351 This aims to provide backwards compatibility by guessing the algorithm for a key based on the key's contents, but it will likely fail in corner cases. If this is merged, users **SHOULD** be explicit about the algorithms they're using. i.e. Instead of $keyAsString, pass in (new JWTKey($keyAsString, 'ES384')) --- src/JWT.php | 75 ++++++++++++++++++++++------ src/Keys/JWTKey.php | 113 +++++++++++++++++++++++++++++++++++++++++++ src/Keys/Keyring.php | 81 +++++++++++++++++++++++++++++++ 3 files changed, 254 insertions(+), 15 deletions(-) create mode 100644 src/Keys/JWTKey.php create mode 100644 src/Keys/Keyring.php diff --git a/src/JWT.php b/src/JWT.php index 99d6dcd2..36abd0bd 100644 --- a/src/JWT.php +++ b/src/JWT.php @@ -2,8 +2,11 @@ namespace Firebase\JWT; +use ArrayAccess; use DomainException; use Exception; +use Firebase\JWT\Keys\JWTKey; +use Firebase\JWT\Keys\Keyring; use InvalidArgumentException; use UnexpectedValueException; use DateTime; @@ -111,7 +114,9 @@ public static function decode($jwt, $key, array $allowed_algs = array()) $sig = self::signatureToDER($sig); } - if (\is_array($key) || $key instanceof \ArrayAccess) { + /** @var Keyring|JWTKey $key */ + $key = self::getKeyType($key, $allowed_algs); + if ($key instanceof Keyring) { if (isset($header->kid)) { if (!isset($key[$header->kid])) { throw new UnexpectedValueException('"kid" invalid, unable to lookup correct key'); @@ -121,9 +126,16 @@ public static function decode($jwt, $key, array $allowed_algs = array()) throw new UnexpectedValueException('"kid" empty, unable to lookup correct key'); } } + if (!($key instanceof JWTKey)) { + throw new UnexpectedValueException('$key should be an instance of JWTKey'); + } // Check the signature - if (!static::verify("$headb64.$bodyb64", $sig, $key, $header->alg)) { + if (!$key->isValidForAlg($header->alg)) { + // See issue #351 + throw new UnexpectedValueException('Incorrect key for this algorithm'); + } + if (!static::verify("$headb64.$bodyb64", $sig, $key->getKeyMaterial(), $header->alg)) { throw new SignatureInvalidException('Signature verification failed'); } @@ -285,18 +297,7 @@ private static function verify($msg, $signature, $key, $alg) case 'hash_hmac': default: $hash = \hash_hmac($algorithm, $msg, $key, true); - if (\function_exists('hash_equals')) { - return \hash_equals($signature, $hash); - } - $len = \min(static::safeStrlen($signature), static::safeStrlen($hash)); - - $status = 0; - for ($i = 0; $i < $len; $i++) { - $status |= (\ord($signature[$i]) ^ \ord($hash[$i])); - } - $status |= (static::safeStrlen($signature) ^ static::safeStrlen($hash)); - - return ($status === 0); + return self::constantTimeEquals($signature, $hash); } } @@ -384,6 +385,50 @@ public static function urlsafeB64Encode($input) return \str_replace('=', '', \strtr(\base64_encode($input), '+/', '-_')); } + /** + * @param string $left + * @param string $right + * @return bool + */ + public static function constantTimeEquals($left, $right) + { + if (\function_exists('hash_equals')) { + return \hash_equals($left, $right); + } + $len = \min(static::safeStrlen($left), static::safeStrlen($right)); + + $status = 0; + for ($i = 0; $i < $len; $i++) { + $status |= (\ord($left[$i]) ^ \ord($right[$i])); + } + $status |= (static::safeStrlen($left) ^ static::safeStrlen($right)); + + return ($status === 0); + } + + /** + * @param string|array|ArrayAccess $oldType + * @param string[] $algs + * @return KeyInterface + */ + public static function getKeyType($oldType, $algs) + { + if ($oldType instanceof KeyInterface) { + return $oldType; + } + if (is_string($oldType)) { + return new JWTKey($oldType, $algs); + } + if (is_array($oldType) || $oldType instanceof ArrayAccess) { + $keyring = new Keyring(array()); + foreach ($oldType as $kid => $key) { + $keyring[$kid] = new JWTKey($key, $algs); + } + return $keyring; + } + throw new InvalidArgumentException('Invalid type: Must be string or array'); + } + /** * Helper method to create a JSON error. * @@ -414,7 +459,7 @@ private static function handleJsonError($errno) * * @return int */ - private static function safeStrlen($str) + public static function safeStrlen($str) { if (\function_exists('mb_strlen')) { return \mb_strlen($str, '8bit'); diff --git a/src/Keys/JWTKey.php b/src/Keys/JWTKey.php new file mode 100644 index 00000000..6e095ad7 --- /dev/null +++ b/src/Keys/JWTKey.php @@ -0,0 +1,113 @@ +keyMaterial = $keyMaterial; + $this->alg = $alg; + } + + /** + * Is the header algorithm valid for this key? + * + * @param string $headerAlg + * @return bool + */ + public function isValidForAlg($headerAlg) + { + return JWT::constantTimeEquals($this->alg, $headerAlg); + } + + /** + * @return string + */ + public function getKeyMaterial() + { + return $this->keyMaterial; + } + + /** + * This is a best-effort attempt to guess the algorithm for a given key + * based on its contents. + * + * It will probably be wrong in a lot of corner cases. + * + * If it is, construct a JWTKey object and/or Keyring of JWTKey objects + * with the correct algorithms. + * + * @param string $keyMaterial + * @param array $candidates + * @return string + */ + public static function guessAlgFromKeyMaterial($keyMaterial, array $candidates = array()) + { + $length = JWT::safeStrlen($keyMaterial); + if ($length >= 720) { + // RSA keys + if (preg_match('#^-+BEGIN.+(PRIVATE|PUBLIC) KEY-+#', $keyMaterial)) { + if (in_array('RS512', $candidates)) { + return 'RS512'; + } + if (in_array('RS384', $candidates)) { + return 'RS384'; + } + return 'RS256'; + } + } elseif ($length >= 220) { + // ECDSA private keys + if (preg_match('#^-+BEGIN EC PRIVATE KEY-+#', $keyMaterial)) { + if (in_array('ES512', $candidates)) { + return 'ES512'; + } + if (in_array('ES384', $candidates)) { + return 'ES384'; + } + return 'ES256'; + } + } elseif ($length >= 170) { + // ECDSA public keys + if (preg_match('#^-+BEGIN EC PUBLICY-+#', $keyMaterial)) { + if (in_array('ES512', $candidates)) { + return 'ES512'; + } + if (in_array('ES384', $candidates)) { + return 'ES384'; + } + return 'ES256'; + } + } elseif ($length >= 40 && $length <= 88) { + // Likely base64-encoded EdDSA key + if (in_array('EdDSA', $candidates)) { + return 'EdDSA'; + } + } + + // Last resort: HMAC + if (in_array('HS512', $candidates)) { + return 'HS512'; + } + if (in_array('HS384', $candidates)) { + return 'HS384'; + } + return 'HS256'; + } +} diff --git a/src/Keys/Keyring.php b/src/Keys/Keyring.php new file mode 100644 index 00000000..72572a86 --- /dev/null +++ b/src/Keys/Keyring.php @@ -0,0 +1,81 @@ + $mapping */ + private $mapping; + + /** + * @param array $mapping + */ + public function __construct(array $mapping = array()) + { + $this->mapping = $mapping; + } + + /** + * @param string $keyId + * @param JWTKey $key + * @return $this + */ + public function mapKeyId($keyId, JWTKey $key) + { + $this->mapping[$keyId] = $key; + return $this; + } + + /** + * @param mixed $offset + * @return bool + */ + public function offsetExists($offset) + { + if (!is_string($offset)) { + throw new RuntimeException('Type error: argument 1 must be a string'); + } + return array_key_exists($offset, $this->mapping); + } + + /** + * @param mixed $offset + * @return JWTKey + */ + public function offsetGet($offset) + { + $value = $this->mapping[$offset]; + if (!($value instanceof JWTKey)) { + throw new RuntimeException('Type error: return value not an instance of JWTKey'); + } + return $value; + } + + /** + * @param string $offset + * @param JWTKey $value + */ + public function offsetSet($offset, $value) + { + if (!is_string($offset)) { + throw new RuntimeException('Type error: argument 1 must be a string'); + } + if (!($value instanceof JWTKey)) { + throw new RuntimeException('Type error: argument 2 must be an instance of JWT'); + } + $this->mapKeyId($offset, $value); + } + + /** + * @param string $offset + */ + public function offsetUnset($offset) + { + if (!is_string($offset)) { + throw new RuntimeException('Type error: argument 1 must be a string'); + } + unset($this->mapping[$offset]); + } +} From e08160a44d4fb7b639c791672419a91d557750e1 Mon Sep 17 00:00:00 2001 From: Paragon Initiative Enterprises Date: Wed, 4 Aug 2021 06:03:00 -0400 Subject: [PATCH 2/7] Add unit tests for current behavior --- tests/Keys/JWTKeyTest.php | 87 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 tests/Keys/JWTKeyTest.php diff --git a/tests/Keys/JWTKeyTest.php b/tests/Keys/JWTKeyTest.php new file mode 100644 index 00000000..6084fa7a --- /dev/null +++ b/tests/Keys/JWTKeyTest.php @@ -0,0 +1,87 @@ +getEcdsaPublicKey(); + $rsa = $this->getRsaPublicKey(); + $misc = 'maybe_use_paseto_instead'; + + $this->assertSame( + 'RS512', + JWTKey::guessAlgFromKeyMaterial($rsa, array('RS512')) + ); + $this->assertSame( + 'RS384', + JWTKey::guessAlgFromKeyMaterial($rsa, array('RS384')) + ); + $this->assertSame( + 'RS256', + JWTKey::guessAlgFromKeyMaterial($rsa, array('RS256')) + ); + $this->assertSame( + 'RS256', + JWTKey::guessAlgFromKeyMaterial($rsa) + ); + $this->assertSame( + 'ES384', + JWTKey::guessAlgFromKeyMaterial($ecc384, array('ES384')) + ); + $this->assertSame( + 'ES256', + JWTKey::guessAlgFromKeyMaterial($ecc384) + ); + $this->assertSame( + 'EdDSA', + JWTKey::guessAlgFromKeyMaterial($eddsa, array('EdDSA')) + ); + $this->assertSame( + 'HS256', + JWTKey::guessAlgFromKeyMaterial($eddsa) + ); + $this->assertSame( + 'HS384', + JWTKey::guessAlgFromKeyMaterial($misc, array('HS512')) + ); + $this->assertSame( + 'HS384', + JWTKey::guessAlgFromKeyMaterial($misc, array('HS384')) + ); + $this->assertSame( + 'HS256', + JWTKey::guessAlgFromKeyMaterial($misc, array('HS256')) + ); + $this->assertSame( + 'HS256', + JWTKey::guessAlgFromKeyMaterial($misc) + ); + } + + public function getRsaPublicKey() + { + $privKey = openssl_pkey_new(array('digest_alg' => 'sha256', + 'private_key_bits' => 1024, + 'private_key_type' => OPENSSL_KEYTYPE_RSA)); + $pubKey = openssl_pkey_get_details($privKey); + return $pubKey['key']; + } + + public function getEcdsaPublicKey() + { + $privKey = openssl_pkey_new( + array( + 'curve_name' => 'secp384r1', + 'digest_alg' => 'sha384', + 'private_key_bits' => 384, + 'private_key_type' => OPENSSL_KEYTYPE_EC + ) + ); + $pubKey = openssl_pkey_get_details($privKey); + return $pubKey['key']; + } +} From 28eb0e3a220aee486986fc1398b7c4f5e9a1c143 Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Wed, 3 Nov 2021 13:44:10 -0700 Subject: [PATCH 3/7] add key object support in v5 --- .github/actions/entrypoint.sh | 1 + README.md | 18 ++++-- src/JWT.php | 118 +++++++++++++++++++--------------- src/Key.php | 58 +++++++++++++++++ src/Keys/JWTKey.php | 113 -------------------------------- src/Keys/Keyring.php | 81 ----------------------- tests/JWTTest.php | 28 ++++++++ tests/Keys/JWTKeyTest.php | 87 ------------------------- 8 files changed, 166 insertions(+), 338 deletions(-) create mode 100644 src/Key.php delete mode 100644 src/Keys/JWTKey.php delete mode 100644 src/Keys/Keyring.php delete mode 100644 tests/Keys/JWTKeyTest.php diff --git a/.github/actions/entrypoint.sh b/.github/actions/entrypoint.sh index 8b6b9e1b..40402bc8 100755 --- a/.github/actions/entrypoint.sh +++ b/.github/actions/entrypoint.sh @@ -5,6 +5,7 @@ apt-get install -y --no-install-recommends \ git \ zip \ curl \ + ca-certificates \ unzip \ wget diff --git a/README.md b/README.md index a8556aa5..4194b9a6 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,7 @@ Example ------- ```php use Firebase\JWT\JWT; +use Firebase\JWT\Key; $key = "example_key"; $payload = array( @@ -43,7 +44,7 @@ $payload = array( * for a list of spec-compliant algorithms. */ $jwt = JWT::encode($payload, $key); -$decoded = JWT::decode($jwt, $key, array('HS256')); +$decoded = JWT::decode($jwt, new Key($key, 'HS256')); print_r($decoded); @@ -62,12 +63,13 @@ $decoded_array = (array) $decoded; * Source: http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#nbfDef */ JWT::$leeway = 60; // $leeway in seconds -$decoded = JWT::decode($jwt, $key, array('HS256')); +$decoded = JWT::decode($jwt, new Key($key, 'HS256')); ``` Example with RS256 (openssl) ---------------------------- ```php use Firebase\JWT\JWT; +use Firebase\JWT\Key; $privateKey = << []]; // JWK::parseKeySet($jwks) returns an associative array of **kid** to private // key. Pass this as the second parameter to JWT::decode. -JWT::decode($payload, JWK::parseKeySet($jwks), $supportedAlgorithm); +JWT::decode($payload, JWK::parseKeySet($jwks)); ``` Changelog diff --git a/src/JWT.php b/src/JWT.php index 36abd0bd..b7eded18 100644 --- a/src/JWT.php +++ b/src/JWT.php @@ -61,11 +61,13 @@ class JWT * Decodes a JWT string into a PHP object. * * @param string $jwt The JWT - * @param string|array|resource $key The key, or map of keys. + * @param Key|array $keyOrKeyArray The Key or array of Key objects. * If the algorithm used is asymmetric, this is the public key - * @param array $allowed_algs List of supported verification algorithms + * Each Key object contains an algorithm and matching key. * Supported algorithms are 'ES384','ES256', 'HS256', 'HS384', * 'HS512', 'RS256', 'RS384', and 'RS512' + * @param array $allowed_algs [DEPRECATED] List of supported verification algorithms. Only + * should be used for BC. * * @return object The JWT's payload as a PHP object * @@ -79,11 +81,11 @@ class JWT * @uses jsonDecode * @uses urlsafeB64Decode */ - public static function decode($jwt, $key, array $allowed_algs = array()) + public static function decode($jwt, $keyOrKeyArray, array $allowed_algs = array()) { $timestamp = \is_null(static::$timestamp) ? \time() : static::$timestamp; - if (empty($key)) { + if (empty($keyOrKeyArray)) { throw new InvalidArgumentException('Key may not be empty'); } $tks = \explode('.', $jwt); @@ -106,36 +108,32 @@ public static function decode($jwt, $key, array $allowed_algs = array()) if (empty(static::$supported_algs[$header->alg])) { throw new UnexpectedValueException('Algorithm not supported'); } - if (!\in_array($header->alg, $allowed_algs)) { - throw new UnexpectedValueException('Algorithm not allowed'); + + list($keyMaterial, $algorithm) = self::getKeyMaterialAndAlgorithm( + $keyOrKeyArray, + empty($header->kid) ? null : $header->kid + ); + + if (empty($algorithm)) { + // Use deprecated "allowed_algs" to determine if the algorithm is supported. + // This opens up the possibility of an attack in some implementations. + // @see https://github.com/firebase/php-jwt/issues/351 + if (!\in_array($header->alg, $allowed_algs)) { + throw new UnexpectedValueException('Algorithm not allowed'); + } + } else { + // Check the algorithm + if (!self::constantTimeEquals($algorithm, $header->alg)) { + // See issue #351 + throw new UnexpectedValueException('Incorrect key for this algorithm'); + } } if ($header->alg === 'ES256' || $header->alg === 'ES384') { // OpenSSL expects an ASN.1 DER sequence for ES256/ES384 signatures $sig = self::signatureToDER($sig); } - /** @var Keyring|JWTKey $key */ - $key = self::getKeyType($key, $allowed_algs); - if ($key instanceof Keyring) { - if (isset($header->kid)) { - if (!isset($key[$header->kid])) { - throw new UnexpectedValueException('"kid" invalid, unable to lookup correct key'); - } - $key = $key[$header->kid]; - } else { - throw new UnexpectedValueException('"kid" empty, unable to lookup correct key'); - } - } - if (!($key instanceof JWTKey)) { - throw new UnexpectedValueException('$key should be an instance of JWTKey'); - } - - // Check the signature - if (!$key->isValidForAlg($header->alg)) { - // See issue #351 - throw new UnexpectedValueException('Incorrect key for this algorithm'); - } - if (!static::verify("$headb64.$bodyb64", $sig, $key->getKeyMaterial(), $header->alg)) { + if (!static::verify("$headb64.$bodyb64", $sig, $keyMaterial, $header->alg)) { throw new SignatureInvalidException('Signature verification failed'); } @@ -385,6 +383,47 @@ public static function urlsafeB64Encode($input) return \str_replace('=', '', \strtr(\base64_encode($input), '+/', '-_')); } + + /** + * Determine if an algorithm has been provided for each Key + * + * @param string|array $keyOrKeyArray + * + * @return an array containing the keyMaterial and algorithm + */ + private static function getKeyMaterialAndAlgorithm($keyOrKeyArray, $kid = null) + { + if (is_string($keyOrKeyArray)) { + return [$keyOrKeyArray, null]; + } + + if ($keyOrKeyArray instanceof Key) { + return [$keyOrKeyArray->getKeyMaterial(), $keyOrKeyArray->getAlgorithm()]; + } + + if (is_array($keyOrKeyArray) || $keyOrKeyArray instanceof ArrayAccess) { + if (!isset($kid)) { + throw new UnexpectedValueException('"kid" empty, unable to lookup correct key'); + } + if (!isset($keyOrKeyArray[$kid])) { + throw new UnexpectedValueException('"kid" invalid, unable to lookup correct key'); + } + + $key = $keyOrKeyArray[$kid]; + + if ($key instanceof Key) { + return [$key->getKeyMaterial(), $key->getAlgorithm()]; + } + + return [$key, null]; + } + + throw new UnexpectedValueException( + '$keyOrKeyArray must be a string key, an array of string keys, ' + . 'an instance of Firebase\JWT\Key key or an array of Firebase\JWT\Key keys' + ); + } + /** * @param string $left * @param string $right @@ -406,29 +445,6 @@ public static function constantTimeEquals($left, $right) return ($status === 0); } - /** - * @param string|array|ArrayAccess $oldType - * @param string[] $algs - * @return KeyInterface - */ - public static function getKeyType($oldType, $algs) - { - if ($oldType instanceof KeyInterface) { - return $oldType; - } - if (is_string($oldType)) { - return new JWTKey($oldType, $algs); - } - if (is_array($oldType) || $oldType instanceof ArrayAccess) { - $keyring = new Keyring(array()); - foreach ($oldType as $kid => $key) { - $keyring[$kid] = new JWTKey($key, $algs); - } - return $keyring; - } - throw new InvalidArgumentException('Invalid type: Must be string or array'); - } - /** * Helper method to create a JSON error. * diff --git a/src/Key.php b/src/Key.php new file mode 100644 index 00000000..76a4d40f --- /dev/null +++ b/src/Key.php @@ -0,0 +1,58 @@ +keyMaterial = $keyMaterial; + $this->algorithm = $algorithm; + } + + /** + * Return the algorithm valid for this key + * + * @return string + */ + public function getAlgorithm() + { + return $this->algorithm; + } + + /** + * @return string|resource + */ + public function getKeyMaterial() + { + return $this->keyMaterial; + } +} diff --git a/src/Keys/JWTKey.php b/src/Keys/JWTKey.php deleted file mode 100644 index 6e095ad7..00000000 --- a/src/Keys/JWTKey.php +++ /dev/null @@ -1,113 +0,0 @@ -keyMaterial = $keyMaterial; - $this->alg = $alg; - } - - /** - * Is the header algorithm valid for this key? - * - * @param string $headerAlg - * @return bool - */ - public function isValidForAlg($headerAlg) - { - return JWT::constantTimeEquals($this->alg, $headerAlg); - } - - /** - * @return string - */ - public function getKeyMaterial() - { - return $this->keyMaterial; - } - - /** - * This is a best-effort attempt to guess the algorithm for a given key - * based on its contents. - * - * It will probably be wrong in a lot of corner cases. - * - * If it is, construct a JWTKey object and/or Keyring of JWTKey objects - * with the correct algorithms. - * - * @param string $keyMaterial - * @param array $candidates - * @return string - */ - public static function guessAlgFromKeyMaterial($keyMaterial, array $candidates = array()) - { - $length = JWT::safeStrlen($keyMaterial); - if ($length >= 720) { - // RSA keys - if (preg_match('#^-+BEGIN.+(PRIVATE|PUBLIC) KEY-+#', $keyMaterial)) { - if (in_array('RS512', $candidates)) { - return 'RS512'; - } - if (in_array('RS384', $candidates)) { - return 'RS384'; - } - return 'RS256'; - } - } elseif ($length >= 220) { - // ECDSA private keys - if (preg_match('#^-+BEGIN EC PRIVATE KEY-+#', $keyMaterial)) { - if (in_array('ES512', $candidates)) { - return 'ES512'; - } - if (in_array('ES384', $candidates)) { - return 'ES384'; - } - return 'ES256'; - } - } elseif ($length >= 170) { - // ECDSA public keys - if (preg_match('#^-+BEGIN EC PUBLICY-+#', $keyMaterial)) { - if (in_array('ES512', $candidates)) { - return 'ES512'; - } - if (in_array('ES384', $candidates)) { - return 'ES384'; - } - return 'ES256'; - } - } elseif ($length >= 40 && $length <= 88) { - // Likely base64-encoded EdDSA key - if (in_array('EdDSA', $candidates)) { - return 'EdDSA'; - } - } - - // Last resort: HMAC - if (in_array('HS512', $candidates)) { - return 'HS512'; - } - if (in_array('HS384', $candidates)) { - return 'HS384'; - } - return 'HS256'; - } -} diff --git a/src/Keys/Keyring.php b/src/Keys/Keyring.php deleted file mode 100644 index 72572a86..00000000 --- a/src/Keys/Keyring.php +++ /dev/null @@ -1,81 +0,0 @@ - $mapping */ - private $mapping; - - /** - * @param array $mapping - */ - public function __construct(array $mapping = array()) - { - $this->mapping = $mapping; - } - - /** - * @param string $keyId - * @param JWTKey $key - * @return $this - */ - public function mapKeyId($keyId, JWTKey $key) - { - $this->mapping[$keyId] = $key; - return $this; - } - - /** - * @param mixed $offset - * @return bool - */ - public function offsetExists($offset) - { - if (!is_string($offset)) { - throw new RuntimeException('Type error: argument 1 must be a string'); - } - return array_key_exists($offset, $this->mapping); - } - - /** - * @param mixed $offset - * @return JWTKey - */ - public function offsetGet($offset) - { - $value = $this->mapping[$offset]; - if (!($value instanceof JWTKey)) { - throw new RuntimeException('Type error: return value not an instance of JWTKey'); - } - return $value; - } - - /** - * @param string $offset - * @param JWTKey $value - */ - public function offsetSet($offset, $value) - { - if (!is_string($offset)) { - throw new RuntimeException('Type error: argument 1 must be a string'); - } - if (!($value instanceof JWTKey)) { - throw new RuntimeException('Type error: argument 2 must be an instance of JWT'); - } - $this->mapKeyId($offset, $value); - } - - /** - * @param string $offset - */ - public function offsetUnset($offset) - { - if (!is_string($offset)) { - throw new RuntimeException('Type error: argument 1 must be a string'); - } - unset($this->mapping[$offset]); - } -} diff --git a/tests/JWTTest.php b/tests/JWTTest.php index 3dee0450..63386d88 100644 --- a/tests/JWTTest.php +++ b/tests/JWTTest.php @@ -344,6 +344,34 @@ public function testEncodeDecode($privateKeyFile, $publicKeyFile, $alg) $this->assertEquals('bar', $decoded->foo); } + /** + * @runInSeparateProcess + * @dataProvider provideEncodeDecode + */ + public function testEncodeDecodeWithKeyObject($privateKeyFile, $publicKeyFile, $alg) + { + $privateKey = file_get_contents($privateKeyFile); + $payload = array('foo' => 'bar'); + $encoded = JWT::encode($payload, $privateKey, $alg); + + // Verify decoding succeeds + $publicKey = file_get_contents($publicKeyFile); + $decoded = JWT::decode($encoded, new Key($publicKey, $alg)); + + $this->assertEquals('bar', $decoded->foo); + } + + public function testArrayAccessKIDChooserWithKeyObject() + { + $keys = new ArrayObject(array( + '1' => new Key('my_key', 'HS256'), + '2' => new Key('my_key2', 'HS256'), + )); + $msg = JWT::encode('abc', $keys['1']->getKeyMaterial(), 'HS256', '1'); + $decoded = JWT::decode($msg, $keys); + $this->assertEquals($decoded, 'abc'); + } + public function provideEncodeDecode() { return array( diff --git a/tests/Keys/JWTKeyTest.php b/tests/Keys/JWTKeyTest.php deleted file mode 100644 index 6084fa7a..00000000 --- a/tests/Keys/JWTKeyTest.php +++ /dev/null @@ -1,87 +0,0 @@ -getEcdsaPublicKey(); - $rsa = $this->getRsaPublicKey(); - $misc = 'maybe_use_paseto_instead'; - - $this->assertSame( - 'RS512', - JWTKey::guessAlgFromKeyMaterial($rsa, array('RS512')) - ); - $this->assertSame( - 'RS384', - JWTKey::guessAlgFromKeyMaterial($rsa, array('RS384')) - ); - $this->assertSame( - 'RS256', - JWTKey::guessAlgFromKeyMaterial($rsa, array('RS256')) - ); - $this->assertSame( - 'RS256', - JWTKey::guessAlgFromKeyMaterial($rsa) - ); - $this->assertSame( - 'ES384', - JWTKey::guessAlgFromKeyMaterial($ecc384, array('ES384')) - ); - $this->assertSame( - 'ES256', - JWTKey::guessAlgFromKeyMaterial($ecc384) - ); - $this->assertSame( - 'EdDSA', - JWTKey::guessAlgFromKeyMaterial($eddsa, array('EdDSA')) - ); - $this->assertSame( - 'HS256', - JWTKey::guessAlgFromKeyMaterial($eddsa) - ); - $this->assertSame( - 'HS384', - JWTKey::guessAlgFromKeyMaterial($misc, array('HS512')) - ); - $this->assertSame( - 'HS384', - JWTKey::guessAlgFromKeyMaterial($misc, array('HS384')) - ); - $this->assertSame( - 'HS256', - JWTKey::guessAlgFromKeyMaterial($misc, array('HS256')) - ); - $this->assertSame( - 'HS256', - JWTKey::guessAlgFromKeyMaterial($misc) - ); - } - - public function getRsaPublicKey() - { - $privKey = openssl_pkey_new(array('digest_alg' => 'sha256', - 'private_key_bits' => 1024, - 'private_key_type' => OPENSSL_KEYTYPE_RSA)); - $pubKey = openssl_pkey_get_details($privKey); - return $pubKey['key']; - } - - public function getEcdsaPublicKey() - { - $privKey = openssl_pkey_new( - array( - 'curve_name' => 'secp384r1', - 'digest_alg' => 'sha384', - 'private_key_bits' => 384, - 'private_key_type' => OPENSSL_KEYTYPE_EC - ) - ); - $pubKey = openssl_pkey_get_details($privKey); - return $pubKey['key']; - } -} From 65920fde7910205e89d41739fde0a51e511ba22c Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Wed, 3 Nov 2021 13:56:45 -0700 Subject: [PATCH 4/7] fix array syntax for PHP 5.3 --- src/JWT.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/JWT.php b/src/JWT.php index b7eded18..740c56c1 100644 --- a/src/JWT.php +++ b/src/JWT.php @@ -394,11 +394,11 @@ public static function urlsafeB64Encode($input) private static function getKeyMaterialAndAlgorithm($keyOrKeyArray, $kid = null) { if (is_string($keyOrKeyArray)) { - return [$keyOrKeyArray, null]; + return array($keyOrKeyArray, null); } if ($keyOrKeyArray instanceof Key) { - return [$keyOrKeyArray->getKeyMaterial(), $keyOrKeyArray->getAlgorithm()]; + return array($keyOrKeyArray->getKeyMaterial(), $keyOrKeyArray->getAlgorithm()); } if (is_array($keyOrKeyArray) || $keyOrKeyArray instanceof ArrayAccess) { @@ -412,10 +412,10 @@ private static function getKeyMaterialAndAlgorithm($keyOrKeyArray, $kid = null) $key = $keyOrKeyArray[$kid]; if ($key instanceof Key) { - return [$key->getKeyMaterial(), $key->getAlgorithm()]; + return array($key->getKeyMaterial(), $key->getAlgorithm()); } - return [$key, null]; + return array($key, null); } throw new UnexpectedValueException( From 0822edd2e924919c0f8b9688152354ffb7335046 Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Wed, 3 Nov 2021 14:13:08 -0700 Subject: [PATCH 5/7] misc cleanup --- src/JWT.php | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/JWT.php b/src/JWT.php index 740c56c1..6a60c921 100644 --- a/src/JWT.php +++ b/src/JWT.php @@ -5,8 +5,6 @@ use ArrayAccess; use DomainException; use Exception; -use Firebase\JWT\Keys\JWTKey; -use Firebase\JWT\Keys\Keyring; use InvalidArgumentException; use UnexpectedValueException; use DateTime; @@ -475,7 +473,7 @@ private static function handleJsonError($errno) * * @return int */ - public static function safeStrlen($str) + private static function safeStrlen($str) { if (\function_exists('mb_strlen')) { return \mb_strlen($str, '8bit'); From 58d0d58f6c28f4e08314d4bf4bb3982476b941b8 Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Wed, 3 Nov 2021 14:36:30 -0700 Subject: [PATCH 6/7] misc docbloc fixes --- src/JWT.php | 3 ++- src/Key.php | 7 ++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/JWT.php b/src/JWT.php index 6a60c921..f46e8372 100644 --- a/src/JWT.php +++ b/src/JWT.php @@ -65,7 +65,7 @@ class JWT * Supported algorithms are 'ES384','ES256', 'HS256', 'HS384', * 'HS512', 'RS256', 'RS384', and 'RS512' * @param array $allowed_algs [DEPRECATED] List of supported verification algorithms. Only - * should be used for BC. + * should be used for backwards compatibility. * * @return object The JWT's payload as a PHP object * @@ -386,6 +386,7 @@ public static function urlsafeB64Encode($input) * Determine if an algorithm has been provided for each Key * * @param string|array $keyOrKeyArray + * @param string|null $kid * * @return an array containing the keyMaterial and algorithm */ diff --git a/src/Key.php b/src/Key.php index 76a4d40f..f1ede6f2 100644 --- a/src/Key.php +++ b/src/Key.php @@ -10,11 +10,11 @@ class Key /** @var string $algorithm */ private $algorithm; - /** @var string $keyMaterial */ + /** @var string|resource|OpenSSLAsymmetricKey $keyMaterial */ private $keyMaterial; /** - * @param string|resource $keyMaterial + * @param string|resource|OpenSSLAsymmetricKey $keyMaterial * @param string $algorithm */ public function __construct($keyMaterial, $algorithm) @@ -34,6 +34,7 @@ public function __construct($keyMaterial, $algorithm) if (!is_string($algorithm)|| empty($keyMaterial)) { throw new InvalidArgumentException('Type error: $algorithm must be a string'); } + $this->keyMaterial = $keyMaterial; $this->algorithm = $algorithm; } @@ -49,7 +50,7 @@ public function getAlgorithm() } /** - * @return string|resource + * @return string|resource|OpenSSLAsymmetricKey */ public function getKeyMaterial() { From b9f6c393d1a55b83ea5a4a778e1963d36bf4a334 Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Wed, 3 Nov 2021 14:38:59 -0700 Subject: [PATCH 7/7] unfortunately, pareKeySet requires supportedAlgorithm for BC --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 4194b9a6..ee98c47f 100644 --- a/README.md +++ b/README.md @@ -200,7 +200,8 @@ $jwks = ['keys' => []]; // JWK::parseKeySet($jwks) returns an associative array of **kid** to private // key. Pass this as the second parameter to JWT::decode. -JWT::decode($payload, JWK::parseKeySet($jwks)); +// NOTE: The deprecated $supportedAlgorithm must be supplied when parsing from JWK. +JWT::decode($payload, JWK::parseKeySet($jwks), $supportedAlgorithm); ``` Changelog