-
Notifications
You must be signed in to change notification settings - Fork 108
/
Parser.php
358 lines (337 loc) · 11.8 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
<?php
declare(strict_types=1);
namespace ParagonIE\PAST;
use ParagonIE\ConstantTime\Base64UrlSafe;
use ParagonIE\PAST\Exception\{
EncodingException,
InvalidKeyException,
InvalidPurposeException,
InvalidVersionException,
PastException,
RuleViolation,
SecurityException
};
use ParagonIE\PAST\Keys\{
AsymmetricPublicKey,
AsymmetricSecretKey,
SymmetricAuthenticationKey,
SymmetricEncryptionKey
};
use ParagonIE\PAST\Protocol\{
Version1,
Version2
};
use ParagonIE\PAST\Traits\RegisteredClaims;
/**
* Class Parser
* @package ParagonIE\PAST
* @psalm-suppress PropertyNotSetInConstructor
*/
class Parser
{
use RegisteredClaims;
const DEFAULT_VERSION_ALLOW = [
Version1::HEADER,
Version2::HEADER
];
/** @var array<int, string> */
protected $allowedVersions;
/** @var KeyInterface $key */
protected $key;
/** @var string $purpose */
protected $purpose;
/** @var array<int, ValidationRuleInterface> */
protected $rules = [];
/**
* Parser constructor.
*
* @param array<int, string> $allowedVersions
* @param string $purpose
* @param KeyInterface|null $key
* @param array<int, ValidationRuleInterface> $parserRules
* @throws PastException
*/
public function __construct(
array $allowedVersions = self::DEFAULT_VERSION_ALLOW,
string $purpose = '',
KeyInterface $key = null,
array $parserRules = []
) {
$this->allowedVersions = $allowedVersions;
$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);
}
}
}
}
/**
* 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;
}
/**
* 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 PastException
*/
public function parse(string $tainted, bool $skipValidation = false): JsonToken
{
/** @var array<int, string> $pieces */
$pieces = \explode('.', $tainted);
if (\count($pieces) < 3) {
throw new SecurityException('Truncated or invalid token');
}
// First, check against the user's specified list of allowed versions.
$header = $pieces[0];
if (!\in_array($header, $this->allowedVersions, true)) {
throw new InvalidVersionException('Disallowed or unsupported version');
}
// Our parser's built-in whitelist of headers is defined here.
switch ($header) {
case Version1::HEADER:
$protocol = Version1::class;
break;
case Version2::HEADER:
$protocol = Version2::class;
break;
default:
throw new InvalidVersionException('Disallowed or unsupported version');
}
/** @var ProtocolInterface $protocol */
/** @var string $purpose */
$footer = '';
$purpose = $pieces[1];
// $this->purpose is not mandatory, but if it's set, verify against it.
if (!empty($this->purpose)) {
if (!\hash_equals($this->purpose, $purpose)) {
throw new InvalidPurposeException('Disallowed or unsupported purpose');
}
}
// Let's verify/decode according to the appropriate method:
switch ($purpose) {
case 'auth':
if (!($this->key instanceof SymmetricAuthenticationKey)) {
throw new InvalidKeyException('Invalid key type');
}
$footer = (\count($pieces) > 3)
? Base64UrlSafe::decode($pieces[3])
: '';
try {
/** @var string $decoded */
$decoded = $protocol::authVerify($tainted, $this->key, $footer);
} catch (\Throwable $ex) {
throw new PastException('An error occurred', 0, $ex);
}
break;
case 'enc':
if (!($this->key instanceof SymmetricEncryptionKey)) {
throw new InvalidKeyException('Invalid key type');
}
$footer = (\count($pieces) > 3)
? Base64UrlSafe::decode($pieces[3])
: '';
try {
/** @var string $decoded */
$decoded = $protocol::decrypt($tainted, $this->key, $footer);
} catch (\Throwable $ex) {
throw new PastException('An error occurred', 0, $ex);
}
break;
case 'seal':
if (!($this->key instanceof AsymmetricSecretKey)) {
throw new InvalidKeyException('Invalid key type');
}
$footer = (\count($pieces) > 4)
? Base64UrlSafe::decode($pieces[4])
: '';
try {
/** @var string $decoded */
$decoded = $protocol::unseal($tainted, $this->key, $footer);
} catch (\Throwable $ex) {
throw new PastException('An error occurred', 0, $ex);
}
break;
case 'sign':
if (!($this->key instanceof AsymmetricPublicKey)) {
throw new InvalidKeyException('Invalid key type');
}
$footer = (\count($pieces) > 4)
? Base64UrlSafe::decode($pieces[4])
: '';
try {
/** @var string $decoded */
$decoded = $protocol::signVerify($tainted, $this->key, $footer);
} catch (\Throwable $ex) {
throw new PastException('An error occurred', 0, $ex);
}
break;
}
// Did we get data?
if (!isset($decoded)) {
throw new PastException('Unsupported purpose or version.');
}
/** @var array $claims */
$claims = \json_decode((string) $decoded, true);
if (!\is_array($claims)) {
throw new EncodingException('Not a JSON token.');
}
// Let's build the token object.
$token = (new JsonToken())
->setVersion($header)
->setPurpose($purpose)
->setKey($this->key)
->setFooter($footer)
->setClaims($claims);
if (!$skipValidation && !empty($this->rules)) {
// Validate all of the rules that were specified:
$this->validate($token, true);
}
return $token;
}
/**
* Which protocol versions to permit.
*
* @param array<int, string> $whitelist
* @return self
*/
public function setAllowedVarsions(array $whitelist): self
{
$this->allowedVersions = $whitelist;
return $this;
}
/**
* Specify the key for the token we are going to parse.
*
* @param KeyInterface $key
* @param bool $checkPurpose
* @return self
* @throws PastException
*/
public function setKey(KeyInterface $key, bool $checkPurpose = false): self
{
if ($checkPurpose) {
switch ($this->purpose) {
case 'auth':
if (!($key instanceof SymmetricAuthenticationKey)) {
throw new InvalidKeyException(
'Invalid key type. Expected ' . SymmetricAuthenticationKey::class . ', got ' . \get_class($key)
);
}
break;
case 'enc':
if (!($key instanceof SymmetricEncryptionKey)) {
throw new InvalidKeyException(
'Invalid key type. Expected ' . SymmetricEncryptionKey::class . ', got ' . \get_class($key)
);
}
break;
case 'seal':
if (!($key instanceof AsymmetricSecretKey)) {
throw new InvalidKeyException(
'Invalid key type. Expected ' . AsymmetricSecretKey::class . ', got ' . \get_class($key)
);
}
break;
case 'sign':
if (!($key instanceof AsymmetricPublicKey)) {
throw new InvalidKeyException(
'Invalid key type. Expected ' . AsymmetricPublicKey::class . ', got ' . \get_class($key)
);
}
break;
default:
throw new InvalidKeyException('Unknown purpose');
}
}
$this->key = $key;
return $this;
}
/**
* Specify the allowed 'purpose' for the token we are going to parse.
*
* @param string $purpose
* @param bool $checkKeyType
* @return self
* @throws PastException
*/
public function setPurpose(string $purpose, bool $checkKeyType = false): self
{
if ($checkKeyType) {
$keyType = \get_class($this->key);
switch ($keyType) {
case SymmetricAuthenticationKey::class:
if (!\hash_equals('auth', $purpose)) {
throw new InvalidPurposeException(
'Invalid purpose. Expected auth, got ' . $purpose
);
}
break;
case SymmetricEncryptionKey::class:
if (!\hash_equals('enc', $purpose)) {
throw new InvalidPurposeException(
'Invalid purpose. Expected enc, got ' . $purpose
);
}
break;
case AsymmetricSecretKey::class:
if (!\hash_equals('seal', $purpose)) {
throw new InvalidPurposeException(
'Invalid purpose. Expected seal, got ' . $purpose
);
}
break;
case AsymmetricPublicKey::class:
if (!\hash_equals('sign', $purpose)) {
throw new InvalidPurposeException(
'Invalid purpose. Expected sign, got ' . $purpose
);
}
break;
default:
throw new InvalidPurposeException('Unknown purpose: ' . $purpose);
}
}
$this->purpose = $purpose;
return $this;
}
/**
* 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
{
if (empty($this->rules)) {
return true;
}
/** @var ValidationRuleInterface $rule */
foreach ($this->rules as $rule) {
if (!$rule->isValid($token)) {
if ($throwOnFailure) {
throw new RuleViolation($rule->getFailureMessage());
}
return false;
}
}
return true;
}
}