From 4806851ae3bd301899b694f491e9052cfaa01210 Mon Sep 17 00:00:00 2001 From: "Grot (@grafanabot)" <43478413+grafanabot@users.noreply.github.com> Date: Tue, 8 Feb 2022 20:57:43 +0100 Subject: [PATCH] pkg/web: X-Forwarded-For multi-IP handling (#45098) (#45103) 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. (cherry picked from commit 6a2255abe7bd0abf62e70495745b28c9111ee307) Co-authored-by: sam boyer --- pkg/macaron/context.go | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/pkg/macaron/context.go b/pkg/macaron/context.go index 309c882f53c..1275bc0742d 100644 --- a/pkg/macaron/context.go +++ b/pkg/macaron/context.go @@ -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 { - addr = ctx.Req.Header.Get("X-Forwarded-For") - if addr == "" { - addr = ctx.Req.RemoteAddr - if i := strings.LastIndex(addr, ":"); i > -1 { - addr = addr[:i] - } + // 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.RemoteAddr + if i := strings.LastIndex(addr, ":"); i > -1 { + addr = addr[:i] } } return addr