SecurityComponent.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  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 (!in_array($this->_action, (array)$this->unlockedActions) && $isPost && $isNotRequestAction) {
  204. if ($this->validatePost && $this->_validatePost($controller) === false) {
  205. return $this->blackHole($controller, 'auth');
  206. }
  207. if ($this->csrfCheck && $this->_validateCsrf($controller) === false) {
  208. return $this->blackHole($controller, 'csrf');
  209. }
  210. }
  211. $this->generateToken($controller->request);
  212. if ($isPost && is_array($controller->request->data)) {
  213. unset($controller->request->data['_Token']);
  214. }
  215. }
  216. /**
  217. * Sets the actions that require a POST request, or empty for all actions
  218. *
  219. * @return void
  220. * @link http://book.cakephp.org/2.0/en/core-libraries/components/security-component.html#SecurityComponent::requirePost
  221. */
  222. public function requirePost() {
  223. $args = func_get_args();
  224. $this->_requireMethod('Post', $args);
  225. }
  226. /**
  227. * Sets the actions that require a GET request, or empty for all actions
  228. *
  229. * @return void
  230. */
  231. public function requireGet() {
  232. $args = func_get_args();
  233. $this->_requireMethod('Get', $args);
  234. }
  235. /**
  236. * Sets the actions that require a PUT request, or empty for all actions
  237. *
  238. * @return void
  239. */
  240. public function requirePut() {
  241. $args = func_get_args();
  242. $this->_requireMethod('Put', $args);
  243. }
  244. /**
  245. * Sets the actions that require a DELETE request, or empty for all actions
  246. *
  247. * @return void
  248. */
  249. public function requireDelete() {
  250. $args = func_get_args();
  251. $this->_requireMethod('Delete', $args);
  252. }
  253. /**
  254. * Sets the actions that require a request that is SSL-secured, or empty for all actions
  255. *
  256. * @return void
  257. * @link http://book.cakephp.org/2.0/en/core-libraries/components/security-component.html#SecurityComponent::requireSecure
  258. */
  259. public function requireSecure() {
  260. $args = func_get_args();
  261. $this->_requireMethod('Secure', $args);
  262. }
  263. /**
  264. * Sets the actions that require an authenticated request, or empty for all actions
  265. *
  266. * @return void
  267. * @link http://book.cakephp.org/2.0/en/core-libraries/components/security-component.html#SecurityComponent::requireAuth
  268. */
  269. public function requireAuth() {
  270. $args = func_get_args();
  271. $this->_requireMethod('Auth', $args);
  272. }
  273. /**
  274. * Black-hole an invalid request with a 400 error or custom callback. If SecurityComponent::$blackHoleCallback
  275. * is specified, it will use this callback by executing the method indicated in $error
  276. *
  277. * @param Controller $controller Instantiating controller
  278. * @param string $error Error method
  279. * @return mixed If specified, controller blackHoleCallback's response, or no return otherwise
  280. * @see SecurityComponent::$blackHoleCallback
  281. * @link http://book.cakephp.org/2.0/en/core-libraries/components/security-component.html#handling-blackhole-callbacks
  282. * @throws BadRequestException
  283. */
  284. public function blackHole(Controller $controller, $error = '') {
  285. if ($this->blackHoleCallback == null) {
  286. throw new BadRequestException(__d('cake_dev', 'The request has been black-holed'));
  287. } else {
  288. return $this->_callback($controller, $this->blackHoleCallback, array($error));
  289. }
  290. }
  291. /**
  292. * Sets the actions that require a $method HTTP request, or empty for all actions
  293. *
  294. * @param string $method The HTTP method to assign controller actions to
  295. * @param array $actions Controller actions to set the required HTTP method to.
  296. * @return void
  297. */
  298. protected function _requireMethod($method, $actions = array()) {
  299. if (isset($actions[0]) && is_array($actions[0])) {
  300. $actions = $actions[0];
  301. }
  302. $this->{'require' . $method} = (empty($actions)) ? array('*'): $actions;
  303. }
  304. /**
  305. * Check if HTTP methods are required
  306. *
  307. * @param Controller $controller Instantiating controller
  308. * @return boolean true if $method is required
  309. */
  310. protected function _methodsRequired(Controller $controller) {
  311. foreach (array('Post', 'Get', 'Put', 'Delete') as $method) {
  312. $property = 'require' . $method;
  313. if (is_array($this->$property) && !empty($this->$property)) {
  314. $require = $this->$property;
  315. if (in_array($this->_action, $require) || $this->$property == array('*')) {
  316. if (!$this->request->is($method)) {
  317. if (!$this->blackHole($controller, $method)) {
  318. return null;
  319. }
  320. }
  321. }
  322. }
  323. }
  324. return true;
  325. }
  326. /**
  327. * Check if access requires secure connection
  328. *
  329. * @param Controller $controller Instantiating controller
  330. * @return boolean true if secure connection required
  331. */
  332. protected function _secureRequired(Controller $controller) {
  333. if (is_array($this->requireSecure) && !empty($this->requireSecure)) {
  334. $requireSecure = $this->requireSecure;
  335. if (in_array($this->_action, $requireSecure) || $this->requireSecure == array('*')) {
  336. if (!$this->request->is('ssl')) {
  337. if (!$this->blackHole($controller, 'secure')) {
  338. return null;
  339. }
  340. }
  341. }
  342. }
  343. return true;
  344. }
  345. /**
  346. * Check if authentication is required
  347. *
  348. * @param Controller $controller Instantiating controller
  349. * @return boolean true if authentication required
  350. */
  351. protected function _authRequired(Controller $controller) {
  352. if (is_array($this->requireAuth) && !empty($this->requireAuth) && !empty($this->request->data)) {
  353. $requireAuth = $this->requireAuth;
  354. if (in_array($this->request->params['action'], $requireAuth) || $this->requireAuth == array('*')) {
  355. if (!isset($controller->request->data['_Token'] )) {
  356. if (!$this->blackHole($controller, 'auth')) {
  357. return null;
  358. }
  359. }
  360. if ($this->Session->check('_Token')) {
  361. $tData = $this->Session->read('_Token');
  362. if (
  363. !empty($tData['allowedControllers']) &&
  364. !in_array($this->request->params['controller'], $tData['allowedControllers']) ||
  365. !empty($tData['allowedActions']) &&
  366. !in_array($this->request->params['action'], $tData['allowedActions'])
  367. ) {
  368. if (!$this->blackHole($controller, 'auth')) {
  369. return null;
  370. }
  371. }
  372. } else {
  373. if (!$this->blackHole($controller, 'auth')) {
  374. return null;
  375. }
  376. }
  377. }
  378. }
  379. return true;
  380. }
  381. /**
  382. * Validate submitted form
  383. *
  384. * @param Controller $controller Instantiating controller
  385. * @return boolean true if submitted form is valid
  386. */
  387. protected function _validatePost(Controller $controller) {
  388. if (empty($controller->request->data)) {
  389. return true;
  390. }
  391. $data = $controller->request->data;
  392. if (!isset($data['_Token']) || !isset($data['_Token']['fields']) || !isset($data['_Token']['unlocked'])) {
  393. return false;
  394. }
  395. $locked = '';
  396. $check = $controller->request->data;
  397. $token = urldecode($check['_Token']['fields']);
  398. $unlocked = urldecode($check['_Token']['unlocked']);
  399. if (strpos($token, ':')) {
  400. list($token, $locked) = explode(':', $token, 2);
  401. }
  402. unset($check['_Token']);
  403. $locked = explode('|', $locked);
  404. $unlocked = explode('|', $unlocked);
  405. $lockedFields = array();
  406. $fields = Hash::flatten($check);
  407. $fieldList = array_keys($fields);
  408. $multi = array();
  409. foreach ($fieldList as $i => $key) {
  410. if (preg_match('/(\.\d+)+$/', $key)) {
  411. $multi[$i] = preg_replace('/(\.\d+)+$/', '', $key);
  412. unset($fieldList[$i]);
  413. }
  414. }
  415. if (!empty($multi)) {
  416. $fieldList += array_unique($multi);
  417. }
  418. $unlockedFields = array_unique(
  419. array_merge((array)$this->disabledFields, (array)$this->unlockedFields, $unlocked)
  420. );
  421. foreach ($fieldList as $i => $key) {
  422. $isLocked = (is_array($locked) && in_array($key, $locked));
  423. if (!empty($unlockedFields)) {
  424. foreach ($unlockedFields as $off) {
  425. $off = explode('.', $off);
  426. $field = array_values(array_intersect(explode('.', $key), $off));
  427. $isUnlocked = ($field === $off);
  428. if ($isUnlocked) {
  429. break;
  430. }
  431. }
  432. }
  433. if ($isUnlocked || $isLocked) {
  434. unset($fieldList[$i]);
  435. if ($isLocked) {
  436. $lockedFields[$key] = $fields[$key];
  437. }
  438. }
  439. }
  440. sort($unlocked, SORT_STRING);
  441. sort($fieldList, SORT_STRING);
  442. ksort($lockedFields, SORT_STRING);
  443. $fieldList += $lockedFields;
  444. $unlocked = implode('|', $unlocked);
  445. $check = Security::hash(serialize($fieldList) . $unlocked . Configure::read('Security.salt'));
  446. return ($token === $check);
  447. }
  448. /**
  449. * Manually add CSRF token information into the provided request object.
  450. *
  451. * @param CakeRequest $request The request object to add into.
  452. * @return boolean
  453. */
  454. public function generateToken(CakeRequest $request) {
  455. if (isset($request->params['requested']) && $request->params['requested'] === 1) {
  456. if ($this->Session->check('_Token')) {
  457. $request->params['_Token'] = $this->Session->read('_Token');
  458. }
  459. return false;
  460. }
  461. $authKey = Security::generateAuthKey();
  462. $token = array(
  463. 'key' => $authKey,
  464. 'allowedControllers' => $this->allowedControllers,
  465. 'allowedActions' => $this->allowedActions,
  466. 'unlockedFields' => array_merge($this->disabledFields, $this->unlockedFields),
  467. 'csrfTokens' => array()
  468. );
  469. $tokenData = array();
  470. if ($this->Session->check('_Token')) {
  471. $tokenData = $this->Session->read('_Token');
  472. if (!empty($tokenData['csrfTokens']) && is_array($tokenData['csrfTokens'])) {
  473. $token['csrfTokens'] = $this->_expireTokens($tokenData['csrfTokens']);
  474. }
  475. }
  476. if ($this->csrfUseOnce || empty($token['csrfTokens'])) {
  477. $token['csrfTokens'][$authKey] = strtotime($this->csrfExpires);
  478. }
  479. if (!$this->csrfUseOnce) {
  480. $csrfTokens = array_keys($token['csrfTokens']);
  481. $token['key'] = $csrfTokens[0];
  482. }
  483. $this->Session->write('_Token', $token);
  484. $request->params['_Token'] = array(
  485. 'key' => $token['key'],
  486. 'unlockedFields' => $token['unlockedFields']
  487. );
  488. return true;
  489. }
  490. /**
  491. * Validate that the controller has a CSRF token in the POST data
  492. * and that the token is legit/not expired. If the token is valid
  493. * it will be removed from the list of valid tokens.
  494. *
  495. * @param Controller $controller A controller to check
  496. * @return boolean Valid csrf token.
  497. */
  498. protected function _validateCsrf(Controller $controller) {
  499. $token = $this->Session->read('_Token');
  500. $requestToken = $controller->request->data('_Token.key');
  501. if (isset($token['csrfTokens'][$requestToken]) && $token['csrfTokens'][$requestToken] >= time()) {
  502. if ($this->csrfUseOnce) {
  503. $this->Session->delete('_Token.csrfTokens.' . $requestToken);
  504. }
  505. return true;
  506. }
  507. return false;
  508. }
  509. /**
  510. * Expire CSRF nonces and remove them from the valid tokens.
  511. * Uses a simple timeout to expire the tokens.
  512. *
  513. * @param array $tokens An array of nonce => expires.
  514. * @return array An array of nonce => expires.
  515. */
  516. protected function _expireTokens($tokens) {
  517. $now = time();
  518. foreach ($tokens as $nonce => $expires) {
  519. if ($expires < $now) {
  520. unset($tokens[$nonce]);
  521. }
  522. }
  523. $overflow = count($tokens) - $this->csrfLimit;
  524. if ($overflow > 0) {
  525. $tokens = array_slice($tokens, $overflow + 1, null, true);
  526. }
  527. return $tokens;
  528. }
  529. /**
  530. * Calls a controller callback method
  531. *
  532. * @param Controller $controller Controller to run callback on
  533. * @param string $method Method to execute
  534. * @param array $params Parameters to send to method
  535. * @return mixed Controller callback method's response
  536. * @throws BadRequestException When a the blackholeCallback is not callable.
  537. */
  538. protected function _callback(Controller $controller, $method, $params = array()) {
  539. if (is_callable(array($controller, $method))) {
  540. return call_user_func_array(array(&$controller, $method), empty($params) ? null : $params);
  541. } else {
  542. throw new BadRequestException(__d('cake_dev', 'The request has been black-holed'));
  543. }
  544. }
  545. }