PageRenderTime 58ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/Cake/Controller/Component/SecurityComponent.php

https://bitbucket.org/dosm123/crm
PHP | 596 lines | 275 code | 57 blank | 264 comment | 72 complexity | ee963c6bd3e10ea98ec06bc923a43489 MD5 | raw file
Possible License(s): LGPL-3.0, GPL-3.0, LGPL-2.1
  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 $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 $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 $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 $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 $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 (
  358. !empty($tData['allowedControllers']) &&
  359. !in_array($this->request->params['controller'], $tData['allowedControllers']) ||
  360. !empty($tData['allowedActions']) &&
  361. !in_array($this->request->params['action'], $tData['allowedActions'])
  362. ) {
  363. if (!$this->blackHole($controller, 'auth')) {
  364. return null;
  365. }
  366. }
  367. } else {
  368. if (!$this->blackHole($controller, 'auth')) {
  369. return null;
  370. }
  371. }
  372. }
  373. }
  374. return true;
  375. }
  376. /**
  377. * Validate submitted form
  378. *
  379. * @param Controller $controller Instantiating controller
  380. * @return boolean true if submitted form is valid
  381. */
  382. protected function _validatePost(Controller $controller) {
  383. if (empty($controller->request->data)) {
  384. return true;
  385. }
  386. $data = $controller->request->data;
  387. if (!isset($data['_Token']) || !isset($data['_Token']['fields']) || !isset($data['_Token']['unlocked'])) {
  388. return false;
  389. }
  390. $locked = '';
  391. $check = $controller->request->data;
  392. $token = urldecode($check['_Token']['fields']);
  393. $unlocked = urldecode($check['_Token']['unlocked']);
  394. if (strpos($token, ':')) {
  395. list($token, $locked) = explode(':', $token, 2);
  396. }
  397. unset($check['_Token']);
  398. $locked = explode('|', $locked);
  399. $unlocked = explode('|', $unlocked);
  400. $lockedFields = array();
  401. $fields = Set::flatten($check);
  402. $fieldList = array_keys($fields);
  403. $multi = array();
  404. foreach ($fieldList as $i => $key) {
  405. if (preg_match('/(\.\d+)+$/', $key)) {
  406. $multi[$i] = preg_replace('/(\.\d+)+$/', '', $key);
  407. unset($fieldList[$i]);
  408. }
  409. }
  410. if (!empty($multi)) {
  411. $fieldList += array_unique($multi);
  412. }
  413. $unlockedFields = array_unique(
  414. array_merge((array)$this->disabledFields, (array)$this->unlockedFields, $unlocked)
  415. );
  416. foreach ($fieldList as $i => $key) {
  417. $isLocked = (is_array($locked) && in_array($key, $locked));
  418. if (!empty($unlockedFields)) {
  419. foreach ($unlockedFields as $off) {
  420. $off = explode('.', $off);
  421. $field = array_values(array_intersect(explode('.', $key), $off));
  422. $isUnlocked = ($field === $off);
  423. if ($isUnlocked) {
  424. break;
  425. }
  426. }
  427. }
  428. if ($isUnlocked || $isLocked) {
  429. unset($fieldList[$i]);
  430. if ($isLocked) {
  431. $lockedFields[$key] = $fields[$key];
  432. }
  433. }
  434. }
  435. sort($unlocked, SORT_STRING);
  436. sort($fieldList, SORT_STRING);
  437. ksort($lockedFields, SORT_STRING);
  438. $fieldList += $lockedFields;
  439. $unlocked = implode('|', $unlocked);
  440. $check = Security::hash(serialize($fieldList) . $unlocked . Configure::read('Security.salt'));
  441. return ($token === $check);
  442. }
  443. /**
  444. * Manually add CSRF token information into the provided request object.
  445. *
  446. * @param CakeRequest $request The request object to add into.
  447. * @return boolean
  448. */
  449. public function generateToken(CakeRequest $request) {
  450. if (isset($request->params['requested']) && $request->params['requested'] === 1) {
  451. if ($this->Session->check('_Token')) {
  452. $request->params['_Token'] = $this->Session->read('_Token');
  453. }
  454. return false;
  455. }
  456. $authKey = Security::generateAuthKey();
  457. $token = array(
  458. 'key' => $authKey,
  459. 'allowedControllers' => $this->allowedControllers,
  460. 'allowedActions' => $this->allowedActions,
  461. 'unlockedFields' => array_merge($this->disabledFields, $this->unlockedFields),
  462. 'csrfTokens' => array()
  463. );
  464. $tokenData = array();
  465. if ($this->Session->check('_Token')) {
  466. $tokenData = $this->Session->read('_Token');
  467. if (!empty($tokenData['csrfTokens']) && is_array($tokenData['csrfTokens'])) {
  468. $token['csrfTokens'] = $this->_expireTokens($tokenData['csrfTokens']);
  469. }
  470. }
  471. if ($this->csrfUseOnce || empty($token['csrfTokens'])) {
  472. $token['csrfTokens'][$authKey] = strtotime($this->csrfExpires);
  473. }
  474. if (!$this->csrfUseOnce) {
  475. $csrfTokens = array_keys($token['csrfTokens']);
  476. $token['key'] = $csrfTokens[0];
  477. }
  478. $this->Session->write('_Token', $token);
  479. $request->params['_Token'] = array(
  480. 'key' => $token['key'],
  481. 'unlockedFields' => $token['unlockedFields']
  482. );
  483. return true;
  484. }
  485. /**
  486. * Validate that the controller has a CSRF token in the POST data
  487. * and that the token is legit/not expired. If the token is valid
  488. * it will be removed from the list of valid tokens.
  489. *
  490. * @param Controller $controller A controller to check
  491. * @return boolean Valid csrf token.
  492. */
  493. protected function _validateCsrf(Controller $controller) {
  494. $token = $this->Session->read('_Token');
  495. $requestToken = $controller->request->data('_Token.key');
  496. if (isset($token['csrfTokens'][$requestToken]) && $token['csrfTokens'][$requestToken] >= time()) {
  497. if ($this->csrfUseOnce) {
  498. $this->Session->delete('_Token.csrfTokens.' . $requestToken);
  499. }
  500. return true;
  501. }
  502. return false;
  503. }
  504. /**
  505. * Expire CSRF nonces and remove them from the valid tokens.
  506. * Uses a simple timeout to expire the tokens.
  507. *
  508. * @param array $tokens An array of nonce => expires.
  509. * @return array An array of nonce => expires.
  510. */
  511. protected function _expireTokens($tokens) {
  512. $now = time();
  513. foreach ($tokens as $nonce => $expires) {
  514. if ($expires < $now) {
  515. unset($tokens[$nonce]);
  516. }
  517. }
  518. $overflow = count($tokens) - $this->csrfLimit;
  519. if ($overflow > 0) {
  520. $tokens = array_slice($tokens, $overflow + 1, null, true);
  521. }
  522. return $tokens;
  523. }
  524. /**
  525. * Calls a controller callback method
  526. *
  527. * @param Controller $controller Controller to run callback on
  528. * @param string $method Method to execute
  529. * @param array $params Parameters to send to method
  530. * @return mixed Controller callback method's response
  531. */
  532. protected function _callback(Controller $controller, $method, $params = array()) {
  533. if (is_callable(array($controller, $method))) {
  534. return call_user_func_array(array(&$controller, $method), empty($params) ? null : $params);
  535. } else {
  536. return null;
  537. }
  538. }
  539. }