Security Playbook

The URL-fetch feature your agent wrote will happily call your internal network: an attack table and a connect-time guard for C#

Agents write SSRF checks that compare host strings and then fetch. Here's a failing test table first, a guard that checks the address actually dialled, and a prompt that makes any agent keep it. About 40 minutes, no accounts needed.

A pale gate-shaped doorframe split by horizontal glitch tears, with one gold slice slid sideways out of line

A feature request arrives that sounds harmless: let users paste a URL and show a preview of the page, or pull in a remote avatar, or register a webhook and send a test ping. The agent builds it in one pass, adds a check that rejects localhost and the private ranges, and the demo works. Then somebody pastes http://169.254.169.254/latest/meta-data/ and the service politely returns the cloud instance’s metadata, credentials included.

That’s server-side request forgery (SSRF), and it’s one of the defects generated code reproduces reliably, because the obvious implementation is a string check on the host followed by a fetch. Both halves are wrong. The string check misses addresses written in forms the parser accepts and the socket layer understands. The fetch resolves the name again, follows redirects, and connects wherever it ends up.

This Playbook builds the fix in the order that keeps an agent honest: an attack table as failing tests first, then a guard that checks the address the socket is about to dial, then a prompt and a CI line that keep it that way. The code is C# on .NET 10 with xUnit. The method (the table, the failing run, the connect-time check) works with any coding agent that can read files and run a shell, and the same shape ports to TypeScript or any other stack.

What the first draft looks like

Ask an agent for “a function that fetches a URL but blocks internal addresses” and the result is usually this:

public static class NaiveFetcher
{
    public static async Task<string> GetAsync(string url)
    {
        var uri = new Uri(url);
        if (uri.Scheme is not ("http" or "https"))
            throw new SsrfBlockedException("scheme");

        var host = uri.Host;
        if (host == "localhost" || host.StartsWith("127.") || host.StartsWith("10.")
            || host.StartsWith("192.168.") || host.StartsWith("169.254."))
            throw new SsrfBlockedException("private host");

        using var http = new HttpClient();
        return await http.GetStringAsync(uri);
    }
}

It reads fine in review. It also has four separate problems. It’s a deny-list, and OWASP’s SSRF cheat sheet is blunt about those: deny-lists are bypass-prone. It never mentions IPv6, so [::1] sails through. It forgets whole ranges (172.16.0.0/12, carrier-grade NAT, the IPv6 unique-local block). And HttpClient follows redirects by default (AllowAutoRedirect is true on the handler), so a public URL that answers 302 with a Location of an internal address is fetched anyway, with no check on the second hop.

The fix isn’t a longer list of prefixes. A decision about an address has to be made where the address is used.

Step 1: write the attack table before the guard

The table is the part worth keeping, because it outlives whichever implementation the agent produces next month. Each row is a URL a hostile user could submit. Each row must end in an SsrfBlockedException, and an in-process “internal service” counts how many requests actually reached it, so a blocked row has to show zero hits.

public sealed class InternalService : IDisposable
{
    private readonly HttpListener _listener = new();
    public int Port { get; }
    public int Hits;
    public string? RedirectTo;

    public InternalService()
    {
        var probe = new System.Net.Sockets.TcpListener(IPAddress.Loopback, 0);
        probe.Start(); Port = ((IPEndPoint)probe.LocalEndpoint).Port; probe.Stop();
        _listener.Prefixes.Add($"http://127.0.0.1:{Port}/");
        _listener.Start();
        _ = Task.Run(async () =>
        {
            while (_listener.IsListening)
            {
                HttpListenerContext c;
                try { c = await _listener.GetContextAsync(); } catch { return; }
                Interlocked.Increment(ref Hits);
                if (RedirectTo is null) await c.Response.OutputStream.WriteAsync("internal secret"u8.ToArray());
                else { c.Response.StatusCode = 302; c.Response.Headers["Location"] = RedirectTo; }
                c.Response.Close();
            }
        });
    }

    public void Dispose() => _listener.Close();
}

That’s the test double: a real HTTP listener on a free loopback port that stands in for the admin endpoint, the metrics port or the metadata service. Now the table:

public class SsrfAttackTable
{
    public static TheoryData<string> Attacks() => new()
    {
        "http://127.0.0.1:{0}/",
        "http://[::1]:{0}/",
        "http://0.0.0.0:{0}/",
        "http://[::ffff:127.0.0.1]:{0}/",
        "http://2130706433:{0}/",
        "http://127.1:{0}/",
        "http://169.254.169.254/latest/meta-data/",
        "http://100.100.100.200/",
        "http://[fd00:ec2::254]/latest/meta-data/",
        "file:///etc/passwd",
    };

    [Theory, MemberData(nameof(Attacks))]
    public async Task Naive_blocks(string template)
    {
        using var svc = new InternalService();
        var url = string.Format(template, svc.Port);
        await Assert.ThrowsAsync<SsrfBlockedException>(() => NaiveFetcher.GetAsync(url));
        Assert.Equal(0, svc.Hits);
    }
}

Several rows are the same address in a different costume. 2130706433 is 127.0.0.1 as a single decimal number and 127.1 is the short form; .NET’s Uri normalises both, which is why a naive check that runs after parsing catches them and one that runs on the raw string wouldn’t. [::ffff:127.0.0.1] is an IPv4-mapped IPv6 address, which OWASP says to unmap before checking. 0.0.0.0 isn’t in the agent’s list at all, and it isn’t a normal destination address either. 100.100.100.200 sits inside 100.64.0.0/10, the carrier-grade NAT block, which no prefix list in a first draft includes.

Run it against the naive fetcher:

dotnet test --filter "FullyQualifiedName~Naive"
  Failed Fetch.Tests.SsrfAttackTable.Naive_blocks(template: "http://[::1]:{0}/")
  Failed Fetch.Tests.SsrfAttackTable.Naive_blocks(template: "http://0.0.0.0:{0}/")
  Failed Fetch.Tests.SsrfAttackTable.Naive_blocks(template: "http://[::ffff:127.0.0.1]:{0}/")
  Failed Fetch.Tests.SsrfAttackTable.Naive_blocks(template: "http://100.100.100.200/")
  Failed Fetch.Tests.SsrfAttackTable.Naive_blocks(template: "http://[fd00:ec2::254]/latest/meta-data/")
Failed!  - Failed:     5, Passed:     5, Skipped:     0, Total:    10

Five of ten rows get past the guard. A precise reading matters here: those rows failed because the guard didn’t raise SsrfBlockedException, and the table treats that as the defect. In this sandbox none of those requests reached the listener (it’s bound to IPv4 loopback only, and the connections failed for other reasons), so the run proves the string check let them through, not that each one would have returned data in production. On a real network, 100.100.100.200 and a metadata address are exactly the kind of thing that answers.

Step 2: check the address that gets dialled

The principle comes straight from OWASP: validate the resolved IP addresses, and make sure the client connects only to those validated addresses. Domain allow-listing alone doesn’t stop DNS rebinding, where a name resolves to a public address for the check and an internal one for the connection. In .NET the place to do that is SocketsHttpHandler.ConnectCallback, the documented hook that opens each new connection. The check and the connect happen in the same function, on the same list of addresses, so there’s no second lookup to race.

First the address policy. It canonicalises mapped IPv6 to IPv4, then tests against the ranges OWASP lists plus a few more special-purpose blocks:

public static class IpPolicy
{
    private static readonly (IPAddress Net, int Bits)[] Blocked =
    [
        (IPAddress.Parse("0.0.0.0"), 8),
        (IPAddress.Parse("10.0.0.0"), 8),
        (IPAddress.Parse("100.64.0.0"), 10),    // carrier-grade NAT
        (IPAddress.Parse("127.0.0.0"), 8),
        (IPAddress.Parse("169.254.0.0"), 16),   // link-local, cloud metadata
        (IPAddress.Parse("172.16.0.0"), 12),
        (IPAddress.Parse("192.0.0.0"), 24),
        (IPAddress.Parse("192.168.0.0"), 16),
        (IPAddress.Parse("198.18.0.0"), 15),
        (IPAddress.Parse("224.0.0.0"), 4),      // multicast
        (IPAddress.Parse("240.0.0.0"), 4),      // reserved and broadcast
        (IPAddress.Parse("::"), 128),
        (IPAddress.Parse("::1"), 128),
        (IPAddress.Parse("64:ff9b::"), 96),     // NAT64
        (IPAddress.Parse("100::"), 64),         // discard-only
        (IPAddress.Parse("2001:db8::"), 32),    // documentation
        (IPAddress.Parse("fc00::"), 7),         // unique local
        (IPAddress.Parse("fe80::"), 10),        // link-local
        (IPAddress.Parse("ff00::"), 8),         // multicast
    ];

    public static bool IsPublic(IPAddress ip)
    {
        if (ip.IsIPv4MappedToIPv6) ip = ip.MapToIPv4();
        foreach (var (net, bits) in Blocked)
            if (net.AddressFamily == ip.AddressFamily && InRange(ip, net, bits)) return false;
        return true;
    }

    private static bool InRange(IPAddress ip, IPAddress net, int bits)
    {
        var a = ip.GetAddressBytes();
        var b = net.GetAddressBytes();
        var full = bits / 8;
        for (var i = 0; i < full; i++) if (a[i] != b[i]) return false;
        var rem = bits % 8;
        if (rem == 0) return true;
        var mask = (byte)(0xFF << (8 - rem));
        return (a[full] & mask) == (b[full] & mask);
    }
}

This is still a deny-list, which OWASP lists as the last resort for when the destinations can’t be enumerated. If the feature only ever talks to a known set of hosts (a payment provider, your own CDN), use an allow-list of hostnames in front of this and treat the IP check as the backstop. The preview and webhook features are the cases where users choose the destination, and there a deny-list is what’s left.

Now the fetcher. Redirects are switched off on the handler and followed by hand, so each hop is a fresh connection and a fresh check:

var handler = new SocketsHttpHandler
{
    AllowAutoRedirect = false,
    ConnectTimeout = TimeSpan.FromSeconds(5),
    ConnectCallback = async (ctx, ct) =>
    {
        var host = ctx.DnsEndPoint.Host;
        var port = ctx.DnsEndPoint.Port;
        var addresses = IPAddress.TryParse(host, out var literal)
            ? [literal]
            : await resolver(host, ct);

        foreach (var ip in addresses)
        {
            var ok = options.AllowOverride?.Invoke(ip, port) ?? IpPolicy.IsPublic(ip);
            if (!ok) throw new SsrfBlockedException($"{host} resolves to {ip}");
        }

        var socket = new Socket(SocketType.Stream, ProtocolType.Tcp) { NoDelay = true };
        try
        {
            await socket.ConnectAsync(addresses, port, ct);
            return new NetworkStream(socket, ownsSocket: true);
        }
        catch { socket.Dispose(); throw; }
    },
};

Two choices in there deserve a sentence each. Every resolved address is checked, not just the first, because a name can return a public address and an internal one together and the socket may try either. And ConnectAsync receives the same addresses array that was checked, so nothing is looked up twice. The AllowOverride parameter is a test seam, explained below; production code never sets it.

The loop that follows redirects:

public async Task<string> GetAsync(string url, CancellationToken ct = default)
{
    var uri = new Uri(url);
    for (var hop = 0; ; hop++)
    {
        if (uri.Scheme is not ("http" or "https"))
            throw new SsrfBlockedException($"scheme {uri.Scheme}");

        HttpResponseMessage response;
        try { response = await _http.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, ct); }
        catch (HttpRequestException e) when (e.InnerException is SsrfBlockedException blocked) { throw blocked; }

        using (response)
        {
            if ((int)response.StatusCode is >= 300 and < 400 && response.Headers.Location is { } next)
            {
                if (hop >= _maxRedirects) throw new SsrfBlockedException("too many redirects");
                uri = next.IsAbsoluteUri ? next : new Uri(uri, next);
                continue;
            }
            response.EnsureSuccessStatusCode();
            return await response.Content.ReadAsStringAsync(ct);
        }
    }
}

The catch matters more than it looks. An exception thrown inside ConnectCallback surfaces from HttpClient wrapped in an HttpRequestException, so without unwrapping, callers see a generic network error and a test asserting on the blocked exception type can’t tell a guard from a timeout. The Microsoft documentation also notes that the callback applies only to stream-based connections (HTTP/1.1 and HTTP/2) and isn’t invoked for HTTP/3. Don’t enable HTTP/3 on this client without re-reading that remark.

Step 3: extend the table until it covers the second hop

Single requests are the easy part. The redirect and rebinding rows need two extra seams: a resolver the test can control, and a way to say “pretend this loopback port is a public host”. The second is the AllowOverride predicate. It exists so one local listener can play the part of an allowed public server while another plays the internal one.

[Fact]
public async Task Safe_blocks_hostname_that_resolves_inside()
{
    using var svc = new InternalService();
    using var f = new SafeFetcher(new FetchOptions(
        Resolver: (_, _) => Task.FromResult(new[] { IPAddress.Loopback })));
    await AssertBlocked(u => f.GetAsync(u), "http://innocent.example:{0}/", svc);
}

[Fact]
public async Task Safe_checks_every_address_not_just_the_first()
{
    using var svc = new InternalService();
    using var f = new SafeFetcher(new FetchOptions(Resolver: (_, _) =>
        Task.FromResult(new[] { IPAddress.Parse("93.184.216.34"), IPAddress.Loopback })));
    await AssertBlocked(u => f.GetAsync(u), "http://mixed.example:{0}/", svc);
}

[Fact]
public async Task Safe_rechecks_each_redirect_hop()
{
    using var inside = new InternalService();
    using var outside = new InternalService();   // stands in for a public host the guard allows
    outside.RedirectTo = $"http://127.0.0.1:{inside.Port}/";
    using var f = new SafeFetcher(new FetchOptions(AllowOverride: (ip, port) => port == outside.Port));

    await Assert.ThrowsAsync<SsrfBlockedException>(() => f.GetAsync($"http://127.0.0.1:{outside.Port}/"));
    Assert.Equal(1, outside.Hits);   // the first hop was allowed and fetched
    Assert.Equal(0, inside.Hits);    // the redirect target never was
}

The first test is the DNS case: a harmless-looking name that resolves to loopback. The second is the mixed answer. The third is the redirect, and its two assertions are the useful part: the allowed hop was reached exactly once, the internal one not at all. Add one positive test too, because a guard that blocks everything also passes every negative test:

[Fact]
public async Task Safe_still_fetches_an_allowed_destination()
{
    using var svc = new InternalService();
    using var f = new SafeFetcher(new FetchOptions(AllowOverride: (_, port) => port == svc.Port));
    Assert.Equal("internal secret", await f.GetAsync($"http://127.0.0.1:{svc.Port}/"));
}

Finally a table for the policy itself, with the boundary values where off-by-one errors in a prefix mask hide:

[Theory]
[InlineData("93.184.216.34", true)]
[InlineData("172.32.0.1", true)]
[InlineData("172.31.255.255", false)]
[InlineData("100.127.255.255", false)]
[InlineData("100.128.0.1", true)]
[InlineData("::ffff:10.0.0.1", false)]
[InlineData("64:ff9b::a9fe:a9fe", false)]
[InlineData("2606:4700:4700::1111", true)]
public void Ip_policy_table(string ip, bool isPublic) =>
    Assert.Equal(isPublic, IpPolicy.IsPublic(IPAddress.Parse(ip)));

64:ff9b::a9fe:a9fe is the NAT64 form of 169.254.169.254, the metadata address again, tucked inside an IPv6 prefix that a hand-written IPv4 check would never see.

Show it working

Run the whole suite, naive rows included, to see the difference side by side:

dotnet test
  Failed Fetch.Tests.SsrfAttackTable.Naive_blocks(template: "http://[::1]:{0}/")
  Failed Fetch.Tests.SsrfAttackTable.Naive_blocks(template: "http://0.0.0.0:{0}/")
  Failed Fetch.Tests.SsrfAttackTable.Naive_blocks(template: "http://[::ffff:127.0.0.1]:{0}/")
  Failed Fetch.Tests.SsrfAttackTable.Naive_blocks(template: "http://100.100.100.200/")
  Failed Fetch.Tests.SsrfAttackTable.Naive_blocks(template: "http://[fd00:ec2::254]/latest/meta-data/")
Failed!  - Failed:     5, Passed:    28, Skipped:     0, Total:    33

Then only the hardened implementation:

dotnet test --filter "FullyQualifiedName~Safe"
Passed!  - Failed:     0, Passed:    14, Skipped:     0, Total:    14

The naive class is there to keep the table honest. Delete it once the table has done its job, or keep it in the test project as the reference for what the table is meant to catch. In a real repository the five failing rows are the ones to run before accepting the agent’s first draft, because they show the draft is wrong without anyone having to argue about it.

One row from the original attempt is missing from the table: http://localhost.:{0}/, a trailing-dot hostname. It never got a verdict because the name didn’t resolve in the sandbox the examples ran in, so the request failed with a name-resolution error rather than a blocked exception. Behaviour of that form depends on the machine’s resolver. If it resolves on yours, add the row; it should block, since the guard sees only the resolved address.

Step 4: make the agent keep it

The table is the contract. The prompt hands it over, so the next agent doesn’t reinvent the check from memory:

Add a "fetch preview" feature to the Web project that takes a user-supplied URL.

Rules:
1. All outbound requests to user-supplied URLs go through SafeFetcher. Do not
   construct an HttpClient for them anywhere else, and do not change SafeFetcher
   to make a test pass.
2. Do not edit SsrfAttackTable or IpPolicy tests. If a row is wrong, tell me why
   and stop.
3. Run `dotnet test` before finishing and paste the summary line.
4. If the feature needs a destination the guard blocks, say so. Do not add an
   exception.

Rule 1 is the one that fails quietly. An agent in a hurry writes new HttpClient() in a new service, and no test notices because the table only exercises SafeFetcher. Close that gap with a build check:

# Fails the build if new HttpClient() appears outside the one allowed file.
! grep -rn --include='*.cs' 'new HttpClient(' src/ | grep -v 'SafeFetcher.cs'

Better, if the project uses a banned-API analyser, put HttpClient..ctor on its banned list with an exception for the one file. Either way the instruction in the prompt and the check in CI say the same thing, and only one of them can be argued out of.

Make it yours

For TypeScript on Node, the same decision belongs where the socket is opened: a custom lookup function on the http.Agent that rejects non-public addresses, with redirect: "manual" on fetch and a loop that re-checks each hop. The table of URLs carries over unchanged, and a Vitest it.each over the same rows replaces the xUnit theory.

If the destinations are known, put an allow-list in front. A webhook feature that only posts to hosts a tenant has registered and verified needs the IP check far less than a free-text preview box does. OWASP’s advice is to prefer allow-lists, and to accept a host and build the URL yourself, with a fixed scheme, port and path, rather than accepting a whole URL.

At the network layer, outbound routes can be restricted with a firewall or segregation, which OWASP recommends in addition to code checks, and on AWS the metadata service should be on IMDSv2 with IMDSv1 disabled. Code-level guards are the thing the application owns; the network rules are what still hold when the code has a bug.

What goes wrong

The guard doesn’t help if something between the app and the internet is doing the dialling. If outbound traffic is configured to go through an egress proxy, the address the socket connects to is the proxy’s, and the destination check has to happen at the proxy. Test that path explicitly before relying on the callback.

Response handling is a separate risk the table doesn’t cover. MaxResponseContentBufferSize bounds the buffered body and the client has a timeout, but a preview feature that renders what it fetched also needs size limits, a content-type allow-list and no reflecting of raw error bodies back to the caller. Error messages that say innocent.example resolves to 127.0.0.1 tell an attacker which names are internal, so log them and return a generic message.

DNS rebinding is closed here because the check and the connect use one lookup, but a deny-list can still be outflanked by ranges that aren’t on it. New special-purpose blocks do get allocated, and the table above is a snapshot, not a permanent answer.

Don’t bother if the service never fetches a URL a user supplied, directly or through a webhook, an image proxy, an import-from-URL button or an OAuth discovery document. If it does any of those, the code was probably written to be demoed, and that’s the case this is for.

First 15 minutes

Search the codebase for new HttpClient( and HttpClient.GetAsync and list every place a URL that came from a user, a database row or a config a tenant controls is fetched. For the first one, copy the attack table into a test class, point it at the existing code, and run it. Every row that fails is a finding, and the failing output is the bug report to hand to the agent along with the prompt above.