← Blog

SSRF via PDF Generation and Headless Browser Rendering in MCP Skills

When an MCP skill generates a PDF, renders an HTML report, or takes a screenshot, it typically delegates that work to a headless browser — puppeteer, wkhtmltopdf, html-pdf, or Playwright. Each of these tools fetches URLs and resolves file paths on the server's behalf. When user-controlled input reaches page.goto(), --header-html, or an <img src> in the rendered HTML, the headless browser becomes a full-capability SSRF agent that can read AWS IMDS credentials, internal service endpoints, and local filesystem contents — and return them to the attacker embedded in the generated document.

By SkillAudit  |  8 Nov 2026
CVSS 9.1 — SSRF9-001 puppeteer IMDS credential read  |  CVSS 9.3 — SSRF9-003 PhantomJS file:// arbitrary read

Server-Side Request Forgery in headless browser contexts is qualitatively different from SSRF in a simple fetch() call. A headless Chromium instance is a full HTTP client with cookie jars, JavaScript execution, redirect following, and support for file://, data://, and blob:// URI schemes. It navigates to the target URL, runs any JavaScript on the page, follows meta-refresh redirects, and can be instrumented via its DevTools Protocol to return the full DOM, screenshots, and network request logs. When an attacker controls the URL passed to a headless browser in an MCP skill, they are not just making one outbound HTTP request — they are handing the attacker a scriptable browser session running from inside the server's network.

The class has become more prevalent as MCP skills add report generation features. An audit skill that produces a branded PDF of its findings, a monitoring skill that generates weekly HTML summaries, a documentation skill that screenshots external pages for archiving — all of these patterns require a headless browser, and all of them are vulnerable if the URL or HTML content that feeds the browser is not strictly controlled before the render call.

SkillAudit's SA-SKL-SSRF9 check covers four distinct patterns in this class. Each exploits a different entry point into the headless rendering pipeline, and each requires a different mitigation strategy.

SSRF9-001: puppeteer page.goto() on user URL

Skill passes user-supplied URL directly to page.goto(). Attacker navigates to http://169.254.169.254/latest/meta-data/iam/security-credentials/ and reads AWS role credentials from the PDF screenshot.

SSRF9-002: wkhtmltopdf --header-html from user input

Header HTML parameter accepts a URL. Attacker supplies an internal service URL as the header template. wkhtmltopdf fetches and renders the internal endpoint in the PDF header on every page.

SSRF9-003: html-pdf PhantomJS file:// URI render

User HTML body includes <img src="file:///etc/passwd"> or an <iframe src="file:///proc/self/environ">. PhantomJS resolves local file paths and embeds the content in the output PDF.

SSRF9-004: CDP port :9222 exposed to network

Chromium DevTools Protocol bound to 0.0.0.0:9222 — any host on the same network can open a WebSocket session, call Page.evaluate to execute arbitrary JavaScript, and read responses from internal URLs via Runtime.evaluate.

IMDS impact: Successful SSRF to http://169.254.169.254/latest/meta-data/iam/security-credentials/<role-name> returns a JSON object with AccessKeyId, SecretAccessKey, and Token — credentials that allow full API access under the instance's IAM role, typically including S3, DynamoDB, and Secrets Manager access. These credentials are rotated every 6 hours but are live immediately upon exfiltration.

SSRF9-001 — puppeteer page.goto() on user-supplied URL

The most direct entry point. An MCP skill that generates audit report PDFs, preview screenshots, or document exports will typically accept a URL to render and pass it directly to page.goto(url). The developer's intent is that callers supply legitimate HTTPS URLs to external resources. The reality is that there is no enforcement at the puppeteer API level — page.goto() will navigate to any scheme and any host that the Chromium process can reach.

In a typical cloud deployment, the Chromium process runs with the same network access as the application container. This means it can reach http://169.254.169.254/ (AWS IMDS v1), http://metadata.google.internal/ (GCP metadata), http://100.100.100.200/ (Alibaba Cloud IMDS), and any other RFC 1918 host in the VPC. The attacker constructs a URL that points to the IMDS credentials endpoint, calls the MCP skill's PDF generation tool with that URL, and the generated PDF contains a screenshot of the IMDS credential JSON response.

The correct fix has two independent layers. First, intercept all requests inside the puppeteer page and block any that target RFC 1918 addresses, loopback, or the IMDS endpoint. Second, validate the URL before calling page.goto() using a DNS lookup that checks whether the resolved IP is in a blocked range — the DNS rebinding protection prevents the bypass where an attacker controls a domain that resolves to an internal IP after the allowlist check.

Wrong
// VULNERABLE — passes user URL to page.goto() with no validation or request interception
import puppeteer from 'puppeteer';

export async function generatePdf(userUrl: string): Promise<Buffer> {
  const browser = await puppeteer.launch({
    args: ['--no-sandbox', '--disable-setuid-sandbox']
  });
  const page = await browser.newPage();

  // VULNERABLE: no URL validation — attacker sends http://169.254.169.254/latest/meta-data/
  // The screenshot of the response is embedded in the returned PDF
  await page.goto(userUrl, { waitUntil: 'networkidle2' });

  const pdf = await page.pdf({ format: 'A4' });
  await browser.close();
  return pdf;
}
Fixed
// FIXED — URL allowlist + request interception blocks RFC1918, IMDS, and loopback
import puppeteer from 'puppeteer';
import dns from 'dns/promises';
import { isIP } from 'net';

// RFC 1918 / IMDS / loopback blocks (CIDR ranges checked via integer comparison)
const BLOCKED_RANGES = [
  { start: '10.0.0.0',      end: '10.255.255.255' },
  { start: '172.16.0.0',    end: '172.31.255.255' },
  { start: '192.168.0.0',   end: '192.168.255.255' },
  { start: '127.0.0.0',     end: '127.255.255.255' },
  { start: '169.254.0.0',   end: '169.254.255.255' }, // IMDS
  { start: '100.100.100.0', end: '100.100.100.255' }, // Alibaba Cloud IMDS
  { start: '::1',           end: '::1' },              // IPv6 loopback
];

function ipToInt(ip: string): number {
  return ip.split('.').reduce((acc, oct) => (acc << 8) | parseInt(oct, 10), 0) >>> 0;
}

function isBlockedIp(ip: string): boolean {
  if (ip.includes(':')) return ip === '::1'; // IPv6: block only loopback
  const n = ipToInt(ip);
  return BLOCKED_RANGES.some(r => n >= ipToInt(r.start) && n <= ipToInt(r.end));
}

async function validateUrl(rawUrl: string): Promise<URL> {
  const parsed = new URL(rawUrl); // throws on malformed
  if (!['https:', 'http:'].includes(parsed.protocol)) {
    throw new Error('Only https: and http: schemes are allowed');
  }
  const hostname = parsed.hostname;
  // Block literal IP addresses in the URL
  if (isIP(hostname) && isBlockedIp(hostname)) {
    throw new Error('URL resolves to a blocked IP range');
  }
  // DNS rebinding protection: resolve hostname and check every returned IP
  if (!isIP(hostname)) {
    const addrs = await dns.resolve4(hostname).catch(() => [] as string[]);
    const addrs6 = await dns.resolve6(hostname).catch(() => [] as string[]);
    for (const ip of [...addrs, ...addrs6]) {
      if (isBlockedIp(ip)) throw new Error('URL resolves to a blocked IP range');
    }
  }
  return parsed;
}

export async function generatePdf(userUrl: string): Promise<Buffer> {
  const validated = await validateUrl(userUrl); // throws if blocked

  const browser = await puppeteer.launch({
    args: ['--no-sandbox', '--disable-setuid-sandbox']
  });
  const page = await browser.newPage();

  // Defense-in-depth: block requests inside the page as well
  // This catches redirects to internal URLs that bypass DNS pre-check
  await page.setRequestInterception(true);
  page.on('request', async (req) => {
    try {
      const reqUrl = new URL(req.url());
      const ips = await dns.resolve4(reqUrl.hostname).catch(() => [] as string[]);
      if (ips.some(isBlockedIp) || isBlockedIp(reqUrl.hostname)) {
        req.abort('blockedbyclient');
        return;
      }
    } catch {
      req.abort('blockedbyclient');
      return;
    }
    req.continue();
  });

  await page.goto(validated.href, { waitUntil: 'networkidle2', timeout: 15000 });
  const pdf = await page.pdf({ format: 'A4' });
  await browser.close();
  return pdf;
}

SSRF9-002 — wkhtmltopdf --header-html with user-supplied URL

wkhtmltopdf is a command-line tool that uses the Qt WebKit engine to convert HTML to PDF. It accepts a --header-html flag that specifies a URL or file path for the HTML content to render in the page header. Many MCP skill developers use this flag to inject branded letterheads or dynamic headers. The vulnerability is that if the header URL originates from user input — even indirectly via a configuration value that users can set — wkhtmltopdf will fetch that URL server-side and render it at the top of every PDF page.

Unlike puppeteer, wkhtmltopdf does not expose a request interception API. The only reliable mitigation is to prevent user-controlled values from reaching the --header-html argument. The header content should be generated from a local temporary file whose contents are derived from an allowlisted template, not from a user-supplied URL.

wkhtmltopdf deprecation note: The project is unmaintained as of 2024. Known SSRF and local file read vulnerabilities have been reported but not patched. If your MCP skill currently uses wkhtmltopdf, the safest migration path is to puppeteer or Playwright with request interception enabled from the start.

Wrong
// VULNERABLE — header URL taken from user-controlled config and passed to wkhtmltopdf
import { execFile } from 'child_process';
import { promisify } from 'util';

const execFileAsync = promisify(execFile);

interface ReportConfig {
  headerUrl: string; // user sets this in their account settings
  contentUrl: string;
}

async function renderReport(cfg: ReportConfig, outputPath: string): Promise<void> {
  // VULNERABLE: cfg.headerUrl is user-supplied — attacker sets it to
  // http://169.254.169.254/latest/meta-data/iam/security-credentials/
  // wkhtmltopdf fetches the IMDS URL and renders credentials in the PDF header
  await execFileAsync('wkhtmltopdf', [
    '--header-html', cfg.headerUrl,  // ← user-controlled SSRF vector
    '--footer-center', '[page]/[topage]',
    cfg.contentUrl,
    outputPath,
  ]);
}
Fixed
// FIXED — header HTML written to a local tmp file from a static template; no user URLs
import { execFile } from 'child_process';
import { promisify } from 'util';
import fs from 'fs/promises';
import os from 'os';
import path from 'path';
import { randomUUID } from 'crypto';

const execFileAsync = promisify(execFile);

// Static header template — no user-controlled input, only org name from safe source
function buildHeaderHtml(orgName: string): string {
  // Escape only trusted values; never interpolate user URLs here
  const safe = orgName.replace(/[<>&"]/g, c => ({'<':'&lt;','>':'&gt;','&':'&amp;','"':'&quot;'}[c]!));
  return `<!doctype html><html><body style="font-family:sans-serif;font-size:11px;color:#555">
    <span>${safe} — Confidential Audit Report</span>
  </body></html>`;
}

async function renderReport(
  orgName: string,   // comes from verified DB field, not raw user input
  contentHtmlPath: string, // local path to already-generated content
  outputPath: string
): Promise<void> {
  const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'report-'));
  const headerPath = path.join(tmpDir, 'header.html');
  try {
    await fs.writeFile(headerPath, buildHeaderHtml(orgName), 'utf8');
    // Pass a file:// path, not a user URL — wkhtmltopdf cannot fetch external URLs from here
    await execFileAsync('wkhtmltopdf', [
      '--header-html', headerPath,       // ← local file, not user URL
      '--no-external-links',             // block wkhtmltopdf from following any external href
      '--disable-javascript',            // JS disabled — no dynamic SSRF via script
      '--footer-center', '[page]/[topage]',
      contentHtmlPath,
      outputPath,
    ]);
  } finally {
    await fs.rm(tmpDir, { recursive: true, force: true });
  }
}

SSRF9-003 — html-pdf PhantomJS resolves file:// URIs from user HTML

The html-pdf npm package uses PhantomJS as its rendering engine. PhantomJS supports the file:// URI scheme in all contexts: <img src>, <iframe src>, CSS url(), and XHR requests in page scripts. When an MCP skill accepts a user-supplied HTML body and passes it to html-pdf for rendering, an attacker can embed file read payloads directly in the HTML.

The exploit is simple: include <img src="file:///etc/passwd"> in the HTML body. PhantomJS attempts to load the image, the content of /etc/passwd is treated as image data and embedded in the PDF as a broken image — but more usefully, the attacker can use an <iframe src="file:///proc/self/environ"> which PhantomJS renders as text, exposing environment variables including AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and DATABASE_URL.

Beyond the file read vector, PhantomJS itself is an unmaintained project with known CVEs and no path forward for security updates. MCP skills should migrate away from html-pdf and PhantomJS entirely. For skills that remain on this library short-term, the minimum mitigation is to strip all absolute URLs from the HTML using a server-side sanitizer before passing to html-pdf.

Wrong
// VULNERABLE — user HTML passed directly to html-pdf; PhantomJS resolves file:// URIs
import pdf from 'html-pdf';
import { promisify } from 'util';

// html-pdf doesn't natively support promises — wrap it
function createPdf(html: string, options: pdf.CreateOptions): Promise<pdf.CreateResult> {
  return new Promise((resolve, reject) => {
    pdf.create(html, options).toBuffer((err, res) => {
      if (err) reject(err); else resolve(res);
    });
  });
}

export async function generateAuditPdf(userHtml: string): Promise<Buffer> {
  // VULNERABLE: attacker sends HTML containing:
  //   <iframe src="file:///proc/self/environ"></iframe>
  // PhantomJS renders the env vars file and embeds it in the PDF
  const result = await createPdf(userHtml, { format: 'A4', border: '20mm' });
  return result.toBuffer();
}
Fixed
// FIXED — sanitize HTML with DOMPurify server-side before rendering; migrate to puppeteer
import { JSDOM } from 'jsdom';
import createDOMPurify from 'dompurify';
import puppeteer from 'puppeteer';
import dns from 'dns/promises';

const { window } = new JSDOM('');
const DOMPurify = createDOMPurify(window as unknown as Window);

// Strip all src/href attributes that are not safe relative paths or data: URIs
// FORBID_ATTR removes the most dangerous attributes entirely
function sanitizeHtml(dirty: string): string {
  return DOMPurify.sanitize(dirty, {
    FORBID_TAGS: ['script', 'object', 'embed', 'base', 'link', 'meta', 'iframe'],
    FORBID_ATTR: ['src', 'href', 'action', 'formaction', 'xlink:href'],
    ALLOW_DATA_ATTR: false,
    FORCE_BODY: true,
  });
}

export async function generateAuditPdf(userHtml: string): Promise<Buffer> {
  const clean = sanitizeHtml(userHtml);

  // Use puppeteer with request interception instead of html-pdf/PhantomJS
  const browser = await puppeteer.launch({ args: ['--no-sandbox'] });
  const page = await browser.newPage();

  // Block all navigation — we set content directly, no external fetches allowed
  await page.setRequestInterception(true);
  page.on('request', req => {
    // Allow only stylesheets and fonts from an explicit CDN allowlist
    const url = req.url();
    if (url.startsWith('data:') || url.startsWith('about:')) { req.continue(); return; }
    req.abort('blockedbyclient'); // block everything else
  });

  await page.setContent(clean, { waitUntil: 'domcontentloaded' });
  const pdf = await page.pdf({ format: 'A4', margin: { top: '20mm', bottom: '20mm', left: '20mm', right: '20mm' } });
  await browser.close();
  return pdf;
}

SSRF9-004 — Chromium DevTools Protocol exposed on :9222

When puppeteer or Playwright launches Chromium with remote debugging enabled — either explicitly via --remote-debugging-port=9222 or via the environment variable DEVTOOLS_PORT — the browser opens a WebSocket server on that port. The DevTools Protocol allows the connected client to call any CDP method: Page.navigate to navigate to any URL, Runtime.evaluate to run JavaScript in the page context, Network.enable to intercept all network traffic, and IO.read to stream any file. If the CDP port is bound to 0.0.0.0 rather than 127.0.0.1, any host that can reach the server's port 9222 — including other containers in the same Kubernetes namespace or any host in the same VPC — can connect and use the browser as a full SSRF and remote code execution primitive.

This is not a theoretical attack. In containerised MCP skill deployments it is common to find Chromium launched with debugging enabled for local development and never disabled in the production Dockerfile. A network scan for open port 9222 across a cloud environment's internal subnet will find exposed instances within seconds. Once connected, the attacker uses the CDP Page.navigate method to navigate the page to http://169.254.169.254/ and reads the response via Runtime.evaluate(() => document.body.innerText) — the full IMDS credential response is returned directly in the CDP protocol message.

Wrong
// VULNERABLE — Chromium launched with --remote-debugging-port bound to all interfaces
import puppeteer from 'puppeteer';

// Often inherited from a development Dockerfile ENV:
//   ENV DEVTOOLS_PORT=9222
// Or set during debugging and never removed:
const browser = await puppeteer.launch({
  args: [
    '--no-sandbox',
    '--disable-setuid-sandbox',
    `--remote-debugging-port=${process.env.DEVTOOLS_PORT || 9222}`,
    // VULNERABLE: no --remote-debugging-address flag defaults to 0.0.0.0
    // Any host on the same network can connect to ws://server-ip:9222/
    // and control this browser with full CDP access
  ]
});
Fixed
// FIXED — no remote debugging in production; if needed, bind explicitly to 127.0.0.1 only
import puppeteer from 'puppeteer';

const IS_DEV = process.env.NODE_ENV === 'development';

const args = [
  '--no-sandbox',
  '--disable-setuid-sandbox',
  '--disable-dev-shm-usage',   // avoids /dev/shm exhaustion in containers
  '--disable-gpu',
  // Never enable remote debugging in production:
];

if (IS_DEV && process.env.DEVTOOLS_PORT) {
  // Development only: bind to localhost so only local processes can connect
  args.push(`--remote-debugging-port=${process.env.DEVTOOLS_PORT}`);
  args.push('--remote-debugging-address=127.0.0.1'); // ← loopback only
}

const browser = await puppeteer.launch({ args });
// In production: no --remote-debugging-port flag at all
// If you need debugging in production: use puppeteer.connect() from a secure
// local tunnel (ssh -L), never expose CDP on a network-reachable port

Detection with SkillAudit

SA-SKL-SSRF9 is part of SkillAudit's SSRF rule family, which now covers nine distinct SSRF entry points across MCP skill codebases. The scanner uses AST analysis to trace data flow from tool call parameters to headless browser API calls. For puppeteer and Playwright, it checks whether request interception is enabled and whether the interceptor has a default-deny rule for RFC 1918 ranges. For wkhtmltopdf and html-pdf usage, it checks whether the HTML or URL arguments can be influenced by user-controlled values using taint analysis across async call boundaries.

For the CDP exposure pattern, SkillAudit checks the args array passed to the browser launcher for the presence of --remote-debugging-port without a corresponding --remote-debugging-address=127.0.0.1 argument. It also checks process.env reads for DEVTOOLS_PORT and similar names that might inject the flag indirectly.

SA-SKL-SSRF9 findings summary
Critical 9.1SSRF9-001 — puppeteer page.goto(userUrl) without request interception and IP validation
HIGH 8.2SSRF9-002 — wkhtmltopdf --header-html set from user-controlled config value
Critical 9.3SSRF9-003 — html-pdf PhantomJS rendering user HTML without DOMPurify src/href stripping
Critical 9.8SSRF9-004 — Chromium DevTools Protocol bound to 0.0.0.0:9222 in production container

Remediation checklist for MCP skills using headless rendering

FindingPatternSeverityVulnerable codeFix
SSRF9-001 puppeteer page.goto() on user URL Critical 9.1 page.goto(req.body.url) with no interception page.setRequestInterception(true) + DNS-based IP range validation before goto
SSRF9-002 wkhtmltopdf --header-html from user value High 8.2 ['--header-html', cfg.headerUrl] where headerUrl is user-settable Write header to a local tmp file from a static template; pass --no-external-links --disable-javascript
SSRF9-003 html-pdf PhantomJS renders user HTML Critical 9.3 pdf.create(userHtml) with no sanitization DOMPurify FORBID_ATTR src/href before create; migrate to puppeteer with request interception
SSRF9-004 CDP port exposed on 0.0.0.0 Critical 9.8 --remote-debugging-port=9222 without address restriction Remove flag in production; dev only with --remote-debugging-address=127.0.0.1

Relationship to other SSRF patterns in MCP skills

Headless browser SSRF is the highest-impact variant of a broader SSRF class that SkillAudit tracks across all MCP skill codebases. For the more common fetch() and axios.get() SSRF patterns — including markdown image rendering and RSS feed import — see the SA-SKL-SSRF8 guide on markdown and HTML render server-side SSRF. For the foundational SSRF detection approach that covers fetch-based SSRF across MCP skills more broadly, see the MCP server SSRF security reference. The CORS patterns that sometimes occur alongside headless renderer deployments — particularly internal microservice CORS that makes CDN-exposed renderer endpoints cross-origin readable — are covered in SA-SKL-CORS11: internal microservice CORS security.

Run SA-SKL-SSRF9 on your skill: Paste your MCP skill's GitHub URL at skillaudit.dev to get a full SSRF9 scan alongside all other SkillAudit security checks. The free tier covers public repositories with a shareable badge you can embed in your README to show the Anthropic skills directory reviewers your security posture before submission.

Related rule
SA-SKL-SSRF9: SSRF via PDF Generation and Headless Browser Rendering
Related rule
SA-SKL-SSRF8: SSRF via Markdown and HTML Render Server-Side