[Security] What is a CSRF attack? How to avoid it? How to prevent it during development?

Preface

CSRF concept

CSRF definition: Cross-site request forgery (English: Cross-site request forgery) is a malicious use of a website, also known as one-click attack or session riding, usually abbreviated as CSRF or An attack method that performs unintended operations on the currently logged-in web application. CSRF Cross-Site Request Forgery (Cross-Site Request Forgery) is as harmful as XSS attacks.

You can understand it this way: the attacker has stolen your identity and sent a malicious request in your name. This request is completely legal to the server, but it completes an operation expected by the attacker, such as in your name. Send emails, send messages, steal your account, add system administrators, and even purchase goods, transfer virtual currency, etc.

Simply put, the attacker uses some technical means to deceive the user's browser to visit a website that he has authenticated and perform some operations (such as sending emails, sending messages, and even property operations such as transferring money and purchasing goods). Since the browser has been authenticated, the visited website will regard it as a real user operation and execute it. This exploits a vulnerability in user authentication on the web: simple authentication can only guarantee that the request comes from a user's browser, but cannot guarantee that the request itself was made voluntarily by the user.

CSRF status: It is a method of network attack and one of the major security risks of the Internet. NYTimes.com (New York Times), Metafilter, YouTube, Gmail and Baidu HI have all been subject to such attacks.

Comparing XSS: Compared with cross-site scripting (XSS), XSS takes advantage of the user's trust in the specified website, while CSRF takes advantage of the website's trust in the user's web browser.

As follows: Web A is a website with a CSRF vulnerability, Web B is a malicious website built by an attacker, and User C is a legitimate user of the Web A website.

If you don’t understand the CSRF principle above, you can look at this principle again:
First understand the concept of first-party and third-party cookies.
Cookie is a small piece of data stored in the browser by a domain server. It can only be accessed by this domain. Whoever sets it Who visits.

First-party Cookie: For example, when visiting the website www.a.com, this website sets a cookie, and this cookie can only be read by web pages under the domain www.a.com.
Third-party cookies: For example, when visiting the website www.a.com, a picture from the website www.b.com is used in the webpage. When the browser requests the picture from www.b.com, www.b.com sets it. A cookie, then this cookie can only be accessed by the domain www.b.com, but cannot be accessed by the domain www.a.com, because for us, we are actually setting it when visiting the website www.a.com A cookie under the domain www.b.com is obtained, so it is called a third-party cookie.

CSRF principle

  1. User C opens the browser, visits trusted website A, enters the username and password to request to log in to website A;
  2. 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 requests to website A normally;
  3. Before the user exits website A, he opens a TAB page in the same browser to visit website B;
  4. After website B receives the user's request, it returns some offensive code and issues a request to access third-party site A;
  5. After receiving these offensive codes, the browser carries the cookie information according to the request of website B without the user's knowledge, and sends a request to website A. Website A does not know that the request is actually initiated by B, so it will process the request with C's permissions based on user C's cookie information, causing the malicious code from website B to be executed.

In short: By visiting a malicious URL, the malicious URL returns js and automatically executes access to the URL you logged in before. Because you are already logged in, cookies will be carried when you visit again, because the server only recognizes whether there are cookies and cannot distinguish whether they are cookies or not. Users have normal access, so they will deceive the server and cause harm.

CSRF attack defense

The focus of CSRF attack defense is to use cookie values ​​that can only be read by the first party and cannot read third-party cookie values.

defense method

A simple and feasible way to prevent CSRF attacks is to add a cookie again on the client web page to save a random number. When the user visits, first read the value of this cookie, hash the cookie value and send it to the server. The server receives After the hash value of the user, the value of the cookie previously set on the user side is taken out, and the cookie value is hashed using the same algorithm. If the two hash values ​​are compared, it is legal if they are the same. (If the user visits a virus website and wants to bring this cookie to visit, at this time, because the virus website cannot obtain the value of the third-party cookie, he cannot hash the random number, so it will be verified by the server. filtered out)

How session works

About browser cache, cookies, session: www.cnblogs.com/yigeqi/p/62...Understand
the Cookie and Session mechanism: www.cnblogs.com/andy-zhou/p...In-depth
understanding of the browser session mechanism (session && cookie) :blog.csdn.net/xi_2130/art…
Detailed explanation of the difference between cookie and session: www.cnblogs.com/shiyangxt/a…
Detailed explanation of cookie and session: blog.csdn.net/gaoyong_sto…
CSRF is more dangerous than XSS. To deeply understand the attack characteristics of CSRF, we need to understand how the website session works.

I think everyone is familiar with session. Whether you have developed a website using .net or PHP, you must have used the session object. However, how does session work? If you are not sure, please read below.

Let me ask a little question first: If I disable cookies in my browser, do you think the session can still work normally?
The answer is no. I will give a simple example here to help you understand session.
For example, I bought a golf club membership card, and the club gave me a membership card with a card number. What rights I can enjoy (for example, I have a senior membership card that allows me to play 19 holes and pay for drinks, while a junior membership card can only swing at the driving range) and my personal information are stored in the golf club's database. Every time I go to the golf club, I only need to show this premium membership card, and the club will know who I am and serve me.

Here our premium membership card number = sessionid saved in the cookie; and my premium membership card rights and personal information are the session objects on the server side.

We know that http requests are stateless, which means that each http request is independent and has nothing to do with previous operations, but each http request will send all cookies in this domain to the server as part of the http request header. Therefore, the server finds the member information in the session object based on the sessionid stored in the cookie in the request.
Of course, there are various ways to save sessions, which can be saved in files or in memory. Considering the distributed horizontal expansion, we still recommend saving it in a third-party media, such as redis or mongodb.

Once we understand the working mechanism of session, CSRF will be easy to understand. A CSRF attack is equivalent to malicious user A copying my premium membership card. One day, malicious user A can also use this fake premium membership card to play 19 holes at the golf club and enjoy delicious drinks, and I will be able to enjoy delicious drinks at the end of the month. Will receive golf club bill!

After understanding the mechanism of CSRF, I believe the dangers are self-evident to everyone. I can forge the identity of a user and send spam messages to his friends. The hyperlinks of these spam messages may contain Trojan horse programs or some deceptive information (such as Borrowing money, etc.), if the spam messages sent by CSRF also contain worm links, those friends who have received these harmful messages will also become the spread of harmful information if they open the link in the private message, so tens of thousands of Users had their data stolen and Trojans planted. The application of the entire website may crash in an instant, users will complain, users will be lost, and the company's reputation will plummet or even face bankruptcy. Once on MSN, a 19-year-old American named Samy exploited the CSS background vulnerability to successfully infect more than 1 million users with his worm within a few hours. Although the worm did not destroy the entire application, it only added a signature to each user's signature. The sentence "Samy is my idol" is added at the end. However, once these vulnerabilities are exploited by malicious users, the consequences will be disastrous. The same thing also happened on Sina Weibo.

Example:
The main purpose of a CSRF attack is to allow users to attack a system they have logged into without their knowledge, similar to phishing. If the user is currently logged into an email or bbs, and at the same time is using another site that is already controlled by you, let's call it a phishing website. This website may attract you because of a certain picture. If you click it, a js click event may be triggered to construct a bbs posting request and go to your bbs to post. Since the current status of your browser has It is the login status, so the session login cookie information will be the same as the normal request. It is a natural use of the current login status to allow users to help you post or do other things without knowing it.

The principle and process of CSRF attack are as follows:

User C opens the browser, visits trusted website A, enters the user name and password to request to log in 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 normally Request to website A;
before the user exits website A, he opens a TAB page in the same browser to visit website B;
after website B receives the user's request, it returns some offensive code and sends a request to access third-party website A. ;
After receiving these offensive codes, the browser carries the cookie information according to the request of website B without the user's knowledge, and sends a request to website A. Website A does not know that the request is actually initiated by B, so it will process the request with C's permissions based on user C's cookie information, causing the malicious code from website B to be executed.

Therefore, to be attacked by CSRF, two conditions must be met at the same time:

Log in to trusted website A and generate cookies locally.
Access dangerous website B without logging out of A.

Several common types of attacks

Dark cloud case: GET type CSRF
This type of CSRF is generally caused by programmers' lack of security awareness. GET type CSRF exploitation is very simple and only requires an HTTP request, so it is generally exploited like this:

<img src=http://wooyun.org/csrf?xx=11 /> 

After visiting the page containing this img, an HTTP request was successfully made to wooyun.org/csrf?xx=11. Therefore, if the URL is replaced with an address with GET-type CSRF, the attack can be completed.

Dark cloud case: POST type CSRF.
This type of CSRF is not as harmful as GET type. It is usually exploited using an automatically submitted form, such as:

<form action=http://wooyun.org/csrf.php method=POST>
    <input type="text" name="xx" value="11" />
</form>
<script> document.forms[0].submit(); </script> 

After accessing this page, the form will be automatically submitted, which is equivalent to simulating a user completing a POST operation.

Dark Cloud Case: Other wretched CSRF
CSRF that has passed basic authentication (commonly used in routers):
POC:

<img src=http://admin:[email protected] /> 

After loading the image, the router will give the user a legal SESSION and you can proceed to the next step.

CSRF attack example:
The victim Bob has a deposit in the bank. By sending a request to the bank's website bank.example/withdraw?ac..., Bob can transfer the deposit of 1,000,000 to bob2's account. Normally, after the request is sent to the website, the server will first verify whether the request comes from a legitimate session, and the user Bob of the session has successfully logged in.
The hacker Mallory himself also has an account in the bank, and he knows that the URL above can transfer money. Mallory can send a request to the bank himself: bank.example/withdraw?ac... Mallory, not Bob, cannot pass security authentication, so the request will not work.
At this time, Mallory thought of using CSRF attack method. He first made a website by himself, put the following code in the website: src="bank.example/withdraw?ac...", and induced Bob to visit his through advertisements, etc. 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, this request will fail because it requires Bob's authentication information. However, if Bob happens to have just visited his bank at that time, the session between his browser and the bank's website has not expired, and the browser's cookie contains Bob's authentication information. At this time, tragedy happened, the URL request would be responded to, and the money would be transferred from Bob's account to Mallory's account, without Bob knowing at the time. Later, Bob found that there was less money in his account. 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, on the other hand, could get the money and get away with it.

CSRF attack example

Daguanren (big official) has a deposit in the bank. He enters his username and password to log in to the bank's online banking and then sends a request to transfer funds to his account:
http://www.bank.example/withdraw?account=daguanren1&amount=999&for=daguanren2

Transferred 999 blocks from daguanren1 to daguanren2 account. Usually after a user logs in, the system will save the session value of the user's login (which may be the user's mobile phone number, account number, etc.). But if daguanren accidentally opens a new tab page and enters the website of a hacker Jinlian (Jinlian), and the page of Jinlian website has the following HTML tag embedded in it:

<!DOCTYPE html>
<html>
    <!--其他页面元素-->
 
    <img src=http://www.bank.example/withdraw?account=daguanren1&amount=888&for=jinlian width='0' height='0'>
 
    <!--其他页面元素-->
</html>

This request will be accompanied by daguanren's session value, and the daguanren's 888 yuan will be successfully transferred to jinlian's account. However, if daguanren has not logged into online banking before, but directly opens jinlian's website, he will not be attacked because there is no session value. Although the above example is a get request, the form submitted by the post request will also be attacked.

<form method='POST' action='http://www.bank.example/withdraw' target="csrf-frame" id="csrf-form">
  <input type='hidden' name='account' value='daguanren1'>
  <input type='hidden' name='amount' value='888'>
  <input type='hidden' name='for' value='jinlian'>
  <input type='submit' value='submit'>
</form>
<script>document.getElementById("csrf-form").submit()</script>

Targets of CSRF attacks

Before discussing how to defend against CSRF, we must first clarify the object of the CSRF attack, that is, the object to be protected. As can be seen from the above examples, a CSRF attack is a hacker using the victim's cookie (session) to deceive the server's trust, but the hacker cannot obtain the cookie and cannot see the content of the cookie. In addition, hackers cannot parse the results returned by the server due to the browser's same-origin policy restrictions. 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 and directly change the value of the data on the server side instead of stealing the data in the server. Therefore, the objects we want to protect are those services that can directly produce data changes. For services that read data, CSRF protection is not required. For example, a transfer request in the banking system will directly change the amount of the account, which will be subject to CSRF attacks and needs protection. Querying the balance is a read operation of the amount and does not change the data. CSRF attacks cannot parse the results returned by the server and do not require protection.
Therefore: additions, deletions and modifications need to be guarded against CSRF attacks, but reading (i.e. reading the database) does not need to be guarded against.

For example
, simple version:
If the blog garden has a GET interface for adding followers, the blogUserGuid parameter is obviously the follower ID, as follows:
http://www.cnblogs.com/mvc/Follow/FollowBlogger.aspx?blogUserGuid=4e8c33d0- 77fe-df11-ac81-842b2b196315

Then I only need to write an img tag in the content of one of my blog posts:

<img style="width:0;" src="http://www.cnblogs.com/mvc/Follow/FollowBlogger.aspx?blogUserGuid=4e8c33d0-77fe-df11-ac81-842b2b196315"   />

Then as long as someone opens this blog post of mine, they will automatically follow me.
Upgraded version:
If the blog park still has an interface to add attention, it has been restricted to only obtain data from POST requests. At this time, a third-party page is created, but it contains the form submission code, and then spreads it through social tools such as QQ and email, tempting users to open it. Users who have opened the blog park will be tricked.
Before giving an example, I need to correct an iframe problem. Some people will write this directly on a third-party page. as follows:

<!DOCTYPE HTML>
<html lang="en-US">
<head>
<title>CSRF SHOW</title>
</head>
     <body>
          <!--不嵌iframe会跳转-->
          <iframe style="display:none;">
               <form  name="form1" action="http://www.cnblogs.com/mvc/Follow/FollowBlogger.aspx" method="post">
                    <input type="hidden" name="blogUserGuid" value="4e8c33d0-77fe-df11-ac81-842b2b196315"/>
                    <input type="submit" value>
               </form>
               <script>
                    document.forms.form1.submit();
               </script>
          </iframe>
     </body>
</html>

This is a problem. Due to the same-origin policy, the iframe content cannot be loaded at all, so of course the form submission inside will not be executed.
PS: I tried chrome, IE11, and Firefox, and the situation is the same.
Therefore, it can be solved by embedding one more layer of pages, as follows:
The first display page (test):

<!DOCTYPE HTML>
<html lang="en-US">
<head>
<title>CSRF SHOW</title>
</head>
     <body>
          <iframe style="display:none;" src="test2.html"></iframe>
     </body>
</html>

The second hidden page (test2):

<!DOCTYPE HTML>
<html lang="en-US">
<head>
<title>CSRF GET</title>
<body>
     <form  name="form1" action="http://www.cnblogs.com/mvc/Follow/FollowBlogger.aspx" method="post">
          <input type="hidden" name="blogUserGuid" value="4e8c33d0-77fe-df11-ac81-842b2b196315"/>
          <input type="submit" value>
     </form>
     <script>
          document.forms.form1.submit();
     </script>
</body>
</html>

This can be solved. Some people will ask why an extra layer of iframe is needed, because the page without iframe will be redirected, which reduces the concealment of the attack. In addition, our test page does not use XMLHTTPRequest to send POST requests because there are cross-domain problems, and form can post data across domains.
Advanced version:
If the blog park still has an interface to add attention, and POST has been restricted, but the content of the blog post is directly pasted into HTML (unfiltered), it will suffer from XSS attacks. Then you can directly embed the above code into the blog post, and as long as someone opens my blog post, they will automatically follow me. This combined attack method is called XSRF.
The essential cause of CSRF attacks
CSRF attacks originate from the implicit authentication mechanism of the Web! Although the Web's authentication mechanism can guarantee that a request comes from a user's browser, it cannot guarantee that the request is approved by the user. CSRF attacks are generally solved by the server.
The above briefly talks about the idea of ​​CSRF attacks. Below I will use several examples to explain specific CSRF attacks in detail. Here I take a bank transfer operation as an example (just an example, real bank websites are not so stupid:> )
Example 1:
  Bank website A, which uses GET requests to complete bank transfer operations, such as: www.mybank.com/Transfer.ph...
  Dangerous website B, which contains a piece of HTML code as follows:
  <img src=www. mybank.com/Transfer.ph...
  First, you log in to bank website A, and then visit dangerous website B. Oh, then you will find that your bank account is missing 1,000 yuan...
  Why is this so? The reason is that bank website A violates HTTP specifications and uses GET requests to update resources. Before accessing dangerous website B, you have already logged in to bank website A, and B uses GET to request third-party resources (the third party here refers to the bank website. Originally this was a legal request, but here it was Criminals have taken advantage of it), so your browser will bring the cookie of your bank website A to issue a Get request to obtain the resource "www.mybank.com/Transfer.php?toBankId=11&money=1000". As a result, the bank website server After receiving the request, it thinks that this is an update resource operation (transfer operation), so the transfer operation is performed immediately...
  Example 2:
  In order to eliminate the above problem, the bank decided to use POST request to complete the transfer operation.
  The WEB form of bank website A is as follows:

<form action="Transfer.php" method="POST">
    <p>ToBankId: <input type="text" name="toBankId" /></p>
    <p>Money: <input type="text" name="money" /></p>
    <p><input type="submit" value="Transfer" /></p>
  </form>

The background processing page Transfer.php is as follows:

<?php
    session_start();
    if (isset($_REQUEST['toBankId'] && isset($_REQUEST['money']))
    {
    
    
        buy_stocks($_REQUEST['toBankId'], $_REQUEST['money']);
    }
  ?>

Dangerous website B still only contains the HTML code:

<img src=http://www.mybank.com/Transfer.php?toBankId=11&money=1000>

Same as the operation in Example 1, you first logged in to bank website A, and then visited dangerous website B. The result... Same as example 1, you lost 1,000 yuan again~T_T. The cause of this accident is: the bank backend used REQUEST To get the requested data, and _REQUEST to get the requested data, and REQUEST to get the requested data, and _REQUEST can get both the GET requested data and the POST requested data, which results in the background The handler cannot distinguish whether this is the data of the GET request or the data of the POST request. In PHP, you can use GET and _GET and GET and _POST to obtain the data of GET request and POST request respectively. In JAVA, the request used to obtain request data also has the problem of being unable to distinguish between GET request data and POST data.
Example 3:
  After the previous two painful lessons, the bank decided to change the method of obtaining request data and instead used $_POST to only obtain the data of POST request. The background processing page Transfer.php code is as follows:

<?php
    session_start();
    if (isset($_POST['toBankId'] && isset($_POST['money']))
    {
    
    
        buy_stocks($_POST['toBankId'], $_POST['money']);
    }
  ?>

However, Dangerous Website B has kept pace with the times and changed its code:

<html>
  <head>
    <script type="text/javascript">
      function steal()
      {
      
      
               iframe = document.frames["steal"];
               iframe.document.Submit("transfer");
      }
    </script>
  </head>

  <body οnlοad="steal()">
    <iframe name="steal" display="none">
      <form method="POST" name="transfer" action="http://www.myBank.com/Transfer.php">
        <input type="hidden" name="toBankId" value="11">
        <input type="hidden" name="money" value="1000">
      </form>
    </iframe>
  </body>
</html>

If the user still continues the above operation, unfortunately, the result will be that 1,000 yuan will be lost again... because the dangerous website B here secretly sends a POST request to the bank!

To summarize the above 3 examples, the main CSRF attack modes are basically the above 3 types, of which the 1st and 2nd are the most serious because the triggering conditions are very simple, just one is enough, while the 3rd type is more troublesome and needs to be used JavaScript, so the chances of using it will be much less than the previous ones, but no matter what the situation is, as long as a CSRF attack is triggered, the consequences may be serious.

Understanding the above three attack modes, it can actually be seen that CSRF attacks originate from the implicit authentication mechanism of WEB! Although the WEB authentication mechanism can guarantee that a request comes from a certain user's browser, it cannot guarantee that the request is approved by the user!
CSRF vulnerability detection:

Detecting CSRF vulnerabilities is a relatively tedious task. The simplest method is to grab a normal request data packet, remove the Referer field and then resubmit it. If the submission is still valid, it can basically be determined that a CSRF vulnerability exists.
As the research on CSRF vulnerabilities continues to deepen, some tools that specifically detect CSRF vulnerabilities have emerged, such as CSRFTester, CSRF Request Builder, etc.

Taking the CSRFTester tool as an example, the testing principle of the CSRF vulnerability detection tool is as follows: When using CSRFTester for testing, we first need to capture all links and all forms and other information that we have visited in the browser, and then modify the corresponding information in CSRFTester. Resubmit the form and other information, which is equivalent to a forged client request. If the modified test request is successfully accepted by the website server, it indicates that there is a CSRF vulnerability. Of course, this tool can also be used to conduct CSRF attacks.

Several current strategies to defend against CSRF

There are currently four main strategies to defend against CSRF attacks in the industry:

  • Validate HTTP Referer field;
  • Add token to the request address and verify;
  • Customize attributes in HTTP headers and verify them;
  • Enable SameSite cookie on Chrome browser

Validate HTTP Referer field

What is HTTP Referer? The following GIF is a Referer view showing the jump from Baidu to the QQ mailbox page:

It can be seen that Referer is

Referer:https://www.baidu.com/

According to the HTTP protocol, there is a field called Referer in the HTTP header, which records the source address of the HTTP request. Under normal circumstances, the request to access a secure restricted page comes from the same website, such as accessing bank.example/withdraw?ac... bank.example, and then triggering a transfer event by clicking a button on the page. At this time, the Referer value of the transfer request will be the URL of the page where the transfer button is located, usually an address starting with the bank.example domain name. If a hacker wants to implement a CSRF attack on a bank's website, he can only construct a request on his own website. When a user sends a request to the bank through the hacker's website, the Referer of the request points to the hacker's own website. Therefore, to defend against CSRF attacks, the bank website only needs to verify the Referer value of each transfer request. If it is a domain name starting with bank.example, it means that the request is from the bank website itself and is legal. If the Referer is another website, it may be a CSRF attack by a hacker and the request will be rejected.

The obvious benefit of this method is that it is simple and easy to implement. Ordinary developers of the website do not need to worry about CSRF vulnerabilities. They only need to add an interceptor to all security-sensitive requests at the end to check the Referer value. Especially for the current existing system, there is no need to change any existing code and logic of the current system, there is no risk, and it is very convenient.

However, this method is not foolproof. The value of Referer is provided by the browser. Although the HTTP protocol has clear requirements, each browser may have different implementations of Referer, which does not guarantee that the browser itself has no security vulnerabilities. Using the method of verifying the Referer value relies on a third party (i.e. the browser) to ensure security. In theory, this is not safe. In fact, for some browsers, such as IE6 or FF2, there are already some methods to tamper with the Referer value. If the bank.example website supports the IE6 browser, a hacker can set the Referer value of the user's browser to an address starting with the bank.example domain name, so that it can pass the verification and conduct a CSRF attack.

Even with the latest browsers, where hackers cannot tamper with the Referer value, there are still problems with this approach. Because the Referer value will record the user's access source, some users believe that this will infringe on their own privacy. In particular, some organizations are worried that the Referer value will leak certain information in the organization's intranet to the external network. Therefore, the user himself can set the browser so that it no longer provides a Referer when sending a request. When they visit the bank website normally, the website will consider it a CSRF attack because the request does not have a Referer value, and deny access to legitimate users.
In addition, if the Referer's judgment logic is not written rigorously, it can be easily broken, for example

const referer = request.headers.referer;
if (referer.indexOf('www.bank.example') > -1) {
    
    
  // pass
}

If the hacker's website is www.bank.example.hack.com, the referer check has no effect.

Add token to request address and verify

The reason why CSRF attacks are successful is that hackers can completely forge the user's request. All user verification information in the request exists in cookies, so hackers can directly use the user's cookies without knowing the verification information. Pass security verification. The key to resisting CSRF is to put information in the request that hackers cannot forge, and that information does not exist in cookies. You can add a randomly generated token as a parameter to the HTTP request, and create an interceptor on the server side to verify the token. If there is no token in the request or the token content is incorrect, it is considered that it may be a CSRF attack and the request will be rejected. .

This method is safer than checking the Referer. The token can be generated after the user logs in and placed in the session. Then the token can be taken out of the session during each request and compared with the token in the request, but this The difficulty of this method is how to add the token to the request in the form of a parameter. For GET requests, the token will be appended to the request address, so that the URL becomes
http://url?csrftoken=tokenvalue

For POST requests, add at the end of the form

<input type="hidden" name="csrftoken" value="tokenvalue"/>

One disadvantage of this method is that it is difficult to ensure the security of the token itself. Especially in some forums and other websites that support users to publish their own content, hackers can publish the address of their own personal website. Since the system will also add a token after this address, hackers can get this token on their own website and launch a CSRF attack immediately. In order to avoid this, the system can add a judgment when adding the token. If the link is to the own site, the token will be added later. If it leads to the external network, it will not be added. However, even if the csrftoken is not attached to the request in the form of a parameter, the hacker's website can still obtain the token value through the Referer to launch a CSRF attack. This is also the reason why some users like to manually turn off the browser Referer function.

Customize attributes in HTTP headers and verify

This method also uses tokens for verification. Different from the previous method, the token is not placed in the HTTP request in the form of parameters, but is placed in the custom attributes in the HTTP header. Through the XMLHttpRequest class, you can add the csrftoken HTTP header attribute to all requests of this type at once and put the token value into it. This solves the inconvenience of adding the token to the request in the previous method. At the same time, the address requested through XMLHttpRequest will not be recorded in the browser's address bar, and there is no need to worry about the token being leaked to other websites through the Referer.

However, this method has great limitations. The XMLHttpRequest request is usually used for partial asynchronous refresh of the page in the Ajax method. Not all requests are suitable to be initiated with this class, and the page obtained through this class request cannot be recorded by the browser, so that forward, backward, and refresh can be performed. , collection and other operations bring inconvenience to users. In addition, for legacy systems that do not have CSRF protection, if you want to use this method for protection, all requests must be changed to XMLHttpRequest requests, which will almost rewrite the entire website. This cost is undoubtedly unacceptable.

Enable SameSite cookie on Chrome browser

Here's how to enable SameSite cookie settings, it's very simple.
The original cookie header setting looks like this:
ini copy code Set-Cookie: session_id=esadfas325

Just add SameSite at the end:
ini copy code Set-Cookie: session_id=esdfas32e5; SameSite

SameSite has two modes, Lax and Strict mode. Strict mode is enabled by default. You can specify the mode yourself:
ini copy code Set-Cookie: session_id=esdfas32e5; SameSite=Strict
Set-Cookie: foo=bar; SameSite=Lax

Strict mode specifies that cookies are only allowed to be used on the same site and should not be added in any cross site request. That is, the content submitted by a tag, form form and XMLHttpRequest will not bring cookies as long as it is submitted to different sites.
But there are also inconveniences. For example, a friend sent me a link to a page that I have already logged in. After I click on it, I still need to log in again.
There are two ways to deal with it. The first one is to prepare two different sets of cookies like Amazon. The first set is used to maintain the login status without setting SameSite. The second set is used for some sensitive operations (such as purchasing, Payment, setting up accounts, etc.) strictly set SameSite.
Based on this idea, another mode of SameSite was born: Lax mode.
Lax mode opens some restrictions, such as
ini copy code

These will bring cookies. However, the form of the POST method, or as long as it is POST, PUT, DELETE, these methods will not bring cookies.
But be sure to change the important request method to POST, otherwise GET will still be attacked.
PS: This method is currently only supported by Chrome.

Defense methods of CSRF tools

1. Try to use POST and limit GET

The GET interface is too easy to be used for CSRF attacks. As you can see from the first example, you only need to construct an img tag, and the img tag is data that cannot be filtered. It is best to limit the interface to POST, and GET is invalid to reduce the risk of attacks.
Of course, POST is not foolproof. The attacker only needs to construct a form, but it needs to be done on a third-party page, which increases the possibility of exposure.

2. Browser Cookie Policy

IE6, 7, 8, and Safari will intercept the sending of third-party local cookies (Third-party Cookie) by default. However, Firefox 2, 3, Opera, Chrome, Android, etc. will not intercept, so using browser cookie policies to defend against CSRF attacks is unreliable. It can only be said to reduce the risk.
PS: There are two types of cookies, Session Cookie (which will become invalid after the browser is closed and is saved in memory), and Third-party Cookie (which will only become invalid after the Exprie time is reached. This kind of Cookie will be saved in local).
PS: In addition, if the HTTP header returned by the website contains the P3P Header, the browser will be allowed to send third-party cookies.

3. Add verification code

Verification code, which forces the user to interact with the application to complete the final request. Under normal circumstances, verification codes can effectively contain CSRF attacks. However, due to user experience considerations, the website cannot add verification codes to all operations. Therefore, the verification code can only be used as an auxiliary means and cannot be used as the main solution.

4. Referer Check

The most common application of Referer Check on the Web is to “prevent image hotlinking”. In the same way, Referer Check can also be used to check whether the request comes from a legitimate "source" (whether the Referer value is the specified page, or the domain of the website). If not, then it is most likely a CSRF attack.
However, because the server cannot obtain the Referer at all times, it cannot be used as the main means of CSRF defense. However, using Referer Check to monitor the occurrence of CSRF attacks is a feasible method.

5. Anti CSRF Token

The industry's current common approach to CSRF defense is to use a Token (Anti CSRF Token).
example:

The user accesses a form page.

The server generates a Token and puts it in the user's Session or the browser's Cookie.

The page form comes with the Token parameter.

After the user submits the request, the server verifies whether the Token in the form is consistent with the Token in the user's Session (or Cookies). If they are consistent, it is a legal request. If not, it is an illegal request.

The value of this Token must be random and unpredictable. Due to the existence of the token, the attacker can no longer construct a request with a legitimate token to implement a CSRF attack. In addition, when using Token, you should pay attention to the confidentiality of Token, try to change sensitive operations from GET to POST, and submit them in form or AJAX to avoid Token leakage.
Note:
CSRF Token is only used to resist CSRF attacks. When the website also has XSS vulnerabilities, then this solution is empty talk. Therefore, the problems caused by XSS should be solved using XSS defense solutions.

Summarize

CSRF attack is an attack method in which attackers use the user's identity to operate user accounts. Anti-CSRF Token is usually used to defend against CSRF attacks. At the same time, attention should be paid to the confidentiality and randomness of the Token.

Guess you like

Origin blog.csdn.net/u011397981/article/details/132871362