SecurityComponent.php 17 KB

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