Cross-site request forgery (CSRF)
In this section, we’ll explain what cross site request forgery is and describe some common features
CSRFVulnerability examples, and how to defend
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. Attackers
CSRFIt can partly avoid the homology strategy.
What impact can CSRF attack have
On the way to success
CSRFIn 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
CSRFThere 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 example
- 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.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.
CSRFIt 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
CSRFThe 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. structure
CSRFThe easiest way to attack is to use
Burp 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 simple
CSRFThe 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:
Defending against CSRF attacks
CSRFThe most effective way to attack is to use it in related requests
CSRF token, this
- Having high entropy
- Bind to the user’s session
- Before the implementation of relevant operations, strictly verify each case
Can be compared with
CSRF tokenThe additional defense measures used together are
SameSite cookies 。
Common CSRF vulnerabilities
The most interesting
CSRFThe vulnerability is caused by the
CSRF tokenThere is a problem with the validation of.
In the previous example, assume that the application needs to include a
CSRF 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 defensible
CSRFAttack because it breaks
CSRFNecessary 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 vulnerable
CSRFIt’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 attack
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 attack
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 application
CSRFUse 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 do
CSRF 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 for
CSRFThe 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 browser
CSRFThe token is provided to the victim in the attack.
Note: Cookie setting behavior doesn’t even have to be associated with
CSRFThe 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 the
secure.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 targeting
CSRFThe “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 again
CSRFAttack. 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 browser
CSRFThis token is provided to the victim during the attack.
CSRF defense based on referer
In addition to using
CSRF tokenIn addition to defense, some applications use HTTP
RefererHead to defense
CSRFThe 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.
RefererThe 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 modified
RefererThe value of the header. This is usually for privacy reasons.
The validation of a referer depends on its existence
Some applications use the
RefererIt 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 attack
CSRFAttack, so that the victim’s browser is discarded in the request
RefererHead. There are many ways to do this, but the simplest is in hosting
CSRFUsing 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 bypassed
RefererHead. For example, if the application just validates
RefererIf it contains its own domain name, the attacker can put the required value in another location of the URL:
If the application validates
RefererIf the domain in starts with the expected value, the attacker can use it as a child domain of his own domain:
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 explain
CSRFAnd discuss the differences between them
CSRF tokenDoes it help defense
What is the difference between XSS and CSRF
Cross site scripting attack
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 than
CSRFMore serious loopholes:
CSRFIt is usually only applicable to a subset of actions that the user can perform. In general, many applications implement
CSRFDefense, but ignore one or two of the exposed operations. On the contrary, successful
XSSThe 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
XSSAttacks can really be used effectively
CSRF tokenTo defend. Suppose there is a simple reflection type
XSSThe vulnerability can be exploited as follows:
Now, suppose the vulnerability function contains a
CSRF token :
If the server verifies correctly
CSRF 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 request
XSSMinor attack of vulnerability.
Here are some important considerations:
- If reflective
XSSThe vulnerability exists in any other part of the site that is not affected
CSRF tokenIt can be used in the normal way
- If there are available resources anywhere on the site
XSSVulnerability, the vulnerability can be used to make the victim perform operations, even if the operations themselves are affected
CSRF tokenThe protection of the environment. In this case, the attacker’s script can request the relevant page to obtain valid information
CSRF tokenAnd then use the token to perform the protected operation.
CSRF tokenUnprotected storage
XSSloophole. If affected by
CSRF tokenProtected pages are also stored
XSSThe output point of the vulnerability can be exploited in the usual way
XSSVulnerability, and when the user accesses the page, the
Some websites use samesite cookies for defense
SameSiteProperty 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.
SameSiteProperty on the server’s
Set-CookieResponse header, which can be set to
LaxRelax. For example:
SetCookie: SessionId=sYMnfCUrAlmqVVZn9dqevxyFpKZt30NN; SameSite=Strict; SetCookie: SessionId=sYMnfCUrAlmqVVZn9dqevxyFpKZt30NN; SameSite=Lax;
Strict, 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.
Lax, 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.
LaxThe model is right
CSRFThe attack provides part of the defense because
CSRFThe 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 on
SameSiteCookie to resist
CSRFAttack. When it comes to
CSRF tokenWhen used in combination,
SameSiteCookies can provide an additional layer of defense and mitigate any flaws in token based defense.