Claude skill JWT algorithm confusion and weak key security — SA-SKL-JWT3
JWT authentication in MCP skills is vulnerable to a class of cryptographic attacks that do not require breaking RSA or HMAC — they exploit implementation flaws in how libraries validate the algorithm field. SA-SKL-JWT3 covers four patterns: the alg:none unsigned token bypass where a library accepts a token with an empty signature when the algorithm header is set to "none"; the RS256-to-HS256 downgrade attack where the attacker uses the public RSA key as the HMAC secret; a brute-forceable JWT_SECRET default value of "secret"; and the use of jwt.decode() instead of jwt.verify() which skips signature validation entirely.
Why JWT algorithm confusion is still widespread in MCP skills
MCP skills frequently add JWT-based authentication to protect their tool endpoints from unauthorized callers. The jsonwebtoken npm package is the dominant choice, and its API makes it easy to verify tokens — but also easy to introduce algorithm confusion bugs. The most common mistake is calling jwt.verify(token, secret) without passing an explicit algorithms option. Without this option, older versions of jsonwebtoken (pre-9.0) would accept any algorithm including none. Even in newer versions that restrict none by default, omitting the algorithm option allows the RS256-to-HS256 downgrade if the application uses asymmetric keys.
The severity of these bugs is uniformly high or critical: a successful JWT forgery means an attacker can authenticate as any user including admins, bypass rate limits tied to user identity, and access private audit data or CI webhook endpoints. SkillAudit's AST scanner checks for all four JWT3 patterns in a single pass over the skill's JavaScript or TypeScript source.
SA-SKL-JWT3 in scope: JWT3-001 (alg:none unsigned token bypass — library accepts token with empty signature when header algorithm changed to "none"), JWT3-002 (RS256→HS256 downgrade — attacker signs HS256 token with PEM-encoded public RSA key as HMAC secret), JWT3-003 (brute-forceable JWT_SECRET with default value "secret" or other short hardcoded value), JWT3-004 (jwt.decode() without signature verification accepts any payload). Each finding includes SkillAudit detection rules and correct Node.js fixes.
JWT3-001 — Algorithm confusion: alg:none unsigned token bypass
The JWT specification defines alg: "none" as a valid algorithm identifier meaning the token is unsecured — no signature is computed and the signature component of the JWT is an empty string. Some JWT libraries, particularly pre-9.0 versions of jsonwebtoken and older JJWT builds, would accept a token with alg: "none" in the header even when jwt.verify() was called with a secret. The attack is straightforward: take any valid JWT, decode the header, change "alg" to "none", change the payload claims as desired (e.g., escalate role from "user" to "admin"), re-encode as base64url without computing a signature, and append a trailing dot. The resulting token is accepted as valid.
Even in libraries where none is blocked by default, the fix requires explicitly passing the algorithms option to jwt.verify() so the library rejects tokens with any other algorithm. This defense-in-depth ensures that even if the library's default changes in a future version or the dependency is replaced with one that behaves differently, the explicit allowlist prevents unexpected algorithm acceptance.
// VULNERABLE — jwt.verify() without explicit algorithms option
// Vulnerable to alg:none bypass in jsonwebtoken < 9.0.0
// In newer versions, still vulnerable to RS256→HS256 downgrade (JWT3-002)
import jwt from 'jsonwebtoken';
const JWT_SECRET = process.env.JWT_SECRET || 'secret'; // Also vulnerable: JWT3-003
export function verifyToken(token: string): { userId: string; role: string } {
// VULNERABLE: no algorithms option — library decides what to accept
// attacker crafts: header = {"alg":"none","typ":"JWT"}
// payload = {"userId":"user123","role":"admin","iat":1699999999}
// signature = "" (empty)
// token = base64(header).base64(payload). ← trailing dot, empty sig
// jwt.verify() accepts this in vulnerable versions
const payload = jwt.verify(token, JWT_SECRET) as { userId: string; role: string };
return payload;
}
// In an MCP skill tool handler:
server.tool(
'get_audit_history',
'Get the authenticated user\'s audit history',
{ token: z.string() },
async ({ token }) => {
const { userId, role } = verifyToken(token); // role = "admin" from forged token
const audits = await db.query(
'SELECT * FROM audits WHERE owner_id = $1',
[userId]
);
// role check: attacker escalated to admin
if (role === 'admin') {
// Returns ALL audits, not just this user's
const allAudits = await db.query('SELECT * FROM audits');
return { content: [{ type: 'text', text: JSON.stringify(allAudits.rows) }] };
}
return { content: [{ type: 'text', text: JSON.stringify(audits.rows) }] };
}
);
// FIXED — explicit algorithms allowlist; strong secret from environment
import jwt from 'jsonwebtoken';
// Never use a default — if JWT_SECRET is missing, fail fast at startup
const JWT_SECRET = process.env.JWT_SECRET;
if (!JWT_SECRET || JWT_SECRET.length < 64) {
throw new Error(
'JWT_SECRET must be set in environment and at least 64 characters. ' +
'Generate with: node -e "console.log(require(\'crypto\').randomBytes(64).toString(\'hex\'))"'
);
}
export function verifyToken(token: string): { userId: string; role: string } {
// FIXED: explicit algorithms option — only HS256 is accepted
// alg:none, RS256, RS512, ES256, etc. all rejected
const payload = jwt.verify(token, JWT_SECRET, {
algorithms: ['HS256'], // Explicit allowlist — no other algorithm accepted
// Also set audience and issuer if applicable:
// audience: 'skillaudit.dev',
// issuer: 'api.skillaudit.dev',
}) as { userId: string; role: string };
return payload;
}
// Token generation must use the same algorithm:
export function generateToken(userId: string, role: string): string {
return jwt.sign(
{ userId, role },
JWT_SECRET,
{
algorithm: 'HS256', // Explicit algorithm — matches allowlist in verify
expiresIn: '15m', // Short-lived access token
issuer: 'api.skillaudit.dev',
audience: 'skillaudit.dev',
}
);
}
jwt.verify(token, secret) without an explicit algorithms option, allowing an attacker to change the token's alg header to "none", remove the signature, and present an unsigned token that the library accepts as valid — enabling arbitrary claim forgery including role escalation; fix by passing { algorithms: ['HS256'] } (or the specific algorithm in use) to every jwt.verify() call and failing startup if JWT_SECRET is absent or shorter than 64 characters. Detection: SkillAudit flags every jwt.verify() call that does not include an algorithms array in its options argument.JWT3-002 — RS256 to HS256 downgrade using the public key as HMAC secret
When an MCP skill uses asymmetric JWT signing (RS256 or ES256), the public key is typically distributed openly — for example, served at a /.well-known/jwks.json endpoint or embedded in the client application. The RS256-to-HS256 downgrade attack exploits a subtle interaction between asymmetric and symmetric JWT libraries: if the server accepts both RS256 and HS256 tokens (or if the algorithms option is omitted), an attacker can take the server's public RSA key (which is not secret), use it as the HMAC-SHA256 signing key, and sign an HS256 token. When the server calls jwt.verify(token, publicKey) without specifying algorithms: ['RS256'], the library switches to HMAC mode because the token header says alg: "HS256", and the HMAC signature verifies correctly because the attacker used the public key as the HMAC secret — the same key the server passes to jwt.verify().
The fix is strict: when using RS256, pass algorithms: ['RS256'] to jwt.verify() so the library rejects any token with an alg other than RS256. Additionally, use a separate signing key registry that associates each algorithm with its key — never pass a key that could be interpreted as a secret for another algorithm.
// VULNERABLE — RS256 skill that accepts HS256 downgrade
// Public key is served at /.well-known/jwks.json — attacker has it
import jwt from 'jsonwebtoken';
import fs from 'fs';
const PUBLIC_KEY = fs.readFileSync('./keys/public.pem', 'utf8');
// PEM-encoded RSA public key — attacker obtains this from JWKS endpoint
export function verifyToken(token: string) {
// VULNERABLE: no algorithms option
// If token header has alg: "HS256", jwt.verify() switches to HMAC mode
// and verifies the signature using PUBLIC_KEY as the HMAC secret.
// Attacker:
// 1. Gets public key from /.well-known/jwks.json
// 2. Signs a token: jwt.sign({userId:'admin',role:'admin'}, publicKey, {algorithm:'HS256'})
// 3. Sends HS256-signed token — server accepts it as valid!
return jwt.verify(token, PUBLIC_KEY);
}
// Even worse: accepting multiple algorithms
export function verifyTokenPermissive(token: string) {
// VULNERABLE: explicitly allows both — attacker can choose HS256 and use public key
return jwt.verify(token, PUBLIC_KEY, {
algorithms: ['RS256', 'HS256'], // Never mix asymmetric and symmetric
});
}
// FIXED — strict RS256 only; separate key registry per algorithm
import jwt from 'jsonwebtoken';
import fs from 'fs';
import { createPublicKey } from 'crypto';
// Key registry — maps algorithm to its verification key
// For RS256: public key (KeyObject) only
// For HS256: would use a separate symmetric secret — never shared with asymmetric
const KEY_REGISTRY: Record<string, { key: jwt.Secret | jwt.GetPublicKeyOrSecret; algorithms: jwt.Algorithm[] }> = {
RS256: {
key: fs.readFileSync('./keys/public.pem', 'utf8'),
algorithms: ['RS256'], // Only RS256 — HS256 not in this registry entry
},
// HS256 would be a separate entry with a different secret — never the RSA public key
// HS256: { key: process.env.HS_SECRET, algorithms: ['HS256'] }
};
export function verifyToken(token: string) {
// Decode header first to find algorithm — only used for key registry lookup,
// not trusted for security (the algorithms option in jwt.verify enforces the actual check)
const decoded = jwt.decode(token, { complete: true });
if (!decoded || typeof decoded === 'string') {
throw new Error('Invalid JWT format');
}
const alg = decoded.header.alg as string;
const entry = KEY_REGISTRY[alg];
if (!entry) {
throw new Error(`Algorithm '${alg}' is not permitted — only RS256 is accepted`);
}
// jwt.verify with explicit algorithms — library enforces this regardless of header
// Even if attacker crafts alg: "HS256" token and passes it here,
// jwt.verify rejects it because algorithms: ['RS256'] — header alg must match
return jwt.verify(token, entry.key, {
algorithms: entry.algorithms,
issuer: 'api.skillaudit.dev',
audience: 'skillaudit.dev',
});
}
jwt.verify(token, publicKey) without algorithms: ['RS256'], allowing an attacker who obtains the public key (from JWKS, source code, or public endpoints) to sign an HS256 token using that public key as the HMAC secret — the server verifies the HMAC signature with the same public key it passes to jwt.verify() and accepts the forged token; fix by always passing algorithms: ['RS256'] (or the single specific algorithm in use) and never mixing asymmetric and symmetric algorithms in the same allowlist. Detection: SkillAudit flags jwt.verify() calls that pass a PEM-encoded key without restricting the algorithms option to the specific asymmetric algorithm in use.JWT3-003 — JWT secret from process.env with brute-forceable default value
Many MCP skill boilerplate templates include a JWT secret initialization pattern like const SECRET = process.env.JWT_SECRET || 'secret'. The fallback value 'secret' (and common alternatives like 'changeme', 'development', 'jwt-secret', and the application name) is in every JWT brute-force dictionary. Hashcat with a GPU can exhaust all 7-character lowercase secrets in under a minute. Even a 32-character random string is insufficient for HS256 — NIST SP 800-131A recommends at least 256 bits (32 bytes) of entropy for HMAC-SHA256 keys. The practical fix is 64 bytes (512 bits) generated by crypto.randomBytes(64).toString('hex'), stored only in the deployment environment's secrets manager, never in source code or a .env file committed to git.
The secondary issue is the fallback pattern itself: using || 'default' means a misconfigured deployment silently uses a weak secret rather than failing. The correct pattern is to throw at startup if JWT_SECRET is absent or too short, so the deployment fails visibly rather than running insecurely.
// VULNERABLE — multiple weak secret patterns
import jwt from 'jsonwebtoken';
// Pattern 1: hardcoded fallback — most dangerous
const SECRET_1 = process.env.JWT_SECRET || 'secret';
// Pattern 2: app-name as secret — in every dictionary
const SECRET_2 = process.env.JWT_SECRET || 'skillaudit';
// Pattern 3: empty string default — jwt.verify() with empty string always passes
// (some library versions accept any payload when secret is empty)
const SECRET_3 = process.env.JWT_SECRET || '';
// Pattern 4: short random secret in source — committed to git, not rotatable
const SECRET_4 = 'x9k2mP4q'; // 8 chars — brute-forceable in <1s
// Pattern 5: UUID as secret — only 122 bits of entropy, format is predictable
const SECRET_5 = process.env.JWT_SECRET || '550e8400-e29b-41d4-a716-446655440000';
function signToken(userId: string) {
return jwt.sign({ userId }, SECRET_1); // Uses weak fallback when env var is unset
}
// FIXED — strong secret enforcement; fail fast at startup
import jwt from 'jsonwebtoken';
import { randomBytes } from 'crypto';
// Fail at startup if JWT_SECRET is absent or too short
// This surfaces misconfiguration immediately rather than allowing insecure operation
function loadJwtSecret(): string {
const secret = process.env.JWT_SECRET;
if (!secret) {
throw new Error(
'JWT_SECRET environment variable is required but not set.\n' +
'Generate a strong secret with:\n' +
' node -e "console.log(require(\'crypto\').randomBytes(64).toString(\'hex\'))"\n' +
'Then set it in your deployment environment secrets manager.'
);
}
// Minimum 64 hex characters = 32 bytes = 256 bits of entropy for HS256
// We recommend 128 hex chars (64 bytes / 512 bits) to exceed NIST recommendations
if (secret.length < 64) {
throw new Error(
`JWT_SECRET is too short (${secret.length} chars). ` +
'Minimum 64 characters (32 bytes). ' +
'Regenerate with: node -e "console.log(require(\'crypto\').randomBytes(64).toString(\'hex\'))"'
);
}
// Reject known weak defaults — defense against copy-paste errors
const WEAK_SECRETS = new Set([
'secret', 'password', 'changeme', 'development', 'production',
'jwt-secret', 'jwt_secret', 'skillaudit', 'mysecret', 'supersecret',
]);
if (WEAK_SECRETS.has(secret.toLowerCase())) {
throw new Error(
`JWT_SECRET has a known-weak value ('${secret}'). ` +
'Use a randomly generated secret of at least 64 characters.'
);
}
return secret;
}
// Called at module load — crashes the process if secret is misconfigured
// This is the correct behavior: fail visible, not silently insecure
const JWT_SECRET = loadJwtSecret();
export function signToken(userId: string, role: string): string {
return jwt.sign(
{ userId, role },
JWT_SECRET,
{
algorithm: 'HS256',
expiresIn: '15m',
issuer: 'api.skillaudit.dev',
}
);
}
export function verifyToken(token: string): { userId: string; role: string } {
return jwt.verify(token, JWT_SECRET, {
algorithms: ['HS256'],
issuer: 'api.skillaudit.dev',
}) as { userId: string; role: string };
}
// Key generation utility — run once at deployment setup:
// node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"
// Store the output in AWS Secrets Manager / GCP Secret Manager / Vault
// Never commit to .env files in source control
|| 'secret', || 'changeme', app name, etc.) that appears in JWT brute-force wordlists and can be cracked by Hashcat with a GPU in under a minute, allowing an attacker to sign arbitrary tokens; fix by throwing at startup when JWT_SECRET is absent or shorter than 64 characters, never using a fallback value, and generating the secret with crypto.randomBytes(64).toString('hex'). Detection: SkillAudit flags the patterns process.env.JWT_SECRET || '..., hardcoded string secrets under 64 characters, and known-weak secret values in JWT sign or verify call sites.JWT3-004 — jwt.decode() used instead of jwt.verify() — claims accepted without signature check
jwt.decode() and jwt.verify() are both part of the jsonwebtoken API and both return the token payload as a JavaScript object — but they are not equivalent. jwt.verify() validates the signature against the secret and checks the expiry, issuer, and audience claims. jwt.decode() does nothing except base64url-decode the header and payload — it performs no signature verification, no expiry check, and no claim validation. It is intended for cases where you already trust the token (e.g., after verification) and need to inspect the payload without a secret on hand, such as a client-side application displaying the user's name from a token the server already verified.
Using jwt.decode() as the authentication check in a server-side tool handler is a complete authentication bypass: an attacker can create any JWT payload they want, base64url-encode it with any header and any (or no) signature, and the server will accept it and act on the claims. This bug typically appears when a developer copies a client-side pattern into a server-side context without understanding the difference between the two functions.
// VULNERABLE — jwt.decode() on server side: no signature verification
import jwt from 'jsonwebtoken';
// Pattern 1: direct use of decode() as authentication
export function authenticateRequest(token: string): { userId: string; role: string } {
// VULNERABLE: jwt.decode() performs NO signature verification
// Attacker can send: btoa('{"alg":"HS256","typ":"JWT"}') + '.' + btoa('{"userId":"admin","role":"admin"}') + '.'
// jwt.decode() will return { userId: 'admin', role: 'admin' } without any check
const payload = jwt.decode(token) as { userId: string; role: string } | null;
if (!payload) throw new Error('Invalid token format');
return payload; // Trusts forged payload!
}
// Pattern 2: decode() used in middleware to "get" the user
// (may occur alongside a verify() call elsewhere, but this path bypasses it)
function extractUserFromToken(authHeader: string | undefined) {
if (!authHeader?.startsWith('Bearer ')) return null;
const token = authHeader.slice(7);
// Developer thought this reads the user from the token
// but forgot that decode() doesn't verify anything
return jwt.decode(token) as { userId: string } | null;
}
server.tool(
'delete_audit',
'Delete an audit record',
{ token: z.string(), auditId: z.string() },
async ({ token, auditId }) => {
const user = authenticateRequest(token); // No signature check
if (user.role !== 'admin') throw new Error('Forbidden');
await db.query('DELETE FROM audits WHERE id = $1', [auditId]);
return { content: [{ type: 'text', text: 'Deleted' }] };
}
);
// FIXED — always use jwt.verify() on the server; decode() only for pre-verified tokens
import jwt from 'jsonwebtoken';
const JWT_SECRET = (() => {
const s = process.env.JWT_SECRET;
if (!s || s.length < 64) throw new Error('JWT_SECRET missing or too short');
return s;
})();
// Server-side authentication ALWAYS uses verify(), never decode()
export function authenticateRequest(token: string): { userId: string; role: string } {
// jwt.verify():
// 1. Decodes the base64url header and payload
// 2. Recomputes the HMAC-SHA256 signature using JWT_SECRET
// 3. Compares computed signature with token's signature (constant-time)
// 4. Checks exp, nbf, iat, iss, aud claims if configured
// 5. Throws if any check fails — never returns a payload from an invalid token
const payload = jwt.verify(token, JWT_SECRET, {
algorithms: ['HS256'],
issuer: 'api.skillaudit.dev',
}) as { userId: string; role: string; exp: number };
return payload;
}
// jwt.decode() is ONLY acceptable in these scenarios:
// 1. Client-side display of non-sensitive claims (username, avatar URL)
// where the server already verified the token before issuing the session
// 2. Reading the 'kid' (key ID) header to look up which key to use in verify()
// — in this case decode() is called to find the key, then verify() is called with it
// Example of the ONLY valid server-side use of decode() — key ID lookup:
export function verifyMultiKeyToken(token: string, keyStore: Map<string, string>): object {
// Step 1: decode header ONLY to find key ID — not trusted for auth
const decoded = jwt.decode(token, { complete: true });
if (!decoded || typeof decoded === 'string') throw new Error('Invalid JWT');
const kid = decoded.header.kid as string | undefined;
if (!kid) throw new Error('Missing key ID in JWT header');
const key = keyStore.get(kid);
if (!key) throw new Error(`Unknown key ID: ${kid}`);
// Step 2: VERIFY with the found key — this is the actual authentication check
return jwt.verify(token, key, { algorithms: ['RS256'] }) as object;
}
jwt.decode() as its server-side authentication check instead of jwt.verify(), performing no signature verification, expiry check, or claim validation — an attacker can craft any JWT payload (including role: "admin"), base64url-encode it without a valid signature, and the server accepts it; fix by replacing every server-side jwt.decode() authentication call with jwt.verify(token, secret, { algorithms: ['HS256'] }) and reserving jwt.decode() only for client-side display of pre-verified claims or for key-ID header lookup before a subsequent jwt.verify() call. Detection: SkillAudit flags every jwt.decode() call in a server-side module where the return value is used in an authorization or authentication check.Detection summary
| ID | Severity | Pattern | Fix |
|---|---|---|---|
| JWT3-001 | CRITICAL | jwt.verify() without algorithms option — accepts alg:none unsigned token with forged claims |
{ algorithms: ['HS256'] } in every jwt.verify() call |
| JWT3-002 | CRITICAL | RS256→HS256 downgrade — attacker uses public RSA key as HMAC secret for HS256 token; server accepts it without algorithms: ['RS256'] |
Pass algorithms: ['RS256']; never mix asymmetric and symmetric in one allowlist |
| JWT3-003 | HIGH | JWT_SECRET fallback default ('secret', app name, empty string) — brute-forceable; deploy without env var uses weak value silently |
Throw at startup if absent or <64 chars; generate with randomBytes(64).toString('hex') |
| JWT3-004 | CRITICAL | jwt.decode() as server-side auth check — no signature, expiry, or claim validation; complete authentication bypass |
Replace with jwt.verify(); decode() only for client-side display or kid lookup |
Related patterns: SA-SKL-SESSION2 covers session fixation and concurrent session security for MCP skills using session-based (non-JWT) authentication. SA-SKL-OAUTH3 covers the OAuth PKCE flow — the authorization code layer that issues JWTs — including missing PKCE, weak code_verifier entropy, and state CSRF. SA-SKL-DEPENDENCY3 covers supply chain risks including malicious versions of jwt libraries published to npm.