Speaking of front-end security issues, most of them have heard the terms XSS and CSRF. In front-end interviews, we often ask these two points as some basic inspections of web security. But most of them just start talking about the basic words and stay on the basic meaning of words. Few people have really actively practiced safety and thought about the connection behind it.
There are two main sources of front-end security. One is unsafe scripts and the other is unsafe requests. The former represents various means of injecting scripts such as XSS, the latter initiates illegal requests, and CSRF is the representative.
Web Security Cornerstone - Same Origin Policy
This article mainly wants to analyze the security attacks and protection represented by cross-domain. Many people know the Same Origin Policy SOP, which is the cornerstone of web security. Since the browser is an http stateless connection, it is very important to distinguish between different sources. In short: the protocol, domain name, and port are the same, and the browser considers it to be the same source. Under the same source, such as, Resources such as cookie\html5 storage can be shared.
With the same-origin policy as a guarantee, why would there be illegal requests from other origins?
This is where a lot of people get confused. The core of the same-origin policy is to protect resources belonging to a source from being read by other sources. They are independent of each other. The original intention of this design is not to prevent illegal requests, that is to say, same-origin does not equal legal requests, and it does not care Whether the request is legitimate. The simple definition is "writable and unreadable".
So the question is, why do we get an error from the browser when we make a cross-domain request? (explained later)
The image above is an error message that the request is blocked by CORS rules.
Sharing policies across domains
The same-origin policy is to protect the unified source resource from being stolen, but the reality is that in many scenarios, we need to share between different sources, and cross-origin resource sharing (CORS) is both aimed at how to legally break the SOP. Before the official agreement was formed, there used to be unofficial means to break through the sharing of resources between different sources, such as JSOP. CORS is an official protocol used to directly share resources between different sources, so its purpose is not for security. To some extent, it is unsafe because of unreasonable use, such as using this protocol: Access-Control-Allow -Origin: * Allows all origins to share resources, undoubtedly opening the door to intruders.
So, SOP and CORS are opposite directions of resource isolation and sharing.
The essence of CSRF
The reason for emphasizing this point is to tell developers that what the browser does is just implement the relevant basic protocols. Don't try to misunderstand that these two protocols will protect your application. The security of the application should be under your own control.
Going back to the CSRF scenario, the attacker makes a request to your origin from another illegal origin, fooling the server. Why does the server trust an illegal source, or how does the server guarantee that the source is legitimate. As early as a statistic, at least 30% of websites have CSRF vulnerabilities, and many developers do not have a deep understanding of CSRF. Since http is stateless, the maintenance of front-end and back-end sessions and user identity verification are mostly based on cookies. The cookie data is protected by SOP policy by default - it cannot be shared between different origins. However, the browser does not guarantee whether the cookie is from the same source in each request, which is the root cause of CSRF.
That is to say, if the same interface is requested from different sources, the cookie will be carried over. If you just rely on the token login state in the cookie to verify the user's identity, then it is not safe at all. Suppose a user logs in to a personal account at site A, this site maintains a session based on cookies, and does not do any scrf protection. Next, it receives an intermediate email and clicks to open a phishing web page, which can be sent as site A. Any data that carries the login state can arbitrarily modify the user's data on site A.
Compared with many students who have doubts, we just didn't show it above. The existence of the CORS protocol will cause the console to report an error, indicating that the request failed? Even if it is a phishing webpage requesting site A to carry the cookie after the user has logged in, isn't this request not sent?
This error is easy to be misunderstood. The error of cross-domain resource sharing does not mean that the request fails, but that the resource read area fails. That is to say, although the browser reports an error in the interface cross-domain logic, the http request error is still successful, it reaches the background and returns the corresponding result, but the browser prevents you from accessing this data based on the SOP policy. Just got this prompt.
This proves once again that SOP only serves source data isolation, it does not impose any restrictions on requests, and even does not restrict cookie carrying when it is cross-domain. This is also the source of a large number of CSRF vulnerabilities.
To repeat, based on the login state maintained by the cookie, if there is no verification by any other means, the HTTP request with the login cookie received in the background is not necessarily "legitimate". The easiest way to test whether our interface has CSRF protection is to copy the request content and do a http replay on the console. If it returns successfully, it basically means that there is a loophole.
CSRF Protection
The essence of cross-domain request attacks is to use cookies to carry them. The simplest protection method is to not use cookies, change them to html storage, such as localstorage, etc., and then maintain a set of cookie-like expiration logic before and after.
However, although cookie has many problems, its original purpose is to provide an identity record for stateless HTTP requests, and it cannot be completely abandoned. Under the premise of doing a good job of security, it is still the simplest solution. The following are some common protections measure.
check source
Each http request of the browser will carry two header fields. Referer and Origin represent the requested url and the source of the request respectively. Referer is becoming an abandoned field because it contains all the paths, while Origin only has the protocol, domain name and port. In line with the rules defined by the SOP source, we use the Origin judgment to be the most appropriate.
Origin verification can only be used as an auxiliary method, not a final judgment. Because the Origin field has continuously exposed many vulnerabilities in major browsers, it cannot be strictly relied upon.
CSRF Token
This is a textbook-style solution, but I still want to focus on it, because I recently researched a web site of a major domestic manufacturer and found a serious scrf loophole.
As mentioned above, the root of CSRF vulnerability lies in trust cookie, token is a random card we assign to each user, and each request checks the token to determine whether the source is correct. This token essentially replaces the role of the origin of the verification source, but is generated and controlled by ourselves.
someone will ask? Can the attacker get/use this token? The answer is that due to the existence of the SOP policy, the attacker cannot get any data of the third-party domain, including cookies and other content.
However, if your token is not properly stored, it can still be exploited. The essence of scrf is to use the characteristics of cookie to carry, so CSRF token cannot be saved in cookie, other than that, it can be used anywhere, such as dom, localstorage, etc.
Random cookie verification
SOP does not prevent cookies from being sent across domains, but does prevent cookie fetching. We can use this feature to return a random value for each request and set it in the cookie. In the next request, use js to take this value out of the cookie and splicing it into the parameters. When the background receives the interface, Check this parameter first. It can be determined whether it is a trusted source. Since the random value cannot be taken out by js in the third-party source, the request initiated by it will naturally be filtered out.
Samesite Cookies
The root of CSRF is that cookies can be sent across domains, Samesite Cookie (opens new window) is a draft drafted by Google to improve the HTTP protocol, in short, it is possible to declare whether cookies are limited to the first party or the same site context. Since it is a new protocol, while using this feature, you need to pay attention to the compatible version of the browser.
bypass SOP
Although scrf tokens can be used to protect CSRF attacks, cross-domain attacks often try to bypass SOP illegally by various means, and the most vulnerable parts are the users and developers themselves. Here are some examples.
iframe interface camouflage
CSRF tokens can protect the user interface from forgery, but if a target url is placed in an iframe of a controlled domain name, the iframe will load the token in the target url by default. An attacker could make the iframe transparent and elevate it to a trick button on the rest of the main interface. When the position of the inducement button just coincides with the button of a request in the iframe, the click is a "cross-domain request" without the user's knowledge. This attack is also called clickjacking(opens new window).
The way to deal with this is: the source that allows nesting can be defined through the X-Frame-Options parameter.
SOP and CORS
SOP is a restriction on different source resources, while CORS is an official policy of opening restrictions. Unreasonable use will bring risks, such as:
Access-Control-Allow-Origin: *
Setting too much permission is equivalent to not setting it.
source changes
window.domain can make changes to the current source, which may be needed in some scenarios where the subdomain communicates with the parent domain. Once the subdomain is changed to the parent domain via window.domain, which means a larger scope, then it will have cross-domain access under any subdomain.
// 对当前域 store.abc.com 进行更改
document.domain = abc.com
// hack.abc.com 可以对 store.abc.com 进行跨域访问
CSRF attack example (for testing only)
For security issues, it is often necessary to know oneself and the other in order to be prepared. Below are some examples of CSRF attacks.
<iframe >
// 目标网站
<form method="post" action="https://demodexx.com/modify-password">
// 通过接口分析得到对方的字段名
// 设置攻击者想要的新密码
<input name="password" value="123456">
<input type="button" value="点击领取 100万大奖">
</form>
</iframe>
When the user enters a source controlled by an attacker and induces a click to submit the form in the hidden form, at this time, it will automatically carry the demoxx cookie for submission. If the other party is in the login state, the password will be directly modified.
Forms through style camouflage are commonly used methods. It has several advantages over ajax requests. First, it has less compatibility problems. Second, it avoids cross-domain preflight requests (opens new window).
The following is an example of ajax simulation, the value of Content-Type is limited to one of three: text/plain, multipart/form-data, application/x-www-form-urlencoded, there will be no preflight request
const x = new XMLHttpRequest();
x.open('POST', 'url')
x.withCredentials = true // 允许携带 cookie
x.responseType='application/x-www-form-urlencoded';
const d = new FormData()
d.append('password', '12345')
x.send(d)
Knot
Many cross-domain security problems are caused by the unwritten rule of browser "default permission". The reason for this may be based on the open and interoperable web thinking, or browser manufacturers provide more open services in order to occupy more markets. free behavior.
In any case, for developers, the read and write permissions of front-end resources should not trust other third-party sources, and background services do not trust any requests (including their own domains) by default. Approach all security issues with a tacit rejection mentality.
——————
Document Information Title: Web Cross-Origin Request Security Issues
Published: January 24, 2022 Pseudonym: Chaos Fu Wang Original link: https://imwangfu.com/2022/01/web-csrf.html
Copyright statement: If you need to reprint, please email imwangfu@gmail.com and keep this statement ——————
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。