JWT Pitfalls: alg none, HS/RS Confusion, exp and aud
The JWT format has a design decision that has caused a long line of vulnerabilities: the token says, in its own header, which algorithm should be used to verify it. A verifier that obeys the header lets the attacker choose the rules of the check. Add libraries that once accepted "alg": "none", keys that can be read as either an RSA key or an HMAC secret, and verifiers that check the signature but forget what the token is for, and you get the classic JWT bugs. This lesson writes a naive verifier, breaks it four ways with tokens the example forges itself, and then fixes each break. It builds on the hand-made tokens of the previous lesson.
The four classic mistakes
| Mistake | Mechanism | Fix |
|---|---|---|
alg: none accepted |
RFC 7518 defines an "unsecured" JWS with alg = none and an empty signature; a verifier that dispatches on the header accepts it |
allow-list of algorithms fixed by the verifier |
| HS/RS confusion | the server verifies RS256 with its public key. A token with alg: HS256 makes a naive verifier use that same key as an HMAC secret, and the public key is public, so the attacker can compute the HMAC |
bind each key to one algorithm; never pass the same key object to HMAC and RSA code |
Missing exp / aud / iss checks |
a valid signature is treated as "valid token": expired tokens and tokens for other services are accepted | require and check them every time |
| Weak HMAC secret | an HS256 token is an offline guessing oracle: anyone holding one token can test candidate secrets | 256-bit random secrets, or asymmetric algorithms |
Two header fields extend the list: kid (key id) used unsafely as a file path or SQL value (path traversal, injection), and jku/x5u (URLs to fetch keys from) honoured from the token itself, so the attacker points them at their own key. Verifiers must look kid up in a fixed key set and ignore jku/x5u unless they match a pinned URL.
A naive verifier, broken four ways
The issuer here signs with RS256. Its RSA key is generated in the example (so it changes every run, and the output shows only verdicts), and the public key is published as PEM, as real issuers do through JWKS.
import base64, hashlib, hmac, json
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding, rsa
from cryptography.exceptions import InvalidSignature
def b64url(b): return base64.urlsafe_b64encode(b).rstrip(b"=").decode()
def unb64(s): return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
def enc(obj): return b64url(json.dumps(obj, separators=(",", ":")).encode())
NOW = 1_790_000_000
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
PUBLIC_PEM = private_key.public_key().public_bytes(serialization.Encoding.PEM,
serialization.PublicFormat.SubjectPublicKeyInfo)
def issue(claims):
si = enc({"alg": "RS256", "typ": "JWT"}) + "." + enc(claims)
return si + "." + b64url(private_key.sign(si.encode(), padding.PKCS1v15(), hashes.SHA256()))
def naive_verify(token, key=PUBLIC_PEM):
h, p, s = token.split(".")
alg = json.loads(unb64(h))["alg"] # BUG: the token chooses the algorithm
si = f"{h}.{p}".encode()
if alg == "none":
pass
elif alg == "HS256":
if not hmac.compare_digest(hmac.new(key, si, hashlib.sha256).digest(), unb64(s)):
raise ValueError("bad signature")
elif alg == "RS256":
serialization.load_pem_public_key(key).verify(unb64(s), si, padding.PKCS1v15(), hashes.SHA256())
return json.loads(unb64(p)) # BUG: no exp / aud / iss checks
def strict_verify(token, audience, now=NOW):
h, p, s = token.split(".")
if json.loads(unb64(h)).get("alg") != "RS256":
raise ValueError("alg not allowed")
serialization.load_pem_public_key(PUBLIC_PEM).verify(unb64(s), f"{h}.{p}".encode(),
padding.PKCS1v15(), hashes.SHA256())
c = json.loads(unb64(p))
if c.get("iss") != "https://auth.lab.test": raise ValueError("wrong iss")
if c.get("aud") != audience: raise ValueError("wrong aud")
if not isinstance(c.get("exp"), int) or c["exp"] + 60 < now: raise ValueError("expired or no exp")
return c
good = issue({"iss": "https://auth.lab.test", "sub": "user-42", "aud": "orders-api", "role": "customer", "exp": NOW + 900})
admin = {"iss": "https://auth.lab.test", "sub": "user-42", "aud": "orders-api", "role": "admin", "exp": NOW + 900}
attacks = {
"genuine token": good,
"alg none": enc({"alg": "none", "typ": "JWT"}) + "." + enc(admin) + ".",
"HS256 signed with the public key": (lambda si: si + "." + b64url(hmac.new(PUBLIC_PEM, si.encode(), hashlib.sha256).digest()))(
enc({"alg": "HS256", "typ": "JWT"}) + "." + enc(admin)),
"expired a day ago": issue({**admin, "role": "customer", "exp": NOW - 86400}),
"token for billing-api": issue({**admin, "role": "customer", "aud": "billing-api"}),
}
for name, tok in attacks.items():
try:
r1 = "accepted, role=" + naive_verify(tok)["role"]
except (ValueError, InvalidSignature) as e:
r1 = "rejected"
try:
r2 = "accepted, role=" + strict_verify(tok, "orders-api")["role"]
except (ValueError, InvalidSignature) as e:
r2 = f"rejected ({e or 'bad signature'})"
print(f"{name:34} naive: {r1:24} strict: {r2}")genuine token naive: accepted, role=customer strict: accepted, role=customer
alg none naive: accepted, role=admin strict: rejected (alg not allowed)
HS256 signed with the public key naive: accepted, role=admin strict: rejected (alg not allowed)
expired a day ago naive: accepted, role=customer strict: rejected (expired or no exp)
token for billing-api naive: accepted, role=customer strict: rejected (wrong aud)
The naive verifier accepted every forgery. With alg: none there was nothing to check. With HS256 it computed an HMAC keyed with the PEM text of the public key, which the attacker had computed too. The expired token and the token meant for another service had genuine signatures, and the naive verifier never asked more. The strict verifier fixes the algorithm itself, binds the key to RSA, and checks iss, aud and exp (with 60 seconds of leeway for clock skew).
Weak HMAC secrets fall offline
An HS256 token lets anyone test a guess for the secret without contacting the server: recompute the HMAC and compare. With a secret from a word list, that takes microseconds per guess. The token below is made in the example with a deliberately bad secret.
import base64, hashlib, hmac
def b64url(b): return base64.urlsafe_b64encode(b).rstrip(b"=").decode()
si = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyLTQyIn0"
token = si + "." + b64url(hmac.new(b"changeme", si.encode(), hashlib.sha256).digest())
candidates = ["secret", "password", "jwt-secret", "admin", "changeme", "letmein"]
h, p, s = token.split(".")
for i, guess in enumerate(candidates, 1):
if b64url(hmac.new(guess.encode(), f"{h}.{p}".encode(), hashlib.sha256).digest()) == s:
print(f"secret found after {i} guesses: {guess!r}")
break
print("a uniformly chosen 256-bit secret has 2**256 =", f"{2**256:.2e}", "candidates")secret found after 5 guesses: 'changeme'
a uniformly chosen 256-bit secret has 2**256 = 1.16e+77 candidates
Once the secret is known, the attacker mints any token. Tools such as hashcat (mode 16500) and jwt_tool do this at GPU speed, which is why audits test HS256 secrets against common lists, in a lab, on tokens from the system under test.
How JWT flaws are detected
- Testing in scope: take a genuine token and send variants:
algset tonone/None/NONEwith an empty signature;algswitched from RS256 to HS256 and signed with the published public key (from/.well-known/jwks.jsonconverted to PEM); payload edits with the old signature; expired tokens; tokens from another environment or audience;kidvalues like../../dev/null. Burp's JWT Editor extension andjwt_toolautomate the list. - Code review: decoding before verifying,
algorithmsmissing or taken from the header, one verify function used for several key types, custom JWT code,verify_exp: False. - Logs: tokens with
algvalues the issuer never uses, unknownkids,expfar in the past, tokens whoseissbelongs to another environment.
How they are fixed
- Use a maintained library and pass
algorithms=["RS256"](or your one algorithm),issuer=andaudience=explicitly; requireexp. - Keep keys typed: an RSA public key object can't be passed to HMAC; some libraries added after the 2015 disclosures refuse PEM-looking HMAC secrets (PyJWT does, for example), but don't rely on that.
- Resolve
kidonly against a fixed JWKS from a configured issuer URL; ignore token-suppliedjku,x5uand embeddedjwk. - HS256 secrets: 32+ random bytes, rotated, never shared between environments.
Pitfalls
- Checking
audwith "contains" on a string audience ("orders-api-test"contains"orders-api"). - Accepting both RS256 and HS256 "for compatibility": that is the confusion bug.
- Validating the ID token's signature but not its
noncein OIDC, which allows replay of an old ID token (OAuth flaws).
Practice
1. A library call is jwt.decode(token, key) with no algorithms argument. What do you check?
Which algorithms the library then allows. Modern PyJWT raises an error without algorithms=; older or other libraries may read alg from the header. Pin the list explicitly either way.
2. ExcelTAD's TAD client checks the ID token header with header.alg !== 'RS256' || header.typ !== 'JWT' before verifying. Which attack does this line stop?
Both alg: none and HS/RS confusion: any token whose header names another algorithm is rejected before any key is used, and the key used is an RSA key from TAD's JWKS imported for RSASSA-PKCS1-v1_5 only.
Test yourself
What is the root cause of the alg none and HS/RS confusion bugs?
- Weak RSA keys
- The verifier lets the token's header choose the algorithm
- Base64url encoding
- Short expiry
In the HS/RS confusion attack, what does the attacker use as the HMAC key?
- The server's private key
- The server's public key, which is published
- A random value
- The user's password
The strict verifier rejected the token for billing-api although its signature was valid. Which check did that?
- exp
- aud
- alg
- iss
Why can an HS256 secret be guessed without sending requests to the server?
- The secret is in the header
- Anyone with one token can recompute HMACs offline and compare with its signature
- HS256 is reversible
- The server leaks it