SecurityComponent.php 16 KB

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