CSRF concept:

CSRF definition: Cross-site request forgery Cross-site request forgery (CSRF, XSRF, CSRF, CSRF, CSRF, CSRF, CSRF, CSRF, CSRF, CSRF, CSRF, CSRF, CSRF, CSRF, CSRF, CSRF, CSRF, CSRF, CSRF, CSRF Is a method of hijacking a user to perform unintended actions on a currently logged Web application. CSRF Cross-site Request Forgery is as harmful as XSS attack. You can understand it this way: the attacker steal your identity, in the name of your sending malicious request, the request for server is perfectly legal, but finished the attacker’s expectation of an operation, such as in the name of your email, send messages, to steal your account, add a system administrator, or even to buy goods, virtual currency transfer, etc. To put it simply, the attacker uses some technical means to trick the user’s browser into visiting a previously authenticated website and performing some operations (such as sending emails, sending messages, or even property operations such as transferring money or buying goods). Because the browser has been authenticated, the site being visited will act as if it is a genuine user action. This exploits a flaw in user authentication on the Web: simple authentication can only guarantee that a request is sent from a user’s browser, but not that the request itself is voluntarily made by the user.

CSRF status: CSRF is a kind of cyber attack, which is one of the major security risks of the Internet. NYTimes.com (New York Times), Metafilter, YouTube, Gmail and Baidu HI have all been attacked by this kind of attack.

Compare XSS: In contrast to cross-site scripting (XSS), XSS exploits the user’s trust in a specific web site, while CSRF exploits the site’s trust in the user’s Web browser.

Web A is A website with CSRF vulnerability, Web B is A malicious website constructed by an attacker, and User C is A legitimate User of Web A.

If you don’t understand the CSRF principle, you can look at this principle again:

First understand the concepts of first-party and third-party cookies

A Cookie is a small block of data stored by a domain server in a browser that can only be accessed by the domain, depending on who sets it.

First-party Cookie: For example, visit www.a.com, which sets a Cookie that can only be read by web pages in www.a.com.

Third-party Cookie: For example, if you visit www.a.com, there is an image from www.b.com. When www.b.com requests the image, www.b.com sets a Cookie, which can only be accessed by the field of www.b.com. Instead, it cannot be accessed by the www.a.com domain, because for us, we are actually accessing the website www.a.com with a Cookie set under the www.b.com domain, so it is called a third-party Cookie.

CSRF principle:

  • 1. User C opens A browser, accesses trusted website A, and enters the user name and password to request to log in to website A.
  • 2. After the user information is authenticated, website A generates Cookie information and returns it to the browser. At this time, the user successfully logs in to website A and sends requests to website A.
  • 3. Before exiting website A, open A TAB page in the same browser to access website B.
  • 4. After receiving user requests, website B returns some offensive codes and sends A request to visit third-party site A;
  • 5. After receiving these offensive codes, according to the request of Website B, the browser sends A request to Website A with Cookie information without the user’s knowledge. Website A does not know that the request is actually initiated by B, so it will process the request with C’s permission according to the Cookie information of user C, resulting in the malicious code from Website B being executed.

In short: by visiting the malicious web site, the malicious web site returned js automatic execution to visit the site you logged in before, because you have logged in, so visit again will carry cookies, because the server only recognize there is no cookie, can not distinguish whether the user is normal access, so it will deceive the server, causing harm

CSRF Attack defense

CSRF attack defense focuses on cookie values that can only be read by the first party, but cannot be read by the third party.

Defense methods:

The simple and feasible method to prevent CSRF attacks is to add a cookie on the client web page and save a random number. When the user accesses the web page, the user first reads the cookie value, hashes the cookie value and sends it to the server. The server receives the hash value from the user. At the same time, fetch the cookie value set on the client and hash the cookie value using the same algorithm. If the two hash values are identical, they are valid. (If a user visits a virus website and wants to visit it with this cookie, the virus website cannot obtain the value of the third-party cookie, so he cannot hash the random number, so it will be filtered out by the server verification)

How session works

About the browser cache, cookies, session:www.cnblogs.com/yigeqi/p/62…

Understand cookies and Session mechanisms: www.cnblogs.com/andy-zhou/p… An in-depth understanding of browser session mechanisms (Session && Cookies) : blog.csdn.net/xi_2130/art… The difference between the cookie and session a: www.cnblogs.com/shiyangxt/a… Cookie and Session details: blog.csdn.net/gaoyong_sto…

CSRF is more dangerous than XSS. To understand the nature of CSRF attacks, it is important to understand how web sessions work.

I think everyone is familiar with session objects, whether you have developed a website in.NET or PHP, but how does session work? If you don’t know, read on. Quick question: If I disable cookies in my browser, do you think sessions still work?

The answer is no, but let me give you a simple example here to help you understand sessions. For example, if I buy a golf club membership, the club gives me a membership card with a card number. My rights (like 19 holes and post-paid drinks for my premium membership, while my junior membership only allows me to swing on the driving range) and my personal information are kept in the golf club’s database. Every time I go to a golf club, ALL I have to do is show this premium membership card and the club knows who I am and serves me.

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

We know that HTTP requests are stateless, that is, each HTTP request is independent of previous operations, but each HTTP request will send all cookies in the local domain as part of the HTTP request header to the server. So the server will find the session object based on the sessionID stored in the cookie in the request. Of course, session can be saved in various ways, including file or memory. Considering the distributed horizontal expansion, we still recommend that it be saved in a third-party medium, such as Redis or mongodb.

Once we understand how sessions work, CSRF is easy to understand. The CSRF attack is equivalent to malicious user A copying my premium membership card. Malicious user A can take this fake premium membership card to the golf club to play 19 holes and enjoy delicious drinks, and I will receive the golf club bill at the end of the month!

To understand the mechanism of CSRF, harm I believe everyone is self-evident, I can forge a user’s identity to his friends send spam, these spam links or some cheating with Trojan program information (like money), if CSRF send spam links with worms, Those friends who received the harmful information could also spread the harmful information if they opened the link in the private message, so that tens of thousands of users had their data stolen and planted Trojan horses. An entire website’s application can crash in an instant, users complain, users lose, and the company’s reputation plummets or even goes out of business. Once on MSN, a 19-year-old American named Samy took advantage of the BACKGROUND flaw in THE CSS to infect more than 1 million users with his worm in a few hours. Although the worm did not destroy the entire application, it just added a sentence “Samy is my idol” to the end of each user’s signature. But if these vulnerabilities are exploited by malicious users, as happened to Sina Weibo, the consequences can be disastrous.

Example: The main purpose of CSRF attack is to let users unknowingly attack a system they have logged in, similar to phishing. If the user is currently logged into a mailbox, or BBS, and the user is using another site, which is already under your control, let’s call it a phishing site. There may be a picture on this website that attracts you, and when you click on it, a JS click event may be triggered to construct a REQUEST for BBS Posting to your BBS. As your browser is in login state, session login cookie information will be the same as normal request. Natural use of current login status to allow users to help you post or do other things without their knowledge.

CSRF attack The attack mechanism and process are as follows:

  1. User C opens the browser, accesses trusted website A, and enters the user name 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 exiting website A, the user opens A TAB page in the same browser to visit website B.
  4. After receiving the user’s request, website B returns some offensive code and sends A request to visit third-party site A.
  5. After receiving these offensive codes, the browser, according to the request of website B, carries the Cookie information 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 permission according to the Cookie information of user C, resulting in the malicious code from Website B being executed.

Therefore, to be attacked by CSRF, two conditions must be met simultaneously:

  1. Log in to trusted website A and generate cookies locally.
  2. Visit dangerous site B without logging out of A.

 

Several common types of attacks

 

Cloud case: GET type CSRF

This type of CSRF is usually the result of programmers not being security-conscious. CSRF utilization of the GET type is very simple and requires only one HTTP request, so it is generally used as follows:

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

After visiting the page containing the IMG, a successful HTTP request was made to wooyun.org/csrf?xx=11. So, if you replace this url with an address with a GET CSRF, you can complete the attack.

 

Uyun case: CSRF of POST type

This type of CSRF is not as harmful as GET, and is usually exploited using an auto-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> 
Copy the code

When you visit the page, the form is automatically submitted, simulating a POST operation.

 

Cloud case: Other obscene stream CSRF

CSRF with basic authentication (commonly used for routers):

POC:

/ > < img SRC = http://admin:[email protected]Copy the code

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

 

CSRF attack examples:

Bank. Example /withdraw? Ac… Bob can transfer 1,000,000 deposits to boB2 account. Typically, after the request is sent to the site, the server first verifies that the request came from a valid session and that the session’s user Bob has logged in successfully.

Mallory himself had an account at the bank and knew that the URL could transfer money. Mallory can send a request to the bank: 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, put the following code in the website: SRC = “bank.example/withdraw? Ac…” “, and entices Bob to visit his website by advertising and so on. When Bob visits the site, the above URL is sent from Bob’s browser to the bank, and the request is sent to the bank server with a cookie from Bob’s browser. In most cases, the request fails because it asks for Bob’s authentication information. However, if Bob happens to visit his bank shortly after that, his browser’s session with the bank’s web site has not expired, and the browser’s cookie contains Bob’s authentication information. The url request will be answered, and the money will be transferred from Bob’s account to Mallory’s, without Bob knowing it. When Bob later found that the money was missing, even if he checked the bank logs, he could only find that there was indeed a legitimate request from him to transfer the money, without any trace of attack. Mallory gets the money and gets away with it.

**CSRF attack instances **Copy the code

Daguanren (a senior official) has a sum of money in the bank, input his user name and password to log in to the bank’s online banking, and then send a request to transfer money to his account under his own name:

http://www.bank.example/withdraw?account=daguanren1&amount=999&for=daguanren2
Copy the code

Transfer 999 from daguanren1 to account daguanren2. After a user logs in, the system saves the session value (including the user’s mobile phone number and account number). However, if Daguanren accidentally opens a new TAB page and enters a hacker jinlian’s website, jinlian’s page contains the following HTML tags:

<! DOCTYPE html> <html> <! - other elements on the page - > < img SRC = http://www.bank.example/withdraw?account=daguanren1&amount=888&for=jinlian width = '0' height = '0' > <! -- Other page elements --> </ HTML >Copy the code

This request will be attached with Daguanren’s session value, and the 888 yuan of the senior official will be successfully transferred to Jinlian’s account. However, if Daguanren does not log in to e-bank before, but directly opens Jinlian’s website, it will not be attacked because there is no session value. Although the above example is a GET request, the form submitted by a POST request is also vulnerable.

<iframe style="display:none" name="csrf-frame"></iframe> <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>Copy the code

CSRF attack object

Before discussing how to defend against CSRF, it is important to know what CSRF attacks, that is, what you want to protect. As can be seen from the above examples, a CSRF attack means that the hacker uses the victim’s cookie (session) to win the trust of the server, but the hacker cannot get the cookie or see the content of the cookie. In addition, the result returned by the server cannot be parsed by the hacker due to the same origin policy of the browser. Therefore, the hacker gets nothing from the returned result, and all he can do is send a request to the server to execute the command described in the request, changing the value of the data directly on the server side, rather than stealing the data from the server. Therefore, we want to protect the services that can directly change the data, but for the services that read the data, CSRF protection is not required. For example, the transfer request in the banking system will directly change the amount of the account, which will be attacked by CSRF and need to be protected. However, the query balance is a reading operation of the amount, which does not change the data. CSRF attacks cannot parse the results returned by the server, so no protection is required.

Therefore, add, delete, and modify need to defend against CSRF attacks, but read (read database) need not defend.

 

For example

Simple version:

If the blogpark had a GET interface to follow, the blogUserGuid parameter would obviously be the Id of the person to follow, as follows:

http://www.cnblogs.com/mvc/Follow/FollowBlogger.aspx?blogUserGuid=4e8c33d0-77fe-df11-ac81-842b2b196315
Copy the code

I just need to put an IMG tag in one of my blog posts:

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

So as soon as someone opens my blog, it automatically follows me.

The upgrade version:

The blogosphere still has a focus interface, but it has restricted access to POST requests only. This time to make a third party page, but it contains the form submission code, and then spread through QQ, mailbox and other social tools to lure users to open, that opened the blog park users will be fooled.

To correct an iframe problem before going into the example, someone 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 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>Copy the code

Because of the same origin policy, the iframe content cannot be loaded at all, so the form submission will not be executed. PS: I’ve tried Chrome, IE11, Firefox, and it’s all the same.

So it can be solved by embedding one more layer of pages, as follows:

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>Copy the code

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>Copy the code

This would solve the problem of adding an extra layer of iframe, as pages without embedded iframe would be redirected, thus reducing the vulnerability of attacks. In addition, our Test page does not use XMLHTTPRequest to send POST requests because there are cross-domain issues, whereas forms can POST data across domains.

The advanced version:

If the blog park still has a focused interface that restricts posts, but the content is posted directly into HTML (unfiltered), then it is exposed to XSS attacks. You can embed the above code directly into a blog post, so that whenever someone opens my blog post, they will automatically follow me. This combination of attacks is called XSRF.

The essential cause of CSRF attacks

The CSRF attack is an implicit authentication mechanism from the Web! The Web’s authentication mechanism guarantees that a request is from a user’s browser, but it does not guarantee that the request was approved by the user. CSRF attacks are usually resolved by the server.

I have outlined the idea of CSRF attacks in general. Here I will use several examples to elaborate on specific CSRF attacks. Here I will use a bank transfer operation as an example (just an example, real bank websites are not so stupid :>).

Example 1:

Bank web site A, it to GET requests to complete the operation of the bank transfer, such as: www.mybank.com/Transfer.ph…

Dangerous web site B, which contains the following HTML code:

The < img src=www.mybank.com/Transfer.ph…

First, you log on to the bank’s website A, then to the dangerous website B, and oh, that’s when you find that your bank account is missing $1000……

Why is that? The reason is that bank website A violates the HTTP specification by using GET requests to update resources. Before visiting the dangerous website B, you have logged into the bank’s website A, and the bank’s website BRequest third party resources in the way of GET (the third party here refers to the bank website, originally this is A legitimate request, but here is used by criminals), so your browser will bring your bank website A Cookie to send A GET request, to obtain resources.www.mybank.com/Transfer.php? ToBankId =11&money=1000 “, the bank website server received the request, thought it was an update resource operation (transfer operation), so immediately conducted the transfer operation……

Example 2:

To eliminate the above problems, 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" /> < input type = "text" name = "money" / > < / p > < p > < input type = "submit" value = "Transfer" / > < / p > < / form >Copy the code

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 ']); }? >Copy the code

Dangerous site B, again, just contains the HTML code:

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

As in example 1, you log on to the bank’s website A, then to the risk website B, resulting in….. As in example 1, you again lose 1000 ~ T_T. The cause of this accident is: The bank background uses REQUEST to GET the requested data, and _REQUEST to GET the requested data, and _REQUEST can GET the data of both GET REQUEST and POST REQUEST. This makes it impossible for the daemon to distinguish between GET and POST request data. In PHP, you can use GET and _GET and GET and _POST to GET data for GET and POST requests, respectively. In JAVA, request, which is used to obtain request data, also has the problem of not distinguishing GET request data from POST data.

Example 3:

After the previous two painful lessons, the bank decided to change the method of obtaining the request data to $_POST, and only obtain the data of the POST request. The code of the background processing page transfer.php is as follows:

<? PHP \ session_start (); If (isset ($_POST [' toBankId] && isset ($_POST [' money '])) {buy_stocks ($_POST [' toBankId], $_POST [' money ']); }? >Copy the code

However, dangerous B has moved with The Times and changed its code:

< HTML > <head> <script type="text/javascript"> function Steal () {iframe = Document. The frames (" steal "); The 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>Copy the code

If the user continues with the above operation, unfortunately, the result will again be no 1000…… Because here dangerous website B secretly sent a POST request to the bank!

To sum up the above three examples, the main attack modes of CSRF are basically the above three, among which the first and second are the most serious, because the triggering conditions are very simple, oneThe third one is more troublesome and requires JavaScript, so there are fewer opportunities to use it, but in either case, CSRF attacks can be serious.

Understanding the above three attack modes, you can actually see that the CSRF attack is an implicit authentication mechanism derived from the WEB! The WEB’s authentication mechanism can guarantee that a request is from a user’s browser, but it can’t guarantee that the request is user-approved!

CSRF vulnerability detection:

 

Detection of CSRF vulnerability is a tedious work. The simplest method is to capture a normal request packet, remove the Referer field and then resubmit it. If the submission is still valid, it can basically confirm the existence of CSRF vulnerability.

With the deepening of CSRF vulnerability research, some special CSRF vulnerability detection tools have emerged, such as CSRFTester, CSRF Request Builder and so on.

Taking CSRFTester as an example, the test principles of CSRF vulnerability detection tool are as follows: When testing with CSRFTester, we first need to grab all the links we visited in the browser, all the forms and other information, and then resubmit by modifying the corresponding forms and other information in CSRFTester, which is equivalent to a forged client request. If the modified test request is successfully accepted by the website server, the CSRF vulnerability exists. Of course, this tool can also be used to carry out CSRF attacks.

 

 

Current strategies to defend against CSRF:

 

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

  1. Validate the HTTP Referer field;
  2. Add token to request address and verify;
  3. Customize and validate properties in HTTP headers;
  4. The SameSite cookie is enabled on Chrome

 

(1) Verify the HTTP Referer field

What is HTTP Referer? The following GIF is the Referer of baidu’s jump to QQ mailbox page:

It can be seen that the Referer is

Referer:https://www.baidu.com/
Copy the code

According to the HTTP protocol, there is a field in the HTTP header called Referer that records the source address of the HTTP request. Typically, a request to access a security-restricted page comes from the same website, such as the need to access bank.example/withdraw? Ac… Bank.example, and then trigger the transfer event by clicking the button on the page. In this case, the Referer value of the transfer request will be the URL of the page where the transfer button is located, usually starting with the bank.example domain name. If a hacker wants to carry out 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 is directed to the hacker’s own website. Therefore, to defend against CSRF attacks, bank websites only need to verify the Referer value of each transfer request. If the domain name starts with bank.example, it indicates that the request is from the bank website itself and is legitimate. If the Referer is any other site, it could be a CSRF attack by a hacker to reject the request.

The obvious benefit of this approach is that it is so simple that the average developer of a site doesn’t have to worry about CSRF vulnerabilities, just adding a single 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, 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, the specific implementation of the Referer by each browser may be different, and there is no guarantee that the browser itself is free of security vulnerabilities. The method of verifying the Referer value relies on the security of a third party (i.e. the browser), which in theory is not secure. In fact, for some browsers, such as IE6 or FF2, there are already ways to tamper with the Referer value. If the bank.example site supports Internet Explorer 6, the hacker could have set the Referer value of the user’s browser to an address that starts with the bank.example domain name, so that it can be verified and CSRF attacks can be carried out.

Even with the latest browsers, hackers can’t tamper with the Referer value, which is problematic. Because Referer records the source of the user’s access, some users feel that this will violate their privacy, especially some organizations concerned that the Referer value will leak some information from their internal network to the external network. Therefore, users themselves can set the browser to no longer provide Referer when sending requests. When they visit the bank’s website normally, the website will consider the request as a CSRF attack because it does not have the Referer value and deny the access to legitimate users.

In addition, if the Referer’s judgment logic is not strict, it is also easy to be breached, for example

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

If the hacker’s web site is www.bank.example.hack.com, check invalid referer.

(2) Add token to request address and verify

The reason why CSRF attack can be successful is that the hacker can completely forge the user’s request, and all the user authentication information in the request is stored in the cookie, so the hacker can directly use the user’s cookie to pass the security authentication without knowing the authentication information. The key to defending against CSRF is to put information in the request that a hacker cannot forge and that does not exist in a cookie. A randomly generated token can be added to the HTTP request as a parameter, and an interceptor can be established on the server side to verify the token. If there is no token in the request or the token content is incorrect, the request may be rejected as a CSRF attack.

This is more secure than checking the Referer. Tokens can be generated after the user logs in and placed in the session, and then taken out of the session on each request and compared with the tokens in the request. The difficulty with this approach, however, is how to add tokens to the request as parameters. For GET requests, the token is appended to the request address so that the URL becomes

http://url?csrftoken=tokenvalue
Copy the code

For POST requests, add it at the end of the form

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

One drawback of this method is that it is difficult to guarantee the security of the token itself. Especially in some forums and other websites that support users to publish their own content, hackers can publish their own personal website address. Since the system also adds a token to the address, the hacker can get the token on his own website and launch a CSRF attack right away. In order to avoid this, the system can add a judgment when adding the token, if the link is linked to their own site, add the token later, if it is to the Internet, do not add. However, even if the CSRFtoken is not attached to the request as a parameter, a hacker’s site can also obtain the token value via the Referer to launch a CSRF attack. This is why some users prefer to turn off the browser Referer manually.

 

(3) Customize attributes in HTTP headers and validate them

This method also uses the token and validates it. Unlike the previous method, instead of placing the token in the HTTP request as a parameter, it places it in a custom attribute in the HTTP header. With the XMLHttpRequest class, you can add the CSRFToken HTTP header attribute and put the token value into all of the class requests at once. This eliminates the inconvenience of adding the token to the request in the previous method, and the XMLHttpRequest address is not logged in the browser’s address bar, and the token is not leaked to other sites through the Referer.

However, this approach has significant limitations. XMLHttpRequest is usually used for asynchronous partial page refresh in Ajax methods. Not all requests are suitable to be initiated with this class, and the page obtained through this class cannot be recorded by the browser, thus making it inconvenient for users to move forward, backward, refresh, and save. In addition, for legacy systems without CSRF protection, this approach to protection requires that all requests be converted to XMLHttpRequest requests, which is almost an entire web site rewrite, an unacceptable cost.

**4. Enable SameSite cookie** on ChromeCopy the code

Here’s how to enable the SameSite cookie Settings. It’s easy.

The original Cookie header would look like this:

Set-Cookie: session_id=esadfas325
Copy the code

Add SameSite to the end:

Set-Cookie: session_id=esdfas32e5; SameSite
Copy the code

SameSite has two modes: Lax and Strict. Strict mode is enabled by default. You can specify the mode by yourself:

Set-Cookie: session_id=esdfas32e5; SameSite=Strict
Set-Cookie: foo=bar; SameSite=Lax
Copy the code

Strict mode specifies that cookies are only allowed for the same site and should not be added to any cross site request. The A tag, form, and XMLHttpRequest submissions do not carry cookies as long as they are submitted to a different site.

But there are inconveniences, such as clicking on a link to a page I’ve already logged into when a friend sends me a link.

There are two approaches. The first is to prepare two different sets of cookies, just like Amazon. The first group is used to maintain the login status without setting SameSite, and the second group is used to set SameSite strictly for sensitive operations (such as buying, paying, setting up accounts, etc.).

This idea led to another pattern for SameSite: the Lax pattern.

The Lax mode opens some restrictions, for example

<a>
<link rel="prerender">
<form method="GET">
Copy the code

These all have cookies on them. But the FORM of the POST method, or as long as it’s a POST, PUT, or DELETE method, doesn’t take a cookie.

Be sure to change the important request mode to POST, otherwise GET will still be attacked.

PS: This mode is supported only by Chrome.



CSRF tool defense means

1. Use POST instead of GET

The GET interface is too easy to use for CSRF attacks, as the first example shows, simply by constructing an IMG tag, which is unfiltered data. You are advised to limit the use of the interface to POST. GET is invalid to reduce attack risks.

Of course, POST is not foolproof. An attacker can simply create a form, but it needs to be done on a third-party page, which increases the possibility of exposure.

2. Cookie policy of the browser

By default, Internet Explorer 6, 7, 8, and Safari block sending third-party local cookies. However, Firefox2, 3, Opera, Chrome, and Android do not block CSRF attacks, so using the browser Cookie policy to defend against CSRF attacks is not reliable, but can only reduce the risk.

PS: Cookies are divided into two types: Session cookies (which expire after the browser closes and are saved in memory) and third-party cookies (which expire after the Exprie time and are saved locally).

PS: In addition, if the web site returns an HTTP Header containing the P3P Header, it will allow the browser to send third-party cookies.

3. Add the verification code

A verification code that forces the user to interact with the application before completing the final request. In general, captchas are good at deterring CSRF attacks. But for the sake of user experience, sites can’t add captcha codes to all operations. Therefore, captchas can only be used as an auxiliary means, not as the main solution.

4. Referer Check

The most common use of Referer Check on the Web is to prevent image theft. In the same way, the Referer Check can be used to Check whether the request is coming from a legitimate “source” (whether the Referer value is the specified page, or the domain of the site), and if neither is, it is most likely a CSRF attack.

However, because the server does not always have access to the Referer, it cannot be used as a primary means of CSRF defense. However, Referer Check is a feasible method to monitor the occurrence of CSRF attacks.

5. Anti CSRF Token

Now the industry defense against CSRF, the consistent approach is to use a Token (Anti CSRF Token).

Example:

  1. A user visits a form page.

  2. The server generates a Token and places it in the user’s Session or in the browser’s Cookie.

  3. Attach the Token parameter to the page form.

  4. After a user submits a request, the server verifies whether the Token in the form is the same as the Token in the user Session (or Cookies). If the Token in the form is the same, the request is valid. If the Token in the form is not invalid, the request is invalid.

The value of this Token must be random and unpredictable. Because of the Token, the attacker can no longer construct a request with a valid Token to carry out a CSRF attack. In addition, when using tokens, you should pay attention to the confidentiality of tokens. Try to change sensitive operations from GET to POST and submit them in form or AJAX to avoid Token disclosure.

Note:

CSRF tokens are only used to defend against CSRF attacks. When the site also has XSS vulnerability, then this solution is also empty. Therefore, XSS problems should be solved using XSS defense solutions.

conclusion

The anti-CSRF Token is used to defend against CSRF attacks. The security and randomness of the Token must be considered.

Code sample

 

The following JAVA code examples are excerpted from this article on how to deal with CSRF attacks

The first three methods are illustrated in code below. Regardless of the method used, an interceptor on the server side is essential, which checks the incoming request for compliance and then decides whether to continue or discard the request based on the result. In Java, interceptors are implemented by filters. We can write a Filter and configure it in web.xml to intercept requests for access to all resources that need CSRF protection. The Referer validation code for the request in the filter is as follows

Listing 1. Validate the Referer in the Filter

String Referer = request.getheader ("Referer"); If ((Referer! = null) && (referer. The trim (). The startsWith (" bank. Example "))) {chain. DoFilter (request, response); } else {request. GetRequestDispatcher (" error. JSP "). The forward (request, response); }Copy the code

The above code gets the Referer value, evaluates it, and if it is non-empty and starts with bank.example, continues the request, otherwise it could be a CSRF attack and go to the error.jsp page.

To further verify the token value in the request, the code is as follows

Listing 2. Validate the token in the request in filter

HttpServletRequest req = (HttpServletRequest)request; HttpSession s = req.getSession(); // Get the csrfToken attribute from session. String sToken = (String) s.get_attribute (" csrftoken "); If (sToken == null){// Generate a new token into the session sToken = generateToken(); S.s etAttribute (" csrftoken, "sToken); chain.doFilter(request, response); } else{// Get csrfToken from HTTP header String xhrToken = req.getheader (" csrftoken "); PToken = req.getParameter(" csrfToken "); if(sToken ! = null && xhrToken ! = null && sToken.equals(xhrToken)){ chain.doFilter(request, response); }else if(sToken ! = null && pToken ! = null && sToken.equals(pToken)){ chain.doFilter(request, response); } else {request. GetRequestDispatcher (" error. JSP "). The forward (request, response); }}Copy the code

First, check whether there is a CSRftoken in the session. If there is no cSRFtoken in the session, it is considered as the first access and the session is newly established. In this case, a new token is generated, placed in the session, and the request continues to be executed. If there is a cSRFToken in the session, then the user has established an active session with the server. If there is a cSRFToken in the session, then the user has established an active session with the server. We try to get the CSRFToken parameter from the request and the cSRFToken custom attribute from the HTTP header respectively and compare it with the value in the session. As long as there is a valid token in one place, the request is judged to be valid and can continue to execute, otherwise we will go to the error page. There are many ways to generate tokens, and any random algorithm can be used. Java’s UUID class is also a good choice.

In addition to using filter to verify the token value on the server side, we also need to append the token to each request on the client side, which uses JS to append cSRFToken code to the link and form request address in HTML, where token has been defined as a global variable. The value can be obtained from session.

Listing 3. Attach tokens to requests on the client side

var plainXhr = dojo.xhr; . / / rewrite the dojo XHR method dojo XHR = function (method, args, hasBody) {/ / make sure the header object exists the args. The headers = args. The header | | {}; tokenValue = '<%=request.getSession(false).getAttribute("csrftoken")%>'; var token = dojo.getObject("tokenValue"); Args. headers["csrftoken"] = (token)? token : " "; return plainXhr(method,args,hasBody); };Copy the code

This overwrites the dojo. XHR method by first ensuring that dojo. XHR has HTTP headers, then adding the CSRFToken field to args.headers and taking the token value out of the session and putting it in the field.

PHP code please refer to this article on CSRF attack mode

conclusion

Based on the above analysis, the most convenient way at present is to directly discriminate the Referer value to ensure that the same-domain request is allowed. In most cases, XmlHttpRequest is not appropriate. Tokens can only be used as parameters in requests. If your system does not support user Posting, this level of protection is sufficient. It’s still hard to prevent your tokens from being stolen and attacked by hackers. In this case, you need to carefully plan the various services provided by your website, identify the parts that allow users to publish their own information, separate them from other services, and use different tokens to protect them, so that you can effectively prevent hackers from attacking your key services and minimize the harm.

If you are developing an entirely new system, the options for resisting CSRF are much greater. I recommend that you use XMLHttpRequest to access important services as much as possible, which makes it much easier to add tokens. Also try to avoid using complex logic in JS code to construct regular synchronous requests to access CSRF protected resources such as window.location and document.createElement(” a “). This can also reduce unnecessary hassle when attaching tokens.

Finally, keep in mind that CSRF is not the only means of attack for hackers. No matter how well protected you are against CSRF, if you have other security vulnerabilities, such as cross-site scripting against XSS, then hackers can bypass your security and carry out various attacks, including CSRF, and your defenses will be useless.

The resources

 

1. Discussion on CSRF Attack Mode

2. White Hat on Web Security

  • Wikipedia CSRF, here is a more comprehensive introduction to CSRF. En.wikipedia.org/wiki/Cross-…
  • CSRFGuard, an open source project, describes how to defend against CSRF by adding tokens to HTTP requests and verifying them. www.owasp.org/index.php/C…
  • Robust confident for cross-site Request Forgery: analyzed some commonly used CSRF resistance methods and creatively proposed browser enhancement solutions.
  • DeveloperWorks Web Development Zone: Expand your Web development skills with articles and tutorials dedicated to Web technologies.
  • DeveloperWorks Ajax Resource Center: This is a one-stop center for information on the Ajax programming model, including numerous documents, tutorials, forums, blogs, wikis, and news. Any new Ajax information can be found here.
  • DeveloperWorks Web 2.0 Resource Center, a one-stop center for Web 2.0-related information, includes a wealth of Web 2.0 technical articles, tutorials, downloads, and related technical resources. You can also quickly learn about Web 2.0 concepts through the Getting Started Web 2.0 section.
  • Check out HTML5 Topics for more information and trends related to HTML5.
  • Discussion on CSRF attack mode
  • CSRF attack response
  • Let’s talk about CSRF