csrf.txt 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  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 :rfc:`7231#section-4.2.1`) are side effect free.
  15. Requests via 'unsafe' methods, such as POST, PUT, and DELETE, can then be
  16. protected by following the steps below.
  17. .. _Cross Site Request Forgeries: https://www.squarefree.com/securitytips/web-developers.html#CSRF
  18. .. _using-csrf:
  19. How to use it
  20. =============
  21. To take advantage of CSRF protection in your views, follow these steps:
  22. #. The CSRF middleware is activated by default in the :setting:`MIDDLEWARE`
  23. setting. If you override that setting, remember that
  24. ``'django.middleware.csrf.CsrfViewMiddleware'`` should come before any view
  25. middleware that assume that CSRF attacks have been dealt with.
  26. If you disabled it, which is not recommended, you can use
  27. :func:`~django.views.decorators.csrf.csrf_protect` on particular views
  28. you want to protect (see below).
  29. #. In any template that uses a POST form, use the :ttag:`csrf_token` tag inside
  30. the ``<form>`` element if the form is for an internal URL, e.g.:
  31. .. code-block:: html+django
  32. <form 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. #. 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 (as specified by the
  47. :setting:`CSRF_HEADER_NAME` setting) to the value of the CSRF token. This is
  48. often easier because many JavaScript frameworks provide hooks that allow
  49. headers to be set on every request.
  50. First, you must get the CSRF token. How to do that depends on whether or not
  51. the :setting:`CSRF_USE_SESSIONS` and :setting:`CSRF_COOKIE_HTTPONLY` settings
  52. are enabled.
  53. .. _acquiring-csrf-token-from-cookie:
  54. Acquiring the token if :setting:`CSRF_USE_SESSIONS` and :setting:`CSRF_COOKIE_HTTPONLY` are ``False``
  55. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  56. The recommended source for the token is the ``csrftoken`` cookie, which will be
  57. set if you've enabled CSRF protection for your views as outlined above.
  58. The CSRF token cookie is named ``csrftoken`` by default, but you can control
  59. the cookie name via the :setting:`CSRF_COOKIE_NAME` setting.
  60. You can acquire the token like this:
  61. .. code-block:: javascript
  62. function getCookie(name) {
  63. let cookieValue = null;
  64. if (document.cookie && document.cookie !== '') {
  65. const cookies = document.cookie.split(';');
  66. for (let i = 0; i < cookies.length; i++) {
  67. const cookie = cookies[i].trim();
  68. // Does this cookie string begin with the name we want?
  69. if (cookie.substring(0, name.length + 1) === (name + '=')) {
  70. cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
  71. break;
  72. }
  73. }
  74. }
  75. return cookieValue;
  76. }
  77. const csrftoken = getCookie('csrftoken');
  78. The above code could be simplified by using the `JavaScript Cookie library
  79. <https://github.com/js-cookie/js-cookie/>`_ to replace ``getCookie``:
  80. .. code-block:: javascript
  81. const csrftoken = Cookies.get('csrftoken');
  82. .. note::
  83. The CSRF token is also present in the DOM, but only if explicitly included
  84. using :ttag:`csrf_token` in a template. The cookie contains the canonical
  85. token; the ``CsrfViewMiddleware`` will prefer the cookie to the token in
  86. the DOM. Regardless, you're guaranteed to have the cookie if the token is
  87. present in the DOM, so you should use the cookie!
  88. .. warning::
  89. If your view is not rendering a template containing the :ttag:`csrf_token`
  90. template tag, Django might not set the CSRF token cookie. This is common in
  91. cases where forms are dynamically added to the page. To address this case,
  92. Django provides a view decorator which forces setting of the cookie:
  93. :func:`~django.views.decorators.csrf.ensure_csrf_cookie`.
  94. .. _acquiring-csrf-token-from-html:
  95. Acquiring the token if :setting:`CSRF_USE_SESSIONS` or :setting:`CSRF_COOKIE_HTTPONLY` is ``True``
  96. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  97. If you activate :setting:`CSRF_USE_SESSIONS` or
  98. :setting:`CSRF_COOKIE_HTTPONLY`, you must include the CSRF token in your HTML
  99. and read the token from the DOM with JavaScript:
  100. .. code-block:: html+django
  101. {% csrf_token %}
  102. <script>
  103. const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
  104. </script>
  105. Setting the token on the AJAX request
  106. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  107. Finally, you'll need to set the header on your AJAX request. Using the
  108. `fetch()`_ API:
  109. .. code-block:: javascript
  110. const request = new Request(
  111. /* URL */,
  112. {headers: {'X-CSRFToken': csrftoken}}
  113. );
  114. fetch(request, {
  115. method: 'POST',
  116. mode: 'same-origin' // Do not send CSRF token to another domain.
  117. }).then(function(response) {
  118. // ...
  119. });
  120. .. _fetch(): https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
  121. Using CSRF in Jinja2 templates
  122. ------------------------------
  123. Django's :class:`~django.template.backends.jinja2.Jinja2` template backend
  124. adds ``{{ csrf_input }}`` to the context of all templates which is equivalent
  125. to ``{% csrf_token %}`` in the Django template language. For example:
  126. .. code-block:: html+jinja
  127. <form method="post">{{ csrf_input }}
  128. The decorator method
  129. --------------------
  130. .. module:: django.views.decorators.csrf
  131. Rather than adding ``CsrfViewMiddleware`` as a blanket protection, you can use
  132. the ``csrf_protect`` decorator, which has exactly the same functionality, on
  133. particular views that need the protection. It must be used **both** on views
  134. that insert the CSRF token in the output, and on those that accept the POST form
  135. data. (These are often the same view function, but not always).
  136. Use of the decorator by itself is **not recommended**, since if you forget to
  137. use it, you will have a security hole. The 'belt and braces' strategy of using
  138. both is fine, and will incur minimal overhead.
  139. .. function:: csrf_protect(view)
  140. Decorator that provides the protection of ``CsrfViewMiddleware`` to a view.
  141. Usage::
  142. from django.shortcuts import render
  143. from django.views.decorators.csrf import csrf_protect
  144. @csrf_protect
  145. def my_view(request):
  146. c = {}
  147. # ...
  148. return render(request, "a_template.html", c)
  149. If you are using class-based views, you can refer to
  150. :ref:`Decorating class-based views<decorating-class-based-views>`.
  151. .. _csrf-rejected-requests:
  152. Rejected requests
  153. =================
  154. By default, a '403 Forbidden' response is sent to the user if an incoming
  155. request fails the checks performed by ``CsrfViewMiddleware``. This should
  156. usually only be seen when there is a genuine Cross Site Request Forgery, or
  157. when, due to a programming error, the CSRF token has not been included with a
  158. POST form.
  159. The error page, however, is not very friendly, so you may want to provide your
  160. own view for handling this condition. To do this, set the
  161. :setting:`CSRF_FAILURE_VIEW` setting.
  162. CSRF failures are logged as warnings to the :ref:`django.security.csrf
  163. <django-security-logger>` logger.
  164. .. _how-csrf-works:
  165. How it works
  166. ============
  167. The CSRF protection is based on the following things:
  168. #. A CSRF cookie that is based on a random secret value, which other sites
  169. will not have access to.
  170. This cookie is set by ``CsrfViewMiddleware``. It is sent with every
  171. response that has called ``django.middleware.csrf.get_token()`` (the
  172. function used internally to retrieve the CSRF token), if it wasn't already
  173. set on the request.
  174. In order to protect against `BREACH`_ attacks, the token is not simply the
  175. secret; a random mask is prepended to the secret and used to scramble it.
  176. For security reasons, the value of the secret is changed each time a
  177. user logs in.
  178. #. A hidden form field with the name 'csrfmiddlewaretoken' present in all
  179. outgoing POST forms. The value of this field is, again, the value of the
  180. secret, with a mask which is both added to it and used to scramble it. The
  181. mask is regenerated on every call to ``get_token()`` so that the form field
  182. value is changed in every such response.
  183. This part is done by the template tag.
  184. #. For all incoming requests that are not using HTTP GET, HEAD, OPTIONS or
  185. TRACE, a CSRF cookie must be present, and the 'csrfmiddlewaretoken' field
  186. must be present and correct. If it isn't, the user will get a 403 error.
  187. When validating the 'csrfmiddlewaretoken' field value, only the secret,
  188. not the full token, is compared with the secret in the cookie value.
  189. This allows the use of ever-changing tokens. While each request may use its
  190. own token, the secret remains common to all.
  191. This check is done by ``CsrfViewMiddleware``.
  192. #. ``CsrfViewMiddleware`` verifies the `Origin header`_, if provided by the
  193. browser, against the current host and the :setting:`CSRF_TRUSTED_ORIGINS`
  194. setting. This provides protection against cross-subdomain attacks.
  195. #. In addition, for HTTPS requests, if the ``Origin`` header isn't provided,
  196. ``CsrfViewMiddleware`` performs strict referer checking. This means that
  197. even if a subdomain can set or modify cookies on your domain, it can't force
  198. a user to post to your application since that request won't come from your
  199. own exact domain.
  200. This also addresses a man-in-the-middle attack that's possible under HTTPS
  201. when using a session independent secret, due to the fact that HTTP
  202. ``Set-Cookie`` headers are (unfortunately) accepted by clients even when
  203. they are talking to a site under HTTPS. (Referer checking is not done for
  204. HTTP requests because the presence of the ``Referer`` header isn't reliable
  205. enough under HTTP.)
  206. If the :setting:`CSRF_COOKIE_DOMAIN` setting is set, the referer is compared
  207. against it. You can allow cross-subdomain requests by including a leading
  208. dot. For example, ``CSRF_COOKIE_DOMAIN = '.example.com'`` will allow POST
  209. requests from ``www.example.com`` and ``api.example.com``. If the setting is
  210. not set, then the referer must match the HTTP ``Host`` header.
  211. Expanding the accepted referers beyond the current host or cookie domain can
  212. be done with the :setting:`CSRF_TRUSTED_ORIGINS` setting.
  213. .. versionadded:: 4.0
  214. ``Origin`` checking was added, as described above.
  215. This ensures that only forms that have originated from trusted domains can be
  216. used to POST data back.
  217. It deliberately ignores GET requests (and other requests that are defined as
  218. 'safe' by :rfc:`7231#section-4.2.1`). These requests ought never to have any
  219. potentially dangerous side effects, and so a CSRF attack with a GET request
  220. ought to be harmless. :rfc:`7231#section-4.2.1` defines POST, PUT, and DELETE
  221. as 'unsafe', and all other methods are also assumed to be unsafe, for maximum
  222. protection.
  223. The CSRF protection cannot protect against man-in-the-middle attacks, so use
  224. :ref:`HTTPS <security-recommendation-ssl>` with
  225. :ref:`http-strict-transport-security`. It also assumes :ref:`validation of
  226. the HOST header <host-headers-virtual-hosting>` and that there aren't any
  227. :ref:`cross-site scripting vulnerabilities <cross-site-scripting>` on your site
  228. (because XSS vulnerabilities already let an attacker do anything a CSRF
  229. vulnerability allows and much worse).
  230. .. admonition:: Removing the ``Referer`` header
  231. To avoid disclosing the referrer URL to third-party sites, you might want
  232. to `disable the referer`_ on your site's ``<a>`` tags. For example, you
  233. might use the ``<meta name="referrer" content="no-referrer">`` tag or
  234. include the ``Referrer-Policy: no-referrer`` header. Due to the CSRF
  235. protection's strict referer checking on HTTPS requests, those techniques
  236. cause a CSRF failure on requests with 'unsafe' methods. Instead, use
  237. alternatives like ``<a rel="noreferrer" ...>"`` for links to third-party
  238. sites.
  239. .. _BREACH: http://breachattack.com/
  240. .. _Origin header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin
  241. .. _disable the referer: https://www.w3.org/TR/referrer-policy/#referrer-policy-delivery
  242. Caching
  243. =======
  244. If the :ttag:`csrf_token` template tag is used by a template (or the
  245. ``get_token`` function is called some other way), ``CsrfViewMiddleware`` will
  246. add a cookie and a ``Vary: Cookie`` header to the response. This means that the
  247. middleware will play well with the cache middleware if it is used as instructed
  248. (``UpdateCacheMiddleware`` goes before all other middleware).
  249. However, if you use cache decorators on individual views, the CSRF middleware
  250. will not yet have been able to set the Vary header or the CSRF cookie, and the
  251. response will be cached without either one. In this case, on any views that
  252. will require a CSRF token to be inserted you should use the
  253. :func:`django.views.decorators.csrf.csrf_protect` decorator first::
  254. from django.views.decorators.cache import cache_page
  255. from django.views.decorators.csrf import csrf_protect
  256. @cache_page(60 * 15)
  257. @csrf_protect
  258. def my_view(request):
  259. ...
  260. If you are using class-based views, you can refer to :ref:`Decorating
  261. class-based views<decorating-class-based-views>`.
  262. Testing
  263. =======
  264. The ``CsrfViewMiddleware`` will usually be a big hindrance to testing view
  265. functions, due to the need for the CSRF token which must be sent with every POST
  266. request. For this reason, Django's HTTP client for tests has been modified to
  267. set a flag on requests which relaxes the middleware and the ``csrf_protect``
  268. decorator so that they no longer rejects requests. In every other respect
  269. (e.g. sending cookies etc.), they behave the same.
  270. If, for some reason, you *want* the test client to perform CSRF
  271. checks, you can create an instance of the test client that enforces
  272. CSRF checks::
  273. >>> from django.test import Client
  274. >>> csrf_client = Client(enforce_csrf_checks=True)
  275. .. _csrf-limitations:
  276. Limitations
  277. ===========
  278. Subdomains within a site will be able to set cookies on the client for the whole
  279. domain. By setting the cookie and using a corresponding token, subdomains will
  280. be able to circumvent the CSRF protection. The only way to avoid this is to
  281. ensure that subdomains are controlled by trusted users (or, are at least unable
  282. to set cookies). Note that even without CSRF, there are other vulnerabilities,
  283. such as session fixation, that make giving subdomains to untrusted parties a bad
  284. idea, and these vulnerabilities cannot easily be fixed with current browsers.
  285. Edge cases
  286. ==========
  287. Certain views can have unusual requirements that mean they don't fit the normal
  288. pattern envisaged here. A number of utilities can be useful in these
  289. situations. The scenarios they might be needed in are described in the following
  290. section.
  291. Utilities
  292. ---------
  293. The examples below assume you are using function-based views. If you
  294. are working with class-based views, you can refer to :ref:`Decorating
  295. class-based views<decorating-class-based-views>`.
  296. .. function:: csrf_exempt(view)
  297. This decorator marks a view as being exempt from the protection ensured by
  298. the middleware. Example::
  299. from django.http import HttpResponse
  300. from django.views.decorators.csrf import csrf_exempt
  301. @csrf_exempt
  302. def my_view(request):
  303. return HttpResponse('Hello world')
  304. .. function:: requires_csrf_token(view)
  305. Normally the :ttag:`csrf_token` template tag will not work if
  306. ``CsrfViewMiddleware.process_view`` or an equivalent like ``csrf_protect``
  307. has not run. The view decorator ``requires_csrf_token`` can be used to
  308. ensure the template tag does work. This decorator works similarly to
  309. ``csrf_protect``, but never rejects an incoming request.
  310. Example::
  311. from django.shortcuts import render
  312. from django.views.decorators.csrf import requires_csrf_token
  313. @requires_csrf_token
  314. def my_view(request):
  315. c = {}
  316. # ...
  317. return render(request, "a_template.html", c)
  318. .. function:: ensure_csrf_cookie(view)
  319. This decorator forces a view to send the CSRF cookie.
  320. Scenarios
  321. ---------
  322. CSRF protection should be disabled for just a few views
  323. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  324. Most views requires CSRF protection, but a few do not.
  325. Solution: rather than disabling the middleware and applying ``csrf_protect`` to
  326. all the views that need it, enable the middleware and use
  327. :func:`~django.views.decorators.csrf.csrf_exempt`.
  328. CsrfViewMiddleware.process_view not used
  329. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  330. There are cases when ``CsrfViewMiddleware.process_view`` may not have run
  331. before your view is run - 404 and 500 handlers, for example - but you still
  332. need the CSRF token in a form.
  333. Solution: use :func:`~django.views.decorators.csrf.requires_csrf_token`
  334. Unprotected view needs the CSRF token
  335. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  336. There may be some views that are unprotected and have been exempted by
  337. ``csrf_exempt``, but still need to include the CSRF token.
  338. Solution: use :func:`~django.views.decorators.csrf.csrf_exempt` followed by
  339. :func:`~django.views.decorators.csrf.requires_csrf_token`. (i.e. ``requires_csrf_token``
  340. should be the innermost decorator).
  341. View needs protection for one path
  342. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  343. A view needs CSRF protection under one set of conditions only, and mustn't have
  344. it for the rest of the time.
  345. Solution: use :func:`~django.views.decorators.csrf.csrf_exempt` for the whole
  346. view function, and :func:`~django.views.decorators.csrf.csrf_protect` for the
  347. path within it that needs protection. Example::
  348. from django.views.decorators.csrf import csrf_exempt, csrf_protect
  349. @csrf_exempt
  350. def my_view(request):
  351. @csrf_protect
  352. def protected_path(request):
  353. do_something()
  354. if some_condition():
  355. return protected_path(request)
  356. else:
  357. do_something_else()
  358. Page uses AJAX without any HTML form
  359. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  360. A page makes a POST request via AJAX, and the page does not have an HTML form
  361. with a :ttag:`csrf_token` that would cause the required CSRF cookie to be sent.
  362. Solution: use :func:`~django.views.decorators.csrf.ensure_csrf_cookie` on the
  363. view that sends the page.
  364. Contrib and reusable apps
  365. =========================
  366. Because it is possible for the developer to turn off the ``CsrfViewMiddleware``,
  367. all relevant views in contrib apps use the ``csrf_protect`` decorator to ensure
  368. the security of these applications against CSRF. It is recommended that the
  369. developers of other reusable apps that want the same guarantees also use the
  370. ``csrf_protect`` decorator on their views.
  371. Settings
  372. ========
  373. A number of settings can be used to control Django's CSRF behavior:
  374. * :setting:`CSRF_COOKIE_AGE`
  375. * :setting:`CSRF_COOKIE_DOMAIN`
  376. * :setting:`CSRF_COOKIE_HTTPONLY`
  377. * :setting:`CSRF_COOKIE_NAME`
  378. * :setting:`CSRF_COOKIE_PATH`
  379. * :setting:`CSRF_COOKIE_SAMESITE`
  380. * :setting:`CSRF_COOKIE_SECURE`
  381. * :setting:`CSRF_FAILURE_VIEW`
  382. * :setting:`CSRF_HEADER_NAME`
  383. * :setting:`CSRF_TRUSTED_ORIGINS`
  384. * :setting:`CSRF_USE_SESSIONS`
  385. Frequently Asked Questions
  386. ==========================
  387. Is posting an arbitrary CSRF token pair (cookie and POST data) a vulnerability?
  388. -------------------------------------------------------------------------------
  389. No, this is by design. Without a man-in-the-middle attack, there is no way for
  390. an attacker to send a CSRF token cookie to a victim's browser, so a successful
  391. attack would need to obtain the victim's browser's cookie via XSS or similar,
  392. in which case an attacker usually doesn't need CSRF attacks.
  393. Some security audit tools flag this as a problem but as mentioned before, an
  394. attacker cannot steal a user's browser's CSRF cookie. "Stealing" or modifying
  395. *your own* token using Firebug, Chrome dev tools, etc. isn't a vulnerability.
  396. Is it a problem that Django's CSRF protection isn't linked to a session by default?
  397. -----------------------------------------------------------------------------------
  398. No, this is by design. Not linking CSRF protection to a session allows using
  399. the protection on sites such as a *pastebin* that allow submissions from
  400. anonymous users which don't have a session.
  401. If you wish to store the CSRF token in the user's session, use the
  402. :setting:`CSRF_USE_SESSIONS` setting.
  403. Why might a user encounter a CSRF validation failure after logging in?
  404. ----------------------------------------------------------------------
  405. For security reasons, CSRF tokens are rotated each time a user logs in. Any
  406. page with a form generated before a login will have an old, invalid CSRF token
  407. and need to be reloaded. This might happen if a user uses the back button after
  408. a login or if they log in a different browser tab.