refactor: improve error interceptor

This commit is contained in:
Jonas Kaninda
2024-11-14 00:26:21 +01:00
parent 328703ad79
commit 42abf56473
15 changed files with 284 additions and 185 deletions

View File

@@ -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
}
}