From 82c32c21f4a10fb4485e561e51a921199ea0b576 Mon Sep 17 00:00:00 2001 From: fiatjaf Date: Thu, 26 Sep 2024 07:30:24 -0300 Subject: [PATCH] we were using conflicting IP addresses from different sources. fix this. --- block.go | 8 +------- http_logging.go | 2 +- ip.go | 16 ++++++++++++++++ 3 files changed, 18 insertions(+), 8 deletions(-) create mode 100644 ip.go diff --git a/block.go b/block.go index ca12646..a2119cf 100644 --- a/block.go +++ b/block.go @@ -1,7 +1,6 @@ package main import ( - "fmt" "io" "net" "net/http" @@ -25,20 +24,15 @@ func agentBlock(next http.Handler) http.Handler { func cloudflareBlock(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - ip := net.ParseIP(r.Header.Get("CF-Connecting-IP")) - fmt.Println("should blopccccccccccc?", ip) + ip := net.ParseIP(actualIP(r)) if ip != nil { - fmt.Println(" !") for _, ipnet := range cloudflareRanges { - fmt.Println(" range", ipnet) if ipnet.Contains(ip) { - fmt.Println(" match") // cloudflare is not allowed log.Debug().Stringer("ip", ip).Msg("cloudflare (attacker) ip blocked") http.Redirect(w, r, "https://njump.me/", 302) return } - fmt.Println(" no match") } } diff --git a/http_logging.go b/http_logging.go index 0ff38f1..ae09ff4 100644 --- a/http_logging.go +++ b/http_logging.go @@ -9,7 +9,7 @@ func loggingMiddleware(next http.Handler) http.Handler { path += "?" + r.URL.RawQuery } log.Debug(). - Str("ip", r.Header.Get("X-Forwarded-For")). + Str("ip", actualIP(r)). Str("path", path). Str("user-agent", r.Header.Get("User-Agent")). Str("referer", r.Header.Get("Referer")). diff --git a/ip.go b/ip.go new file mode 100644 index 0000000..2981ba5 --- /dev/null +++ b/ip.go @@ -0,0 +1,16 @@ +package main + +import ( + "net/http" + "strings" +) + +func actualIP(r *http.Request) string { + if cf := r.Header.Get("CF-Connecting-IP"); cf != "" { + return cf + } else if xff := r.Header.Get("X-Forwarded-For"); xff != "" { + return strings.Split(xff, ",")[0] + } else { + return r.RemoteAddr + } +}