PageRenderTime 101ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

Plain Text | 472 lines | 370 code | 102 blank | 0 comment | 0 complexity | 1796f55fb4b6e95ed06c06f8b0a51116 MD5 | raw file
Possible License(s): BSD-3-Clause
  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:
  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/`` 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. .. _csrf-ajax:
  64. AJAX
  65. ----
  66. While the above method can be used for AJAX POST requests, it has some
  67. inconveniences: you have to remember to pass the CSRF token in as POST data with
  68. every POST request. For this reason, there is an alternative method: on each
  69. XMLHttpRequest, set a custom `X-CSRFToken` header to the value of the CSRF
  70. token. This is often easier, because many javascript frameworks provide hooks
  71. that allow headers to be set on every request. In jQuery, you can use the
  72. ``ajaxSend`` event as follows:
  73. .. code-block:: javascript
  74. $(document).ajaxSend(function(event, xhr, settings) {
  75. function getCookie(name) {
  76. var cookieValue = null;
  77. if (document.cookie && document.cookie != '') {
  78. var cookies = document.cookie.split(';');
  79. for (var i = 0; i < cookies.length; i++) {
  80. var cookie = jQuery.trim(cookies[i]);
  81. // Does this cookie string begin with the name we want?
  82. if (cookie.substring(0, name.length + 1) == (name + '=')) {
  83. cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
  84. break;
  85. }
  86. }
  87. }
  88. return cookieValue;
  89. }
  90. function sameOrigin(url) {
  91. // url could be relative or scheme relative or absolute
  92. var host =; // host + port
  93. var protocol = document.location.protocol;
  94. var sr_origin = '//' + host;
  95. var origin = protocol + sr_origin;
  96. // Allow absolute or scheme relative URLs to same origin
  97. return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
  98. (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
  99. // or any other URL that isn't scheme relative or absolute i.e relative.
  100. !(/^(\/\/|http:|https:).*/.test(url));
  101. }
  102. function safeMethod(method) {
  103. return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
  104. }
  105. if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
  106. xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
  107. }
  108. });
  109. .. note::
  110. Due to a bug introduced in jQuery 1.5, the example above will not work
  111. correctly on that version. Make sure you are running at least jQuery 1.5.1.
  112. Adding this to a javascript file that is included on your site will ensure that
  113. AJAX POST requests that are made via jQuery will not be caught by the CSRF
  114. protection.
  115. The decorator method
  116. --------------------
  117. Rather than adding ``CsrfViewMiddleware`` as a blanket protection, you can use
  118. the ``csrf_protect`` decorator, which has exactly the same functionality, on
  119. particular views that need the protection. It must be used **both** on views
  120. that insert the CSRF token in the output, and on those that accept the POST form
  121. data. (These are often the same view function, but not always). It is used like
  122. this::
  123. from django.views.decorators.csrf import csrf_protect
  124. from django.template import RequestContext
  125. @csrf_protect
  126. def my_view(request):
  127. c = {}
  128. # ...
  129. return render_to_response("a_template.html", c,
  130. context_instance=RequestContext(request))
  131. Use of the decorator is **not recommended** by itself, since if you forget to
  132. use it, you will have a security hole. The 'belt and braces' strategy of using
  133. both is fine, and will incur minimal overhead.
  134. Legacy method
  135. -------------
  136. In Django 1.1, the template tag did not exist. Instead, a post-processing
  137. middleware that re-wrote POST forms to include the CSRF token was used. If you
  138. are upgrading a site from version 1.1 or earlier, please read this section and
  139. the `Upgrading notes`_ below. The post-processing middleware is still available
  140. as ``CsrfResponseMiddleware``, and it can be used by following these steps:
  141. 1. Follow step 1 above to install ``CsrfViewMiddleware``.
  142. 2. Add ``'django.middleware.csrf.CsrfResponseMiddleware'`` to your
  143. :setting:`MIDDLEWARE_CLASSES` setting.
  144. ``CsrfResponseMiddleware`` needs to process the response before things
  145. like compression or setting ofETags happen to the response, so it must
  146. come after ``GZipMiddleware``, ``CommonMiddleware`` and
  147. ``ConditionalGetMiddleware`` in the list. It also must come after
  148. ``CsrfViewMiddleware``.
  149. Use of the ``CsrfResponseMiddleware`` is not recommended because of the
  150. performance hit it imposes, and because of a potential security problem (see
  151. below). It can be used as an interim measure until applications have been
  152. updated to use the :ttag:`csrf_token` tag. It is deprecated and will be
  153. removed in Django 1.4.
  154. Django 1.1 and earlier provided a single ``CsrfMiddleware`` class. This is also
  155. still available for backwards compatibility. It combines the functions of the
  156. two middleware.
  157. Note also that previous versions of these classes depended on the sessions
  158. framework, but this dependency has now been removed, with backward compatibility
  159. support so that upgrading will not produce any issues.
  160. Security of legacy method
  161. ~~~~~~~~~~~~~~~~~~~~~~~~~
  162. The post-processing ``CsrfResponseMiddleware`` adds the CSRF token to all POST
  163. forms (unless the view has been decorated with ``csrf_response_exempt``). If
  164. the POST form has an external untrusted site as its target, rather than an
  165. internal page, that site will be sent the CSRF token when the form is submitted.
  166. Armed with this leaked information, that site will then be able to successfully
  167. launch a CSRF attack on your site against that user. The
  168. ``@csrf_response_exempt`` decorator can be used to fix this, but only if the
  169. page doesn't also contain internal forms that require the token.
  170. .. _ref-csrf-upgrading-notes:
  171. Upgrading notes
  172. ---------------
  173. When upgrading to version 1.2 or later, you may have applications that rely on
  174. the old post-processing functionality for CSRF protection, or you may not have
  175. enabled any CSRF protection. This section outlines the steps necessary for a
  176. smooth upgrade, without having to fix all the applications to use the new
  177. template tag method immediately.
  178. First of all, the location of the middleware and related functions have
  179. changed. There are backwards compatible stub files so that old imports will
  180. continue to work for now, but they are deprecated and will be removed in Django
  181. 1.4. The following changes have been made:
  182. * Middleware have been moved to ``django.middleware.csrf``
  183. * Decorators have been moved to ``django.views.decorators.csrf``
  184. ====================================================== ==============================================
  185. Old New
  186. ====================================================== ==============================================
  187. django.contrib.csrf.middleware.CsrfMiddleware django.middleware.csrf.CsrfMiddleware
  188. django.contrib.csrf.middleware.CsrfViewMiddleware django.middleware.csrf.CsrfViewMiddleware
  189. django.contrib.csrf.middleware.CsrfResponseMiddleware django.middleware.csrf.CsrfResponseMiddleware
  190. django.contrib.csrf.middleware.csrf_exempt django.views.decorators.csrf.csrf_exempt
  191. django.contrib.csrf.middleware.csrf_view_exempt django.views.decorators.csrf.csrf_view_exempt
  192. django.contrib.csrf.middleware.csrf_response_exempt django.views.decorators.csrf.csrf_response_exempt
  193. ====================================================== ==============================================
  194. You should update any imports, and also the paths in your
  195. :setting:`MIDDLEWARE_CLASSES`.
  196. If you have ``CsrfMiddleware`` in your :setting:`MIDDLEWARE_CLASSES`, you will now
  197. have a working installation with CSRF protection. It is recommended at this
  198. point that you replace ``CsrfMiddleware`` with its two components,
  199. ``CsrfViewMiddleware`` and ``CsrfResponseMiddleware`` (in that order).
  200. If you do not have any of the middleware in your :setting:`MIDDLEWARE_CLASSES`,
  201. you will have a working installation but without any CSRF protection for your
  202. views (just as you had before). It is strongly recommended to install
  203. ``CsrfViewMiddleware`` and ``CsrfResponseMiddleware``, as described above.
  204. Note that contrib apps, such as the admin, have been updated to use the
  205. ``csrf_protect`` decorator, so that they are secured even if you do not add the
  206. ``CsrfViewMiddleware`` to your settings. However, if you have supplied
  207. customised templates to any of the view functions of contrib apps (whether
  208. explicitly via a keyword argument, or by overriding built-in templates), **you
  209. MUST update them** to include the :ttag:`csrf_token` template tag as described
  210. above, or they will stop working. (If you cannot update these templates for
  211. some reason, you will be forced to use ``CsrfResponseMiddleware`` for these
  212. views to continue working).
  213. Note also, if you are using the comments app, and you are not going to add
  214. ``CsrfViewMiddleware`` to your settings (not recommended), you will need to add
  215. the ``csrf_protect`` decorator to any views that include the comment forms and
  216. target the comment views (usually using the :ttag:`comment_form_target` template
  217. tag).
  218. Assuming you have followed the above, all views in your Django site will now be
  219. protected by the ``CsrfViewMiddleware``. Contrib apps meet the requirements
  220. imposed by the ``CsrfViewMiddleware`` using the template tag, and other
  221. applications in your project will meet its requirements by virtue of the
  222. ``CsrfResponseMiddleware``.
  223. The next step is to update all your applications to use the template tag, as
  224. described in `How to use it`_, steps 2-3. This can be done as soon as is
  225. practical. Any applications that are updated will now require Django 1.1.2 or
  226. later, since they will use the CSRF template tag which was not available in
  227. earlier versions. (The template tag in 1.1.2 is actually a no-op that exists
  228. solely to ease the transition to 1.2 รข&#x20AC;&#x201D; it allows apps to be created that have
  229. CSRF protection under 1.2 without requiring users of the apps to upgrade to the
  230. Django 1.2.X series).
  231. The utility script ``extras/`` can help to automate the
  232. finding of code and templates that may need to be upgraded. It contains full
  233. help on how to use it.
  234. Finally, once all applications are upgraded, ``CsrfResponseMiddleware`` can be
  235. removed from your settings.
  236. While ``CsrfResponseMiddleware`` is still in use, the ``csrf_response_exempt``
  237. decorator, described in `Exceptions`_, may be useful. The post-processing
  238. middleware imposes a performance hit and a potential vulnerability, and any
  239. views that have been upgraded to use the new template tag method no longer need
  240. it.
  241. Exceptions
  242. ----------
  243. .. versionchanged:: 1.2
  244. Import paths for the decorators below were changed.
  245. To manually exclude a view function from being handled by either of the two CSRF
  246. middleware, you can use the ``csrf_exempt`` decorator, found in the
  247. ``django.views.decorators.csrf`` module. For example::
  248. from django.views.decorators.csrf import csrf_exempt
  249. @csrf_exempt
  250. def my_view(request):
  251. return HttpResponse('Hello world')
  252. Like the middleware, the ``csrf_exempt`` decorator is composed of two parts: a
  253. ``csrf_view_exempt`` decorator and a ``csrf_response_exempt`` decorator, found
  254. in the same module. These disable the view protection mechanism
  255. (``CsrfViewMiddleware``) and the response post-processing
  256. (``CsrfResponseMiddleware``) respectively. They can be used individually if
  257. required.
  258. Subdomains
  259. ----------
  260. By default, CSRF cookies are specific to the subdomain they are set for. This
  261. means that a form served from one subdomain (e.g. will not
  262. be able to have a target on another subdomain (e.g. This
  263. restriction can be removed by setting :setting:`CSRF_COOKIE_DOMAIN` to be
  264. something like ``""``.
  265. Please note that, with or without use of this setting, this CSRF protection
  266. mechanism is not safe against cross-subdomain attacks -- see `Limitations`_.
  267. Rejected requests
  268. =================
  269. By default, a '403 Forbidden' response is sent to the user if an incoming
  270. request fails the checks performed by ``CsrfViewMiddleware``. This should
  271. usually only be seen when there is a genuine Cross Site Request Forgery, or
  272. when, due to a programming error, the CSRF token has not been included with a
  273. POST form.
  274. No logging is done, and the error message is not very friendly, so you may want
  275. to provide your own page for handling this condition. To do this, simply set
  276. the :setting:`CSRF_FAILURE_VIEW` setting to a dotted path to your own view
  277. function, which should have the following signature::
  278. def csrf_failure(request, reason="")
  279. where ``reason`` is a short message (intended for developers or logging, not for
  280. end users) indicating the reason the request was rejected.
  281. How it works
  282. ============
  283. The CSRF protection is based on the following things:
  284. 1. A CSRF cookie that is set to a random value (a session independent nonce, as
  285. it is called), which other sites will not have access to.
  286. This cookie is set by ``CsrfViewMiddleware``. It is meant to be permanent,
  287. but since there is no way to set a cookie that never expires, it is sent with
  288. every response that has called ``django.middleware.csrf.get_token()``
  289. (the function used internally to retrieve the CSRF token).
  290. 2. A hidden form field with the name 'csrfmiddlewaretoken' present in all
  291. outgoing POST forms. The value of this field is the value of the CSRF
  292. cookie.
  293. This part is done by the template tag (and with the legacy method, it is done
  294. by ``CsrfResponseMiddleware``).
  295. 3. For all incoming POST requests, a CSRF cookie must be present, and the
  296. 'csrfmiddlewaretoken' field must be present and correct. If it isn't, the
  297. user will get a 403 error.
  298. This check is done by ``CsrfViewMiddleware``.
  299. 4. In addition, for HTTPS requests, strict referer checking is done by
  300. ``CsrfViewMiddleware``. This is necessary to address a Man-In-The-Middle
  301. attack that is possible under HTTPS when using a session independent nonce,
  302. due to the fact that HTTP 'Set-Cookie' headers are (unfortunately) accepted
  303. by clients that are talking to a site under HTTPS. (Referer checking is not
  304. done for HTTP requests because the presence of the Referer header is not
  305. reliable enough under HTTP.)
  306. This ensures that only forms that have originated from your Web site can be used
  307. to POST data back.
  308. It deliberately only targets HTTP POST requests (and the corresponding POST
  309. forms). GET requests ought never to have any potentially dangerous side effects
  310. (see `9.1.1 Safe Methods, HTTP 1.1, RFC 2616`_), and so a CSRF attack with a GET
  311. request ought to be harmless.
  312. ``CsrfResponseMiddleware`` checks the Content-Type before modifying the
  313. response, and only pages that are served as 'text/html' or
  314. 'application/xml+xhtml' are modified.
  315. .. _9.1.1 Safe Methods, HTTP 1.1, RFC 2616:
  316. Caching
  317. =======
  318. If the :ttag:`csrf_token` template tag is used by a template (or the ``get_token``
  319. function is called some other way), ``CsrfViewMiddleware`` will add a cookie and
  320. a ``Vary: Cookie`` header to the response. Similarly,
  321. ``CsrfResponseMiddleware`` will send the ``Vary: Cookie`` header if it inserted
  322. a token. This means that these middleware will play well with the cache
  323. middleware if it is used as instructed (``UpdateCacheMiddleware`` goes before
  324. all other middleware).
  325. However, if you use cache decorators on individual views, the CSRF middleware
  326. will not yet have been able to set the Vary header or the CSRF cookie, and the
  327. response will be cached without either one. In this case, on any views that
  328. will require a CSRF token to be inserted you should use the
  329. :func:`django.views.decorators.csrf.csrf_protect` decorator first::
  330. from django.views.decorators.cache import cache_page
  331. from django.views.decorators.csrf import csrf_protect
  332. @cache_page(60 * 15)
  333. @csrf_protect
  334. def my_view(request):
  335. # ...
  336. Testing
  337. =======
  338. The ``CsrfViewMiddleware`` will usually be a big hindrance to testing view
  339. functions, due to the need for the CSRF token which must be sent with every POST
  340. request. For this reason, Django's HTTP client for tests has been modified to
  341. set a flag on requests which relaxes the middleware and the ``csrf_protect``
  342. decorator so that they no longer rejects requests. In every other respect
  343. (e.g. sending cookies etc.), they behave the same.
  344. If, for some reason, you *want* the test client to perform CSRF
  345. checks, you can create an instance of the test client that enforces
  346. CSRF checks::
  347. >>> from django.test import Client
  348. >>> csrf_client = Client(enforce_csrf_checks=True)
  349. Limitations
  350. ===========
  351. Subdomains within a site will be able to set cookies on the client for the whole
  352. domain. By setting the cookie and using a corresponding token, subdomains will
  353. be able to circumvent the CSRF protection. The only way to avoid this is to
  354. ensure that subdomains are controlled by trusted users (or, are at least unable
  355. to set cookies). Note that even without CSRF, there are other vulnerabilities,
  356. such as session fixation, that make giving subdomains to untrusted parties a bad
  357. idea, and these vulnerabilities cannot easily be fixed with current browsers.
  358. If you are using ``CsrfResponseMiddleware`` and your app creates HTML pages and
  359. forms in some unusual way, (e.g. it sends fragments of HTML in JavaScript
  360. document.write statements) you might bypass the filter that adds the hidden
  361. field to the form, in which case form submission will always fail. You should
  362. use the template tag or :meth:`django.middleware.csrf.get_token` to get
  363. the CSRF token and ensure it is included when your form is submitted.
  364. Contrib and reusable apps
  365. =========================
  366. Because it is possible for the developer to turn off the ``CsrfViewMiddleware``,
  367. all relevant views in contrib apps use the ``csrf_protect`` decorator to ensure
  368. the security of these applications against CSRF. It is recommended that the
  369. developers of other reusable apps that want the same guarantees also use the
  370. ``csrf_protect`` decorator on their views.