How to Prevent CSRF Cross-Site Request Forgery Attacks in Django

How to Prevent CSRF Cross-Site Request Forgery Attacks in Django

CSRF Cross-Site Request Forgery.

CSRF Cross-Site Request Forgery.

The attacker stole your identity and sent a malicious request on your behalf. The request is completely legitimate for the server, but it completes an operation that the attacker expects, such as sending an email or sending a message on your behalf. Steal your account, add system administrators, and even purchase goods, virtual currency transfers, and more.

CSRF attack principle and process

User C opens a browser, accesses trusted website A, and enters a username and password to request login to website A;

After the user information is verified, Website A generates cookie information and returns it to the browser. At this time, the user successfully logs in to Website A and can send a request to Website A normally;

Before the user logs out of website A, open a TAB page in the same browser to visit website B;

After receiving the user's request, website B returns some offensive codes and sends a request to visit third-party site A;

After receiving the offensive code, the browser sends cookie information to the website A according to the request of the website B without the user's knowledge. Website A does not know that the request was actually initiated by B, so it will process the request with the authority of C according to the cookie information of user C, resulting in the execution of malicious code from website B.

CSRF attack example

The victim Bob has a deposit in the bank. By sending a request to the bank's website http: //bank.example/withdraw? Account = bob & amount = 1000000 & for = bob2, Bob can transfer 1000000 deposit to bob2's account. Normally, after the request is sent to the website, the server first verifies whether the request comes from a legitimate session, and the user Bob of the session has successfully logged in.

The hacker Mallory also has an account with the bank himself, and he knows that the URL above can be used to transfer money. Mallory can send a request to the bank itself: http: //bank.example/withdraw? Account = bob & amount = 1000000 & for = Mallory. But this request comes from Mallory instead of Bob, he cannot pass the security authentication, so the request will not work.

At this time, Mallory thought of using the CSRF attack method, he first made a website by himself, put the following code in the website: src = ”http: //bank.example/withdraw? Account = bob & amount = 1000000 & for = Mallory”, and passed Advertising, etc. enticed Bob to visit his website. When Bob visits the website, the above URL will be sent from Bob's browser to the bank, and this request will be sent to the bank server along with the cookie in Bob's browser. In most cases, the request fails because he requires Bob's authentication information. However, if Bob happened to visit his bank shortly after that, the session between his browser and the bank's website had not expired, and the browser's cookie contained Bob's authentication information. At this time, a tragedy happened, the url request would be responded, and money would be transferred from Bob's account to Mallory's account, and Bob had no knowledge at the time. After waiting, Bob found that the account had less money. Even if he went to the bank to check the logs, he could only find that there was indeed a legitimate request from him to transfer the funds without any trace of being attacked. Mallory can get away with it.

How to prevent CSRF in Django

Django uses specialized middleware (CsrfMiddleware) for CSRF protection. The specific principle is as follows:

  1. It modifies the currently processed request, adds a hidden form field to all POST forms, uses the name csrfmiddlewaretoken, the value is the current session ID plus a hash of the key. If the session ID is not set, the middleware will not modify the response result, so the performance loss is negligible for requests that do not use a session.

  2. For all incoming POST requests with a session cookie collection, it will check for the existence of csrfmiddlewaretoken and its correctness. If not, the user will receive a 403 HTTP error. The content of the 403 error page was a cross-domain request masquerade detected. Terminate the request.

This step ensures that only forms originating from your site can POST the data back.

It should also be noted that POST requests that do not use session cookies cannot be protected, but they also do not need to be protected because malicious websites can make such requests in any way. To avoid converting non-HTML requests, the middleware checks its Content-Type header before editing the response result. Only pages marked as text / html or application / xml + xhtml will be modified.

Specific operations of Django to prevent CSRF
  1. Add 'django.middleware.csrf.CsrfViewMiddleware' to the MIDDLEWARE_CLASSES list in Django's settings.py file (it is added by default). The middleware must be executed after SessionMiddleware, so CsrfMiddleware must appear before SessionMiddleware in the list (because the response middleware is executed from back to front). At the same time, it must also process the response result before the response is compressed or decompressed, so CsrfMiddleware must be executed after GZipMiddleware.
MIDDLEWARE_CLASSES = (

    'django.middleware.common.CommonMiddleware',

    'django.contrib.sessions.middleware.SessionMiddleware',

    'django.middleware.csrf.CsrfViewMiddleware',

    'django.contrib.auth.middleware.AuthenticationMiddleware',

    'django.contrib.messages.middleware.MessageMiddleware',

    # Uncomment the next line for simple clickjacking protection:

    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',

)
  1. Add the csrf_token tag to the page that submits the FORM using the POST method, for example:
<form action="." method="post">{% csrf_token %}
  1. In the corresponding view, ensure that the "django.core.context_processors.csrf" context processor is used correctly. There are two ways to achieve this. One is to use RequestContext, which will automatically use "django.core.context_processors" internally. .csrf ". Another method is to use this processor manually, the sample code is as follows:
from django.core.context_processors import csrf

from django.shortcuts import render_to_response

def my_view(request):

    c = {}

    c.update(csrf(request))

    # ... view code here

return render_to_response("a_template.html", c)

Python Django Tutorial | Django Course

Python Django Tutorial | Django Course

🔥Intellipaat Django course: https://intellipaat.com/python-django-training/ 👉This Python Django tutorial will help you learn what is django web development &...

This Python Django tutorial will help you learn what is django web development & application, what is django and introduction to django framework, how to install django and start programming, how to create a django project and how to build django app. There is a short django project as well to master this python django framework.

Why should you watch this Django tutorial?

You can learn Django much faster than any other programming language and this Django tutorial helps you do just that. Our Django tutorial has been created with extensive inputs from the industry so that you can learn Django and apply it for real world scenarios.

Django

Well i used django ... i want to know after completing all the coding stuff, can i make all the codes online ?

Well i used django ... i want to know after completing all the coding stuff, can i make all the codes online ?

as Django give you a local host, i have a .com domain but can i integrate the codes to it so it works ?