package enforce import ( "net/netip" "os" "path/filepath" "strings" "testing" "time" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" ) func sshEv(ip string, at time.Time) core.Event { return core.Event{Time: at, IP: ip, Cat: core.SSHFail, Source: "ssh", User: "root"} } func histRig(t *testing.T, mod func(*Config)) *rig { return newRig(t, ModeOn, func(c *Config) { c.Trusted = append(c.Trusted, netip.MustParsePrefix("168.196.85.0/24")) if mod != nil { mod(c) } }) } func TestKnownAttackerBansOnFirstEvent(t *testing.T) { lv := map[string]core.Level{"203.0.114.50": core.LevelHostile, "203.0.114.51": core.LevelSuspicious} sc := map[string]float64{"203.0.114.50": 80, "203.0.114.51": 40, "203.0.114.52": 120} lv["203.0.114.52"] = core.LevelSuspicious r := histRig(t, func(c *Config) { c.Rep = func(ip string) (float64, core.Level, bool) { l, ok := lv[ip]; return sc[ip], l, ok } }) for _, ip := range []string{"203.0.114.50", "203.0.114.51", "203.0.114.52"} { r.e.handle(atk(ip, r.now, "/x", 404), "") } got := map[string]bool{} for _, l := range r.lines(t) { for _, ip := range []string{"203.0.114.50", "203.0.114.51", "203.0.114.52"} { if len(l) > 0 && contains(l, ip) { got[ip] = true if !contains(l, "known-attacker") { t.Errorf("reason: %s", l) } } } } if !got["203.0.114.50"] || got["203.0.114.51"] || !got["203.0.114.52"] { t.Fatalf("bans: %v", got) } } func contains(s, sub string) bool { for i := 0; i+len(sub) <= len(s); i++ { if s[i:i+len(sub)] == sub { return true } } return false } func TestSlowSSH24h(t *testing.T) { r := histRig(t, func(c *Config) { c.Tally = func(ip string, from int64) Tally { return Tally{SSH: 9} } // 9 already in the registry }) r.e.handle(sshEv("203.0.114.60", r.now), "") if len(r.lines(t)) != 0 { t.Fatal("9 in 24h must not ban") } r.now = r.now.Add(time.Minute) r.e.handle(sshEv("203.0.114.60", r.now), "") // the 10th if l := r.lines(t); len(l) != 1 || !contains(l[0], "ssh-bruteforce") { t.Fatalf("lines: %v", l) } } func TestTrustedNeverBannedByHistory(t *testing.T) { r := histRig(t, func(c *Config) { c.Rep = func(string) (float64, core.Level, bool) { return 200, core.LevelHostile, true } c.Tally = func(string, int64) Tally { return Tally{SSH: 500, Web: 500} } c.Roster = func(int64) []Seen { return []Seen{{IP: "168.196.85.9", Score: 200, Level: core.LevelHostile}} } }) r.e.handle(sshEv("168.196.85.9", r.now), "") r.e.Sweep() r.e.drain() if len(r.lines(t)) != 0 { t.Fatalf("trusted banned: %v", r.lines(t)) } } func TestSweepRespectsExclusionsAndCap(t *testing.T) { var roster []Seen tal := map[string]Tally{} for i := 1; i <= 5; i++ { ip := "203.0.114." + itoa(100+i) roster = append(roster, Seen{IP: ip, Score: float64(60 - i), Level: core.LevelHostile}) } roster = append(roster, Seen{IP: "168.196.85.7", Score: 90, Level: core.LevelHostile}, // trusted Seen{IP: "10.0.0.5", Score: 90, Level: core.LevelHostile}, // private Seen{IP: "203.0.114.120", Score: 90, Level: core.LevelHostile, Jails: []string{"sshd"}}, // already Seen{IP: "203.0.114.121", Score: 20, Level: core.LevelSuspicious}, // slow web ) tal["203.0.114.121"] = Tally{Web: 25} r := histRig(t, func(c *Config) { c.MaxPerMin = 2 c.Roster = func(int64) []Seen { return roster } c.Tallies = func(int64) map[string]Tally { return tal } }) r.e.Sweep() r.e.drain() if n := len(r.lines(t)); n != 2 { t.Fatalf("minute 1: %d lines", n) } r.now = r.now.Add(time.Minute) r.e.drain() r.now = r.now.Add(time.Minute) r.e.drain() r.now = r.now.Add(time.Minute) r.e.drain() ls := r.lines(t) if len(ls) != 6 { t.Fatalf("total %d: %v", len(ls), ls) } for _, l := range ls { for _, bad := range []string{"168.196.85.7", "10.0.0.5", "203.0.114.120"} { if contains(l, bad) { t.Errorf("banned %s", bad) } } } if !contains(ls[len(ls)-1], "203.0.114.121") || !contains(ls[len(ls)-1], "scanner-flood") { t.Errorf("last: %s", ls[len(ls)-1]) } if r.e.counts.DroppedRate != 0 { t.Errorf("cap must defer, not drop: %d", r.e.counts.DroppedRate) } } func TestCoverageSurvivesRestart(t *testing.T) { roster := []Seen{ {IP: "203.0.114.70", Jails: []string{"sshd"}}, {IP: "203.0.114.71", Jails: []string{"urutau"}}, {IP: "203.0.114.72"}, {IP: "203.0.114.73"}, } cfg := func(c *Config) { c.Roster = func(int64) []Seen { return roster } } r := histRig(t, cfg) r.e.AcceptPeer("x", nil) r.e.process(atk("203.0.114.72", r.now, "/.env", 200), "env-credentials") // 72 gets banned by the engine (written decision), 73 stays unblocked. r.e.mu.Lock() r.e.bans[netip.MustParseAddr("203.0.114.72")] = banRec{Until: r.now.Add(time.Hour).Unix(), Last: r.now.Unix(), Offences: 1} r.e.dirty = true r.e.mu.Unlock() r.e.saveState() from := r.now.Add(-24 * time.Hour).Unix() want := r.e.Report(from).Coverage if want.AttackIPs != 4 || want.BlockedByFirewall != 1 || want.BlockedByUrutau != 2 || want.Unblocked != 1 { t.Fatalf("coverage: %+v", want) } // restart: a new engine over the same state file and the same store c := Config{Mode: ModeOn, Path: r.log, StatePath: r.e.cfg.StatePath, Host: "oracle", Now: func() time.Time { return r.now }} cfg(&c) e2 := New(c) if got := e2.Report(from).Coverage; got != want { t.Fatalf("after restart %+v want %+v", got, want) } } func itoa(n int) string { if n == 0 { return "0" } s := "" for ; n > 0; n /= 10 { s = string(rune('0'+n%10)) + s } return s } func TestOperatorAllowBlocksBansAndExpires(t *testing.T) { r := histRig(t, func(c *Config) { c.UnbanPath = filepath.Join(t.TempDir(), "u", "unban.log") }) ip := netip.MustParseAddr("203.0.114.80") r.hits(ip.String(), 5, "/x", 404) if len(r.lines(t)) != 1 { t.Fatalf("expected a ban: %v", r.lines(t)) } if err := r.e.Unban(ip, 3600, "local"); err != nil { t.Fatal(err) } if b, _ := os.ReadFile(r.e.UnbanLogPath()); !strings.HasSuffix(string(b), " urutau unban ip=203.0.114.80 allow=3600\n") { t.Fatalf("file %q", b) } r.now = r.now.Add(time.Minute) r.hits(ip.String(), 8, "/y", 404) if len(r.lines(t)) != 1 { t.Fatalf("allowed address was banned: %v", r.lines(t)) } if r.e.counts.Skipped[SkipOperator] == 0 { t.Fatal("skip not counted") } // survives a restart e2 := New(Config{Mode: ModeOn, Path: r.log, StatePath: r.e.cfg.StatePath, Now: func() time.Time { return r.now }}) if len(e2.Allows()) != 1 { t.Fatal("allow not persisted") } // expires by itself r.now = r.now.Add(2 * time.Hour) if len(r.e.Allows()) != 0 { t.Fatal("allow did not expire") } r.hits(ip.String(), 8, "/z", 404) if len(r.lines(t)) != 2 { t.Fatalf("not banned after expiry: %v", r.lines(t)) } // ending early lets the engine decide again r.e.Unban(ip, 3600, "local") if !r.e.EndAllow(ip) || r.e.EndAllow(ip) { t.Fatal("EndAllow") } if got := r.e.UnbansSince(0); len(got) != 2 || got[0].IP != ip.String() { t.Fatalf("unbans for peers: %v", got) } if rep := r.e.Report(0); rep.Recent[0].Action != "unban" { t.Fatalf("recent: %+v", rep.Recent[0]) } if err := New(Config{Mode: ModeOn, Path: r.log}).Unban(ip, 0, "local"); err != ErrNoUnbanLog { t.Fatalf("no file: %v", err) } }