Skip to content

Fix whitespace handling in X-Forwarded-For header parsing #228

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions proxy_headers.go
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
6 changes: 5 additions & 1 deletion proxy_headers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 {
Expand All @@ -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)
}
}
Expand Down