SecurityComponent.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  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/view/1296/Security-Component
  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/view/1299/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/view/1300/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/view/1301/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 404 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/view/1307/blackHole-object-controller-string-error
  255. */
  256. public function blackHole($controller, $error = '') {
  257. if ($this->blackHoleCallback == null) {
  258. $code = 404;
  259. if ($error == 'login') {
  260. $code = 401;
  261. $controller->header($this->loginRequest());
  262. }
  263. return $controller->redirect(null, $code, true);
  264. } else {
  265. return $this->_callback($controller, $this->blackHoleCallback, array($error));
  266. }
  267. }
  268. /**
  269. * Sets the actions that require a $method HTTP request, or empty for all actions
  270. *
  271. * @param string $method The HTTP method to assign controller actions to
  272. * @param array $actions Controller actions to set the required HTTP method to.
  273. * @return void
  274. */
  275. protected function _requireMethod($method, $actions = array()) {
  276. if (isset($actions[0]) && is_array($actions[0])) {
  277. $actions = $actions[0];
  278. }
  279. $this->{'require' . $method} = (empty($actions)) ? array('*'): $actions;
  280. }
  281. /**
  282. * Check if HTTP methods are required
  283. *
  284. * @param Controller $controller Instantiating controller
  285. * @return boolean true if $method is required
  286. */
  287. protected function _methodsRequired($controller) {
  288. foreach (array('Post', 'Get', 'Put', 'Delete') as $method) {
  289. $property = 'require' . $method;
  290. if (is_array($this->$property) && !empty($this->$property)) {
  291. $require = $this->$property;
  292. if (in_array($this->_action, $require) || $this->$property == array('*')) {
  293. if (!$this->request->is($method)) {
  294. if (!$this->blackHole($controller, $method)) {
  295. return null;
  296. }
  297. }
  298. }
  299. }
  300. }
  301. return true;
  302. }
  303. /**
  304. * Check if access requires secure connection
  305. *
  306. * @param Controller $controller Instantiating controller
  307. * @return boolean true if secure connection required
  308. */
  309. protected function _secureRequired($controller) {
  310. if (is_array($this->requireSecure) && !empty($this->requireSecure)) {
  311. $requireSecure = $this->requireSecure;
  312. if (in_array($this->_action, $requireSecure) || $this->requireSecure == array('*')) {
  313. if (!$this->request->is('ssl')) {
  314. if (!$this->blackHole($controller, 'secure')) {
  315. return null;
  316. }
  317. }
  318. }
  319. }
  320. return true;
  321. }
  322. /**
  323. * Check if authentication is required
  324. *
  325. * @param Controller $controller Instantiating controller
  326. * @return boolean true if authentication required
  327. */
  328. protected function _authRequired($controller) {
  329. if (is_array($this->requireAuth) && !empty($this->requireAuth) && !empty($this->request->data)) {
  330. $requireAuth = $this->requireAuth;
  331. if (in_array($this->request->params['action'], $requireAuth) || $this->requireAuth == array('*')) {
  332. if (!isset($controller->request->data['_Token'] )) {
  333. if (!$this->blackHole($controller, 'auth')) {
  334. return null;
  335. }
  336. }
  337. if ($this->Session->check('_Token')) {
  338. $tData = $this->Session->read('_Token');
  339. if (!empty($tData['allowedControllers']) && !in_array($this->request->params['controller'], $tData['allowedControllers']) || !empty($tData['allowedActions']) && !in_array($this->request->params['action'], $tData['allowedActions'])) {
  340. if (!$this->blackHole($controller, 'auth')) {
  341. return null;
  342. }
  343. }
  344. } else {
  345. if (!$this->blackHole($controller, 'auth')) {
  346. return null;
  347. }
  348. }
  349. }
  350. }
  351. return true;
  352. }
  353. /**
  354. * Validate submitted form
  355. *
  356. * @param Controller $controller Instantiating controller
  357. * @return boolean true if submitted form is valid
  358. */
  359. protected function _validatePost($controller) {
  360. if (empty($controller->request->data)) {
  361. return true;
  362. }
  363. $data = $controller->request->data;
  364. if (!isset($data['_Token']) || !isset($data['_Token']['fields']) || !isset($data['_Token']['unlocked'])) {
  365. return false;
  366. }
  367. $locked = '';
  368. $check = $controller->request->data;
  369. $token = urldecode($check['_Token']['fields']);
  370. $unlocked = urldecode($check['_Token']['unlocked']);
  371. if (strpos($token, ':')) {
  372. list($token, $locked) = explode(':', $token, 2);
  373. }
  374. unset($check['_Token']);
  375. $locked = explode('|', $locked);
  376. $unlocked = explode('|', $unlocked);
  377. $lockedFields = array();
  378. $fields = Set::flatten($check);
  379. $fieldList = array_keys($fields);
  380. $multi = array();
  381. foreach ($fieldList as $i => $key) {
  382. if (preg_match('/\.\d+$/', $key)) {
  383. $multi[$i] = preg_replace('/\.\d+$/', '', $key);
  384. unset($fieldList[$i]);
  385. }
  386. }
  387. if (!empty($multi)) {
  388. $fieldList += array_unique($multi);
  389. }
  390. $unlockedFields = array_unique(
  391. array_merge((array)$this->disabledFields, (array)$this->unlockedFields, $unlocked)
  392. );
  393. foreach ($fieldList as $i => $key) {
  394. $isDisabled = false;
  395. $isLocked = (is_array($locked) && in_array($key, $locked));
  396. if (!empty($unlockedFields)) {
  397. foreach ($unlockedFields as $off) {
  398. $off = explode('.', $off);
  399. $field = array_values(array_intersect(explode('.', $key), $off));
  400. $isUnlocked = ($field === $off);
  401. if ($isUnlocked) {
  402. break;
  403. }
  404. }
  405. }
  406. if ($isUnlocked || $isLocked) {
  407. unset($fieldList[$i]);
  408. if ($isLocked) {
  409. $lockedFields[$key] = $fields[$key];
  410. }
  411. }
  412. }
  413. sort($unlocked, SORT_STRING);
  414. sort($fieldList, SORT_STRING);
  415. ksort($lockedFields, SORT_STRING);
  416. $fieldList += $lockedFields;
  417. $unlocked = implode('|', $unlocked);
  418. $check = Security::hash(serialize($fieldList) . $unlocked . Configure::read('Security.salt'));
  419. return ($token === $check);
  420. }
  421. /**
  422. * Add authentication key for new form posts
  423. *
  424. * @param Controller $controller Instantiating controller
  425. * @return boolean Success
  426. */
  427. protected function _generateToken($controller) {
  428. if (isset($controller->request->params['requested']) && $controller->request->params['requested'] === 1) {
  429. if ($this->Session->check('_Token')) {
  430. $tokenData = $this->Session->read('_Token');
  431. $controller->request->params['_Token'] = $tokenData;
  432. }
  433. return false;
  434. }
  435. $authKey = Security::generateAuthKey();
  436. $token = array(
  437. 'key' => $authKey,
  438. 'allowedControllers' => $this->allowedControllers,
  439. 'allowedActions' => $this->allowedActions,
  440. 'unlockedFields' => array_merge($this->disabledFields, $this->unlockedFields),
  441. 'csrfTokens' => array()
  442. );
  443. $tokenData = array();
  444. if ($this->Session->check('_Token')) {
  445. $tokenData = $this->Session->read('_Token');
  446. if (!empty($tokenData['csrfTokens']) && is_array($tokenData['csrfTokens'])) {
  447. $token['csrfTokens'] = $this->_expireTokens($tokenData['csrfTokens']);
  448. }
  449. }
  450. if ($this->csrfCheck && ($this->csrfUseOnce || empty($token['csrfTokens'])) ) {
  451. $token['csrfTokens'][$authKey] = strtotime($this->csrfExpires);
  452. }
  453. if ($this->csrfCheck && $this->csrfUseOnce == false) {
  454. $csrfTokens = array_keys($token['csrfTokens']);
  455. $token['key'] = $csrfTokens[0];
  456. }
  457. $this->Session->write('_Token', $token);
  458. $controller->request->params['_Token'] = array(
  459. 'key' => $token['key'],
  460. 'unlockedFields' => $token['unlockedFields']
  461. );
  462. return true;
  463. }
  464. /**
  465. * Validate that the controller has a CSRF token in the POST data
  466. * and that the token is legit/not expired. If the token is valid
  467. * it will be removed from the list of valid tokens.
  468. *
  469. * @param Controller $controller A controller to check
  470. * @return boolean Valid csrf token.
  471. */
  472. protected function _validateCsrf($controller) {
  473. $token = $this->Session->read('_Token');
  474. $requestToken = $controller->request->data('_Token.key');
  475. if (isset($token['csrfTokens'][$requestToken]) && $token['csrfTokens'][$requestToken] >= time()) {
  476. if ($this->csrfUseOnce) {
  477. $this->Session->delete('_Token.csrfTokens.' . $requestToken);
  478. }
  479. return true;
  480. }
  481. return false;
  482. }
  483. /**
  484. * Expire CSRF nonces and remove them from the valid tokens.
  485. * Uses a simple timeout to expire the tokens.
  486. *
  487. * @param array $tokens An array of nonce => expires.
  488. * @return array An array of nonce => expires.
  489. */
  490. protected function _expireTokens($tokens) {
  491. $now = time();
  492. foreach ($tokens as $nonce => $expires) {
  493. if ($expires < $now) {
  494. unset($tokens[$nonce]);
  495. }
  496. }
  497. return $tokens;
  498. }
  499. /**
  500. * Calls a controller callback method
  501. *
  502. * @param Controller $controller Controller to run callback on
  503. * @param string $method Method to execute
  504. * @param array $params Parameters to send to method
  505. * @return mixed Controller callback method's response
  506. */
  507. protected function _callback($controller, $method, $params = array()) {
  508. if (is_callable(array($controller, $method))) {
  509. return call_user_func_array(array(&$controller, $method), empty($params) ? null : $params);
  510. } else {
  511. return null;
  512. }
  513. }
  514. }