TExcelTAD
Home › Web Application Security: OWASP Top 10, APIs & Authentication › CORS: Preflight, Credentials and the Wildcard Trap

CORS: Preflight, Credentials and the Wildcard Trap

The same-origin policy stops evil.example from reading api.shop.lab.test. But the shop's own front end on shop.lab.test is a different origin from its API too, and it needs to read the answers. Cross-Origin Resource Sharing (CORS) is how a server tells the browser "this other origin may read my responses". It is an opt-in that relaxes SOP, so every CORS mistake is a hole in it, and the most common mistake is a server that, tired of CORS errors, simply says yes to everyone. This lesson builds such an API on loopback, shows what an attacker's page would gain, and replaces the reflection with an allow-list.

Definitions (the Fetch standard)

  • Origin request header: the browser's statement of which origin the calling script runs in. Scripts can't forge it in a browser; curl can, which doesn't matter, because CORS protects browser users, not servers.
  • Access-Control-Allow-Origin (ACAO): the one origin allowed to read the response, or * for any origin.
  • Access-Control-Allow-Credentials: true: the response may be read even though the request carried cookies or HTTP authentication. Browsers refuse * together with credentials: the server must name the origin.
  • Simple request: GET, HEAD or POST with only "safe" headers and a Content-Type of text/plain, application/x-www-form-urlencoded or multipart/form-data. Sent directly; CORS only decides whether the script may read the answer.
  • Preflight: for anything else (PUT, DELETE, JSON bodies, Authorization headers), the browser first sends OPTIONS with Access-Control-Request-Method and Access-Control-Request-Headers; only if the answer allows them is the real request sent.
  • Vary: Origin: tells caches that the response differs by origin, so one origin's ACAO isn't served to another.

A reflecting API and its fix

The session starts the toy API on 127.0.0.1:8000. With argument reflect it copies any Origin into ACAO and allows credentials, a pattern found in real code because it makes every CORS error disappear. With allowlist it answers only for https://shop.lab.test. curl plays the browser: it sends the Origin a page on that origin would send, plus the victim's cookie, and we print the CORS headers the browser would base its decision on.

bash · try it yourself
cat > api.py <<'PY'
import json, sys
from wsgiref.simple_server import make_server, WSGIRequestHandler

MODE = sys.argv[1]
ALLOWED = {"https://shop.lab.test"}

class Quiet(WSGIRequestHandler):
    def log_message(self, *args):
        pass

def cors_headers(origin):
    if MODE == "reflect" and origin:
        return [("Access-Control-Allow-Origin", origin), ("Access-Control-Allow-Credentials", "true")]
    if MODE == "allowlist" and origin in ALLOWED:
        return [("Access-Control-Allow-Origin", origin), ("Access-Control-Allow-Credentials", "true"),
                ("Vary", "Origin")]
    return [("Vary", "Origin")]

def app(environ, start_response):
    origin = environ.get("HTTP_ORIGIN")
    h = cors_headers(origin)
    if environ["REQUEST_METHOD"] == "OPTIONS":                 # preflight
        if any(k == "Access-Control-Allow-Origin" for k, _ in h):
            h += [("Access-Control-Allow-Methods", "GET, PUT"),
                  ("Access-Control-Allow-Headers", "Content-Type"), ("Access-Control-Max-Age", "600")]
        start_response("204 No Content", h)
        return [b""]
    logged_in = "sid=lab-alice" in environ.get("HTTP_COOKIE", "")
    data = {"user": "alice", "email": "alice@lab.test", "api_key": "lab-key-91c"} if logged_in else {"error": "login"}
    start_response("200 OK", [("Content-Type", "application/json")] + h)
    return [json.dumps(data).encode() + b"\n"]

make_server("127.0.0.1", 8000, app, handler_class=Quiet).serve_forever()
PY
show() {   # $1 = Origin, rest = extra curl args; print status line, CORS headers and body
  curl -s -i -H "Origin: $1" -b 'sid=lab-alice' "${@:2}" http://127.0.0.1:8000/api/me |
    tr -d '\r' | grep -E '^(HTTP/|Access-Control|Vary|\{)' | sed 's/^/    /'
}
for mode in reflect allowlist; do
  python3 api.py $mode &
  for i in $(seq 50); do curl -s -o /dev/null http://127.0.0.1:8000/ && break; sleep 0.1; done
  echo "=== mode: $mode"
  echo "  page on https://shop.lab.test reads /api/me:";   show https://shop.lab.test
  echo "  page on https://evil.example reads /api/me:";    show https://evil.example
  echo "  sandboxed or file:// page (Origin: null):";      show null
  echo "  preflight for PUT from evil.example:";           show https://evil.example -X OPTIONS -H 'Access-Control-Request-Method: PUT'
  kill %1; wait 2>/dev/null
done
=== mode: reflect
  page on https://shop.lab.test reads /api/me:
    HTTP/1.0 200 OK
    Access-Control-Allow-Origin: https://shop.lab.test
    Access-Control-Allow-Credentials: true
    {"user": "alice", "email": "alice@lab.test", "api_key": "lab-key-91c"}
  page on https://evil.example reads /api/me:
    HTTP/1.0 200 OK
    Access-Control-Allow-Origin: https://evil.example
    Access-Control-Allow-Credentials: true
    {"user": "alice", "email": "alice@lab.test", "api_key": "lab-key-91c"}
  sandboxed or file:// page (Origin: null):
    HTTP/1.0 200 OK
    Access-Control-Allow-Origin: null
    Access-Control-Allow-Credentials: true
    {"user": "alice", "email": "alice@lab.test", "api_key": "lab-key-91c"}
  preflight for PUT from evil.example:
    HTTP/1.0 204 No Content
    Access-Control-Allow-Origin: https://evil.example
    Access-Control-Allow-Credentials: true
    Access-Control-Allow-Methods: GET, PUT
    Access-Control-Allow-Headers: Content-Type
    Access-Control-Max-Age: 600
=== mode: allowlist
  page on https://shop.lab.test reads /api/me:
    HTTP/1.0 200 OK
    Access-Control-Allow-Origin: https://shop.lab.test
    Access-Control-Allow-Credentials: true
    Vary: Origin
    {"user": "alice", "email": "alice@lab.test", "api_key": "lab-key-91c"}
  page on https://evil.example reads /api/me:
    HTTP/1.0 200 OK
    Vary: Origin
    {"user": "alice", "email": "alice@lab.test", "api_key": "lab-key-91c"}
  sandboxed or file:// page (Origin: null):
    HTTP/1.0 200 OK
    Vary: Origin
    {"user": "alice", "email": "alice@lab.test", "api_key": "lab-key-91c"}
  preflight for PUT from evil.example:
    HTTP/1.0 204 No Content
    Vary: Origin

Read the two modes against the browser's rule: a script may read the response only if ACAO equals its origin (and, with cookies, Allow-Credentials: true is present).

  • In reflect mode the API hands every origin, including https://evil.example and the opaque null origin of sandboxed frames and local files, a perfect ACAO with credentials. Any page the logged-in victim visits can fetch('https://api.shop.lab.test/api/me', {credentials: 'include'}) and read the e-mail address and the API key. The preflight is approved too, so the attacker's page can also send PUT requests with JSON bodies.
  • In allowlist mode only the shop's own origin gets ACAO. The other requests still reach the server (CORS is not access control for the server), but the browser hides the answers from the calling script and refuses to send the PUT after the failed preflight.

Why not just *?

Access-Control-Allow-Origin: * is correct and safe for public, uncredentialed data: fonts, public JSON, open APIs keyed by tokens in headers. Browsers won't let a * response be read when the request carried cookies, so * can't leak a session. The trap is what developers do next: when the credentialed request fails, they reflect Origin to "make it work", which is strictly worse than *. If you need credentials, you need an allow-list.

The same-origin lab runs the browser's side of these rules. Its page on https://blog.example.com sends a credentialed PUT with an X-Custom header to https://shop.example.com, so the browser first sends an OPTIONS preflight without cookies. The server names the page's origin but doesn't allow credentials, so the preflight fails ("credentials need Access-Control-Allow-Credentials: true") and the PUT is never sent. Switch the server to ACAO: * and it still fails: * is not allowed with credentials. Set the fetch credentials back to 'same-origin' and * works, but no cookie travels. Only the exact origin plus Allow-Credentials: true gives a cookie and a readable response, the setting you should reserve for origins you trust.

fetch(url, { method: "PUT", headers: { "X-Custom": "1" }, credentials: "include" })page (script runs here)https://blog.example.comhttps://shop.example.comcookie session: SameSite=LaxSecure; HttpOnlyOPTIONS (preflight, no cookies)204: not allowed✕ not sent✕same origin: no (host differs)✓same site: yes (same scheme and registrable domain example.com)✕preflight: fails (credentials need Access-Control-Allow-Credentials: true)✕request sent: no✕cookie attached: no (request not sent)✕script reads the response: no (the request was never sent)

How CORS misconfigurations are detected

  • Testing: send requests with Origin: https://evil.example, Origin: null, and look-alikes of the real origin (https://shop.lab.test.evil.example, https://evilshop.lab.test, http://shop.lab.test). Any ACAO that echoes them with Allow-Credentials: true is a finding. Burp Suite and ZAP have checks for exactly this.
  • Code review: ACAO set from the request's Origin; origin checks with startswith, endswith, in or unanchored regular expressions (/shop\.lab\.test/ also matches shop.lab.test.evil.example); null in the allow-list; framework settings like origin: true or allow_origins=["*"] with allow_credentials=True.
  • Logs: API requests with Origin values you don't own, especially to endpoints returning personal data.

How it is fixed

  1. An exact allow-list of full origins (scheme, host and port), compared as strings, never null.
  2. Access-Control-Allow-Credentials: true only for those origins, and only where cookies are really needed.
  3. Vary: Origin on every response whose CORS headers depend on the request.
  4. Preflight answers limited to the methods and headers the front end uses; a modest Max-Age.
  5. Remember that CORS is about reading. The server still needs authentication, authorization and CSRF protection for state changes, because simple cross-origin requests are sent whatever the CORS headers say.

Pitfalls

  • Treating CORS as a firewall. curl and server-side code ignore it. It protects users' browsers from other sites, nothing else.
  • Trusting all subdomains (*.lab.test): one XSS or one subdomain takeover anywhere in the zone then reads your API.
  • Allowing null "for local testing" lets any sandboxed iframe on any site read the API.

Practice

1. A server sends Access-Control-Allow-Origin: * and Access-Control-Allow-Credentials: true. Can evil.example read a logged-in user's data?

No: browsers reject that combination for credentialed requests, so the read fails. It is still a sign that the developer misunderstands CORS; check whether other endpoints reflect the origin instead.

2. The check is if origin.endswith("shop.lab.test"). Give an origin that passes and shouldn't.

http://shop.lab.test (plain HTTP, so anyone on the network path can inject a page with that origin), https://shop.lab.test:8443 (another port, possibly another service), and any other host whose name ends that way, such as https://evilshop.lab.test, if anyone else can get such a name in the zone. Compare against a set of exact origins.

Test yourself

What does CORS control?

  1. Which clients may send requests to the server
  2. Which other origins' scripts may read the server's responses in a browser
  3. Which cookies are sent
  4. Whether TLS is used

Why is reflecting the Origin header with Allow-Credentials worse than *?

  1. It is slower
  2. Browsers refuse * with credentials, but a reflected origin with credentials lets any site read users' authenticated data
  3. Reflection breaks preflight
  4. It isn't worse

Which request triggers a preflight?

  1. A GET for an image
  2. A form POST with application/x-www-form-urlencoded
  3. A fetch with method PUT and a JSON body
  4. Following a link

Why add Vary: Origin?

  1. To speed up responses
  2. So caches don't serve a response with one origin's ACAO to another origin
  3. It is required by HTTP/1.0
  4. To enable cookies

In the same-origin lab, a credentialed fetch PUT from https://blog.example.com meets a server that answers ACAO: *. What happens?

  1. The PUT is sent and the response is readable
  2. The preflight fails, because * is not allowed with credentials, so the PUT is never sent
  3. The PUT is sent without the cookie
  4. The browser upgrades * to the page origin