Claude MCP skill privilege escalation — admin console and system configuration endpoints

SA-SKL-PRIVESC18 documents four privilege escalation vulnerabilities in MCP skill registry admin console and system configuration endpoints. Reading the admin role from a JWT claim allows any user to forge admin access by crafting a token with role:'system_admin'; the system configuration PATCH endpoint is missing an admin role check, allowing any authenticated user to disable security scanners or switch the LLM model; the user impersonation endpoint creates sessions without writing an audit log entry, leaving no trace of admin account abuse; and the admin metrics endpoint serves revenue, scan volume, and infrastructure health data without any authentication.

Critical PRIVESC18-001 — admin console reads role from JWT role claim; attacker crafts JWT with role:'system_admin' bypassing all admin checks without needing a compromised admin account
High PRIVESC18-002 — system configuration PATCH /api/admin/config missing admin role verification; any authenticated user modifies system-wide scanner config — disabling SSRF scanner, enabling debug output, or changing the LLM model for all organizations
High PRIVESC18-003 — admin user impersonation POST /api/admin/impersonate/:userId creates impersonation session without writing an audit log entry; attacker with compromised admin account impersonates any user with no audit trail
High PRIVESC18-004 — admin metrics endpoint GET /api/admin/metrics requires no authentication; any network-reachable client reads MRR, churn, plan distribution, scan volumes, and infrastructure health data

PRIVESC18-001 (Critical): JWT role claim bypass grants attacker system_admin access without credentials

JWTs are designed to carry claims that the issuing server vouches for. The JWT signature verifies that the token was issued by a trusted party — it does not prevent the holder from reading or attempting to forge claims if the signing key is known or if claim validation is performed by the client rather than the server. When an MCP skill registry reads the admin role from the JWT role claim directly in the authorization middleware rather than fetching the user's role from the database, the authorization boundary shifts to whoever controls JWT issuance.

If the registry allows users to supply their own JWTs (e.g., through a "bring your own API key" feature, service account tokens, or integration tokens that are signed server-side but whose payload content is derived from user input), an attacker can include "role": "system_admin" in the claims payload. The middleware trusts this claim and grants admin access. Even in systems where the registry signs all JWTs itself, a JWT signing secret exposed via SSRF, source code leak, or misconfigured environment variable allows an attacker to forge tokens with arbitrary role claims. Reading roles from the database on every request eliminates this entire class of attack: even a fully forged JWT with a valid signature cannot grant admin access if the role lookup ignores the JWT role claim. CVSS 9.8 (AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H).

// VULNERABLE — admin role read from JWT claims
// File: middleware/auth.js

const jwt = require('jsonwebtoken');

function requireAdminRole(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' });
  }

  // VULNERABILITY: role read from JWT claims — attacker crafts token with role:'system_admin'
  // JWT signature verifies token integrity but cannot prevent attacker from forging
  // tokens if signing secret is exposed, or from exploiting any BYO-token feature
  if (decoded.role !== 'system_admin') {
    return res.status(403).json({ error: 'Admin role required' });
  }

  req.user = decoded;
  next();
}

Fix: Fetch the user's role from the database on every request — never trust role claims in the JWT. The JWT should carry only the user ID (sub) as an identity claim; the role is authoritative only in the database. Cache the role server-side with a short TTL (e.g., 30 seconds per user ID) using Redis to reduce database load on high-traffic endpoints. For the admin console specifically, require MFA re-authentication at the start of each admin session, adding a second factor that cannot be forged even if the JWT secret is compromised.

// FIXED — role fetched from DB; JWT carries identity only; server-side role cache
// File: middleware/auth.js

const jwt = require('jsonwebtoken');
const redis = require('./redis');

async function requireAdminRole(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' });
  }

  const userId = decoded.sub;
  if (!userId) return res.status(401).json({ error: 'Invalid token: missing sub' });

  // Server-side role cache (30s TTL) — never trusts JWT role claim
  const cacheKey = `role:${userId}`;
  let role = await redis.get(cacheKey);

  if (!role) {
    const { rows } = await db.query(
      'SELECT role FROM users WHERE id = $1 AND active = true',
      [userId]
    );
    if (!rows.length) return res.status(401).json({ error: 'User not found or inactive' });
    role = rows[0].role;
    await redis.set(cacheKey, role, 'EX', 30);
  }

  if (role !== 'system_admin') {
    return res.status(403).json({ error: 'Admin role required' });
  }

  req.user = { ...decoded, role };  // role from DB, not JWT
  next();
}

PRIVESC18-002 (High): System configuration PATCH missing admin role check allows any user to disable security scanners

MCP skill registries expose a system configuration endpoint at PATCH /api/admin/config that allows operators to modify system-wide settings: which security scanners are enabled (SSRF, injection, CORS, deserialization), debug output level, the LLM model used for AI-assisted analysis, rate limits, and scanner sensitivity thresholds. When this endpoint is missing an admin role verification middleware, any authenticated user — including free-tier users — can modify these system-wide settings that affect all organizations on the registry.

An attacker who disables the SSRF scanner prevents future SSRF findings from being reported for their own submitted skills and for all other organizations' skills. An attacker who enables debug output causes verbose internal error messages (including stack traces, SQL query fragments, and internal service URLs) to be returned to all users. An attacker who switches the LLM model to a cheaper or less capable model degrades the quality of AI-assisted analysis for all paying customers. These are business-logic attacks that do not require code execution — they abuse misconfigured authorization to modify the product's operational behavior. CVSS 8.1 (AV:N/AC:L/PR:L/UI:N/S:C/C:L/I:H/A:L).

// VULNERABLE — system config PATCH accessible to any authenticated user
// File: routes/admin.js

const router = require('express').Router();

// VULNERABILITY: authenticate middleware present but no admin role check
// Any authenticated user can PATCH system-wide scanner config
router.patch('/admin/config', authenticate, async (req, res) => {
  const updates = req.body;

  // Any authenticated user can reach here and modify system config
  // E.g.: { ssrfScannerEnabled: false, debugOutput: true, llmModel: 'gpt-3.5-turbo' }
  const allowedKeys = ['ssrfScannerEnabled', 'injectionScannerEnabled', 'debugOutput',
    'llmModel', 'maxScanDuration', 'rateLimitPerOrg'];

  const setClause = Object.keys(updates)
    .filter(k => allowedKeys.includes(k))
    .map((k, i) => `"${k}" = $${i + 1}`)
    .join(', ');

  if (!setClause) return res.status(400).json({ error: 'No valid fields' });

  await db.query(
    `UPDATE system_config SET ${setClause} WHERE id = 1`,
    Object.values(updates).filter((_, i) => allowedKeys.includes(Object.keys(updates)[i]))
  );

  res.json({ updated: true });
});

Fix: Add requireAdminRole middleware that reads the role from the database (per PRIVESC18-001 fix) before any config modification is allowed. Add a CSRF token check for state-modifying endpoints accessed via the admin console browser. Write a full audit log entry for every config change, including the previous value, new value, changing user ID, and timestamp. Use a Zod schema to validate the update payload — only allow specific known-safe config keys and value ranges, preventing unexpected system configurations.

// FIXED — requireAdminRole middleware; CSRF token; audit log; Zod validation
// File: routes/admin.js

const { z } = require('zod');

const SystemConfigUpdateSchema = z.object({
  ssrfScannerEnabled: z.boolean().optional(),
  injectionScannerEnabled: z.boolean().optional(),
  corsScannerEnabled: z.boolean().optional(),
  deserializationScannerEnabled: z.boolean().optional(),
  debugOutput: z.boolean().optional(),
  llmModel: z.enum(['claude-sonnet-4-6', 'claude-haiku-4-5-20251001']).optional(),
  maxScanDurationSeconds: z.number().int().min(30).max(600).optional(),
  rateLimitPerOrgPerDay: z.number().int().min(10).max(10000).optional(),
});

router.patch('/admin/config',
  authenticate,
  requireAdminRole,    // DB-sourced role check, not JWT claim
  validateCsrfToken,   // CSRF token from X-CSRF-Token header
  async (req, res) => {
    const result = SystemConfigUpdateSchema.safeParse(req.body);
    if (!result.success) {
      return res.status(400).json({ error: 'Invalid config update', details: result.error.issues });
    }

    const updates = result.data;
    if (!Object.keys(updates).length) {
      return res.status(400).json({ error: 'No valid config fields provided' });
    }

    // Read current values for audit log
    const { rows: current } = await db.query('SELECT * FROM system_config WHERE id = 1');

    // Apply update
    const setClause = Object.keys(updates).map((k, i) => `"${k}" = $${i + 2}`).join(', ');
    await db.query(
      `UPDATE system_config SET ${setClause} WHERE id = $1`,
      [1, ...Object.values(updates)]
    );

    // Write immutable audit log entry
    await db.query(
      `INSERT INTO admin_audit_log (admin_user_id, action, previous_values, new_values, created_at)
       VALUES ($1, 'system_config_update', $2, $3, NOW())`,
      [req.user.sub, JSON.stringify(current[0]), JSON.stringify(updates)]
    );

    res.json({ updated: true });
  }
);

PRIVESC18-003 (High): Admin impersonation endpoint creates sessions without audit log entry

MCP skill registry admin consoles commonly include a user impersonation feature that allows support staff to log in as any user to diagnose billing or access issues. When this endpoint creates an impersonation session without first writing an immutable audit log entry, any abuse of an admin account — either by the admin themselves acting outside their authority, or by an attacker who has compromised an admin account — leaves no trace. The absence of an audit trail means the impersonation is effectively invisible: there is no record of which users were impersonated, when, or what actions were taken during the impersonation session.

The practical impact is that a compromised admin account can be used to impersonate high-value users (organization owners, billing contacts) to change payment methods, export sensitive audit data, or modify security configurations, with no audit record linking these actions to the admin-level impersonation. The impersonated user will not receive any notification of the access. If the impersonation token does not have a short TTL or automatic session termination, the attacker retains access to the impersonated session indefinitely. CVSS 7.2 (AV:N/AC:L/PR:H/UI:N/S:C/C:H/I:H/A:N).

// VULNERABLE — impersonation endpoint creates session without audit log
// File: routes/admin.js

router.post('/admin/impersonate/:userId',
  authenticate,
  requireAdminRole,
  async (req, res) => {
    const { userId } = req.params;
    const adminUserId = req.user.sub;

    // VULNERABILITY: no audit log written before session creation
    // If admin account is compromised, attacker impersonates any user with no trace
    const { rows } = await db.query(
      'SELECT id, email, role FROM users WHERE id = $1',
      [userId]
    );
    if (!rows.length) return res.status(404).json({ error: 'User not found' });

    // Impersonation token with no TTL — persists indefinitely
    const impersonationToken = jwt.sign(
      { sub: userId, impersonatedBy: adminUserId },
      process.env.JWT_SECRET
    );

    res.json({ token: impersonationToken });
  }
);

Fix: Write an immutable audit log entry as the first action in the endpoint handler, before any session creation. Use a database transaction that atomically writes the log entry and creates the impersonation token — if the log write fails, the impersonation token is not issued. Require MFA re-authentication from the admin immediately before impersonation. Issue an impersonation token with a 15-minute TTL and automatic session termination flag. Consider notifying the impersonated user via email that their account was accessed by support staff.

// FIXED — audit log written first (atomic); MFA re-auth; 15-min TTL
// File: routes/admin.js

router.post('/admin/impersonate/:userId',
  authenticate,
  requireAdminRole,
  requireMfaReauth,    // MFA re-authentication required for impersonation
  async (req, res) => {
    const { userId } = req.params;
    const adminUserId = req.user.sub;

    const { rows } = await db.query(
      'SELECT id, email, role FROM users WHERE id = $1 AND active = true',
      [userId]
    );
    if (!rows.length) return res.status(404).json({ error: 'User not found or inactive' });

    // Atomic: audit log written inside transaction before token issuance
    // If log write fails (e.g., disk full), token is not issued
    const impersonationSessionId = crypto.randomUUID();

    await db.transaction(async (txn) => {
      await txn.query(
        `INSERT INTO admin_audit_log
           (id, admin_user_id, action, target_user_id, metadata, created_at)
         VALUES ($1, $2, 'user_impersonation_start', $3, $4, NOW())`,
        [
          impersonationSessionId,
          adminUserId,
          userId,
          JSON.stringify({ targetEmail: rows[0].email, targetRole: rows[0].role }),
        ]
      );
    });

    // 15-minute TTL; impersonation session ID links token to audit log entry
    const impersonationToken = jwt.sign(
      {
        sub: userId,
        impersonatedBy: adminUserId,
        impersonationSessionId,
        impersonation: true,
      },
      process.env.JWT_SECRET,
      { expiresIn: '15m' }
    );

    // Optionally notify the impersonated user
    await sendImpersonationNotificationEmail(rows[0].email, adminUserId);

    res.json({ token: impersonationToken, expiresIn: 900 });
  }
);

PRIVESC18-004 (High): Unauthenticated admin metrics endpoint exposes MRR and infrastructure health

Admin metrics endpoints in MCP skill registries aggregate revenue data, operational metrics, and infrastructure health indicators into a single API response. When this endpoint serves data without any authentication, any client that can reach the endpoint on the network — including public internet clients if the admin API is not behind a network boundary — can read this data.

The data exposed typically includes: monthly recurring revenue (MRR), plan distribution (how many users on each tier), churn rate, failed payment counts, monthly active users, scan volume by organization size, vulnerability finding distribution by severity, infrastructure health indicators (database connection pool status, Redis latency, queue depth), and worker process metrics. This combination of financial, operational, and infrastructure data provides a competitor with accurate intelligence about the registry's business performance, and reveals infrastructure weaknesses (high queue depth, elevated error rates) that an attacker can exploit for targeted timing attacks. The lack of authentication also means this data is accessible to automated scrapers and can be indexed by search engines or monitoring tools. CVSS 7.5 (AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N).

// VULNERABLE — admin metrics endpoint requires no authentication
// File: routes/admin.js

// VULNERABILITY: no authenticate middleware; no admin role check
// Any network-reachable client reads MRR, plan distribution, scan volumes
router.get('/admin/metrics', async (req, res) => {
  const [revenueMetrics, scanMetrics, infraMetrics] = await Promise.all([
    db.query(`
      SELECT
        SUM(monthly_price_usd) AS mrr_usd,
        COUNT(*) FILTER (WHERE plan = 'pro') AS pro_count,
        COUNT(*) FILTER (WHERE plan = 'enterprise') AS enterprise_count,
        COUNT(*) FILTER (WHERE churned_at > NOW() - INTERVAL '30 days') AS monthly_churn
      FROM subscriptions
      WHERE active = true
    `),
    db.query(`
      SELECT COUNT(*) AS total_scans, AVG(duration_ms) AS avg_duration
      FROM scan_runs
      WHERE created_at > NOW() - INTERVAL '24 hours'
    `),
    getInfraHealth(),
  ]);

  res.json({
    revenue: revenueMetrics.rows[0],
    scans: scanMetrics.rows[0],
    infrastructure: infraMetrics,
  });
});

Fix: Add authenticate and requireAdminRole middleware to the metrics endpoint. As an additional layer, place the admin API on a separate internal port that is not exposed to the public internet — the admin console should be accessible only from your corporate VPN or a specific IP allowlist. Add a rate limit on the metrics endpoint even for authenticated admins to prevent bulk data harvesting. Consider whether infrastructure health metrics (which may reveal exploitable states) should be accessible via the same endpoint as business metrics, or served on a separate endpoint with stricter access controls.

// FIXED — authenticate + requireAdminRole; IP allowlist; separate admin port
// File: routes/admin.js

router.get('/admin/metrics',
  authenticate,
  requireAdminRole,    // DB-sourced role check
  requireAdminIp,      // optional: IP allowlist middleware
  async (req, res) => {
    const [revenueMetrics, scanMetrics, infraMetrics] = await Promise.all([
      db.query(`
        SELECT
          SUM(monthly_price_usd) AS mrr_usd,
          COUNT(*) FILTER (WHERE plan = 'pro') AS pro_count,
          COUNT(*) FILTER (WHERE plan = 'enterprise') AS enterprise_count,
          COUNT(*) FILTER (WHERE churned_at > NOW() - INTERVAL '30 days') AS monthly_churn
        FROM subscriptions
        WHERE active = true
      `),
      db.query(`
        SELECT COUNT(*) AS total_scans, AVG(duration_ms) AS avg_duration
        FROM scan_runs
        WHERE created_at > NOW() - INTERVAL '24 hours'
      `),
      getInfraHealth(),
    ]);

    // Write access log entry for metrics reads (financial data access auditing)
    await db.query(
      'INSERT INTO admin_audit_log (admin_user_id, action, created_at) VALUES ($1, $2, NOW())',
      [req.user.sub, 'admin_metrics_read']
    );

    res.json({
      revenue: revenueMetrics.rows[0],
      scans: scanMetrics.rows[0],
      infrastructure: infraMetrics,
    });
  }
);

Compound attack chain: JWT role forgery to admin console takeover

The four PRIVESC18 vulnerabilities create an escalating compromise path starting from a standard user account.

Phase 1 — JWT role forgery (PRIVESC18-001). An attacker obtains the JWT signing secret via SSRF (targeting a metadata endpoint), source code leak, or environment variable exfiltration from an injection attack (see SA-SKL-INJECTION25). With the secret, they forge a JWT with role:'system_admin'. This grants admin console access without needing any existing admin account credentials.

Phase 2 — Scanner disablement (PRIVESC18-002). As a forged admin, the attacker PATCHes the system configuration to disable the SSRF scanner and injection scanner. This creates a window during which the attacker's skills pass security audits with no findings, enabling submission of malicious MCP skills to the registry without detection.

Phase 3 — Invisible impersonation (PRIVESC18-003). The attacker uses the impersonation endpoint to create a session for a high-value organization owner — an enterprise customer. Because no audit log is written, this access is invisible. The attacker modifies the organization's billing settings, reads private audit findings, and exports vulnerability data.

Phase 4 — Business intelligence harvest (PRIVESC18-004). Even before achieving admin access, the attacker can read the unauthenticated metrics endpoint to identify the registry's MRR, plan distribution, and infrastructure vulnerabilities — informing the attack strategy and identifying the highest-value impersonation targets from the scan volume data.

Chain severity: This chain progresses from JWT secret exposure (a common consequence of the SSRF and injection vulnerabilities in prior SA-SKL advisories) to full admin console compromise, invisible user impersonation, and business intelligence exfiltration. The root fix is PRIVESC18-001: reading roles from the database rather than JWT claims eliminates the JWT forgery entry point for the entire chain.

Detection with tree-sitter queries

Query 1 — Role read from JWT decoded object. Matches property access of role, isAdmin, or permissions on a JWT-decoded object (typically decoded.* or req.user.* immediately after jwt.verify()) used in a conditional — the PRIVESC18-001 pattern.

; tree-sitter query: role/isAdmin property accessed on JWT-decoded object (PRIVESC18-001)

(if_statement
  condition: (binary_expression
    left: (member_expression
      object: (identifier) @decoded (#match? @decoded "^(decoded|payload|claims|token)$")
      property: (property_identifier) @prop (#match? @prop "^(role|isAdmin|admin|permissions|scope)$")
    )
  )
) @jwt-role-claim-check

; Each @jwt-role-claim-check: role read from JWT claims object.
; Fix: replace with DB lookup using decoded.sub as the lookup key.

Query 2 — Route handler without requireAdminRole on /admin/ path. Matches router.get/router.post/router.patch calls on paths starting with /admin/ where the middleware chain does not include an identifier matching requireAdmin or adminRole.

; tree-sitter query: /admin/ route missing requireAdminRole-pattern middleware (PRIVESC18-002/004)

(call_expression
  function: (member_expression
    property: (property_identifier) @verb (#match? @verb "^(get|post|patch|put|delete)$")
  )
  arguments: (arguments
    (string) @path (#match? @path "^/admin/")
    . (_)* @middlewares
      (#not-match? @middlewares "requireAdmin|adminRole|isAdmin|checkAdmin")
  )
) @admin-route-no-admin-check

; Each @admin-route-no-admin-check: admin-prefixed route without admin role middleware.
; Fix: add requireAdminRole middleware before the handler.

Query 3 — Impersonate route without audit log INSERT. Matches router.post calls on paths containing impersonate where the handler body does not contain a db.query or INSERT string — indicating no audit log write in the impersonation handler.

; tree-sitter query: impersonate route handler missing audit log INSERT (PRIVESC18-003)

(call_expression
  function: (member_expression
    property: (property_identifier) @verb (#eq? @verb "post")
  )
  arguments: (arguments
    (string) @path (#match? @path "impersonat")
    (_)*
    (arrow_function
      body: (statement_block) @body
        (#not-match? @body "audit_log|auditLog|INSERT INTO")
    )
  )
) @impersonate-no-audit-log

; Each @impersonate-no-audit-log: impersonation endpoint without audit log write.
; Fix: atomic DB transaction that writes audit log before issuing impersonation token.

Summary

ID Severity Surface Root cause Fix
PRIVESC18-001 Critical Admin console authentication middleware Role read from JWT role claim; forged JWT with role:'system_admin' bypasses all admin checks Fetch role from DB using decoded.sub; JWT carries identity only; 30s server-side role cache; MFA re-auth for admin
PRIVESC18-002 High PATCH /api/admin/config Missing admin role middleware; any authenticated user modifies system-wide scanner config and LLM model requireAdminRole + CSRF token; Zod schema; audit log on every config change
PRIVESC18-003 High POST /api/admin/impersonate/:userId No audit log entry written before session creation; impersonation token has no TTL Atomic audit log write in transaction before token issuance; MFA re-auth; 15-min TTL; impersonated user notification
PRIVESC18-004 High GET /api/admin/metrics No authentication on metrics endpoint; any client reads MRR, churn, plan distribution, infrastructure health authenticate + requireAdminRole; IP allowlist; internal-port-only deployment; access audit log

Checklist for MCP skill registry operators: (1) Grep all authentication middleware for decoded.role, payload.role, or similar JWT claim reads used in authorization decisions — replace all with DB lookups keyed on sub. (2) Audit all /admin/ route handlers — confirm requireAdminRole (DB-sourced) is present on every handler. (3) Review all impersonation and session-creation endpoints — confirm an immutable audit log entry is written as the first action inside a database transaction. (4) Confirm the admin metrics endpoint requires authentication — test with an unauthenticated curl request. (5) Verify the admin console enforces MFA re-authentication at the start of each admin session, not just at login. (6) Run all three tree-sitter queries above in CI. See also: SA-SKL-PRIVESC17 for org-level privilege escalation; SA-SKL-CORS35 for privilege escalation via team invitation CORS.

Scan your MCP skills for PRIVESC18 and 2400+ other patterns

SkillAudit continuously audits MCP server and Claude skill codebases for CORS misconfigurations, injection vulnerabilities, deserialization flaws, SSRF, and privilege escalation. Get findings in minutes.

Get started at skillaudit.dev