| 1 |
===================================== |
| 2 |
Cross Site Request Forgery protection |
| 3 |
===================================== |
| 4 |
|
| 5 |
.. module:: django.middleware.csrf |
| 6 |
:synopsis: Protects against Cross Site Request Forgeries |
| 7 |
|
| 8 |
The CSRF middleware and template tag provides easy-to-use protection against |
| 9 |
`Cross Site Request Forgeries`_. This type of attack occurs when a malicious |
| 10 |
website contains a link, a form button or some JavaScript that is intended to |
| 11 |
perform some action on your website, using the credentials of a logged-in user |
| 12 |
who visits the malicious site in their browser. A related type of attack, |
| 13 |
'login CSRF', where an attacking site tricks a user's browser into logging into |
| 14 |
a site with someone else's credentials, is also covered. |
| 15 |
|
| 16 |
The first defense against CSRF attacks is to ensure that GET requests (and other |
| 17 |
'safe' methods, as defined by :rfc:`9110#section-9.2.1`) are side effect free. |
| 18 |
Requests via 'unsafe' methods, such as POST, PUT, and DELETE, can then be |
| 19 |
protected by the steps outlined in :ref:`using-csrf`. |
| 20 |
|
| 21 |
.. _Cross Site Request Forgeries: https://owasp.org/www-community/attacks/csrf#overview |
| 22 |
|
| 23 |
.. _how-csrf-works: |
| 24 |
|
| 25 |
How it works |
| 26 |
============ |
| 27 |
|
| 28 |
The CSRF protection is based on the following things: |
| 29 |
|
| 30 |
#. A CSRF cookie that is a random secret value, which other sites will not have |
| 31 |
access to. |
| 32 |
|
| 33 |
``CsrfViewMiddleware`` sends this cookie with the response whenever |
| 34 |
``django.middleware.csrf.get_token()`` is called. It can also send it in |
| 35 |
other cases. For security reasons, the value of the secret is changed each |
| 36 |
time a user logs in. |
| 37 |
|
| 38 |
#. A hidden form field with the name 'csrfmiddlewaretoken', present in all |
| 39 |
outgoing POST forms. |
| 40 |
|
| 41 |
In order to protect against `BREACH`_ attacks, the value of this field is |
| 42 |
not simply the secret. It is scrambled differently with each response using |
| 43 |
a mask. The mask is generated randomly on every call to ``get_token()``, so |
| 44 |
the form field value is different each time. |
| 45 |
|
| 46 |
This part is done by the :ttag:`csrf_token` template tag. |
| 47 |
|
| 48 |
#. For all incoming requests that are not using HTTP GET, HEAD, OPTIONS or |
| 49 |
TRACE, a CSRF cookie must be present, and the 'csrfmiddlewaretoken' field |
| 50 |
must be present and correct. If it isn't, the user will get a 403 error. |
| 51 |
|
| 52 |
When validating the 'csrfmiddlewaretoken' field value, only the secret, |
| 53 |
not the full token, is compared with the secret in the cookie value. |
| 54 |
This allows the use of ever-changing tokens. While each request may use its |
| 55 |
own token, the secret remains common to all. |
| 56 |
|
| 57 |
This check is done by ``CsrfViewMiddleware``. |
| 58 |
|
| 59 |
#. ``CsrfViewMiddleware`` verifies the `Origin header`_, if provided by the |
| 60 |
browser, against the current host and the :setting:`CSRF_TRUSTED_ORIGINS` |
| 61 |
setting. This provides protection against cross-subdomain attacks. |
| 62 |
|
| 63 |
#. In addition, for HTTPS requests, if the ``Origin`` header isn't provided, |
| 64 |
``CsrfViewMiddleware`` performs strict referer checking. This means that |
| 65 |
even if a subdomain can set or modify cookies on your domain, it can't force |
| 66 |
a user to post to your application since that request won't come from your |
| 67 |
own exact domain. |
| 68 |
|
| 69 |
This also addresses a man-in-the-middle attack that's possible under HTTPS |
| 70 |
when using a session independent secret, due to the fact that HTTP |
| 71 |
``Set-Cookie`` headers are (unfortunately) accepted by clients even when |
| 72 |
they are talking to a site under HTTPS. (Referer checking is not done for |
| 73 |
HTTP requests because the presence of the ``Referer`` header isn't reliable |
| 74 |
enough under HTTP.) |
| 75 |
|
| 76 |
If the :setting:`CSRF_COOKIE_DOMAIN` setting is set, the referer is compared |
| 77 |
against it. You can allow cross-subdomain requests by including a leading |
| 78 |
dot. For example, ``CSRF_COOKIE_DOMAIN = '.example.com'`` will allow POST |
| 79 |
requests from ``www.example.com`` and ``api.example.com``. If the setting is |
| 80 |
not set, then the referer must match the HTTP ``Host`` header. |
| 81 |
|
| 82 |
Expanding the accepted referers beyond the current host or cookie domain can |
| 83 |
be done with the :setting:`CSRF_TRUSTED_ORIGINS` setting. |
| 84 |
|
| 85 |
This ensures that only forms that have originated from trusted domains can be |
| 86 |
used to POST data back. |
| 87 |
|
| 88 |
It deliberately ignores GET requests (and other requests that are defined as |
| 89 |
'safe' by :rfc:`9110#section-9.2.1`). These requests ought never to have any |
| 90 |
potentially dangerous side effects, and so a CSRF attack with a GET request |
| 91 |
ought to be harmless. :rfc:`9110#section-9.2.1` defines POST, PUT, and DELETE |
| 92 |
as 'unsafe', and all other methods are also assumed to be unsafe, for maximum |
| 93 |
protection. |
| 94 |
|
| 95 |
The CSRF protection cannot protect against man-in-the-middle attacks, so use |
| 96 |
:ref:`HTTPS <security-recommendation-ssl>` with |
| 97 |
:ref:`http-strict-transport-security`. It also assumes :ref:`validation of |
| 98 |
the HOST header <host-headers-virtual-hosting>` and that there aren't any |
| 99 |
:ref:`cross-site scripting vulnerabilities <cross-site-scripting>` on your site |
| 100 |
(because XSS vulnerabilities already let an attacker do anything a CSRF |
| 101 |
vulnerability allows and much worse). |
| 102 |
|
| 103 |
.. admonition:: Removing the ``Referer`` header |
| 104 |
|
| 105 |
To avoid disclosing the referrer URL to third-party sites, you might want |
| 106 |
to `disable the referer`_ on your site's ``<a>`` tags. For example, you |
| 107 |
might use the ``<meta name="referrer" content="no-referrer">`` tag or |
| 108 |
include the ``Referrer-Policy: no-referrer`` header. Due to the CSRF |
| 109 |
protection's strict referer checking on HTTPS requests, those techniques |
| 110 |
cause a CSRF failure on requests with 'unsafe' methods. Instead, use |
| 111 |
alternatives like ``<a rel="noreferrer" ...>"`` for links to third-party |
| 112 |
sites. |
| 113 |
|
| 114 |
.. _BREACH: https://www.breachattack.com/ |
| 115 |
.. _Origin header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin |
| 116 |
.. _disable the referer: https://www.w3.org/TR/referrer-policy/#referrer-policy-delivery |
| 117 |
|
| 118 |
.. _csrf-limitations: |
| 119 |
|
| 120 |
Limitations |
| 121 |
=========== |
| 122 |
|
| 123 |
Subdomains within a site will be able to set cookies on the client for the whole |
| 124 |
domain. By setting the cookie and using a corresponding token, subdomains will |
| 125 |
be able to circumvent the CSRF protection. The only way to avoid this is to |
| 126 |
ensure that subdomains are controlled by trusted users (or, are at least unable |
| 127 |
to set cookies). Note that even without CSRF, there are other vulnerabilities, |
| 128 |
such as session fixation, that make giving subdomains to untrusted parties a bad |
| 129 |
idea, and these vulnerabilities cannot easily be fixed with current browsers. |
| 130 |
|
| 131 |
Utilities |
| 132 |
========= |
| 133 |
|
| 134 |
.. module:: django.views.decorators.csrf |
| 135 |
|
| 136 |
The examples below assume you are using function-based views. If you |
| 137 |
are working with class-based views, you can refer to :ref:`Decorating |
| 138 |
class-based views<decorating-class-based-views>`. |
| 139 |
|
| 140 |
.. function:: csrf_exempt(view) |
| 141 |
|
| 142 |
This decorator marks a view as being exempt from the protection ensured by |
| 143 |
the middleware. Example:: |
| 144 |
|
| 145 |
from django.http import HttpResponse |
| 146 |
from django.views.decorators.csrf import csrf_exempt |
| 147 |
|
| 148 |
|
| 149 |
@csrf_exempt |
| 150 |
def my_view(request): |
| 151 |
return HttpResponse("Hello world") |
| 152 |
|
| 153 |
.. function:: csrf_protect(view) |
| 154 |
|
| 155 |
Decorator that provides the protection of |
| 156 |
:class:`~django.middleware.csrf.CsrfViewMiddleware` to a view. |
| 157 |
|
| 158 |
Usage:: |
| 159 |
|
| 160 |
from django.shortcuts import render |
| 161 |
from django.views.decorators.csrf import csrf_protect |
| 162 |
|
| 163 |
|
| 164 |
@csrf_protect |
| 165 |
def my_view(request): |
| 166 |
c = {} |
| 167 |
# ... |
| 168 |
return render(request, "a_template.html", c) |
| 169 |
|
| 170 |
.. function:: requires_csrf_token(view) |
| 171 |
|
| 172 |
Normally the :ttag:`csrf_token` template tag will not work if |
| 173 |
``CsrfViewMiddleware.process_view`` or an equivalent like ``csrf_protect`` |
| 174 |
has not run. The view decorator ``requires_csrf_token`` can be used to |
| 175 |
ensure the template tag does work. This decorator works similarly to |
| 176 |
``csrf_protect``, but never rejects an incoming request. |
| 177 |
|
| 178 |
Example:: |
| 179 |
|
| 180 |
from django.shortcuts import render |
| 181 |
from django.views.decorators.csrf import requires_csrf_token |
| 182 |
|
| 183 |
|
| 184 |
@requires_csrf_token |
| 185 |
def my_view(request): |
| 186 |
c = {} |
| 187 |
# ... |
| 188 |
return render(request, "a_template.html", c) |
| 189 |
|
| 190 |
.. function:: ensure_csrf_cookie(view) |
| 191 |
|
| 192 |
This decorator forces a view to send the CSRF cookie. |
| 193 |
|
| 194 |
Settings |
| 195 |
======== |
| 196 |
|
| 197 |
A number of settings can be used to control Django's CSRF behavior: |
| 198 |
|
| 199 |
* :setting:`CSRF_COOKIE_AGE` |
| 200 |
* :setting:`CSRF_COOKIE_DOMAIN` |
| 201 |
* :setting:`CSRF_COOKIE_HTTPONLY` |
| 202 |
* :setting:`CSRF_COOKIE_NAME` |
| 203 |
* :setting:`CSRF_COOKIE_PATH` |
| 204 |
* :setting:`CSRF_COOKIE_SAMESITE` |
| 205 |
* :setting:`CSRF_COOKIE_SECURE` |
| 206 |
* :setting:`CSRF_FAILURE_VIEW` |
| 207 |
* :setting:`CSRF_HEADER_NAME` |
| 208 |
* :setting:`CSRF_TRUSTED_ORIGINS` |
| 209 |
* :setting:`CSRF_USE_SESSIONS` |
| 210 |
|
| 211 |
Frequently Asked Questions |
| 212 |
========================== |
| 213 |
|
| 214 |
Is posting an arbitrary CSRF token pair (cookie and POST data) a vulnerability? |
| 215 |
------------------------------------------------------------------------------- |
| 216 |
|
| 217 |
No, this is by design. Without a man-in-the-middle attack, there is no way for |
| 218 |
an attacker to send a CSRF token cookie to a victim's browser, so a successful |
| 219 |
attack would need to obtain the victim's browser's cookie via XSS or similar, |
| 220 |
in which case an attacker usually doesn't need CSRF attacks. |
| 221 |
|
| 222 |
Some security audit tools flag this as a problem but as mentioned before, an |
| 223 |
attacker cannot steal a user's browser's CSRF cookie. "Stealing" or modifying |
| 224 |
*your own* token using Firebug, Chrome dev tools, etc. isn't a vulnerability. |
| 225 |
|
| 226 |
Is it a problem that Django's CSRF protection isn't linked to a session by default? |
| 227 |
----------------------------------------------------------------------------------- |
| 228 |
|
| 229 |
No, this is by design. Not linking CSRF protection to a session allows using |
| 230 |
the protection on sites such as a *pastebin* that allow submissions from |
| 231 |
anonymous users which don't have a session. |
| 232 |
|
| 233 |
If you wish to store the CSRF token in the user's session, use the |
| 234 |
:setting:`CSRF_USE_SESSIONS` setting. |
| 235 |
|
| 236 |
Why might a user encounter a CSRF validation failure after logging in? |
| 237 |
---------------------------------------------------------------------- |
| 238 |
|
| 239 |
For security reasons, CSRF tokens are rotated each time a user logs in. Any |
| 240 |
page with a form generated before a login will have an old, invalid CSRF token |
| 241 |
and need to be reloaded. This might happen if a user uses the back button after |
| 242 |
a login or if they log in a different browser tab. |