package app import ( "bufio" "context" "encoding/json" "fmt" "io" "log/slog" "net" "net/netip" "net/url" "os" "path/filepath" "strings" "time" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" ) // newEnforce builds the second firewall and hooks it into the store; nil when off. func newEnforce(c Config, st *store.Store, peers []fed.Peer, en enricher, ready func() bool) *enforce.Engine { mode := strings.ToLower(c.Enforce) if mode != enforce.ModeObserve && mode != enforce.ModeOn { return nil } trusted, _ := core.ParseCIDRs(c.Ignore + "," + c.Trusted) var hosts []string for _, p := range peers { if u, err := url.Parse(p.URL); err == nil && u.Hostname() != "" { hosts = append(hosts, u.Hostname()) } } e := enforce.New(enforce.Config{ Mode: mode, Path: c.EnforceLog, UnbanPath: unbanLogPath(c), StatePath: filepath.Join(c.DataDir, "enforce.json"), Host: c.Name, Threshold: c.EnforceThreshold, MaxPerMin: c.EnforceMaxPerMin, Share: strings.EqualFold(c.EnforceShare, "on"), Trusted: trusted, PeerHosts: hosts, InfraHosts: hosts, Resolve: resolveHost, Crawler: func(ip string, uas []string) bool { v := st.FCrDNS(ip, uas); return v != nil && *v }, Rep: st.Reputation, Tally: func(ip string, from int64) (int, int) { t := st.AttackTally(ip, from); return t.SSH, t.Web }, Roster: func(from int64) []enforce.Seen { rows := st.AttackRoster(from) out := make([]enforce.Seen, len(rows)) for i, r := range rows { out[i] = enforce.Seen{IP: r.IP, Score: r.Score, Level: r.Level, Jails: r.Jails, Est: enforce.Tally{SSH: r.Est.SSH, Web: r.Est.Web}} } return out }, Tallies: func(from int64) map[string]enforce.Tally { m := st.AttackTallies(from) out := make(map[string]enforce.Tally, len(m)) for k, v := range m { out[k] = enforce.Tally{SSH: v.SSH, Web: v.Web} } return out }, Ready: ready, Geo: func(ip string) (string, uint32, string) { if en.g == nil { return "", 0, "" } g := en.Geo(ip) return g.CC, g.ASN, g.ASOrg }, }) st.SetIngestHook(e.Observe) return e } func resolveHost(h string) []netip.Addr { if a, err := netip.ParseAddr(h); err == nil { return []netip.Addr{a.Unmap()} } ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() ips, err := net.DefaultResolver.LookupNetIP(ctx, "ip", h) if err != nil { return nil } for i := range ips { ips[i] = ips[i].Unmap() } return ips } // shareDecisions pulls the decisions of every peer and pushes the local ones, every 30 s. func shareDecisions(ctx context.Context, hub *fed.Hub, e *enforce.Engine, log *slog.Logger) { pulled := map[string]int64{} pushed := map[string]int64{} pushedUn := map[string]int64{} t := time.NewTicker(30 * time.Second) defer t.Stop() for { for _, p := range hub.Peers { start := time.Now().Unix() var in struct { Decisions []enforce.Wire `json:"decisions"` } if err := hub.Get(ctx, p, fmt.Sprintf("/api/v1/peer/decisions?since=%d", pulled[p.Name]), &in); err == nil { e.AcceptPeer(p.Name, in.Decisions) pulled[p.Name] = start - 5 } else if ctx.Err() == nil { log.Debug("enforce: pull failed", "peer", p.Name, "err", err) } if mine := e.LocalSince(pushed[p.Name]); len(mine) > 0 { if err := hub.PostJSON(ctx, p, "/api/v1/peer/decisions?from="+url.QueryEscape(e.Host()), map[string]any{"decisions": mine}); err == nil { pushed[p.Name] = start } else if ctx.Err() == nil { log.Debug("enforce: push failed", "peer", p.Name, "err", err) } } } for _, p := range hub.Peers { if mine := e.UnbansSince(pushedUn[p.Name]); len(mine) > 0 { start := time.Now().Unix() if err := hub.PostJSON(ctx, p, "/api/v1/peer/unban?from="+url.QueryEscape(e.Host()), map[string]any{"unbans": mine}); err == nil { pushedUn[p.Name] = start } else if ctx.Err() == nil { log.Debug("enforce: unban push failed", "peer", p.Name, "err", err) } } } select { case <-ctx.Done(): return case <-t.C: } } } // doctorEnforce reports the mode of the second firewall and its file. func doctorEnforce(c Config, add func(name, status, detail string)) { mode := strings.ToLower(c.Enforce) if mode == "" || mode == "off" { add("enforce", "off", "disabled (--enforce=off)") return } w := enforce.Writable(c.EnforceLog) detail := fmt.Sprintf("mode=%s share=%s threshold=%d file=%s writable=%v", mode, strings.ToLower(orDefault(c.EnforceShare, "off")), c.EnforceThreshold, c.EnforceLog, w) switch { case mode == "on" && !w: add("enforce", "fail", detail) case !w: add("enforce", "warn", detail) default: add("enforce", "ok", detail) } if mode == "on" { if n, tot := cloudflareClients(c.TraefikLog); n > 0 { add("enforce-cdn", "warn", fmt.Sprintf("%d of the last %d requests in %s come from Cloudflare addresses: Traefik is not "+ "restoring the real client IP (set entryPoints.*.forwardedHeaders.trustedIPs to the Cloudflare ranges); "+ "Cloudflare is never banned, but the real attackers stay invisible", n, tot, c.TraefikLog)) } } } // cloudflareClients counts, in the tail of the Traefik JSON access log, the // requests whose ClientHost is a Cloudflare address. func cloudflareClients(path string) (cf, total int) { if path == "" { return 0, 0 } f, err := os.Open(path) if err != nil { return 0, 0 } defer f.Close() const tail = 512 << 10 if fi, err := f.Stat(); err == nil && fi.Size() > tail { f.Seek(fi.Size()-tail, io.SeekStart) } sc := bufio.NewScanner(f) sc.Buffer(make([]byte, 0, 64<<10), 1<<20) for sc.Scan() { var l struct { ClientHost string `json:"ClientHost"` } if json.Unmarshal(sc.Bytes(), &l) != nil || l.ClientHost == "" { continue } a, err := netip.ParseAddr(l.ClientHost) if err != nil { continue } total++ if enforce.IsCloudflare(a) { cf++ } } return cf, total } // unbanLogPath is --enforce-unban-log, or unban.log next to --enforce-log. func unbanLogPath(c Config) string { if c.EnforceUnbanLog != "" { return c.EnforceUnbanLog } if c.EnforceLog == "" { return "" } return filepath.Join(filepath.Dir(c.EnforceLog), "unban.log") }