From 0983c23835820bca4dad397cfb34b742ac71faa2 Mon Sep 17 00:00:00 2001 From: Jay Hemnani <193022578+jayhemnani9910@users.noreply.github.com> Date: Mon, 19 Oct 2026 15:07:13 +0530 Subject: [PATCH] caddyhttp: Support a count for `trusted_proxies_strict` --- caddyconfig/httpcaddyfile/serveroptions.go | 9 +++- ...trusted_proxies_strict_count.caddyfiletest | 46 +++++++++++++++++++ modules/caddyhttp/server.go | 36 +++++++++++---- modules/caddyhttp/server_test.go | 37 +++++++++++++++ 4 files changed, 117 insertions(+), 11 deletions(-) create mode 100644 caddytest/integration/caddyfile_adapt/global_server_options_trusted_proxies_strict_count.caddyfiletest diff --git a/caddyconfig/httpcaddyfile/serveroptions.go b/caddyconfig/httpcaddyfile/serveroptions.go index 670aed193..1e25001b2 100644 --- a/caddyconfig/httpcaddyfile/serveroptions.go +++ b/caddyconfig/httpcaddyfile/serveroptions.go @@ -349,10 +349,17 @@ func unmarshalCaddyfileServerOptions(d *caddyfile.Dispenser) (any, error) { serverOpts.TrustedProxiesRaw = jsonSource case "trusted_proxies_strict": + serverOpts.TrustedProxiesStrict = 1 + if d.NextArg() { + count, err := strconv.Atoi(d.Val()) + if err != nil || count < 1 { + return nil, d.Errf("trusted_proxies_strict count must be a positive integer: %s", d.Val()) + } + serverOpts.TrustedProxiesStrict = count + } if d.NextArg() { return nil, d.ArgErr() } - serverOpts.TrustedProxiesStrict = 1 case "trusted_proxies_unix": if d.NextArg() { diff --git a/caddytest/integration/caddyfile_adapt/global_server_options_trusted_proxies_strict_count.caddyfiletest b/caddytest/integration/caddyfile_adapt/global_server_options_trusted_proxies_strict_count.caddyfiletest new file mode 100644 index 000000000..287c59d5e --- /dev/null +++ b/caddytest/integration/caddyfile_adapt/global_server_options_trusted_proxies_strict_count.caddyfiletest @@ -0,0 +1,46 @@ +{ + servers { + trusted_proxies static private_ranges + trusted_proxies_strict 2 + } +} + +:8080 { + respond "ok" +} +---------- +{ + "apps": { + "http": { + "servers": { + "srv0": { + "listen": [ + ":8080" + ], + "routes": [ + { + "handle": [ + { + "body": "ok", + "handler": "static_response" + } + ] + } + ], + "trusted_proxies": { + "ranges": [ + "192.168.0.0/16", + "172.16.0.0/12", + "10.0.0.0/8", + "127.0.0.1/8", + "fd00::/8", + "::1" + ], + "source": "static" + }, + "trusted_proxies_strict": 2 + } + } + } + } +} diff --git a/modules/caddyhttp/server.go b/modules/caddyhttp/server.go index ed4c6ef80..fe5c5cebf 100644 --- a/modules/caddyhttp/server.go +++ b/modules/caddyhttp/server.go @@ -316,8 +316,14 @@ type Server struct { // If greater than zero, enables strict ClientIPHeaders // (default X-Forwarded-For) parsing. If enabled, the // ClientIPHeaders will be parsed from right to left, and - // the first value that is both valid and doesn't match the - // trusted proxy list will be used as client IP. If zero, + // the Nth value that is both valid and doesn't match the + // trusted proxy list will be used as client IP, where N is + // this value. Use N > 1 when there are proxies in front of + // the trusted ones whose addresses are not known, such as a + // WAF in front of a load balancer. Only untrusted values are + // counted. If a header has fewer such values, the left-most + // of them is used; if it has none, the next header is tried, + // then the remote address. If zero, // the ClientIPHeaders will be parsed from left to right, // and the first value that is a valid IP address will be // used as client IP. @@ -1850,7 +1856,7 @@ func determineTrustedProxy(r *http.Request, s *Server) (bool, string) { if s.trustedProxies != nil { ipRanges = s.trustedProxies.GetIPRanges(r) } - return true, strictUntrustedClientIp(r, s.ClientIPHeaders, ipRanges, "@") + return true, strictUntrustedClientIp(r, s.ClientIPHeaders, ipRanges, "@", s.TrustedProxiesStrict) } else { return true, trustedRealClientIP(r, s.ClientIPHeaders, "@") } @@ -1880,7 +1886,7 @@ func determineTrustedProxy(r *http.Request, s *Server) (bool, string) { if isTrustedClientIP(ipAddr, s.trustedProxies.GetIPRanges(r)) { if s.TrustedProxiesStrict > 0 { - return true, strictUntrustedClientIp(r, s.ClientIPHeaders, s.trustedProxies.GetIPRanges(r), ipAddr.String()) + return true, strictUntrustedClientIp(r, s.ClientIPHeaders, s.trustedProxies.GetIPRanges(r), ipAddr.String(), s.TrustedProxiesStrict) } return true, trustedRealClientIP(r, s.ClientIPHeaders, ipAddr.String()) } @@ -1941,13 +1947,15 @@ func trustedRealClientIP(r *http.Request, headers []string, clientIP string) str } // strictUntrustedClientIp iterates through the list of client IP headers, -// parses them from right-to-left, and returns the first valid IP address -// that is untrusted. If no valid IP address is found, then the direct -// remote address is returned. -func strictUntrustedClientIp(r *http.Request, headers []string, trusted []netip.Prefix, clientIP string) string { +// parses them from right-to-left, and returns the count-th valid IP address +// that is untrusted, or the left-most one if a header has fewer. If no valid +// untrusted IP address is found, then the direct remote address is returned. +func strictUntrustedClientIp(r *http.Request, headers []string, trusted []netip.Prefix, clientIP string, count int) string { for _, headerName := range headers { parts := strings.Split(strings.Join(r.Header.Values(headerName), ","), ",") + var untrusted string + seen := 0 for _, part := range slices.Backward(parts) { // Some proxies may retain the port number, so split if possible host, _, err := net.SplitHostPort(part) @@ -1963,9 +1971,17 @@ func strictUntrustedClientIp(r *http.Request, headers []string, trusted []netip. if err != nil { continue } - if !isTrustedClientIP(ipAddr, trusted) { - return ipAddr.String() + if isTrustedClientIP(ipAddr, trusted) { + continue } + untrusted = ipAddr.String() + seen++ + if seen >= count { + return untrusted + } + } + if untrusted != "" { + return untrusted } } diff --git a/modules/caddyhttp/server_test.go b/modules/caddyhttp/server_test.go index 2021fb0aa..d7290d456 100644 --- a/modules/caddyhttp/server_test.go +++ b/modules/caddyhttp/server_test.go @@ -1391,6 +1391,43 @@ func TestServer_DetermineTrustedProxy_MatchRightMostUntrustedFirst(t *testing.T) assert.Equal(t, clientIP, "90.100.110.120") } +func TestServer_DetermineTrustedProxy_MatchRightMostUntrustedCount(t *testing.T) { + localPrivatePrefix, _ := netip.ParsePrefix("10.0.0.0/8") + + for _, tc := range []struct { + count int + xff string + want string + }{ + // a WAF (20.20.20.20) in front of a trusted load balancer + {count: 1, xff: "30.30.30.30, 45.54.45.54, 20.20.20.20", want: "20.20.20.20"}, + {count: 2, xff: "30.30.30.30, 45.54.45.54, 20.20.20.20", want: "45.54.45.54"}, + {count: 3, xff: "30.30.30.30, 45.54.45.54, 20.20.20.20", want: "30.30.30.30"}, + // trusted and invalid values are not counted + {count: 2, xff: "45.54.45.54, 10.0.0.5, bad, 20.20.20.20, 10.0.0.4", want: "45.54.45.54"}, + // fewer untrusted values than the count: the left-most one + {count: 3, xff: "45.54.45.54, 20.20.20.20", want: "45.54.45.54"}, + {count: 2, xff: "10.0.0.5, 10.0.0.4", want: "10.0.0.1"}, + } { + server := &Server{ + trustedProxies: &StaticIPRange{ + ranges: []netip.Prefix{localPrivatePrefix}, + }, + ClientIPHeaders: []string{"X-Forwarded-For"}, + TrustedProxiesStrict: tc.count, + } + + req := httptest.NewRequest("GET", "/", nil) + req.RemoteAddr = "10.0.0.1:12345" + req.Header.Set("X-Forwarded-For", tc.xff) + + trusted, clientIP := determineTrustedProxy(req, server) + + assert.True(t, trusted) + assert.Equal(t, tc.want, clientIP, "count %d, X-Forwarded-For %q", tc.count, tc.xff) + } +} + func TestServer_LogRequest_WithWriteError(t *testing.T) { s := &Server{} ctx := context.WithValue(context.Background(), ExtraLogFieldsCtxKey, new(ExtraLogFields))