Skip to content

SSRF, Explained: When Your Server Becomes the Attacker's Proxy

Server-side request forgery turns a trusted server into a request-making proxy for the attacker, reaching internal services and cloud credentials the internet should never touch. Here is how it works and how to lock it down.

SelfSec Team 9 min read

Part 1 of 4From the SSRF series

At a glance

CWE-918
Interpreter
Server-side HTTP client and URL parser
Required condition
A request value chooses, or helps build, the destination of a request the server makes.
Potential impact
Access to internal services, cloud credential theft from metadata endpoints, and internal network mapping.
Primary defense
An exact destination allowlist enforced on resolved addresses, with redirects off and egress restricted.

Safe practice: use benign proof only, in a disposable local lab or on a system you are explicitly authorized to test.

Server-side request forgery (SSRF) happens when an application can be tricked into making HTTP — or other-protocol — requests to a destination the attacker chooses. The request leaves from the server, so it carries the server's network position and trust. Anything the application can reach from inside the perimeter, the attacker can now reach too: internal-only admin panels, databases, and the cloud instance-metadata service that hands out credentials.

That last point is why SSRF had its own category in the OWASP Top 10:2021. The 2025 edition maps it to A01 Broken Access Control — the server reaches resources the requester was never allowed to reach — but the danger has not shrunk: in cloud environments it is one of the most reliable paths from a single vulnerable parameter to full account compromise. This post walks through how it happens, what an attacker does with it, and how to stop it.

The mental model: the server's network, the requester's choice

A fetch-by-URL feature splits one decision between two parties. The server owns the network position and the identity the request carries. The URL decides where that position and identity are spent.

Question Safe design SSRF
Which host does the server contact? Server configuration The request
Which scheme and port? Server configuration The request
Which networks can it reach? Only what the feature needs Loopback, private ranges and link-local metadata included
Whose identity does it carry? The server's Still the server's, now spent for the attacker

The URL itself is not the problem. The problem is letting the requester make a decision that only the server's configuration should make.

How it happens

The root cause is simple: the application takes a user-supplied URL and fetches it without checking where it points. Think of a feature that generates link previews, imports an image from a URL, or proxies a webhook:

@app.route("/fetch")
def fetch():
    url = request.args.get("url")
    resp = requests.get(url)
    return resp.content

The developer pictured url being https://example.com/logo.png. But nothing forces that. The value is fully attacker-controlled, and the server will dutifully request whatever it is given — including addresses that only exist inside the network.

A concrete attack

On a cloud host, the attacker does not aim at the public internet. They aim inward, at the instance-metadata endpoint that every major cloud exposes on a link-local address:

GET /fetch?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/ HTTP/1.1
Host: app.example

The server connects to 169.254.169.254 from inside the VPC, the metadata service answers because the request came from the instance itself, and the response — temporary IAM access keys — gets handed straight back to the attacker. From there they can act as the application's cloud role.

The same trick reaches internal services. Pointing url at http://127.0.0.1:6379 or http://10.0.0.5:8080/admin lets the attacker probe ports and talk to back-ends that were never meant to face the internet. Naive filters that just block the string 127.0.0.1 are easy to slip past:

GET /fetch?url=http://2130706433/            # decimal form of 127.0.0.1
GET /fetch?url=http://0x7f000001/            # hex form
GET /fetch?url=http://0177.0.0.1/            # octal form
GET /fetch?url=http://127.1/                 # shortened form
GET /fetch?url=http://[::1]/                 # IPv6 loopback
GET /fetch?url=http://[::ffff:127.0.0.1]/    # IPv4-mapped IPv6

Allowlists written as string checks fail the same way. A check that the URL merely starts with an approved host is satisfied by userinfo, and a hand-rolled parser that looks for the host after an @ disagrees with the client that actually sends the request:

http://[email protected]/      # userinfo: the real host is 127.0.0.1
http://127.0.0.1#@images.example.com/     # fragment: a naive parser reads the host after @

The attacker never gained access to the internal network. They borrowed the server's access — every request is made with the server's identity, from inside the firewall.

Header-gated metadata is a layer, not a fix

Cloud providers have hardened their metadata services against exactly this attack. AWS IMDSv2 hands out a session token only in response to a PUT carrying X-aws-ec2-metadata-token-ttl-seconds, GCP requires Metadata-Flavor: Google, and Azure requires Metadata: true. A fetcher that can only send a plain GET with no custom headers cannot satisfy those checks.

A fetcher that accepts gopher:// can. The scheme writes arbitrary bytes to a TCP socket, so a single URL can carry a complete HTTP request, method and headers included. Enforcing IMDSv2 is still worth doing — it closes the most common GET-only case — but the fix remains controlling where the server can send requests. The cloud metadata deep-dive and the protocol smuggling post cover both halves in detail.

When nothing comes back: blind SSRF

Many fetchers never return the body: webhooks, link unfurlers, PDF renderers and import jobs. The request still leaves the server. In an authorized test, pointing the URL at a unique hostname on an out-of-band listener operated for the assessment proves it: a DNS lookup or HTTP hit for that name can only come from the server resolving and fetching the injected URL. Blind SSRF walks through that technique and how internal reachability is inferred without a response body.

What an attacker gains

Once the server can be pointed anywhere, the blast radius is large:

  • Cloud credential theft — reading IAM tokens from 169.254.169.254 and pivoting to the whole cloud account.
  • Internal service access — reaching admin panels, dashboards and databases bound to localhost or private ranges.
  • Port scanning and enumeration — mapping the internal network by watching which addresses respond.
  • Protocol smuggling — using gopher://, dict:// or file:// to talk to Redis, hit other TCP services, or read local files like /etc/passwd.

Where SSRF hides

A parameter named url is the obvious case. Less obvious ones include webhook targets saved in settings, avatar and image import, link previews, HTML-to-PDF renderers that fetch the page's own resources, OpenID Connect discovery and jwks_uri values, and file importers that accept a URL. XML parsers that resolve external entities make requests too, which is how XXE becomes SSRF. And a fetcher that follows redirects can be bounced from an allowed URL to an internal one through an open redirect on any host it trusts.

The fix: allowlist destinations, block the internal world

Blocklists lose against the long tail of IP encodings and URL tricks. The reliable approach is to decide up front exactly where the server is allowed to go, and refuse everything else. Parse the URL, check the scheme, host and port against an allowlist, check every address the host resolves to, and only then make the request:

import ipaddress
import socket
from urllib.parse import urlsplit

import requests

ALLOWED_HOSTS = {"images.example.com", "cdn.example.com"}

def safe_fetch(url):
    parts = urlsplit(url)
    if parts.scheme != "https" or parts.username or parts.password:
        raise ValueError("destination not allowed")
    if parts.hostname not in ALLOWED_HOSTS or parts.port not in (None, 443):
        raise ValueError("destination not allowed")

    for *_, sockaddr in socket.getaddrinfo(parts.hostname, 443, proto=socket.IPPROTO_TCP):
        if not ipaddress.ip_address(sockaddr[0]).is_global:
            raise ValueError("internal address blocked")

    return requests.get(url, allow_redirects=False, timeout=5).content

The address check covers every IPv4 and IPv6 address the name resolves to, and is_global also excludes shared, reserved and other non-public ranges that a hand-written private-range list tends to miss. It is a second line of defense, not the first: requests resolves the name again when it connects, so a resolver that answered differently the second time would slip past it. Because the allowlist names only hosts you operate or trust, that answer is not the attacker's to choose. When a feature genuinely has to fetch arbitrary public URLs, enforce the address check where the connection is made — in an egress proxy, or in a connection hook such as .NET's SocketsHttpHandler.ConnectCallback — so the address that is checked is the address that is used.

The same allowlist in C#, with redirects disabled on the handler and a cap on how much of the response is buffered:

private static readonly HashSet<string> AllowedHosts = new(StringComparer.OrdinalIgnoreCase)
{
    "images.example.com",
    "cdn.example.com"
};

private static readonly HttpClient Http = new(new SocketsHttpHandler { AllowAutoRedirect = false })
{
    Timeout = TimeSpan.FromSeconds(5),
    MaxResponseContentBufferSize = 5 * 1024 * 1024
};

public static async Task<byte[]> SafeFetchAsync(string userUrl, CancellationToken ct)
{
    if (!Uri.TryCreate(userUrl, UriKind.Absolute, out var uri)
        || uri.Scheme != Uri.UriSchemeHttps
        || !uri.IsDefaultPort
        || uri.UserInfo.Length > 0
        || !AllowedHosts.Contains(uri.IdnHost))
    {
        throw new ArgumentException("Destination not allowed.", nameof(userUrl));
    }

    using var response = await Http.GetAsync(uri, ct);
    response.EnsureSuccessStatusCode();
    return await response.Content.ReadAsByteArrayAsync(ct);
}

Comparing IdnHost checks the ASCII form of the name, so an internationalized look-alike cannot match an allowlist entry by accident, and both the decimal and userinfo tricks above fail because the parsed host is not on the list.

Reinforce it with a few more controls: allow only the schemes the feature needs (only https survives above, killing file, gopher and dict), do not follow redirects automatically (a 302 to 169.254.169.254 defeats a host check made before the redirect), and require the IMDSv2 token flow so the metadata service is not readable by a plain GET. Where possible, route outbound fetches through an egress proxy that enforces the allowlist for you, and keep the fetching service off networks it has no reason to reach.

Fixes that do not hold

  • Blocklisting 127.0.0.1, localhost and 169.254.169.254: decimal, hex, octal, shortened and IPv6 forms reach the same addresses, and any DNS name the attacker controls can resolve to them.
  • Validating the string, then fetching it: the parser in your check and the one in your HTTP client can disagree about userinfo, fragments and backslashes.
  • Checking the first URL, then following redirects: a 302 from an allowed host lands wherever it points.
  • Resolving once and connecting later: DNS rebinding answers with a public address for the check and an internal one for the connection.
  • Relying on metadata headers or IMDSv2 alone: they stop GET-only fetchers, not ones that can smuggle a full request through gopher://.
  • Hiding the response body: the request still happens; blind SSRF is confirmed out of band.

A developer review checklist

  1. Inventory every feature that fetches a URL, including webhooks, previews, importers, renderers and document parsers.
  2. Prefer server-owned destinations: map an identifier to a URL instead of accepting a URL.
  3. Allow only the schemes the feature needs and an exact host and port allowlist; reject userinfo.
  4. Check every resolved address, and enforce that check at connection time or in an egress proxy.
  5. Disable automatic redirects, or re-validate every hop.
  6. Require IMDSv2 and block link-local metadata addresses for workloads that do not need them.
  7. Apply timeouts and response-size limits, and return generic errors that do not reveal which internal hosts answered.

References

Module: Server Side Request Forgery. How it probes: Replaces query, form, JSON and WebSocket values with loopback and encoded internal addresses, cloud metadata URLs (including header-gated endpoints reached through gopher), internal ports, file, gopher and dict URLs, and unique out-of-band callback hosts. How it confirms: A reflected result needs a response-only marker, such as instance metadata, a temporary cloud credential, a memcached STAT line or file contents, that the baseline and a benign control lack; a DNS or HTTP callback to a unique out-of-band host confirms the request, including blind cases. A finding moves from Possible to Confirmed only after this check. Reported as CWE-918 · ATT&CK T1190 · SARIF 2.1.0.
How SelfSec proves this one
Module
Server Side Request Forgery
How it probes
Replaces query, form, JSON and WebSocket values with loopback and encoded internal addresses, cloud metadata URLs (including header-gated endpoints reached through gopher), internal ports, file, gopher and dict URLs, and unique out-of-band callback hosts.
How it confirms
A reflected result needs a response-only marker, such as instance metadata, a temporary cloud credential, a memcached STAT line or file contents, that the baseline and a benign control lack; a DNS or HTTP callback to a unique out-of-band host confirms the request, including blind cases.
Reported as CWE-918 · ATT&CK T1190 · SARIF 2.1.0

A reflected response alone is not enough to promote a SSRF finding. The classical engine has to confirm the behavior before it reaches the report. See the detection engine

SelfSec scanner

Find SSRF in your own app

Reading about the class is one thing. SelfSec tests for it against an application you are authorized to assess, and only calls it real when independent evidence agrees.

Join the launch list