From d79ddc673188180199ad5b49464cc4f7e2953b4b Mon Sep 17 00:00:00 2001 From: jordi fita mas Date: Tue, 13 Jun 2023 14:21:54 +0200 Subject: [PATCH] Log the remote address, and only trust localhost proxies I need the actual remote address to add fail2ban rules for it, but i also to not want everyone to be able to fake X-Forward-For HTTP headers. Which can contain multiple ip addresses, by the way, so i have to get only the first one, as the others will be the proxies that the request has been (re)forwarded to. --- pkg/logger.go | 2 +- pkg/login.go | 18 ++++++++++++++---- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/pkg/logger.go b/pkg/logger.go index 618c120..d40b14a 100644 --- a/pkg/logger.go +++ b/pkg/logger.go @@ -44,7 +44,7 @@ func Logger(handler http.Handler) http.Handler { referer = "-" } log.Printf("HTTP - %s - - [%s] \"%s %s %s\" %d %d \"%s\" \"%s\" %s\n", - r.RemoteAddr, + remoteAddr(r), t.Format("02/Jan/2006:15:04:05 -0700"), r.Method, r.URL.Path, diff --git a/pkg/login.go b/pkg/login.go index 66ad121..658d85a 100644 --- a/pkg/login.go +++ b/pkg/login.go @@ -7,6 +7,7 @@ import ( "html/template" "net" "net/http" + "strings" "time" "golang.org/x/text/language" @@ -129,11 +130,20 @@ func HandleLogout(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { } func remoteAddr(r *http.Request) string { - address := r.Header.Get("X-Forwarded-For") - if address == "" { - address, _, _ = net.SplitHostPort(r.RemoteAddr) + address, _, _ := net.SplitHostPort(r.RemoteAddr) + if address != "localhost" && address != "127.0.0.1" && address != "::1" { + return address } - return address + forwarded := r.Header.Get("X-Forwarded-For") + if forwarded == "" { + return address + } + ips := strings.Split(forwarded, ", ") + forwarded = ips[0] + if forwarded == "" { + return address + } + return forwarded } func setSessionCookie(w http.ResponseWriter, cookie string) {