Django web security checklist before deployment | Secure your Django App
Tags: python, django, security, webdev
Published: 2019-12-21 20:04:11


This post cross-published with [OnePublish](https://www.onepubli.sh)

<p>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.</p>


<h3>Deployment Checklist</h3>
<p>First thing first, check your security vulnerabilities by following command:</p>

```
manage.py check --deploy
```
<p>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.</p>

<h3>The Mozilla Observatory</h3>
<p>If you already deployed you application then use <a href="https://observatory.mozilla.org/">Observatory by Mozilla</a> site to scan the security status of your site. The site also includes third-party scanners which test other security aspects of your site.</p>

<p>Here is the example of scan:</p>
<img src="https://thepracticaldev.s3.amazonaws.com/i/69djyhdunmbozn7klglr.png" alt="Reverse Python" />

<h3>Cross site request forgery (CSRF) protection</h3>
<p>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.</p>

<p>As stated in the <a href="https://docs.djangoproject.com/en/3.0/ref/csrf/#using-csrf">documentation</a>, be very careful when marking views with the <b>csrf_exempt</b> decorator, unless it is absolutely necessary.</p>

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

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

<p>Once you’ve set up HTTPS, add these lines in your <b>settings.py</b></p>

```python

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.

```
<h3>Cross-site Scripting (XSS)</h3>
<p>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.</p>

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

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

```python
SECURE_BROWSER_XSS_FILTER = True
SECURE_CONTENT_TYPE_NOSNIFF = True
```
<h3>Django Admin Security</h3>
<p>One of the most important thing is to make Django administration secure. Before you deploy your application you must change <b>admin/</b> path to something only you know. Otherwise, someone can easily type /admin in url and access to adminsitrator login page.</p>

```python
#urls.py

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

urlpatterns = [
    path('admin/', admin.site.urls) # change admin something different
```

<p>You can create fake admin login page using <a href="https://pypi.org/project/django-admin-honeypot/">django-admin-honeypot</a> and it will notify you if someone try attempt unauthorized access.</p>

<h3>SSL Redirect</h3>
<p>Add following line to your <b>settings.py</b> to force Django redirect all non-HTTPS requests to HTTPS.</p>

```python
SECURE_SSL_REDIRECT = True
```

<h3>Content Security Policy (CSP)</h3>
<p>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.</p>

<p>For more information about CSP visit 
<a href="https://www.html5rocks.com/en/tutorials/security/content-security-policy/">An Introduction to Content Security Policy</a>
</p>

<p>Django does not have a built-in method for creating a CSP header, so you can install Mozilla’s <a href="https://github.com/mozilla/django-csp">django-csp</a> module and use your browser's console to track the security violations in your code.</p>

<p>Once you installed django-csp, add following lines to your <b>settings.py</b></p>

```python
# Content Security Policy
CSP_DEFAULT_SRC = ("'none'", )
CSP_STYLE_SRC = ("'self'", )
CSP_SCRIPT_SRC = ("'self'", )
CSP_IMG_SRC = ("'self'", )
CSP_FONT_SRC = ("'self'", )
```

<p>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.</p>

<p>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:</p>

```python
#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',)
```
<p>Fore more information take a look <a href="https://django-csp.readthedocs.io/en/latest/configuration.html">django-csp documentation</a>.</p>

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

<h3>HTTP Strict Transport Security</h3>
<p>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.</p>

<p>Add the following lines to your <b>settings.py</b>:</p>

```python
SECURE_HSTS_SECONDS = 86400  # 1 day
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
```

<h3>Mission Accomplished!</h3>
<p>Now your app is almost secure. Additionally you can scan your open ports by using <a href="https://nmap.org/">nmap</a> and try to google how to fix these open ports.</p>

<p>If you liked the post please visit <a href="https://reversepython.net/">Reverse Python</a> and share it with your friends!</p>