AleannLab

SSRF: When Your "Import From URL" Feature Fetches Your Own Infrastructure

AleannLab team2 min read

Server-side request forgery (SSRF) happens when your server fetches a URL that a user supplied. The request comes from inside your network, so it can reach things the internet cannot: cloud metadata endpoints that hand out credentials, admin panels on localhost, databases and internal APIs. Any feature that fetches user URLs needs an allowlist of schemes, a check on the resolved IP address, no blind redirects, and limits on time and size.

On this page
  1. The vulnerable pattern
  2. Why simple checks fail
  3. A fetch that holds
  4. Defence in depth
  5. AI agents with web access
  6. Test it

Features that cause it are ordinary and popular in AI products: "import from URL", link previews, "summarise this page", avatar from URL, webhook test buttons, PDF generation from HTML, and AI agents with a web-fetch tool.

The vulnerable pattern

TypeScript
export async function POST(req: Request) {
  const { url } = await req.json();
  const res = await fetch(url);                  // whatever the user asked for
  const html = await res.text();
  return Response.json({ title: extractTitle(html), body: html.slice(0, 5000) });
}

Things a user can send:

code
http://169.254.169.254/latest/meta-data/iam/security-credentials/
http://localhost:5432/
http://127.0.0.1:3000/api/admin/users
http://10.0.0.12:9200/_cat/indices
file:///etc/passwd

The first is the AWS instance metadata service. On a server that still allows the older IMDSv1, it returns temporary cloud credentials in plain text. Google Cloud and Azure have equivalents.

Even when the response is not shown to the user, SSRF can reveal which internal ports are open (by timing), trigger internal actions on GET, or be chained with other bugs.

Why simple checks fail

A blocklist of strings like localhost and 127.0.0.1 is bypassed by:

  • other spellings: http://2130706433/, http://0x7f.1/, http://[::1]/, http://127.1/
  • a public hostname whose DNS record points at 127.0.0.1 or 10.x
  • a public URL that redirects to an internal one
  • DNS that answers differently the second time (rebinding), between your check and the fetch

A fetch that holds

TypeScript
import { lookup } from 'node:dns/promises';
import ipaddr from 'ipaddr.js';

async function assertPublicUrl(raw: string): Promise<URL> {
  const url = new URL(raw);
  if (!['http:', 'https:'].includes(url.protocol)) throw new Error('Scheme not allowed');
  if (url.port && !['80', '443'].includes(url.port)) throw new Error('Port not allowed');

  const addresses = await lookup(url.hostname, { all: true });
  for (const { address } of addresses) {
    const range = ipaddr.process(address).range();
    if (range !== 'unicast') throw new Error('Address not allowed');   // private, loopback, link-local...
  }
  return url;
}

export async function safeFetch(raw: string) {
  let url = await assertPublicUrl(raw);
  for (let hops = 0; hops < 3; hops++) {
    const res = await fetch(url, {
      redirect: 'manual',
      signal: AbortSignal.timeout(5000),
      headers: { 'User-Agent': 'YourApp-LinkPreview/1.0' },
    });
    if (res.status >= 300 && res.status < 400 && res.headers.get('location')) {
      url = await assertPublicUrl(new URL(res.headers.get('location')!, url).href);  // check every hop
      continue;
    }
    return res;
  }
  throw new Error('Too many redirects');
}

Read the body with a size cap and check the content type before parsing it.

The check-then-fetch gap still leaves DNS rebinding possible. Closing it fully means connecting to the IP address you checked (a custom agent such as ssrf-req-filter or request-filtering-agent for Node does this), or sending all outbound fetches through an egress proxy that enforces the rules.

Defence in depth

  • Allowlist domains when the feature only needs a few (your CDN, YouTube, GitHub). Much safer than filtering everything else.
  • Require IMDSv2 on AWS and set the hop limit to 1, so containers cannot reach the metadata service through a forwarded request.
  • Run fetchers where there is nothing to reach: a separate function or service with no VPC access and no credentials in its environment.
  • Do not return raw responses. Return the extracted title and image, not the full body and headers.
  • Headless browsers (PDF and screenshot features) are SSRF engines with JavaScript. Run them sandboxed, without network access to internal ranges, and block file://.

AI agents with web access

A fetch tool given to an LLM is an SSRF surface that anyone who can put text in front of the model can steer. See prompt injection in LLM features. The tool should use the same safe fetch, with a domain allowlist where possible.

Test it

Point your URL feature at:

code
http://127.0.0.1:<your-app-port>/
http://169.254.169.254/latest/meta-data/
http://[::1]/
http://2130706433/

and at a URL on a server you control that answers with a 302 redirect to http://127.0.0.1/. Every one should be refused, ideally with the same generic error.

If your product fetches user-supplied URLs, we review that path as part of our app rescue and security audit. The rest of the checks are in our security checklist for vibe-coded apps.

All articles →

Gotowy, aby omówić swój projekt z nami?

idea
*
*
*
Interesuje mnie...
Tworzenie stron internetowych
Tworzenie aplikacji
Projektowanie UX/UI
DevOps
Sztuczna inteligencja i uczenie maszynowe
Testowanie QA
Tworzenie aplikacji mobilnych
Konsultacja
Outsourcing
Budżet projektu (USD)
≤ $5K
$10K-$20K
$30K-$40K
$50K-$60K
>$100K
Prześlij plik