Claude skill JWT token security — SA-SKL-JWT
MCP skills that issue or validate JWT tokens for session management, API authorization, or cross-tool authentication are exposed to four JWT-specific attack patterns: algorithm substitution bypassing signature verification entirely, brute-forcing of weak HMAC secrets from leaked tokens, SQL or path injection via the JWT kid (key ID) header parameter, and use of jwt.decode() without jwt.verify() silently accepting forged tokens. SA-SKL-JWT covers all four patterns with the attack mechanics and correct fixes for Claude skill deployments.
JWT-001 — alg:none header bypass (CRITICAL)
The alg:none attack is one of the oldest JWT vulnerabilities and remains exploitable in any Node.js skill that calls jwt.verify() without an explicit algorithms option. The JWT specification allows an algorithm value of "none" to signal that the token is unsecured, and several versions of the jsonwebtoken library honor this when no algorithm restriction is supplied.
Vulnerable code
// auth-middleware.ts — VULNERABLE
import jwt from 'jsonwebtoken';
export function verifyToken(token: string): JwtPayload {
// No algorithms option — library accepts alg:none tokens
const payload = jwt.verify(token, process.env.JWT_SECRET as string);
return payload as JwtPayload;
}
// Called in skill handler:
const user = verifyToken(req.headers.authorization!.replace('Bearer ', ''));
Attack mechanics
An attacker who holds any legitimate JWT (even one with minimal permissions) can craft a forged alg:none token in seconds:
# Step 1: decode a legitimate token from an HTTP response or log
# Original header: {"alg":"HS256","typ":"JWT"}
# Original payload: {"userId":"user-123","role":"viewer","iat":1730700000}
# Step 2: craft forged header and payload
import base64, json
forged_header = base64.urlsafe_b64encode(
json.dumps({"alg": "none", "typ": "JWT"}).encode()
).rstrip(b'=').decode()
forged_payload = base64.urlsafe_b64encode(
json.dumps({"userId": "admin-001", "role": "admin", "iat": 1730700000}).encode()
).rstrip(b'=').decode()
# Step 3: produce token with EMPTY signature segment
forged_token = f"{forged_header}.{forged_payload}."
# → eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJ1c2VySWQiOiJhZG1pbi0wMDEiLCJyb2xlIjoiYWRtaW4iLCJpYXQiOjE3MzA3MDAwMDB9.
# Step 4: send in Authorization header — jwt.verify() accepts it
Impact: Complete authentication bypass. The attacker forges a token with any userId, role, or permission claim. All skill endpoints that gate on JWT claims are compromised. No brute force or key material is needed — the attack requires only a single valid token for the base64 encoding reference.
Secure fix
// auth-middleware.ts — SECURE
import jwt, { JwtPayload, VerifyOptions } from 'jsonwebtoken';
const JWT_VERIFY_OPTIONS: VerifyOptions = {
algorithms: ['HS256'], // explicit allowlist — rejects alg:none and RS256 confusion attacks
issuer: 'skillaudit-mcp',
audience: 'mcp-skill-api',
};
export function verifyToken(token: string): JwtPayload {
// Throws JsonWebTokenError if alg:none or any non-HS256 algorithm is presented
const payload = jwt.verify(
token,
process.env.JWT_SECRET as string,
JWT_VERIFY_OPTIONS,
);
return payload as JwtPayload;
}
// For asymmetric keys (RS256), provide the PUBLIC KEY and restrict algorithm:
export function verifyTokenRS256(token: string): JwtPayload {
const publicKey = fs.readFileSync('/run/secrets/jwt_public_key', 'utf8');
return jwt.verify(token, publicKey, { algorithms: ['RS256'] }) as JwtPayload;
}
Detection: SkillAudit's AST scanner flags any call to jwt.verify(token, secret) with exactly two arguments — the missing third options argument is the indicator. It also flags jwt.verify(token, secret, {}) where the options object has no algorithms property, since an empty options object provides no algorithm restriction.
JWT-002 — HMAC secret brute force via weak or static key (HIGH)
HMAC-SHA256 JWT signatures are only as strong as the secret used to create them. When a skill uses a short, predictable, or hardcoded JWT secret, any attacker who obtains a signed token can mount an offline dictionary or brute-force attack to recover the secret and subsequently forge arbitrary tokens.
Vulnerable code
// config.ts — VULNERABLE patterns
// Pattern A: hardcoded short secret
const JWT_SECRET = 'secret';
// Pattern B: predictable secret derived from app metadata
const JWT_SECRET = process.env.APP_NAME + '_jwt_2024';
// Pattern C: environment variable with weak default fallback
const JWT_SECRET = process.env.JWT_SECRET ?? 'dev-secret-change-me';
// All three produce JWTs that are trivially crackable offline
const token = jwt.sign({ userId: user.id, role: user.role }, JWT_SECRET, {
algorithm: 'HS256',
expiresIn: '24h',
});
Attack mechanics
JWT HMAC cracking requires only a single valid signed token, which is often available from API responses, error logs, or even browser developer tools:
# Offline brute force with hashcat (mode 16500 = JWT HS256/HS384/HS512)
# A stolen token: eyJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOiJ1c2VyLTEyMyJ9.<signature>
hashcat -a 0 -m 16500 stolen_token.txt /usr/share/wordlists/rockyou.txt
# → "secret" cracked in 0.003s on consumer GPU
# Brute force short alphanumeric secrets (up to 7 chars) with jwt-cracker
npx jwt-cracker --token "eyJ..." --alphabet "abcdefghijklmnopqrstuvwxyz0123456789" --maxLength 7
# → 7-char alphanumeric exhausted in ~8 minutes on M2 MacBook Pro
# Once secret is known, forge any payload:
const forgedToken = jwt.sign(
{ userId: 'admin-001', role: 'admin', isSuper: true },
'secret', // recovered secret
{ algorithm: 'HS256', noTimestamp: true }
);
Impact: Once the HMAC secret is recovered, the attacker can forge tokens with any claims indefinitely — until the secret is rotated. Because rotation requires redeployment and invalidates all existing sessions, many teams delay it, extending the window of compromise.
Secure fix
// config.ts — SECURE
import crypto from 'node:crypto';
import { SecretsManagerClient, GetSecretValueCommand } from '@aws-sdk/client-secrets-manager';
// Option A: generate a 256-bit secret at startup (ephemeral — good for single-instance)
// Store in secret manager for multi-instance or persistent sessions
const JWT_SECRET = crypto.randomBytes(32).toString('hex');
// → 64 hex chars = 256 bits of entropy; brute force is computationally infeasible
// Option B: load from AWS Secrets Manager (recommended for production)
async function loadJwtSecret(): Promise<string> {
const client = new SecretsManagerClient({ region: process.env.AWS_REGION });
const response = await client.send(
new GetSecretValueCommand({ SecretId: 'skillaudit/jwt-secret' })
);
return response.SecretString!;
}
// Option C: RS256 with 2048-bit key pair — secret never needs to be shared
// Generate once: openssl genrsa -out jwt_private.pem 2048
// openssl rsa -in jwt_private.pem -pubout -out jwt_public.pem
const PRIVATE_KEY = fs.readFileSync('/run/secrets/jwt_private_key', 'utf8');
const PUBLIC_KEY = fs.readFileSync('/run/secrets/jwt_public_key', 'utf8');
export function signToken(payload: object): string {
return jwt.sign(payload, PRIVATE_KEY, {
algorithm: 'RS256',
expiresIn: '1h',
issuer: 'skillaudit-mcp',
});
}
// Fail-fast if a weak secret is configured
if (process.env.JWT_SECRET && process.env.JWT_SECRET.length < 32) {
throw new Error('JWT_SECRET must be at least 32 characters (256 bits). Use crypto.randomBytes(32).');
}
Detection: SkillAudit flags string literals assigned to variables named JWT_SECRET, jwtSecret, or jwtKey, and any jwt.sign() call where the second argument is a string literal shorter than 32 characters. It also flags ?? or || fallback patterns that substitute a literal string when the environment variable is absent.
JWT-003 — JWT kid header SQL injection and path traversal (HIGH)
The JWT kid (key ID) header parameter allows issuers to signal which key was used to sign a token, enabling key rotation and multi-key setups. When a skill uses the kid value directly in a database query or filesystem path without validation, an attacker who can craft a JWT header controls that lookup — leading to SQL injection or path traversal before the signature is even checked.
Vulnerable code
// key-resolver.ts — VULNERABLE (SQL injection via kid)
import { pool } from './db';
import jwt from 'jsonwebtoken';
async function getSigningKey(kid: string): Promise<string> {
// kid flows directly into SQL string — NEVER do this
const result = await pool.query(
`SELECT signing_key FROM jwt_keys WHERE id = '${kid}'`
);
return result.rows[0].signing_key;
}
export async function verifyTokenDynamic(token: string): Promise<JwtPayload> {
// jwt.decode() reads the unverified header to extract kid
const decoded = jwt.decode(token, { complete: true });
const kid = decoded?.header?.kid; // attacker-controlled value
const key = await getSigningKey(kid); // unsafe DB lookup
return jwt.verify(token, key, { algorithms: ['HS256'] }) as JwtPayload;
}
// key-resolver.ts — VULNERABLE (path traversal via kid)
async function getSigningKeyFromFile(kid: string): Promise<Buffer> {
// kid flows directly into filesystem path — path traversal possible
return fs.readFileSync('/var/app/keys/' + kid + '.pem');
}
Attack mechanics
# Attack A: SQL injection — override signing key with attacker-controlled value
# Set kid header to: ' UNION SELECT 'attacker_secret' --
# jwt.decode() extracts this, getSigningKey() executes:
# SELECT signing_key FROM jwt_keys WHERE id = '' UNION SELECT 'attacker_secret' --'
# → returns 'attacker_secret'
# Attacker signs token with 'attacker_secret', kid = "' UNION SELECT 'attacker_secret' --"
# jwt.verify() uses 'attacker_secret' as the key → signature valid → auth bypass
import base64, json
malicious_header = {
"alg": "HS256",
"typ": "JWT",
"kid": "' UNION SELECT 'attacker_secret' --"
}
# Encode, sign with 'attacker_secret', append admin payload → valid token
# Attack B: path traversal — force key read from /dev/null (empty string)
# kid = "../../../dev/null"
# fs.readFileSync('/var/app/keys/../../../dev/null.pem')
# → may throw (file not found) or return empty buffer
# If library treats empty key as "no key required" → auth bypass
# Attack C: path traversal to controlled file
# Attacker previously uploaded file to /tmp/evil.txt containing 'evil_key'
# kid = "../../../tmp/evil"
# → reads /var/app/keys/../../../tmp/evil.pem if file exists
# Attacker signs with 'evil_key' → signature valid
Impact: SQL injection via kid can return an attacker-controlled signing key, enabling complete authentication bypass. Path traversal can direct the key lookup to a file the attacker controls or to a predictable system file. Both attacks occur before signature verification, so the JWT is always accepted once the key lookup is poisoned.
Secure fix
// key-resolver.ts — SECURE
import crypto from 'node:crypto';
// Option A: static in-memory key map — no DB or filesystem lookup at all
const KEY_MAP = new Map<string, string>([
['v1', process.env.JWT_SECRET_V1 as string],
['v2', process.env.JWT_SECRET_V2 as string],
]);
function getSigningKeyFromMap(kid: string): string {
// kid is validated against a fixed allowlist — no injection surface
const key = KEY_MAP.get(kid);
if (!key) throw new Error(`Unknown kid: ${kid}`);
return key;
}
// Option B: parameterized query + strict allowlist validation
const KID_PATTERN = /^[a-zA-Z0-9_-]{1,64}$/;
async function getSigningKeyFromDB(kid: string): Promise<string> {
// 1. Reject kid values that don't match the allowlist pattern
if (!KID_PATTERN.test(kid)) {
throw new Error(`Invalid kid format: ${JSON.stringify(kid)}`);
}
// 2. Parameterized query — kid is never interpolated into SQL string
const result = await pool.query(
'SELECT signing_key FROM jwt_keys WHERE id = $1',
[kid] // parameterized — safe from SQL injection
);
if (result.rows.length === 0) throw new Error('Key not found');
return result.rows[0].signing_key;
}
// Option C: filesystem lookup with strict path confinement
const KEYS_DIR = path.resolve('/var/app/keys');
async function getSigningKeyFromFile(kid: string): Promise<Buffer> {
if (!KID_PATTERN.test(kid)) throw new Error('Invalid kid');
const resolved = path.resolve(KEYS_DIR, kid + '.pem');
// Ensure resolved path is within the keys directory
if (!resolved.startsWith(KEYS_DIR + path.sep)) {
throw new Error('Path traversal detected');
}
return fs.readFileSync(resolved);
}
// Wrapper — validates kid before any lookup
export async function verifyTokenDynamic(token: string): Promise<JwtPayload> {
const decoded = jwt.decode(token, { complete: true });
const kid = decoded?.header?.kid;
if (typeof kid !== 'string') throw new Error('Missing kid header');
const key = getSigningKeyFromMap(kid); // allowlist — safe
return jwt.verify(token, key, { algorithms: ['HS256'] }) as JwtPayload;
}
Detection: SkillAudit traces the data flow from jwt.decode(token, { complete: true })?.header?.kid to template literal SQL strings, string-concatenated filesystem paths, and unparameterized query calls. It flags any path where kid (or any JWT header field) reaches a sink without an allowlist pattern test interposed in the control flow.
JWT-004 — jwt.decode() used instead of jwt.verify() (HIGH)
The jsonwebtoken package exports two distinct functions: jwt.decode() parses the base64-encoded token and returns the payload without checking the signature, while jwt.verify() validates the signature and throws if it is invalid. Code that calls jwt.decode() in an authentication path silently accepts forged tokens with any payload the attacker chooses.
Vulnerable code
// auth.ts — VULNERABLE
import jwt from 'jsonwebtoken';
import type { Request, Response, NextFunction } from 'express';
export function authenticate(req: Request, res: Response, next: NextFunction): void {
const authHeader = req.headers.authorization;
if (!authHeader?.startsWith('Bearer ')) {
res.status(401).json({ error: 'Missing token' });
return;
}
// jwt.decode() does NOT verify the signature — any payload is accepted
const token = authHeader.replace('Bearer ', '');
const user = jwt.decode(token); // ← BUG: should be jwt.verify()
if (!user || typeof user === 'string') {
res.status(401).json({ error: 'Invalid token' });
return;
}
// req.user is now set from an UNVERIFIED payload
req.user = user as JwtPayload;
next();
}
// Also vulnerable — decode after type check still doesn't verify signature
const decoded = jwt.decode(token, { complete: true });
if (decoded?.payload?.role === 'admin') {
grantAdminAccess(); // attacker-controlled decoded.payload.role
}
Attack mechanics
# jwt.decode() accepts any base64-encoded payload regardless of signature
# Attacker crafts a token with admin claims and a garbage signature
import base64, json, secrets
def b64url(data: bytes) -> str:
return base64.urlsafe_b64encode(data).rstrip(b'=').decode()
header = b64url(json.dumps({"alg": "HS256", "typ": "JWT"}).encode())
payload = b64url(json.dumps({
"userId": "admin-001",
"role": "admin",
"isAdmin": True,
"iat": 1730700000,
"exp": 9999999999
}).encode())
sig = b64url(secrets.token_bytes(32)) # random garbage — never checked by decode()
forged = f"{header}.{payload}.{sig}"
# → jwt.decode(forged) returns {"userId":"admin-001","role":"admin","isAdmin":true}
# → skill grants admin access with no valid signature
# In Node.js:
# jwt.decode('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJhZG1pbi0wMDEiLCJyb2xlIjoiYWRtaW4iLCJpc0FkbWluIjp0cnVlfQ.GARBAGE')
# → { userId: 'admin-001', role: 'admin', isAdmin: true } — no error thrown
Impact: Any user, authenticated or not, can claim any identity or role simply by encoding the desired payload. This is a full authentication bypass requiring zero cryptographic knowledge — just base64 encoding, which any HTTP client can perform.
Secure fix
// auth.ts — SECURE
import jwt, { JwtPayload, VerifyOptions } from 'jsonwebtoken';
import type { Request, Response, NextFunction } from 'express';
const VERIFY_OPTIONS: VerifyOptions = {
algorithms: ['HS256'],
issuer: 'skillaudit-mcp',
audience: 'mcp-skill-api',
};
export function authenticate(req: Request, res: Response, next: NextFunction): void {
const authHeader = req.headers.authorization;
if (!authHeader?.startsWith('Bearer ')) {
res.status(401).json({ error: 'Missing token' });
return;
}
const token = authHeader.slice(7);
try {
// jwt.verify() validates signature AND options (exp, iss, aud, alg)
const payload = jwt.verify(
token,
process.env.JWT_SECRET as string,
VERIFY_OPTIONS,
) as JwtPayload;
req.user = payload;
next();
} catch (err) {
// JsonWebTokenError, TokenExpiredError, NotBeforeError
res.status(401).json({ error: 'Invalid or expired token' });
}
}
// CORRECT usage of jwt.decode() — only after successful verify, for claim extraction
export function extractUserForLogging(token: string): string | null {
try {
// First verify — this is the guard
jwt.verify(token, process.env.JWT_SECRET as string, VERIFY_OPTIONS);
// Then decode to avoid double JSON parse (verify() already returned payload above,
// but illustrating the pattern for cases where you call verify() elsewhere)
const decoded = jwt.decode(token) as JwtPayload;
return decoded?.sub ?? null;
} catch {
return null;
}
}
// ESLint rule to ban jwt.decode() in auth files:
// In .eslintrc or eslint.config.js:
// {
// "rules": {
// "no-restricted-imports": ["error", {
// "paths": [{
// "name": "jsonwebtoken",
// "importNames": ["decode"],
// "message": "Use jwt.verify() for authentication. jwt.decode() does not check signatures."
// }]
// }]
// }
// }
Detection: SkillAudit's AST scanner flags any call to jwt.decode() in files that are part of the authentication middleware chain (detected via import graph from route files). It also flags patterns where the return value of jwt.decode() is used in a conditional that gates access, privilege escalation, or capability checks — regardless of file name.
SA-SKL-JWT findings summary
SkillAudit reports these four JWT findings with the following severities and detection methods when scanning a Claude MCP skill codebase:
jwt.verify() called without explicit algorithms option, permitting alg:none header bypass and algorithm substitution attacks. Fix: add { algorithms: ['HS256'] } (or ['RS256'] for asymmetric keys) as the third argument to every jwt.verify() call. Detection: AST check for CallExpression where callee is jwt.verify and arguments.length < 3, or where the third argument is an object literal without an algorithms property.crypto.randomBytes(32).toString('hex') for a 256-bit secret, store in a secret manager, and reject startup if secret length is below 32 characters. Detection: string literal assignments to identifiers matching /jwt.?secret|jwt.?key/i; jwt.sign() calls where the second argument is a string literal; ?? fallback to string literal from environment variable.kid header value used directly in SQL template literals or filesystem path concatenation, allowing SQL injection or path traversal to substitute the signing key. Fix: validate kid against /^[a-zA-Z0-9_-]{1,64}$/ before any lookup, prefer a static in-memory key map, and use parameterized queries if a database lookup is required. Detection: taint flow from jwt.decode(token, { complete: true })?.header?.kid to template literal SQL or string-concatenated path.join() / readFileSync() without an intervening regex test.jwt.decode() used in authentication middleware or access-control logic, silently accepting forged tokens with arbitrary payloads because signature verification is never performed. Fix: replace jwt.decode() with jwt.verify() in all auth paths; restrict jwt.decode() to logging and observability code via an ESLint no-restricted-imports rule. Detection: jwt.decode() calls where the return value flows into a conditional guarding route handlers, capability checks, or role comparisons.Running SA-SKL-JWT on your MCP skill
SkillAudit scans your skill's source tree for all four JWT patterns in a single pass. The scanner resolves import graphs to identify auth middleware files, traces taint flows from JWT header fields to dangerous sinks, and checks every jwt.verify() call for the presence and correctness of the algorithms option. Findings are reported with file path, line number, severity, and a code snippet showing the vulnerable pattern alongside the recommended fix.
To run SA-SKL-JWT against your skill, connect your repository to SkillAudit and select the JWT token security audit from the skill audit catalog. Results are available within minutes and include a SARIF report compatible with GitHub Advanced Security and VS Code.
SA-SKL-JWT is part of the SkillAudit Authentication & Authorization audit bundle, which also includes SA-SKL-OAUTH (OAuth 2.0 PKCE and state parameter validation), SA-SKL-SESSION (session fixation and cookie security), and SA-SKL-APIKEY (API key rotation and entropy checks).