PageRenderTime 44ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/en/core-libraries/components/security-component.rst

https://bitbucket.org/cakephp/docs
ReStructuredText | 332 lines | 243 code | 89 blank | 0 comment | 0 complexity | 64f7a8f593a5668a2acf232565c936cb MD5 | raw file
  1. Security
  2. ########
  3. .. php:class:: SecurityComponent(ComponentCollection $collection, array $settings = array())
  4. The Security Component creates an easy way to integrate tighter
  5. security in your application. It provides methods for various tasks like:
  6. * Restricting which HTTP methods your application accepts.
  7. * CSRF protection.
  8. * Form tampering protection
  9. * Requiring that SSL be used.
  10. * Limiting cross controller communication.
  11. Like all components it is configured through several configurable parameters.
  12. All of these properties can be set directly or through setter methods of the
  13. same name in your controller's beforeFilter.
  14. By using the Security Component you automatically get
  15. `CSRF <http://en.wikipedia.org/wiki/Cross-site_request_forgery>`_
  16. and form tampering protection. Hidden token fields will
  17. automatically be inserted into forms and checked by the Security
  18. component. Among other things, a form submission will not be
  19. accepted after a certain period of inactivity, which is controlled by
  20. the ``csrfExpires`` time.
  21. If you are using Security component's form protection features and
  22. other components that process form data in their ``startup()``
  23. callbacks, be sure to place Security Component before those
  24. components in your ``$components`` array.
  25. .. note::
  26. When using the Security Component you **must** use the FormHelper to create
  27. your forms. In addition, you must **not** override any of the fields' "name"
  28. attributes. The Security Component looks for certain indicators that are
  29. created and managed by the FormHelper (especially those created in
  30. :php:meth:`~FormHelper::create()` and :php:meth:`~FormHelper::end()`).
  31. Dynamically altering the fields that are submitted in a POST request (e.g.
  32. disabling, deleting or creating new fields via JavaScript) is likely to
  33. trigger a black-holing of the request. See the ``$validatePost`` or
  34. ``$disabledFields`` configuration parameters.
  35. Handling blackhole callbacks
  36. ============================
  37. If an action is restricted by the Security Component it is
  38. black-holed as an invalid request which will result in a 404 error
  39. by default. You can configure this behavior by setting the
  40. ``$this->Security->blackHoleCallback`` property to a callback function
  41. in the controller.
  42. .. php:method:: blackHole(object $controller, string $error)
  43. Black-hole an invalid request with a 404 error or a custom
  44. callback. With no callback, the request will be exited. If a
  45. controller callback is set to SecurityComponent::blackHoleCallback,
  46. it will be called and passed any error information.
  47. .. php:attr:: blackHoleCallback
  48. A Controller callback that will handle and requests that are
  49. blackholed. A blackhole callback can be any public method on a controllers.
  50. The callback should expect an parameter indicating the type of error::
  51. public function beforeFilter() {
  52. $this->Security->blackHoleCallback = 'blackhole';
  53. }
  54. public function blackhole($type) {
  55. // handle errors.
  56. }
  57. The ``$type`` parameter can have the following values:
  58. * 'auth' Indicates a form validation error, or a controller/action mismatch
  59. error.
  60. * 'csrf' Indicates a CSRF error.
  61. * 'get' Indicates an HTTP method restriction failure.
  62. * 'post' Indicates an HTTP method restriction failure.
  63. * 'put' Indicates an HTTP method restriction failure.
  64. * 'delete' Indicates an HTTP method restriction failure.
  65. * 'secure' Indicates an SSL method restriction failure.
  66. Restricting HTTP methods
  67. ========================
  68. .. php:method:: requirePost()
  69. Sets the actions that require a POST request. Takes any number of
  70. arguments. Can be called with no arguments to force all actions to
  71. require a POST.
  72. .. php:method:: requireGet()
  73. Sets the actions that require a GET request. Takes any number of
  74. arguments. Can be called with no arguments to force all actions to
  75. require a GET.
  76. .. php:method:: requirePut()
  77. Sets the actions that require a PUT request. Takes any number of
  78. arguments. Can be called with no arguments to force all actions to
  79. require a PUT.
  80. .. php:method:: requireDelete()
  81. Sets the actions that require a DELETE request. Takes any number of
  82. arguments. Can be called with no arguments to force all actions to
  83. require a DELETE.
  84. Restrict actions to SSL
  85. =======================
  86. .. php:method:: requireSecure()
  87. Sets the actions that require a SSL-secured request. Takes any
  88. number of arguments. Can be called with no arguments to force all
  89. actions to require a SSL-secured.
  90. .. php:method:: requireAuth()
  91. Sets the actions that require a valid Security Component generated
  92. token. Takes any number of arguments. Can be called with no
  93. arguments to force all actions to require a valid authentication.
  94. Restricting cross controller communication
  95. ==========================================
  96. .. php:attr:: allowedControllers
  97. A List of Controller from which the actions of the current
  98. controller are allowed to receive requests from. This can be used
  99. to control cross controller requests.
  100. .. php:attr:: allowedActions
  101. Actions from which actions of the current controller are allowed to
  102. receive requests. This can be used to control cross controller
  103. requests.
  104. Form tampering prevention
  105. =========================
  106. By default ``SecurityComponent`` prevents users from tampering with forms. It
  107. does this by working with FormHelper and tracking which files are in a form. It
  108. also keeps track of the values of hidden input elements. All of this data is
  109. combined and turned into a hash. When a form is submitted, SecurityComponent
  110. will use the POST data to build the same structure and compare the hash.
  111. .. php:attr:: unlockedFields
  112. Set to a list of form fields to exclude from POST validation. Fields can be
  113. unlocked either in the Component, or with
  114. :php:meth:`FormHelper::unlockField()`. Fields that have been unlocked are
  115. not required to be part of the POST and hidden unlocked fields do not have
  116. their values checked.
  117. .. php:attr:: validatePost
  118. Set to ``false`` to completely skip the validation of POST
  119. requests, essentially turning off form validation.
  120. CSRF configuration
  121. ==================
  122. .. php:attr:: csrfCheck
  123. Whether to use CSRF protected forms. Set to ``false`` to disable
  124. CSRF protection on forms.
  125. .. php:attr:: csrfExpires
  126. The duration from when a CSRF token is created that it will expire on.
  127. Each form/page request will generate a new token that can only
  128. be submitted once unless it expires. Can be any value compatible
  129. with ``strtotime()``. The default is +30 minutes.
  130. .. php:attr:: csrfUseOnce
  131. Controls whether or not CSRF tokens are use and burn. Set to
  132. ``false`` to not generate new tokens on each request. One token
  133. will be reused until it expires. This reduces the chances of
  134. users getting invalid requests because of token consumption.
  135. It has the side effect of making CSRF less secure, as tokens are reusable.
  136. Usage
  137. =====
  138. Using the security component is generally done in the controller
  139. beforeFilter(). You would specify the security restrictions you
  140. want and the Security Component will enforce them on its startup::
  141. class WidgetController extends AppController {
  142. public $components = array('Security');
  143. public function beforeFilter() {
  144. $this->Security->requirePost('delete');
  145. }
  146. }
  147. In this example the delete action can only be successfully
  148. triggered if it receives a POST request::
  149. class WidgetController extends AppController {
  150. public $components = array('Security');
  151. public function beforeFilter() {
  152. if (isset($this->request->params['admin'])) {
  153. $this->Security->requireSecure();
  154. }
  155. }
  156. }
  157. This example would force all actions that had admin routing to
  158. require secure SSL requests::
  159. class WidgetController extends AppController {
  160. public $components = array('Security');
  161. public function beforeFilter() {
  162. if (isset($this->params['admin'])) {
  163. $this->Security->blackHoleCallback = 'forceSSL';
  164. $this->Security->requireSecure();
  165. }
  166. }
  167. public function forceSSL() {
  168. $this->redirect('https://' . env('SERVER_NAME') . $this->here);
  169. }
  170. }
  171. This example would force all actions that had admin routing to
  172. require secure SSL requests. When the request is black holed, it
  173. will call the nominated forceSSL() callback which will redirect
  174. non-secure requests to secure requests automatically.
  175. .. _security-csrf:
  176. CSRF protection
  177. ===============
  178. CSRF or Cross Site Request Forgery is a common vulnerability in web
  179. applications. It allows an attacker to capture and replay a previous request,
  180. and sometimes submit data requests using image tags or resources on other
  181. domains.
  182. Double submission and replay attacks are handled by the SecurityComponent's CSRF
  183. features. They work by adding a special token to each form request. This token
  184. once used cannot be used again. If an attempt is made to re-use an expired
  185. token the request will be blackholed.
  186. Using CSRF protection
  187. ---------------------
  188. Simply by adding the :php:class:`SecurityComponent` to your components array,
  189. you can benefit from the CSRF protection it provides. By default CSRF tokens are
  190. valid for 30 minutes and expire on use. You can control how long tokens last by setting
  191. csrfExpires on the component.::
  192. public $components = array(
  193. 'Security' => array(
  194. 'csrfExpires' => '+1 hour'
  195. )
  196. );
  197. You can also set this property in your controller's ``beforeFilter``::
  198. public function beforeFilter() {
  199. $this->Security->csrfExpires = '+1 hour';
  200. // ...
  201. }
  202. The csrfExpires property can be any value that is compatible with
  203. `strtotime() <http://php.net/manual/en/function.strtotime.php>`_. By default the
  204. :php:class:`FormHelper` will add a ``data[_Token][key]`` containing the CSRF
  205. token to every form when the component is enabled.
  206. Handling missing or expired tokens
  207. ----------------------------------
  208. Missing or expired tokens are handled similar to other security violations. The
  209. SecurityComponent's blackHoleCallback will be called with a 'csrf' parameter.
  210. This helps you filter out CSRF token failures, from other warnings.
  211. Using per-session tokens instead of one-time use tokens
  212. -------------------------------------------------------
  213. By default a new CSRF token is generated for each request, and each token can
  214. only be used one. If a token is used twice, it will be blackholed. Sometimes,
  215. this behaviour is not desirable, as it can create issues with single page
  216. applications. You can toggle on longer, multi-use tokens by setting
  217. ``csrfUseOnce`` to ``false``. This can be done in the components array, or in
  218. the ``beforeFilter`` of your controller::
  219. public $components = array(
  220. 'Security' => array(
  221. 'csrfUseOnce' => false
  222. )
  223. );
  224. This will tell the component that you want to re-use a CSRF token until it
  225. expires - which is controlled by the ``csrfExpires`` value. If you are having
  226. issues with expired tokens, this is a good balance between security and ease of
  227. use.
  228. Disabling the CSRF protection
  229. -----------------------------
  230. There may be cases where you want to disable CSRF protection on your forms for
  231. some reason. If you do want to disable this feature, you can set
  232. ``$this->Security->csrfCheck = false;`` in your ``beforeFilter`` or use the
  233. components array. By default CSRF protection is enabled, and configured to use
  234. one-use tokens.
  235. Disabling Security Component For Specific Actions
  236. =================================================
  237. There may be cases where you want to disable all security checks for an action (ex. ajax request).
  238. You may "unlock" these actions by listing them in ``$this->Security->unlockedActions`` in your
  239. ``beforeFilter``.
  240. .. versionadded:: 2.3
  241. .. meta::
  242. :title lang=en: Security
  243. :keywords lang=en: configurable parameters,security component,configuration parameters,invalid request,protection features,tighter security,holing,php class,meth,404 error,period of inactivity,csrf,array,submission,security class,disable security,unlockActions