Scanners love this one. You send a request with Origin: https://evil-attacker.test, the response comes back with Access-Control-Allow-Origin: https://evil-attacker.test, and the report says "CORS misconfiguration, high".
Sometimes that really is a cross-origin data leak. Sometimes it's a public endpoint that returns nothing an attacker couldn't fetch directly, or the session cookie never reaches a cross-site request anyway. The header alone doesn't tell you which. This article covers what CORS actually does, the misconfigurations that matter, how to find them quickly, and how to show a real leak with your own test account before you call it a vulnerability.
Only test applications you own or are explicitly authorized to test. Every host below is a stand-in.
What CORS actually does
Browsers enforce the same-origin policy: a script on https://evil-attacker.test can send requests to https://api.example.com, but it can't read the responses. CORS is how a server relaxes that rule. It tells the browser which other origins may read its responses.
Three details decide whether a misconfiguration is exploitable:
- CORS controls reading, not sending. MDN notes that simple cross-origin requests reach the server without any opt-in. CORS decides whether the calling page gets to see the response. It's not CSRF protection and it's not access control. PortSwigger makes the same point: CORS never replaces server-side checks.
-
The wildcard can't carry credentials. If a request is made with cookies (
credentials: "include"infetch), the browser rejectsAccess-Control-Allow-Origin: *. The server must name one explicit origin and sendAccess-Control-Allow-Credentials: true, or the browser throws the response away. -
Reading private data needs cookies. An attacker's page can make your browser attach your cookies, but it can't attach your bearer token from another site's
localStorage. So the dangerous case is cookie-authenticated endpoints.
Point 2 explains why developers end up with the bug. They want credentialed requests from several front-ends, * doesn't work, so they echo back whatever Origin arrives. That's the most common CORS bug.
The misconfigurations that matter
PortSwigger's CORS topic describes four patterns. They all come down to the server trusting an origin it shouldn't.
-
Reflected origin. The server copies the request's
OriginintoAccess-Control-Allow-Originand setsAccess-Control-Allow-Credentials: true. Any website can then read authenticated responses. -
Trusted
null. Teams allowlistnullfor local development. But browsers also sendOrigin: nullfrom sandboxed iframes,file:pages and some cross-origin redirects, and an attacker can serve a sandboxed iframe from any site. -
Broken origin matching. A check like "starts with
https://app.example.com" also matcheshttps://app.example.com.evil-attacker.test. "Ends withexample.com" also matcheshttps://evil-attacker-example.com. Unanchored regexes fail in the same ways. -
Trusting weaker origins. Allowing
http://app.example.com(plain HTTP) or every subdomain means anyone who can run script there, through an XSS bug or a network position on the HTTP origin, inherits the API's trust.
Finding it: six requests per endpoint
You don't need a browser for discovery. CORS headers are just response headers, so send the same request with different Origin values and compare. Start with endpoints that return user-specific data: /api/me, account settings, API keys, billing, anything a session cookie unlocks.
One request by hand:
curl -s -o /dev/null -D - https://api.example.com/api/me \
-H "Origin: https://evil-attacker.test" | grep -i '^access-control\|^vary'
For more than a couple of endpoints, a small script is quicker. This one only uses the Python standard library:
#!/usr/bin/env python3
"""Send one GET per Origin variant and print what the server allows.
Only run it against systems you own or are authorized to test."""
import sys
import urllib.request
url = sys.argv[1] # e.g. https://api.example.com/api/me
trusted = sys.argv[2] # e.g. app.example.com
origins = [
"https://evil-attacker.test", # plain reflection
"null", # sandboxed iframe / file: / redirects
f"https://{trusted}.evil-attacker.test", # prefix match
f"https://evil-attacker-{trusted}", # suffix match
f"http://{trusted}", # insecure protocol
f"https://sub.{trusted}", # any-subdomain trust
]
for origin in origins:
req = urllib.request.Request(url, headers={"Origin": origin})
with urllib.request.urlopen(req, timeout=10) as resp:
acao = resp.headers.get("Access-Control-Allow-Origin")
acac = resp.headers.get("Access-Control-Allow-Credentials")
vary = resp.headers.get("Vary")
flag = " <-- reflected with credentials" if acao == origin and acac == "true" else ""
print(f"{origin:45} ACAO={acao!s:35} ACAC={acac!s:5} Vary={vary}{flag}")
Run it as python3 cors_probe.py https://api.example.com/api/me app.example.com. Against a local test server that reflects every origin, every line gets flagged:
https://evil-attacker.test ACAO=https://evil-attacker.test ACAC=true Vary=None <-- reflected with credentials
null ACAO=null ACAC=true Vary=None <-- reflected with credentials
https://app.example.com.evil-attacker.test ACAO=https://app.example.com.evil-attacker.test ACAC=true Vary=None <-- reflected with credentials
...
Against the fixed version further down, every one of those origins gets no CORS headers, and Vary: Origin is present.
Some servers only add CORS headers when a session cookie is present, or only on certain paths. If an endpoint looks clean, repeat the probe with your test account's cookie and on a few more routes.
The sub. line is worth a second look even when it's "allowed by design". If the API trusts every subdomain, the question becomes whether any subdomain has an XSS bug or still serves plain HTTP. That's a separate finding you'd need to prove on its own.
Detection isn't proof: four checks before you report
A flagged line from the script is a lead, not a finding. Before writing it up, confirm all four of these:
-
The attacker origin is allowed with credentials.
Access-Control-Allow-Originechoes your test origin andAccess-Control-Allow-Credentials: trueis set. A wildcard or a reflection without the credentials header lets a page read only what it could get without cookies. - The response is actually private. It must contain data that depends on who's logged in: an email, an API key, a CSRF token, account details. A reflected origin on a public price list leaks nothing.
-
Authentication rides on a cookie. If the endpoint only accepts an
Authorization: Bearerheader the front-end adds from its own storage, a cross-site page can't supply it. Then the reflection is a hardening issue, not a data leak. -
The cookie is sent on a cross-site request. MDN's SameSite docs say
Laxcookies aren't sent on cross-sitefetch()calls, and some browsers treat a cookie with noSameSiteattribute asLax. You usually needSameSite=None; Secure. Browser third-party cookie policies differ too, so test in a real browser rather than assuming.
If all four hold, you have a real cross-origin data exposure. If one fails, say which in your notes and report it at the right severity, or as a hardening recommendation.
Proving it safely
The proof is short: a page on an origin you control reads your own test account's data from the target, in a real browser.
- Create a test account on the in-scope application and log in normally in your browser.
- Host this page on an origin you control. In a lab that's the provided exploit server. Otherwise a local page served from a different origin works:
<!doctype html>
<meta charset="utf-8">
<title>CORS PoC (authorized test)</title>
<pre id="out">loadingβ¦</pre>
<script>
fetch("https://api.example.com/api/me", { credentials: "include" })
.then((r) => r.text())
.then((body) => { document.getElementById("out").textContent = body; })
.catch((e) => { document.getElementById("out").textContent = "blocked: " + e; });
</script>
- Open it in the same browser. If your test account's email or key appears on the page, the browser let a foreign origin read authenticated data. If you see
blocked: TypeErrorβ¦, the browser refused, and the DevTools console usually explains why.
The PoC shows the data on screen instead of sending it anywhere. That's enough for the report, and you never collect anything outside your own test account. For a null-origin finding, put the same script inside an <iframe sandbox="allow-scripts" srcdoc="β¦"> so the request goes out with Origin: null.
In the report, include the request with your test Origin, the response headers, a screenshot of the PoC page showing your test account's data (with anything sensitive redacted), and which of the four checks you verified.
Fixing it
The fix is the same in any stack: compare the incoming Origin against an exact list of trusted origins, and send nothing for anything else. Here's a dependency-free Node version. The same function works as Express middleware.
const ALLOWED_ORIGINS = new Set([
"https://app.example.com",
"https://admin.example.com",
]);
function applyCors(req, res) {
const origin = req.headers.origin;
res.setHeader("Vary", "Origin"); // caches must key on Origin
if (origin && ALLOWED_ORIGINS.has(origin)) { // exact string match, no regex
res.setHeader("Access-Control-Allow-Origin", origin);
res.setHeader("Access-Control-Allow-Credentials", "true");
}
// anything else (including "null") gets no CORS headers at all
}
The rules behind it:
-
Exact matches only. Full scheme, host and port, compared as strings. No
startsWith,endsWith,includes, or regex you haven't anchored and tested against the prefix and suffix tricks above. -
Never allow
null. Use a real local origin likehttp://localhost:5173in a development-only config instead. - HTTPS origins only in production lists.
-
Send
Vary: Originwhenever the allowed origin depends on the request. MDN recommends it so a cache doesn't serve one origin's CORS headers to another. -
Use
*only for truly public, cookie-free resources. It's fine on a public API that needs no credentials. -
If you need preflighted requests (custom headers,
PUT,DELETE), answerOPTIONSwith the same origin check plus explicitAccess-Control-Allow-MethodsandAccess-Control-Allow-Headers. - Keep your real access control on the server. CORS decides who can read a response in a browser. It doesn't decide who can call your API.
Then re-run the probe and the PoC against the fix. The probe should show no CORS headers for any of the six origins, and the PoC page should show blocked. That's how you know the fix holds, not just that the code changed.
Try it yourself
PortSwigger's Web Security Academy has free labs for exactly these patterns:
- CORS vulnerability with basic origin reflection
- CORS vulnerability with trusted null origin
- CORS vulnerability with trusted insecure protocols
Work through them with the probe script first, then the PoC page. The labs give you an exploit server for the "victim" step, so you can practise the whole chain on a target that exists for this purpose. Outside labs, stick to programs and systems where you have written permission.
Wrapping up
A reflected Origin header is easy to find and easy to over-report. What makes it a vulnerability is a chain: an attacker-controlled origin allowed with credentials, a private response, cookie-based auth, and a cookie the browser actually sends cross-site. Check all four, prove the read with your own test account in a real browser, and your report will hold up. Fix it with an exact allowlist and Vary: Origin, then prove the fix the same way.
Further reading
- PortSwigger Web Security Academy: Cross-origin resource sharing (CORS)
- PortSwigger: CORS and the Access-Control-Allow-Origin response header
- MDN: Cross-Origin Resource Sharing (CORS)
- MDN: Access-Control-Allow-Origin (including CORS and caching)
- MDN: Set-Cookie, the SameSite attribute
- CWE-942: Permissive Cross-domain Security Policy with Untrusted Domains
I'm Krishna, a pentester and the founder of Xalgorix, an open-source AI pentester that only reports vulnerabilities it has actually exploited.
π If this was useful, follow me for more hands-on web & API security write-ups.
π Connect with me on LinkedIn: https://www.linkedin.com/in/xalgord/

Top comments (0)