diff --git a/internal/api/handlers.go b/internal/api/handlers.go index 95c2ca2..b99031d 100644 --- a/internal/api/handlers.go +++ b/internal/api/handlers.go @@ -130,14 +130,34 @@ var ForbiddenPatterns = []string{ "etc/passwd", "cgi-bin", } +func GetRealIP(r *http.Request) string { + ip, _, err := net.SplitHostPort(r.RemoteAddr) + if err != nil { + ip = r.RemoteAddr + } + + if xff := r.Header.Get("X-Forwarded-For"); xff != "" { + if comma := strings.IndexByte(xff, ','); comma != -1 { + return strings.TrimSpace(xff[:comma]) + } + return strings.TrimSpace(xff) + } + + if xri := r.Header.Get("X-Real-IP"); xri != "" { + return strings.TrimSpace(xri) + } + + return ip +} + func BotBlockerMiddleware(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { path := strings.ToLower(r.URL.Path) - query := strings.ToLower(r.URL.RawQuery) for _, pattern := range ForbiddenPatterns { - if strings.Contains(path, pattern) || strings.Contains(query, pattern) { - log.Printf("Blocked suspicious request: %s from %s", r.URL.String(), r.RemoteAddr) + if strings.Contains(path, pattern) { + ip := GetRealIP(r) + log.Printf("Blocked suspicious request: %s from %s", r.URL.String(), ip) http.Error(w, "Forbidden", http.StatusForbidden) return } @@ -276,18 +296,7 @@ func AuthMiddleware(am *AuthManager, next http.HandlerFunc) http.HandlerFunc { func LimitMiddleware(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - ip, _, err := net.SplitHostPort(r.RemoteAddr) - if err != nil { - ip = r.RemoteAddr - } - - if xff := r.Header.Get("X-Forwarded-For"); xff != "" { - if comma := strings.IndexByte(xff, ','); comma != -1 { - ip = xff[:comma] - } else { - ip = xff - } - } + ip := GetRealIP(r) ua := r.Header.Get("User-Agent") hash := sha256.New()