From 24623330745b29cc09e93933104385b770101a39 Mon Sep 17 00:00:00 2001 From: Adam Pritchard Date: Sun, 27 Mar 2022 14:37:31 -0400 Subject: [PATCH] Fix #227: correct whitespace handling in XFF header parsing --- proxy_headers.go | 6 +++--- proxy_headers_test.go | 6 +++++- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/proxy_headers.go b/proxy_headers.go index ed939dc..38257a3 100644 --- a/proxy_headers.go +++ b/proxy_headers.go @@ -69,13 +69,13 @@ func getIP(r *http.Request) string { if fwd := r.Header.Get(xForwardedFor); fwd != "" { // Only grab the first (client) address. Note that '192.168.0.1, - // 10.1.1.1' is a valid key for X-Forwarded-For where addresses after + // 10.1.1.1' is a valid value for X-Forwarded-For where addresses after // the first may represent forwarding proxies earlier in the chain. - s := strings.Index(fwd, ", ") + s := strings.Index(fwd, ",") if s == -1 { s = len(fwd) } - addr = fwd[:s] + addr = strings.TrimSpace(fwd[:s]) } else if fwd := r.Header.Get(xRealIP); fwd != "" { // X-Real-IP should only contain one IP address (the client making the // request). diff --git a/proxy_headers_test.go b/proxy_headers_test.go index b1fe685..e4a49e2 100644 --- a/proxy_headers_test.go +++ b/proxy_headers_test.go @@ -17,6 +17,8 @@ func TestGetIP(t *testing.T) { {xForwardedFor, "8.8.8.8", "8.8.8.8"}, // Single address {xForwardedFor, "8.8.8.8, 8.8.4.4", "8.8.8.8"}, // Multiple {xForwardedFor, "[2001:db8:cafe::17]:4711", "[2001:db8:cafe::17]:4711"}, // IPv6 address + {xForwardedFor, "8.8.8.8,8.8.4.4", "8.8.8.8"}, // No space after comma + {xForwardedFor, "8.8.8.8 , 8.8.4.4", "8.8.8.8"}, // Space before comma {xForwardedFor, "", ""}, // None {xRealIP, "8.8.8.8", "8.8.8.8"}, // Single address {xRealIP, "8.8.8.8, 8.8.4.4", "8.8.8.8, 8.8.4.4"}, // Multiple @@ -27,6 +29,8 @@ func TestGetIP(t *testing.T) { {forwarded, `for=192.0.2.60;proto=http;by=203.0.113.43`, `192.0.2.60`}, // Multiple params {forwarded, `for=192.0.2.43, for=198.51.100.17`, "192.0.2.43"}, // Multiple params {forwarded, `for="workstation.local",for=198.51.100.17`, "workstation.local"}, // Hostname + {forwarded, `for=192.0.2.43,for=198.51.100.17`, "192.0.2.43"}, // No space after comma + {forwarded, `for=192.0.2.43 , for=198.51.100.17`, "192.0.2.43"}, // Space before comma } for _, v := range headers { @@ -36,7 +40,7 @@ func TestGetIP(t *testing.T) { }} res := getIP(req) if res != v.expected { - t.Fatalf("wrong header for %s: got %s want %s", v.key, res, + t.Fatalf("wrong header for %s: got %q want %q", v.key, res, v.expected) } }