CSRF of Web Security

Time:2021-6-8

Cross-site request forgery (CSRF)

In this section, we’ll explain what cross site request forgery is and describe some common featuresCSRFVulnerability examples, and how to defendCSRFAttack.

What is CSRF

Cross Site Request Forgery(CSRF)Is a web security vulnerability that allows attackers to trick users into performing operations they don’t want to perform. AttackersCSRFIt can partly avoid the homology strategy.

CSRF of Web Security

What impact can CSRF attack have

On the way to successCSRFIn the attack, the attacker will make the victim perform an operation unintentionally. For example, it could be changing their email address on their account, changing their password, or making a fund transfer. Depending on the nature of the operation, the attacker may be able to take full control of the user’s account. If the victim has a privileged role in the application, the attacker may be able to completely control all the data and functions of the application.

How does CSRF work

To makeCSRFThere are three key conditions for an attack to be possible

  • Related actions. The attacker has reason to induce some action in the application. This can be a privileged operation (such as modifying the permissions of other users) or any operation on user specific data (such as changing the user’s own password).
  • Cookie based session processing. Performing this operation involves making one or more HTTP requests, and the application only relies on session cookies to identify the user making the request. There is no other mechanism for tracking sessions or validating user requests.
  • There are no unpredictable request parameters. The request to perform this operation does not contain any parameters whose value cannot be determined or guessed by the attacker. For example, if the attacker needs to know the value of the existing password when causing the user to change the password, the function will not be attacked.

Suppose the application contains a feature that allows users to change their email address. When the user performs this operation, the following HTTP request will be issued:

POST /email/change HTTP/1.1
Host: vulnerable-website.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 30
Cookie: session=yvthwsztyeQkAPzeQ5gHgTvlyxHfsAfE

[email protected]

This is a good exampleCSRFRequired conditions:

  • Changing the email address on a user account can be of interest to an attacker. After performing this operation, the attacker is usually able to trigger a password reset and take full control of the user’s account.
  • The application uses session cookies to identify the user who made the request. There are no other tags or mechanisms to track user sessions.
  • The attacker can easily determine the value of the request parameter required to perform the operation.

With these conditions, an attacker can build a web page containing the following HTML:

<html>
  <body>
    <form action="https://vulnerable-website.com/email/change" method="POST">
      <input type="hidden" name="email" value="[email protected]" />
    </form>
    <script>
      document.forms[0].submit();
    </script>
  </body>
</html>

If the victim visits the attacker’s web page, the following will happen:

  • The attacker’s page will trigger an HTTP request to the vulnerable website.
  • If a user logs on to a vulnerable website, his browser will automatically include his session cookie in the request (assuming samesite cookies are not used).
  • Vulnerable sites will process requests in the normal way, treat them as requests from victim users, and change their email addresses.

Note: AlthoughCSRFIt is usually described in terms of cookie based session processing, but it also occurs in the context of applications automatically adding some user credentials to requests, such as HTTP basic authentication and certificate based authentication.

How to construct CSRF attack

Create manuallyCSRFThe HTML required for the attack can be cumbersome, especially when the request contains a large number of parameters, or when there are other exceptions in the request. structureCSRFThe easiest way to attack is to useBurp Suite ProfessionalIn (paid software)CSRF PoC generator

How to transfer CSRF

The transmission mechanism of cross site request forgery attack is basically the same as that of reflective XSS. Usually, attackers will put malicious HTML on the website they control, and then induce the victim to visit the website. This can be achieved by providing users with a link to the website through email or social media messages. Or, if the attack is placed on a popular website (for example, in user comments), just wait for the user to take the bait.

Please note that some simpleCSRFThe attack uses the get method and can be completely self-contained through a single URL on the vulnerable website. In this case, the attacker may not need to use an external site, and can directly provide the victim with a malicious URL on the vulnerable domain. In the previous example, if you can use the get method to perform a request to change an e-mail address, the self-contained attack is as follows:

![](https://vulnerable-website.com/email/[email protected])

Defending against CSRF attacks

defenseCSRFThe most effective way to attack is to use it in related requestsCSRF token, thistokenShould be:

  • Having high entropy
  • Bind to the user’s session
  • Before the implementation of relevant operations, strictly verify each case

Can be compared withCSRF tokenThe additional defense measures used together areSameSite cookies

Common CSRF vulnerabilities

The most interestingCSRFThe vulnerability is caused by theCSRF tokenThere is a problem with the validation of.

In the previous example, assume that the application needs to include aCSRF token

POST /email/change HTTP/1.1
Host: vulnerable-website.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 68
Cookie: session=2yQIDcpia41WrATfjPqvm9tOkDvkMvLm

csrf=WfF1szMUHhiokx9AHFply5L2xAOfjRkE&[email protected]

It looks like it’s defensibleCSRFAttack because it breaksCSRFNecessary condition: the application no longer only relies on cookies for session processing, and the request also contains parameters whose value cannot be determined by the attacker. However, there are still many ways to break the defense, which means that the application is still vulnerableCSRFIt’s an attack.

The verification of CSRF token depends on the request method

Some applications verify the token correctly when requesting to use the post method, but skip verification when using the get method.

In this case, the attacker can switch to the get method to bypass the verification and initiate the attackCSRFAttack:

GET /email/[email protected] HTTP/1.1
Host: vulnerable-website.com
Cookie: session=2yQIDcpia41WrATfjPqvm9tOkDvkMvLm

The verification of CSRF token depends on whether the token exists

Some applications verify the token correctly when it exists, but skip verification if it does not exist.

In this case, the attacker can delete the entire parameter containing the token, thus bypassing the verification and initiating the attackCSRFAttack:

POST /email/change HTTP/1.1
Host: vulnerable-website.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 25
Cookie: session=2yQIDcpia41WrATfjPqvm9tOkDvkMvLm

[email protected]

CSRF token is not bound to user session

Some applications do not verify that the token belongs to the same session as the user who made the request. Instead, the application maintains a global pool of issued tokens and accepts any tokens that appear in the pool.

In this case, the attacker can use his own account to log in to the application, obtain a valid token, and then log in to the applicationCSRFUse your own token in the attack.

The CSRF token is bound to a non session cookie

Among the variants of the above vulnerability, some applications doCSRF tokenBound to a cookie, but not to the same cookie used to track the session. This can easily happen when an application uses two different frameworks, one for session processing and the other forCSRFThe two frameworks are not integrated

POST /email/change HTTP/1.1
Host: vulnerable-website.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 68
Cookie: session=pSJYSScWKpmC60LpFOAHKixuFuM4uXWF; csrfKey=rZHCnSzEp8dbI6atzagGoSYyqJqTz5dv

csrf=RhV7yQDO0xcq9gLEah2WVbmuFqyOq7tY&[email protected]

This situation is difficult to exploit, but there are still loopholes. If the website contains any behavior that allows an attacker to set a cookie in the victim’s browser, an attack may occur. The attacker can use his own account to log in to the application, obtain valid token and associated cookie, and put his cookie into the victim’s browser by cookie setting behavior, and then send it to the victim’s browserCSRFThe token is provided to the victim in the attack.

Note: Cookie setting behavior doesn’t even have to be associated withCSRFThe vulnerability exists in the same web application. If the controlled cookie has an appropriate range, the cookie can be set in the target application using any other application in the same overall DNS domain. For example,staging.demo.normal-website.comThe cookie setting function on the domain can be placed to submit to thesecure.normal-website.comThe cookie on the.

CSRF token is only required to be the same as in cookie

In a further variant of the above vulnerability, some applications do not maintain any server-side records of issued tokens, but copy each token in the cookie and request parameters. When verifying subsequent requests, the application only needs to verify whether the token submitted in the request parameters matches the value submitted in the cookie. This is sometimes called targetingCSRFThe “double commit” defense is advocated because it is easy to implement and avoids the need for any server state

POST /email/change HTTP/1.1
Host: vulnerable-website.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 68
Cookie: session=1DQGdzYbOJQzLP7460tfyiv3do7MjyPw; csrf=R8ov2YBfTYmzFyjit8o2hKBuoIjXXVpa

csrf=R8ov2YBfTYmzFyjit8o2hKBuoIjXXVpa&[email protected]

In this case, if the website contains any cookie setting function, the attacker can execute it againCSRFAttack. Here, the attacker does not need to obtain his own valid token. They just need to invent a token, use the cookie setting behavior to put the cookie into the victim’s browser, and use it in the browserCSRFThis token is provided to the victim during the attack.

CSRF defense based on referer

In addition to usingCSRF tokenIn addition to defense, some applications use HTTPRefererHead to defenseCSRFThe attack is usually to verify that the request comes from the application’s own domain name. This method is usually not very effective and is often bypassed.

Note: httpRefererThe header is an optional request header that contains the URL of the web page linked to the requested resource. Usually, when a user triggers an HTTP request, such as clicking a link or submitting a form, the browser automatically adds it. However, there are various ways to allow linked pages to be retained or modifiedRefererThe value of the header. This is usually for privacy reasons.

The validation of a referer depends on its existence

Some applications use theRefererIt is validated when the header is used, but if it is not, the validation is skipped.

In this case, the attacker can carefully design the attackCSRFAttack, so that the victim’s browser is discarded in the requestRefererHead. There are many ways to do this, but the simplest is in hostingCSRFUsing meta tag in the HTML page of the attack:

<meta name="referrer" content="never">

Referer validation can be circumvented

Some applications validate in a way that can be bypassedRefererHead. For example, if the application just validatesRefererIf it contains its own domain name, the attacker can put the required value in another location of the URL:

http://attacker-website.com/csrf-attack?vulnerable-website.com

If the application validatesRefererIf the domain in starts with the expected value, the attacker can use it as a child domain of his own domain:

http://vulnerable-website.com.attacker-website.com/csrf-attack

CSRF tokens

In this section, we will explain what CSRF tokens are, how they defend against CSRF attacks, and how to generate and verify CSRF tokens.

What is CSRF token

CSRF token is a unique, secret and unpredictable value, which is generated by the server application and transmitted to the client in this way, so that it is included in the subsequent HTTP requests sent by the client. When a subsequent request is issued, the server application will verify whether the request contains the expected token and reject the request if the token is missing or invalid.

Because attackers can’t determine or predict the value of the user’s CSRF token, they can’t construct a request for all the parameters needed for application verification. So CSRF token can prevent CSRF attack.

How to generate CSRF token

CSRF token should contain significant entropy and be highly unpredictable. It usually has the same characteristics as session token.

You should use the encryption strength pseudo-random number generator (PRNG), which comes with a time stamp at the time of creation and a static password.

If you need further assurance beyond the strength of PRNG, you can generate a separate token by connecting its output to some user specific entropy, and strongly hash the entire structure. This creates additional obstacles for attackers trying to analyze tokens.

How to transmit CSRF token

CSRF token should be treated as confidential and handled in a secure manner throughout its life cycle. A commonly effective method is to transfer the token to the client in the hidden field of the HTML form submitted by the post method. When the form is submitted, the token will be included as a request parameter:

<input type="hidden" name="csrf-token" value="CIwNZNlR4XbisJF39I8yWnWX9wX4WFoz" />

For security reasons, fields containing CSRF tokens should be placed in HTML documents as early as possible, preferably before any non hidden input fields and before embedding user controlled data anywhere in HTML. This can counter various techniques for attackers to manipulate HTML documents and capture part of their contents with well-designed data.

Another method is to put the token into the URL query string, which is slightly less secure because the query string:

  • Record in each location of client and server;
  • It is easy to transfer to a third party in the HTTP referer header;
  • It can be displayed on the screen in the user’s browser.

Some applications transmit CSRF tokens in custom request headers. This further prevents an attacker from predicting or capturing another user’s token, as browsers generally do not allow custom headers to be sent across domains. However, this approach limits applications to CSRF protected requests using XHR (as opposed to HTML forms), and may be considered too complex in many cases.

CSRF token should not be transmitted in cookie.

How to verify CSRF token

When the CSRF token is generated, it should be stored in the user session data on the server side. When receiving a subsequent request that needs to be verified, the server-side application should verify that the request contains a token that matches the value stored in the user session. This validation must be performed regardless of the HTTP method or content type of the request. If the request does not contain any tokens at all, the request should be rejected in the same way as if there were invalid tokens.


XSS vs CSRF

In this section, we will explainXSSandCSRFAnd discuss the differences between themCSRF tokenDoes it help defenseXSSAttack.

What is the difference between XSS and CSRF

Cross site scripting attackXSSAllows an attacker to execute arbitrary JavaScript in the victim user’s browser.

Cross-site request forgery CSRFAllows attackers to forge victim users to perform operations they do not intend to perform.

XSSThe consequences of a vulnerability are usually greater thanCSRFMore serious loopholes:

  • CSRFIt is usually only applicable to a subset of actions that the user can perform. In general, many applications implementCSRFDefense, but ignore one or two of the exposed operations. On the contrary, successfulXSSThe attack can usually perform any operation that the user can perform, regardless of the function in which the vulnerability is generated.
  • CSRFIt can be described as a “one-way” vulnerability because although the attacker can induce the victim to issue an HTTP request, they cannot retrieve the response from the request. contrary,XSSIt is “bidirectional” because the script injected by the attacker can make any request, read the response and transfer the data to the external domain chosen by the attacker.

Can CSRF token defend against XSS attack

someXSSAttacks can really be used effectivelyCSRF tokenTo defend. Suppose there is a simple reflection typeXSSThe vulnerability can be exploited as follows:

https://insecure-website.com/status?message=<script>/*+Bad+stuff+here...+*/</script>

Now, suppose the vulnerability function contains aCSRF token :

https://insecure-website.com/status?csrf-token=CIwNZNlR4XbisJF39I8yWnWX9wX4WFoz&message=<script>/*+Bad+stuff+here...+*/</script>

If the server verifies correctlyCSRF token, and rejected the request without a valid token, then the token can indeed prevent the exploitation of this XSS vulnerability. The key point here is that the cross site request is involved in the cross site script attack. Therefore, by preventing the attacker from forging the cross site request, the application can prevent the cross site requestXSSMinor attack of vulnerability.

Here are some important considerations:

  • If reflectiveXSSThe vulnerability exists in any other part of the site that is not affectedCSRF tokenIt can be used in the normal wayXSSloophole.
  • If there are available resources anywhere on the siteXSSVulnerability, the vulnerability can be used to make the victim perform operations, even if the operations themselves are affectedCSRF tokenThe protection of the environment. In this case, the attacker’s script can request the relevant page to obtain valid informationCSRF tokenAnd then use the token to perform the protected operation.
  • CSRF tokenUnprotected storageXSSloophole. If affected byCSRF tokenProtected pages are also storedXSSThe output point of the vulnerability can be exploited in the usual wayXSSVulnerability, and when the user accesses the page, theXSSPayload.

SameSite cookies

Some websites use samesite cookies for defenseCSRFAttack.

thisSameSiteProperty can be used to control whether and how cookies are submitted in cross site requests. By setting the properties of session cookies, the application can prevent the browser from automatically adding cookies to the request by default, regardless of where the cookie comes from.

thisSameSiteProperty on the server’sSet-CookieResponse header, which can be set toStrictStrict orLaxRelax. For example:

SetCookie: SessionId=sYMnfCUrAlmqVVZn9dqevxyFpKZt30NN; SameSite=Strict;

SetCookie: SessionId=sYMnfCUrAlmqVVZn9dqevxyFpKZt30NN; SameSite=Lax;

IfSameSiteProperty toStrict, the browser will not include cookies in any requests from other sites. This is the most defensive choice, but it can damage the user experience, because if the logged in user accesses a site through a third-party link, they will not log in and need to log in again before they can interact with the site in a normal way.

IfSameSiteProperty toLax, the browser will include the cookie in the request from another site, provided that the following two conditions are met:

  • Request to use the get method. Requests using other methods, such as post, will not include cookies.
  • Requests are generated by the user’s top-level navigation, such as clicking a link. Other requests, such as those initiated by scripts, will not include cookies.

useSameSiteOfLaxThe model is rightCSRFThe attack provides part of the defense becauseCSRFThe target user operation of the attack is usually implemented by post method. Here are two important considerations:

  • Some applications do use get requests for sensitive operations.
  • Many applications and frameworks can tolerate different HTTP methods. In this case, even if the application itself is designed to use the post method, it will actually accept the request to be switched to use the get method.

For the above reasons, it is not recommended to rely solely onSameSiteCookie to resistCSRFAttack. When it comes toCSRF tokenWhen used in combination,SameSiteCookies can provide an additional layer of defense and mitigate any flaws in token based defense.

CSRF of Web Security

Recommended Today

What is “hybrid cloud”?

In this paper, we define the concept of “hybrid cloud”, explain four different cloud deployment models of hybrid cloud, and deeply analyze the industrial trend of hybrid cloud through a series of data and charts. 01 introduction Hybrid cloud is a computing environment that integrates multiple platforms and data centers. Generally speaking, hybrid cloud is […]