-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathFormProtector.php
591 lines (520 loc) · 18.1 KB
/
FormProtector.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
<?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 4.0.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\Form;
use Cake\Core\Configure;
use Cake\Utility\Hash;
use Cake\Utility\Security;
/**
* Protects against form tampering. It ensures that:
*
* - Form's action (URL) is not modified.
* - Unknown / extra fields are not added to the form.
* - Existing fields have not been removed from the form.
* - Values of hidden inputs have not been changed.
*
* @internal
*/
class FormProtector
{
/**
* Fields list.
*
* @var array
*/
protected $fields = [];
/**
* Unlocked fields.
*
* @var array
*/
protected $unlockedFields = [];
/**
* Error message providing detail for failed validation.
*
* @var string|null
*/
protected $debugMessage;
/**
* Construct.
*
* @param array $data Data array, can contain key `unlockedFields` with list of unlocked fields.
*/
public function __construct(array $data = [])
{
if (!empty($data['unlockedFields'])) {
$this->unlockedFields = $data['unlockedFields'];
}
}
/**
* Validate submitted form data.
*
* @param mixed $formData Form data.
* @param string $url URL form was POSTed to.
* @param string $sessionId Session id for hash generation.
* @return bool
*/
public function validate($formData, string $url, string $sessionId): bool
{
$this->debugMessage = null;
$extractedToken = $this->extractToken($formData);
if (empty($extractedToken)) {
return false;
}
$hashParts = $this->extractHashParts($formData);
$generatedToken = $this->generateHash(
$hashParts['fields'],
$hashParts['unlockedFields'],
$url,
$sessionId
);
if (hash_equals($generatedToken, $extractedToken)) {
return true;
}
if (Configure::read('debug')) {
$debugMessage = $this->debugTokenNotMatching($formData, $hashParts + compact('url', 'sessionId'));
if ($debugMessage) {
$this->debugMessage = $debugMessage;
}
}
return false;
}
/**
* Determine which fields of a form should be used for hash.
*
* @param string|array $field Reference to field to be secured. Can be dot
* separated string to indicate nesting or array of fieldname parts.
* @param bool $lock Whether this field should be part of the validation
* or excluded as part of the unlockedFields. Default `true`.
* @param mixed $value Field value, if value should not be tampered with.
* @return $this
*/
public function addField($field, bool $lock = true, $value = null)
{
if (is_string($field)) {
$field = $this->getFieldNameArray($field);
}
if (empty($field)) {
return $this;
}
foreach ($this->unlockedFields as $unlockField) {
$unlockParts = explode('.', $unlockField);
if (array_values(array_intersect($field, $unlockParts)) === $unlockParts) {
return $this;
}
}
$field = implode('.', $field);
$field = preg_replace('/(\.\d+)+$/', '', $field);
if ($lock) {
if (!in_array($field, $this->fields, true)) {
if ($value !== null) {
$this->fields[$field] = $value;
return $this;
}
if (isset($this->fields[$field])) {
unset($this->fields[$field]);
}
$this->fields[] = $field;
}
} else {
$this->unlockField($field);
}
return $this;
}
/**
* Parses the field name to create a dot separated name value for use in
* field hash. If fieldname is of form Model[field] or Model.field an array of
* fieldname parts like ['Model', 'field'] is returned.
*
* @param string $name The form inputs name attribute.
* @return string[] Array of field name params like ['Model.field'] or
* ['Model', 'field'] for array fields or empty array if $name is empty.
*/
protected function getFieldNameArray(string $name): array
{
if (empty($name) && $name !== '0') {
return [];
}
if (strpos($name, '[') === false) {
return Hash::filter(explode('.', $name));
}
$parts = explode('[', $name);
$parts = array_map(function ($el) {
return trim($el, ']');
}, $parts);
return Hash::filter($parts, 'strlen');
}
/**
* Add to the list of fields that are currently unlocked.
*
* Unlocked fields are not included in the field hash.
*
* @param string $name The dot separated name for the field.
* @return $this
*/
public function unlockField($name)
{
if (!in_array($name, $this->unlockedFields, true)) {
$this->unlockedFields[] = $name;
}
$index = array_search($name, $this->fields, true);
if ($index !== false) {
unset($this->fields[$index]);
}
unset($this->fields[$name]);
return $this;
}
/**
* Get validation error message.
*
* @return string|null
*/
public function getError(): ?string
{
return $this->debugMessage;
}
/**
* Extract token from data.
*
* @param mixed $formData Data to validate.
* @return string|null Fields token on success, null on failure.
*/
protected function extractToken($formData): ?string
{
if (!is_array($formData)) {
$this->debugMessage = 'Request data is not an array.';
return null;
}
$message = '`%s` was not found in request data.';
if (!isset($formData['_Token'])) {
$this->debugMessage = sprintf($message, '_Token');
return null;
}
if (!isset($formData['_Token']['fields'])) {
$this->debugMessage = sprintf($message, '_Token.fields');
return null;
}
if (!is_string($formData['_Token']['fields'])) {
$this->debugMessage = '`_Token.fields` is invalid.';
return null;
}
if (!isset($formData['_Token']['unlocked'])) {
$this->debugMessage = sprintf($message, '_Token.unlocked');
return null;
}
if (Configure::read('debug') && !isset($formData['_Token']['debug'])) {
$this->debugMessage = sprintf($message, '_Token.debug');
return null;
}
if (!Configure::read('debug') && isset($formData['_Token']['debug'])) {
$this->debugMessage = 'Unexpected `_Token.debug` found in request data';
return null;
}
$token = urldecode($formData['_Token']['fields']);
if (strpos($token, ':')) {
[$token, ] = explode(':', $token, 2);
}
return $token;
}
/**
* Return hash parts for the token generation
*
* @param array $formData Form data.
* @return array
* @psalm-return array{fields: array, unlockedFields: array}
*/
protected function extractHashParts(array $formData): array
{
$fields = $this->extractFields($formData);
$unlockedFields = $this->sortedUnlockedFields($formData);
return [
'fields' => $fields,
'unlockedFields' => $unlockedFields,
];
}
/**
* Return the fields list for the hash calculation
*
* @param array $formData Data array
* @return array
*/
protected function extractFields(array $formData): array
{
$locked = '';
$token = urldecode($formData['_Token']['fields']);
$unlocked = urldecode($formData['_Token']['unlocked']);
if (strpos($token, ':')) {
[, $locked] = explode(':', $token, 2);
}
unset($formData['_Token']);
$locked = $locked ? explode('|', $locked) : [];
$unlocked = $unlocked ? explode('|', $unlocked) : [];
$fields = Hash::flatten($formData);
$fieldList = array_keys($fields);
$multi = $lockedFields = [];
$isUnlocked = false;
foreach ($fieldList as $i => $key) {
if (is_string($key) && preg_match('/(\.\d+){1,10}$/', $key)) {
$multi[$i] = preg_replace('/(\.\d+){1,10}$/', '', $key);
unset($fieldList[$i]);
} else {
$fieldList[$i] = (string)$key;
}
}
if (!empty($multi)) {
$fieldList += array_unique($multi);
}
$unlockedFields = array_unique(
array_merge(
$this->unlockedFields,
$unlocked
)
);
foreach ($fieldList as $i => $key) {
$isLocked = in_array($key, $locked, true);
if (!empty($unlockedFields)) {
foreach ($unlockedFields as $off) {
$off = explode('.', $off);
$field = array_values(array_intersect(explode('.', $key), $off));
$isUnlocked = ($field === $off);
if ($isUnlocked) {
break;
}
}
}
if ($isUnlocked || $isLocked) {
unset($fieldList[$i]);
if ($isLocked) {
$lockedFields[$key] = $fields[$key];
}
}
}
sort($fieldList, SORT_STRING);
ksort($lockedFields, SORT_STRING);
$fieldList += $lockedFields;
return $fieldList;
}
/**
* Get the sorted unlocked string
*
* @param array $formData Data array
* @return string[]
*/
protected function sortedUnlockedFields(array $formData): array
{
$unlocked = urldecode($formData['_Token']['unlocked']);
if (empty($unlocked)) {
return [];
}
$unlocked = explode('|', $unlocked);
sort($unlocked, SORT_STRING);
return $unlocked;
}
/**
* Generate the token data.
*
* @param string $url Form URL.
* @param string $sessionId Session Id.
* @return array The token data.
* @psalm-return array{fields: string, unlocked: string, debug: string}
*/
public function buildTokenData(string $url = '', string $sessionId = ''): array
{
$fields = $this->fields;
$unlockedFields = $this->unlockedFields;
$locked = [];
foreach ($fields as $key => $value) {
if (is_numeric($value)) {
$value = (string)$value;
}
if (!is_int($key)) {
$locked[$key] = $value;
unset($fields[$key]);
}
}
sort($unlockedFields, SORT_STRING);
sort($fields, SORT_STRING);
ksort($locked, SORT_STRING);
$fields += $locked;
$fields = $this->generateHash($fields, $unlockedFields, $url, $sessionId);
$locked = implode('|', array_keys($locked));
return [
'fields' => urlencode($fields . ':' . $locked),
'unlocked' => urlencode(implode('|', $unlockedFields)),
'debug' => urlencode(json_encode([
$url,
$this->fields,
$this->unlockedFields,
])),
];
}
/**
* Generate validation hash.
*
* @param array $fields Fields list.
* @param array $unlockedFields Unlocked fields.
* @param string $url Form URL.
* @param string $sessionId Session Id.
* @return string
*/
protected function generateHash(array $fields, array $unlockedFields, string $url, string $sessionId)
{
$hashParts = [
$url,
serialize($fields),
implode('|', $unlockedFields),
$sessionId,
];
return hash_hmac('sha1', implode('', $hashParts), Security::getSalt());
}
/**
* Create a message for humans to understand why Security token is not matching
*
* @param array $formData Data.
* @param array $hashParts Elements used to generate the Token hash
* @return string Message explaining why the tokens are not matching
*/
protected function debugTokenNotMatching(array $formData, array $hashParts): string
{
$messages = [];
if (!isset($formData['_Token']['debug'])) {
return 'Form protection debug token not found.';
}
$expectedParts = json_decode(urldecode($formData['_Token']['debug']), true);
if (!is_array($expectedParts) || count($expectedParts) !== 3) {
return 'Invalid form protection debug token.';
}
$expectedUrl = Hash::get($expectedParts, 0);
$url = Hash::get($hashParts, 'url');
if ($expectedUrl !== $url) {
$messages[] = sprintf('URL mismatch in POST data (expected `%s` but found `%s`)', $expectedUrl, $url);
}
$expectedFields = Hash::get($expectedParts, 1);
$dataFields = Hash::get($hashParts, 'fields') ?: [];
$fieldsMessages = $this->debugCheckFields(
(array)$dataFields,
$expectedFields,
'Unexpected field `%s` in POST data',
'Tampered field `%s` in POST data (expected value `%s` but found `%s`)',
'Missing field `%s` in POST data'
);
$expectedUnlockedFields = Hash::get($expectedParts, 2);
$dataUnlockedFields = Hash::get($hashParts, 'unlockedFields') ?: [];
$unlockFieldsMessages = $this->debugCheckFields(
(array)$dataUnlockedFields,
$expectedUnlockedFields,
'Unexpected unlocked field `%s` in POST data',
'',
'Missing unlocked field: `%s`'
);
$messages = array_merge($messages, $fieldsMessages, $unlockFieldsMessages);
return implode(', ', $messages);
}
/**
* Iterates data array to check against expected
*
* @param array $dataFields Fields array, containing the POST data fields
* @param array $expectedFields Fields array, containing the expected fields we should have in POST
* @param string $intKeyMessage Message string if unexpected found in data fields indexed by int (not protected)
* @param string $stringKeyMessage Message string if tampered found in
* data fields indexed by string (protected).
* @param string $missingMessage Message string if missing field
* @return string[] Messages
*/
protected function debugCheckFields(
array $dataFields,
array $expectedFields = [],
string $intKeyMessage = '',
string $stringKeyMessage = '',
string $missingMessage = ''
): array {
$messages = $this->matchExistingFields($dataFields, $expectedFields, $intKeyMessage, $stringKeyMessage);
$expectedFieldsMessage = $this->debugExpectedFields($expectedFields, $missingMessage);
if ($expectedFieldsMessage !== null) {
$messages[] = $expectedFieldsMessage;
}
return $messages;
}
/**
* Generate array of messages for the existing fields in POST data, matching dataFields in $expectedFields
* will be unset
*
* @param array $dataFields Fields array, containing the POST data fields
* @param array $expectedFields Fields array, containing the expected fields we should have in POST
* @param string $intKeyMessage Message string if unexpected found in data fields indexed by int (not protected)
* @param string $stringKeyMessage Message string if tampered found in
* data fields indexed by string (protected)
* @return string[] Error messages
*/
protected function matchExistingFields(
array $dataFields,
array &$expectedFields,
string $intKeyMessage,
string $stringKeyMessage
): array {
$messages = [];
foreach ($dataFields as $key => $value) {
if (is_int($key)) {
$foundKey = array_search($value, $expectedFields, true);
if ($foundKey === false) {
$messages[] = sprintf($intKeyMessage, $value);
} else {
unset($expectedFields[$foundKey]);
}
} else {
if (isset($expectedFields[$key]) && $value !== $expectedFields[$key]) {
$messages[] = sprintf($stringKeyMessage, $key, $expectedFields[$key], $value);
}
unset($expectedFields[$key]);
}
}
return $messages;
}
/**
* Generate debug message for the expected fields
*
* @param array $expectedFields Expected fields
* @param string $missingMessage Message template
* @return string|null Error message about expected fields
*/
protected function debugExpectedFields(array $expectedFields = [], string $missingMessage = ''): ?string
{
if (count($expectedFields) === 0) {
return null;
}
$expectedFieldNames = [];
foreach ($expectedFields as $key => $expectedField) {
if (is_int($key)) {
$expectedFieldNames[] = $expectedField;
} else {
$expectedFieldNames[] = $key;
}
}
return sprintf($missingMessage, implode(', ', $expectedFieldNames));
}
/**
* Return debug info
*
* @return array
*/
public function __debugInfo(): array
{
return [
'fields' => $this->fields,
'unlockedFields' => $this->unlockedFields,
'debugMessage' => $this->debugMessage,
];
}
}