FormProtector.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  5. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  6. *
  7. * Licensed under The MIT License
  8. * For full copyright and license information, please see the LICENSE.txt
  9. * Redistributions of files must retain the above copyright notice.
  10. *
  11. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  12. * @link https://cakephp.org CakePHP(tm) Project
  13. * @since 4.0.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Form;
  17. use Cake\Core\Configure;
  18. use Cake\Utility\Hash;
  19. use Cake\Utility\Security;
  20. /**
  21. * Protects against form tampering. It ensures that:
  22. *
  23. * - Form's action (URL) is not modified.
  24. * - Unknown / extra fields are not added to the form.
  25. * - Existing fields have not been removed from the form.
  26. * - Values of hidden inputs have not been changed.
  27. *
  28. * @internal
  29. */
  30. class FormProtector
  31. {
  32. /**
  33. * Fields list.
  34. *
  35. * @var array
  36. */
  37. protected $fields = [];
  38. /**
  39. * Unlocked fields.
  40. *
  41. * @var array
  42. */
  43. protected $unlockedFields = [];
  44. /**
  45. * Form URL
  46. *
  47. * @var string
  48. */
  49. protected $url = '';
  50. /**
  51. * Session Id
  52. *
  53. * @var string
  54. */
  55. protected $sessionId = '';
  56. /**
  57. * Error message providing detail for failed validation.
  58. *
  59. * @var string|null
  60. */
  61. protected $debugMessage;
  62. /**
  63. * Construct.
  64. *
  65. * @param string $url Form URL.
  66. * @param string $sessionId Session Id.
  67. * @param array $data Data array, can contain key `unlockedFields` with list of unlocked fields.
  68. */
  69. public function __construct(string $url = '', string $sessionId = '', array $data = [])
  70. {
  71. $this->url = $url;
  72. $this->sessionId = $sessionId;
  73. if (!empty($data['unlockedFields'])) {
  74. $this->unlockedFields = $data['unlockedFields'];
  75. }
  76. }
  77. /**
  78. * Validate submitted form data.
  79. *
  80. * @param mixed $formData Form data.
  81. * @param string $url URL form was POSTed to.
  82. * @param string $sessionId Session id for hash generation.
  83. * @return bool
  84. */
  85. public function validate($formData, string $url, string $sessionId): bool
  86. {
  87. $this->debugMessage = null;
  88. $extractedToken = $this->extractToken($formData);
  89. if (empty($extractedToken)) {
  90. return false;
  91. }
  92. $hashParts = $this->extractHashParts($formData);
  93. $generatedToken = $this->generateHash(
  94. $hashParts['fields'],
  95. $hashParts['unlockedFields'],
  96. $url,
  97. $sessionId
  98. );
  99. if (hash_equals($generatedToken, $extractedToken)) {
  100. return true;
  101. }
  102. if (Configure::read('debug')) {
  103. $debugMessage = $this->debugTokenNotMatching($formData, $hashParts + compact('url', 'sessionId'));
  104. if ($debugMessage) {
  105. $this->debugMessage = $debugMessage;
  106. }
  107. }
  108. return false;
  109. }
  110. /**
  111. * Determine which fields of a form should be used for hash.
  112. *
  113. * @param string|array $field Reference to field to be secured. Can be dot
  114. * separated string to indicate nesting or array of fieldname parts.
  115. * @param bool $lock Whether this field should be part of the validation
  116. * or excluded as part of the unlockedFields. Default `true`.
  117. * @param mixed $value Field value, if value should not be tampered with.
  118. * @return $this
  119. */
  120. public function addField($field, bool $lock = true, $value = null)
  121. {
  122. if (is_string($field)) {
  123. $field = $this->getFieldNameArray($field);
  124. }
  125. if (empty($field)) {
  126. return $this;
  127. }
  128. foreach ($this->unlockedFields as $unlockField) {
  129. $unlockParts = explode('.', $unlockField);
  130. if (array_values(array_intersect($field, $unlockParts)) === $unlockParts) {
  131. return $this;
  132. }
  133. }
  134. $field = implode('.', $field);
  135. $field = preg_replace('/(\.\d+)+$/', '', $field);
  136. if ($lock) {
  137. if (!in_array($field, $this->fields, true)) {
  138. if ($value !== null) {
  139. $this->fields[$field] = $value;
  140. return $this;
  141. }
  142. if (isset($this->fields[$field])) {
  143. unset($this->fields[$field]);
  144. }
  145. $this->fields[] = $field;
  146. }
  147. } else {
  148. $this->unlockField($field);
  149. }
  150. return $this;
  151. }
  152. /**
  153. * Parses the field name to create a dot separated name value for use in
  154. * field hash. If filename is of form Model[field] or Model.field an array of
  155. * fieldname parts like ['Model', 'field'] is returned.
  156. *
  157. * @param string $name The form inputs name attribute.
  158. * @return string[] Array of field name params like ['Model.field'] or
  159. * ['Model', 'field'] for array fields or empty array if $name is empty.
  160. */
  161. protected function getFieldNameArray(string $name): array
  162. {
  163. if (empty($name) && $name !== '0') {
  164. return [];
  165. }
  166. if (strpos($name, '[') === false) {
  167. return Hash::filter(explode('.', $name));
  168. }
  169. $parts = explode('[', $name);
  170. $parts = array_map(function ($el) {
  171. return trim($el, ']');
  172. }, $parts);
  173. return Hash::filter($parts, 'strlen');
  174. }
  175. /**
  176. * Add to the list of fields that are currently unlocked.
  177. *
  178. * Unlocked fields are not included in the field hash.
  179. *
  180. * @param string $name The dot separated name for the field.
  181. * @return $this
  182. */
  183. public function unlockField($name)
  184. {
  185. if (!in_array($name, $this->unlockedFields, true)) {
  186. $this->unlockedFields[] = $name;
  187. }
  188. $index = array_search($name, $this->fields, true);
  189. if ($index !== false) {
  190. unset($this->fields[$index]);
  191. }
  192. unset($this->fields[$name]);
  193. return $this;
  194. }
  195. /**
  196. * Get validation error message.
  197. *
  198. * @return string|null
  199. */
  200. public function getError(): ?string
  201. {
  202. return $this->debugMessage;
  203. }
  204. /**
  205. * Extract token from data.
  206. *
  207. * @param mixed $formData Data to validate.
  208. * @return string|null Fields token on success, null on failure.
  209. */
  210. protected function extractToken($formData): ?string
  211. {
  212. if (!is_array($formData)) {
  213. $this->debugMessage = 'Request data is not an array.';
  214. return null;
  215. }
  216. $message = '`%s` was not found in request data.';
  217. if (!isset($formData['_Token'])) {
  218. $this->debugMessage = sprintf($message, '_Token');
  219. return null;
  220. }
  221. if (!isset($formData['_Token']['fields'])) {
  222. $this->debugMessage = sprintf($message, '_Token.fields');
  223. return null;
  224. }
  225. if (!isset($formData['_Token']['unlocked'])) {
  226. $this->debugMessage = sprintf($message, '_Token.unlocked');
  227. return null;
  228. }
  229. if (Configure::read('debug') && !isset($formData['_Token']['debug'])) {
  230. $this->debugMessage = sprintf($message, '_Token.debug');
  231. return null;
  232. }
  233. if (!Configure::read('debug') && isset($formData['_Token']['debug'])) {
  234. $this->debugMessage = 'Unexpected `_Token.debug` found in request data';
  235. return null;
  236. }
  237. $token = urldecode($formData['_Token']['fields']);
  238. if (strpos($token, ':')) {
  239. [$token, ] = explode(':', $token, 2);
  240. }
  241. return $token;
  242. }
  243. /**
  244. * Return hash parts for the token generation
  245. *
  246. * @param array $formData Form data.
  247. * @return array
  248. * @psalm-return array{fields: array, unlockedFields: array}
  249. */
  250. protected function extractHashParts(array $formData): array
  251. {
  252. $fields = $this->extractFields($formData);
  253. $unlockedFields = $this->sortedUnlockedFields($formData);
  254. return [
  255. 'fields' => $fields,
  256. 'unlockedFields' => $unlockedFields,
  257. ];
  258. }
  259. /**
  260. * Return the fields list for the hash calculation
  261. *
  262. * @param array $formData Data array
  263. * @return array
  264. */
  265. protected function extractFields(array $formData): array
  266. {
  267. $locked = '';
  268. $token = urldecode($formData['_Token']['fields']);
  269. $unlocked = urldecode($formData['_Token']['unlocked']);
  270. if (strpos($token, ':')) {
  271. [, $locked] = explode(':', $token, 2);
  272. }
  273. unset($formData['_Token']);
  274. $locked = explode('|', $locked);
  275. $unlocked = explode('|', $unlocked);
  276. $fields = Hash::flatten($formData);
  277. $fieldList = array_keys($fields);
  278. $multi = $lockedFields = [];
  279. $isUnlocked = false;
  280. foreach ($fieldList as $i => $key) {
  281. if (is_string($key) && preg_match('/(\.\d+){1,10}$/', $key)) {
  282. $multi[$i] = preg_replace('/(\.\d+){1,10}$/', '', $key);
  283. unset($fieldList[$i]);
  284. } else {
  285. $fieldList[$i] = (string)$key;
  286. }
  287. }
  288. if (!empty($multi)) {
  289. $fieldList += array_unique($multi);
  290. }
  291. $unlockedFields = array_unique(
  292. array_merge(
  293. $this->unlockedFields,
  294. $unlocked
  295. )
  296. );
  297. foreach ($fieldList as $i => $key) {
  298. $isLocked = in_array($key, $locked, true);
  299. if (!empty($unlockedFields)) {
  300. foreach ($unlockedFields as $off) {
  301. $off = explode('.', $off);
  302. $field = array_values(array_intersect(explode('.', $key), $off));
  303. $isUnlocked = ($field === $off);
  304. if ($isUnlocked) {
  305. break;
  306. }
  307. }
  308. }
  309. if ($isUnlocked || $isLocked) {
  310. unset($fieldList[$i]);
  311. if ($isLocked) {
  312. $lockedFields[$key] = $fields[$key];
  313. }
  314. }
  315. }
  316. sort($fieldList, SORT_STRING);
  317. ksort($lockedFields, SORT_STRING);
  318. $fieldList += $lockedFields;
  319. return $fieldList;
  320. }
  321. /**
  322. * Get the sorted unlocked string
  323. *
  324. * @param array $formData Data array
  325. * @return string[]
  326. */
  327. protected function sortedUnlockedFields(array $formData): array
  328. {
  329. $unlocked = urldecode($formData['_Token']['unlocked']);
  330. if (empty($unlocked)) {
  331. return [];
  332. }
  333. $unlocked = explode('|', $unlocked);
  334. sort($unlocked, SORT_STRING);
  335. return $unlocked;
  336. }
  337. /**
  338. * Generate the token data.
  339. *
  340. * @return array The token data.
  341. * @psalm-return array{fields: string, unlocked: string}
  342. */
  343. public function buildTokenData(): array
  344. {
  345. $fields = $this->fields;
  346. $unlockedFields = $this->unlockedFields;
  347. $locked = [];
  348. foreach ($fields as $key => $value) {
  349. if (is_numeric($value)) {
  350. $value = (string)$value;
  351. }
  352. if (!is_int($key)) {
  353. $locked[$key] = $value;
  354. unset($fields[$key]);
  355. }
  356. }
  357. sort($unlockedFields, SORT_STRING);
  358. sort($fields, SORT_STRING);
  359. ksort($locked, SORT_STRING);
  360. $fields += $locked;
  361. $fields = $this->generateHash($fields, $unlockedFields, $this->url, $this->sessionId);
  362. $locked = implode('|', array_keys($locked));
  363. return [
  364. 'fields' => urlencode($fields . ':' . $locked),
  365. 'unlocked' => urlencode(implode('|', $unlockedFields)),
  366. 'debug' => urlencode(json_encode([
  367. $this->url,
  368. $this->fields,
  369. $this->unlockedFields,
  370. ])),
  371. ];
  372. }
  373. /**
  374. * Generate validation hash.
  375. *
  376. * @param array $fields Fields list.
  377. * @param array $unlockedFields Unlocked fields.
  378. * @param string $url Form URL.
  379. * @param string $sessionId Session Id.
  380. * @return string
  381. */
  382. protected function generateHash(array $fields, array $unlockedFields, string $url, string $sessionId)
  383. {
  384. $hashParts = [
  385. $url,
  386. serialize($fields),
  387. implode('|', $unlockedFields),
  388. $sessionId,
  389. ];
  390. return hash_hmac('sha1', implode('', $hashParts), Security::getSalt());
  391. }
  392. /**
  393. * Create a message for humans to understand why Security token is not matching
  394. *
  395. * @param array $formData Data.
  396. * @param array $hashParts Elements used to generate the Token hash
  397. * @return string Message explaining why the tokens are not matching
  398. */
  399. protected function debugTokenNotMatching(array $formData, array $hashParts): string
  400. {
  401. $messages = [];
  402. if (!isset($formData['_Token']['debug'])) {
  403. return 'Form protection debug token not found.';
  404. }
  405. $expectedParts = json_decode(urldecode($formData['_Token']['debug']), true);
  406. if (!is_array($expectedParts) || count($expectedParts) !== 3) {
  407. return 'Invalid form protection debug token.';
  408. }
  409. $expectedUrl = Hash::get($expectedParts, 0);
  410. $url = Hash::get($hashParts, 'url');
  411. if ($expectedUrl !== $url) {
  412. $messages[] = sprintf('URL mismatch in POST data (expected `%s` but found `%s`)', $expectedUrl, $url);
  413. }
  414. $expectedFields = Hash::get($expectedParts, 1);
  415. $dataFields = Hash::get($hashParts, 'fields') ?: [];
  416. $fieldsMessages = $this->debugCheckFields(
  417. (array)$dataFields,
  418. $expectedFields,
  419. 'Unexpected field `%s` in POST data',
  420. 'Tampered field `%s` in POST data (expected value `%s` but found `%s`)',
  421. 'Missing field `%s` in POST data'
  422. );
  423. $expectedUnlockedFields = Hash::get($expectedParts, 2);
  424. $dataUnlockedFields = Hash::get($hashParts, 'unlockedFields') ?: [];
  425. $unlockFieldsMessages = $this->debugCheckFields(
  426. (array)$dataUnlockedFields,
  427. $expectedUnlockedFields,
  428. 'Unexpected unlocked field `%s` in POST data',
  429. '',
  430. 'Missing unlocked field: `%s`'
  431. );
  432. $messages = array_merge($messages, $fieldsMessages, $unlockFieldsMessages);
  433. return implode(', ', $messages);
  434. }
  435. /**
  436. * Iterates data array to check against expected
  437. *
  438. * @param array $dataFields Fields array, containing the POST data fields
  439. * @param array $expectedFields Fields array, containing the expected fields we should have in POST
  440. * @param string $intKeyMessage Message string if unexpected found in data fields indexed by int (not protected)
  441. * @param string $stringKeyMessage Message string if tampered found in
  442. * data fields indexed by string (protected).
  443. * @param string $missingMessage Message string if missing field
  444. * @return string[] Messages
  445. */
  446. protected function debugCheckFields(
  447. array $dataFields,
  448. array $expectedFields = [],
  449. string $intKeyMessage = '',
  450. string $stringKeyMessage = '',
  451. string $missingMessage = ''
  452. ): array {
  453. $messages = $this->matchExistingFields($dataFields, $expectedFields, $intKeyMessage, $stringKeyMessage);
  454. $expectedFieldsMessage = $this->debugExpectedFields($expectedFields, $missingMessage);
  455. if ($expectedFieldsMessage !== null) {
  456. $messages[] = $expectedFieldsMessage;
  457. }
  458. return $messages;
  459. }
  460. /**
  461. * Generate array of messages for the existing fields in POST data, matching dataFields in $expectedFields
  462. * will be unset
  463. *
  464. * @param array $dataFields Fields array, containing the POST data fields
  465. * @param array $expectedFields Fields array, containing the expected fields we should have in POST
  466. * @param string $intKeyMessage Message string if unexpected found in data fields indexed by int (not protected)
  467. * @param string $stringKeyMessage Message string if tampered found in
  468. * data fields indexed by string (protected)
  469. * @return string[] Error messages
  470. */
  471. protected function matchExistingFields(
  472. array $dataFields,
  473. array &$expectedFields,
  474. string $intKeyMessage,
  475. string $stringKeyMessage
  476. ): array {
  477. $messages = [];
  478. foreach ($dataFields as $key => $value) {
  479. if (is_int($key)) {
  480. $foundKey = array_search($value, (array)$expectedFields, true);
  481. if ($foundKey === false) {
  482. $messages[] = sprintf($intKeyMessage, $value);
  483. } else {
  484. unset($expectedFields[$foundKey]);
  485. }
  486. } else {
  487. if (isset($expectedFields[$key]) && $value !== $expectedFields[$key]) {
  488. $messages[] = sprintf($stringKeyMessage, $key, $expectedFields[$key], $value);
  489. }
  490. unset($expectedFields[$key]);
  491. }
  492. }
  493. return $messages;
  494. }
  495. /**
  496. * Generate debug message for the expected fields
  497. *
  498. * @param array $expectedFields Expected fields
  499. * @param string $missingMessage Message template
  500. * @return string|null Error message about expected fields
  501. */
  502. protected function debugExpectedFields(array $expectedFields = [], string $missingMessage = ''): ?string
  503. {
  504. if (count($expectedFields) === 0) {
  505. return null;
  506. }
  507. $expectedFieldNames = [];
  508. foreach ((array)$expectedFields as $key => $expectedField) {
  509. if (is_int($key)) {
  510. $expectedFieldNames[] = $expectedField;
  511. } else {
  512. $expectedFieldNames[] = $key;
  513. }
  514. }
  515. return sprintf($missingMessage, implode(', ', $expectedFieldNames));
  516. }
  517. /**
  518. * Return debug info
  519. *
  520. * @return array
  521. */
  522. public function __debugInfo(): array
  523. {
  524. return [
  525. 'url' => $this->url,
  526. 'sessionId' => $this->sessionId,
  527. 'fields' => $this->fields,
  528. 'unlockedFields' => $this->unlockedFields,
  529. 'debugMessage' => $this->debugMessage,
  530. ];
  531. }
  532. }