Cross-Origin Resource Sharing (CORS) – Overview
Cross-Origin Resource Sharing (CORS) is a security mechanism implemented by browsers to control how web applications from one origin can interact with resources on a different origin using specific HTTP headers.
Same-Origin Policy (SOP)
The Same-Origin Policy (SOP) is a fundamental security concept in browsers that restricts how documents or scripts loaded from one origin can interact with resources from another origin.
- SOP prevents reading between different origins, not writing.
-
An origin is defined by the combination of:
- Scheme (protocol, e.g.,
http,https) - Hostname (e.g.,
example.com) - Port (e.g.,
:8080)
- Scheme (protocol, e.g.,
Key CORS Headers
Access-Control-Allow-Origin
This header specifies which origins are permitted to access the resource.
- Specific origin: For example,
https://example.com - Wildcard (
*): Allows all origins, but cannot be used when credentials are involved. -
null: A special value representing requests originating from:- Sandboxed documents (e.g.,
<iframe sandbox>) - Files loaded via the
file://scheme - Some browser extensions or data URLs
- Sandboxed documents (e.g.,
Misconfigured servers that trust
nullas an origin may become vulnerable to attacks originating from these restricted contexts.
Access-Control-Allow-Credentials
This header indicates whether the response to the request can be exposed when the request’s credentials mode is include.
- Accepts the value
trueorfalse. - If set to
true, theAccess-Control-Allow-Originheader must specify an explicit origin, not a wildcard (*).
⚠️ Important:
Access-Control-Allow-Origin: *cannot be used withAccess-Control-Allow-Credentials: true— browsers will block it.
CORS Misconfiguration Risks
Misconfigurations in CORS can lead to serious security issues such as:
- Unauthorized Data Access: Sensitive data exposed to malicious third-party websites.
- Credential Theft: Access to protected endpoints using victim session cookies.
- Cross-Site Scripting (XSS): When combined with reflection or parsing issues.
- Exploitation via
nullorigin: If a server incorrectly trustsnull, it may be exploitable from local or sandboxed environments.
JavaScript Templates to Test for CORS Vulnerabilities
These templates can be used in a browser console to test whether a cross-origin endpoint is accessible and leaks sensitive information.
Method 1
var req = new XMLHttpRequest();
req.onload = function () {
alert(this.responseText);
};
req.open('GET', 'https://target-site.com/endpoint', true);
req.withCredentials = true;
req.send(null);
Method 2
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
alert(xhr.responseText);
}
};
xhr.open('GET', 'http://targetapp/api/v1/user', true);
xhr.withCredentials = true;
xhr.send(null);
These scripts attempt to retrieve sensitive information from the target site using the victim’s authenticated session.