Claude MCP skill privilege escalation — audit plan management and subscription enforcement — SA-SKL-PRIVESC9
Subscription enforcement is the revenue boundary of any SaaS product: when it fails, attackers gain paid features for free and billing data becomes unreliable. SA-SKL-PRIVESC9 covers four privilege escalation patterns in MCP skill registry audit plan management and subscription enforcement — a JWT payload plan field that bypasses Stripe subscription verification entirely, an audit count query scoped to userId rather than orgId that enables multi-account limit multiplication, a seat upgrade endpoint that writes the attacker-supplied seat count to the database before validating the Stripe charge response, and a free-tier depth check that trusts the request body instead of reading from the server-side plan configuration.
req.user.plan directly from the decoded JWT payload without querying the subscription record — attacker crafts a JWT with plan:"team" using the app's signing secret, bypassing Stripe verification entirely; full team plan features (SSO, policy export, 10 seats) become accessible for $0SELECT count(*) FROM audits WHERE userId=? does not join on subscription plan or orgId — attacker creates a second free account sharing the same orgId, runs audits from both; total audits equal 2× the per-user free limit at $0; with N accounts, N× the limitPATCH /api/subscription/seats missing server-side seat count validation — attacker sends {"seats":9999}; the internal seat_count table is updated to 9999 before the Stripe proration charge is validated; Stripe charge fails but seat count persistsdepth parameter from the request body instead of the server-side plan config — attacker POST /api/audits with {"repoUrl":"...","depth":"deep"} receives a full deep scan (LLM prompt-injection probing, SBOM analysis) on the free tier at $0Background: plan enforcement in MCP skill registry subscription flows
MCP skill registries gate their most expensive operations — deep LLM-assisted scans, policy report exports, SSO integration, additional seats — behind paid subscription tiers. Correctly enforcing these gates requires that every authorization decision reads plan entitlements from a server-side authoritative source (a subscription record in the database, confirmed against Stripe) rather than from client-supplied or JWT-cached data. When developers shortcut this by embedding plan information in the JWT or reading feature flags from the request body, they create privilege escalation paths that allow free-tier users to access team or enterprise features without payment.
PRIVESC9-001 represents the most severe class: the JWT itself becomes the authorization artifact. JWT signing secrets in Node.js applications are frequently recoverable — through environment variable leaks, misconfigured secret managers, or disclosure in error responses — and once known, an attacker can self-issue tokens granting any plan level. PRIVESC9-002 exploits a subtler assumption: that "per-user" limits adequately constrain per-organization consumption. When orgId-level aggregation is absent, limit bypass scales linearly with the number of throwaway accounts created. PRIVESC9-003 and PRIVESC9-004 both stem from optimistic write ordering: state is committed before the external payment or configuration source confirms the authorization, leaving a window (and in PRIVESC9-003, a persistent state) that the attacker exploits.
Related patterns: SA-SKL-PRIVESC8 (RBAC enforcement privilege escalation), SA-SKL-INJECTION16 (command injection in package build pipeline), SA-SKL-CORS26 (CORS on audit submission and result delivery).
PRIVESC9-001 — CRITICAL — Plan gate reads JWT payload plan field without server-side subscription verification
The plan authorization middleware reads req.user.plan directly from the decoded JWT payload. The JWT is verified for signature validity using jsonwebtoken.verify(), confirming it was signed with the application's secret — but the plan field inside the payload is never cross-checked against the subscription record in the database. The only server-side check is JWT signature validity; the plan level embedded in the token is trusted as authoritative.
An attacker who obtains the application's JWT signing secret (via environment variable disclosure in a 500 error, a misconfigured secrets manager, a leaked .env file in a public repository, or brute-force of a short secret) can self-issue a token with any plan value. Setting plan:"team" in the payload grants access to team-tier features: SSO configuration, policy export, 10-seat provisioning, and advanced audit depth. No Stripe charge occurs and no subscription record is created — the payment system is bypassed entirely. The escalation requires only the signing secret, not any other credential; it persists for the lifetime of the self-issued token.
The fix is to remove all plan-level authorization logic from the JWT payload. Plan entitlements must be read from the subscription record in the database on every authorization check. The JWT should encode only the user identity (userId) and session metadata (issued-at, expiry, jti for revocation); all role and plan data must be fetched from the authoritative subscription store. If per-request database reads are unacceptable for latency reasons, a short-lived server-side cache (keyed by userId, TTL 60 seconds) is appropriate — but the cache must be invalidated immediately on subscription change events from Stripe webhooks.
// VULNERABLE — PRIVESC9-001
// middleware/requirePlan.js
const jwt = require('jsonwebtoken');
// BUG: plan check trusts req.user.plan from JWT payload
// If attacker obtains JWT_SECRET they self-issue token with plan:"team"
// No database query verifies the subscription record — Stripe bypassed entirely
function requirePlan(minPlan) {
const PLAN_ORDER = { free: 0, pro: 1, team: 2, enterprise: 3 };
return (req, res, next) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ error: 'Unauthorized' });
let decoded;
try {
decoded = jwt.verify(token, process.env.JWT_SECRET);
} catch {
return res.status(401).json({ error: 'Invalid token' });
}
// BUG: plan comes directly from the JWT payload — never verified against DB
req.user = decoded;
const userPlanLevel = PLAN_ORDER[req.user.plan] ?? 0;
const requiredLevel = PLAN_ORDER[minPlan] ?? 0;
if (userPlanLevel < requiredLevel) {
return res.status(403).json({ error: `Plan ${minPlan} required` });
}
next();
};
}
// Route gated on team plan — bypassed by crafting JWT with plan:"team"
app.get('/api/policy/export',
requirePlan('team'),
async (req, res) => {
const report = await PolicyExporter.generate(req.user.orgId);
res.json(report);
}
);
// FIXED — PRIVESC9-001
// middleware/requirePlan.js
const jwt = require('jsonwebtoken');
const { getSubscription } = require('../db/subscriptions');
const PLAN_ORDER = { free: 0, pro: 1, team: 2, enterprise: 3 };
// Cache subscription lookups for 60s to avoid per-request DB round-trips
// Cache invalidated on Stripe webhook events (subscription.updated, etc.)
const subscriptionCache = new Map(); // userId → { plan, expiresAt }
async function fetchPlan(userId) {
const cached = subscriptionCache.get(userId);
if (cached && cached.expiresAt > Date.now()) return cached.plan;
// Authoritative source: subscription record in DB, confirmed against Stripe status
const sub = await getSubscription(userId);
const plan = (sub?.stripeStatus === 'active') ? (sub.plan ?? 'free') : 'free';
subscriptionCache.set(userId, { plan, expiresAt: Date.now() + 60_000 });
return plan;
}
// Called by Stripe webhook handler to invalidate cache on subscription change
function invalidateSubscriptionCache(userId) {
subscriptionCache.delete(userId);
}
function requirePlan(minPlan) {
return async (req, res, next) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ error: 'Unauthorized' });
let decoded;
try {
decoded = jwt.verify(token, process.env.JWT_SECRET);
} catch {
return res.status(401).json({ error: 'Invalid token' });
}
// JWT carries only userId — plan fetched from authoritative DB record
req.user = { id: decoded.sub, orgId: decoded.orgId };
const activePlan = await fetchPlan(req.user.id);
req.user.plan = activePlan; // set from DB, not from JWT
const userPlanLevel = PLAN_ORDER[activePlan] ?? 0;
const requiredLevel = PLAN_ORDER[minPlan] ?? 0;
if (userPlanLevel < requiredLevel) {
logger.warn('PRIVESC9-001: plan gate denied', {
userId: req.user.id, activePlan, requiredPlan: minPlan,
});
return res.status(403).json({ error: `Plan ${minPlan} required` });
}
next();
};
}
module.exports = { requirePlan, invalidateSubscriptionCache };
PRIVESC9-001 impact: Complete subscription bypass — an attacker with the JWT signing secret self-issues tokens granting any plan level, accessing SSO configuration, policy export, 10-seat provisioning, and deep audit scans for $0. JWT signing secrets are frequently the highest-value secret in a Node.js application and appear in a disproportionate share of environment variable leaks, leaked .env files, and misconfigured secrets managers. SkillAudit detects this pattern by identifying plan authorization middleware that reads from req.user fields populated directly from JWT decode output without an intervening database subscription query.
PRIVESC9-002 — HIGH — Audit count check scoped to userId enables multi-account limit multiplication
The free-tier audit gate checks whether the requesting user has exhausted their monthly audit allowance using SELECT count(*) FROM audits WHERE userId = ?. This query is scoped exclusively to the individual user's row-level identifier. When a user creates a second free account under the same organization (or even under a different organization — the per-orgId aggregate is never checked), the count for that new userId starts at zero, giving the attacker a fresh allocation.
An attacker creates N free-tier accounts, each with a unique email address (disposable addresses are sufficient). Each account shares the same payment context: $0 spent. Each account receives the full per-user free-tier audit allocation — typically 5 to 10 audits per month. The attacker can run N × the per-user limit across their controlled accounts, with the aggregate cost remaining $0. At scale, this means significant LLM compute and SBOM analysis is consumed for free, directly increasing SkillAudit's operational cost per attacker-controlled organization.
The correct fix is to enforce limits at the organization level in addition to (or instead of) the user level. The audit count query should aggregate across all users belonging to the same orgId. For free accounts without an organization, the per-email or per-verified-domain limit should apply. Rate limiting by IP address provides an additional control for account creation velocity. A secondary control is email domain verification for organization membership — accounts sharing an orgId must share a verified email domain, raising the cost of multi-account attacks.
// VULNERABLE — PRIVESC9-002
// routes/audits.js
// BUG: limit enforced per-userId only — attacker creates second account,
// count resets to 0, doubles free-tier audit budget at $0
const FREE_TIER_MONTHLY_LIMIT = 5;
app.post('/api/audits', authenticate, async (req, res) => {
// Count only the requesting user's audits — does not aggregate by org
const [{ count }] = await db.query(
'SELECT count(*) AS count FROM audits WHERE userId = ? AND createdAt >= ?',
[req.user.id, startOfMonth()]
);
if (count >= FREE_TIER_MONTHLY_LIMIT && req.user.plan === 'free') {
return res.status(402).json({ error: 'Free tier limit reached' });
}
const audit = await AuditQueue.enqueue({
userId: req.user.id,
repoUrl: req.body.repoUrl,
});
res.status(202).json(audit);
});
// FIXED — PRIVESC9-002
// routes/audits.js
const FREE_TIER_MONTHLY_LIMIT = 5;
app.post('/api/audits', authenticate, async (req, res) => {
// Fetch the user's active plan from server-side subscription record
const sub = await getSubscription(req.user.id);
const plan = sub?.stripeStatus === 'active' ? sub.plan : 'free';
if (plan !== 'free') {
// Paid plans: enforce per-org seat/audit quotas via Stripe entitlements
// No per-user count check needed here — handled by plan entitlement record
return proceedWithAudit(req, res, plan);
}
// For free tier: aggregate count at org level, not user level
// orgId is set at registration and cannot be changed without re-verification
const orgId = req.user.orgId;
const [{ orgCount }] = await db.query(
`SELECT count(*) AS orgCount
FROM audits a
JOIN users u ON u.id = a.userId
WHERE u.orgId = ?
AND a.createdAt >= ?`,
[orgId, startOfMonth()]
);
if (orgCount >= FREE_TIER_MONTHLY_LIMIT) {
logger.warn('PRIVESC9-002: org-level free tier limit reached', {
orgId, orgCount, userId: req.user.id,
});
return res.status(402).json({
error: 'Free tier monthly limit reached for your organization',
orgCount,
limit: FREE_TIER_MONTHLY_LIMIT,
});
}
return proceedWithAudit(req, res, plan);
});
async function proceedWithAudit(req, res, plan) {
const audit = await AuditQueue.enqueue({
userId: req.user.id,
orgId: req.user.orgId,
repoUrl: req.body.repoUrl,
plan,
});
res.status(202).json(audit);
}
PRIVESC9-002 impact: Free-tier audit limit bypass scales linearly with the number of attacker-controlled accounts — N accounts yield N × the per-user monthly allocation at $0. Each extra audit consumes LLM API credits, compute, and SBOM analysis resources that SkillAudit pays for. At 10 free audits per account and $0.80 LLM cost per audit, a single attacker with 50 accounts consumes $400/month in compute for free. SkillAudit detects this by identifying audit count queries that filter only on userId and do not join or aggregate on orgId for plan-enforcement decisions.
PRIVESC9-003 — HIGH — Seat upgrade endpoint updates seat count before Stripe charge validation
The team plan seat upgrade endpoint PATCH /api/subscription/seats allows an authenticated team plan user to increase their seat allocation. The implementation sends the proration charge to Stripe and simultaneously (before awaiting the Stripe response) writes the requested seat count to the internal seat_count table. When the Stripe charge fails — because the card is declined, the billing limit is exceeded, or the attacker submits a request for 9999 seats knowing the charge will be refused — the internal seat count has already been persisted at the attacker-supplied value.
The resulting state is a team plan subscription showing 9999 seats in the application database while Stripe records the last successful seat count at the original value. This discrepancy is exploitable: the application enforces seat limits by reading from its internal seat_count table (which now shows 9999), so the attacker can invite 9999 users to their organization, granting each of them team-plan access. The Stripe billing record reflects none of these seats. The divergence persists until a reconciliation job detects and corrects it — a job that most implementations run infrequently (daily or weekly) if at all.
The fix is to adopt a strict write-after-confirm pattern: never update the internal seat count until the Stripe charge has been confirmed as successful. The Stripe charge result must be awaited synchronously before any database write. Additionally, the requested seat count must be validated against a server-side maximum (the plan's seat ceiling, e.g., 100 for team plan) before the Stripe call is made — an attacker should never be able to submit 9999 as a valid seat count regardless of payment outcome.
// VULNERABLE — PRIVESC9-003
// routes/subscription.js
// BUG: seat_count written to DB before Stripe charge is awaited
// If charge fails (declined card, billing limit), DB still shows 9999 seats
app.patch('/api/subscription/seats', authenticate, requirePlan('team'), async (req, res) => {
const { seats } = req.body;
// BUG: no server-side validation of seats value — 9999 accepted
const sub = await Subscription.findOne({ userId: req.user.id });
// BUG: DB updated BEFORE Stripe response arrives
await db.query(
'UPDATE seat_count SET count = ? WHERE orgId = ?',
[seats, req.user.orgId]
);
// Stripe charge fires after DB write — if this fails, DB is already corrupted
try {
await stripe.subscriptions.update(sub.stripeSubId, {
items: [{ id: sub.stripePriceItemId, quantity: seats }],
proration_behavior: 'always_invoice',
});
} catch (err) {
// Stripe failed — but DB already shows seats=9999
// Error logged but seat_count not rolled back
logger.error('Stripe seat update failed', { err: err.message });
return res.status(402).json({ error: 'Payment failed' });
}
res.json({ seats });
});
// FIXED — PRIVESC9-003
// routes/subscription.js
const PLAN_MAX_SEATS = { team: 100, enterprise: 1000 };
app.patch('/api/subscription/seats', authenticate, requirePlan('team'), async (req, res) => {
const { seats } = req.body;
// Validate seat count against server-side plan ceiling before any external call
const maxSeats = PLAN_MAX_SEATS[req.user.plan] ?? 10;
if (!Number.isInteger(seats) || seats < 1 || seats > maxSeats) {
return res.status(400).json({
error: `Seat count must be between 1 and ${maxSeats}`,
});
}
const sub = await Subscription.findOne({ userId: req.user.id });
if (!sub) return res.status(404).json({ error: 'Subscription not found' });
// Confirm current seat count — prevent downgrade below active user count
const [{ activeUsers }] = await db.query(
'SELECT count(*) AS activeUsers FROM org_members WHERE orgId = ? AND status = ?',
[req.user.orgId, 'active']
);
if (seats < activeUsers) {
return res.status(400).json({
error: `Cannot set seats below active member count (${activeUsers})`,
});
}
// Stripe charge FIRST — await confirmation before any DB write
let stripeResult;
try {
stripeResult = await stripe.subscriptions.update(sub.stripeSubId, {
items: [{ id: sub.stripePriceItemId, quantity: seats }],
proration_behavior: 'always_invoice',
});
} catch (err) {
logger.warn('PRIVESC9-003: Stripe seat update failed — no DB write', {
userId: req.user.id, requestedSeats: seats, err: err.message,
});
return res.status(402).json({ error: 'Payment failed — seat count not changed' });
}
// Write to DB only after Stripe confirms the charge
await db.query(
'UPDATE seat_count SET count = ?, stripeQuantity = ?, updatedAt = NOW() WHERE orgId = ?',
[seats, stripeResult.items.data[0].quantity, req.user.orgId]
);
res.json({ seats, stripeQuantity: stripeResult.items.data[0].quantity });
});
PRIVESC9-003 impact: Persistent internal state corruption — the internal seat count is set to the attacker-supplied value regardless of payment outcome, allowing the attacker to invite an arbitrary number of users to their organization at team-plan access level for $0. The divergence between Stripe billing (original seat count) and the application database (9999 seats) persists until a reconciliation job corrects it. If no reconciliation job exists, the corrupted state is permanent. SkillAudit detects this by identifying database write operations on seat or quota fields that are not gated on an awaited Stripe API response within the same transaction or promise chain.
PRIVESC9-004 — HIGH — Free-tier audit depth check reads depth parameter from request body
The audit submission endpoint POST /api/audits accepts a depth parameter in the request body that controls the scan depth: "shallow" performs a fast static analysis pass, while "deep" triggers LLM prompt-injection probing, full dependency SBOM analysis, and secrets scanning. The free tier is documented as restricted to shallow scans; deep scans are a paid feature. The enforcement logic reads the depth value directly from req.body.depth and checks whether it is "deep" before applying the plan gate. Because the check reads from the request body, an attacker on the free tier simply sends {"depth":"deep"} in the POST body and receives the full deep scan.
The fundamental error is that feature entitlements must never be derived from client-supplied input. The depth level permitted for a given request must be read from the server-side plan configuration — a static mapping from plan name to maximum allowed depth — and the client's requested depth must be clamped to the plan's ceiling. If the client sends "deep" and their plan permits only "shallow", the server ignores the client value and applies "shallow". The client should never be able to escalate their own feature level by modifying a request field.
This pattern — reading capability parameters from request body rather than from server-side configuration — appears in many forms beyond scan depth: report format, export type, model selection, rate limit tier, and timeout values. Each represents a client-controllable privilege escalation if the server does not cap the value against the user's entitlement. SkillAudit's static analysis flags all patterns where a capability-gating parameter is passed through from req.body or req.query to a downstream function without an intervening plan-based ceiling check.
// VULNERABLE — PRIVESC9-004
// routes/audits.js
// BUG: depth read from request body and checked against plan — but attacker
// controls req.body.depth; sending depth:"deep" bypasses free-tier gate
app.post('/api/audits', authenticate, async (req, res) => {
const { repoUrl, depth } = req.body;
// BUG: plan gate checks the attacker-controlled depth value
// Attacker on free plan sends depth:"deep" → condition is true → 403 never fires
if (depth === 'deep' && req.user.plan === 'free') {
return res.status(403).json({ error: 'Deep scan requires a paid plan' });
}
// depth passed through unchecked — attacker gets deep scan for free
const audit = await AuditQueue.enqueue({
userId: req.user.id,
repoUrl,
depth: depth || 'shallow',
});
res.status(202).json(audit);
});
// FIXED — PRIVESC9-004
// routes/audits.js
// Server-side plan configuration — single source of truth for feature entitlements
// Never read from req.body or req.query for capability gating
const PLAN_MAX_DEPTH = {
free: 'shallow',
pro: 'standard',
team: 'deep',
enterprise: 'deep',
};
const DEPTH_ORDER = { shallow: 0, standard: 1, deep: 2 };
app.post('/api/audits', authenticate, async (req, res) => {
const { repoUrl, depth: requestedDepth } = req.body;
// Fetch plan from authoritative subscription record (not JWT payload)
const sub = await getSubscription(req.user.id);
const plan = sub?.stripeStatus === 'active' ? sub.plan : 'free';
// Server-side ceiling: clamp requested depth to plan maximum
const maxDepth = PLAN_MAX_DEPTH[plan] ?? 'shallow';
const requestedLevel = DEPTH_ORDER[requestedDepth] ?? 0;
const maxLevel = DEPTH_ORDER[maxDepth];
// If client requested more than their plan allows, silently cap (or reject)
const effectiveDepth = requestedLevel <= maxLevel
? (requestedDepth || 'shallow')
: maxDepth;
if (requestedDepth && requestedLevel > maxLevel) {
logger.warn('PRIVESC9-004: depth escalation attempt blocked', {
userId: req.user.id, plan, requestedDepth, effectiveDepth,
});
// Return 403 rather than silently downgrading, to signal the gate clearly
return res.status(403).json({
error: `Depth "${requestedDepth}" requires a plan with ${requestedDepth} scan access`,
yourPlan: plan,
maxDepth,
});
}
const audit = await AuditQueue.enqueue({
userId: req.user.id,
orgId: req.user.orgId,
repoUrl,
depth: effectiveDepth,
plan,
});
res.status(202).json(audit);
});
PRIVESC9-004 impact: Free-tier users receive full deep scan capability — LLM prompt-injection probing, SBOM analysis, and secrets scanning — at $0. Each deep scan consumes significantly more LLM API credits than a shallow scan (typically 10–20× more tokens for a medium-sized repository). At scale, unrestricted deep scans from free-tier users represent substantial uncompensated compute cost. Beyond direct cost, deep scans also expose more of the analysis pipeline to attacker-controlled input (the repository contents), increasing the attack surface for prompt injection and SSRF via dependency resolution. SkillAudit detects this by flagging audit submission handlers that pass a capability parameter from req.body directly to the queue enqueue call without an intervening server-side plan ceiling check.
Detection with SkillAudit
SkillAudit's static analysis scans subscription enforcement and plan management modules for all four SA-SKL-PRIVESC9 patterns. For PRIVESC9-001 it identifies plan gate middleware that reads from req.user.plan or any field populated directly from a decoded JWT without a database subscription query in the same middleware chain. For PRIVESC9-002 it identifies audit or usage count queries that filter on userId alone without a join or subquery on orgId. For PRIVESC9-003 it identifies database write operations on seat or quota fields that precede an awaited Stripe API call in the same code path. For PRIVESC9-004 it identifies capability-gating parameters read from req.body or req.query that are compared against plan values without a server-side ceiling applied from a static plan configuration.
| Finding | Severity | Root cause | Fix |
|---|---|---|---|
| PRIVESC9-001 | CRITICAL | Plan gate reads JWT payload plan field without server-side subscription query; attacker self-issues JWT with team plan using obtained signing secret | Remove plan from JWT; fetch plan from DB subscription record on every authorization check; invalidate cache on Stripe webhook events |
| PRIVESC9-002 | HIGH | Audit count query scoped to userId only; second account with same orgId resets count to zero; N accounts yield N× free limit | Aggregate audit count at orgId level; verify org membership by domain; rate-limit account creation by IP |
| PRIVESC9-003 | HIGH | Seat count written to DB before Stripe charge awaited; Stripe failure leaves DB showing attacker-supplied 9999 seats | Await Stripe confirmation before any DB write; validate seat count against server-side plan ceiling before Stripe call |
| PRIVESC9-004 | HIGH | Audit depth read from req.body.depth; free-tier gate checks attacker-controlled value; sending depth:deep bypasses the gate | Read max depth from server-side plan config; cap requested depth against plan ceiling; never trust client-supplied capability values |
Related findings: SA-SKL-PRIVESC8 (RBAC enforcement privilege escalation), SA-SKL-INJECTION16 (command injection in package build pipeline), SA-SKL-CORS26 (CORS on audit submission and result delivery).
SkillAudit scans your MCP skill registry for all SA-SKL-PRIVESC9 patterns — JWT plan field bypasses, per-user limit multiplication, optimistic seat count writes, and request body capability escalation — and delivers a prioritized fix report in minutes.
Join the waitlist →