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)
Originrequest header: the browser's statement of which origin the calling script runs in. Scripts can't forge it in a browser;curlcan, 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,HEADorPOSTwith only "safe" headers and aContent-Typeoftext/plain,application/x-www-form-urlencodedormultipart/form-data. Sent directly; CORS only decides whether the script may read the answer. - Preflight: for anything else (
PUT,DELETE, JSON bodies,Authorizationheaders), the browser first sendsOPTIONSwithAccess-Control-Request-MethodandAccess-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.
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
reflectmode the API hands every origin, includinghttps://evil.exampleand the opaquenullorigin of sandboxed frames and local files, a perfect ACAO with credentials. Any page the logged-in victim visits canfetch('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 sendPUTrequests with JSON bodies. - In
allowlistmode 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 thePUTafter 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.
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 withAllow-Credentials: trueis a finding. Burp Suite and ZAP have checks for exactly this. - Code review: ACAO set from the request's
Origin; origin checks withstartswith,endswith,inor unanchored regular expressions (/shop\.lab\.test/also matchesshop.lab.test.evil.example);nullin the allow-list; framework settings likeorigin: trueorallow_origins=["*"]withallow_credentials=True. - Logs: API requests with
Originvalues you don't own, especially to endpoints returning personal data.
How it is fixed
- An exact allow-list of full origins (scheme, host and port), compared as strings, never
null. Access-Control-Allow-Credentials: trueonly for those origins, and only where cookies are really needed.Vary: Originon every response whose CORS headers depend on the request.- Preflight answers limited to the methods and headers the front end uses; a modest
Max-Age. - 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.
curland 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?
- Which clients may send requests to the server
- Which other origins' scripts may read the server's responses in a browser
- Which cookies are sent
- Whether TLS is used
Why is reflecting the Origin header with Allow-Credentials worse than *?
- It is slower
- Browsers refuse
*with credentials, but a reflected origin with credentials lets any site read users' authenticated data - Reflection breaks preflight
- It isn't worse
Which request triggers a preflight?
- A GET for an image
- A form POST with application/x-www-form-urlencoded
- A fetch with method PUT and a JSON body
- Following a link
Why add Vary: Origin?
- To speed up responses
- So caches don't serve a response with one origin's ACAO to another origin
- It is required by HTTP/1.0
- 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?
- The PUT is sent and the response is readable
- The preflight fails, because * is not allowed with credentials, so the PUT is never sent
- The PUT is sent without the cookie
- The browser upgrades * to the page origin