cld-toys › Toys › jwt-from-scratch

Commentary: jwt-from-scratch

A verifier that accepts only two strong algorithms still accepts a forged role: admin token. The attacker signs it with HMAC, using the server's own public key as the HMAC secret, and needs no secret at all. A study guide for jwt.py.

jwt-from-scratch/ on GitHub·the source with line numbers, for reading rather than downloading
How to read this Read this page with jwt.py open beside you. The page is the toy's only documentation, and the toy has five files. jwt.py is the toy itself, 212 lines: two base64 helpers, three signature functions, an encoder, and four verifiers. demo.py runs four scenes, which it calls acts, against all four verifiers. oneline.py is a single verifier in which one line can be switched between two versions, to show that this line alone decides the result. sweep.py runs every experiment this page quotes, as ten numbered checks, C1 to C10. test_jwt.py turns the main results into tests, so they cannot change without anyone noticing. The toy uses only the standard library (base64, hashlib, hmac, json) and makes no network calls. No token on this page belongs to a real service. Every output on this page was captured from a real run on macOS 26.5.2 (Darwin 25.5.0), arm64 Apple Silicon, Python 3.15.0a8. The toy has no clock and no randomness, so every token is identical on every run: we ran demo.py twice and diffed the output, and there was no difference. The one exception is the timing table in section 6.5, which is a measurement and says so.
cd jwt-from-scratch
python3 demo.py      # the four acts (section 6)
python3 oneline.py   # the one line that decides the result (section 6.4)
python3 sweep.py     # every experiment this page quotes (checks C1 to C10)
python3 test_jwt.py  # tests that pin both forgeries
Contents
  1. Orientation
  2. The problem this mechanism exists to solve
  3. Background you need
  4. The mental model
  5. Reading the source
  6. The demo, and what it proves
  7. Design decisions and roads not taken
  8. What's simplified vs. the real thing
  9. Check yourself
  10. Further reading

1. Orientation

Suppose your server issues a token that says "this is alice, and she is a regular user". A week later it receives a token that says "this is alice, and she is an admin". The server has to decide whether it wrote that second token. That decision is the job of a verifier, and this toy is about four ways to write one.

A JSON Web Token (JWT) is a small signed document in three parts: a header, a payload of claims such as sub: alice (the subject, who the token is about) and role: user, and a signature over the first two. The header names the algorithm the signer used, in a field called alg. The toy builds JWTs from scratch and then writes four verifiers for them.

The toy supports two real signing algorithms. HS256 is HMAC with SHA-256: one shared secret both signs and verifies (section 2 explains HMAC). RS256 is an RSA signature over a SHA-256 hash: a private key signs, and a separate public key verifies. Because the public key can only verify, the server publishes it so anyone can check its tokens. The toy writes each part of a token in base64url, a reversible way to write bytes as text that is safe in a URL.

An attacker who wants role: admin has two classic ways to forge a token. The rest of the page is about which verifier stops which:

Here are the four verifiers, in the order a real codebase tends to acquire them. Each one is a reasonable response to the failure of the one before it. The source and the demo output number them v0 to v3, so the table gives both names:

verifierwhat it doesforgeries it accepts
verify_naive (v0)uses the algorithm header["alg"] namesboth
verify_blocklist (v1)same, but refuses "none"key confusion
verify_allowlist (v2)same, but accepts only HS256 and RS256key confusion
verify_strict (v3)never reads header["alg"]neither

The third row is the surprise. The alg: none forgery is well known, and verify_blocklist already stops it. verify_allowlist is what a careful engineer writes next: it accepts only two real, strong, standard algorithms. It still returns role: admin for a token made by someone who knows no secret at all. A shorter or stricter list does not fix this. The fix is to stop reading alg out of the token, which is one line (section 6.4).

The feature that makes this possible is called algorithm agility: the token itself says which algorithm should check it. Agility is useful. It lets a system move from one algorithm to another gradually, without upgrading every issuer and every verifier on the same day. It also means the verifier takes an instruction from a field the attacker writes.

By the end you should be able to:


2. The problem this mechanism exists to solve

A server wants to hand a client a small piece of state, such as "you are alice, you are an admin, until 3pm". The client carries it around and sends it back later, and the server wants to accept it without a database lookup. The token has to survive a round trip through someone who may want to change it.

That is a message-authentication problem, and a message authentication code (MAC) solves it. A MAC is a short tag computed from the message and a secret key. Without the key you cannot compute a valid tag, so any change to the message is caught. HMAC is the standard way to build a MAC from a hash function, and in an HS256 token the signature is exactly this HMAC tag. If JWT were only this, the toy would demonstrate HMAC and nothing else.

JWT adds a second requirement on top: algorithm agility, from section 1. Systems run for years, and algorithms get retired. If every token is checked with one fixed algorithm, changing it means upgrading every issuer and every verifier at the same moment. If the token names its algorithm, the system can change gradually. So JSON Web Signature (JWS), the signing format underneath JWT, puts the algorithm name in the header, and the verifier reads the header first.

Several goals pull against each other here, which is why more than one design is defensible:


3. Background you need

You don't need deep cryptography for this page, but it relies on the seven ideas below.

ConceptWhere it's used hereOne source
The alg header verify_naive, jwt.py:156, the line this page is about RFC 7515 §4.1.1
The JWS signing input split, jwt.py:135: the encoded segments and the dot, not the parsed JSON RFC 7515 §5.1
HMAC accepts any bytes as a key hs256, jwt.py:81-85, which is why a public key works as a secret RFC 7518 §3.2
Key-pair signatures publish the verification key PUBLIC_KEY, jwt.py:66-71 RFC 7518 §3.3
base64url b64e and b64d, jwt.py:37-44; padding is stripped and never sent RFC 7515 Appendix C
Constant-time comparison hmac.compare_digest, jwt.py:160; it takes the same time however many bytes match, and section 6.5 measures whether that matters here hmac.compare_digest
Textbook RSA rs256_sign and rs256_check, jwt.py:88-103; insecure on purpose (section 7.3) RFC 7518 §3.3

Two of these rows produce the result. Row 1 is the bug: the verifier reads an instruction from a document the attacker wrote. Row 3 is what lets an attacker use the hole without any secret: hmac.new(key, ...) accepts any bytes as a key, so a key that was published on purpose works as an HMAC secret. Neither row is a weakness in the cryptography. HMAC-SHA-256 is not broken here. Every forged token on this page passes because its signature is genuinely correct for the key the server used.


4. The mental model

Let's picture the problem before any code. A JWT is three base64url segments joined by dots, and the signature covers the first two segments as text:

header segment payload segment signature segment ┌───────────────────┐ ┌─────────────────────────┐ ┌─────────────────────┐ eyJhbGciOiJIUzI1Ni… . eyJleHAiOjE3MzE1MzYwMDA… . GxRO95UmzYpcud7Wm0v… └───────────────────┴──┴─────────────────────────┘ this, exactly this ASCII, is the signing input │ ▼ alg = ??? ───────────────► MAC/verify ───► true / false ▲ │ read out of the header segment, which is the attacker's document.

This is circular. To check the signature, the verifier must first know which algorithm to use, and the only place that is written is inside the part it has not checked yet.

Here are the two forgeries side by side. The demo prints them as FORGERY A and FORGERY B, so the diagram uses the same labels:

FORGERY A, the alg: none forgery header {"alg":"none","typ":"JWT"} <- attacker writes payload {"role":"admin",...} <- attacker writes sig (empty) <- attacker deletes verifier takes the `none` branch, never touches a key, returns the claims. FORGERY B, the key-confusion forgery header {"alg":"HS256","typ":"JWT"} <- attacker writes payload {"role":"admin",...} <- attacker writes sig HMAC-SHA256(PUBLIC_KEY, signing_input) <- attacker COMPUTES server holds PUBLIC_KEY (to check RS256). server takes the HS256 branch, computes HMAC-SHA256(PUBLIC_KEY, ...), gets the same 32 bytes, and agrees. Nothing was broken. Both parties did the arithmetic correctly. The attacker's advantage is that the server's key is published.

The alg: none forgery works because a check is missing. The key-confusion forgery works because a check passes, using a key the server itself publishes, and that is the one to remember. In one sentence: an RSA public key is safe to publish because it can only verify, but hand that same key to HMAC, where one key both signs and verifies, and anyone who can verify can also sign.


5. Reading the source

jwt.py is 212 lines: nine small functions and four verifiers. Its docstrings number the verifiers v0 to v3, as in the table in section 1. We'll read it in this order.

5.1 The claim, stated in the module docstring

Just above this excerpt, the docstring says that the header names the algorithm the verifier should use. "That last sentence" refers to it.

jwt.py · lines 11–21
That last sentence is the toy. The header is a document the attacker hands
you, and a verifier that reads `alg` out of it is asking the attacker how the
attacker should be checked. Four verifiers here, in the order a codebase
usually acquires them:

    verify_naive      dispatch on header["alg"]
    verify_blocklist  ... but refuse "none"
    verify_allowlist  ... but only allow HS256 and RS256
    verify_strict     never read header["alg"] at all

The first three all accept a forged token. See commentary section 6.

Why four verifiers instead of two? A broken one and a fixed one would have been 19 lines shorter: the middle two are jwt.py:172-190. Those two show how the bug survives the fixes people actually write. Each verifier is a competent response to the failure of the one before, and the third one is still wrong. Section 7.1 argues this choice in more detail.

5.2 The key pair, and why the public key is bytes

jwt.py · lines 66–76
# PUBLIC_KEY is what the server holds in order to *verify* RS256, and what
# anybody at all can fetch from a /.well-known/jwks.json. It is bytes,
# because that is how a real verifier receives it: a PEM blob, a JWKS entry,
# a file read off disk. Section 6.3 is about what happens when those bytes
# reach a function that was expecting an HMAC secret.
PUBLIC_KEY = _json({"kty": "RSA", "n": N, "e": E})
PRIVATE_KEY = _json({"kty": "RSA", "n": N, "d": D})

# The shared secret for a symmetric deployment. Section 6.7 uses it to show
# where the attack stops working.
SECRET = b"correct horse battery staple"

PUBLIC_KEY is plain bytes, not a parsed key object, and the whole toy depends on that choice. It is also realistic. A real verifier receives its key as a PEM string (the text format for keys that begins with -----BEGIN), as an entry in a JWKS (a JSON Web Key Set, the JSON document where a service publishes its public keys), or as a file it just read. rs256_check parses those bytes as an RSA key. hs256 uses the same bytes directly as an HMAC secret. So one value means two different things in two functions, and nothing in its type says which was intended.

_json writes compact JSON with sorted keys, so the bytes are the same on every run. Printed, the public key holds only e, the public exponent, and n, the modulus:

{"e":65537,"kty":"RSA","n":3351951982485649274893506249551461531869841455148098344436679965392306817304849849230228707730300726176936796585226029889698681638201343575652945364008631}

That is 182 bytes, and all of them are safe to publish. PRIVATE_KEY holds d, the private exponent, instead of e, and shares n. It is the only value in the file that must stay secret.

5.3 The two primitives, and the asymmetry between them

jwt.py · lines 81–103
def hs256(signing_input, key):
    """HMAC-SHA-256. `key` is arbitrary bytes -- any bytes at all, which is
    exactly the property section 6.3 turns into a forgery.
    """
    return hmac.new(key, signing_input, hashlib.sha256).digest()


def rs256_sign(signing_input, priv):
    """Textbook RSA: s = h^d mod n, over the bare digest. Deterministic,
    unpadded, and insecure -- see the module docstring.
    """
    k = json.loads(priv)
    h = int.from_bytes(hashlib.sha256(signing_input).digest(), "big")
    return pow(h, k["d"], k["n"]).to_bytes(64, "big")


def rs256_check(signing_input, sig, pub):
    """s^e mod n == h. Note the asymmetry that makes RS256 worth having:
    this needs only `pub`, while rs256_sign needs `priv`.
    """
    k = json.loads(pub)
    h = int.from_bytes(hashlib.sha256(signing_input).digest(), "big")
    return pow(int.from_bytes(sig, "big"), k["e"], k["n"]) == h

These 23 lines hold the whole vulnerability, in the contrast between the first function and the other two.

rs256_sign needs d. rs256_check needs only e and n. That gap is what public-key cryptography means: the ability to verify is separated from the ability to sign, so the verification key can be published safely.

hs256 has no such gap. HMAC is symmetric: the same key both creates and checks a tag. And it accepts any byte string as that key. Put those two facts together and the attack follows. Take the key that was published because it can only verify, and give it to an algorithm where verifying and signing use the same key.

pow(h, d, n) and pow(s, e, n) use Python's three-argument pow, which computes modular exponentiation. That is all of RSA. It is also textbook RSA, with no padding. Real RSA signatures first wrap the hash in a fixed format, the padding, which blocks known attacks. Leaving it out is fine for this toy and dangerous in production. Section 7.3 explains why the toy accepts that cost.

5.4 split, and what the signature actually covers

jwt.py · lines 129–135
def split(token):
    """(header, payload, signature bytes, signing input). The signing input
    is the first two segments and the dot between them, as ASCII -- not the
    decoded JSON, which is why re-serialising a header breaks a signature.
    """
    h, p, s = token.split(".")
    return json.loads(b64d(h)), json.loads(b64d(p)), b64d(s), f"{h}.{p}".encode()

Look at the fourth return value, f"{h}.{p}".encode(). The signing input, the bytes the signature is computed over, is built from the segments while they are still encoded. The verifier does not parse the JSON and encode it again. Section 5.1 of RFC 7515 requires this, for a practical reason. JSON has no single canonical form, since key order and whitespace are free. A verifier that re-encoded the parsed header would get different bytes whenever its JSON library formatted differently from the signer's, and honest tokens would fail.

This matters for the rest of the page: an attacker cannot edit the header of an existing token. Changing one character of the header segment changes the signing input, so the signature no longer matches; section 7.4 shows the run. The header is signed data. The problem is not that someone can modify it. The problem is that the verifier follows its instruction before checking that nobody changed it.

5.5 verify_naive, and the line this page is about

jwt.py · lines 148–169
def verify_naive(token, key, now=0):
    """v0. Asks the token how the token should be checked.

    Returns the payload on success, None on rejection. Read the first two
    lines of the body: `alg` comes out of the header, and the header came
    from whoever sent the token.
    """
    header, payload, sig, signing_input = split(token)
    alg = header["alg"]
    if alg == "none":
        ok = sig == b""
    elif alg == "HS256":
        ok = hmac.compare_digest(hs256(signing_input, key), sig)
    elif alg == "RS256":
        ok = rs256_check(signing_input, sig, key)
    else:
        return None
    if not ok:
        return None
    if "exp" in payload and payload["exp"] < now:
        return None
    return payload

This is v0. Read it slowly.

Everything after the line alg = header["alg"] is done well. hmac.compare_digest is the constant-time comparison: it takes the same time however many bytes match, so the time it takes reveals nothing. The RSA check is real. The expiry claim exp is checked. Unknown algorithms fall through to the else branch and are rejected, so this verifier does not accept "HS512" or "foo". The signature comparison does not use ==.

None of it helps. The second line of the body chooses which of those careful checks runs, and it chooses by reading a field the attacker wrote.

Notice also if "exp" in payload. The expiry is enforced only when the token contains an exp claim. That is a second, separate bug, and it is there on purpose. Section 7.5 tests it on its own, because exploiting it needs the real signing key: it is a mismatch between what the issuer sends and what the verifier requires, not a forgery.

The verifier returns the payload rather than True on success. That lets the demo print which role it accepted, ADMIN or ok:user, so you see what the attacker actually gained, not just that a check passed (section 7.6).

5.6 verify_blocklist and verify_allowlist, the two fixes that don't work

jwt.py · lines 172–190
def verify_blocklist(token, key, now=0):
    """v1. The reflex fix, and the one the industry shipped in 2015:
    refuse the algorithm that turned out to be a hole.
    """
    header, _payload, _sig, _si = split(token)
    if header["alg"] == "none":
        return None
    return verify_naive(token, key, now)


def verify_allowlist(token, key, now=0, allowed=("HS256", "RS256")):
    """v2. The careful fix. Name the algorithms you are prepared to accept,
    up front, and reject everything else. Both of these are real, strong,
    standard algorithms. This verifier is still broken -- section 6.3.
    """
    header, _payload, _sig, _si = split(token)
    if header["alg"] not in allowed:
        return None
    return verify_naive(token, key, now)

Both run their own check and then call verify_naive. That makes the comparison fair. verify_naive, verify_blocklist and verify_allowlist run exactly the same verification code, so any difference in their results comes from the one added check and nothing else.

verify_blocklist is the patch the ecosystem shipped in 2015, after Tim McLean disclosed both forgeries. verify_allowlist is what you write if you read section 3.2 of RFC 8725 ("applications MUST only allow the use of cryptographically current algorithms") and stop there. It is a real improvement: it rejects none, and it rejects every unknown or retired algorithm for good.

It does nothing against the key-confusion forgery, because HS256 is on the list. HS256 has to be on the list, or the experiment would test nothing. A list that contains only RS256 no longer lets the token choose anything, so it behaves like verify_strict (section 5.7). Section 7.1 explains this choice.

5.7 verify_strict, and why passing the algorithm is not enough

jwt.py · lines 193–212
def verify_strict(token, key, alg, now=0):
    """v3. The caller names the algorithm. `header["alg"]` is never read --
    the header is now signed *data*, not an instruction.

    `alg` must be the algorithm that matches `key`. Passing "HS256" here
    together with an RSA public key reproduces the whole bug (section 7.2),
    so the pairing is the fix, not the keyword.
    """
    _header, payload, sig, signing_input = split(token)
    if alg == "HS256":
        ok = hmac.compare_digest(hs256(signing_input, key), sig)
    elif alg == "RS256":
        ok = rs256_check(signing_input, sig, key)
    else:
        raise ValueError(alg)
    if not ok:
        return None
    if payload.get("exp", 0) < now:
        return None
    return payload

Compare it with verify_naive in section 5.5, line by line. The branches are the same, the signature functions are the same, and compare_digest is the same. Only three things differ:

  1. the header is unpacked into _header and never used, and the underscore says so on purpose;
  2. alg arrives as an argument from the server;
  3. the expiry check is payload.get("exp", 0) instead of if "exp" in payload, so a token with no expiry is treated as expired instead of valid forever.

An unknown algorithm raises ValueError(alg) here instead of returning None, and that is deliberate. alg now comes from the server, so an unrecognised value is a bug in the server's own configuration, not a bad token. Returning None would turn a typo in your config into an outage that looks like every user failing to log in.

It's tempting to conclude that passing the algorithm as an argument is the fix, and that is a mistake. Section 7.2 calls verify_strict(..., "HS256", ...) with the RSA public key and gets the forgery back exactly. The fix is that alg and key are chosen together, by the party that owns both. Section 3.1 of RFC 8725 says the same: "each key MUST be used with exactly one algorithm, and this MUST be checked when the cryptographic operation is performed."


6. The demo, and what it proves

demo.py creates one honest RS256 token and runs four acts, numbered 0 to 3, against all four verifiers. In its output each verifier has a short label: v0 naive is verify_naive, v1 -none is verify_blocklist, v2 allow is verify_allowlist, and v3 strict is verify_strict. ok:user means the verifier accepted a token with role user, ADMIN means it accepted a token with role admin, and reject means it refused the token. peek decodes a token without checking it (section 6.6).

python3 demo.py
=== act 0: the honest token === eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHA... length 186 chars peek header (no key) {'alg': 'RS256', 'typ': 'JWT'} peek payload (no key) {'exp': 1700003600, 'role': 'user', 'sub': 'alice'} verify_naive ok:user === act 1: tamper the payload, keep the signature === sub alice->alicf (1 byte) reject role user->admin reject ^ what everyone predicts. This is a MAC doing its job. === act 2: FORGERY A -- alg: none === eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJleHAiOjE3MzE1MzYwMDAsInJvbGUiOiJhZG1pbiIsInN1YiI6ImFsaWNlIn0. signature bytes 0 v0 naive ADMIN v1 -none reject v2 allow reject v3 strict reject === act 3: FORGERY B -- HS256/RS256 key confusion === the attacker knows only PUBLIC_KEY, which is public on purpose: {"e":65537,"kty":"RSA","n":3351951982485649274893506249551... (182 bytes) eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MzE1MzYwMDAsInJvbGUiOiJhZG1pbiIsInN1YiI6ImFsaWNlIn0.GxRO95UmzYpcud7Wm0vg9xOwxCQ2Zf47URntQe9TdVs signature bytes 32 v0 naive ADMIN v1 -none ADMIN v2 allow ADMIN v3 strict reject ================================================================== token v0 naive v1 -none v2 allow v3 strict ------------------------------------------------------------------ honest RS256 ok:user ok:user ok:user ok:user alg:none ADMIN reject reject reject key confusion ADMIN ADMIN ADMIN reject ==================================================================

6.1 Acts 0 and 1: the honest token, and the result everyone predicts

Act 0 is a real signature. The claims are sub=alice, role=user, exp=1700003600. The toy's clock, NOW, is fixed at 1_700_000_000, and the token expires 3600 seconds later, which gives 1700003600. All four verifiers accept it. That matters, because it shows that verify_strict rejects the forgeries in acts 2 and 3 without rejecting every token.

Act 1 changes the payload, keeps the old signature, and every verifier rejects the result. Both changes are small: alice to alicf changes one byte, and "user" to "admin" is the change an attacker would actually want (test_tampering_the_payload_is_caught).

This is exactly what a MAC is for, so nobody predicts otherwise. Act 1 is here so you see the signature check working before you see it defeated. When acts 2 and 3 succeed, you know the signature check itself was not broken.

6.2 Act 2: the alg: none forgery, and a verifier that never uses a key

GREEDY is the attacker's payload: sub alice, role admin, expiring a year after NOW. The whole forgery is one call:

demo.py · line 55
forged_none = jwt.encode(GREEDY, "none", None)

The None in the key position is deliberate: there is no key. The token is two base64url segments, a trailing dot, and 0 signature bytes. verify_naive takes the none branch, sets ok = sig == b"", and returns the claims.

How much does the verifier depend on its key here? Check C1 of sweep.py passes it four different keys:

C1 Is the verification key even an input? (alg:none) ----------------------------------------------------- verify_naive(alg:none, key=real public key ) -> ADMIN verify_naive(alg:none, key=empty bytes ) -> ADMIN verify_naive(alg:none, key=garbage ) -> ADMIN verify_naive(alg:none, key=the HS256 secret ) -> ADMIN

Four different keys, one of them empty, and all four give ADMIN. The key plays no part in the decision (test_alg_none_forgery_ignores_the_key_entirely). So alg: none is not a weak signature. It is no signature at all, accepted through the same function call as a real one.

This is the well-known bug, published by Tim McLean in March 2015, and verify_blocklist stops it with one line. Libraries patched it soon after. If the toy stopped here, it would be a history lesson.

6.3 Act 3: the key-confusion forgery

This is the central result of the page. The forgery is again one call:

demo.py · line 65
forged_conf = jwt.encode(GREEDY, "HS256", jwt.PUBLIC_KEY)

The attacker signs with HS256 and uses the server's RSA public key as the HMAC secret. Here is the full token:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MzE1MzYwMDAsInJvbGUiOiJhZG1pbiIsInN1YiI6ImFsaWNlIn0.GxRO95UmzYpcud7Wm0vg9xOwxCQ2Zf47URntQe9TdVs

And here is verify_allowlist, which accepts only HS256 and RS256, accepting it:

v2 allow ADMIN

Let's work out why. The three segments decode to:

header json : {"alg":"HS256","typ":"JWT"} payload json : {"exp":1731536000,"role":"admin","sub":"alice"} signing input: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MzE1MzYwMDAsInJvbGUiOiJhZG1pbiIsInN1YiI6ImFsaWNlIn0 len signing input: 100

The attacker computes HMAC-SHA256(PUBLIC_KEY, signing_input). The server holds the same PUBLIC_KEY so it can check RS256 tokens. The header says HS256, so the server takes the HS256 branch and computes the same thing:

attacker: HMAC(PUBLIC_KEY, signing_input) = 1b144ef79526cd8a5cb9ded69b4be0f713b0c4243665fe3b5119ed41ef53755b server : HMAC(PUBLIC_KEY, signing_input) = 1b144ef79526cd8a5cb9ded69b4be0f713b0c4243665fe3b5119ed41ef53755b sig from token = 1b144ef79526cd8a5cb9ded69b4be0f713b0c4243665fe3b5119ed41ef53755b equal: True

(1b144e… in hexadecimal is GxRO95… in base64url, the third segment of the token above.)

The two values are equal because both sides ran the same function on the same inputs. No cryptography was broken. The 32 bytes in that token are a correct HMAC-SHA-256 tag. The attacker's whole advantage is that the server publishes the key.

How much secret did the forgery need? Check C9 of sweep.py counts it:

C9 What each forgery costs, in secret bits ------------------------------------------- honest RS256 signature needs D : 509 bits of secret alg:none forgery needs : 0 bits of secret key confusion needs PUBLIC_KEY, 1456 bits of material published on purpose : 0 bits of secret HS256-only forgery needs SECRET : 224 bits of secret bytes of the accepted key-confusion token written by the attacker: 144 of 144

The 1456 bits are the 182-byte public key from section 5.2, and the 224 bits are the 28-byte SECRET. The attacker wrote every one of the 144 bytes the server accepted, using zero bits of secret. The honest issuer needed a 509-bit private exponent to produce a token the server would accept.

The idea to keep is this: an allowlist limits which algorithms run. It says nothing about which key each algorithm runs with, and the attack runs an allowed algorithm with the wrong key.

6.4 The line that decides the result

oneline.py is one verifier with a single line switched between two versions. Everything else stays the same: the same allowlist, the same compare_digest, the same RSA check, the same expiry check:

oneline.py · lines 20–34
def verify(token, key, server_alg, trust_the_token):
    header, payload, sig, signing_input = jwt.split(token)
    if trust_the_token:
        alg = header["alg"]           # LINE A: the token decides
    else:
        alg = server_alg              # LINE B: the server decides
    if alg not in ("HS256", "RS256"):
        return None
    if alg == "HS256":
        ok = hmac.compare_digest(jwt.hs256(signing_input, key), sig)
    else:
        ok = jwt.rs256_check(signing_input, sig, key)
    if not ok or payload.get("exp", 0) < NOW:
        return None
    return payload
python3 oneline.py
alg = header["alg"] honest -> user forged -> admin alg = server_alg honest -> user forged -> REJECTED

The honest token is accepted in both rows, so the second version is not simply stricter. It has stopped taking instructions from the token it is checking.

6.5 Two widely repeated claims that did not reproduce

We expected to demonstrate both of these claims and could not. We report them anyway, because a page that showed only the results that worked would mislead you.

Claim 1: "block none, and the attacker sends nOnE." This is repeated everywhere, and against verify_blocklist as written it does not work. Check C2 of sweep.py tries five spellings. It runs each one against verify_blocklist as shipped, and against a variant whose parser normalises the algorithm name first:

C2 The blocklist and its folklore bypass: does 'nOnE' work? ------------------------------------------------------------ alg='none' v1 as shipped -> reject v1 + normalising parser -> reject alg='nOnE' v1 as shipped -> reject v1 + normalising parser -> ADMIN alg='NONE' v1 as shipped -> reject v1 + normalising parser -> ADMIN alg=' none' v1 as shipped -> reject v1 + normalising parser -> ADMIN alg='none ' v1 as shipped -> reject v1 + normalising parser -> ADMIN

Every row in the left column is a rejection. The reason is in section 5.5: the branches in verify_naive also compare exact strings, so "nOnE" matches none of the three strings "none", "HS256" and "RS256", and reaches return None. The bypass needs a second ingredient, a parser that normalises alg before choosing a branch while the blocklist compares the raw string:

sweep.py · lines 48–57
def verify_normalising(token, key, now=0):
    """v1, but with a parser that is liberal in what it accepts:
    canonicalise `alg` before dispatch, and blocklist the exact string.
    """
    header, payload, sig, si = jwt.split(token)
    if header["alg"] == "none":
        return None
    alg = header["alg"].strip().upper()
    if alg == "NONE":
        ok = sig == b""

So the accurate statement is not "blocklists can be bypassed with case variants". It is this: a blocklist and a normalising parser compare different strings, and the attacker sends a string where they disagree. That tells you where to look in your own code: not at the blocklist alone, but at whether the blocklist's check and the parser's check see the same string.

Claim 2: "== leaks the signature one byte at a time." The usual reason given for hmac.compare_digest is that == stops at the first byte that differs. An attacker could then measure response times and recover a signature byte by byte. We tried to measure it with check C8 of sweep.py:

C8 `==` vs hmac.compare_digest: does the timing attack reproduce? ------------------------------------------------------------------ good is full -> False, good == full -> True candidate == ns/op compare_digest 0 leading bytes match 29.70 40.79 1 leading byte matches 31.65 38.85 31 leading bytes match 31.41 40.36 32 = full match 31.57 40.42 (4000 reps x 9 trials, median of trials) spread across prefix lengths, `==`: 1.95 ns/op (6.6%) monotone in prefix length, over 10 fresh rounds: 1/10

There is no trend. A 1-byte prefix match (31.65 ns) and a 31-byte prefix match (31.41 ns) take the same time, and the 31-byte one is slightly faster, the wrong direction for a leak. The whole spread across the four prefix lengths is 1.95 ns, or 6.6%.

One timing run is not enough to conclude anything, so the last line repeats the whole four-way measurement ten more times. It counts how often the four medians come out in increasing order. If == leaked a per-byte signal, that count would be 10/10. It is 1/10, about what you get by ranking four numbers drawn from the same distribution. (The line good is full -> False checks that the correct signature, good, and the full-match candidate, full, are separate objects. If they were the same object, Python could skip the comparison, and the timing would mean nothing.)

The reason is that Python does not compare bytes objects in a Python loop. Two bytes objects of equal length go to the C function memcmp, which compares 32 bytes in a couple of vector instructions, with no per-byte early exit that we can observe. The measurable difference runs the other way: averaged over the four rows, hmac.compare_digest takes 40.11 ns per call here, against 31.08 for ==, so it is about 9 ns, or 30%, slower.

Use compare_digest anyway. The toy does, at jwt.py:160 and jwt.py:203. Use it because it costs about 9 ns and makes the timing question go away, not because this measurement supports the usual story.

One machine, one build These numbers came from macOS 26.5.2, arm64 Apple Silicon, Python 3.15.0a8, on a laptop with other programs running. They are a measurement, not a universal claim. Different hardware, a different interpreter, a comparison written in pure Python, or a signature compared across a network can each change the answer. The timing attack is real wherever the comparison is a loop. Run python3 sweep.py on your own machine and read your own check C8 before you rely on this.

6.6 base64 is not encryption

Can anyone read a JWT without the key? Check C10 of sweep.py calls peek, which takes no key, on the honest token:

C10 base64 is not encryption ---------------------------- peek(honest RS256 token), no key at all: header {'alg': 'RS256', 'typ': 'JWT'} payload {'exp': 1700003600, 'role': 'user', 'sub': 'alice'} bytes of that token that are ciphertext: 0 of 186

peek (jwt.py:138-143) takes no key and checks nothing, because reading a JWT needs neither. A signature proves that nobody changed the claims. It does nothing to stop anybody reading them, and zero of the token's 186 bytes are encrypted. Anything you would not print in a log does not belong in a JWT payload. Put it in a JWE, the encrypted format, or keep it on the server behind an opaque session id.

6.7 Where the forgery stops working

We measured two boundaries. Together they let you decide whether your own system is exposed.

Boundary 1: the attacker needs the exact bytes of the key. Knowing the public key as a number is not enough. The attacker needs the exact byte string the server passes to HMAC. Check C3 of sweep.py tries six versions of the key:

C3 Key confusion: how exact must the attacker's key bytes be? -------------------------------------------------------------- attacker uses exact bytes -> v2 allowlist ADMIN attacker uses trailing newline -> v2 allowlist reject attacker uses one digit off -> v2 allowlist reject attacker uses keys reordered -> v2 allowlist reject attacker uses spaces after colons -> v2 allowlist reject attacker uses modulus alone, decimal -> v2 allowlist reject

One row succeeds and five fail. A cleverer attacker cannot get partial credit for a nearly right key, because changing any byte of an HMAC key changes the whole tag. A PEM file with a trailing newline and the same file without one are two different keys to HMAC. In the real-world bug, this is why exploitability depends on the library: the attacker has to guess a format, how the server stores and loads its key, but no secret (test_key_confusion_needs_the_bytes_exactly).

This also gives you a practical defence. Each JWKS entry carries a key id, kid. If the verifier looks up a parsed key object by kid and passes that object, not raw bytes, to the signature check, there is no byte string for the attacker to guess.

Boundary 2: a system that uses only shared secrets is immune to key confusion. Check C4 of sweep.py runs a system that uses only HS256 with a secret key:

C4 Boundary: an HS256-only deployment (the verification key is secret) ----------------------------------------------------------------------- honest HS256 token, v0 -> ok attacker guesses '' -> v2 allowlist reject attacker guesses 'secret' -> v2 allowlist reject attacker tries PUBLIC_KEY -> v2 allowlist reject attacker knows the secret -> v2 allowlist ADMIN but alg:none still walks in -> v0 ADMIN v1 reject

The key-confusion forgery uses a published key as if it were a shared secret. If your system publishes no verification key, there is nothing to misuse, and verify_allowlist holds. The attacker is back to guessing a secret, which is the problem the cryptography was designed for. The last row is the exception. The alg: none forgery uses no key at all, so it works against every kind of system, which is why it needed its own fix and got one first.

So ask three questions of any verifier you review:

  1. Does the verifier read alg out of the token? If not, neither forgery applies.
  2. If it does, does it accept both a shared-secret algorithm and a key-pair algorithm through one key parameter? If not, key confusion does not apply, but still check that it rejects none.
  3. If it does, is the verification key public, and can an attacker reproduce the exact bytes the verifier is given? This answer decides whether you have a theoretical finding or a working exploit.

6.8 The tests

python3 test_jwt.py
PASS test_honest_tokens_round_trip PASS test_tampering_the_payload_is_caught PASS test_alg_none_forgery_beats_the_naive_verifier PASS test_alg_none_forgery_ignores_the_key_entirely PASS test_key_confusion_beats_the_allowlist PASS test_the_load_bearing_line_is_where_alg_comes_from PASS test_strict_must_pair_the_alg_with_the_key PASS test_key_confusion_needs_the_bytes_exactly PASS test_symmetric_deployments_are_immune_to_key_confusion PASS test_the_header_is_signed_data PASS test_exp_is_only_an_expiry_if_it_is_required PASS test_peek_needs_no_key PASS test_wrong_signatures_are_still_rejected PASS test_rsa_round_trips_and_is_not_a_stub All 14 tests PASSED

There are fourteen tests, written with plain assert statements and no pytest. test_alg_none_forgery_beats_the_naive_verifier and test_key_confusion_beats_the_allowlist check the two forgeries. test_key_confusion_needs_the_bytes_exactly and test_symmetric_deployments_are_immune_to_key_confusion check the two boundaries from section 6.7. Two more, test_wrong_signatures_are_still_rejected and test_honest_tokens_round_trip, guard against a "fix" that simply rejects every token. test_rsa_round_trips_and_is_not_a_stub checks that the toy RSA is real: a signature made with D checks out under E, and N really is the 511-bit product of the two hardcoded primes. Without that test, section 6.3 would prove nothing, because a fake RS256 could not show that the public key is genuinely public.


7. Design decisions and roads not taken

7.1 Four verifiers instead of two

The short version of this toy is verify_naive and verify_strict: broken and fixed, 19 lines shorter, same conclusion. We built the middle two anyway, because they carry the lesson.

verify_blocklist exists because it is the fix libraries shipped in 2015, and because a reader who knows only the alg: none story needs to see that story end before act 3 can surprise them. verify_allowlist exists because it is a good answer. It is what a careful engineer writes and what a plain reading of section 3.2 of RFC 8725 asks for, and it is still wrong. Without it, the page would be arguing against a verifier nobody would write.

The lesson reaches beyond JWT: limiting which operations an attacker may request is a different control from taking away the attacker's ability to choose. verify_allowlist does the first. Only verify_strict does the second.

Why is allowed=("HS256", "RS256") and not just ("RS256",)? An allowlist with one entry no longer lets the token choose anything. It behaves like verify_strict, so it would prove nothing. The interesting case is a system that genuinely supports two algorithms, which is the case algorithm agility exists for.

7.2 Why the fix is choosing the algorithm and the key together

The tempting one-line summary of this page is "pass the algorithm explicitly". That is not enough, and we ran it to check, with check C5 of sweep.py:

C5 Is 'the server chooses' enough, or must the alg match the key? ------------------------------------------------------------------ v3 strict, server says RS256, key=PUBLIC -> reject v3 strict, server says HS256, key=PUBLIC -> ADMIN v3 strict, server says HS256, key=SECRET -> reject

Row 2 is verify_strict, the "fixed" verifier that never reads header["alg"], returning ADMIN for the same forged token. The server chose the algorithm, but it chose one that does not belong to the key it holds.

That is why section 3.1 of RFC 8725 is worded the way it is:

Libraries MUST enable the caller to specify a supported set of algorithms and MUST NOT use any other algorithms when performing cryptographic operations. The library MUST ensure that the "alg" or "enc" header specifies the same algorithm that is used for the cryptographic operation. Moreover, each key MUST be used with exactly one algorithm, and this MUST be checked when the cryptographic operation is performed.

That paragraph makes three requirements, and its last sentence forbids exactly what row 2 does. In a real library the types enforce it: keys are typed objects, and an HMAC function will not accept an RSA public key at all. The toy passes raw bytes on purpose, so the failure is visible (section 5.2).

test_strict_must_pair_the_alg_with_the_key checks rows 2 and 3.

7.3 Textbook RSA rather than a stand-in

The alternative was a fake RS256, "HMAC with a key the attacker doesn't have", which would have saved twelve lines. We built real RSA instead: pow(h, d, n) to sign, pow(s, e, n) == h to check, and a 511-bit modulus from two hardcoded 256-bit primes.

The reason is that section 6.3 depends on the verification key being genuinely public. With a fake, "the attacker knows the verification key" is a claim you have to accept. With real RSA you can check it: rs256_check needs only e and n, and rs256_sign needs d.

The cost is a warning in the module docstring, because this RSA is insecure in ways unrelated to the toy's point. It has no PKCS#1 or PSS padding (the standard schemes that make RSA signatures safe), a modulus small enough to factor, and a bare digest raised to a power directly. Unpadded RSA has real attacks of its own. None of them appear on this page, and none are needed. Key confusion does not depend on the padding scheme. Check C3 in section 6.7 shows why: what decides success is the exact serialisation of the key, not the mathematics.

A side benefit is that textbook RSA has no random padding, so every signature on this page is reproducible. PSS would have cost that.

7.4 The header is data, as long as the verifier does not obey it

Is the header protected at all? "The attacker rewrites the header" makes it sound unprotected, so we checked. Check C6 of sweep.py edits the header of a valid token. typ is the header field that names the token type:

C6 Under every verifier, is the header data or instruction? ------------------------------------------------------------ edit typ to JWS v0 reject v2 reject relabel alg to RS256 v0 reject v2 reject

Editing one field of a valid token's header breaks its signature at every verifier, because the signing input is the encoded header text (section 5.4). An attacker cannot take a token they were legitimately given and change its label.

What they can do is sign a new token. That is the difference between acts 1 and 3: act 1 edits an existing token and fails, and act 3 creates a new one and succeeds. So the whole attack comes down to one question: can the attacker compute a valid tag? The answer becomes yes as soon as a published key reaches a shared-secret algorithm.

7.5 Why exp is checked two different ways

verify_naive checks if "exp" in payload and payload["exp"] < now. verify_strict checks if payload.get("exp", 0) < now. The difference is deliberate, and it shows a second, smaller bug. Check C7 of sweep.py:

C7 The expiry check: `if 'exp' in payload` vs `payload.get('exp', 0)` ---------------------------------------------------------------------- signed, no `exp` claim, v0 (`in`) -> ADMIN signed, no `exp` claim, v3 (`.get`) -> reject signed, exp in the past, v0 -> reject ten years after issue, v0 -> ADMIN

An expiry that is enforced only when the claim is present is optional: the issuer can leave it out. Row 4 is a token that verify_naive still accepts ten years after it was issued.

This is not a forgery. It needs the real signing key, and it is a mismatch between what the issuer sends and what the verifier requires. That is why it is an experiment in sweep.py rather than an act in the demo. It is here because it shows a general rule: every claim in the payload is optional until a verifier requires it. The same applies to aud (the intended audience), iss (the issuer) and nbf (not valid before), none of which this toy implements.

test_exp_is_only_an_expiry_if_it_is_required checks the same behaviour.

7.6 Verifiers return the payload, not True

Every verifier here returns the claims on success and None on failure. Returning a boolean would be more conventional, and test_jwt.py would be shorter.

Returning the payload lets the demo print ADMIN instead of True, and that one word shows you what the forgery bought, not merely that a check passed. It also removes a temptation the boolean version creates: code that verifies the token and then parses the claims out of it a second time. If the two decodes disagree, for example because one JSON parser keeps the first of two duplicate keys and the other keeps the last, the code checks one set of claims and acts on another.

The cost is a Python detail you have to read carefully: None is falsy, and so is an empty payload {}. A production interface would raise an exception on failure instead of returning a special value, which is what real libraries do.


8. What's simplified vs. the real thing


9. Check yourself

Answer each question before you expand it. Each answer can be worked out from the source, and each was checked by running it.

Question 1

Your verifier accepts only RS256: you checked, and the allowlist is ("RS256",). Are you safe from the key-confusion forgery in section 6.3?

Answer

Yes. An allowlist with exactly one entry behaves like verify_strict (section 7.1). The forged token declares HS256, fails the membership test, and never reaches a key.

Notice what did the work. It was not that the list is short. It was that the list can no longer choose between two algorithms, so the attacker's alg field no longer affects anything. As soon as you add a second algorithm, for example during a key rotation, you have verify_allowlist again. This row of the demo's summary table shows what that costs:

key confusion ADMIN ADMIN ADMIN reject

The v2 allow column is verify_allowlist, returning ADMIN (section 7.1).

Question 2

The attacker knows your RSA public key. It is in your JWKS, which is the point of publishing it. Does that mean the key-confusion forgery works against you?

Answer

Not necessarily. The attacker needs the exact bytes your verifier passes to HMAC, not the key as a number. Check C3 of sweep.py:

attacker uses exact bytes -> v2 allowlist ADMIN attacker uses trailing newline -> v2 allowlist reject attacker uses one digit off -> v2 allowlist reject attacker uses keys reordered -> v2 allowlist reject attacker uses spaces after colons -> v2 allowlist reject attacker uses modulus alone, decimal -> v2 allowlist reject

Five of the six fail. A PEM file with a trailing newline and one without are different keys to HMAC. If your verifier looks up a parsed key object by kid and passes that object, there is no byte string to guess at all (section 6.7, boundary 1).

This changes how hard the bug is to exploit, not whether you have it. Fix the bug.

Question 3

You follow the advice and pass the algorithm explicitly: verify_strict(token, key, "HS256"). key is your RSA public key, because that is the variable your verifier already had. Are you fixed?

Answer

No. You have written the same bug out by hand. Check C5 of sweep.py:

v3 strict, server says RS256, key=PUBLIC -> reject v3 strict, server says HS256, key=PUBLIC -> ADMIN v3 strict, server says HS256, key=SECRET -> reject

Row 2 is the forged token, accepted by the "fixed" verifier. What protects you is not the argument. It is that the algorithm and the key are chosen together, by the party that owns both. Section 3.1 of RFC 8725 says it as "each key MUST be used with exactly one algorithm" (section 7.2).

Question 4

Your system uses only HS256, with a strong shared secret and an allowlist. Which of the two forgeries still works?

Answer

Neither works against verify_allowlist. The alg: none forgery still works against any verifier that does not reject none, such as verify_naive, whatever your keys are. Check C4 of sweep.py:

attacker guesses '' -> v2 allowlist reject attacker guesses 'secret' -> v2 allowlist reject attacker tries PUBLIC_KEY -> v2 allowlist reject attacker knows the secret -> v2 allowlist ADMIN but alg:none still walks in -> v0 ADMIN v1 reject

The key-confusion forgery needs a published key to use as a shared secret, and a system with only shared secrets publishes none. The alg: none forgery uses no key at all, so your choice of keys does not affect it (section 6.7, boundary 2).

Question 5

You use == instead of hmac.compare_digest to compare signatures. Measure the timing attack on this toy. What do you find?

Answer

On this machine, it does not reproduce:

candidate == ns/op compare_digest 0 leading bytes match 29.70 40.79 1 leading byte matches 31.65 38.85 31 leading bytes match 31.41 40.36 32 = full match 31.57 40.42 spread across prefix lengths, `==`: 1.95 ns/op (6.6%) monotone in prefix length, over 10 fresh rounds: 1/10

There is no trend: 1 matching byte and 31 matching bytes take the same time, and the 31-byte match is slightly faster. Repeated ten times, the four medians come out in increasing order once, where a real per-byte leak would give 10/10. Python compares equal-length bytes with memcmp, which shows no per-byte early exit at this size. The measurable difference runs the other way: compare_digest is about 9 ns (about 30%) slower per call.

Use compare_digest regardless. It costs about 9 ns and settles the question. But don't repeat the usual story as though this toy showed it. This is also one machine and one Python build, and a comparison written as a Python loop, or different hardware, can behave differently (section 6.5).

Question 6

You are reviewing a service. Its verifier calls a library function that takes (token, key) and returns claims, with no algorithm argument. You can see nothing else. What do you write in the review?

Answer

That you cannot approve it without reading the implementation, because the interface allows only two designs and one of them is broken.

If the function is not told which algorithm to use, there are two possibilities. Either it has one algorithm hardcoded, which is safe from both forgeries but means the caller can never change algorithms, or it reads alg from the token, which is verify_naive. There is no third possibility. So the parameter list alone is enough to raise the question, and the body decides the answer.

Then ask the three questions from section 6.7: does it read alg; does one key parameter serve both a shared-secret and a key-pair algorithm; and are the exact bytes of that key public. The first decides whether the bug exists. The other two decide how easily it can be exploited.


10. Further reading

Every link below was fetched and confirmed live when this was written.