Skip to content
javahacks.dev
Security

SSRF Java Prevention for Services That Fetch User URLs

Prevent server side request forgery in Java: allowlists for outbound URLs, blocking private and metadata addresses, DNS rebinding and redirect handling.

6 min read
Summarize in AI
Flat illustration of an entity class mapped to a database table, with the OpenJDK, Spring Security, Spring and MySQL logos.

Your service sits inside a network that trusts it. A feature that fetches a URL on a user's behalf lets the user borrow that trust: they can ask your server to call http://169.254.169.254/ (the cloud metadata service), http://localhost:8080/actuator, or an internal admin API.

A vulnerable feature

java
@PostMapping("/preview")
String preview(@RequestParam String url) throws IOException {
    return Jsoup.connect(url).get().title();         // fetches anything
}

The attacker supplies http://169.254.169.254/latest/meta-data/iam/security-credentials/ and receives cloud credentials in the response. Even if the response is not returned, timing and error messages can reveal the internal network.

Defence 1: allowlist

If the set of destinations is known, accept only those:

java
private static final Set<String> ALLOWED_HOSTS = Set.of("images.example.com", "cdn.partner.com");

URI uri = URI.create(url);
if (!"https".equals(uri.getScheme()) || !ALLOWED_HOSTS.contains(uri.getHost())) {
    throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "host not allowed");
}

This is the strongest option for webhooks to partners or image sources you control. Schemes matter: reject file:, ftp: and gopher:.

Defence 2: validate the resolved address

When arbitrary hosts are allowed (a link preview), validate the IP address, not the name:

java
static InetAddress resolveSafely(String host) throws UnknownHostException {
    InetAddress address = InetAddress.getByName(host);
    if (address.isAnyLocalAddress() || address.isLoopbackAddress() || address.isLinkLocalAddress()
            || address.isSiteLocalAddress() || address.isMulticastAddress() || isUniqueLocal(address)) {
        throw new IllegalArgumentException("address not allowed");
    }
    return address;
}

private static boolean isUniqueLocal(InetAddress a) {
    byte[] b = a.getAddress();
    return b.length == 16 && (b[0] & 0xFE) == 0xFC;                 // fc00::/7
}

isSiteLocalAddress covers 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16. isLinkLocalAddress covers 169.254.0.0/16, which includes the metadata service. Encodings such as 0x7f000001, 2130706433 or [::ffff:127.0.0.1] are normalized by InetAddress, which is a reason to check the resolved object, not string patterns.

Defence 3: connect to what you checked

A check followed by a second lookup is a race: DNS rebinding returns a safe address for the check and an internal one for the connection. Resolve once and connect to that address, keeping the Host header:

java
InetAddress ip = resolveSafely(uri.getHost());
HttpClient client = HttpClient.newBuilder()
        .followRedirects(HttpClient.Redirect.NEVER)
        .connectTimeout(Duration.ofSeconds(3))
        .build();
// connect to the resolved IP with a custom socket factory or an HTTP library that supports pinned resolution

Most HTTP clients allow a custom DNS resolver or a socket factory for this. Apply the same validation in that hook, so every connection, including redirects, is checked.

Redirects

An allowed host can answer 302 to http://169.254.169.254/. Disable automatic redirects (Redirect.NEVER) and, if you need them, follow manually with the full validation on each hop and a limit on the count.

Other settings

  • Timeouts and size limits on the response, so a fetch cannot hang a thread or fill memory.
  • Do not return raw responses or error text from the fetch to the user.
  • Protect the metadata service: use IMDSv2 on AWS, which needs a session token, and restrict the hop limit.
  • Egress rules: run the fetching component in a network segment that cannot reach internal systems.
  • Authentication on internal services. Internal APIs should not trust the network alone.

What the JVM does with odd address spellings

An allowlist of names does not stop an attacker who supplies an address, and a blocklist of strings does not stop one who spells it differently. Running the validator from this post against a set of spellings shows which ones the JVM collapses to the same address. This output is from JDK 17; the address parsing in InetAddress has not changed in later releases.

Ssrf.javajava
for (String h : List.of("127.0.0.1", "2130706433", "0x7f000001", "0177.0.0.1",
        "169.254.169.254", "10.1.2.3", "[::1]", "[::ffff:127.0.0.1]", "[fd00::1]", "93.184.216.34")) {
    InetAddress a = InetAddress.getByName(h);
    System.out.printf("%-20s -> %-18s blocked=%s%n", h, a.getHostAddress(), blocked(a));
}
Text
127.0.0.1            -> 127.0.0.1          blocked=true
2130706433           -> 127.0.0.1          blocked=true
0x7f000001           -> 127.0.0.1          blocked=true
0177.0.0.1           -> 177.0.0.1          blocked=false
169.254.169.254      -> 169.254.169.254    blocked=true
10.1.2.3             -> 10.1.2.3           blocked=true
[::1]                -> 0:0:0:0:0:0:0:1    blocked=true
[::ffff:127.0.0.1]   -> 127.0.0.1          blocked=true
[fd00::1]            -> fd00:0:0:0:0:0:0:1 blocked=true
93.184.216.34        -> 93.184.216.34      blocked=false

Four spellings of loopback, one IPv4-mapped IPv6 form and a unique local address are all caught because the check runs on the parsed object. The surprise is 0177.0.0.1. The JVM reads the leading zero as decimal and yields 177.0.0.1, while curl and most C libraries read it as octal and connect to 127.0.0.1. If any component between your validator and the socket parses the host with different rules, the check passes and the connection goes somewhere else. That is the strongest argument for the next section: connect to the address you validated, not to the string you validated.

Pin the address in the HTTP client

With Apache HttpClient 5, a custom DnsResolver runs for every connection the client opens, including those caused by redirects, so one class enforces the rule everywhere.

src/main/java/dev/javahacks/web/SafeHttpClient.javajava
public final class SafeHttpClient {

    public static CloseableHttpClient create() {
        var resolver = new SystemDefaultDnsResolver() {
            @Override
            public InetAddress[] resolve(String host) throws UnknownHostException {
                InetAddress[] all = super.resolve(host);
                for (InetAddress a : all) {
                    if (Ssrf.blocked(a)) {
                        throw new UnknownHostException("blocked address for " + host);
                    }
                }
                return all;
            }
        };
        var connections = PoolingHttpClientConnectionManagerBuilder.create()
                .setDnsResolver(resolver)
                .build();
        return HttpClients.custom()
                .setConnectionManager(connections)
                .disableRedirectHandling()
                .setDefaultRequestConfig(RequestConfig.custom()
                        .setConnectTimeout(Timeout.ofSeconds(3))
                        .setResponseTimeout(Timeout.ofSeconds(5))
                        .build())
                .build();
    }
}

The resolver rejects the whole host if any returned address is internal, which closes the trick of publishing one public and one private A record. Because the client connects to the addresses the resolver returned, there is no second lookup to rebind.

Bound what comes back

A fetch that is allowed to run forever or return a gigabyte is a denial of service on its own. Read with a ceiling and refuse content you did not expect.

java
static byte[] readLimited(InputStream in, int max) throws IOException {
    byte[] data = in.readNBytes(max + 1);
    if (data.length > max) {
        throw new IOException("response larger than " + max + " bytes");
    }
    return data;
}

Check the Content-Type before parsing: a link preview needs text/html, and anything else is dropped. Do not forward the upstream status or body to the caller. Return one generic error for every rejected URL, so the response does not tell an attacker whether a host exists, refused, or timed out.

Alert on attempts

Blocked requests are signal. A user pasting a normal link never triggers the resolver check, so each rejection is either a mistake or a probe. Count them by authenticated user and source address and alert on a burst. Logging the attempted host, not the full URL with its query string, keeps credentials in a pasted link out of the log.

Where the other defences fit

Validation of the destination is the main control, and it is not the only one. The fetching component should run with the least network access it can: an egress rule that allows only the ports it needs and blocks the metadata address and private ranges at the network layer protects you on the day the application check has a bug. Treat the application check and the network rule as two independent layers, because each has failed for someone else.

On AWS, require IMDSv2 on every instance and set the hop limit to 1 for hosts that do not run containers needing the metadata service. IMDSv2 requires a PUT request to obtain a session token, and a simple fetch of a URL cannot send one, so the classic attack of reading credentials through a GET-only SSRF stops working. Verify it with a request from the application host to http://169.254.169.254/latest/meta-data/ without a token: it should now return 401. Test the same boundary from inside your pod or container, since the hop limit is what decides whether a container can reach the service at all.

Where this does not apply

Features that never fetch user-provided locations are not exposed, and the status code to return for a rejected URL is covered in returning the right status codes. Check libraries that fetch on your behalf: XML parsers resolving external entities (XXE), PDF and image converters, and OAuth discovery. The general checklist is in Java security basics. The reference is the OWASP SSRF Prevention Cheat Sheet, and AWS IMDSv2 describes the metadata hardening.

Also inSpring MVC
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.