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