csrf.txt 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. =====================================
  2. Cross Site Request Forgery protection
  3. =====================================
  4. .. module:: django.middleware.csrf
  5. :synopsis: Protects against Cross Site Request Forgeries
  6. The CSRF middleware and template tag provides easy-to-use protection against
  7. `Cross Site Request Forgeries`_. This type of attack occurs when a malicious
  8. website contains a link, a form button or some JavaScript that is intended to
  9. perform some action on your website, using the credentials of a logged-in user
  10. who visits the malicious site in their browser. A related type of attack,
  11. 'login CSRF', where an attacking site tricks a user's browser into logging into
  12. a site with someone else's credentials, is also covered.
  13. The first defense against CSRF attacks is to ensure that GET requests (and other
  14. 'safe' methods, as defined by 9.1.1 Safe Methods, HTTP 1.1,
  15. :rfc:`2616#section-9.1.1`) are side-effect free. Requests via 'unsafe' methods,
  16. such as POST, PUT and DELETE, can then be protected by following the steps
  17. below.
  18. .. _Cross Site Request Forgeries: https://www.squarefree.com/securitytips/web-developers.html#CSRF
  19. .. _using-csrf:
  20. How to use it
  21. =============
  22. To take advantage of CSRF protection in your views, follow these steps:
  23. 1. The CSRF middleware is activated by default in the
  24. :setting:`MIDDLEWARE_CLASSES` setting. If you override that setting, remember
  25. that ``'django.middleware.csrf.CsrfViewMiddleware'`` should come before any
  26. view middleware that assume that CSRF attacks have been dealt with.
  27. If you disabled it, which is not recommended, you can use
  28. :func:`~django.views.decorators.csrf.csrf_protect` on particular views
  29. you want to protect (see below).
  30. 2. In any template that uses a POST form, use the :ttag:`csrf_token` tag inside
  31. the ``<form>`` element if the form is for an internal URL, e.g.::
  32. <form action="." method="post">{% csrf_token %}
  33. This should not be done for POST forms that target external URLs, since
  34. that would cause the CSRF token to be leaked, leading to a vulnerability.
  35. 3. In the corresponding view functions, ensure that
  36. :class:`~django.template.RequestContext` is used to render the response so
  37. that ``{% csrf_token %}`` will work properly. If you're using the
  38. :func:`~django.shortcuts.render` function, generic views, or contrib apps,
  39. you are covered already since these all use ``RequestContext``.
  40. .. _csrf-ajax:
  41. AJAX
  42. ----
  43. While the above method can be used for AJAX POST requests, it has some
  44. inconveniences: you have to remember to pass the CSRF token in as POST data with
  45. every POST request. For this reason, there is an alternative method: on each
  46. XMLHttpRequest, set a custom ``X-CSRFToken`` header to the value of the CSRF
  47. token. This is often easier, because many JavaScript frameworks provide hooks
  48. that allow headers to be set on every request.
  49. As a first step, you must get the CSRF token itself. The recommended source for
  50. the token is the ``csrftoken`` cookie, which will be set if you've enabled CSRF
  51. protection for your views as outlined above.
  52. .. note::
  53. The CSRF token cookie is named ``csrftoken`` by default, but you can control
  54. the cookie name via the :setting:`CSRF_COOKIE_NAME` setting.
  55. The CSRF header name is ``HTTP_X_CSRFTOKEN`` by default, but you can
  56. customize it using the :setting:`CSRF_HEADER_NAME` setting.
  57. Acquiring the token is straightforward:
  58. .. code-block:: javascript
  59. // using jQuery
  60. function getCookie(name) {
  61. var cookieValue = null;
  62. if (document.cookie && document.cookie != '') {
  63. var cookies = document.cookie.split(';');
  64. for (var i = 0; i < cookies.length; i++) {
  65. var cookie = jQuery.trim(cookies[i]);
  66. // Does this cookie string begin with the name we want?
  67. if (cookie.substring(0, name.length + 1) == (name + '=')) {
  68. cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
  69. break;
  70. }
  71. }
  72. }
  73. return cookieValue;
  74. }
  75. var csrftoken = getCookie('csrftoken');
  76. The above code could be simplified by using the `JavaScript Cookie library
  77. <https://github.com/js-cookie/js-cookie/>`_ to replace ``getCookie``:
  78. .. code-block:: javascript
  79. var csrftoken = Cookies.get('csrftoken');
  80. .. note::
  81. The CSRF token is also present in the DOM, but only if explicitly included
  82. using :ttag:`csrf_token` in a template. The cookie contains the canonical
  83. token; the ``CsrfViewMiddleware`` will prefer the cookie to the token in
  84. the DOM. Regardless, you're guaranteed to have the cookie if the token is
  85. present in the DOM, so you should use the cookie!
  86. .. warning::
  87. If your view is not rendering a template containing the :ttag:`csrf_token`
  88. template tag, Django might not set the CSRF token cookie. This is common in
  89. cases where forms are dynamically added to the page. To address this case,
  90. Django provides a view decorator which forces setting of the cookie:
  91. :func:`~django.views.decorators.csrf.ensure_csrf_cookie`.
  92. Finally, you'll have to actually set the header on your AJAX request, while
  93. protecting the CSRF token from being sent to other domains using
  94. `settings.crossDomain <https://api.jquery.com/jQuery.ajax>`_ in jQuery 1.5.1 and
  95. newer:
  96. .. code-block:: javascript
  97. function csrfSafeMethod(method) {
  98. // these HTTP methods do not require CSRF protection
  99. return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
  100. }
  101. $.ajaxSetup({
  102. beforeSend: function(xhr, settings) {
  103. if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
  104. xhr.setRequestHeader("X-CSRFToken", csrftoken);
  105. }
  106. }
  107. });
  108. Other template engines
  109. ----------------------
  110. When using a different template engine than Django's built-in engine, you can
  111. set the token in your forms manually after making sure it's available in the
  112. template context.
  113. For example, in the Jinja2 template language, your form could contain the
  114. following:
  115. .. code-block:: html
  116. <div style="display:none">
  117. <input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}">
  118. </div>
  119. You can use JavaScript similar to the :ref:`AJAX code <csrf-ajax>` above to get
  120. the value of the CSRF token.
  121. The decorator method
  122. --------------------
  123. .. module:: django.views.decorators.csrf
  124. Rather than adding ``CsrfViewMiddleware`` as a blanket protection, you can use
  125. the ``csrf_protect`` decorator, which has exactly the same functionality, on
  126. particular views that need the protection. It must be used **both** on views
  127. that insert the CSRF token in the output, and on those that accept the POST form
  128. data. (These are often the same view function, but not always).
  129. Use of the decorator by itself is **not recommended**, since if you forget to
  130. use it, you will have a security hole. The 'belt and braces' strategy of using
  131. both is fine, and will incur minimal overhead.
  132. .. function:: csrf_protect(view)
  133. Decorator that provides the protection of ``CsrfViewMiddleware`` to a view.
  134. Usage::
  135. from django.views.decorators.csrf import csrf_protect
  136. from django.shortcuts import render
  137. @csrf_protect
  138. def my_view(request):
  139. c = {}
  140. # ...
  141. return render(request, "a_template.html", c)
  142. If you are using class-based views, you can refer to
  143. :ref:`Decorating class-based views<decorating-class-based-views>`.
  144. Rejected requests
  145. =================
  146. By default, a '403 Forbidden' response is sent to the user if an incoming
  147. request fails the checks performed by ``CsrfViewMiddleware``. This should
  148. usually only be seen when there is a genuine Cross Site Request Forgery, or
  149. when, due to a programming error, the CSRF token has not been included with a
  150. POST form.
  151. The error page, however, is not very friendly, so you may want to provide your
  152. own view for handling this condition. To do this, simply set the
  153. :setting:`CSRF_FAILURE_VIEW` setting.
  154. .. _how-csrf-works:
  155. How it works
  156. ============
  157. The CSRF protection is based on the following things:
  158. 1. A CSRF cookie that is set to a random value (a session independent nonce, as
  159. it is called), which other sites will not have access to.
  160. This cookie is set by ``CsrfViewMiddleware``. It is meant to be permanent,
  161. but since there is no way to set a cookie that never expires, it is sent with
  162. every response that has called ``django.middleware.csrf.get_token()``
  163. (the function used internally to retrieve the CSRF token).
  164. 2. A hidden form field with the name 'csrfmiddlewaretoken' present in all
  165. outgoing POST forms. The value of this field is the value of the CSRF
  166. cookie.
  167. This part is done by the template tag.
  168. 3. For all incoming requests that are not using HTTP GET, HEAD, OPTIONS or
  169. TRACE, a CSRF cookie must be present, and the 'csrfmiddlewaretoken' field
  170. must be present and correct. If it isn't, the user will get a 403 error.
  171. This check is done by ``CsrfViewMiddleware``.
  172. 4. In addition, for HTTPS requests, strict referer checking is done by
  173. ``CsrfViewMiddleware``. This is necessary to address a Man-In-The-Middle
  174. attack that is possible under HTTPS when using a session independent nonce,
  175. due to the fact that HTTP 'Set-Cookie' headers are (unfortunately) accepted
  176. by clients that are talking to a site under HTTPS. (Referer checking is not
  177. done for HTTP requests because the presence of the Referer header is not
  178. reliable enough under HTTP.)
  179. If the :setting:`CSRF_COOKIE_DOMAIN` setting is set, the referer is compared
  180. against it. This setting supports subdomains. For example,
  181. ``CSRF_COOKIE_DOMAIN = '.example.com'`` will allow POST requests from
  182. ``www.example.com`` and ``api.example.com``. If the setting is not set, then
  183. the referer must match the HTTP ``Host`` header.
  184. Expanding the accepted referers beyond the current host or cookie domain can
  185. be done with the :setting:`CSRF_TRUSTED_ORIGINS` setting.
  186. This ensures that only forms that have originated from trusted domains can be
  187. used to POST data back.
  188. It deliberately ignores GET requests (and other requests that are defined as
  189. 'safe' by :rfc:`2616`). These requests ought never to have any potentially
  190. dangerous side effects , and so a CSRF attack with a GET request ought to be
  191. harmless. :rfc:`2616` defines POST, PUT and DELETE as 'unsafe', and all other
  192. methods are assumed to be unsafe, for maximum protection.
  193. .. versionchanged:: 1.9
  194. Checking against the :setting:`CSRF_COOKIE_DOMAIN` setting was added.
  195. Caching
  196. =======
  197. If the :ttag:`csrf_token` template tag is used by a template (or the
  198. ``get_token`` function is called some other way), ``CsrfViewMiddleware`` will
  199. add a cookie and a ``Vary: Cookie`` header to the response. This means that the
  200. middleware will play well with the cache middleware if it is used as instructed
  201. (``UpdateCacheMiddleware`` goes before all other middleware).
  202. However, if you use cache decorators on individual views, the CSRF middleware
  203. will not yet have been able to set the Vary header or the CSRF cookie, and the
  204. response will be cached without either one. In this case, on any views that
  205. will require a CSRF token to be inserted you should use the
  206. :func:`django.views.decorators.csrf.csrf_protect` decorator first::
  207. from django.views.decorators.cache import cache_page
  208. from django.views.decorators.csrf import csrf_protect
  209. @cache_page(60 * 15)
  210. @csrf_protect
  211. def my_view(request):
  212. ...
  213. If you are using class-based views, you can refer to :ref:`Decorating
  214. class-based views<decorating-class-based-views>`.
  215. Testing
  216. =======
  217. The ``CsrfViewMiddleware`` will usually be a big hindrance to testing view
  218. functions, due to the need for the CSRF token which must be sent with every POST
  219. request. For this reason, Django's HTTP client for tests has been modified to
  220. set a flag on requests which relaxes the middleware and the ``csrf_protect``
  221. decorator so that they no longer rejects requests. In every other respect
  222. (e.g. sending cookies etc.), they behave the same.
  223. If, for some reason, you *want* the test client to perform CSRF
  224. checks, you can create an instance of the test client that enforces
  225. CSRF checks::
  226. >>> from django.test import Client
  227. >>> csrf_client = Client(enforce_csrf_checks=True)
  228. .. _csrf-limitations:
  229. Limitations
  230. ===========
  231. Subdomains within a site will be able to set cookies on the client for the whole
  232. domain. By setting the cookie and using a corresponding token, subdomains will
  233. be able to circumvent the CSRF protection. The only way to avoid this is to
  234. ensure that subdomains are controlled by trusted users (or, are at least unable
  235. to set cookies). Note that even without CSRF, there are other vulnerabilities,
  236. such as session fixation, that make giving subdomains to untrusted parties a bad
  237. idea, and these vulnerabilities cannot easily be fixed with current browsers.
  238. Edge cases
  239. ==========
  240. Certain views can have unusual requirements that mean they don't fit the normal
  241. pattern envisaged here. A number of utilities can be useful in these
  242. situations. The scenarios they might be needed in are described in the following
  243. section.
  244. Utilities
  245. ---------
  246. The examples below assume you are using function-based views. If you
  247. are working with class-based views, you can refer to :ref:`Decorating
  248. class-based views<decorating-class-based-views>`.
  249. .. function:: csrf_exempt(view)
  250. This decorator marks a view as being exempt from the protection ensured by
  251. the middleware. Example::
  252. from django.views.decorators.csrf import csrf_exempt
  253. from django.http import HttpResponse
  254. @csrf_exempt
  255. def my_view(request):
  256. return HttpResponse('Hello world')
  257. .. function:: requires_csrf_token(view)
  258. Normally the :ttag:`csrf_token` template tag will not work if
  259. ``CsrfViewMiddleware.process_view`` or an equivalent like ``csrf_protect``
  260. has not run. The view decorator ``requires_csrf_token`` can be used to
  261. ensure the template tag does work. This decorator works similarly to
  262. ``csrf_protect``, but never rejects an incoming request.
  263. Example::
  264. from django.views.decorators.csrf import requires_csrf_token
  265. from django.shortcuts import render
  266. @requires_csrf_token
  267. def my_view(request):
  268. c = {}
  269. # ...
  270. return render(request, "a_template.html", c)
  271. .. function:: ensure_csrf_cookie(view)
  272. This decorator forces a view to send the CSRF cookie.
  273. Scenarios
  274. ---------
  275. CSRF protection should be disabled for just a few views
  276. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  277. Most views requires CSRF protection, but a few do not.
  278. Solution: rather than disabling the middleware and applying ``csrf_protect`` to
  279. all the views that need it, enable the middleware and use
  280. :func:`~django.views.decorators.csrf.csrf_exempt`.
  281. CsrfViewMiddleware.process_view not used
  282. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  283. There are cases when ``CsrfViewMiddleware.process_view`` may not have run
  284. before your view is run - 404 and 500 handlers, for example - but you still
  285. need the CSRF token in a form.
  286. Solution: use :func:`~django.views.decorators.csrf.requires_csrf_token`
  287. Unprotected view needs the CSRF token
  288. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  289. There may be some views that are unprotected and have been exempted by
  290. ``csrf_exempt``, but still need to include the CSRF token.
  291. Solution: use :func:`~django.views.decorators.csrf.csrf_exempt` followed by
  292. :func:`~django.views.decorators.csrf.requires_csrf_token`. (i.e. ``requires_csrf_token``
  293. should be the innermost decorator).
  294. View needs protection for one path
  295. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  296. A view needs CSRF protection under one set of conditions only, and mustn't have
  297. it for the rest of the time.
  298. Solution: use :func:`~django.views.decorators.csrf.csrf_exempt` for the whole
  299. view function, and :func:`~django.views.decorators.csrf.csrf_protect` for the
  300. path within it that needs protection. Example::
  301. from django.views.decorators.csrf import csrf_exempt, csrf_protect
  302. @csrf_exempt
  303. def my_view(request):
  304. @csrf_protect
  305. def protected_path(request):
  306. do_something()
  307. if some_condition():
  308. return protected_path(request)
  309. else:
  310. do_something_else()
  311. Page uses AJAX without any HTML form
  312. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  313. A page makes a POST request via AJAX, and the page does not have an HTML form
  314. with a :ttag:`csrf_token` that would cause the required CSRF cookie to be sent.
  315. Solution: use :func:`~django.views.decorators.csrf.ensure_csrf_cookie` on the
  316. view that sends the page.
  317. Contrib and reusable apps
  318. =========================
  319. Because it is possible for the developer to turn off the ``CsrfViewMiddleware``,
  320. all relevant views in contrib apps use the ``csrf_protect`` decorator to ensure
  321. the security of these applications against CSRF. It is recommended that the
  322. developers of other reusable apps that want the same guarantees also use the
  323. ``csrf_protect`` decorator on their views.
  324. Settings
  325. ========
  326. A number of settings can be used to control Django's CSRF behavior:
  327. * :setting:`CSRF_COOKIE_AGE`
  328. * :setting:`CSRF_COOKIE_DOMAIN`
  329. * :setting:`CSRF_COOKIE_HTTPONLY`
  330. * :setting:`CSRF_COOKIE_NAME`
  331. * :setting:`CSRF_COOKIE_PATH`
  332. * :setting:`CSRF_COOKIE_SECURE`
  333. * :setting:`CSRF_FAILURE_VIEW`
  334. * :setting:`CSRF_HEADER_NAME`
  335. * :setting:`CSRF_TRUSTED_ORIGINS`