JWT.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. <?php
  2. namespace Firebase\JWT;
  3. use ArrayAccess;
  4. use DateTime;
  5. use DomainException;
  6. use Exception;
  7. use InvalidArgumentException;
  8. use OpenSSLAsymmetricKey;
  9. use OpenSSLCertificate;
  10. use stdClass;
  11. use UnexpectedValueException;
  12. /**
  13. * JSON Web Token implementation, based on this spec:
  14. * https://tools.ietf.org/html/rfc7519
  15. *
  16. * PHP version 5
  17. *
  18. * @category Authentication
  19. * @package Authentication_JWT
  20. * @author Neuman Vong <neuman@twilio.com>
  21. * @author Anant Narayanan <anant@php.net>
  22. * @license http://opensource.org/licenses/BSD-3-Clause 3-clause BSD
  23. * @link https://github.com/firebase/php-jwt
  24. */
  25. class JWT
  26. {
  27. private const ASN1_INTEGER = 0x02;
  28. private const ASN1_SEQUENCE = 0x10;
  29. private const ASN1_BIT_STRING = 0x03;
  30. /**
  31. * When checking nbf, iat or expiration times,
  32. * we want to provide some extra leeway time to
  33. * account for clock skew.
  34. *
  35. * @var int
  36. */
  37. public static $leeway = 0;
  38. /**
  39. * Allow the current timestamp to be specified.
  40. * Useful for fixing a value within unit testing.
  41. * Will default to PHP time() value if null.
  42. *
  43. * @var ?int
  44. */
  45. public static $timestamp = null;
  46. /**
  47. * @var array<string, string[]>
  48. */
  49. public static $supported_algs = [
  50. 'ES384' => ['openssl', 'SHA384'],
  51. 'ES256' => ['openssl', 'SHA256'],
  52. 'HS256' => ['hash_hmac', 'SHA256'],
  53. 'HS384' => ['hash_hmac', 'SHA384'],
  54. 'HS512' => ['hash_hmac', 'SHA512'],
  55. 'RS256' => ['openssl', 'SHA256'],
  56. 'RS384' => ['openssl', 'SHA384'],
  57. 'RS512' => ['openssl', 'SHA512'],
  58. 'EdDSA' => ['sodium_crypto', 'EdDSA'],
  59. ];
  60. /**
  61. * Decodes a JWT string into a PHP object.
  62. *
  63. * @param string $jwt The JWT
  64. * @param Key|array<string,Key> $keyOrKeyArray The Key or associative array of key IDs (kid) to Key objects.
  65. * If the algorithm used is asymmetric, this is the public key
  66. * Each Key object contains an algorithm and matching key.
  67. * Supported algorithms are 'ES384','ES256', 'HS256', 'HS384',
  68. * 'HS512', 'RS256', 'RS384', and 'RS512'
  69. *
  70. * @return stdClass The JWT's payload as a PHP object
  71. *
  72. * @throws InvalidArgumentException Provided key/key-array was empty or malformed
  73. * @throws DomainException Provided JWT is malformed
  74. * @throws UnexpectedValueException Provided JWT was invalid
  75. * @throws SignatureInvalidException Provided JWT was invalid because the signature verification failed
  76. * @throws BeforeValidException Provided JWT is trying to be used before it's eligible as defined by 'nbf'
  77. * @throws BeforeValidException Provided JWT is trying to be used before it's been created as defined by 'iat'
  78. * @throws ExpiredException Provided JWT has since expired, as defined by the 'exp' claim
  79. *
  80. * @uses jsonDecode
  81. * @uses urlsafeB64Decode
  82. */
  83. public static function decode(
  84. string $jwt,
  85. $keyOrKeyArray
  86. ): stdClass {
  87. // Validate JWT
  88. $timestamp = \is_null(static::$timestamp) ? \time() : static::$timestamp;
  89. if (empty($keyOrKeyArray)) {
  90. throw new InvalidArgumentException('Key may not be empty');
  91. }
  92. $tks = \explode('.', $jwt);
  93. if (\count($tks) !== 3) {
  94. throw new UnexpectedValueException('Wrong number of segments');
  95. }
  96. list($headb64, $bodyb64, $cryptob64) = $tks;
  97. $headerRaw = static::urlsafeB64Decode($headb64);
  98. if (null === ($header = static::jsonDecode($headerRaw))) {
  99. throw new UnexpectedValueException('Invalid header encoding');
  100. }
  101. $payloadRaw = static::urlsafeB64Decode($bodyb64);
  102. if (null === ($payload = static::jsonDecode($payloadRaw))) {
  103. throw new UnexpectedValueException('Invalid claims encoding');
  104. }
  105. if (\is_array($payload)) {
  106. // prevent PHP Fatal Error in edge-cases when payload is empty array
  107. $payload = (object) $payload;
  108. }
  109. if (!$payload instanceof stdClass) {
  110. throw new UnexpectedValueException('Payload must be a JSON object');
  111. }
  112. $sig = static::urlsafeB64Decode($cryptob64);
  113. if (empty($header->alg)) {
  114. throw new UnexpectedValueException('Empty algorithm');
  115. }
  116. if (empty(static::$supported_algs[$header->alg])) {
  117. throw new UnexpectedValueException('Algorithm not supported');
  118. }
  119. $key = self::getKey($keyOrKeyArray, property_exists($header, 'kid') ? $header->kid : null);
  120. // Check the algorithm
  121. if (!self::constantTimeEquals($key->getAlgorithm(), $header->alg)) {
  122. // See issue #351
  123. throw new UnexpectedValueException('Incorrect key for this algorithm');
  124. }
  125. if ($header->alg === 'ES256' || $header->alg === 'ES384') {
  126. // OpenSSL expects an ASN.1 DER sequence for ES256/ES384 signatures
  127. $sig = self::signatureToDER($sig);
  128. }
  129. if (!self::verify("{$headb64}.{$bodyb64}", $sig, $key->getKeyMaterial(), $header->alg)) {
  130. throw new SignatureInvalidException('Signature verification failed');
  131. }
  132. // Check the nbf if it is defined. This is the time that the
  133. // token can actually be used. If it's not yet that time, abort.
  134. if (isset($payload->nbf) && $payload->nbf > ($timestamp + static::$leeway)) {
  135. throw new BeforeValidException(
  136. 'Cannot handle token prior to ' . \date(DateTime::ISO8601, $payload->nbf)
  137. );
  138. }
  139. // Check that this token has been created before 'now'. This prevents
  140. // using tokens that have been created for later use (and haven't
  141. // correctly used the nbf claim).
  142. if (isset($payload->iat) && $payload->iat > ($timestamp + static::$leeway)) {
  143. throw new BeforeValidException(
  144. 'Cannot handle token prior to ' . \date(DateTime::ISO8601, $payload->iat)
  145. );
  146. }
  147. // Check if this token has expired.
  148. if (isset($payload->exp) && ($timestamp - static::$leeway) >= $payload->exp) {
  149. throw new ExpiredException('Expired token');
  150. }
  151. return $payload;
  152. }
  153. /**
  154. * Converts and signs a PHP array into a JWT string.
  155. *
  156. * @param array<mixed> $payload PHP array
  157. * @param string|resource|OpenSSLAsymmetricKey|OpenSSLCertificate $key The secret key.
  158. * @param string $alg Supported algorithms are 'ES384','ES256', 'HS256', 'HS384',
  159. * 'HS512', 'RS256', 'RS384', and 'RS512'
  160. * @param string $keyId
  161. * @param array<string, string> $head An array with header elements to attach
  162. *
  163. * @return string A signed JWT
  164. *
  165. * @uses jsonEncode
  166. * @uses urlsafeB64Encode
  167. */
  168. public static function encode(
  169. array $payload,
  170. $key,
  171. string $alg,
  172. string $keyId = null,
  173. array $head = null
  174. ): string {
  175. $header = ['typ' => 'JWT', 'alg' => $alg];
  176. if ($keyId !== null) {
  177. $header['kid'] = $keyId;
  178. }
  179. if (isset($head) && \is_array($head)) {
  180. $header = \array_merge($head, $header);
  181. }
  182. $segments = [];
  183. $segments[] = static::urlsafeB64Encode((string) static::jsonEncode($header));
  184. $segments[] = static::urlsafeB64Encode((string) static::jsonEncode($payload));
  185. $signing_input = \implode('.', $segments);
  186. $signature = static::sign($signing_input, $key, $alg);
  187. $segments[] = static::urlsafeB64Encode($signature);
  188. return \implode('.', $segments);
  189. }
  190. /**
  191. * Sign a string with a given key and algorithm.
  192. *
  193. * @param string $msg The message to sign
  194. * @param string|resource|OpenSSLAsymmetricKey|OpenSSLCertificate $key The secret key.
  195. * @param string $alg Supported algorithms are 'ES384','ES256', 'HS256', 'HS384',
  196. * 'HS512', 'RS256', 'RS384', and 'RS512'
  197. *
  198. * @return string An encrypted message
  199. *
  200. * @throws DomainException Unsupported algorithm or bad key was specified
  201. */
  202. public static function sign(
  203. string $msg,
  204. $key,
  205. string $alg
  206. ): string {
  207. if (empty(static::$supported_algs[$alg])) {
  208. throw new DomainException('Algorithm not supported');
  209. }
  210. list($function, $algorithm) = static::$supported_algs[$alg];
  211. switch ($function) {
  212. case 'hash_hmac':
  213. if (!\is_string($key)) {
  214. throw new InvalidArgumentException('key must be a string when using hmac');
  215. }
  216. return \hash_hmac($algorithm, $msg, $key, true);
  217. case 'openssl':
  218. $signature = '';
  219. $success = \openssl_sign($msg, $signature, $key, $algorithm); // @phpstan-ignore-line
  220. if (!$success) {
  221. throw new DomainException('OpenSSL unable to sign data');
  222. }
  223. if ($alg === 'ES256') {
  224. $signature = self::signatureFromDER($signature, 256);
  225. } elseif ($alg === 'ES384') {
  226. $signature = self::signatureFromDER($signature, 384);
  227. }
  228. return $signature;
  229. case 'sodium_crypto':
  230. if (!\function_exists('sodium_crypto_sign_detached')) {
  231. throw new DomainException('libsodium is not available');
  232. }
  233. if (!\is_string($key)) {
  234. throw new InvalidArgumentException('key must be a string when using EdDSA');
  235. }
  236. try {
  237. // The last non-empty line is used as the key.
  238. $lines = array_filter(explode("\n", $key));
  239. $key = base64_decode((string) end($lines));
  240. return sodium_crypto_sign_detached($msg, $key);
  241. } catch (Exception $e) {
  242. throw new DomainException($e->getMessage(), 0, $e);
  243. }
  244. }
  245. throw new DomainException('Algorithm not supported');
  246. }
  247. /**
  248. * Verify a signature with the message, key and method. Not all methods
  249. * are symmetric, so we must have a separate verify and sign method.
  250. *
  251. * @param string $msg The original message (header and body)
  252. * @param string $signature The original signature
  253. * @param string|resource|OpenSSLAsymmetricKey|OpenSSLCertificate $keyMaterial For HS*, a string key works. for RS*, must be an instance of OpenSSLAsymmetricKey
  254. * @param string $alg The algorithm
  255. *
  256. * @return bool
  257. *
  258. * @throws DomainException Invalid Algorithm, bad key, or OpenSSL failure
  259. */
  260. private static function verify(
  261. string $msg,
  262. string $signature,
  263. $keyMaterial,
  264. string $alg
  265. ): bool {
  266. if (empty(static::$supported_algs[$alg])) {
  267. throw new DomainException('Algorithm not supported');
  268. }
  269. list($function, $algorithm) = static::$supported_algs[$alg];
  270. switch ($function) {
  271. case 'openssl':
  272. $success = \openssl_verify($msg, $signature, $keyMaterial, $algorithm); // @phpstan-ignore-line
  273. if ($success === 1) {
  274. return true;
  275. }
  276. if ($success === 0) {
  277. return false;
  278. }
  279. // returns 1 on success, 0 on failure, -1 on error.
  280. throw new DomainException(
  281. 'OpenSSL error: ' . \openssl_error_string()
  282. );
  283. case 'sodium_crypto':
  284. if (!\function_exists('sodium_crypto_sign_verify_detached')) {
  285. throw new DomainException('libsodium is not available');
  286. }
  287. if (!\is_string($keyMaterial)) {
  288. throw new InvalidArgumentException('key must be a string when using EdDSA');
  289. }
  290. try {
  291. // The last non-empty line is used as the key.
  292. $lines = array_filter(explode("\n", $keyMaterial));
  293. $key = base64_decode((string) end($lines));
  294. return sodium_crypto_sign_verify_detached($signature, $msg, $key);
  295. } catch (Exception $e) {
  296. throw new DomainException($e->getMessage(), 0, $e);
  297. }
  298. case 'hash_hmac':
  299. default:
  300. if (!\is_string($keyMaterial)) {
  301. throw new InvalidArgumentException('key must be a string when using hmac');
  302. }
  303. $hash = \hash_hmac($algorithm, $msg, $keyMaterial, true);
  304. return self::constantTimeEquals($hash, $signature);
  305. }
  306. }
  307. /**
  308. * Decode a JSON string into a PHP object.
  309. *
  310. * @param string $input JSON string
  311. *
  312. * @return mixed The decoded JSON string
  313. *
  314. * @throws DomainException Provided string was invalid JSON
  315. */
  316. public static function jsonDecode(string $input)
  317. {
  318. $obj = \json_decode($input, false, 512, JSON_BIGINT_AS_STRING);
  319. if ($errno = \json_last_error()) {
  320. self::handleJsonError($errno);
  321. } elseif ($obj === null && $input !== 'null') {
  322. throw new DomainException('Null result with non-null input');
  323. }
  324. return $obj;
  325. }
  326. /**
  327. * Encode a PHP array into a JSON string.
  328. *
  329. * @param array<mixed> $input A PHP array
  330. *
  331. * @return string JSON representation of the PHP array
  332. *
  333. * @throws DomainException Provided object could not be encoded to valid JSON
  334. */
  335. public static function jsonEncode(array $input): string
  336. {
  337. if (PHP_VERSION_ID >= 50400) {
  338. $json = \json_encode($input, \JSON_UNESCAPED_SLASHES);
  339. } else {
  340. // PHP 5.3 only
  341. $json = \json_encode($input);
  342. }
  343. if ($errno = \json_last_error()) {
  344. self::handleJsonError($errno);
  345. } elseif ($json === 'null' && $input !== null) {
  346. throw new DomainException('Null result with non-null input');
  347. }
  348. if ($json === false) {
  349. throw new DomainException('Provided object could not be encoded to valid JSON');
  350. }
  351. return $json;
  352. }
  353. /**
  354. * Decode a string with URL-safe Base64.
  355. *
  356. * @param string $input A Base64 encoded string
  357. *
  358. * @return string A decoded string
  359. *
  360. * @throws InvalidArgumentException invalid base64 characters
  361. */
  362. public static function urlsafeB64Decode(string $input): string
  363. {
  364. $remainder = \strlen($input) % 4;
  365. if ($remainder) {
  366. $padlen = 4 - $remainder;
  367. $input .= \str_repeat('=', $padlen);
  368. }
  369. return \base64_decode(\strtr($input, '-_', '+/'));
  370. }
  371. /**
  372. * Encode a string with URL-safe Base64.
  373. *
  374. * @param string $input The string you want encoded
  375. *
  376. * @return string The base64 encode of what you passed in
  377. */
  378. public static function urlsafeB64Encode(string $input): string
  379. {
  380. return \str_replace('=', '', \strtr(\base64_encode($input), '+/', '-_'));
  381. }
  382. /**
  383. * Determine if an algorithm has been provided for each Key
  384. *
  385. * @param Key|ArrayAccess<string,Key>|array<string,Key> $keyOrKeyArray
  386. * @param string|null $kid
  387. *
  388. * @throws UnexpectedValueException
  389. *
  390. * @return Key
  391. */
  392. private static function getKey(
  393. $keyOrKeyArray,
  394. ?string $kid
  395. ): Key {
  396. if ($keyOrKeyArray instanceof Key) {
  397. return $keyOrKeyArray;
  398. }
  399. if (empty($kid)) {
  400. throw new UnexpectedValueException('"kid" empty, unable to lookup correct key');
  401. }
  402. if ($keyOrKeyArray instanceof CachedKeySet) {
  403. // Skip "isset" check, as this will automatically refresh if not set
  404. return $keyOrKeyArray[$kid];
  405. }
  406. if (!isset($keyOrKeyArray[$kid])) {
  407. throw new UnexpectedValueException('"kid" invalid, unable to lookup correct key');
  408. }
  409. return $keyOrKeyArray[$kid];
  410. }
  411. /**
  412. * @param string $left The string of known length to compare against
  413. * @param string $right The user-supplied string
  414. * @return bool
  415. */
  416. public static function constantTimeEquals(string $left, string $right): bool
  417. {
  418. if (\function_exists('hash_equals')) {
  419. return \hash_equals($left, $right);
  420. }
  421. $len = \min(self::safeStrlen($left), self::safeStrlen($right));
  422. $status = 0;
  423. for ($i = 0; $i < $len; $i++) {
  424. $status |= (\ord($left[$i]) ^ \ord($right[$i]));
  425. }
  426. $status |= (self::safeStrlen($left) ^ self::safeStrlen($right));
  427. return ($status === 0);
  428. }
  429. /**
  430. * Helper method to create a JSON error.
  431. *
  432. * @param int $errno An error number from json_last_error()
  433. *
  434. * @throws DomainException
  435. *
  436. * @return void
  437. */
  438. private static function handleJsonError(int $errno): void
  439. {
  440. $messages = [
  441. JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
  442. JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON',
  443. JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
  444. JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON',
  445. JSON_ERROR_UTF8 => 'Malformed UTF-8 characters' //PHP >= 5.3.3
  446. ];
  447. throw new DomainException(
  448. isset($messages[$errno])
  449. ? $messages[$errno]
  450. : 'Unknown JSON error: ' . $errno
  451. );
  452. }
  453. /**
  454. * Get the number of bytes in cryptographic strings.
  455. *
  456. * @param string $str
  457. *
  458. * @return int
  459. */
  460. private static function safeStrlen(string $str): int
  461. {
  462. if (\function_exists('mb_strlen')) {
  463. return \mb_strlen($str, '8bit');
  464. }
  465. return \strlen($str);
  466. }
  467. /**
  468. * Convert an ECDSA signature to an ASN.1 DER sequence
  469. *
  470. * @param string $sig The ECDSA signature to convert
  471. * @return string The encoded DER object
  472. */
  473. private static function signatureToDER(string $sig): string
  474. {
  475. // Separate the signature into r-value and s-value
  476. $length = max(1, (int) (\strlen($sig) / 2));
  477. list($r, $s) = \str_split($sig, $length);
  478. // Trim leading zeros
  479. $r = \ltrim($r, "\x00");
  480. $s = \ltrim($s, "\x00");
  481. // Convert r-value and s-value from unsigned big-endian integers to
  482. // signed two's complement
  483. if (\ord($r[0]) > 0x7f) {
  484. $r = "\x00" . $r;
  485. }
  486. if (\ord($s[0]) > 0x7f) {
  487. $s = "\x00" . $s;
  488. }
  489. return self::encodeDER(
  490. self::ASN1_SEQUENCE,
  491. self::encodeDER(self::ASN1_INTEGER, $r) .
  492. self::encodeDER(self::ASN1_INTEGER, $s)
  493. );
  494. }
  495. /**
  496. * Encodes a value into a DER object.
  497. *
  498. * @param int $type DER tag
  499. * @param string $value the value to encode
  500. *
  501. * @return string the encoded object
  502. */
  503. private static function encodeDER(int $type, string $value): string
  504. {
  505. $tag_header = 0;
  506. if ($type === self::ASN1_SEQUENCE) {
  507. $tag_header |= 0x20;
  508. }
  509. // Type
  510. $der = \chr($tag_header | $type);
  511. // Length
  512. $der .= \chr(\strlen($value));
  513. return $der . $value;
  514. }
  515. /**
  516. * Encodes signature from a DER object.
  517. *
  518. * @param string $der binary signature in DER format
  519. * @param int $keySize the number of bits in the key
  520. *
  521. * @return string the signature
  522. */
  523. private static function signatureFromDER(string $der, int $keySize): string
  524. {
  525. // OpenSSL returns the ECDSA signatures as a binary ASN.1 DER SEQUENCE
  526. list($offset, $_) = self::readDER($der);
  527. list($offset, $r) = self::readDER($der, $offset);
  528. list($offset, $s) = self::readDER($der, $offset);
  529. // Convert r-value and s-value from signed two's compliment to unsigned
  530. // big-endian integers
  531. $r = \ltrim($r, "\x00");
  532. $s = \ltrim($s, "\x00");
  533. // Pad out r and s so that they are $keySize bits long
  534. $r = \str_pad($r, $keySize / 8, "\x00", STR_PAD_LEFT);
  535. $s = \str_pad($s, $keySize / 8, "\x00", STR_PAD_LEFT);
  536. return $r . $s;
  537. }
  538. /**
  539. * Reads binary DER-encoded data and decodes into a single object
  540. *
  541. * @param string $der the binary data in DER format
  542. * @param int $offset the offset of the data stream containing the object
  543. * to decode
  544. *
  545. * @return array{int, string|null} the new offset and the decoded object
  546. */
  547. private static function readDER(string $der, int $offset = 0): array
  548. {
  549. $pos = $offset;
  550. $size = \strlen($der);
  551. $constructed = (\ord($der[$pos]) >> 5) & 0x01;
  552. $type = \ord($der[$pos++]) & 0x1f;
  553. // Length
  554. $len = \ord($der[$pos++]);
  555. if ($len & 0x80) {
  556. $n = $len & 0x1f;
  557. $len = 0;
  558. while ($n-- && $pos < $size) {
  559. $len = ($len << 8) | \ord($der[$pos++]);
  560. }
  561. }
  562. // Value
  563. if ($type === self::ASN1_BIT_STRING) {
  564. $pos++; // Skip the first contents octet (padding indicator)
  565. $data = \substr($der, $pos, $len - 1);
  566. $pos += $len - 1;
  567. } elseif (!$constructed) {
  568. $data = \substr($der, $pos, $len);
  569. $pos += $len;
  570. } else {
  571. $data = null;
  572. }
  573. return [$pos, $data];
  574. }
  575. }