88 lines
2.3 KiB
Go
88 lines
2.3 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"sync/atomic"
|
|
|
|
"zoraxy-firewall/zoraxy_plugin"
|
|
)
|
|
|
|
var breaker = newCircuitBreaker()
|
|
|
|
// Metrics counters
|
|
var (
|
|
requestsTotal uint64
|
|
requestsAllowed uint64
|
|
requestsBlocked uint64
|
|
requestsBypassed uint64 // fail-open or disabled
|
|
)
|
|
|
|
func metricsSnapshot() map[string]interface{} {
|
|
return map[string]interface{}{
|
|
"total": atomic.LoadUint64(&requestsTotal),
|
|
"allowed": atomic.LoadUint64(&requestsAllowed),
|
|
"blocked": atomic.LoadUint64(&requestsBlocked),
|
|
"bypassed": atomic.LoadUint64(&requestsBypassed),
|
|
"circuit": circuitStateStr(breaker.State()),
|
|
"enabled": getConfig().Enabled,
|
|
}
|
|
}
|
|
|
|
func circuitStateStr(s CircuitState) string {
|
|
switch s {
|
|
case StateClosed:
|
|
return "closed"
|
|
case StateOpen:
|
|
return "open"
|
|
case StateHalfOpen:
|
|
return "half-open"
|
|
}
|
|
return "unknown"
|
|
}
|
|
|
|
// handleInspect is the static capture ingress handler.
|
|
// Zoraxy proxies matching requests here. The plugin decides:
|
|
// - Return 280 (CAPTURED) → block the request
|
|
// - Return 284 (UNHANDLED) → forward as normal
|
|
func handleInspect(w http.ResponseWriter, r *http.Request) {
|
|
atomic.AddUint64(&requestsTotal, 1)
|
|
cfg := getConfig()
|
|
if !cfg.Enabled {
|
|
atomic.AddUint64(&requestsBypassed, 1)
|
|
w.WriteHeader(int(zoraxy_plugin.ControlStatusCode_UNHANDLED))
|
|
return
|
|
}
|
|
|
|
state := breaker.State()
|
|
if state == StateOpen {
|
|
atomic.AddUint64(&requestsBypassed, 1)
|
|
log.Printf("WAF: breaker OPEN — fail-open, passing %s %s", r.Method, r.URL.Path)
|
|
w.WriteHeader(int(zoraxy_plugin.ControlStatusCode_UNHANDLED))
|
|
return
|
|
}
|
|
|
|
resp, err := inspect(r)
|
|
if err != nil {
|
|
atomic.AddUint64(&requestsBypassed, 1)
|
|
log.Printf("WAF: inspection error: %v", err)
|
|
breaker.RecordFailure()
|
|
w.WriteHeader(int(zoraxy_plugin.ControlStatusCode_UNHANDLED))
|
|
return
|
|
}
|
|
|
|
breaker.RecordSuccess()
|
|
|
|
if resp.Verdict == "block" {
|
|
atomic.AddUint64(&requestsBlocked, 1)
|
|
log.Printf("WAF: BLOCKED %s %s — reason: %s", r.Method, r.URL.Path, resp.Reason)
|
|
w.Header().Set("Content-Type", "text/html")
|
|
w.WriteHeader(int(zoraxy_plugin.ControlStatusCode_CAPTURED))
|
|
fmt.Fprintf(w, `<html><body><h1>403 Forbidden</h1><p>Request blocked by WAF.</p></body></html>`)
|
|
return
|
|
}
|
|
|
|
atomic.AddUint64(&requestsAllowed, 1)
|
|
w.WriteHeader(int(zoraxy_plugin.ControlStatusCode_UNHANDLED))
|
|
}
|