# Securing Django Applications

Source: https://djangotv.com/videos/djangocon-europe/2021/djangocon-2021-securing-django-applications-gajendra-deshpande/
Date: 2021-07-31
Speakers: Gajendra Deshpande

## Summary

Gajendra Deshpande explains how to identify and reduce common Django application vulnerabilities using simple checkup tools, Django’s security settings, OWASP guidance, and security-focused packages. He covers injection, broken authentication, sensitive-data exposure, XXE, broken access control, security misconfiguration, XSS, insecure deserialization, vulnerable dependencies, and inadequate logging, pairing each risk with mitigations such as parameterized queries, MFA, secure session handling, TLS, input validation, careful template escaping, dependency management, and centralized monitoring. He also introduces tools and learning resources including Django Hunter, Django Goat, Shadow Daemon, and Django’s security documentation, and stresses that both developers and users share responsibility for protecting applications and data.

## Transcript

### [00:00] Introduction and Django Security Checkup

[00:08] My name is Gajinda Desh Pandey and I will be presenting a talk on securing Django applications. So in today's talk, we will see how we can do simple testing for identifying the vulnerabilities in Django Web applications. Then we will see the overview of OAS top 10 risks. Then we will see some tools like Django Hunter and Django Goat. Then strategies and configuration settings to make Django application secure. Of course, we will not be following them in sequence. So whenever we discuss an issue, we will also be discussing about the possible solutions.

[00:55] Now this is an interesting website, so you can just try out So it's djcheckup. com slash pony and here you can enter any website which has been created using Django. So when you click on run checkup on my site, it will identify some issues. So for example, I just tried out the DjangoCon. eu website and it says that there are one there is one recommendation. That means there is one small security issue which we need to fix. So similarly you can try out for some other websites where you can find out the issues.

[01:41] But you can see here that there are many things which have been taken care of. For example, debug not enabled, HTTP rewriting to HTTPS. Die right. So HTTPS enabled, HSTS enabled. So these are some of the things which are which have been taken care of by this website so similarly it's a very useful tool which you can use to find out are to find out the vulnerabilities in Django web applications Now, whenever you create a Django project, right, so there is a settings. py file, and if you visit the settings. py file, you can see some security warnings there. For example, the security warning says keep the secret key used in production secret. And second one says that don't run with

[02:27] debug turned on in production So you have to disable these things. You have to make debug equal to false whenever you are going for production. Because what happens is if you enable debug equal to true Then hackers can use some commands and they can identify some errors and locks. And note here that The errors and locks also reveal a lot of information regarding the configuration, regarding the tools, their versions, etc. etc. And these can be used to carry out these further attacks So you need to make these settings. So you have to make debug equal to false. So in the previous slide, you might have seen that debug not enabled. So that because this website is in production and the developers have taken care of it.

### [03:17] OWASP Top 10 Overview

[03:17] Then let us see what are the top ten vulnerabilities defined by OWASP. So OASP stands for open web. Application Security Project. It's a non-profit organization and it defines top 10 vulnerabilities with respect to web technology. But not only your technology, but all the technologies related to the web or internet, you can say. So top 10 vulnerabilities identified by OASPAR First one is the injection attack, then broken authentication, then third one is the sensitive data exposure, and fourth one is XML external entities Then what next one is broken access control, then security misconfigurations, cross-site scripting, insecure deserialization.

[04:03] using components with known vulnerabilities, then insufficient logging and monitoring. Now what happens here is when we consider Django publication Or say for example Django web framework. We know that it's a most popular web framework for Python and it is used for developing web applications. Django already has some mechanisms, some packages in place. So you can start using those packages. And some are guidelines. So these guidelines are common to most of the web applications. But You can use built-in modules and take care of many security aspects. So we will see what are those modules and how we can do it later

### [04:48] Injection Attacks

[04:48] in next few slides. So, first one is the injection attack. So, when we say injection attack, we are going to frame an attack vector and which is it is going to be a malicious attack. In injection there are different types of injection attacks. So the most popular ones are SQL injection. Then apart from if you if you are using XML, then there will be XML injection or XPath injection, right? So it depends on what is your backend, where you are storing the data. So if you are using relational DBMS, then definitely it will be SQL injection if you're using XML then definitely it will be X path injection.

[05:33] So similarly The injection vulnerabilities can be found in SQL or LDAP. So LDAP is authentication service. Then similarly there is no SQL now, then it can be found in opening system commands Now, injection can result in several things like data loss or corruption of data or disclosure to unauthorized parties, the information, the confidential information, then loss of accountability or even the denial of access now here you can see here that the string query has been mentioned so it says that select start from accounts where customer id

[06:20] Is equal to request. get parameter of ID. Now this ID can be modified, right? So you can see here after ID the Boolean operators have been used. So we are saying R1 equal to one So no matter whatever is our left side query, right, or the query before R, it doesn't matter to us because after R One equal to one, it's always going to result into true and it will reveal the information, confidential information. So it may reveal even username and passwords. So there are different mechanisms which you can. Use to handle these things. So and one more security problem here is there are some methods like extra

[07:06] and raw SQL. So these are the features provided in Django. So you can use them to write custom queries in Django. Since it they enable you have to write custom queries in Django. They also come up with some security threats. So whenever you are using these, you have to use them with caution. Then the solution for SQL injection is query parameterization. So it is by default in Django you can directly use The query parameterization method. So don't use direct queries, instead parameterize them. Then, as I have said, use extra and RASQL with caution. Then use positive or whitelist server-side input validation. So input validation is

### [07:52] Broken Authentication

[07:52] one of the important techniques by which you can avoid SQL injection or say even XPath injection. But of course it may not be able to provide a complete defense, but you can achieve defense up to certain level. The next is broken authentication. So what happens in broken authentication is attackers will be having access to Hundreds and millions of valid usernames and password combinations for credential staffing. So they will also be having default administrative account lists then automated brute force and dictionary attack tools. So you know that they will get access, they will be having access to the ready-made databases

[08:38] which they may be buying from dark web then also the session management related attacks Are carried out in a broken authentication, then attackers have to gain access only to a few accounts Or just one admin account. So that is enough. So if they get access to one admin account, then they can do anything. So they can even delete the account, they can change any records They can even change the access control. So basically they can do whatever. So in broken authentication, they their goal is to Get access to the admin account. Then in current shell stuffing, they use the list of known passwords.

[09:23] So, what happens here is whenever the accounts have been created So generally the default password will be provided. So whenever the people who are responsible and when they are providing the default passwords, they have to be very, very careful. They should not use the common passwords so maybe they can use random functions and generate the passwords randomly Then most authentication attacks occur due to the continued use of passports as a sole factor. Yeah, this is also very important. So It's a most common practice. So whenever we say the authentication means username and password will be provided. But It should not be the only case.

[10:09] So whenever you are developing the application, you have to provide or you have to implement additional security features. Then application session timeouts aren't set properly. So if there's an application and if you are inactive for certain amount of time, say few seconds, it should log out to you automatically. So if that is not set properly then it is going to create a problem. Then how you can protect or how you can get the protection from broken authentication. So wherever possible implement multi-factor authentication to prevent automated credential stuffing brute force and Solen credential reuse attacks. So multi-factor authentication, it can be the two-factor authentication.

[10:56] Nowadays many applications come up with Two factor authentication, but it need not be the only one. You can also go for single sign-on. That is you can Whenever you want to log in, you can just opt for single sign-on. If it is implemented, then you will get an OTP or a password to your mobile phone or a email id and you can enter it so the basically here is you need not have to remember the password but you should have your device with you Then do not ship or deploy with any default credentials, particularly for admin users. So even if that is done, then the responsible person, the admin has to change the password. Then implement weak check weak password checks such as testing new or unchanged passwords against a list of

[11:45] top 10,000 worst passwords So basically you can write a code which will check the strength of the password and also you can use some APIs. Say for example there is a site called as haveibinpond. com that is H I B P in short. So you can use their APIs and check whether the password which you are setting is it part of the hacked database. So if it is part of the hacked database then you can suggest the user to enter a new password. Then align the password length, complexity, and rotation policy with NIST 8063 B standard. Then ensure registration, credential recovery, and API pathways are hardened against account enumeration

[12:35] attack by using the same messages for all outcomes. So hardening is a process So basically what we do here is we change the default settings. We customize it so that hackers should not be able to guess What is the configuration and so and other things. Then limit or increasingly delay the failed login attempts. So log all failures and alert administrators when credential stuffing, brute force or other attacks are detected. So again here you can use some code or you can write your own code or you can use Django module if it is available then you can count the number of login attempts and once

[13:22] Let's say for example you can set a limit for three attempts. So once three once three attempts are over, then what you can do is you can lock the entire login system for say 20 minutes or 30 minutes. So ready-made firewalls are available and you can just configure them. Then use a server-side secure built-in session manager that generates a new random session ID With high entropy after login. So session ID should not be in the URL be securely stored and invalidated after logout. So basically, you are generating the temporary session IDs, which are Valid for only that session. Now, if you are interested to implement, then you can consider these modules.

[14:09] These modules will give you up to certain level of protection. So if you are interested to implement one-time passwords, then You can go for Django OTP and if you are interested to implement two factor authentication, then you can go for Django two-factor auth. Then similarly for Django user sessions management. There is a module or package here. So Django user sessions. So you can just visit these URLs. You will find the link there. You will find the information regarding how to install them, how to configure them and how to use them. The next is sensitive data exposure. So rather than directly attacking crypto attackers

### [14:54] Sensitive Data Exposure

[14:54] Steal keys, execute man-in-the-middle attacks or steal clear text data of the server, so while in transit, or from the user's client, for example the browser. So here the manual attack is generally required. So the example scenarios are like so the application encrypts credit card numbers in a database using automatic database encryption. So however this data is automatically decrypted when retrieved So allowing SQL injection floor to retrive credit card numbers in clear text. One way you can handle this issue is you can use the advancements in cryptography. Okay, say for example you can go for partially homomorphic encryption techniques or fully homomorphic encryption techniques

[15:42] depending on your requirement So, what they do basically is they perform some computation or they enable computations on the encrypted data. So, you need not have to decrypt the data whenever you are processing. So, you can do Processing on encrypted data. So whether you have to use the algorithms or you have to explore the properties of Homomorphic encryption of the available encryption algorithms. So all cryptographic algorithms they have one or the other Encryption homomorphic properties which enable you to perform computations on the encrypted data.

[16:28] Then a site doesn't use or enforce TLS for all pages or supports weak encryption. So SSL that is Secure Sockets layer has to be Enabled for a web application and if you're storing the data in the database, then the data has to be stored in encrypted form. Then the password database use unsorted or simple hashes. to store everyone's passwords. So this is again a problem. So you have to always sort and Hash the passwords and store them in the database. So the possible solutions are here like classify the data processed. Stored or transmitted by an application. So identify which data is sensitive, which data is not sensitive.

[17:15] Then according to the privacy laws, regulatory requirements Or business needs, then apply controls as per the classification. Here it is very important to understand the privacy laws and regulatory requirements. So you should see which technique is supported by the law and implement those things. So if you don't use those technologies, if you don't use the technique which is mentioned in the law, then In case of attack or in case of damage, then there will be problems in the claims or getting a relief. Then don't store sensitive data unnecessarily, right? So discard it as soon as possible, right?

[18:03] Then next make sure to encrypt all sensitive data at rest. Then ensure up-to-date and strong standard algorithms, protocols, and keys are in place. So use proper key management Then encrypt all data in transit with secure protocols such as TLS with preferred forward secrecy ciphers. Then disable caching for response that contains sensitive data, then store password using strong adaptive and salted hashing functions. Then verify independently the effectiveness of configuration and settings. So apart from these things, I have also mentioned that you can use homomorphic encryption algorithms Now, this is a sample

[18:51] setting which you need to do. In your production. py file. So you can see here that the options have been enabled here. Say for example The secure proxy SSL header is mapped to HTTPS, then even the host scheme is mentioned as HTTPS. Session cookie secure is true. So basically we have set all the security parameters to true. Then if you want to wrap standard Django fields with encryption provided by Python Cryptographic Library, so you can use this library, Django encrypted model

### [19:36] XML External Entities

[19:36] fields. Then a set of primitives for easily encrypting data in Django. So you can again use the Django cryptography library. Then if you are interested in symmetric encryption for Django model feeds, then you can use Furnet. Next is X XML entities. Now attackers can exploit vulnerable XML processors if they can upload XML or include hostile content in an XML document. Exploiting vulnerable code dependencies or integrations. So these flaws can be used to extract data, execute a remote request from the server. Can internal systems perform a denial of service attack as well as execute other attacks?

[20:24] So we know that XML allows us to create our own tags, our own attributes and our own entities. Right. So when it allows this feature, so i it's also providing it's also coming up with some security flaws because it enables us to create our own entities and these entities can be malicious. So in the first example, you can see here the attacker is attempting to extract the data from the server. So you can see here the entity which is mentioned here. So it is the syntax of XML file Right. So first one is element which is used to create your own element. So here we are trying to create foo element in XML. Then next one is XXC

[21:10] is a Entity which we are trying to create. So if you are familiar with HTML, you know what are these elements and what are these entities, right? And you know how to access these entities also So basically when this entity is used that is ampersand XXC semicolon, when I say it, so it may retrieve me the password or it may try to extract some information from the server. Then similarly, an attacker props the server's private network by changing above the entity line to this information. Say for example, he says that Entity access system, then he's specifying the IP address and he's saying private. So by that he's getting the server

[21:55] trying to get the server's private network information And also he can try to perform denial of service attack. So by including potentially endless file. So basically denial of service attack is very simple. You are keeping the server busy So your server is busy in serving your request while it is blocking others request. So this can be done when you are specifying potentially endless file. Then to The solution for X XML entities is that one way is that you can use JSON format that is JavaScript object notation format and avoid the serialization of sensitive data then disable

[22:44] XML external entity and DTD processing in all XML parsers then Again implement whitelisting that is server side input validation. Then verify that XML or XL XSL file uploaded Upload functionality validates incoming XML using XSD validation or similar. So we know that all our markup languages they come up with the validation tools. So your HTML has validation tool, even XML has validation tool, you can also validate your DTD file. So you can use those validators Here to ensure that it conforms to the applications standards or applications rules only

[23:34] Then you can also go for shadow demon Here we which is used to detect record and block attacks on the publications So Shadow Demon is a web application firewall that intercepts requests and filters out malicious parameters. So it's a modular system that separates web application analysis. interface to increase security, flexibility and expandability. So it's a free software, it supports Python, Django, and Flask And also it is available for other languages such as PHP and Perl. So to get more information, you can just visit the URL mentioned on this slide.

### [24:21] Broken Access Control

[24:21] So basically it's a web application firewall. Then broken access control. So here the application uses unverified data in SQL. So you can do it by using the statement mentioned here. So here we are mentioning that The account variable in get parameter function. So, what attacker can do is he can just replace the account variable with the account number to get the information if it is not verified then he will get access to the account So here you can see here

[25:06] the attacker is mentioning not my account, so that's a account number, so that's a dummy account number. Or you can even simply force the browsers to target URLs. Then admin rights are required for access the For accessing the admin web page. So if there's an unauthenticated user can access these pages, then it's a flaw. So non-admin should not access the admin page So the appropriate code has to be written to take care of this issue. Now to provide the protection Access control is only effective if it is enforced in trusted server side code or serverless API.

[25:55] So where the attacker cannot modify the access control check or metadata. You have to write the appropriate code on the server side. Then with an exception of public resources deny by default. Then disable web server directory listing and ensure file metadata and backup files are not present with the web routes. Then log access control failures. It is very, very important to analyze the information later whenever attack happens then very important you can go for Django user management and define the various Access levels. So basically in access control, we are defining who are the superusers, who are the admins, then who are the customers, and depending on the users and their roles, we are providing the

### [26:43] Security Misconfiguration

[26:43] access. Then security misconfiguration, it is also one of the important problems With respect to Django applications or even any web application, so security misconfigurations will occur. So if your application is not properly configured, then again It's a flaw and attackers can exploit those flaws. So attacker will often attempt to exploit unpatched flaws or access default accounts, unused pages, unprotected files and directories Etc. To gain unauthorized access or knowledge of the system. Then security misconfiguration can happen at any level of application stack, including network services, platform, web server, application server,

[27:31] database. frameworks, custom code or even pre-installed virtual machines. Automated scanners are useful for detecting the misconfigurations. Use of default accounts or configurations, then unnecessary services, let's see options. Then application server comes with sample applications that are not removed from production server Then directory listing is not disabled on the server. So many times whenever we try to access website, generally if the web user is experienced user Right. He tries to access the directory. He see he tries to check whether the directory listing is enabled. And if it is enabled, then he will try to access the files By visiting those folders. So it has to be disabled and appropriate error messages has to be

[28:19] displayed. Then the application server configuration allows detailed error messages stack traces to be written to the users. This is very important. Right? So even the error messages, they reveal some information about the system. They will reveal some information about the configuration and this information can be used to carry out the further attacks. Then a cloud service provider has default sharing permissions open to the internet by other CSP users. Now the possible solutions are here Django hardening, then disable directory listing, then use automatic scanners. Then customize error messages to hide sensitive information. This is very, very important. So when you customize your error messages, you are just displaying the error messages which you want to display.

### [29:07] Cross-Site Scripting

[29:07] So in this way you are hiding the sensitive information. Then class set scripting. So application uses untested data in the construction of the following HTML snippet without validation or escaping. So you can see here there is a Basically, a field so which accepts some input. Say, for example, in your web application, there will be a text field. Say there's a simple text field search. So in the text field, you are going to write a JavaScript code, say for example, alert And when you click on search function, it will execute. So if it executes, then you can assume that there is a flaw in that. Now to protect from cross-site

[29:53] scripting you can use Django templates. So Django templates protect you against the majority of the excess attacks, but there are some exceptions. Then Django templates escape specific characters which are particularly dangerous to HTML. Now you know that our recent web technology such as Angular or Node They support this style of coding. Now note here that I need not have to specify the JavaScript code here alert. Instead, I can store that code where is equal to alert of hello. And so in this case, whenever this code gets executed, it calls the JavaScript code and this is also a problem. So it will not protect such types of

### [30:40] Insecure Deserialization

[30:40] So it is also important to be particularly careful when you are using e safe or custom template tags and also the safe template tag, mark safe and auto escape is turned off. So you should also be very careful when storing HTML in the database, especially when that HTML is retrieved and displayed. The next one is insecure deserialization. So applications and APIs will be vulnerable if they deserialize Hostile or tampered objects supplied by an attacker. So this can result in two primary types of attacks. So one is object and data structure-related attacks where the attacker modifies the application logic Or achieves arbitrary remote code execution

[31:26] if there are classes available to the application that can change behavior During or after deserialization. Second one is typical data tampering attacks such as access control related attacks where existing data structures are used but content is changed Now serialization may be used in applications for example remote and inter-process communication, wire protocols, web services, message brokers, caching or persistence Even in case of databases, caching servers, file systems, then HTTP cookies, HTML form parameters, and AP authentication tokens Now the only safe artificial pattern is to not accept the serialized objects from untrusted source.

[32:12] So if it is from untrusted source, just don't block it. or to use syllacion mediums that only permit primitive data types. So don't allow custom data types. Then implementing integrity checks such as distal signatures or any serialized objects to prevent hostile object creation or data tampering so you can use Django J signature package for this then enforcing strict type constraints during deserialization before object creation as the core typically expects to A definable set of classes, then isolating and running code that deserializes in rope low privilege environments, then log deserialization exceptions and failures

### [32:59] Components with Known Vulnerabilities

[32:59] The next one is using compounds with known vulnerabilities. Now what happens is the component have heavy development patterns can lead to development teams. not even understanding which components they use in their application or API. So much less keeping them to up to date. So components typical run with the same privileges as the application itself. So flaws in any component can result in serious impact. So such flaws can be accidental, for example, coding error or even intentional that is backdoor in the component. Now there should be a patch management process in place to remove unused dependencies, unnecessary features, components, files, and documentation. Then continuously inventory the

[33:46] versions of both clients and server-side components. Continuously monitor sources such as C V and MVD for vulnerabilities in the components. Then only obtain components from official sources. Over secure links, then use tools like Shodan and Django Hunter. So basically, whenever you are depending on component-oriented development, you should see whichever component you are using Whether it fits into your project. So basically, many times these components have been provided by third party. You should see whether the third party service provider, whether he or she is Or whether the company or the developer, whether they are updating their component To match the recent

### [34:32] Logging and Monitoring

[34:32] Version of the Django framework. If it is not matching, if they are not updating it frequently, then it's a problem. You should use always the compatible Component. Then Shodan is a search engine which is basically used to find out the vulnerabilities in the devices connected to the internet. So Django Hunter uses Shodan inside internally to find out the vulnerabilities An insufficient logging and monitoring. So exploitation of insufficient logging and monitoring is bedrock for nearly every major incident. So attackers rely on Lack of monitoring and timely response to achieve their goals without being deleted.

[35:20] So one strategy for determining if you have sufficient monitoring is to examine the logs following penetration testing. So the tester 's action should be recorded sufficiently to understand what damages They have inflicted. So again, there are ready-made tools. You should use those ready-made tools and configure your sites there. So it will do continuous monitoring. Regarding the component versions, regarding the updates. So ensure all login access controls failures and server side input validation failures Can be logged with sufficient user context to identify suspicious or malicious accounts. So ensure that logs are generated in a format that can be easily consumed by the centralized log management solutions.

### [36:10] Django Security Tools and Resources

[36:10] Then establish effective monitoring and alerting such that suspicious activities are detected and responded to in a timely fashion. So basically, here you need to configure the automated scanners. Okay. Yeah. So you can use Django Hunter tool which is a tool which can be used to identify incorrectly configured Django applications. You can refer the link and this is how you can use it Then similarly Django goat is it's an intentionally vulnerable Django app to help Django developers to learn security testing. So if you want to learn more about it, then you can visit this link. Then these are the two resources. You can use the first link

[36:57] to find out different security. Resources related to Django, then there is official Django security documentation also available. So in summary, so since Django is a web framework, it maps to OAS top 10 vulnerabilities It has built-in modules to build secure Django applications. Then security of the application and data is not only the responsibility of the developer, so the user is also equally responsible for security of the data and accounts. So thank you everyone for attending my talk.
