caddyhttp: Support a count for trusted_proxies_strict

This commit is contained in:
Jay Hemnani 2026-10-19 15:07:13 +05:30
parent 612128e3b0
commit 0983c23835
4 changed files with 117 additions and 11 deletions

View file

@ -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() {

View file

@ -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
}
}
}
}
}

View file

@ -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
}
}

View file

@ -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))