csrf.txt 20 KB

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