/lib/php-jwt/src/JWT.php

https://bitbucket.org/moodle/moodle · PHP · 512 lines · 279 code · 45 blank · 188 comment · 54 complexity · e07adc034b2efb2548177c4d188bde56 MD5 · raw file

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