| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409 |
- <?php
- /**
- * Security Component
- *
- * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
- * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
- *
- * Licensed under The MIT License
- * For full copyright and license information, please see the LICENSE.txt
- * Redistributions of files must retain the above copyright notice.
- *
- * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
- * @link http://cakephp.org CakePHP(tm) Project
- * @since CakePHP(tm) v 0.10.8.2156
- * @license http://www.opensource.org/licenses/mit-license.php MIT License
- */
- namespace Cake\Controller\Component;
- use Cake\Controller\Component;
- use Cake\Controller\ComponentRegistry;
- use Cake\Controller\Controller;
- use Cake\Core\Configure;
- use Cake\Error;
- use Cake\Event\Event;
- use Cake\Network\Request;
- use Cake\Utility\Hash;
- use Cake\Utility\Security;
- /**
- * The Security Component creates an easy way to integrate tighter security in
- * your application. It provides methods for various tasks like:
- *
- * - Restricting which HTTP methods your application accepts.
- * - Form tampering protection
- * - Requiring that SSL be used.
- * - Limiting cross controller communication.
- *
- * @link http://book.cakephp.org/2.0/en/core-libraries/components/security-component.html
- */
- class SecurityComponent extends Component {
- /**
- * The controller method that will be called if this request is black-hole'd
- *
- * @var string
- */
- public $blackHoleCallback = null;
- /**
- * List of actions that require an SSL-secured connection
- *
- * @var array
- * @see SecurityComponent::requireSecure()
- */
- public $requireSecure = array();
- /**
- * List of actions that require a valid authentication key
- *
- * @var array
- * @see SecurityComponent::requireAuth()
- */
- public $requireAuth = array();
- /**
- * Controllers from which actions of the current controller are allowed to receive
- * requests.
- *
- * @var array
- * @see SecurityComponent::requireAuth()
- */
- public $allowedControllers = array();
- /**
- * Actions from which actions of the current controller are allowed to receive
- * requests.
- *
- * @var array
- * @see SecurityComponent::requireAuth()
- */
- public $allowedActions = array();
- /**
- * Form fields to exclude from POST validation. Fields can be unlocked
- * either in the Component, or with FormHelper::unlockField().
- * Fields that have been unlocked are not required to be part of the POST
- * and hidden unlocked fields do not have their values checked.
- *
- * @var array
- */
- public $unlockedFields = array();
- /**
- * Actions to exclude from POST validation checks.
- * Other checks like requireAuth(), requireSecure()
- * etc. will still be applied.
- *
- * @var array
- */
- public $unlockedActions = array();
- /**
- * Whether to validate POST data. Set to false to disable for data coming from 3rd party
- * services, etc.
- *
- * @var boolean
- */
- public $validatePost = true;
- /**
- * Other components used by the Security component
- *
- * @var array
- */
- public $components = array('Session');
- /**
- * Holds the current action of the controller
- *
- * @var string
- */
- protected $_action = null;
- /**
- * Request object
- *
- * @var Cake\Network\Request
- */
- public $request;
- /**
- * Component startup. All security checking happens here.
- *
- * @param Event $event An Event instance
- * @return void
- */
- public function startup(Event $event) {
- $controller = $event->subject();
- $this->request = $controller->request;
- $this->_action = $this->request->params['action'];
- $this->_secureRequired($controller);
- $this->_authRequired($controller);
- $isPost = $this->request->is(array('post', 'put'));
- $isNotRequestAction = (
- !isset($controller->request->params['requested']) ||
- $controller->request->params['requested'] != 1
- );
- if ($this->_action == $this->blackHoleCallback) {
- return $this->blackHole($controller, 'auth');
- }
- if (!in_array($this->_action, (array)$this->unlockedActions) && $isPost && $isNotRequestAction) {
- if ($this->validatePost && $this->_validatePost($controller) === false) {
- return $this->blackHole($controller, 'auth');
- }
- }
- $this->generateToken($controller->request);
- if ($isPost && is_array($controller->request->data)) {
- unset($controller->request->data['_Token']);
- }
- }
- /**
- * Sets the actions that require a request that is SSL-secured, or empty for all actions
- *
- * @return void
- * @link http://book.cakephp.org/2.0/en/core-libraries/components/security-component.html#SecurityComponent::requireSecure
- */
- public function requireSecure() {
- $args = func_get_args();
- $this->_requireMethod('Secure', $args);
- }
- /**
- * Sets the actions that require whitelisted form submissions.
- *
- * Adding actions with this method will enforce the restrictions
- * set in SecurityComponent::$allowedControllers and
- * SecurityComponent::$allowedActions.
- *
- * @return void
- * @link http://book.cakephp.org/2.0/en/core-libraries/components/security-component.html#SecurityComponent::requireAuth
- */
- public function requireAuth() {
- $args = func_get_args();
- $this->_requireMethod('Auth', $args);
- }
- /**
- * Black-hole an invalid request with a 400 error or custom callback. If SecurityComponent::$blackHoleCallback
- * is specified, it will use this callback by executing the method indicated in $error
- *
- * @param Controller $controller Instantiating controller
- * @param string $error Error method
- * @return mixed If specified, controller blackHoleCallback's response, or no return otherwise
- * @see SecurityComponent::$blackHoleCallback
- * @link http://book.cakephp.org/2.0/en/core-libraries/components/security-component.html#handling-blackhole-callbacks
- * @throws Cake\Error\BadRequestException
- */
- public function blackHole(Controller $controller, $error = '') {
- if (!$this->blackHoleCallback) {
- throw new Error\BadRequestException('The request has been black-holed');
- }
- return $this->_callback($controller, $this->blackHoleCallback, array($error));
- }
- /**
- * Sets the actions that require a $method HTTP request, or empty for all actions
- *
- * @param string $method The HTTP method to assign controller actions to
- * @param array $actions Controller actions to set the required HTTP method to.
- * @return void
- */
- protected function _requireMethod($method, $actions = array()) {
- if (isset($actions[0]) && is_array($actions[0])) {
- $actions = $actions[0];
- }
- $this->{'require' . $method} = (empty($actions)) ? array('*') : $actions;
- }
- /**
- * Check if access requires secure connection
- *
- * @param Controller $controller Instantiating controller
- * @return boolean true if secure connection required
- */
- protected function _secureRequired(Controller $controller) {
- if (is_array($this->requireSecure) && !empty($this->requireSecure)) {
- $requireSecure = $this->requireSecure;
- if (in_array($this->_action, $requireSecure) || $this->requireSecure == array('*')) {
- if (!$this->request->is('ssl')) {
- if (!$this->blackHole($controller, 'secure')) {
- return null;
- }
- }
- }
- }
- return true;
- }
- /**
- * Check if authentication is required
- *
- * @param Controller $controller Instantiating controller
- * @return boolean true if authentication required
- */
- protected function _authRequired(Controller $controller) {
- if (is_array($this->requireAuth) && !empty($this->requireAuth) && !empty($this->request->data)) {
- $requireAuth = $this->requireAuth;
- if (in_array($this->request->params['action'], $requireAuth) || $this->requireAuth == array('*')) {
- if (!isset($controller->request->data['_Token'])) {
- if (!$this->blackHole($controller, 'auth')) {
- return null;
- }
- }
- if ($this->Session->check('_Token')) {
- $tData = $this->Session->read('_Token');
- if (
- !empty($tData['allowedControllers']) &&
- !in_array($this->request->params['controller'], $tData['allowedControllers']) ||
- !empty($tData['allowedActions']) &&
- !in_array($this->request->params['action'], $tData['allowedActions'])
- ) {
- if (!$this->blackHole($controller, 'auth')) {
- return null;
- }
- }
- } else {
- if (!$this->blackHole($controller, 'auth')) {
- return null;
- }
- }
- }
- }
- return true;
- }
- /**
- * Validate submitted form
- *
- * @param Controller $controller Instantiating controller
- * @return boolean true if submitted form is valid
- */
- protected function _validatePost(Controller $controller) {
- if (empty($controller->request->data)) {
- return true;
- }
- $data = $controller->request->data;
- if (!isset($data['_Token']) || !isset($data['_Token']['fields']) || !isset($data['_Token']['unlocked'])) {
- return false;
- }
- $locked = '';
- $check = $controller->request->data;
- $token = urldecode($check['_Token']['fields']);
- $unlocked = urldecode($check['_Token']['unlocked']);
- if (strpos($token, ':')) {
- list($token, $locked) = explode(':', $token, 2);
- }
- unset($check['_Token']);
- $locked = explode('|', $locked);
- $unlocked = explode('|', $unlocked);
- $lockedFields = array();
- $fields = Hash::flatten($check);
- $fieldList = array_keys($fields);
- $multi = array();
- foreach ($fieldList as $i => $key) {
- if (preg_match('/(\.\d+)+$/', $key)) {
- $multi[$i] = preg_replace('/(\.\d+)+$/', '', $key);
- unset($fieldList[$i]);
- }
- }
- if (!empty($multi)) {
- $fieldList += array_unique($multi);
- }
- $unlockedFields = array_unique(
- array_merge((array)$this->disabledFields, (array)$this->unlockedFields, $unlocked)
- );
- foreach ($fieldList as $i => $key) {
- $isLocked = (is_array($locked) && in_array($key, $locked));
- if (!empty($unlockedFields)) {
- foreach ($unlockedFields as $off) {
- $off = explode('.', $off);
- $field = array_values(array_intersect(explode('.', $key), $off));
- $isUnlocked = ($field === $off);
- if ($isUnlocked) {
- break;
- }
- }
- }
- if ($isUnlocked || $isLocked) {
- unset($fieldList[$i]);
- if ($isLocked) {
- $lockedFields[$key] = $fields[$key];
- }
- }
- }
- sort($unlocked, SORT_STRING);
- sort($fieldList, SORT_STRING);
- ksort($lockedFields, SORT_STRING);
- $fieldList += $lockedFields;
- $unlocked = implode('|', $unlocked);
- $check = Security::hash(serialize($fieldList) . $unlocked . Configure::read('Security.salt'), 'sha1');
- return ($token === $check);
- }
- /**
- * Manually add CSRF token information into the provided request object.
- *
- * @param Cake\Network\Request $request The request object to add into.
- * @return boolean
- */
- public function generateToken(Request $request) {
- if (isset($request->params['requested']) && $request->params['requested'] === 1) {
- if ($this->Session->check('_Token')) {
- $request->params['_Token'] = $this->Session->read('_Token');
- }
- return false;
- }
- $token = array(
- 'allowedControllers' => $this->allowedControllers,
- 'allowedActions' => $this->allowedActions,
- 'unlockedFields' => $this->unlockedFields,
- );
- $tokenData = array();
- if ($this->Session->check('_Token')) {
- $tokenData = $this->Session->read('_Token');
- }
- $this->Session->write('_Token', $token);
- $request->params['_Token'] = array(
- 'unlockedFields' => $token['unlockedFields']
- );
- return true;
- }
- /**
- * Calls a controller callback method
- *
- * @param Controller $controller Controller to run callback on
- * @param string $method Method to execute
- * @param array $params Parameters to send to method
- * @return mixed Controller callback method's response
- * @throws Cake\Error\BadRequestException When a the blackholeCallback is not callable.
- */
- protected function _callback(Controller $controller, $method, $params = array()) {
- if (!is_callable(array($controller, $method))) {
- throw new Error\BadRequestException('The request has been black-holed');
- }
- return call_user_func_array(array(&$controller, $method), empty($params) ? null : $params);
- }
- }
|