Principles and practical combat of CSRF vulnerabilities in network security, as well as CSRF vulnerability protection methods

1. Introduction

Generally speaking, CSRF is a deceptive behavior and a malicious use of a website. Although it sounds like cross-site scripting (XSS), it is very different from XSS, and the attack method is almost the same. XSS exploits trusted users within a site, while CSRF exploits trusted websites by disguising requests from trusted users. Generally, the combination of CSRF and XSS is more dangerous. This kind of attack has the greatest impact or loss on the victim, but poses little threat to the attacked website itself.
CSRF is generally divided into: HTML CSRF, JSON HiJacking and Flash CSRF

2. Principle of CSRF vulnerability

A cross-site request attack, simply put, is when an attacker uses some technical means to trick the user’s browser into accessing 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). )
The following is a scenario for attack engineering simulation:

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 receiving the user request, website B returns some offensive code and sends 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.

The whole process is as shown below:
csrf attack process
From this attack process, we can know that the prerequisite for the attack is that the user has logged in to site A and recorded the cookie locally, and the user has not exited site A, and the token or session of site A has not expired. Secondly, site A has not Do any CSRF defenses.
In order to facilitate understanding, let us first enumerate a scenario
Scenario requirements:
Xiao Hei wants to modify the membership address that Da Bai filled in on the shopping website tianxiewww.xx.com.
Let’s take a look at how Dabai changed his password:
Log in-modify member information, submit request-modification successful.
So if Xiao Hei wants to modify Da Bai’s information, he needs to have: 1. Login permission 2. A request to modify personal information.
But Dabai will not tell Xiaohei his account and password for the xxx website, so what should Xiaohei do?
So he went to www.xx.com to register an account of his own, and then modified his personal information (for example: E-mail address). He found that the modification request was:
【http://www.xxx.com/[email protected] &Change=Change】
So, he carried out such an operation: disguise the link, and trick Xiaobai into clicking after logging into the xxx website. After Xiaobai clicked on the link, his personal information was modified, and Xiaohei completed the attack purpose.
Why is Xiaohei’s operation possible? There are several key points as follows:
1. The website www.xxx.com does not perform excessive verification when users modify personal information, making this request easily forged;
-Therefore, when we determine whether a website has a CSRF vulnerability, we actually determine whether its operations (additions, deletions, modifications) on key information (such as passwords and other sensitive information) are easily forged.
2. Xiaobai clicked on the link sent by Xiaohei, and Xiaobai happened to be logged in to the shopping website at this time;
-If Xiaobai has high security awareness and does not click on unknown links, the attack will not be successful, or even if Xiaobai clicks on the link, but Xiaobai is not logged in to the shopping website at this time, it will not succeed.
-Therefore, to successfully implement a CSRF attack, the conditions of “time, location, and people” are required.
Of course, if Xiaohei discovers an XSS vulnerability on the homepage of the xxx website in advance, Xiaohei may do this: trick Xiaobai into accessing the page where XSS scripts (scripts that steal cookies) are hidden, and Xiaobai is fooled. Hei gets Xiaobai’s cookie, and then Xiaohei successfully logs into Xiaobai’s backend, and Xiaohei modifies Xiaobai’s relevant information by himself.
-So by comparing with the above, you can see the difference between CSRF and XSS: CSRF uses the user’s permissions to complete the attack. The attacker does not get the user’s permissions, while XSS directly steals the user’s permissions< /strong>, and then carry out the destruction.
Therefore, if a website wants to prevent CSRF attacks, it needs to implement corresponding security measures for the operations of sensitive information to prevent these operations from being forged, resulting in CSRF. for example:
–Add secure tokens for operations on sensitive information;
– Add secure verification codes for operations on sensitive information;
– Implement secure logic processes for operations on sensitive information. For example, when changing a password, the old password needs to be verified first.
If you don’t understand it clearly, don’t hesitate to read it again.
Next we try different types of CSRF attack processes:

3. Types of CSRF vulnerabilities

Before the start of the program, I recommend a better place for CSRF practice: Pikachu vulnerability platform. If you are a Web penetration tester and are worried about not having a suitable shooting range to practice, then Pikachu may be what you want. You need to download it and then do it yourself Let’s set up the steps to build the Pikachu vulnerability platform.

After setting up, it looks like above

3.1. GET type CSRF attack

Sending get requests, usually when we write code, we usually send get requests, such as clicking on the a tag, img tag of html, or actively constructing parameters to send get requests. All Get request parameters will be spliced into the url. Above, so the attack can be completed by simply constructing the URL. Next we will demonstrate the CSRF GET attack on the Pikachu vulnerability platform
Step 1. Open Pikachu and select the csrf in get mode.
The second step is to log in to any account: vince/allen/kobe/grady/kevin/lucy/lili. The password is 123456. For example, log in to lili, and then use burpsuite to capture the data packets that modify personal information, or F12 to open the console switch. Go to Network to capture packets
The third step is to change the request parameters of the captured URL to our own, for example, change the email parameter to [email protected], then the resulting CSRF attack payload is

http://127.0.0.1/pikachu/vul/csrf/csrfget/csrf_get_edit.php?sex=boy & amp;phonenum=18626545453 & amp;add=chain & amp;[email protected] & amp ;submit=submit


The user’s unique login identifier here is the string of values in PHPSESSID.

If the user clicks on the forged URL above, the user’s own email will be changed to [email protected], which completes a CSRF attack.
Please add image description
In the same way, the user name and password of the victim user can be changed, and the attacker can log in to the victim’s account. From this example, you may see that the account lili changed the email address to [email protected], but If the CSRF attack cooperates with the XSS attack, then the user first obtains the victim’s cookie/token through the XSS attack, such as the PHPSESSID in the above question, and then constructs a new request with the cookie information or token information for login authentication, then isn’t it? The harm is increased.

3.2. POST CSRF attack

Although POST requests cannot be attacked by forging URLs, you can forge malicious web pages, hide the forged POST requests in the form of the malicious web page, and then induce the user to click the button to submit the form, and the data will naturally be POSTed to the web page with CSRF vulnerabilities. End user information will be modified

Run the CSRFTESTER tool here to create a malicious web page. First, configure the network proxy in the browser to listen to the 8008 port of the machine, and then click Start Recording on CSRFTESTER to start capturing packets.

After catching the data packet that modifies personal information, delete other data except the POST request in CSRFTESTER, change the type to POST, and then click Generate HTML below to generate the HTML file

Find the generated HTML file and edit it. Modify the following line to, and then you can set other POST parameters yourself. Here I modified the phone number to 999999999

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
<title>OWASP CRSFTester Demonstration</title>
</head>

<body onload="javascript:fireForms()">
<script language="JavaScript">
var pauses = new Array( "30" );

function pausecomp(millis)
{<!-- -->
    var date = new Date();
    var curDate = null;

    do {<!-- --> curDate = new Date(); }
    while(curDate-date < millis);
}

function fireForms()
{<!-- -->
    var count = 1;
    var i=0;
    
    for(i=0; i<count; i + + )
    {<!-- -->
        document.forms[i].submit();
        
        pausecomp(pauses[i]);
    }
}
    
</script>
<H2>OWASP CRSFTester Demonstration</H2>
<form method="POST" name="form0" action="http://127.0.0.1:80/pikachu/vul/csrf/csrfpost/csrf_post_edit.php">
<input type="hidden" name="sex" value="girl"/>
<input type="hidden" name="phonenum" value="999999999"/>
<input type="hidden" name="add" value="chain"/>
<input type="hidden" name="email" value="[email protected]"/>
<input type="submit" name="submit" value="submit"/>
</form>

</body>
</html>

Open the generated malicious web page in the browser, and when the user clicks the submit button, the user’s personal information will be modified.
Please add image description

4. Protection methods for CSRF vulnerabilities

4.1 Verify HTTP Referer field

According to the HTTP protocol, there is a field called Referer in the HTTP header, which records the source address of the HTTP request. Typically, requests to access a secure restricted page originate from the same website. 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 its Referer value for 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.
Disadvantages: It is too simple and can be easily cracked.

4.2 TOKEN verification

The main reason for CSRF vulnerabilities is that data packets requesting sensitive operations are easily forged. In fact, as long as a random code (Token) is added to each request, the backend must process this random code every time the front-end and back-end interact with each other. Code verification to protect against CSRF attacks
Check the source code of token_get_edit.php and find that there is a set_token() function. This function is called every time the page is refreshed. Then the token in the SESSION is destroyed, and a new token is generated and sent to the front-end form.

<div id="per_info">
   <form method="get">
   <h1 class="per_title">hello,{$name},Welcome to the personal member center | <a style="color:bule;" href="token_get.php?logout=1">Log out</a> </h1>
   <p class="per_name">Name:{$name}</p>
   <p class="per_sex">Gender:<input type="text" name="sex" value="{$sex}"/></p>
   <p class="per_phone">Mobile phone:<input class="phonenum" type="text" name="phonenum" value="{$phonenum}"/></p>
   <p class="per_add">Address:<input class="add" type="text" name="add" value="{$add}"/></p>
   <p class="per_email">Email:<input class="email" type="text" name="email" value="{$email}"/></p>
       
   <input type="hidden" name="token" value="{$_SESSION['token']}" />
       
   <input class="sub" type="submit" name="submit" value="submit"/>
   </form>
</div>

Every time a form is submitted, the token value of the front-end page will be sent to the backend for comparison and verification with the token in the SESSION. Since hackers do not know the user’s current token value, they cannot conduct CSRF attacks.

4.3. Customize attributes and verify in HTTP headers

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 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.

4.4. Using SameSite Cookie attributes

CSRF attacks use user information carried in cookies. To protect cookies from being used by third-party websites, we can set the Samesite attribute. SameSite was originally designed to prevent CSRF. SameSite has three values: Strict/Lax/None.

(1) Strict is the most stringent. If the value of SameSite is Strict, the browser will completely prohibit third parties.

Set-Cookie: SID=312556; SameSite=Strict; Secure; HttpOnly; Path=/

(2) Lax is relatively loose. In the case of cross-site, both opening the link from the third-party site and submitting the Get method form from the third-party site will carry cookies. However, if the Post method is used in a third-party site, or the URL is loaded through tags such as img and iframe, cookies will not be carried in these scenarios.

Set-Cookie: foo=bar; SameSite=Lax; Domain=example.com; Path=/

(3) If None is used, Cookie data will be sent in any case.
Setting method one, tomcat8 and above, add a child node to the node in the /conf/context.xml file

<Context>
   <CookieProcessor sameSiteCookies="lax" />
</Context>

Method two, in the java code, ask for filtering

 String cookieHeader = req.getHeader("Cookie");
        if(cookieHeader != null) {
        String[] cookiesHeaders = cookieHeader.split(";");
             boolean firstHeader = true;
         for (String header : cookiesHeaders) {
         header = header.trim();
         if(header != null) {
         String[] headStr = header.split("=");
             if(headStr[0].equals("name") & amp; & amp;firstHeader) {
             firstHeader = false;
             resp.setHeader("Set-Cookie", String.format("%s; %s", header, "Path=/;HttpOnly=True;Secure=true;SameSite=Lax;"));
             }
         }
              }
        }

4.5. Use double cookie verification (similar to token mechanism)

When a user submits certain requests to the website through a page form, the server will verify 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 legitimate request, otherwise the request is illegal. The value of this Token must be random and unpredictable. Due to the existence of Token, the attacker can no longer construct a request with a legal Token to implement a CSRF attack. The subdomain problem mentioned by the questioner can be partially solved by using Token.

4.6. Use verification code for human-machine identification

Verification codes are considered the most concise and effective defense method against CSRF attacks.
The process of a CSRF attack often involves constructing a network request without the user’s knowledge, and the verification code forces the user to interact with the application to complete the final request. However, many times, due to user experience considerations, websites cannot add verification codes to all operations. Therefore, verification codes can only be used as an auxiliary means to defend against CSRF, but not as the main solution.

4.7. Other protective measures

Set up a session management mechanism, for example, if there is no operation for 15 minutes, you will automatically log out.
Modifying sensitive information requires secondary verification of the ID card. For example, when changing the password, you need to enter the old password.
Modify sensitive information using POST requests instead of GET requests

5. Summary

The above content is how to learn and exploit CSRF vulnerability attacks. CSRF attacks are very harmful to users. On the one hand, we should not easily go to unknown websites and click on unknown links. On the other hand, we need to understand the principles behind them. If you don’t quite understand it or have other ideas, you can send me a private message or type it in the comment area. Please forgive me if there is anything wrong with what I wrote.

syntaxbug.com © 2021 All Rights Reserved.