Cross-Site Request Forgery

Cross-site request forgery (CSRF) happens when a malicious Web site tricks users into unknowingly loading a URL from a site at which they’re already authenticated — hence taking advantage of their authenticated status. Django has built-in tools to protect from this kind of attack.

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).

Use of the decorator by itself is not recommended, 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.

Usage:
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)

If you are using class-based views, you can refer to decorating class-based views in the Django documentation.

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 CSRF_FAILURE_VIEW setting.

How It Works

The CSRF protection is based on the following things:

  • 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).
  • 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.
  • For all incoming requests that are not using HTTP GET, HEAD, OPTIONS or TRACE, 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.
  • In addition, for HTTPS requests, strict referrer 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 ignores GET requests (and other requests that are defined as ‘safe’ by RFC 2616). These requests ought never to have any potentially dangerous side effects, and so a CSRF attack with a GET request ought to be harmless. RFC 2616 defines POST, PUT and DELETE as ‘unsafe’, and all other methods are assumed to be unsafe, for maximum protection.

Caching

If the 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 or the CSRF cookie, and the response will be cached without either one.

In this case, on any views that will require a CSRF token to be inserted you should use the django.views.decorators.csrf.csrf_protect() decorator first:

from django.views.decorators.cache import cache_page
from django.views.decorators.csrf import csrf_protect

@cache_page(60 * 15)
@csrf_protect
def my_view(request):

If you are using class-based views, you can refer to decorating class-based views in the Django documentation.

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.

CSRF Utilities

The examples below assume you are using function-based views. If you are working with class-based views, you can refer to decorating class-based views in the Django documentation.

django.views.decorators.csrf.csrf_exempt(view) – Most views require CSRF protection, but a few do not. Rather than disabling the middleware and applying csrf_protect to all the views that need it, enable the middleware and use csrf_exempt().

This decorator marks a view as being exempt from the protection ensured by the middleware.

Example:
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse

@csrf_exempt
def my_view(request):
return HttpResponse(‘Hello world’)

django.views.decorators.csrf.requires_csrf_token(view) – There are cases when CsrfViewMiddleware.process_view 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.

Normally the 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)

There may also be some views that are unprotected and have been exempted by csrf_exempt, but still need to include the CSRF token. In these cases, use csrf_exempt() followed by requires_csrf_token(). (i.e. requires_csrf_token should be the innermost decorator).

A final example is where a view needs CSRF protection under one set of conditions only, and mustn’t have it for the rest of the time. A solution is to use csrf_exempt() for the whole view function, and csrf_protect() for the path within it that needs protection.

For example:
from django.views.decorators.csrf import csrf_exempt,
csrf_protect

@csrf_exempt
def my_view(request):

@csrf_protect
def protected_path(request):
do_something()

if some_condition():
return protected_path(request)
else:
do_something_else()

django.views.decorators.csrf.ensure_csrf_cookie(view) – This decorator forces a view to send the CSRF cookie. A scenario where this would be used is if a page makes a POST request via AJAX, and the page does not have an HTML form with a csrf_token that would cause the required CSRF cookie to be sent. The solution would be to use ensure_csrf_cookie() on the view that sends the page.

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.

CSRF Settings

A number of settings can be used to control Django’s CSRF behavior:

  •  CSRF_COOKIE_AGE
  • CSRF_COOKIE_DOMAIN
  • CSRF_COOKIE_HTTPONLY
  • CSRF_COOKIE_NAME
  • CSRF_COOKIE_PATH
  • CSRF_COOKIE_SECURE
  • CSRF_FAILURE_VIEW

Back to Tutorial

Share this post
[social_warfare]
Cross-Site Scripting (XSS)
Advanced IO and Tomcat

Get industry recognized certification – Contact us

keyboard_arrow_up