/class/libraries/vendor/firebase/php-jwt/src/JWT.php

https://gitlab.com/VoyaTrax/vtCMS2 · PHP · 357 lines · 191 code · 26 blank · 140 comment · 43 complexity · 8377a0dd4f81fa9c0e987f676b91700c 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. * http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-06
  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. /**
  23. * When checking nbf, iat or expiration times,
  24. * we want to provide some extra leeway time to
  25. * account for clock skew.
  26. */
  27. public static $leeway = 0;
  28. public static $supported_algs = array(
  29. 'HS256' => array('hash_hmac', 'SHA256'),
  30. 'HS512' => array('hash_hmac', 'SHA512'),
  31. 'HS384' => array('hash_hmac', 'SHA384'),
  32. 'RS256' => array('openssl', 'SHA256'),
  33. );
  34. /**
  35. * Decodes a JWT string into a PHP object.
  36. *
  37. * @param string $jwt The JWT
  38. * @param string|array|null $key The key, or map of keys.
  39. * If the algorithm used is asymmetric, this is the public key
  40. * @param array $allowed_algs List of supported verification algorithms
  41. * Supported algorithms are 'HS256', 'HS384', 'HS512' and 'RS256'
  42. *
  43. * @return object The JWT's payload as a PHP object
  44. *
  45. * @throws DomainException Algorithm was not provided
  46. * @throws UnexpectedValueException Provided JWT was invalid
  47. * @throws SignatureInvalidException Provided JWT was invalid because the signature verification failed
  48. * @throws BeforeValidException Provided JWT is trying to be used before it's eligible as defined by 'nbf'
  49. * @throws BeforeValidException Provided JWT is trying to be used before it's been created as defined by 'iat'
  50. * @throws ExpiredException Provided JWT has since expired, as defined by the 'exp' claim
  51. *
  52. * @uses jsonDecode
  53. * @uses urlsafeB64Decode
  54. */
  55. public static function decode($jwt, $key, $allowed_algs = array())
  56. {
  57. if (empty($key)) {
  58. throw new InvalidArgumentException('Key may not be empty');
  59. }
  60. $tks = explode('.', $jwt);
  61. if (count($tks) != 3) {
  62. throw new UnexpectedValueException('Wrong number of segments');
  63. }
  64. list($headb64, $bodyb64, $cryptob64) = $tks;
  65. if (null === ($header = JWT::jsonDecode(JWT::urlsafeB64Decode($headb64)))) {
  66. throw new UnexpectedValueException('Invalid header encoding');
  67. }
  68. if (null === $payload = JWT::jsonDecode(JWT::urlsafeB64Decode($bodyb64))) {
  69. throw new UnexpectedValueException('Invalid claims encoding');
  70. }
  71. $sig = JWT::urlsafeB64Decode($cryptob64);
  72. if (empty($header->alg)) {
  73. throw new DomainException('Empty algorithm');
  74. }
  75. if (empty(self::$supported_algs[$header->alg])) {
  76. throw new DomainException('Algorithm not supported');
  77. }
  78. if (!is_array($allowed_algs) || !in_array($header->alg, $allowed_algs)) {
  79. throw new DomainException('Algorithm not allowed');
  80. }
  81. if (is_array($key) || $key instanceof \ArrayAccess) {
  82. if (isset($header->kid)) {
  83. $key = $key[$header->kid];
  84. } else {
  85. throw new DomainException('"kid" empty, unable to lookup correct key');
  86. }
  87. }
  88. // Check the signature
  89. if (!JWT::verify("$headb64.$bodyb64", $sig, $key, $header->alg)) {
  90. throw new SignatureInvalidException('Signature verification failed');
  91. }
  92. // Check if the nbf if it is defined. This is the time that the
  93. // token can actually be used. If it's not yet that time, abort.
  94. if (isset($payload->nbf) && $payload->nbf > (time() + self::$leeway)) {
  95. throw new BeforeValidException(
  96. 'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->nbf)
  97. );
  98. }
  99. // Check that this token has been created before 'now'. This prevents
  100. // using tokens that have been created for later use (and haven't
  101. // correctly used the nbf claim).
  102. if (isset($payload->iat) && $payload->iat > (time() + self::$leeway)) {
  103. throw new BeforeValidException(
  104. 'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->iat)
  105. );
  106. }
  107. // Check if this token has expired.
  108. if (isset($payload->exp) && (time() - self::$leeway) >= $payload->exp) {
  109. throw new ExpiredException('Expired token');
  110. }
  111. return $payload;
  112. }
  113. /**
  114. * Converts and signs a PHP object or array into a JWT string.
  115. *
  116. * @param object|array $payload PHP object or array
  117. * @param string $key The secret key.
  118. * If the algorithm used is asymmetric, this is the private key
  119. * @param string $alg The signing algorithm.
  120. * Supported algorithms are 'HS256', 'HS384', 'HS512' and 'RS256'
  121. * @param array $head An array with header elements to attach
  122. *
  123. * @return string A signed JWT
  124. *
  125. * @uses jsonEncode
  126. * @uses urlsafeB64Encode
  127. */
  128. public static function encode($payload, $key, $alg = 'HS256', $keyId = null, $head = null)
  129. {
  130. $header = array('typ' => 'JWT', 'alg' => $alg);
  131. if ($keyId !== null) {
  132. $header['kid'] = $keyId;
  133. }
  134. if ( isset($head) && is_array($head) ) {
  135. $header = array_merge($head, $header);
  136. }
  137. $segments = array();
  138. $segments[] = JWT::urlsafeB64Encode(JWT::jsonEncode($header));
  139. $segments[] = JWT::urlsafeB64Encode(JWT::jsonEncode($payload));
  140. $signing_input = implode('.', $segments);
  141. $signature = JWT::sign($signing_input, $key, $alg);
  142. $segments[] = JWT::urlsafeB64Encode($signature);
  143. return implode('.', $segments);
  144. }
  145. /**
  146. * Sign a string with a given key and algorithm.
  147. *
  148. * @param string $msg The message to sign
  149. * @param string|resource $key The secret key
  150. * @param string $alg The signing algorithm.
  151. * Supported algorithms are 'HS256', 'HS384', 'HS512' and 'RS256'
  152. *
  153. * @return string An encrypted message
  154. *
  155. * @throws DomainException Unsupported algorithm was specified
  156. */
  157. public static function sign($msg, $key, $alg = 'HS256')
  158. {
  159. if (empty(self::$supported_algs[$alg])) {
  160. throw new DomainException('Algorithm not supported');
  161. }
  162. list($function, $algorithm) = self::$supported_algs[$alg];
  163. switch($function) {
  164. case 'hash_hmac':
  165. return hash_hmac($algorithm, $msg, $key, true);
  166. case 'openssl':
  167. $signature = '';
  168. $success = openssl_sign($msg, $signature, $key, $algorithm);
  169. if (!$success) {
  170. throw new DomainException("OpenSSL unable to sign data");
  171. } else {
  172. return $signature;
  173. }
  174. }
  175. }
  176. /**
  177. * Verify a signature with the message, key and method. Not all methods
  178. * are symmetric, so we must have a separate verify and sign method.
  179. *
  180. * @param string $msg The original message (header and body)
  181. * @param string $signature The original signature
  182. * @param string|resource $key For HS*, a string key works. for RS*, must be a resource of an openssl public key
  183. * @param string $alg The algorithm
  184. *
  185. * @return bool
  186. *
  187. * @throws DomainException Invalid Algorithm or OpenSSL failure
  188. */
  189. private static function verify($msg, $signature, $key, $alg)
  190. {
  191. if (empty(self::$supported_algs[$alg])) {
  192. throw new DomainException('Algorithm not supported');
  193. }
  194. list($function, $algorithm) = self::$supported_algs[$alg];
  195. switch($function) {
  196. case 'openssl':
  197. $success = openssl_verify($msg, $signature, $key, $algorithm);
  198. if (!$success) {
  199. throw new DomainException("OpenSSL unable to verify data: " . openssl_error_string());
  200. } else {
  201. return $signature;
  202. }
  203. case 'hash_hmac':
  204. default:
  205. $hash = hash_hmac($algorithm, $msg, $key, true);
  206. if (function_exists('hash_equals')) {
  207. return hash_equals($signature, $hash);
  208. }
  209. $len = min(self::safeStrlen($signature), self::safeStrlen($hash));
  210. $status = 0;
  211. for ($i = 0; $i < $len; $i++) {
  212. $status |= (ord($signature[$i]) ^ ord($hash[$i]));
  213. }
  214. $status |= (self::safeStrlen($signature) ^ self::safeStrlen($hash));
  215. return ($status === 0);
  216. }
  217. }
  218. /**
  219. * Decode a JSON string into a PHP object.
  220. *
  221. * @param string $input JSON string
  222. *
  223. * @return object Object representation of JSON string
  224. *
  225. * @throws DomainException Provided string was invalid JSON
  226. */
  227. public static function jsonDecode($input)
  228. {
  229. if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  230. /** In PHP >=5.4.0, json_decode() accepts an options parameter, that allows you
  231. * to specify that large ints (like Steam Transaction IDs) should be treated as
  232. * strings, rather than the PHP default behaviour of converting them to floats.
  233. */
  234. $obj = json_decode($input, false, 512, JSON_BIGINT_AS_STRING);
  235. } else {
  236. /** Not all servers will support that, however, so for older versions we must
  237. * manually detect large ints in the JSON string and quote them (thus converting
  238. *them to strings) before decoding, hence the preg_replace() call.
  239. */
  240. $max_int_length = strlen((string) PHP_INT_MAX) - 1;
  241. $json_without_bigints = preg_replace('/:\s*(-?\d{'.$max_int_length.',})/', ': "$1"', $input);
  242. $obj = json_decode($json_without_bigints);
  243. }
  244. if (function_exists('json_last_error') && $errno = json_last_error()) {
  245. JWT::handleJsonError($errno);
  246. } elseif ($obj === null && $input !== 'null') {
  247. throw new DomainException('Null result with non-null input');
  248. }
  249. return $obj;
  250. }
  251. /**
  252. * Encode a PHP object into a JSON string.
  253. *
  254. * @param object|array $input A PHP object or array
  255. *
  256. * @return string JSON representation of the PHP object or array
  257. *
  258. * @throws DomainException Provided object could not be encoded to valid JSON
  259. */
  260. public static function jsonEncode($input)
  261. {
  262. $json = json_encode($input);
  263. if (function_exists('json_last_error') && $errno = json_last_error()) {
  264. JWT::handleJsonError($errno);
  265. } elseif ($json === 'null' && $input !== null) {
  266. throw new DomainException('Null result with non-null input');
  267. }
  268. return $json;
  269. }
  270. /**
  271. * Decode a string with URL-safe Base64.
  272. *
  273. * @param string $input A Base64 encoded string
  274. *
  275. * @return string A decoded string
  276. */
  277. public static function urlsafeB64Decode($input)
  278. {
  279. $remainder = strlen($input) % 4;
  280. if ($remainder) {
  281. $padlen = 4 - $remainder;
  282. $input .= str_repeat('=', $padlen);
  283. }
  284. return base64_decode(strtr($input, '-_', '+/'));
  285. }
  286. /**
  287. * Encode a string with URL-safe Base64.
  288. *
  289. * @param string $input The string you want encoded
  290. *
  291. * @return string The base64 encode of what you passed in
  292. */
  293. public static function urlsafeB64Encode($input)
  294. {
  295. return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
  296. }
  297. /**
  298. * Helper method to create a JSON error.
  299. *
  300. * @param int $errno An error number from json_last_error()
  301. *
  302. * @return void
  303. */
  304. private static function handleJsonError($errno)
  305. {
  306. $messages = array(
  307. JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
  308. JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
  309. JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON'
  310. );
  311. throw new DomainException(
  312. isset($messages[$errno])
  313. ? $messages[$errno]
  314. : 'Unknown JSON error: ' . $errno
  315. );
  316. }
  317. /**
  318. * Get the number of bytes in cryptographic strings.
  319. *
  320. * @param string
  321. *
  322. * @return int
  323. */
  324. private static function safeStrlen($str)
  325. {
  326. if (function_exists('mb_strlen')) {
  327. return mb_strlen($str, '8bit');
  328. }
  329. return strlen($str);
  330. }
  331. }