Django Security guide

Akash Jatav
mewt
9 min readOct 16, 2021

--

  1. Cross site request forgery (CSRF)- In a web application, basically the webforms take input from the user and send them to server side components to process them. The server-side components generally expose the service as a POST, PUT, DELETE methods for accepting the data over HTTP. Django has built-in security against most forms of CSRF threats, as long as you have allowed and used it if necessary. As stated in the documentation, be very careful when marking views with the CSRF_exempt decorator, unless it is absolutely necessary. If someone has access (through an man-in-the-middle attack or XSS) to your CSRF token cookie, then this is a vulnerability. The CSRF protection cannot protect against man-in-the-middle attacks, so use HTTPS with HTTP Strict Transport Security.

2.SQL injection protection: SQL injection is a type of attack where a malicious user is able to execute arbitrary SQL code on a database. This can result in records being deleted or data leakage.

How to prevent SQL Injection- Django’s query sets are protected from SQL injection since their queries are constructed using query parameterization. A query’s SQL code is defined separately from the query’s parameters. Since parameters may be user-provided and therefore unsafe, they are escaped by the underlying database driver.

3. JWT Grant Type: This is an open security standard to securely communicate data between multiple parties as JSON objects. It defines a compact and self-contained way to securely transmit information between parties, verified and trusted because it is digitally signed. In this grant type, it is possible to send user claims to the backend to validate. Before issuing an access token, the authorization server can use these claims to property identify the end-user.

4. Clickjacking attack: This type of attack occurs when a malicious site tricks a user into clicking on a concealed element of another site which they have loaded in a hidden frame or iframe.

Preventing Clickjacking — • Modern browsers honor the X-frame-Options HTTP header that indicates whether or not a resource is allowed to load within a frame or iframe. If the response contains the header with a value of SAMEORIGIN then the browser will only load the resource in a frame if the request originated from the same site. If the header is set to DENY then the browser will block the resource from loading in a frame no matter which site made the request.

4.Cross-site Scripting (XSS) :A Cross-site Scripting (XSS) allows an attacker to inject a script into the content of a website or app. When a user visits the infected page, the script will execute in the victim’s browser. This allows attackers to steal private information like cookies, account information, etc.

X-XSS-Protection: 1.mode=block enables XSS filtering. Rather than sanitizing the page, the browser will prevent rendering of the page if an attack is detected. 2.To enable it in Django, make sure django.middleware.security.SecurityMiddleware is present in middleware’s list and add following lines in your settings.py:

5.Authentication: Authentication is the process our API relies on to verify the identity of a user associated with an incoming request. Authentication is running as soon as a request is received, before permissions and throttling, and before any other code is executed. The authentication scheme we decide to implement will depend upon the needs of the individual project itself, but we should familiarise ourself with implementing authentication on both global and per-view or per-view set levels. if the majority of our API is going to use these authentication classes set them globally and override as needed. While we are at it, make it a mixin to keep It DRY:

It’s better to have an endpoint that it too restrictive than to leave it open to the wrong users. Restrict, a then revise as needed. Extending DRF’s base authentication. Even if we don’t have a need for it now, create this mixin anyway to make our authentication more accessible and maintainable in the future.

Again, create custom permissions classes to extend built-in classes. Implement them on global, view or viewset and object levels- in that order.

6.Permissions: Permissions are used alongside authentication to determine whether access to a resource should be accepted or denied. Permissions checks run after authentication, so any information gathered from authentication checks is available for their use. This is where we may find it useful to fine-tune privileges, controlling access to parts of our API based on criteria of our choice, Permissions, like authentication, may be applied at different levels within the REST framework.

7.Host header validation :Django user the HOST header provided by the client to construct URLs in certain cases. While these values are sanitized to prevent Cross Site Scripting attackers, a fake Host value can be used for Cross -Site-Request Forgery. Cache poisoning attacks, and poisoning links in emails. Because even seemingly -secure web server configurations are susceptible to fake HOST headers, Django validations HOST headers against the ALLOWED_HOST setting in the django.http.HttpRequest.get_host() method. This validation only applies via get_host() .if your code accesses the host header directly from request.META you are bypassing this security protection.

8. Session security: Similar to the CSRF -limitations requiring a site to be deployed such that untrusted users don’t have access to any subdomains, django.contrib.sessions also has limitations.

9. Django Admin Security: One of the most important things is to make Django administrations secure. Before you deploy your applications, you must change admin/path to something only you know. Otherwise, someone can easily type/admin in URL and access to administrator login page.

10.HTTP Strict Transport Security: When this policy is set, browsers will refuse to connect to your site for the given time period if you’re not properly serving HTTPS resources, or if your certificate expires.

11. Use ‘Django-admin-honeypot: Once you have moved your admin site to a new URL (or even decided to host it in its own domain), install the library django-admin-honeypot on your old/admin/URL to capture attempts to hack your site. Django-admin-honeypot generates a fake admin login screen and will email your site administrations whenever someone tries to log in to your old/admin/URL. The email generated by Django-admin-honeypot will contain the attacker’s IP address, so for added security if you notice repeated login attempts from the same IP address, you can block that address from using your site.

12. Be careful with your cookies: Some cookies are more secure than others — the default cookie behaviour is to connect over http. However, since we already established that you need to use https, you want to make sure your cookies are only being sent over https as well. To prevent leaking cookies, be sure to set your SESSION_COOKIE_SECURE and CSRF_COOKIE_SECURE settings to True. This instructs the browser to only send these cookies over HTTPS connections. There are some interesting side effects to setting these parameters to true, but they should be mitigated by redirecting http traffic to https.

13. Carefully handle user uploads: If your web application allows users to upload files, you are opening yourself to an attack vector and the upload logic should there be handled carefully. First, it is important to validate all uploaded files to be sure they are what you expect (for instance, an image file and not a PHP script!). You don’t want it to be possible for a user to run code. There are a number of things to help validate uploaded files or handle them more carefully. They include the following: 1.Create a whitelist of acceptable file types 2.Limit file size allowed for uploads to prevent denial of service problems 3. Disable handlers that would execute static files as code (for example, disable Apache’s mod_php) 4.Make cross site scripting protections work for you. If you serve user content from a distinct top-level domain, the protections against cross site scripting will kick in to protect you. This can be a domain that you manage, although it is probably easier to serve the files from a cloud service or content delivery network provider.

14. Safe Dependencies: When installing third-party libraries, preferring active and well-maintained projects to stale or obscure libraries that are less likely to be kept up to date. We don’t have to reinvent the wheel for with every feature request, but spend some time researching options and don’t settle for one that has long been abandoned when there are better options available. Keep our dependencies up to date, run safety checks on our dependencies routinely, and update as needed. In addition to third-party services available GitHub will alert you of vulnerabilities in your dependencies if we update our repository settings to allow them read-only access to our code.

15. SSL / HTTPS: It is always better for security to deploy your site behind HTTPS without this, it is possible for malicious network users to sniff authentications credentials or any other information’s transferred between client and server, and in some cases — active network attackers — to alter data that is sent in either direction. If you want the protection that HTTPS provides and have enabled it on your server, there are some additional steps you may need.

➢ If necessary, set SECURE_PROXY_SSL_HEADER, ensuring that you have understood the warning there thoroughly. failure to do this can result in CSRF vulnerabilities and failure to to it correctly can also be dangerous.

➢ Set SECURE_SSL_REDIRECT to True, so that request over HTTP is redirected to HTTPS.

➢ Please note the caveats under SECURE_PROXY_SLL_HEADER. For the case of a reverse proxy, it may be easier or more secure to configure the main. Web server to do the redirect to HTTPS.

➢ Use HTTP Strict Transport Security (HSTS) HSTS is an HTTP header that informs a browser that all future connections to a particular site should always use HTTPS. Combined with redirecting request over HTTP to HTTPS, this will ensure that connections always enjoy the added security of SSL provided one successful connection has occurred. HSTS may either be configured with SECURE_HSTS_SECONDS, SECURE_HSTS_INCLUDE_SUBDOMAINS, and SECURE_HSTS_PRELOAD, or on the web server.

16. What is a DDoS Attack? Distributed Network Attacks are often referred to as Distributed Denial of Service (DDoS) attacks. This type of attack takes advantage of the specific capacity limits that apply to any network resources-such as the infrastructure that enables a company’s website. The DDoS attack will send multiple requests to the attacked web resources-with the aim of exceeding the website’s capacity to handle multiple requests and prevent the website form functioning correctly.

How a DDoS attack works: Network resources -such as web servers -have a finite limit to the number of requests that they can service simultaneously, in addition to the capacity limit of the sever, the channel that connects the server to the internet will also have a finite bandwidth / capacity. Whenever the number of requests exceeds the capacity limits of any component of the infrastructure, the level of service is likely to suffer in one of the following ways:

➢ The response to requests will be much slower than normal. Some or all- user’s requests may be totally ignored. Usually, the attacker’s ultimate aim is the total prevention of the web resource’s normal functioning — a total ‘denial of service’. The attacker may also request payment for stopping the attack. In some cases, a DDoS attack may even be attempt to discredit or damage a competitor’s business.

Best Open-Source DDoS Mitigation Software:

➢ OWASP HTTP POST — OWASP stands for Open Web Application Security Project. OWASP HTTP POST is an open-source DDoS mitigation software for application-layer attacks. It is also recommended to be used while testing the performance. It is one of the best open-source DDoS mitigation software to decide the capacity of the server.

➢ NGINX- NGINX is a popular open-source DDoS mitigation software. It offers a suite of technologies that support the development and delivery of modern applications. NGINX provides organization solutions for digital transformations, monolithic application, delivering microservices-based application, etc. NGINX is the open source DDoS mitigation software trusted by more than 400 million sites. Companies like Netflix, Hulu, Pinterest, McDonald’s etc. have been benefitted and reached high visibility on the sites.

➢ HA Proxy — HA Proxy is the fastest and globally used open-source DDoS mitigation software. It offers solutions for load balancers and population delivery control. HA Proxy provides powerful and tailored solutions according to the agenda and objective of an organization. It offers business high availability, security, administration, and support for their websites and applications.

➢ DDoS Deflate — DDoS Deflate is an open-source shell script mitigation software. It allows, a company to easily implement and configure its solutions on its services to reduce DDoS attacks. It offers feature to block whitelist and blacklist IP addresses and notify admins regarding the actions.

--

--

Akash Jatav
mewt

My name is Akash Jatav , I am a final year Undergraduate student of IIT Kanpur.