仰望星辰工作室

miaopanel

miaopanel/ internal/waf/waf.go 14.7 KB · 502 行 原始文件
1// Package waf implements the standalone layer-1 WAF module: settings, custom
2// rules, nginx rendering and log based metrics.
3package waf
4
5import (
6 "context"
7 "errors"
8 "fmt"
9 "net"
10 "os"
11 "regexp"
12 "strconv"
13 "strings"
14 "sync"
15 "sync/atomic"
16
17 "github.com/miaopanel/miaopanel/internal/config"
18 "github.com/miaopanel/miaopanel/internal/site"
19 "github.com/miaopanel/miaopanel/internal/store"
20 "github.com/miaopanel/miaopanel/internal/system"
21 "github.com/miaopanel/miaopanel/internal/webserver"
22)
23
24// Settings is the operator facing configuration.
25type Settings struct {
26 Enabled bool `json:"enabled"`
27 BlockStatus int `json:"block_status"`
28 Rate int `json:"rate"`
29 Burst int `json:"burst"`
30 ConnPerIP int `json:"conn_per_ip"`
31 BadUA bool `json:"bad_ua"`
32 BadUAExtra []string `json:"bad_ua_extra"`
33 Sensitive bool `json:"sensitive"`
34 Whitelist []string `json:"whitelist"`
35 Blacklist []string `json:"blacklist"`
36 RetentionDays int `json:"retention_days"`
37
38 // Deep inspection gateway (SQL injection, XSS, RCE, body inspection).
39 Gateway bool `json:"gateway"`
40 GatewayStrict bool `json:"gateway_strict"`
41 GatewayThreshold int `json:"gateway_threshold"`
42}
43
44// Service applies WAF configuration to nginx and exposes rule management.
45type Service struct {
46 db *store.Store
47 cfg *config.Config
48 nginx *webserver.Manager
49 sites *site.Service
50
51 mu sync.Mutex
52 // gatewayAvailable is false when the loopback listener could not start;
53 // rendering gateway configs in that state would produce a 502 for every
54 // request, so the renderer falls back to the nginx-only path.
55 gatewayAvailable atomic.Bool
56}
57
58// New builds the WAF service.
59func New(db *store.Store, cfg *config.Config, nginx *webserver.Manager, sites *site.Service) *Service {
60 return &Service{db: db, cfg: cfg, nginx: nginx, sites: sites}
61}
62
63const (
64 keyEnabled = "waf.enabled"
65 keyStatus = "waf.block_status"
66 keyRate = "waf.rate"
67 keyBurst = "waf.burst"
68 keyConn = "waf.conn_per_ip"
69 keyBadUA = "waf.bad_ua"
70 keyBadUAExtra = "waf.bad_ua_extra"
71 keySensitive = "waf.sensitive"
72 keyWhitelist = "waf.whitelist"
73 keyBlacklist = "waf.blacklist"
74 keyRetention = "waf.retention_days"
75 keyGateway = "waf.gateway"
76 keyGwStrict = "waf.gateway_strict"
77 keyGwThreshold = "waf.gateway_threshold"
78 defaultRetDays = 7
79)
80
81func (s *Service) getBool(ctx context.Context, key string, def bool) bool {
82 v, err := s.db.Setting(ctx, key, "")
83 if err != nil || v == "" {
84 return def
85 }
86 return v == "1" || v == "true"
87}
88
89func (s *Service) getInt(ctx context.Context, key string, def int) int {
90 v, err := s.db.Setting(ctx, key, "")
91 if err != nil || v == "" {
92 return def
93 }
94 n, err := strconv.Atoi(v)
95 if err != nil {
96 return def
97 }
98 return n
99}
100
101func (s *Service) getList(ctx context.Context, key string) []string {
102 v, err := s.db.Setting(ctx, key, "")
103 if err != nil || strings.TrimSpace(v) == "" {
104 return []string{}
105 }
106 out := []string{}
107 for _, item := range strings.FieldsFunc(v, func(r rune) bool { return r == ',' || r == '\n' || r == ' ' }) {
108 item = strings.TrimSpace(item)
109 if item != "" {
110 out = append(out, item)
111 }
112 }
113 return out
114}
115
116// Settings loads the persisted configuration with secure defaults.
117func (s *Service) Settings(ctx context.Context) (Settings, error) {
118 st := Settings{
119 Enabled: s.getBool(ctx, keyEnabled, true),
120 BlockStatus: s.getInt(ctx, keyStatus, 444),
121 Rate: s.getInt(ctx, keyRate, 50),
122 Burst: s.getInt(ctx, keyBurst, 200),
123 ConnPerIP: s.getInt(ctx, keyConn, 50),
124 BadUA: s.getBool(ctx, keyBadUA, true),
125 BadUAExtra: s.getList(ctx, keyBadUAExtra),
126 Sensitive: s.getBool(ctx, keySensitive, true),
127 Whitelist: s.getList(ctx, keyWhitelist),
128 Blacklist: s.getList(ctx, keyBlacklist),
129 RetentionDays: s.getInt(ctx, keyRetention, defaultRetDays),
130
131 Gateway: s.getBool(ctx, keyGateway, false),
132 GatewayStrict: s.getBool(ctx, keyGwStrict, false),
133 GatewayThreshold: s.getInt(ctx, keyGwThreshold, 8),
134 }
135 return st, nil
136}
137
138// Validate checks every field and returns a user facing error.
139func (st *Settings) Validate() error {
140 if st.BlockStatus != 403 && st.BlockStatus != 444 {
141 return errors.New("拦截响应码只能是 403 或 444")
142 }
143 if st.Rate < 1 || st.Rate > 2000 {
144 return errors.New("限速需在 1-2000 请求/秒之间")
145 }
146 if st.Burst < 1 || st.Burst > 20000 {
147 return errors.New("突发值需在 1-20000 之间")
148 }
149 if st.ConnPerIP < 0 || st.ConnPerIP > 10000 {
150 return errors.New("单 IP 并发需在 0-10000 之间")
151 }
152 if st.RetentionDays < 1 || st.RetentionDays > 90 {
153 return errors.New("日志保留需在 1-90 天之间")
154 }
155 if st.GatewayThreshold == 0 {
156 st.GatewayThreshold = 8 // unset by an older UI
157 }
158 if st.GatewayThreshold < 1 || st.GatewayThreshold > 100 {
159 return errors.New("深度检测阈值需在 1-100 之间")
160 }
161 for _, ip := range append(append([]string{}, st.Whitelist...), st.Blacklist...) {
162 if !validIP(ip) {
163 return fmt.Errorf("IP 格式不正确: %s", ip)
164 }
165 }
166 for _, kw := range st.BadUAExtra {
167 if len(kw) > 64 || strings.ContainsAny(kw, "\"\\\n\r;{}# \t") {
168 return fmt.Errorf("UA 关键词不合法: %s", kw)
169 }
170 }
171 return nil
172}
173
174func validIP(s string) bool {
175 s = strings.TrimSpace(s)
176 if strings.Contains(s, "/") {
177 _, _, err := net.ParseCIDR(s)
178 return err == nil
179 }
180 return net.ParseIP(s) != nil
181}
182
183// SaveSettings validates, persists and applies the configuration. When nginx
184// rejects the rendered result the previous settings are restored, otherwise a
185// failed save would leave the database and the running configuration apart and
186// every later apply would keep failing.
187func (s *Service) SaveSettings(ctx context.Context, st Settings) error {
188 if err := st.Validate(); err != nil {
189 return err
190 }
191 old, err := s.Settings(ctx)
192 if err != nil {
193 return err
194 }
195 if err := s.writeSettings(ctx, st); err != nil {
196 return err
197 }
198 if err := s.Apply(ctx); err != nil {
199 _ = s.writeSettings(ctx, old)
200 _ = s.Apply(ctx)
201 return err
202 }
203 return nil
204}
205
206func (s *Service) writeSettings(ctx context.Context, st Settings) error {
207 pairs := map[string]string{
208 keyEnabled: boolString(st.Enabled),
209 keyStatus: strconv.Itoa(st.BlockStatus),
210 keyRate: strconv.Itoa(st.Rate),
211 keyBurst: strconv.Itoa(st.Burst),
212 keyConn: strconv.Itoa(st.ConnPerIP),
213 keyBadUA: boolString(st.BadUA),
214 keyBadUAExtra: strings.Join(st.BadUAExtra, ","),
215 keySensitive: boolString(st.Sensitive),
216 keyWhitelist: strings.Join(st.Whitelist, "\n"),
217 keyBlacklist: strings.Join(st.Blacklist, "\n"),
218 keyRetention: strconv.Itoa(st.RetentionDays),
219
220 keyGateway: boolString(st.Gateway),
221 keyGwStrict: boolString(st.GatewayStrict),
222 keyGwThreshold: strconv.Itoa(st.GatewayThreshold),
223 }
224 for k, v := range pairs {
225 if err := s.db.SetSetting(ctx, k, v); err != nil {
226 return err
227 }
228 }
229 return nil
230}
231
232func boolString(b bool) string {
233 if b {
234 return "1"
235 }
236 return "0"
237}
238
239// Config converts settings plus rules into a render configuration.
240func (s *Service) Config(ctx context.Context) (webserver.WAFConfig, error) {
241 st, err := s.Settings(ctx)
242 if err != nil {
243 return webserver.WAFConfig{}, err
244 }
245 rules, err := s.db.WAFRules(ctx)
246 if err != nil {
247 return webserver.WAFConfig{}, err
248 }
249 out := webserver.WAFConfig{
250 Enabled: st.Enabled, BlockStatus: st.BlockStatus, Rate: st.Rate,
251 Burst: st.Burst, ConnPerIP: st.ConnPerIP, BadUA: st.BadUA,
252 BadUAExtra: st.BadUAExtra, Sensitive: st.Sensitive,
253 Whitelist: st.Whitelist, Blacklist: st.Blacklist,
254 Gateway: st.Gateway && s.gatewayAvailable.Load(), GatewayAddr: s.cfg.WAFGatewayAddr,
255 GatewayStrict: st.GatewayStrict, GatewayThreshold: st.GatewayThreshold,
256 }
257 // The geo include is only rendered when the file actually exists: a stale
258 // setting must never produce a configuration nginx refuses to load.
259 if intel, err := s.IntelSettings(ctx); err == nil && intel.Enabled && intel.URL != "" {
260 if fi, statErr := os.Stat(s.IntelPath()); statErr == nil && !fi.IsDir() {
261 out.Intel = true
262 out.IntelFile = s.IntelPath()
263 }
264 }
265 for _, r := range rules {
266 out.Rules = append(out.Rules, webserver.WAFRule{
267 ID: r.ID, Name: r.Name, MatchOn: r.MatchOn, Op: r.Op,
268 Pattern: r.Pattern, Action: r.Action, Enabled: r.Enabled,
269 })
270 }
271 return out, nil
272}
273
274// SetGatewayAvailable records whether the loopback gateway is listening.
275func (s *Service) SetGatewayAvailable(ok bool) {
276 s.gatewayAvailable.Store(ok)
277}
278
279// GatewayAvailable reports whether deep inspection can actually be applied.
280func (s *Service) GatewayAvailable() bool { return s.gatewayAvailable.Load() }
281
282// Apply updates the nginx manager and re-renders every site.
283func (s *Service) Apply(ctx context.Context) error {
284 s.mu.Lock()
285 defer s.mu.Unlock()
286 cfg, err := s.Config(ctx)
287 if err != nil {
288 return err
289 }
290 sites, err := s.db.ListSites(ctx)
291 if err != nil {
292 return err
293 }
294 if cfg.Gateway {
295 if err := s.ensureGatewayPorts(ctx, sites); err != nil {
296 return err
297 }
298 if sites, err = s.db.ListSites(ctx); err != nil {
299 return err
300 }
301 }
302 s.nginx.SetWAF(cfg)
303 return s.nginx.ApplyAll(ctx, sites)
304}
305
306// ensureGatewayPorts assigns a loopback origin port to every protected site
307// that has none yet. Existing ports are kept so a reload never invalidates a
308// running origin listener.
309func (s *Service) ensureGatewayPorts(ctx context.Context, sites []*store.Site) error {
310 used, err := s.db.PortsInUse(ctx)
311 if err != nil {
312 return err
313 }
314 for _, st := range sites {
315 if st.Options.GatewayPort > 0 {
316 used[st.Options.GatewayPort] = st.Slug
317 }
318 }
319 for _, st := range sites {
320 if !st.Options.WAF || st.Options.GatewayPort > 0 {
321 continue
322 }
323 port, err := system.AllocatePort(10000, 10999, used)
324 if err != nil {
325 return err
326 }
327 st.Options.GatewayPort = port
328 used[port] = st.Slug
329 if err := s.db.UpdateSite(ctx, st); err != nil {
330 return err
331 }
332 }
333 return nil
334}
335
336// Init loads settings into the renderer at boot without touching nginx.
337func (s *Service) Init(ctx context.Context) error {
338 cfg, err := s.Config(ctx)
339 if err != nil {
340 return err
341 }
342 s.nginx.SetWAF(cfg)
343 return nil
344}
345
346// RuleInput is the create/update payload.
347type RuleInput struct {
348 Name string `json:"name"`
349 MatchOn string `json:"match_on"`
350 Op string `json:"op"`
351 Pattern string `json:"pattern"`
352 Action string `json:"action"`
353 Enabled bool `json:"enabled"`
354 Note string `json:"note"`
355}
356
357// Validate checks a rule before it reaches nginx.
358func (r *RuleInput) Validate() error {
359 r.Name = strings.TrimSpace(r.Name)
360 r.Pattern = strings.TrimSpace(r.Pattern)
361 if r.Name == "" || len(r.Name) > 64 {
362 return errors.New("规则名称需为 1-64 个字符")
363 }
364 switch r.MatchOn {
365 case "uri", "ua", "referer", "method":
366 default:
367 return errors.New("匹配对象只能是 uri / ua / referer / method")
368 }
369 switch r.Op {
370 case "contains", "prefix", "regex":
371 default:
372 return errors.New("匹配方式只能是 contains / prefix / regex")
373 }
374 if r.Pattern == "" || len(r.Pattern) > 512 {
375 return errors.New("匹配内容需为 1-512 个字符")
376 }
377 if strings.ContainsAny(r.Pattern, "\"\\\n\r;{}") {
378 return errors.New("匹配内容不能包含引号、反斜杠、分号或花括号")
379 }
380 if r.Op == "regex" {
381 // Compile before it reaches nginx: a rejected rule that already landed
382 // in the database used to break every later apply.
383 if _, err := regexp.Compile(r.Pattern); err != nil {
384 return fmt.Errorf("正则表达式无效: %v", err)
385 }
386 }
387 if r.Action != "block" {
388 return errors.New("当前版本仅支持拦截动作")
389 }
390 if r.MatchOn == "method" && r.Op == "regex" {
391 return errors.New("请求方法不支持正则匹配")
392 }
393 return nil
394}
395
396// CreateRule validates, stores and applies a new rule.
397func (s *Service) CreateRule(ctx context.Context, in RuleInput) (*store.WAFRule, error) {
398 if err := in.Validate(); err != nil {
399 return nil, err
400 }
401 rule := &store.WAFRule{
402 Name: in.Name, MatchOn: in.MatchOn, Op: in.Op, Pattern: in.Pattern,
403 Action: in.Action, Enabled: in.Enabled, Note: in.Note,
404 }
405 if err := s.db.CreateWAFRule(ctx, rule); err != nil {
406 return nil, err
407 }
408 if err := s.Apply(ctx); err != nil {
409 _ = s.db.DeleteWAFRule(ctx, rule.ID)
410 _ = s.Apply(ctx)
411 return nil, err
412 }
413 return rule, nil
414}
415
416// UpdateRule validates, stores and applies changes. A rule nginx refuses is
417// rolled back to its previous value, otherwise the rejected row stays in the
418// database and every subsequent apply fails until it is deleted by hand.
419func (s *Service) UpdateRule(ctx context.Context, id int64, in RuleInput) (*store.WAFRule, error) {
420 if err := in.Validate(); err != nil {
421 return nil, err
422 }
423 old, err := s.ruleByID(ctx, id)
424 if err != nil {
425 return nil, err
426 }
427 rule := &store.WAFRule{
428 ID: id, Name: in.Name, MatchOn: in.MatchOn, Op: in.Op, Pattern: in.Pattern,
429 Action: in.Action, Enabled: in.Enabled, Note: in.Note,
430 }
431 if err := s.db.UpdateWAFRule(ctx, rule); err != nil {
432 return nil, err
433 }
434 if err := s.Apply(ctx); err != nil {
435 _ = s.db.UpdateWAFRule(ctx, old)
436 _ = s.Apply(ctx)
437 return nil, err
438 }
439 return rule, nil
440}
441
442func (s *Service) ruleByID(ctx context.Context, id int64) (*store.WAFRule, error) {
443 rules, err := s.db.WAFRules(ctx)
444 if err != nil {
445 return nil, err
446 }
447 for i := range rules {
448 if rules[i].ID == id {
449 return &rules[i], nil
450 }
451 }
452 return nil, store.ErrNotFound
453}
454
455// DeleteRule removes a rule and re-renders.
456func (s *Service) DeleteRule(ctx context.Context, id int64) error {
457 if err := s.db.DeleteWAFRule(ctx, id); err != nil {
458 return err
459 }
460 return s.Apply(ctx)
461}
462
463// SetSiteWAF toggles protection for one site and re-renders it.
464func (s *Service) SetSiteWAF(ctx context.Context, id int64, enabled bool) error {
465 st, err := s.db.SiteByID(ctx, id)
466 if err != nil {
467 return err
468 }
469 s.mu.Lock()
470 defer s.mu.Unlock()
471 if enabled && st.Options.GatewayPort == 0 {
472 if v, _ := s.db.Setting(ctx, keyGateway, ""); v == "1" || v == "true" {
473 if used, err := s.db.PortsInUse(ctx); err == nil {
474 if port, err := system.AllocatePort(10000, 10999, used); err == nil {
475 st.Options.GatewayPort = port
476 }
477 }
478 }
479 }
480 st.Options.WAF = enabled
481 if err := s.db.UpdateSite(ctx, st); err != nil {
482 return err
483 }
484 return s.nginx.ApplySite(ctx, st)
485}
486
487// Overview is the dashboard payload.
488type Overview struct {
489 Requests int64 `json:"requests"`
490 Blocked int64 `json:"blocked"`
491 Throttled int64 `json:"throttled"`
492 YesterdayReqs int64 `json:"yesterday_requests"`
493 YesterdayBlk int64 `json:"yesterday_blocked"`
494 ReqGrowth float64 `json:"requests_growth"`
495 BlkGrowth float64 `json:"blocked_growth"`
496 QPS float64 `json:"qps"`
497 Traffic float64 `json:"traffic"` // bytes per second
498 RT float64 `json:"rt"` // milliseconds
499 RetentionDays int `json:"retention_days"`
500 Sites int `json:"sites"`
501 ProtectedSites int `json:"protected_sites"`
502}