Claude MCP skill privilege escalation via plan tier bypass and feature flag confusion — SA-SKL-PRIVESC2
Billing and feature-gating systems in MCP skills are a frequent source of privilege escalation because they mix authoritative data sources (the database) with derived or cached values (JWT claims, Redis flags, request headers) that are cheaper to read but easier to manipulate. The four SA-SKL-PRIVESC2 patterns cover stale JWT plan claims that persist after downgrades, quota limits derived from attacker-controlled request headers, JavaScript type coercion silently granting unlimited trials, and Redis cache eviction silently elevating plan tier — all exploitable without any special access beyond a valid account.
Why billing enforcement is a privilege escalation target
MCP skill platforms gate valuable functionality — unlimited audits, CI webhooks, SSO, private repository access — behind paid plan tiers. The plan tier check is on the hot path of every gated request, so developers optimise it: read the plan from the JWT (already in memory) rather than querying the database on every call. This optimisation creates a window where the token-encoded plan diverges from the database-encoded plan after a downgrade, cancellation, or refund. An attacker who was on a team plan, got refunded, but still holds an unexpired JWT can continue to use team features for the remaining token lifetime.
The same performance pressure pushes developers toward Redis-cached feature flags, which are fast to read but can be evicted under memory pressure, and toward trusting proxy-forwarded headers for plan tier — which are spoofable at the HTTP layer. SkillAudit's SA-SKL-PRIVESC2 rule set detects each of these patterns through data-flow analysis, flagging cases where the plan tier authorising a privileged action was read from a source other than the database record for the authenticated user.
X-Plan-Tier request header without signature validation; attacker sends X-Plan-Tier: team to bypass quota enforcementnull >= 0 evaluates to true in JavaScript; trialEnd: null (no trial record) treated as unlimited free trial via type coercionundefined; missing key falls through to attacker-writable default, silently granting team planPRIVESC2-001 — Stale JWT plan claim persists after plan downgrade
JWTs are signed but not encrypted, and they are issued at login time with a TTL of several hours or a day. If the platform encodes the user's plan tier in the JWT payload at issuance time, the token-encoded plan reflects the plan at login, not the plan now. When a user is downgraded from team to free (via cancellation, refund, or admin action), their existing JWT still contains "plan": "team". Any endpoint that reads the plan from req.user.plan (decoded JWT) rather than re-fetching from the database will continue to serve team-gated features until the token expires. With standard 24-hour JWT TTLs, an attacker who downgrades their own account after getting a refund has 24 hours of free team access.
The fix is to remove the plan from the JWT entirely and re-fetch it from the database on every request that checks the plan. The JWT should contain only the user ID; the plan is authoritative in the database, not in the token. For performance, cache the plan in a short-TTL Redis key (plan:userId with 60-second TTL) so the DB is not hit on every single request, but invalidate the cache immediately on plan change.
// VULNERABLE — plan read from JWT claim; stale after downgrade
import jwt from 'jsonwebtoken';
import express from 'express';
const router = express.Router();
function requirePlan(minPlan: 'free' | 'pro' | 'team') {
const PLAN_RANK = { free: 0, pro: 1, team: 2 };
return (req, res, next) => {
// VULNERABLE: req.user.plan is decoded from JWT
// JWT was issued at login time — may reflect old (higher) plan tier
// attacker gets refund on day 1; JWT still says "team" until expiry (day 2)
if (PLAN_RANK[req.user.plan] >= PLAN_RANK[minPlan]) {
return next();
}
res.status(403).json({ error: 'Plan upgrade required' });
};
}
router.post('/api/audits/ci-webhook', requirePlan('pro'), async (req, res) => {
// pro+ only feature — but attacker retains access via stale JWT
const webhook = await createCiWebhook(req.user.id, req.body);
res.json(webhook);
});
// FIXED — re-fetch plan from DB on every gated request; invalidate cache on change
import { db } from './db.js';
import { redis } from './redis.js';
async function getUserPlan(userId: string): Promise<'free' | 'pro' | 'team'> {
// 60-second cache — fast but bounded; invalidated on plan change via redis.del()
const cached = await redis.get(`plan:${userId}`);
if (cached) return cached as 'free' | 'pro' | 'team';
const user = await db.query('SELECT plan FROM users WHERE id = ?', [userId]);
if (!user) return 'free';
await redis.setex(`plan:${userId}`, 60, user.plan);
return user.plan;
}
function requirePlan(minPlan: 'free' | 'pro' | 'team') {
const PLAN_RANK = { free: 0, pro: 1, team: 2 };
return async (req, res, next) => {
// DB (or short-TTL cache) — never JWT claim
const currentPlan = await getUserPlan(req.user.id);
if (PLAN_RANK[currentPlan] >= PLAN_RANK[minPlan]) {
return next();
}
res.status(403).json({ error: 'Plan upgrade required' });
};
}
// On plan change, invalidate the cache immediately so next request re-fetches
async function changePlan(userId: string, newPlan: string) {
await db.query('UPDATE users SET plan = ? WHERE id = ?', [newPlan, userId]);
await redis.del(`plan:${userId}`); // force next request to re-read from DB
}
PRIVESC2-002 — Usage quota limit read from X-Plan-Tier request header
Some MCP skill platforms derive the per-request quota limit from a header added by an upstream proxy or load balancer — something like X-Plan-Tier: pro injected by an API gateway that has already authenticated the user and determined their plan. This architecture works when the gateway is the only entity that can set the header, but breaks if the application also reads the header from direct HTTP requests without verifying that it was set by a trusted gateway. An attacker who calls the API directly (bypassing the gateway) or spoofs the header through a misconfigured proxy can set X-Plan-Tier: team and have the quota enforcement code read the attacker-supplied limit instead of the authoritative one.
The fix is to never derive security-relevant values from request headers unless those headers are signed with a shared secret or the application's network architecture guarantees they cannot be set by external callers. For plan tier specifically, the value must come from the authenticated user record in the database.
// VULNERABLE — quota limit read from X-Plan-Tier header
const PLAN_LIMITS = { free: 3, pro: 100, team: Infinity };
async function checkRateLimit(req, res, next) {
// VULNERABLE: plan tier read from request header — attacker can set X-Plan-Tier: team
const planTier = req.headers['x-plan-tier'] as string || 'free';
const limit = PLAN_LIMITS[planTier] ?? PLAN_LIMITS.free;
const count = await redis.incr(`audits:${req.user.id}:${currentMonth()}`);
if (count > limit) {
return res.status(429).json({ error: 'Monthly audit limit reached' });
}
next();
}
// FIXED — plan read from DB; header never touches authorization logic
const PLAN_LIMITS = { free: 3, pro: 100, team: Infinity };
async function checkRateLimit(req, res, next) {
// Plan comes from getUserPlan() which reads DB, never from headers
const plan = await getUserPlan(req.user.id); // from PRIVESC2-001 fix
const limit = PLAN_LIMITS[plan] ?? PLAN_LIMITS.free;
const key = `audits:${req.user.id}:${currentMonth()}`;
const count = await redis.incr(key);
// Set TTL on first increment so the counter expires at month end
if (count === 1) await redis.expire(key, 32 * 24 * 3600);
if (count > limit) {
return res.status(429).json({ error: 'Monthly audit limit reached', plan, limit });
}
next();
}
PRIVESC2-003 — null trial date coerced to unlimited trial via JavaScript type coercion
Free trial enforcement typically checks whether the trial expiry date has passed: if (user.trialEnd >= Date.now()) { grantTrialAccess(); }. When a user has no trial record in the database, the ORM returns null for trialEnd. In JavaScript, null >= 0 evaluates to true — because null is coerced to 0 for numeric comparison, and 0 >= 0 is true. If Date.now() is a positive number (it always is — Unix epoch in milliseconds), and null coerces to 0, then null >= Date.now() evaluates to false — which is safe. But null >= 0 before date comparison, used as a "is trial active" pre-check, evaluates to true, granting trial access. The exact coercion behaviour depends on how the check is written; this pattern appears in several variations in real production code.
// VULNERABLE — null trialEnd coerced to unlimited trial access
async function getTrialStatus(userId: string) {
const user = await db.query('SELECT trial_end FROM users WHERE id = ?', [userId]);
// VULNERABLE: user.trial_end is null when no trial record exists
// JavaScript: null >= 0 evaluates to true (null coerces to 0 for numeric comparison)
// This grants trial access to ALL users, including those who never had a trial
if (user.trial_end >= 0) {
const isActive = user.trial_end >= Date.now();
return { hasTrial: true, isActive };
}
return { hasTrial: false, isActive: false };
}
// FIXED — explicit null check before any date comparison
async function getTrialStatus(userId: string) {
const user = await db.query('SELECT trial_end FROM users WHERE id = ?', [userId]);
// Explicit null check — null means no trial record, not an expired trial
// Never rely on JavaScript numeric coercion for security decisions
if (user.trial_end === null || user.trial_end === undefined) {
return { hasTrial: false, isActive: false };
}
const trialEndMs = Number(user.trial_end); // ensure numeric; throws on NaN
if (!Number.isFinite(trialEndMs)) {
return { hasTrial: false, isActive: false };
}
const isActive = trialEndMs >= Date.now();
return { hasTrial: true, isActive };
}
PRIVESC2-004 — Redis feature flag eviction silently grants team plan
Per-tenant feature flags stored in Redis provide fast, centrally-updateable feature gates. The pattern is: redis.set(`ff:team:${tenantId}`, '1') for team tenants; free tenants have no key. On each gated request, the code reads the key and checks if it equals '1'. Under Redis memory pressure, LRU eviction can silently delete any key that has not been accessed recently. When the feature flag key is evicted, the subsequent redis.get() returns null. If the application treats null as "free" (the safe default), no escalation occurs. But if the code has been structured so that the absence of a key triggers a database re-read which then writes a default back to Redis, an attacker who has previously written a team-granting default key (via a race, via SETEX without TTL, or via a misconfigured admin endpoint) will have that default read and cached as the team flag for the evicted tenant.
// VULNERABLE — Redis eviction + attacker-writable default key enables escalation async function hasTeamFeature(tenantId: string): Promise{ const flag = await redis.get(`ff:team:${tenantId}`); if (flag !== null) { return flag === '1'; } // Key evicted — read from DB and re-cache const tenant = await db.query('SELECT plan FROM tenants WHERE id = ?', [tenantId]); const isTeam = tenant?.plan === 'team'; // VULNERABLE: attacker calls SETEX ff:team:default '1' (no TTL, never evicted) // when flag === null and tenantId-specific key is absent, this fallback // reads the attacker-written default key instead of the DB record const defaultFlag = await redis.get('ff:team:default'); if (defaultFlag === '1') return true; // attacker-controlled escalation await redis.setex(`ff:team:${tenantId}`, 3600, isTeam ? '1' : '0'); return isTeam; }
// FIXED — Redis eviction falls through to DB only; no attacker-readable defaults async function hasTeamFeature(tenantId: string): Promise{ const flag = await redis.get(`ff:team:${tenantId}`); if (flag !== null) { // Explicit boolean parse — only '1' is truthy; missing, '0', or null = false return flag === '1'; } // Key evicted — re-fetch from authoritative DB source only const tenant = await db.query('SELECT plan FROM tenants WHERE id = ?', [tenantId]); const isTeam = tenant?.plan === 'team'; // Re-cache with 5-minute TTL; no fallback to any default key await redis.setex(`ff:team:${tenantId}`, 300, isTeam ? '1' : '0'); return isTeam; } // Admin-only endpoint to change plan MUST invalidate the Redis flag async function setTenantPlan(tenantId: string, newPlan: string) { await db.query('UPDATE tenants SET plan = ? WHERE id = ?', [newPlan, tenantId]); // Flush both the specific key and any stale cache entries await redis.del(`ff:team:${tenantId}`); await redis.del(`plan:${tenantId}`); // from PRIVESC2-001 fix }
Detection with SkillAudit
SkillAudit's SA-SKL-PRIVESC2 rule set detects plan-tier privilege escalation through data-flow analysis. The static pass traces plan tier values from their source (JWT decode, request header, Redis get, database query) to their use in plan-gating conditionals, flagging any path where the plan originates from a source other than a database query on the authenticated user record. The null-coercion pattern (PRIVESC2-003) is detected by looking for numeric comparisons on ORM result fields that can return null without an explicit null guard. See also SA-SKL-PRIVESC1 for role-confusion patterns in JWT claims and multi-tenant row isolation bypasses.
Run SA-SKL-PRIVESC2 on your skill: Paste your MCP skill's GitHub URL at skillaudit.dev to get a full scan. The free tier covers public repositories and returns a shareable security badge.
| Finding | Severity | Vulnerable pattern | Fix |
|---|---|---|---|
PRIVESC2-001 | Critical | JWT plan claim read without DB re-fetch; stale team claim persists after downgrade for full token TTL | Remove plan from JWT; re-fetch from DB with 60s Redis cache; invalidate cache on plan change |
PRIVESC2-002 | Critical | X-Plan-Tier request header controls quota limit; attacker sets header to bypass monthly cap | Derive plan from getUserPlan(userId) — DB-sourced — never from request headers |
PRIVESC2-003 | High | null >= 0 evaluates to true; trialEnd: null (no trial) grants unlimited trial access via type coercion | Explicit null check before date comparison; null means no trial, not expired trial |
PRIVESC2-004 | High | Redis feature flag eviction silently falls through to attacker-writable default key granting team plan | Missing key re-fetches from DB only; no default key fallback; plan changes flush Redis immediately |