csrf.txt 18 KB

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