fix: forge browsing, verified crawlers, ban feedback loop, coverage metrics and slow-attacker policy (1.6.0)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lucas RayanandClaude Opus 5.5 committed 2026-11-15 20:26:56 -03:00
1 parent 393a31cebe
commit 54b9ae65cd
23 files changed
+802 -100

No files matched your search

+33 -6
View File
@@ -47,11 +47,20 @@ type SSHDefense struct {
// BlocklistStat describes the blocklist the instance would publish.
type BlocklistStat struct {
Size int `json:"size"`
V4 int `json:"v4"`
V6 int `json:"v6"`
Updated int64 `json:"updated"`
CoveragePct float64 `json:"coverage_pct"` // attackers of the window that are listed
Size int `json:"size"`
V4 int `json:"v4"`
V6 int `json:"v6"`
Updated int64 `json:"updated"`
// CoveragePct is the share of the window's attackers that are protected: listed
// on the blocklist OR banned by any jail (fail2ban or Urutau's enforce).
CoveragePct float64 `json:"coverage_pct"`
Attackers int `json:"attackers"` // distinct attackers of the window
Covered int `json:"covered"` // of them, listed or banned
OneShot int `json:"one_shot"` // attackers with a single event: impossible to block reactively
Repeat int `json:"repeat_ips"` // attackers with 2 or more events
RepeatCover int `json:"repeat_covered"`
// RepeatCoveragePct is the coverage among the repeated attackers (>= 2 events).
RepeatCoveragePct float64 `json:"repeat_coverage_pct"`
}
// LeakStat counts attackers that kept arriving after a ban or listing.
@@ -89,6 +98,7 @@ func defenseStep(span int64) int64 {
type ipDef struct {
firstMal, firstBan, firstFail int64
malN int
okAfter bool
mal, bans []int64
}
@@ -162,6 +172,7 @@ func (s *Store) defense(q PeriodQuery) DefenseOut {
fallthrough
case c.IsMalicious():
d := get(key)
d.malN++
if d.firstMal == 0 || r.T < d.firstMal {
d.firstMal = r.T
}
@@ -182,10 +193,12 @@ func (s *Store) defense(q PeriodQuery) DefenseOut {
// live state of the registry: active bans, jails, blocklist
active := map[string]int{}
listed := map[string]int64{}
jailed := map[string]bool{}
s.mu.RLock()
for ip, r := range s.ips {
if len(r.Jails) > 0 {
out.BansActive++
jailed[ip] = true
for _, j := range r.Jails {
active[j]++
}
@@ -246,9 +259,19 @@ func (s *Store) defense(q PeriodQuery) DefenseOut {
continue
}
attackers++
if _, ok := listed[ip]; ok {
_, isListed := listed[ip]
protected := isListed || d.firstBan > 0 || jailed[ip]
if protected {
covered++
}
if d.malN >= 2 {
out.Blocklist.Repeat++
if protected {
out.Blocklist.RepeatCover++
}
} else {
out.Blocklist.OneShot++
}
ttb = append(ttb, episodeTTB(d.mal, d.bans)...)
cut := d.firstBan
if l := listed[ip]; l > 0 && (cut == 0 || l < cut) {
@@ -277,6 +300,10 @@ func (s *Store) defense(q PeriodQuery) DefenseOut {
if attackers > 0 {
out.Blocklist.CoveragePct = float64(covered) / float64(attackers) * 100
}
out.Blocklist.Attackers, out.Blocklist.Covered = attackers, covered
if out.Blocklist.Repeat > 0 {
out.Blocklist.RepeatCoveragePct = float64(out.Blocklist.RepeatCover) / float64(out.Blocklist.Repeat) * 100
}
for u, c := range users {
out.SSH.Users = append(out.SSH.Users, SSHUser{User: u, N: c, Admin: adminOf[u]})
}
+5 -3
View File
@@ -547,14 +547,16 @@ func (s *Store) metrics(rg Range) MetricsOut {
if core.LevelOf(r.Score, strong, r.adminAt(now)) == core.LevelHostile {
hostile++
banned := len(r.Jails) > 0
listed := false
// protected: on the blocklist this instance publishes (public address)
// or already banned by a jail; a private address can be neither.
listed := r.ListedSince > 0
if a, err := netip.ParseAddr(strings.SplitN(ip, "/", 2)[0]); err == nil {
listed = core.IsGlobal(a)
listed = listed && core.IsGlobal(a)
}
if banned {
hostileBanned++
}
if listed {
if listed || banned {
hostileListed++
}
if !banned && !listed {
+94
View File
@@ -0,0 +1,94 @@
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)
}
}
+74 -27
View File
@@ -2,6 +2,7 @@ package store
import (
"strings"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
@@ -9,16 +10,18 @@ import (
// RosterRow is one address with malicious activity, as the second firewall needs it.
type RosterRow struct {
IP string
Score float64
Level core.Level
Jails []string
Last int64
Est Tally24 // 24 h estimate from the per-day counters (the registry may not cover the whole window)
IP string
Score float64
Level core.Level
Jails []string
Last int64
Events int // malicious events recorded for the address
Est Tally24 // 24 h estimate from the per-day counters (the registry may not cover the whole window)
}
// dayEstimate estimates the SSH and web malicious events of the last 24 h from
// the per-day counters: today plus the share of yesterday still inside the window.
// dayEstimate estimates the SSH, ssh-probe and web malicious events of the last
// 24 h (SSH, Web, Probe) and of the last 7 days (SSH7, Web7, Probe7) from the
// per-day counters: today plus the share of the oldest day still inside the window.
func dayEstimate(r *IPRec, nowU int64) Tally24 {
if len(r.DayCats) == 0 {
return Tally24{}
@@ -26,24 +29,43 @@ func dayEstimate(r *IPRec, nowU int64) Tally24 {
today := nowU / 86400
frac := 1 - float64(nowU%86400)/86400
var t Tally24
for k := int64(0); k <= 1; k++ {
for k := int64(0); k <= 7; k++ {
i := int(r.DayBase - (today - k))
if i < 0 || i >= len(r.DayCats) {
continue
}
w := 1.0
if k == 1 {
w = frac
}
c := r.DayCats[i]
t.SSH += int(float64(c[core.SSHFail.Index()])*w + 0.999)
t.Web += int(float64(c[core.Scanner.Index()]+c[core.Exploit.Index()]+c[core.BruteForce.Index()])*w + 0.999)
ssh, probe := float64(c[core.SSHFail.Index()]), float64(c[core.SSHProbe.Index()])
web := float64(c[core.Scanner.Index()] + c[core.Exploit.Index()] + c[core.BruteForce.Index()])
if k <= 1 {
w := 1.0
if k == 1 {
w = frac
}
t.SSH += int(ssh*w + 0.999)
t.Web += int(web*w + 0.999)
t.Probe += int(probe*w + 0.999)
}
if k <= 6 {
w := 1.0
if k == 6 {
w = frac
}
t.SSH7 += int(ssh*w + 0.999)
t.Web7 += int(web*w + 0.999)
t.Probe7 += int(probe*w + 0.999)
}
}
return t
}
// Tally24 counts the malicious events of one address in a window.
type Tally24 struct{ SSH, Web int }
// SSH, Web and Probe cover the last 24 h; SSH7, Web7 and Probe7 the whole scanned
// window (7 days for the enforce sweep).
type Tally24 struct{ SSH, Web, Probe, SSH7, Web7, Probe7 int }
// maxTallyIPs bounds the memory of one tally pass.
const maxTallyIPs = 100000
// AttackRoster lists the addresses with malicious activity since from (unix).
func (s *Store) AttackRoster(from int64) []RosterRow {
@@ -57,7 +79,7 @@ func (s *Store) AttackRoster(from int64) []RosterRow {
}
strong := r.Strong || attackKinds(r.Counts) >= 2
out = append(out, RosterRow{IP: ip, Score: round1(r.Score), Level: core.LevelOf(r.Score, strong, r.adminAt(nowU)),
Jails: append([]string(nil), r.Jails...), Last: r.Last, Est: dayEstimate(r, nowU)})
Jails: append([]string(nil), r.Jails...), Last: r.Last, Events: int(malOf(r.Counts)), Est: dayEstimate(r, nowU)})
}
return out
}
@@ -75,31 +97,47 @@ func (s *Store) Reputation(ip string) (float64, core.Level, bool) {
return r.Score, core.LevelOf(r.Score, strong, r.adminAt(s.now().Unix())), true
}
var tallyCats = map[string]bool{string(core.SSHFail): true, string(core.Scanner): true, string(core.Exploit): true, string(core.BruteForce): true}
var tallyCats = map[string]bool{string(core.SSHFail): true, string(core.SSHProbe): true, string(core.Scanner): true, string(core.Exploit): true, string(core.BruteForce): true}
func tallyAdd(m map[string]*Tally24, r evlog.Rec) {
func tallyAdd(m map[string]*Tally24, r evlog.Rec, cut24 int64) {
t := m[r.IP]
if t == nil {
if len(m) >= maxTallyIPs {
return
}
t = &Tally24{}
m[r.IP] = t
}
recent := r.T >= cut24
switch {
case r.Cat == string(core.SSHFail):
t.SSH++
t.SSH7++
if recent {
t.SSH++
}
case r.Cat == string(core.SSHProbe):
t.Probe7++
if recent {
t.Probe++
}
case r.Source == "traefik" && !strings.Contains(r.Flags, "F"):
t.Web++
t.Web7++
if recent {
t.Web++
}
}
}
// AttackTallies counts, in one pass over the event log, the SSH failures and web
// scan/exploit events of every address since from. Nil without an event log.
// AttackTallies counts, in one pass over the event log, the SSH failures, ssh
// probes and web scan/exploit events of every address since from. Nil without an event log.
func (s *Store) AttackTallies(from int64) map[string]Tally24 {
if s.elog == nil {
return nil
}
cut24 := s.now().Add(-24 * time.Hour).Unix()
m := map[string]*Tally24{}
s.elog.Scan(evlog.Filter{From: from, Cats: tallyCats}, 4<<30, false, func(r evlog.Rec, _ []byte) bool {
tallyAdd(m, r)
tallyAdd(m, r, cut24)
return true
})
out := make(map[string]Tally24, len(m))
@@ -120,16 +158,25 @@ func (s *Store) AttackTally(ip string, from int64) Tally24 {
if s.elog == nil {
return est
}
cut24 := s.now().Add(-24 * time.Hour).Unix()
m := map[string]*Tally24{}
s.elog.Scan(evlog.Filter{From: from, IP: ip, Cats: tallyCats}, 1<<30, false, func(r evlog.Rec, _ []byte) bool {
tallyAdd(m, r)
tallyAdd(m, r, cut24)
return true
})
var t Tally24
for _, v := range m {
t.SSH += v.SSH
t.Web += v.Web
t.Probe += v.Probe
t.SSH7 += v.SSH7
t.Web7 += v.Web7
t.Probe7 += v.Probe7
}
t.SSH, t.Web = max(t.SSH, est.SSH), max(t.Web, est.Web)
return t
return MaxTally(t, est)
}
// MaxTally is the field-wise maximum.
func MaxTally(a, b Tally24) Tally24 {
return Tally24{max(a.SSH, b.SSH), max(a.Web, b.Web), max(a.Probe, b.Probe), max(a.SSH7, b.SSH7), max(a.Web7, b.Web7), max(a.Probe7, b.Probe7)}
}
+42 -1
View File
@@ -186,7 +186,32 @@ var crawlerSuffixes = []struct {
suffixes []string
}{
{"googlebot", []string{"googlebot.com", "google.com"}},
{"googleother", []string{"googlebot.com", "google.com"}},
{"google-inspectiontool", []string{"googlebot.com", "google.com"}},
{"adsbot-google", []string{"googlebot.com", "google.com"}},
{"mediapartners-google", []string{"googlebot.com", "google.com"}},
{"apis-google", []string{"googlebot.com", "google.com"}},
{"storebot-google", []string{"googlebot.com", "google.com"}},
{"bingbot", []string{"search.msn.com"}},
{"msnbot", []string{"search.msn.com"}},
{"applebot", []string{"applebot.apple.com"}},
}
// verifiedSuffixes are the reverse DNS domains of the crawlers Urutau trusts once
// forward-confirmed, whatever the User-Agent says.
var verifiedSuffixes = []string{"googlebot.com", "google.com", "search.msn.com", "applebot.apple.com"}
// VerifiedCrawler reports whether ip is a crawler of a known search engine,
// proven by forward-confirmed reverse DNS alone (no User-Agent is trusted).
func (s *Store) VerifiedCrawler(ip string) bool {
v, ok := s.rdns.(FCrDNSVerifier)
if !ok || s.rdns == nil {
return false
}
if a, err := netip.ParseAddr(ip); err != nil || a.Zone() != "" {
return false
}
return v.FCrDNS(ip, verifiedSuffixes)
}
// FCrDNS verifies an address that claims, through one of its User-Agents, to
@@ -474,6 +499,10 @@ func (s *Store) Ingest(ev core.Event) {
if scored {
r.Counts[ci]++
w := ev.Cat.Weight()
derived := ev.Cat == core.Ban && DerivedJail(ev.Jail)
if derived {
w = 0 // our own decision (or its repetition) is not independent evidence
}
if ev.Soft && (ev.Cat == core.Scanner || ev.Cat == core.Exploit) {
w = softWeight // answered 2xx/3xx: probably nothing was found
}
@@ -495,7 +524,7 @@ func (s *Store) Ingest(ev core.Event) {
r.StrongWhy |= whyTool
r.StrongAt = max(r.StrongAt, ts)
}
if (ev.Strong && !framed) || ev.Cat == core.Ban {
if (ev.Strong && !framed) || ev.Cat == core.Ban && !derived {
r.Strong = true
if ev.Cat == core.Ban {
r.StrongWhy |= whyBan
@@ -580,6 +609,18 @@ func (s *Store) feedOf(ev core.Event, ts int64, fam string, tech []string, marke
Bytes: ev.Bytes, DurMS: ev.DurationNS / 1e6, Flags: flags, Port: int(ev.Port), Proto: probeProto(ev)}
}
// DerivedJail reports whether bans of the jail come from Urutau's own decisions
// (the "urutau" jail reads the enforce file; "recidive" only repeats bans of
// other jails, ours included). Such bans must never feed back as evidence in the
// score, the strong signal or the blocklist. Independent jails (sshd, traefik...) still count.
func DerivedJail(j string) bool {
switch strings.ToLower(strings.TrimSpace(j)) {
case "urutau", "recidive":
return true
}
return false
}
// listedRule is the blocklist rule: score of 50, a strong signal and not an admin.
func listedRule(r *IPRec, now int64) bool {
return r.Score >= core.HostileScore && (r.Strong || attackKinds(r.Counts) >= 2) && !r.adminAt(now)
+1 -1
View File
@@ -80,7 +80,7 @@ func TestBansAndFeed(t *testing.T) {
b.Unban, b.Jail = true, "sshd"
s.Ingest(b)
r, _ := s.IP("5.5.5.5")
if len(r.Jails) != 1 || r.Jails[0] != "recidive" || r.Score != 20 {
if len(r.Jails) != 1 || r.Jails[0] != "recidive" || r.Score != 10 { // the recidive ban adds no evidence
t.Fatalf("%+v", r)
}
if rec := s.Recent(10); len(rec) != 3 || !rec[0].Unban {