From d500716f29568c108f71d3f5bccc61aa96019549 Mon Sep 17 00:00:00 2001 From: Henrique Dias Date: Mon, 21 Oct 2024 08:01:37 +0200 Subject: [PATCH] fix: spoofing of X-Forwarded-For --- README.md | 5 +++++ lib/config.go | 1 + lib/handler.go | 25 ++++++++++++++----------- 3 files changed, 20 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 837d273..7e273ad 100644 --- a/README.md +++ b/README.md @@ -71,6 +71,11 @@ debug: false # Disable sniffing the files to detect their content type. Default is 'false'. noSniff: false +# Whether the server runs behind a trusted proxy or not. When this is true, +# the header X-Forwarded-For will be used for logging the remote addresses +# of logging attempts (if available). +behindProxy: false + # The directory that will be able to be accessed by the users when connecting. # This directory will be used by users unless they have their own 'directory' defined. # Default is '.' (current directory). diff --git a/lib/config.go b/lib/config.go index fdc444a..b605416 100644 --- a/lib/config.go +++ b/lib/config.go @@ -33,6 +33,7 @@ type Config struct { Prefix string NoSniff bool NoPassword bool + BehindProxy bool Log Log CORS CORS Users []User diff --git a/lib/handler.go b/lib/handler.go index 7915cf3..d671cd2 100644 --- a/lib/handler.go +++ b/lib/handler.go @@ -17,14 +17,16 @@ type handlerUser struct { } type Handler struct { - noPassword bool - user *handlerUser - users map[string]*handlerUser + noPassword bool + behindProxy bool + user *handlerUser + users map[string]*handlerUser } func NewHandler(c *Config) (http.Handler, error) { h := &Handler{ - noPassword: c.NoPassword, + noPassword: c.NoPassword, + behindProxy: c.BehindProxy, user: &handlerUser{ User: User{ UserPermissions: c.UserPermissions, @@ -85,7 +87,7 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`) // Retrieve the real client IP address using the updated helper function - remoteAddr := getRealRemoteIP(r) + remoteAddr := getRealRemoteIP(r, h.behindProxy) // Gets the correct user for this request. username, password, ok := r.BasicAuth() @@ -166,12 +168,13 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } // getRealRemoteIP retrieves the client's actual IP address, considering reverse proxies. -func getRealRemoteIP(r *http.Request) string { - ip := r.Header.Get("X-Forwarded-For") - if ip == "" { - ip = r.RemoteAddr - } - return ip +func getRealRemoteIP(r *http.Request, behindProxy bool) string { + if behindProxy { + if ip := r.Header.Get("X-Forwarded-For"); ip != "" { + return ip + } + } + return r.RemoteAddr } type responseWriterNoBody struct {