Claude skill timing side-channel attacks in MCP skill token and secret comparison — SA-SKL-TIMING2
Timing attacks exploit the fact that code paths that process correct secrets take measurably different time than paths that process incorrect ones. With enough requests and statistical averaging over network jitter, an attacker can recover secret values or enumerate valid users one byte at a time. SA-SKL-TIMING2 covers four timing vulnerabilities in MCP skill backends: string equality in API key verification, bcrypt format short-circuit, TOTP nonexistent-user skip, and database query response time as a data-existence oracle.
TIMING2-001 — token === req.headers['x-api-key']: variable-length comparison leaks key bits
JavaScript's === operator on strings terminates as soon as it finds the first character mismatch. This means that an API key comparison like storedKey === submittedKey takes longer when the first N characters match than when they differ at position 1 — the CPU does more work because it examines more bytes. For a 32-byte API key, an attacker who sends millions of requests and measures response time precisely can determine, byte-by-byte, the value of the stored key: first try all 256 values for byte 0, pick the one that takes longest, then fix byte 0 and iterate over byte 1, and so on. This requires overcoming network jitter through statistical averaging (typically thousands of requests per byte), but the attack is feasible against a local network or co-hosted adversary and has been demonstrated against HMAC verification in real-world systems. The fix is to use crypto.timingSafeEqual(), which is implemented in constant time regardless of the content of the buffers being compared. Because timingSafeEqual requires both buffers to be the same length, length must be checked separately — but the length check itself does not leak the value of the secret, only its length, which is typically not sensitive.
# VULNERABLE — TIMING2-001: string equality on API key — short-circuits on first mismatch
// API authentication middleware:
app.use('/api', (req, res, next) => {
const submitted = req.headers['x-api-key'];
const stored = process.env.API_KEY; // e.g. "sk-audit-abc123def456ghi789"
// VULNERABLE: === is variable-time — exits on first byte mismatch
// 'sk-audit-aXX...' takes longer than 'sk-XXXXXX...' (more matching bytes → more work)
if (submitted !== stored) {
return res.status(401).json({ error: 'Invalid API key' });
}
next();
});
# Timing oracle exploit (conceptual — requires co-location or low-jitter network):
# for each position i from 0 to key_length-1:
# for each character c in '0'-'9', 'a'-'f':
# prefix = known_prefix + c + 'A' * (key_length - i - 1)
# times = [measure_response_time(prefix) for _ in range(1000)]
# if median(times) > threshold:
# known_prefix += c # this character matched — comparison ran one byte further
# break
# After O(key_length * 16) requests, full key is recovered
# FIXED — TIMING2-001: crypto.timingSafeEqual with same-length padding
const { timingSafeEqual } = require('crypto');
app.use('/api', (req, res, next) => {
const submitted = req.headers['x-api-key'] || '';
const stored = process.env.API_KEY || '';
// timingSafeEqual requires Buffer arguments of the same length.
// Pad/truncate to stored length so comparison always takes the same time.
// Important: if lengths differ, we know the submitted key is wrong (length is not secret),
// but we still run timingSafeEqual on a fixed-length dummy to avoid a timing branch on length.
const storedBuf = Buffer.from(stored, 'utf8');
const submittedBuf = Buffer.alloc(storedBuf.length); // zero-padded to stored length
// Copy submitted bytes in, truncating if longer
Buffer.from(submitted, 'utf8').copy(submittedBuf, 0, 0, storedBuf.length);
// Always runs in constant time regardless of byte content
const keysMatch = timingSafeEqual(storedBuf, submittedBuf);
// Separately track length mismatch (not secret to know the key has wrong length)
const lengthMatch = submitted.length === stored.length;
if (!keysMatch || !lengthMatch) {
return res.status(401).json({ error: 'Invalid API key' });
}
next();
});
// For HMAC-based API key verification (recommended over raw comparison):
const { createHmac } = require('crypto');
function verifyHmacKey(submitted, stored) {
// Compare HMACs instead of raw values — attacker cannot control HMAC preimage
const hmacSubmitted = createHmac('sha256', process.env.HMAC_SECRET).update(submitted).digest();
const hmacStored = createHmac('sha256', process.env.HMAC_SECRET).update(stored).digest();
return timingSafeEqual(hmacSubmitted, hmacStored);
}
=== string equality operator leaks the number of matching leading bytes in the response time because V8 short-circuits the comparison on the first mismatch, enabling a byte-by-byte timing oracle that can recover the full stored key given sufficient requests; fix by replacing all secret comparisons with crypto.timingSafeEqual(Buffer.from(stored), paddedSubmittedBuffer) which runs in constant time regardless of byte content. Detection: SkillAudit flags === req.headers['x-api-key'], === token, or === secret patterns in Express middleware that handle authentication without a timingSafeEqual call.TIMING2-002 — bcrypt.compare() short-circuit on hash format mismatch
bcrypt's compare() function performs two things before the actual computation: it checks that the stored hash string begins with a valid bcrypt prefix ($2a$, $2b$, $2y$) and that the cost factor is a valid number. If the format check fails — because the stored value is not a bcrypt hash at all, perhaps because the user record was created before bcrypt was adopted, or the hash field is empty for a newly provisioned account — the function returns false immediately without running the bcrypt computation. The bcrypt computation is intentionally slow (200–1000ms at cost 10–12); the format rejection is instant. An attacker who measures response time for login attempts can distinguish between "user does not exist" (account lookup fails: <1ms), "user exists but no valid bcrypt hash" (format check fails: <1ms), and "user exists with valid bcrypt hash but wrong password" (full computation: 200+ms). This timing difference reliably enumerates which users have valid stored passwords regardless of whether the login endpoint returns identical error messages for all failure cases. The fix is to always run bcrypt.compare() against a valid sentinel hash when the user is not found or the stored hash is not a valid bcrypt string — discarding the result — to ensure all code paths take the same time.
# VULNERABLE — TIMING2-002: bcrypt.compare fast-paths on invalid hash format
const bcrypt = require('bcrypt');
app.post('/login', async (req, res) => {
const { email, password } = req.body;
const user = await db.query('SELECT * FROM users WHERE email = $1', [email]);
if (!user) {
// FAST PATH: <1ms — user not found, no bcrypt computation
return res.status(401).json({ error: 'Invalid credentials' });
}
if (!user.password_hash) {
// FAST PATH: <1ms — user exists but no password (OAuth-only account, etc.)
return res.status(401).json({ error: 'Invalid credentials' });
}
// SLOW PATH: 200-500ms — bcrypt computation (cost 10)
const valid = await bcrypt.compare(password, user.password_hash);
if (!valid) {
return res.status(401).json({ error: 'Invalid credentials' });
}
issueSession(res, user);
});
# Timing oracle:
# Request for nonexistent user: responds in ~2ms → user does not exist
# Request for existing OAuth user (no hash): ~2ms → user exists, no password
# Request for existing user with wrong password: ~350ms → user exists, has password
# Identical error messages — but timing reveals user enumeration information
# FIXED — TIMING2-002: sentinel hash ensures constant time regardless of user existence
const bcrypt = require('bcrypt');
// Sentinel hash — computed once at startup with a known dummy password
// This is a real bcrypt hash, so compare() always runs the full computation
const SENTINEL_HASH = await bcrypt.hash('sentinel-password-never-used', 10);
app.post('/login', async (req, res) => {
const { email, password } = req.body;
const user = await db.query('SELECT * FROM users WHERE email = $1', [email]);
// Always run bcrypt.compare() — against stored hash if user exists, sentinel if not.
// This ensures the response time is dominated by the bcrypt computation in ALL cases.
const hashToCheck = user?.password_hash || SENTINEL_HASH;
// Run comparison regardless of whether user exists
const valid = await bcrypt.compare(password, hashToCheck);
// Check both conditions after the constant-time comparison
if (!user || !user.password_hash || !valid) {
return res.status(401).json({ error: 'Invalid credentials' });
}
issueSession(res, user);
});
// Note: cost factor must match across real hashes and sentinel hash.
// If some users have cost=10 and others have cost=12, timing still differs by user.
// Standardize cost factor when re-hashing on next login:
async function rehashIfNeeded(user, password) {
const needsRehash = await bcrypt.getRounds(user.password_hash) !== TARGET_COST;
if (needsRehash) {
const newHash = await bcrypt.hash(password, TARGET_COST);
await db.query('UPDATE users SET password_hash=$1 WHERE id=$2', [newHash, user.id]);
}
}
bcrypt.compare() when a user is not found or has no stored hash return in under 1ms versus 200+ms for valid-hash comparisons, creating a user enumeration timing oracle even when all error responses are identical text; fix by always running bcrypt.compare(password, user?.password_hash || SENTINEL_HASH) with a sentinel hash pre-computed at startup, discarding the result if the user does not exist, so all code paths consume the same bcrypt computation time. Detection: SkillAudit flags login route handlers where bcrypt.compare is called inside a conditional block that is only reached when the user exists rather than unconditionally before all early-return branches.TIMING2-003 — TOTP verification skipped for nonexistent users creates user enumeration oracle
Time-based one-time password (TOTP) verification adds a second factor to login: after the password is verified, the user enters a 6-digit code that rotates every 30 seconds. Many implementations follow the pattern: look up the user, verify their password, then verify their TOTP code. If the user is not found or the password is wrong, the handler returns early without running verifyTOTP(). The TOTP library (otplib, speakeasy) must hash the secret with the current timestamp to generate the expected code — this takes a measurable amount of CPU time (typically 1–5ms, much less than bcrypt but nonzero). An attacker who sends requests with correct username format but wrong passwords can measure response time to distinguish "user does not exist" (skips TOTP: <0.5ms after DB query) from "user exists but wrong password" (also skips TOTP in this code path, same <0.5ms, BUT may differ based on DB index hit). More critically, if TOTP is verified in a second request and the first request does a user-exists check with TOTP skip, response timing on the second factor step leaks whether a user enumeration is in progress. The fix is to always run TOTP verification with a dummy secret on the nonexistent-user path and discard the result, matching the timing of real TOTP verification.
# VULNERABLE — TIMING2-003: TOTP skip for nonexistent users creates timing difference
const { TOTP } = require('otplib');
app.post('/login/verify-otp', async (req, res) => {
const { email, otp } = req.body;
const user = await db.query('SELECT * FROM users WHERE email = $1', [email]);
if (!user) {
// FAST: returns without running TOTP verification (~1ms)
return res.status(401).json({ error: 'Invalid credentials' });
}
// SLOW: runs TOTP verify (~3-5ms for HMAC computation)
const isValid = TOTP.verify({ token: otp, secret: user.totp_secret });
if (!isValid) {
return res.status(401).json({ error: 'Invalid credentials' });
}
issueSession(res, user);
});
# Timing oracle:
# email=nonexistent@test.com, otp=123456 → ~1ms → user does not exist
# email=real@user.com, otp=123456 → ~4ms → user exists (wrong OTP)
# Attacker enumerates registered emails by timing this endpoint
# FIXED — TIMING2-003: always run TOTP verify with dummy secret on nonexistent user
const { TOTP } = require('otplib');
const { randomBytes } = require('crypto');
// Dummy TOTP secret — never registered to any user
// Pre-encode to base32 (otplib requires base32 secrets)
const DUMMY_TOTP_SECRET = randomBytes(20).toString('hex').toUpperCase().slice(0, 32);
app.post('/login/verify-otp', async (req, res) => {
const { email, otp } = req.body;
const user = await db.query('SELECT * FROM users WHERE email = $1', [email]);
// Always run TOTP verification — against real secret or dummy secret
const secret = user?.totp_secret || DUMMY_TOTP_SECRET;
const isValid = TOTP.verify({ token: otp, secret });
// After constant-time TOTP: check user existence and code validity together
if (!user || !isValid) {
return res.status(401).json({ error: 'Invalid credentials' });
}
issueSession(res, user);
});
// Additional timing hardening: add jitter to ALL responses regardless of code path
// to prevent statistical averaging attacks even with the sentinel pattern:
app.post('/login/verify-otp', async (req, res) => {
const start = Date.now();
// ... authentication logic ...
// Ensure minimum response time of 100ms regardless of path
const elapsed = Date.now() - start;
const minDelay = 100;
if (elapsed < minDelay) {
await new Promise(resolve => setTimeout(resolve, minDelay - elapsed));
}
res.status(401).json({ error: 'Invalid credentials' });
});
verifyTOTP() when the user is not found return measurably faster than when a valid user's TOTP is checked, creating a user enumeration timing oracle even when all error responses are identical text; fix by always running TOTP verification against user?.totp_secret || DUMMY_TOTP_SECRET and discarding the result when the user does not exist, optionally adding a minimum-response-time floor to absorb statistical timing attacks across all code paths. Detection: SkillAudit flags TOTP verification calls inside if (user) blocks rather than unconditionally before all early-return branches in login route handlers.TIMING2-004 — Search endpoint indexed vs. full-scan timing difference: data existence oracle
When a search or lookup endpoint queries a database, the response time depends on whether the queried value exists: an indexed lookup for a present record returns immediately (the B-tree finds the entry), while a lookup for an absent record performs a full index scan to confirm absence — which takes longer when the index is large. This response-time difference — typically 5–50ms on a loaded database with millions of rows — allows an attacker to determine whether a record exists without being authorized to read its content. For MCP skill platforms that support searching for user accounts by email, skill names by identifier, or audit reports by hash, an attacker who repeatedly queries for target values and measures response times can build a data-existence oracle: quickly confirm whether a target email is registered, whether a private audit report exists, or whether a competitor's skill ID is in the system. The fix is two-pronged: add artificial random jitter to all search responses so timing is non-deterministic, and return the same response format for found and not-found results (never a 404 for one and 200 with empty results for the other — both should be 200 with consistent structure).
# VULNERABLE — TIMING2-004: search response time exposes data existence via index timing
// User search endpoint:
app.get('/api/check-email', async (req, res) => {
const { email } = req.query;
// Indexed query — response time differs for found vs not-found:
// Found: ~2ms (B-tree lookup, returns on first leaf node match)
// Not found: ~15ms (B-tree traversal to confirm absence, varies with index size)
const user = await db.query(
'SELECT id, email FROM users WHERE email = $1',
[email.toLowerCase()]
);
if (!user.rows.length) {
// 404 response AND fast timing (or slow timing) — both leak existence
return res.status(404).json({ error: 'Not found' });
}
res.json({ exists: true, userId: user.rows[0].id });
});
# Timing oracle (against an indexed 1M-row users table):
# email=registered@user.com → 200 OK, 2ms → user exists (and reveals userId)
# email=unknown@attacker.com → 404, 18ms → user does not exist
# Even if both returned identical 404s, timing still leaks existence
# Attacker confirms targets' email registrations without authentication
# FIXED — TIMING2-004: uniform response format + random jitter on all search responses
const { randomInt } = require('crypto');
// Helper: add non-deterministic jitter to all responses
async function withJitter(minMs, maxMs, fn) {
const jitter = randomInt(minMs, maxMs);
const [result] = await Promise.all([
fn(),
new Promise(resolve => setTimeout(resolve, jitter))
]);
return result;
}
app.get('/api/check-email', async (req, res) => {
const { email } = req.query;
// Add 10-30ms random jitter to ALL responses — absorbs index timing differences
const user = await withJitter(10, 30, () =>
db.query('SELECT id FROM users WHERE email = $1', [email.toLowerCase()])
);
// Uniform response format — same HTTP status and structure for found AND not-found
// Never return 404 for "not found" if 200 is returned for "found" on same endpoint
res.json({
// Avoid leaking userId to unauthenticated callers — just a boolean
registered: user.rows.length > 0
// If this endpoint should not exist at all for unauthenticated users,
// require authentication before even running the query
});
});
// Better: require authentication on all lookup endpoints
// Timing attacks are only useful if the endpoint is accessible to the attacker
app.get('/api/check-email', requireAuth, async (req, res) => {
// Authenticated users searching within their own org — timing still leaks, so jitter still needed
// but the attack surface is reduced to authenticated insiders vs. external attackers
});
// For public registration flows where email existence is intentionally exposed:
// Add rate limiting AND jitter to prevent statistical averaging:
// - 1 request per second per IP via express-rate-limit
// - 10-50ms random delay per response
// Together these make the oracle impractical without millions of requests over hours
crypto.randomInt(10, 30) milliseconds of jitter to all search responses regardless of result, returning the same HTTP status and response structure for found and not-found results, and gating sensitive lookups behind authentication. Detection: SkillAudit flags search and lookup endpoints that return different HTTP status codes (200 vs. 404) for found vs. not-found results without a jitter mechanism on routes accessible to unauthenticated callers.Detection summary
| ID | Severity | Pattern | Fix |
|---|---|---|---|
| TIMING2-001 | HIGH | token === req.headers['x-api-key'] — V8 short-circuit on first mismatch leaks key bits through response time |
crypto.timingSafeEqual(storedBuf, paddedSubmittedBuf) — constant time regardless of content |
| TIMING2-002 | HIGH | bcrypt.compare() returns <1ms on hash format mismatch vs. 200+ms on full computation — leaks user existence |
Always compare against user?.password_hash || SENTINEL_HASH; run full bcrypt computation unconditionally |
| TIMING2-003 | MEDIUM | TOTP skip for nonexistent users — 1ms vs. 4ms reveals whether email is registered | Always run TOTP.verify(otp, user?.totp_secret || DUMMY_SECRET); optionally add response-time floor |
| TIMING2-004 | MEDIUM | Search indexed column — B-tree returns in ~2ms for hits vs. ~15ms for misses; data existence oracle | crypto.randomInt(10, 30) ms jitter on all responses; uniform HTTP status for found/not-found; require auth |
Related patterns: SA-SKL-RATELIMIT5 covers rate limiting strategies that complement timing attack mitigations — burst detection, per-IP sliding windows, and account lockout policies that make statistical timing oracle attacks impractical even when jitter is not sufficient. MCP server authentication security covers the full authentication hardening checklist including constant-time token verification, secure session management, and credential storage for MCP skill backends.