Brute Force and Account Lockout Security in Claude MCP Skills
MCP skill brute force protection requires four independent properties: a failed-attempt counter that fires before credential verification, a lockout key that includes both the account identifier and the client IP, a normalized form of the identifier so case variants map to the same key, and a constant response time regardless of lockout state. Miss any one and an attacker can guess credentials at scale. SA-SKL-BRUTEFORCE-001 through BRUTEFORCE-004 cover the four most common gaps found in community MCP skill audits.
Contents
- Why brute force protection must be layered
- BRUTEFORCE-001 — No lockout on login endpoint
- BRUTEFORCE-002 — Lockout bypass via IP rotation
- BRUTEFORCE-003 — Email case normalization gap
- BRUTEFORCE-004 — Timing oracle via lockout response latency
- Complete production implementation
- SkillAudit detection summary
Why brute force protection must be layered
Brute force attacks against MCP skill login endpoints take three forms, and each requires a different defense layer. Targeted attacks try many passwords against one account — stopped by per-account lockout (N consecutive failures blocks the account for T minutes). Password spraying tries one common password against many accounts, staying below per-account thresholds — stopped by per-IP rate limits and CAPTCHA after the first suspicious signal. Credential stuffing replays breached email/password pairs from other sites — also stopped by per-IP rate limits, but primarily by requiring a second factor for new devices.
The critical insight is that none of these layers is redundant. Per-account lockout doesn't stop spraying because each account sees only one attempt per spray cycle. Per-IP rate limits don't stop targeted attacks from residential proxy pools because each attempt comes from a different IP. A CAPTCHA doesn't stop sophisticated bots that solve them at $0.001 per solve via CAPTCHA-solving services. The correct architecture deploys all three in combination, with each layer catching what the others let through.
For MCP skills, the attack surface is particularly narrow: the login endpoint is almost always a single POST /auth/login route that accepts an email and password. That makes the lockout implementation simpler than on a general web app — there's one place to add it, and one place for it to be wrong.
Prerequisite: These patterns assume the skill uses bcrypt or Argon2 for password hashing. If your skill stores plaintext passwords or uses MD5/SHA-1 hashing, the brute force vulnerability is the least of your problems — see SA-SKL-CRYPTO for credential hashing security first.
BRUTEFORCE-001 — No lockout on login endpoint
The most common brute force vulnerability in community MCP skills is a login endpoint with no failed-attempt counter at all. With no lockout mechanism, an attacker can attempt unlimited password guesses against any account. The only constraint is the speed of bcrypt comparison on the server — typically 300ms per attempt at cost factor 12. That sounds slow, but a botnet of 100 concurrent threads trying 3 guesses per second each delivers 18,000 attempts per minute against a single account. Against a user with a common password pattern, this is a matter of seconds.
// VULNERABLE: login endpoint with no failed-attempt counter
app.post('/auth/login', async (req, res) => {
const { email, password } = req.body;
const user = await db.users.findOne({ email });
if (!user) {
return res.status(401).json({ error: 'Invalid credentials' });
}
const valid = await bcrypt.compare(password, user.passwordHash);
if (!valid) {
// No counter, no lockout — attacker retries indefinitely
return res.status(401).json({ error: 'Invalid credentials' });
}
req.session.userId = user.id;
res.json({ ok: true });
});
The fix uses Redis INCR and EXPIRE to implement a sliding counter per account. After five consecutive failures the account enters a 15-minute lockout window, and the counter is cleared on successful login. The lockout check runs before the bcrypt comparison so locked accounts return immediately without consuming server CPU on the hash comparison.
// FIXED: Redis-based per-account lockout
const redis = require('ioredis');
const client = new redis(process.env.REDIS_URL);
const MAX_ATTEMPTS = 5;
const LOCKOUT_SECONDS = 900; // 15 minutes
app.post('/auth/login', async (req, res) => {
const normalizedEmail = req.body.email.toLowerCase().trim();
const lockKey = `lockout:${normalizedEmail}`;
// Check lockout before touching DB or running bcrypt
const attempts = parseInt(await client.get(lockKey) || '0', 10);
if (attempts >= MAX_ATTEMPTS) {
return res.status(429).json({ error: 'Account temporarily locked. Try again later.' });
}
const user = await db.users.findOne({ email: normalizedEmail });
if (!user) {
await client.multi().incr(lockKey).expire(lockKey, LOCKOUT_SECONDS).exec();
return res.status(401).json({ error: 'Invalid credentials' });
}
const valid = await bcrypt.compare(req.body.password, user.passwordHash);
if (!valid) {
await client.multi().incr(lockKey).expire(lockKey, LOCKOUT_SECONDS).exec();
return res.status(401).json({ error: 'Invalid credentials' });
}
await client.del(lockKey); // Clear on success
req.session.userId = user.id;
res.json({ ok: true });
});
BRUTEFORCE-002 — Lockout bypass via IP rotation
A per-account lockout keyed only on the username is defeated by IP rotation. Residential proxy services provide pools of tens of thousands of IP addresses at $3–$10 per GB of traffic. An attacker who exhausts the per-account attempt counter simply waits for the lockout window to expire — but if the lockout key contains only the email, the attacker doesn't need to wait at all if they also rotate account aliases (see BRUTEFORCE-003). More importantly, a pure per-IP rate limit is fully bypassed by IP rotation: each attempt comes from a fresh IP, and each fresh IP gets the full attempt budget.
The correct architecture requires both layers: per-account lockout (catches targeted attacks against a single account) paired with per-IP rate limiting (catches attacks from a fixed IP or slow-rotation botnet). The two counters use different keys, different thresholds, and different windows.
// VULNERABLE: lockout keyed on username only — bypassed by IP rotation
const lockKey = `lockout:${email}`; // No IP component
// IP rotation attack:
// From 1.2.3.4: fail (lockout:user@ex.com = 1)
// From 1.2.3.5: fail (lockout:user@ex.com = 2)
// ...5 failures from 5 different IPs → account locked
// But per-IP rate limit never triggered (1 req per IP)
// Switch to User@ex.com case variant → lockout:User@ex.com = 0
// Fresh counter, unlimited retries resume immediately
// FIXED: dual-key lockout — per-account AND per-IP
const normalizedEmail = req.body.email.toLowerCase().trim();
const accountLockKey = `lockout:account:${normalizedEmail}`;
const ipLockKey = `lockout:ip:${req.ip}`;
const [accountAttempts, ipAttempts] = await Promise.all([
client.get(accountLockKey),
client.get(ipLockKey),
]);
if (parseInt(accountAttempts || '0', 10) >= 5) {
return res.status(429).json({ error: 'Account temporarily locked. Try again later.' });
}
if (parseInt(ipAttempts || '0', 10) >= 20) {
return res.status(429).json({ error: 'Too many requests. Try again later.' });
}
// On failure: increment both counters
await client.multi()
.incr(accountLockKey).expire(accountLockKey, 900) // 15 min window
.incr(ipLockKey).expire(ipLockKey, 60) // 1 min window
.exec();
BRUTEFORCE-003 — Email case normalization gap in lockout key
Email addresses are case-insensitive by standard (RFC 5321 §2.4), but Redis keys and most database string comparisons are case-sensitive. If the lockout key is built from the raw email string in the request body, then user@example.com and USER@EXAMPLE.COM produce different keys even though they refer to the same account. An attacker who exhausts the attempt counter for user@example.com (5 failures, account locked) resets the counter instantly by switching to User@Example.Com — a fresh Redis key with zero failures pointing to the same underlying user record.
This vulnerability is surprisingly common because developers often apply lowercase normalization at the database query stage (to find the right user record) but forget to apply it earlier at the lockout key construction stage. The fix is to normalize the email as the absolute first operation in the handler — before constructing any key, before any DB query, and before any comparison.
// VULNERABLE: lockout key uses email as-supplied
app.post('/auth/login', async (req, res) => {
const { email, password } = req.body;
// VULNERABLE: lockout key is case-sensitive string from request body
const lockKey = `lockout:${email}`; // 'user@ex.com' != 'USER@EX.COM'
const attempts = parseInt(await client.get(lockKey) || '0', 10);
if (attempts >= MAX_ATTEMPTS) {
return res.status(429).json({ error: 'Account temporarily locked.' });
}
// Normalization only at DB query — lockout key already set above
const user = await db.users.findOne({ email: email.toLowerCase() });
// ...
// Attack: exhaust lockout:user@ex.com with 5 fails
// then switch to lockout:USER@EX.COM (counter = 0)
});
// FIXED: normalize email as first operation, before any key or query
app.post('/auth/login', async (req, res) => {
// FIXED: normalize before constructing any keys or running any queries
const normalizedEmail = req.body.email.toLowerCase().trim();
const lockKey = `lockout:${normalizedEmail}`; // Case-invariant
const attempts = parseInt(await client.get(lockKey) || '0', 10);
if (attempts >= MAX_ATTEMPTS) {
return res.status(429).json({ error: 'Account temporarily locked.' });
}
// DB query also uses normalized email (consistent with registration)
const user = await db.users.findOne({ email: normalizedEmail });
// ...
});
${email} or ${req.body.email} without a preceding .toLowerCase() call; case variation resets the counter. Fix: email.toLowerCase().trim() as the first line in the handler, applied to all lockout keys and DB queries.BRUTEFORCE-004 — Timing oracle via lockout response latency
Even a correctly implemented lockout can leak information through response timing. The lockout check performs a Redis GET (~1ms). The credential check runs a bcrypt comparison (~300ms at cost factor 12). If the lockout path returns HTTP 429 immediately after the Redis check and the invalid-credential path returns HTTP 401 after bcrypt, then measuring response latency distinguishes the two states.
This timing oracle has two consequences: it reveals whether an email address corresponds to an existing account (non-existent accounts receive no bcrypt comparison — a different timing profile), and it reveals when an existing account is locked. An attacker can enumerate account existence by triggering a lockout and measuring the timing switch from ~300ms to ~1ms. This is the same account enumeration vulnerability that many apps have from using different error messages for "no account" vs "wrong password", but delivered through timing rather than text.
The fix is to run a bcrypt comparison on every request path, including the lockout path and the non-existent-account path. Use a pre-computed dummy hash as the comparison target when the account doesn't exist or is locked. Pair the lockout check and DB lookup with Promise.all() so the bcrypt comparison can start as soon as either result is available.
// VULNERABLE: lockout path returns in 1ms; invalid-credential path takes 300ms
app.post('/auth/login', async (req, res) => {
const normalizedEmail = req.body.email.toLowerCase().trim();
const lockKey = `lockout:${normalizedEmail}`;
const attempts = parseInt(await client.get(lockKey) || '0', 10);
// TIMING ORACLE: returns in ~1ms — reveals account is locked / exists
if (attempts >= MAX_ATTEMPTS) {
return res.status(429).json({ error: 'Account temporarily locked.' });
}
const user = await db.users.findOne({ email: normalizedEmail });
if (!user) {
// TIMING ORACLE: returns in ~1ms (no bcrypt) — reveals account doesn't exist
return res.status(401).json({ error: 'Invalid credentials' });
}
const valid = await bcrypt.compare(req.body.password, user.passwordHash); // 300ms
// ...
});
// FIXED: uniform response time via dummy bcrypt hash on all paths
// Pre-compute a dummy hash at startup (not in the request path)
const DUMMY_HASH = await bcrypt.hash('__dummy_skillaudit_placeholder__', 12);
app.post('/auth/login', async (req, res) => {
const normalizedEmail = req.body.email.toLowerCase().trim();
const lockKey = `lockout:${normalizedEmail}`;
// Run lockout check and DB lookup in parallel
const [attempts, user] = await Promise.all([
client.get(lockKey).then(v => parseInt(v || '0', 10)),
db.users.findOne({ email: normalizedEmail }),
]);
const isLocked = attempts >= MAX_ATTEMPTS;
// Always run bcrypt — against real hash or dummy hash
// Response time is ~300ms regardless of lockout or account existence
const hashToCompare = (user && !isLocked) ? user.passwordHash : DUMMY_HASH;
const valid = await bcrypt.compare(req.body.password, hashToCompare);
if (isLocked) {
return res.status(429).json({ error: 'Account temporarily locked. Try again later.' });
}
if (!user || !valid) {
if (user) { // Only increment for existing accounts
await client.multi().incr(lockKey).expire(lockKey, 900).exec();
}
return res.status(401).json({ error: 'Invalid credentials' });
}
await client.del(lockKey);
req.session.regenerate(() => {
req.session.userId = user.id;
res.json({ ok: true });
});
});
bcrypt.compare(); timing oracle reveals account existence and lock state. Fix: always run bcrypt against real or dummy hash; use Promise.all() for lockout check and DB lookup.Complete production implementation
The four patterns above combine into a single login handler that is correct across all brute force scenarios. The key properties of the production implementation are:
- Normalize first.
email.toLowerCase().trim()as the first operation, before any Redis key, DB query, or comparison. - Dual-key lockout. Per-account key (15-minute window, 5-attempt threshold) paired with per-IP key (1-minute window, 20-attempt threshold).
- Always bcrypt. Compare against dummy hash on locked or non-existent accounts. Pre-compute the dummy hash at startup, not inside the handler.
- Clear on success. Delete both lockout keys after a successful login to avoid locking out legitimate users on subsequent sessions.
- Session regeneration. Call
req.session.regenerate()before setting session data to prevent session fixation (see SA-SKL-SESSION).
// Complete production login handler — covers all four SA-SKL-BRUTEFORCE patterns
const DUMMY_HASH = await bcrypt.hash('__dummy_sa_placeholder__', 12);
const MAX_ACCOUNT_ATTEMPTS = 5;
const MAX_IP_ATTEMPTS = 20;
const ACCOUNT_LOCKOUT_SECONDS = 900; // 15 minutes
const IP_WINDOW_SECONDS = 60; // 1 minute
app.post('/auth/login', async (req, res) => {
// 1. Normalize identifier before any operation
const normalizedEmail = (req.body.email || '').toLowerCase().trim();
if (!normalizedEmail) {
return res.status(400).json({ error: 'Email required' });
}
const accountLockKey = `lockout:account:${normalizedEmail}`;
const ipLockKey = `lockout:ip:${req.ip}`;
// 2. Parallel: lockout checks + DB lookup
const [accountAttempts, ipAttempts, user] = await Promise.all([
client.get(accountLockKey).then(v => parseInt(v || '0', 10)),
client.get(ipLockKey).then(v => parseInt(v || '0', 10)),
db.users.findOne({ email: normalizedEmail }),
]);
const isAccountLocked = accountAttempts >= MAX_ACCOUNT_ATTEMPTS;
const isIpLocked = ipAttempts >= MAX_IP_ATTEMPTS;
// 3. Always bcrypt — equalize response time
const hashToCompare = (user && !isAccountLocked) ? user.passwordHash : DUMMY_HASH;
const valid = await bcrypt.compare(req.body.password || '', hashToCompare);
// 4. Return lockout errors after bcrypt to avoid timing oracle
if (isAccountLocked) {
return res.status(429).json({ error: 'Account temporarily locked. Try again later.' });
}
if (isIpLocked) {
return res.status(429).json({ error: 'Too many requests. Try again later.' });
}
if (!user || !valid) {
// 5. Increment counters only for real accounts (prevent lockout DoS via enumeration)
if (user) {
await client.multi()
.incr(accountLockKey).expire(accountLockKey, ACCOUNT_LOCKOUT_SECONDS)
.incr(ipLockKey).expire(ipLockKey, IP_WINDOW_SECONDS)
.exec();
} else {
await client.multi()
.incr(ipLockKey).expire(ipLockKey, IP_WINDOW_SECONDS)
.exec();
}
return res.status(401).json({ error: 'Invalid credentials' });
}
// 6. Success — clear lockout, regenerate session
await client.del(accountLockKey);
req.session.regenerate((err) => {
if (err) return res.status(500).json({ error: 'Session error' });
req.session.userId = user.id;
res.json({ ok: true });
});
});
Redis or in-memory? In-memory stores (express-rate-limit default MemoryStore) lose their counters on process restart — a crash or deploy resets all lockout state. For MCP skills that restart frequently during development this may be acceptable, but for production skills use Redis with rate-limit-redis or ioredis. See SA-SKL-RATELIMIT2 for counter persistence patterns.
SkillAudit detection summary
| Pattern ID | Severity | What SkillAudit flags | Fix |
|---|---|---|---|
| BRUTEFORCE-001 | CRITICAL | bcrypt.compare() in a POST route handler with no preceding Redis/DB attempt counter check |
Redis INCR + EXPIRE lockout; 5 failures → 15-min lock; clear on success |
| BRUTEFORCE-002 | HIGH | Lockout key contains only email (no IP component) or only an IP rate limit with no per-account counter | Dual-key lockout: per-account (email) + per-IP (req.ip), separate thresholds and windows |
| BRUTEFORCE-003 | HIGH | Lockout key of the form lockout:${email} or lockout:${req.body.email} without preceding .toLowerCase() |
email.toLowerCase().trim() as first operation in handler; apply same normalization at registration |
| BRUTEFORCE-004 | MEDIUM | Lockout or non-existent-account branch returns before any bcrypt.compare() call |
Always run bcrypt against real or dummy hash; Promise.all() for lockout + DB lookup |
Related patterns: For magic link and passwordless token security gaps, see SA-SKL-MAGICLINK. For JWT algorithm confusion vulnerabilities in token-based skills. For timing side-channel vulnerabilities beyond login (API key comparison, HMAC verification), see SA-SKL-TIMING. For advanced rate-limit implementation gaps including MemoryStore persistence failure, see SA-SKL-RATELIMIT2.