Security in Django

Ensuring that the sites you build are secure is of the utmost importance to a professional web applications developer.

The Django framework is now very mature and the majority of common security issues are addressed in some way by the framework itself, however no security measure is 100% guaranteed and there are new threats emerging all the time, so it’s up to you as a web developer to ensure that your web sites and applications are secure.

Web security is too large a subject to cover in depth in a single book chapter. This chapter includes an overview of Django’s security features and advice on securing a Django-powered site that will protect your sites 99% of the time, but it’s up to you to keep abreast of changes in web security.

For more detailed information on web security, Django’s archive of security issues is a good place to start, along with Wikipedia’s web application security page.

Django’s Built in Security Features

Cross Site Scripting (XSS) Protection

XSS attacks allow a user to inject client side scripts into the browsers of other users.

This is usually achieved by storing the malicious scripts in the database where it will be retrieved and displayed to other users, or by getting users to click a link which will cause the attacker’s JavaScript to be executed by the user’s browser. However, XSS attacks can originate from any untrusted source of data, such as cookies or Web services, whenever the data is not sufficiently sanitized before including in a page.

Using Django templates protects you against the majority of XSS attacks. However, it is important to understand what protections it provides and its limitations.

Django templates escape specific characters which are particularly dangerous to HTML. While this protects users from most malicious input, it is not entirely foolproof. For example, it will not protect the following:

<style class={{ var }}>...</style>

If var is set to 'class1 onmouseover=javascript:func()', this can result in unauthorized JavaScript execution, depending on how the browser renders imperfect HTML. (Quoting the attribute value would fix this case.)

It is also important to be particularly careful when using is_safe with custom template tags, the safe template tag, mark_safe, and when autoescape is turned off.

In addition, if you are using the template system to output something other than HTML, there may be entirely separate characters and words which require escaping.

You should also be very careful when storing HTML in the database, especially when that HTML is retrieved and displayed.

Cross Site Request Forgery (CSRF) Protection

CSRF attacks allow a malicious user to execute actions using the credentials of another user without that user’s knowledge or consent.

Django has built-in protection against most types of CSRF attacks, providing you have enabled and used it where appropriate. However, as with any mitigation technique, there are limitations.

For example, it is possible to disable the CSRF module globally or for particular views. You should only do this if you know what you are doing. There are other limitations if your site has subdomains that are outside of your control.

CSRF protection works by checking for a nonce in each POST request. This ensures that a malicious user cannot simply replay a form POST to your Web site and have another logged in user unwittingly submit that form. The malicious user would have to know the nonce, which is user specific (using a cookie).

When deployed with HTTPS, CsrfViewMiddleware will check that the HTTP referrer header is set to a URL on the same origin (including subdomain and port). Because HTTPS provides additional security, it is imperative to ensure connections use HTTPS where it is available by forwarding insecure connection requests and using HSTS for supported browsers.

Be very careful with marking views with the csrf_exempt decorator unless it is absolutely necessary.

Django’s CSRF middleware and template tag provides easy-to-use protection against Cross Site Request Forgeries.

The first defense against CSRF attacks is to ensure that GET requests (and other ‘safe’ methods, as defined by 9.1.1 Safe Methods, HTTP 1.1, RFC 2616) are side-effect free. Requests via ‘unsafe’ methods, such as POST, PUT and DELETE, can then be protected by following the steps below.

How to Use It

To take advantage of CSRF protection in your views, follow these steps:

  1. The CSRF middleware is activated by default in the MIDDLEWARE_CLASSES setting. If you override that setting, remember that 'django.middleware.csrf.CsrfViewMiddleware' should come before any view middleware that assume that CSRF attacks have been dealt with.If you disabled it, which is not recommended, you can use csrf_protect() on particular views you want to protect (see below).
  2. In any template that uses a POST form, use the 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.template.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.template.context_processors.csrf' (no matter what template context processors are configured in the TEMPLATES 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.shortcuts import render_to_response
       from django.template.context_processors import csrf
      
       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.

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.

As a first step, you must get the CSRF token itself. The recommended source for the token is the csrftoken cookie, which will be set if you’ve enabled CSRF protection for your views as outlined above.

The CSRF token cookie is named csrftoken by default, but you can control the cookie name via the CSRF_COOKIE_NAME setting.

Acquiring the token is straightforward:

// using jQuery
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;
}
var csrftoken = getCookie('csrftoken');
The above code could be simplified by using the jQuery cookie plugin[56]
to replace `getCookie`:

var csrftoken = $.cookie('csrftoken');

Finally, you’ll have to actually set the header on your AJAX request, while protecting the CSRF token from being sent to other domains using settings.crossDomain in jQuery 1.5.1 and newer:

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});
Other Template Engines

When using a different template engine than Django’s built-in engine, you can set the token in your forms manually after making sure it’s available in the template context.

For example, in the Jinja2 template language, your form could contain the following:

<div style="display:none">
    <input type="hidden" name="csrfmiddlewaretoken"
value="{{ csrf_token }}">
</div>

You can use JavaScript similar to the AJAX code above to get the value of the CSRF token.