Python Automated Operations-Day17-django (iii) CSRF

Source: Internet
Author: User
Tags csrf attack

CSRF Cross-site request forgery

CSRF Cross-site request forgery (Cross-site requests forgery), as with XSS attacks, there is a huge harm, you can understand: The attacker stole your identity, in your name to send a malicious request, to the server this request is completely legal, But it completes an action that the attacker expects, such as sending mail in your name, texting, stealing your account, adding system administrators, and even buying goods, virtual currency transfers, and so on.

CSRF Attack Introduction and defense

People: Web A is a Web site with csrf vulnerabilities, Web B is a malicious website built by attackers, and user C is a legitimate user of web a sites.

CSRF attack attack principle and process are as follows:

1. User C opens the browser, accesses a trusted site A, enters a username and password request to log on to website A;

2. After the user information is verified, website a generates cookie information and returns it to the browser, at which point the user logs on to site a successfully and can send the request to site a normally;

3. Before the user exits site A, in the same browser, open a tab page to access site B;

4. After receiving the user request, website b returns some offensive code and makes a request to access the third party site A;

5. After receiving these offensive codes, the browser, upon request of site B, carries cookie information without the user's knowledge and makes a request to site A. Web site A does not know that the request is actually initiated by B, so the request is processed in accordance with the user C's cookie information, which causes malicious code from site B to be executed.

PS: There is also a case: a multi-window browser, it is convenient to also bring some problems, because the window browser is open with the new Windows is all the current session. That is, I used IE landed my blog, and then I want to see the news, and run an IE process, this time two IE window session is independent of each other, from the news of the IE to send a request to the blog will not have my login cookie; But the multi-window browser will always have only one process, Each window of the session is universal, that is, watching the news of the window to send a request to the blog is to bring my blog login cookies, there may also be csrf attacks.

        The victim Bob has a deposit at the bank, and by sending a request to the bank's website Http://bank.example/withdraw?account=bob&amount=1000000&for=bob2 can make Bob 1000000 of the deposit is transferred to BOB2 's account. Typically, after the request is sent to the Web site, the server verifies that the request is from a valid session and that the user Bob of the session has successfully logged in. The        hacker Mallory himself has an account with the bank and knows that the URL above can transfer money. Mallory can send a request to the bank by itself: Http://bank.example/withdraw?account=bob&amount=1000000&for=Mallory. But this request comes from Mallory, not Bob, who cannot pass security authentication, so the request will not work.        at this time, Mallory think of using CSRF attack way, he first make a website, put the following code in the site: src= "http://bank.example/withdraw?account=bob&amount= 1000000&for=mallory "and lured Bob to visit his website by advertising. When Bob visits the site, the above URLs are sent from Bob's browser to the bank, which is sent to the bank server with a cookie from Bob's browser. In most cases, the request fails because he requires BOB's authentication information. However, if Bob had just visited his bank shortly after, 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 point, the tragedy occurred, the URL request will be answered, the money will be transferred from Bob's account to Mallory's account, and Bob was not informed. After Bob found that the account was less money, even if he went to the bank to check the log, he can only find that there is a legitimate request from his own transfer of funds, without any traces of attack. And Mallory can get the money and go unpunished.     
CSRF Attack InstancesDefensive csrf Attack

There are three main strategies for defending against CSRF attacks: Validating HTTP Referer fields, adding tokens to the request address and validating it, and customizing properties in the HTTP header and validating.

      (1) Verify that the HTTP Referer field is based on the HTTP protocol, there is a field called Referer in the HTTP header, which records the source address of the HTTP request. In general, requests to access a secure restricted page come from the same site, such as the need to access http://bank.example/withdraw?account=bob&amount=1000000&for=Mallory , the user must first log in to Bank.example and then trigger the transfer event by clicking on the button on the page. At this point, the Referer value of the transfer request will be the URL of the page where the transfer button is located, usually the address beginning with the Bank.example domain name. And if the hacker wants to carry on the CSRF attack to the bank website, he only constructs the request in his own website, when the user sends the request to the bank through the hacker's website, the request Referer is pointing at the hacker own website. Therefore, to defend against CSRF attacks, the bank website only needs to verify its Referer value for each transfer request, if it is a domain name beginning with bank.example, it is legitimate that the request is from the bank website itself.        If Referer is a different Web site, it could be a hacker's CSRF attack, rejecting the request. The obvious benefit of this approach is simplicity, the site's general developers do not need to worry about CSRF's vulnerability, only need to be in the end to all security-sensitive requests unified add an interceptor to check the value of Referer.        Especially for current systems, there is no need to change any existing code and logic of the current system, no risk, very convenient. However, this approach is not foolproof. The value of the Referer is provided by the browser, although there are clear requirements on the HTTP protocol, but each browser may have a different implementation for Referer, and there is no guarantee that the browser itself does not have a security vulnerability. The method of validating Referer values is to ensure that security is dependent on a third party (ie, the browser), which in theory is not secure. In fact, for some browsers, such as IE6 or FF2, there are ways to tamper with Referer values. If the Bank.example website supports IE6 browser, the hacker can completely set the Referer value of the user's browser to the address beginning with the Bank.example domain name, so that it can be authenticated for CSRF attacks. Even with the latest browsers, hackers cannot tamper with Referer values, and this method stillThere is a problem. Because the Referer value records the user's access to the source, some users believe that this violates their own privacy, especially some organizations worry that the Referer value will disclose some information in the organization intranet to the external network. As a result, users can set their own browser to no longer provide Referer when sending requests.       When they visit the bank website normally, the website will be considered as a CSRF attack because the request does not have Referer value, and deny access to legitimate users. (2) Add token to the request address and verify that the CSRF attack is successful because the hacker can completely forge the user's request, all the user authentication information in the request is present in the cookie, so the hacker can use the user's own co directly without knowing the authentication information. Okie to pass security verification. The key to defending against CSRF is to put in the request information that the hacker cannot forge, and that the information does not exist in the cookie.        A randomly generated token can be added as a parameter in an HTTP request, and an interceptor is established on the server side to verify the token, and if no token or token content is incorrect in the request, it may be rejected as a CSRF attack. This method is more secure than checking the Referer, token can be generated after the user login and placed in the session, and then on each request to take the token from the session, and the token in the request to compare, but the difficulty of this method is how to put token to The form of the parameter is added to the request. For a GET request, token is appended to the request address so that the URL becomes http://url?csrftoken=tokenvalue. For a POST request, add the <input type= "hidden" name= "Csrftoken" to the end of the form and value= "Tokenvalue", so that token is added to the request in the form of a parameter. However, in a Web site, there are many places to accept requests, it is cumbersome to add tokens to each request, and it is easy to miss out, usually using JavaScript to traverse the entire DOM tree every time the page loads, for all the A and form tags in the DOM Add token. This solves most of the requests, but this method has no effect on the dynamically generated HTML code after the page is loaded, and requires the programmer to manually add the T when codingOken One drawback of this approach is that it is difficult to secure the token itself. In particular, in some forums and other sites that support users to publish their own content, hackers can post their own personal website address. Since the system will also add tokens to this address, hackers can get this token on their website and can launch CSRF attacks immediately. In order to avoid this, the system can add tokens when adding a judgment, if the link is linked to their own site, in the back to add tokens, if it is to the outside network is not added. However, even if the csrftoken is not appended to the request in the form of a parameter, the hacker's website can also be Referer to get the token value to launch the CSRF attack.      This is also why some users prefer to manually turn off the browser Referer feature. (3) Customizing attributes in the HTTP header and verifying that the method is also using token and validating, unlike the previous method, where token is not placed in an HTTP request as an argument, but instead placed in a custom attribute in the HTTP header. By XMLHttpRequest This class, you can add Csrftoken this HTTP header attribute to all requests at once, and put the token value into it.        This solves the inconvenience of adding tokens to the request, while the address requested by XMLHttpRequest is not recorded in the browser's address bar, nor does it worry that tokens will be leaked to other websites through Referer. However, the limitations of this approach are very large. XMLHttpRequest requests are usually used in the Ajax method for the partial page of the asynchronous refresh, not all requests are suitable for this class to initiate, and through the request of this kind of page can not be recorded by the browser, so as to advance, backward, refresh, collection and other operations, to the user inconvenience. In addition, for legacy systems that do not have CSRF protection, it is not acceptable to use this approach for protection, to change all requests to xmlhttprequest requests, almost to rewrite the entire site.
Three principles of strategyDjango CSRF Token

In Django, the middleware is the middleware that validates the CSRF, and the information about it is described in a later section. PS: Do you remember the django.middleware.csrf.CsrfViewMiddleware that was previously commented out in settings.py? , it is the middleware used to detect CSRF. If we render the page back, then when the user accesses the site using a GET request, the site returns a random Csrf_token and writes a key named Csrftoken in the cookie, which has a different value for the two keys.

Based on these two tokens, we have two ways of passing and validating CSRF tokens (first open the CSRF middleware, if commented out previously).

    1. Form form Submission
    2. Ajax Submissions
Form form Submission

Add {% Csrf_token%} to the form to render the Csrf_token returned by the server, which will generate an input tag in the form in hidden, which we will bring to the server for verification when we use the form submission, When we use AJAX instead of the submission of the form, we can get the Csrf_token in the data field to render in the form form, and, of course, the key name must be Csrfmiddlewaretoken, otherwise it will not be recognized. You can see it from the Name property of the generated input.

Ajax Submissions

When there is no form form on the page (get a manual rendering without using a form), you can also use the Csrftoken in the cookie to perform CSRF validation, because the cookie is placed in the request header at the request, so this uses the AJAX headers to customize the request header, Note that the key for the request header must be (X-csrftoken), using the jquery cookie plugin and $.cookie (' Csrftoken ') to get the corresponding value.

Python Automated Operations-Day17-django (iii) CSRF

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.