CYART // SCHEMA · REQUEST-PATH7 NODES · 6 LINKSLOOKUP1HTTPS234READ / WRITE5HIT FIRSTACTOR · User — browser / appACTOR01Userbrowser / appEDGE · DNS — resolves nameEDGE02DNSresolves nameEDGE · CDN / WAF — TLS ends hereEDGE03CDN / WAFTLS ends hereEDGE · Load balancer — L7, health checksEDGE04Load balancerL7, health checksSERVICE · API service — authn + authzSERVICE05API serviceauthn + authzDATA · Database — primary + replicasDATA06Databaseprimary + replicasDATA · Cache — short TTLDATA07Cacheshort TTL

Server-side request forgery for defenders

How features that fetch URLs become a proxy into your network and cloud metadata service, why blocklists of hostnames fail, and the layered fix: avoid user URLs, validate resolved addresses, pin and re-check redirects, isolate egress and require IMDSv2.

FREEBy ·Lesson·13 min read·Intermediate → Advanced
SSRFcloud metadata IMDSv2DNS rebindingegress proxywebhook securityCapital One breach

01Your server as the attacker's proxy

✓What you will learn
  • Explain SSRF and recognise the features that create it
  • Describe why cloud metadata services and internal admin endpoints are the usual targets
  • Explain why hostname blocklists fail (encodings, redirects, DNS rebinding)
  • Build a layered fix: resolved-IP validation, pinning, egress isolation and IMDSv2

Server-side request forgery (SSRF) happens when an application fetches a URL that an attacker controls, from inside your network. The request comes from a trusted host, so it can reach things the attacker cannot: internal admin panels, databases with HTTP interfaces, service meshes and the cloud provider's metadata endpoint.

FeatureWhy it fetchesSSRF risk
WebhooksCalls a customer-supplied callback URLCustomer points it at http://10.0.0.5/admin
Link previews and unfurlingFetches a page to show title and imageFetches internal pages and returns their content
Import from URLAvatar, CSV or document importReads internal files over HTTP, or file:// if allowed
PDF and HTML renderersHeadless browser renders user-supplied HTMLMarkup such as an iframe or image pointing at internal hosts
XML parsersExternal entities resolve URLsXXE becomes SSRF
FigWhere SSRF reaches
CYART // SCHEMA · REQUEST-PATH7 NODES · 6 LINKSLOOKUP1HTTPS234READ / WRITE5HIT FIRSTACTOR · User — browser / appACTOR01Userbrowser / appEDGE · DNS — resolves nameEDGE02DNSresolves nameEDGE · CDN / WAF — TLS ends hereEDGE03CDN / WAFTLS ends hereEDGE · Load balancer — L7, health checksEDGE04Load balancerL7, health checksSERVICE · API service — authn + authzSERVICE05API serviceauthn + authzDATA · Database — primary + replicasDATA06Databaseprimary + replicasDATA · Cache — short TTLDATA07Cacheshort TTL
  • ACTOR
  • EDGE
  • SERVICE
  • DATA
  • Live flow
  • Lookup / async
//An external request lands on an application server that sits inside the trusted network. If that server fetches attacker-chosen URLs, every internal service and the metadata endpoint reachable from it are reachable by the attacker.

02Cloud metadata and other targets

Every major cloud exposes an instance metadata service (IMDS) at the link-local address 169.254.169.254. It returns details about the instance and, crucially, temporary credentials for the instance's IAM role. An SSRF that can read metadata turns into cloud API access with whatever that role allows.

The Capital One breach in 2019 is the reference case. A misconfigured web application firewall could be made to fetch arbitrary URLs; the attacker requested the role credentials from IMDSv1 and used them to read S3 buckets holding data on roughly 100 million people. The role had far more S3 access than the WAF needed, which turned a request-forgery bug into a breach.

ProviderMetadata protection
AWSIMDSv2 requires a session token obtained with an HTTP PUT carrying a TTL header; a hop limit of 1 stops containers and forwarded requests reaching it. Can be enforced per instance or account-wide
Google CloudRequests must include Metadata-Flavor: Google; requests containing X-Forwarded-For are rejected
AzureRequests must include Metadata: true and must not include X-Forwarded-For
  • Other internal targets: localhost admin ports, Redis and Elasticsearch HTTP APIs, the Kubernetes API and kubelet, internal dashboards that trust the network, and other services' unauthenticated health or debug endpoints.
  • Blind SSRF: the response is never shown, but the request still happens. Attackers detect it with an out-of-band callback to a domain they control, and use it for port scanning by timing.

03Why blocklists fail

The obvious first fix, rejecting URLs whose host is localhost or 169.254.169.254, fails because there are many ways to write the same address and because the hostname you check is not necessarily where the request ends up.

TrickExampleWhy the naive check misses it
Alternative IP notationhttp://2130706433/ or http://0x7f.1/Both mean 127.0.0.1 to many URL parsers and resolvers
IPv6 formshttp://[::ffff:127.0.0.1]/IPv4-mapped IPv6 loopback
DNS pointing inwardhttp://internal.attacker.example/ resolving to 10.0.0.5The hostname looks external
RedirectsExternal URL returns 302 Location: http://169.254.169.254/...The check ran only on the first URL
DNS rebindingFirst lookup returns a public IP, second returns 127.0.0.1Validation and connection resolve separately
Parser differenceshttp://good.example@evil.example/Validator and HTTP client disagree on the host
!Validate what you connect to, not what you were given

The only check that holds is on the IP address the socket actually connects to, after DNS resolution, on every hop. Parse the URL once with the same library that makes the request.

04The layered fix

  1. Avoid it: if the feature does not need arbitrary URLs, do not accept them. Let users upload files instead of supplying URLs; offer a fixed list of integration endpoints.
  2. Allow-list where you can: webhooks to registered domains, imports from known providers.
  3. Validate the resolved IP against blocked ranges (loopback, private, link-local, carrier-grade NAT, unique-local IPv6, the metadata address), then connect to that exact IP so a second DNS answer cannot differ.
  4. Restrict schemes and ports to https (and http if you must) on 443 and 80. No file, gopher, ftp or dict.
  5. Handle redirects manually and re-run every check on each Location, with a small hop limit.
  6. Isolate egress: route all user-directed fetches through a dedicated egress proxy in its own network segment that cannot reach internal ranges at all. Stripe's open-source Smokescreen is an example.
  7. Harden the targets: require IMDSv2 with a hop limit of 1, give instance roles least privilege, and require authentication on internal services instead of trusting the network.
Validating the resolved destinationts
import { lookup } from "node:dns/promises";
import { BlockList, isIP } from "node:net";

const blocked = new BlockList();
for (const [net, bits] of [["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], ["172.16.0.0", 12], ["192.168.0.0", 16]] as const) blocked.addSubnet(net, bits, "ipv4");
for (const [net, bits] of [["::1", 128], ["fc00::", 7], ["fe80::", 10], ["::ffff:0:0", 96]] as const) blocked.addSubnet(net, bits, "ipv6");

export async function vetUrl(raw: string): Promise<{ url: URL; address: string; family: 4 | 6 }> {
  const url = new URL(raw);                                   // parse once; reuse this object for the request
  if (url.protocol !== "https:") throw new Error("scheme not allowed");
  if (url.port && url.port !== "443") throw new Error("port not allowed");
  if (url.username || url.password) throw new Error("credentials in URL not allowed");
  const host = url.hostname.replace(/^\[|\]$/g, "");
  const answers = isIP(host) ? [{ address: host, family: isIP(host) as 4 | 6 }] : await lookup(host, { all: true });
  for (const a of answers) {                                  // every answer must be public, not just the first
    if (blocked.check(a.address, a.family === 6 ? "ipv6" : "ipv4")) throw new Error("destination not allowed");
  }
  return { url, address: answers[0].address, family: answers[0].family as 4 | 6 };
  // Connect to 'address' (for example via a custom lookup on the HTTP agent), keep SNI and Host as url.hostname,
  // set redirect handling to manual, and call vetUrl again on every Location header.
}
iDefence in depth is not optional here

Application checks will eventually have a gap: a new HTTP library, a renderer that follows redirects on its own, an IPv6 form nobody thought of. The egress proxy and IMDSv2 are what make that gap harmless.

05Explaining it well

▭On the whiteboard · SSRF controls by layer4 points
01
feature
no user URLs if possible | allow-list destinations | upload instead of fetch
02
application
parse once | https only | resolve and check every IP | pin the IP | re-check redirects
03
network
dedicated egress proxy | no route from fetchers to internal ranges
04
targets
IMDSv2 required, hop limit 1 | least-privilege roles | auth on internal services
◎Interview radar

"Design a webhook feature securely" is a favourite. Interviewers want SSRF named early, then the layers: resolved-IP validation with pinning (to beat DNS rebinding), manual redirect handling, an isolated egress proxy, and IMDSv2. Citing Capital One shows you understand that the role's permissions decided the blast radius, not just the bug.

“How to say it in the room

"Any feature that fetches a user-supplied URL is SSRF unless proven otherwise. I'd accept only https, resolve the host, reject if any address is private, loopback, link-local or metadata, then connect to that vetted IP and handle redirects myself, re-checking each hop. All of this runs through an egress proxy that has no route to internal networks. On the cloud side, IMDSv2 is enforced with a hop limit of 1 and the instance role is least privilege, so even a bypass does not yield useful credentials."

Test yourself

A webhook service checks that the callback hostname does not resolve to a private address, then calls `fetch(url)` with default settings. What is the most important remaining gap?

Q1How does IMDSv2 stop most SSRF?+

Getting credentials requires first sending a PUT with a special header to obtain a token, then sending that token as a header. Most SSRF bugs can only make simple GET requests to a URL, so they cannot complete the exchange. A hop limit of 1 also stops the token response from crossing an extra network hop, such as from a container through a proxy.

Q2Is blind SSRF low severity?+

Not necessarily. It can still trigger state-changing internal endpoints, scan internal ports by timing, and exploit internal services with GET-based vulnerabilities.

Q3Why route fetches through a separate egress proxy?+

It moves enforcement out of every application and into one place that has no network path to internal ranges. A bug in application validation then cannot reach anything sensitive.

Finished this one?
Tick it and it shows as done on the roadmap and the course.