From 14e819e09bad507b62244b0337dd87dd8b6d3620 Mon Sep 17 00:00:00 2001 From: minoplhy Date: Thu, 11 Apr 2024 20:27:57 +0700 Subject: [PATCH] fix: properly Set Real IP --- main.go | 10 ++++++++-- src/handler/net.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) create mode 100644 src/handler/net.go diff --git a/main.go b/main.go index 142e0f5..643261b 100644 --- a/main.go +++ b/main.go @@ -88,7 +88,10 @@ func uploadHandler(w http.ResponseWriter, r *http.Request) { UploadHeaders := map[string]string{ "X-Api-Key": API_Key, "Content-Type": "application/json", - "X-Real-IP": r.RemoteAddr, + } + + if handler.IsInternalIP(r.RemoteAddr) { + UploadHeaders["X-Real-IP"] = r.RemoteAddr } chibisafe_post, err := handler.UploadPost(Chibisafe_basepath, UploadHeaders, PostData) @@ -129,7 +132,10 @@ func uploadHandler(w http.ResponseWriter, r *http.Request) { ProcessHeaders := map[string]string{ "X-Api-Key": API_Key, "Content-Type": "application/json", - "X-Real-IP": r.RemoteAddr, + } + + if handler.IsInternalIP(r.RemoteAddr) { + ProcessHeaders["X-Real-IP"] = r.RemoteAddr } PostProcess, err := handler.UploadProcessPost(Chibisafe_basepath, ProcessHeaders, PostProcessData) diff --git a/src/handler/net.go b/src/handler/net.go new file mode 100644 index 0000000..8b051ac --- /dev/null +++ b/src/handler/net.go @@ -0,0 +1,30 @@ +package handler + +import "net" + +func IsInternalIP(ip string) bool { + // Parse the IP address + ipAddress := net.ParseIP(ip) + if ipAddress == nil { + return false + } + + internalRanges := []string{ + "10.0.0.0/8", + "172.16.0.0/12", + "192.168.0.0/16", + } + + for _, internalRange := range internalRanges { + _, ipNet, err := net.ParseCIDR(internalRange) + if err != nil { + return false + } + + if ipNet.Contains(ipAddress) { + return true + } + } + + return false +}