DEV Community

Cover image for Django web security checklist before deployment | Secure your Django App
Rashid
Rashid

Posted on • Edited on

Django web security checklist before deployment | Secure your Django App

This post cross-published with OnePublish

You already know web security is important to keeping hackers and cyber-thieves from accessing sensitive information. So, in this post we are going to check Django security vulnerabilities and how to fix them.

Deployment Checklist

First thing first, check your security vulnerabilities by following command:

manage.py check --deploy
Enter fullscreen mode Exit fullscreen mode

You can see some descriptions which provide information about your Django web application vulnerabilities. Try to google these security issues and fix them before production.

The Mozilla Observatory

If you already deployed you application then use Observatory by Mozilla site to scan the security status of your site. The site also includes third-party scanners which test other security aspects of your site.

Here is the example of scan:

Reverse Python

Cross site request forgery (CSRF) protection

In a web application, basically the webforms take input from the user and send them to server-side components to process them. The server-side components generally expose the service as a POST, PUT, DELETE methods for accepting the data over HTTP. Django has built-in security against most forms of CSRF threats, as long as you have allowed and used it if necessary.

As stated in the documentation, be very careful when marking views with the csrf_exempt decorator, unless it is absolutely necessary.

If someone has access (through an man-in-the-middle attack or xss) to your csrftoken cookie, then this is a vulnerability.

The CSRF protection cannot protect against man-in-the-middle attacks, so use HTTPS with HTTP Strict Transport Security (We will discuss it in post later).

Once you’ve set up HTTPS, add these lines in your settings.py


CSRF_COOKIE_SECURE = True #to avoid transmitting the CSRF cookie over HTTP accidentally.
SESSION_COOKIE_SECURE = True #to avoid transmitting the session cookie over HTTP accidentally.

Enter fullscreen mode Exit fullscreen mode

Cross-site Scripting (XSS)

A Cross-site Scripting (XSS) allows an attacker to inject a script into the content of a website or app. When a user visits the infected page the script will execute in the victim’s browser. This allows attackers to steal private information like cookies, account information, etc.

X-XSS-Protection: 1; mode=block enables XSS filtering. Rather than sanitizing the page, the browser will prevent rendering of the page if an attack is detected.

To enable it in Django, make sure django.middleware.security.SecurityMiddleware is present in middleware's list and add following lines in your settings.py:

SECURE_BROWSER_XSS_FILTER = True
SECURE_CONTENT_TYPE_NOSNIFF = True
Enter fullscreen mode Exit fullscreen mode

Django Admin Security

One of the most important thing is to make Django administration secure. Before you deploy your application you must change admin/ path to something only you know. Otherwise, someone can easily type /admin in url and access to adminsitrator login page.

#urls.py

from django.contrib import admin
from django.urls import path

urlpatterns = [
    path('admin/', admin.site.urls) # change admin something different
Enter fullscreen mode Exit fullscreen mode

You can create fake admin login page using django-admin-honeypot and it will notify you if someone try attempt unauthorized access.

SSL Redirect

Add following line to your settings.py to force Django redirect all non-HTTPS requests to HTTPS.

SECURE_SSL_REDIRECT = True
Enter fullscreen mode Exit fullscreen mode

Content Security Policy (CSP)

If your Django application is large, contains a lot of third-party code, and has a lot of inline scripts and styles scattered all over the project, then you should add CSP to your site.

For more information about CSP visit An Introduction to Content Security Policy

Django does not have a built-in method for creating a CSP header, so you can install Mozilla’s django-csp module and use your browser's console to track the security violations in your code.

Once you installed django-csp, add following lines to your settings.py

# Content Security Policy
CSP_DEFAULT_SRC = ("'none'", )
CSP_STYLE_SRC = ("'self'", )
CSP_SCRIPT_SRC = ("'self'", )
CSP_IMG_SRC = ("'self'", )
CSP_FONT_SRC = ("'self'", )
Enter fullscreen mode Exit fullscreen mode

So, basically, your all inline scripts and styles will not be allowed anymore. All scripts and styles must be loaded from a resource. You can add ‘unsafe-inline’ to your script and style CSP headers, however, it negates the whole policy.

Its really important to clean your code from all these inline styles and scripts. However, some external resources such as Google Tag Manager or Google Analytics should be allowed in your CSP policy. To achieve that update your code like this:

#Content Security Policy
CSP_DEFAULT_SRC = ("'none'", )
CSP_STYLE_SRC = ("'self'", "fonts.googleapis.com", "'sha256-/3kWSXHts8LrwfemLzY9W0tOv5I4eLIhrf0pT8cU0WI='")
CSP_SCRIPT_SRC = ("'self'", "ajax.googleapis.com", "www.googletagmanager.com", "www.google-analytics.com")
CSP_IMG_SRC = ("'self'", "data:", "www.googletagmanager.com", "www.google-analytics.com")
CSP_FONT_SRC = ("'self'", "fonts.gstatic.com")
CSP_CONNECT_SRC = ("'self'", )
CSP_OBJECT_SRC = ("'none'", )
CSP_BASE_URI = ("'none'", )
CSP_FRAME_ANCESTORS = ("'none'", )
CSP_FORM_ACTION = ("'self'", )
CSP_INCLUDE_NONCE_IN = ('script-src',)
Enter fullscreen mode Exit fullscreen mode

Fore more information take a look django-csp documentation.

Note that this configuration depends on which external resources you are using so please first read the documentation and then apply changes to your site.

HTTP Strict Transport Security

When this policy is set, browsers will refuse to connect to your site for the given time period if you’re not properly serving HTTPS resources, or if your certificate expires.

Add the following lines to your settings.py:

SECURE_HSTS_SECONDS = 86400  # 1 day
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
Enter fullscreen mode Exit fullscreen mode

Mission Accomplished!

Now your app is almost secure. Additionally you can scan your open ports by using nmap and try to google how to fix these open ports.

If you liked the post please visit Reverse Python and share it with your friends!

Top comments (2)

Collapse
 
sobolevn profile image
Nikita Sobolev

Awesome article! I can probably add several important things here:

  1. Use django-axes or similar to block brute-force requests
  2. Use Feature-Policy header to switch on only things you really need in user's browser
  3. Use Referrer-Policy header to prevent sensitive information from leaking into other resources
  4. Use safety to make sure your dependencies are secure and do not contain any known vulnerabilities
  5. Use wemake-python-styleguide to check for your source code to be secure

I recommend to use wemake-django-template. It is a new project boilerplate focused on security and code quality. It has everything from the list. And even several more advanced features!

GitHub logo wemake-services / wemake-django-template

Bleeding edge django template focused on code quality and security.

wemake-django-template

wemake.services Awesome Build status Documentation Status Dependencies Status wemake-python-styleguide

Bleeding edge django4.2 template focused on code quality and security.


Purpose

This project is used to scaffold a django project structure Just like django-admin.py startproject but better.

Features

Installation

Firstly, you will need to install dependencies.

The recommended way is via pipx:

pipx install cookiecutter
pipx inject cookiecutter jinja2-git
Enter fullscreen mode Exit fullscreen mode

Or via global pip:

pip install cookiecutter jinja2-git
Enter fullscreen mode Exit fullscreen mode

Then, create a project itself:

cookiecutter gh:wemake-services/wemake-django-template
Enter fullscreen mode Exit fullscreen mode

Who is using this template?

If you use our template, please add yourself or your company in the list

And by the way, don't forget to audit your setup. twa is a great start. It is simple, yet quite feature rich.

Collapse
 
thedevtimeline profile image
Rashid

Wow! Thank you for additional gold information!🚀🚀