CSRF (Cross site request forgery, multi-site domain requests forgery)
CSRF Background and introduction
CSRF (Cross site request forgery) is a network attack mode, which was listed as one of the 20 major security risks in the Internet in 2007. Other security risks, such as SQL script injection, cross-site scripting attacks, have been gradually known in recent years, and many websites have defended them. However, for most people, CSRF is still a strange concept. Even the well-known Gmail, at the end of 2007, there are CSRF loopholes, so that hackers to attack the users of Gmail caused huge losses.
CSRF Attack instances
The CSRF attack can be sent to the compromised site in the name of the victim without the knowledge of the victim, thereby performing an operation under rights protection if not authorized. For example, 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 object of attack
Before discussing how to defend against CSRF, it is very clear that the object of the CSRF attack is the object to be protected. From the above example, the CSRF attack is a hacker's use of the victim's cookie to defraud the server of trust, but hackers do not have access to cookies, but also do not see the content of cookies. In addition, for the results returned by the server, due to browser-origin policy restrictions, hackers can not be resolved. Therefore, the hacker cannot get anything from the returned results, all he can do is send a request to the server to execute the command described in the request, directly change the value of the data on the server side, rather than stealing the data from the server. Therefore, the objects we want to protect are those that can directly generate data changes, and for the services that read the data, there is no need for CSRF protection. For example, the transfer request in the banking system will change the amount of the account directly, will be CSRF attack, need to protect. The query balance is a read operation on the amount, does not change the data, the CSRF attack cannot resolve the results returned by the server, without protection.
Defense strategy: Add tokens to the request address and verify
The success of the CSRF attack is because the hacker can completely forge the user's request, all the user authentication information in the request is in the cookie, so the hacker can directly use the user's own cookie to pass the security authentication without knowing the authentication information. 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.
Tokens can be generated and placed in the session after the user logs in, and then the token is taken out of the session on each request and compared to the token in the request, but the difficulty of this method is how to add tokens as parameters 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 add tokens manually when encoding.
Using Csrfhow to use it¶ in Django
To take advantage of CSRF protection in your views, follow these steps:
-
the CSRF middleware was activated by default in The middleware_classes
setting. If you override that setting, remember That Django.middleware.csrf.CsrfViewMiddleware '
should come before any view middleware this assume that CSRF Attacks has been dealt with.
If you disabled it, which isn't recommended, you can use csrf_ Protect ()
on particular views the want to protect (see below).
-
in any template, the uses a POST form, use The Csrf_token
tag inside The <FORM>
element if the form is for an internal URL, e.g.:
< Form action= "" method= "post" >{% csrf_token%}
This should is done for post forms that targe T external URLs, since that would cause the CSRF tokens to being leaked, leading to a vulnerability.
In the corresponding view functions, ensure that's used to render the response so that'll work RequestContext
{%csrf_token %}
properly. If you're using the render()
function, generic views, or contrib apps, you're covered already since these all use RequestContext
.
The meaning of this paragraph is
1, it is not recommended to disable the CSRF in Django.
2. We can add Csrf_token to the form form of the HTML page and send the request with the form to the server to verify.
<form enctype= "Multipart/form-data" method= "POST" action= "{% url ' new_article '%}" > {% csrf_ Token%}
3, in the back end must use the render () method to return data.
return render (Request, ' article_new.html ', {' article_list ': article_list})
CSRF with AJAX
While the above method can is used for AJAX POST requests, it had some inconveniences: you had to remember to pass th e CSRF token in as post data with every POST request. For this reason, there are an alternative method:on each xmlhttprequest, set a custom header to the value of the X-CSRFToken
CSR F token. This is often easier, because many JavaScript frameworks provide hooks the Allow headers to be set on every request.
As a first step, you must get the CSRF token itself. The recommended source csrftoken
for the token is the cookie, which'll be set if you've enabled CSRF protection for your view s as outlined above.
Using Jqueryfunction GetCookie (name) { var cookievalue = null; if (document.cookie && document.cookie! = ") { var cookies = Document.cookie.split (';'); for (var i = 0; i < cookies.length; i++) { var cookie = Jquery.trim (Cookies[i]); Does this cookie, string begin with the name we want? if (cookie.substring (0, name.length + 1) = = (name + ' = ')) { Cookievalue = decodeuricomponent (cookie.substring (name.le Ngth + 1)); Break ; }}} return cookievalue;} var csrftoken = GetCookie (' Csrftoken ');
The above code could is simplified by using the JavaScript Cookie library to replace getCookie
:
var csrftoken = cookies.get (' Csrftoken ');
Finally, you'll have a actually set the header on your AJAX request, while protecting the CSRF token from being sent to O ther domains using Settings.crossdomain in JQuery 1.5.1 and newer:
function Csrfsafemethod (method) { //These HTTP methods does not require CSRF protection return (/^ (get| head| options| TRACE) $/.test (method));} $.ajaxsetup ({ beforesend:function (XHR, settings) { if (!csrfsafemethod (settings.type) &&!) This.crossdomain) { xhr.setrequestheader ("X-csrftoken", Csrftoken);}} );
The CSRF in Django