Skip to content
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

Remove square brackets from ipv6 addresses in XFF #2182

Merged
merged 3 commits into from Nov 24, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 4 additions & 1 deletion context.go
Expand Up @@ -282,7 +282,10 @@ func (c *context) RealIP() string {
if ip := c.request.Header.Get(HeaderXForwardedFor); ip != "" {
i := strings.IndexAny(ip, ",")
if i > 0 {
return strings.TrimSpace(ip[:i])
42wim marked this conversation as resolved.
Show resolved Hide resolved
xffip := ip[:i]
xffip = strings.ReplaceAll(xffip, "[", "")
xffip = strings.ReplaceAll(xffip, "]", "")
return xffip
42wim marked this conversation as resolved.
Show resolved Hide resolved
}
return ip
}
Expand Down
24 changes: 24 additions & 0 deletions context_test.go
Expand Up @@ -904,6 +904,30 @@ func TestContext_RealIP(t *testing.T) {
},
"127.0.0.1",
},
{
&context{
request: &http.Request{
Header: http.Header{HeaderXForwardedFor: []string{"[2001:db8:85a3:8d3:1319:8a2e:370:7348], 2001:db8::1, "}},
},
},
"2001:db8:85a3:8d3:1319:8a2e:370:7348",
},
{
&context{
request: &http.Request{
Header: http.Header{HeaderXForwardedFor: []string{"[2001:db8:85a3:8d3:1319:8a2e:370:7348],[2001:db8::1]"}},
},
},
"2001:db8:85a3:8d3:1319:8a2e:370:7348",
},
{
&context{
request: &http.Request{
Header: http.Header{HeaderXForwardedFor: []string{"2001:db8:85a3:8d3:1319:8a2e:370:7348"}},
},
},
"2001:db8:85a3:8d3:1319:8a2e:370:7348",
},
{
&context{
request: &http.Request{
Expand Down
2 changes: 2 additions & 0 deletions ip.go
Expand Up @@ -248,6 +248,8 @@ func ExtractIPFromXFFHeader(options ...TrustOption) IPExtractor {
}
ips := append(strings.Split(strings.Join(xffs, ","), ","), directIP)
for i := len(ips) - 1; i >= 0; i-- {
ips[i] = strings.ReplaceAll(ips[i], "[", "")
42wim marked this conversation as resolved.
Show resolved Hide resolved
ips[i] = strings.ReplaceAll(ips[i], "]", "")
ip := net.ParseIP(strings.TrimSpace(ips[i]))
if ip == nil {
// Unable to parse IP; cannot trust entire records
Expand Down