Skip to content
Katabench
Try free
8 min read The Katabench team

X-Forwarded-For spoofing: stop trusting the leftmost IP

X-Forwarded-For spoofing let one client pass a 10-per-minute limiter 1,000 times. Trusting only the proxy-written hop cut that to 10 accepted.

We sent 1,000 requests from one client at a limiter set to 10 per minute. All 1,000 came back 200.

The limiter partitioned on the client address, and it took that address from the first entry of a header:

C#
var forwarded = context.Request.Headers["X-Forwarded-For"].ToString();
var clientIp = forwarded.Length > 0
    ? forwarded.Split(',')[0].Trim()
    : context.Connection.RemoteIpAddress!.ToString();

Our test client put a different made-up address in that header on every request, so the limiter saw 1,000 visitors with one request each. With a trusted proxy configured as this post describes and the same traffic, the count became 10 accepted and 990 rejected.

Who wrote which part of the header

Many proxies append by default: they add the address of whoever connected to them and keep what was already there. nginx's $proxy_add_x_forwarded_for is defined that way. So a client can start the list with anything it likes:

HTTP
GET /login HTTP/1.1
Host: shop.example
X-Forwarded-For: 1.2.3.4, 203.0.113.50

Here the visitor at 203.0.113.50 sent X-Forwarded-For: 1.2.3.4, and the proxy added the address it actually saw. The leftmost entry is the most attacker-controlled value in the whole request. MDN's X-Forwarded-For reference allows it only where a spoofed value has no negative impact. RFC 7239, which standardized the newer Forwarded header, gives the same warning for that header: every node on the path can change it, the client included.

What breaks when you read the wrong end

We ran each of these with ASP.NET Core's test server on .NET 10, setting the connection address directly. Your own results will depend on your limiter and policies, but the mechanism is the same.

With 1,000 rotated header values, a 10-per-minute limiter rejected 0 requests keyed on the leftmost entry and 990 keyed on the address the trusted proxy wrote.

Credential stuffing and enumeration both depend on staying under a per-address limit, and the leftmost key hands them an unlimited supply of addresses.

An admin allowlist fails the same way. A gate comparing the leftmost address to 198.51.100.7 returned 200 for X-Forwarded-For: 198.51.100.7, 203.0.113.50, a request that came from 203.0.113.50. The same policy reading RemoteIpAddress after the configured middleware returned 403.

An audit log recording the leftmost entry stores whichever address the attacker chose, and that can be a real customer's. Decisions built on those logs inherit the error, including the abuse report sent to the wrong network and the automatic ban on an innocent address.

Walk from the right, starting at the socket

The only address no client can forge at this layer is the TCP peer of your application, since that connection really happened. Begin there. If that peer is a proxy you run, you can believe the entry it appended, which is the rightmost one. If that entry is another proxy of yours, believe the entry before it. The first address you cannot vouch for is your client, and everything further left is that client's story.

Trust runs from the socket backward

X-Forwarded-For: 1.2.3.4, 203.0.113.50, 10.0.0.1

  1. Start

    10.0.0.2

    TCP peer of the app. No client can forge this.

    Trusted, read the last entry

  2. Rightmost entry

    10.0.0.1

    Written by the load balancer

    Trusted, read the next entry

  3. Next entry

    203.0.113.50

    Written by the edge proxy

    Not ours: this is the client

  4. Leftmost entry

    1.2.3.4

    Written by the client

    Never read

The walk reads the header backward, one hop at a time. Each entry is only as believable as the machine that wrote it, so the walk stops at the first address your own infrastructure cannot vouch for.

MDN describes two ways to decide where to stop. A proxy count says how many hops to take from the right, and a trusted list skips known proxy addresses. A count is simple and goes wrong whenever the topology changes. A list also tells you what to do with a request that did not come through your proxies at all: ignore the header. MDN adds a warning for both methods: if the application can be reached directly from the internet, no part of the list can be trusted. So close that path at the network too, and treat the peer check as the layer that catches a request when the firewall rule is wrong.

ASP.NET Core ForwardedHeaders settings

The middleware does this walk for you, right to left, and replaces RemoteIpAddress. The proxy and load balancer documentation lists the defaults, which we confirmed: no headers forwarded, ForwardLimit of 1, and only loopback trusted (127.0.0.0/8 and ::1).

The trouble usually begins when a deployment behind a real proxy keeps logging the proxy's address, and someone clears the lists to make it stop. We sent two requests through each configuration. In the first column the peer is the proxy 10.0.0.2, with the header 1.2.3.4, 203.0.113.50. In the second, a client at 203.0.113.66 connects directly and sends X-Forwarded-For: 1.2.3.4.

Configuration Through the proxy Direct to the app
Flag set, defaults kept 10.0.0.2 203.0.113.66
Lists cleared, limit 1 203.0.113.50 1.2.3.4 (spoofed)
Lists cleared, limit 2 1.2.3.4 (spoofed) 1.2.3.4 (spoofed)
Lists cleared, limit null 1.2.3.4 (spoofed) 1.2.3.4 (spoofed)
KnownProxies holds 10.0.0.2 203.0.113.50 203.0.113.66

The first row is safe and useless: every visitor shares the proxy's address, so one abuser can fill a limit for everyone. The next three rows are the forum fixes. Clearing the lists with a limit of 1 looks correct behind a proxy, and it lets any direct connection pick its own address. Setting the limit to null with empty lists brings back the leftmost bug inside the framework. The documentation warns against this, saying a null limit belongs only with configured proxies or networks.

For a chain of two proxies you control, name the network and set the limit to the number of proxy hops:

C#
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders =
        ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
    options.ForwardLimit = 2; // edge proxy, then load balancer
    options.KnownProxies.Clear();
    options.KnownIPNetworks.Clear();
    options.KnownIPNetworks.Add(System.Net.IPNetwork.Parse("10.0.0.0/24"));
});

var app = builder.Build();

app.UseForwardedHeaders(); // before anything that reads the client address
app.UseRateLimiter();

Run literally against a peer of 10.0.0.2, that configuration resolved 1.2.3.4, 203.0.113.50, 10.0.0.1 to 203.0.113.50. A direct connection from 203.0.113.66 carrying the same header kept its own address. Leaving the limit at 1 returned 10.0.0.1, which again puts every client in one bucket. An IPv4-mapped peer such as ::ffff:10.0.0.2 matched the network as well. KnownIPNetworks is the .NET 10 name; earlier versions use KnownNetworks.

  • Order is a security setting. With UseRateLimiter ahead of UseForwardedHeaders, two honest clients sending 10 requests each shared one partition and got 10 accepted and 10 rejected. With the order reversed, all 20 went through.
  • Malformed entries stop the walk. A rightmost value of not-an-ip left RemoteIpAddress as the proxy. Check that your proxy overwrites or appends correctly, because a junk entry there collapses clients together.
  • The environment switch has no peer check. Microsoft warns that ASPNETCORE_FORWARDEDHEADERS_ENABLED does not restrict which addresses may forward headers, so treat it as a shortcut for hosts that cannot be reached directly.

A correct result still identifies a machine at your edge, and a corporate gateway can put thousands of people behind that one address, so a limit tight enough for one person can lock out an office. The rate limiter design covers where the counters belong, and the algorithms post covers how to count.

Assert the spoof in a test, not in a review

Forwarded-header settings tend to change during infrastructure work, far from anyone thinking about security, so pin the behavior. TestServer lets you choose the peer directly:

C#
var context = await server.SendAsync(c =>
{
    c.Connection.RemoteIpAddress = IPAddress.Parse("10.0.0.2");
    c.Request.Headers["X-Forwarded-For"] = "1.2.3.4, 203.0.113.50";
});

Assert that your handler saw 203.0.113.50, then repeat with an untrusted peer and assert the header was ignored. Writing that walk yourself, with no shortcut for private ranges, is the whole of the Find the Trusted Forwarded Hop kata in the Katabench Secure Coding track. The free C# secure coding exercises are the place to start if you are not on Pro.

Practice Security & Reliability

More like this: C# secure coding exercises →

Get new katas and .NET tips in your inbox

A short note when fresh kata land, plus the C# and performance tricks behind the grading. No spam, unsubscribe anytime.