Security Best Practices for Django Applications with Gajendra Deshpande
Published November 16, 2022
This video features Gajendra Deshpande at PyCascades 2023 in Vancouver, British Columbia, Canada.
Django being one of the most popular Python-based web frameworks, applications developed using Django are always on the radar of hackers who try to find the vulnerabilities in the Django application and exploit the same for their benefit. This talk will discuss how to secure Django Web applications.
Django applications need security controls because data leaks can harm both users and a business’s reputation. Gajendra Deshpande explains how to inspect deployments with Mozilla Observatory, Django Checkup, and related tools, then relates the OWASP Top 10 to Django: broken access control, cryptographic failures, injection and XSS, insecure design, misconfiguration, outdated components, authentication failures, integrity failures, inadequate logging, and SSRF. He recommends secure settings such as keeping `SECRET_KEY` private, disabling `DEBUG`, enforcing HTTPS, using Django’s parameterized queries and template escaping, validating input, protecting sensitive data with current cryptography and salted adaptive password hashes, applying MFA and rate limits, updating dependencies, and monitoring failures. He also stresses secure design and deployment practices, trusted dependencies and repositories, careful handling of XML and remote requests, and shared responsibility between developers and users.
Summarised automatically from the transcript.
Automatically transcribed, so expect mistakes in names and technical terms.
Speaker 1: We have security best practices in Django applications with Cagendra. Kitchener, we're ready for ya.
Speaker 2: Yeah, thank you. Uh first of all, I would like to thank uh Pie Cascade's team for giving me an opportunity to uh speak in PyCasket 's conference. Yeah, it's uh a bit midnight for me. I'm speaking from India. Uh so it's 11. 30 p. m. here. So just pardon me because I'm feeling a little bit sleepy uh because of uh hectic day today. Yeah, nevertheless. Let's let me start my talk that is security best practices for Django applications. So in today's talk, we'll be discussing in brief the importance of Security with respect to web applications, then identifying security issues using
Speaker 2: Mozilla Observatory, then OSP top 10 issues and how to address them in Django, then built-in security features in Django. Then secure deployment of Django applications. I'm not sure whether I'll be able to cover all these topics, but I can share the slides later with the organizers so that you can refer for uh refer it for your future use. Yeah. So, importance of web application security. So, web application security is very important because If you don't secure applications, then the sensitive data will be leaked and it will Actually damage your applications. So it will also damage, it will also cause a damage to the reputation of the business.
Speaker 2: Now, why would we look at security important is that you can just go through the statistics mentioned on this site. So you can see here that Uh nearly just 19% of the websites have passed the module observatory test. So when I'm saying uh 19 % of the websites, these are the number of sites uh Basically, submitted to the Module Observatories tool. It's an open source tool, so we will discuss it later. But just for statistics purpose, I have included this slide here. Now there's a website called as DJ Checkup. You can use this tool here. You have to just mention the URL of a Django site.
Speaker 2: and click on run a checkup on my site and when you click on it it will show the results so wherever you see thumbs up That means it says that that issue has been taken care. Say for example, here debug not enabled, and below that you can see the description, it says that your site correctly has the debug setting disabled. Now, whenever you are creating the applications in Django, there is a file called a settings. py. And in settings. py you need to make these two settings. First one is you need to set a secret key and you need to keep this secret key secret. And second one is you need to set debug equal to false.
Speaker 2: If you set debug equal to true, then hackers will be able to discover the errors. And these errors also reveal some information about your framework, about your application, or about your system. And that information can be further used uh to exploit your application. Yeah. So coming back to Mozilla Observatory Tool, it's nothing but just a set of tools to analyze your website and inform you if you are utilizing many of them available methods to secure it. So it it was created by Apple King at Mozilla. It is divided into three projects One is HTTP observatory, which is a scanner or a grader.
Speaker 2: Basically we are going to use this user interface Where we are going to specify the URL of the website and click on scan to identify the problems. Then, second one is the observatory CLI, it is the command line interface And third one is actually the HTTP observatory website. Now it's uh since it's an open source, uh the source code is available on GitHub. You can Download the HTTP observatory source code and install it locally on your machine Now, this is the web interface of Mozilla Observatory website. So here you just need to mention the domain name of the website you want to scan, and it's going to identify the issues
Speaker 2: uh in the websites. Next is OAS top ten vulnerabilities Now on this slide you can see that there are two versions. One is 2017 version and second one is 2021 version. So generally, whenever OASP that is open web publication security project That was the earlier name but now just uh I think last month. Its name got changed and it is now Open worldwide application security project. So the scope is increased now So whenever OASP releases top 10 vulnerabilities, generally the ranking changes. So you can observe here on this slide, in 2017, injection
Speaker 2: vulnerability was ranked first. But now in 2021 it's been ranked third. So similarly, in 2017, broken authentication was ranked second. But now it has been clubbed and it has been ranked third. So generally what happens is that uh whenever uh new version of wasp is released, uh Some vulnerabilities will be clubbed together and some vulnerabilities will be removed and new vulnerabilities have been new vulnerability issues will be introduced. Say for example in 2021 version three new vulnerabilities have been introduced. So one is the insecure design that is ranked fourth, then
Speaker 2: in Software and data integrity failures, it's ranked 8th, and the 10th one is server-side request forgery. So these are the three new categories. So basically in 2021, the update is that there are three new categories. And four categories with naming and scoping changes and some consolidation in the top ten for 2021. Now let us first discuss the first issue that is broken access control. So this is as per 2021. So here what happens is the application uses the Unverified data in SQL call that is accessing the account information. So for example, you can see here in the statement that is V
Speaker 2: statement. sat string. So here request. getParameter account is mentioned. So what hacker can do is Or, attacker can do is he can just modify this parameter in the browser and send whatever account number they want. So basically, how they can do is that they can use some tools like uh where they can configure the proxy in the browser. So whatever request uh goes to that particular site it It will be routed via tools like Birth Suite. So Birth Suite knows what is the URL, and there they can actually modify the URL and send the updated request So, because of this, the attacker can simply force the browser
Speaker 2: to target the URLs. So here admin rights are required To access the admin page. But if hacker is able to access the admin page without logging in, then that means there's a flop. Now, prevention is that you can follow deny by default mechanism. So the deny by default mechanism is that You have to deny all private resources, allow only public information. So one more important point to note here is that access control is only effective If enforced in trusted server-side code or serverless API, where attacker cannot modify the access control, check, or metadata Then next is disable the web
Speaker 2: server directory listing and ensure that file metadata and backup files are not present within the web route. So you can configure a different folder and you can keep your Backup there, or even you can push it to cloud. Then log access control failures, alert admins when appropriate. So this is very very important because Whenever you are reinvesting the cause, then the log files play very very important role. Then rate limit API and controller access to the Minimize control the access to the minimize the harm from automated attack tooling. Then use Django user management packages with respect to Django applications.
Speaker 2: Now, let us discuss this second vulnerability that is cryptographic failures. So here what attacker does is that rather than directly attacking the crypto, attackers steal keys, execute the man-in-the-middle attacks, or steal clear text data of the server. While in transit or from the user's client. For example, the browser. So here the manual attack is generally required. So again, they can route all the requests Through tools like Burpsuit or Wireshark. Now, here an application encrypts credit card numbers in a database using automatic Database encryption.
Speaker 2: However, this data is automatically decrypted when retrieved, allowing a SQL injection floor to retrieve credit card numbers in the clear text. Now, the problem here is that what if the device itself is compromised? Some spyware are installed on it. So the moment you decrypt the information, it is visible or that can be Sent to the hacker or attacker. Now the solution or the recent developments in cryptography are that homomorphic encryption. So that allows you to performs perform Computations on the encrypted data. So you have partially homomorphic encryption algorithms and you have fully homomorphic encryption algorithms
Speaker 2: The standard cryptographic algorithms such as RSA, L Gamal, or LLP curve, they have Homomorphic properties. So the same can be used uh to tackle such issues. So in that case, even you can use uh compromised device also uh for performing computation you can use its capability then the third scenario uh here for cryptography failure is that site does not use or enforce TLS for all pages or supports weak encryption. Then the password database uses unsalted or simple hashes to store everyone's passwords. So salt is a special string which can be
Speaker 2: concatenated with hash to make it even more complicated or to make the life of uh uh hacker difficult so that he should not be able to guess the or compute the hash codes easily. Now the solution is that classify the data processed, stored, or transmitted by the application. So identify which data is sensitive, which is not sensitive according to the Laws and regulatory requirements or the business needs, then apply controls as per the classification. Then don't store sensitive data unnecessarily. Disc it as soon as possible. Then make sure that uh the information is compliance to some standards, maybe
Speaker 2: VCI DSS in terms with respect to uh credit cards or debit cards or basically the payment cards or HIPAA with respect to health information and so on Then make sure to encrypt all sensitive data at rest. Then use up-to-date and strong standard algorithms. Then disable caching for the response that contain the sensitive data. Then store passwords using strong adaptive and sorted. Hashing functions with the work factor, then verify independently the effectiveness of the configuration and settings. Now these are some of the settings which you can uh make with respect to Django applications.
Speaker 2: So you can see here that Most of the secure properties are set to true and always the request should be forwarded to HTTPS. All HTTP requests must be forwarded to HTTPS. Now you can use the mentioned packages of Django. For example, you can use Django encrypted model fields or Django cryptography packages. to make sure that you encrypt the sensitive information. Then third one is the injection So it is one of the most widely known vulnerability. So injection vulnerabilities are often found in SQL, LDAP, XPath, and
Speaker 2: No SQL queries, even they are present in operating system commands, parsers, and etc. Now you can see here that there is a valid query. Uh the first one is a valid Where uh selects are from accounts where customer ID is equal to D ID. But the second one is the URL. So you can see here that at the end, instead of specifying the valid ID. The attacker is specifying a malicious query using some Boolean operators. So this attack payload basically What it makes is that the left hand side query invalid and uh no right hand side query invalid.
Speaker 2: So whatever may be the uh left hand side query That will be considered as true, and it is going to reveal all the information. So it can basically display even the hidden information Uh which is stored in that database. Whether it satisfies the condition or it is uh doesn't satisfy the condition, that doesn't matter. The next is extra and raw SQL uh enables Django developer to write custom queries in Django. So those things need to be used with care. So now on this screen you can see here that The example, so how SQL injection attacks are performed. So instead of specifying the valid password, the user has specified admin
Speaker 2: 1 or 1 equal to 1. So that's an attack payload So with this, it's a most simplest example, of course. So there are many repositories in GitHub. They basically Have the list of all attack payloads and even you can construct your attack payload and you can try, you can automate also to get into the database and display the hidden information Now this is the example of command injection. So you can see here that the website name is mentioned along with the Command that is if config. So it's going to basically display the network information. So along with the Google. com that is the dig command, which basically displays the information about the
Speaker 2: Google server. It is also displaying the information about the network Now, the prevention is that you follow query parameterization and it is by default in Django. And whenever you are using extra and raw SQL, use it with caution. Then use positive or allow list server-side input validation. Then escape all supplied input. Then do not call OS commands or operating system commands directly. And use limit and other SQL controls. Within queries to prevent mass disclosure of records in case of SQL injection. Then cross-site scripting is also part of SQL injection. Now
Speaker 2: you can see here that there's a text field and user is entering some code there and when he clicks on go button note here that it is displaying the output So he has applied the hacker has basically applied the font color that is the green color to the text. And you can see that is reflected in the output. So if the JavaScript code or if the HTML code works here, that means that that particular site has got cross-site scripting vulnerability here. Now, to handle cross-site scripting vulnerability, you can use Django templates which protect you against the majority of XSS attacks. But of course, maybe complete protection may not be
Speaker 2: possible. But you can use Django templates. Now, the fourth one is insecure design. It's a new category for 2021 which focuses on the risk related to design and architectural flaws. So basically your design should be foolproof. It should be fault-proof. So there should not be any fundamental flaws or security-related flaws in the design. Otherwise, what happens is that hackers can exploit these vulnerabilities and they can basically achieve their goals. Say, for example, if there is a website which Allows the mass booking of uh tickets say in a group, say
Speaker 2: you can book if website allows 15 tickets to book, but if hacker is able to book 600 tickets At a time, then uh that too with few requests, then there is a design flaw. So such things need to be addressed. So to address insecure design, you need to basically Consider OWASP software assurance majority model, then establish and use secure development lifecycle with application security. Then establish and use the library of secure design patterns, then write unit and integration tests to validate that all critical flaws are resistant to the threat model.
Speaker 2: And the fifth one is the security misconfiguration. It is again a very very important parameter here. Your application may be most secure. Uh but if it is not configured properly for secure controls, then uh it's a flaw. Say for example, you might be aware that you have accounts such as Facebook or Instagram or even your Laptop has built-in controls for security. If they are not configured properly, then your laptop or your application is vulnerable So that's why it becomes very important for us to address this equity misconfiguration. The solutions are go for Django hardening with respect to Django applications, then disable directory
Speaker 2: listing. Then use automated scanners. So when I am speaking about hardening, I'm saying that don't use default settings. Customize everything. Then customize error messages to high-sensitive information. Then there is a uh XML external entities, so here uh The attacker can inject again malicious payload into the XML file or XPath query and Achieve his task. Say, for example, here he can create a malicious entity which is basically linking to slash slash password file, or it may be attempting to access or uh
Speaker 2: cause a denial of service attack by including a potentially endless file whenever uh malicious entity is injected into the web page So again the solution is that whenever possible use JSON instead of XML and disable external entity and DTD processing. Then again implement positive or allow listing. Then verify that XML or XSL file upload functionality validates incoming XML using XSD validation or similar Then you can use some tools like Shadow Demon. It's a free software and basically it is used to detect and block attacks on the web applications The sixth one is the vulnerable and outdated components.
Speaker 2: So basically we deal with open source softwares and we cannot guarantee that all the packages are whatever we are using they are maintained properly so whenever you are using the uh components third party components make sure that you Don't use outdated components. You use only well-maintained components so that these outdated components, vulnerabilities are taken care of. So seventh one is the identification and authentication failures. So here attackers have access to the hundreds of millions of valid usernames. So instead of Attacking all these accounts, they will directly try to gain access to only few accounts, especially the privileged accounts.
Speaker 2: So the solution is that wherever possible, implement multi-factor authentication, then check it against worst passwords list and ensure that it conforms to the standards, such as NIST 800. 63B guidelines and so on. Then prevention is you can use one-time passwords, multi-factor authentication, captchas, limit number of login attempts, and so on. Then eighth one is software and data integrity failures. Again, it's a new category in 2021. So many applications now include out-of-date functionality. So it's not sure that when they're automatically updating it, the integrity is maintained. So the solution is that use digital signatures
Speaker 2: And ensure that libraries and dependencies are consuming the trusted repositories. Then again, now insecurity serialization is also part of the same category The ninth one is security logging and monitoring failures. So you have to ensure that uh you uh your software or your server is uh having proper logging and monitoring tools because it helps in the uh Investigation of the incident. Then the last category is the server side request forgery. So it also basically it occurs whenever a web application is fetching remote resource without validating the user
Speaker 2: supplied URL. So the prevention is that there are basically two ways. One is from the network layer, second one is from the application layer. So in application layer, sanitize and validate All clients supplied input data, disable HTTP redirections and so on. So beyond 11 beyond OASP top 10. So we have got code quality issues, denial of service, memory management errors. So all these things are already mentioned in OWASP website And there are some security features in Django. Of course, again, all these details you can find in the link mentioned on this slide below. Then there are some additional security guidelines. So again, these are mentioned in Django
Speaker 2: site Then lastly, I would like to mention that there's a tool called a Django Hunter. So you can use that where you can identify the incorrectly configured Django applications. Now, this application I would like to recommend. This is called as PyCode. So you can use PyCode to learn about security issues, especially about OASP top 10 issues. You can install it on your System. Now the live version is not available, but you can go to the repository and install it. It will help you to learn about various vulnerabilities and the possible solutions about Django applications So there are few more resources you can refer these slides for more details later.
Speaker 2: Summary, so since Django is a web framework, it maps to OAS top 10 vulnerabilities. It has built-in modules to build secure Django web applications. Then the security of the application and data is not only the responsibility of the developer, the user is also equally responsible for the security of the data and accounts. Thank you everyone for patience listening. Again, I once again thank the organizers of PyCast for giving me an opportunity. Thank you, everyone.
Speaker 1: Sound things again, Katra.
Poor security can expose sensitive data, damage the application, and harm the business’s reputation. The talk emphasizes that security should be treated as a core application concern rather than an afterthought.
Discussed at 1:08Use Django Checkup by entering the site URL, or scan the domain with Mozilla Observatory. These tools report configuration and security issues and indicate which checks have passed.
Discussed at 2:43Keep Django’s `SECRET_KEY` secret and set `DEBUG = False` in production. Leaving debug enabled can expose framework, application, and system details through error pages.
Discussed at 2:43Deny access by default and allow only explicitly public resources, enforcing authorization in trusted server-side code. Also avoid exposing backups and directory listings, log access-control failures, rate-limit APIs, and use Django’s user-management packages.
Discussed at 8:10Classify data, avoid storing sensitive information unnecessarily, encrypt sensitive data at rest and use TLS in transit, and disable caching for sensitive responses. Store passwords with strong adaptive salted hashes and use maintained cryptographic algorithms; Django encryption packages can help protect sensitive fields.
Discussed at 12:03Django parameterizes queries by default, but extra and raw SQL must be used carefully. Validate input with allow-lists, escape supplied values, avoid calling operating-system commands directly, and use query limits to reduce disclosure if an injection occurs.
Discussed at 16:42Use Django templates, which protect against most XSS attacks through their built-in escaping. The speaker notes that templates may not provide complete protection in every situation.
Discussed at 17:27Use a secure development lifecycle, secure design patterns, and threat modeling. Add unit and integration tests that verify critical flaws are resistant to the identified threats, such as abuse of booking limits.
Discussed at 19:00Harden Django instead of relying on default settings, disable directory listings, customize error messages so they do not reveal sensitive information, and use automated scanners to find configuration problems.
Discussed at 19:45Use multi-factor authentication where possible, reject commonly compromised passwords, and follow relevant password standards. One-time passwords, CAPTCHAs, and limiting login attempts provide additional protection against automated attacks.
Discussed at 22:51Validate and sanitize all user-supplied URLs and apply controls at both the application and network layers. The talk also recommends disabling HTTP redirects where appropriate.
Discussed at 24:25Note: We understand that names change, people change, and bodies change. We respect each individual's journey and privacy. If you have any concerns about a video or need us to remove content, please don't hesitate to contact us. We will handle your request with care and promptly address any issues.
Published May 23, 2026
Published February 26, 2025
Published February 21, 2021