Application security is or should always be at the top of every developer’s list of priorities, but there’s the tendency when using some frameworks and packages to forget about this and assume that it is handled for you. Django, a high-level Python web framework, provides several built-in security features that can help protect your applications. This post will walk you through some best practices and techniques to ensure the security of your Python Django application.
We recently wrote a blog post on some common web frameworks for Python where we talk about the benefits of using the Django framework here. In essence, Django is a full-featured Python web framework that provides a large set of tools and features for building complex and scalable web applications. It contains virtually every tool that you’ll need which is one reason it draws a lot of attention.
While the Django web framework is known for having security features baked in, it is still a web framework and thus susceptible to the same types of attacks that other web applications are vulnerable to—meaning you need to understand these vulnerabilities to effectively protect your application. The Django team is very good at publicizing and disclosing information on these vulnerabilities as well as their causes and fixes so it is worth keeping an eye on their security disclosure page.
Just this last year there have been a few Denial-of-Service (DoS) vulnerabilities published, with CVE-2024-27351, CVE-2024-24680, and CVE-2023-46695 all pointing at possibilities of DoS with causes rooted in Django classes and templates.
Cross-site scripting attacks are known in Django too, with CVE-2022-22818 and CV-2020-13596 both having a CVSS rating of 6.1 Medium.
To ensure your application stands the best chance against published CVEs such as the ones above, make sure you are using the most recent versions of Django and packages in your projects, as the team will usually list the discovered versions and their vulnerable components.
The settings.py
file is the central configuration file for Django projects. Since this includes the application’s security settings, only administrators should have access to edit it. Some of these settings include specifying a secret key for cryptographic operations such as generating cookies and tokens and enforcing HTTPS-only connections for session and CSRF cookies.
In addition, Django allows password configuration and policy rules using its settings.py
file. This means that options features such as validators, password hashers, and timeouts can be configured using this file.
DoS attacks target web applications to disrupt the availability by overwhelming it with a high volume of malicious requests, the nature of this attack means that every application is susceptible. With Django applications, some extra steps can be taken.
Django Middleware for Rate Limiting: You can create custom middleware or use middleware packages like Django Ratelimit to enforce rate limits on incoming requests. This helps prevent an individual user or IP address from making too many requests within a short period, mitigating the impact of DoS attacks.
One common security vulnerability is XSS attacks. XSS attacks occur when an attacker injects malicious code into a website to be stored in a database, which is then unintentionally and likely unknowingly executed by users. The consequences of this allowing the attacker to steal sensitive information, manipulate web content, or perform actions on behalf of the victim.
Auto-Escape Templates: Django’s template engine automatically escapes variables by default, rendering them safe from XSS attacks. This means that any data rendered in templates (using syntax) is HTML-escaped by default, preventing the execution of injected scripts.
Content Security Policy (CSP): Adding CSP headers in your Django application can mitigate the impact of XSS attacks by specifying which resources (e.g., scripts, stylesheets, images) are allowed to be loaded and executed and the origin they can be sourced from. With XSS, the attacker abuses the trust of web browsers as these will by default trust the content received from a server, implementing CSP prevents inline script execution and limits the domains from which resources can be loaded.
Avoid the “safe” Filter: Django templates allow the use of a “safe” filter to explicitly mark content as safe for HTML rendering, it should be used sparingly and only when absolutely necessary otherwise there is a risk of inadvertently introducing unsafe content or by stringing multiple filters together to render an unsafe output. Use auto-escaping and safe template tags instead to maintain a consistent and secure approach to outputting HTML content.
CSRF is a type of attack that occurs when a victim’s web browser is forced to perform an unwanted action on a trusted site, while authenticated by a trusted server, by visiting a malicious site, blog, or email. It often means the victim has been tricked or manipulated into clicking a link which performs an action on a website which the user is already authenticated on. The link will usually contain a script or payload to perform an action such as resetting emails or passwords, or worse.
CSRF Token: Django comes with built-in CSRF protection middleware, by using a CSRF token which is randomized when a user is authenticated, this is then verified when completing any forms or requests to ensure the request originated from the correct point of origin.
Django supports a range of different SQL based databases, which means it is open to SQL Injection attacks. These types of attacks are performed when precautions haven’t been implemented or implemented poorly for communications between the website and the database. They are relatively straightforward to carry out, where they only require an attacker to try a few different queries in the frontend of a website to wreak havoc.
Django ORM: Like any website and database, mitigating SQL Injection comes in the form of using parameterization and sanitizing user input. One of the features of Django which is encouraged is the use of its ORM (Object-Relational Mapping) for database interactions. Where ORM methods automatically handle parameterization of SQL queries, reducing the risk of SQL injection vulnerabilities.
The good news is that nowadays there is a wide range of resources and tools and resources that can be used to improve security in web applications. From gathering more information on vulnerabilities there are wells of information such as OWASP’s Top 10 list and SecureFlag’s own Knowledge Base, which has the added benefit of linking to related labs to get more experience remediating the vulnerabilities in a developer environment too.
Django also offers an in-depth guide breakdown on all the security features they include on their website.
At SecureFlag we are big believers in improving and implementing comprehensive training for developers and other team members that interact with the development process. Our catalog of interactive and virtual labs features a wide range of technologies with vulnerabilities to remediate including web frameworks like Django, Flask, and Sinatra. With SecureFlag labs your teams get access to training in their browser which simulates the tools used in the modern SDLC such as Android Studio, AWS, Azure, Visual Studio Code and many others.
Get in touch with our team today to learn more about SecureFlag and integrating secure code training into your development pipelines to boost your organization’s culture of security!