SA-SKL-SSRF41 — Server-Side Request Forgery

SSRF in MCP Skill Registry Skill Review and Static Analysis Tool Integration Endpoints

Static analysis tool integration is a cornerstone of automated skill quality assurance in MCP skill registries. SSRF41 covers four distinct patterns — a CodeQL database download URL that an attacker redirects to the AWS Instance Metadata Service to steal live IAM credentials; a SonarQube results URL that an attacker targets at an internal Consul agent to exfiltrate the entire internal service catalog; a webhook delivery callback that silently follows a CNAME redirect to an internal Vault KV store, returning secret data to the attacker as delivery confirmation; and a license verification URL that an attacker aims at an internal InfluxDB HTTP API to enumerate all monitoring measurement names. Each finding exploits the same root cause: a user-controlled URL is fetched server-side with no hostname validation, no pre-connect IP address check, and the full response body returned to the calling user.

SA-SKL-SSRF41 findings
CRITICALSSRF41-001 — Static analysis tool integration endpoint fetches user-supplied codeqlDbUrl without validation; attacker targets AWS IMDS at 169.254.169.254 to steal IAM security credentials returned as downloaded CodeQL database content; fix: hostname allowlist, DNS-based private IP block before connect, redirect: 'error', return only parsed DB metadata
HIGHSSRF41-002 — Review tool integration endpoint fetches user-supplied sonarqubeUrl without validation; attacker targets internal Consul agent at consul-agent:8500 to exfiltrate full service catalog topology as skill review data; fix: SonarQube hostname allowlist, Zod schema parsing of severity, message, line, component only, never return raw body
HIGHSSRF41-003 — Webhook delivery endpoint fetches user-supplied callbackUrl with redirect: 'follow'; attacker registers a CNAME pointing to internal Vault KV store; Vault secret data returned in webhook delivery confirmation; fix: redirect: 'error', CI/CD callback host allowlist, return only HTTP status and timestamp
MEDIUMSSRF41-004 — License verification endpoint fetches user-supplied licenseServerUrl; attacker targets internal InfluxDB HTTP API at influxdb:8086 to enumerate monitoring measurement names returned to any registry administrator; fix: pre-registered hostname allowlist per tool vendor, return only boolean valid and expiry timestamp

SSRF41-001 — CodeQL database download URL fetches AWS IMDS and returns IAM credentials

The static analysis tool integration endpoint accepts a codeqlDbUrl parameter pointing to the location of a prebuilt CodeQL database for the skill under review. The endpoint fetches the URL server-side, writes the response body to a temporary file, and returns a confirmation object including the raw downloaded bytes for the client to inspect. Because the registry infrastructure runs on AWS EC2, the link-local address 169.254.169.254 is reachable from within the VPC without any special routing. An attacker submits codeqlDbUrl: "http://169.254.169.254/latest/meta-data/iam/security-credentials/skill-analysis-role" and receives the full JSON blob of temporary AccessKeyId, SecretAccessKey, and Token fields as the “downloaded database content” in the response.

The credentials belong to the IAM role attached to the analysis worker instance. Depending on the permissions granted to that role, the attacker gains the ability to read S3 buckets, invoke Lambda functions, query DynamoDB tables, or assume further roles within the AWS account. Because the credentials are temporary STS tokens, they are valid for one to six hours by default and do not trigger IAM key rotation alerts. The fix requires a strict hostname allowlist covering only the known CodeQL database storage providers, a pre-connect DNS resolution step that rejects any resolved IP falling within RFC 1918, loopback, link-local, or cloud metadata address ranges, disabling redirect following, and returning only structured metadata fields parsed from the database manifest rather than any raw response bytes.

Vulnerable
// SSRF41-001 — VULNERABLE
// codeqlDbUrl fetched server-side with no hostname or IP validation.
// Full response body returned as "downloaded database content".

import { Router } from 'express';
const router = Router();

router.post('/skills/:skillId/analysis/codeql', requireSession, async (req, res) => {
  const { codeqlDbUrl } = req.body; // attacker-controlled URL — no validation

  // Fetch the CodeQL database from wherever the user says it lives
  const response = await fetch(codeqlDbUrl); // VULNERABLE — fetches any URL including IMDS
  const rawBytes = await response.arrayBuffer();
  const content = Buffer.from(rawBytes).toString('utf-8');

  // Store the downloaded content as the CodeQL DB and return it to the caller
  await db.analysisJobs.create({
    skillId: req.params.skillId,
    codeqlDbContent: content, // ← stores IAM credentials when URL is IMDS endpoint
    status: 'downloaded',
  });

  // Return the raw response content — attacker reads AWS creds from this field
  res.json({
    jobId: job.id,
    downloadedContent: content, // VULNERABLE — raw IMDS response body returned to caller
    status: 'downloaded',
  });
});
Fixed
// SSRF41-001 — FIXED
// 1. Hostname allowlist covering known CodeQL DB storage providers.
// 2. Pre-connect DNS resolution rejects RFC 1918, loopback, link-local, metadata IPs.
// 3. redirect: 'error' prevents open-redirect pivots.
// 4. Only parsed CodeQL DB metadata returned — never raw bytes.

import dns from 'node:dns/promises';
import net from 'node:net';
import { z } from 'zod';

const CODEQL_DB_HOSTS = new Set([
  'storage.googleapis.com',
  'github.com',
  'objects.githubusercontent.com',
  'codeql-db-storage.internal',
]);

const BLOCKED_RANGES = [
  // loopback
  (ip) => ip === '127.0.0.1' || ip === '::1',
  // link-local / AWS IMDS
  (ip) => ip.startsWith('169.254.'),
  // RFC 1918
  (ip) => ip.startsWith('10.') || ip.startsWith('192.168.') ||
           /^172\.(1[6-9]|2\d|3[01])\./.test(ip),
  // IPv6 ULA
  (ip) => /^f[cd]/i.test(ip),
];

async function assertSafeUrl(raw) {
  let parsed;
  try { parsed = new URL(raw); } catch { throw new Error('Invalid URL'); }

  if (parsed.protocol !== 'https:') throw new Error('Only HTTPS URLs are permitted');
  if (!CODEQL_DB_HOSTS.has(parsed.hostname)) throw new Error('Hostname not in allowlist');

  // Resolve DNS before connecting — reject private/metadata IPs
  const addrs = await dns.resolve4(parsed.hostname).catch(() => []);
  const addrs6 = await dns.resolve6(parsed.hostname).catch(() => []);
  for (const ip of [...addrs, ...addrs6]) {
    if (BLOCKED_RANGES.some((fn) => fn(ip)))
      throw new Error(`Resolved IP ${ip} is in a blocked range`);
  }
}

const CodeQLManifestSchema = z.object({
  name: z.string().max(128),
  language: z.string().max(32),
  version: z.string().max(32),
  createdAt: z.string().optional(),
});

router.post('/skills/:skillId/analysis/codeql', requireSession, async (req, res) => {
  const { codeqlDbUrl } = req.body;

  await assertSafeUrl(codeqlDbUrl); // throws 400 for disallowed URLs

  const response = await fetch(codeqlDbUrl, {
    redirect: 'error', // never follow redirects
    signal: AbortSignal.timeout(10_000),
  });
  if (!response.ok) return res.status(502).json({ error: 'DB fetch failed' });

  // Parse only the manifest header from the CodeQL DB bundle — never store raw bytes
  const manifest = CodeQLManifestSchema.parse(await response.json());

  const job = await db.analysisJobs.create({
    skillId: req.params.skillId,
    codeqlDbName: manifest.name,
    codeqlDbLanguage: manifest.language,
    codeqlDbVersion: manifest.version,
    status: 'queued',
  });

  // Return only structured metadata — no raw response body
  res.json({ jobId: job.id, metadata: manifest, status: 'queued' });
});

SSRF41-002 — SonarQube results URL fetches internal Consul catalog and exposes infrastructure topology

The review tool integration endpoint accepts a sonarqubeUrl parameter identifying the customer’s SonarQube instance so the registry can pull code-quality findings directly into the skill review workflow. The endpoint appends a fixed API path to the base URL and fetches the result, then stores the entire response JSON as the analysis findings object associated with the skill review. Because the fetch is unauthenticated and the URL is entirely user-controlled, an attacker can substitute the SonarQube base URL with any reachable internal address. Targeting http://consul-agent:8500/v1/catalog/services returns a JSON object whose keys are every registered internal service name and whose values list the tags associated with each service — a complete map of the internal infrastructure stored verbatim as the skill’s analysis results.

The leaked Consul catalog may reveal database hostnames, internal API service names, monitoring endpoints, secret management service locations, and cluster health state — all of which an attacker can use to plan further lateral movement or craft more targeted SSRF probes against specific internal services. The fix requires that every SonarQube instance be pre-registered by hostname before the registry will make outbound requests to it, and that the response be parsed through a strict Zod schema that extracts only the severity, message, line, and component fields from each issue object, discarding all other fields regardless of their content.

Vulnerable
// SSRF41-002 — VULNERABLE
// sonarqubeUrl is user-controlled. Full response JSON stored and returned as analysis results.

router.post('/skills/:skillId/review/sonarqube', requireSession, async (req, res) => {
  const { sonarqubeUrl, projectKey } = req.body; // attacker-controlled base URL

  // Build the API endpoint from the user-supplied base URL — no hostname validation
  const apiUrl = `${sonarqubeUrl}/api/issues/search?projectKeys=${projectKey}`;
  const response = await fetch(apiUrl); // VULNERABLE — fetches any internal URL
  const analysisData = await response.json(); // includes full Consul catalog when redirected

  // Store raw response as analysis results — exposes entire internal service topology
  await db.reviewAnalysis.create({
    skillId: req.params.skillId,
    reviewerId: req.session.userId,
    sonarData: analysisData, // VULNERABLE — Consul JSON stored verbatim
  });

  res.json({ analysisData }); // attacker reads internal Consul catalog from response
});
Fixed
// SSRF41-002 — FIXED
// 1. sonarqubeUrl hostname must be pre-registered in the registry config.
// 2. Zod schema parses only severity/message/line/component — ignores all other fields.
// 3. Never return or store raw response body.

import { z } from 'zod';

const SonarIssueSchema = z.object({
  severity: z.enum(['BLOCKER', 'CRITICAL', 'MAJOR', 'MINOR', 'INFO']),
  message: z.string().max(512),
  line: z.number().int().nonneg().optional(),
  component: z.string().max(256),
});

const SonarResponseSchema = z.object({
  issues: z.array(SonarIssueSchema).max(500),
});

async function assertRegisteredSonarHost(rawUrl) {
  let parsed;
  try { parsed = new URL(rawUrl); } catch { throw new Error('Invalid URL'); }
  if (parsed.protocol !== 'https:') throw new Error('Only HTTPS permitted');

  const registered = await db.sonarRegistrations.findOne({
    where: { hostname: parsed.hostname, ownerId: /* current org */ null },
  });
  if (!registered) throw new Error('SonarQube hostname not registered for this organization');
}

router.post('/skills/:skillId/review/sonarqube', requireSession, async (req, res) => {
  const { sonarqubeUrl, projectKey } = req.body;

  await assertRegisteredSonarHost(sonarqubeUrl); // throws if hostname not pre-registered

  const apiUrl = `${sonarqubeUrl}/api/issues/search?projectKeys=${encodeURIComponent(projectKey)}`;
  const response = await fetch(apiUrl, {
    redirect: 'error',
    signal: AbortSignal.timeout(15_000),
    headers: { 'Authorization': `Bearer ${registeredToken}` },
  });
  if (!response.ok) return res.status(502).json({ error: 'SonarQube fetch failed' });

  // Parse and validate — only the four allowed fields survive; everything else is discarded
  const parsed = SonarResponseSchema.parse(await response.json());

  await db.reviewAnalysis.create({
    skillId: req.params.skillId,
    reviewerId: req.session.userId,
    issues: parsed.issues, // only severity/message/line/component stored
  });

  res.json({ issues: parsed.issues, count: parsed.issues.length });
});

SSRF41-003 — Webhook callback follows CNAME redirect to internal Vault KV store and returns secrets

The tool result webhook delivery endpoint notifies skill authors that their analysis job has completed by sending an HTTP POST to the author-supplied callbackUrl. The endpoint uses fetch(callbackUrl, { redirect: 'follow' }) and includes the full analysis result payload in the POST body. After delivery, it reads the response body from the callback endpoint and returns it to the calling user as part of the delivery confirmation object. An attacker registers a public domain and configures a CNAME DNS record pointing it to an internal Vault server address (vault:8200). When the registry worker resolves the CNAME and follows the redirect, it reaches the Vault HTTP API; the analysis result payload is ignored, but the Vault KV response body — containing database credentials, API keys, or other secrets — is returned to the attacker in the confirmation response.

The CNAME technique is particularly effective because the attacker’s domain resolves to a valid external IP during the initial DNS check, only redirecting to an internal target after the connection is established. This defeats naive allowlist checks based on the raw domain string. The correct fix is to set redirect: 'error' on the fetch call so that any redirect from the callback endpoint causes the delivery to fail rather than follow, combined with an allowlist of known CI/CD callback hosts such as GitHub Actions, GitLab CI webhooks, Slack incoming webhooks, and Zapier. The delivery confirmation must include only the HTTP status code and delivery timestamp — never the response body from the callback endpoint.

Vulnerable
// SSRF41-003 — VULNERABLE
// callbackUrl fetched with redirect:'follow'. Full response body returned to caller.
// CNAME trick: attacker's public domain CNAMEs to internal vault:8200.

router.post('/skills/:skillId/analysis/webhook', requireSession, async (req, res) => {
  const { callbackUrl, jobId } = req.body; // attacker-controlled callback URL

  const job = await db.analysisJobs.findByPk(jobId);
  if (!job) return res.status(404).json({ error: 'Job not found' });

  // POST analysis results to the author's callback URL
  const callbackResponse = await fetch(callbackUrl, { // VULNERABLE — no host validation
    method: 'POST',
    redirect: 'follow', // VULNERABLE — CNAME to vault:8200 is silently followed
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ jobId, results: job.results }),
  });

  // Read the response body from the callback — returns Vault KV secrets to attacker
  const callbackBody = await callbackResponse.text();

  res.json({
    delivered: callbackResponse.ok,
    callbackStatus: callbackResponse.status,
    callbackBody, // VULNERABLE — Vault secret data returned to the attacker here
  });
});
Fixed
// SSRF41-003 — FIXED
// 1. redirect:'error' — any redirect aborts delivery immediately.
// 2. Allowlist of known CI/CD and notification callback hostnames.
// 3. Response body from callback endpoint is never read or returned.
// 4. Return only HTTP status code and delivery timestamp.

const CALLBACK_HOST_ALLOWLIST = new Set([
  'api.github.com',
  'hooks.github.com',
  'gitlab.com',
  'hooks.slack.com',
  'hooks.zapier.com',
  'notify.pagerduty.com',
]);

function assertCallbackHost(rawUrl) {
  let parsed;
  try { parsed = new URL(rawUrl); } catch { throw new Error('Invalid callback URL'); }
  if (parsed.protocol !== 'https:') throw new Error('Callback URL must use HTTPS');
  if (!CALLBACK_HOST_ALLOWLIST.has(parsed.hostname))
    throw new Error(`Callback host ${parsed.hostname} is not in the permitted allowlist`);
}

router.post('/skills/:skillId/analysis/webhook', requireSession, async (req, res) => {
  const { callbackUrl, jobId } = req.body;

  assertCallbackHost(callbackUrl); // throws for any non-allowlisted host

  const job = await db.analysisJobs.findByPk(jobId);
  if (!job) return res.status(404).json({ error: 'Job not found' });

  const callbackResponse = await fetch(callbackUrl, {
    method: 'POST',
    redirect: 'error', // any redirect terminates delivery — CNAME trick fails here
    signal: AbortSignal.timeout(10_000),
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ jobId, skillId: req.params.skillId, event: 'analysis.complete' }),
  });

  // Drain the response body without reading or storing it
  await callbackResponse.body?.cancel();

  // Return only delivery status and timestamp — never any response body content
  res.json({
    delivered: callbackResponse.ok,
    httpStatus: callbackResponse.status,
    deliveredAt: new Date().toISOString(),
  });
});

SSRF41-004 — License server URL fetches internal InfluxDB measurements and returns monitoring data

The tool license verification endpoint accepts a licenseServerUrl from the requesting user and makes an outbound GET request to validate whether the user holds a valid license for the static analysis tool they want to integrate with the registry. The endpoint then returns the license server’s full response object as the validity result. An attacker sets licenseServerUrl to http://influxdb:8086/query?q=SHOW+MEASUREMENTS. The InfluxDB HTTP query API accepts unauthenticated requests in many default configurations and returns a JSON object listing all measurement names in the monitoring database. This information is returned to any registry administrator as the “license validity” response, enumerating every metric being tracked — application names, service identifiers, infrastructure host labels — that can guide further reconnaissance.

Even though this finding is rated MEDIUM rather than HIGH, the data returned is not trivial: measurement names in a production InfluxDB instance commonly include service names, deployment identifiers, region codes, and feature flag metrics that together form a detailed picture of the deployment. The fix requires that every license server URL be pre-registered at product configuration time by a registry super-administrator, binding a tool vendor to a specific set of approved hostnames. The response handler must extract only a boolean valid field and an expiry timestamp using strict schema validation; the raw response body must never be returned to the calling user or written to application logs.

Vulnerable
// SSRF41-004 — VULNERABLE
// licenseServerUrl is user-controlled. Full license server response returned to caller.
// Attacker sets URL to http://influxdb:8086/query?q=SHOW+MEASUREMENTS.

router.get('/tools/:toolId/license/verify', requireSession, requireRole('admin'), async (req, res) => {
  const { licenseServerUrl } = req.query; // attacker-controlled URL — no validation

  // Fetch the license status from wherever the user claims the server lives
  const licenseResponse = await fetch(licenseServerUrl); // VULNERABLE — fetches InfluxDB
  const licenseData = await licenseResponse.json();

  // Return the full license server response — InfluxDB measurement names visible here
  res.json({
    toolId: req.params.toolId,
    licenseValid: licenseData.valid ?? true, // truthy for InfluxDB results object
    licenseDetails: licenseData, // VULNERABLE — full InfluxDB query results returned
  });
});
Fixed
// SSRF41-004 — FIXED
// 1. licenseServerUrl hostname must be pre-registered per tool vendor at config time.
// 2. Zod schema extracts only boolean valid and expiry timestamp.
// 3. Raw response body never returned or logged.
// 4. HTTPS required; redirect:error.

import { z } from 'zod';

const LicenseResponseSchema = z.object({
  valid: z.boolean(),
  expiresAt: z.string().datetime().optional(),
});

async function assertRegisteredLicenseHost(toolId, rawUrl) {
  let parsed;
  try { parsed = new URL(rawUrl); } catch { throw new Error('Invalid license server URL'); }
  if (parsed.protocol !== 'https:') throw new Error('License server URL must use HTTPS');

  const registration = await db.toolLicenseServers.findOne({
    where: { toolId, hostname: parsed.hostname },
  });
  if (!registration)
    throw new Error(`License server hostname ${parsed.hostname} is not registered for tool ${toolId}`);
}

router.get('/tools/:toolId/license/verify', requireSession, requireRole('admin'), async (req, res) => {
  const { licenseServerUrl } = req.query;

  await assertRegisteredLicenseHost(req.params.toolId, licenseServerUrl);

  const response = await fetch(licenseServerUrl, {
    redirect: 'error',
    signal: AbortSignal.timeout(8_000),
  });

  if (!response.ok) {
    // Discard body; return a safe negative result
    await response.body?.cancel();
    return res.json({ toolId: req.params.toolId, valid: false, expiresAt: null });
  }

  // Parse only the two safe fields — all other fields are dropped by Zod
  const parsed = LicenseResponseSchema.parse(await response.json());

  // Return only the boolean and expiry — no raw response data, no extra fields
  res.json({ toolId: req.params.toolId, valid: parsed.valid, expiresAt: parsed.expiresAt ?? null });
});

Related findings