Claude skill timing attack security
Timing side-channel attacks exploit the fact that most comparison operations terminate as soon as they find a mismatch — returning faster for incorrect inputs than for nearly-correct ones. An attacker who can call a skill’s authentication or validation endpoint thousands of times and measure response times can recover secret values byte by byte, determine whether user accounts exist, and deduce API key prefixes — all without triggering authentication failures. SA-SKL-TIMER covers four timing side-channel vulnerabilities that are specific to MCP skill authentication patterns, where the high concurrency and programmatic nature of skill callers makes automated timing attacks more practical than against human-facing web apps.
Timing attacks are frequently dismissed as impractical — network jitter supposedly drowns the signal. That assumption breaks down in MCP skill deployments: skills run on predictable cloud infrastructure, skill callers are automated programs that issue thousands of requests per minute with no human rate-limiting, and the response latency baseline for a co-located attacker on the same container network can be under 500 microseconds. At that baseline, a 300-nanosecond signal from a byte mismatch becomes statistically separable after a few hundred measurements. The four SA-SKL-TIMER patterns cover the most common places where timing leaks appear in MCP skill authentication code: direct string comparisons of secrets, early exit before bcrypt for nonexistent users, segment-by-segment API key comparison loops, and cache hit/miss timing differences on user record lookups.
SA-SKL-TIMER-001: Password and secret comparison with string equality — timing oracle recovers key byte by byte
JavaScript’s === operator and string comparison methods exit on the first mismatched character. For a 32-character API key, a comparison that fails on byte 0 returns approximately 31 character-comparisons faster than a comparison that fails on byte 31. An attacker who controls the input and can measure response time iterates through all 256 possible first-byte values, identifies the one that consistently takes ~300ns longer than the others (because the comparison moved to byte 1), then fixes that byte and repeats for byte 1 — recovering the full key in roughly 32 × 256 = 8,192 requests. At 1,000 requests per second this takes under nine seconds of wall time:
// VULNERABLE: string equality exits on first mismatched byte
import crypto from 'crypto';
function validateApiKey(incoming: string): boolean {
const stored = process.env.ADMIN_API_KEY!;
return incoming === stored; // <-- timing oracle: returns faster when byte 0 mismatches
}
// Also vulnerable: naive hash comparison with ===
async function validatePassword(password: string, storedHash: string): Promise<boolean> {
const computedHash = crypto.createHash('sha256').update(password).digest('hex');
return computedHash === storedHash; // <-- timing oracle on the hex-string comparison
}
// ATTACK: byte-by-byte key recovery
// Target: 32-character hex API key, e.g. "a3f8c2d1e9b04756..."
// Round 1 — recover byte 0:
// Send "a0000000000000000000000000000000" → measure response time T_a
// Send "b0000000000000000000000000000000" → measure response time T_b
// ...
// Send "a0000..." returns consistently T_a ≈ baseline + 0.3μs (compared two bytes)
// All others return T ≈ baseline (compared one byte then returned false)
// → byte 0 is 'a'
//
// Round 2 — recover byte 1 (fix byte 0 = 'a'):
// Send "a0000000000000000000000000000000"
// Send "a1000000000000000000000000000000"
// Send "a2000000000000000000000000000000" ... → find longest: 'a3...'
// → byte 1 is '3'
//
// At 1000 req/sec: 32 rounds × 256 probes = 8192 requests ≈ 8 seconds
// In practice: use median of 20 samples per probe for statistical confidence
// Network jitter: use same-DC or same-VPC attacker; median eliminates outliers
// SECURE: crypto.timingSafeEqual — constant time regardless of which byte mismatches
function validateApiKeySecure(incoming: string): boolean {
const stored = process.env.ADMIN_API_KEY!;
// Both values must be the same byte length for timingSafeEqual
// If lengths differ, fail before the comparison (but don't leak timing on length)
const a = Buffer.from(incoming, 'utf8');
const b = Buffer.from(stored, 'utf8');
if (a.length !== b.length) {
// Run a dummy comparison to avoid leaking length information via timing
crypto.timingSafeEqual(b, b);
return false;
}
return crypto.timingSafeEqual(a, b);
}
// SECURE: for hash comparisons, hash both values to fixed-length outputs first
async function validatePasswordSecure(password: string, storedHash: string): Promise<boolean> {
// Hash the incoming password
const computedHash = crypto.createHash('sha256').update(password).digest();
const expectedHash = Buffer.from(storedHash, 'hex');
// Both are 32 bytes (SHA-256) — timingSafeEqual is now constant-time
if (computedHash.length !== expectedHash.length) return false;
return crypto.timingSafeEqual(computedHash, expectedHash);
// NOTE: for passwords, prefer bcrypt/scrypt/argon2 over SHA-256
// SHA-256 is fast and therefore brute-forceable; shown here for hash equality pattern
}
The length check before timingSafeEqual must not leak timing information itself: If your code returns immediately when a.length !== b.length, you have inadvertently created a timing oracle on the key length. Run a dummy crypto.timingSafeEqual(b, b) before returning false to burn the same time the real comparison would take, or normalize all keys to a fixed length by hashing them to a uniform output size (e.g. HMAC-SHA256) before comparing.
===) used to compare API keys, tokens, or hash digests: early-exit byte comparison leaks secret value byte by byte via response time; full 32-byte key recoverable in ~8,192 requests at 1,000 req/sec. Fix: crypto.timingSafeEqual(Buffer.from(a), Buffer.from(b)); normalize lengths before comparison; run dummy comparison to avoid leaking length. Detection: === process.env. or === storedHash patterns in authentication paths → HIGH.SA-SKL-TIMER-002: User enumeration via bcrypt timing difference — account existence revealed in 1ms vs 100ms
bcrypt is intentionally slow — a cost-12 hash takes approximately 100ms to compute. This is the correct defense against offline brute-force attacks on a compromised password database. However, the same slowness creates a timing oracle when an authentication function short-circuits for nonexistent users: an existing user triggers await bcrypt.compare() and returns in ~100ms; a nonexistent user hits a throw new Error('User not found') and returns in under 1ms. An attacker who measures this 99ms difference can enumerate which email addresses have accounts in the system, then target only confirmed accounts with password spray or credential-stuffing attacks:
// VULNERABLE: early exit for nonexistent user leaks account existence via timing
import bcrypt from 'bcrypt';
import { db } from './db.js';
async function authenticate(email: string, password: string): Promise<User> {
const userRow = await db.query('SELECT * FROM users WHERE email = $1', [email]);
if (!userRow) {
throw new AuthError('Invalid email or password'); // <-- returns in <1ms
}
const match = await bcrypt.compare(password, userRow.hashedPassword); // ~100ms
if (!match) {
throw new AuthError('Invalid email or password');
}
return userRow;
}
// ATTACK: account enumeration via bcrypt timing
// Attacker has a leaked email list of 10,000 addresses from a data breach
// For each email: measure login response time
// <5ms → no account exists (skipped bcrypt) → discard
// ~100ms → account exists (bcrypt ran) → add to confirmed list
//
// At 100ms per bcrypt + network latency ≈ 150ms per probe:
// 10,000 addresses / 1000 concurrent = ~10 seconds wall time
// Result: a list of confirmed account holders ready for credential stuffing
// Attacker then uses confirmed list + leaked passwords from other breaches
// No authentication failures on the enumeration phase → no lockout triggered
// SECURE: always run bcrypt.compare even for nonexistent users
// Use a dummy hash that is structurally valid but will never match
const DUMMY_HASH = '$2b$12$invalidhashxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
async function authenticateSecure(email: string, password: string): Promise<User> {
const userRow = await db.query('SELECT * FROM users WHERE email = $1', [email]);
// Always run bcrypt.compare so both paths take ~100ms
const hashToCompare = userRow?.hashedPassword ?? DUMMY_HASH;
const match = await bcrypt.compare(password, hashToCompare);
// Check user existence AFTER bcrypt, not before
if (!userRow || !match) {
throw new AuthError('Invalid email or password');
}
return userRow;
}
// IMPORTANT: the DUMMY_HASH must be a valid bcrypt hash string
// '$2b$12$invalidhash...' satisfies the format and will consistently return false
// Do NOT use an empty string — bcrypt.compare('', '') returns true for some versions
// Do NOT use a hash of an empty string — could match an empty-string password
// Generate a one-time dummy at startup if preferred:
const STARTUP_DUMMY_HASH = await bcrypt.hash(crypto.randomUUID(), 12);
// This is bcrypt'd with the same cost factor as your real hashes → identical timing
The dummy hash cost factor must match your real hashes: If your real passwords are stored with bcrypt.hash(password, 12) (cost 12) but your dummy hash was generated with cost 10, the timing difference between existing-user (cost 12, ~100ms) and nonexistent-user (cost 10, ~40ms) is still exploitable. Generate the dummy hash at application startup using await bcrypt.hash(crypto.randomUUID(), BCRYPT_COST_FACTOR) with the same cost constant used for real password hashes, and store it in a module-level variable.
bcrypt.compare() for nonexistent users: <1ms vs ~100ms response time reveals account existence; attacker enumerates confirmed accounts from leaked email lists in seconds without triggering lockouts. Fix: always run bcrypt.compare(password, userRow?.hashedPassword ?? DUMMY_HASH); check user existence after bcrypt; use same-cost dummy hash. Detection: if (!userRow) or if (!user) throw before bcrypt.compare in authentication path → HIGH.SA-SKL-TIMER-003: API key prefix disclosure via early-exit segment comparison — key structure leaked byte by byte
Many MCP skills use structured API keys with human-readable prefixes (e.g. sk_live_<segment1>_<segment2>) to aid debugging and log filtering. When these keys are validated with a character-by-character loop that exits early on mismatch, or compared with === after a startsWith() prefix check, the fixed prefix structure becomes a timing oracle even if the secret segments are properly random. An attacker can first confirm the prefix format, then recover each random segment using the same byte-by-byte technique as TIMER-001, except that the structured format reduces the search space significantly by allowing segment-by-segment recovery:
// VULNERABLE: early-exit character loop leaks correct prefix position
function validateApiKey(incoming: string): boolean {
const expected = process.env.API_KEY!; // e.g. "sk_live_a3f8c2d1_9b04756e"
if (incoming.length !== expected.length) return false;
for (let i = 0; i < expected.length; i++) {
if (incoming[i] !== expected[i]) return false; // <-- exits at first mismatch
}
return true;
}
// ALSO VULNERABLE: startsWith check before constant-time comparison
// The startsWith short-circuit confirms prefix structure via timing
function validateApiKeyV2(incoming: string): boolean {
const expected = process.env.API_KEY!;
// "optimization": reject obviously wrong keys early
if (!incoming.startsWith('sk_live_')) return false; // <-- leaks prefix presence
return incoming === expected; // then leaks byte-by-byte from position 8
}
// ALSO VULNERABLE: segment-by-segment comparison for structured keys
function validateStructuredKey(incoming: string): boolean {
const [inPrefix, inEnv, inSeg1, inSeg2] = incoming.split('_');
const [exPrefix, exEnv, exSeg1, exSeg2] = process.env.API_KEY!.split('_');
// Each === is an independent timing oracle on its segment
return inPrefix === exPrefix &&
inEnv === exEnv &&
inSeg1 === exSeg1 &&
inSeg2 === exSeg2;
}
// ATTACK: segment-aware prefix recovery
// Key format: sk_live_AAAAAAAA_BBBBBBBB (8+8 random hex chars per segment)
// Step 1: confirm prefix 'sk_live_' — anything else returns in <1μs (startsWith fast path)
// 'sk_live_' returns slightly longer → prefix confirmed
// Step 2: recover segment 1 'AAAAAAAA' byte by byte (8 × 16 = 128 probes hex charset)
// total: 128 probes × 20 samples = 2560 requests
// Step 3: recover segment 2 'BBBBBBBB' byte by byte (another 128 probes)
// total: 2560 + 2560 = 5120 requests
// Full key recovered in ~5120 requests vs 8192 for unstructured — prefix leaks help attacker
// SECURE: HMAC both keys and compare the HMACs with timingSafeEqual
// HMAC output is fixed length (32 bytes for SHA-256) and structurally opaque
import crypto from 'crypto';
const HMAC_SECRET = process.env.KEY_COMPARISON_SECRET!; // separate pepper, not the API key itself
function hmacKey(key: string): Buffer {
return crypto.createHmac('sha256', HMAC_SECRET).update(key).digest();
}
function validateApiKeySecure(incoming: string): boolean {
const expected = process.env.API_KEY!;
const hmacIncoming = hmacKey(incoming);
const hmacExpected = hmacKey(expected);
// Both are 32 bytes; timingSafeEqual is constant-time on 32 bytes regardless of key structure
return crypto.timingSafeEqual(hmacIncoming, hmacExpected);
}
// WHY HMAC AND NOT HASH?
// If you hash both keys with SHA-256 and compare the hashes:
// hash(incoming) === hash(expected) — still uses ===, still timing oracle on the hash strings
// HMAC(key, pepper) + timingSafeEqual(hmacA, hmacB) is correct because:
// - pepper prevents hash precomputation attacks on stored key material
// - timingSafeEqual on 32-byte Buffers is guaranteed constant time in Node.js ≥10
// - key structure (segments, prefix) is completely hidden in the HMAC output
Store only the HMAC of API keys, not the keys themselves: If your database stores hmac(apiKey, pepper) rather than the raw key, you eliminate both the timing oracle and the risk of raw key disclosure from a database breach. When a client presents a key, compute its HMAC and do a constant-time comparison against the stored HMAC. The pepper (stored in an environment variable or secrets manager) means that even a full database dump does not give the attacker the raw API keys.
=== comparison on structured API keys: prefix format confirmed and each segment recovered byte by byte; structured keys recoverable in fewer probes than unstructured. Fix: crypto.timingSafeEqual(hmacKey(incoming), hmacKey(expected)); store only HMAC of keys; never use startsWith() as an optimization before constant-time comparison. Detection: for loop character comparison or split('_') segment comparison in key validation path → HIGH.SA-SKL-TIMER-004: Cache timing oracle — cache membership leaks user existence before password check
Many MCP skill authentication flows cache user records in an in-memory LRU cache or Redis to reduce database load. A cache hit returns in under 0.1ms; a cache miss triggers a database query that takes 20–80ms. This timing difference exists independently of password validation and independently of whether the user’s account is active. An attacker can probe account existence by measuring total authentication endpoint response time before any password logic runs: a cache-hit response (user exists and was recently active) takes noticeably less time than a cache-miss response (user does not exist or has never authenticated). Rate limiters, session stores, and Redis key lookups exhibit the same pattern for any identifier-keyed store:
// VULNERABLE: cache hit/miss timing reveals account existence before password check
import { LRUCache } from 'lru-cache';
import { db } from './db.js';
import bcrypt from 'bcrypt';
const userCache = new LRUCache<string, User>({ max: 1000, ttl: 5 * 60 * 1000 });
async function authenticate(email: string, password: string): Promise<User> {
// Cache hit: <0.1ms — signals "this user exists and was recently active"
// Cache miss: 20–80ms DB round-trip — signals "user does not exist or is cold"
const cached = userCache.get(email);
const userRow = cached ?? await db.query('SELECT * FROM users WHERE email = $1', [email]);
if (!userRow) {
throw new AuthError('Invalid email or password'); // 20–80ms total (cache miss + early exit)
}
if (cached) userCache.set(email, userRow);
const match = await bcrypt.compare(password, userRow.hashedPassword); // +~100ms
if (!match) throw new AuthError('Invalid email or password');
return userRow;
}
// ATTACK: cache membership enumeration
// Phase 1: attacker times login for target email WITHOUT trying password spray
// Response ~0.5ms → cache hit → user exists AND was active recently
// Response ~25ms → cache miss + DB hit → user exists but cold
// Response ~25ms + early exit (no bcrypt) → user does not exist
//
// Phase 1 is noisier (cache-miss-but-exists vs no-exists are both ~25ms)
// but Phase 2 (after one successful auth warms the cache) gives clean 0.1ms vs 25ms signal
//
// ALSO VULNERABLE: Redis rate-limiter counter lookup
// if (await redis.get(`ratelimit:${email}`) !== null) { ... }
// Key-exists check: ~0.5ms (key present — user has made recent requests)
// Key-absent check: ~0.5ms BUT pipeline ordering differences leakable at μs scale
//
// ALSO VULNERABLE: session store lookup
// const session = await sessionStore.get(sessionId);
// Existing session: fast in-memory path; expired/missing: slower cleanup path
// SECURE OPTION 1: constant-time floor on all authentication responses
async function authenticateSecure(email: string, password: string): Promise<User> {
const startTime = Date.now();
const MIN_RESPONSE_MS = 150; // > max(bcrypt_time) + max(db_time)
const userRow = await db.query('SELECT * FROM users WHERE email = $1', [email]);
const hashToCompare = userRow?.hashedPassword ?? '$2b$12$invalidhashxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
const match = await bcrypt.compare(password, hashToCompare);
// Pad response to MIN_RESPONSE_MS before returning — masks all timing variation
const elapsed = Date.now() - startTime;
if (elapsed < MIN_RESPONSE_MS) {
await new Promise(r => setTimeout(r, MIN_RESPONSE_MS - elapsed));
}
if (!userRow || !match) throw new AuthError('Invalid email or password');
return userRow;
}
// SECURE OPTION 2: hash userId with a pepper before cache lookup
// Prevents enumeration even if attacker can observe cache metrics externally
const CACHE_PEPPER = process.env.CACHE_LOOKUP_PEPPER!;
function cacheKey(email: string): string {
return crypto.createHmac('sha256', CACHE_PEPPER).update(email).digest('hex');
}
// Cache keyed by HMAC(email, pepper) — attacker cannot probe cache for a known email
// because they cannot compute the cache key without the pepper
const securCache = new LRUCache<string, User>({ max: 1000, ttl: 5 * 60 * 1000 });
async function authenticateSecureV2(email: string, password: string): Promise<User> {
const key = cacheKey(email);
const cached = securCache.get(key);
const userRow = cached ?? await db.query('SELECT * FROM users WHERE email = $1', [email]);
if (userRow && !cached) securCache.set(key, userRow);
const hashToCompare = userRow?.hashedPassword ?? '$2b$12$invalidhashxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
const match = await bcrypt.compare(password, hashToCompare);
if (!userRow || !match) throw new AuthError('Invalid email or password');
return userRow;
}
The minimum response time floor must be calibrated above the worst-case legitimate response time: If MIN_RESPONSE_MS is set to 150ms but bcrypt occasionally takes 180ms on a loaded server, the floor becomes ineffective for those requests (they return in exactly 180ms, still within normal variance). Measure the 99th-percentile bcrypt + DB time in production and set the floor to 120% of that value. Monitor it as a dashboarded metric and adjust as the server load profile changes. The floor should be treated as a security invariant, not a performance tuning parameter.
cache.get(email) or cache.get(userId) before authentication completion in login handler → MEDIUM.Remediation summary
| Finding | Severity | Vulnerable pattern | Fix | Detection signal for SkillAudit |
|---|---|---|---|---|
| TIMER-001: String equality timing oracle | HIGH | incoming === storedSecret or hashA === hashB in auth path |
crypto.timingSafeEqual(Buffer.from(a), Buffer.from(b)); normalize lengths first |
=== process.env. or === storedHash in authentication or key validation functions |
| TIMER-002: User enumeration via bcrypt skip | HIGH | if (!userRow) throw before await bcrypt.compare() |
Always run bcrypt.compare(password, userRow?.hash ?? DUMMY_HASH); check existence after bcrypt |
Early throw or return before bcrypt.compare in login handler |
| TIMER-003: API key prefix disclosure | HIGH | Character loop with early exit or startsWith() before === comparison |
crypto.timingSafeEqual(hmacKey(incoming), hmacKey(expected)); store only HMAC of keys |
for loop character comparison or split('_') segment === in key validation |
| TIMER-004: Cache membership timing oracle | MEDIUM | cache.get(email) before auth completion leaks account existence via hit/miss timing |
Constant-time response floor above 99th-pct bcrypt+DB time; or pepper cache keys with HMAC | cache.get(email) or cache.get(userId) in authentication path before final response |
SkillAudit detects all four SA-SKL-TIMER-001 through TIMER-004 patterns through static analysis of skill authentication code: === comparisons of environment variable secrets or hash digests, early exits before bcrypt.compare(), character-loop or segment-split key comparisons, and cache lookups in authentication paths that precede the final response. For related security patterns see SA-SKL-SESS session management security, SA-SKL-AUT authentication security, and SA-SKL-LOG logging security. See the complete SA-SKL attack surface reference for the full vulnerability taxonomy.
Scan your Claude skill for timing side-channel vulnerabilities
SkillAudit detects string equality timing oracles, bcrypt skip enumeration, early-exit key comparisons, and cache membership timing leaks across the full SA-SKL-TIMER family in 60 seconds.
Get your free audit