PageRenderTime 56ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

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

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