Claude MCP skill authentication bypass — API key validation and service account management — SA-SKL-AUTH16
API keys and service accounts are the primary authentication mechanism for automated MCP skill registry integrations — CI/CD pipelines, audit bots, and third-party tooling. SA-SKL-AUTH16 covers four implementation weaknesses in key management: an MD5 hash that makes the key database reversible, a timezone bug that silently extends key validity, a missing audience claim that lets service account tokens authenticate at user endpoints, and a synchronous last-used write that leaks key existence via timing.
api_keys table can recover all keys that follow predictable patterns (UUID-based, base64 segments) within hours using GPU-accelerated rainbow tables or offline brute-force"2026-11-30T00:00:00") without a timezone designator; expiry check uses new Date(key.expiresAt) > new Date(); on a server running in UTC+2 (e.g., after a Daylight Saving Time change), the string is parsed as local time, shifting the expiry boundary by 2 hours past the intended UTC midnight — expired keys remain valid for 2 hours longer than intendedaud (audience) claim; both user sessions and service accounts share the same JWT signing secret and the same jwt.verify() call in the auth middleware; a service account token (intended only for the CI audit API) is accepted at user-facing endpoints such as POST /api/account/delete and PATCH /api/account/billing, which only check that a valid JWT is presentlast_used_at via a synchronous await db.update() call before returning the validation result; for a valid key this write takes ~8ms (row exists, UPDATE succeeds); for an invalid key the UPDATE affects 0 rows and returns in ~2ms; this 6ms timing difference, measurable over 100+ requests, allows an attacker to determine whether a key exists in the database without knowing the key valueBackground: API key security in multi-tenant registries
API keys are long-lived credentials that grant programmatic access to registry resources. Unlike user sessions (which expire with browser activity), API keys may be valid for months or years. This makes their storage and validation security properties critical: a compromised key database that is reversible exposes all integrations indefinitely. The findings in SA-SKL-AUTH16 represent four independent failure modes, each of which degrades the security of the key lifecycle in a different phase: storage (AUTH16-001), expiry enforcement (AUTH16-002), scope enforcement (AUTH16-003), and information leakage during validation (AUTH16-004).
These issues build on the credential management patterns documented in SA-SKL-AUTH15 (OAuth token storage) and the JWT scope bypass patterns in SA-SKL-AUTH10. AUTH16-003 is the most directly exploitable: a service account token with no audience restriction is a user-impersonation primitive for any endpoint that trusts any valid JWT.
AUTH16-001 — HIGH — API key hashed with MD5 — rainbow table recovery
API keys generated by the registry are stored in the api_keys table as MD5 hashes of the plaintext key. The choice of MD5 likely reflects a misunderstanding of its intended use: MD5 was designed for data integrity checksums, not for credential storage. Its speed — over 10 billion iterations per second on a modern GPU — makes it unsuitable as a credential hash. An attacker who exfiltrates the table (via a SQL injection vulnerability, a misconfigured backup, or insider access) can run hashcat against each MD5 hash using a GPU cluster. For API keys that follow predictable formats (prefix + UUID, base64-encoded 32 bytes), the keyspace is small enough to recover within hours. Without per-key salts, identical keys produce identical hashes, so a single precomputed rainbow table covers all users who happen to share key patterns.
API keys should be stored using a slow, salted key derivation function: either Argon2id (preferred) or PBKDF2 with at least 600,000 iterations. The salt should be randomly generated per key and stored alongside the hash. Because API key validation occurs on every authenticated request, the hash algorithm must be chosen with both security and latency in mind. Argon2id with memory: 65536 (64 MB), iterations: 3, and parallelism: 1 takes approximately 150ms on a typical server — acceptable for per-request API key validation where keys are cached after first validation.
// VULNERABLE — AUTH16-001
// services/api-keys.js
const crypto = require('crypto');
function hashApiKey(key) {
// BUG: MD5 — fast, unsalted, GPU-crackable at 10B hashes/s
return crypto.createHash('md5').update(key).digest('hex');
}
async function validateApiKey(rawKey) {
const hash = hashApiKey(rawKey);
const result = await db.query(
'SELECT id, org_id, scope, expires_at FROM api_keys WHERE key_hash = $1',
[hash]
);
return result.rows[0] || null;
}
// FIXED — AUTH16-001
// services/api-keys.js
const argon2 = require('argon2');
const crypto = require('crypto');
const ARGON2_OPTIONS = {
type: argon2.argon2id,
memoryCost: 65536, // 64 MB
timeCost: 3,
parallelism: 1,
};
async function hashApiKey(key) {
return argon2.hash(key, ARGON2_OPTIONS); // includes random salt automatically
}
async function validateApiKey(rawKey) {
// Store key prefix (first 8 chars) in plaintext for fast lookup — not secret
const prefix = rawKey.slice(0, 8);
const result = await db.query(
'SELECT id, org_id, scope, expires_at, key_hash FROM api_keys WHERE key_prefix = $1',
[prefix]
);
if (!result.rows.length) return null;
const row = result.rows[0];
// Argon2 verify includes timing-safe comparison + constant-time dummy op for misses
const valid = await argon2.verify(row.key_hash, rawKey, ARGON2_OPTIONS);
if (!valid) return null;
return { id: row.id, orgId: row.org_id, scope: row.scope, expiresAt: row.expires_at };
}
AUTH16-001 migration path: Existing MD5-hashed keys cannot be re-hashed without the plaintext, which is never stored. The migration plan is: (1) on next successful key validation, re-hash the key with Argon2id and update the DB row; (2) set a migration deadline (e.g., 90 days); (3) after the deadline, invalidate all keys that still have an MD5 hash and require users to generate new keys. SkillAudit flags the use of MD5, SHA-1, or SHA-256 without a salt and iteration count in key hashing code.
AUTH16-002 — HIGH — API key expiry bypass via timezone normalization
API key expiry is stored in the database as an ISO 8601 string without a timezone designator (e.g., "2026-11-30T00:00:00"). The expiry check constructs a JavaScript Date from this string and compares it to new Date(). When JavaScript's Date constructor receives a string without a timezone designator, it parses it as local time in the runtime's timezone, not as UTC. On a server configured to UTC+2 (which may occur after Daylight Saving Time configuration, cloud region migration, or a misconfigured container image), new Date("2026-11-30T00:00:00") resolves to 2026-11-29T22:00:00Z — two hours before midnight UTC. The key expires at the UTC+2 local midnight, not at the intended UTC midnight, granting an extra two hours of validity. The reverse is also true for UTC-X timezones: keys expire two hours early, causing valid keys to be rejected and breaking legitimate integrations.
The fix is to always store and compare timestamps as Unix epoch integers (seconds since 1970-01-01T00:00:00Z), which are timezone-agnostic. If a string format is required for human readability in the DB, append the UTC designator (Z or +00:00) to all stored timestamps. Use Date.now() / 1000 for the current timestamp and compare against the stored epoch integer. Never compare new Date(stringWithoutTZ) to new Date() for security-relevant expiry checks.
// VULNERABLE — AUTH16-002
// services/api-keys.js
function isKeyExpired(key) {
if (!key.expires_at) return false; // no expiry = never expires
// BUG: string without timezone parsed as local time, not UTC
// "2026-11-30T00:00:00" on UTC+2 server = 2026-11-29T22:00:00Z
// key valid for 2 extra hours past intended expiry
const expiresAt = new Date(key.expires_at);
return expiresAt < new Date(); // "already expired?"
}
// FIXED — AUTH16-002
// services/api-keys.js
function isKeyExpired(key) {
if (!key.expires_at_epoch) return false;
// Compare Unix epoch integers — timezone-agnostic, no Date string parsing
const nowSec = Math.floor(Date.now() / 1000);
return key.expires_at_epoch < nowSec;
}
// DB migration: add expires_at_epoch INTEGER column
// UPDATE api_keys SET expires_at_epoch = EXTRACT(EPOCH FROM expires_at AT TIME ZONE 'UTC')::INTEGER;
// When creating keys: always store UTC epoch
async function createApiKey(orgId, scopeList, expiryDays) {
const rawKey = crypto.randomBytes(32).toString('base64url');
const hash = await hashApiKey(rawKey);
const expiresAtEpoch = expiryDays
? Math.floor(Date.now() / 1000) + expiryDays * 86400
: null;
await db.query(
'INSERT INTO api_keys (org_id, key_prefix, key_hash, scope, expires_at_epoch) VALUES ($1,$2,$3,$4,$5)',
[orgId, rawKey.slice(0, 8), hash, scopeList.join(','), expiresAtEpoch]
);
return rawKey; // shown to user once — never stored plaintext
}
AUTH16-002 impact: The severity depends on whether the server timezone differs from UTC. Registries deployed in cloud regions configured to UTC+X timezones (common in EU deployments) silently extend all API key expiry windows. The 2-hour extension means a key expired after a suspected compromise remains valid, allowing an attacker who captured the key before revocation to continue using it past the intended revocation point. SkillAudit detects this by scanning expiry check code for new Date(stringField) comparisons where the string field is a DB-sourced timestamp column without an explicit Z suffix.
AUTH16-003 — HIGH — Service account JWT missing audience claim
The registry issues two types of JWT: user session tokens (for interactive UI users) and service account tokens (for CI/CD pipeline integrations). Both are signed with the same HMAC secret and verified with the same jwt.verify(token, secret) call in the shared auth middleware. User session tokens carry { sub: userId, role: 'user' }. Service account tokens carry { sub: serviceAccountId, type: 'service' }. Neither carries an aud (audience) claim. The auth middleware does not inspect type or any other claim to restrict which endpoints a token may be used against. A service account token is therefore accepted at any endpoint that uses requireAuth, including POST /api/account/delete, PATCH /api/billing/plan, and GET /api/users/:id/private-data — endpoints intended only for authenticated human users. An attacker who obtains a service account token (e.g., from a leaked CI variable) can use it to call user-facing endpoints that the service account should have no access to.
The fix is to add an aud claim to all JWTs and enforce audience validation at the middleware level. User session tokens should carry aud: "skillaudit:user-session"; service account tokens should carry aud: "skillaudit:service-account". Each endpoint group should validate that the token's aud matches the expected audience for that group. Use the audience option in jwt.verify() to enforce this automatically.
// VULNERABLE — AUTH16-003
// middleware/auth.js
function requireAuth(req, res, next) {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ error: 'Missing token' });
try {
// BUG: no audience validation — service account tokens accepted everywhere
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded; // { sub: serviceAccountId, type: 'service' }
next();
} catch {
res.status(401).json({ error: 'Invalid token' });
}
}
// routes/account.js — user-only endpoint but accepts any valid JWT
router.post('/api/account/delete', requireAuth, async (req, res) => {
// BUG: service account token passes requireAuth and can delete user accounts
await deleteAccount(req.user.sub);
res.json({ deleted: true });
});
// FIXED — AUTH16-003
// middleware/auth.js
const USER_AUD = 'skillaudit:user-session';
const SERVICE_AUD = 'skillaudit:service-account';
function requireAuth(allowedAudiences = [USER_AUD]) {
return (req, res, next) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ error: 'Missing token' });
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET, {
algorithms: ['HS256'],
audience: allowedAudiences, // JWT library enforces aud claim match
});
req.user = decoded;
next();
} catch (err) {
res.status(401).json({ error: 'Invalid or unauthorized token' });
}
};
}
// routes/account.js — user-only: only user-session tokens accepted
router.post(
'/api/account/delete',
requireAuth([USER_AUD]), // explicitly: user sessions only
async (req, res) => {
await deleteAccount(req.user.sub);
res.json({ deleted: true });
}
);
// routes/audits.js — CI/CD: only service account tokens accepted
router.post(
'/api/audits',
requireAuth([SERVICE_AUD]),
async (req, res) => { /* ... */ }
);
// When issuing tokens, always include the aud claim:
function issueUserToken(userId) {
return jwt.sign({ sub: userId, aud: USER_AUD }, process.env.JWT_SECRET, {
algorithm: 'HS256', expiresIn: '1h',
});
}
function issueServiceAccountToken(serviceAccountId) {
return jwt.sign({ sub: serviceAccountId, aud: SERVICE_AUD }, process.env.JWT_SECRET, {
algorithm: 'HS256', expiresIn: '90d',
});
}
AUTH16-003 impact: A leaked service account token (CI/CD variable exposed in a public repository, logged in CI output, or included in an error response) grants full access to all user-facing endpoints, including account deletion, billing plan changes, and private data reads. Service account tokens are typically long-lived (90 days or more), increasing the exposure window. SkillAudit detects this by issuing a service account token and attempting to call user-facing endpoints that should reject it, verifying the response is 401 and not 200.
AUTH16-004 — MEDIUM — Key last-used timestamp write timing side-channel
The API key validator updates the last_used_at column synchronously before returning the validation result. For a valid key, the UPDATE modifies one row and returns in approximately 8ms. For an invalid key (no matching hash in the table), the UPDATE matches no rows and returns in approximately 2ms. This 6ms difference in response latency is consistent and measurable across repeated requests. An attacker who can send thousands of key guesses and measure per-request response latency can distinguish valid-but-wrong-secret keys from completely non-existent keys. This information narrows the keyspace for a targeted brute-force attack: the attacker learns which key prefixes correspond to real keys in the database.
The fix is to convert the last-used timestamp update to an asynchronous fire-and-forget operation that does not block the response path. The validation result is returned immediately after the hash comparison, and the UPDATE runs in the background. This eliminates the latency difference between valid and invalid keys, as both paths now return after the same cryptographic comparison time. Use setImmediate() or a background job queue for the write.
// VULNERABLE — AUTH16-004
// services/api-keys.js
async function validateApiKey(rawKey) {
const prefix = rawKey.slice(0, 8);
const result = await db.query(
'SELECT id, org_id, key_hash, expires_at_epoch FROM api_keys WHERE key_prefix = $1',
[prefix]
);
if (!result.rows.length) return null; // ~2ms (no UPDATE)
const row = result.rows[0];
const valid = await argon2.verify(row.key_hash, rawKey);
if (!valid) return null;
// BUG: synchronous DB write blocks response — 8ms write visible vs 2ms no-write
await db.query(
'UPDATE api_keys SET last_used_at = NOW() WHERE id = $1',
[row.id]
);
// Response returns AFTER the write — timing difference leaks key existence
return { id: row.id, orgId: row.org_id };
}
// FIXED — AUTH16-004
// services/api-keys.js
async function validateApiKey(rawKey) {
const prefix = rawKey.slice(0, 8);
const result = await db.query(
'SELECT id, org_id, key_hash, expires_at_epoch FROM api_keys WHERE key_prefix = $1',
[prefix]
);
if (!result.rows.length) return null;
const row = result.rows[0];
const valid = await argon2.verify(row.key_hash, rawKey);
if (!valid) return null;
// Fire-and-forget: last_used_at update does not block the response path
// setImmediate defers to the next event loop iteration — no await
setImmediate(() => {
db.query(
'UPDATE api_keys SET last_used_at = NOW() WHERE id = $1',
[row.id]
).catch(err => logger.warn({ err, keyId: row.id }, 'last_used_at update failed'));
});
// Response returned immediately — timing is now: prefix lookup + argon2.verify only
return { id: row.id, orgId: row.org_id };
}
AUTH16-004 notes: The timing oracle from last-used writes is a medium finding because it requires statistical analysis over many requests and only reveals key prefix existence, not the full key value. However, combined with prefix enumeration, it can narrow the brute-force space significantly for short or patterned keys. The fire-and-forget fix is correct and low-risk: last_used_at is an audit field, not a security control, so a small delay or occasional missed update is acceptable. SkillAudit flags synchronous await db.update() calls on audit columns (last_used_at, last_seen_at, access_count) that occur in the response path of key validation functions.
Detection with SkillAudit
SkillAudit's authentication audit module scans for all four SA-SKL-AUTH16 patterns. AUTH16-001 is detected by scanning the key hashing code for MD5, SHA-1, or any fast hash algorithm without iteration count and salt. AUTH16-002 is detected by scanning timestamp comparison code for new Date(stringField) patterns on DB-sourced columns that lack a Z suffix. AUTH16-003 is detected by running a service account token against user-facing endpoints and asserting they return 401. AUTH16-004 is detected by measuring the latency difference between valid and invalid key validation requests over 100 samples.
| Finding | Severity | Root cause | Fix |
|---|---|---|---|
| AUTH16-001 | HIGH | MD5 hash of API key — GPU-crackable rainbow table | Argon2id with per-key salt; migrate existing keys on next use |
| AUTH16-002 | HIGH | Expiry string without timezone parsed as local time | Store/compare as Unix epoch integers; append Z to all timestamps |
| AUTH16-003 | HIGH | Service account JWT lacks aud claim; shared verifier | aud claim on all tokens; audience-restricted middleware per route group |
| AUTH16-004 | MEDIUM | Synchronous last-used DB write timing side-channel | Fire-and-forget setImmediate — decouple audit write from response path |
Related findings: SA-SKL-AUTH15 (OAuth2 token storage), SA-SKL-AUTH14 (brute force and account enumeration), SA-SKL-RATELIMIT14 (bulk API rate limiting).