Related Articles

Related Articles

Adding CSP headers in Django Project
  • Last Updated : 08 Nov, 2020

Website security has been an important factor while developing websites and web applications. Many frameworks come with their own security policies and developers also try to implement the atmost security policies while developing their applications. Still even after this much of hard work hackers will find new ways to penetrate into our app, exploit our code to vulnerabilities. In this article we are going to implement a security header often referred as CSP headers to a Django application.

Terminology

  • CSP: Content-Security-Policy is a HTTP response header that modern browsers use to enhance the security of the  web page by  allowing you to restrict how resources such as JavaScript, CSS, or pretty much anything that the browser loads.
  • HTTP header: HTTP headers let the client and the server pass additional information with an HTTP request or response like MIME type, request status code, cookie and proxy information and more
  • XSS: Also abbrevated as  Cross Side Scripting, XSS attacks enable attackers to inject client-side scripts into web pages viewed by other users in simple words if exploited can change look and behavior of webpage
  • Django: django is an python based web application framework which used to build variety of web apps

What is Content Security Policy?

Content-Security-Policy is a HTTP response header that modern browsers use to enhance the security of the  web page by  allowing you to restrict how resources such as JavaScript, CSS, or pretty much anything that the browser loads designed to prevent XSS attacks which enable attackers to inject client-side scripts into web pages viewed by other users in simple words if exploited can change look and behavior of webpage. It also called successor of X-Content-Security-Policy or X-Webkit-CSP headers. CSP can also be implemented using meta tag.

Some CSP header terminology are

  • default-src : the default source to load everything
  • style-src : source to load styles
  • script-src : source to load javascrpt or generally scripts
  • img-src : source to load images
  • object-src : source to load media
  • report-to : uri to send reports for violating CSP
  • ‘self’ : load from same host
  • ‘unsafe-inline’ : allow inline styles and scripts
  • ‘unsafe-eval’ : allows eval() and similar methods for creating code from strings
  • ‘nonce’ : a random string which should be unique per request

How Content Security policy works?

CSP works by blocking execution of styles, scripts and other things unless they are allowed in the policy. CSP doesn’t allow execution of inline scripts and styles which means we can’t use <script/> and <style/> tags for javascript and styling.

An example of CSP headers is



Content-Security-Policy: default-src 'self';
style-src: 'self' stakpath.bootstrapcdn.com;
script 'self' *.cloudflare.com;
img-src 'self' imgur.com;

In this CSP header we are telling the browser that the default source for all the styles, scripts, images, objects should be the domain which is passed in the header, along with that we are also allowing stylesheet from stackpath.bootstrapcdn.com which is cdn for bootstrap styles. We are also allowing scripts to be loaded from all Cloudflare subdomains using wildcard subdomain and for images browser can allow to load from imgur.com. Apart from these if the webpage tries to load from other domain like twitter the browser will block the requests.

Implementing CSP headers in django

Django doesn’t come with CSP headers in its core but thanks to Mozilla, they have created a package django-csp to add CSP headers.

# instaling django-csp
pip3 install django-csp

add CSP to middleware in our setting.py file of the django project and the we will configure our headers

filter_none

edit
close

play_arrow

link
brightness_4
code

MIDDLEWARE = (
    # ...
    'csp.middleware.CSPMiddleware',
    # ...
)

chevron_right


Configuring CSP headers

Go to settings file of the django project and add the following in the last or anywhere you want

filter_none

edit
close

play_arrow

link
brightness_4
code

# uri to report policy violations
# uri to report policy violations
CSP_REPORT_URI = '<add your reporting uri>'
   
# default source as self
CSP_DEFAULT_SRC = ("'self'", )
   
# style from our domain and bootstrapcdn
CSP_STYLE_SRC = ("'self'",  
    "stackpath.bootstrapcdn.com")
   
# scripts from our domain and other domains
CSP_SCRIPT_SRC = ("'self'"
    "ajax.cloudflare.com"
    "static.cloudflareinsights.com"
    "www.google-analytics.com"
    "ssl.google-analytics.com"
    "cdn.ampproject.org"
    "www.googletagservices.com"
    "pagead2.googlesyndication.com")
   
# images from our domain and other domains
CSP_IMG_SRC = ("'self'"
    "www.google-analytics.com"
    "raw.githubusercontent.com"
    "googleads.g.doubleclick.net")
   
# loading manifest, workers, frames, etc
CSP_FONT_SRC = ("'self'", )
CSP_CONNECT_SRC = ("'self'",  
    "www.google-analytics.com" )
CSP_OBJECT_SRC = ("'self'", )
CSP_BASE_URI = ("'self'", )
CSP_FRAME_ANCESTORS = ("'self'", )
CSP_FORM_ACTION = ("'self'", )
CSP_INCLUDE_NONCE_IN = ('script-src', )
CSP_MANIFEST_SRC = ("'self'", )
CSP_WORKER_SRC = ("'self'", )
CSP_MEDIA_SRC = ("'self'", )

chevron_right


You can add required hostname according to your needs

Instructions to add CSP Header settings in Django Project

Here are some instructions to perfectly implement CSP in your web apps

  • Try to avoid adding unnecessary hostnames
  • Check as many times as possible while adding or removing hostnames
  • Until absolutely necessary don’t add ‘unsafe-inline’, it will weaken our security policy
  • Try to avoid inline style and scripts
  • Its better not to use CSP in development server right from the start
  • Always try to use HTTPS while loading scripts, styles, images.

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :