refactor: improve error interceptor
This commit is contained in:
@@ -18,15 +18,19 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
errorinterceptor "github.com/jkaninda/goma-gateway/pkg/error-interceptor"
|
||||
"github.com/jkaninda/goma-gateway/pkg/logger"
|
||||
"net/http"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
type BlockCommon struct {
|
||||
ErrorInterceptor errorinterceptor.ErrorInterceptor
|
||||
}
|
||||
|
||||
// BlockExploitsMiddleware Middleware to block common exploits
|
||||
func BlockExploitsMiddleware(next http.Handler) http.Handler {
|
||||
func (blockCommon BlockCommon) BlockExploitsMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Patterns to detect SQL injection attempts
|
||||
sqlInjectionPattern := regexp.MustCompile(sqlPatterns)
|
||||
@@ -42,36 +46,18 @@ func BlockExploitsMiddleware(next http.Handler) http.Handler {
|
||||
pathTraversalPattern.MatchString(r.URL.Path) ||
|
||||
xssPattern.MatchString(r.URL.RawQuery) {
|
||||
logger.Error("%s: %s Forbidden - Potential exploit detected", getRealIP(r), r.URL.Path)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
err := json.NewEncoder(w).Encode(ProxyResponseError{
|
||||
Success: false,
|
||||
Code: http.StatusForbidden,
|
||||
Message: fmt.Sprintf("Forbidden - Potential exploit detected"),
|
||||
})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
RespondWithError(w, http.StatusForbidden, fmt.Sprintf("%d Forbidden - Potential exploit detected", http.StatusForbidden), blockCommon.ErrorInterceptor)
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
// Check form data (for POST requests)
|
||||
if r.Method == http.MethodPost {
|
||||
if err := r.ParseForm(); err == nil {
|
||||
for _, values := range r.Form {
|
||||
for _, value := range values {
|
||||
if sqlInjectionPattern.MatchString(value) || xssPattern.MatchString(value) {
|
||||
logger.Error("%s: %s Forbidden - Potential exploit detected", getRealIP(r), r.URL.Path)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
err := json.NewEncoder(w).Encode(ProxyResponseError{
|
||||
Success: false,
|
||||
Code: http.StatusForbidden,
|
||||
Message: fmt.Sprintf("Forbidden - Potential exploit detected"),
|
||||
})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
logger.Error("%s: %s %s Forbidden - Potential exploit detected", getRealIP(r), r.Method, r.URL.Path)
|
||||
RespondWithError(w, http.StatusForbidden, fmt.Sprintf("%d Forbidden - Potential exploit detected", http.StatusForbidden), blockCommon.ErrorInterceptor)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user