仰望星辰工作室

miaopanel

miaopanel/ internal/waf/intel.go 8.9 KB · 296 行 原始文件
1package waf
2
3import (
4 "bufio"
5 "context"
6 "errors"
7 "fmt"
8 "io"
9 "net/http"
10 "os"
11 "path/filepath"
12 "strings"
13 "time"
14
15 "github.com/miaopanel/miaopanel/internal/config"
16)
17
18// IP threat intelligence: a subscription URL (for example the Chaitin
19// "IP 组订阅" feed) is fetched once a day and rendered as an nginx geo map.
20// Large lists must never be rendered into every site block, so the entries
21// live in a standalone include file next to the vhost directory.
22
23const (
24 keyIntelEnabled = "waf.intel.enabled"
25 keyIntelURL = "waf.intel.url"
26 keyIntelHour = "waf.intel.hour"
27 keyIntelLast = "waf.intel.last_sync"
28 keyIntelAttempt = "waf.intel.last_attempt"
29 keyIntelCount = "waf.intel.last_count"
30 keyIntelError = "waf.intel.last_error"
31
32 intelMaxEntries = 200000
33 intelMaxBody = 32 << 20
34 intelMinDrop = 100 // only guard against drop-outs once the list is meaningful
35)
36
37// IntelSettings is the operator facing configuration plus the last sync state.
38type IntelSettings struct {
39 Enabled bool `json:"enabled"`
40 URL string `json:"url"`
41 Hour int `json:"hour"`
42 LastSync int64 `json:"last_sync"`
43 LastCount int `json:"last_count"`
44 LastError string `json:"last_error"`
45 Count int `json:"count"`
46
47 LastAttempt int64 `json:"last_attempt"`
48}
49
50// IntelPath returns the include file consumed by the http level geo map.
51func (s *Service) IntelPath() string {
52 return filepath.Join(s.cfg.Nginx.VhostDir, "intel", "blocklist.conf")
53}
54
55// IntelSettings loads the persisted configuration and sync state.
56func (s *Service) IntelSettings(ctx context.Context) (IntelSettings, error) {
57 st := IntelSettings{
58 Enabled: s.getBool(ctx, keyIntelEnabled, false),
59 URL: s.getText(ctx, keyIntelURL),
60 Hour: s.getInt(ctx, keyIntelHour, 4),
61 LastSync: int64(s.getInt(ctx, keyIntelLast, 0)),
62 LastCount: s.getInt(ctx, keyIntelCount, 0),
63 LastError: s.getText(ctx, keyIntelError),
64 LastAttempt: int64(s.getInt(ctx, keyIntelAttempt, 0)),
65 }
66 st.Count = st.LastCount
67 if st.Hour < 0 || st.Hour > 23 {
68 st.Hour = 4
69 }
70 return st, nil
71}
72
73func (s *Service) getText(ctx context.Context, key string) string {
74 v, err := s.db.Setting(ctx, key, "")
75 if err != nil {
76 return ""
77 }
78 return v
79}
80
81// SaveIntel validates and persists the configuration, then re-renders nginx so
82// enabling the feature takes effect immediately.
83func (s *Service) SaveIntel(ctx context.Context, st IntelSettings) error {
84 st.URL = strings.TrimSpace(st.URL)
85 if st.Hour < 0 || st.Hour > 23 {
86 return errors.New("同步时间需在 0-23 点之间")
87 }
88 if st.Enabled {
89 if st.URL == "" {
90 return errors.New("请填写 IP 情报订阅地址")
91 }
92 if !validFeedURL(st.URL) {
93 return errors.New("订阅地址必须是 http:// 或 https:// 链接")
94 }
95 }
96 if len(st.URL) > 2048 || strings.ContainsAny(st.URL, "\r\n\t \"'") {
97 return errors.New("订阅地址不合法")
98 }
99 pairs := map[string]string{
100 keyIntelEnabled: boolString(st.Enabled),
101 keyIntelURL: st.URL,
102 keyIntelHour: fmt.Sprintf("%d", st.Hour),
103 }
104 for k, v := range pairs {
105 if err := s.db.SetSetting(ctx, k, v); err != nil {
106 return err
107 }
108 }
109 // nginx fails to start when the geo include is missing, so the (possibly
110 // empty) file must exist before the configuration is rendered.
111 if err := s.EnsureIntelFile(); err != nil {
112 return err
113 }
114 return s.Apply(ctx)
115}
116
117func validFeedURL(u string) bool {
118 return strings.HasPrefix(u, "http://") || strings.HasPrefix(u, "https://")
119}
120
121// EnsureIntelFile creates an empty include file when it does not exist yet.
122func (s *Service) EnsureIntelFile() error {
123 path := s.IntelPath()
124 if _, err := os.Stat(path); err == nil {
125 return nil
126 }
127 return config.WriteFileAtomic(path, []byte("# managed by MiaoPanel - empty IP intelligence list\n"), 0o644)
128}
129
130// IntelDue reports whether the daily sync is pending. A missed window (panel
131// was down at the configured hour) is caught up on the next check.
132func (s *Service) IntelDue(now time.Time) bool {
133 st, err := s.IntelSettings(context.Background())
134 if err != nil || !st.Enabled || st.URL == "" {
135 return false
136 }
137 if st.LastSync > 0 {
138 last := time.Unix(st.LastSync, 0)
139 if last.Format("2006-01-02") == now.Format("2006-01-02") {
140 return false
141 }
142 }
143 // Failed attempts back off to one retry per half hour instead of hammering
144 // an unreachable feed every scheduler tick.
145 if st.LastAttempt > 0 && now.Sub(time.Unix(st.LastAttempt, 0)) < 30*time.Minute {
146 return false
147 }
148 return now.Hour() >= st.Hour
149}
150
151// SyncIntel downloads the feed and replaces the include file. The previous
152// list is kept when the download, the content or the nginx validation fails.
153func (s *Service) SyncIntel(ctx context.Context, force bool) error {
154 st, err := s.IntelSettings(ctx)
155 if err != nil {
156 return err
157 }
158 if !st.Enabled {
159 return errors.New("IP 情报库未启用")
160 }
161 if st.URL == "" {
162 return errors.New("请先填写订阅地址")
163 }
164 _ = s.db.SetSetting(ctx, keyIntelAttempt, fmt.Sprintf("%d", time.Now().Unix()))
165 entries, err := fetchIntel(ctx, st.URL)
166 if err != nil {
167 s.recordIntelError(ctx, err)
168 return err
169 }
170 if len(entries) == 0 {
171 err = errors.New("订阅返回空列表,已保留旧库")
172 s.recordIntelError(ctx, err)
173 return err
174 }
175 // A truncated feed (network hiccup, upstream outage) must not wipe the
176 // protection. Operators can still force a replace explicitly.
177 if !force && st.LastCount >= intelMinDrop && len(entries)*2 < st.LastCount {
178 err = fmt.Errorf("订阅条数异常下降(%d → %d),已保留旧库", st.LastCount, len(entries))
179 s.recordIntelError(ctx, err)
180 return err
181 }
182
183 path := s.IntelPath()
184 previous, readErr := os.ReadFile(path)
185 if err := config.WriteFileAtomic(path, renderIntelFile(entries), 0o644); err != nil {
186 s.recordIntelError(ctx, err)
187 return fmt.Errorf("写入情报库失败: %w", err)
188 }
189 if err := s.Apply(ctx); err != nil {
190 if readErr == nil {
191 _ = config.WriteFileAtomic(path, previous, 0o644)
192 }
193 s.recordIntelError(ctx, err)
194 return fmt.Errorf("应用情报库失败,已回滚: %w", err)
195 }
196 now := time.Now().Unix()
197 for k, v := range map[string]string{
198 keyIntelLast: fmt.Sprintf("%d", now),
199 keyIntelCount: fmt.Sprintf("%d", len(entries)),
200 keyIntelError: "",
201 } {
202 if err := s.db.SetSetting(ctx, k, v); err != nil {
203 return err
204 }
205 }
206 return nil
207}
208
209func (s *Service) recordIntelError(ctx context.Context, err error) {
210 msg := err.Error()
211 if len(msg) > 300 {
212 msg = msg[:300]
213 }
214 _ = s.db.SetSetting(ctx, keyIntelError, msg)
215}
216
217func renderIntelFile(entries []string) []byte {
218 var b strings.Builder
219 b.WriteString("# managed by MiaoPanel - IP threat intelligence\n")
220 fmt.Fprintf(&b, "# entries: %d\n", len(entries))
221 for _, ip := range entries {
222 b.WriteString(ip)
223 b.WriteString(" 1;\n")
224 }
225 return []byte(b.String())
226}
227
228// fetchIntel downloads the feed and parses it. The response is capped so a
229// misbehaving endpoint cannot exhaust memory.
230func fetchIntel(ctx context.Context, url string) ([]string, error) {
231 ctx, cancel := context.WithTimeout(ctx, 60*time.Second)
232 defer cancel()
233 req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
234 if err != nil {
235 return nil, fmt.Errorf("订阅地址无效: %w", err)
236 }
237 req.Header.Set("Accept", "text/plain, */*")
238 req.Header.Set("User-Agent", "MiaoPanel-IPIntel/1.0")
239 resp, err := (&http.Client{Timeout: 60 * time.Second}).Do(req)
240 if err != nil {
241 return nil, fmt.Errorf("下载失败: %w", err)
242 }
243 defer resp.Body.Close()
244 if resp.StatusCode != http.StatusOK {
245 return nil, fmt.Errorf("下载失败:HTTP %d", resp.StatusCode)
246 }
247 return parseIntelList(io.LimitReader(resp.Body, intelMaxBody))
248}
249
250// parseIntelList accepts nginx deny/allow listings, plain IP lists and CSV-ish
251// lines. Anything that is not a valid address or subnet is ignored.
252func parseIntelList(r io.Reader) ([]string, error) {
253 scanner := bufio.NewScanner(r)
254 scanner.Buffer(make([]byte, 64<<10), 1<<20)
255 seen := make(map[string]bool)
256 out := make([]string, 0, 4096)
257 for scanner.Scan() {
258 line := scanner.Text()
259 if i := strings.IndexByte(line, '#'); i >= 0 {
260 line = line[:i]
261 }
262 line = strings.TrimSpace(line)
263 if line == "" {
264 continue
265 }
266 lower := strings.ToLower(line)
267 switch {
268 case strings.HasPrefix(lower, "allow"):
269 continue // "allow all;" and whitelist feeds are not used here
270 case strings.HasPrefix(lower, "deny "):
271 line = strings.TrimSpace(line[len("deny "):])
272 }
273 line = strings.TrimSpace(strings.TrimSuffix(strings.TrimSpace(line), ";"))
274 if !validIntelEntry(line) || seen[line] {
275 continue
276 }
277 seen[line] = true
278 out = append(out, line)
279 if len(out) >= intelMaxEntries {
280 break
281 }
282 }
283 if err := scanner.Err(); err != nil {
284 return nil, fmt.Errorf("解析订阅内容失败: %w", err)
285 }
286 return out, nil
287}
288
289// validIntelEntry accepts only bare IPs and CIDR blocks so the geo include can
290// never contain nginx directives or comments from upstream.
291func validIntelEntry(s string) bool {
292 if s == "" || len(s) > 64 {
293 return false
294 }
295 return validIP(s)
296}