JWT.php 20 KB

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