SecurityComponent.php 16 KB

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