| 1 |
<?php |
| 2 |
|
| 3 |
namespace Firebase\JWT; |
| 4 |
use \DomainException; |
| 5 |
use \InvalidArgumentException; |
| 6 |
use \UnexpectedValueException; |
| 7 |
use \DateTime; |
| 8 |
|
| 9 |
/** |
| 10 |
* JSON Web Token implementation, based on this spec: |
| 11 |
* https://tools.ietf.org/html/rfc7519 |
| 12 |
* |
| 13 |
* PHP version 5 |
| 14 |
* |
| 15 |
* @category Authentication |
| 16 |
* @package Authentication_JWT |
| 17 |
* @author Neuman Vong <neuman@twilio.com> |
| 18 |
* @author Anant Narayanan <anant@php.net> |
| 19 |
* @license http://opensource.org/licenses/BSD-3-Clause 3-clause BSD |
| 20 |
* @link https://github.com/firebase/php-jwt |
| 21 |
*/ |
| 22 |
class JWT { |
| 23 |
|
| 24 |
|
| 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 = 0; |
| 31 |
|
| 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 |
|
| 40 |
public static $supported_algs = array( |
| 41 |
'HS256' => array( 'hash_hmac', 'SHA256' ), |
| 42 |
'HS512' => array( 'hash_hmac', 'SHA512' ), |
| 43 |
'HS384' => array( 'hash_hmac', 'SHA384' ), |
| 44 |
'RS256' => array( 'openssl', 'SHA256' ), |
| 45 |
'RS384' => array( 'openssl', 'SHA384' ), |
| 46 |
'RS512' => array( 'openssl', 'SHA512' ), |
| 47 |
); |
| 48 |
|
| 49 |
/** |
| 50 |
* Decodes a JWT string into a PHP object. |
| 51 |
* |
| 52 |
* @param string $jwt The JWT |
| 53 |
* @param string|array $key The key, or map of keys. |
| 54 |
* If the algorithm used is asymmetric, this is the public key |
| 55 |
* @param array $allowed_algs List of supported verification algorithms |
| 56 |
* Supported algorithms are 'HS256', 'HS384', 'HS512' and 'RS256' |
| 57 |
* |
| 58 |
* @return object The JWT's payload as a PHP object |
| 59 |
* |
| 60 |
* @throws UnexpectedValueException Provided JWT was invalid |
| 61 |
* @throws SignatureInvalidException Provided JWT was invalid because the signature verification failed |
| 62 |
* @throws BeforeValidException Provided JWT is trying to be used before it's eligible as defined by 'nbf' |
| 63 |
* @throws BeforeValidException Provided JWT is trying to be used before it's been created as defined by 'iat' |
| 64 |
* @throws ExpiredException Provided JWT has since expired, as defined by the 'exp' claim |
| 65 |
* |
| 66 |
* @uses jsonDecode |
| 67 |
* @uses urlsafeB64Decode |
| 68 |
*/ |
| 69 |
public static function decode( $jwt, $key, array $allowed_algs = array() ) { |
| 70 |
$timestamp = is_null( static::$timestamp ) ? time() : static::$timestamp; |
| 71 |
|
| 72 |
if ( empty( $key ) ) { |
| 73 |
throw new InvalidArgumentException( 'Key may not be empty' ); |
| 74 |
} |
| 75 |
$tks = explode( '.', $jwt ); |
| 76 |
if ( count( $tks ) != 3 ) { |
| 77 |
throw new UnexpectedValueException( 'Wrong number of segments' ); |
| 78 |
} |
| 79 |
list($headb64, $bodyb64, $cryptob64) = $tks; |
| 80 |
if ( null === ( $header = static::jsonDecode( static::urlsafeB64Decode( $headb64 ) ) ) ) { |
| 81 |
throw new UnexpectedValueException( 'Invalid header encoding' ); |
| 82 |
} |
| 83 |
if ( null === $payload = static::jsonDecode( static::urlsafeB64Decode( $bodyb64 ) ) ) { |
| 84 |
throw new UnexpectedValueException( 'Invalid claims encoding' ); |
| 85 |
} |
| 86 |
if ( false === ( $sig = static::urlsafeB64Decode( $cryptob64 ) ) ) { |
| 87 |
throw new UnexpectedValueException( 'Invalid signature encoding' ); |
| 88 |
} |
| 89 |
if ( empty( $header->alg ) ) { |
| 90 |
throw new UnexpectedValueException( 'Empty algorithm' ); |
| 91 |
} |
| 92 |
if ( empty( static::$supported_algs[ $header->alg ] ) ) { |
| 93 |
throw new UnexpectedValueException( 'Algorithm not supported' ); |
| 94 |
} |
| 95 |
if ( ! in_array( $header->alg, $allowed_algs ) ) { |
| 96 |
throw new UnexpectedValueException( 'Algorithm not allowed' ); |
| 97 |
} |
| 98 |
if ( is_array( $key ) || $key instanceof \ArrayAccess ) { |
| 99 |
if ( isset( $header->kid ) ) { |
| 100 |
if ( ! isset( $key[ $header->kid ] ) ) { |
| 101 |
throw new UnexpectedValueException( '"kid" invalid, unable to lookup correct key' ); |
| 102 |
} |
| 103 |
$key = $key[ $header->kid ]; |
| 104 |
} else { |
| 105 |
throw new UnexpectedValueException( '"kid" empty, unable to lookup correct key' ); |
| 106 |
} |
| 107 |
} |
| 108 |
|
| 109 |
// Check the signature |
| 110 |
if ( ! static::verify( "$headb64.$bodyb64", $sig, $key, $header->alg ) ) { |
| 111 |
throw new SignatureInvalidException( 'Signature verification failed' ); |
| 112 |
} |
| 113 |
|
| 114 |
// Check if 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 |
|
| 122 |
// Check that this token has been created before 'now'. This prevents |
| 123 |
// using tokens that have been created for later use (and haven't |
| 124 |
// correctly used the nbf claim). |
| 125 |
if ( isset( $payload->iat ) && $payload->iat > ( $timestamp + static::$leeway ) ) { |
| 126 |
throw new BeforeValidException( |
| 127 |
'Cannot handle token prior to ' . date( DateTime::ISO8601, $payload->iat ) |
| 128 |
); |
| 129 |
} |
| 130 |
|
| 131 |
// Check if this token has expired. |
| 132 |
if ( isset( $payload->exp ) && ( $timestamp - static::$leeway ) >= $payload->exp ) { |
| 133 |
throw new ExpiredException( 'Expired token' ); |
| 134 |
} |
| 135 |
|
| 136 |
return $payload; |
| 137 |
} |
| 138 |
|
| 139 |
/** |
| 140 |
* Converts and signs a PHP object or array into a JWT string. |
| 141 |
* |
| 142 |
* @param object|array $payload PHP object or array |
| 143 |
* @param string $key The secret key. |
| 144 |
* If the algorithm used is asymmetric, this is the private key |
| 145 |
* @param string $alg The signing algorithm. |
| 146 |
* Supported algorithms are 'HS256', 'HS384', 'HS512' and 'RS256' |
| 147 |
* @param mixed $keyId |
| 148 |
* @param array $head An array with header elements to attach |
| 149 |
* |
| 150 |
* @return string A signed JWT |
| 151 |
* |
| 152 |
* @uses jsonEncode |
| 153 |
* @uses urlsafeB64Encode |
| 154 |
*/ |
| 155 |
public static function encode( $payload, $key, $alg = 'HS256', $keyId = null, $head = null ) { |
| 156 |
$header = array( |
| 157 |
'typ' => 'JWT', |
| 158 |
'alg' => $alg, |
| 159 |
); |
| 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 |
|
| 171 |
$signature = static::sign( $signing_input, $key, $alg ); |
| 172 |
$segments[] = static::urlsafeB64Encode( $signature ); |
| 173 |
|
| 174 |
return implode( '.', $segments ); |
| 175 |
} |
| 176 |
|
| 177 |
/** |
| 178 |
* Sign a string with a given key and algorithm. |
| 179 |
* |
| 180 |
* @param string $msg The message to sign |
| 181 |
* @param string|resource $key The secret key |
| 182 |
* @param string $alg The signing algorithm. |
| 183 |
* Supported algorithms are 'HS256', 'HS384', 'HS512' and 'RS256' |
| 184 |
* |
| 185 |
* @return string An encrypted message |
| 186 |
* |
| 187 |
* @throws DomainException Unsupported algorithm was specified |
| 188 |
*/ |
| 189 |
public static function sign( $msg, $key, $alg = 'HS256' ) { |
| 190 |
if ( empty( static::$supported_algs[ $alg ] ) ) { |
| 191 |
throw new DomainException( 'Algorithm not supported' ); |
| 192 |
} |
| 193 |
list($function, $algorithm) = static::$supported_algs[ $alg ]; |
| 194 |
switch ( $function ) { |
| 195 |
case 'hash_hmac': |
| 196 |
return hash_hmac( $algorithm, $msg, $key, true ); |
| 197 |
case 'openssl': |
| 198 |
$signature = ''; |
| 199 |
$success = openssl_sign( $msg, $signature, $key, $algorithm ); |
| 200 |
if ( ! $success ) { |
| 201 |
throw new DomainException( 'OpenSSL unable to sign data' ); |
| 202 |
} else { |
| 203 |
return $signature; |
| 204 |
} |
| 205 |
} |
| 206 |
} |
| 207 |
|
| 208 |
/** |
| 209 |
* Verify a signature with the message, key and method. Not all methods |
| 210 |
* are symmetric, so we must have a separate verify and sign method. |
| 211 |
* |
| 212 |
* @param string $msg The original message (header and body) |
| 213 |
* @param string $signature The original signature |
| 214 |
* @param string|resource $key For HS*, a string key works. for RS*, must be a resource of an openssl public key |
| 215 |
* @param string $alg The algorithm |
| 216 |
* |
| 217 |
* @return bool |
| 218 |
* |
| 219 |
* @throws DomainException Invalid Algorithm or OpenSSL failure |
| 220 |
*/ |
| 221 |
private static function verify( $msg, $signature, $key, $alg ) { |
| 222 |
if ( empty( static::$supported_algs[ $alg ] ) ) { |
| 223 |
throw new DomainException( 'Algorithm not supported' ); |
| 224 |
} |
| 225 |
|
| 226 |
list($function, $algorithm) = static::$supported_algs[ $alg ]; |
| 227 |
switch ( $function ) { |
| 228 |
case 'openssl': |
| 229 |
$success = openssl_verify( $msg, $signature, $key, $algorithm ); |
| 230 |
if ( $success === 1 ) { |
| 231 |
return true; |
| 232 |
} elseif ( $success === 0 ) { |
| 233 |
return false; |
| 234 |
} |
| 235 |
// returns 1 on success, 0 on failure, -1 on error. |
| 236 |
throw new DomainException( |
| 237 |
'OpenSSL error: ' . openssl_error_string() |
| 238 |
); |
| 239 |
case 'hash_hmac': |
| 240 |
default: |
| 241 |
$hash = hash_hmac( $algorithm, $msg, $key, true ); |
| 242 |
if ( function_exists( 'hash_equals' ) ) { |
| 243 |
return hash_equals( $signature, $hash ); |
| 244 |
} |
| 245 |
$len = min( static::safeStrlen( $signature ), static::safeStrlen( $hash ) ); |
| 246 |
|
| 247 |
$status = 0; |
| 248 |
for ( $i = 0; $i < $len; $i++ ) { |
| 249 |
$status |= ( ord( $signature[ $i ] ) ^ ord( $hash[ $i ] ) ); |
| 250 |
} |
| 251 |
$status |= ( static::safeStrlen( $signature ) ^ static::safeStrlen( $hash ) ); |
| 252 |
|
| 253 |
return ( $status === 0 ); |
| 254 |
} |
| 255 |
} |
| 256 |
|
| 257 |
/** |
| 258 |
* Decode a JSON string into a PHP object. |
| 259 |
* |
| 260 |
* @param string $input JSON string |
| 261 |
* |
| 262 |
* @return object Object representation of JSON string |
| 263 |
* |
| 264 |
* @throws DomainException Provided string was invalid JSON |
| 265 |
*/ |
| 266 |
public static function jsonDecode( $input ) { |
| 267 |
if ( version_compare( PHP_VERSION, '5.4.0', '>=' ) && ! ( defined( 'JSON_C_VERSION' ) && PHP_INT_SIZE > 4 ) ) { |
| 268 |
/** In PHP >=5.4.0, json_decode() accepts an options parameter, that allows you |
| 269 |
* to specify that large ints (like Steam Transaction IDs) should be treated as |
| 270 |
* strings, rather than the PHP default behaviour of converting them to floats. |
| 271 |
*/ |
| 272 |
$obj = json_decode( $input, false, 512, JSON_BIGINT_AS_STRING ); |
| 273 |
} else { |
| 274 |
/** Not all servers will support that, however, so for older versions we must |
| 275 |
* manually detect large ints in the JSON string and quote them (thus converting |
| 276 |
*them to strings) before decoding, hence the preg_replace() call. |
| 277 |
*/ |
| 278 |
$max_int_length = strlen( (string) PHP_INT_MAX ) - 1; |
| 279 |
$json_without_bigints = preg_replace( '/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $input ); |
| 280 |
$obj = json_decode( $json_without_bigints ); |
| 281 |
} |
| 282 |
|
| 283 |
if ( function_exists( 'json_last_error' ) && $errno = json_last_error() ) { |
| 284 |
static::handleJsonError( $errno ); |
| 285 |
} elseif ( $obj === null && $input !== 'null' ) { |
| 286 |
throw new DomainException( 'Null result with non-null input' ); |
| 287 |
} |
| 288 |
return $obj; |
| 289 |
} |
| 290 |
|
| 291 |
/** |
| 292 |
* Encode a PHP object into a JSON string. |
| 293 |
* |
| 294 |
* @param object|array $input A PHP object or array |
| 295 |
* |
| 296 |
* @return string JSON representation of the PHP object or array |
| 297 |
* |
| 298 |
* @throws DomainException Provided object could not be encoded to valid JSON |
| 299 |
*/ |
| 300 |
public static function jsonEncode( $input ) { |
| 301 |
$json = json_encode( $input ); |
| 302 |
if ( function_exists( 'json_last_error' ) && $errno = json_last_error() ) { |
| 303 |
static::handleJsonError( $errno ); |
| 304 |
} elseif ( $json === 'null' && $input !== null ) { |
| 305 |
throw new DomainException( 'Null result with non-null input' ); |
| 306 |
} |
| 307 |
return $json; |
| 308 |
} |
| 309 |
|
| 310 |
/** |
| 311 |
* Decode a string with URL-safe Base64. |
| 312 |
* |
| 313 |
* @param string $input A Base64 encoded string |
| 314 |
* |
| 315 |
* @return string A decoded string |
| 316 |
*/ |
| 317 |
public static function urlsafeB64Decode( $input ) { |
| 318 |
$remainder = strlen( $input ) % 4; |
| 319 |
if ( $remainder ) { |
| 320 |
$padlen = 4 - $remainder; |
| 321 |
$input .= str_repeat( '=', $padlen ); |
| 322 |
} |
| 323 |
return base64_decode( strtr( $input, '-_', '+/' ) ); |
| 324 |
} |
| 325 |
|
| 326 |
/** |
| 327 |
* Encode a string with URL-safe Base64. |
| 328 |
* |
| 329 |
* @param string $input The string you want encoded |
| 330 |
* |
| 331 |
* @return string The base64 encode of what you passed in |
| 332 |
*/ |
| 333 |
public static function urlsafeB64Encode( $input ) { |
| 334 |
return str_replace( '=', '', strtr( base64_encode( $input ), '+/', '-_' ) ); |
| 335 |
} |
| 336 |
|
| 337 |
/** |
| 338 |
* Helper method to create a JSON error. |
| 339 |
* |
| 340 |
* @param int $errno An error number from json_last_error() |
| 341 |
* |
| 342 |
* @return void |
| 343 |
*/ |
| 344 |
private static function handleJsonError( $errno ) { |
| 345 |
$messages = array( |
| 346 |
JSON_ERROR_DEPTH => 'Maximum stack depth exceeded', |
| 347 |
JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON', |
| 348 |
JSON_ERROR_CTRL_CHAR => 'Unexpected control character found', |
| 349 |
JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON', |
| 350 |
JSON_ERROR_UTF8 => 'Malformed UTF-8 characters', //PHP >= 5.3.3 |
| 351 |
); |
| 352 |
throw new DomainException( |
| 353 |
isset( $messages[ $errno ] ) |
| 354 |
? $messages[ $errno ] |
| 355 |
: 'Unknown JSON error: ' . $errno |
| 356 |
); |
| 357 |
} |
| 358 |
|
| 359 |
/** |
| 360 |
* Get the number of bytes in cryptographic strings. |
| 361 |
* |
| 362 |
* @param string |
| 363 |
* |
| 364 |
* @return int |
| 365 |
*/ |
| 366 |
private static function safeStrlen( $str ) { |
| 367 |
if ( function_exists( 'mb_strlen' ) ) { |
| 368 |
return mb_strlen( $str, '8bit' ); |
| 369 |
} |
| 370 |
return strlen( $str ); |
| 371 |
} |
| 372 |
} |
| 373 |
|