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

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.1
      • 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
    • Network
      • Email
      • Http
    • Routing
      • Route
    • TestSuite
      • Coverage
      • Fixture
      • Reporter
    • Utility
    • View
      • Helper

Classes

  • AclComponent
  • AuthComponent
  • CookieComponent
  • DbAcl
  • EmailComponent
  • IniAcl
  • PaginatorComponent
  • RequestHandlerComponent
  • SecurityComponent
  • SessionComponent

Interfaces

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