SecurityComponent.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. <?php
  2. /**
  3. * Security Component
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright 2005-2010, 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-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. * @link http://cakephp.org CakePHP(tm) Project
  15. * @package cake.libs.controller.components
  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.libs.controller.components
  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. * @access public
  34. */
  35. public $blackHoleCallback = null;
  36. /**
  37. * List of controller actions for which a POST request is required
  38. *
  39. * @var array
  40. * @access public
  41. * @see SecurityComponent::requirePost()
  42. */
  43. public $requirePost = array();
  44. /**
  45. * List of controller actions for which a GET request is required
  46. *
  47. * @var array
  48. * @access public
  49. * @see SecurityComponent::requireGet()
  50. */
  51. public $requireGet = array();
  52. /**
  53. * List of controller actions for which a PUT request is required
  54. *
  55. * @var array
  56. * @access public
  57. * @see SecurityComponent::requirePut()
  58. */
  59. public $requirePut = array();
  60. /**
  61. * List of controller actions for which a DELETE request is required
  62. *
  63. * @var array
  64. * @access public
  65. * @see SecurityComponent::requireDelete()
  66. */
  67. public $requireDelete = array();
  68. /**
  69. * List of actions that require an SSL-secured connection
  70. *
  71. * @var array
  72. * @access public
  73. * @see SecurityComponent::requireSecure()
  74. */
  75. public $requireSecure = array();
  76. /**
  77. * List of actions that require a valid authentication key
  78. *
  79. * @var array
  80. * @access public
  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. * @access public
  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. * @access public
  99. * @see SecurityComponent::requireAuth()
  100. */
  101. public $allowedActions = array();
  102. /**
  103. * Form fields to disable
  104. *
  105. * @var array
  106. * @access public
  107. */
  108. public $disabledFields = array();
  109. /**
  110. * Whether to validate POST data. Set to false to disable for data coming from 3rd party
  111. * services, etc.
  112. *
  113. * @var boolean
  114. * @access public
  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. * @access public
  147. */
  148. public $components = array('Session');
  149. /**
  150. * Holds the current action of the controller
  151. *
  152. * @var string
  153. */
  154. protected $_action = null;
  155. /**
  156. * Request object
  157. *
  158. * @var CakeRequest
  159. */
  160. public $request;
  161. /**
  162. * Component startup. All security checking happens here.
  163. *
  164. * @param object $controller Instantiating controller
  165. * @return void
  166. */
  167. public function startup($controller) {
  168. $this->request = $controller->request;
  169. $this->_action = $this->request->params['action'];
  170. $this->_methodsRequired($controller);
  171. $this->_secureRequired($controller);
  172. $this->_authRequired($controller);
  173. $isPost = ($this->request->is('post') || $this->request->is('put'));
  174. $isRequestAction = (
  175. !isset($controller->request->params['requested']) ||
  176. $controller->request->params['requested'] != 1
  177. );
  178. if ($isPost && $isRequestAction && $this->validatePost) {
  179. if ($this->_validatePost($controller) === false) {
  180. return $this->blackHole($controller, 'auth');
  181. }
  182. }
  183. if ($isPost && $this->csrfCheck) {
  184. if ($this->_validateCsrf($controller) === false) {
  185. return $this->blackHole($controller, 'csrf');
  186. }
  187. }
  188. $this->_generateToken($controller);
  189. }
  190. /**
  191. * Sets the actions that require a POST request, or empty for all actions
  192. *
  193. * @return void
  194. * @link http://book.cakephp.org/view/1299/requirePost
  195. */
  196. public function requirePost() {
  197. $args = func_get_args();
  198. $this->_requireMethod('Post', $args);
  199. }
  200. /**
  201. * Sets the actions that require a GET request, or empty for all actions
  202. *
  203. * @return void
  204. */
  205. public function requireGet() {
  206. $args = func_get_args();
  207. $this->_requireMethod('Get', $args);
  208. }
  209. /**
  210. * Sets the actions that require a PUT request, or empty for all actions
  211. *
  212. * @return void
  213. */
  214. public function requirePut() {
  215. $args = func_get_args();
  216. $this->_requireMethod('Put', $args);
  217. }
  218. /**
  219. * Sets the actions that require a DELETE request, or empty for all actions
  220. *
  221. * @return void
  222. */
  223. public function requireDelete() {
  224. $args = func_get_args();
  225. $this->_requireMethod('Delete', $args);
  226. }
  227. /**
  228. * Sets the actions that require a request that is SSL-secured, or empty for all actions
  229. *
  230. * @return void
  231. * @link http://book.cakephp.org/view/1300/requireSecure
  232. */
  233. public function requireSecure() {
  234. $args = func_get_args();
  235. $this->_requireMethod('Secure', $args);
  236. }
  237. /**
  238. * Sets the actions that require an authenticated request, or empty for all actions
  239. *
  240. * @return void
  241. * @link http://book.cakephp.org/view/1301/requireAuth
  242. */
  243. public function requireAuth() {
  244. $args = func_get_args();
  245. $this->_requireMethod('Auth', $args);
  246. }
  247. /**
  248. * Black-hole an invalid request with a 404 error or custom callback. If SecurityComponent::$blackHoleCallback
  249. * is specified, it will use this callback by executing the method indicated in $error
  250. *
  251. * @param object $controller Instantiating controller
  252. * @param string $error Error method
  253. * @return mixed If specified, controller blackHoleCallback's response, or no return otherwise
  254. * @access public
  255. * @see SecurityComponent::$blackHoleCallback
  256. * @link http://book.cakephp.org/view/1307/blackHole-object-controller-string-error
  257. */
  258. function blackHole($controller, $error = '') {
  259. if ($this->blackHoleCallback == null) {
  260. $code = 404;
  261. if ($error == 'login') {
  262. $code = 401;
  263. $controller->header($this->loginRequest());
  264. }
  265. return $controller->redirect(null, $code, true);
  266. } else {
  267. return $this->_callback($controller, $this->blackHoleCallback, array($error));
  268. }
  269. }
  270. /**
  271. * Sets the actions that require a $method HTTP request, or empty for all actions
  272. *
  273. * @param string $method The HTTP method to assign controller actions to
  274. * @param array $actions Controller actions to set the required HTTP method to.
  275. * @return void
  276. */
  277. protected function _requireMethod($method, $actions = array()) {
  278. if (isset($actions[0]) && is_array($actions[0])) {
  279. $actions = $actions[0];
  280. }
  281. $this->{'require' . $method} = (empty($actions)) ? array('*'): $actions;
  282. }
  283. /**
  284. * Check if HTTP methods are required
  285. *
  286. * @param object $controller Instantiating controller
  287. * @return bool true if $method is required
  288. */
  289. protected function _methodsRequired($controller) {
  290. foreach (array('Post', 'Get', 'Put', 'Delete') as $method) {
  291. $property = 'require' . $method;
  292. if (is_array($this->$property) && !empty($this->$property)) {
  293. $require = $this->$property;
  294. if (in_array($this->_action, $require) || $this->$property == array('*')) {
  295. if (!$this->request->is($method)) {
  296. if (!$this->blackHole($controller, $method)) {
  297. return null;
  298. }
  299. }
  300. }
  301. }
  302. }
  303. return true;
  304. }
  305. /**
  306. * Check if access requires secure connection
  307. *
  308. * @param object $controller Instantiating controller
  309. * @return bool true if secure connection required
  310. */
  311. protected function _secureRequired($controller) {
  312. if (is_array($this->requireSecure) && !empty($this->requireSecure)) {
  313. $requireSecure = $this->requireSecure;
  314. if (in_array($this->_action, $requireSecure) || $this->requireSecure == array('*')) {
  315. if (!$this->request->is('ssl')) {
  316. if (!$this->blackHole($controller, 'secure')) {
  317. return null;
  318. }
  319. }
  320. }
  321. }
  322. return true;
  323. }
  324. /**
  325. * Check if authentication is required
  326. *
  327. * @param object $controller Instantiating controller
  328. * @return bool true if authentication required
  329. */
  330. protected function _authRequired($controller) {
  331. if (is_array($this->requireAuth) && !empty($this->requireAuth) && !empty($this->request->data)) {
  332. $requireAuth = $this->requireAuth;
  333. if (in_array($this->request->params['action'], $requireAuth) || $this->requireAuth == array('*')) {
  334. if (!isset($controller->request->data['_Token'] )) {
  335. if (!$this->blackHole($controller, 'auth')) {
  336. return null;
  337. }
  338. }
  339. if ($this->Session->check('_Token')) {
  340. $tData = $this->Session->read('_Token');
  341. if (!empty($tData['allowedControllers']) && !in_array($this->request->params['controller'], $tData['allowedControllers']) || !empty($tData['allowedActions']) && !in_array($this->request->params['action'], $tData['allowedActions'])) {
  342. if (!$this->blackHole($controller, 'auth')) {
  343. return null;
  344. }
  345. }
  346. } else {
  347. if (!$this->blackHole($controller, 'auth')) {
  348. return null;
  349. }
  350. }
  351. }
  352. }
  353. return true;
  354. }
  355. /**
  356. * Validate submitted form
  357. *
  358. * @param object $controller Instantiating controller
  359. * @return bool true if submitted form is valid
  360. */
  361. protected function _validatePost($controller) {
  362. if (empty($controller->request->data)) {
  363. return true;
  364. }
  365. $data = $controller->request->data;
  366. if (!isset($data['_Token']) || !isset($data['_Token']['fields'])) {
  367. return false;
  368. }
  369. $locked = null;
  370. $check = $controller->request->data;
  371. $token = urldecode($check['_Token']['fields']);
  372. if (strpos($token, ':')) {
  373. list($token, $locked) = explode(':', $token, 2);
  374. }
  375. unset($check['_Token']);
  376. $locked = explode('|', $locked);
  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. foreach ($fieldList as $i => $key) {
  391. $isDisabled = false;
  392. $isLocked = (is_array($locked) && in_array($key, $locked));
  393. if (!empty($this->disabledFields)) {
  394. foreach ((array)$this->disabledFields as $disabled) {
  395. $disabled = explode('.', $disabled);
  396. $field = array_values(array_intersect(explode('.', $key), $disabled));
  397. $isDisabled = ($field === $disabled);
  398. if ($isDisabled) {
  399. break;
  400. }
  401. }
  402. }
  403. if ($isDisabled || $isLocked) {
  404. unset($fieldList[$i]);
  405. if ($isLocked) {
  406. $lockedFields[$key] = $fields[$key];
  407. }
  408. }
  409. }
  410. sort($fieldList, SORT_STRING);
  411. ksort($lockedFields, SORT_STRING);
  412. $fieldList += $lockedFields;
  413. $check = Security::hash(serialize($fieldList) . Configure::read('Security.salt'));
  414. return ($token === $check);
  415. }
  416. /**
  417. * Add authentication key for new form posts
  418. *
  419. * @param object $controller Instantiating controller
  420. * @return bool Success
  421. */
  422. protected function _generateToken($controller) {
  423. if (isset($controller->request->params['requested']) && $controller->request->params['requested'] === 1) {
  424. if ($this->Session->check('_Token')) {
  425. $tokenData = $this->Session->read('_Token');
  426. $controller->request->params['_Token'] = $tokenData;
  427. }
  428. return false;
  429. }
  430. $authKey = Security::generateAuthKey();
  431. $token = array(
  432. 'key' => $authKey,
  433. 'allowedControllers' => $this->allowedControllers,
  434. 'allowedActions' => $this->allowedActions,
  435. 'disabledFields' => $this->disabledFields,
  436. 'csrfTokens' => array()
  437. );
  438. $tokenData = array();
  439. if ($this->Session->check('_Token')) {
  440. $tokenData = $this->Session->read('_Token');
  441. if (!empty($tokenData['csrfTokens']) && is_array($tokenData['csrfTokens'])) {
  442. $token['csrfTokens'] = $this->_expireTokens($tokenData['csrfTokens']);
  443. }
  444. }
  445. if ($this->csrfCheck && ($this->csrfUseOnce || empty($tokenData['csrfTokens'])) ) {
  446. $token['csrfTokens'][$authKey] = strtotime($this->csrfExpires);
  447. }
  448. $this->Session->write('_Token', $token);
  449. $controller->request->params['_Token'] = array(
  450. 'key' => $token['key'],
  451. 'disabledFields' => $token['disabledFields']
  452. );
  453. return true;
  454. }
  455. /**
  456. * Validate that the controller has a CSRF token in the POST data
  457. * and that the token is legit/not expired. If the token is valid
  458. * it will be removed from the list of valid tokens.
  459. *
  460. * @param Controller $controller A controller to check
  461. * @return boolean Valid csrf token.
  462. */
  463. protected function _validateCsrf($controller) {
  464. $token = $this->Session->read('_Token');
  465. $requestToken = $controller->request->data('_Token.key');
  466. if (isset($token['csrfTokens'][$requestToken]) && $token['csrfTokens'][$requestToken] >= time()) {
  467. if ($this->csrfUseOnce) {
  468. $this->Session->delete('_Token.csrfTokens.' . $requestToken);
  469. }
  470. return true;
  471. }
  472. return false;
  473. }
  474. /**
  475. * Expire CSRF nonces and remove them from the valid tokens.
  476. * Uses a simple timeout to expire the tokens.
  477. *
  478. * @param array $tokens An array of nonce => expires.
  479. * @return An array of nonce => expires.
  480. */
  481. protected function _expireTokens($tokens) {
  482. $now = time();
  483. foreach ($tokens as $nonce => $expires) {
  484. if ($expires < $now) {
  485. unset($tokens[$nonce]);
  486. }
  487. }
  488. return $tokens;
  489. }
  490. /**
  491. * Calls a controller callback method
  492. *
  493. * @param object $controller Controller to run callback on
  494. * @param string $method Method to execute
  495. * @param array $params Parameters to send to method
  496. * @return mixed Controller callback method's response
  497. */
  498. protected function _callback($controller, $method, $params = array()) {
  499. if (is_callable(array($controller, $method))) {
  500. return call_user_func_array(array(&$controller, $method), empty($params) ? null : $params);
  501. } else {
  502. return null;
  503. }
  504. }
  505. }