CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Reporting Security Issues
    • Privacy Policy
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Get Involved
    • Issues (GitHub)
    • Bakery
    • Featured Resources
    • Training
    • Meetups
    • My CakePHP
    • CakeFest
    • Newsletter
    • Linkedin
    • YouTube
    • Facebook
    • Twitter
    • Mastodon
    • Help & Support
    • Forum
    • Stack Overflow
    • Slack
    • Paid Support
CakePHP

C CakePHP 2.2 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.2
      • 4.2
      • 4.1
      • 4.0
      • 3.9
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Packages

  • Cake
    • Cache
      • Engine
    • Configure
    • Console
      • Command
        • Task
    • Controller
      • Component
        • Acl
        • Auth
    • Core
    • Error
    • Event
    • I18n
    • Log
      • Engine
    • Model
      • Behavior
      • Datasource
        • Database
        • Session
      • Validator
    • Network
      • Email
      • Http
    • Routing
      • Filter
      • Route
    • TestSuite
      • Coverage
      • Fixture
      • Reporter
    • Utility
    • View
      • Helper

Classes

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

Generated using CakePHP API Docs