I am not afraid of seeing CSRF.

Recently, a new project, the first task is to solve the problem of security check discovery, one of which is the CSRF processing. CSRF before heard it, I learned some fans, but I didn’t actually handle it. When using Django, you or go directly, remove the middleware, or you will add @CSRF_EXEMPT shield. Because I don’t understand, I have been committed, and the throne is avoided. However, this time is really can’t escape. . . . Moreover, this time you still have trouble, it is a combination of Django + JINJA2. . . . . No way, then go, it can be difficult to get on the sky, hey! Bamboo

First of all, first understand what is CSRF?

Understand CSRF

The following is extracted from http://www.django-china.cn/topic/580/ (text straight, the content is very easy to understand, it is the type I like ^ _ ^)

What is CSRF?

CSRF (Cross-Site Request Forgery, Chinese Name: Cross-station request forgery, also known as: One click attic / session riding, abbreviation: CSRF / XSRF is a malicious utilization for the website. Although it sounds like a cross-station script (XSS), it is very different from XSS, and the attack mode is almost left. XSS uses trusted users in the site, while CSRF uses trusted websites by disguising requests from trusted users. Compared to XSS attacks, CSRF attacks are often unflavored (therefore the resources to prevent them are quite rare) and difficult to prevent, so they are considered more dangerous than XSS.

What can CSRF do?

You can understand this CSRF attack: the attacker is stealing your identity, sending malicious requests in your name. What CSRFs can do include: sending messages, messages, stealing your account, even purchasing goods, virtual currency transfers, including: Personal privacy leaks and property safety.

CSRF vulnerability status

This attack method has been submitted by security personnel in 2000, but in China, until 2006 began to be concerned. In 2008, many large communities and interactive websites at home and abroad have exploded CSRF vulnerabilities, such as: NYTIMES .com (New York Times), MetaFilter (a large blog website), YouTube and Baidu Hi ……

Now, many sites on the Internet have no preparation, so that the security industry is called CSRF as “sleeping giant.”

Principle of CSRF

The following figure simply elaborated the idea of ??CSRF attacks:

CSRF attack

As can be seen from the above figure, to complete a CSRF attack, the victim must complete two steps:

Log in to trusted website A and generate cookies locally.

Access the dangerous website B without listening A.

Seeing this, you may say: “If I don’t satisfy one of the two conditions, I will not be attacked by CSRF.” Yes, this is true, but you can’t guarantee that the following will not happen:

You can’t guarantee that after you log in to a website, you will no longer open a TAB page and visit additional websites.

You can’t guarantee that you close your browser, your local cookie immediately expires, and your last session is over. (In fact, close the browser can’t end a session, but most people will be wrong to close the browser is equal to exit login / end session …)

The so-called attack site in the above picture may be a trustworthy website with other vulnerabilities.

CSRF attack is the implicit authentication mechanism stem from the web! Although the web authentication mechanism can ensure a request from a user’s browser, it is impossible to ensure that the request is sent by the user!

CSRF defense

CSRF’s defense can start from both the server and the client, the defense effect is better from the server to start the effect, and now the general CSRF defense is also in the server.

The CSRF method of the server is a variety of ways, but the general thinking is consistent, that is, add the number of pseudo-random in the client page.

1, cookie hashing

All forms contain the same pseudo-random value.

This may be the easiest solution, because the attacker cannot obtain a third party’s cookie (theoretical), so the data in the form failed.

This method is personal that I have already put an end to 99% of the CSRF attack. There is a 1% …. Since the user’s cookie is easy to steal due to the XSS vulnerability of the website, this is another 1%. The general attacker sees that there is a need for a Hash value, and basically gives up. Some except, so if it takes 100% to eliminate, this is not the best way.

2, verification code

The idea of ??this program is that each user submission requires a user to fill in a random string on a picture in the form, Er … This program can completely solve the CSRF, but personal feelings don’t seem to be too good in terms of ease of use. Hearing is that the use of the verification code is involved in a bug called MHTML, which may be affected in some versions of Microsoft IE. 3, One-Time tokens

Different forms contain a different pseudo-random value.

When implementing One-Time tokens, you should pay attention to a point: “Compatibility of parallel sessions”. If the user opened two different forms on a site, CSRF protection should not affect his submission of any form. Consideration If each form is loaded, the site generates a pseudo-random value to overwrite what the previous pseudo-random value will happen: the user can only submit his final open form, because all other forms contain illegal Pseudo random value. Be careful to ensure that CSRF protection does not affect tab-style browsing or use multiple browser windows to browse a site.

Django solution

principle

Django uses a special middleware (CSRFMIDdleWare) to perform CSRF protection. The specific principle is as follows:

It modifies the currently processed request, add a hidden form field to all POST forms, using the name of CSRFMIDdleWareToken, and the value of the current session ID plus a hash value. If the session ID is not set, the middleware will not modify the result of the response, so performance loss can be ignored for requests for unused sessions.

For all incoming POST requests for session cookie collections, it will check if there is CSRFMIDdleWareToken and it is correct. If not, the user will receive a 403 HTTP error. The content of the 403 error page is to detect cross-domain request camouflage. Terminate the request.

This step ensures that only the form from your site can return the data POST.

It is also necessary to explain that POST requests that do not use session cookies cannot be protected, but they do not need to be protected because the malicious website can be used to manufacture this request. In order to avoid converting non-HTML requests, the middleware checks it before editing the response result. Only pages labeled text / html or Application / XML + XHTML will be modified.

Specific operation

Form form submit POST request

1, settings.py In Middleware_Classes, add the ‘Django.middleWare.csrf.csrfviewMiddleWare’ middleware, plus CSRF protection globally (the default has been added); if not, you can also add it on the view function. @CSRF_PROTECT performs single view control, but this is not a recommended method, because this may have omissions.

Note: This middleware must be executed after SessionMiddleWare, so CSRFMIDdleWare must appear before sessionMiddleWare (because the response middleware is performed forward). At the same time, it must also process the response results before the response is compressed or decompressed, so CSRFMIDdleWare must be executed after GzipmIDdleWare.

2, add {% CSRF_TOKEN%} after the FORM tag in the form of HTML, such as:

& lt; form action “” Method “POST” & gt; {% CSRF_TOKEN%}

3. VIEW do not want CSRF protection in the view function can be added to @CSRF_EXEMPT

4. Add the Django.core.Context_Processors.csrf context processor to the template_context_processors of the configuration file; or manually generate CSRFTOKEN and add Template Context, such as:

from django.core.context_processors import csrffrom django.shortcuts import render_to_responsedef my_view (request): c {} c.update (csrf (request)) # … view code herereturn render_to_response ( “a_template.html”, c)

Ajax Submit the POST Request Settings Set the same year;

Use render in the view (instead of render_to_response), such as:

render

Add in the HTML template Script tag (Note: You can’t. JS file):

$ .ajaxsetup ({name “cssfmiddleWaretoken” value “{{csrf_token}}” & gt;

3. If you do not need to verify the CSRF value in the cookie, import it in Views.py

From Django.views.Decorators.csrf import CSRF_EXEMPT

Corresponding function plus @CSRF_EXEMPT decorator

finally

As the saying goes: the difficulties will not, and the will be is not difficult.I understand it, I found it is not so difficult, I saw CSRF later, I am not afraid, I am not afraid ~ ^ o ^ ~