Claude MCP skill timing side-channel attacks in authentication and audit result access — SA-SKL-TIMING6
Timing side-channel attacks exploit the fact that JavaScript string comparison (===) short-circuits on the first differing byte, making the response time depend on how many leading bytes match. When secrets — API keys, share tokens, JWT signatures — are compared with ===, an attacker who can measure request latency can narrow the search space from the full key space to 36 sequential guesses per character position. SA-SKL-TIMING6 covers four timing side-channel patterns unique to MCP skill registry authentication flows.
compare() skipped entirely when user record is not found — attacker measures <1ms response for unknown email vs ~100ms bcrypt response for wrong password on known account; enumerates all registered developer accounts at the registry===) which short-circuits on first differing byte — timing difference leaks how many leading characters of a submitted key match the stored key, reducing 32-char hex key brute-force from 16^32 to 32 sequential rounds of 16 guesses=== string equality — timing oracle allows brute-forcing the 6-character alphanumeric token character-by-character: 36 guesses per position × 6 positions = 216 total requests instead of 2.1 billion; private audit reports readable by unauthenticated attackers=== instead of using jsonwebtoken.verify() — RSA signature comparison timing oracle leaks partial signature information enabling signature forgery over many requestsTIMING6-001 — bcrypt early return leaks account existence
Password login flows typically look up the user by email, then compare the submitted password against the stored bcrypt hash. If the user is not found, many implementations skip the bcrypt comparison entirely and immediately return an error. This creates a measurable timing difference: unknown emails receive a response in under 1 millisecond (database miss, immediate return), while known emails with wrong passwords wait 50-200ms for bcrypt to complete. An attacker who submits the same wrong password to hundreds of email addresses can enumerate which addresses have accounts by measuring response latency.
// VULNERABLE — TIMING6-001
// bcrypt.compare() not called when user not found — measurable timing difference.
// Attacker submits: POST /api/auth/login { email: "guess@example.com", password: "wrong" }
// Unknown email: response in <1ms (no bcrypt)
// Known email wrong password: response in ~100ms (bcrypt runs)
app.post('/api/auth/login', async (req, res) => {
const { email, password } = req.body;
const user = await db.users.findOne({ email });
if (!user) {
// VULNERABLE: immediate return, no bcrypt — timing oracle for account existence
return res.status(401).json({ error: 'Invalid credentials' });
}
const valid = await bcrypt.compare(password, user.passwordHash);
if (!valid) {
return res.status(401).json({ error: 'Invalid credentials' });
}
res.json({ token: issueJWT(user) });
});
// FIXED — TIMING6-001
// Fix: Always run bcrypt.compare() even for non-existent accounts using a constant dummy hash.
// The dummy hash ensures the response time is always dominated by bcrypt regardless of whether the account exists.
// Pre-computed hash of a dummy password — generated once at startup, never changes.
// Use cost factor 12 to match your production bcrypt settings.
const DUMMY_HASH = '$2b$12$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';
app.post('/api/auth/login', async (req, res) => {
const { email, password } = req.body;
const user = await db.users.findOne({ email });
// FIX: Always run bcrypt — use dummy hash if user not found
const hashToCompare = user ? user.passwordHash : DUMMY_HASH;
const valid = await bcrypt.compare(password, hashToCompare);
// FIX: Never short-circuit on user not found before bcrypt completes
if (!user || !valid) {
return res.status(401).json({ error: 'Invalid credentials' });
}
res.json({ token: issueJWT(user) });
});
Why dummy hash must match your cost factor: If your production bcrypt uses cost factor 12 but the dummy hash was generated at cost factor 10, the dummy comparison completes faster than a real comparison — the timing difference leaks account existence again. Generate the DUMMY_HASH constant with the same cost factor as your production password hashing: DUMMY_HASH = await bcrypt.hash('dummy-' + crypto.randomBytes(16).toString('hex'), 12) — computed once at startup.
TIMING6-002 — API key string equality leaks prefix characters
MCP skill registries issue API keys so developers can authenticate CI/CD pipelines and GitHub Actions workflows. When the server looks up the API key by value using WHERE api_key = ? (which is a constant-time database scan) and then compares the result with ===, the comparison itself leaks timing. More commonly, some implementations skip the database lookup entirely and use an in-memory Map or Redis hash — the hash lookup is O(1) but the string comparison to verify the full key is linear. For 32-character hex API keys, an attacker who can send thousands of requests and measure microsecond latency can recover the key character by character over 32 rounds of 16 guesses.
// VULNERABLE — TIMING6-002
// API key comparison uses string equality which short-circuits.
// In-memory map lookup + string compare leaks prefix timing.
const apiKeys = new Map(); // keyId → { key: "sk_live_a3f7...", userId: "..." }
app.use('/api/v1', async (req, res, next) => {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Unauthorized' });
}
const submittedKey = authHeader.slice(7);
const [keyId] = submittedKey.split('_');
const record = apiKeys.get(keyId);
if (!record) return res.status(401).json({ error: 'Unauthorized' });
// VULNERABLE: string === short-circuits — timing leaks how many leading bytes match
if (record.key !== submittedKey) {
return res.status(401).json({ error: 'Unauthorized' });
}
req.userId = record.userId;
next();
});
// FIXED — TIMING6-002
// Fix: Use crypto.timingSafeEqual() for all API key comparisons.
// Buffers must be the same length — pad or use fixed-length keys.
const { timingSafeEqual } = require('crypto');
app.use('/api/v1', async (req, res, next) => {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Unauthorized' });
}
const submittedKey = authHeader.slice(7);
const [keyId] = submittedKey.split('_');
const record = apiKeys.get(keyId);
// FIX: Always run timingSafeEqual even when record is not found (use dummy)
const storedKey = record ? record.key : 'sk_dummy_' + '0'.repeat(submittedKey.length - 9);
let valid = false;
try {
// FIX: timingSafeEqual requires equal-length buffers
const a = Buffer.from(storedKey);
const b = Buffer.from(submittedKey.padEnd(storedKey.length, '\0').slice(0, storedKey.length));
valid = record && timingSafeEqual(a, b) && storedKey.length === submittedKey.length;
} catch {
valid = false;
}
if (!valid) return res.status(401).json({ error: 'Unauthorized' });
req.userId = record.userId;
next();
});
TIMING6-003 — Share token timing oracle enables character-by-character brute-force
Audit reports are shared via 6-character alphanumeric tokens (e.g. https://skillaudit.dev/audits/x9kZ4r). The token space is 36^6 = 2.17 billion combinations — large enough to resist brute-force if each attempt is counted independently. But if the token comparison uses === string equality, an attacker can exploit the short-circuit behaviour to brute-force one character at a time. For each of the 6 positions, the attacker sends 36 requests (a-z + 0-9) and identifies the correct character as the one that takes slightly longer to return. 36 × 6 = 216 total requests to recover any share token.
// VULNERABLE — TIMING6-003
// 6-char alphanumeric share token compared with === string equality.
// 36 sequential guesses per character × 6 chars = 216 requests to brute-force.
app.get('/audits/:auditId/share/:token', async (req, res) => {
const { auditId, token } = req.params;
const audit = await db.audits.findOne({ id: auditId });
if (!audit || !audit.shareToken) {
return res.status(404).json({ error: 'Not found' });
}
// VULNERABLE: === short-circuits — timing reveals how many characters match
if (audit.shareToken !== token) {
return res.status(403).json({ error: 'Invalid token' });
}
res.json({ audit: redactPrivateFields(audit) });
});
// FIXED — TIMING6-003
// Fix 1: Use crypto.timingSafeEqual() for share token comparison.
// Fix 2: Use longer tokens (16+ chars) to make even non-timing brute-force infeasible.
// Fix 3: Rate-limit share token verification endpoints per IP.
const { timingSafeEqual } = require('crypto');
app.get('/audits/:auditId/share/:token', rateLimiter(10, '1m'), async (req, res) => {
const { auditId, token } = req.params;
const audit = await db.audits.findOne({ id: auditId });
// FIX 1: Always compare with timingSafeEqual; use dummy token if audit not found
const storedToken = audit?.shareToken ?? crypto.randomBytes(8).toString('hex');
// FIX 2: Pad/truncate submitted token to stored length to prevent length oracle
const storedBuf = Buffer.from(storedToken, 'utf8');
const submittedBuf = Buffer.from(token.slice(0, storedBuf.length).padEnd(storedBuf.length, '\x00'), 'utf8');
const tokenValid = timingSafeEqual(storedBuf, submittedBuf)
&& storedToken.length === token.length;
if (!audit || !tokenValid) {
return res.status(404).json({ error: 'Not found' });
}
res.json({ audit: redactPrivateFields(audit) });
});
Upgrade share token length: A 6-character alphanumeric token is 35 bits of entropy. Even with timingSafeEqual(), rate-limit bypasses or high-volume distributed requests could exhaust the space. Use 16-character tokens (83 bits) or 32-character hex tokens (128 bits) for new audit shares. The URL is negligibly longer and the security gain is enormous.
TIMING6-004 — Legacy JWT signature comparison timing oracle
JWT libraries like jsonwebtoken perform timing-safe signature verification internally. Problems arise when developers write legacy verification code that manually base64-decodes the JWT parts and compares the decoded signature using ===. RSA signatures are 256 bytes (2048-bit RSA) or 64 bytes (ES256 ECDSA). String comparison with === on these byte arrays is linear and reveals how many leading bytes of the submitted signature match the expected signature. Over thousands of requests, an attacker can recover the expected signature byte by byte and forge a valid JWT without the private key.
// VULNERABLE — TIMING6-004
// Manual JWT verification with string === comparison on decoded signature.
// Legacy code from before jsonwebtoken was added as a dependency.
function verifyJWT(token, publicKey) {
const [headerB64, payloadB64, signatureB64] = token.split('.');
const data = `${headerB64}.${payloadB64}`;
const signature = Buffer.from(signatureB64, 'base64url').toString('binary');
const expectedSig = crypto.createVerify('RSA-SHA256')
.update(data)
.sign(privateKey, 'binary'); // BUG: should use verify() not sign()
// VULNERABLE: string comparison leaks timing for multi-byte signatures
if (signature !== expectedSig) {
throw new Error('Invalid signature');
}
return JSON.parse(Buffer.from(payloadB64, 'base64url').toString());
}
// Even the correct verify() path can be miscoded with string ===:
function verifyJWTAlt(token, publicKey) {
const [headerB64, payloadB64, signatureB64] = token.split('.');
const signature = Buffer.from(signatureB64, 'base64url');
const data = Buffer.from(`${headerB64}.${payloadB64}`);
const verifier = crypto.createVerify('RSA-SHA256');
verifier.update(data);
const expectedSig = Buffer.from(computeExpectedSig(data, publicKey));
// VULNERABLE: even Buffer comparison with === converts to string first
if (signature.toString('hex') !== expectedSig.toString('hex')) {
throw new Error('Invalid signature');
}
return JSON.parse(Buffer.from(payloadB64, 'base64url').toString());
}
// FIXED — TIMING6-004
// Fix: Use jsonwebtoken.verify() exclusively — never manually compare JWT signatures.
// jsonwebtoken uses crypto.createVerify() internally which is timing-safe.
const jwt = require('jsonwebtoken');
function verifyJWT(token, publicKey) {
// FIX: jsonwebtoken.verify() performs all comparison internally using crypto APIs
// which are designed to be timing-safe for signature verification.
// Never extract the signature and compare it manually.
const payload = jwt.verify(token, publicKey, {
algorithms: ['RS256', 'ES256'], // explicit algorithm allowlist — never 'none'
audience: 'skillaudit.dev',
issuer: 'skillaudit.dev',
});
return payload;
}
// If you absolutely must compare a signature manually (e.g. implementing a custom JWT lib):
function timingSafeSignatureVerify(submittedSig, expectedSig) {
// FIX: Use crypto.timingSafeEqual() on equal-length Buffers
if (submittedSig.length !== expectedSig.length) return false;
return crypto.timingSafeEqual(submittedSig, expectedSig);
}
Algorithm confusion risk in legacy code: The manual JWT verification code in TIMING6-004 shows a subtle bug: it calls .sign() (which uses the private key to generate a new signature) instead of .verify() (which checks the submitted signature). This means the "comparison" is computing a fresh signature on each request, then comparing two server-generated signatures — the actual submitted signature is never checked. The endpoint accepts any JWT regardless of signature. Always use jsonwebtoken.verify() — it handles algorithm validation, timing-safe comparison, expiry, audience, and issuer in one call.
Summary — SA-SKL-TIMING6 at a glance
| Pattern | Root cause | Fix | Severity |
|---|---|---|---|
| TIMING6-001 | bcrypt skipped for unknown users — timing leaks account existence | Always run bcrypt with dummy hash for unknown users | HIGH |
| TIMING6-002 | API key string === short-circuits — leaks prefix characters | crypto.timingSafeEqual() for all key comparisons | HIGH |
| TIMING6-003 | Share token === comparison enables character-by-character brute-force | timingSafeEqual() + rate-limiting + longer tokens | CRITICAL |
| TIMING6-004 | Manual JWT signature comparison with === leaks signature bytes | jsonwebtoken.verify() exclusively — no manual comparison | HIGH |
SkillAudit's timing analysis probes all authentication endpoints with crafted requests designed to surface timing differences in secret comparison code. See also SA-SKL-TIMING5 (webhook API key timing) and SA-SKL-AUTH11 (OAuth PKCE bypass).