// Package wafgw runs the request inspection gateway that sits between nginx // and a site's origin. nginx keeps TLS, L1 signature rules and rate limiting; // the gateway adds the part nginx cannot do without Lua/ModSecurity: decoding // and inspecting the query string, headers, cookies and request body of every // request before it reaches the application. package wafgw import ( "bytes" "compress/gzip" "compress/zlib" "context" "crypto/tls" "encoding/json" "fmt" "io" "log/slog" "net" "net/http" "net/http/httputil" "net/url" "regexp" "strconv" "strings" "sync" "sync/atomic" "time" "github.com/miaopanel/miaopanel/internal/config" "github.com/miaopanel/miaopanel/internal/store" "github.com/miaopanel/miaopanel/internal/waf" "github.com/miaopanel/miaopanel/internal/wafengine" ) const ( // maxBufferedBody is the largest body the gateway buffers for inspection. // Larger uploads are streamed after the first bytes were checked. maxBufferedBody = 2 << 20 eventQueueSize = 2048 // Each buffered request can hold up to maxBufferedBody while it is being // decoded and inspected. Bound the number of concurrent body buffers so a // burst of uploads cannot multiply this allocation. maxConcurrentInspections = 16 ) // Policy is an immutable snapshot of the WAF settings used per request. type Policy struct { Enabled bool Strict bool Threshold int BlockStatus int Rate int Burst int Whitelist []string Custom []wafengine.CustomRule // Origins maps a site slug to its registered loopback origin. nginx sends // X-MP-Origin, but that header must never decide where the gateway // connects: trusting it turned the listener into a proxy for any internal // address reachable from the panel. Origins map[string]string } // Service owns the gateway listener and the policy refresh loop. type Service struct { cfg *config.Config db *store.Store waf *waf.Service log *slog.Logger addr string policy atomic.Pointer[Policy] policyAt atomic.Int64 started atomic.Bool dropEvents atomic.Int64 events chan store.WAFEvent stop chan struct{} once sync.Once limiter *rateLimiter inspectSlots chan struct{} proxy *httputil.ReverseProxy serve *http.Server } type ctxKey int const ctxTarget ctxKey = iota // New builds a gateway bound to the panel services. func New(cfg *config.Config, db *store.Store, wafSvc *waf.Service, log *slog.Logger) *Service { s := &Service{ cfg: cfg, db: db, waf: wafSvc, log: log, addr: cfg.WAFGatewayAddr, events: make(chan store.WAFEvent, eventQueueSize), stop: make(chan struct{}), limiter: newRateLimiter(), inspectSlots: make(chan struct{}, maxConcurrentInspections), } if s.addr == "" { s.addr = "127.0.0.1:8899" } transport := &http.Transport{ // Loopback traffic must never be routed through an environment proxy. Proxy: nil, DialContext: (&net.Dialer{Timeout: 10 * time.Second, KeepAlive: 30 * time.Second}).DialContext, MaxIdleConns: 512, MaxIdleConnsPerHost: 128, IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: time.Second, ResponseHeaderTimeout: 300 * time.Second, // Match nginx's default proxy_ssl_verify off for application upstreams. TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } s.proxy = &httputil.ReverseProxy{ Rewrite: func(pr *httputil.ProxyRequest) { if target, ok := pr.In.Context().Value(ctxTarget).(*url.URL); ok && target != nil { pr.SetURL(target) } pr.Out.Host = pr.In.Host pr.SetXForwarded() pr.Out.Header.Del("X-MP-Site") pr.Out.Header.Del("X-MP-Origin") pr.Out.Header.Del("X-MP-Upstream") pr.Out.Header.Del("X-MP-Real-IP") }, Transport: transport, FlushInterval: 100 * time.Millisecond, ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) { s.log.Warn("waf gateway upstream error", "path", r.URL.Path, "error", err) writeJSON(w, http.StatusBadGateway, map[string]any{ "code": 502, "msg": "上游服务不可用", }) }, } s.serve = &http.Server{ Addr: s.addr, Handler: s, ReadHeaderTimeout: 10 * time.Second, IdleTimeout: 90 * time.Second, MaxHeaderBytes: 1 << 20, } return s } // Start begins listening and refreshing the policy. It returns an error when // the loopback address cannot be bound so the panel can report it. func (s *Service) Start(ctx context.Context) error { ln, err := net.Listen("tcp", s.addr) if err != nil { return fmt.Errorf("WAF 网关监听 %s 失败: %w", s.addr, err) } s.started.Store(true) if err := s.Reload(ctx); err != nil { s.log.Warn("WAF 网关策略加载失败", "error", err) } go s.refresh(ctx) go s.eventLoop(ctx) go func() { if err := s.serve.Serve(ln); err != nil && err != http.ErrServerClosed { s.log.Error("WAF 网关退出", "error", err) s.started.Store(false) } }() s.log.Info("WAF 网关已启动", "addr", s.addr) return nil } // Close stops the listener and the background workers. func (s *Service) Close() { s.once.Do(func() { close(s.stop) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() _ = s.serve.Shutdown(ctx) s.started.Store(false) }) } // Ready reports whether the listener is running. func (s *Service) Ready() bool { return s.started.Load() } // Addr returns the loopback address the gateway listens on. func (s *Service) Addr() string { return s.addr } // Reload rebuilds the policy snapshot from SQLite. func (s *Service) Reload(ctx context.Context) error { st, err := s.waf.Settings(ctx) if err != nil { return err } rules, err := s.db.WAFRules(ctx) if err != nil { return err } p := &Policy{ Enabled: st.Gateway, Strict: st.GatewayStrict, Threshold: st.GatewayThreshold, BlockStatus: st.BlockStatus, Rate: st.Rate, Burst: st.Burst, Whitelist: st.Whitelist, Origins: map[string]string{}, } if sites, err := s.db.ListSites(ctx); err == nil { for _, site := range sites { if site.Options.GatewayPort > 0 { p.Origins[site.Slug] = fmt.Sprintf("127.0.0.1:%d", site.Options.GatewayPort) } } } for _, rule := range rules { if !rule.Enabled || rule.Action != "block" { continue } p.Custom = append(p.Custom, wafengine.CustomRule{ Name: rule.Name, MatchOn: rule.MatchOn, Op: rule.Op, Pattern: rule.Pattern, Enabled: true, }) } s.policy.Store(p) s.policyAt.Store(time.Now().Unix()) return nil } func (s *Service) refresh(ctx context.Context) { ticker := time.NewTicker(2 * time.Second) defer ticker.Stop() for { select { case <-ctx.Done(): return case <-s.stop: return case <-ticker.C: reloadCtx, cancel := context.WithTimeout(ctx, 3*time.Second) _ = s.Reload(reloadCtx) cancel() } } } func (s *Service) eventLoop(ctx context.Context) { for { select { case <-ctx.Done(): return case <-s.stop: return case ev := <-s.events: addCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second) if err := s.db.WAFEventAdd(addCtx, &ev); err != nil { s.log.Debug("waf gateway event", "error", err) } cancel() } } } func (s *Service) enqueue(ev store.WAFEvent) { select { case s.events <- ev: default: s.dropEvents.Add(1) } } // ServeHTTP implements the inspection and forwarding pipeline. func (s *Service) ServeHTTP(w http.ResponseWriter, r *http.Request) { if !isLoopback(r.RemoteAddr) { http.Error(w, "forbidden", http.StatusForbidden) return } // Health is only reachable directly; nginx always sets X-MP-Site, so an // external request for this path is forwarded to the site like any other. if r.URL.Path == "/__mp_waf/health" && r.Header.Get("X-MP-Site") == "" { s.health(w) return } slug := strings.TrimSpace(r.Header.Get("X-MP-Site")) if slug == "" { writeJSON(w, http.StatusBadRequest, map[string]any{"code": 400, "msg": "缺少站点标识"}) return } pol := s.policy.Load() target, err := targetFor(r, pol, slug) if err != nil { writeJSON(w, http.StatusBadGateway, map[string]any{"code": 502, "msg": err.Error()}) return } ip := clientIP(r) if pol == nil || !pol.Enabled { s.forward(w, r, target) return } if isStaticPath(r.URL.Path) { // Static assets are not rate limited and normally do not need body // inspection, but the query string is still checked by the engine. } else if !ipWhitelisted(pol.Whitelist, ip) && !s.limiter.allow(ip+"|"+slug, pol.Rate, pol.Burst) { s.block(w, r, pol, ip, slug, 429, wafengine.Result{ Score: 0, Hits: []wafengine.Hit{{Module: "cc", Rule: "rate_limit", Score: 0, Location: "remote", Evidence: ip}}, }, "请求过于频繁") return } // Only requests with a body need the expensive buffer/decode path. The // semaphore applies backpressure instead of letting concurrent uploads // reserve an unbounded amount of memory. hasBody := r.Body != nil && r.Method != http.MethodGet && r.Method != http.MethodHead && r.ContentLength != 0 // A form or JSON body larger than the inspection window can hide its // payload behind filler bytes, which used to pass untouched. Legitimate // requests of that shape are rare, so treat them as an attack surface // instead of forwarding unscanned bytes. Multipart uploads keep streaming. if hasBody && r.ContentLength > int64(wafengine.MaxBodyScan) { ct := strings.ToLower(r.Header.Get("Content-Type")) if strings.Contains(ct, "application/x-www-form-urlencoded") || strings.Contains(ct, "application/json") { s.block(w, r, pol, ip, slug, http.StatusRequestEntityTooLarge, wafengine.Result{ Hits: []wafengine.Hit{{Module: "body", Rule: "oversized_body", Location: "body", Evidence: "body exceeds inspection limit"}}, }, "请求体超过检测上限") return } } releaseInspect := func() {} if hasBody { select { case s.inspectSlots <- struct{}{}: released := false releaseInspect = func() { if !released { released = true <-s.inspectSlots } } defer releaseInspect() case <-r.Context().Done(): return } } body, truncated, err := bufferBody(r) if err != nil { writeJSON(w, http.StatusBadRequest, map[string]any{"code": 400, "msg": "读取请求体失败"}) return } inspectBody := decodeContent(body, r.Header.Get("Content-Encoding")) req := &wafengine.Request{ Method: r.Method, Path: r.URL.Path, RawQuery: r.URL.RawQuery, ContentType: r.Header.Get("Content-Type"), RemoteIP: ip, Header: r.Header, Cookies: cookieMap(r), Body: inspectBody, } if truncated { if len(req.Body) > wafengine.MaxBodyScan { req.Body = req.Body[:wafengine.MaxBodyScan] } } res := wafengine.Inspect(req, wafengine.Config{ Strict: pol.Strict, Threshold: pol.Threshold, Whitelist: pol.Whitelist, Custom: pol.Custom, }) // Inspection is done; do not hold a slot while the origin streams a long // upload or response. releaseInspect() if res.Blocked { s.block(w, r, pol, ip, slug, pol.BlockStatus, res, "") return } s.forward(w, r, target) } func (s *Service) block(w http.ResponseWriter, r *http.Request, pol *Policy, ip, slug string, status int, res wafengine.Result, reason string) { rule, detail := summarize(res) if reason == "" { reason = "请求包含恶意特征" } ev := store.WAFEvent{ TS: time.Now().Unix(), Site: slug, IP: ip, Method: r.Method, URI: truncate(r.URL.RequestURI(), 500), UA: truncate(r.UserAgent(), 300), Status: status, Rule: rule, Module: moduleOf(res), Score: res.Score, Detail: detail, } if s.started.Load() { s.enqueue(ev) } else { // Direct handler use (tests, or a failed listener) still records. _ = s.db.WAFEventAdd(context.Background(), &ev) } w.Header().Set("X-MP-WAF", "blocked") w.Header().Set("Cache-Control", "no-store") if wantsJSON(r) { writeJSON(w, status, map[string]any{ "code": status, "msg": reason, "data": map[string]any{"request_id": ev.TS, "rule": rule, "score": res.Score}, }) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") w.WriteHeader(status) _, _ = fmt.Fprintf(w, blockPage, status, rule, res.Score) } func (s *Service) forward(w http.ResponseWriter, r *http.Request, target *url.URL) { ctx := context.WithValue(r.Context(), ctxTarget, target) s.proxy.ServeHTTP(w, r.WithContext(ctx)) } func (s *Service) health(w http.ResponseWriter) { age := int64(0) if at := s.policyAt.Load(); at > 0 { age = time.Now().Unix() - at } writeJSON(w, http.StatusOK, map[string]any{ "ok": true, "addr": s.addr, "ready": s.started.Load(), "policy_age": age, "dropped_events": s.dropEvents.Load(), }) } func targetFor(r *http.Request, pol *Policy, slug string) (*url.URL, error) { // The registered origin always wins: nginx sets the header from the site // row, and nothing derived from a request header may choose the target. // Previously any local process could point X-MP-Origin at an arbitrary // internal host and use the gateway as a proxy. if pol != nil { if origin := pol.Origins[slug]; origin != "" { return &url.URL{Scheme: "http", Host: origin}, nil } } if origin := strings.TrimSpace(r.Header.Get("X-MP-Origin")); origin != "" { if !loopbackAuthority(origin) { return nil, fmt.Errorf("origin 必须是本机回环地址") } return &url.URL{Scheme: "http", Host: origin}, nil } upstream := strings.TrimSpace(r.Header.Get("X-MP-Upstream")) if upstream == "" { return nil, fmt.Errorf("缺少上游地址") } u, err := url.Parse(upstream) if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" { return nil, fmt.Errorf("上游地址不合法") } if !loopbackAuthority(u.Host) { return nil, fmt.Errorf("上游地址必须是本机回环地址") } return u, nil } // loopbackAuthority accepts "127.0.0.1:8080" and "[::1]:8080". func loopbackAuthority(a string) bool { host, port, err := net.SplitHostPort(a) if err != nil || port == "" { return false } if _, err := strconv.Atoi(port); err != nil { return false } ip := net.ParseIP(host) return ip != nil && ip.IsLoopback() } // ipWhitelisted mirrors the nginx level exemption for the CC limiter: an // operator who trusted an address must not be throttled by the gateway. func ipWhitelisted(list []string, ip string) bool { addr := net.ParseIP(strings.TrimSpace(ip)) if addr == nil { return false } for _, item := range list { item = strings.TrimSpace(item) if item == "" { continue } if strings.Contains(item, "/") { if _, block, err := net.ParseCIDR(item); err == nil && block.Contains(addr) { return true } continue } if v := net.ParseIP(item); v != nil && v.Equal(addr) { return true } } return false } func bufferBody(r *http.Request) ([]byte, bool, error) { if r.Body == nil || r.Method == http.MethodGet || r.Method == http.MethodHead { return nil, false, nil } if r.ContentLength > maxBufferedBody { // Read the head for a cheap inspection, then let the proxy stream the // rest without buffering a large upload in memory. Compressed bodies // need a larger head because the payload only appears after inflation. limit := int64(wafengine.MaxBodyScan) if compressedEncoding(r.Header.Get("Content-Encoding")) { limit = maxBufferedBody } head, err := io.ReadAll(io.LimitReader(r.Body, limit)) if err != nil { return nil, false, err } r.Body = io.NopCloser(io.MultiReader(bytes.NewReader(head), r.Body)) return head, true, nil } orig := r.Body buf, err := io.ReadAll(io.LimitReader(orig, maxBufferedBody+1)) if err != nil { return nil, false, err } if len(buf) > maxBufferedBody { r.Body = io.NopCloser(io.MultiReader(bytes.NewReader(buf), orig)) return buf[:wafengine.MaxBodyScan], true, nil } r.Body = io.NopCloser(bytes.NewReader(buf)) return buf, false, nil } func compressedEncoding(encoding string) bool { enc := strings.ToLower(strings.TrimSpace(encoding)) if i := strings.IndexByte(enc, ','); i >= 0 { enc = strings.TrimSpace(enc[:i]) } return enc == "gzip" || enc == "deflate" } // decodeContent returns a plaintext copy for inspection. The original body is // still forwarded unchanged, so applications that accept gzip keep working. func decodeContent(body []byte, encoding string) []byte { if len(body) == 0 { return body } enc := strings.ToLower(strings.TrimSpace(encoding)) if i := strings.IndexByte(enc, ','); i >= 0 { enc = strings.TrimSpace(enc[:i]) } var reader io.Reader switch enc { case "gzip": zr, err := gzip.NewReader(bytes.NewReader(body)) if err != nil { return body } defer zr.Close() reader = zr case "deflate": zr, err := zlib.NewReader(bytes.NewReader(body)) if err != nil { return body } defer zr.Close() reader = zr default: return body } out, err := io.ReadAll(io.LimitReader(reader, maxBufferedBody)) if err != nil || len(out) == 0 { return body } return out } func summarize(res wafengine.Result) (string, string) { if len(res.Hits) == 0 { return "unknown", "" } parts := make([]string, 0, 3) for i, h := range res.Hits { if i >= 3 { break } parts = append(parts, fmt.Sprintf("%s/%s(%d) %s", h.Module, h.Rule, h.Score, h.Evidence)) } first := res.Hits[0] return first.Module + "/" + first.Rule, truncate(strings.Join(parts, " | "), 500) } func moduleOf(res wafengine.Result) string { if len(res.Hits) == 0 { return "" } return res.Hits[0].Module } var reStatic = regexp.MustCompile(`(?i)\.(css|js|mjs|map|png|jpe?g|gif|svg|webp|ico|woff2?|ttf|otf|eot|mp4|webm|mp3|pdf|txt|xml|json)$`) func isStaticPath(p string) bool { return reStatic.MatchString(p) } func isLoopback(remote string) bool { host, _, err := net.SplitHostPort(remote) if err != nil { host = remote } ip := net.ParseIP(host) return ip != nil && ip.IsLoopback() } func clientIP(r *http.Request) string { if v := strings.TrimSpace(r.Header.Get("X-Real-IP")); v != "" { if ip := net.ParseIP(v); ip != nil { return ip.String() } } host, _, err := net.SplitHostPort(r.RemoteAddr) if err != nil { return r.RemoteAddr } return host } func cookieMap(r *http.Request) map[string]string { out := map[string]string{} for _, c := range r.Cookies() { out[c.Name] = c.Value } return out } func wantsJSON(r *http.Request) bool { return strings.Contains(r.Header.Get("Accept"), "application/json") || strings.EqualFold(r.Header.Get("X-Requested-With"), "XMLHttpRequest") } func writeJSON(w http.ResponseWriter, status int, v any) { w.Header().Set("Content-Type", "application/json; charset=utf-8") w.Header().Set("Cache-Control", "no-store") w.WriteHeader(status) _ = json.NewEncoder(w).Encode(v) } func truncate(s string, n int) string { if len(s) <= n { return s } return s[:n] } const blockPage = ` 请求被拦截

请求被 WAF 拦截

状态码 %d · 规则 %s · 评分 %d

如果这是正常业务请求,请联系站点管理员。

` // --- token bucket ---------------------------------------------------------- type bucket struct { tokens float64 last time.Time } type rateLimiter struct { mu sync.Mutex buckets map[string]*bucket lastGC time.Time } func newRateLimiter() *rateLimiter { return &rateLimiter{buckets: map[string]*bucket{}, lastGC: time.Now()} } func (l *rateLimiter) allow(key string, rate, burst int) bool { if rate <= 0 { rate = 50 } if burst <= 0 { burst = 200 } now := time.Now() l.mu.Lock() defer l.mu.Unlock() b := l.buckets[key] if b == nil { b = &bucket{tokens: float64(burst), last: now} l.buckets[key] = b } b.tokens += now.Sub(b.last).Seconds() * float64(rate) if b.tokens > float64(burst) { b.tokens = float64(burst) } b.last = now if now.Sub(l.lastGC) > 10*time.Minute { for k, v := range l.buckets { if now.Sub(v.last) > 10*time.Minute { delete(l.buckets, k) } } l.lastGC = now } if b.tokens < 1 { return false } b.tokens-- return true }