Securing Django Applications
Outline
- Security aspects of Django web applications (03 minutes)
- Penetration testing of Django web applications (05 Minutes)
- Overview of Open Web Application Security Project (OWASP) Top 10 risks (10 Minutes)
- Djangohunter tool demonstration (03 Minutes)
- Strategies and configuration settings to make Django Application secure (07 Minutes)
- Conclusion and Questions (02 Minutes)
This session took place in track Django and was classified suitable for some domain / some python by the speaker.
Transcript (auto)
Auto-generated from the recording utilizing Open-Source AI. Speaker labels (Speaker 1, Speaker 2) reflect diarization, not identity. Timestamps refer to the recording.
Speaker 1 [00:04]
Thank you. It's very nice to be here and speak about Django. Unfortunately, I'm not able to attend the in-person conference. That's fine, but even virtual experience will be great, I feel. Today I'll be talking about securing Django applications. So let's see in in brief uh what am i am i going to speak so i'm going to cover security aspects of django web applications then penetration testing of django web applications overview of oasp top 10 risks so oasp stands for open web application security project so that's the the non-profit organization which looks after various vulnerabilities with respect to web applications. Then we'll discuss in brief the applications Django Hunter and Django Go and strategies and configuration settings to make Django applications secure. So we will not be covering some of the topics in sequence. will be covering wasp topic wasp risk and its associated mitigation strategies now there's a very nice website that is known as django that's not djcheckup.com slash pony so you can just type this url on your machines and you can specify the url of any Django website. So when you specify URL and when you click on run a checkup on my site, it will give you the results and you can see here that you can see thumbs ups and thumbs up thumbs down buttons. So thumbs up means that vulnerability has been taken care and thumbs down means you need to take care of that particular vulnerability. Now say for For example, here HTTP redirecting to HTTPS, HTTPS is enabled, HHTPS is enabled, debug is not enabled. So these are the good things and these have been already taken care on a particular site. So I have hidden the website URL which I have checked for security reasons. The next is you can see here that it's a Django framework whenever you create a new project you are going to get the files like this one important file is the settings.py and when you go to settings.py you can see these settings one is the security key second one is the debug equal to true now secret key you need to keep it secret whenever you are using in production you can use a different secret key for development purpose then second one is debug equal to true you can set it to true only when you are developing the application but once you deploy the application you need to set it to false the reason is that if you set it to true it may display error messages and error messages reveal system information and hackers can use this system information to carry out further attacks so that's the reason you need to set debug equal to false whenever you deploy the application now let us see was top 10 vulnerabilities so as i have mentioned wasp is a non-profit organization stands for open web application security project so these are the top 10 risks first one is the injection then broken authentication sensitive data exposure xml external entities broken access control security misconfigurations cross-site scripting insecurity serialization using components with non-vulnerabilities insufficient logging and monitoring you can classify or you can group these vulnerabilities into several categories so some say in one category you may have to make the settings in the code that is you have to write code in such a way that your application becomes secure and some things are related to the configurations and some are related to the logging and monitoring so always you are not writing a code to make your application secure now let us first discuss the injection vulnerability so in injection vulnerability there are many types but the most popular ones is SQL injection it's a type of attack where malicious user is able to execute arbitrary SQL code on a database so this can result in records being deleted or data leakage now injection vulnerabilities can be found in in SQL or LDAP. LDAP is basically used for authentication. Then XPath is used to write queries to access the elements in the XML file. Then we have got NoSQL queries, OS commands and so on. Injection can result in data loss, corruption of the data, disclosure of information to unauthorized parties denial of access and sometimes it may also lead to complete host takeover now there's an example mentioned in this slide so the first example you can see that it it's mentioned here string query is equal to select start from accounts where customer id equal to request dot get parameters of id now this is a valid query which is written but hackers can modify the sql query here so they will supply malicious input they will append the malicious input at the end of valid url so you can say id equal to after that the malicious query is used malicious attack vector is used it is mentioned here or one equal to one so how it works is whatever may be the left hand side query it's always going to return true and it will reveal the information stored in the SQL database of course whatever example you are seeing on this side is the most simplest example and in real world hackers use more complex attack vectors then there are two more aspects one is extra and raw sql so they enable the developer to write custom queries in django so because of this attackers can frame a attack vector and perform the sql injection attack now to protect against sql injection query parameterization can be used and it is available by default in Django. Then whenever you're using extra and raw SQL, you need to use it with caution in Django. Then use positive or whitelist server side input validation. So whenever I'm saying whitelist, that means we are using only known input validation cases and unknown things we are avoiding or we are blocking. So again, it may not be a complete defense then second one is broken authentication so we know that attackers have access to hundreds of millions of valid usernames and password combinations for credential stuffing then default administrative account lists automated brute force and dictionary attack tools and and so on. So with this attackers have to gain access to only few accounts that is they need not have to log into all the accounts instead they can just identify the admin account and super user account to compromise the system. Then credential stuffing is credential stuffing the use of lists known passwords. It's a common attack. Most authentication attacks occur due to the continued use of passwords as a sole factor. And application session timeouts aren't set properly. To protect against broken authentication, wherever possible, implement multi-factor authentication to prevent automated or credential stuffing or brute force or even stolen credential reuse attacks. So most of the email accounts or most of the applications now provide multi-factor authentication feature if you don't want to use multi-factor authentication then and if you don't want use even passwords you can use otps that is one-time passwords then do not ship or deploy with any default credentials particularly for admin users so this is one of the important feature so if the admin is from non-technical background then they may use only the default credentials so in that case we need to create the awareness and we need to ensure that they don't use the default credentials then implement weak password checks such as testing new or changed passwords against the list of top 10,000 worst passwords then align the password length complexity and rotation policies with NIST standard then ensure registration credential recovery and API pathways are hardened against the account enumeration attacks by using the same messages for all outcomes then limit or increasingly delay the failed login attempts This is very very important because attackers may use bots right so you can say that after three attempts the admin page will be blocked for half an hour or one hour. Then you have to log all the failures and alert administrators whenever credential stuffing or brute force or other attacks are detected now to implement in Django you can use one-time passwords package in Django so that is Django OTP then for two-factor authentication there is a Django two-factor or package then for Django user sessions management you can use Django user sessions so session management is also very very important so you can set that after two minutes of inactivity or after 30 seconds of inactivity the application will logout automatically otherwise if you are using some public places and if you have left your system open for some reason then maybe some person or hacker can just get into your system and send the mails or operate the software on your behalf and it may create problem for you the next is the sensitive data exposure so rather than directly attacking the crypto attackers steal keys execute the man-in-the-middle attacks or still clear text data of the server while in transit or from users client so for example the browser so here manual attack is generally required so an application encrypts credit card numbers in a database using automatic database encryption however this data is automatically decrypted when retrieved allowing SQL injection flow to retrieve credit card numbers in clear text now there is a solution for this so what happens is whenever we send the information it will be encrypted and when we want to process it on the destination we will decrypt it so the moment we decrypt it if the system is compromised if the destination system is compromised then the data can be stolen so now there are advancements in cryptography such as homomorphic encryption or confidential computing that allows us to perform computations on the encrypted data that is we need not have to decrypt the data we can directly perform computations on the encrypted data so most of the algorithms such as rsa or l-gamal or even elliptic curve algorithms they have these homomorphic properties so they may not support arbitrary computations but they support partial computations so there are complex algorithms which also supports arbitrary computations so depending on your need you can use the appropriate homomorphic property of a cryptographic algorithm then if a site doesn't use or enforce tls that is transport layer security for all pages or supports a weak encryption then also the sensitive data will be exposed now this okay so now the solution is classified data process stored or transmitted by an application identify which data is sensitive and which is not sensitive according to privacy laws and regulatory requirements and apply controls as per the classification don't store sensitive data unnecessarily discard it as soon as possible or use pci dss compliant tokenization this is especially useful when you are implementing credit card or wallet applications functions. So make sure to encrypt all sensitive data at rest. Then ensure up to date and strong standard algorithms, protocols and keys are in place. Disable caching for response that contain sensitive data and store passwords using strong adaptive and sorted hashing functions. Now this is what you can do in Django. So there's a file called production.py and you have to set these parameters to true. So if you see here, most of the parameters are related to HSTS or HTTPS. Now to protect against sensitive data exposure, you can use the Django packages such as Django encrypted model fields, Django cryptography, and Django fernet fields. So these are basically used for encryption and decryption. The next worst risk is XML XML entities. So 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, scan internal systems, perform a denial of service attack and so on. Now these are the few examples. So in the first example, you can see here that attacker attempts to extract data from the server. So in HTML, we know that it has entities. So these character entities are used to print a special character such as copyright symbol or trademark symbol and so on and the beauty of XML is that you can create your own elements. You can create your own entities. So here the custom entity XSE is created and this XSE is related is linked to a system file called slash it is a slash password. So whenever a person uses this entity that is ampersand XXE semicolon that's how it is used it is getting access to the file slash it is slash password I mean second case an attacker probes the server's private network by changing the entity line to the private network address so you can see here that it is this entity is linked to HTTPS 182.168.1.1 Then an attacker can also perform denial of service attack by linking the entity to potentially endless file. So here slash dev slash random is endless file and it can be used to perform denial of service attack. Just a single line and to protect against XML entities attacks. So whenever possible use less complex data formats such as JSON and avoid serialization of sensitive data disable XML external entity and DTD processing is really stands for document type definitions processing in all XML parsers in the application then I can implement a positive server-side input validation filtering or sanitization to prevent hostile data within XML documents headers or notes and verify that XML or XSL file upload functionality validates incoming XML using XSD validation or similar. So most of the editors they come up with the validators, right? So you have you can validate XML you can validate DTD you can even validate XSD. Then you can use a software called a shadow demon which is a collection of tools to detect record and block attacks on the web applications so it's a web application firewall that intercepts the requests and filters out malicious parameters so it's free software it supports python and web frameworks such as django and flask apart from that it also supports other languages other other scripting languages PHP and Perl. The next is broken access control. The application uses unverified data in a SQL call that is accessing account information. So this is how the account information is accessed. The sets string function is used and some parameters are passed like request dot get parameter and the account and to print the results result set is used and the query is executed. So what attacker does is it attacker simply modifies the account parameters. So what is happening in this case is if the account is not properly verified attacker can get access to the user's account. So an attacker simply force browsers to target URLs admin rights are required to access the admin page but if it is not properly authenticated or if an authenticated user can access the either page it's a flaw then to protect against broken access control the access control is only effective if it is enforced in trusted server-side code and serverless api where the attacker cannot modify the access control check or metadata now disable web server directory listing and ensure file metadata and backup files are not present in the web roots then log access control failures alert admins whenever appropriate and use django user management so django user management package will help you to implement access control features the next is the security misconfiguration this is is very very important. You may write extraordinary code and your application may be totally secure but if it is not properly configured or if it is misconfigured then no application is secure. For example if the digital listing is not disabled on the server, it gives some information to the attacker. So attacker knows what is the data structure, which files are stored in which folder. so that's a flaw so in this case you can use Django hardening that is don't use default settings then disable directory listing don't display the files and folders which are hosted on the web server's root directory then use automated scanners so you'll get a lot of automated scanners CMS scanners so you can use them to identify the misconfigurations then customize error messages to hide sensitive information this is very very important because if you display the system error message it may reveal the information about the operating system and operating system version browser version or the server version so these versions are enough to get the vulnerability present in those particular versions of opening systems so just a simple google search is enough for them the next is cross-site scripting So here the application uses untrusted data in the construction of following HTML snippet without validating or escaping. So now here you can see here that a simple HTML code is written and the JavaScript code is mentioned here that is request.get parameter and also in this case what attacker does is attacker modifies the cc parameter and may specify something else so in this case the attacker the attack causes the victim session id to be sent to the attackers website allowing the attacker to hijack the users current session now the solution is use django templates and django templates protect you against the majority of cross-site scripting attacks but there are exceptions say for example this is a valid syntax style class is equal to where it's a valid syntax in html but the same can be used same can be bypassed by django templates so try avoiding such syntaxes in your code the next is insecure deserialization so applications and api will be vulnerable if they deserialize 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 application logic or achieves arbitrary remote code execution if there are classes available to application that can change the behavior during or after a deserialization then typical data tampering attacks such as access control related attacks are possible then to protect against insecure deserialization you can use django j signature package so which ensures that you are using integrity checks and integrity checks or decision ensure that there is no data tampering or data tampering is not happened or it can easily detect the data tampering if you implement digital signatures then using components with the known vulnerabilities so django is a component heavy software or even any open source software such as wordpress they are component heavy softwares so by default or by design django is secure but packages may not be secure because they are developed by the community and they may not be aware of the secure practices secure coding practices when they are developing a package so that may create a problem so the solution is that remove unused packages unused dependencies unnecessary features components then only obtain components from official sources over secure links then use tools like shodan and jango hunter to find the vulnerabilities the next is insufficient logging and monitoring so here exploitation of insufficient logging and monitoring is the bedrock of nearly every major incident so attackers rely on the lack of monitoring and timely response to achieve their goals without being detected so the solution is to install appropriate logging and monitoring softwares so whenever the violation happens the admin can be alerted regarding the incident now there's a tool called a django hunter so it's a tool designed to help identify incorrectly configured django applications that are exposing sensitive information so you can use this command python3 then django hunter.py you have to specify the show then then you can use google docs like this allowed host key error operational errors page not found and so on it depends exactly what you want to check then this is a very nice application you can use django goat it's an intentionally vulnerable django application which can and help Django developers to learn security testing. If you visit OWASP website, you will find many Goat applications, right? So you have even web Goat of web applications. Then Django also has got very nice resources. You can visit these two links to find out the security resources and security document related to Django. So, in summary, since Django is a web framework, it maps to OSP top 10 vulnerabilities, it has built-in modules to build software, built-in modules to build secure Django web applications. Then security of the application and the data is not only the responsibility of the developers, the user is also equally responsible for the security of the data and accounts. Thank you everyone for listening to my talk. If there are any questions, I can take them. Are there any questions in the room? A lot of you use Django, and security is very important. In case there is not, then I would have a question. You showed us a slide of the top ten vulnerabilities. Was it in this exact order, or was it just random? Is it like a guide that could do like step by step and just like hit like the few ones? Actually, that number changes every year. But the SQL injection is most widely used. That number changes every year. So to know the exact order, you can visit OWASP's website and you'll find more details there. Okay, nice. So thanks again, the speaker. Thank you.