Security Best Practices for Django Applications with Gajendra Deshpande

This video features Gajendra Deshpande at DjangoCon US 2022 in San Diego, California, USA.

Security Best Practices for Django Applications with Gajendra Deshpande
0:36:05
Published November 16, 2022
1,336 views

Security is of utmost importance to most applications in general and web applications in particular. 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. Many times security is ignored or not well done due to a lack of awareness and the cost associated with it. But Security is too costly to be ignored. Although Django has many built-in security features, they are not sufficient to safeguard the application. The talk begins with highlighting the importance of security and identifying security issues in Django applications using the Mozilla Observatory tool, then using the recommendations of the tool to secure them. Next, I will compare and contrast Mozilla's Web Security recommendations and Open Web Application Security Project(OWASP) Top 10 recommendations. Next, I will discuss built-in security features in Django. Finally, I will discuss the configuration settings and issues that may affect the secure deployment of Django applications.

This talk was presented at: https://2022.djangocon.us/talks/security-best-practices-for-django/

LINKS:
Follow Gajendra Deshpande 👇
On Twitter: https://twitter.com/gcdeshpande

Follow DjangCon US 👇
https://twitter.com/djangocon

Follow DEFNA 👇
https://twitter.com/defnado
https://www.defna.org/

Summary

Gajendra Deshpande explains why Django application security matters, including the risks of data leakage, reputational damage and financial loss, and recommends Mozilla Observatory and DJ Checkup for assessing configuration. He walks through the OWASP Top 10 for 2021—covering access control, cryptographic failures, injection, XSS, insecure design, misconfiguration, outdated components, authentication, integrity, logging and SSRF—and gives Django-focused mitigations such as server-side authorization, TLS, parameterized queries, safe templates, threat modeling, dependency management, MFA, rate limiting and monitoring. He also highlights Django’s built-in protections, production settings such as keeping DEBUG off and SECRET_KEY private, secure deployment practices, and resources including Django Hunter, PyGoat and security documentation. His central argument is that secure design, careful configuration and ongoing monitoring are shared responsibilities rather than tasks left solely to developers.

Key takeaways

  • Keep production settings secure: use a private SECRET_KEY, set DEBUG to False, enforce HTTPS and protect security-related headers.
  • Use deny-by-default, server-side access controls, short-lived or invalidated sessions, MFA, strong password handling and login throttling.
  • Prefer Django’s parameterized ORM and auto-escaping, and treat raw SQL, shell commands, safe HTML and custom template code as high-risk areas.
  • Manage the full application supply chain by removing unused dependencies, patching components, verifying trusted sources and protecting CI/CD integrity.
  • Use threat modeling and tests to address insecure design, and configure logging, centralized monitoring and alerts for suspicious activity.
  • Assess deployments with tools such as Mozilla Observatory, DJ Checkup and Django Hunter, while applying Django’s built-in security features correctly.

Summarised automatically from the transcript.

Chapters

  1. 0:00 Django Security Fundamentals An introduction to the importance of web application security, its business impact, and the talk's main topics.
  2. 1:55 Django Security Checks and Settings A look at DJ Checkup and essential production settings such as the secret key and debug mode.
  3. 3:29 Mozilla Observatory A demonstration of Mozilla Observatory, including HTTP, TLS, SSH, and third-party security scans.
  4. 6:47 OWASP Top 10 Overview An overview of the OWASP Top 10 and the major changes between the 2017 and 2021 editions.
  5. 8:18 Broken Access Control Examples of unauthorized account and administrative access, along with server-side prevention techniques.
  6. 10:41 Cryptographic Failures Common failures involving encryption, password storage, TLS, sensitive data, and Django cryptography tools.
  7. 13:48 Injection and Cross-Site Scripting SQL, command, and XSS injection examples with Django practices for parameterization, validation, and safe templating.
  8. 18:31 Insecure Design How architectural and business-logic flaws arise, and how threat modeling and secure development practices address them.
  9. 20:03 Security Misconfiguration and XXE Risks from default or incorrect configuration, exposed error details, XML external entities, and defensive tools.
  10. 23:47 Vulnerable Components Managing third-party Django packages and dependencies through patching, inventory, monitoring, and trusted sources.
  11. 24:41 Authentication Failures Defenses against credential stuffing, brute force, weak passwords, insecure sessions, and missing multi-factor authentication.
  12. 26:13 Software Integrity and Deserialization Protecting software supply chains, CI/CD processes, updates, and serialized data from tampering and hostile objects.
  13. 28:38 Logging, Monitoring, and SSRF Detecting attacks through effective logging and monitoring, followed by network and application defenses against server-side request forgery.
  14. 31:42 Django Security Features Built-in Django protections and additional deployment guidance for uploaded files, throttling, secrets, databases, and caching.
  15. 33:23 Security Tools and Resources A tour of Django Hunter, PyGoat, security references, recommended documentation, and the closing security summary.

Transcript

5,025 words · auto-generated Show

Automatically transcribed, so expect mistakes in names and technical terms.

0:20

Hello everyone, my name is Gajanda Deshpande and today I'll be presenting a talk on security-based practices for Django applications. In today's talk, I'll be discussing briefly on importance of security with respect to web applications, identifying security issues using Mozilla Observatory Tool. Then was top 10 issues and how to address them in Django, built-in security features in Django, and finally secure deployment of Django applications. So, security to web applications is very, very important. First one is leakage of sensitive data, and second one is damage to reputation of the business. Now, whenever your website is hacked or attacked by then by the attacker, the sensitive information of your website gets leaked to the public.

1:09

So this definitely affects the Repetition of the business. So it may result into loss of trust and thereby it also results into huge financial loss. So therefore everyone needs to take care of their web applications. Now, why it is so much important? So you can see here on this slide, there is the statistics. From Mozilla HTTP observatory tool. And you can see here the last parameter that is percentage of sites passing the HTTP observatory. It is just Around 19% of the websites have passed Mozilla's HTTP observatory test. That means there are

1:55

more than 80% of the websites still on the internet which have not taken care of security or not taken care of security seriously Now, let us see some web applications which will help us to identify the vulnerabilities in our web applications. So, first one is the DJ checkup application. So here you can enter the URL of any Django website and you can click on run a checkup on my site. So here I have scanned one website. So for security reasons, I am not Displaying the name of the website, but you can see here that for some of the results it's showing thumbs up and for some of the results

2:41

it is showing thumbs down So thumbs up means those security aspects have been taken care and thumbs down means you need to take care of those security aspects. Now, whenever you create a Django application, there is a file which is created that is settings. py. So in settings. py also you need to Take care of few security settings. First one is there's a secret key parameters. So you need to put a secret uh secret key here and It should be kept secret whenever you are using it in production environment. Then similarly, you need to set debug equal to false whenever you are deploying the application. If you are in a development mode, yes, you can set it to true, but once your development is over

3:29

and once you put your application in the production, you need to set debug parameters to true Now let us see a tool called as Mozilla Observatory. So it's a set of tools to analyze your website and inform You, if you are utilizing many available methods to secure it, it's created by Apple King at Mozilla. It is split into three projects. First one is HTTP observatory, which is a scanner or grader, which basically scans. the URL of the web application and grade set so it shows a score so basically you should get A plus score When you get A plus score, that means that you have passed or your website has passed the security test and it is secure.

4:16

Then there is second tool that is observator CLI, which is the command line interface Then finally there is a web interface that is HTTP observatory website. Now to access the scanner, you have to go to the URL observatory. mozula. org Then there is GitHub repository also. You can visit this GitHub repository and download the entire CDP observatory and set it up locally on your machine. But if you want to use it online, you can use it online. So when you open observatory website, it looks something like this. And there is a demo link which basically analyzes the security of Mozilla observatory website itself. Let's see how it works

5:08

Yeah, so I have already opened the URL and you can see here that there are four options: one is STTP observatory, then TLS observatory, third one is SSH observatory. And fourth one is third party test. And you can see here it is showing the scan summary. So basically it is showing that it has got A plus rating. So test pass at 12 out of 12 Now it also shows the recommendation. Now, right now there are no recommendations for this website and you can go on seeing the score here. You can see the test which is performed and Whether it has passed or failed the test. So whenever it passes the test, you get a positive score. Whenever it fails the test, you get a negative score and a cross mark instead of tick mark. And you can also see here what are the tests which are performed under content security policy

5:59

and other parameters. So this is about STDP observatory. Then similarly, there is something called as TLS observatory. So it basically deals with transport layer security and certificate information. So you can also see here that which are the cipher suits used. And and so on, it also uh shows you the suggestions to improve the security of your application. Then The SSH observatory by default it is not performed. So to initiate a scan you have to click on this button. So right now it shows unable to connect, that's fine.

6:47

Then there's something called as third-party tests. So here they have integrated the services of few third-party service providers, such as SSL Labs, ImmuniWeb. And so on. If one more details you can click on the links provided on third party scans tab. Now let us go to the next one that is OWASP top 10 vulnerabilities visibility. Very very important whenever we are dealing with the web applications security aspect. Now there are two versions of OWASP top 10. One is 2017 edition and second one is 2021 edition.

7:32

Since we are in 2022 edition, we need to deal with 2021 edition because it is updated. Now you can see here that these are the top 10 issues, but these are not the only issues, but these are top 10 most important issues. And one more important factor with respect to us -top-drain vulnerabilities is that the ranking of these vulnerabilities keeps on changing every year. So now you can see here that in 2017 injection was ranked first, but in 2021 it is ranked third. So in 2021 what has happened is that there have been few vulnerabilities, vulnerability categories, which have been clubbed into other categories And ranking of few vulnerabilities has changed.

8:18

Now in 2021, broken access control has got the first rank, whereas it was The fifth rank in 2017. So basically there are three new categories and four categories with naming and scoping changes and some consolidation in top 10 for 2021. Now let us discuss all these issues and the possible remedies one by one. So first one is broken access control. So here the application uses unverified data in SQL call that is accessing the account information. So here What attacker does is simply modifies the account parameter in the browser to send whatever account number they want. So if not properly verified, the attacker can access any user's account

9:07

So here again there is a second scenario here an attacker can simply force browser to target URLs. So admin drives are required to access the admin web page. But if there is If there is an authentication problem, then attacker can easily access the admin page without authentication. So that's a flaw. So prevention is Deny by default except public resources. So 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. So, with exception of public resources, so deny by default, then disable web server directory listing

9:56

and ensure File metadata and backup files are not present within web roots. Then log access control failures alert admits Whenever appropriate, then implement rate limit API and controller access to minimize the harm from automated attack tooling. Then for stateful session identifiers Those should be invalidated on the server after logout. For stateless, tokens should rather be short-lived so that the window of the opportunity for an attacker is minimized. Then use Django User Management plugin Then second one is cryptographic uh

10:41

failures. So rather than directly attacking the crypto, so attackers Steel keys execute man in the middle attacks or steal clear text data of the server while in transit or from the user's client or browser. So here a manual attack is generally required So for example an application encrypts credit card numbers in a database using automatic database encryption. However, this data is automatically decrypted When retrieved, so logging a SQL injection floor to retry the credit card numbers in the clear text. So for this solution, there have been advances in the Uh cryptography field. We now have got homomorphic encryption algorithms.

11:27

So basically, what they do is they enable us to perform computations on the encrypted text. So without need of decrypting the data but still it still the field field in its uh nascent stage so many developments are going on but the problem with homomorphic encryption is that they are all very computation intensive So a site doesn't use or enforce TLS for all pages or supports weak encryption. Then the password database uses unsorted or simple hashes to store everyone's passwords Then to prevent cryptographic failures, classify the data processed, stored, or transmitted by an application Then identify which data is sensitive according to privacy laws, regulatory requirements

12:12

or business needs. Apply controls as per the classification. Then don't store sensitive data unnecessarily then make sure to encrypt all sensitive data at rest don't just use encryption use authenticated encryption Then encrypt all data in transit with secure protocols such as TLS with perfect forward sequencing ciphers. Then disable caching for response that contains sensitive data. Then store passwords using strong adaptive solid hashing functions with a delay factor such as Aragon 2 script bcrypt and so on then verify independently the effectiveness of configuration and settings

12:59

then if you are Deploying your application, then you need to make the following settings in the production. py file. So you need to set these headers such as cost replace HTTP reference to two, host scheme to HTTPS And security HSH includes subdomains to true and so on. Then To prevent cryptographic failures, you need to wrap standard Django feeds with encrypted with encryption provided by the Python Cryptography Library. Then a set of primitives for easily encrypting data in Django can be used. Then a Fernet symmetric encryption for Django model fields library can be used Then the third one and the most common attack is the injection attack.

13:48

So in injection attack there are multiple types Such as SQL injection, XML injection, LDAP injection, XPath injection, ORM query injection, no SQL query injection, OS commands injection, and So injection can result into data loss, corruption, or disclosure to Unauthorized parties, loss of accountability or denial of access, and so on. Now, this is how the SQL injection attack is carried out. Now, first line you can see here there is a valid SQL query Where the second line shows the malicious SQL query. So where the malicious payload such as R1 equal to 1 is used. So in this case, what happens is whatever may be the left hand side of your SQL query, it always results into true and it reveals the information which is stored in the database.

14:37

Then There are two functions in Django, they are extra and raw and sql which enable the developer to write custom queries in Django. So which is also cause of injection attacks in Django. Now, how SQL injection is performed? So there will be a user form so which asks username and password. Now you can see here in the password field I have entered a malicious payload. So it it may be a very simple example, but There are there's you'll get in the internet huge list of uh payloads. So one of them will work and eventually it will result into the display of uh data

15:23

Now similarly there is a command injection. So in command injection you can see here that I am performing name server lookup. So specify the website name google. com And to that I have combined the command for the f config. So depending on the operating system, the command may change. So you can see here that it is Revealing the information about google. com that is the output of the command and then it is also displaying the output of if config command which basically displays the IP address and the network information about the server Then to prevent SQL injection and command injection attacks, you need to perform query parameterization, which is by default

16:10

in Django. Then use extra and draw SQL with caution whenever there is a need. Then only use it, then use positive or whitelist server-side input validation. Then escape all user supplied input Then do not call OS commands directly. Then use limit and other SQL controls within queries to prevent mass disclosure of records in case of skill injection. Then next one is cross-site scripting. In 2017, this was a separate category, but in 2021 it is part of Injection now. Now you can see here that there is a search field, and in that search field, I have entered a simple HTML command. So now you can see here that

16:55

when I click On go, it is applying the green color to the text. So that means that this particular script is vulnerable to XSS attacks. So now you can go ahead and type the Manages JavaScript code and executed. So this is another example. So here the application is understood data. In the construction of following HTML snippet without validation or escaping. So here attacker modifies CC parameter in the browser to the Following line. So this attack causes the victim session ID to be sent to the attacker's website, allowing the attacker to hijack

17:41

the user's current session. Now to prevent XSS attacks, you can use Django templates which automatically protect you against the majority of XSS attacks. But there are some exceptions. For example, no HTML code is foolproof. A valid HTM code itself may become or may make the code vulnerable So it is also very important to be particularly careful when you are using ESF with custom template tags and safe template tag and mark safe. So, you should also be very careful when storing HTML in the database, especially when that SML is retrieved and displayed Next is the insecure design. This is again a new category for 2021 which focuses on the risks related to the design and architectural flaws.

18:31

So here consider a website that allows group booking discounts and has a maximum of 15 attendees before requiring a deposit. So attackers could threat model this flow and test if they could book 606 and all bookings at once in a few requests, causing huge financial loss. This is a design flaw. So insecure design is a broad category representing different weaknesses Expressed as missing or ineffective control design. So one of the factors that contribute to insecure design is the lack of business risk profiling inherent in the Software or system being developed, and thus the failure to determine what level of security design is required. So that is a very very important statement here: that is, a secure design can have implementation defects

19:17

And an insecure design cannot be fixed by a perfect implementation. Now prevention. So consider using OWASP software assurance maturity model, SAM to help structure your secure software development efforts. Then establish and use a secure development life cycle with application security professionals to help you all attend design security and privacy-related controls Establish and use a library of securities and patterns, then use threat modeling for critical authentication, access control, business logic and key flows. Then Limit resource consumption by user or service, then write appropriate unit 10 integration tests to validate that all critical flows are resistant to the threat model.

20:03

Compile use cases and misuse cases for each tier of your publication. Very very important is understand the business logic, understand What application you are building and what is the correct flow and then design your tests, then design your security strategy. Fifth one is security misconfiguration. So here attackers will often attempt to exploit unpassed flaws. Or access default accounts, unused pages, unproduct files, directories to gain unauthorized access or knowledge of the System and security maze configuration can happen at any level of an application stack, including net of services, platform web server, application server, database frameworks

20:48

And so on. So here the very very important point is that your application may be secure. But if it is wrongly configured, if it is not correctly configured, if its security features are not correctly configured, then your application becomes vulnerable. two attacks so prevention is go for Django holding that is don't go for default settings customize all the settings including the directory listing, including all the parameters, then disable directory listing, then use automated scanners. then customize error error messages to hide sensitive information because error messages usually display the information about the system for example auditing system Open systems version, servers, operating

21:33

server software and its version, and so on. Once the attacker knows the version, the attacker automatically comes to know about the vulnerabilities present in that version Then sending security data to clients, for example, sending the security headers. Then use the automated tools to verify the effectiveness of configurations and settings in all environments. Then review cloud storage permissions. Now XML External Entities is also part of the fifth category that is security misconfigurations So here attackers can exploit vulnerable XML processors if they can upload XML file or include hostile content in an XML document. So exploiting vulnerable code dependencies or integrations Now, this is an example.

22:20

Now we know that XML allows us to create our own tags, our own entities, our own attributes. So here the attacker is trying to create an entity called XXC, which is directly linked to file So whenever a user uses this particular entity, automatically he gets access to the slash ADC slash password file Now to prevent XXC attacks whenever possible use JSON instead of XML. Then disable XML, XML entity, and DTD processing in all XML parsers. Then again implement whitelisting serves validation. Then verify that XML or XSL file, uploaded functionality, validates incoming XML using XSD validation or similar

23:07

Then you can also go for Shadow Demon, which is a collection of tools to detect the vulnerabilities. It's a web application firewall that intercepts requests and filters out malicious parameters. So it's a free software and it supports Python, Django and Flask frameworks and it can also be used with PHP and per programming languages. Then sixth category is vulnerable and outdated components. So component 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 up to date. So components typically run with the same privileges as the application itself. So flaws in any component can result in serious impact so such plots can be accidental

23:53

or intentional. Now for example when you consider Django or Applications like WordPress, they heavily dependent on the components developed by the third party. So you need to make sure that the third party plugin It's secure and you need to download it from the trusted source. So prevention is that there should be a patch management process in place to remove unused dependencies, unnecessary features, components, files And documentation. There has to be continuously inventory the versions of both clients and server-side components and the dependencies using tools like versions, dependency check And so on, then continuously monitor the sources such as C B N V D and so on. Then only obtain components from the official sources over secure links.

24:41

Use tools like Shodan and Django Hunter Then seventh one is identification and authentication failures. So here attackers have access to the hundreds of millions of valid usernames and password combinations for credential stuffing Default administrative account list, automated brute force, and dictionary attack tools. So attackers have to gain access to only a few accounts. For example, just the access to admin account. Once they get access to the admin account, they can do anything with Other remaining accounts. Most authentication attacks occur due to the use of continued use of passwords as the sole factor and application session timeouts aren't set properly. So prevention

25:27

is wherever possible implement multi-factor authentication that do not ship or deploy. with default passwords then implement big password checks that is testing new and change passwords against the list of top 1000 worst passwords Then limit or increasingly delay the failed login attempts. Then use a server-side secure built-in session manager that generates a new random session ID with High entropy after login. So session IDs should not be in the URL, be securely stored and invalidated after logout, idle and absolute timeouts. So for prevention in Django, you can use the following plugins or packages. It is one-time password for Django, then two-factor authentication for Django, then Django user

26:13

seasons management, then you can go for CAPTCHA. Then you can limit the number of login attempts. Then you can block multiple requests from the same IP address. Then, eighth category is software and data integrity failures. So it's again a new category for 2021, which focuses on making assumptions related to software updates, critical data, and CICD pipelines without verifying the So software and detailed integrity failures relate to code and infrastructure that does not protect against integrity violations. So an example of this is where an application relies upon plugins, libraries or modules from untrusted sources, repositories, and content delivery networks. Now many applications now include out of

27:00

date functionality wherever updates are downloaded without sufficient integrity verification and apply to previously trusted application. For example, when you install WordPress nowadays, so you can automatically update the themes, you can automatically update the plugins. So there you get a feature enable automatic updates. Now, prevention is use DC signatures or similar mechanisms to verify the software or data that ensures that it has not been altered. Then ensure libraries and dependencies such as npm or maven that are consuming trusted repositories. Then ensure that software supply chain security tool such as OAS dependency check or OSC Cyclone DX is used to verify that the components do not contain non

27:48

-vulnerabilities. Ensure that your CICD pipeline has proper segregation, configuration, and access control to ensure the integrity of the code flowing through the build and deploy processes. Now insecure deseralization is also part of this category. So here applications and APIs will be vulnerable if they deservize hostile or tampered objects supplied by an attacker. So this can result into two primary types of attacks. One is object and data structure related attacks Where the attacker modifies the application logic and achieves arbitrary remote code execution. Then second one is typical data dampling attacks, which is access control related attacks where existing data structures are used, but the content is

28:36

Changed. Now prevention against insecurity serialization is that the only safe market cell pattern is not to accept serialized objects from untrusted sources or to use serialization medium that is that only permit into data types. Then log deserialization exceptions and failures The ninth category is security logging and monitoring failures. So exploitation of insufficient logging and monitoring is better off of nearly every major incident. So attackers rely on the lack of monitoring and timely response to achieve their goals without being detected. So one strategy for determining if you have sufficient monitoring is to examine the logs following penetration Testing. The testers

29:21

action should be recorded sufficiently to understand what damages they may have inflicted. Now the prevention is Ensure all login access control failures and server-side input validation failures can be logged with sufficient user context to identify suspicious or malicious accounts. And held for sufficient time to allow delayed forensic analysis. So ensure that logs are generated in a format that can be easily consumed by centralized log management solutions Then establish effective monitoring and alerting mechanisms such that suspicious activities are detected and responded to in a timely fashion. Then dev check-up teams Should establish effective monitoring and alerting such that

30:07

activities are detected and responded to quickly. Then the last category is server-side request forgery So this is also a new category in 2021. So SSRF flaws occur whenever a web application is fetching a remote resource without validating the user supplied URL. So it allows an attacker to coerce the application to send a crafted request to an unexpected destination, even when protected by a firewall, VPN, or another type of network access control list. As the modern web application provides end users with convenient features, fetching a URL becomes a common scenario. So as a result, the incidence of SSRF is also increasing Also, the severity of SSRF is becoming higher due to cloud services and complexity

30:55

of architectures. Now there are There is a prevention from two layers. First one is from network layer and second one is from application layer. From network layer, segment remote resource access functionality in separate networks to reduce the impact of SSRM. Then second one is enforced deny by default firewall policies. Then from the application layer, sanitize and validate all clients applied input data, enforce URL schema, port, destination with a positive alloy list Do not send raw responses to clients, disable HTTP redirections. Then be aware of URL consistency to avoid attacks such as DNS, rebinding and time of check, time of use, race conditions. Now there is a new category that is A11.

31:42

So we cannot fit all the vulnerabilities in top 10. So It's beyond was top then you have got three issues which you need to address. One is core quality issues, then second one is denial of service, and third one is memory management errors Now, Django also provides many security features by default. You just need to enable them and use them. So Django by default provides protection against cross-site scripting. Cross-site request posterior, SQL injection, click jacking. You can enable SSL and HTTPS Then you can validate the host header, referrer policies, cross-origin opener policy, session security and user

32:28

uploaded content So you can find more details on the below given link. Now additional security guidelines for making your application secure. So make sure that your Python code is Outside of the web service route. So this will ensure that your Python code is not accidentally served as a plain text. Then take care with any user uploaded files Then Django does not throttle request to authenticate users to protect against brute force attacks against the authentication system. You may consider deploying Django plugin or web server module to throttle these requests. So keep your secret key and secret key fallbacks. If you use secret, so this we have already seen in our initial slides, then it is a good idea to limit the accessibility of your caching system and database using a firewall

33:23

There's a tool called as Django Hunter. It's a tool designed to help identify incorrectly configured Django applications that are exposing sensitive information. So this is how you have to use you need to use Python 3 command, then the script name that is Django Hunter. py, then specify the show then key, then specify Google Docs depending on your requirement. Then there is a very interesting application known as PyGode. It's a OASP project. So it's an intensely vulnerable platform for developers and testers. for learning how to test applications and how to code securely. So PyCode is written in Python and it uses Django Web Framework as a Platform. So you can see the source code for security vulnerability and modify it to make it secure.

34:09

So it can be installed locally as well as you can use it online. So source code can be accessed using the link below and You can also see the demonstration. The only problem with PyCode is that it uses uh Or it is designed to demonstrate the OWASP top 10 issues of 2017 and not 2021. Okay. Then Django Security Resources. So you can visit few of these links. Which will definitely help you to make your

34:55

Django application secure. So there is a very nice GitHub repository that is known as Awesome Django Security. Then you can refer Django's official security documentation, then OAS Top 10 for 2021. It's a very nice resource. Then you can also check for Mozilla Web Security Guidelines Then there are two nice articles which I would like to recommend. One is from RealPython and second one was dev. 2, which discusses secure deployment of Django applications. So finally, this summary. So since Django is a web framework, it maps to over top 10 vulnerabilities. So it has built-in models to build secure Django web applications. And you can also make use of Mozilla web observatory tool.

35:40

Which ensures that if you get a plus uh rating your application is almost secure. Then security of the application and data is not only the responsibility of the developer The user is also equally responsible for the security of data and the accounts.

Questions this talk answers

Why is security important for Django and other web applications?

A breach can expose sensitive data, damage a business’s reputation, reduce customer trust, and cause substantial financial loss. The speaker notes that most websites still fail to pass the Mozilla HTTP Observatory test.

Discussed at 0:20

What should I configure in Django settings.py before deploying to production?

Keep the production secret key private and set DEBUG to False before deployment; DEBUG may be enabled only during development.

Discussed at 2:41

How can I check the security of a Django website with Mozilla Observatory?

Submit the site URL to Mozilla Observatory, which scans and grades its security configuration. An A+ rating means the site passed all available checks, while the results also show failed tests and recommendations.

Discussed at 3:29

How do I prevent broken access control in Django?

Deny access by default except for public resources, and enforce authorization in trusted server-side code rather than relying on client-controlled data. Also invalidate sessions after logout, use short-lived stateless tokens, rate-limit access, and use Django’s user-management features.

Discussed at 9:07

How can I prevent cryptographic failures in a Django application?

Classify sensitive data, avoid storing it unnecessarily, encrypt sensitive data at rest and all traffic with secure TLS, disable caching for sensitive responses, and use strong adaptive password hashing such as Argon2 or bcrypt. Production settings should enforce HTTPS-related security headers, and Django data can be encrypted with libraries such as Python Cryptography and Fernet.

Discussed at 12:07

How do I prevent SQL injection and command injection in Django?

Use parameterized queries, which Django provides by default, and treat raw SQL or extra queries with caution. Validate and escape user input, avoid calling operating-system commands directly, and use query limits to reduce the impact of accidental or malicious disclosure.

Discussed at 16:10

How can I protect a Django application against cross-site scripting (XSS)?

Django templates automatically defend against most XSS, but developers must be careful with custom template tags, safe or `mark_safe` output, and HTML stored in the database. User-controlled HTML should be validated or escaped before it is rendered.

Discussed at 17:41

How do I prevent security misconfiguration in Django?

Do not rely on default settings: customize the configuration, disable directory listings, use automated scanners, and avoid exposing sensitive details in error messages. Review security settings in every environment and check cloud-storage permissions.

Discussed at 20:48

How can I protect Django applications from vulnerable or outdated dependencies?

Remove unused dependencies and features, maintain an inventory of client- and server-side component versions, monitor vulnerability sources, and obtain packages only from trusted official sources over secure links. Third-party Django plugins should also be downloaded from reputable sources and kept patched.

Discussed at 23:53

How can I prevent authentication and session attacks in Django?

Use multi-factor authentication, never deploy default passwords, check new passwords against common-password lists, and throttle or delay failed logins. Generate high-entropy server-side session IDs, keep them out of URLs, and invalidate them after logout and on session timeouts; Django packages can provide MFA, CAPTCHA, and login-attempt limiting.

Discussed at 25:27

What security protections does Django provide by default?

Django includes protections against XSS, CSRF, SQL injection, and clickjacking, and supports HTTPS, host-header validation, referrer policies, cross-origin opener policy, session security, and safer handling of uploaded content. The speaker emphasizes that these features still need to be enabled and used correctly.

Discussed at 31:42

What additional steps should I take when securely deploying a Django application?

Keep Python code outside the web-server root, handle uploaded files carefully, add throttling for authentication requests, protect secret keys, and restrict database and cache access with a firewall. Tools such as Django Hunter can help find incorrectly configured Django deployments exposing sensitive information.

Discussed at 32:28

Note: 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.

More videos by Gajendra Deshpande

More videos from DjangoCon US