SSRF in features that fetch user-supplied URLs: the metadata and internal-service targets, why naive URL validation fails, connect-time IP checks with SocketsHttpHandler, redirects, DNS rebinding and network-level egress controls.
SSRF is when your server makes a request to a destination the attacker chooses, using your network position and identity. Features like webhooks, URL previews and image fetches are classic entry points. The prize is usually internal: the cloud metadata endpoint (169.254.169.254) or a managed identity endpoint that hands out tokens, internal admin APIs, or services on localhost.
Defend in layers: allow only https and standard ports, resolve and check the IP at connect time (with SocketsHttpHandler.ConnectCallback) so private, loopback and link-local ranges are refused even after DNS rebinding, disable auto-redirects or re-check each hop, cap time and size, and never echo the response. Then add network egress controls so the fetcher can't reach internal ranges at all. The trade-off: strict egress isolation is the strongest control but needs infrastructure work.
"SSRF is turning my server into the attacker's proxy. Anything that takes a URL from a user and fetches it — webhooks, 'import from URL', link previews, PDF generators that load images — can be pointed at places only my server can reach. In the cloud the best-known target is the instance metadata service at
169.254.169.254, and on App Service or AKS the managed identity endpoint, because a token from there is my app's identity in Azure. The Capital One breach in 2019 was exactly this pattern on AWS. That's why OWASP's 2025 list folds SSRF into broken access control: it's the server accessing things on the attacker's behalf.The naive fix is to parse the URL and block
localhostand private IPs by hostname. That fails three ways: alternative encodings of the same IP, a hostname that resolves to an internal address, and DNS rebinding, where the name resolves to a public IP when you check and a private one when you connect. So in .NET I check at connect time: aSocketsHttpHandlerwith aConnectCallbackthat resolves the name, rejects private, loopback, link-local and IPv4-mapped addresses, and connects to the exact IP it validated. I turn off automatic redirects, set a short timeout and a response size cap, and I never return the fetched body or detailed errors to the caller. For example, at [company] our [webhook delivery service] was found able to reach [an internal endpoint] in a pen test; moving it to [an isolated subnet with an egress allow-list] plus connect-time IP checks closed it and the retest found nothing.The mistake I see is relying only on application checks. The strongest control is network: the fetcher runs where it physically can't reach internal ranges. Code checks are the second layer."
var bytes = await http.GetByteArrayAsync(request.ImageUrl); returned to the user as the avatar.localhost admin port, or a domain that rebinds to 10.x) and reads the response through the avatar endpoint.HttpClient whose handler validates scheme, port and resolved IP at connect time, follows no redirects, caps size and time, and an image pipeline that re-encodes the result so arbitrary bytes are never echoed.| Bypass | Why a hostname check misses it | Defence |
|---|---|---|
| Decimal/octal/hex IP forms | Parser and blocklist disagree | Check the resolved IPAddress, not the string |
Domain resolving to 10.0.0.5 |
Name looks public | Resolve and check the IP |
| DNS rebinding | Check and connect resolve differently | Validate and connect in the same ConnectCallback |
| Open redirect on a trusted site | First hop is allowed | Disable auto-redirect or re-validate each hop |
IPv6 / IPv4-mapped (::ffff:10.0.0.1) |
Only IPv4 ranges blocked | Normalise with MapToIPv4() |
| Layer | Control |
|---|---|
| Product | Do you need arbitrary URLs? Allow-list domains for integrations where possible |
| Application | Scheme/port allow-list, connect-time IP check, no redirects, timeouts, size cap |
| Identity | Least-privilege managed identity; the fetcher service has no identity at all if possible |
| Network | Fetcher in an isolated subnet; Azure Firewall/NSG blocks RFC 1918, link-local, internal DNS |
| Monitoring | Log destination IPs; alert on blocked attempts |
For a webhook platform delivering about 2 million events a day, moving delivery to a separate worker in its own subnet with an Azure Firewall rule denying all private ranges, plus a connect-time IP check, added under 1 ms per connection; blocked-destination alerts fired around 20 times a month, almost all from customers misconfiguring internal URLs, and a few from probing that previously would have succeeded.
Checks that the candidate understands SSRF's real targets in the cloud, knows why naive URL validation fails, and layers application and network defences.
Green flags
Red flags
Attacker --(URL)--> Your API --(request from inside)--> internal target
| - 169.254.169.254 (IMDS)
| - IDENTITY_ENDPOINT (App Service MI)
| - http://localhost:xxxx/admin
| - 10.x internal APIs, Redis, Elasticsearch
+-- response (or timing/errors) back to attacker
The attacker gains your server's network reachability and sometimes its identity. Even 'blind' SSRF (no response returned) can port-scan via timing or trigger state-changing internal GETs.
http://169.254.169.254/metadata/...) on VMs, VM scale sets and AKS nodes. It requires the header Metadata: true and rejects requests containing X-Forwarded-For, which stops the simplest SSRF where the attacker controls only the URL, but not a server-side feature that lets attackers set headers.IDENTITY_ENDPOINT protected by an X-IDENTITY-HEADER secret.Don't rely on these: they are platform mitigations, not your control.
The only safe check is on the IP address you actually connect to. SocketsHttpHandler.ConnectCallback runs for each new connection with the target DnsEndPoint. Resolve it yourself, reject disallowed addresses, then connect the socket to the validated address. Because validation and connection use the same resolution, DNS rebinding can't swap the address in between. TLS still validates the certificate against the original hostname, so HTTPS keeps working.
Block at least: 0.0.0.0/8, 10.0.0.0/8, 100.64.0.0/10 (CGNAT), 127.0.0.0/8, 169.254.0.0/16, 172.16.0.0/12, 192.168.0.0/16, ::1, fc00::/7, fe80::/10, and normalise IPv4-mapped IPv6 before checking.
HttpClientHandler.AllowAutoRedirect / SocketsHttpHandler.AllowAutoRedirect = false. If you must follow, do it manually with the same checks (the ConnectCallback re-runs for new hosts anyway, but your scheme/port rules may not).HttpClient only speaks HTTP(S), which removes file:///gopher:// tricks common in other stacks; keep it that way (don't hand URLs to libraries that support other schemes).MaxResponseContentBufferSize, use HttpCompletionOption.ResponseHeadersRead with a bounded read, and set short timeouts.The strongest control puts URL-fetching code in its own service with an egress path that can't reach internal addresses: a separate subnet with a NAT gateway, an Azure Firewall application rule allowing only outbound 443 to the internet, NSGs denying VNet ranges, and no managed identity (or one with no roles). Then a code bug isn't a breach.
Validate the URL at registration and at delivery (DNS changes), sign payloads with HMAC so receivers can verify them, retry with backoff, and disable endpoints that keep failing.
http://127.0.0.1:5000/admin and confirm the handler rejects it at connect time.An SSRF-resistant HttpClient for user-supplied URLs: connect-time IP validation (defeats DNS rebinding), no redirects, size and time caps, registered with IHttpClientFactory.
using System.Net;
using System.Net.Sockets;
namespace Hooks.Delivery;
public static class SafeOutboundHttp
{
public const string ClientName = "untrusted-urls";
public static IServiceCollection AddSafeOutboundHttp(this IServiceCollection services)
{
services.AddHttpClient(ClientName, c =>
{
c.Timeout = TimeSpan.FromSeconds(10);
c.MaxResponseContentBufferSize = 2 * 1024 * 1024; // 2 MB
})
.ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler
{
AllowAutoRedirect = false, // a redirect could point inside
UseProxy = false,
ConnectCallback = ConnectToPublicAddressOnlyAsync,
});
return services;
}
public static bool IsAllowedUrl(Uri uri) =>
uri.IsAbsoluteUri && uri.Scheme == Uri.UriSchemeHttps && uri.Port == 443 && uri.UserInfo.Length == 0;
private static async ValueTask<Stream> ConnectToPublicAddressOnlyAsync(
SocketsHttpConnectionContext context, CancellationToken ct)
{
var addresses = await Dns.GetHostAddressesAsync(context.DnsEndPoint.Host, ct);
var target = addresses.FirstOrDefault(IsPublic)
?? throw new HttpRequestException($"Destination '{context.DnsEndPoint.Host}' is not allowed.");
var socket = new Socket(target.AddressFamily, SocketType.Stream, ProtocolType.Tcp) { NoDelay = true };
try
{
// Connect to the address we validated, so DNS can't change between check and use
await socket.ConnectAsync(new IPEndPoint(target, context.DnsEndPoint.Port), ct);
return new NetworkStream(socket, ownsSocket: true);
}
catch
{
socket.Dispose();
throw;
}
}
private static bool IsPublic(IPAddress ip)
{
if (ip.IsIPv4MappedToIPv6) ip = ip.MapToIPv4();
if (IPAddress.IsLoopback(ip)) return false;
if (ip.AddressFamily == AddressFamily.InterNetworkV6)
return !(ip.IsIPv6LinkLocal || ip.IsIPv6SiteLocal || ip.IsIPv6UniqueLocal || ip.Equals(IPAddress.IPv6Any));
var b = ip.GetAddressBytes();
return !(b[0] == 0 || b[0] == 10 || b[0] == 127 ||
(b[0] == 100 && b[1] >= 64 && b[1] <= 127) || // CGNAT
(b[0] == 169 && b[1] == 254) || // link-local, IMDS
(b[0] == 172 && b[1] >= 16 && b[1] <= 31) ||
(b[0] == 192 && b[1] == 168));
}
}
// Usage: validate the URL shape, then let the handler enforce the destination
app.MapPost("/webhooks", async (WebhookRegistration reg, IHttpClientFactory factory, CancellationToken ct) =>
{
if (!Uri.TryCreate(reg.Url, UriKind.Absolute, out var uri) || !SafeOutboundHttp.IsAllowedUrl(uri))
return Results.ValidationProblem(new Dictionary<string, string[]> { ["url"] = ["Use an https URL on port 443."] });
var client = factory.CreateClient(SafeOutboundHttp.ClientName);
using var ping = await client.PostAsync(uri, new StringContent("{}"), ct); // verification call
return Results.Created($"/webhooks/{Guid.NewGuid()}", null); // never echo the response body
});
public sealed record WebhookRegistration(string Url);
localhost and 169.254.169.254 by string match on the URL. Why it is wrong: alternative IP encodings, hostnames that resolve internally and DNS rebinding all bypass it. Instead: check the resolved IP at connect time.HttpClient resolve again to connect. Why it is wrong: DNS rebinding returns a public IP for the check and a private one for the connection. Instead: validate and connect in the same ConnectCallback.Metadata: true header requirement. Why it is wrong: any feature that lets users set headers bypasses it, and other internal targets have no such protection. Instead: block link-local and private ranges yourself and at the network.The senior view: SSRF is a network-trust problem wearing an input-validation costume. Application checks are necessary but brittle; the durable fix is architecture: put untrusted-URL fetching in a component that has no route to internal networks and no meaningful identity. Then decide product-wise whether arbitrary URLs are needed at all — a domain allow-list for integrations is far simpler than defending the whole internet.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Domain allow-list | Integrations with known partners | Onboarding friction | Customer-defined webhooks |
| Connect-time IP validation in code | Any feature fetching user URLs | Small, needs tests | As the only control for high-value environments |
| Isolated egress (separate subnet, firewall, no identity) | Webhook platforms, URL import at scale | Infrastructure and ops | Tiny apps with no internal network |
| Third-party fetch proxy (e.g. a hardened egress proxy) | Many services need safe outbound fetches | Another component | Single feature |
Measure: blocked-destination counts and alerts, pen-test retests, and a periodic check that the fetcher subnet truly can't reach 10.0.0.0/8 or 169.254.169.254.
A firewall allows or blocks traffic based on rules (source, destination, port, protocol, and for L7 firewalls/WAFs, HTTP content).
Troubleshoot by symptom: timeout usually means dropped by a firewall or routing, refused means reached the host but nothing listening, reset after idle often means a firewall or load balancer idle timeout removed the connection state. Test from the source (nc -vz, Test-NetConnection), check rules and flow logs in both directions, and set TCP keep-alives or shorter pool idle timeouts below the firewall's idle timeout.
HMAC-SHA256 is a keyed hash: the sender computes HMAC(secret, message) and you recompute it with the same secret. A match proves the body wasn't altered and came from someone holding the secret; it does not encrypt anything.
Three details make verification correct. Hash the raw request bytes exactly as received, because re-serialising JSON changes whitespace and ordering. Compare with CryptographicOperations.FixedTimeEquals, because an early-exit comparison leaks how many leading bytes matched through timing. And sign a timestamp with the payload and reject old ones (Stripe uses a 5-minute default) so a captured request can't be replayed; store event ids for idempotency too. Keep the secret in Key Vault and accept two during rotation. Use asymmetric signatures instead when many parties must verify but shouldn't be able to forge.
How to tell it (STAR)
**S:** At [company] a pen test showed our 'import image from URL' feature could reach internal addresses, and our app's managed identity had access to [storage and Key Vault]. **T:** I led the fix and needed it closed before [the onboarding date]. **A:** We switched the feature off, I confirmed from sign-in and Key Vault logs it hadn't been abused, and I shipped a connect-time IP check with redirects disabled and generic errors. Then I moved fetching into a separate worker with no identity, behind Azure Firewall allowing only public HTTPS. **R:** The retest found nothing, the feature was back in [days], and even a future code bug can no longer reach anything internal.
Last updated 23 Nov 2026.