package enforce import ( "net/netip" "sort" "time" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" ) // SweepEvery is the period of the proactive sweep. const SweepEvery = 10 * time.Minute const ( longTTL = 10 * time.Minute // a loaded 24 h count is trusted this long, then reloaded maxLong = 20000 jailOurs = "urutau" ) // IsKnown reports whether a verdict alone justifies a ban. func IsKnown(score float64, level core.Level) bool { return level == core.LevelHostile || (level == core.LevelSuspicious && score >= KnownSuspiciousScore) } // handle is the live path of one event: it loads the history of a malicious // address (outside the lock, at most once per longTTL) and then decides. func (e *Engine) handle(ev core.Event, fam string) { e.prefetch(ev) e.process(ev, fam) } func (e *Engine) prefetch(ev core.Event) { if e.cfg.Rep == nil && e.cfg.Tally == nil { return } if ev.Cat != core.SSHFail && ev.Cat != core.SSHProbe && !CountsAsAttack(ev) { return } a, err := netip.ParseAddr(ev.IP) if err != nil { return } a = a.Unmap().WithZone("") now := e.cfg.Now() if ev.Time.Unix() < now.Add(-Window).Unix() { // replayed history: no decision, no query return } e.mu.Lock() skip := e.excl.Excluded(a) != "" lr := e.long[a] stale := lr == nil || now.Unix()-lr.at > int64(longTTL/time.Second) e.mu.Unlock() if skip { return } var known bool if e.cfg.Rep != nil { if sc, lv, ok := e.cfg.Rep(a.String()); ok { known = IsKnown(sc, lv) } } var tl Tally if stale && e.cfg.Tally != nil { tl = e.cfg.Tally(a.String(), now.Add(-WeekWindow).Unix()) } e.mu.Lock() defer e.mu.Unlock() if len(e.long) >= maxLong { cut := now.Add(-LongWindow).Unix() for k, v := range e.long { if v.at < cut { delete(e.long, k) } } if len(e.long) >= maxLong { e.long = map[netip.Addr]*longRec{} } } lr = e.long[a] if lr == nil { lr = &longRec{} e.long[a] = lr } lr.known = known if stale { lr.ssh, lr.web, lr.probe, lr.ssh7, lr.web7, lr.probe7 = tl.SSH, tl.Web, tl.Probe, max(tl.SSH7, tl.SSH), max(tl.Web7, tl.Web), max(tl.Probe7, tl.Probe) lr.at, lr.fresh = now.Unix(), true } } // Sweep evaluates the addresses with malicious activity in the last 24 h that // nothing blocks yet and queues a ban for those the long rules justify. The // queue is drained at most MaxPerMin per minute by Run. func (e *Engine) Sweep() { if e.cfg.Roster == nil { return } if !e.sweeping.CompareAndSwap(false, true) { return } defer e.sweeping.Store(false) now := e.cfg.Now() from := now.Add(-WeekWindow).Unix() roster := e.cfg.Roster(from) var tallies map[string]Tally if e.cfg.Tallies != nil { tallies = e.cfg.Tallies(from) } sort.SliceStable(roster, func(i, j int) bool { return roster[i].Score > roster[j].Score }) var q []cand e.mu.Lock() defer e.mu.Unlock() for _, r := range roster { if len(r.Jails) > 0 { continue // fail2ban or our own jail holds it } a, err := netip.ParseAddr(r.IP) if err != nil { continue } a = a.Unmap().WithZone("") st := e.stateOf(a) t := tallies[a.String()] t = Tally{max(t.SSH, r.Est.SSH), max(t.Web, r.Est.Web), max(t.Probe, r.Est.Probe), max(t.SSH7, r.Est.SSH7, t.SSH), max(t.Web7, r.Est.Web7, t.Web), max(t.Probe7, r.Est.Probe7, t.Probe)} in := Input{Now: now, Known: IsKnown(r.Score, r.Level), SSH24: t.SSH, Web24: t.Web, Probe24: t.Probe, SSH7: t.SSH7, Web7: t.Web7, Probe7: t.Probe7, Neighbor: e.neighborBanned(a, now) >= NeighborIPs && r.Last >= now.Add(-LongWindow).Unix() && r.Last > 0, Legit: st.legit >= now.Add(-LegitWindow).Unix(), Exclude: e.excl.Excluded(a)} e.fill(a, st, &in, now) d := Decide(in, Params{Threshold: e.cfg.Threshold}) if d.Action == ActBan && e.cfg.Crawler != nil && e.cfg.Crawler(a.String(), st.uas) { in.Exclude = SkipCrawler d = Decide(in, Params{Threshold: e.cfg.Threshold}) } switch d.Action { case ActBan: q = append(q, cand{a, d}) case ActSkip: e.apply(a, st, d, "sweep", now) } } e.queue = q } // drain applies queued sweep bans while this minute has budget left. func (e *Engine) drain() { e.mu.Lock() defer e.mu.Unlock() now := e.cfg.Now() for len(e.queue) > 0 { if m := now.Unix() / 60; m != e.minute { e.minute, e.inMinute = m, 0 } if e.inMinute >= e.cfg.MaxPerMin { return } c := e.queue[0] e.queue = e.queue[1:] st := e.stateOf(c.a) if st.banned > now.Unix() { continue } in := Input{Now: now} e.fill(c.a, st, &in, now) if in.Active { continue } c.d.TTL = TTLFor(in.Offences) e.apply(c.a, st, c.d, "local", now) } } // coverageOf computes the coverage from the registry's roster plus the engine's // durable decisions; the lock is held. func (e *Engine) coverageOf(roster []Seen, from int64) Coverage { var cv Coverage for _, r := range roster { cv.AttackIPs++ a, _ := netip.ParseAddr(r.IP) a = a.Unmap().WithZone("") f2b, ours := false, false for _, j := range r.Jails { if j == jailOurs { ours = true } else { f2b = true } } if b, ok := e.bans[a]; ok && b.Last >= from { ours = true } st := e.ips[a] repeat := r.Events >= 2 if repeat { cv.Repeat++ } else { cv.OneShot++ } switch { case f2b: cv.BlockedByFirewall++ case ours || (st != nil && st.urutauAt >= from && st.urutauAt > 0): cv.BlockedByUrutau++ case e.would[a] > 0 || (st != nil && st.wouldAt >= from && st.wouldAt > 0): cv.WouldBlock++ default: cv.Unblocked++ if repeat { cv.RepeatUnblocked++ } } } return cv }