
Hardening Rust HTTP Clients Against SSRF and Internal Network Abuse
Why SSRF matters in client code
SSRF is not limited to web servers that accept URLs from users. Any Rust service that:
- fetches remote content on behalf of users,
- follows redirects automatically,
- resolves hostnames dynamically,
- or talks to internal services based on external input
can be abused to reach internal IPs, loopback interfaces, link-local metadata endpoints, or private admin services.
Common examples include:
- URL preview generators
- webhook testers
- image or document importers
- “fetch this URL” integrations
- internal proxy or relay services
The security goal is simple: only allow requests to destinations you explicitly intend to reach.
A safe mental model for outbound requests
Treat every outbound request as a policy decision, not just a network operation. Before sending a request, decide:
- Is the scheme allowed?
- Is the hostname allowed?
- Does the resolved IP fall inside a forbidden range?
- Are redirects allowed, and if so, where can they go?
- Are proxy settings under your control?
- Is the response size bounded?
That policy should be enforced in code, not by convention.
Start with a deny-by-default URL policy
A common mistake is to accept any URL that parses successfully. Parsing only proves the string is syntactically valid, not that it is safe.
A better approach is to allow only a narrow set of schemes and hosts.
use url::Url;
#[derive(Debug)]
enum UrlPolicyError {
InvalidUrl,
DisallowedScheme,
DisallowedHost,
}
fn validate_target(input: &str) -> Result<Url, UrlPolicyError> {
let url = Url::parse(input).map_err(|_| UrlPolicyError::InvalidUrl)?;
match url.scheme() {
"https" => {}
_ => return Err(UrlPolicyError::DisallowedScheme),
}
let host = url.host_str().ok_or(UrlPolicyError::DisallowedHost)?;
let allowed_hosts = ["api.example.com", "cdn.example.com"];
if !allowed_hosts.contains(&host) {
return Err(UrlPolicyError::DisallowedHost);
}
Ok(url)
}
This is intentionally strict. If your application needs more flexibility, prefer explicit allowlists over pattern matching such as “any subdomain” unless you fully control the domain space.
Why this helps
- Blocks
file://,ftp://,gopher://, and other unexpected schemes. - Prevents requests to arbitrary hosts.
- Makes the security boundary visible in code review.
Validate the resolved IP, not just the hostname
Hostname allowlists are necessary but not sufficient. DNS can resolve a permitted hostname to an internal or loopback address. Attackers may also exploit DNS rebinding or manipulate DNS responses in compromised environments.
After resolving the hostname, reject private, loopback, link-local, multicast, and unspecified addresses.
use std::net::{IpAddr, ToSocketAddrs};
fn is_forbidden_ip(ip: IpAddr) -> bool {
match ip {
IpAddr::V4(v4) => {
v4.is_private()
|| v4.is_loopback()
|| v4.is_link_local()
|| v4.is_broadcast()
|| v4.is_unspecified()
}
IpAddr::V6(v6) => {
v6.is_loopback()
|| v6.is_unique_local()
|| v6.is_unicast_link_local()
|| v6.is_unspecified()
}
}
}
fn resolve_and_check(host: &str, port: u16) -> Result<(), &'static str> {
let addrs = (host, port).to_socket_addrs().map_err(|_| "dns resolution failed")?;
for addr in addrs {
if is_forbidden_ip(addr.ip()) {
return Err("destination resolves to a forbidden address");
}
}
Ok(())
}
Important caveat
This check is useful, but it is not a complete defense if the actual HTTP client resolves again later using a different resolver path. Ideally, your request path should:
- resolve once,
- validate the resulting IPs,
- and connect using the validated destination.
If your client library does not make that easy, combine IP validation with network-level egress controls.
Control redirects explicitly
Redirects are a frequent SSRF bypass. A safe initial URL can redirect to an unsafe internal target. For example, a request to https://api.example.com/redirect might return Location: http://169.254.169.254/latest/meta-data/.
The safest default is to disable automatic redirects and handle them manually.
| Redirect strategy | Security posture | Typical use |
|---|---|---|
| Follow all redirects | Weak | Convenience-only clients |
| Follow same-host redirects | Moderate | Controlled APIs |
| Disable redirects | Strong | Security-sensitive clients |
| Manual redirect validation | Strongest | Untrusted or user-influenced URLs |
With reqwest, you can disable redirects and inspect them yourself:
use reqwest::redirect::Policy;
let client = reqwest::Client::builder()
.redirect(Policy::none())
.build()?;
If you do allow redirects, validate each Location header with the same policy as the original URL. Do not assume that a redirect to a relative path is safe; it can still lead to a different authority if the server changes scheme or host.
Avoid proxy surprises
Outbound proxies can silently change the destination of a request. In some environments, HTTP_PROXY, HTTPS_PROXY, or ALL_PROXY environment variables may be honored automatically.
That can be dangerous when:
- the application should never use a proxy,
- the proxy is user-controlled,
- or the proxy can observe sensitive traffic.
When building a security-sensitive client, configure proxy behavior deliberately. If you do not want proxies, disable them in your HTTP client configuration and document that decision.
Also remember that proxies can be used to reach internal resources indirectly. A destination check that only inspects the original URL is not enough if the transport layer can be redirected elsewhere.
Bound response size and time
SSRF is often paired with resource exhaustion. Even if the destination is benign, an attacker may point your client at a slow or huge response to consume memory, sockets, or worker threads.
Set strict limits on:
- connection timeout,
- request timeout,
- read timeout,
- maximum response body size.
A practical pattern is to stream the body and stop after a fixed limit.
use futures_util::StreamExt;
use reqwest::Client;
async fn fetch_limited(client: &Client, url: &str) -> Result<Vec<u8>, reqwest::Error> {
let resp = client.get(url).send().await?.error_for_status()?;
let mut stream = resp.bytes_stream();
let mut body = Vec::new();
let max_bytes = 1024 * 1024; // 1 MiB
while let Some(chunk) = stream.next().await {
let chunk = chunk?;
if body.len() + chunk.len() > max_bytes {
break;
}
body.extend_from_slice(&chunk);
}
Ok(body)
}
For many applications, it is better to reject oversized responses than to truncate them silently. Truncation can create confusing partial data and downstream parsing bugs.
Prefer fixed destinations over user-supplied URLs
The safest design is often to avoid arbitrary URLs entirely. Instead of accepting a full URL from the user, accept a small identifier and map it to a known endpoint.
For example:
provider = "github"→https://api.github.comprovider = "stripe"→https://api.stripe.comregion = "eu-west"→ a controlled regional endpoint
This reduces the attack surface dramatically because the application owns the destination selection logic.
If you must accept a URL, consider accepting only a path or query fragment and combining it with a fixed base URL:
use url::Url;
fn build_api_url(path: &str) -> Result<Url, url::ParseError> {
let base = Url::parse("https://api.example.com/")?;
base.join(path)
}
This approach is safer than accepting a full absolute URL because the host and scheme remain fixed.
Be careful with IP literals and alternative host representations
Attackers often try to bypass hostname checks using unusual representations:
- dotted decimal variants,
- hexadecimal or integer IP forms,
- IPv6 literals,
- embedded credentials like
user@host, - punycode or Unicode lookalikes.
Use a real URL parser and inspect the parsed host, not string prefixes. Avoid checks such as:
starts_with("https://example.com")contains("example.com")- manual splitting on
://
These are easy to bypass.
Also consider rejecting raw IP literals unless your application explicitly needs them. If you allow them, apply the same private-range checks as you would for resolved DNS results.
A practical request pipeline
A secure outbound request flow usually looks like this:
- Parse the input as a URL.
- Verify the scheme is allowed.
- Verify the hostname is on an allowlist.
- Resolve the hostname.
- Reject forbidden IP ranges.
- Disable or strictly validate redirects.
- Enforce timeouts and response size limits.
- Send the request.
That pipeline is more work than a naive client.get(url).send(), but it is the difference between a controlled integration and a pivot point into your internal network.
Common mistakes to avoid
| Mistake | Why it is dangerous | Safer alternative |
|---|---|---|
| Accepting any parsed URL | Parsing is not validation | Use scheme and host allowlists |
| Trusting DNS blindly | DNS can resolve to internal IPs | Check resolved addresses |
| Following redirects automatically | Redirects can bypass validation | Disable or revalidate redirects |
| Allowing proxies implicitly | Proxies can alter reachability | Configure proxy use explicitly |
| Using string matching for URLs | Easy to bypass with encoding or userinfo | Use a URL parser |
| Ignoring response limits | Large or slow responses can exhaust resources | Set size and time bounds |
Testing your defenses
Security controls should be tested with malicious inputs, not just normal cases. Add tests for:
http://127.0.0.1http://[::1]http://169.254.169.254http://localhost- redirect chains to internal hosts
- oversized responses
- invalid or mixed-scheme URLs
If your application uses a mock server, include redirect responses and malformed Location headers. The goal is to verify that unsafe destinations are rejected before any network access occurs.
When network controls should back up code controls
Application-level validation is essential, but it should not be your only defense. Add infrastructure controls such as:
- egress firewall rules,
- container network policies,
- restricted DNS resolution,
- metadata service protection,
- service mesh outbound policies.
These controls reduce the blast radius if a bug slips through. A secure Rust client plus restrictive network policy is much stronger than either one alone.