SecurityComponent.php 18 KB

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