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.9 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.9
      • 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
  • None

Classes

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