From 54a18169d71eb7f4a58034af313045a6affbbcc5 Mon Sep 17 00:00:00 2001 From: Toby Chui Date: Thu, 16 Oct 2025 20:13:33 +0800 Subject: [PATCH] Added untrust ip get in netutils --- src/accesslist.go | 5 +++-- src/mod/netutils/ipmatch.go | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/accesslist.go b/src/accesslist.go index 46a4861..525da35 100644 --- a/src/accesslist.go +++ b/src/accesslist.go @@ -210,9 +210,10 @@ func handleListBlacklisted(w http.ResponseWriter, r *http.Request) { } resulst := []string{} - if bltype == "country" { + switch bltype { + case "country": resulst = rule.GetAllBlacklistedCountryCode() - } else if bltype == "ip" { + case "ip": resulst = rule.GetAllBlacklistedIp() } diff --git a/src/mod/netutils/ipmatch.go b/src/mod/netutils/ipmatch.go index a0c65a1..5df5595 100644 --- a/src/mod/netutils/ipmatch.go +++ b/src/mod/netutils/ipmatch.go @@ -13,6 +13,25 @@ import ( CIDR and IPv4 / v6 validations */ +// Get the requester IP without trusting any proxy headers +func GetRequesterIPUntrusted(r *http.Request) string { + // If the request is from an untrusted IP, we should not trust the X-Real-IP and X-Forwarded-For headers + ip := r.RemoteAddr + // Trim away the port number + reqHost, _, err := net.SplitHostPort(ip) + if err == nil { + ip = reqHost + } + + // Check if the IP is a valid IPv4 or IPv6 address + parsedIP := net.ParseIP(ip) + if parsedIP == nil { + return "" + } + return ip +} + +// Get the requester IP, trust the X-Real-IP and X-Forwarded-For headers func GetRequesterIP(r *http.Request) string { ip := r.Header.Get("X-Real-Ip") if ip == "" {