Skip to content

SSRF in AI Agents & Webhooks: Blocking Cloud Metadata Leaks

AI agent or webhook vulnerable to SSRF? Block 169.254.169.254, defeat DNS rebinding, enforce AWS IMDSv2, and deploy forward proxy egress filters.

SSRF in AI Agents & Webhooks: Blocking Cloud Metadata Leaks

You give an autonomous AI agent a web-browsing tool, or allow customers to configure outbound webhook notification URLs. Within days, automated security scanners or malicious actors feed the input field manipulated addresses, probing your internal network perimeter.

Server-Side Request Forgery (SSRF) occurs when an application backend makes an outbound HTTP request to an untrusted URL supplied by a client. In cloud environments, the ultimate prize is 169.254.169.254, the link-local Instance Metadata Service (IMDS). Stealing temporary IAM credentials from IMDS allows attackers to pivot directly into your AWS, GCP, or Azure infrastructure.

Here is the immediate triage checklist to audit and defend against SSRF:

  1. Enforce AWS IMDSv2 Globally: Disable IMDSv1 across all EC2 instances, EKS worker nodes, and ECS tasks by setting HttpTokens=required and configuring the hop limit to 1.
  2. Block Link-Local and Private Ranges at the Firewall: Implement host-level iptables or cloud security group egress rules dropping all outbound packets destined for 169.254.169.254/32 and RFC 1918 private subnets.
  3. Validate and Pin IP Addresses Before Socket Connection: Resolve the target hostname to an IP address, verify that the IP is not in private or reserved ranges, and connect directly to the verified IP to defeat DNS rebinding attacks.
  4. Isolate Outbound Fetches via Dedicated Forward Proxies: Route all customer webhooks and AI agent web crawlers through an egress proxy (like Stripe’s open-source Smokescreen) situated in an isolated DMZ VPC.

Illustrative command verifying whether an AWS EC2 instance still permits insecure IMDSv1 access:

# Check if IMDSv2 is strictly enforced on the host
aws ec2 describe-instances --instance-ids i-0123456789abcdef0 \
  --query "Reservations[].Instances[].MetadataOptions"

Illustrative output showing a vulnerable IMDSv1 configuration:

[
  {
    "State": "applied",
    "HttpTokens": "optional",
    "HttpPutResponseHopLimit": 2,
    "HttpEndpoint": "enabled"
  }
]

When HttpTokens is optional, any simple GET request issued by a vulnerable application can exfiltrate IAM role credentials without authentication.


The Target: Why Attackers Exploit 169.254.169.254

The link-local IPv4 address 169.254.169.254 (defined in RFC 3927) is reserved for local communication between an operating system instance and the underlying hypervisor.

Cloud providers leverage this address to provide instance metadata to running workloads:

  • AWS: Instance identity, user-data startup scripts, and AWS Security Token Service (STS) temporary credentials for the attached IAM instance profile.
  • GCP: Instance attributes, service account tokens, and SSH keys via metadata.google.internal.
  • Azure: Subscription IDs, managed identity tokens, and VM scale set configuration via the Azure Instance Metadata Service.

In an unhardened environment (IMDSv1), an attacker who controls a webhook URL or feeds a link to an AI document summarizer simply targets:

GET /latest/meta-data/iam/security-credentials/production-backend-role HTTP/1.1
Host: 169.254.169.254

The vulnerable application server issues an internal GET request, receives the JSON payload containing AccessKeyId, SecretAccessKey, and Token, and reflects or processes the data. The attacker extracts the keys and gains complete administrative API access to the cloud account.

+-------------------------------------------------------------------------+
|                    Classic Cloud SSRF Exploitation Path                 |
|                                                                         |
| Attacker                                                                |
|   |--- Inputs URL: "169.254.169.254/.../security-credentials/"          |
|   v                                                                     |
| Vulnerable Backend Server (EC2 / Container)                             |
|   |--- Fetches: 169.254.169.254 (Allowed internally!) ---------------+  |
|   |                                                                  |  |
|   v                                                                  v  |
| AWS Hypervisor Metadata Engine                                          |
|   Emits temporary IAM AccessKeyId, SecretAccessKey, and SessionToken.   |
|   Backend reflects data back to attacker -> Complete Account Takeover!  |
+-------------------------------------------------------------------------+

The Three Most Common SSRF Filter Bypass Vectors

Naively checking url.hostname != "169.254.169.254" fails reliably. Attackers leverage protocol parsing inconsistencies and DNS manipulation to circumvent basic regex validation.

1. Alternative IP Representations

The IPv4 specification allows multiple numerical encodings. Operating system network sockets parse hexadecimal, octal, and single-integer representations transparently:

  • Dotted Decimal: 169.254.169.254
  • Integer (Dword): 2852039166
  • Hexadecimal: 0xa9fea9fe
  • Octal: 0251.0376.0251.0376
  • IPv6 Mapped IPv4: [::ffff:169.254.169.254] or [::ffff:a9fe:a9fe]

A simple string comparison looking for "169.254.169.254" lets all four alternative encodings pass directly to the underlying HTTP client, which resolves them to the metadata service.

2. The DNS Rebinding Race Condition

Many developers implement SSRF protection by resolving the domain to an IP address, checking that IP against a blocklist, and then invoking standard fetch libraries:

// ❌ Dangerous Anti-Pattern: Vulnerable to Time-of-Check to Time-of-Use (TOCTOU)
const ip = await dns.resolve(targetUrl.hostname);
if (isPrivateIp(ip)) {
  throw new Error("Forbidden IP");
}
// DNS Rebinding window: The hostname is resolved a SECOND time here!
const response = await fetch(targetUrl);

An attacker configures an authoritative DNS server for attacker.internal with a TTL = 0:

  1. When your application calls dns.resolve(), the attacker’s DNS server returns a benign public IP (198.51.100.1). The check passes.
  2. Milliseconds later, fetch(targetUrl) establishes a TCP socket. The operating system resolves attacker.internal a second time.
  3. The attacker’s DNS server immediately responds with 169.254.169.254.
  4. The fetch client connects directly to the metadata endpoint, completely bypassing your validation check.

3. Open Redirect Chaining

If your application follows HTTP 301, 302, or 307 redirects automatically, attackers supply a benign public URL (attacker.internal/webhook).

When your server issues the request, the remote server replies:

HTTP/1.1 302 Found
Location: /latest/meta-data/

If redirect handling is unconstrained, the HTTP client follows the redirect path internally, querying the link-local metadata address behind your firewall.


Defense in Depth 1: Enforcing AWS IMDSv2

The most robust architectural defense on AWS is enforcing IMDSv2 and adhering to OWASP SSRF Prevention Guidance.

IMDSv2 transitions the metadata service from simple GET requests to a session-oriented protocol requiring token negotiation:

  1. The client must first send an HTTP PUT request with the header X-aws-ec2-metadata-token-ttl-seconds: 21600.
  2. The metadata service returns a signed secret token.
  3. The client includes this token in the header X-aws-ec2-metadata-token on subsequent GET requests.

Because virtually all SSRF vulnerabilities in web applications (image downloaders, link previews, webhook dispatchers) only execute GET or POST requests and cannot inject arbitrary PUT headers, IMDSv2 neutralizes the exploit vector at the hypervisor boundary.

Enabling IMDSv2 via AWS CLI

Enforce IMDSv2 across existing EC2 instances:

# Require IMDSv2 and restrict hop limit to 1
aws ec2 modify-instance-metadata-options \
  --instance-id i-0123456789abcdef0 \
  --http-tokens required \
  --http-put-response-hop-limit 1 \
  --http-endpoint enabled

The Hop Limit Constraint: Protecting Docker Containers

Notice the directive --http-put-response-hop-limit 1.

When your application runs inside a Docker container or Kubernetes pod using bridge networking, packets traveling from the container to the host hypervisor decrement the IP packet’s Time To Live (TTL) by 1 hop.

If http-put-response-hop-limit is set to 1, the packet’s TTL drops to 0 when passing through the container bridge, causing the network stack to discard the packet before it reaches 169.254.169.254. This guarantees that containers cannot reach the host metadata service, even if they attempt IMDSv2 token negotiation.


Defense in Depth 2: Hardened Node.js Outbound Fetch Wrapper

To defend against DNS rebinding, IP obfuscation, and redirect attacks at the application layer, you must intercept the socket connection at the TCP level.

The following production TypeScript implementation resolves the DNS query once, normalizes IP addresses, checks against all private and link-local ranges, pins the resolved IP directly to the socket, and disables automatic redirect following:

// safe-fetch.ts
import http from "http";
import https from "https";
import dns from "dns/promises";
import ipaddr from "ipaddr.js";
import { URL } from "url";

// Define blocked CIDR ranges: Link-Local, Loopback, Private RFC 1918, Carrier-grade NAT
const BLOCKED_RANGES = [
  "0.0.0.0/8",
  "10.0.0.0/8",
  "100.64.0.0/10",
  "127.0.0.0/8",
  "169.254.0.0/16", // Cloud Metadata & Link-Local
  "172.16.0.0/12",
  "192.168.0.0/16",
  "::1/128",        // IPv6 Loopback
  "fc00::/7",       // IPv6 Unique Local
  "fe80::/10",      // IPv6 Link-Local
];

export async function safeOutboundFetch(
  targetUrlString: string,
  options: { timeoutMs?: number; maxBytes?: number } = {}
): Promise<{ statusCode: number; body: string }> {
  const timeoutMs = options.timeoutMs || 5000;
  const maxBytes = options.maxBytes || 1024 * 1024; // 1MB ceiling

  const parsedUrl = new URL(targetUrlString);

  // 1. Strictly enforce HTTP/HTTPS protocols
  if (parsedUrl.protocol !== "http:" && parsedUrl.protocol !== "https:") {
    throw new Error(`Disallowed protocol: ${parsedUrl.protocol}`);
  }

  // 2. Resolve DNS and validate the IP
  const lookupResults = await dns.lookup(parsedUrl.hostname, { all: true });
  if (lookupResults.length === 0) {
    throw new Error("DNS resolution yielded zero addresses.");
  }

  // Select the first resolved IP
  const resolvedIp = lookupResults[0].address;
  const parsedIp = ipaddr.parse(resolvedIp);

  // Check if IP falls within any blocked range
  for (const cidr of BLOCKED_RANGES) {
    const range = ipaddr.parseCIDR(cidr);
    if (parsedIp.kind() === range[0].kind() && (parsedIp as any).match(range)) {
      throw new Error(`SSRF Blocked: IP ${resolvedIp} belongs to restricted range ${cidr}`);
    }
  }

  // 3. Connect directly to the validated IP to defeat DNS rebinding
  return new Promise((resolve, reject) => {
    const isHttps = parsedUrl.protocol === "https:";
    const transport = isHttps ? https : http;

    const requestOptions: http.RequestOptions = {
      protocol: parsedUrl.protocol,
      host: resolvedIp, // Connect to IP directly
      port: parsedUrl.port || (isHttps ? 443 : 80),
      path: parsedUrl.pathname + parsedUrl.search,
      method: "GET",
      headers: {
        Host: parsedUrl.hostname, // Preserve original Host header for virtual hosts
        "User-Agent": "SecureWebhookDispatcher/1.0",
      },
      timeout: timeoutMs,
      // Verify TLS certificate against the original hostname, not the raw IP
      servername: isHttps ? parsedUrl.hostname : undefined,
    };

    const req = transport.request(requestOptions, (res) => {
      // 4. Do not follow redirects automatically
      if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400) {
        req.destroy();
        return reject(new Error("Automated redirects are prohibited for untrusted URLs."));
      }

      let receivedBytes = 0;
      let bodyData = "";

      res.on("data", (chunk) => {
        receivedBytes += chunk.length;
        if (receivedBytes > maxBytes) {
          req.destroy();
          return reject(new Error("Response exceeded maximum allowable size payload."));
        }
        bodyData += chunk.toString("utf8");
      });

      res.on("end", () => {
        resolve({
          statusCode: res.statusCode || 200,
          body: bodyData,
        });
      });
    });

    req.on("timeout", () => {
      req.destroy();
      reject(new Error("Outbound request timed out."));
    });

    req.on("error", (err) => reject(err));
    req.end();
  });
}

Defense in Depth 3: Host Firewall Rules (iptables)

Even if application code contains validation bugs, operating system firewall rules provide an unbreakable baseline.

Add the following iptables rule on EC2 worker nodes or Docker container hosts to drop all traffic destined for 169.254.169.254 originating from non-root processes:

# Block non-root processes from accessing AWS metadata service
sudo iptables --append OUTPUT \
  --proto tcp \
  --destination 169.254.169.254 \
  --match owner ! --uid-owner 0 \
  --jump DROP

With this rule active, standard application runtimes (such as node, python, or www-data running under UID 1000) are blocked by the Linux kernel from reaching the metadata IP. Only system root daemons can interact with hypervisor metadata.


Comparison: SSRF Defense Strategies

The following table contrasts defense layers across architectural complexity, effectiveness, and bypass resistance:

Defense MechanismLayerResists DNS Rebinding?Resists 302 Redirects?Operational Overhead
URL Regex / Domain FilterApplicationNo (DNS changes)No (Redirects bypass)Minimal (Easily broken)
IP Pinning in Socket HookApplicationYes (Pins IP)Yes (Disables redirects)Moderate (Custom fetch agent)
AWS IMDSv2 (Hop Limit 1)HypervisorYes (Requires PUT token)Yes (Clients lack token)Minimal (One-time AWS config)
Host iptables RuleLinux KernelYes (Drops packet by IP)Yes (Kernel blocks socket)Low (Host provisioning script)
Dedicated DMZ Proxy (Smokescreen)NetworkYes (Centralized egress)Yes (Enforces ACLs)High (Requires dedicated proxy infra)

Frequently Asked Questions

Does Google Cloud Platform (GCP) suffer from the same SSRF vulnerability?

Yes, but GCP enforces a mandatory HTTP header: Metadata-Flavor: Google. A plain GET request that cannot inject custom headers will receive a 403 Forbidden response. However, if your application allows users to customize headers, GCP metadata is vulnerable unless blocked.

Can an attacker reach 169.254.169.254 from client-side browser JavaScript?

No. Web browsers enforce CORS and private network access protections. Client-side browser code cannot access link-local IP ranges. SSRF specifically targets backend servers making outbound HTTP requests on behalf of users.

Does setting up AWS VPC Endpoints prevent SSRF to metadata?

No. VPC Endpoints route traffic to AWS service APIs (such as S3 or DynamoDB) through private AWS network pathways, but 169.254.169.254 is a link-local address serviced directly by the host hypervisor, completely independent of VPC routing tables.

Why is disabling HTTP redirects necessary?

Because an attacker can host a server that passes all initial domain and IP validations, and then emits an HTTP 302 Found redirect targeting 169.254.169.254/. If the client follows the redirect, the secondary request bypasses initial checks.


Written By

Marcus Vance

Principal Systems Architect

Systems engineer focusing on distributed backends, database concurrency, and application security. Specializes in high-throughput PostgreSQL concurrency, serverless connection pooling, and infrastructure hardening.

Practice: Vexn • Focus: Deep Engineering, Infrastructure & Security
Frequently Asked Questions
What is Server-Side Request Forgery (SSRF) and why is 169.254.169.254 targeted?
SSRF occurs when a backend server fetches a user-supplied URL without proper validation. Attackers target the link-local IP 169.254.169.254 because cloud providers (AWS, GCP, Azure) host their Instance Metadata Service on this address, exposing temporary IAM credentials and cluster secrets.
How does DNS rebinding bypass simple IP blocklists in SSRF filters?
In a DNS rebinding attack, an attacker controls an authoritative name server that returns a public IP during initial application validation with a 0-second TTL, and then immediately responds with 169.254.169.254 when the HTTP client establishes the actual TCP connection.
Why does AWS IMDSv2 prevent SSRF credential exfiltration?
IMDSv2 requires a session token obtained via an HTTP PUT request with the X-aws-ec2-metadata-token-ttl-seconds header before serving metadata. Most SSRF vectors (such as blind image scrapers or URL unfurlers) only support simple GET or POST requests and cannot inject custom PUT headers.
What is the recommended egress architecture for outbound webhooks and AI agent tools?
Route all untrusted outbound web traffic through an isolated forward proxy (such as Smokescreen) operating in a dedicated DMZ subnet, paired with network-level iptables rules blocking link-local and RFC 1918 private IP ranges.
Need an Architectural Audit?

Have our team inspect your AI-generated codebase.

48-hour turnaround with direct pull requests fixing security and scale bottlenecks.

Request Audit