package waf import ( "bufio" "context" "errors" "fmt" "io" "net/http" "os" "path/filepath" "strings" "time" "github.com/miaopanel/miaopanel/internal/config" ) // IP threat intelligence: a subscription URL (for example the Chaitin // "IP 组订阅" feed) is fetched once a day and rendered as an nginx geo map. // Large lists must never be rendered into every site block, so the entries // live in a standalone include file next to the vhost directory. const ( keyIntelEnabled = "waf.intel.enabled" keyIntelURL = "waf.intel.url" keyIntelHour = "waf.intel.hour" keyIntelLast = "waf.intel.last_sync" keyIntelAttempt = "waf.intel.last_attempt" keyIntelCount = "waf.intel.last_count" keyIntelError = "waf.intel.last_error" intelMaxEntries = 200000 intelMaxBody = 32 << 20 intelMinDrop = 100 // only guard against drop-outs once the list is meaningful ) // IntelSettings is the operator facing configuration plus the last sync state. type IntelSettings struct { Enabled bool `json:"enabled"` URL string `json:"url"` Hour int `json:"hour"` LastSync int64 `json:"last_sync"` LastCount int `json:"last_count"` LastError string `json:"last_error"` Count int `json:"count"` LastAttempt int64 `json:"last_attempt"` } // IntelPath returns the include file consumed by the http level geo map. func (s *Service) IntelPath() string { return filepath.Join(s.cfg.Nginx.VhostDir, "intel", "blocklist.conf") } // IntelSettings loads the persisted configuration and sync state. func (s *Service) IntelSettings(ctx context.Context) (IntelSettings, error) { st := IntelSettings{ Enabled: s.getBool(ctx, keyIntelEnabled, false), URL: s.getText(ctx, keyIntelURL), Hour: s.getInt(ctx, keyIntelHour, 4), LastSync: int64(s.getInt(ctx, keyIntelLast, 0)), LastCount: s.getInt(ctx, keyIntelCount, 0), LastError: s.getText(ctx, keyIntelError), LastAttempt: int64(s.getInt(ctx, keyIntelAttempt, 0)), } st.Count = st.LastCount if st.Hour < 0 || st.Hour > 23 { st.Hour = 4 } return st, nil } func (s *Service) getText(ctx context.Context, key string) string { v, err := s.db.Setting(ctx, key, "") if err != nil { return "" } return v } // SaveIntel validates and persists the configuration, then re-renders nginx so // enabling the feature takes effect immediately. func (s *Service) SaveIntel(ctx context.Context, st IntelSettings) error { st.URL = strings.TrimSpace(st.URL) if st.Hour < 0 || st.Hour > 23 { return errors.New("同步时间需在 0-23 点之间") } if st.Enabled { if st.URL == "" { return errors.New("请填写 IP 情报订阅地址") } if !validFeedURL(st.URL) { return errors.New("订阅地址必须是 http:// 或 https:// 链接") } } if len(st.URL) > 2048 || strings.ContainsAny(st.URL, "\r\n\t \"'") { return errors.New("订阅地址不合法") } pairs := map[string]string{ keyIntelEnabled: boolString(st.Enabled), keyIntelURL: st.URL, keyIntelHour: fmt.Sprintf("%d", st.Hour), } for k, v := range pairs { if err := s.db.SetSetting(ctx, k, v); err != nil { return err } } // nginx fails to start when the geo include is missing, so the (possibly // empty) file must exist before the configuration is rendered. if err := s.EnsureIntelFile(); err != nil { return err } return s.Apply(ctx) } func validFeedURL(u string) bool { return strings.HasPrefix(u, "http://") || strings.HasPrefix(u, "https://") } // EnsureIntelFile creates an empty include file when it does not exist yet. func (s *Service) EnsureIntelFile() error { path := s.IntelPath() if _, err := os.Stat(path); err == nil { return nil } return config.WriteFileAtomic(path, []byte("# managed by MiaoPanel - empty IP intelligence list\n"), 0o644) } // IntelDue reports whether the daily sync is pending. A missed window (panel // was down at the configured hour) is caught up on the next check. func (s *Service) IntelDue(now time.Time) bool { st, err := s.IntelSettings(context.Background()) if err != nil || !st.Enabled || st.URL == "" { return false } if st.LastSync > 0 { last := time.Unix(st.LastSync, 0) if last.Format("2006-01-02") == now.Format("2006-01-02") { return false } } // Failed attempts back off to one retry per half hour instead of hammering // an unreachable feed every scheduler tick. if st.LastAttempt > 0 && now.Sub(time.Unix(st.LastAttempt, 0)) < 30*time.Minute { return false } return now.Hour() >= st.Hour } // SyncIntel downloads the feed and replaces the include file. The previous // list is kept when the download, the content or the nginx validation fails. func (s *Service) SyncIntel(ctx context.Context, force bool) error { st, err := s.IntelSettings(ctx) if err != nil { return err } if !st.Enabled { return errors.New("IP 情报库未启用") } if st.URL == "" { return errors.New("请先填写订阅地址") } _ = s.db.SetSetting(ctx, keyIntelAttempt, fmt.Sprintf("%d", time.Now().Unix())) entries, err := fetchIntel(ctx, st.URL) if err != nil { s.recordIntelError(ctx, err) return err } if len(entries) == 0 { err = errors.New("订阅返回空列表,已保留旧库") s.recordIntelError(ctx, err) return err } // A truncated feed (network hiccup, upstream outage) must not wipe the // protection. Operators can still force a replace explicitly. if !force && st.LastCount >= intelMinDrop && len(entries)*2 < st.LastCount { err = fmt.Errorf("订阅条数异常下降(%d → %d),已保留旧库", st.LastCount, len(entries)) s.recordIntelError(ctx, err) return err } path := s.IntelPath() previous, readErr := os.ReadFile(path) if err := config.WriteFileAtomic(path, renderIntelFile(entries), 0o644); err != nil { s.recordIntelError(ctx, err) return fmt.Errorf("写入情报库失败: %w", err) } if err := s.Apply(ctx); err != nil { if readErr == nil { _ = config.WriteFileAtomic(path, previous, 0o644) } s.recordIntelError(ctx, err) return fmt.Errorf("应用情报库失败,已回滚: %w", err) } now := time.Now().Unix() for k, v := range map[string]string{ keyIntelLast: fmt.Sprintf("%d", now), keyIntelCount: fmt.Sprintf("%d", len(entries)), keyIntelError: "", } { if err := s.db.SetSetting(ctx, k, v); err != nil { return err } } return nil } func (s *Service) recordIntelError(ctx context.Context, err error) { msg := err.Error() if len(msg) > 300 { msg = msg[:300] } _ = s.db.SetSetting(ctx, keyIntelError, msg) } func renderIntelFile(entries []string) []byte { var b strings.Builder b.WriteString("# managed by MiaoPanel - IP threat intelligence\n") fmt.Fprintf(&b, "# entries: %d\n", len(entries)) for _, ip := range entries { b.WriteString(ip) b.WriteString(" 1;\n") } return []byte(b.String()) } // fetchIntel downloads the feed and parses it. The response is capped so a // misbehaving endpoint cannot exhaust memory. func fetchIntel(ctx context.Context, url string) ([]string, error) { ctx, cancel := context.WithTimeout(ctx, 60*time.Second) defer cancel() req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { return nil, fmt.Errorf("订阅地址无效: %w", err) } req.Header.Set("Accept", "text/plain, */*") req.Header.Set("User-Agent", "MiaoPanel-IPIntel/1.0") resp, err := (&http.Client{Timeout: 60 * time.Second}).Do(req) if err != nil { return nil, fmt.Errorf("下载失败: %w", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("下载失败:HTTP %d", resp.StatusCode) } return parseIntelList(io.LimitReader(resp.Body, intelMaxBody)) } // parseIntelList accepts nginx deny/allow listings, plain IP lists and CSV-ish // lines. Anything that is not a valid address or subnet is ignored. func parseIntelList(r io.Reader) ([]string, error) { scanner := bufio.NewScanner(r) scanner.Buffer(make([]byte, 64<<10), 1<<20) seen := make(map[string]bool) out := make([]string, 0, 4096) for scanner.Scan() { line := scanner.Text() if i := strings.IndexByte(line, '#'); i >= 0 { line = line[:i] } line = strings.TrimSpace(line) if line == "" { continue } lower := strings.ToLower(line) switch { case strings.HasPrefix(lower, "allow"): continue // "allow all;" and whitelist feeds are not used here case strings.HasPrefix(lower, "deny "): line = strings.TrimSpace(line[len("deny "):]) } line = strings.TrimSpace(strings.TrimSuffix(strings.TrimSpace(line), ";")) if !validIntelEntry(line) || seen[line] { continue } seen[line] = true out = append(out, line) if len(out) >= intelMaxEntries { break } } if err := scanner.Err(); err != nil { return nil, fmt.Errorf("解析订阅内容失败: %w", err) } return out, nil } // validIntelEntry accepts only bare IPs and CIDR blocks so the geo include can // never contain nginx directives or comments from upstream. func validIntelEntry(s string) bool { if s == "" || len(s) > 64 { return false } return validIP(s) }