1: <?php
2: /**
3: * Security Component
4: *
5: * PHP 5
6: *
7: * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
8: * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
9: *
10: * Licensed under The MIT License
11: * For full copyright and license information, please see the LICENSE.txt
12: * Redistributions of files must retain the above copyright notice.
13: *
14: * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
15: * @link http://cakephp.org CakePHP(tm) Project
16: * @package Cake.Controller.Component
17: * @since CakePHP(tm) v 0.10.8.2156
18: * @license http://www.opensource.org/licenses/mit-license.php MIT License
19: */
20:
21: App::uses('Component', 'Controller');
22: App::uses('String', 'Utility');
23: App::uses('Hash', 'Utility');
24: App::uses('Security', 'Utility');
25:
26: /**
27: * The Security Component creates an easy way to integrate tighter security in
28: * your application. It provides methods for various tasks like:
29: *
30: * - Restricting which HTTP methods your application accepts.
31: * - CSRF protection.
32: * - Form tampering protection
33: * - Requiring that SSL be used.
34: * - Limiting cross controller communication.
35: *
36: * @package Cake.Controller.Component
37: * @link http://book.cakephp.org/2.0/en/core-libraries/components/security-component.html
38: */
39: class SecurityComponent extends Component {
40:
41: /**
42: * The controller method that will be called if this request is black-hole'd
43: *
44: * @var string
45: */
46: public $blackHoleCallback = null;
47:
48: /**
49: * List of controller actions for which a POST request is required
50: *
51: * @var array
52: * @deprecated Use CakeRequest::onlyAllow() instead.
53: * @see SecurityComponent::requirePost()
54: */
55: public $requirePost = array();
56:
57: /**
58: * List of controller actions for which a GET request is required
59: *
60: * @var array
61: * @deprecated Use CakeRequest::onlyAllow() instead.
62: * @see SecurityComponent::requireGet()
63: */
64: public $requireGet = array();
65:
66: /**
67: * List of controller actions for which a PUT request is required
68: *
69: * @var array
70: * @deprecated Use CakeRequest::onlyAllow() instead.
71: * @see SecurityComponent::requirePut()
72: */
73: public $requirePut = array();
74:
75: /**
76: * List of controller actions for which a DELETE request is required
77: *
78: * @var array
79: * @deprecated Use CakeRequest::onlyAllow() instead.
80: * @see SecurityComponent::requireDelete()
81: */
82: public $requireDelete = array();
83:
84: /**
85: * List of actions that require an SSL-secured connection
86: *
87: * @var array
88: * @see SecurityComponent::requireSecure()
89: */
90: public $requireSecure = array();
91:
92: /**
93: * List of actions that require a valid authentication key
94: *
95: * @var array
96: * @see SecurityComponent::requireAuth()
97: */
98: public $requireAuth = array();
99:
100: /**
101: * Controllers from which actions of the current controller are allowed to receive
102: * requests.
103: *
104: * @var array
105: * @see SecurityComponent::requireAuth()
106: */
107: public $allowedControllers = array();
108:
109: /**
110: * Actions from which actions of the current controller are allowed to receive
111: * requests.
112: *
113: * @var array
114: * @see SecurityComponent::requireAuth()
115: */
116: public $allowedActions = array();
117:
118: /**
119: * Deprecated property, superseded by unlockedFields.
120: *
121: * @var array
122: * @deprecated
123: * @see SecurityComponent::$unlockedFields
124: */
125: public $disabledFields = array();
126:
127: /**
128: * Form fields to exclude from POST validation. Fields can be unlocked
129: * either in the Component, or with FormHelper::unlockField().
130: * Fields that have been unlocked are not required to be part of the POST
131: * and hidden unlocked fields do not have their values checked.
132: *
133: * @var array
134: */
135: public $unlockedFields = array();
136:
137: /**
138: * Actions to exclude from CSRF and POST validation checks.
139: * Other checks like requireAuth(), requireSecure(),
140: * requirePost(), requireGet() etc. will still be applied.
141: *
142: * @var array
143: */
144: public $unlockedActions = array();
145:
146: /**
147: * Whether to validate POST data. Set to false to disable for data coming from 3rd party
148: * services, etc.
149: *
150: * @var boolean
151: */
152: public $validatePost = true;
153:
154: /**
155: * Whether to use CSRF protected forms. Set to false to disable CSRF protection on forms.
156: *
157: * @var boolean
158: * @see http://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)
159: * @see SecurityComponent::$csrfExpires
160: */
161: public $csrfCheck = true;
162:
163: /**
164: * The duration from when a CSRF token is created that it will expire on.
165: * Each form/page request will generate a new token that can only be submitted once unless
166: * it expires. Can be any value compatible with strtotime()
167: *
168: * @var string
169: */
170: public $csrfExpires = '+30 minutes';
171:
172: /**
173: * Controls whether or not CSRF tokens are use and burn. Set to false to not generate
174: * new tokens on each request. One token will be reused until it expires. This reduces
175: * the chances of users getting invalid requests because of token consumption.
176: * It has the side effect of making CSRF less secure, as tokens are reusable.
177: *
178: * @var boolean
179: */
180: public $csrfUseOnce = true;
181:
182: /**
183: * Control the number of tokens a user can keep open.
184: * This is most useful with one-time use tokens. Since new tokens
185: * are created on each request, having a hard limit on the number of open tokens
186: * can be useful in controlling the size of the session file.
187: *
188: * When tokens are evicted, the oldest ones will be removed, as they are the most likely
189: * to be dead/expired.
190: *
191: * @var integer
192: */
193: public $csrfLimit = 100;
194:
195: /**
196: * Other components used by the Security component
197: *
198: * @var array
199: */
200: public $components = array('Session');
201:
202: /**
203: * Holds the current action of the controller
204: *
205: * @var string
206: */
207: protected $_action = null;
208:
209: /**
210: * Request object
211: *
212: * @var CakeRequest
213: */
214: public $request;
215:
216: /**
217: * Component startup. All security checking happens here.
218: *
219: * @param Controller $controller Instantiating controller
220: * @return void
221: */
222: public function startup(Controller $controller) {
223: $this->request = $controller->request;
224: $this->_action = $this->request->params['action'];
225: $this->_methodsRequired($controller);
226: $this->_secureRequired($controller);
227: $this->_authRequired($controller);
228:
229: $isPost = ($this->request->is('post') || $this->request->is('put'));
230: $isNotRequestAction = (
231: !isset($controller->request->params['requested']) ||
232: $controller->request->params['requested'] != 1
233: );
234:
235: if ($this->_action == $this->blackHoleCallback) {
236: return $this->blackHole($controller, 'auth');
237: }
238:
239: if (!in_array($this->_action, (array)$this->unlockedActions) && $isPost && $isNotRequestAction) {
240: if ($this->validatePost && $this->_validatePost($controller) === false) {
241: return $this->blackHole($controller, 'auth');
242: }
243: if ($this->csrfCheck && $this->_validateCsrf($controller) === false) {
244: return $this->blackHole($controller, 'csrf');
245: }
246: }
247: $this->generateToken($controller->request);
248: if ($isPost && is_array($controller->request->data)) {
249: unset($controller->request->data['_Token']);
250: }
251: }
252:
253: /**
254: * Sets the actions that require a POST request, or empty for all actions
255: *
256: * @return void
257: * @deprecated Use CakeRequest::onlyAllow() instead.
258: * @link http://book.cakephp.org/2.0/en/core-libraries/components/security-component.html#SecurityComponent::requirePost
259: */
260: public function requirePost() {
261: $args = func_get_args();
262: $this->_requireMethod('Post', $args);
263: }
264:
265: /**
266: * Sets the actions that require a GET request, or empty for all actions
267: *
268: * @deprecated Use CakeRequest::onlyAllow() instead.
269: * @return void
270: */
271: public function requireGet() {
272: $args = func_get_args();
273: $this->_requireMethod('Get', $args);
274: }
275:
276: /**
277: * Sets the actions that require a PUT request, or empty for all actions
278: *
279: * @deprecated Use CakeRequest::onlyAllow() instead.
280: * @return void
281: */
282: public function requirePut() {
283: $args = func_get_args();
284: $this->_requireMethod('Put', $args);
285: }
286:
287: /**
288: * Sets the actions that require a DELETE request, or empty for all actions
289: *
290: * @deprecated Use CakeRequest::onlyAllow() instead.
291: * @return void
292: */
293: public function requireDelete() {
294: $args = func_get_args();
295: $this->_requireMethod('Delete', $args);
296: }
297:
298: /**
299: * Sets the actions that require a request that is SSL-secured, or empty for all actions
300: *
301: * @return void
302: * @link http://book.cakephp.org/2.0/en/core-libraries/components/security-component.html#SecurityComponent::requireSecure
303: */
304: public function requireSecure() {
305: $args = func_get_args();
306: $this->_requireMethod('Secure', $args);
307: }
308:
309: /**
310: * Sets the actions that require whitelisted form submissions.
311: *
312: * Adding actions with this method will enforce the restrictions
313: * set in SecurityComponent::$allowedControllers and
314: * SecurityComponent::$allowedActions.
315: *
316: * @return void
317: * @link http://book.cakephp.org/2.0/en/core-libraries/components/security-component.html#SecurityComponent::requireAuth
318: */
319: public function requireAuth() {
320: $args = func_get_args();
321: $this->_requireMethod('Auth', $args);
322: }
323:
324: /**
325: * Black-hole an invalid request with a 400 error or custom callback. If SecurityComponent::$blackHoleCallback
326: * is specified, it will use this callback by executing the method indicated in $error
327: *
328: * @param Controller $controller Instantiating controller
329: * @param string $error Error method
330: * @return mixed If specified, controller blackHoleCallback's response, or no return otherwise
331: * @see SecurityComponent::$blackHoleCallback
332: * @link http://book.cakephp.org/2.0/en/core-libraries/components/security-component.html#handling-blackhole-callbacks
333: * @throws BadRequestException
334: */
335: public function blackHole(Controller $controller, $error = '') {
336: if (!$this->blackHoleCallback) {
337: throw new BadRequestException(__d('cake_dev', 'The request has been black-holed'));
338: }
339: return $this->_callback($controller, $this->blackHoleCallback, array($error));
340: }
341:
342: /**
343: * Sets the actions that require a $method HTTP request, or empty for all actions
344: *
345: * @param string $method The HTTP method to assign controller actions to
346: * @param array $actions Controller actions to set the required HTTP method to.
347: * @return void
348: */
349: protected function _requireMethod($method, $actions = array()) {
350: if (isset($actions[0]) && is_array($actions[0])) {
351: $actions = $actions[0];
352: }
353: $this->{'require' . $method} = (empty($actions)) ? array('*'): $actions;
354: }
355:
356: /**
357: * Check if HTTP methods are required
358: *
359: * @param Controller $controller Instantiating controller
360: * @return boolean true if $method is required
361: */
362: protected function _methodsRequired(Controller $controller) {
363: foreach (array('Post', 'Get', 'Put', 'Delete') as $method) {
364: $property = 'require' . $method;
365: if (is_array($this->$property) && !empty($this->$property)) {
366: $require = $this->$property;
367: if (in_array($this->_action, $require) || $this->$property == array('*')) {
368: if (!$this->request->is($method)) {
369: if (!$this->blackHole($controller, $method)) {
370: return null;
371: }
372: }
373: }
374: }
375: }
376: return true;
377: }
378:
379: /**
380: * Check if access requires secure connection
381: *
382: * @param Controller $controller Instantiating controller
383: * @return boolean true if secure connection required
384: */
385: protected function _secureRequired(Controller $controller) {
386: if (is_array($this->requireSecure) && !empty($this->requireSecure)) {
387: $requireSecure = $this->requireSecure;
388:
389: if (in_array($this->_action, $requireSecure) || $this->requireSecure == array('*')) {
390: if (!$this->request->is('ssl')) {
391: if (!$this->blackHole($controller, 'secure')) {
392: return null;
393: }
394: }
395: }
396: }
397: return true;
398: }
399:
400: /**
401: * Check if authentication is required
402: *
403: * @param Controller $controller Instantiating controller
404: * @return boolean true if authentication required
405: */
406: protected function _authRequired(Controller $controller) {
407: if (is_array($this->requireAuth) && !empty($this->requireAuth) && !empty($this->request->data)) {
408: $requireAuth = $this->requireAuth;
409:
410: if (in_array($this->request->params['action'], $requireAuth) || $this->requireAuth == array('*')) {
411: if (!isset($controller->request->data['_Token'])) {
412: if (!$this->blackHole($controller, 'auth')) {
413: return null;
414: }
415: }
416:
417: if ($this->Session->check('_Token')) {
418: $tData = $this->Session->read('_Token');
419:
420: if (
421: !empty($tData['allowedControllers']) &&
422: !in_array($this->request->params['controller'], $tData['allowedControllers']) ||
423: !empty($tData['allowedActions']) &&
424: !in_array($this->request->params['action'], $tData['allowedActions'])
425: ) {
426: if (!$this->blackHole($controller, 'auth')) {
427: return null;
428: }
429: }
430: } else {
431: if (!$this->blackHole($controller, 'auth')) {
432: return null;
433: }
434: }
435: }
436: }
437: return true;
438: }
439:
440: /**
441: * Validate submitted form
442: *
443: * @param Controller $controller Instantiating controller
444: * @return boolean true if submitted form is valid
445: */
446: protected function _validatePost(Controller $controller) {
447: if (empty($controller->request->data)) {
448: return true;
449: }
450: $data = $controller->request->data;
451:
452: if (!isset($data['_Token']) || !isset($data['_Token']['fields']) || !isset($data['_Token']['unlocked'])) {
453: return false;
454: }
455:
456: $locked = '';
457: $check = $controller->request->data;
458: $token = urldecode($check['_Token']['fields']);
459: $unlocked = urldecode($check['_Token']['unlocked']);
460:
461: if (strpos($token, ':')) {
462: list($token, $locked) = explode(':', $token, 2);
463: }
464: unset($check['_Token']);
465:
466: $locked = explode('|', $locked);
467: $unlocked = explode('|', $unlocked);
468:
469: $lockedFields = array();
470: $fields = Hash::flatten($check);
471: $fieldList = array_keys($fields);
472: $multi = array();
473:
474: foreach ($fieldList as $i => $key) {
475: if (preg_match('/(\.\d+)+$/', $key)) {
476: $multi[$i] = preg_replace('/(\.\d+)+$/', '', $key);
477: unset($fieldList[$i]);
478: }
479: }
480: if (!empty($multi)) {
481: $fieldList += array_unique($multi);
482: }
483:
484: $unlockedFields = array_unique(
485: array_merge((array)$this->disabledFields, (array)$this->unlockedFields, $unlocked)
486: );
487:
488: foreach ($fieldList as $i => $key) {
489: $isLocked = (is_array($locked) && in_array($key, $locked));
490:
491: if (!empty($unlockedFields)) {
492: foreach ($unlockedFields as $off) {
493: $off = explode('.', $off);
494: $field = array_values(array_intersect(explode('.', $key), $off));
495: $isUnlocked = ($field === $off);
496: if ($isUnlocked) {
497: break;
498: }
499: }
500: }
501:
502: if ($isUnlocked || $isLocked) {
503: unset($fieldList[$i]);
504: if ($isLocked) {
505: $lockedFields[$key] = $fields[$key];
506: }
507: }
508: }
509: sort($unlocked, SORT_STRING);
510: sort($fieldList, SORT_STRING);
511: ksort($lockedFields, SORT_STRING);
512:
513: $fieldList += $lockedFields;
514: $unlocked = implode('|', $unlocked);
515: $check = Security::hash(serialize($fieldList) . $unlocked . Configure::read('Security.salt'), 'sha1');
516: return ($token === $check);
517: }
518:
519: /**
520: * Manually add CSRF token information into the provided request object.
521: *
522: * @param CakeRequest $request The request object to add into.
523: * @return boolean
524: */
525: public function generateToken(CakeRequest $request) {
526: if (isset($request->params['requested']) && $request->params['requested'] === 1) {
527: if ($this->Session->check('_Token')) {
528: $request->params['_Token'] = $this->Session->read('_Token');
529: }
530: return false;
531: }
532: $authKey = Security::generateAuthKey();
533: $token = array(
534: 'key' => $authKey,
535: 'allowedControllers' => $this->allowedControllers,
536: 'allowedActions' => $this->allowedActions,
537: 'unlockedFields' => array_merge($this->disabledFields, $this->unlockedFields),
538: 'csrfTokens' => array()
539: );
540:
541: $tokenData = array();
542: if ($this->Session->check('_Token')) {
543: $tokenData = $this->Session->read('_Token');
544: if (!empty($tokenData['csrfTokens']) && is_array($tokenData['csrfTokens'])) {
545: $token['csrfTokens'] = $this->_expireTokens($tokenData['csrfTokens']);
546: }
547: }
548: if ($this->csrfUseOnce || empty($token['csrfTokens'])) {
549: $token['csrfTokens'][$authKey] = strtotime($this->csrfExpires);
550: }
551: if (!$this->csrfUseOnce) {
552: $csrfTokens = array_keys($token['csrfTokens']);
553: $token['key'] = $csrfTokens[0];
554: }
555: $this->Session->write('_Token', $token);
556: $request->params['_Token'] = array(
557: 'key' => $token['key'],
558: 'unlockedFields' => $token['unlockedFields']
559: );
560: return true;
561: }
562:
563: /**
564: * Validate that the controller has a CSRF token in the POST data
565: * and that the token is legit/not expired. If the token is valid
566: * it will be removed from the list of valid tokens.
567: *
568: * @param Controller $controller A controller to check
569: * @return boolean Valid csrf token.
570: */
571: protected function _validateCsrf(Controller $controller) {
572: $token = $this->Session->read('_Token');
573: $requestToken = $controller->request->data('_Token.key');
574: if (isset($token['csrfTokens'][$requestToken]) && $token['csrfTokens'][$requestToken] >= time()) {
575: if ($this->csrfUseOnce) {
576: $this->Session->delete('_Token.csrfTokens.' . $requestToken);
577: }
578: return true;
579: }
580: return false;
581: }
582:
583: /**
584: * Expire CSRF nonces and remove them from the valid tokens.
585: * Uses a simple timeout to expire the tokens.
586: *
587: * @param array $tokens An array of nonce => expires.
588: * @return array An array of nonce => expires.
589: */
590: protected function _expireTokens($tokens) {
591: $now = time();
592: foreach ($tokens as $nonce => $expires) {
593: if ($expires < $now) {
594: unset($tokens[$nonce]);
595: }
596: }
597: $overflow = count($tokens) - $this->csrfLimit;
598: if ($overflow > 0) {
599: $tokens = array_slice($tokens, $overflow + 1, null, true);
600: }
601: return $tokens;
602: }
603:
604: /**
605: * Calls a controller callback method
606: *
607: * @param Controller $controller Controller to run callback on
608: * @param string $method Method to execute
609: * @param array $params Parameters to send to method
610: * @return mixed Controller callback method's response
611: * @throws BadRequestException When a the blackholeCallback is not callable.
612: */
613: protected function _callback(Controller $controller, $method, $params = array()) {
614: if (!is_callable(array($controller, $method))) {
615: throw new BadRequestException(__d('cake_dev', 'The request has been black-holed'));
616: }
617: return call_user_func_array(array(&$controller, $method), empty($params) ? null : $params);
618: }
619:
620: }
621: