Deep Dive into CSRF Vulnerabilities

1.1. Definition

Cross-site request forgery (English: Cross-site request forgery), also known as  one-click attack or  session riding , usually abbreviated as  CSRF or  XSRF , is a method that coerces users to execute unintentional The attack method of the operation. Compared with XSS跨站脚本(XSS) , which uses the user's trust in the specified website, CSRF uses the website's trust in the user's web browser.

The cross-site request forgery attack is that the attacker uses some technical means to deceive the user's browser to visit a website that the user himself 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 consider it to be a real user operation and execute it. This takes advantage of a loophole in user authentication on the web: simple authentication can only guarantee that the request is sent from a user's browser, but cannot guarantee that the request itself is voluntarily sent by the user .

Note

Simply put, if you click on the malicious link I constructed, I can initiate an http request in your name

1.2. Examples

  1. If the URL address used by Bank X to perform the transfer operation is as follows
    https://bank.example.com/withdraw?amount=1000&to=PayeeName

  2. A malicious attacker https://evil.com/places the following code in another website
    html <img src="https://bank.example.com/withdraw?amount=1000&to=Bob" />

  3. If a user who has logged in to Bank X visits a malicious site https://evil.com/, it will carry a cookie to request the corresponding transfer URL, and Bobtransfer 1,000 yuan to

Note This kind of malicious URL can take many forms and hide in many places on the webpage, as long as the victim can initiate a corresponding request , such as the above-mentioned transfer request.

The attacker does not need to control the website where the malicious code is placed. For example, he can hide this address in any website with user-generated content such as major forums and blogs. This means that if the server does not have appropriate defense measures, even if the user Visiting familiar and trusted websites is also at risk of attack .

It can also be seen from the example that the attacker cannot directly obtain the user's account control right through CSRF attack, nor can he directly steal any information of the user. What they can do is trick the user's browser into performing actions on their behalf .

1.3. Attack process

The specific attack process is as follows:

  1. The user logs in to the web service normally and remains online

  2. The server returns the user credentials Session and saves it in a cookie

  3. The attacker generates the payload and places it where the user can access it

  4. The attacker induces the user to click the link placed in step 3. At this time, the user is always online and opened with the same browser (to ensure that the cookie is not invalid)

  5. User clicks on malicious link

  6. The malicious link requests to the server, and since the user cookie has not expired, it carries the user cookie to access the server

  7. The server receives the request, and the user cookie is not invalid at this time, and determines that it is a normal request initiated by the " user ", and responds

1.4. Classification

1.4.1. GET type

This type is the easiest to use. Compared with the POST type, the attack surface is much larger. For example, the above CSRF transfer example is the GET type.

In web applications, many interfaces request and store data through GET. If the source is not verified and there is no token protection, the attacker can directly induce clicks by sending links containing payloads; or through the comment area or similar Publish pictures at the function place, save them to the page by modifying the img address, and the user will automatically load them when they visit to cause an attack

<!-- 不论什么手段,只要能让受害者访问一个链接即可 -->
<img src="https://bank.example.com/withdraw?amount=1000&to=Bob" />

1.4.2. POST-form type

Compared with the GET type, this type is much more, because many developers will use it when submitting data function points POST, such as creating users, creating articles, sending messages, etc., and it is relatively troublesome to use

Note During the test, in order to expand the damage, you can try to convert the POST data packet into a GET data packet. If the backend adopts this method to @RequestMaping("/")accept POST and GET requests at the same time, it will be successful.

It is nothing more than constructing an automatically submitted form, and then embedding it in the page to induce the victim to visit. After the victim visits, the form will be automatically submitted to initiate the request

<form action=http://bank.example.com/csrf method=POST>
<input type="text" name="amount" value="1000" />
</form>
<script> document.forms[0].submit(); </script>

1.4.3. POST-JSON type

Now more and more systems are developed in RESTfulstyle, the front and back ends are separated, ajax requests the back end to obtain data and then renders it to the front end, so the above form types are becoming less and less

If we find that the value in the request header Content-Typeis application/json, we can basically determine that the front and back ends are separated

There are generally 4 ways to use this method:

  1. json to param

  2. closed JSON

  3. ajax initiates a request

  4. flash+307 jump


json to param

Some websites may support json and form formats at the same time, so we can try to convert them, which can be regarded as a small tip

If  {"a":"b"}converted to  a=b, the server may also parse


closed JSON

This requirement has no restrictions on the Content-Type , such as the transmitted data is  {"a":"b"}, then we can construct a form

<form action=http://test.example.com/csrf method=POST>
    <!-- 重点是下面这一行 -->
    <input type="hidden" name='{"a":"' value='b"}' />
</form>
<script> document.forms[0].submit(); </script>

When the form is automatically submitted in this way, the submitted data is  {"a":"=b"}, closed into json Note

I have never encountered it in the actual environment, basically all I encountered are mandatory requirements Content-Typefor json


ajax initiates a request

When a cross-domain impact user data HTTPrequest (such as XMLHttpRequestsent by user get/post), the browser will send a preflight request ( OPTIONSrequest) to the server to solicit support for the request method, and then send the real request according to the server's response permission.

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Access-Control-Allow-Origin: http://localhost:63342
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 1800
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: content-type,access-control-request-headers,access-control-request-method,accept,origin,x-requested-with
Content-Length: 0
Date: Wed, 11 Mar 2015 05:16:31 GMT

However, if the server verifies Content-Typethe OPTIONS request, it will not respond to the OPTIONS request, and the exploit will fail. But in more cases, the server may not verify Content-Type, or not strictly verify Content-Typewhether it is application/json, so this is available in many cases

<script>
  windows.onload = () => {
    var xhr = new XMLHttpRequest()
    xhr.open("POST", "http://test.example.com/csrf")
    xhr.setRequestHeader("Accept", "*/*")
    xhr.setRequestHeader("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3")
    xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8")
    xhr.withCredentials = true // 携带cookie
    xhr.send(JSON.stringify({"a":"b"})
  }
</script>

flash+307 jump

Use Flash's cross-domain and 307 redirection to bypass http custom header restrictions. The difference between 307 and other 3XX HTTP status codes is that HTTP 307 can ensure that the request method and request body will not occur after the redirection request is sent. any changes. HTTP 307 will redirect the POST body and HTTP header to the final URL we specified, and complete the attack

For details, refer to another article of mine in this series: A combined attack of XSS and CSRF (CSRF+JSON)

1.5. Mining

It can be regarded as some mining experience. Many friends know this vulnerability, but they don’t know how to dig it.

1.5.1. Application scenarios

In fact, CSRF may exist in all places where login authentication is required and there are operations; such as modifying personal information, sending emails, creating administrator users, etc., functions that can only be viewed are not considered, because they cannot be regarded as real use

1.5.2. How to quickly verify

Tip

Observe the data packet, if there is no token in the header and data, and then try to delete the referer, if the request can still be successfully sent, it can be determined that there is a CSRF vulnerability

To be on the safe side, if there is enough time, it is still necessary to pass the POC verification as much as possible. Generally, there is no need for two accounts for verification, and one account is enough (two can only be said to be more secure)

In the case of non-json, use burp to quickly generate POC, or write it yourself, anyway, the principle is to initiate a request

If you log in to the account and visit this poc, if you can successfully get your own results, it is OK.

1.6. Defense

The WEB authentication mechanism can guarantee which user's browser a request comes from, but it cannot guarantee whether the request is initiated by the user, so the repair and defense can only ensure that the request is initiated by the user himself.

Tip

To put it simply, or when communicating with customers, directly say that the repair method is to prevent request replay , and their developers almost know how to fix it

1.6.1. Token Synchronization Mode

Token synchronization pattern (English: Synchronizer token pattern, referred to as STP).

The principle is: when a user sends a request, the server-side application embeds a token (token: a confidential and unique value) into an HTML form and sends it to the client. When the client submits the HTML form, it will send the token to the server, and then the server will verify the token. Tokens can be generated in any way as long as they are random and unique . This ensures that when an attacker sends a request, he cannot pass the verification without the token. (The packet cannot be replayed without token)

<input type="hidden" name="_csrf_token" value="YidlXHhlMVx4YmJceDkxQFx4OTdceDg5a1x4OTJcbic=">


Note

STP can work smoothly under HTML, but it will lead to increased complexity on the server side. The complexity stems from the generation and verification of tokens. Because tokens are unique and random, if each table uses a unique token, then when there are too many pages, the burden on the server due to token production will also increase. If you use a session-level token instead, the burden on the server will not be so heavy.

1.6.2. Check the Referer field

There is a Referer field in the HTTP header, which is used to indicate which address the request comes from. When handling sensitive data requests, generally speaking, the Referer field should be under the same domain name as the requested address .

Taking the bank operation above as an example, the address of the Referer field should usually be the address of the web page where the transfer button is located, and it should also be located below bank.example.com. And if it is a request from a CSRF attack, the Referer field will contain an address containing a malicious URL, and will not be located below bank.example.com. At this time, the server can recognize the malicious access.

Warning

This method is simple and easy, with low workload, and only needs to add one step of verification at key access points.

But this method also has its limitations, because it completely depends on the browser to send the correct Referer field; although the http protocol has clear regulations on the content of this field, it cannot guarantee the specific implementation of the visiting browser, nor can it guarantee that the browser will send the correct Referer field. There is no security hole in the browser that affects this field, and there is also the possibility that attackers attack some browsers and tamper with their Referer field.

1.6.3. Add verification token

Note

The submission is not necessarily submitted in the data, but also in the header

Since the essence of CSRF is that the attacker deceives the user to visit the address set by himself, if the user's browser is required to provide data that is not stored in the cookie and cannot be forged by the attacker as a verification when accessing sensitive data requests, then the attack The attacker can no longer perform CSRF attacks.

This data is usually a data item in a form. The server generates it and appends it to the form, and its content is a pseudo-random number. When the client submits a request through the form, the pseudo-random number is also submitted for verification. During normal access, the client browser can correctly obtain and return the pseudo-random number, but in the fraudulent attack through CSRF, the attacker has no way of knowing the value of the pseudo-random number in advance, and the server will fail because of the calibration. Check that the value of the token is empty or wrong, and reject the suspicious request.

1.6.4. One-time verification code

Add a one-time, one-use verification code at the key operation, the attacker cannot know the value of the verification code in advance, and cannot successfully construct the data packet that initiates the request.

Attention

User interaction is required. If it is added in many places, the user experience will be extremely poor, so this is generally not recommended

1.6.5. Using SameSite Cookies

Set SameSiteproperties, need to be set as needed

  1. If the Samesite Cookie is set to Strict, the browser will not carry Cookie in any cross-domain request, and the new tab will not carry Cookie, so there is basically no chance for CSRF attacks; but jumping to a sub-domain name or reopening a new tab has just logged in site, the previous cookies will not exist. Especially for websites with logins, we need to log in again when we open a new tab to enter, or jump to a website with a subdomain. For users, the experience may not be very good.

  2. If Samesite Cookie is set to Lax, then other websites can use cookies when they jump over the page, which can ensure the user's login status when the page is opened by an external domain connection. But correspondingly, its security is relatively low.

1.7. Personal precautions

If there is a CSRF vulnerability on the website, how do individuals generally operate to prevent themselves from being attacked?

  1. Try to use a private browser every time, because all cookies will be cleared after it is closed

  2. Do not open the link casually, if you must open it, you can use a private browser

Guess you like

Origin blog.csdn.net/m8330466/article/details/130814902