// Package waf implements the standalone layer-1 WAF module: settings, custom // rules, nginx rendering and log based metrics. package waf import ( "context" "errors" "fmt" "net" "os" "regexp" "strconv" "strings" "sync" "sync/atomic" "github.com/miaopanel/miaopanel/internal/config" "github.com/miaopanel/miaopanel/internal/site" "github.com/miaopanel/miaopanel/internal/store" "github.com/miaopanel/miaopanel/internal/system" "github.com/miaopanel/miaopanel/internal/webserver" ) // Settings is the operator facing configuration. type Settings struct { Enabled bool `json:"enabled"` BlockStatus int `json:"block_status"` Rate int `json:"rate"` Burst int `json:"burst"` ConnPerIP int `json:"conn_per_ip"` BadUA bool `json:"bad_ua"` BadUAExtra []string `json:"bad_ua_extra"` Sensitive bool `json:"sensitive"` Whitelist []string `json:"whitelist"` Blacklist []string `json:"blacklist"` RetentionDays int `json:"retention_days"` // Deep inspection gateway (SQL injection, XSS, RCE, body inspection). Gateway bool `json:"gateway"` GatewayStrict bool `json:"gateway_strict"` GatewayThreshold int `json:"gateway_threshold"` } // Service applies WAF configuration to nginx and exposes rule management. type Service struct { db *store.Store cfg *config.Config nginx *webserver.Manager sites *site.Service mu sync.Mutex // gatewayAvailable is false when the loopback listener could not start; // rendering gateway configs in that state would produce a 502 for every // request, so the renderer falls back to the nginx-only path. gatewayAvailable atomic.Bool } // New builds the WAF service. func New(db *store.Store, cfg *config.Config, nginx *webserver.Manager, sites *site.Service) *Service { return &Service{db: db, cfg: cfg, nginx: nginx, sites: sites} } const ( keyEnabled = "waf.enabled" keyStatus = "waf.block_status" keyRate = "waf.rate" keyBurst = "waf.burst" keyConn = "waf.conn_per_ip" keyBadUA = "waf.bad_ua" keyBadUAExtra = "waf.bad_ua_extra" keySensitive = "waf.sensitive" keyWhitelist = "waf.whitelist" keyBlacklist = "waf.blacklist" keyRetention = "waf.retention_days" keyGateway = "waf.gateway" keyGwStrict = "waf.gateway_strict" keyGwThreshold = "waf.gateway_threshold" defaultRetDays = 7 ) func (s *Service) getBool(ctx context.Context, key string, def bool) bool { v, err := s.db.Setting(ctx, key, "") if err != nil || v == "" { return def } return v == "1" || v == "true" } func (s *Service) getInt(ctx context.Context, key string, def int) int { v, err := s.db.Setting(ctx, key, "") if err != nil || v == "" { return def } n, err := strconv.Atoi(v) if err != nil { return def } return n } func (s *Service) getList(ctx context.Context, key string) []string { v, err := s.db.Setting(ctx, key, "") if err != nil || strings.TrimSpace(v) == "" { return []string{} } out := []string{} for _, item := range strings.FieldsFunc(v, func(r rune) bool { return r == ',' || r == '\n' || r == ' ' }) { item = strings.TrimSpace(item) if item != "" { out = append(out, item) } } return out } // Settings loads the persisted configuration with secure defaults. func (s *Service) Settings(ctx context.Context) (Settings, error) { st := Settings{ Enabled: s.getBool(ctx, keyEnabled, true), BlockStatus: s.getInt(ctx, keyStatus, 444), Rate: s.getInt(ctx, keyRate, 50), Burst: s.getInt(ctx, keyBurst, 200), ConnPerIP: s.getInt(ctx, keyConn, 50), BadUA: s.getBool(ctx, keyBadUA, true), BadUAExtra: s.getList(ctx, keyBadUAExtra), Sensitive: s.getBool(ctx, keySensitive, true), Whitelist: s.getList(ctx, keyWhitelist), Blacklist: s.getList(ctx, keyBlacklist), RetentionDays: s.getInt(ctx, keyRetention, defaultRetDays), Gateway: s.getBool(ctx, keyGateway, false), GatewayStrict: s.getBool(ctx, keyGwStrict, false), GatewayThreshold: s.getInt(ctx, keyGwThreshold, 8), } return st, nil } // Validate checks every field and returns a user facing error. func (st *Settings) Validate() error { if st.BlockStatus != 403 && st.BlockStatus != 444 { return errors.New("拦截响应码只能是 403 或 444") } if st.Rate < 1 || st.Rate > 2000 { return errors.New("限速需在 1-2000 请求/秒之间") } if st.Burst < 1 || st.Burst > 20000 { return errors.New("突发值需在 1-20000 之间") } if st.ConnPerIP < 0 || st.ConnPerIP > 10000 { return errors.New("单 IP 并发需在 0-10000 之间") } if st.RetentionDays < 1 || st.RetentionDays > 90 { return errors.New("日志保留需在 1-90 天之间") } if st.GatewayThreshold == 0 { st.GatewayThreshold = 8 // unset by an older UI } if st.GatewayThreshold < 1 || st.GatewayThreshold > 100 { return errors.New("深度检测阈值需在 1-100 之间") } for _, ip := range append(append([]string{}, st.Whitelist...), st.Blacklist...) { if !validIP(ip) { return fmt.Errorf("IP 格式不正确: %s", ip) } } for _, kw := range st.BadUAExtra { if len(kw) > 64 || strings.ContainsAny(kw, "\"\\\n\r;{}# \t") { return fmt.Errorf("UA 关键词不合法: %s", kw) } } return nil } func validIP(s string) bool { s = strings.TrimSpace(s) if strings.Contains(s, "/") { _, _, err := net.ParseCIDR(s) return err == nil } return net.ParseIP(s) != nil } // SaveSettings validates, persists and applies the configuration. When nginx // rejects the rendered result the previous settings are restored, otherwise a // failed save would leave the database and the running configuration apart and // every later apply would keep failing. func (s *Service) SaveSettings(ctx context.Context, st Settings) error { if err := st.Validate(); err != nil { return err } old, err := s.Settings(ctx) if err != nil { return err } if err := s.writeSettings(ctx, st); err != nil { return err } if err := s.Apply(ctx); err != nil { _ = s.writeSettings(ctx, old) _ = s.Apply(ctx) return err } return nil } func (s *Service) writeSettings(ctx context.Context, st Settings) error { pairs := map[string]string{ keyEnabled: boolString(st.Enabled), keyStatus: strconv.Itoa(st.BlockStatus), keyRate: strconv.Itoa(st.Rate), keyBurst: strconv.Itoa(st.Burst), keyConn: strconv.Itoa(st.ConnPerIP), keyBadUA: boolString(st.BadUA), keyBadUAExtra: strings.Join(st.BadUAExtra, ","), keySensitive: boolString(st.Sensitive), keyWhitelist: strings.Join(st.Whitelist, "\n"), keyBlacklist: strings.Join(st.Blacklist, "\n"), keyRetention: strconv.Itoa(st.RetentionDays), keyGateway: boolString(st.Gateway), keyGwStrict: boolString(st.GatewayStrict), keyGwThreshold: strconv.Itoa(st.GatewayThreshold), } for k, v := range pairs { if err := s.db.SetSetting(ctx, k, v); err != nil { return err } } return nil } func boolString(b bool) string { if b { return "1" } return "0" } // Config converts settings plus rules into a render configuration. func (s *Service) Config(ctx context.Context) (webserver.WAFConfig, error) { st, err := s.Settings(ctx) if err != nil { return webserver.WAFConfig{}, err } rules, err := s.db.WAFRules(ctx) if err != nil { return webserver.WAFConfig{}, err } out := webserver.WAFConfig{ Enabled: st.Enabled, BlockStatus: st.BlockStatus, Rate: st.Rate, Burst: st.Burst, ConnPerIP: st.ConnPerIP, BadUA: st.BadUA, BadUAExtra: st.BadUAExtra, Sensitive: st.Sensitive, Whitelist: st.Whitelist, Blacklist: st.Blacklist, Gateway: st.Gateway && s.gatewayAvailable.Load(), GatewayAddr: s.cfg.WAFGatewayAddr, GatewayStrict: st.GatewayStrict, GatewayThreshold: st.GatewayThreshold, } // The geo include is only rendered when the file actually exists: a stale // setting must never produce a configuration nginx refuses to load. if intel, err := s.IntelSettings(ctx); err == nil && intel.Enabled && intel.URL != "" { if fi, statErr := os.Stat(s.IntelPath()); statErr == nil && !fi.IsDir() { out.Intel = true out.IntelFile = s.IntelPath() } } for _, r := range rules { out.Rules = append(out.Rules, webserver.WAFRule{ ID: r.ID, Name: r.Name, MatchOn: r.MatchOn, Op: r.Op, Pattern: r.Pattern, Action: r.Action, Enabled: r.Enabled, }) } return out, nil } // SetGatewayAvailable records whether the loopback gateway is listening. func (s *Service) SetGatewayAvailable(ok bool) { s.gatewayAvailable.Store(ok) } // GatewayAvailable reports whether deep inspection can actually be applied. func (s *Service) GatewayAvailable() bool { return s.gatewayAvailable.Load() } // Apply updates the nginx manager and re-renders every site. func (s *Service) Apply(ctx context.Context) error { s.mu.Lock() defer s.mu.Unlock() cfg, err := s.Config(ctx) if err != nil { return err } sites, err := s.db.ListSites(ctx) if err != nil { return err } if cfg.Gateway { if err := s.ensureGatewayPorts(ctx, sites); err != nil { return err } if sites, err = s.db.ListSites(ctx); err != nil { return err } } s.nginx.SetWAF(cfg) return s.nginx.ApplyAll(ctx, sites) } // ensureGatewayPorts assigns a loopback origin port to every protected site // that has none yet. Existing ports are kept so a reload never invalidates a // running origin listener. func (s *Service) ensureGatewayPorts(ctx context.Context, sites []*store.Site) error { used, err := s.db.PortsInUse(ctx) if err != nil { return err } for _, st := range sites { if st.Options.GatewayPort > 0 { used[st.Options.GatewayPort] = st.Slug } } for _, st := range sites { if !st.Options.WAF || st.Options.GatewayPort > 0 { continue } port, err := system.AllocatePort(10000, 10999, used) if err != nil { return err } st.Options.GatewayPort = port used[port] = st.Slug if err := s.db.UpdateSite(ctx, st); err != nil { return err } } return nil } // Init loads settings into the renderer at boot without touching nginx. func (s *Service) Init(ctx context.Context) error { cfg, err := s.Config(ctx) if err != nil { return err } s.nginx.SetWAF(cfg) return nil } // RuleInput is the create/update payload. type RuleInput struct { Name string `json:"name"` MatchOn string `json:"match_on"` Op string `json:"op"` Pattern string `json:"pattern"` Action string `json:"action"` Enabled bool `json:"enabled"` Note string `json:"note"` } // Validate checks a rule before it reaches nginx. func (r *RuleInput) Validate() error { r.Name = strings.TrimSpace(r.Name) r.Pattern = strings.TrimSpace(r.Pattern) if r.Name == "" || len(r.Name) > 64 { return errors.New("规则名称需为 1-64 个字符") } switch r.MatchOn { case "uri", "ua", "referer", "method": default: return errors.New("匹配对象只能是 uri / ua / referer / method") } switch r.Op { case "contains", "prefix", "regex": default: return errors.New("匹配方式只能是 contains / prefix / regex") } if r.Pattern == "" || len(r.Pattern) > 512 { return errors.New("匹配内容需为 1-512 个字符") } if strings.ContainsAny(r.Pattern, "\"\\\n\r;{}") { return errors.New("匹配内容不能包含引号、反斜杠、分号或花括号") } if r.Op == "regex" { // Compile before it reaches nginx: a rejected rule that already landed // in the database used to break every later apply. if _, err := regexp.Compile(r.Pattern); err != nil { return fmt.Errorf("正则表达式无效: %v", err) } } if r.Action != "block" { return errors.New("当前版本仅支持拦截动作") } if r.MatchOn == "method" && r.Op == "regex" { return errors.New("请求方法不支持正则匹配") } return nil } // CreateRule validates, stores and applies a new rule. func (s *Service) CreateRule(ctx context.Context, in RuleInput) (*store.WAFRule, error) { if err := in.Validate(); err != nil { return nil, err } rule := &store.WAFRule{ Name: in.Name, MatchOn: in.MatchOn, Op: in.Op, Pattern: in.Pattern, Action: in.Action, Enabled: in.Enabled, Note: in.Note, } if err := s.db.CreateWAFRule(ctx, rule); err != nil { return nil, err } if err := s.Apply(ctx); err != nil { _ = s.db.DeleteWAFRule(ctx, rule.ID) _ = s.Apply(ctx) return nil, err } return rule, nil } // UpdateRule validates, stores and applies changes. A rule nginx refuses is // rolled back to its previous value, otherwise the rejected row stays in the // database and every subsequent apply fails until it is deleted by hand. func (s *Service) UpdateRule(ctx context.Context, id int64, in RuleInput) (*store.WAFRule, error) { if err := in.Validate(); err != nil { return nil, err } old, err := s.ruleByID(ctx, id) if err != nil { return nil, err } rule := &store.WAFRule{ ID: id, Name: in.Name, MatchOn: in.MatchOn, Op: in.Op, Pattern: in.Pattern, Action: in.Action, Enabled: in.Enabled, Note: in.Note, } if err := s.db.UpdateWAFRule(ctx, rule); err != nil { return nil, err } if err := s.Apply(ctx); err != nil { _ = s.db.UpdateWAFRule(ctx, old) _ = s.Apply(ctx) return nil, err } return rule, nil } func (s *Service) ruleByID(ctx context.Context, id int64) (*store.WAFRule, error) { rules, err := s.db.WAFRules(ctx) if err != nil { return nil, err } for i := range rules { if rules[i].ID == id { return &rules[i], nil } } return nil, store.ErrNotFound } // DeleteRule removes a rule and re-renders. func (s *Service) DeleteRule(ctx context.Context, id int64) error { if err := s.db.DeleteWAFRule(ctx, id); err != nil { return err } return s.Apply(ctx) } // SetSiteWAF toggles protection for one site and re-renders it. func (s *Service) SetSiteWAF(ctx context.Context, id int64, enabled bool) error { st, err := s.db.SiteByID(ctx, id) if err != nil { return err } s.mu.Lock() defer s.mu.Unlock() if enabled && st.Options.GatewayPort == 0 { if v, _ := s.db.Setting(ctx, keyGateway, ""); v == "1" || v == "true" { if used, err := s.db.PortsInUse(ctx); err == nil { if port, err := system.AllocatePort(10000, 10999, used); err == nil { st.Options.GatewayPort = port } } } } st.Options.WAF = enabled if err := s.db.UpdateSite(ctx, st); err != nil { return err } return s.nginx.ApplySite(ctx, st) } // Overview is the dashboard payload. type Overview struct { Requests int64 `json:"requests"` Blocked int64 `json:"blocked"` Throttled int64 `json:"throttled"` YesterdayReqs int64 `json:"yesterday_requests"` YesterdayBlk int64 `json:"yesterday_blocked"` ReqGrowth float64 `json:"requests_growth"` BlkGrowth float64 `json:"blocked_growth"` QPS float64 `json:"qps"` Traffic float64 `json:"traffic"` // bytes per second RT float64 `json:"rt"` // milliseconds RetentionDays int `json:"retention_days"` Sites int `json:"sites"` ProtectedSites int `json:"protected_sites"` }