middleware: treat RemoteAddr as the rightmost hop in ClientIPFrom* (#1214)

* middleware: treat RemoteAddr as the rightmost hop in ClientIPFrom*

ClientIPFromXFF trusted X-Forwarded-For entries in the configured CIDRs
but never checked that the TCP peer was one of those proxies. A client
reaching the origin directly could pick its own client IP.

- ClientIPFromXFF: a peer outside the trusted prefixes is now the client
  IP and XFF is ignored. Calling it with no prefixes now panics; use
  ClientIPFromXFFTrustedProxies(1) or pass the proxy's address instead.
- ClientIPFromHeader: accepts optional trusted prefixes with the same
  rule, matching nginx set_real_ip_from, Apache RemoteIPTrustedProxy and
  Caddy trusted_proxies. Without prefixes, behavior is unchanged.
- ClientIPFromXFFTrustedProxies: unchanged; it is for unknown proxy IPs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* middleware: note Cloudflare CIDRs in example are a partial list

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Vojtech Vitek (golang.cz) 2026-10-12 13:22:20 +02:00 committed by GitHub
parent 167e1e3bd0
commit 7f9b7448f5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 233 additions and 48 deletions

View file

@ -39,15 +39,37 @@ const xForwardedForHeader = "X-Forwarded-For"
//
// v4-mapped IPv6 (::ffff:a.b.c.d) folds to plain v4 and IPv6 zones are
// stripped before storage.
func ClientIPFromHeader(trustedHeader string) func(http.Handler) http.Handler {
//
// Overwriting only protects requests that pass through your proxy. A client
// that reaches this server directly can set the header to anything. Pass
// your proxy's CIDR prefixes as trustedIPPrefixes to close that gap: the
// header is then read only when r.RemoteAddr falls within one of them;
// otherwise r.RemoteAddr itself is the client IP. This mirrors nginx
// (set_real_ip_from), Apache (RemoteIPTrustedProxy), and Caddy
// (trusted_proxies), and Cloudflare's advice to accept origin traffic only
// from its IP ranges. Without trustedIPPrefixes, guarantee at the network
// layer (security group / firewall) that only your proxy can reach this
// server.
//
// r.Use(middleware.ClientIPFromHeader("CF-Connecting-IP",
// "173.245.48.0/20", // Cloudflare IPv4, see https://www.cloudflare.com/ips/
// "2400:cb00::/32", // Cloudflare IPv6
// ))
//
// Panics at startup if any prefix is invalid.
func ClientIPFromHeader(trustedHeader string, trustedIPPrefixes ...string) func(http.Handler) http.Handler {
header := http.CanonicalHeaderKey(trustedHeader)
prefixes := mustParsePrefixes(trustedIPPrefixes)
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
values := r.Header.Values(header)
if len(values) > 0 {
if ip, ok := parseHeaderAddr(values[len(values)-1]); ok {
r = r.WithContext(context.WithValue(r.Context(), clientIPCtxKey, ip))
}
var found netip.Addr
if peer, untrusted := untrustedPeer(r, prefixes); untrusted {
found = peer
} else if values := r.Header.Values(header); len(values) > 0 {
found, _ = parseHeaderAddr(values[len(values)-1])
}
if found.IsValid() {
r = r.WithContext(context.WithValue(r.Context(), clientIPCtxKey, found))
}
h.ServeHTTP(w, r)
})
@ -78,9 +100,15 @@ func ClientIPFromHeader(trustedHeader string) func(http.Handler) http.Handler {
// "2600:9000::/28", // CloudFront IPv6
// ))
//
// Calling with no arguments returns the rightmost XFF entry, or no IP if
// that entry doesn't parse (fail-closed) — safe only if you have exactly
// one trusted hop directly in front of this server (e.g., nginx on localhost).
// The TCP peer in r.RemoteAddr is treated as the rightmost hop: if it is
// not within a trusted prefix, it is the client IP and X-Forwarded-For is
// ignored. A client reaching this server directly therefore cannot spoof
// its IP. If r.RemoteAddr doesn't parse, no client IP is set (fail-closed).
//
// At least one prefix is required. For a single trusted hop directly in
// front of this server (e.g., nginx on localhost), pass its address:
//
// r.Use(middleware.ClientIPFromXFF("127.0.0.1/32", "::1/128"))
//
// v4-mapped IPv6 (::ffff:a.b.c.d) folds to plain v4 and IPv6 zones are
// stripped before the prefix check and storage; otherwise an attacker
@ -89,26 +117,30 @@ func ClientIPFromHeader(trustedHeader string) func(http.Handler) http.Handler {
// If you know the number of trusted proxies but not their IPs, use
// [ClientIPFromXFFTrustedProxies] instead.
//
// Panics at startup if any prefix is invalid.
// Panics at startup if no prefix is given or any prefix is invalid.
func ClientIPFromXFF(trustedIPPrefixes ...string) func(http.Handler) http.Handler {
prefixes := make([]netip.Prefix, len(trustedIPPrefixes))
for i, p := range trustedIPPrefixes {
prefixes[i] = netip.MustParsePrefix(p)
if len(trustedIPPrefixes) == 0 {
panic("middleware.ClientIPFromXFF: at least one trusted IP prefix is required; use ClientIPFromXFFTrustedProxies(1) to trust any peer")
}
prefixes := mustParsePrefixes(trustedIPPrefixes)
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var found netip.Addr
walkXFF(r.Header[xForwardedForHeader], func(v string) bool {
ip, ok := parseHeaderAddr(v)
if !ok {
return true // fail-closed; leave found unset
}
if inAnyPrefix(ip, prefixes) {
return false // trusted hop; keep walking left
}
found = ip
return true
})
if peer, untrusted := untrustedPeer(r, prefixes); untrusted {
found = peer
} else {
walkXFF(r.Header[xForwardedForHeader], func(v string) bool {
ip, ok := parseHeaderAddr(v)
if !ok {
return true // fail-closed; leave found unset
}
if inAnyPrefix(ip, prefixes) {
return false // trusted hop; keep walking left
}
found = ip
return true
})
}
if found.IsValid() {
r = r.WithContext(context.WithValue(r.Context(), clientIPCtxKey, found))
}
@ -187,12 +219,8 @@ func ClientIPFromXFFTrustedProxies(numTrustedProxies int) func(http.Handler) htt
// IPv6 zones are preserved (link-local connections may legitimately have one).
func ClientIPFromRemoteAddr(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
host = r.RemoteAddr // RemoteAddr may already be a bare IP (e.g. in tests).
}
if ip, err := netip.ParseAddr(host); err == nil {
r = r.WithContext(context.WithValue(r.Context(), clientIPCtxKey, ip.Unmap()))
if ip, ok := parseRemoteAddr(r.RemoteAddr); ok {
r = r.WithContext(context.WithValue(r.Context(), clientIPCtxKey, ip))
}
h.ServeHTTP(w, r)
})
@ -246,6 +274,45 @@ func walkXFF(headers []string, visit func(entry string) bool) {
}
}
// mustParsePrefixes parses CIDR prefixes, panicking on the first invalid one.
func mustParsePrefixes(cidrs []string) []netip.Prefix {
prefixes := make([]netip.Prefix, len(cidrs))
for i, p := range cidrs {
prefixes[i] = netip.MustParsePrefix(p)
}
return prefixes
}
// untrustedPeer reports whether the TCP peer in r.RemoteAddr is outside
// prefixes. If so, peer is the client IP, or invalid if RemoteAddr doesn't
// parse. With no prefixes, every peer is trusted.
func untrustedPeer(r *http.Request, prefixes []netip.Prefix) (peer netip.Addr, untrusted bool) {
if len(prefixes) == 0 {
return netip.Addr{}, false
}
peer, ok := parseRemoteAddr(r.RemoteAddr)
if !ok {
return netip.Addr{}, true
}
// Zoned addresses never match a prefix, so check a link-local peer without its zone.
return peer, !inAnyPrefix(peer.WithZone(""), prefixes)
}
// parseRemoteAddr parses the host of r.RemoteAddr. v4-mapped IPv6 folds to
// plain v4; the IPv6 zone is preserved (link-local connections may
// legitimately have one).
func parseRemoteAddr(remoteAddr string) (netip.Addr, bool) {
host, _, err := net.SplitHostPort(remoteAddr)
if err != nil {
host = remoteAddr // RemoteAddr may already be a bare IP (e.g. in tests).
}
ip, err := netip.ParseAddr(host)
if err != nil {
return netip.Addr{}, false
}
return ip.Unmap(), true
}
// inAnyPrefix reports whether ip falls within any of the given prefixes.
func inAnyPrefix(ip netip.Addr, prefixes []netip.Prefix) bool {
for _, p := range prefixes {
@ -263,7 +330,7 @@ func inAnyPrefix(ip netip.Addr, prefixes []netip.Prefix) bool {
// address, so without folding/stripping an attacker could escape an
// otherwise valid trust list.
//
// Header-sourced IPs only. [ClientIPFromRemoteAddr] normalizes inline
// Header-sourced IPs only. r.RemoteAddr goes through parseRemoteAddr
// (Unmap, but zone preserved for legitimate link-local connections).
func parseHeaderAddr(s string) (netip.Addr, bool) {
ip, err := netip.ParseAddr(s)

View file

@ -35,8 +35,8 @@ func BenchmarkWalkXFF(b *testing.B) {
}
// BenchmarkWalkXFF_RightmostStop measures the common case for both
// ClientIPFromXFF (no trusted prefixes => stop at the first / rightmost
// entry) and ClientIPFromXFFTrustedProxies(1). Should be near-constant
// ClientIPFromXFF (rightmost entry untrusted => stop at the first visit)
// and ClientIPFromXFFTrustedProxies(1). Should be near-constant
// regardless of n, since the walker stops after the first visit.
func BenchmarkWalkXFF_RightmostStop(b *testing.B) {
for _, n := range []int{1, 10, 100, 1000, 10000} {

View file

@ -44,12 +44,18 @@ func Example_clientIP() {
// (1) Behind a reverse proxy that sets a single-IP header for every
// request and overwrites any client-supplied value (Cloudflare, Nginx
// with ngx_http_realip_module, Apache with mod_remoteip, ...).
r.Use(middleware.ClientIPFromHeader("CF-Connecting-IP"))
// with ngx_http_realip_module, Apache with mod_remoteip, ...). The
// header is read only from peers in your proxy's CIDRs.
// Partial list, see https://www.cloudflare.com/ips/ for all ranges.
r.Use(middleware.ClientIPFromHeader("CF-Connecting-IP",
"173.245.48.0/20", // Cloudflare IPv4.
"2400:cb00::/32", // Cloudflare IPv6.
))
// (2) Behind reverse proxies whose IP ranges you can enumerate as CIDRs.
// The middleware walks X-Forwarded-For right-to-left, skipping trusted
// entries; fail-closed on garbage.
// entries; fail-closed on garbage. A peer outside these CIDRs is the
// client.
//
// r.Use(middleware.ClientIPFromXFF(
// "13.32.0.0/15", // CloudFront IPv4.
@ -70,6 +76,7 @@ func Example_clientIP() {
})
req := httptest.NewRequest("GET", "/", nil)
req.RemoteAddr = "173.245.48.1:443" // Cloudflare edge.
req.Header.Set("CF-Connecting-IP", "198.51.100.42")
req.Header.Set("X-Forwarded-For", "1.2.3.4") // attacker-supplied; ignored.
w := httptest.NewRecorder()

View file

@ -52,7 +52,7 @@ func TestClientIPFromHeader(t *testing.T) {
}
}
func TestClientIPFromXFF_NoTrustedPrefixes(t *testing.T) {
func TestClientIPFromXFF_SingleTrustedHop(t *testing.T) {
tt := []struct {
name string
xff []string
@ -80,7 +80,7 @@ func TestClientIPFromXFF_NoTrustedPrefixes(t *testing.T) {
}
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
got := run(t, ClientIPFromXFF(), func(r *http.Request) {
got := run(t, ClientIPFromXFF(testPeerPrefix), func(r *http.Request) {
for _, v := range tc.xff {
r.Header.Add("X-Forwarded-For", v)
}
@ -161,6 +161,7 @@ func TestClientIPFromXFF_TrustedPrefixes(t *testing.T) {
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
got := run(t, ClientIPFromXFF(tc.prefixes...), func(r *http.Request) {
r.RemoteAddr = peerIn(tc.prefixes[0])
for _, v := range tc.xff {
r.Header.Add("X-Forwarded-For", v)
}
@ -181,6 +182,63 @@ func TestClientIPFromXFF_PanicsOnBadPrefix(t *testing.T) {
ClientIPFromXFF("not-a-cidr")
}
func TestClientIPFromXFF_PanicsOnNoPrefixes(t *testing.T) {
defer func() {
if recover() == nil {
t.Fatal("expected panic on no trusted prefixes")
}
}()
ClientIPFromXFF()
}
func TestClientIPFromHeader_PanicsOnBadPrefix(t *testing.T) {
defer func() {
if recover() == nil {
t.Fatal("expected panic on invalid CIDR")
}
}()
ClientIPFromHeader("X-Real-IP", "not-a-cidr")
}
// TestClientIP_TrustedPeer pins that r.RemoteAddr is the rightmost hop:
// headers are read only when the TCP peer is within a trusted prefix.
func TestClientIP_TrustedPeer(t *testing.T) {
tt := []struct {
name string
remoteAddr string
out string
}{
{"trusted_peer_reads_header", "10.0.0.5:1234", "203.0.113.7"},
{"untrusted_peer_is_client", "198.51.100.9:1234", "198.51.100.9"},
{"v4_mapped_trusted_peer", "[::ffff:10.0.0.5]:1234", "203.0.113.7"},
{"v4_mapped_untrusted_peer_folded", "[::ffff:198.51.100.9]:1234", "198.51.100.9"},
{"zoned_trusted_peer", "[fe80::1%eth0]:1234", "203.0.113.7"},
{"untrusted_ipv6_peer", "[2001:db8::9]:1234", "2001:db8::9"},
{"bare_ip_peer", "10.0.0.5", "203.0.113.7"},
{"unparseable_peer_fails_closed", "@", ""},
{"empty_peer_fails_closed", "", ""},
}
prefixes := []string{"10.0.0.0/8", "fe80::/10"}
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
xff := run(t, ClientIPFromXFF(prefixes...), func(r *http.Request) {
r.RemoteAddr = tc.remoteAddr
r.Header.Set("X-Forwarded-For", "203.0.113.7, 10.0.0.1")
})
if xff != tc.out {
t.Errorf("ClientIPFromXFF: want %q, got %q", tc.out, xff)
}
hdr := run(t, ClientIPFromHeader("X-Real-IP", prefixes...), func(r *http.Request) {
r.RemoteAddr = tc.remoteAddr
r.Header.Set("X-Real-IP", "203.0.113.7")
})
if hdr != tc.out {
t.Errorf("ClientIPFromHeader: want %q, got %q", tc.out, hdr)
}
})
}
}
func TestClientIPFromXFFTrustedProxies(t *testing.T) {
tt := []struct {
name string
@ -188,7 +246,7 @@ func TestClientIPFromXFFTrustedProxies(t *testing.T) {
xff []string
out string
}{
// N=1 ⇒ rightmost (equivalent to ClientIPFromXFF() with no prefixes).
// N=1 ⇒ rightmost.
{"n1_rightmost", 1, []string{"1.1.1.1, 2.2.2.2"}, "2.2.2.2"},
{"n2_second_from_right", 2, []string{"1.1.1.1, 2.2.2.2, 3.3.3.3"}, "2.2.2.2"},
{"n3_third_from_right", 3, []string{"1.1.1.1, 2.2.2.2, 3.3.3.3, 4.4.4.4"}, "2.2.2.2"},
@ -279,7 +337,7 @@ func TestClientIPLastWriteWins(t *testing.T) {
t.Run("later_overrides_earlier", func(t *testing.T) {
got := runChain(t,
[]func(http.Handler) http.Handler{
ClientIPFromXFF(),
ClientIPFromXFF(testPeerPrefix),
ClientIPFromHeader("CF-Connecting-IP"),
},
func(r *http.Request) {
@ -294,7 +352,7 @@ func TestClientIPLastWriteWins(t *testing.T) {
t.Run("earlier_persists_when_later_finds_nothing", func(t *testing.T) {
got := runChain(t,
[]func(http.Handler) http.Handler{
ClientIPFromXFF(),
ClientIPFromXFF(testPeerPrefix),
ClientIPFromHeader("CF-Connecting-IP"), // missing → no-op.
},
func(r *http.Request) {
@ -313,10 +371,10 @@ func TestClientIPLastWriteWins(t *testing.T) {
},
func(r *http.Request) {
r.Header.Set("X-Forwarded-For", "10.0.0.1, 10.0.0.2")
r.RemoteAddr = "192.0.2.1:1234"
r.RemoteAddr = "10.0.0.3:1234"
})
if got != "192.0.2.1" {
t.Errorf("want 192.0.2.1, got %q", got)
if got != "10.0.0.3" {
t.Errorf("want 10.0.0.3, got %q", got)
}
})
}
@ -391,6 +449,7 @@ func TestAdvisory_GHSA_3fxj_6jh8_hvhx(t *testing.T) {
// entry is the genuine attacker IP, never the prepended spoof.
t.Run("behind_proxy_uses_xff", func(t *testing.T) {
got := run(t, ClientIPFromXFF("10.0.0.0/8"), func(r *http.Request) {
r.RemoteAddr = peerIn("10.0.0.0/8")
r.Header.Set("X-Forwarded-For", "1.2.3.4, 99.99.99.99")
})
if got == "1.2.3.4" {
@ -410,7 +469,7 @@ func TestAdvisory_GHSA_9g5q_2w5x_hmxf(t *testing.T) {
var capturedClientIP, capturedRemoteAddr string
r := chi.NewRouter()
r.Use(ClientIPFromXFF())
r.Use(ClientIPFromXFF("203.0.113.99/32"))
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
capturedClientIP = GetClientIP(r.Context())
capturedRemoteAddr = r.RemoteAddr
@ -445,6 +504,7 @@ func TestAdvisory_GHSA_rjr7_jggh_pgcp(t *testing.T) {
// rightmost-untrusted entry is never the loopback spoof.
t.Run("xff_loopback_spoof_rejected", func(t *testing.T) {
got := run(t, ClientIPFromXFF("10.0.0.0/8"), func(r *http.Request) {
r.RemoteAddr = peerIn("10.0.0.0/8")
r.Header.Set("X-Forwarded-For", "127.0.0.1, 99.99.99.99")
})
if got == "127.0.0.1" {
@ -469,6 +529,44 @@ func TestAdvisory_GHSA_rjr7_jggh_pgcp(t *testing.T) {
})
}
// GHSA-j6qf-3m9c-vwj3 (tenbbughunters): ClientIPFromXFF never checked that
// the TCP peer was a trusted proxy, so a client reaching the origin directly
// could pick its own IP. Now an untrusted peer is the client IP; the same
// applies to ClientIPFromHeader when trusted prefixes are given.
func TestAdvisory_GHSA_j6qf_3m9c_vwj3(t *testing.T) {
const attacker = "127.0.0.1:54417"
for _, xff := range []string{
"10.0.0.7, 198.51.100.42", // reporter's PoC: forged trusted hop appended.
"10.0.0.7",
} {
t.Run("xff/"+xff, func(t *testing.T) {
got := run(t, ClientIPFromXFF("198.51.100.0/24"), func(r *http.Request) {
r.RemoteAddr = attacker
r.Header.Set("X-Forwarded-For", xff)
})
if got == "10.0.0.7" {
t.Fatal("VULNERABLE: returned attacker-supplied allowlisted IP")
}
if got != "127.0.0.1" {
t.Errorf("want 127.0.0.1 (real TCP peer), got %q", got)
}
})
}
t.Run("header", func(t *testing.T) {
got := run(t, ClientIPFromHeader("CF-Connecting-IP", "173.245.48.0/20"), func(r *http.Request) {
r.RemoteAddr = attacker
r.Header.Set("CF-Connecting-IP", "10.0.0.7")
})
if got == "10.0.0.7" {
t.Fatal("VULNERABLE: returned attacker-supplied allowlisted IP")
}
if got != "127.0.0.1" {
t.Errorf("want 127.0.0.1 (real TCP peer), got %q", got)
}
})
}
// "Multiple XFF headers" attack — Go's http.Header.Get returns only the first
// value, but the security-relevant rightmost IP is in the LAST instance after
// the proxy appends. We must merge all values; otherwise an attacker can pick
@ -481,6 +579,7 @@ func TestXFF_MultipleHeadersMerged(t *testing.T) {
// chain. A naive http.Header.Get() implementation would only see the first
// header and return the attacker's prepended value.
got := run(t, ClientIPFromXFF("198.51.100.0/24"), func(r *http.Request) {
r.RemoteAddr = peerIn("198.51.100.0/24")
r.Header.Add("X-Forwarded-For", "127.0.0.1") // attacker-injected.
r.Header.Add("X-Forwarded-For", "8.8.8.8, 198.51.100.1") // appended by trusted proxy.
})
@ -579,6 +678,7 @@ func TestXFF_V4MappedIPv6BypassesTrustedV4Prefix(t *testing.T) {
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
got := run(t, ClientIPFromXFF(tc.prefixes...), func(r *http.Request) {
r.RemoteAddr = peerIn(tc.prefixes[0])
r.Header.Set("X-Forwarded-For", tc.xff)
})
if got != tc.out {
@ -600,6 +700,7 @@ func TestXFF_V4MappedIPv6BypassesTrustedV4Prefix(t *testing.T) {
// and skipped.
func TestXFF_IPv6ZoneIDBypassesTrustedV6Prefix(t *testing.T) {
got := run(t, ClientIPFromXFF("2606:4700::/32"), func(r *http.Request) {
r.RemoteAddr = peerIn("2606:4700::/32")
r.Header.Set("X-Forwarded-For", "2606:4700::1%attacker, 2606:4700::5")
})
if got != "" {
@ -656,9 +757,10 @@ func TestXFF_FailClosedOnUnparseable(t *testing.T) {
// otherwise-valid 1.1.1.1 to the left. Without fail-closed, garbage
// to the right of a real client could be silently elided.
{
name: "garbage_rightmost_no_prefixes",
xff: []string{"1.1.1.1, garbage"},
out: "",
name: "garbage_rightmost",
prefixes: []string{"10.0.0.0/8"},
xff: []string{"1.1.1.1, garbage"},
out: "",
},
// Garbage between the client and a trusted proxy hop. Without fail-
// closed, the walker would skip the trusted hop, silently skip the
@ -690,6 +792,7 @@ func TestXFF_FailClosedOnUnparseable(t *testing.T) {
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
got := run(t, ClientIPFromXFF(tc.prefixes...), func(r *http.Request) {
r.RemoteAddr = peerIn(tc.prefixes[0])
for _, v := range tc.xff {
r.Header.Add("X-Forwarded-For", v)
}
@ -701,6 +804,14 @@ func TestXFF_FailClosedOnUnparseable(t *testing.T) {
}
}
// testPeerPrefix covers httptest.NewRequest's default RemoteAddr.
const testPeerPrefix = "192.0.2.1/32"
// peerIn returns a RemoteAddr inside prefix.
func peerIn(prefix string) string {
return netip.AddrPortFrom(netip.MustParsePrefix(prefix).Addr().Next(), 1234).String()
}
// run invokes mw with the request constructed by buildReq and returns the
// client IP captured inside the handler (or "" if none was set).
func run(t *testing.T, mw func(http.Handler) http.Handler, buildReq func(*http.Request)) string {