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/app.go b/modules/caddyhttp/app.go index 1c42212b2..976824976 100644 --- a/modules/caddyhttp/app.go +++ b/modules/caddyhttp/app.go @@ -446,6 +446,11 @@ func (app *App) Validate() error { } } + // zero disables strict parsing; a negative count would silently do the same + if srv.TrustedProxiesStrict < 0 { + return fmt.Errorf("server %s: trusted_proxies_strict must not be negative: %d", srvName, srv.TrustedProxiesStrict) + } + // logger names must not have ports if srv.Logs != nil { for host := range srv.Logs.LoggerNames { diff --git a/modules/caddyhttp/app_test.go b/modules/caddyhttp/app_test.go index b1819d24d..9b4bc82ee 100644 --- a/modules/caddyhttp/app_test.go +++ b/modules/caddyhttp/app_test.go @@ -16,6 +16,7 @@ package caddyhttp import ( "context" + "encoding/json" "fmt" "io" "net/http" @@ -184,3 +185,26 @@ func TestServerErrorLoggerLevels(t *testing.T) { }) } } + +func TestValidateTrustedProxiesStrictCount(t *testing.T) { + for _, tc := range []struct { + count string + wantErr bool + }{ + {"0", false}, + {"2", false}, + {"-1", true}, + } { + t.Run(tc.count, func(t *testing.T) { + var app App + config := `{"servers": {"srv0": {"listen": [":443"], "trusted_proxies_strict": ` + tc.count + `}}}` + if err := json.Unmarshal([]byte(config), &app); err != nil { + t.Fatal(err) + } + err := app.Validate() + if tc.wantErr != (err != nil) { + t.Fatalf("Validate() = %v, want error: %t", err, tc.wantErr) + } + }) + } +} diff --git a/modules/caddyhttp/server.go b/modules/caddyhttp/server.go index 8a7431792..a09bf19b0 100644 --- a/modules/caddyhttp/server.go +++ b/modules/caddyhttp/server.go @@ -317,8 +317,18 @@ 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 some untrusted values but fewer + // than N, the request did not come through the expected + // proxies, so the direct remote address is used; if it has + // none, the next header is tried, then the remote address. + // N > 1 is safe only if clients cannot reach the trusted + // proxies without going through the untrusted ones, and the + // outermost proxy controls the incoming header value. 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. @@ -1874,7 +1884,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, "@") } @@ -1904,7 +1914,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()) } @@ -1965,13 +1975,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. If a header has fewer untrusted addresses than count, or +// 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), ","), ",") + seen := 0 for _, part := range slices.Backward(parts) { // Some proxies may retain the port number, so split if possible host, _, err := net.SplitHostPort(part) @@ -1987,10 +1999,19 @@ func strictUntrustedClientIp(r *http.Request, headers []string, trusted []netip. if err != nil { continue } - if !isTrustedClientIP(ipAddr, trusted) { + if isTrustedClientIP(ipAddr, trusted) { + continue + } + seen++ + if seen >= count { return ipAddr.String() } } + if seen > 0 { + // Fewer untrusted hops than configured: the request + // bypassed part of the expected proxy chain. + return clientIP + } } return clientIP diff --git a/modules/caddyhttp/server_test.go b/modules/caddyhttp/server_test.go index 6692456a6..6d921c4a0 100644 --- a/modules/caddyhttp/server_test.go +++ b/modules/caddyhttp/server_test.go @@ -1445,6 +1445,46 @@ 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 remote address + {count: 3, xff: "45.54.45.54, 20.20.20.20", want: "10.0.0.1"}, + {count: 2, xff: "10.0.0.5, 10.0.0.4", want: "10.0.0.1"}, + // a client that skipped the WAF and reached the load balancer directly + {count: 2, xff: "45.54.45.54", want: "10.0.0.1"}, + {count: 2, xff: "45.54.45.54, 10.0.0.5", 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))