CSRF vulnerability principle attack and defense (very detailed)

CSRF vulnerability principle attack and defense

Directory

  • CSRF vulnerability principle attack and defense
  • 1. What is CSRF?
  • 2. CSRF attack principle and process
  • 3. CSRF classification
    • 1. GET type CSRF
    • 2. POST type CSRF
  • 4. Digging of CSRF vulnerabilities
  • 5. Defense against CSRF vulnerabilities
    • 1. Verification code
    • 2. Add token to the request address and verify it
    • 3. Customize attributes in HTTP headers and verify
    • 4. Verify HTTP Referer field
  • Summarize

Tips: The following is the text of this article, the following cases are for reference

1. What is CSRF?

CSRF (Cross-site request forgery), also known as One Click Attack or Session Riding, often abbreviated as CSRF or XSRF, is a malicious use of a website. Although it sounds like cross-site scripting (XSS), it is very different from XSS, which exploits trusted users within a site, while CSRF makes requests to trusted websites by masquerading as a trusted user.

Simply put, the attacker uses some technical means to trick the user’s browser into visiting a site that he has previously authenticated and perform some operations (such as sending emails, sending messages, and even property operations (such as transferring money and purchasing goods)). Because the browser has been authenticated before, the visited site will think that this is a real user operation and run it.

2. CSRF attack principle and process

Why can CSRF attack successfully?

The essential reason is that all parameters of important operations can be guessed by the attacker.

Only by predicting all parameters and parameter values of the URL can the attacker successfully construct a forged request; otherwise, the attacker will not be able to successfully attack.

As can be seen from the above figure, to complete a CSRF attack, the victim must complete two steps in sequence:

 Log in to trusted site A and generate cookies locally.

        Access critical site B without logging out of A.

1. The client logs in to website A through the account and password.
2. Website A verifies the client’s account and password. If successful, a sessionld is generated and returned to the client to be stored in the browser.
3. The client visited website B on a new page.
4. Website B automatically triggers a request for the client to access website A. (That is, there is a link in website B pointing to website A)
5. The client accesses website A through the link in website B. (At this time, carry the legal SessionID to access station A)
6. At this time, website A only needs to check whether sessionIld is legal, and if it is legal, perform the corresponding operation. (So the specific tool depends on the link and the data carried by website B when requesting access)

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.

3. CSRF classification

CSRF (Cross-Site Request Forgery), like XSS vulnerability attacks, is extremely harmful.

You can understand it this way: the attacker has stolen your identity and sent a malicious request in your name. To the server, this request is completely legal, 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, virtual currency transfers, etc.

1. GET type CSRF

1.GET type CSRF

Only one HTTP request is required. You can construct a simple CSRF.

Example:

Bank site A: It uses a GET request to complete the bank transfer operation, such as:

http://www.mybank.com/Transfer.php?toBankId=11 & amp;money=1000

Dangerous site B: It contains a piece of HTML code such as the following:

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

first. You log in to bank site A and then visit dangerous site B. Oh, then you will find that your bank account is missing 1,000 yuan.

Why is this so? The reason is that bank site A violates the HTTP specification and uses GET requests to update resources.

Before visiting dangerous site B. You have logged into bank site A, and there is a legitimate request in B, but it has been exploited by criminals).

So your browser will bring the cookie of your bank site A to issue a Get request to obtain resources and request third-party resources in the GET method (the third party here refers to the bank site).

Originally this was:

http://www.mybank.com/Transfer.php?toBankId=11 & amp;money=1000

As a result, after the bank site server received the request, it felt that this was a resource update operation (transfer operation), so it immediately performed the transfer operation.

2. POST type CSRF

At the beginning of the popularity of CSRF attacks, there was a wrong view that CSRF attacks could only be initiated by GET requests. Therefore, many developers believe that CSRF attacks can be prevented by changing important operations to only allow POST requests.

The main reason for this misconception is that when most CSRF attacks are launched, the HTML tags used are,,

For many website applications, some important operations do not strictly distinguish between GET and POST. Attackers can use GET to request the form submission address. For example, in PHP, if you use

_

R

E

Q

U

E

S

T

, rather than

\_REQUEST instead of

_REQUEST instead of _POST to obtain variables will have this problem.

For a form, users can often submit parameters using GET. For example, the following form:

<form action=" / register" id="register" method="post" >
<input type=text name="username" value="" />
<input type=password name="password" value="" />
<input type=submit name="submit" value="submit" />
</form>


Users can try to construct a GET request

http: //host/register?username=test & amp;password=passwd

To submit, if the server does not restrict the request method, the request will pass.

If the server has distinguished GET and POST, what method does the attacker have? For an attacker, there are several methods to construct a POST request.

The simplest method is to construct a form on a page and then use JavaScript to automatically submit the form. For example, the attacker writes the following code in www.b.com/test.html:

<form action="http: / / www . a.com/register" id="register" method="post" ><input type=text name="username" value=""/>
<input type=password name="password" value=""/><input type=submit name="submit" value="submit"/></ form>
<script>
var f = document.getElementById ("register");
f.inputs [0].value = "test";
f.inputs [1].value = "passwd" ;
f.submit();
</script>


An attacker can even hide this page in an invisible iframe window, so the entire process of automatically submitting the form is invisible to the user.

During the Gmail CSRF vulnerability attack in 2007, security researcher pdp demonstrated this technique. First, the user needs to log in to the Gmail account so that the browser can obtain Gmail’s temporary cookie.

User logs into Gmail

The attacker then tricks the user into visiting a malicious page.


Attackers trick users into visiting malicious pages

In this malicious page, an iframe is hidden, and the address of the iframe points to the CSRF structure page written by pdp.

http: //www.gnucitizen.org/util/csrf?_method=POST & amp;_enctype=multipart/form-data & amp;_action=https://mail.google.com/mail/h/ewtljmuj4ddv /?v=prf & amp;cf2_emc=true & amp;cf2_email=evilinboxmailinator.com & amp;cfl_from & amp;cfl_toucf1_subjicf1_has & amp;cfl_hasnotscf1_attach=truestfi & amp;S=z & amp;irf=on & amp;nvp bu_cftb =Create Filter

The actual function of this link is to generate a POST form from the parameters and automatically submit it.
Since Gmail’s temporary cookie already exists in the browser, the user’s request to Gmail in the iframe will succeed – a new rule will be created in the mailbox’s Filter to forward all emails with attachments to the attacker’s mailbox. middle.

The malicious site creates a rule in the user’s Gmail via CSRF.

If the above example is still a bit confusing, let’s give another example:

In the eyes of ordinary users, clicking on a webpage -> opening a preview video -> purchasing a video is a very normal process. However, in the eyes of attackers, it can be considered normal but not normal. Of course, abnormal situations are caused by developers’ lack of security awareness. The attacker caught the address where the website processes the purchase (deducts) the user’s balance at the time of purchase.

for example:

/coures/user/handler666buy.php</font>

By submitting the form, buy.php processes the purchase information, where 666 is the video ID. The attacker now constructs a link containing the following content.

<form action=/coures/user/handler/666/buy method=POST>
<input type="text" name="xx" value="xx" />
</form>
<script> document.forms[0].submit(); </script>

When the user visits this page, the form will be automatically submitted, which is equivalent to simulating the user to complete a POST operation and automatically purchase the video with ID 666, resulting in the victim’s balance being deducted.

4. Mining CSRF vulnerabilities

1. The simplest method is to capture a normal request data packet. If there is no Referer field and token, then there is a high possibility of a CSRF vulnerability.

2. If there is a Referer field, but the Referer field is removed and then resubmitted, if the submission is still valid, then it is basically certain that there is a CSRF vulnerability.

3. 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 the links we have visited in the browser and all forms and other information, and then modify the corresponding form and other information in CSRFTester and resubmit. This 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.

5. Defense against CSRF vulnerabilities

1. Verification code

Verification codes are considered the most concise and effective defense method against CSRF attacks.

The process of CSRF attack often constructs network requests without the user’s knowledge. The verification code forces the user to interact with the application to complete the final request. Therefore, under normal circumstances, verification codes can effectively contain CSRF attacks.

But the verification code is not a panacea. Many times, due to user experience considerations, websites cannot add verification codes to all operations. Therefore, the verification code can only be used as an auxiliary means to defend against CSRF, but not as the main solution.

2. Add token to the request address and verify it

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 own cookie without knowing the verification information. to pass security verification.

The key to resisting CSRF is to put information in the request that hackers cannot forge, and this 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, so that the token is added to the request as a parameter.

However, in a website, there are many places where requests can be accepted. It is very troublesome to add a token to each request, and it is easy to miss. The commonly used method is to use javascript to traverse every time the page is loaded. For the entire dom tree, tokens are added after all a and form tags in the dom.

This can solve most requests, but for html code that is dynamically generated after the page is loaded, this method has no effect and requires programmers to manually add tokens when coding.

Another 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 website, add the token later. If it leads to the external network, it will not be added.

However, even if the csrftoken is not attached to the request as 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.

3. Customize attributes in HTTP headers and verify them

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 used by the browser. Record so that operations such as forward, backward, refresh, and collection can be performed, causing 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. 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. Under normal circumstances, the request to access a secure restricted page comes from the same website, for example, you need to visit:

http://bank.example/withdraw?account=bob & amp;amount=1000000 & amp;for=Mallory

The user must first log in to bank.example and then trigger the 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 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.

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.

The method of verifying the Referer value relies on the third party (i.e. the browser) to ensure security. Theoretically, 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, this approach is still problematic. 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 from the organization’s intranet to the external network.

Therefore, users themselves can set their browsers so that they no longer provide a Referer when sending requests. 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.

Summary

A CSRF attack is an attack method in which an attacker uses the user’s identity to operate a user account. When designing a CSRF defense solution, you must first understand the principles and nature of CSRF attacks. We usually use Anti CSRF Token to defend against CSRF attacks. When using Token, we must pay attention to the confidentiality and randomness of Token.

Network Security Engineer (White Hat) Enterprise Level Learning Route

Phase 1: Security Basics (Getting Started)

img

The second stage: Web penetration (junior network security engineer)

img

The third stage: Advanced part (intermediate network security engineer)

img

If you are interested in getting started with network security, you can click here if you need it Big benefits of network security: Getting started & advanced full set of 282G learning resource package to share for free!

Learning resource sharing

The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly

There are three ways to learn network security technology:

The first is to apply for the cybersecurity major, now called the cyberspace security major. The main professional courses are: programming, computer composition principles, data structures, operating system principles, database systems, computer networks, artificial intelligence, natural language processing, and social computing. , network security laws and regulations, network security, content security, digital forensics, machine learning, multimedia technology, information retrieval, public opinion analysis, etc.

The second type is self-study, which means looking for resources and tutorials on the Internet, or trying to get to know some big guys and hug them tightly. However, this method is very time-consuming, and there is no plan for learning. You may feel that you are not familiar with it for a long time. If there is no progress, it is easy to be discouraged.

If you are interested in getting started with network security, you can click here if you need it Big benefits of network security: Getting started & advanced full set of 282G learning resource package to share for free!

The third way is to find training.

image.png

Next, I will teach you how to quickly get started with network security from scratch.

When getting started with network security, should you first learn programming or computer basics? This is a controversial issue. Some people will suggest learning programming first, while others will suggest learning computer basics first. In fact, these are all things you need to learn. And these are very important to learn about cybersecurity. But for people with no basic knowledge or those who are eager to change careers, learning programming or computer basics is difficult and takes too long.

The first stage: basic preparation 4 weeks to 6 weeks

This stage is a must-learn for all those who are preparing to enter the security industry. As the saying goes: if the foundation is not worked, the earth will shake.
image.png

The second stage: web penetration

Learning Basics Time: 1 week ~ 2 weeks:

① Understand basic concepts: (SQL injection, XSS, upload, CSRF, one-sentence Trojan, etc.) to lay the foundation for subsequent WEB penetration testing.
② Check out some Web penetration in some forums and learn the ideas from the cases. Every site is different, so the ideas are the main thing.
③ Learn the art of asking questions. If you encounter something you don’t know, you should be good at asking questions.
image.png

Configuring penetration environment time: 3 weeks ~ 4 weeks:

① Understand the commonly used tools for penetration testing, such as (AWVS, SQLMAP, NMAP, BURP, Chinese Chopper, etc.).
② Download the backdoor-free versions of these tools and install them on your computer.
③ Understand the usage scenarios of these tools and understand the basic usage. It is recommended to search them on Google.

Penetration actual operation time: about 6 weeks:

① Search for actual penetration cases on the Internet, and gain an in-depth understanding of the use of SQL injection, file upload, parsing vulnerabilities, etc. in actual combat.
② Build your own vulnerability environment for testing. DWVA, SQLi-labs, Upload-labs, and bWAPP are recommended.
③ Understand the stages of penetration testing and what actions are required at each stage: such as PTES penetration testing execution standards.
④ Study in depth manual SQL injection, find ways to bypass waf, and make your own scripts.
⑤ Study the principle of file upload, how to perform truncation, double suffix spoofing (IIS, PHP), parsing vulnerability exploitation (IIS, Nignix, Apache), etc., refer to: Upload Attack Framework.
⑥ Understand the principles and types of XSS formation, practice in DWVA, use a cms containing XSS vulnerabilities, install security dogs, etc. for testing.
⑦ Understand the one-sentence Trojan and try to write a one-sentence Trojan.
⑧ Study privilege escalation under Windows and Linux, Google keywords: privilege escalation
image.png
The above is the entry stage

The third stage: advanced

After you have already started and found a job, how can you advance? See the picture below for details
image.png

Getting started tips for newbies:
It is best for novices to start learning from videos. Videos are easy to understand and easier to absorb than obscure texts. Here I have prepared a set of video learning materials for network security from entry to proficiency for free. oh!

If you are interested in getting started with network security, you can click here if you need it Big benefits of network security: Getting started & advanced full set of 282G learning resource package to share for free!