Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

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