Subversion Repositories oidplus

Rev

Go to most recent revision | Blame | Last modification | View Log | RSS feed

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