Claude MCP skill timing attacks on secret comparison in CI webhook and API key verification — SA-SKL-TIMING5
Timing attacks exploit the fact that JavaScript's === operator compares strings character-by-character and returns false at the first mismatch — meaning a string that shares a longer common prefix with the correct value takes slightly longer to reject than one that differs at the first character. In a high-throughput MCP skill CI webhook or API key verification endpoint, an attacker who can send thousands of requests and measure response times can statistically recover secrets one character at a time. This is not a theoretical attack — documented exploits have recovered HMAC webhook secrets in under an hour against production endpoints with sub-millisecond timing resolution via HTTP/2. SA-SKL-TIMING5 covers four timing attack surfaces in MCP skill secret comparison code: webhook HMAC signatures, API key suffix comparison, TOTP codes, and password reset tokens.
computedSignature === req.headers['x-hub-signature-256']; === short-circuits on first character mismatch; timing oracle allows attacker to recover the full HMAC signature byte-by-byte over many requests, then forge valid webhook payloadssk_live_AAAA... — first 12 chars identify the account) followed by === comparison on the remaining suffix; suffix comparison is timing-vulnerable; attacker who knows a valid prefix can recover the suffix byte-by-byte without brute-forcing the full key spaceparseInt(userCode) === parseInt(storedCode); integer comparison short-circuits digit by digit in the string representation; timing leak reveals correct leading digits; combined with TOTP's 30-second window, reduces brute-force from 1,000,000 to ~60 attemptsreq.body.token === storedToken in Express middleware; timing oracle allows attacker to enumerate valid reset tokens for any user account without triggering account lockout (no failed-login counter incremented for token comparisons)TIMING5-001 — Webhook HMAC signature verified with === string comparison
The GitHub Actions CI webhook and similar MCP skill CI integrations use HMAC-SHA256 signatures to authenticate inbound webhook payloads. The server computes an expected HMAC over the raw request body using the shared webhook secret, then compares it with the X-Hub-Signature-256 header sent by the caller. When this comparison uses JavaScript's === operator, the comparison exits as soon as it finds the first differing character. An attacker who can observe response times (or connection timing in HTTP/2 multiplexed connections) can send many crafted signatures that share an increasing-length prefix with the expected value and use the timing delta to identify when each additional prefix character is correct. The fix is a constant-time comparison that always examines every byte regardless of where the mismatch occurs.
// VULNERABLE — TIMING5-001
// Webhook HMAC-SHA256 verified with === — timing-vulnerable comparison.
// Attacker sends 10,000 signatures starting with 'a', 'b', ..., 'f' for first byte.
// The correct first byte takes microseconds longer — statistical timing reveals it.
// Repeat for each of 64 hex characters in the signature.
import crypto from 'crypto';
app.post('/webhook/ci', express.raw({ type: '*/*' }), (req, res) => {
const secret = process.env.WEBHOOK_SECRET;
const payload = req.body;
const signature = req.headers['x-hub-signature-256'];
const expectedHmac = crypto
.createHmac('sha256', secret)
.update(payload)
.digest('hex');
const expected = `sha256=${expectedHmac}`;
// VULNERABLE: === exits on first mismatch — timing leak reveals correct prefix
if (signature !== expected) {
return res.status(401).json({ error: 'Invalid signature' });
}
processWebhook(req.body);
res.status(200).send('OK');
});
// FIXED — TIMING5-001
// Fix 1: crypto.timingSafeEqual() on Buffer representations — constant time regardless of match position.
// Fix 2: Check length equality first (also constant-time concern for padding attacks).
// Fix 3: Use raw request body (express.raw) — do not parse; signature covers unparsed bytes.
import crypto from 'crypto';
app.post('/webhook/ci', express.raw({ type: '*/*' }), (req, res) => {
const secret = process.env.WEBHOOK_SECRET;
const payload = req.body; // Buffer — express.raw gives unparsed bytes
const signature = req.headers['x-hub-signature-256'];
if (!signature) return res.status(401).json({ error: 'Missing signature' });
const expectedHmac = crypto
.createHmac('sha256', secret)
.update(payload)
.digest('hex');
const expected = `sha256=${expectedHmac}`;
// FIX 1: timingSafeEqual — always compares every byte, no early exit
const sigBuf = Buffer.from(signature);
const expBuf = Buffer.from(expected);
// FIX 2: Length check must also be constant-time — different-length strings differ in timing
if (sigBuf.length !== expBuf.length ||
!crypto.timingSafeEqual(sigBuf, expBuf)) {
return res.status(401).json({ error: 'Invalid signature' });
}
processWebhook(payload);
res.status(200).send('OK');
});
Detection: SkillAudit scans for HMAC computation calls (crypto.createHmac().digest()) followed by ===, !==, or .includes() comparison rather than crypto.timingSafeEqual(). It flags all secret comparison paths where non-constant-time operators are used.
TIMING5-002 — API key suffix compared with === after prefix-based account lookup
Many API key schemes split the key into a public prefix (used to look up the account) and a private suffix (the actual secret, verified against a stored hash). When the suffix verification is done by comparing the hash of the submitted suffix against the stored hash using ===, the comparison is timing-vulnerable at the hash string level. If the stored hash is a plain SHA-256 hex string (not a password-hashing algorithm like bcrypt), and both the submitted and stored hashes are equal-length hex strings, an attacker can send many API keys with the same account prefix but different suffixes and measure whether the hex hashes share a longer common prefix — revealing one hex character of the hash per timing round. This is an amplified attack because the attacker only needs to crack the hash of the suffix rather than the suffix itself.
// VULNERABLE — TIMING5-002
// API key: "sk_live_" + accountPrefix (12 chars) + secret (32 chars)
// Account looked up by prefix; secret suffix hashed and compared with ===.
// Timing leak on hash comparison reveals hash bytes; combined with suffix entropy, exploitable.
import crypto from 'crypto';
import db from './db.js';
async function verifyApiKey(apiKey) {
if (!apiKey.startsWith('sk_live_')) return null;
const prefix = apiKey.slice(8, 20); // 12-char account identifier
const suffix = apiKey.slice(20); // 32-char secret
const account = await db.accounts.findByKeyPrefix(prefix);
if (!account) return null;
const submittedHash = crypto.createHash('sha256').update(suffix).digest('hex');
// VULNERABLE: === on two 64-char hex strings — timing-vulnerable comparison
if (submittedHash !== account.apiKeyHash) {
return null;
}
return account;
}
// FIXED — TIMING5-002
// Fix 1: timingSafeEqual() on Buffer(submittedHash) vs Buffer(storedHash).
// Fix 2: Store the full key hash (prefix + suffix), look up by account ID not by prefix in key.
// Fix 3: Use HMAC rather than plain SHA-256 for key hashing — prevents hash precomputation attacks.
import crypto from 'crypto';
import db from './db.js';
const KEY_HASH_SECRET = process.env.API_KEY_HASH_SECRET; // server-side HMAC secret for key hashing
async function verifyApiKey(apiKey) {
if (!apiKey.startsWith('sk_live_')) return null;
const prefix = apiKey.slice(8, 20);
const suffix = apiKey.slice(20);
const account = await db.accounts.findByKeyPrefix(prefix);
if (!account) return null;
// FIX 3: HMAC of full suffix — keyed hash prevents precomputation
const submittedHash = crypto
.createHmac('sha256', KEY_HASH_SECRET)
.update(suffix)
.digest(); // Buffer, not hex string
// FIX 1: timingSafeEqual on Buffer — constant-time regardless of which byte mismatches
const storedHashBuf = Buffer.from(account.apiKeyHash, 'hex'); // 32-byte Buffer
if (submittedHash.length !== storedHashBuf.length ||
!crypto.timingSafeEqual(submittedHash, storedHashBuf)) {
return null;
}
return account;
}
TIMING5-003 — TOTP code verified with integer comparison
TOTP (Time-based One-Time Password) 2FA codes are 6-digit numbers. When a MCP skill platform implements its own TOTP verification by comparing parseInt(userCode) === parseInt(storedCode), the comparison is a numeric equality check on integers, which JavaScript evaluates by comparing the decimal representations byte-by-byte internally. Even if the integer comparison is not directly timing-vulnerable, using an integer comparison instead of the proper speakeasy.totp.verify() (or equivalent) also forfeits the TOTP window validation — the ±1 step tolerance that handles clock skew — and the replay protection (each code should be valid only once). The combination of stripped replay protection and potentially timing-leaky comparison degrades the security of the 2FA implementation significantly.
// VULNERABLE — TIMING5-003
// TOTP code compared with parseInt() === — bypasses speakeasy's window and replay protection.
// Even if timing is not exploitable here, this misses clock-skew window (±1 step) and replay guard.
import speakeasy from 'speakeasy';
app.post('/auth/verify-totp', requireSession, (req, res) => {
const { code } = req.body;
const user = getUserFromSession(req);
const currentCode = speakeasy.totp({
secret: user.totpSecret,
encoding: 'base32',
});
// VULNERABLE: integer comparison — misses window tolerance and no replay protection
if (parseInt(code, 10) !== parseInt(currentCode, 10)) {
return res.status(401).json({ error: 'Invalid TOTP code' });
}
completeLogin(req, user);
res.json({ success: true });
});
// FIXED — TIMING5-003
// Fix 1: Use speakeasy.totp.verify() — built-in constant-time comparison + window + replay guard.
// Fix 2: Set window:1 for ±30s clock skew tolerance.
// Fix 3: Store last used token and reject reuse — replay protection.
import speakeasy from 'speakeasy';
import db from './db.js';
app.post('/auth/verify-totp', requireSession, async (req, res) => {
const { code } = req.body;
const user = getUserFromSession(req);
// FIX 1 + 2: speakeasy.totp.verify() — constant-time, window:1, returns token used
const result = speakeasy.totp.verify({
secret: user.totpSecret,
encoding: 'base32',
token: String(code),
window: 1, // FIX 2: ±1 step (±30s) clock skew tolerance
step: 30,
});
if (!result) {
return res.status(401).json({ error: 'Invalid TOTP code' });
}
// FIX 3: Replay protection — reject this code if it was already used
const tokenHash = crypto.createHash('sha256').update(String(code) + user.id).digest('hex');
const alreadyUsed = await db.usedTotpTokens.findOne({ hash: tokenHash });
if (alreadyUsed) {
return res.status(401).json({ error: 'TOTP code already used' });
}
// Store used token for the duration of its validity window (90s = 3 steps)
await db.usedTotpTokens.insert({ hash: tokenHash, expiresAt: Date.now() + 90_000 });
completeLogin(req, user);
res.json({ success: true });
});
Detection: SkillAudit scans for TOTP verification code that uses ===, parseInt()===, or string comparison on TOTP codes instead of speakeasy.totp.verify() or equivalent constant-time library functions. It also checks for missing replay protection (last-used-token tracking).
TIMING5-004 — Password reset token timing oracle in Express middleware
Password reset flows generate single-use cryptographic tokens (typically 32 bytes of crypto.randomBytes() encoded as hex). When the submitted token is compared against the stored token using === in Express middleware, an attacker can send thousands of reset requests for a known user email address and vary the token one character at a time, measuring response timing. Unlike authentication endpoints that lock accounts after N failed attempts, password reset token comparison is not typically rate-limited or counted as a "failed login" — allowing the attacker to perform the full timing enumeration without account lockout. The timing oracle approach also reveals valid unexpired tokens for accounts where the user has not yet clicked the reset link.
// VULNERABLE — TIMING5-004
// Password reset token compared with === — timing oracle allows token enumeration.
// No rate limiting on this endpoint (not counted as "failed login").
// Attacker can recover the hex token one character at a time over ~6400 requests.
app.post('/auth/reset-password', async (req, res) => {
const { email, token, newPassword } = req.body;
const record = await db.resetTokens.findOne({ email, used: false });
if (!record) return res.status(400).json({ error: 'No pending reset' });
// VULNERABLE: === on hex-encoded token strings — timing oracle
if (req.body.token !== record.token) {
return res.status(400).json({ error: 'Invalid token' });
}
if (record.expiresAt < Date.now()) {
return res.status(400).json({ error: 'Token expired' });
}
await resetPassword(email, newPassword);
await db.resetTokens.update({ email }, { used: true });
res.json({ success: true });
});
// FIXED — TIMING5-004
// Fix 1: crypto.timingSafeEqual() on Buffer.from() of both token strings.
// Fix 2: Check expiry BEFORE token comparison — do not reveal timing info on expired tokens.
// Fix 3: Rate-limit reset attempts per email — attacker can't send 10,000 requests.
// Fix 4: Store HMAC of token, not plaintext — if DB leaked, tokens not directly usable.
import crypto from 'crypto';
import rateLimit from 'express-rate-limit';
const resetLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 5, // FIX 3: max 5 attempts per IP per 15 minutes
message: { error: 'Too many attempts' },
});
app.post('/auth/reset-password', resetLimiter, async (req, res) => {
const { email, token, newPassword } = req.body;
const record = await db.resetTokens.findOne({ email, used: false });
// FIX 2: Check expiry first — consistent failure path regardless of token value
if (!record || record.expiresAt < Date.now()) {
return res.status(400).json({ error: 'Invalid or expired reset request' });
}
// FIX 1: timingSafeEqual — constant-time comparison of token strings
const submittedBuf = Buffer.from(token || '', 'utf8');
const storedBuf = Buffer.from(record.token, 'utf8');
const tokenValid =
submittedBuf.length === storedBuf.length &&
crypto.timingSafeEqual(submittedBuf, storedBuf);
if (!tokenValid) {
return res.status(400).json({ error: 'Invalid or expired reset request' });
}
await resetPassword(email, newPassword);
await db.resetTokens.update({ email }, { used: true });
res.json({ success: true });
});
Summary — SA-SKL-TIMING5 at a glance
| Pattern | Root cause | Fix | Severity |
|---|---|---|---|
| TIMING5-001 | Webhook HMAC-SHA256 verified with === — early exit on first mismatch; timing oracle recovers HMAC byte-by-byte over many requests; forged signatures allow attacker to inject arbitrary CI payloads | crypto.timingSafeEqual() on Buffer.from() of both signature strings; check lengths separately | High |
| TIMING5-002 | API key suffix hash compared with === after prefix-based account lookup; timing oracle on SHA-256 hex strings recovers hash bytes; combined with low-entropy suffix, may allow full key recovery | crypto.timingSafeEqual() on Buffer hash comparison; HMAC-SHA256 for key hashing with server-side secret | High |
| TIMING5-003 | TOTP code compared with parseInt()=== — bypasses speakeasy's constant-time compare, clock-skew window, and replay protection; reduced effective brute-force space per timing round | speakeasy.totp.verify() with window:1; store and reject reused token hashes for replay protection | Medium |
| TIMING5-004 | Password reset token compared with === in Express middleware; no rate limiting on endpoint; timing oracle allows full token enumeration without account lockout or detection | crypto.timingSafeEqual() on Buffer.from(); rate-limit reset attempts per IP; check expiry before comparison | High |
Does your MCP skill's secret comparison code protect against timing attacks?
SkillAudit scans for === comparisons on HMAC signatures, API key hashes, TOTP codes, and password reset tokens — and flags every case where crypto.timingSafeEqual() should be used instead, before an attacker times their way into your CI pipeline or user accounts.