SSRF (Server-Side Request Forgery)

Difficulty: Advanced

Question

What is Server-Side Request Forgery (SSRF), why is it dangerous in cloud environments, and how do you prevent it?

Answer

SSRF is a vulnerability where an attacker makes your server send HTTP (or other protocol) requests to a destination the attacker chooses, usually by supplying a URL that the server fetches. Because the request comes from inside your network, it can reach internal services, admin panels and cloud metadata endpoints that are never exposed to the internet. In cloud setups, SSRF is often the first step to stealing credentials and taking over an account.

Where SSRF hides

Any feature where the server fetches a user-supplied URL:

  • Link previews and URL unfurling in chat or social apps.
  • "Import from URL" for images, resumes or CSV files.
  • Webhook configuration, where the user sets the callback URL.
  • PDF or screenshot generators that render user HTML (headless Chrome will load <img src> and <iframe> targets).
  • XML parsers with external entities enabled (XXE often turns into SSRF).

In blind SSRF the response is not shown, but the attacker can still hit internal endpoints that trigger actions, or infer open ports from timing.

Why the cloud makes it worse

Cloud VMs expose an instance metadata service at the link-local address 169.254.169.254. On AWS, a request to /latest/meta-data/iam/security-credentials/<role> returns temporary access keys for the instance's IAM role. The 2019 Capital One breach followed this pattern: an SSRF through a misconfigured WAF let the attacker read role credentials and then download S3 data.

AWS IMDSv2 mitigates this by requiring a session token obtained with a PUT request and a custom header, which most SSRF primitives (simple GET with a URL) cannot send. Enforce IMDSv2 (HttpTokens=required) and keep the hop limit at 1 for containers that do not need metadata. GCP and Azure require a Metadata-Flavor: Google or Metadata: true header for similar reasons.

Why naive blocklists fail

Checking that the URL string does not contain localhost or 169.254 is easy to bypass:

  • Alternate encodings: http://2130706433/ (decimal for 127.0.0.1), http://0x7f.1/, http://[::1]/, http://[::ffff:169.254.169.254]/.
  • DNS names that resolve to internal IPs, including DNS rebinding where the first lookup is public and the second is private.
  • Open redirects: the allowed host returns a 302 to the metadata endpoint and the HTTP client follows it.
  • Other schemes: file://, gopher://, dict:// in libraries like curl.

How to prevent it

  1. Allowlist destination hosts where possible (for example, only your S3 bucket or known partner domains).
  2. If you must accept arbitrary URLs, resolve DNS yourself, reject private, loopback, link-local and reserved ranges for both IPv4 and IPv6, then connect to that exact IP so the check and the request cannot diverge.
  3. Allow only http and https, disable redirects or re-validate every hop, set short timeouts and a response size limit.
  4. Run fetchers in an isolated network segment or through an egress proxy that enforces the same rules.
  5. Enforce IMDSv2 and give instances least-privilege IAM roles so a leak is less damaging.

SSRF was its own category (A10) in the OWASP Top 10 2021; the 2025 edition folds it into Broken Access Control, but the impact has not changed.

SSRF to cloud credential theft. The attacker never touches the internal network directly; your server makes the request for them.
  1. Attacker submits URL: url=http://169.254.169.254/latest/meta-data/
  2. Image import endpoint: Server fetches the URL without checks.
  3. Instance metadata service: Reachable only from inside the VM.
  4. IAM role credentials: Temporary keys returned in the response.
  5. Data exfiltration: Attacker uses keys to read S3 buckets.

Code examples

Validating the resolved IP before fetching (Node.js)

import dns from 'node:dns/promises';
import ipaddr from 'ipaddr.js';

async function assertPublicUrl(raw) {
  const url = new URL(raw);
  if (!['http:', 'https:'].includes(url.protocol)) {
    throw new Error('Only http(s) allowed');
  }
  const records = await dns.lookup(url.hostname, { all: true });
  for (const { address } of records) {
    let ip = ipaddr.parse(address);
    if (ip.kind() === 'ipv6' && ip.isIPv4MappedAddress()) ip = ip.toIPv4Address();
    if (ip.range() !== 'unicast') { // private, loopback, linkLocal, etc.
      throw new Error(`Blocked internal address ${address}`);
    }
  }
  return { url, ip: records[0].address };
}

// Then connect to the validated IP (e.g. a custom undici dispatcher
// with a fixed lookup) and set redirect: 'manual' to stop 302 tricks.

The check runs on the resolved IP, not the URL string, which defeats decimal and hex encodings. Pinning the connection to the checked IP blocks DNS rebinding.

Enforcing IMDSv2 on an EC2 instance

# Require session tokens and keep metadata unreachable from extra network hops
aws ec2 modify-instance-metadata-options \
  --instance-id i-0abc123def4567890 \
  --http-tokens required \
  --http-put-response-hop-limit 1 \
  --http-endpoint enabled

# A legitimate IMDSv2 call needs a PUT first
TOKEN=$(curl -s -X PUT http://169.254.169.254/latest/api/token \
  -H 'X-aws-ec2-metadata-token-ttl-seconds: 300')
curl -s -H "X-aws-ec2-metadata-token: $TOKEN" \
  http://169.254.169.254/latest/meta-data/instance-id

Most SSRF bugs only let the attacker control a GET URL, so they cannot perform the PUT with a custom header that IMDSv2 requires.

Key points

  • SSRF turns your server into a proxy into your own private network
  • The cloud metadata endpoint 169.254.169.254 is the classic high-value target
  • String blocklists are bypassed by IP encodings, DNS rebinding and redirects
  • Validate the resolved IP, pin the connection, restrict schemes and disable redirects
  • Enforce IMDSv2 and least-privilege IAM roles as defence in depth

Common follow-up questions

  • What is DNS rebinding and how does it bypass SSRF filters?
  • How does IMDSv2 reduce SSRF impact compared to IMDSv1?
  • How would you safely implement a webhook feature that calls user-supplied URLs?
  • What is blind SSRF and how would you detect it?

Interview tips

  • Give a concrete feature example like 'import resume from URL' and the metadata endpoint; it makes the risk real
  • Explain why blocklisting 'localhost' is not enough; naming two bypasses impresses interviewers
  • Mention network-level controls (egress proxy, IMDSv2) in addition to code fixes

Concepts covered

SSRF, Cloud Metadata API, IMDSv2, Allowlisting, Internal Network

More Web Security (OWASP, JWT, XSS, CSRF) questions