SSRF through an AI agent's “fetch this URL” tool – how it happens and how to block it

By Abheesht Tripathi · Published

Risk: fetch_url("http://169.254.169.254/latest/meta-data/iam/security-credentials/") runs on your server because a user, a web page or an email told the model to call it

What happens

Server-side request forgery (SSRF) means getting your server to send a request the attacker chooses. Your server can reach places the attacker can't: cloud metadata endpoints that hand out credentials, localhost admin ports, internal APIs and databases on a private network. Any feature that fetches a user-supplied URL is a candidate: link previews, “import from URL”, webhooks you call, image URLs.

AI agents widen the door. The URL doesn't have to come from a form field: the model picks it, and the model can be steered by the user, by a web page it read, or by an email it summarised (indirect prompt injection). A fetch_url or browser tool therefore needs the same protection as any SSRF-prone endpoint, plus the assumption that every URL may be hostile.

Targets to block

Fix 1: allowlist when you can

If the agent only needs your docs, a few APIs or a known set of sites, allow exactly those hosts and reject everything else. That is far stronger than any blocklist.

Fix 2: check the IP you actually connect to

For open-web fetching, validate at connection time, after DNS resolution, so rebinding can't slip through. In Node.js, give undici a custom lookup and refuse non-public addresses (this uses the ipaddr.js package):

import dns from 'node:dns';
import net from 'node:net';
import ipaddr from 'ipaddr.js';
import { Agent, fetch } from 'undici';

function isPublic(ip: string): boolean {
  let addr = ipaddr.parse(ip);
  if (addr.kind() === 'ipv6' && (addr as ipaddr.IPv6).isIPv4MappedAddress()) {
    addr = (addr as ipaddr.IPv6).toIPv4Address();
  }
  return addr.range() === 'unicast';          // not private, loopback, linkLocal, carrierGradeNat, ...
}

const safeAgent = new Agent({
  connect: {
    lookup(hostname, options: any, callback: any) {
      dns.lookup(hostname, { ...options, all: true }, (err, addresses: any) => {
        if (err) return callback(err);
        if (!addresses.length || addresses.some((a: any) => !isPublic(a.address))) {
          return callback(new Error('blocked: non-public address'));
        }
        if (options.all) return callback(null, addresses);
        callback(null, addresses[0].address, addresses[0].family);
      });
    },
  },
});

export async function safeFetch(raw: string, hops = 0): Promise<string> {
  const url = new URL(raw);
  if (!['http:', 'https:'].includes(url.protocol)) throw new Error('scheme not allowed');
  const host = url.hostname.replace(/^\[|\]$/g, '');
  if (net.isIP(host) && !isPublic(host)) throw new Error('blocked IP');   // IP literals skip DNS lookup

  const res = await fetch(url, {
    dispatcher: safeAgent,
    redirect: 'manual',
    signal: AbortSignal.timeout(5000),
  });
  if (res.status >= 300 && res.status < 400 && res.headers.get('location')) {
    if (hops >= 3) throw new Error('too many redirects');
    return safeFetch(new URL(res.headers.get('location')!, url).toString(), hops + 1);  // re-checked
  }
  const text = await res.text();
  return text.slice(0, 100_000);               // cap what goes back into the model
}

The WHATWG URL parser normalises odd IPv4 spellings to dotted form, and the custom lookup runs for every connection, including redirect hops. Never forward the user's cookies or your own API keys on these requests.

Fix 3: isolate the fetcher on the network

Code checks are one layer. Also run URL fetching where internal targets aren't reachable: a separate container or function with no access to your private network, or an egress proxy that enforces the same rules for every outbound request (Stripe's open-source Smokescreen is one). On AWS, require IMDSv2: metadata then needs a token obtained with a PUT request and a special header, which a simple GET-based SSRF cannot do.

Fix 4: treat the page as untrusted input

Whatever the tool fetched goes back into the model's context. It can contain instructions, so a turn that fetched a web page should not be able to call sending or writing tools without a user confirmation.

How to verify

Ask the agent (or call the tool directly) with each of: http://169.254.169.254/latest/meta-data/, http://127.0.0.1:5432/, http://[::1]/, http://2130706433/, file:///etc/passwd, a public URL that redirects to http://127.0.0.1/, and a hostname you control that resolves to 10.0.0.1. Every one must fail before any connection to the internal address is made; a normal public page still loads.

Related guides

More in AI agent and LLM app security · all guides