Dev.to Security πŸ” Cybersecurity πŸ‘ 0 πŸ“– 9 min read

🌐 CORS Misconfigurations: Find the Reflected Origin, Then Prove It

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".

🌐 CORS Misconfigurations: Find the Reflected Origin, Then Prove It

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:

  1. 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.
  2. The wildcard can't carry credentials. If a request is made with cookies (credentials: "include" in fetch), the browser rejects Access-Control-Allow-Origin: *. The server must name one explicit origin and send Access-Control-Allow-Credentials: true, or the browser throws the response away.
  3. 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 Origin into Access-Control-Allow-Origin and sets Access-Control-Allow-Credentials: true. Any website can then read authenticated responses.
  • Trusted null. Teams allowlist null for local development. But browsers also send Origin: null from 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 matches https://app.example.com.evil-attacker.test. "Ends with example.com" also matches https://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:

Four checks that turn a reflected Origin into a proven CORS finding

  1. The attacker origin is allowed with credentials. Access-Control-Allow-Origin echoes your test origin and Access-Control-Allow-Credentials: true is set. A wildcard or a reflection without the credentials header lets a page read only what it could get without cookies.
  2. 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.
  3. Authentication rides on a cookie. If the endpoint only accepts an Authorization: Bearer header 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.
  4. The cookie is sent on a cross-site request. MDN's SameSite docs say Lax cookies aren't sent on cross-site fetch() calls, and some browsers treat a cookie with no SameSite attribute as Lax. You usually need SameSite=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.

  1. Create a test account on the in-scope application and log in normally in your browser.
  2. 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>
  1. 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 like http://localhost:5173 in a development-only config instead.
  • HTTPS origins only in production lists.
  • Send Vary: Origin whenever 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), answer OPTIONS with the same origin check plus explicit Access-Control-Allow-Methods and Access-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

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/

πŸ“° Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.