package store import ( "testing" "time" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" ) type fakeRDNS struct{ ok map[string]bool } func (f fakeRDNS) Lookup(string) string { return "" } func (f fakeRDNS) FCrDNS(ip string, suffixes []string) bool { for _, s := range suffixes { if s == "googlebot.com" { return f.ok[ip] } } return false } func TestVerifiedCrawlerIgnoresUA(t *testing.T) { s := store30("x") s.SetRDNS(fakeRDNS{ok: map[string]bool{"66.249.66.1": true}}) if !s.VerifiedCrawler("66.249.66.1") || s.VerifiedCrawler("47.82.1.1") { t.Fatal("verified crawler") } if v := s.FCrDNS("66.249.66.1", []string{"Mozilla/5.0 (compatible; GoogleOther)"}); v == nil || !*v { t.Fatalf("GoogleOther UA: %v", v) } } func TestOwnJailBanIsNotEvidence(t *testing.T) { s := store30("x") for _, j := range []string{"urutau", "recidive"} { ip := "203.0.114.9" if j == "recidive" { ip = "203.0.114.10" } s.Ingest(core.Event{Time: t0.Add(-time.Hour), IP: ip, Cat: core.Ban, Source: "fail2ban", Jail: j}) r := s.ips[ip] if r == nil || r.Strong || r.StrongWhy&whyBan != 0 || r.Score != 0 || len(r.Jails) != 1 { t.Fatalf("%s: %+v", j, r) } if listedRule(r, t0.Unix()) { t.Fatalf("%s listed", j) } } s.Ingest(core.Event{Time: t0.Add(-time.Hour), IP: "203.0.114.11", Cat: core.Ban, Source: "fail2ban", Jail: "sshd"}) if r := s.ips["203.0.114.11"]; r == nil || !r.Strong || r.Score < 10 { t.Fatalf("sshd ban must stay evidence: %+v", r) } } func TestDefenseCoverageMetrics(t *testing.T) { s := store30("x") l := openLog(t) s.SetEventLog(l) scan := func(ip string, n int) { for i := 0; i < n; i++ { s.Ingest(core.Event{Time: t0.Add(-time.Duration(60+i) * time.Minute), IP: ip, Cat: core.Scanner, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/x", Status: 404, UA: "curl/8"}) } } scan("203.0.114.20", 1) // one shot scan("203.0.114.21", 3) // repeated, banned by our own jail s.Ingest(core.Event{Time: t0.Add(-30 * time.Minute), IP: "203.0.114.21", Cat: core.Ban, Source: "fail2ban", Jail: "urutau"}) scan("203.0.114.22", 3) // repeated, unprotected l.Flush() d := s.Defense(PeriodQuery{From: t0.Add(-24 * time.Hour).Unix(), To: t0.Unix()}) b := d.Blocklist if b.Attackers != 3 || b.Covered != 1 || b.OneShot != 1 || b.Repeat != 2 || b.RepeatCover != 1 { t.Fatalf("%+v", b) } if b.RepeatCoveragePct != 50 || b.CoveragePct < 33 || b.CoveragePct > 34 { t.Fatalf("%+v", b) } } func TestTalliesCountSSHProbeAndWeek(t *testing.T) { s := store30("x") l := openLog(t) s.SetEventLog(l) for i := 0; i < 4; i++ { s.Ingest(core.Event{Time: t0.Add(-time.Duration(i+1) * time.Hour), IP: "203.0.114.30", Cat: core.SSHProbe, Source: "ssh"}) s.Ingest(core.Event{Time: t0.Add(-time.Duration(i+3) * 24 * time.Hour), IP: "203.0.114.30", Cat: core.SSHFail, Source: "ssh", User: "root"}) } l.Flush() m := s.AttackTallies(t0.Add(-7 * 24 * time.Hour).Unix()) x := m["203.0.114.30"] if x.Probe != 4 || x.Probe7 != 4 || x.SSH != 0 || x.SSH7 != 4 { t.Fatalf("%+v", x) } }