Claude MCP skill privilege escalation — API quota enforcement and rate limit bypass
SA-SKL-PRIVESC15 documents four privilege escalation vulnerabilities in MCP skill registry API quota and rate limit enforcement. Free-tier users can self-grant unlimited API quota via JWT manipulation, bypass per-IP rate limits through header spoofing, export complete audit history by overriding server-side page size, and overdraft their LLM token budget through concurrent non-atomic requests.
quotaLimit field; attacker crafts token with quotaLimit:999999 to bypass free-tier limits entirely
X-Forwarded-For header; rotating that header value bypasses per-IP throttle making free-tier rate limit 1000x intended
pageSize from req.query without plan gating; free-tier user sets pageSize:10000 to export complete audit history in one request
UPDATE; concurrent audits race to double-spend a 100-token budget consuming 200 tokens
PRIVESC15-001 (Critical): JWT-encoded API quota allows self-grant of unlimited monthly calls
MCP skill registries commonly embed user plan metadata in the JWT access token so that middleware can enforce usage limits without a database round-trip on every request. When the monthly API call quota is one of those embedded claims — stored as quotaLimit in the token payload — a free-tier attacker gains full control over the enforcement ceiling by simply issuing themselves a fresh JWT with an arbitrarily large value. Because the JWT is signed with the user's own session credentials and many registry implementations only verify the signature and expiry without cross-checking plan entitlements from an authoritative source, the forged claim passes validation undetected.
The practical impact is total bypass of the monthly API call limit. A free-tier account nominally capped at 100 calls per month can craft a JWT with quotaLimit:999999 and invoke arbitrary MCP skills at full throughput for the billing cycle. Because the quota check occurs before any downstream metering, usage may never reach the billing layer at all. This pattern is not theoretical: JWT payload manipulation requires no cryptographic attack — only a JWT library and a valid signing key, which every authenticated session already possesses in the form of a refresh-token exchange endpoint.
// VULNERABLE — quota enforcement reads limit from JWT claims
// File: middleware/quotaCheck.js
const jwt = require('jsonwebtoken');
async function quotaCheckMiddleware(req, res, next) {
const token = req.headers.authorization?.split(' ')[1];
const decoded = jwt.verify(token, process.env.JWT_SECRET);
// VULNERABILITY: quotaLimit is attacker-controlled — any JWT claim can be forged
const quotaLimit = decoded.quotaLimit; // e.g. attacker sets 999999
const userId = decoded.sub;
const { rows } = await db.query(
'SELECT calls_this_month FROM api_usage WHERE user_id = $1',
[userId]
);
const used = rows[0]?.calls_this_month ?? 0;
if (used >= quotaLimit) {
return res.status(429).json({ error: 'Monthly quota exceeded' });
}
req.quotaRemaining = quotaLimit - used;
next();
}
Fix: Never read enforcement limits from client-supplied tokens. Fetch the quota value from the subscription plan configuration stored server-side in the subscription database. The JWT should carry only the subscriber identity (sub) — plan entitlements are authoritative only when read directly from the plan config record. Reject any JWT that embeds quota or tier claims by omitting those fields from the token schema entirely.
// FIXED — quota limit fetched from server-side plan config, never from JWT
// File: middleware/quotaCheck.js
const jwt = require('jsonwebtoken');
const { getPlanConfig } = require('../services/subscriptionService');
async function quotaCheckMiddleware(req, res, next) {
const token = req.headers.authorization?.split(' ')[1];
// JWT carries identity only — no quota or tier claims accepted
const decoded = jwt.verify(token, process.env.JWT_SECRET);
const userId = decoded.sub;
// Authoritative quota from subscription DB, not from token
const planConfig = await getPlanConfig(userId); // DB lookup by userId
const quotaLimit = planConfig.monthlyApiCallLimit; // e.g. 100 for free tier
const { rows } = await db.query(
'SELECT calls_this_month FROM api_usage WHERE user_id = $1',
[userId]
);
const used = rows[0]?.calls_this_month ?? 0;
if (used >= quotaLimit) {
return res.status(429).json({ error: 'Monthly quota exceeded' });
}
req.quotaRemaining = quotaLimit - used;
next();
}
PRIVESC15-002 (High): X-Forwarded-For rate limit key enables per-IP throttle bypass
Rate limiting in MCP skill registries is frequently implemented at the IP level, using the client's IP address as the Redis key so each IP is independently throttled. When the middleware derives that IP from the X-Forwarded-For HTTP header rather than the actual TCP connection address, the rate limit becomes trivially bypassable. The X-Forwarded-For header is set by the client, not by a trusted infrastructure component, and there is no mechanism by which the server can verify its contents. An attacker increments a counter in the header value on each request — X-Forwarded-For: 192.0.2.1, then 192.0.2.2, and so on — presenting a fresh synthetic IP to the rate limiter with every call.
On a free-tier account with a limit of 10 requests per minute, rotating through 1,000 synthetic IPs delivers 10,000 requests per minute — a 1,000x amplification with no credentials or tooling beyond a standard HTTP client. The free-tier cap becomes meaningless. This matters especially for MCP skill invocations that consume compute or trigger downstream LLM calls, where each bypassed rate limit unit represents a real operating cost absorbed by the platform. Many Node.js rate-limit libraries read req.ip which Express populates from X-Forwarded-For by default when trust proxy is enabled, making this a subtle misconfiguration rather than an obvious coding error.
// VULNERABLE — rate limit key derived from X-Forwarded-For header
// File: middleware/rateLimit.js
const redis = require('../lib/redis');
async function rateLimitMiddleware(req, res, next) {
// VULNERABILITY: X-Forwarded-For is attacker-controlled; trivially rotated
const clientIp = req.headers['x-forwarded-for']?.split(',')[0].trim()
|| req.connection.remoteAddress;
const key = `rate:${clientIp}`;
const limit = 10; // requests per minute
const window = 60; // seconds
const current = await redis.incr(key);
if (current === 1) await redis.expire(key, window);
if (current > limit) {
return res.status(429).json({ error: 'Rate limit exceeded' });
}
next();
}
Fix: Use req.socket.remoteAddress as the primary rate limit key — this reflects the actual TCP connection address and cannot be spoofed by the client. Supplement with a per-account rate limit keyed on the authenticated user ID as a secondary enforcement layer, so that an attacker operating through a rotating proxy still hits the account-level ceiling. Never trust X-Forwarded-For from untrusted proxies; if your infrastructure runs behind a load balancer you control, configure a fixed trusted proxy list and reject requests where the header chain extends beyond it.
// FIXED — rate limit keyed on actual TCP address + per-account fallback
// File: middleware/rateLimit.js
const redis = require('../lib/redis');
async function rateLimitMiddleware(req, res, next) {
// Actual TCP address — not spoofable by the client
const actualIp = req.socket.remoteAddress;
const accountId = req.user?.sub ?? 'anon'; // set by auth middleware
const ipKey = `rate:ip:${actualIp}`;
const accKey = `rate:acc:${accountId}`;
const window = 60;
// Check both IP and account limits independently
const [ipCount, accCount] = await Promise.all([
redis.incr(ipKey),
redis.incr(accKey),
]);
if (ipCount === 1) await redis.expire(ipKey, window);
if (accCount === 1) await redis.expire(accKey, window);
if (ipCount > 10 || accCount > 10) {
return res.status(429).json({ error: 'Rate limit exceeded' });
}
next();
}
PRIVESC15-003 (High): Uncapped server-side pageSize leaks full audit history to free-tier users
Paginated audit result endpoints in MCP skill registries typically accept a pageSize query parameter so callers can tune response size. When the server forwards that value directly to the database LIMIT clause without enforcing a plan-tier ceiling, any authenticated user — including free-tier accounts — can override the intended pagination and retrieve arbitrarily large result sets. Setting pageSize=10000 turns a single API call into a full audit history export, circumventing any entitlement boundary that restricts free-tier data access to recent or summarised results.
Beyond data exposure, an unbounded pageSize creates a denial-of-service surface: a single request materialising tens of thousands of audit rows from Postgres into memory, serialising them to JSON, and streaming the response can saturate API server memory and exhaust database connection time. For multi-tenant MCP registries the blast radius extends to all co-located tenants sharing the same pool. The root cause is the assumption that the client will apply reasonable values — in practice, any parameter accepted from req.query must be validated and clamped against an authoritative server-side bound before it reaches the query layer.
// VULNERABLE — pageSize passed directly from query string to DB LIMIT
// File: routes/audits.js
router.get('/audits', authenticate, async (req, res) => {
const userId = req.user.sub;
// VULNERABILITY: pageSize from client — attacker sets pageSize=10000
const pageSize = parseInt(req.query.pageSize, 10) || 20;
const page = parseInt(req.query.page, 10) || 1;
const offset = (page - 1) * pageSize;
const { rows } = await db.query(
`SELECT id, skill_id, result_summary, created_at
FROM audit_results
WHERE user_id = $1
ORDER BY created_at DESC
LIMIT $2 OFFSET $3`,
[userId, pageSize, offset] // pageSize is fully attacker-controlled
);
res.json({ results: rows, page, pageSize });
});
Fix: Determine the maximum allowed page size from the subscription plan config retrieved server-side — 100 rows for free tier, 1,000 rows for pro tier. The client-supplied value is treated as a preference, not an authoritative limit. Apply Math.min(requestedSize, planMaxPageSize) so free-tier users cannot exceed their entitlement regardless of what they send in the query string. The server enforces, never the client.
// FIXED — pageSize capped server-side from plan config
// File: routes/audits.js
const { getPlanConfig } = require('../services/subscriptionService');
router.get('/audits', authenticate, async (req, res) => {
const userId = req.user.sub;
const planConfig = await getPlanConfig(userId);
// Plan-tier ceiling: 100 for free, 1000 for pro
const maxPageSize = planConfig.maxAuditPageSize;
// Client preference clamped to plan ceiling — server always wins
const requested = parseInt(req.query.pageSize, 10) || 20;
const pageSize = Math.min(Math.max(1, requested), maxPageSize);
const page = Math.max(1, parseInt(req.query.page, 10) || 1);
const offset = (page - 1) * pageSize;
const { rows } = await db.query(
`SELECT id, skill_id, result_summary, created_at
FROM audit_results
WHERE user_id = $1
ORDER BY created_at DESC
LIMIT $2 OFFSET $3`,
[userId, pageSize, offset]
);
res.json({ results: rows, page, pageSize, maxPageSize });
});
PRIVESC15-004 (Critical): Non-atomic LLM token consumption enables concurrent budget overdraft
LLM analysis in MCP skill audits consumes tokens that count against a per-account monthly budget. When the token accounting logic follows a read-then-write pattern — selecting the current consumed value, checking it against the quota in application code, and then issuing a separate UPDATE — concurrent requests introduce a time-of-check/time-of-use (TOCTOU) race condition. Two concurrent audit requests each read remaining=100 before either write completes, each conclude there is sufficient budget, and each subtract 100 tokens, resulting in a total consumption of 200 tokens against a 100-token budget. The constraint is never violated at the database level because each individual write is valid in isolation.
The severity is critical for cost-based billing: a free-tier account with a 100-token monthly LLM budget can trigger an unbounded number of analyses by firing many concurrent requests within the same millisecond window. At scale — using a script that launches 50 goroutines simultaneously — the account consumes 5,000 tokens for the price of 100. The fix does not require application-level locking or serialisable transactions; a single atomic UPDATE ... WHERE consumed + cost <= quota statement evaluates the check and applies the increment in one indivisible operation within the database engine, eliminating the race entirely.
// VULNERABLE — read-then-write token accounting; TOCTOU race on concurrent audits
// File: services/tokenBudget.js
async function consumeTokens(userId, tokensNeeded) {
// Step 1: READ current state
const { rows } = await db.query(
'SELECT consumed, quota FROM llm_budgets WHERE user_id = $1',
[userId]
);
const { consumed, quota } = rows[0];
// VULNERABILITY: two concurrent calls both read consumed=0, quota=100
// Both pass this check, both proceed to consume 100 tokens each
if (consumed + tokensNeeded > quota) {
throw new Error('LLM token budget exceeded');
}
// Step 2: WRITE — race window between read and write; two writes both succeed
await db.query(
'UPDATE llm_budgets SET consumed = consumed + $1 WHERE user_id = $2',
[tokensNeeded, userId]
);
return { consumed: consumed + tokensNeeded, quota };
}
Fix: Replace the two-step read-check-write sequence with a single atomic UPDATE ... SET consumed = consumed + $cost WHERE user_id = $id AND consumed + $cost <= quota statement. The database evaluates the guard condition and applies the increment atomically — no concurrent request can interleave between the check and the write. Inspect the number of rows affected: zero rows updated means the budget was insufficient and the request must be rejected with a 402/429 response. Never SELECT before UPDATE for quota enforcement.
// FIXED — atomic check-and-increment; no race window
// File: services/tokenBudget.js
async function consumeTokens(userId, tokensNeeded) {
// Single atomic UPDATE: guard and increment in one database operation
// The WHERE clause acts as the budget check — evaluated atomically
const result = await db.query(
`UPDATE llm_budgets
SET consumed = consumed + $1
WHERE user_id = $2
AND consumed + $1 <= quota
RETURNING consumed, quota`,
[tokensNeeded, userId]
);
// Zero rows updated means budget insufficient — no partial state written
if (result.rowCount === 0) {
throw new Error('LLM token budget exceeded');
}
const { consumed, quota } = result.rows[0];
return { consumed, quota };
// No SELECT before UPDATE; concurrent calls are serialised by DB engine
}
Compound attack chain: full quota bypass with concurrent overdraft
These four vulnerabilities compose into a single escalation chain that completely neutralises both the API quota system and the LLM token budget for a free-tier MCP registry account. The chain proceeds in three phases.
Phase 1 — Quota elimination (PRIVESC15-001 + PRIVESC15-002). The attacker first crafts a JWT with quotaLimit:999999 to dissolve the monthly API call ceiling. They supplement this with a rotating X-Forwarded-For header to defeat the IP-level rate limiter, granting themselves effectively unbounded request throughput for the billing period. At this point the account behaves like an uncapped enterprise subscriber from the perspective of all quota and rate limit middleware.
Phase 2 — History exfiltration (PRIVESC15-003). With rate limits neutralised, the attacker issues a single GET /audits?pageSize=10000 request to retrieve the platform's full audit result history for their account — or, if the registry operates a shared public audit pool, potentially records belonging to other tenants. This dump provides intelligence about skill behaviour, internal identifiers, and audit scheduling patterns useful for targeting subsequent phases.
Phase 3 — Token budget overdraft (PRIVESC15-004). The attacker fires 50 concurrent audit requests in the same millisecond window. Each request independently reads consumed=0, quota=100, passes the in-application budget check, and writes an increment. The final consumed value is 5,000 tokens on a 100-token budget. Because the platform's billing layer reads consumed from the same column, this overdraft may be recorded as legitimate usage — resulting in real infrastructure cost borne by the platform with no corresponding revenue from the free-tier account.
Chain severity: The combined chain allows a free-tier account to consume unlimited API calls, bypass IP rate limits, export full audit history, and overdraft the LLM token budget via concurrent requests — all without any cryptographic attack or elevated network access. Each individual fix is straightforward; the compounding effect underlines that quota enforcement must be audited as a system, not a collection of independent checks.
Detection with tree-sitter queries
The following tree-sitter queries target the two most high-value patterns from this advisory: JWT claim reads used directly as enforcement limits (PRIVESC15-001), and SELECT-then-UPDATE token accounting sequences that introduce a TOCTOU race (PRIVESC15-004). Run these against your MCP skill registry codebase during CI to surface regressions before deployment.
Query 1 — JWT claim used as enforcement limit. Matches any member expression that reads a property from a JWT-decoded object and assigns it to a variable whose name contains limit, quota, or cap. Findings warrant manual review to confirm the value is not subsequently cross-checked against a server-side plan config.
; tree-sitter query: JWT claim read used as enforcement limit (PRIVESC15-001)
; Matches: const quotaLimit = decoded.quotaLimit (and similar patterns)
(variable_declarator
name: (identifier) @limit-var
(#match? @limit-var "(quota|limit|cap|tier|plan)")
value: (member_expression
object: (identifier) @jwt-obj
(#match? @jwt-obj "(decoded|payload|claims|token)")
property: (property_identifier) @jwt-claim
)
) @finding
; Review each @finding: confirm enforcement value comes from server-side plan
; config, not from @jwt-claim. Flag any path where @jwt-claim directly gates
; a quota check without a planConfig database lookup in the same scope.
Query 2 — SELECT before UPDATE for numeric budget field. Matches await db.query(...) call pairs where a SELECT on a table whose name contains budget, quota, or usage precedes an UPDATE on the same table within the same function body. This is the structural signature of a TOCTOU race (PRIVESC15-004).
; tree-sitter query: SELECT-then-UPDATE budget race (PRIVESC15-004)
; Matches functions containing both a SELECT and an UPDATE on budget/quota tables
(function_declaration
body: (statement_block
(expression_statement
(await_expression
(call_expression
function: (member_expression property: (property_identifier) @fn1
(#eq? @fn1 "query"))
arguments: (arguments
(string) @select-sql
(#match? @select-sql "SELECT")
(#match? @select-sql "(budget|quota|usage|token)")
)
)
)
)
(expression_statement
(await_expression
(call_expression
function: (member_expression property: (property_identifier) @fn2
(#eq? @fn2 "query"))
arguments: (arguments
(string) @update-sql
(#match? @update-sql "UPDATE")
(#match? @update-sql "(budget|quota|usage|token)")
)
)
)
)
)
) @race-candidate
; Each @race-candidate is a potential TOCTOU race.
; Confirm fix: UPDATE WHERE consumed+cost <= quota with rowCount check;
; no preceding SELECT for the enforcement decision.
Summary
| ID | Severity | Surface | Root cause | Fix |
|---|---|---|---|---|
| PRIVESC15-001 | Critical | JWT middleware / quota enforcement | Monthly API call quota read from attacker-controlled quotaLimit JWT claim |
Fetch quota from server-side subscription plan config; JWT carries sub identity only |
| PRIVESC15-002 | High | Rate limit middleware / IP key derivation | Rate limit key derived from spoofable X-Forwarded-For header value |
Use req.socket.remoteAddress as IP key; add per-account rate limit fallback |
| PRIVESC15-003 | High | Audit results API / pagination | pageSize from req.query forwarded to LIMIT without plan-tier ceiling |
Cap pageSize server-side from plan config (100 free / 1000 pro); client value is a hint |
| PRIVESC15-004 | Critical | LLM token budget / concurrent audit requests | Non-atomic SELECT + UPDATE token accounting; TOCTOU race allows concurrent overdraft | Atomic UPDATE ... WHERE consumed+cost <= quota; check rowCount; no preceding SELECT |
Checklist for MCP skill registry operators: (1) Audit every JWT middleware for claims used as enforcement ceilings — replace with server-side plan config lookups. (2) Search your codebase for X-Forwarded-For in rate-limit key construction — replace with req.socket.remoteAddress and add account-level secondary limits. (3) Grep all paginated endpoints for req.query.pageSize passed directly to LIMIT — apply plan-tier caps before the query. (4) Audit all quota accounting code for read-then-write patterns — replace with atomic UPDATE ... WHERE and rowCount validation. Apply these checks in CI using the tree-sitter queries above to prevent regressions across the full SA-SKL-PRIVESC series.