Implementing Content Security Policy(CSP) in Django Site

Brixlabs
3 min readMar 14, 2019

When it comes to web application security, cross-site scripting(XSS) is one of the most well-known vulnerabilities among developers. By successfully exploiting of XSS an attacker can gain your session and therefore do everything the victim can.

Photo by Samuel Zeller on Unsplash

To prevent XSS vulnerabilities, the most and foremost is adding proper escaping of user input to your code. Today I will talk about another way of mitigating XSS by enforcing Content Security Policy(CSP). Specifically, implementing CSP in Django site.

In this blog, I will go through the steps including installation, configuration and commonly overlooked weaknesses when implementing CSP in Django website. In each step, I will give an

example from my own Django website project.

1. Install Django-csp

Following the guide:

1.

$ pip install django-csp

OR

add django-csp to the requirements.txt file, then run

$ pip install -r requirements.txt

2.

Add the django-csp middleware to MIDDLEWARE_CLASSES, go to settings.py.

MIDDLEWARE_CLASSES = (

# …

‘csp.middleware.CSPMiddleware’,

)

Example in my Django project:

2. Configuring Django-csp

Following the guide:

2.1 Starting by setting everything only allowing resources to be loaded from the current origin:

CSP_DEFAULT_SRC = (“‘none’”, )

CSP_STYLE_SRC = (“‘self’”, )

CSP_SCRIPT_SRC = (“‘self’”, )

CSP_IMG_SRC = (“‘self’”, )

CSP_FONT_SRC = (“‘self’”, )

2.2 With the above settings, all inline Javascript is disallowed. Scripts must be loaded from a resource explicitly allowed in your policy.

Next, we will deal with adding trusted sources to the policy.

For example, the inline Javascript my app relies on is at this location:

https://s3.amazonaws.com/juice/encode.js

At the bottom of index.html, set the location of your resource as the src of the script:

In settings.py, set https://s3.amazon.com to allow my s3 resource to be loaded.

3. One more thing…

In the previous step, we allow the entire external domain(https://s3.amazon.com) as a trusted source. It can become a problem if an attacker sets up a s3 bucket and gets our app to point to their resources. The best practice is to specify resource locations as precise as possible by using complete path or a subdomain only our resources exist.

In my case, I use my s3 bucket as the src where only my resources are available.

This blog provides a walk-through of setting CSP in Django site. In the configuration section, I covered how to specify resource location for SCRIPT. Moving forward, we also need to set up locations for ther resources such as STYLE and IMG. They will be following the same concept and configuration steps.

--

--

Brixlabs

A platform that streamlines the hiring process for local companies to hire vetted talent anywhere.