-
Notifications
You must be signed in to change notification settings - Fork 108
/
Parser.php
695 lines (647 loc) · 20.9 KB
/
Parser.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
<?php
declare(strict_types=1);
namespace ParagonIE\Paseto;
use Exception;
use ParagonIE\ConstantTime\Binary;
use ParagonIE\Paseto\Exception\{EncodingException,
ExceptionCode,
InvalidKeyException,
InvalidPurposeException,
InvalidVersionException,
NotFoundException,
PasetoException,
RuleViolation,
SecurityException};
use ParagonIE\Paseto\Keys\{Base\AsymmetricPublicKey, Base\SymmetricKey};
use ParagonIE\Paseto\Parsing\{NonExpiringSupport, PasetoMessage};
use ParagonIE\Paseto\Rules\NotExpired;
use ParagonIE\Paseto\Traits\RegisteredClaims;
use Throwable;
use TypeError;
use function get_class;
use function is_array;
use function is_null;
use function is_string;
use function json_decode;
use function json_encode;
/**
* Class Parser
* @package ParagonIE\Paseto
*/
class Parser extends PasetoBase
{
use NonExpiringSupport;
use RegisteredClaims;
/** @var ProtocolCollection */
protected ProtocolCollection $allowedVersions;
/** @var string $implicitAssertions */
protected string $implicitAssertions = '';
/** @var ?ReceivingKey $key */
protected ?ReceivingKey $key = null;
/** @var ?int $maxClaimCount */
protected ?int $maxClaimCount = null;
/** @var ?int<1, 2147483647> $maxClaimDepth */
protected ?int $maxClaimDepth = null;
/** @var ?int $maxJsonLength */
protected ?int $maxJsonLength = null;
/** @var Purpose|null $purpose */
protected ?Purpose $purpose;
/** @var array<int, ValidationRuleInterface> */
protected array $rules = [];
/**
* Parser constructor.
*
* @param ProtocolCollection|null $allowedVersions
* @param Purpose|null $purpose
* @param ReceivingKey|null $key
* @param array<int, ValidationRuleInterface> $parserRules
*
* @throws PasetoException
*/
public function __construct(
ProtocolCollection $allowedVersions = null,
Purpose $purpose = null,
ReceivingKey $key = null,
array $parserRules = []
) {
$this->allowedVersions = $allowedVersions ?? ProtocolCollection::default();
$this->purpose = $purpose;
if (!is_null($key)) {
$this->setKey($key, true);
}
if (!empty($parserRules)) {
foreach ($parserRules as $rule) {
if ($rule instanceof ValidationRuleInterface) {
$this->addRule($rule);
}
}
}
}
/**
* Get the configured implicit assertions.
*
* @return array
* @throws EncodingException
*/
public function getImplicitAssertions(): array
{
if (empty($this->implicitAssertions)) {
return [];
}
$decoded = json_decode($this->implicitAssertions, true);
if (!is_array($decoded)) {
throw new EncodingException(
'Implicit Assertion string is not a valid JSON object',
ExceptionCode::FOOTER_JSON_ERROR
);
}
return $decoded;
}
/**
* Extract a footer from the PASETO message, as a string.
*
* @param string $tainted
* @return string
*
* @throws InvalidPurposeException
* @throws PasetoException
* @throws SecurityException
* @throws TypeError
*/
public static function extractFooter(string $tainted): string
{
return PasetoMessage::fromString($tainted)->footer();
}
/**
* Get a Parser instance intended for local usage.
* (i.e. shard-key authenticated encryption)
*
* @param SymmetricKey $key
* @param ProtocolCollection|null $allowedVersions
* @return self
*
* @throws PasetoException
*/
public static function getLocal(
SymmetricKey $key,
ProtocolCollection $allowedVersions = null
): self {
return new self(
$allowedVersions ?? ProtocolCollection::default(),
Purpose::local(),
$key
);
}
/**
* Get a Parser instance intended for local usage.
* (i.e. shard-key authenticated encryption)
*
* @param ReceivingKeyRing $key
* @param ProtocolCollection|null $allowedVersions
* @return self
*
* @throws PasetoException
*/
public static function getLocalWithKeyRing(
ReceivingKeyRing $key,
ProtocolCollection $allowedVersions = null
): self {
return new self(
$allowedVersions ?? ProtocolCollection::default(),
Purpose::local(),
$key
);
}
/**
* Get a Parser instance intended for remote usage.
* (i.e. public-key digital signatures).
*
* @param AsymmetricPublicKey $key
* @param ProtocolCollection|null $allowedVersions
* @return self
*
* @throws PasetoException
*/
public static function getPublic(
AsymmetricPublicKey $key,
ProtocolCollection $allowedVersions = null
): self {
return new self(
$allowedVersions ?? ProtocolCollection::default(),
Purpose::public(),
$key
);
}
/**
* Get a Parser instance intended for remote usage.
* (i.e. public-key digital signatures).
*
* @param ReceivingKeyRing $key
* @param ProtocolCollection|null $allowedVersions
* @return self
*
* @throws PasetoException
*/
public static function getPublicWithKeyRing(
ReceivingKeyRing $key,
ProtocolCollection $allowedVersions = null
): self {
return new self(
$allowedVersions ?? ProtocolCollection::default(),
Purpose::public(),
$key
);
}
/**
* Add a validation rule to be invoked by parse().
*
* @param ValidationRuleInterface $rule
* @return self
*/
public function addRule(ValidationRuleInterface $rule): self
{
$this->rules[] = $rule;
return $this;
}
/**
* If our footer contains a JSON payload, first perform the necessary safety checks
* (string length, number of keys, recursive depth) before attempting json_decode().
*
* If we end up with a valid payload, and a Key ID (`kid`) is defined, return that.
*
* Empty / non-JSON payloads result in an empty string.
* Malformed or unsafe JSON payloads result in an Exception being thrown.
* Missing `kid` results in an empty string.
* A non-string `kid` results in an empty string.
* Otherwise, return the `kid` to the caller.
*
* @ref https://github.com/paseto-standard/paseto-spec/blob/master/docs/02-Implementation-Guide/01-Payload-Processing.md#storing-json-in-the-footer
*
* @param string $data
* @return string
*
* @throws EncodingException
* @throws SecurityException
*/
public function extractKeyIdFromFooterJson(string $data): string
{
$length = Binary::safeStrlen($data);
if ($length < 6) {
// Too short to be JSON
return '';
}
if ($data[0] !== '{' || $data[$length - 1] !== '}') {
// Not JSON
return '';
}
// Perform safety checks before invoking json_decode()
if (!is_null($this->maxJsonLength) && $length > $this->maxJsonLength) {
throw new SecurityException(
"Footer JSON is too long",
ExceptionCode::FOOTER_JSON_ERROR
);
}
if (!is_null($this->maxClaimDepth)) {
if (Util::calculateJsonDepth($data) > $this->maxClaimDepth) {
throw new SecurityException(
"Footer JSON is has too much recursion",
ExceptionCode::FOOTER_JSON_ERROR
);
}
}
if (!is_null($this->maxClaimCount)) {
if (Util::countJsonKeys($data) > $this->maxClaimCount) {
throw new SecurityException(
"Footer JSON is has too many keys",
ExceptionCode::FOOTER_JSON_ERROR
);
}
}
$decoded = json_decode($data, true, $this->maxClaimDepth ?? 512);
if (!is_array($decoded)) {
return '';
}
// No key id -> ''
$index = (string) static::KEY_ID_FOOTER_CLAIM;
if (!isset($decoded[$index])) {
return '';
}
// Non-string in key id -> ''
if (!is_string($decoded[$index])) {
return '';
}
return $decoded[$index];
}
/**
* Fetch a key (either from $this->key directly, or by its Key ID if we've
* stored a KeyRing), then make sure it's an Asymmetric Public Key.
*
* @param string $keyId
*
* @return AsymmetricPublicKey
* @throws InvalidKeyException
* @throws NotFoundException
* @throws PasetoException
*/
public function fetchPublicKey(string $keyId = ''): AsymmetricPublicKey
{
if ($this->key instanceof ReceivingKeyRing) {
$key = $this->key->fetchKey($keyId);
} else {
$key = $this->key;
}
if (!($key instanceof AsymmetricPublicKey)) {
throw new InvalidKeyException(
"Only symmetric keys can be used for local tokens.",
ExceptionCode::PURPOSE_WRONG_FOR_KEY
);
}
return $key;
}
/**
* Fetch a key (either from $this->key directly, or by its Key ID if we've
* stored a KeyRing), then make sure it's a Symmetric Key.
*
* @param string $keyId
*
* @return SymmetricKey
* @throws InvalidKeyException
* @throws NotFoundException
* @throws PasetoException
*/
public function fetchSymmetricKey(string $keyId = ''): SymmetricKey
{
if ($this->key instanceof ReceivingKeyRing) {
$key = $this->key->fetchKey($keyId);
} else {
$key = $this->key;
}
if (!($key instanceof SymmetricKey)) {
throw new InvalidKeyException(
"Only symmetric keys can be used for local tokens.",
ExceptionCode::PURPOSE_WRONG_FOR_KEY
);
}
return $key;
}
/**
* Parse a string into a JsonToken object.
*
* @param string $tainted Tainted user-provided string.
* @param bool $skipValidation Don't validate according to the Rules.
* (Does not disable cryptographic security.)
* @return JsonToken
*
* @throws PasetoException
* @throws TypeError
*/
public function parse(string $tainted, bool $skipValidation = false): JsonToken
{
$parsed = PasetoMessage::fromString($tainted);
// First, check against the user's specified list of allowed versions.
$protocol = $parsed->header()->protocol();
if (!$this->allowedVersions->has($protocol)) {
throw new InvalidVersionException(
'Disallowed or unsupported version',
ExceptionCode::BAD_VERSION
);
}
/** @var Purpose $purpose */
$footer = $parsed->footer();
$purpose = $parsed->header()->purpose();
// $this->purpose is not mandatory, but if it's set, verify against it.
if (isset($this->purpose)) {
if (!$this->purpose->equals($purpose)) {
throw new InvalidPurposeException(
'Disallowed or unsupported purpose',
ExceptionCode::PURPOSE_WRONG_FOR_PARSER
);
}
}
if (!($this->key instanceof ReceivingKeyRing) && !is_null($this->key)) {
if (!$purpose->isReceivingKeyValid($this->key)) {
throw new InvalidKeyException(
'Invalid key type',
ExceptionCode::PASETO_KEY_TYPE_ERROR
);
}
}
$implicit = '';
if (!empty($this->implicitAssertions)) {
if (!$protocol::supportsImplicitAssertions()) {
throw new PasetoException(
'This version does not support implicit assertions',
ExceptionCode::IMPLICIT_ASSERTION_NOT_SUPPORTED
);
}
$implicit = $this->implicitAssertions;
}
$keyId = $this->extractKeyIdFromFooterJson($footer);
/** @var string|null $decoded */
// Let's verify/decode according to the appropriate method:
switch ($purpose) {
case Purpose::local():
// A symmetric key is, by type-safety, suitable for local tokens
$key = $this->fetchSymmetricKey($keyId);
try {
$decoded = $protocol::decrypt($tainted, $key, $footer, $implicit);
} catch (Throwable $ex) {
throw new PasetoException(
'An error occurred',
ExceptionCode::UNSPECIFIED_CRYPTOGRAPHIC_ERROR,
$ex
);
}
break;
case Purpose::public():
// An asymmetric public key is, by type-safety, suitable for public tokens
$key = $this->fetchPublicKey($keyId);
try {
$decoded = $protocol::verify($tainted, $key, $footer, $implicit);
} catch (Throwable $ex) {
throw new PasetoException(
'An error occurred',
ExceptionCode::UNSPECIFIED_CRYPTOGRAPHIC_ERROR,
$ex
);
}
break;
}
// Did we get data?
if (!isset($decoded)) {
throw new PasetoException(
'Unsupported purpose or version.',
ExceptionCode::PURPOSE_NOT_LOCAL_OR_PUBLIC
);
}
// Throw if the claims were invalid:
$this->throwIfClaimsJsonInvalid($decoded);
/** @var array<string, mixed>|bool $claims */
$claims = json_decode($decoded, true, ($this->maxClaimDepth ?? 512));
if (!is_array($claims)) {
throw new EncodingException(
'Not a JSON token.',
ExceptionCode::PAYLOAD_JSON_ERROR
);
}
// Let's build the token object.
$token = (new JsonToken())
->setFooter($footer)
->setClaims($claims);
if (!$skipValidation) {
// Validate all the rules that were specified:
$this->validate($token, true);
}
return $token;
}
/**
* Which protocol versions to permit.
*
* @param ProtocolCollection $allowlist
* @return self
*/
public function setAllowedVersions(ProtocolCollection $allowlist): self
{
$this->allowedVersions = $allowlist;
return $this;
}
/**
* Set the implicit assertions for the constructed PASETO token
* (only affects v3/v4).
*
* @param array $assertions
* @return self
* @throws PasetoException
*/
public function setImplicitAssertions(array $assertions): self
{
if (empty($assertions)) {
$implicit = '';
} else {
$implicit = json_encode($assertions);
}
if (!is_string($implicit)) {
throw new PasetoException(
'Could not serialize as string',
ExceptionCode::IMPLICIT_ASSERTION_JSON_ERROR
);
}
$this->implicitAssertions = $implicit;
return $this;
}
/**
* Limit the length of the decoded JSON payload containing the claims.
*
* @param int|null $length
* @return self
*/
public function setMaxJsonLength(?int $length = null): self
{
$this->maxJsonLength = $length;
return $this;
}
/**
* Limit the maximum number of claims in the decoded JSON payload.
*
* @param int|null $maximum
* @return self
*/
public function setMaxClaimCount(?int $maximum = null): self
{
$this->maxClaimCount = $maximum;
return $this;
}
/**
* Limit the maximum depth of the decoded JSON payload containign the claims.
*
* @param ?int<1, 2147483647> $maximum
* @return self
*/
public function setMaxClaimDepth(?int $maximum = null): self
{
$this->maxClaimDepth = $maximum;
return $this;
}
/**
* Specify the key for the token we are going to parse.
*
* @param ReceivingKey $key
* @param bool $checkPurpose
* @return self
*
* @throws PasetoException
*/
public function setKey(ReceivingKey $key, bool $checkPurpose = false): self
{
if ($key instanceof ReceivingKeyRing) {
$this->key = $key;
return $this;
}
if ($checkPurpose) {
if (is_null($this->purpose)) {
throw new InvalidKeyException(
'Unknown purpose',
ExceptionCode::PURPOSE_NOT_DEFINED
);
} elseif (!$this->purpose->isReceivingKeyValid($key)) {
throw new InvalidKeyException(
'Invalid key type. Expected ' .
$this->purpose->expectedReceivingKeyType() .
', got ' .
get_class($key),
ExceptionCode::PASETO_KEY_TYPE_ERROR
);
}
}
$this->key = $key;
return $this;
}
/**
* Specify the allowed 'purpose' for the token we are going to parse.
*
* @param Purpose $purpose
* @param bool $checkKeyType
* @return self
*
* @throws PasetoException
*/
public function setPurpose(Purpose $purpose, bool $checkKeyType = false): self
{
if ($checkKeyType && !is_null($this->key)) {
$expectedPurpose = Purpose::fromReceivingKey($this->key);
if (!$purpose->equals($expectedPurpose)) {
throw new InvalidPurposeException(
'Invalid purpose. Expected ' .
$expectedPurpose->rawString() .
', got ' . $purpose->rawString(),
ExceptionCode::PURPOSE_WRONG_FOR_KEY
);
}
}
$this->purpose = $purpose;
return $this;
}
/**
* This will throw an EncodingException if the claims JSON string
* violates one of the configured controls.
*
* a. String too long
* b. Too much recursive depth
* c. Too many object keys
*
* @throws EncodingException
*/
public function throwIfClaimsJsonInvalid(string $jsonString): void
{
if (!is_null($this->maxJsonLength)) {
$length = Binary::safeStrlen($jsonString);
if ($length > $this->maxJsonLength) {
throw new EncodingException(
"Claims length is too long ({$length} > {$this->maxJsonLength}",
ExceptionCode::CLAIM_JSON_TOO_LONG
);
}
}
if (!is_null($this->maxClaimCount)) {
$count = Util::countJsonKeys($jsonString);
if ($count > $this->maxClaimCount) {
throw new EncodingException(
"Too many claims in this token ({$count} > {$this->maxClaimCount}",
ExceptionCode::CLAIM_JSON_TOO_MANY_KEYs
);
}
}
if (!is_null($this->maxClaimDepth)) {
$depth = Util::calculateJsonDepth($jsonString);
if ($depth > $this->maxClaimDepth) {
throw new EncodingException(
"Too many layers of claims ({$depth} > {$this->maxClaimDepth}",
ExceptionCode::CLAIM_JSON_TOO_DEEP
);
}
}
}
/**
* Does this token pass all of the rules defined?
*
* @param JsonToken $token
* @param bool $throwOnFailure
* @return bool
*
* @throws RuleViolation
*/
public function validate(JsonToken $token, bool $throwOnFailure = false): bool
{
$rules = $this->rules;
if (!$this->nonExpiring) {
// By default, we disallow expired tokens
$rules[] = new NotExpired();
}
if (empty($rules)) {
// No rules defined, so we default to "true".
return true;
}
foreach ($rules as $rule) {
try {
if (!$rule->isValid($token)) {
if ($throwOnFailure) {
throw new RuleViolation(
$rule->getFailureMessage(),
ExceptionCode::PARSER_RULE_FAILED
);
}
return false;
}
} catch (Exception $ex) {
if ($throwOnFailure) {
throw new RuleViolation(
$ex->getMessage(),
ExceptionCode::PARSER_RULE_FAILED
);
}
return false;
}
}
return true;
}
}