CSRF attack type
CSRF (Cross Site Request Forgery), also known as XSRF, one-click attack, or Session riding, is an attack that hijacks a trusted user to send an unexpected Request to a server. The attacker lures the victim to a third-party site, where a cross-site request is sent to the targeted site. Using the victim in the attacked website has obtained the registration certificate, bypassing the background user authentication, to impersonate the user to perform a certain operation on the attacked website.
In contrast to XSS, XSS exploits the user’s trust in a given web site, and CSRF exploits the site’s trust in the user’s Web browser.
Under normal circumstances, CSRF attack means that the attacker uses the victim’s Cookie to win the trust of the server and sends forged requests to the attacked server in the victim’s name without the victim’s knowledge, so as to perform operations under permission protection without authorization.
Li Xiangtian’s answer from Zhihu includes a vivid description of CSRF:
The burglar system starts: Mom: Keep an eye on my clothes. Child: Ok
Thieves are here Normal Work: Child: Who are you? Thief: I’m Zhang SAN Child: Mom, someone stole clothes Mom: Who? Kid: Zhang SAN
Child: Who are you? Thief: I’m kidding kid: Mom, someone stole clothes. Mom: Who? Kid: I’m kidding. Mom:…
CSRF allows users to make a request without their knowledge: Thief: Your mother asks you to buy laundry detergent
The principle of CSRF is simple and even more monotonous than XSS. Specifically, it includes the following three types of attacks:
- CSRF of the GET type
- CSRF of the POST type
- CSRF of link type
CSRF of the GET type
This type of attack is very simple and requires only one HTTP request:
<img src="http://a.com/withdraw?amount=10000&for=hacker" >
Copy the code
After the victim visits the page containing the IMG, the browser automatically sends an HTTP request to A.com. A.com receives a cross-domain request containing the victim’s login information.
CSRF of the POST type
This type of CSRF is typically exploited using an auto-submitted form, such as:
<form action="http://a.com/withdraw" method=POST>
<input type="hidden" name="account" value="airing" />
<input type="hidden" name="amount" value="10000" />
<input type="hidden" name="for" value="hacker" />
</form>
<script> document.forms[0].submit(); </script>
Copy the code
When you visit the page, the form is automatically submitted, simulating a POST operation. This type of CSRF, like the first type, simulates requests, so the backend interface cannot rely on only allowing POST requests for security.
CSRF of link type
Link-type CSRFS are uncommon and require the user to click on the link to trigger them, as opposed to the other two, but are essentially the same. This type usually involves embedding malicious links in the pictures published in the forum, or inducing users to be lured in the form of advertisements. Attackers usually trick users into clicking with exaggerated words, such as:
<a href="http://a.com/withdraw.php?amount=1000&for=hacker" taget="_blank""> < p style =" max-width: 100%; clear: both; min-height: 1em; <a/>Copy the code
The user has logged in to the trusted website A and saved the login status. As long as the user accesses the page, the attack succeeds.
CSRF defense methods
CSRF is usually launched from third-party websites. Attacked websites cannot prevent attacks, but can only enhance their own protection against CSRF to improve security.
The above mentioned two characteristics of CSRF are described:
- CSRF (usually) occurs in third party domain names.
- CSRF attackers cannot obtain information such as cookies, but only use.
In view of the above characteristics, CSRF can develop the following two defense strategies:
- Automatic defense: Blocks access to unknown outlands
- Homologous detection
- Samesite Cookie
- Active defense: Submission requests additional information that can only be obtained by the local domain
- Synchrogazer Tokens
- Double Cookie Defense
- Custom Header
Automatic defense takes advantage of the inherent features of HTTP, while active defense requires programming.
CSRF Automatic defense policy
Homologous detection
Since most CSRFS come from third-party sites, we simply forbid outlands/untrusted domains from making requests to us.
In HTTP, each asynchronous request carries two headers, which mark the domain name of the source:
-
Origin Header
-
Referer Header
Same-origin detection is implemented by verifying that the two headers are trusted. However, this method is not foolproof, the value of the Referer is provided by the browser, although HTTP protocol has clear requirements, but each browser for the specific implementation of the Referer may be different, and can not guarantee that the browser itself does not have security vulnerabilities. Using the method of verifying the Referer value is to rely on the third party to guarantee the security, which is not very safe in theory. In some cases, attackers can hide or even modify the Referer of their own requests. When writing crawlers, we also often modify the Header to bypass the server’s homology detection.
In Basics front-end Security Series 2: How do I Prevent CSRF Attacks? | Meituan technical team The credibility of the article analyzes the Referer and dangerous scenario, here are limited to space is no longer here.
To sum up, homologous authentication is a relatively simple defense method that can prevent the vast majority of CSRF attacks. However, this is not foolproof. For sites with high security requirements or high user input, we need to implement additional protection measures for key interfaces, which is the active defense strategy described below.
Samesite Cookie
To address this problem at its source, Google has drafted a draft to improve the HTTP protocol by adding a Samesite attribute to the set-cookie response header, which identifies the Cookie as a “same-site Cookie.” A peer cookie can only be used as a first-party cookie, not a third-party cookie. SameSite has two property values, Strict and Lax.
- Samesite=Strict: indicates that this cookie cannot be used as a third-party cookie under any circumstances, without exception.
- Samesite=Lax: loose mode, a little more restrictive than Strict. If the request is synchronous (changes the current page or opens a new page) and is also a GET request, the cookie can be used as a third-party cookie.
But there are some problems with Samesite cookies:
- Samesite is not very compatible, and Safari and iOS Safari are not supported at this stage except for the new Chrome and Firefox versions.
- Also, SamesiteCookie currently has a fatal flaw that does not support subdomains. For example, cookies planted under blog.ursb. Me cannot use SamesiteCookie planted under ursb. Me. This results in the inability to use SamesiteCookie to store user login information in the main domain when our site has multiple subdomains. Each subdomain requires the user to log in again. This is not practical.
CSRF Active defense policy
CSRF active defense measures are as follows:
- Synchronizer Tokens: Render Tokens to the page when responding to the page, and submit Tokens to the hidden field when the form is submitted.
- Double Cookie Defense: Sets the token in the Cookie, submits the Cookie when submitting the POST request, and carries the token in the Cookie through the header or body for the server to compare and verify.
- Custom Header: Trust with a specific header (for example
X-Requested-With: XMLHttpRequest
). This scheme can be bypassed, so frameworks like Rails and Django abandon this defense.
So I’ll focus on the first two types of defense.
Synchrogazer Token
Synchrogazer Token, CSRF validation of synchronized forms. The CSRF attack succeeds because the server mistook the request sent by the attacker for the user’s own request. Then we can require all user requests to carry a Token that a CSRF attacker cannot obtain. By verifying whether the request carries the correct Token, the server can distinguish the normal request from the attack request and defend against CSRF attacks.
Specifically, it can be divided into the following three steps:
- Outputs the CSRF Token to the page
- Requests for page submissions carry this Token and are usually hidden in a form field as a parameter submission or concatenated after a URL as a Query submission.
- The server verifies that the Token is correct
When a user obtains a Token from the client and submits it to the server again, the server needs to determine the validity of the Token by decrypting the Token and comparing the encrypted string with the timestamp. If the encrypted string is consistent and the time has not expired, the Token is valid.
The Token value is usually generated by encryption using a UserID, timestamp, and random number. Such encryption not only verifies the user who requested the request, but also ensures that the Token is not easily cracked. For reference only, individuals use the following encryption methods in the project:
import md5 from 'md5'
export const MESSAGE = {
OK: {
code: 0.message: 'Request successful',},TOKEN_ERROR: {
code: 403.message: 'TOKEN failure',}}const md5Pwd = (password) = > {
const salt = 'Airing_is_genius'
return md5(md5(password + salt))
}
export const validate = (res, check, ... params) = > {
for (let param of params) {
if (typeof param === 'undefined' || param === null) {
return res.json(MESSAGE.PARAMETER_ERROR)
}
}
if (check) {
const uid = params[0]
const timestamp = params[1]
const token = params[2]
if(token ! == md5Pwd(uid.toString() + timestamp.toString() + KEY))return res.json(MESSAGE.TOKEN_ERROR)
}
}
Copy the code
This method is a bit safer than checking Referer or Origin before. Tokens can be generated and placed in the Session, then taken out of the Session on each request and compared with the tokens in the request. But there are two caveats.
- Session Vs Cookie: CSRF tokens are stored in cookies for AJAX requests. However, all subdomains can set cookies. Therefore, when our application cannot guarantee that all subdomains are controlled, storing cookies may be attacked by CSRF. Therefore, if you can store tokens in Session, it is a good choice.
- Refresh CSRF Token: When the CSRF token is stored in a Cookie, once a user switch occurs on the same browser, the newly logged in user will still use the old token (used by the previous user), which brings security risks. Therefore, the CSRF token must be refreshed every time the user logs in.
Double Cookie Defence
Double Cookie Defence.
Storing CSRF tokens in a Session is cumbersome, and all interfaces cannot be handled uniformly for common interception. Another defense is to use double-commit cookies. Taking advantage of the fact that CSRF attacks cannot retrieve user cookies, we can require Ajax and form requests to carry a value from a Cookie.
-
When a user visits a web page, a Cookie is injected into the requested domain name with a random string of content.
-
When the front end makes a request to the back end, the Cookie is fetched and added to the parameters of the URL.
-
The back-end interface verifies whether the fields in the Cookie are consistent with those in the URL parameter, and rejects any inconsistency.
This method is much simpler than the CSRF Token. It can be automated directly through the method of front and back end interception. Backend verification is also more convenient, requiring only the comparison of fields in the request without the need to query and store tokens.
However, it has not been widely used, especially on large websites, and has serious defects. Take a chestnut 🌰 :
Since any cross-domain will cause the front-end to fail to obtain the fields in the Cookie (including between subdomain names), when users access my me.ursb. Me, since my back-end API is deployed on api.ursb. Me, Then the user in me.ursb.me can not get the Cookie of api.ursb.me, so the double Cookie authentication cannot be completed. In this way, our cookies are placed under the ursb.me main domain to ensure that each subdomain is accessible. In fact, I have deployed many other sub-applications under ursb. Me. If there is a vulnerability in a sub-domain xxx.ursb. Me, although there may be no information worth stealing in xxx.ursb. Me, the attacker can modify the Cookie under ursb. So as to realize XSS attack, and use the tampered Cookie to launch CSRF attack against me.ursb.me. At the same time, in order to ensure the security of Cookie transmission, it is best to use this defense mode to ensure that the whole site HTTPS mode is used. If HTTPS is not used, this mode will be risky.
The following is from Basics 2 of the Front-end Security series: How do YOU Prevent CSRF attacks? | Meituan technical team about the dual Token authentication conclusion:
Advantages:
-
No need to use Session, more widely applicable, easy to implement.
-
The Token is stored in the client and does not put pressure on the server.
-
Compared with Token, the implementation cost is lower, and the verification can be uniformly intercepted at the front and back ends without the need to add interfaces and pages one by one.
Disadvantages:
-
Additional fields are added to cookies.
-
If there are other vulnerabilities (such as XSS) where the attacker can inject cookies, this defense fails.
-
Isolation of subdomains is difficult.
-
In order to ensure the security of Cookie transmission, it is best to use this defense mode to ensure that the whole site HTTPS mode is used. If HTTPS is not used, this mode may also be risky.
The resources
- Safety | egg
- 【 Basics 】 Front-end Security Series 2: How to Prevent CSRF Attacks? | Meituan technical team
- CSRF attacks way of dealing with | IBM Developer