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