package enforce import ( "fmt" "net/netip" "os" "path/filepath" "strings" "testing" "time" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel" ) var t0 = time.Date(2026, 11, 14, 22, 0, 0, 0, time.UTC) func TestDecide(t *testing.T) { p := Params{Threshold: 5} cases := []struct { name string in Input act string why string }{ {"below", Input{Attacks: 4, Top: ReasonScannerFlood}, ActNone, ""}, {"threshold", Input{Attacks: 5, Top: ReasonWPBrute}, ActBan, ReasonWPBrute}, {"critical single hit", Input{Crit: ReasonEnvProbe, Crits: 1, Attacks: 1}, ActNone, ""}, {"critical two hits", Input{Crit: ReasonEnvProbe, Crits: 2, Attacks: 2}, ActBan, ReasonEnvProbe}, {"ssh", Input{SSHFails: 5}, ActBan, ReasonSSHBrute}, {"ssh below", Input{SSHFails: 4}, ActNone, ""}, {"trusted", Input{Attacks: 9, Exclude: SkipTrusted}, ActSkip, ""}, {"crawler", Input{Crit: ReasonRCE, Crits: 2, Exclude: SkipCrawler}, ActSkip, ""}, {"infra", Input{Crit: ReasonRCE, Crits: 2, Exclude: SkipInfra}, ActSkip, ""}, {"legit doubles", Input{Attacks: 9, Legit: true, Top: ReasonScannerFlood}, ActNone, ""}, {"legit doubles ok", Input{Attacks: 10, Legit: true, Top: ReasonScannerFlood}, ActBan, ReasonScannerFlood}, {"legit never stops crit", Input{Crit: ReasonRCE, Crits: 2, Attacks: 2, Legit: true}, ActBan, ReasonRCE}, {"legit one crit", Input{Crit: ReasonRCE, Crits: 1, Attacks: 1, Legit: true}, ActNone, ""}, {"legit ssh", Input{SSHFails: 9, Legit: true}, ActNone, ""}, {"already", Input{Attacks: 5, Top: ReasonScannerFlood, Banned: true}, ActAlready, ""}, {"active", Input{Attacks: 5, Top: ReasonScannerFlood, Active: true}, ActActive, ""}, } for _, c := range cases { d := Decide(c.in, p) if d.Action != c.act || (c.why != "" && d.Reason != c.why) { t.Errorf("%s: %+v", c.name, d) } } } func TestTTLEscalation(t *testing.T) { want := []time.Duration{time.Hour, 6 * time.Hour, 24 * time.Hour, 7 * 24 * time.Hour, 7 * 24 * time.Hour} for i, w := range want { if TTLFor(i) != w { t.Errorf("offence %d: %v", i, TTLFor(i)) } } } func TestExclusions(t *testing.T) { x := Exclusions{Trusted: []netip.Prefix{netip.MustParsePrefix("45.0.0.0/8")}, Peers: map[netip.Addr]bool{netip.MustParseAddr("46.1.1.1"): true}, Infra: map[netip.Addr]bool{netip.MustParseAddr("47.1.1.1"): true}} for ip, want := range map[string]string{ "10.1.2.3": SkipPrivate, "127.0.0.1": SkipPrivate, "169.254.1.1": SkipPrivate, "100.64.1.1": SkipPrivate, "::1": SkipPrivate, "fe80::1": SkipPrivate, "fc00::1": SkipPrivate, "ff02::1": SkipPrivate, "224.0.0.1": SkipPrivate, "240.0.0.1": SkipPrivate, "0.0.0.0": SkipPrivate, "::ffff:10.0.0.1": SkipPrivate, "2001:db8::1": SkipPrivate, "45.9.9.9": SkipTrusted, "47.1.1.1": SkipInfra, "46.1.1.1": SkipPeer, "::ffff:46.1.1.1": SkipPeer, "8.8.8.8": SkipInfra, "2606:4700::1111": SkipInfra, "104.16.1.1": SkipInfra, "2a06:98c0::1": SkipInfra, "93.184.216.34": "", } { if got := x.Excluded(netip.MustParseAddr(ip)); got != want { t.Errorf("%s: %q want %q", ip, got, want) } } } func atk(ip string, at time.Time, path string, st int) core.Event { return core.Event{Time: at, IP: ip, Cat: core.Scanner, Source: "traefik", Method: "GET", Path: path, Status: st, UA: "x"} } type rig struct { e *Engine now time.Time log string } func newRig(t *testing.T, mode string, mod func(*Config)) *rig { r := &rig{now: t0, log: filepath.Join(t.TempDir(), "enf", "decisions.log")} c := Config{Mode: mode, Path: r.log, StatePath: filepath.Join(t.TempDir(), "enforce.json"), Host: "oracle", Threshold: 5, MaxPerMin: 60, Trusted: []netip.Prefix{netip.MustParsePrefix("45.0.0.0/8")}, Now: func() time.Time { return r.now }} if mod != nil { mod(&c) } r.e = New(c) return r } func (r *rig) lines(t *testing.T) []string { b, err := os.ReadFile(r.log) if err != nil { return nil } return strings.Split(strings.TrimSpace(string(b)), "\n") } func (r *rig) hits(ip string, n int, path string, st int) { for i := 0; i < n; i++ { r.e.process(atk(ip, r.now.Add(-time.Duration(i)*time.Second), path, st), "") } } func TestEngineThresholdAndLine(t *testing.T) { r := newRig(t, ModeOn, nil) r.hits("203.0.114.7", 4, "/x", 404) if len(r.lines(t)) != 0 { t.Fatal("banned below threshold") } r.hits("203.0.114.7", 1, "/x", 404) l := r.lines(t) if len(l) != 1 || !strings.HasPrefix(l[0], "2026-11-14T22:00:00Z urutau decision=ban ip=203.0.114.7 reason=scanner-flood score=") || !strings.HasSuffix(l[0], " ttl=3600 host=oracle src=local") { t.Fatalf("line %q", l) } // dedupe: more hits while the TTL holds write nothing r.hits("203.0.114.7", 10, "/x", 404) if len(r.lines(t)) != 1 { t.Fatal("rewrote during TTL") } // escalation after the TTL: 6 h, persisted r.now = r.now.Add(61 * time.Minute) r.hits("203.0.114.7", 5, "/x", 404) l = r.lines(t) if len(l) != 2 || !strings.Contains(l[1], "ttl=21600") { t.Fatalf("escalation %q", l) } r.e.saveState() e2 := New(r.e.cfg) if e2.bans[netip.MustParseAddr("203.0.114.7")].Offences != 2 { t.Fatalf("state %+v", e2.bans) } if fi, err := os.Stat(r.log); err != nil || fi.Mode().Perm() != 0o640 { t.Fatalf("mode %v %v", fi, err) } } func TestEngineCriticalAndFamily(t *testing.T) { r := newRig(t, ModeOn, nil) ev := atk("203.0.114.8", r.now, "/.env", 404) ev.Cat = core.Exploit r.e.process(ev, intel.FamEnvCreds) if len(r.lines(t)) != 0 { t.Fatal("a single critical hit banned") } ev.Time = r.now.Add(time.Second) r.e.process(ev, intel.FamEnvCreds) ev2 := atk("203.0.114.9", r.now, "/wp-login.php", 404) r.e.process(ev2, intel.FamWordPress) l := r.lines(t) if len(l) != 1 || !strings.Contains(l[0], "reason=env-probe") { t.Fatalf("%q", l) } } func TestEngineNeverCounts(t *testing.T) { r := newRig(t, ModeOn, nil) for _, st := range []int{404, 400, 405, 500, 502} { ev := atk("203.0.114.10", r.now, "/x", st) ev.Cat = core.NotFound // a plain 404 is not an attack category for i := 0; i < 20; i++ { r.e.process(ev, "") } } // app and proxy errors on attack-category requests do not count either for i := 0; i < 20; i++ { ev := atk("203.0.114.11", r.now, "/x", 500) ev.Proto, ev.Router, ev.OriginStatus = "HTTP/2", "r@docker", 500 r.e.process(ev, "") ev = atk("203.0.114.11", r.now, "/x", 502) ev.Proto, ev.Router, ev.Retries = "HTTP/2", "r@docker", 2 r.e.process(ev, "") fr := atk("203.0.114.11", r.now, "/x", 404) fr.Framed = true r.e.process(fr, "") } if len(r.lines(t)) != 0 { t.Fatalf("banned: %q", r.lines(t)) } } func TestEngineExclusionsAndCounts(t *testing.T) { r := newRig(t, ModeOn, func(c *Config) { c.Crawler = func(ip string, uas []string) bool { return ip == "66.249.66.1" } c.PeerHosts = []string{"46.1.1.1"} }) r.hits("45.1.1.1", 6, "/x", 404) r.hits("10.0.0.5", 6, "/x", 404) r.hits("46.1.1.1", 6, "/x", 404) r.hits("66.249.66.1", 6, "/x", 404) if len(r.lines(t)) != 0 { t.Fatalf("banned excluded: %q", r.lines(t)) } rep := r.e.Report(0) for _, k := range []string{SkipTrusted, SkipPrivate, SkipPeer, SkipCrawler} { if rep.Counts.Skipped[k] != 1 { t.Errorf("skip %s: %v", k, rep.Counts.Skipped) } } // the skip is reported once, not once per event r.hits("45.1.1.1", 30, "/x", 404) if r.e.Report(0).Counts.Skipped[SkipTrusted] != 1 { t.Fatal("skip spam") } } func TestEngineLegitVisitor(t *testing.T) { r := newRig(t, ModeOn, nil) vis := core.Event{Time: r.now.Add(-time.Hour), IP: "203.0.114.20", Cat: core.OK, Source: "traefik", Status: 200, FetchDest: "document"} r.e.process(vis, "") ev := atk("203.0.114.20", r.now, "/.env", 404) ev.Cat = core.Exploit r.e.process(ev, intel.FamEnvCreds) r.hits("203.0.114.20", 7, "/x", 404) if len(r.lines(t)) != 0 { t.Fatalf("legit banned: %q", r.lines(t)) } r.hits("203.0.114.20", 2, "/y", 404) if len(r.lines(t)) != 1 { t.Fatalf("legit double threshold: %q", r.lines(t)) } } func TestEngineAlreadyBlocked(t *testing.T) { r := newRig(t, ModeOn, nil) r.e.process(core.Event{Time: r.now, IP: "203.0.114.30", Cat: core.Ban, Source: "fail2ban", Jail: "sshd"}, "") r.hits("203.0.114.30", 8, "/x", 404) if len(r.lines(t)) != 0 || r.e.Report(0).Counts.AlreadyBlocked != 1 { t.Fatalf("%q %+v", r.lines(t), r.e.Report(0).Counts) } rep := r.e.Report(0) if rep.Coverage.AttackIPs != 1 || rep.Coverage.BlockedByFirewall != 1 { t.Fatalf("coverage %+v", rep.Coverage) } } func TestEngineSSH(t *testing.T) { r := newRig(t, ModeOn, nil) for i := 0; i < 5; i++ { r.e.process(core.Event{Time: r.now.Add(-time.Duration(i) * time.Minute), IP: "203.0.114.40", Cat: core.SSHFail, Source: "ssh", User: "root"}, "") } if l := r.lines(t); len(l) != 1 || !strings.Contains(l[0], "reason=ssh-bruteforce") { t.Fatalf("%q", l) } } func TestEngineRateCapAndObserve(t *testing.T) { r := newRig(t, ModeOn, func(c *Config) { c.MaxPerMin = 3 }) for i := 0; i < 6; i++ { r.hits(fmt.Sprintf("203.0.%d.50", 114+i), 5, "/x", 404) // one /24 each: no neighbor rule } rep := r.e.Report(0) if len(r.lines(t)) != 3 || rep.Counts.Written != 3 || rep.Counts.DroppedRate != 3 || rep.Counts.Decided != 6 { t.Fatalf("%q %+v", r.lines(t), rep.Counts) } o := newRig(t, ModeObserve, nil) o.hits("203.0.114.60", 5, "/x", 404) rep = o.e.Report(0) if _, err := os.Stat(o.log); err == nil { t.Fatal("observe wrote the file") } if len(rep.Recent) != 1 || rep.Recent[0].Action != "would_ban" || rep.Coverage.WouldBlock != 1 || rep.Counts.Written != 0 { t.Fatalf("%+v", rep) } } func TestOldEventsDoNotBan(t *testing.T) { r := newRig(t, ModeOn, nil) for i := 0; i < 20; i++ { r.e.process(atk("203.0.114.70", r.now.Add(-3*time.Hour), "/x", 404), "") } if len(r.lines(t)) != 0 { t.Fatal("replayed events banned") } if r.e.Report(0).Coverage.AttackIPs != 1 { t.Fatal("coverage lost old events") } } func TestObserveNeverBlocks(t *testing.T) { e := New(Config{Mode: ModeOn, Path: filepath.Join(t.TempDir(), "d.log")}) for i := 0; i < 10000; i++ { e.Observe(atk("203.0.114.1", t0, "/x", 404), "") } if e.dropQ.Load() == 0 { t.Fatal("full queue must drop and count") } } func (r *rig) seen(ip string) { r.hits(ip, 2, "/x", 404) } func TestAcceptPeer(t *testing.T) { r := newRig(t, ModeOn, nil) r.seen("203.0.114.80") acc, bad := r.e.AcceptPeer("hostinger", []Wire{ {T: t0.Unix(), IP: "203.0.114.80", Reason: ReasonRCE, Score: 90, TTL: 3600}, {T: t0.Unix(), IP: "203.0.114.81", Reason: "evil\nreason", Score: 90, TTL: 3600}, {T: t0.Unix(), IP: "10.0.0.1", Reason: ReasonRCE, TTL: 3600}, {T: t0.Unix(), IP: "45.2.2.2", Reason: ReasonRCE, TTL: 3600}, {T: t0.Unix(), IP: "nope", Reason: ReasonRCE, TTL: 3600}, }) l := r.lines(t) if acc != 1 || bad != 3 || len(l) != 1 || !strings.HasSuffix(l[0], "src=peer:hostinger") { t.Fatalf("%d %d %q", acc, bad, l) } if len(r.e.LocalSince(0)) != 0 { t.Fatal("peer decisions must not be re-shared") } if r.e.Report(0).Counts.Skipped[SkipTrusted] != 1 { t.Fatalf("%+v", r.e.Report(0).Counts) } } func TestAcceptPeerUnconfirmedTTLAndInfra(t *testing.T) { r := newRig(t, ModeOn, nil) r.seen("203.0.114.90") r.seen("1.1.1.1") r.seen("104.16.5.5") acc, _ := r.e.AcceptPeer("h", []Wire{ {T: t0.Unix(), IP: "203.0.114.99", Reason: ReasonRCE, Score: 90, TTL: 3600}, // never seen here {T: t0.Unix(), IP: "203.0.114.90", Reason: ReasonRCE, Score: 90, TTL: 7 * 24 * 3600}, {T: t0.Unix(), IP: "1.1.1.1", Reason: ReasonRCE, Score: 90, TTL: 3600}, {T: t0.Unix(), IP: "104.16.5.5", Reason: ReasonRCE, Score: 90, TTL: 3600}, }) l := r.lines(t) if acc != 1 || len(l) != 1 || !strings.Contains(l[0], "ip=203.0.114.90") || !strings.Contains(l[0], "ttl=21600") { t.Fatalf("%d %q", acc, l) } sk := r.e.Report(0).Counts.Skipped if sk[SkipUnconfirmed] != 1 || sk[SkipInfra] < 2 { t.Fatalf("%v", sk) } // an attack seen only long ago does not confirm r2 := newRig(t, ModeOn, nil) for i := 0; i < 3; i++ { r2.e.process(atk("203.0.114.91", r2.now.Add(-8*24*time.Hour), "/x", 404), "") } if acc, _ := r2.e.AcceptPeer("h", []Wire{{T: t0.Unix(), IP: "203.0.114.91", Reason: ReasonRCE, TTL: 60}}); acc != 0 { t.Fatal("stale confirmation accepted") } } func TestInfraNeverBannedLocally(t *testing.T) { r := newRig(t, ModeOn, func(c *Config) { c.PeerHosts = []string{"hub.example"} c.InfraHosts = []string{"hub.example"} c.LocalAddrs = func() []netip.Addr { return []netip.Addr{netip.MustParseAddr("203.0.114.200")} } c.Resolve = func(string) []netip.Addr { return []netip.Addr{netip.MustParseAddr("203.0.114.201")} } }) for _, ip := range []string{"104.16.9.9", "8.8.4.4", "2606:4700:4700::1001", "203.0.114.200", "203.0.114.201"} { r.hits(ip, 9, "/x", 404) } if len(r.lines(t)) != 0 { t.Fatalf("infra banned: %q", r.lines(t)) } } func TestPeerResolutionKeepsLastGood(t *testing.T) { fail := false r := newRig(t, ModeOn, func(c *Config) { c.PeerHosts = []string{"peer.example"} c.Resolve = func(string) []netip.Addr { if fail { return nil } return []netip.Addr{netip.MustParseAddr("203.0.114.210")} } }) fail = true r.e.refreshPeers() r.hits("203.0.114.210", 9, "/x", 404) if len(r.lines(t)) != 0 { t.Fatal("peer banned after DNS failure") } } func TestCriticalNeedsTwoHits(t *testing.T) { r := newRig(t, ModeOn, nil) mk := func(at time.Time) { ev := atk("203.0.114.220", at, "/.env", 404) ev.Cat = core.Exploit r.e.process(ev, intel.FamEnvCreds) } mk(r.now) if len(r.lines(t)) != 0 { t.Fatal("one hit") } // a forged legitimate visit does not cancel a critical ban r.e.process(core.Event{Time: r.now, IP: "203.0.114.220", Cat: core.OK, Source: "traefik", Status: 200, FetchDest: "document"}, "") mk(r.now.Add(time.Second)) if len(r.lines(t)) != 1 { t.Fatalf("legit visit blocked crit ban: %q", r.lines(t)) } } func TestWouldAndBansPruned(t *testing.T) { r := newRig(t, ModeObserve, nil) r.e.mu.Lock() for i := 0; i < maxTracked+10; i++ { a := netip.AddrFrom4([4]byte{50, byte(i >> 16), byte(i >> 8), byte(i)}) r.e.would[a] = r.now.Add(time.Hour).Unix() r.e.bans[a] = banRec{Until: r.now.Unix(), Last: r.now.Unix(), Offences: 1} } r.e.would[netip.MustParseAddr("51.0.0.1")] = r.now.Add(-48 * time.Hour).Unix() r.e.trimMaps(r.now) nw, nb := len(r.e.would), len(r.e.bans) _, old := r.e.would[netip.MustParseAddr("51.0.0.1")] r.e.mu.Unlock() if nw > maxTracked || nb > maxTracked || old { t.Fatalf("not pruned: %d %d %v", nw, nb, old) } } func TestSaveStateThrottled(t *testing.T) { r := newRig(t, ModeOn, nil) r.hits("203.0.114.230", 5, "/x", 404) r.e.maybeSave() st := r.e.cfg.StatePath os.Remove(st) r.hits("203.0.114.231", 5, "/x", 404) r.e.maybeSave() // same instant: throttled if _, err := os.Stat(st); err == nil { t.Fatal("saved within 30s") } r.now = r.now.Add(31 * time.Second) r.e.maybeSave() if _, err := os.Stat(st); err != nil { t.Fatal("not saved after 30s") } } func TestRotation(t *testing.T) { l := &logFile{path: filepath.Join(t.TempDir(), "d.log")} line := strings.Repeat("x", 1<<20-1) + "\n" for i := 0; i < 21; i++ { if err := l.write(line); err != nil { t.Fatal(err) } } if _, err := os.Stat(l.path + ".1"); err != nil { t.Fatal("no rotation") } if fi, _ := os.Stat(l.path); fi.Size() > MaxLogBytes { t.Fatal("too big") } } func TestFormatLineInjection(t *testing.T) { ip := netip.MustParseAddr("8.8.8.8") for _, evil := range []string{"x\ny", "a b\r\nurutau decision=ban ip=1.1.1.1", "peer:\x00\n", "\n\n", strings.Repeat("a", 500)} { if _, err := FormatLine(t0, ip, evil, 90, time.Hour, "h", "local"); err == nil { t.Errorf("reason %q accepted", evil) } l, err := FormatLine(t0, ip, ReasonRCE, 90, time.Hour, evil, "peer:"+evil) if err != nil || strings.Count(l, "\n") != 1 || !strings.HasSuffix(l, "\n") || strings.ContainsAny(strings.TrimSuffix(l, "\n"), "\r\x00") || len(strings.Fields(l)) != 9 { t.Errorf("host/src %q -> %q", evil, l) } } if _, err := FormatLine(t0, netip.Addr{}, ReasonRCE, 1, time.Hour, "h", "local"); err == nil { t.Error("invalid ip accepted") } } func FuzzFormatLine(f *testing.F) { f.Add("h", "peer:x", ReasonRCE) f.Add("a\nb", "\r\n", "x\ny") f.Fuzz(func(t *testing.T, host, src, reason string) { l, err := FormatLine(t0, netip.MustParseAddr("2606:4700::1111"), reason, 5, time.Hour, host, src) if err != nil { return } if strings.Count(l, "\n") != 1 || len(strings.Fields(l)) != 9 { t.Fatalf("%q", l) } }) } func TestWritable(t *testing.T) { d := t.TempDir() if !Writable(filepath.Join(d, "sub", "x.log")) || !Writable(filepath.Join(d, "x.log")) { t.Fatal("should be writable") } if _, err := os.Stat(filepath.Join(d, "x.log")); err == nil { t.Fatal("Writable must not create the file") } if Writable("") { t.Fatal("empty path") } }