Lesson 08 · 50 minutes
Fix token, origin and cross-site flaws and test each fix
- Read a bearer token and check a signed token for its algorithm, signature and expiry
- Send CORS headers only to a known origin
- Refuse a cross-site POST by its Origin header and prove each fix with a test
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
A partner builds a web page that calls your notes API. Their security review asks three questions. What happens to an old or forged token? May any website read your answers? Can a page on another site make a logged-in browser post to you? Your task is to build a small server with all three flaws, show each one with a test, fix it, and then add a route that is safe from the first line.
Recall
Lesson 3. Which cookie flag keeps the browser from sending the cookie on a request that starts from another site, and why is it not enough alone?
SameSite=Strict. An old browser may not apply it, so the server should check where the request came from too.
Lesson 7. Where does the secret that signs tokens belong, in the source file or in the environment? Why?
In the environment (or in a .env file that Git ignores). Source code is copied with the repository, so a secret in it leaks with every clone.
The idea
Three gaps, one fix each.
| Gap | What goes wrong | The fix |
|---|---|---|
| Bearer token | The server trusts what the token says about itself | Fix the algorithm, check the signature and the expiry |
| CORS | Any website may read the answers | Send the CORS header only to a list of origins |
| CSRF | A page on another site makes the browser send your cookie | Check the Origin header, keep SameSite |
A bearer token is a secret that works for whoever holds it. The client sends it in the header Authorization: Bearer <token> (RFC 6750). It can be random text that the server looks up, like the session id of lesson 3, or a signed token such as a JSON Web Token (JWT, RFC 7519).
A JWT has three parts in base64url (a URL-safe text form of bytes). The header names the algorithm: HS256 means HMAC with SHA-256, where one shared secret both signs and checks. The claims are facts such as sub (the user) and exp (the expiry time, in seconds since 1970). A JWT is signed, not hidden: anyone can read the claims, and the signature only proves that nobody changed them.
RFC 8725 gives the best-practice rules for JWT. Two faults that it warns about are in the lab: the header says "alg": "none" and the server skips the check, and exp is never read.
An origin is a scheme, a host and a port.
CORS (cross-origin resource sharing) is the browser rule that a script from one origin may read the answer of another only if the header Access-Control-Allow-Origin names it. CORS guards the reader of the answer, not the arrival of the request.
CSRF (cross-site request forgery) uses that gap. A page on another site makes the browser send a POST to your API, and the browser adds your cookie by itself. A bearer header is not added by itself, so a bearer API has no CSRF problem. A page script cannot change the Origin that the browser sets, so the server compares it with a list.
- evil.example → Browser: its script posts to your API
- Browser → Your API (blocked): POST with Cookie sid, Origin evil.example
- Your API → Browser: Origin not in the list: 403, no note made
Worked example
1. Make a secret
The secret that signs tokens stays in the environment (lesson 7). The command is the one of lesson 3: python3 -c makes the random text and $(...) puts it into the variable.
cd ~/krlab/web-apis
export GUARD_SECRET=$(python3 -c "import secrets; print(secrets.token_urlsafe(32))")2. Write the server that has the three flaws
Create guard.py. Five things are new:
base64.urlsafe_b64encodemakes base64url text. The=padding is cut off, andunb64puts it back.hmac.new(key, text, "sha256")makes a signature that only a holder of the key can compute.make_token(user, seconds)builds a token that expires inseconds; a negative number makes an expired one.auth[7:]is the text after the first 7 characters, which areBearer.self.headers.get("Origin")reads the header that a browser sets on a cross-site request.curlsends none.if __name__ == "__main__":runs the server only when you start the file, not when the test imports it.
The comments mark the flaws. SESSIONS holds one fixed cookie session for the test. Nothing runs on port 8310 in this lab: ORIGINS is only a name that the server compares with the Origin header.
guard.py
import base64, hmac, json, os, time
from http.server import BaseHTTPRequestHandler, HTTPServer
SECRET = os.environ["GUARD_SECRET"].encode()
ORIGINS = {"http://127.0.0.1:8310"} # the one web page that may call this API
SESSIONS = {"demo-session": "alice"} # a fixed cookie session, for the test only
NOTES = []
def b64(data):
return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
def unb64(text):
return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
def sign(text):
return b64(hmac.new(SECRET, text.encode(), "sha256").digest())
def make_token(user, seconds):
head = b64(json.dumps({"alg": "HS256", "typ": "JWT"}).encode())
body = b64(json.dumps({"sub": user, "exp": int(time.time()) + seconds}).encode())
return f"{head}.{body}.{sign(head + '.' + body)}"
def read_token(token):
try:
head, body, sig = token.split(".")
header, claims = json.loads(unb64(head)), json.loads(unb64(body))
except ValueError:
return None
if header.get("alg") != "none": # the flaw: the token picks its own check
if not hmac.compare_digest(sig, sign(head + "." + body)):
return None
return claims.get("sub") # the flaw: "exp" is never read
class Handler(BaseHTTPRequestHandler):
def reply(self, status, obj):
data = json.dumps(obj).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
origin = self.headers.get("Origin")
if origin: # the flaw: every site is allowed
self.send_header("Access-Control-Allow-Origin", origin)
self.send_header("Access-Control-Allow-Credentials", "true")
self.end_headers()
self.wfile.write(data)
def user(self):
auth = self.headers.get("Authorization", "")
if auth.startswith("Bearer "):
return read_token(auth[7:])
for part in self.headers.get("Cookie", "").split(";"):
name, _, value = part.strip().partition("=")
if name == "sid":
return SESSIONS.get(value)
def do_GET(self):
user = self.user()
if user is None:
return self.reply(401, {"error": "not authenticated"})
if self.path == "/me":
return self.reply(200, {"user": user})
self.reply(404, {"error": "not found"})
def do_POST(self):
user = self.user()
if user is None:
return self.reply(401, {"error": "not authenticated"})
if self.path != "/notes":
return self.reply(404, {"error": "not found"})
try:
size = max(0, int(self.headers.get("Content-Length") or 0))
text = json.loads(self.rfile.read(size))["text"]
except (ValueError, KeyError, TypeError):
return self.reply(400, {"error": "send JSON with a text field"})
note = {"owner": user, "text": text}
NOTES.append(note)
self.reply(201, note)
if __name__ == "__main__":
HTTPServer(("127.0.0.1", 8300), Handler).serve_forever()3. Write the test
Create guard_test.sh. It makes three tokens with python3 -c (GUARD_SECRET must be exported in this terminal too): a good one, an expired one, and a forged one with alg none, a far expiry and an empty signature. In the forged one, enc turns a small dictionary into base64url text.
Two helper functions do the work:
checkcompares the status of an answer with the status that you expect.withoutfails when a given text appears in the answer, and also when there is no answer at all.
The shell syntax of these functions is new:
check() { ... }defines a function, a named block of commands. Inside it,$1and$2are the first and second argument, and"${@:3}"is every argument from the third on.got=$(...)keeps the output of a command in the variablegot.[ "$got" = "$2" ]tests that two texts are equal.A && B || CrunsBwhenAworks andCwhen it does not. HereCprints FAIL and setsFAILED=1.case "$out" in ... esacpicks the first pattern that fits$out, and;;ends each branch.*stands for any text, so*"$2"*means "the text$2is somewhere in$out", andHTTP*means "starts with HTTP".exit ${FAILED:-0}ends the script with the code1whenFAILEDwas set, and with0when it was not.lambda d: ...in the Python is a function without a name;enc = lambda d: ...gives it the nameenc.
guard_test.sh
H=http://127.0.0.1:8300
J='Content-Type: application/json'
GOOD=$(python3 -c "import guard; print(guard.make_token('alice', 60))")
OLD=$(python3 -c "import guard; print(guard.make_token('alice', -60))")
NONE=$(python3 -c "
import base64, json
enc = lambda d: base64.urlsafe_b64encode(json.dumps(d).encode()).rstrip(b'=').decode()
print(enc({'alg': 'none'}) + '.' + enc({'sub': 'alice', 'exp': 9999999999}) + '.')")
A="Authorization: Bearer $GOOD"
check() { # label, expected status, curl arguments
got=$(curl -s -o /dev/null -w '%{http_code}' "${@:3}")
[ "$got" = "$2" ] && echo "PASS $2 $1" || { echo "FAIL $1: wanted $2, got $got"; FAILED=1; }
}
without() { # label, text that must not appear in the headers or the body, curl arguments
out=$(curl -si "${@:3}")
case "$out" in
*"$2"*) echo "FAIL $1: the answer holds $2"; FAILED=1 ;;
HTTP*) echo "PASS $1" ;;
*) echo "FAIL $1: no answer"; FAILED=1 ;;
esac
}
check "good token" 200 -H "$A" $H/me
check "no token" 401 $H/me
check "expired token" 401 -H "Authorization: Bearer $OLD" $H/me
check "token with alg none" 401 -H "Authorization: Bearer $NONE" $H/me
without "CORS for any site" evil.example -H "$A" -H "Origin: http://evil.example" $H/me
check "cross-site POST" 403 -H "Cookie: sid=demo-session" -H "Origin: http://evil.example" -H "$J" -d '{"text":"x"}' $H/notes
check "own front end POST" 201 -H "Cookie: sid=demo-session" -H "Origin: http://127.0.0.1:8310" -H "$J" -d '{"text":"x"}' $H/notes
exit ${FAILED:-0}4. Run it against the flawed server
Start the server in one terminal with python3 guard.py. A new terminal starts in your home folder, so type cd ~/krlab/web-apis in it. It also does not have GUARD_SECRET, and a new random value would sign tokens that the server rejects (the first line would print FAIL good token: wanted 200, got 401). In the first terminal type echo $GUARD_SECRET. In the second terminal type export GUARD_SECRET= and paste the value after the sign. Then run the test.
bash guard_test.shPASS 200 good token
PASS 401 no token
FAIL expired token: wanted 401, got 200
FAIL token with alg none: wanted 401, got 200
FAIL CORS for any site: the answer holds evil.example
FAIL cross-site POST: wanted 403, got 201
PASS 201 own front end POSTFour lines fail: the server accepted an expired token and an unsigned one, evil.example could read the answer, and a cross-site POST created a note. The three PASS lines must stay: a fix must keep normal use working.
5. Fix the token
Stop the server. Replace read_token with this version. The server chooses the algorithm, compares the signature and refuses an old token. Any odd token ends in except and gets 401, never an error page.
def read_token(token):
try:
head, body, sig = token.split(".")
header, claims = json.loads(unb64(head)), json.loads(unb64(body))
if header["alg"] != "HS256": # the server decides the algorithm
return None
if not hmac.compare_digest(sig, sign(head + "." + body)):
return None
if claims["exp"] < time.time(): # an old token is refused
return None
return claims["sub"]
except (ValueError, KeyError, TypeError, AttributeError):
return None6. Fix the origin
First, in reply, replace the line if origin: and its comment with the line below, and keep the two send_header lines under it. Both headers now go only to a listed origin. The credentials header stays, because the allowed page sends a cookie: without it, the browser does not let that page read the answer.
if origin in ORIGINS: # only the known web page may read the answerSecond, make these three lines the first lines of do_POST, before user = self.user(). They refuse a foreign origin. A request with no Origin is not from a page.
origin = self.headers.get("Origin")
if origin and origin not in ORIGINS: # a browser sets Origin; a foreign page is refused
return self.reply(403, {"error": "origin not allowed"})7. Run the test again
Start python3 guard.py again and run bash guard_test.sh.
PASS 200 good token
PASS 401 no token
PASS 401 expired token
PASS 401 token with alg none
PASS CORS for any site
PASS 403 cross-site POST
PASS 201 own front end POSTAll seven lines pass. Stop the server with Ctrl+C.
8. The finished file
The finished file: guard.py
guard.py
import base64, hmac, json, os, time
from http.server import BaseHTTPRequestHandler, HTTPServer
SECRET = os.environ["GUARD_SECRET"].encode()
ORIGINS = {"http://127.0.0.1:8310"} # the one web page that may call this API
SESSIONS = {"demo-session": "alice"} # a fixed cookie session, for the test only
NOTES = []
def b64(data):
return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
def unb64(text):
return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
def sign(text):
return b64(hmac.new(SECRET, text.encode(), "sha256").digest())
def make_token(user, seconds):
head = b64(json.dumps({"alg": "HS256", "typ": "JWT"}).encode())
body = b64(json.dumps({"sub": user, "exp": int(time.time()) + seconds}).encode())
return f"{head}.{body}.{sign(head + '.' + body)}"
def read_token(token):
try:
head, body, sig = token.split(".")
header, claims = json.loads(unb64(head)), json.loads(unb64(body))
if header["alg"] != "HS256": # the server decides the algorithm
return None
if not hmac.compare_digest(sig, sign(head + "." + body)):
return None
if claims["exp"] < time.time(): # an old token is refused
return None
return claims["sub"]
except (ValueError, KeyError, TypeError, AttributeError):
return None
class Handler(BaseHTTPRequestHandler):
def reply(self, status, obj):
data = json.dumps(obj).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
origin = self.headers.get("Origin")
if origin in ORIGINS: # only the known web page may read the answer
self.send_header("Access-Control-Allow-Origin", origin)
self.send_header("Access-Control-Allow-Credentials", "true")
self.end_headers()
self.wfile.write(data)
def user(self):
auth = self.headers.get("Authorization", "")
if auth.startswith("Bearer "):
return read_token(auth[7:])
for part in self.headers.get("Cookie", "").split(";"):
name, _, value = part.strip().partition("=")
if name == "sid":
return SESSIONS.get(value)
def do_GET(self):
user = self.user()
if user is None:
return self.reply(401, {"error": "not authenticated"})
if self.path == "/me":
return self.reply(200, {"user": user})
self.reply(404, {"error": "not found"})
def do_POST(self):
origin = self.headers.get("Origin")
if origin and origin not in ORIGINS: # a browser sets Origin; a foreign page is refused
return self.reply(403, {"error": "origin not allowed"})
user = self.user()
if user is None:
return self.reply(401, {"error": "not authenticated"})
if self.path != "/notes":
return self.reply(404, {"error": "not found"})
try:
size = max(0, int(self.headers.get("Content-Length") or 0))
text = json.loads(self.rfile.read(size))["text"]
except (ValueError, KeyError, TypeError):
return self.reply(400, {"error": "send JSON with a text field"})
note = {"owner": user, "text": text}
NOTES.append(note)
self.reply(201, note)
if __name__ == "__main__":
HTTPServer(("127.0.0.1", 8300), Handler).serve_forever()Your turn
Add a route to the fixed guard.py that is safe from the first line. There are no steps here.
POST /profiletakes a JSON body with anameand answers 200 with{"user": ..., "name": ...}. A foreignOriginmust get 403, and a bad token 401.- Restart the server. Call
/profilewith a good token and the body{"name":"Ann"}, with and without the headerOrigin: http://evil.example. - Make a token with another secret, in a new shell in the same folder:
GUARD_SECRET=other python3 -c "import guard; print(guard.make_token('alice', 60))". Call/mewith it.
Check yourself
A JWT is signed. Is it safe to put a password in its claims?
No. A signature stops changes; it hides nothing. The parts are plain base64url, and anyone who holds the token can read them.
Why must the server choose the algorithm, and not read it from the token?
The sender writes the header. A server that obeys "alg": "none" lets anyone make a token that it accepts. A fixed algorithm leaves the attacker nothing to choose.
Why does CORS not protect an API from a forged POST?
CORS decides whether a page may read an answer. The browser still sends the request, and the server still runs it, unless it refuses, for example by checking Origin.
Field notes
- In the OWASP API Security Top 10 2023, API2 is "Broken Authentication" (weak token checks belong here) and API8 "Security Misconfiguration" names a wrong CORS policy.
- In production use a tested library for tokens, and fix the allowed algorithms in its settings. Keep a signed token short-lived: it cannot be recalled before
expwithout a revocation list. - Never copy the
Originheader into the answer without a list, as the flawed server did. With a list, also sendVary: Origin, so that a cache does not give one origin's answer to another. - A cross-origin request with
Content-Type: application/jsontriggers a preflightOPTIONSrequest, which this lab server does not answer. But a page can send the same body astext/plain, which needs no preflight, so a JSON API must also refuse a wrongContent-Type(415, lesson 2). - The OWASP CSRF Prevention Cheat Sheet treats the
Origincheck andSameSiteas layers. A missingOriginis no proof of safety: the lab accepts it only because programs send none and still need a credential. - Lesson 9 closes two more gaps of a different kind: a shell that runs user text, and a body that sets any field.