@@ -48,17 +48,11 @@ func (m Defender) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyht
4848 if m .serveGitignore (w , r ) {
4949 return nil
5050 }
51- // Split the RemoteAddr into IP and port
52- host , _ , err := net .SplitHostPort (r .RemoteAddr )
53- if err != nil {
54- m .log .Error ("Invalid client IP format" , zap .String ("ip" , r .RemoteAddr ))
55- return caddyhttp .Error (http .StatusForbidden , fmt .Errorf ("invalid client IP format" ))
56- }
5751
58- clientIP := net . ParseIP ( host )
59- if clientIP = = nil {
60- m .log .Error ("Invalid client IP" , zap .String ("ip " , host ))
61- return caddyhttp .Error (http .StatusForbidden , fmt . Errorf ( "invalid client IP" ) )
52+ clientIP , err := clientIPFromRequest ( r )
53+ if err ! = nil {
54+ m .log .Error ("Invalid client IP" , zap .String ("remote_addr " , r . RemoteAddr ), zap . Error ( err ))
55+ return caddyhttp .Error (http .StatusForbidden , err )
6256 }
6357 m .log .Debug ("Ranges" , zap .Strings ("ranges" , m .Ranges ))
6458
@@ -72,3 +66,23 @@ func (m Defender) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyht
7266 // Request should be blocked
7367 return m .responder .ServeHTTP (w , r , next )
7468}
69+
70+ func clientIPFromRequest (r * http.Request ) (net.IP , error ) {
71+ if clientIP , ok := caddyhttp .GetVar (r .Context (), caddyhttp .ClientIPVarKey ).(string ); ok && clientIP != "" {
72+ return parseClientIP (clientIP )
73+ }
74+
75+ host , _ , err := net .SplitHostPort (r .RemoteAddr )
76+ if err != nil {
77+ return nil , fmt .Errorf ("invalid client IP format" )
78+ }
79+ return parseClientIP (host )
80+ }
81+
82+ func parseClientIP (rawIP string ) (net.IP , error ) {
83+ clientIP := net .ParseIP (rawIP )
84+ if clientIP == nil {
85+ return nil , fmt .Errorf ("invalid client IP" )
86+ }
87+ return clientIP , nil
88+ }
0 commit comments