django/docs/ref/contrib/csrf.txt

357 lines
14 KiB
Plaintext

=====================================
Cross Site Request Forgery protection
=====================================
.. module:: django.middleware.csrf
:synopsis: Protects against Cross Site Request Forgeries
The CSRF middleware and template tag provides easy-to-use protection against
`Cross Site Request Forgeries`_. This type of attack occurs when a malicious
Web site contains a link, a form button or some javascript that is intended to
perform some action on your Web site, using the credentials of a logged-in user
who visits the malicious site in their browser. A related type of attack,
'login CSRF', where an attacking site tricks a user's browser into logging into
a site with someone else's credentials, is also covered.
The first defense against CSRF attacks is to ensure that GET requests are
side-effect free. POST requests can then be protected by following the steps
below.
.. _Cross Site Request Forgeries: http://www.squarefree.com/securitytips/web-developers.html#CSRF
How to use it
=============
To enable CSRF protection for your views, follow these steps:
1. Add the middleware
``'django.middleware.csrf.CsrfViewMiddleware'`` to your list of
middleware classes, :setting:`MIDDLEWARE_CLASSES`. (It should come
and before any view middleware that assume that CSRF attacks have
been dealt with.)
Alternatively, you can use the decorator
``django.views.decorators.csrf.csrf_protect`` on particular views you
want to protect (see below).
2. In any template that uses a POST form, use the :ttag:`csrf_token` tag inside
the ``<form>`` element if the form is for an internal URL, e.g.::
<form action="." method="post">{% csrf_token %}
This should not be done for POST forms that target external URLs, since
that would cause the CSRF token to be leaked, leading to a vulnerability.
3. In the corresponding view functions, ensure that the
``'django.core.context_processors.csrf'`` context processor is
being used. Usually, this can be done in one of two ways:
1. Use RequestContext, which always uses
``'django.core.context_processors.csrf'`` (no matter what your
TEMPLATE_CONTEXT_PROCESSORS setting). If you are using
generic views or contrib apps, you are covered already, since these
apps use RequestContext throughout.
2. Manually import and use the processor to generate the CSRF token and
add it to the template context. e.g.::
from django.core.context_processors import csrf
from django.shortcuts import render_to_response
def my_view(request):
c = {}
c.update(csrf(request))
# ... view code here
return render_to_response("a_template.html", c)
You may want to write your own ``render_to_response`` wrapper that
takes care of this step for you.
The utility script ``extras/csrf_migration_helper.py`` can help to automate the
finding of code and templates that may need these steps. It contains full help
on how to use it.
.. _csrf-ajax:
AJAX
----
While the above method can be used for AJAX POST requests, it has some
inconveniences: you have to remember to pass the CSRF token in as POST data with
every POST request. For this reason, there is an alternative method: on each
XMLHttpRequest, set a custom `X-CSRFToken` header to the value of the CSRF
token. This is often easier, because many javascript frameworks provide hooks
that allow headers to be set on every request. In jQuery, you can use the
``ajaxSend`` event as follows:
.. code-block:: javascript
$(document).ajaxSend(function(event, xhr, settings) {
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
function sameOrigin(url) {
// url could be relative or scheme relative or absolute
var host = document.location.host; // host + port
var protocol = document.location.protocol;
var sr_origin = '//' + host;
var origin = protocol + sr_origin;
// Allow absolute or scheme relative URLs to same origin
return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
(url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
// or any other URL that isn't scheme relative or absolute i.e relative.
!(/^(\/\/|http:|https:).*/.test(url));
}
if (sameOrigin(settings.url)) {
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
});
Adding this to a javascript file that is included on your site will ensure that
AJAX POST requests that are made via jQuery will not be caught by the CSRF
protection.
The decorator method
--------------------
Rather than adding ``CsrfViewMiddleware`` as a blanket protection, you can use
the ``csrf_protect`` decorator, which has exactly the same functionality, on
particular views that need the protection. It must be used **both** on views
that insert the CSRF token in the output, and on those that accept the POST form
data. (These are often the same view function, but not always). It is used like
this::
from django.views.decorators.csrf import csrf_protect
from django.shortcuts import render
@csrf_protect
def my_view(request):
c = {}
# ...
return render(request, "a_template.html", c)
Use of the decorator is **not recommended** by itself, since if you forget to
use it, you will have a security hole. The 'belt and braces' strategy of using
both is fine, and will incur minimal overhead.
Subdomains
----------
By default, CSRF cookies are specific to the subdomain they are set for. This
means that a form served from one subdomain (e.g. server1.example.com) will not
be able to have a target on another subdomain (e.g. server2.example.com). This
restriction can be removed by setting :setting:`CSRF_COOKIE_DOMAIN` to be
something like ``".example.com"``.
Please note that, with or without use of this setting, this CSRF protection
mechanism is not safe against cross-subdomain attacks -- see `Limitations`_.
Rejected requests
=================
By default, a '403 Forbidden' response is sent to the user if an incoming
request fails the checks performed by ``CsrfViewMiddleware``. This should
usually only be seen when there is a genuine Cross Site Request Forgery, or
when, due to a programming error, the CSRF token has not been included with a
POST form.
The error page, however, is not very friendly, so you may want to provide your
own view for handling this condition. To do this, simply set the
:setting:`CSRF_FAILURE_VIEW` setting to a dotted path to your own view function,
which should have the following signature::
def csrf_failure(request, reason="")
where ``reason`` is a short message (intended for developers or logging, not for
end users) indicating the reason the request was rejected.
How it works
============
The CSRF protection is based on the following things:
1. A CSRF cookie that is set to a random value (a session independent nonce, as
it is called), which other sites will not have access to.
This cookie is set by ``CsrfViewMiddleware``. It is meant to be permanent,
but since there is no way to set a cookie that never expires, it is sent with
every response that has called ``django.middleware.csrf.get_token()``
(the function used internally to retrieve the CSRF token).
2. A hidden form field with the name 'csrfmiddlewaretoken' present in all
outgoing POST forms. The value of this field is the value of the CSRF
cookie.
This part is done by the template tag.
3. For all incoming POST requests, a CSRF cookie must be present, and the
'csrfmiddlewaretoken' field must be present and correct. If it isn't, the
user will get a 403 error.
This check is done by ``CsrfViewMiddleware``.
4. In addition, for HTTPS requests, strict referer checking is done by
``CsrfViewMiddleware``. This is necessary to address a Man-In-The-Middle
attack that is possible under HTTPS when using a session independent nonce,
due to the fact that HTTP 'Set-Cookie' headers are (unfortunately) accepted
by clients that are talking to a site under HTTPS. (Referer checking is not
done for HTTP requests because the presence of the Referer header is not
reliable enough under HTTP.)
This ensures that only forms that have originated from your Web site can be used
to POST data back.
It deliberately only targets HTTP POST requests (and the corresponding POST
forms). GET requests ought never to have any potentially dangerous side effects
(see `9.1.1 Safe Methods, HTTP 1.1, RFC 2616`_), and so a CSRF attack with a GET
request ought to be harmless.
.. _9.1.1 Safe Methods, HTTP 1.1, RFC 2616: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
Caching
=======
If the :ttag:`csrf_token` template tag is used by a template (or the
``get_token`` function is called some other way), ``CsrfViewMiddleware`` will
add a cookie and a ``Vary: Cookie`` header to the response. This means that the
middleware will play well with the cache middleware if it is used as instructed
(``UpdateCacheMiddleware`` goes before all other middleware).
However, if you use cache decorators on individual views, the CSRF middleware
will not yet have been able to set the Vary header. In this case, on any views
that will require a CSRF token to be inserted you should use the
:func:`django.views.decorators.vary.vary_on_cookie` decorator first::
from django.views.decorators.cache import cache_page
from django.views.decorators.vary import vary_on_cookie
@cache_page(60 * 15)
@vary_on_cookie
def my_view(request):
# ...
Testing
=======
The ``CsrfViewMiddleware`` will usually be a big hindrance to testing view
functions, due to the need for the CSRF token which must be sent with every POST
request. For this reason, Django's HTTP client for tests has been modified to
set a flag on requests which relaxes the middleware and the ``csrf_protect``
decorator so that they no longer rejects requests. In every other respect
(e.g. sending cookies etc.), they behave the same.
If, for some reason, you *want* the test client to perform CSRF
checks, you can create an instance of the test client that enforces
CSRF checks::
>>> from django.test import Client
>>> csrf_client = Client(enforce_csrf_checks=True)
Limitations
===========
Subdomains within a site will be able to set cookies on the client for the whole
domain. By setting the cookie and using a corresponding token, subdomains will
be able to circumvent the CSRF protection. The only way to avoid this is to
ensure that subdomains are controlled by trusted users (or, are at least unable
to set cookies). Note that even without CSRF, there are other vulnerabilities,
such as session fixation, that make giving subdomains to untrusted parties a bad
idea, and these vulnerabilities cannot easily be fixed with current browsers.
Edge cases
==========
Certain views can have unusual requirements that mean they don't fit the normal
pattern envisaged here. A number of utilities can be useful in these
situations. The scenarios they might be needed in are described in the following
section.
Utilities
---------
.. module:: django.views.decorators.csrf
.. function:: csrf_exempt(view)
This decorator marks a view as being exempt from the protection ensured by
the middleware. Example::
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def my_view(request):
return HttpResponse('Hello world')
.. function:: requires_csrf_token(view)
Normally the :ttag:`csrf_token` template tag will not work if
``CsrfViewMiddleware.process_view`` or an equivalent like ``csrf_protect``
has not run. The view decorator ``requires_csrf_token`` can be used to
ensure the template tag does work. This decorator works similarly to
``csrf_protect``, but never rejects an incoming request.
Example::
from django.views.decorators.csrf import requires_csrf_token
from django.shortcuts import render
@requires_csrf_token
def my_view(request):
c = {}
# ...
return render(request, "a_template.html", c)
Scenarios
---------
CSRF protection should be disabled for just a few views
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Most views requires CSRF protection, but a few do not.
Solution: rather than disabling the middleware and applying ``csrf_protect`` to
all the views that need it, enable the middleware and use
:func:`~django.views.decorators.csrf.csrf_exempt`.
CsrfViewMiddleware.process_view not used
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
There are cases when may not have run before your view is run - 404 and 500
handlers, for example - but you still need the CSRF token in a form.
Solution: use :func:`~django.views.decorators.csrf.requires_csrf_token`
Unprotected view needs the CSRF token
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
There may be some views that are unprotected and have been exempted by
``csrf_exempt``, but still need to include the CSRF token.
Solution: use :func:`~django.views.decorators.csrf.csrf_exempt` followed by
:func:`~django.views.decorators.csrf.requires_csrf_token`.
Contrib and reusable apps
=========================
Because it is possible for the developer to turn off the ``CsrfViewMiddleware``,
all relevant views in contrib apps use the ``csrf_protect`` decorator to ensure
the security of these applications against CSRF. It is recommended that the
developers of other reusable apps that want the same guarantees also use the
``csrf_protect`` decorator on their views.