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('CakeText', '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 3.0.0 Use CakeRequest::allowMethod() 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 3.0.0 Use CakeRequest::allowMethod() 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 3.0.0 Use CakeRequest::allowMethod() 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 3.0.0 Use CakeRequest::allowMethod() 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 3.0.0 Superseded by unlockedFields.
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 bool
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 bool
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 bool
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 int
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: $hasData = !empty($this->request->data);
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) && $hasData && $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 ($hasData && 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 3.0.0 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 3.0.0 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 3.0.0 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 3.0.0 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 bool 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 false;
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 bool 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 false;
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 bool|null 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 (!empty($tData['allowedControllers']) &&
419: !in_array($this->request->params['controller'], $tData['allowedControllers']) ||
420: !empty($tData['allowedActions']) &&
421: !in_array($this->request->params['action'], $tData['allowedActions'])
422: ) {
423: if (!$this->blackHole($controller, 'auth')) {
424: return null;
425: }
426: }
427: } else {
428: if (!$this->blackHole($controller, 'auth')) {
429: return null;
430: }
431: }
432: }
433: }
434: return true;
435: }
436:
437: /**
438: * Validate submitted form
439: *
440: * @param Controller $controller Instantiating controller
441: * @return bool true if submitted form is valid
442: */
443: protected function _validatePost(Controller $controller) {
444: if (empty($controller->request->data)) {
445: return true;
446: }
447: $data = $controller->request->data;
448:
449: if (!isset($data['_Token']) || !isset($data['_Token']['fields']) || !isset($data['_Token']['unlocked'])) {
450: return false;
451: }
452:
453: $locked = '';
454: $check = $controller->request->data;
455: $token = urldecode($check['_Token']['fields']);
456: $unlocked = urldecode($check['_Token']['unlocked']);
457:
458: if (strpos($token, ':')) {
459: list($token, $locked) = explode(':', $token, 2);
460: }
461: unset($check['_Token']);
462:
463: $locked = explode('|', $locked);
464: $unlocked = explode('|', $unlocked);
465:
466: $lockedFields = array();
467: $fields = Hash::flatten($check);
468: $fieldList = array_keys($fields);
469: $multi = array();
470:
471: foreach ($fieldList as $i => $key) {
472: if (preg_match('/(\.\d+){1,10}$/', $key)) {
473: $multi[$i] = preg_replace('/(\.\d+){1,10}$/', '', $key);
474: unset($fieldList[$i]);
475: }
476: }
477: if (!empty($multi)) {
478: $fieldList += array_unique($multi);
479: }
480:
481: $unlockedFields = array_unique(
482: array_merge((array)$this->disabledFields, (array)$this->unlockedFields, $unlocked)
483: );
484:
485: foreach ($fieldList as $i => $key) {
486: $isLocked = (is_array($locked) && in_array($key, $locked));
487:
488: if (!empty($unlockedFields)) {
489: foreach ($unlockedFields as $off) {
490: $off = explode('.', $off);
491: $field = array_values(array_intersect(explode('.', $key), $off));
492: $isUnlocked = ($field === $off);
493: if ($isUnlocked) {
494: break;
495: }
496: }
497: }
498:
499: if ($isUnlocked || $isLocked) {
500: unset($fieldList[$i]);
501: if ($isLocked) {
502: $lockedFields[$key] = $fields[$key];
503: }
504: }
505: }
506: sort($unlocked, SORT_STRING);
507: sort($fieldList, SORT_STRING);
508: ksort($lockedFields, SORT_STRING);
509:
510: $fieldList += $lockedFields;
511: $unlocked = implode('|', $unlocked);
512: $hashParts = array(
513: $this->request->here(),
514: serialize($fieldList),
515: $unlocked,
516: Configure::read('Security.salt')
517: );
518: $check = Security::hash(implode('', $hashParts), 'sha1');
519: return ($token === $check);
520: }
521:
522: /**
523: * Manually add CSRF token information into the provided request object.
524: *
525: * @param CakeRequest $request The request object to add into.
526: * @return bool
527: */
528: public function generateToken(CakeRequest $request) {
529: if (isset($request->params['requested']) && $request->params['requested'] === 1) {
530: if ($this->Session->check('_Token')) {
531: $request->params['_Token'] = $this->Session->read('_Token');
532: }
533: return false;
534: }
535: $authKey = Security::generateAuthKey();
536: $token = array(
537: 'key' => $authKey,
538: 'allowedControllers' => $this->allowedControllers,
539: 'allowedActions' => $this->allowedActions,
540: 'unlockedFields' => array_merge($this->disabledFields, $this->unlockedFields),
541: 'csrfTokens' => array()
542: );
543:
544: $tokenData = array();
545: if ($this->Session->check('_Token')) {
546: $tokenData = $this->Session->read('_Token');
547: if (!empty($tokenData['csrfTokens']) && is_array($tokenData['csrfTokens'])) {
548: $token['csrfTokens'] = $this->_expireTokens($tokenData['csrfTokens']);
549: }
550: }
551: if ($this->csrfUseOnce || empty($token['csrfTokens'])) {
552: $token['csrfTokens'][$authKey] = strtotime($this->csrfExpires);
553: }
554: if (!$this->csrfUseOnce) {
555: $csrfTokens = array_keys($token['csrfTokens']);
556: $authKey = $csrfTokens[0];
557: $token['key'] = $authKey;
558: $token['csrfTokens'][$authKey] = strtotime($this->csrfExpires);
559: }
560: $this->Session->write('_Token', $token);
561: $request->params['_Token'] = array(
562: 'key' => $token['key'],
563: 'unlockedFields' => $token['unlockedFields']
564: );
565: return true;
566: }
567:
568: /**
569: * Validate that the controller has a CSRF token in the POST data
570: * and that the token is legit/not expired. If the token is valid
571: * it will be removed from the list of valid tokens.
572: *
573: * @param Controller $controller A controller to check
574: * @return bool Valid csrf token.
575: */
576: protected function _validateCsrf(Controller $controller) {
577: $token = $this->Session->read('_Token');
578: $requestToken = $controller->request->data('_Token.key');
579: if (isset($token['csrfTokens'][$requestToken]) && $token['csrfTokens'][$requestToken] >= time()) {
580: if ($this->csrfUseOnce) {
581: $this->Session->delete('_Token.csrfTokens.' . $requestToken);
582: }
583: return true;
584: }
585: return false;
586: }
587:
588: /**
589: * Expire CSRF nonces and remove them from the valid tokens.
590: * Uses a simple timeout to expire the tokens.
591: *
592: * @param array $tokens An array of nonce => expires.
593: * @return array An array of nonce => expires.
594: */
595: protected function _expireTokens($tokens) {
596: $now = time();
597: foreach ($tokens as $nonce => $expires) {
598: if ($expires < $now) {
599: unset($tokens[$nonce]);
600: }
601: }
602: $overflow = count($tokens) - $this->csrfLimit;
603: if ($overflow > 0) {
604: $tokens = array_slice($tokens, $overflow + 1, null, true);
605: }
606: return $tokens;
607: }
608:
609: /**
610: * Calls a controller callback method
611: *
612: * @param Controller $controller Controller to run callback on
613: * @param string $method Method to execute
614: * @param array $params Parameters to send to method
615: * @return mixed Controller callback method's response
616: * @throws BadRequestException When a the blackholeCallback is not callable.
617: */
618: protected function _callback(Controller $controller, $method, $params = array()) {
619: if (!is_callable(array($controller, $method))) {
620: throw new BadRequestException(__d('cake_dev', 'The request has been black-holed'));
621: }
622: return call_user_func_array(array(&$controller, $method), empty($params) ? null : $params);
623: }
624:
625: }
626: