csrf.txt 20 KB

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