csrf.txt 19 KB

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