csrf.txt 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. .. _ref-contrib-csrf:
  2. =====================================
  3. Cross Site Request Forgery protection
  4. =====================================
  5. .. module:: django.middleware.csrf
  6. :synopsis: Protects against Cross Site Request Forgeries
  7. The CSRF middleware and template tag provides easy-to-use protection against
  8. `Cross Site Request Forgeries`_. This type of attack occurs when a malicious
  9. Web site contains a link, a form button or some javascript that is intended to
  10. perform some action on your Web site, using the credentials of a logged-in user
  11. who visits the malicious site in their browser. A related type of attack,
  12. 'login CSRF', where an attacking site tricks a user's browser into logging into
  13. a site with someone else's credentials, is also covered.
  14. The first defense against CSRF attacks is to ensure that GET requests are
  15. side-effect free. POST requests can then be protected by following the steps
  16. below.
  17. .. versionadded:: 1.2
  18. The 'contrib' apps, including the admin, use the functionality described
  19. here. Because it is security related, a few things have been added to core
  20. functionality to allow this to happen without any required upgrade steps.
  21. .. _Cross Site Request Forgeries: http://www.squarefree.com/securitytips/web-developers.html#CSRF
  22. How to use it
  23. =============
  24. .. versionchanged:: 1.2
  25. The template tag functionality (the recommended way to use this) was added
  26. in version 1.2. The previous method (still available) is described under
  27. `Legacy method`_.
  28. To enable CSRF protection for your views, follow these steps:
  29. 1. Add the middleware
  30. ``'django.middleware.csrf.CsrfViewMiddleware'`` to your list of
  31. middleware classes, :setting:`MIDDLEWARE_CLASSES`. (It should come
  32. before ``CsrfResponseMiddleware`` if that is being used, and before any
  33. view middleware that assume that CSRF attacks have been dealt with.)
  34. Alternatively, you can use the decorator
  35. ``django.views.decorators.csrf.csrf_protect`` on particular views you
  36. want to protect. This is **not recommended** by itself, since if you
  37. forget to use it, you will have a security hole. The 'belt and braces'
  38. strategy of using both is fine, and will incur minimal overhead.
  39. 2. In any template that uses a POST form, use the ``csrf_token`` tag inside
  40. the ``<form>`` element if the form is for an internal URL, e.g.::
  41. <form action="" method="POST">{% csrf_token %}
  42. This should not be done for POST forms that target external URLs, since
  43. that would cause the CSRF token to be leaked, leading to a vulnerability.
  44. 3. In the corresponding view functions, ensure that the
  45. ``'django.core.context_processors.csrf'`` context processor is
  46. being used. Usually, this can be done in one of two ways:
  47. 1. Use RequestContext, which always uses
  48. ``'django.core.context_processors.csrf'`` (no matter what your
  49. TEMPLATE_CONTEXT_PROCESSORS setting). If you are using
  50. generic views or contrib apps, you are covered already, since these
  51. apps use RequestContext throughout.
  52. 2. Manually import and use the processor to generate the CSRF token and
  53. add it to the template context. e.g.::
  54. from django.core.context_processors import csrf
  55. from django.shortcuts import render_to_response
  56. def my_view(request):
  57. c = {}
  58. c.update(csrf(request))
  59. # ... view code here
  60. return render_to_response("a_template.html", c)
  61. You may want to write your own ``render_to_response`` wrapper that
  62. takes care of this step for you.
  63. The utility script ``extras/csrf_migration_helper.py`` can help to automate the
  64. finding of code and templates that may need to be upgraded. It contains full
  65. help on how to use it.
  66. Legacy method
  67. -------------
  68. In Django 1.1, the template tag did not exist. Instead, a post-processing
  69. middleware that re-wrote POST forms to include the CRSF token was used. If you
  70. are upgrading a site from version 1.1 or earlier, please read this section and
  71. the `Upgrading notes`_ below. The post-processing middleware is still available
  72. as ``CsrfResponseMiddleware``, and it can be used by following these steps:
  73. 1. Follow step 1 above to install ``CsrfViewMiddleware``.
  74. 2. Add ``'django.middleware.csrf.CsrfResponseMiddleware'`` to your
  75. :setting:`MIDDLEWARE_CLASSES` setting.
  76. ``CsrfResponseMiddleware`` needs to process the response before things
  77. like compression or setting ofETags happen to the response, so it must
  78. come after ``GZipMiddleware``, ``CommonMiddleware`` and
  79. ``ConditionalGetMiddleware`` in the list. It also must come after
  80. ``CsrfViewMiddleware``.
  81. Use of the ``CsrfResponseMiddleware`` is not recommended because of the
  82. performance hit it imposes, and because of a potential security problem (see
  83. below). It can be used as an interim measure until applications have been
  84. updated to use the ``{% crsf_token %}`` tag. It is deprecated and will be
  85. removed in Django 1.4.
  86. Django 1.1 and earlier provided a single ``CsrfMiddleware`` class. This is also
  87. still available for backwards compatibility. It combines the functions of the
  88. two middleware.
  89. Note also that previous versions of these classes depended on the sessions
  90. framework, but this dependency has now been removed, with backward compatibility
  91. support so that upgrading will not produce any issues.
  92. Security of legacy method
  93. ~~~~~~~~~~~~~~~~~~~~~~~~~
  94. The post-processing ``CsrfResponseMiddleware`` adds the CSRF token to all POST
  95. forms (unless the view has been decorated with ``csrf_response_exempt``). If
  96. the POST form has an external untrusted site as its target, rather than an
  97. internal page, that site will be sent the CSRF token when the form is submitted.
  98. Armed with this leaked information, that site will then be able to successfully
  99. launch a CSRF attack on your site against that user. The
  100. ``@csrf_response_exempt`` decorator can be used to fix this, but only if the
  101. page doesn't also contain internal forms that require the token.
  102. Upgrading notes
  103. ---------------
  104. When upgrading to version 1.2 or later, you may have applications that rely on
  105. the old post-processing functionality for CSRF protection, or you may not have
  106. enabled any CSRF protection. This section outlines the steps necessary for a
  107. smooth upgrade, without having to fix all the applications to use the new
  108. template tag method immediately.
  109. First of all, the location of the middleware and related functions have
  110. changed. There are backwards compatible stub files so that old imports will
  111. continue to work for now, but they are deprecated and will be removed in Django
  112. 1.4. The following changes have been made:
  113. * Middleware have been moved to ``django.middleware.csrf``
  114. * Decorators have been moved to ``django.views.decorators.csrf``
  115. ====================================================== ==============================================
  116. Old New
  117. ====================================================== ==============================================
  118. django.contrib.csrf.middleware.CsrfMiddleware django.middleware.csrf.CsrfMiddleware
  119. django.contrib.csrf.middleware.CsrfViewMiddleware django.middleware.csrf.CsrfViewMiddleware
  120. django.contrib.csrf.middleware.CsrfResponseMiddleware django.middleware.csrf.CsrfResponseMiddleware
  121. django.contrib.csrf.middleware.csrf_exempt django.views.decorators.csrf_exempt
  122. django.contrib.csrf.middleware.csrf_view_exempt django.views.decorators.csrf_view_exempt
  123. django.contrib.csrf.middleware.csrf_response_exempt django.views.decorators.csrf_response_exempt
  124. ====================================================== ==============================================
  125. You should update any imports, and also the paths in your
  126. :setting:`MIDDLEWARE_CLASSES`.
  127. If you have ``CsrfMiddleware`` in your :setting:`MIDDLEWARE_CLASSES`, you will now
  128. have a working installation with CSRF protection. It is recommended at this
  129. point that you replace ``CsrfMiddleware`` with its two components,
  130. ``CsrfViewMiddleware`` and ``CsrfResponseMiddleware`` (in that order).
  131. If you do not have any of the middleware in your :setting:`MIDDLEWARE_CLASSES`,
  132. you will have a working installation but without any CSRF protection for your
  133. views (just as you had before). It is strongly recommended to install
  134. ``CsrfViewMiddleware`` and ``CsrfResponseMiddleware``, as described above.
  135. (Note that contrib apps, such as the admin, have been updated to use the
  136. ``csrf_protect`` decorator, so that they are secured even if you do not add the
  137. ``CsrfViewMiddleware`` to your settings).
  138. Assuming you have followed the above, all views in your Django site will now be
  139. protected by the ``CsrfViewMiddleware``. Contrib apps meet the requirements
  140. imposed by the ``CsrfViewMiddleware`` using the template tag, and other
  141. applications in your project will meet its requirements by virtue of the
  142. ``CsrfResponseMiddleware``.
  143. The next step is to update all your applications to use the template tag, as
  144. described in `How to use it`_, steps 2-3. This can be done as soon as is
  145. practical. Any applications that are updated will now require Django 1.2 or
  146. later, since they will use the CSRF template tag which was not available in
  147. earlier versions.
  148. The utility script ``extras/csrf_migration_helper.py`` can help to automate the
  149. finding of code and templates that may need to be upgraded. It contains full
  150. help on how to use it.
  151. Finally, once all applications are upgraded, ``CsrfResponseMiddleware`` can be
  152. removed from your settings.
  153. While ``CsrfResponseMiddleware`` is still in use, the ``csrf_response_exempt``
  154. decorator, described in `Exceptions`_, may be useful. The post-processing
  155. middleware imposes a performance hit and a potential vulnerability, and any
  156. views that have been upgraded to use the new template tag method no longer need
  157. it.
  158. Exceptions
  159. ----------
  160. .. versionadded:: 1.1
  161. To manually exclude a view function from being handled by either of the two CSRF
  162. middleware, you can use the ``csrf_exempt`` decorator, found in the
  163. ``django.views.decorators.csrf`` module. For example::
  164. from django.views.decorators.csrf import csrf_exempt
  165. def my_view(request):
  166. return HttpResponse('Hello world')
  167. my_view = csrf_exempt(my_view)
  168. Like the middleware, the ``csrf_exempt`` decorator is composed of two parts: a
  169. ``csrf_view_exempt`` decorator and a ``csrf_response_exempt`` decorator, found
  170. in the same module. These disable the view protection mechanism
  171. (``CsrfViewMiddleware``) and the response post-processing
  172. (``CsrfResponseMiddleware``) respectively. They can be used individually if
  173. required.
  174. You don't have to worry about doing this for most AJAX views. Any request sent
  175. with "X-Requested-With: XMLHttpRequest" is automatically exempt. (See the `How
  176. it works`_ section.)
  177. Subdomains
  178. ----------
  179. By default, CSRF cookies are specific to the subdomain they are set for. This
  180. means that a form served from one subdomain (e.g. server1.example.com) will not
  181. be able to have a target on another subdomain (e.g. server2.example.com). This
  182. restriction can be removed by setting :setting:`CSRF_COOKIE_DOMAIN` to be
  183. something like ``".example.com"``.
  184. Please note that, with or without use of this setting, this CSRF protection
  185. mechanism is not safe against cross-subdomain attacks -- see `Limitations`_.
  186. Rejected requests
  187. =================
  188. By default, a '403 Forbidden' response is sent to the user if an incoming
  189. request fails the checks performed by ``CsrfViewMiddleware``. This should
  190. usually only be seen when there is a genuine Cross Site Request Forgery, or
  191. when, due to a programming error, the CSRF token has not been included with a
  192. POST form.
  193. No logging is done, and the error message is not very friendly, so you may want
  194. to provide your own page for handling this condition. To do this, simply set
  195. the :setting:`CSRF_FAILURE_VIEW` setting to a dotted path to your own view
  196. function, which should have the following signature::
  197. def csrf_failure(request, reason="")
  198. where ``reason`` is a short message (intended for developers or logging, not for
  199. end users) indicating the reason the request was rejected.
  200. How it works
  201. ============
  202. The CSRF protection is based on the following things:
  203. 1. A CSRF cookie that is set to a random value (a session independent nonce, as
  204. it is called), which other sites will not have access to.
  205. This cookie is set by ``CsrfViewMiddleware``. It is meant to be permanent,
  206. but since there is no way to set a cookie that never expires, it is sent with
  207. every response that has called ``django.middleware.csrf.get_token()``
  208. (the function used internally to retrieve the CSRF token).
  209. 2. A hidden form field with the name 'csrfmiddlewaretoken' present in all
  210. outgoing POST forms. The value of this field is the value of the CSRF
  211. cookie.
  212. This part is done by the template tag (and with the legacy method, it is done
  213. by ``CsrfResponseMiddleware``).
  214. 3. For all incoming POST requests, a CSRF cookie must be present, and the
  215. 'csrfmiddlewaretoken' field must be present and correct. If it isn't, the
  216. user will get a 403 error.
  217. This check is done by ``CsrfViewMiddleware``.
  218. 4. In addition, for HTTPS requests, strict referer checking is done by
  219. ``CsrfViewMiddleware``. This is necessary to address a Man-In-The-Middle
  220. attack that is possible under HTTPS when using a session independent nonce,
  221. due to the fact that HTTP 'Set-Cookie' headers are (unfortunately) accepted
  222. by clients that are talking to a site under HTTPS. (Referer checking is not
  223. done for HTTP requests because the presence of the Referer header is not
  224. reliable enough under HTTP.)
  225. This ensures that only forms that have originated from your Web site can be used
  226. to POST data back.
  227. It deliberately only targets HTTP POST requests (and the corresponding POST
  228. forms). GET requests ought never to have any potentially dangerous side effects
  229. (see `9.1.1 Safe Methods, HTTP 1.1, RFC 2616`_), and so a CSRF attack with a GET
  230. request ought to be harmless.
  231. ``CsrfResponseMiddleware`` checks the Content-Type before modifying the
  232. response, and only pages that are served as 'text/html' or
  233. 'application/xml+xhtml' are modified.
  234. AJAX
  235. ----
  236. The middleware tries to be smart about requests that come in via AJAX. Most
  237. modern JavaScript toolkits send an "X-Requested-With: XMLHttpRequest" HTTP
  238. header; these requests are detected and automatically *not* handled by this
  239. middleware. We can do this safely because, in the context of a browser, the
  240. header can only be added by using ``XMLHttpRequest``, and browsers already
  241. implement a same-domain policy for ``XMLHttpRequest``.
  242. For the more recent browsers that relax this same-domain policy, custom headers
  243. like "X-Requested-With" are only allowed after the browser has done a
  244. 'preflight' check to the server to see if the cross-domain request is allowed,
  245. using a strictly 'opt in' mechanism, so the exception for AJAX is still safe—if
  246. the developer has specifically opted in to allowing cross-site AJAX POST
  247. requests on a specific URL, they obviously don't want the middleware to disallow
  248. exactly that.
  249. .. _9.1.1 Safe Methods, HTTP 1.1, RFC 2616: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
  250. Caching
  251. =======
  252. If the ``csrf_token`` template tag is used by a template (or the ``get_token``
  253. function is called some other way), ``CsrfViewMiddleware`` will add a cookie and
  254. a ``Vary: Cookie`` header to the response. Similarly,
  255. ``CsrfResponseMiddleware`` will send the ``Vary: Cookie`` header if it inserted
  256. a token. This means that these middleware will play well with the cache
  257. middleware if it is used as instructed (``UpdateCacheMiddleware`` goes before
  258. all other middleware).
  259. However, if you use cache decorators on individual views, the CSRF middleware
  260. will not yet have been able to set the Vary header. In this case, on any views
  261. that will require a CSRF token to be inserted you should use the
  262. :func:`django.views.decorators.vary.vary_on_cookie` decorator first::
  263. from django.views.decorators.cache import cache_page
  264. from django.views.decorators.vary import vary_on_cookie
  265. @cache_page(60 * 15)
  266. @vary_on_cookie
  267. def my_view(request):
  268. # ...
  269. Testing
  270. =======
  271. The ``CsrfViewMiddleware`` will usually be a big hindrance to testing view
  272. functions, due to the need for the CSRF token which must be sent with every POST
  273. request. For this reason, Django's HTTP client for tests has been modified to
  274. set a flag on requests which relaxes the middleware and the ``csrf_protect``
  275. decorator so that they no longer rejects requests. In every other respect
  276. (e.g. sending cookies etc.), they behave the same.
  277. Limitations
  278. ===========
  279. Subdomains within a site will be able to set cookies on the client for the whole
  280. domain. By setting the cookie and using a corresponding token, subdomains will
  281. be able to circumvent the CSRF protection. The only way to avoid this is to
  282. ensure that subdomains are controlled by trusted users (or, are at least unable
  283. to set cookies). Note that even without CSRF, there are other vulnerabilities,
  284. such as session fixation, that make giving subdomains to untrusted parties a bad
  285. idea, and these vulnerabilities cannot easily be fixed with current browsers.
  286. If you are using ``CsrfResponseMiddleware`` and your app creates HTML pages and
  287. forms in some unusual way, (e.g. it sends fragments of HTML in JavaScript
  288. document.write statements) you might bypass the filter that adds the hidden
  289. field to the form, in which case form submission will always fail. You should
  290. use the template tag or :meth:`django.middleware.csrf.get_token` to get
  291. the CSRF token and ensure it is included when your form is submitted.
  292. Contrib and reusable apps
  293. =========================
  294. Because it is possible for the developer to turn off the ``CsrfViewMiddleware``,
  295. all relevant views in contrib apps use the ``csrf_protect`` decorator to ensure
  296. the security of these applications against CSRF. It is recommended that the
  297. developers of other reusable apps that want the same guarantees also use the
  298. ``csrf_protect`` decorator on their views.