Use rightmost IP from forwarded headers

A client can prepend a spoofed entry to X-Forwarded-For before
the request reaches our load balancer. Taking the first value
would return the attacker's address. Since we sit behind a
single trusted LB that appends the real client IP as the last
entry, switch to rightmost extraction for both X-Forwarded-For
and RFC 7239 Forwarded headers.

Signed-off-by: Émile Ré <emile@getprobo.com>
This commit is contained in:
Émile Ré
2026-04-29 14:16:37 +04:00
parent c0d96e662e
commit 9920093c22
2 changed files with 17 additions and 9 deletions

View File

@@ -48,9 +48,15 @@ func TestExtract(t *testing.T) {
want: "203.0.113.50",
},
{
name: "x-forwarded-for chain",
name: "x-forwarded-for chain takes rightmost",
remoteAddr: "10.0.0.1:1234",
headers: map[string]string{"X-Forwarded-For": "203.0.113.50, 70.41.3.18, 150.172.238.178"},
want: "150.172.238.178",
},
{
name: "x-forwarded-for spoofed prefix",
remoteAddr: "10.0.0.1:1234",
headers: map[string]string{"X-Forwarded-For": "1.2.3.4, 203.0.113.50"},
want: "203.0.113.50",
},
{
@@ -84,10 +90,10 @@ func TestExtract(t *testing.T) {
want: "198.51.100.17",
},
{
name: "forwarded header chain",
name: "forwarded header chain takes rightmost",
remoteAddr: "10.0.0.1:1234",
headers: map[string]string{"Forwarded": "for=198.51.100.17, for=70.41.3.18"},
want: "198.51.100.17",
want: "70.41.3.18",
},
{
name: "forwarded takes precedence over x-forwarded-for",