SecurityComponent.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. <?php
  2. /**
  3. * Security Component
  4. *
  5. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  6. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  7. *
  8. * Licensed under The MIT License
  9. * For full copyright and license information, please see the LICENSE.txt
  10. * Redistributions of files must retain the above copyright notice.
  11. *
  12. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  13. * @link http://cakephp.org CakePHP(tm) Project
  14. * @package Cake.Controller.Component
  15. * @since CakePHP(tm) v 0.10.8.2156
  16. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  17. */
  18. App::uses('Component', 'Controller');
  19. App::uses('String', 'Utility');
  20. App::uses('Hash', 'Utility');
  21. App::uses('Security', 'Utility');
  22. /**
  23. * The Security Component creates an easy way to integrate tighter security in
  24. * your application. It provides methods for various tasks like:
  25. *
  26. * - Restricting which HTTP methods your application accepts.
  27. * - CSRF protection.
  28. * - Form tampering protection
  29. * - Requiring that SSL be used.
  30. * - Limiting cross controller communication.
  31. *
  32. * @package Cake.Controller.Component
  33. * @link http://book.cakephp.org/2.0/en/core-libraries/components/security-component.html
  34. */
  35. class SecurityComponent extends Component {
  36. /**
  37. * The controller method that will be called if this request is black-hole'd
  38. *
  39. * @var string
  40. */
  41. public $blackHoleCallback = null;
  42. /**
  43. * List of controller actions for which a POST request is required
  44. *
  45. * @var array
  46. * @deprecated Use CakeRequest::onlyAllow() instead.
  47. * @see SecurityComponent::requirePost()
  48. */
  49. public $requirePost = array();
  50. /**
  51. * List of controller actions for which a GET request is required
  52. *
  53. * @var array
  54. * @deprecated Use CakeRequest::onlyAllow() instead.
  55. * @see SecurityComponent::requireGet()
  56. */
  57. public $requireGet = array();
  58. /**
  59. * List of controller actions for which a PUT request is required
  60. *
  61. * @var array
  62. * @deprecated Use CakeRequest::onlyAllow() instead.
  63. * @see SecurityComponent::requirePut()
  64. */
  65. public $requirePut = array();
  66. /**
  67. * List of controller actions for which a DELETE request is required
  68. *
  69. * @var array
  70. * @deprecated Use CakeRequest::onlyAllow() instead.
  71. * @see SecurityComponent::requireDelete()
  72. */
  73. public $requireDelete = array();
  74. /**
  75. * List of actions that require an SSL-secured connection
  76. *
  77. * @var array
  78. * @see SecurityComponent::requireSecure()
  79. */
  80. public $requireSecure = array();
  81. /**
  82. * List of actions that require a valid authentication key
  83. *
  84. * @var array
  85. * @see SecurityComponent::requireAuth()
  86. */
  87. public $requireAuth = array();
  88. /**
  89. * Controllers from which actions of the current controller are allowed to receive
  90. * requests.
  91. *
  92. * @var array
  93. * @see SecurityComponent::requireAuth()
  94. */
  95. public $allowedControllers = array();
  96. /**
  97. * Actions from which actions of the current controller are allowed to receive
  98. * requests.
  99. *
  100. * @var array
  101. * @see SecurityComponent::requireAuth()
  102. */
  103. public $allowedActions = array();
  104. /**
  105. * Deprecated property, superseded by unlockedFields.
  106. *
  107. * @var array
  108. * @deprecated
  109. * @see SecurityComponent::$unlockedFields
  110. */
  111. public $disabledFields = array();
  112. /**
  113. * Form fields to exclude from POST validation. Fields can be unlocked
  114. * either in the Component, or with FormHelper::unlockField().
  115. * Fields that have been unlocked are not required to be part of the POST
  116. * and hidden unlocked fields do not have their values checked.
  117. *
  118. * @var array
  119. */
  120. public $unlockedFields = array();
  121. /**
  122. * Actions to exclude from CSRF and POST validation checks.
  123. * Other checks like requireAuth(), requireSecure(),
  124. * requirePost(), requireGet() etc. will still be applied.
  125. *
  126. * @var array
  127. */
  128. public $unlockedActions = array();
  129. /**
  130. * Whether to validate POST data. Set to false to disable for data coming from 3rd party
  131. * services, etc.
  132. *
  133. * @var bool
  134. */
  135. public $validatePost = true;
  136. /**
  137. * Whether to use CSRF protected forms. Set to false to disable CSRF protection on forms.
  138. *
  139. * @var bool
  140. * @see http://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)
  141. * @see SecurityComponent::$csrfExpires
  142. */
  143. public $csrfCheck = true;
  144. /**
  145. * The duration from when a CSRF token is created that it will expire on.
  146. * Each form/page request will generate a new token that can only be submitted once unless
  147. * it expires. Can be any value compatible with strtotime()
  148. *
  149. * @var string
  150. */
  151. public $csrfExpires = '+30 minutes';
  152. /**
  153. * Controls whether or not CSRF tokens are use and burn. Set to false to not generate
  154. * new tokens on each request. One token will be reused until it expires. This reduces
  155. * the chances of users getting invalid requests because of token consumption.
  156. * It has the side effect of making CSRF less secure, as tokens are reusable.
  157. *
  158. * @var bool
  159. */
  160. public $csrfUseOnce = true;
  161. /**
  162. * Control the number of tokens a user can keep open.
  163. * This is most useful with one-time use tokens. Since new tokens
  164. * are created on each request, having a hard limit on the number of open tokens
  165. * can be useful in controlling the size of the session file.
  166. *
  167. * When tokens are evicted, the oldest ones will be removed, as they are the most likely
  168. * to be dead/expired.
  169. *
  170. * @var int
  171. */
  172. public $csrfLimit = 100;
  173. /**
  174. * Other components used by the Security component
  175. *
  176. * @var array
  177. */
  178. public $components = array('Session');
  179. /**
  180. * Holds the current action of the controller
  181. *
  182. * @var string
  183. */
  184. protected $_action = null;
  185. /**
  186. * Request object
  187. *
  188. * @var CakeRequest
  189. */
  190. public $request;
  191. /**
  192. * Component startup. All security checking happens here.
  193. *
  194. * @param Controller $controller Instantiating controller
  195. * @return void
  196. */
  197. public function startup(Controller $controller) {
  198. $this->request = $controller->request;
  199. $this->_action = $this->request->params['action'];
  200. $this->_methodsRequired($controller);
  201. $this->_secureRequired($controller);
  202. $this->_authRequired($controller);
  203. $isPost = $this->request->is(array('post', 'put'));
  204. $isNotRequestAction = (
  205. !isset($controller->request->params['requested']) ||
  206. $controller->request->params['requested'] != 1
  207. );
  208. if ($this->_action === $this->blackHoleCallback) {
  209. return $this->blackHole($controller, 'auth');
  210. }
  211. if (!in_array($this->_action, (array)$this->unlockedActions) && $isPost && $isNotRequestAction) {
  212. if ($this->validatePost && $this->_validatePost($controller) === false) {
  213. return $this->blackHole($controller, 'auth');
  214. }
  215. if ($this->csrfCheck && $this->_validateCsrf($controller) === false) {
  216. return $this->blackHole($controller, 'csrf');
  217. }
  218. }
  219. $this->generateToken($controller->request);
  220. if ($isPost && is_array($controller->request->data)) {
  221. unset($controller->request->data['_Token']);
  222. }
  223. }
  224. /**
  225. * Sets the actions that require a POST request, or empty for all actions
  226. *
  227. * @return void
  228. * @deprecated Use CakeRequest::onlyAllow() instead.
  229. * @link http://book.cakephp.org/2.0/en/core-libraries/components/security-component.html#SecurityComponent::requirePost
  230. */
  231. public function requirePost() {
  232. $args = func_get_args();
  233. $this->_requireMethod('Post', $args);
  234. }
  235. /**
  236. * Sets the actions that require a GET request, or empty for all actions
  237. *
  238. * @deprecated Use CakeRequest::onlyAllow() instead.
  239. * @return void
  240. */
  241. public function requireGet() {
  242. $args = func_get_args();
  243. $this->_requireMethod('Get', $args);
  244. }
  245. /**
  246. * Sets the actions that require a PUT request, or empty for all actions
  247. *
  248. * @deprecated Use CakeRequest::onlyAllow() instead.
  249. * @return void
  250. */
  251. public function requirePut() {
  252. $args = func_get_args();
  253. $this->_requireMethod('Put', $args);
  254. }
  255. /**
  256. * Sets the actions that require a DELETE request, or empty for all actions
  257. *
  258. * @deprecated Use CakeRequest::onlyAllow() instead.
  259. * @return void
  260. */
  261. public function requireDelete() {
  262. $args = func_get_args();
  263. $this->_requireMethod('Delete', $args);
  264. }
  265. /**
  266. * Sets the actions that require a request that is SSL-secured, or empty for all actions
  267. *
  268. * @return void
  269. * @link http://book.cakephp.org/2.0/en/core-libraries/components/security-component.html#SecurityComponent::requireSecure
  270. */
  271. public function requireSecure() {
  272. $args = func_get_args();
  273. $this->_requireMethod('Secure', $args);
  274. }
  275. /**
  276. * Sets the actions that require whitelisted form submissions.
  277. *
  278. * Adding actions with this method will enforce the restrictions
  279. * set in SecurityComponent::$allowedControllers and
  280. * SecurityComponent::$allowedActions.
  281. *
  282. * @return void
  283. * @link http://book.cakephp.org/2.0/en/core-libraries/components/security-component.html#SecurityComponent::requireAuth
  284. */
  285. public function requireAuth() {
  286. $args = func_get_args();
  287. $this->_requireMethod('Auth', $args);
  288. }
  289. /**
  290. * Black-hole an invalid request with a 400 error or custom callback. If SecurityComponent::$blackHoleCallback
  291. * is specified, it will use this callback by executing the method indicated in $error
  292. *
  293. * @param Controller $controller Instantiating controller
  294. * @param string $error Error method
  295. * @return mixed If specified, controller blackHoleCallback's response, or no return otherwise
  296. * @see SecurityComponent::$blackHoleCallback
  297. * @link http://book.cakephp.org/2.0/en/core-libraries/components/security-component.html#handling-blackhole-callbacks
  298. * @throws BadRequestException
  299. */
  300. public function blackHole(Controller $controller, $error = '') {
  301. if (!$this->blackHoleCallback) {
  302. throw new BadRequestException(__d('cake_dev', 'The request has been black-holed'));
  303. }
  304. return $this->_callback($controller, $this->blackHoleCallback, array($error));
  305. }
  306. /**
  307. * Sets the actions that require a $method HTTP request, or empty for all actions
  308. *
  309. * @param string $method The HTTP method to assign controller actions to
  310. * @param array $actions Controller actions to set the required HTTP method to.
  311. * @return void
  312. */
  313. protected function _requireMethod($method, $actions = array()) {
  314. if (isset($actions[0]) && is_array($actions[0])) {
  315. $actions = $actions[0];
  316. }
  317. $this->{'require' . $method} = (empty($actions)) ? array('*') : $actions;
  318. }
  319. /**
  320. * Check if HTTP methods are required
  321. *
  322. * @param Controller $controller Instantiating controller
  323. * @return bool true if $method is required
  324. */
  325. protected function _methodsRequired(Controller $controller) {
  326. foreach (array('Post', 'Get', 'Put', 'Delete') as $method) {
  327. $property = 'require' . $method;
  328. if (is_array($this->$property) && !empty($this->$property)) {
  329. $require = $this->$property;
  330. if (in_array($this->_action, $require) || $this->$property === array('*')) {
  331. if (!$this->request->is($method)) {
  332. if (!$this->blackHole($controller, $method)) {
  333. return null;
  334. }
  335. }
  336. }
  337. }
  338. }
  339. return true;
  340. }
  341. /**
  342. * Check if access requires secure connection
  343. *
  344. * @param Controller $controller Instantiating controller
  345. * @return bool true if secure connection required
  346. */
  347. protected function _secureRequired(Controller $controller) {
  348. if (is_array($this->requireSecure) && !empty($this->requireSecure)) {
  349. $requireSecure = $this->requireSecure;
  350. if (in_array($this->_action, $requireSecure) || $this->requireSecure === array('*')) {
  351. if (!$this->request->is('ssl')) {
  352. if (!$this->blackHole($controller, 'secure')) {
  353. return null;
  354. }
  355. }
  356. }
  357. }
  358. return true;
  359. }
  360. /**
  361. * Check if authentication is required
  362. *
  363. * @param Controller $controller Instantiating controller
  364. * @return bool true if authentication required
  365. */
  366. protected function _authRequired(Controller $controller) {
  367. if (is_array($this->requireAuth) && !empty($this->requireAuth) && !empty($this->request->data)) {
  368. $requireAuth = $this->requireAuth;
  369. if (in_array($this->request->params['action'], $requireAuth) || $this->requireAuth === array('*')) {
  370. if (!isset($controller->request->data['_Token'])) {
  371. if (!$this->blackHole($controller, 'auth')) {
  372. return null;
  373. }
  374. }
  375. if ($this->Session->check('_Token')) {
  376. $tData = $this->Session->read('_Token');
  377. if (
  378. !empty($tData['allowedControllers']) &&
  379. !in_array($this->request->params['controller'], $tData['allowedControllers']) ||
  380. !empty($tData['allowedActions']) &&
  381. !in_array($this->request->params['action'], $tData['allowedActions'])
  382. ) {
  383. if (!$this->blackHole($controller, 'auth')) {
  384. return null;
  385. }
  386. }
  387. } else {
  388. if (!$this->blackHole($controller, 'auth')) {
  389. return null;
  390. }
  391. }
  392. }
  393. }
  394. return true;
  395. }
  396. /**
  397. * Validate submitted form
  398. *
  399. * @param Controller $controller Instantiating controller
  400. * @return bool true if submitted form is valid
  401. */
  402. protected function _validatePost(Controller $controller) {
  403. if (empty($controller->request->data)) {
  404. return true;
  405. }
  406. $data = $controller->request->data;
  407. if (!isset($data['_Token']) || !isset($data['_Token']['fields']) || !isset($data['_Token']['unlocked'])) {
  408. return false;
  409. }
  410. $locked = '';
  411. $check = $controller->request->data;
  412. $token = urldecode($check['_Token']['fields']);
  413. $unlocked = urldecode($check['_Token']['unlocked']);
  414. if (strpos($token, ':')) {
  415. list($token, $locked) = explode(':', $token, 2);
  416. }
  417. unset($check['_Token']);
  418. $locked = explode('|', $locked);
  419. $unlocked = explode('|', $unlocked);
  420. $lockedFields = array();
  421. $fields = Hash::flatten($check);
  422. $fieldList = array_keys($fields);
  423. $multi = array();
  424. foreach ($fieldList as $i => $key) {
  425. if (preg_match('/(\.\d+){1,10}$/', $key)) {
  426. $multi[$i] = preg_replace('/(\.\d+){1,10}$/', '', $key);
  427. unset($fieldList[$i]);
  428. }
  429. }
  430. if (!empty($multi)) {
  431. $fieldList += array_unique($multi);
  432. }
  433. $unlockedFields = array_unique(
  434. array_merge((array)$this->disabledFields, (array)$this->unlockedFields, $unlocked)
  435. );
  436. foreach ($fieldList as $i => $key) {
  437. $isLocked = (is_array($locked) && in_array($key, $locked));
  438. if (!empty($unlockedFields)) {
  439. foreach ($unlockedFields as $off) {
  440. $off = explode('.', $off);
  441. $field = array_values(array_intersect(explode('.', $key), $off));
  442. $isUnlocked = ($field === $off);
  443. if ($isUnlocked) {
  444. break;
  445. }
  446. }
  447. }
  448. if ($isUnlocked || $isLocked) {
  449. unset($fieldList[$i]);
  450. if ($isLocked) {
  451. $lockedFields[$key] = $fields[$key];
  452. }
  453. }
  454. }
  455. sort($unlocked, SORT_STRING);
  456. sort($fieldList, SORT_STRING);
  457. ksort($lockedFields, SORT_STRING);
  458. $fieldList += $lockedFields;
  459. $unlocked = implode('|', $unlocked);
  460. $hashParts = array(
  461. $this->request->here(),
  462. serialize($fieldList),
  463. $unlocked,
  464. Configure::read('Security.salt')
  465. );
  466. $check = Security::hash(implode('', $hashParts), 'sha1');
  467. return ($token === $check);
  468. }
  469. /**
  470. * Manually add CSRF token information into the provided request object.
  471. *
  472. * @param CakeRequest $request The request object to add into.
  473. * @return bool
  474. */
  475. public function generateToken(CakeRequest $request) {
  476. if (isset($request->params['requested']) && $request->params['requested'] === 1) {
  477. if ($this->Session->check('_Token')) {
  478. $request->params['_Token'] = $this->Session->read('_Token');
  479. }
  480. return false;
  481. }
  482. $authKey = Security::generateAuthKey();
  483. $token = array(
  484. 'key' => $authKey,
  485. 'allowedControllers' => $this->allowedControllers,
  486. 'allowedActions' => $this->allowedActions,
  487. 'unlockedFields' => array_merge($this->disabledFields, $this->unlockedFields),
  488. 'csrfTokens' => array()
  489. );
  490. $tokenData = array();
  491. if ($this->Session->check('_Token')) {
  492. $tokenData = $this->Session->read('_Token');
  493. if (!empty($tokenData['csrfTokens']) && is_array($tokenData['csrfTokens'])) {
  494. $token['csrfTokens'] = $this->_expireTokens($tokenData['csrfTokens']);
  495. }
  496. }
  497. if ($this->csrfUseOnce || empty($token['csrfTokens'])) {
  498. $token['csrfTokens'][$authKey] = strtotime($this->csrfExpires);
  499. }
  500. if (!$this->csrfUseOnce) {
  501. $csrfTokens = array_keys($token['csrfTokens']);
  502. $authKey = $csrfTokens[0];
  503. $token['key'] = $authKey;
  504. $token['csrfTokens'][$authKey] = strtotime($this->csrfExpires);
  505. }
  506. $this->Session->write('_Token', $token);
  507. $request->params['_Token'] = array(
  508. 'key' => $token['key'],
  509. 'unlockedFields' => $token['unlockedFields']
  510. );
  511. return true;
  512. }
  513. /**
  514. * Validate that the controller has a CSRF token in the POST data
  515. * and that the token is legit/not expired. If the token is valid
  516. * it will be removed from the list of valid tokens.
  517. *
  518. * @param Controller $controller A controller to check
  519. * @return bool Valid csrf token.
  520. */
  521. protected function _validateCsrf(Controller $controller) {
  522. $token = $this->Session->read('_Token');
  523. $requestToken = $controller->request->data('_Token.key');
  524. if (isset($token['csrfTokens'][$requestToken]) && $token['csrfTokens'][$requestToken] >= time()) {
  525. if ($this->csrfUseOnce) {
  526. $this->Session->delete('_Token.csrfTokens.' . $requestToken);
  527. }
  528. return true;
  529. }
  530. return false;
  531. }
  532. /**
  533. * Expire CSRF nonces and remove them from the valid tokens.
  534. * Uses a simple timeout to expire the tokens.
  535. *
  536. * @param array $tokens An array of nonce => expires.
  537. * @return array An array of nonce => expires.
  538. */
  539. protected function _expireTokens($tokens) {
  540. $now = time();
  541. foreach ($tokens as $nonce => $expires) {
  542. if ($expires < $now) {
  543. unset($tokens[$nonce]);
  544. }
  545. }
  546. $overflow = count($tokens) - $this->csrfLimit;
  547. if ($overflow > 0) {
  548. $tokens = array_slice($tokens, $overflow + 1, null, true);
  549. }
  550. return $tokens;
  551. }
  552. /**
  553. * Calls a controller callback method
  554. *
  555. * @param Controller $controller Controller to run callback on
  556. * @param string $method Method to execute
  557. * @param array $params Parameters to send to method
  558. * @return mixed Controller callback method's response
  559. * @throws BadRequestException When a the blackholeCallback is not callable.
  560. */
  561. protected function _callback(Controller $controller, $method, $params = array()) {
  562. if (!is_callable(array($controller, $method))) {
  563. throw new BadRequestException(__d('cake_dev', 'The request has been black-holed'));
  564. }
  565. return call_user_func_array(array(&$controller, $method), empty($params) ? null : $params);
  566. }
  567. }