Skip to main content

SSRF (Server-Side Request Forgery)

SSRF (Server-Side Request Forgery)

Table of Contents

Quick Answer

Server-side request forgery (SSRF) is a vulnerability in which an attacker makes a server send a request to a destination the attacker chooses. It happens when an application fetches a URL that comes from outside, for a link preview, a webhook or an import, without controlling where that request can go. Because the request comes from the server, it can reach internal services, the server itself and cloud metadata endpoints that hand out credentials. Prevent it with an allow-list of destinations where you can, otherwise by checking every resolved address and refusing redirects, and back that with network rules that stop the server reaching internal ranges.

This defensive guide explains what SSRF is, where it appears and why cloud servers make it so damaging. Two Java examples show the fault, a harmless local test that detects it and the fix, followed by the cloud metadata settings that limit the damage, three real incidents, and how to detect and prevent SSRF in your own applications. There are no bypass lists or attack strings here: the test values are addresses that point back at the test machine.

What is SSRF?

Many applications fetch things from the web on a user's behalf: a page to preview, an image to import, a callback to notify. Server-side request forgery happens when the user decides where that request goes. The server sends it from inside the network, with the server's address and trust, so it can reach systems the user never could: an admin page that only accepts local connections, a database's HTTP interface, an internal API without authentication, or the cloud provider's metadata service.

MITRE catalogues the weakness as CWE-918, Server-Side Request Forgery, 22nd in the 2025 CWE Top 25. OWASP gave it its own category in 2021, A10:2021, and noted it might later be rolled into a larger one. That happened in the Top 10:2025, where CWE-918 is mapped to A01:2025 Broken Access Control. In the OWASP API Security Top 10 2023 it is API7, because so many APIs fetch remote resources for their callers.

TermWho sends the requestWhose trust is abused
SSRFThe serverThe server's network position and credentials
Blind SSRFThe server, without showing the responseThe same, with the effect seen only indirectly
CSRFA logged-in user's browserThe user's session
Open redirectThe user's browser, sent on by your siteYour domain's reputation; it can also feed SSRF when a server follows the redirect

The names SSRF and CSRF are easy to mix up. Our SSRF vs CSRF comparison sets them side by side.

How SSRF works

The destination comes from outside

The pattern is always the same: a value from the request, or one stored earlier, becomes the target of a request the server makes. Sometimes it is a whole URL. Sometimes it is only a host name, a path that is appended to an internal base URL, or a value inside a document the server parses. Any of them lets an outsider choose where the server's request goes.

The server can reach what the caller cannot

Firewalls are built to stop requests coming in from the internet. SSRF starts inside. The server can usually reach localhost and services bound only to it, other hosts in private address ranges, internal load balancers and management interfaces, and, in the cloud, the instance metadata service at the link-local address 169.254.169.254. Many internal services skip authentication because they assume only trusted systems can reach them, and SSRF breaks that assumption.

Blind SSRF

Often the application does not show the fetched response, for example when it only sends a webhook. That is blind SSRF. The request still happens, so it can still trigger actions in internal services, and the time taken or the error returned can reveal which hosts and ports exist. Blind SSRF is less obvious in testing, not less serious.

Where SSRF appears

  • Link previews and unfurling in chat, comments and social features.
  • Webhooks, where customers register a URL your server calls.
  • Import from URL: profile pictures, documents, feeds, calendar files.
  • PDF, screenshot and HTML renderers, which load every image, stylesheet and frame in the page they render.
  • Image and document converters whose input formats can reference other files.
  • XML parsers that load external entities, covered in our XXE attack guide.
  • AI agents and tools that browse on request, where a prompt, or text injected into one, chooses the URL. Our AI agent security guide covers that wider risk.

Java examples with fixes

The two examples below were compiled and run on Java 21, with imports left out for length. The tests use a small service on the test machine that answers only local connections, so a response from it proves the server fetched something a caller should not reach. Run such tests only against systems you own or are authorised to test.

Fetching a URL the user supplies

The fault. A link preview feature fetches whatever URL the client sends and returns the page so the client can build a preview card.

static String previewUnsafe(String url) throws Exception {
    // url comes from the request
    var response = HttpClient.newHttpClient().send(
        HttpRequest.newBuilder(URI.create(url)).build(),
        HttpResponse.BodyHandlers.ofString());
    return response.body();
}

How to detect it. Look for request data reaching an HTTP client, a URL connection or any library that accepts a URL. In a test, give the feature an address that points back at the server, for a service that only listens locally. If its content comes back, the server is fetching destinations the caller chose.

Test input: http://127.0.0.1:8081/, a test service that listens only on the server itself

previewUnsafe -> internal-only status page      the server fetched a local service for the caller
previewFixed  -> IllegalArgumentException       URL not allowed

The fix. A preview feature rarely needs the whole internet. Accept only HTTPS URLs whose host is on a fixed list, with no port and no user name in the URL. Java's HttpClient does not follow redirects unless you ask it to, which matters here: if it did, an allowed host could send the request on somewhere else. Where users may preview any site, move the fetch to the second pattern below.

static final Set<String> PREVIEW_HOSTS = Set.of("www.youtube.com", "vimeo.com");

static String previewFixed(String url) throws Exception {
    URI uri = URI.create(url);
    if (!"https".equals(uri.getScheme()) || uri.getRawUserInfo() != null
            || uri.getPort() != -1 || !PREVIEW_HOSTS.contains(uri.getHost())) {
        throw new IllegalArgumentException("URL not allowed");
    }
    var response = HttpClient.newHttpClient().send(
        HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(5)).build(),
        HttpResponse.BodyHandlers.ofString());
    return response.body();
}

Webhooks to customer URLs

The fault. A webhook feature must call URLs its customers register, so a fixed allow-list is impossible. The developer added a deny-list of internal-looking host names, and used HttpURLConnection, which follows redirects by default.

static int deliverUnsafe(String callbackUrl, String json) throws IOException {
    // callbackUrl was registered by a customer
    String host = URI.create(callbackUrl).getHost();
    if (host.equals("localhost") || host.startsWith("127.") || host.startsWith("169.254.")) {
        throw new IllegalArgumentException("Internal address");
    }
    var con = (HttpURLConnection) URI.create(callbackUrl).toURL().openConnection();
    con.setRequestMethod("POST");
    con.setDoOutput(true);
    con.getOutputStream().write(json.getBytes(StandardCharsets.UTF_8));
    return con.getResponseCode();   // redirects are followed by default
}

How to detect it. Deny-lists of strings are the warning sign. The same address can be written in more than one way, and a host name can resolve to any address at all. In a test, register the IPv6 spelling of the local address. Here the deny-list stopped 127.0.0.1 but let [::1] through, and the local test service received the request.

Test inputs: other spellings of local, metadata and private addresses

deliverUnsafe http://127.0.0.1:8081/hook  -> IllegalArgumentException  Internal address
deliverUnsafe http://[::1]:8081/hook      -> 200                       the test service received the POST
deliverFixed  https://[::1]:8081/hook     -> IllegalArgumentException  Address not allowed
deliverFixed  https://169.254.169.254/    -> IllegalArgumentException  Address not allowed
deliverFixed  https://[fd00:ec2::254]/    -> IllegalArgumentException  Address not allowed
deliverFixed  https://10.0.0.5/           -> IllegalArgumentException  Address not allowed

The fix. Decide on the address, not the text. Resolve the host name and refuse the request if any resulting address is loopback, private, link-local, unique-local IPv6 or another special-purpose range from the IANA registries. Java converts IPv4-mapped IPv6 addresses to IPv4 before these checks, so that spelling is covered too. Refuse redirects, require HTTPS, set timeouts and never pass the response body back to the customer.

static final HttpClient WEBHOOKS = HttpClient.newBuilder()
    .followRedirects(HttpClient.Redirect.NEVER)
    .connectTimeout(Duration.ofSeconds(5))
    .build();

static int deliverFixed(String callbackUrl, String json) throws Exception {
    URI uri = URI.create(callbackUrl);
    if (!"https".equals(uri.getScheme())) {
        throw new IllegalArgumentException("HTTPS only");
    }
    for (InetAddress address : InetAddress.getAllByName(uri.getHost())) {
        if (!isPublic(address)) {
            throw new IllegalArgumentException("Address not allowed");
        }
    }
    var response = WEBHOOKS.send(HttpRequest.newBuilder(uri)
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(json)).build(),
        HttpResponse.BodyHandlers.discarding());
    return response.statusCode();   // a redirect is reported, not followed
}

static boolean isPublic(InetAddress a) {
    if (a.isLoopbackAddress() || a.isAnyLocalAddress() || a.isLinkLocalAddress()
            || a.isSiteLocalAddress() || a.isMulticastAddress()) {
        return false;
    }
    byte[] b = a.getAddress();
    if (b.length == 16 && (b[0] & 0xfe) == 0xfc) return false;   // fc00::/7, unique local
    if (b.length == 4 && (b[0] & 0xff) == 100 && (b[1] & 0xc0) == 64) return false;   // 100.64.0.0/10
    return true;   // add other special-purpose ranges your network uses
}

The gap between checking and connecting

The fix above is still not complete on its own. The HTTP client resolves the host name again when it connects, and a name can return a public address for the check and an internal one for the connection. This is known as DNS rebinding, and the OWASP cheat sheet warns that a second, unchecked lookup can bypass validation. Redirects are the same problem in another form, which is why they are refused.

Close the gap outside the application. Send webhook and fetch traffic through an outbound proxy that applies the same address rules to the connection it actually makes, or run those features on a network segment with no route to internal ranges. In Java that is one line in the client's configuration:

static final HttpClient WEBHOOKS = HttpClient.newBuilder()
    .proxy(ProxySelector.of(new InetSocketAddress("egress-proxy.internal", 3128)))
    .followRedirects(HttpClient.Redirect.NEVER)
    .connectTimeout(Duration.ofSeconds(5))
    .build();

Cloud metadata: why it matters and how to lock it

Every major cloud runs a metadata service that a virtual machine can query over plain HTTP. It tells the machine about itself and, more importantly, can hand out temporary credentials for the cloud role attached to it. An SSRF that reaches this service can turn into access to the cloud account, its storage and its other services. The three providers now protect it with request conditions that a simple SSRF, which controls only the URL, cannot meet.

ProviderAddressProtectionWhat to set
AWS EC2169.254.169.254, and fd00:ec2::254 on Nitro instances with IPv6IMDSv2 needs a session token obtained with a PUT request; token requests with an X-Forwarded-For header are refusedRequire IMDSv2 so IMDSv1 calls fail. Keep the response hop limit at 1, or 2 where containers on the instance need metadata.
Google Cloudmetadata.google.internal, 169.254.169.254Requests must carry Metadata-Flavor: Google; requests with X-Forwarded-For are rejectedNothing to switch on; keep service account permissions small.
Microsoft Azure169.254.169.254Requests must carry Metadata: true and must not carry X-Forwarded-ForNothing to switch on; scope managed identities tightly.

On AWS, IMDSv1 is still accepted unless you turn it off, though Amazon Linux 2023 disables it by default. AWS describes both addresses as link-local, but fd00:ec2::254 sits in the IPv6 unique-local block in the IANA registry. That is why the address check in the webhook example refuses unique-local addresses as well as link-local ones. These protections guard the most valuable target, not the vulnerability: internal services are still within reach until the code is fixed.

Real incidents

Capital One, 2019

Capital One disclosed in July 2019 that an outside individual had obtained personal information about approximately 100 million people in the United States and 6 million in Canada. The company described the cause as a configuration vulnerability, and Amazon said the intrusion was caused by a misconfigured web application firewall. Reporting at the time by KrebsOnSecurity, citing sources familiar with the investigation, described the technique as SSRF: the firewall could be made to relay requests to the metadata service, which returned credentials for the server's cloud role, and those credentials were used to read data from storage.

In November 2019 AWS launched IMDSv2, describing it as defence in depth against open web application firewalls, open reverse proxies and unpatched SSRF vulnerabilities. In August 2020 the US Office of the Comptroller of the Currency fined Capital One $80 million for failing to manage the risks of its move to the cloud.

Microsoft Exchange ProxyLogon, 2021

CVE-2021-26855 was an SSRF in on-premises Microsoft Exchange Server. Microsoft's description of the attacks, published on 2 March 2021, says it let an attacker send arbitrary HTTP requests and authenticate as the Exchange server. Attackers combined it with three other flaws that write files or run code once authenticated, CVE-2021-26857, CVE-2021-26858 and CVE-2021-27065, a chain known as ProxyLogon. Microsoft scored the SSRF 9.1 and NVD 9.8. CISA issued Emergency Directive 21-02 for the Exchange flaws, and its Known Exploited Vulnerabilities catalog records known use in ransomware campaigns.

The lesson is that SSRF is often the first link in a chain. On its own it "only" sends requests; inside a server that trusts its own requests, it can be the authentication that the rest of the chain needs.

Ivanti Connect Secure, 2024

CVE-2024-21893 was an SSRF in the SAML component of Ivanti Connect Secure and Policy Secure, versions 9.x and 22.x, and Ivanti Neurons for ZTA. It allowed access to certain restricted resources without authentication and scored 8.2. CISA added it to the Known Exploited Vulnerabilities catalog on 31 January 2024, the day it was published. It arrived weeks after the authentication bypass and command injection pair in the same products, described in our command injection guide.

How to detect SSRF

In code

Start with an inventory of every place the application makes an outbound request. This search finds the usual Java entry points; add the HTTP libraries your project uses:

grep -rnE "HttpClient|HttpURLConnection|openConnection\(|openStream\(|RestTemplate|WebClient|ImageIO\.read\(" src/

For each result, ask where the destination comes from. A fixed URL in configuration is fine. A URL, host, port or path from a request, a database field a user can edit, or a document the server parses needs the controls on this page. Static analysis that traces request data to these calls helps on large code bases; our guide to SAST and DAST explains where each kind of testing fits. Check document converters, PDF renderers and XML parsers too, because they fetch URLs without an obvious HTTP call in your code.

In tests

Keep the local tests from the examples as regression tests: an address pointing back at the test machine, its IPv6 spelling, the metadata address and a private address should all be refused before any connection is made. For blind SSRF, authorised testers point the feature at a callback domain they control and watch for the server's request. The OWASP Web Security Testing Guide has a test procedure for SSRF, for systems in scope.

At runtime

SignalWhy it mattersWhere to see it
Application servers connecting to the metadata address or to internal ranges they never useA web front end rarely needs another team's admin interface. New internal destinations are a strong sign.Proxy logs, VPC flow logs, firewall logs
Instance credentials used from somewhere elseCredentials taken through SSRF are usually used outside the instance.Amazon GuardDuty findings InstanceCredentialExfiltration.OutsideAWS and .InsideAWS; equivalent cloud audit logs elsewhere
Lookups of unfamiliar domains by fetch featuresBlind SSRF testing, and probing, often uses callback domains.DNS logs
Bursts of timeouts and connection errors from a fetch featureProbing of internal hosts and ports shows up as failed requests.Application logs and metrics

How to prevent SSRF

The controls work in layers. Application checks decide which requests should be made; network controls make sure a missed check cannot reach anything valuable.

1. Avoid fetching user-supplied URLs

Often the user only needs to choose between known destinations. Let them pick an identifier and map it to a URL in code or configuration, so no outside value ever becomes a destination. For uploads, accept the file itself instead of a URL to fetch it from.

2. Allow-list scheme, host and port

Where the destinations are known, compare the parsed URL exactly against a list: HTTPS only, named hosts, default ports, no user information. Parse with one library and use that same parsed value for the request, so the check and the request cannot read the URL differently.

3. Check every resolved address

Where any host is allowed, resolve the name and refuse loopback, private, link-local, unique-local and the other special-purpose ranges, for IPv4 and IPv6. Check every address the name returns, not just the first.

4. Do not follow redirects

Turn redirect following off and treat a redirect as a failure, or check each new destination exactly like the first. Check your HTTP library's default rather than assuming it: in Java, HttpClient does not follow redirects by default but HttpURLConnection does.

5. Lock down cloud metadata

Require IMDSv2 on AWS, keep the hop limit low, and give every instance role and service account only the permissions it needs. If credentials leak, small permissions keep the damage small.

6. Deny outbound traffic by default

Send fetch features through an outbound proxy that enforces the address rules, or place them where the network has no route to internal ranges or the metadata service. This is the control that still works when an application check is missed or bypassed, and it is the same step that limits remote code execution.

7. Return less

Never return the fetched response as it is. Return only what the feature needs, such as a title and an image for a preview, and use one generic error for every failure, so the feature cannot be used to map the internal network.

What to do if you suspect SSRF

  1. Disable or restrict the feature, or block its outbound traffic at the proxy or firewall, while you investigate.
  2. Find out what it could reach: metadata service, internal services, other accounts. Assume anything reachable may have been queried.
  3. Rotate the credentials of the instance role or service account, and any secrets internal services could have returned.
  4. Review cloud audit logs for those credentials, and internal service logs for requests from the affected server.
  5. Fix the code with the controls above, require IMDSv2, and add the local tests to the build so the fix stays fixed.

Developer review questions

  • Where does this application make outbound requests, including through renderers, converters and parsers?
  • Can any part of a destination, including host, port or path, come from a request or from data a user can edit?
  • Could the user choose from fixed destinations instead of entering a URL?
  • Is the allow-list or address check applied to the parsed value that is actually used for the request?
  • Does the check cover IPv6, every resolved address and the metadata addresses?
  • Does the HTTP client follow redirects, and is that what we intend?
  • Is there an outbound proxy or network rule that would stop a missed check from reaching internal ranges?
  • Is IMDSv2 required, and are instance role permissions as small as they can be?
  • Does the feature return raw responses or detailed errors to the caller?
  • Are these tests run only on systems we are authorised to test?

FAQs

It was a category of its own in 2021, A10:2021 Server-Side Request Forgery. The 2025 edition has no separate SSRF category: its weakness, CWE-918, is mapped to A01:2025 Broken Access Control. SSRF is also API7 in the OWASP API Security Top 10 2023. The API Top 10 guide explains that entry.

Blind SSRF is SSRF where the server makes the request but does not show the response to the caller. It is still serious: the request can change state in an internal service, and timing or errors can reveal what exists on the internal network. Testers usually detect it with a callback domain they control, which records the server's request. "No response came back" is not evidence that a feature is safe.

In SSRF, the attacker makes the server send a request, using the server's network position and trust. In CSRF, the attacker makes a logged-in user's browser send a request, using the user's session. The defences are different: SSRF needs destination checks and network controls, CSRF needs tokens and SameSite cookies. Our SSRF vs CSRF comparison covers both side by side.

It can catch some obvious internal addresses in parameters, but it cannot be the fix. An address has many spellings, a hostname can resolve to an internal address, a redirect can move the request after the firewall has seen it, and URLs stored earlier or arriving in files never pass the firewall. A misconfigured firewall or reverse proxy can even become the SSRF route itself, which is one reason AWS built IMDSv2.

No. It protects one valuable target, the instance metadata service and the cloud credentials it hands out, by requiring a session token obtained with a PUT request and refusing requests that carry an X-Forwarded-For header. The SSRF itself remains, and so do the internal services the server can reach. Require IMDSv2 and fix the fetching code.

For a fixed set of hosts you trust, an exact allow-list of scheme, host and port is the strongest control. It is not enough on its own when the allowed hosts can redirect elsewhere, so turn off redirects too. When users may enter any host, as with webhooks, there is nothing to allow-list: check every resolved address and send the requests through an outbound proxy or network policy that blocks internal ranges.

Anything that fetches a URL on someone's behalf: link previews, webhooks, import-from-URL and avatar-from-URL features, PDF and screenshot generators, image and document converters, XML parsers that load external entities, single sign-on metadata fetchers, and AI agents or tools that browse on request. Each one is a request the server sends to a destination someone else chose.

Sources and further reading