# CORS - Misconfigurations & Bypass

## What is CORS <a href="#what-is-cors" id="what-is-cors"></a>

The CORS (Cross-origin resource sharing) standard is needed because it **allows servers to specify who can access its assets** and which **HTTP request methods are allowed** from external resources.

In a **same-origin** policy, is needed that both the **server requesting** a resource and the server where the **resource** is located uses the same protocol (http://),domain name (internal-web.com) and the same **port** (80). Then, if the server forces the same-origin policy, only web pages from the same domain and port will be able to access the resources.

The following table shows how the same-origin policy will be applied in `http://normal-website.com/example/example.html` :

\*_Internet Explorer will allow this access because IE does not take account of the port number when applying the same-origin policy._

The specification of `Access-Control-Allow-Origin` allows for **multiple origins**, or the value **`null`**, or the wildcard **`*`**. However, **no browser supports multiple origins** and there are **restrictions** on the use of the **wildcard** `*`.(_The wildcard can only be used alone, this will fail_ _`Access-Control-Allow-Origin: https://*.normal-website.com`_ _and it cannot be used with_ _Access-Control-Allow-Credentials: true_)

This header is **returned by a server** when a website requests a cross-domain resource, with an `Origin` header added by the browser.

The **default** behaviour of cross-origin resource requests is for **requests** to be **passed without credentials** like cookies and the Authorization header. However, the cross-domain server can **permit reading** of the **response** when **credentials** are **passed** to it by setting the CORS **`Access-Control-Allow-Credentials`** header to **`true`**.

If the value is set to `true`then the browser will send credentials (cookies, authorization headers or TLS client certificates).

```
var xhr = new XMLHttpRequest();xhr.open('GET', 'http://example.com/', true); xhr.withCredentials = true; xhr.send(null);
```

```
fetch(url, {  credentials: 'include'  })
```

### Pre-flight request <a href="#pre-flight-request" id="pre-flight-request"></a>

Under certain circumstances, when a cross-domain request includes a **non-standard HTTP method or headers**, the cross-origin request is preceded by a **request** using the **`OPTIONS`** **method**, and the CORS protocol necessitates an initial check on what **methods and headers are permitted prior to allowing the cross-origin request**. This is called the **pre-flight check**. The server **returns a list of allowed methods** in addition to the **trusted origin** and the browser checks to see if the requesting website's method is allowed.

For **example**, this is a pre-flight request that is seeking to **use the** **`PUT`** **method** together with a **custom** request **header** called `Special-Request-Header`:

```
OPTIONS /data HTTP/1.1Host: ...Origin: https://normal-website.comAccess-Control-Request-Method: PUTAccess-Control-Request-Headers: Special-Request-Header
```

The server might return a response like the following:

```
HTTP/1.1 204 No Content...Access-Control-Allow-Origin: https://normal-website.comAccess-Control-Allow-Methods: PUT, POST, OPTIONSAccess-Control-Allow-Headers: Special-Request-HeaderAccess-Control-Allow-Credentials: trueAccess-Control-Max-Age: 240
```

* `Access-Control-Allow-Headers` Allowed headers
* `Access-Control-Expose-Headers`
* `Access-Control-Max-Age` Defines a maximum timeframe for caching the pre-flight response for reuse
* `Access-Control-Request-Headers` The header the cross-origin request wants to send
* `Access-Control-Request-Method` The method the cross-origin request wants to use
* `Origin` Origin of the cross-origin request (Set automatically by the browser)

![](https://gblobscdn.gitbook.com/assets%2F-L_2uGJGU7AVNRcqRvEi%2F-M7XNRS6GjhzsUs8rbSL%2F-M7XXNT77ojxkwN-NIXD%2Fpreflight.svg?alt=media\&token=2f0f94f5-4181-41cc-ac46-14163a1fa901)

Note that in a **GET/POST request no pre-flight request is sent** (the request is sent **directly**), but if you want to access the **headers/body of the response**, it must contains an _Access-Control-Allow-Origin_ header allowing it. **Therefore, CORS doesn't protect against CSRF (but it can be helpful).**

## Exploitable misconfigurations <a href="#exploitable-misconfigurations" id="exploitable-misconfigurations"></a>

Notice that most of the **real attacks require** **`Access-Control-Allow-Credentials`** to be set to **`true`** because this will allow the browser to send the credentials and read the response. Without credentials, many attacks become irrelevant; it means you can't ride on a user's cookies, so there is often nothing to be gained by making their browser issue the request rather than issuing it yourself.

One notable exception is when the **victim's network location functions as a kind of authentication.** You can use a victim’s browser as a proxy to bypass IP-based authentication and access intranet applications. In terms of impact this is similar to DNS rebinding, but much less fiddly to exploit.

### Reflected `Origin` in `Access-Control-Allow-Origin` <a href="#reflected-origin-in-access-control-allow-origin" id="reflected-origin-in-access-control-allow-origin"></a>

In the real world this cannot happen as **this 2 values of the headers are forbidden together**. It is also true that a lot of developers want to **allow several URLs in the CORS**, but subdomain wildcards or lists of URLs aren't allowed. Then, several developers **generates** the **`Access-Control-Allow-Origin`**&#x68;eader **dynamically**, and in more than one occasion they just **copy the value of the Origin header**.

In that case, the **same vulnerability might be exploited.**

In oder cases, the developer could check that the **domain** (_victimdomain.com_) **appears** in the **Origin header**, then, an attacker can use a domain called **`attackervictimdomain.com`** to steal the confidential information.

### The `null` Origin <a href="#the-null-origin" id="the-null-origin"></a>

`null` is a special value for the **Origin** header. The specification mentions it being triggered by redirects, and local HTML files. Some applications might whitelist the `null` origin to support local development of the application. This is nice because **several application will allow this value** inside the CORS and any **website can easily obtain the null origin using a sandboxed iframe**:

```
<iframe sandbox="allow-scripts allow-top-navigation allow-forms" src='data:text/html,'>iframe>
```

### **Regexp bypasses** <a href="#regexp-bypasses" id="regexp-bypasses"></a>

If you found the domain _victim.com_ to be **whitelisted** you should check if _victim.com.**attacker.com**_ is **whitelisted also**, or, in case you can **takeover some subdomain**, check if _**somesubdomain**.victim.com_ is whitelisted.

### **Advance Regexp bypasses** <a href="#advance-regexp-bypasses" id="advance-regexp-bypasses"></a>

Most of the regex used to identify the domain inside the string will focus on alphanumeric ASCII characters and `.-` . Then, something like `victimdomain.com{.attacker.com` inside the Origin header will be interpreted by the regexp as if the domain was `victimdomain.com` but the browser (in this case Safari supports this character in the domain) will access the domain`attacker.com` .

&#x20;The `_` character (in subdomains) is not only supported in Safari, but also in Chrome and Firefox!

**Then, using one of those subdomains you could bypass some "common" regexps to find the main domain of a URL.**

**For more information and settings of this bypass check:** [**https://www.corben.io/advanced-cors-techniques/**](https://www.corben.io/advanced-cors-techniques/) **and** [**https://medium.com/bugbountywriteup/think-outside-the-scope-advanced-cors-exploitation-techniques-dad019c68397**](https://medium.com/bugbountywriteup/think-outside-the-scope-advanced-cors-exploitation-techniques-dad019c68397)**​**

![](https://gblobscdn.gitbook.com/assets%2F-L_2uGJGU7AVNRcqRvEi%2F-LyJQ930-58wtT7nPOHc%2F-LyJsi-DUjMoa5wbq0H-%2Fimage.png?alt=media\&token=7ed4c1ba-b468-4f35-a2f7-7cf1c292e5f1)

### From XSS inside a subdomain <a href="#from-xss-inside-a-subdomain" id="from-xss-inside-a-subdomain"></a>

One defensive mechanism developers use against CORS exploitation is to white-list domains that frequently requests access for information. However, this isn’t entirely secure, because if even **one** of the subdomains of the **whitelisted** domain is **vulnerable** to other exploits such as **XSS**, it can enable CORS exploitation.

Let us consider an example, the following code shows the configuration that allows subdomains of _requester.com_ to access resources of _provider.com_.

```
if ($_SERVER['HTTP_HOST'] == '*.requester.com') {  else{ } 
```

Assuming that a user has access to sub.requester.com but not requester.com, and assuming that `sub.requester.com` is vulnerable to XSS. The user can exploit `provider.com` by using cross-site scripting attack method.

### **Server-side cache poisoning** <a href="#server-side-cache-poisoning" id="server-side-cache-poisoning"></a>

If the stars are aligned we may be able to use server-side cache poisoning via HTTP header injection to create a [stored XSS](https://portswigger.net/web-security/cross-site-scripting/stored) vulnerability.

If an application **reflects** the **Origin header** without even checking it for illegal characters like **\r**, we effectively have a **HTTP header injection vulnerability against IE/Edge users as Internet Explorer and Edge view \r (0x0d) as a valid HTTP header terminator**:`GET / HTTP/1.1 Origin: z[0x0d]Content-Type: text/html; charset=UTF-7`

Internet Explorer sees the response as:

`HTTP/1.1 200 OK Access-Control-Allow-Origin: z Content-Type: text/html; charset=UTF-7`

This isn't directly exploitable because there's no way for an attacker to make someone's web browser send such a malformed header, but I can **manually craft this request in Burp Suite and a server-side cache may save the response and serve it to other people**. The payload I've used will change the page's character set to **UTF-7**, which is notoriously useful for creating XSS vulnerabilities.

### **Client-Side cache poisoning** <a href="#client-side-cache-poisoning" id="client-side-cache-poisoning"></a>

You may have occasionally encountered a page with [reflected XSS](https://portswigger.net/web-security/cross-site-scripting/reflected) in a custom HTTP header. Say a web page reflects the contents of a custom header without encoding:`GET / HTTP/1.1 Host: example.com X-User-id: HTTP/1.1 200 OK Access-Control-Allow-Origin: * Access-Control-Allow-Headers: X-User-id Content-Type: text/html ... Invalid user:`&#x20;

With CORS, we can send any value in the Header. By itself, **that's useless** since the response containing our **injected JavaScript won't be rendered**. However, **if Vary: Origin hasn't been specified** the response **may be stored in the browser's cache and displayed directly when the browser navigates to the associated URL**. I've made a fiddle to [attempt this attack on a URL of your choice](https://jsfiddle.net/3gk8u8wu/3/). Since this attack uses client-side caching, it's actually quite reliable.

```
<script>function gotcha() { location=url }var req = new XMLHttpRequest();url = 'https://example.com/'; req.onload = gotcha;req.open('get', url, true);req.setRequestHeader("X-Custom-Header", "")req.send();script>
```

## Bypass <a href="#bypass" id="bypass"></a>

### XSSI (Cross-Site Script Inclusion) / JSONP <a href="#xssi-cross-site-script-inclusion-jsonp" id="xssi-cross-site-script-inclusion-jsonp"></a>

XSSI designates a kind of vulnerability which exploits the fact that, when a resource is included using the `script` tag, the SOP doesn’t apply, because scripts have to be able to be included cross-domain. An attacker can thus read everything that was included using the `script` tag.

This is especially interesting when it comes to dynamic JavaScript or JSONP when so-called ambient-authority information like cookies are used for authentication. The cookies are included when requesting a resource from a different host. BurpSuite plugin: [https://github.com/kapytein/jsonp](https://github.com/kapytein/jsonp)​

**​**[**Read more about the difefrent types of XSSI and how to exploit them here.**](https://book.hacktricks.xyz/pentesting-web/xssi-cross-site-script-inclusion)**​**

Try to add a **`callback`** **parameter** in the request. Maybe the page was prepared to send the data as JSONP. In that case the page will send back the data with `Content-Type: application/javascript` which will bypass the CORS policy.

![](https://gblobscdn.gitbook.com/assets%2F-L_2uGJGU7AVNRcqRvEi%2F-M5WB0X4jJjKGl49KShg%2F-M5WHdzWPh8WOP4YSvDT%2Fimage.png?alt=media\&token=113566d9-71f9-4ce6-9453-d7d7ca6d7a30)

### Easy (useless?) bypass <a href="#easy-useless-bypass" id="easy-useless-bypass"></a>

You can ask a web-application to make a request for you and send back the response. This will bypass the the **`Access-Control-Allow-Origin`** but notice that the **credentials to the final victim won't be sent** as you will be **contacting a different domain** (the one that will make the request for you).

CORS-escape provides a **proxy** that **passes** on our **request** along with its **headers**, and it also **spoof** the **Origin** header (Origin = **requested domain**). So the **CORS policy is bypassed**. The source code is [on Github](https://github.com/shalvah/cors-escape), so you can **host your own**.

```
xhr.open("GET", "https://cors-escape.herokuapp.com/https://maximum.blog/@shalvah/posts");
```

Proxying is kinda like “passing on" your request, exactly as you sent it. We could solve this in an alternative way that still involves someone else making the request for you, but this time, **instead of using passing on your request, the server makes its own request, but with whatever parameters you specified.**

### DNS Rebinding <a href="#dns-rebinding" id="dns-rebinding"></a>

![](https://gblobscdn.gitbook.com/assets%2F-L_2uGJGU7AVNRcqRvEi%2F-Lr64R-yaKQCzLx4HFVG%2F-Lr64YANlX1mUgl53qPi%2Fimage.png?alt=media\&token=6637ec18-cbe3-42ec-ad9e-18026b278f1a)

Basically you make the **victim access your page**, then you change the **DNS of your domain (the IP)** and make it **points** to your **victims web page**. You make your **victim execute** (**JS**) something when the **TLS is** **over** so a new DNS request will be made and then you will be able to gather the information (as you will always mantains **the user in your domain**, he won't send **any cookie** to the victim server, so this options abuses the speciall privileges of the IP of the victim).

Also, I don't know why this attack plays with the TLS of the DNS instead of just having a subdomain always pointing to the victims IP.

**Fuzz possible misconfigurations in CORS policies**

*
*
*
*

## References <a href="#references" id="references"></a>
