SecurityComponent.php 17 KB

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