Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
jwt.php
1<?php
2namespace Bitrix\Main\Web;
3
4use \DomainException;
5use \InvalidArgumentException;
6use \UnexpectedValueException;
7use \DateTime;
8
22class JWT
23{
24 const ASN1_INTEGER = 0x02;
25 const ASN1_SEQUENCE = 0x10;
26 const ASN1_BIT_STRING = 0x03;
27
33 public static $leeway = 0;
34
41 public static $timestamp = null;
42
43 public static $supported_algs = array(
44 'ES256' => array('openssl', 'SHA256'),
45 'HS256' => array('hash_hmac', 'SHA256'),
46 'HS384' => array('hash_hmac', 'SHA384'),
47 'HS512' => array('hash_hmac', 'SHA512'),
48 'RS256' => array('openssl', 'SHA256'),
49 'RS384' => array('openssl', 'SHA384'),
50 'RS512' => array('openssl', 'SHA512'),
51 );
52
69 public static function decode($jwt, $key, array $allowed_algs = array())
70 {
71 $timestamp = is_null(static::$timestamp) ? time() : static::$timestamp;
72
73 if (empty($key)) {
74 throw new InvalidArgumentException('Key may not be empty');
75 }
76 $tks = explode('.', $jwt);
77 if (count($tks) != 3) {
78 throw new UnexpectedValueException('Wrong number of segments');
79 }
80 list($headb64, $bodyb64, $cryptob64) = $tks;
81 if (null === ($header = static::jsonDecode(static::urlsafeB64Decode($headb64)))) {
82 throw new UnexpectedValueException('Invalid header encoding');
83 }
84 if (null === $payload = static::jsonDecode(static::urlsafeB64Decode($bodyb64))) {
85 throw new UnexpectedValueException('Invalid claims encoding');
86 }
87 if (false === ($sig = static::urlsafeB64Decode($cryptob64))) {
88 throw new UnexpectedValueException('Invalid signature encoding');
89 }
90 if (empty($header->alg)) {
91 throw new UnexpectedValueException('Empty algorithm');
92 }
93 if (empty(static::$supported_algs[$header->alg])) {
94 throw new UnexpectedValueException('Algorithm not supported');
95 }
96 if (!in_array($header->alg, $allowed_algs)) {
97 throw new UnexpectedValueException('Algorithm not allowed');
98 }
99 if ($header->alg === 'ES256') {
100 // OpenSSL expects an ASN.1 DER sequence for ES256 signatures
101 $sig = self::signatureToDER($sig);
102 }
103
104 if (is_array($key) || $key instanceof \ArrayAccess) {
105 if (isset($header->kid)) {
106 if (!isset($key[$header->kid])) {
107 throw new UnexpectedValueException('"kid" invalid, unable to lookup correct key');
108 }
109 $key = $key[$header->kid];
110 } else {
111 throw new UnexpectedValueException('"kid" empty, unable to lookup correct key');
112 }
113 }
114
115 // Check the signature
116 if (!static::verify("$headb64.$bodyb64", $sig, $key, $header->alg)) {
117 throw new UnexpectedValueException('Signature verification failed');
118 }
119
120 // Check the nbf if it is defined. This is the time that the
121 // token can actually be used. If it's not yet that time, abort.
122 if (isset($payload->nbf) && $payload->nbf > ($timestamp + static::$leeway)) {
123 throw new UnexpectedValueException(
124 'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->nbf)
125 );
126 }
127
128 // Check that this token has been created before 'now'. This prevents
129 // using tokens that have been created for later use (and haven't
130 // correctly used the nbf claim).
131 if (isset($payload->iat) && $payload->iat > ($timestamp + static::$leeway)) {
132 throw new UnexpectedValueException(
133 'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->iat)
134 );
135 }
136
137 // Check if this token has expired.
138 if (isset($payload->exp) && ($timestamp - static::$leeway) >= $payload->exp) {
139 throw new UnexpectedValueException('Expired token');
140 }
141
142 return $payload;
143 }
144
161 public static function encode($payload, $key, $alg = 'HS256', $keyId = null, $head = null)
162 {
163 $header = array('typ' => 'JWT', 'alg' => $alg);
164 if ($keyId !== null) {
165 $header['kid'] = $keyId;
166 }
167 if (isset($head) && is_array($head)) {
168 $header = array_merge($head, $header);
169 }
170 $segments = array();
171 $segments[] = static::urlsafeB64Encode(static::jsonEncode($header));
172 $segments[] = static::urlsafeB64Encode(static::jsonEncode($payload));
173 $signing_input = implode('.', $segments);
174
175 $signature = static::sign($signing_input, $key, $alg);
176 $segments[] = static::urlsafeB64Encode($signature);
177
178 return implode('.', $segments);
179 }
180
193 public static function sign($msg, $key, $alg = 'HS256')
194 {
195 if (empty(static::$supported_algs[$alg])) {
196 throw new DomainException('Algorithm not supported');
197 }
198 list($function, $algorithm) = static::$supported_algs[$alg];
199 switch ($function) {
200 case 'hash_hmac':
201 return hash_hmac($algorithm, $msg, $key, true);
202 case 'openssl':
203 $signature = '';
204 $success = openssl_sign($msg, $signature, $key, $algorithm);
205 if (!$success) {
206 throw new DomainException("OpenSSL unable to sign data");
207 } else {
208 if ($alg === 'ES256') {
209 $signature = self::signatureFromDER($signature, 256);
210 }
211 return $signature;
212 }
213 }
214 }
215
229 private static function verify($msg, $signature, $key, $alg)
230 {
231 if (empty(static::$supported_algs[$alg])) {
232 throw new DomainException('Algorithm not supported');
233 }
234
235 list($function, $algorithm) = static::$supported_algs[$alg];
236 switch ($function) {
237 case 'openssl':
238 $success = openssl_verify($msg, $signature, $key, $algorithm);
239 if ($success === 1) {
240 return true;
241 } elseif ($success === 0) {
242 return false;
243 }
244 // returns 1 on success, 0 on failure, -1 on error.
245 throw new DomainException(
246 'OpenSSL error: ' . openssl_error_string()
247 );
248 case 'hash_hmac':
249 default:
250 $hash = hash_hmac($algorithm, $msg, $key, true);
251 if (function_exists('hash_equals')) {
252 return hash_equals($signature, $hash);
253 }
254 $len = min(strlen($signature), strlen($hash));
255
256 $status = 0;
257 for ($i = 0; $i < $len; $i++) {
258 $status |= (ord($signature[$i]) ^ ord($hash[$i]));
259 }
260 $status |= (strlen($signature) ^ strlen($hash));
261
262 return ($status === 0);
263 }
264 }
265
275 public static function jsonDecode($input)
276 {
277 if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
282 $obj = json_decode($input, false, 512, JSON_BIGINT_AS_STRING);
283 } else {
288 $max_int_length = strlen((string) PHP_INT_MAX) - 1;
289 $json_without_bigints = preg_replace('/:\s*(-?\d{'.$max_int_length.',})/', ': "$1"', $input);
290 $obj = json_decode($json_without_bigints);
291 }
292
293 if ($errno = json_last_error()) {
294 static::handleJsonError($errno);
295 } elseif ($obj === null && $input !== 'null') {
296 throw new DomainException('Null result with non-null input');
297 }
298 return $obj;
299 }
300
310 public static function jsonEncode($input)
311 {
312 $json = json_encode($input);
313 if ($errno = json_last_error()) {
314 static::handleJsonError($errno);
315 } elseif ($json === 'null' && $input !== null) {
316 throw new DomainException('Null result with non-null input');
317 }
318 return $json;
319 }
320
328 public static function urlsafeB64Decode($input)
329 {
330 $remainder = strlen($input) % 4;
331 if ($remainder) {
332 $padlen = 4 - $remainder;
333 $input .= str_repeat('=', $padlen);
334 }
335 return base64_decode(strtr($input, '-_', '+/'));
336 }
337
345 public static function urlsafeB64Encode($input)
346 {
347 return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
348 }
349
357 private static function handleJsonError($errno)
358 {
359 $messages = array(
360 JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
361 JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON',
362 JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
363 JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON',
364 JSON_ERROR_UTF8 => 'Malformed UTF-8 characters' //PHP >= 5.3.3
365 );
366 throw new DomainException(
367 $messages[$errno] ?? 'Unknown JSON error: '.$errno
368 );
369 }
370
377 private static function signatureToDER($sig)
378 {
379 // Separate the signature into r-value and s-value
380 list($r, $s) = str_split($sig, (int) (strlen($sig) / 2));
381
382 // Trim leading zeros
383 $r = ltrim($r, "\x00");
384 $s = ltrim($s, "\x00");
385
386 // Convert r-value and s-value from unsigned big-endian integers to
387 // signed two's complement
388 if (ord($r[0]) > 0x7f) {
389 $r = "\x00" . $r;
390 }
391 if (ord($s[0]) > 0x7f) {
392 $s = "\x00" . $s;
393 }
394
395 return self::encodeDER(
396 self::ASN1_SEQUENCE,
397 self::encodeDER(self::ASN1_INTEGER, $r) .
398 self::encodeDER(self::ASN1_INTEGER, $s)
399 );
400 }
401
409 private static function encodeDER($type, $value)
410 {
411 $tag_header = 0;
412 if ($type === self::ASN1_SEQUENCE) {
413 $tag_header |= 0x20;
414 }
415
416 // Type
417 $der = chr($tag_header | $type);
418
419 // Length
420 $der .= chr(strlen($value));
421
422 return $der . $value;
423 }
424
432 private static function signatureFromDER($der, $keySize)
433 {
434 // OpenSSL returns the ECDSA signatures as a binary ASN.1 DER SEQUENCE
435 list($offset, $_) = self::readDER($der);
436 list($offset, $r) = self::readDER($der, $offset);
437 list($offset, $s) = self::readDER($der, $offset);
438
439 // Convert r-value and s-value from signed two's compliment to unsigned
440 // big-endian integers
441 $r = ltrim($r, "\x00");
442 $s = ltrim($s, "\x00");
443
444 // Pad out r and s so that they are $keySize bits long
445 $r = str_pad($r, $keySize / 8, "\x00", STR_PAD_LEFT);
446 $s = str_pad($s, $keySize / 8, "\x00", STR_PAD_LEFT);
447
448 return $r . $s;
449 }
450
459 private static function readDER($der, $offset = 0)
460 {
461 $pos = $offset;
462 $size = strlen($der);
463 $constructed = (ord($der[$pos]) >> 5) & 0x01;
464 $type = ord($der[$pos++]) & 0x1f;
465
466 // Length
467 $len = ord($der[$pos++]);
468 if ($len & 0x80) {
469 $n = $len & 0x1f;
470 $len = 0;
471 while ($n-- && $pos < $size) {
472 $len = ($len << 8) | ord($der[$pos++]);
473 }
474 }
475
476 // Value
477 if ($type == self::ASN1_BIT_STRING) {
478 $pos++; // Skip the first contents octet (padding indicator)
479 $data = substr($der, $pos, $len - 1);
480 $pos += $len - 1;
481 } elseif (!$constructed) {
482 $data = substr($der, $pos, $len);
483 $pos += $len;
484 } else {
485 $data = null;
486 }
487
488 return array($pos, $data);
489 }
490}
static jsonDecode($input)
Definition jwt.php:275
static urlsafeB64Encode($input)
Definition jwt.php:345
static $timestamp
Definition jwt.php:41
static decode($jwt, $key, array $allowed_algs=array())
Definition jwt.php:69
const ASN1_BIT_STRING
Definition jwt.php:26
const ASN1_SEQUENCE
Definition jwt.php:25
static urlsafeB64Decode($input)
Definition jwt.php:328
const ASN1_INTEGER
Definition jwt.php:24
static jsonEncode($input)
Definition jwt.php:310
static encode($payload, $key, $alg='HS256', $keyId=null, $head=null)
Definition jwt.php:161
static $supported_algs
Definition jwt.php:43
static $leeway
Definition jwt.php:33
static sign($msg, $key, $alg='HS256')
Definition jwt.php:193