仰望星辰工作室

miaopanel

miaopanel/ internal/store/waf.go 8.6 KB · 280 行 原始文件
1package store
2
3import (
4 "context"
5 "database/sql"
6 "errors"
7 "time"
8)
9
10// WAFRule is one operator defined nginx rule.
11type WAFRule struct {
12 ID int64 `json:"id"`
13 Name string `json:"name"`
14 MatchOn string `json:"match_on"` // uri | ua | referer | method
15 Op string `json:"op"` // contains | prefix | regex
16 Pattern string `json:"pattern"`
17 Action string `json:"action"` // block | log
18 Enabled bool `json:"enabled"`
19 Note string `json:"note"`
20 CreatedAt int64 `json:"created_at"`
21 UpdatedAt int64 `json:"updated_at"`
22}
23
24// WAFEvent is one blocked or logged request.
25type WAFEvent struct {
26 ID int64 `json:"id"`
27 TS int64 `json:"ts"`
28 Site string `json:"site"`
29 IP string `json:"ip"`
30 Method string `json:"method"`
31 URI string `json:"uri"`
32 UA string `json:"ua"`
33 Status int `json:"status"`
34 Rule string `json:"rule"`
35 Module string `json:"module"`
36 Score int `json:"score"`
37 Detail string `json:"detail"`
38}
39
40// WAFTotals aggregates counters over a time window.
41type WAFTotals struct {
42 Requests int64 `json:"requests"`
43 Blocked int64 `json:"blocked"`
44 Throttled int64 `json:"throttled"`
45 Bytes int64 `json:"bytes"`
46 RTSum float64 `json:"rt_sum"`
47 RTCount int64 `json:"rt_count"`
48}
49
50// WAFPoint is one chart sample.
51type WAFPoint struct {
52 TS int64 `json:"ts"`
53 Value float64 `json:"value"`
54}
55
56// WAFRules lists every rule ordered by id.
57func (s *Store) WAFRules(ctx context.Context) ([]WAFRule, error) {
58 rows, err := s.db.QueryContext(ctx,
59 `SELECT id, name, match_on, op, pattern, action, enabled, note, created_at, updated_at
60 FROM waf_rules ORDER BY id`)
61 if err != nil {
62 return nil, err
63 }
64 defer rows.Close()
65 out := []WAFRule{}
66 for rows.Next() {
67 var r WAFRule
68 var enabled int
69 if err := rows.Scan(&r.ID, &r.Name, &r.MatchOn, &r.Op, &r.Pattern,
70 &r.Action, &enabled, &r.Note, &r.CreatedAt, &r.UpdatedAt); err != nil {
71 return nil, err
72 }
73 r.Enabled = enabled == 1
74 out = append(out, r)
75 }
76 return out, rows.Err()
77}
78
79// CreateWAFRule inserts a rule.
80func (s *Store) CreateWAFRule(ctx context.Context, r *WAFRule) error {
81 now := time.Now().Unix()
82 res, err := s.db.ExecContext(ctx,
83 `INSERT INTO waf_rules(name, match_on, op, pattern, action, enabled, note, created_at, updated_at)
84 VALUES(?,?,?,?,?,?,?,?,?)`,
85 r.Name, r.MatchOn, r.Op, r.Pattern, r.Action, boolInt(r.Enabled), r.Note, now, now)
86 if err != nil {
87 return err
88 }
89 id, err := res.LastInsertId()
90 if err != nil {
91 return err
92 }
93 r.ID, r.CreatedAt, r.UpdatedAt = id, now, now
94 return nil
95}
96
97// UpdateWAFRule rewrites a rule.
98func (s *Store) UpdateWAFRule(ctx context.Context, r *WAFRule) error {
99 res, err := s.db.ExecContext(ctx,
100 `UPDATE waf_rules SET name=?, match_on=?, op=?, pattern=?, action=?, enabled=?, note=?, updated_at=?
101 WHERE id=?`,
102 r.Name, r.MatchOn, r.Op, r.Pattern, r.Action, boolInt(r.Enabled), r.Note,
103 time.Now().Unix(), r.ID)
104 if err != nil {
105 return err
106 }
107 if n, _ := res.RowsAffected(); n == 0 {
108 return ErrNotFound
109 }
110 return nil
111}
112
113// DeleteWAFRule removes a rule.
114func (s *Store) DeleteWAFRule(ctx context.Context, id int64) error {
115 res, err := s.db.ExecContext(ctx, `DELETE FROM waf_rules WHERE id=?`, id)
116 if err != nil {
117 return err
118 }
119 if n, _ := res.RowsAffected(); n == 0 {
120 return ErrNotFound
121 }
122 return nil
123}
124
125// WAFMetricAdd folds one aggregate into the minute bucket.
126func (s *Store) WAFMetricAdd(ctx context.Context, bucket int64, site string,
127 requests, blocked, throttled, bytes int64, rtSum float64, rtCount int64) error {
128 _, err := s.db.ExecContext(ctx,
129 `INSERT INTO waf_metrics(bucket, site, requests, blocked, throttled, bytes, rt_sum, rt_count)
130 VALUES(?,?,?,?,?,?,?,?)
131 ON CONFLICT(bucket, site) DO UPDATE SET
132 requests = requests + excluded.requests,
133 blocked = blocked + excluded.blocked,
134 throttled = throttled + excluded.throttled,
135 bytes = bytes + excluded.bytes,
136 rt_sum = rt_sum + excluded.rt_sum,
137 rt_count = rt_count + excluded.rt_count`,
138 bucket, site, requests, blocked, throttled, bytes, rtSum, rtCount)
139 return err
140}
141
142// WAFTotals sums counters in [from, to).
143func (s *Store) WAFTotals(ctx context.Context, from, to int64) (WAFTotals, error) {
144 var t WAFTotals
145 err := s.db.QueryRowContext(ctx,
146 `SELECT COALESCE(SUM(requests),0), COALESCE(SUM(blocked),0), COALESCE(SUM(throttled),0),
147 COALESCE(SUM(bytes),0), COALESCE(SUM(rt_sum),0), COALESCE(SUM(rt_count),0)
148 FROM waf_metrics WHERE bucket >= ? AND bucket < ?`, from, to).
149 Scan(&t.Requests, &t.Blocked, &t.Throttled, &t.Bytes, &t.RTSum, &t.RTCount)
150 return t, err
151}
152
153// WAFSeries aggregates per minute and returns requests/blocked/bytes/rt points.
154func (s *Store) WAFSeries(ctx context.Context, from, to, step int64) (map[string][]WAFPoint, error) {
155 if step < 60 {
156 step = 60
157 }
158 rows, err := s.db.QueryContext(ctx,
159 `SELECT (bucket / ?) * ? AS slot,
160 SUM(requests), SUM(blocked), SUM(throttled), SUM(bytes), SUM(rt_sum), SUM(rt_count)
161 FROM waf_metrics WHERE bucket >= ? AND bucket < ?
162 GROUP BY slot ORDER BY slot`, step, step, from, to)
163 if err != nil {
164 return nil, err
165 }
166 defer rows.Close()
167 out := map[string][]WAFPoint{
168 "requests": {}, "blocked": {}, "throttled": {}, "traffic": {}, "rt": {},
169 }
170 for rows.Next() {
171 var slot, req, blocked, throttled, bytes, rtCount int64
172 var rtSum float64
173 if err := rows.Scan(&slot, &req, &blocked, &throttled, &bytes, &rtSum, &rtCount); err != nil {
174 return nil, err
175 }
176 qps := float64(req) / float64(step)
177 traffic := float64(bytes) / float64(step)
178 rt := 0.0
179 if rtCount > 0 {
180 rt = rtSum / float64(rtCount) * 1000
181 }
182 out["requests"] = append(out["requests"], WAFPoint{TS: slot, Value: qps})
183 out["blocked"] = append(out["blocked"], WAFPoint{TS: slot, Value: float64(blocked)})
184 out["throttled"] = append(out["throttled"], WAFPoint{TS: slot, Value: float64(throttled)})
185 out["traffic"] = append(out["traffic"], WAFPoint{TS: slot, Value: traffic})
186 out["rt"] = append(out["rt"], WAFPoint{TS: slot, Value: rt})
187 }
188 return out, rows.Err()
189}
190
191// WAFEventAdd inserts an event unless the same ip+uri was recorded recently.
192func (s *Store) WAFEventAdd(ctx context.Context, e *WAFEvent) error {
193 var n int
194 err := s.db.QueryRowContext(ctx,
195 `SELECT COUNT(1) FROM waf_events WHERE ip=? AND uri=? AND ts >= ?`,
196 e.IP, e.URI, e.TS-60).Scan(&n)
197 if err != nil {
198 return err
199 }
200 if n > 0 {
201 return nil
202 }
203 res, err := s.db.ExecContext(ctx,
204 `INSERT INTO waf_events(ts, site, ip, method, uri, ua, status, rule, module, score, detail, created_at)
205 VALUES(?,?,?,?,?,?,?,?,?,?,?,?)`,
206 e.TS, e.Site, e.IP, e.Method, e.URI, e.UA, e.Status, e.Rule,
207 e.Module, e.Score, e.Detail, time.Now().Unix())
208 if err != nil {
209 return err
210 }
211 e.ID, _ = res.LastInsertId()
212 return nil
213}
214
215// WAFEvents returns the newest events, optionally filtered by site.
216func (s *Store) WAFEvents(ctx context.Context, limit int, site string) ([]WAFEvent, error) {
217 if limit <= 0 || limit > 500 {
218 limit = 100
219 }
220 query := `SELECT id, ts, site, ip, method, uri, ua, status, rule, module, score, detail FROM waf_events`
221 args := []any{}
222 if site != "" {
223 query += ` WHERE site = ?`
224 args = append(args, site)
225 }
226 query += ` ORDER BY id DESC LIMIT ?`
227 args = append(args, limit)
228 rows, err := s.db.QueryContext(ctx, query, args...)
229 if err != nil {
230 return nil, err
231 }
232 defer rows.Close()
233 out := []WAFEvent{}
234 for rows.Next() {
235 var e WAFEvent
236 if err := rows.Scan(&e.ID, &e.TS, &e.Site, &e.IP, &e.Method,
237 &e.URI, &e.UA, &e.Status, &e.Rule, &e.Module, &e.Score, &e.Detail); err != nil {
238 return nil, err
239 }
240 out = append(out, e)
241 }
242 return out, rows.Err()
243}
244
245// WAFOffset returns the stored read offset for a log file.
246func (s *Store) WAFOffset(ctx context.Context, path string) (int64, error) {
247 var off int64
248 err := s.db.QueryRowContext(ctx,
249 `SELECT offset FROM waf_offsets WHERE path=?`, path).Scan(&off)
250 if errors.Is(err, sql.ErrNoRows) {
251 return 0, nil
252 }
253 return off, err
254}
255
256// SetWAFOffset stores the read offset for a log file.
257func (s *Store) SetWAFOffset(ctx context.Context, path string, offset int64) error {
258 _, err := s.db.ExecContext(ctx,
259 `INSERT INTO waf_offsets(path, offset, updated_at) VALUES(?,?,?)
260 ON CONFLICT(path) DO UPDATE SET offset=excluded.offset, updated_at=excluded.updated_at`,
261 path, offset, time.Now().Unix())
262 return err
263}
264
265// PruneWAF drops metrics, events and offsets older than cutoff.
266func (s *Store) PruneWAF(ctx context.Context, cutoff int64) (int64, error) {
267 var total int64
268 for _, q := range []string{
269 `DELETE FROM waf_metrics WHERE bucket < ?`,
270 `DELETE FROM waf_events WHERE ts < ?`,
271 } {
272 res, err := s.db.ExecContext(ctx, q, cutoff)
273 if err != nil {
274 return total, err
275 }
276 n, _ := res.RowsAffected()
277 total += n
278 }
279 return total, nil
280}