Skip to content

Commit

Permalink
pkg/web: X-Forwarded-For multi-IP handling (grafana#45098)
Browse files Browse the repository at this point in the history
It is conventionally common for the X-Forwarded-For header to contain a
comma-separated list of IP addresses, with each intermediate proxy
adding an additional item as a request passes through it. This change
makes the web framework handle this case appropriately, always selecting
the first item in the list.
  • Loading branch information
sdboyer committed Feb 8, 2022
1 parent 2cf421d commit 6a2255a
Showing 1 changed file with 10 additions and 6 deletions.
16 changes: 10 additions & 6 deletions pkg/web/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,13 +77,17 @@ func (ctx *Context) run() {
// RemoteAddr returns more real IP address.
func (ctx *Context) RemoteAddr() string {
addr := ctx.Req.Header.Get("X-Real-IP")

if len(addr) == 0 {
// X-Forwarded-For may contain multiple IP addresses, separated by
// commas.
addr = strings.TrimSpace(strings.Split(ctx.Req.Header.Get("X-Forwarded-For"), ",")[0])
}

if len(addr) == 0 {
addr = ctx.Req.Header.Get("X-Forwarded-For")
if addr == "" {
addr = ctx.Req.RemoteAddr
if i := strings.LastIndex(addr, ":"); i > -1 {
addr = addr[:i]
}
addr = ctx.Req.RemoteAddr
if i := strings.LastIndex(addr, ":"); i > -1 {
addr = addr[:i]
}
}
return addr
Expand Down

0 comments on commit 6a2255a

Please sign in to comment.