package enforce import ( "context" "encoding/json" "net/netip" "os" "path/filepath" "sort" "sync" "sync/atomic" "time" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" ) // Config configures the engine. Mode must be observe or on (off means no engine). type Config struct { Mode string Path string // decision file UnbanPath string // unban requests read by the host (empty: unbanning is unavailable) StatePath string // enforce.json, empty: no persistence Host string // name of this instance, written in every line Threshold int // attack events in Window MaxPerMin int Share bool Trusted []netip.Prefix PeerHosts []string // host names or addresses of the peers InfraHosts []string // hub and other infrastructure hosts, never banned LocalAddrs func() []netip.Addr // default: the addresses of the local interfaces Resolve func(host string) []netip.Addr // default: literal parse only Crawler func(ip string, uas []string) bool // FCrDNS verified crawler Geo func(ip string) (string, uint32, string) // cc, asn, org Now func() time.Time // History hooks (all optional, supplied by the store). Rep func(ip string) (score float64, level core.Level, ok bool) // verdict of an address Tally func(ip string, from int64) (ssh, web int) // 24 h counts of one address Roster func(from int64) []Seen // addresses with malicious activity since from Tallies func(from int64) map[string]Tally // 24 h counts of every address, one pass Ready func() bool // false while sources still backfill } // Seen is one address with malicious activity, as listed by Config.Roster. type Seen struct { IP string Score float64 Level core.Level Jails []string Est Tally // estimate from per-day counters, used when the registry holds less } // Tally counts malicious events of one address in LongWindow. type Tally struct{ SSH, Web int } type longRec struct { ssh, web int at int64 // when loaded from the registry known bool fresh bool // just loaded: the current event is already counted } type cand struct { a netip.Addr d Decision } // Wire is a decision as exchanged between peers. type Wire struct { T int64 `json:"t"` IP string `json:"ip"` Reason string `json:"reason"` Score int `json:"score"` TTL int `json:"ttl"` } // MaxWire is the most decisions accepted or returned in one exchange. const MaxWire = 500 // Recent is one row of the report. type Recent struct { T int64 `json:"t"` IP string `json:"ip"` Reason string `json:"reason"` Score int `json:"score"` TTL int `json:"ttl"` Action string `json:"action"` // ban, would_ban, skip SkipReason string `json:"skip_reason"` Src string `json:"src"` CC string `json:"cc"` ASN uint32 `json:"asn"` Org string `json:"org"` } // Counts are the cumulative counters since start. type Counts struct { Decided int `json:"decided"` Written int `json:"written"` DroppedRate int `json:"dropped_rate"` AlreadyBlocked int `json:"already_blocked"` Skipped map[string]int `json:"skipped"` DroppedQueue int64 `json:"dropped_queue"` WriteErrors int `json:"write_errors"` } // Coverage tells how many attacking addresses were stopped, by whom. type Coverage struct { AttackIPs int `json:"attack_ips"` BlockedByFirewall int `json:"blocked_by_firewall"` BlockedByUrutau int `json:"blocked_by_urutau"` WouldBlock int `json:"would_block"` Unblocked int `json:"unblocked"` } // Report is what the API serves (mode and file status are added by the handler). type Report struct { Coverage Coverage `json:"coverage"` Counts Counts `json:"counts"` Recent []Recent `json:"recent"` } type aevt struct { ts int64 slug string } type ipState struct { ev []aevt ssh []int64 probes map[uint32]int64 // proto<<16|port -> last seen (unix) legit int64 uas []string lastAttack int64 f2bAt int64 urutauAt int64 wouldAt int64 banned int64 // fail2ban holds it until (unix), 0 none } type banRec struct { Until int64 `json:"until"` Offences int `json:"offences"` Last int64 `json:"last"` } type item struct { ev core.Event fam string } const ( maxIPs = 50000 maxEvents = 128 maxRecent = 200 skipQuiet = 10 * time.Minute banAssume = 24 * time.Hour peerRefresh = 10 * time.Minute maxPeerTTL = 6 * time.Hour peerConfirmAge = 7 * 24 * time.Hour maxTracked = 50000 // would and bans saveEvery = 30 * time.Second ) // Engine is the second firewall. type Engine struct { cfg Config log *logFile ch chan item dropQ atomic.Int64 sweeping atomic.Bool unlog *logFile mu sync.Mutex ips map[netip.Addr]*ipState bans map[netip.Addr]banRec would map[netip.Addr]int64 skipSeen map[netip.Addr]int64 excl Exclusions counts Counts recent []Recent shared []Wire minute int64 inMinute int dirty bool lastSave time.Time hostIPs map[string][]netip.Addr // last good resolution per host long map[netip.Addr]*longRec allows map[netip.Addr]int64 // operator allowances: address -> until (unix) unbans []UnbanWire queue []cand } // New builds an engine and loads its state. func New(c Config) *Engine { if c.Now == nil { c.Now = time.Now } if c.Threshold < 1 { c.Threshold = 5 } if c.MaxPerMin < 1 { c.MaxPerMin = 60 } if c.Resolve == nil { c.Resolve = func(h string) []netip.Addr { if a, err := netip.ParseAddr(h); err == nil { return []netip.Addr{a.Unmap()} } return nil } } e := &Engine{cfg: c, log: &logFile{path: c.Path}, ch: make(chan item, 4096), ips: map[netip.Addr]*ipState{}, bans: map[netip.Addr]banRec{}, would: map[netip.Addr]int64{}, skipSeen: map[netip.Addr]int64{}, counts: Counts{Skipped: map[string]int{}}, long: map[netip.Addr]*longRec{}, allows: map[netip.Addr]int64{}} e.unlog = &logFile{path: c.UnbanPath} e.hostIPs = map[string][]netip.Addr{} e.excl = Exclusions{Trusted: c.Trusted, Peers: map[netip.Addr]bool{}, Infra: map[netip.Addr]bool{}} e.refreshPeers() e.loadState() return e } // Mode returns the mode of the engine. func (e *Engine) Mode() string { return e.cfg.Mode } // Host is the name of this instance. func (e *Engine) Host() string { return e.cfg.Host } // Share reports whether decisions are exchanged with peers. func (e *Engine) Share() bool { return e.cfg.Share } // Threshold is the attack-event threshold in use. func (e *Engine) Threshold() int { return e.cfg.Threshold } // LogPath is the decision file. func (e *Engine) LogPath() string { return e.cfg.Path } // Observe is the ingestion hook: cheap, never blocks; a full queue drops the // event and counts it. func (e *Engine) Observe(ev core.Event, fam string) { switch ev.Cat { case core.Ban, core.SSHFail, core.Scanner, core.Exploit, core.BruteForce: case core.OK: if ev.FetchDest != "document" || ev.Status < 200 || ev.Status > 299 { return } default: return } select { case e.ch <- item{ev, fam}: default: e.dropQ.Add(1) } } // Run processes events until ctx is done. func (e *Engine) Run(ctx context.Context) { flush := time.NewTicker(5 * time.Second) peers := time.NewTicker(peerRefresh) defer flush.Stop() defer peers.Stop() defer e.log.close() sweepT := time.NewTicker(SweepEvery) defer sweepT.Stop() started := e.cfg.Now() swept := false for { select { case <-ctx.Done(): e.saveState() return case it := <-e.ch: e.handle(it.ev, it.fam) case <-sweepT.C: if swept { go e.Sweep() } case <-flush.C: e.maybeSave() if !swept && e.cfg.Now().Sub(started) >= 20*time.Second && (e.cfg.Ready == nil || e.cfg.Ready()) { swept = true go e.Sweep() } e.drain() case <-peers.C: e.refreshPeers() } } } // resolveKeep resolves h; an empty answer (DNS failure) keeps the last good one. func (e *Engine) resolveKeep(h string, into map[netip.Addr]bool) { as := e.cfg.Resolve(h) e.mu.Lock() if len(as) == 0 { as = e.hostIPs[h] } else { e.hostIPs[h] = as } e.mu.Unlock() for _, a := range as { into[a.Unmap()] = true } } func (e *Engine) refreshPeers() { m := map[netip.Addr]bool{} for _, h := range e.cfg.PeerHosts { e.resolveKeep(h, m) } infra := map[netip.Addr]bool{} for _, h := range e.cfg.InfraHosts { e.resolveKeep(h, infra) } la := e.cfg.LocalAddrs if la == nil { la = interfaceAddrs } for _, a := range la() { infra[a.Unmap()] = true } e.mu.Lock() e.excl.Peers = m e.excl.Infra = infra e.mu.Unlock() } func (e *Engine) stateOf(a netip.Addr) *ipState { st := e.ips[a] if st == nil { if len(e.ips) >= maxIPs { e.evict() } st = &ipState{} e.ips[a] = st } return st } func (e *Engine) evict() { cut := e.cfg.Now().Add(-24 * time.Hour).Unix() for a, st := range e.ips { if max(st.lastAttack, st.f2bAt, st.legit) < cut { delete(e.ips, a) } } for a := range e.ips { if len(e.ips) < maxIPs/2 { break } delete(e.ips, a) } if len(e.skipSeen) > 10000 { e.skipSeen = map[netip.Addr]int64{} } } // trimMaps prunes would (expired or older than 24 h) and bans (older than 30 d) // and caps both at maxTracked, dropping the least recent first; the lock is held. func (e *Engine) trimMaps(now time.Time) { cutW := now.Unix() for a, u := range e.would { if u < cutW || u < now.Add(-24*time.Hour).Unix() { delete(e.would, a) } } if len(e.would) > maxTracked { type kv struct { a netip.Addr t int64 } l := make([]kv, 0, len(e.would)) for a, u := range e.would { l = append(l, kv{a, u}) } sort.Slice(l, func(i, j int) bool { return l[i].t < l[j].t }) for _, x := range l[:len(l)-maxTracked/2] { delete(e.would, x.a) } } cutB := now.Add(-30 * 24 * time.Hour).Unix() for a, b := range e.bans { if b.Last < cutB { delete(e.bans, a) } } if len(e.bans) > maxTracked { type kv struct { a netip.Addr t int64 } l := make([]kv, 0, len(e.bans)) for a, b := range e.bans { l = append(l, kv{a, b.Last}) } sort.Slice(l, func(i, j int) bool { return l[i].t < l[j].t }) for _, x := range l[:len(l)-maxTracked/2] { delete(e.bans, x.a) } } } // process handles one classified event (called by Run, or directly by tests). func (e *Engine) process(ev core.Event, fam string) { a, err := netip.ParseAddr(ev.IP) if err != nil { return } a = a.Unmap().WithZone("") now := e.cfg.Now() ts := ev.Time.Unix() e.mu.Lock() defer e.mu.Unlock() switch { case ev.Cat == core.Ban: if ts < now.Add(-30*24*time.Hour).Unix() { return } st := e.stateOf(a) switch { case ev.Unban: st.banned = 0 default: if ev.Jail == "urutau" { // our own decision, enforced by the host jail st.urutauAt = max(st.urutauAt, ts) } else { st.banned = max(st.banned, ev.Time.Add(banAssume).Unix()) st.f2bAt = max(st.f2bAt, ts) } } return case LegitVisit(ev): if ts >= now.Add(-LegitWindow).Unix() { e.stateOf(a).legit = max(e.stateOf(a).legit, ts) } return case ev.Cat == core.SSHFail: case ev.Source == "probe" && ev.Cat == core.Scanner: e.processProbe(a, ev, now) return case CountsAsAttack(ev): default: return } if ts < now.Add(-30*24*time.Hour).Unix() { return } st := e.stateOf(a) st.lastAttack = max(st.lastAttack, ts) if ts < now.Add(-Window).Unix() { // a replayed old event: coverage only return } cut := now.Add(-Window).Unix() slug, crit := attackSlug(ev, fam) if ev.Cat == core.SSHFail { st.ssh = prune(append(st.ssh, ts), cut) } else { st.ev = append(st.ev, aevt{ts, slug}) k := 0 for _, x := range st.ev { if x.ts >= cut { st.ev[k] = x k++ } } st.ev = st.ev[:k] if len(st.ev) > maxEvents { st.ev = st.ev[len(st.ev)-maxEvents:] } } if ev.UA != "" && len(st.uas) < 3 { ua := ev.UA if len(ua) > 200 { ua = ua[:200] } dup := false for _, u := range st.uas { dup = dup || u == ua } if !dup { st.uas = append(st.uas, ua) } } lr := e.long[a] if lr != nil { if lr.fresh { lr.fresh = false } else if ev.Cat == core.SSHFail { lr.ssh++ } else { lr.web++ } } crits := 0 for _, x := range st.ev { if criticalReasons[x.slug] { crits++ } } in := Input{Now: now, Attacks: len(st.ev), Top: topSlug(st.ev), SSHFails: len(st.ssh), Crits: crits, Legit: st.legit >= now.Add(-LegitWindow).Unix(), Exclude: e.exclude(a, now)} if crit { in.Crit = slug } if lr != nil { in.Known, in.SSH24, in.Web24 = lr.known, lr.ssh, lr.web } e.fill(a, st, &in, now) d := Decide(in, Params{Threshold: e.cfg.Threshold}) if d.Action == ActBan && e.cfg.Crawler != nil && len(st.uas) > 0 && e.cfg.Crawler(a.String(), st.uas) { in.Exclude = SkipCrawler d = Decide(in, Params{Threshold: e.cfg.Threshold}) } e.apply(a, st, d, "local", now) } func (e *Engine) fill(a netip.Addr, st *ipState, in *Input, now time.Time) { in.Banned = st.banned > now.Unix() if b, ok := e.bans[a]; ok { in.Offences = b.Offences if b.Until > now.Unix() && e.cfg.Mode == ModeOn { in.Active = true } if now.Unix() > b.Until+30*24*3600 { in.Offences = 0 } } if u, ok := e.would[a]; ok && u > now.Unix() && e.cfg.Mode == ModeObserve { in.Active = true } } func prune(l []int64, cut int64) []int64 { k := 0 for _, t := range l { if t >= cut { l[k] = t k++ } } l = l[:k] if len(l) > maxEvents { l = l[len(l)-maxEvents:] } return l } func topSlug(evs []aevt) string { cnt := map[string]int{} best, bn := "", 0 for _, x := range evs { cnt[x.slug]++ if cnt[x.slug] >= bn { best, bn = x.slug, cnt[x.slug] } } return best } // apply records the outcome of a decision; the lock is held. func (e *Engine) apply(a netip.Addr, st *ipState, d Decision, src string, now time.Time) { switch d.Action { case ActSkip, ActAlready: if until, ok := e.skipSeen[a]; ok && until > now.Unix() { return } e.skipSeen[a] = now.Add(skipQuiet).Unix() r := Recent{T: now.Unix(), IP: a.String(), Action: "skip", SkipReason: d.Skip, Src: src} if d.Action == ActAlready { e.counts.AlreadyBlocked++ r.SkipReason = "already_blocked" } else { e.counts.Skipped[d.Skip]++ } e.addRecent(a, r) case ActBan: e.counts.Decided++ m := now.Unix() / 60 if m != e.minute { e.minute, e.inMinute = m, 0 } if e.inMinute >= e.cfg.MaxPerMin { e.counts.DroppedRate++ return } e.inMinute++ r := Recent{T: now.Unix(), IP: a.String(), Reason: d.Reason, Score: d.Score, TTL: int(d.TTL / time.Second), Src: src} if e.cfg.Mode != ModeOn { r.Action = "would_ban" if len(e.would) >= maxTracked { e.trimMaps(now) } e.would[a] = now.Add(d.TTL).Unix() st.wouldAt = now.Unix() e.addRecent(a, r) return } line, err := FormatLine(now, a, d.Reason, d.Score, d.TTL, e.cfg.Host, src) if err == nil { err = e.log.write(line) } if err != nil { e.counts.WriteErrors++ return } r.Action = "ban" e.counts.Written++ if len(e.bans) >= maxTracked { e.trimMaps(now) } b := e.bans[a] if now.Unix() > b.Until+30*24*3600 { b.Offences = 0 } if src == "local" { b.Offences++ e.shared = append(e.shared, Wire{T: now.Unix(), IP: a.String(), Reason: d.Reason, Score: d.Score, TTL: r.TTL}) if len(e.shared) > MaxWire { e.shared = e.shared[len(e.shared)-MaxWire:] } } b.Until, b.Last = now.Add(d.TTL).Unix(), now.Unix() e.bans[a] = b st.urutauAt = now.Unix() e.dirty = true e.addRecent(a, r) } } func (e *Engine) addRecent(a netip.Addr, r Recent) { if e.cfg.Geo != nil { r.CC, r.ASN, r.Org = e.cfg.Geo(a.String()) } e.recent = append(e.recent, r) if len(e.recent) > maxRecent*2 { e.recent = append([]Recent(nil), e.recent[len(e.recent)-maxRecent:]...) } } // LocalSince returns the decisions this instance wrote since the unix time. func (e *Engine) LocalSince(since int64) []Wire { e.mu.Lock() defer e.mu.Unlock() out := []Wire{} for _, w := range e.shared { if w.T >= since { out = append(out, w) } } return out } // AcceptPeer applies decisions received from a peer, after this instance's own // exclusions. It returns how many were accepted for the policy (written or // would-ban) and how many were refused as malformed. func (e *Engine) AcceptPeer(name string, in []Wire) (accepted, invalid int) { if len(in) > MaxWire { in = in[:MaxWire] } src := "peer:" + token(name, "peer") now := e.cfg.Now() e.mu.Lock() defer e.mu.Unlock() for _, w := range in { a, err := netip.ParseAddr(w.IP) if err != nil || !ValidReason(w.Reason) || !Public(a) { invalid++ continue } a = a.Unmap().WithZone("") ttl := min(time.Duration(min(max(w.TTL, 60), 7*24*3600))*time.Second, maxPeerTTL) if w.T > 0 && w.T+int64(ttl/time.Second) < now.Unix() { continue // already expired } st := e.stateOf(a) in := Input{Now: now, Crit: w.Reason, Crits: CritHits, Exclude: e.exclude(a, now)} if in.Exclude == "" && st.lastAttack < now.Add(-peerConfirmAge).Unix() { in.Exclude = SkipUnconfirmed // a peer's word alone never bans: this node must have seen the address attack } e.fill(a, st, &in, now) d := Decide(in, Params{}) if d.Action == ActBan { d.Reason, d.Score, d.TTL = w.Reason, max(0, min(100, w.Score)), ttl accepted++ } e.apply(a, st, d, src, now) } return accepted, invalid } // Report summarizes the activity since the unix time from. func (e *Engine) Report(from int64) Report { var roster []Seen if e.cfg.Roster != nil { roster = e.cfg.Roster(from) // outside the lock: it walks the store } e.mu.Lock() defer e.mu.Unlock() var cv Coverage if e.cfg.Roster != nil { cv = e.coverageOf(roster, from) } for _, st := range e.ips { if e.cfg.Roster != nil { break } if st.lastAttack < from { continue } cv.AttackIPs++ switch { case st.f2bAt > 0 && st.f2bAt >= from: cv.BlockedByFirewall++ case st.urutauAt > 0 && st.urutauAt >= from: cv.BlockedByUrutau++ case st.wouldAt > 0 && st.wouldAt >= from: cv.WouldBlock++ default: cv.Unblocked++ } } c := e.counts c.Skipped = map[string]int{SkipOperator: 0, SkipTrusted: 0, SkipPrivate: 0, SkipCrawler: 0, SkipLegit: 0, SkipPeer: 0, SkipInfra: 0, SkipUnconfirmed: 0} for k, v := range e.counts.Skipped { c.Skipped[k] = v } c.DroppedQueue = e.dropQ.Load() rec := []Recent{} for i := len(e.recent) - 1; i >= 0 && len(rec) < maxRecent; i-- { if e.recent[i].T >= from { rec = append(rec, e.recent[i]) } } return Report{Coverage: cv, Counts: c, Recent: rec} } type stateFile struct { V int `json:"v"` Bans map[string]banRec `json:"bans"` Allows map[string]int64 `json:"allows,omitempty"` } func (e *Engine) loadState() { if e.cfg.StatePath == "" { return } b, err := os.ReadFile(e.cfg.StatePath) if err != nil { return } var sf stateFile if json.Unmarshal(b, &sf) != nil { return } cut := e.cfg.Now().Add(-30 * 24 * time.Hour).Unix() for k, v := range sf.Bans { if a, err := netip.ParseAddr(k); err == nil && v.Last >= cut && v.Offences >= 0 && v.Offences < 1000 { e.bans[a.Unmap()] = v } } nowU := e.cfg.Now().Unix() for k, u := range sf.Allows { if a, err := netip.ParseAddr(k); err == nil && u > nowU && u <= nowU+MaxAllow { e.allows[a.Unmap()] = u } } } // maybeSave writes the state at most every saveEvery. func (e *Engine) maybeSave() { if e.cfg.Now().Sub(e.lastSave) < saveEvery { return } e.saveState() } // saveState writes enforce.json atomically when something changed. func (e *Engine) saveState() { if e.cfg.StatePath == "" { return } e.mu.Lock() if !e.dirty { e.mu.Unlock() return } e.lastSave = e.cfg.Now() e.trimMaps(e.lastSave) sf := stateFile{V: 1, Bans: map[string]banRec{}, Allows: map[string]int64{}} for a, b := range e.bans { sf.Bans[a.String()] = b } for a, u := range e.allows { if u > e.lastSave.Unix() { sf.Allows[a.String()] = u } } e.dirty = false e.mu.Unlock() b, _ := json.Marshal(sf) tmp := e.cfg.StatePath + ".tmp" if err := os.MkdirAll(filepath.Dir(tmp), 0o700); err == nil { if err = os.WriteFile(tmp, b, 0o600); err == nil { if err = os.Rename(tmp, e.cfg.StatePath); err == nil { return } } } e.mu.Lock() e.dirty = true e.mu.Unlock() } // processProbe counts the distinct ports a network probe touched in Window; a // scan of PortScanPorts or more is a ban. Probes never count as web attacks. func (e *Engine) processProbe(a netip.Addr, ev core.Event, now time.Time) { ts := ev.Time.Unix() cut := now.Add(-Window).Unix() if ts < cut || ev.Port == 0 { return } st := e.stateOf(a) st.lastAttack = max(st.lastAttack, ts) if st.probes == nil { st.probes = map[uint32]int64{} } var proto uint32 if ev.Proto == "udp" { proto = 1 } k := proto<<16 | uint32(ev.Port) st.probes[k] = max(st.probes[k], ts) for key, t := range st.probes { if t < cut { delete(st.probes, key) } } in := Input{Now: now, Probes: len(st.probes), Exclude: e.exclude(a, now)} e.fill(a, st, &in, now) e.apply(a, st, Decide(in, Params{Threshold: e.cfg.Threshold}), "local", now) }