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:`7231#section-4.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://www.squarefree.com/securitytips/web-developers.html#CSRF
    
  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 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. .. versionadded:: 4.0
    
  86. 
    
  87.     ``Origin`` checking was added, as described above.
    
  88. 
    
  89. .. versionchanged:: 4.1
    
  90. 
    
  91.     In older versions, the CSRF cookie value was masked.
    
  92. 
    
  93. This ensures that only forms that have originated from trusted domains can be
    
  94. used to POST data back.
    
  95. 
    
  96. It deliberately ignores GET requests (and other requests that are defined as
    
  97. 'safe' by :rfc:`7231#section-4.2.1`). These requests ought never to have any
    
  98. potentially dangerous side effects, and so a CSRF attack with a GET request
    
  99. ought to be harmless. :rfc:`7231#section-4.2.1` defines POST, PUT, and DELETE
    
  100. as 'unsafe', and all other methods are also assumed to be unsafe, for maximum
    
  101. protection.
    
  102. 
    
  103. The CSRF protection cannot protect against man-in-the-middle attacks, so use
    
  104. :ref:`HTTPS <security-recommendation-ssl>` with
    
  105. :ref:`http-strict-transport-security`. It also assumes :ref:`validation of
    
  106. the HOST header <host-headers-virtual-hosting>` and that there aren't any
    
  107. :ref:`cross-site scripting vulnerabilities <cross-site-scripting>` on your site
    
  108. (because XSS vulnerabilities already let an attacker do anything a CSRF
    
  109. vulnerability allows and much worse).
    
  110. 
    
  111. .. admonition:: Removing the ``Referer`` header
    
  112. 
    
  113.     To avoid disclosing the referrer URL to third-party sites, you might want
    
  114.     to `disable the referer`_ on your site's ``<a>`` tags. For example, you
    
  115.     might use the ``<meta name="referrer" content="no-referrer">`` tag or
    
  116.     include the ``Referrer-Policy: no-referrer`` header. Due to the CSRF
    
  117.     protection's strict referer checking on HTTPS requests, those techniques
    
  118.     cause a CSRF failure on requests with 'unsafe' methods. Instead, use
    
  119.     alternatives like ``<a rel="noreferrer" ...>"`` for links to third-party
    
  120.     sites.
    
  121. 
    
  122. .. _BREACH: https://www.breachattack.com/
    
  123. .. _Origin header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin
    
  124. .. _disable the referer: https://www.w3.org/TR/referrer-policy/#referrer-policy-delivery
    
  125. 
    
  126. .. _csrf-limitations:
    
  127. 
    
  128. Limitations
    
  129. ===========
    
  130. 
    
  131. Subdomains within a site will be able to set cookies on the client for the whole
    
  132. domain. By setting the cookie and using a corresponding token, subdomains will
    
  133. be able to circumvent the CSRF protection. The only way to avoid this is to
    
  134. ensure that subdomains are controlled by trusted users (or, are at least unable
    
  135. to set cookies). Note that even without CSRF, there are other vulnerabilities,
    
  136. such as session fixation, that make giving subdomains to untrusted parties a bad
    
  137. idea, and these vulnerabilities cannot easily be fixed with current browsers.
    
  138. 
    
  139. Utilities
    
  140. =========
    
  141. 
    
  142. .. module:: django.views.decorators.csrf
    
  143. 
    
  144. The examples below assume you are using function-based views. If you
    
  145. are working with class-based views, you can refer to :ref:`Decorating
    
  146. class-based views<decorating-class-based-views>`.
    
  147. 
    
  148. .. function:: csrf_exempt(view)
    
  149. 
    
  150.     This decorator marks a view as being exempt from the protection ensured by
    
  151.     the middleware. Example::
    
  152. 
    
  153.         from django.http import HttpResponse
    
  154.         from django.views.decorators.csrf import csrf_exempt
    
  155. 
    
  156.         @csrf_exempt
    
  157.         def my_view(request):
    
  158.             return HttpResponse('Hello world')
    
  159. 
    
  160. .. function:: csrf_protect(view)
    
  161. 
    
  162.     Decorator that provides the protection of ``CsrfViewMiddleware`` to a view.
    
  163. 
    
  164.     Usage::
    
  165. 
    
  166.         from django.shortcuts import render
    
  167.         from django.views.decorators.csrf import csrf_protect
    
  168. 
    
  169.         @csrf_protect
    
  170.         def my_view(request):
    
  171.             c = {}
    
  172.             # ...
    
  173.             return render(request, "a_template.html", c)
    
  174. 
    
  175. .. function:: requires_csrf_token(view)
    
  176. 
    
  177.     Normally the :ttag:`csrf_token` template tag will not work if
    
  178.     ``CsrfViewMiddleware.process_view`` or an equivalent like ``csrf_protect``
    
  179.     has not run. The view decorator ``requires_csrf_token`` can be used to
    
  180.     ensure the template tag does work. This decorator works similarly to
    
  181.     ``csrf_protect``, but never rejects an incoming request.
    
  182. 
    
  183.     Example::
    
  184. 
    
  185.         from django.shortcuts import render
    
  186.         from django.views.decorators.csrf import requires_csrf_token
    
  187. 
    
  188.         @requires_csrf_token
    
  189.         def my_view(request):
    
  190.             c = {}
    
  191.             # ...
    
  192.             return render(request, "a_template.html", c)
    
  193. 
    
  194. .. function:: ensure_csrf_cookie(view)
    
  195. 
    
  196.     This decorator forces a view to send the CSRF cookie.
    
  197. 
    
  198. Settings
    
  199. ========
    
  200. 
    
  201. A number of settings can be used to control Django's CSRF behavior:
    
  202. 
    
  203. * :setting:`CSRF_COOKIE_AGE`
    
  204. * :setting:`CSRF_COOKIE_DOMAIN`
    
  205. * :setting:`CSRF_COOKIE_HTTPONLY`
    
  206. * :setting:`CSRF_COOKIE_NAME`
    
  207. * :setting:`CSRF_COOKIE_PATH`
    
  208. * :setting:`CSRF_COOKIE_SAMESITE`
    
  209. * :setting:`CSRF_COOKIE_SECURE`
    
  210. * :setting:`CSRF_FAILURE_VIEW`
    
  211. * :setting:`CSRF_HEADER_NAME`
    
  212. * :setting:`CSRF_TRUSTED_ORIGINS`
    
  213. * :setting:`CSRF_USE_SESSIONS`
    
  214. 
    
  215. Frequently Asked Questions
    
  216. ==========================
    
  217. 
    
  218. Is posting an arbitrary CSRF token pair (cookie and POST data) a vulnerability?
    
  219. -------------------------------------------------------------------------------
    
  220. 
    
  221. No, this is by design. Without a man-in-the-middle attack, there is no way for
    
  222. an attacker to send a CSRF token cookie to a victim's browser, so a successful
    
  223. attack would need to obtain the victim's browser's cookie via XSS or similar,
    
  224. in which case an attacker usually doesn't need CSRF attacks.
    
  225. 
    
  226. Some security audit tools flag this as a problem but as mentioned before, an
    
  227. attacker cannot steal a user's browser's CSRF cookie. "Stealing" or modifying
    
  228. *your own* token using Firebug, Chrome dev tools, etc. isn't a vulnerability.
    
  229. 
    
  230. Is it a problem that Django's CSRF protection isn't linked to a session by default?
    
  231. -----------------------------------------------------------------------------------
    
  232. 
    
  233. No, this is by design. Not linking CSRF protection to a session allows using
    
  234. the protection on sites such as a *pastebin* that allow submissions from
    
  235. anonymous users which don't have a session.
    
  236. 
    
  237. If you wish to store the CSRF token in the user's session, use the
    
  238. :setting:`CSRF_USE_SESSIONS` setting.
    
  239. 
    
  240. Why might a user encounter a CSRF validation failure after logging in?
    
  241. ----------------------------------------------------------------------
    
  242. 
    
  243. For security reasons, CSRF tokens are rotated each time a user logs in. Any
    
  244. page with a form generated before a login will have an old, invalid CSRF token
    
  245. and need to be reloaded. This might happen if a user uses the back button after
    
  246. a login or if they log in a different browser tab.