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

+1 -1
View File
@@ -254,7 +254,7 @@ func TestEngineSSH(t *testing.T) {
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.114.%d", 50+i), 5, "/x", 404)
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 {
+113 -21
View File
@@ -35,7 +35,7 @@ type Config struct {
// 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
Tally func(ip string, from int64) Tally // counts of one address (24 h and 7 days)
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
@@ -43,21 +43,24 @@ type Config struct {
// 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
IP string
Score float64
Level core.Level
Jails []string
Est Tally // estimate from per-day counters, used when the registry holds less
Events int // malicious events recorded for the address
Last int64 // unix of its last event
}
// Tally counts malicious events of one address in LongWindow.
type Tally struct{ SSH, Web int }
// Tally counts malicious events of one address: SSH, Web and Probe in the last
// 24 h, SSH7, Web7 and Probe7 in the last 7 days (Probe: ssh-probe events).
type Tally struct{ SSH, Web, Probe, SSH7, Web7, Probe7 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
ssh, web, probe, ssh7, web7, probe7 int
at int64 // when loaded from the registry
known bool
fresh bool // just loaded: the current event is already counted
}
type cand struct {
@@ -110,6 +113,12 @@ type Coverage struct {
BlockedByUrutau int `json:"blocked_by_urutau"`
WouldBlock int `json:"would_block"`
Unblocked int `json:"unblocked"`
// OneShot attackers made a single event: impossible to block reactively.
OneShot int `json:"one_shot"`
// Repeat attackers made two or more events; RepeatUnblocked is how many of
// them nothing blocks (neither fail2ban, Urutau nor a would-ban).
Repeat int `json:"repeat_ips"`
RepeatUnblocked int `json:"repeat_unblocked"`
}
// Report is what the API serves (mode and file status are added by the handler).
@@ -127,6 +136,7 @@ type aevt struct {
type ipState struct {
ev []aevt
ssh []int64
sshp []int64 // ssh-probe events in Window
probes map[uint32]int64 // proto<<16|port -> last seen (unix)
legit int64
uas []string
@@ -159,6 +169,7 @@ const (
maxPeerTTL = 6 * time.Hour
peerConfirmAge = 7 * 24 * time.Hour
maxTracked = 50000 // would and bans
maxNbr = 20000 // prefixes of the neighbor rule
saveEvery = 30 * time.Second
)
@@ -186,7 +197,8 @@ type Engine struct {
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)
nbr map[netip.Prefix]map[netip.Addr]int64 // banned addresses per /24 or /64 (unix of the ban)
allows map[netip.Addr]int64 // operator allowances: address -> until (unix)
unbans []UnbanWire
queue []cand
}
@@ -212,7 +224,7 @@ func New(c Config) *Engine {
}
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{}}
counts: Counts{Skipped: map[string]int{}}, long: map[netip.Addr]*longRec{}, nbr: map[netip.Prefix]map[netip.Addr]int64{}, 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{}}
@@ -240,7 +252,7 @@ func (e *Engine) LogPath() string { return e.cfg.Path }
// 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.Ban, core.SSHFail, core.SSHProbe, core.Scanner, core.Exploit, core.BruteForce:
case core.OK:
if ev.FetchDest != "document" || ev.Status < 200 || ev.Status > 299 {
return
@@ -429,6 +441,7 @@ func (e *Engine) process(ev core.Event, fam string) {
st.banned = max(st.banned, ev.Time.Add(banAssume).Unix())
st.f2bAt = max(st.f2bAt, ts)
}
e.noteBan(a, ts, now)
}
return
case LegitVisit(ev):
@@ -436,7 +449,7 @@ func (e *Engine) process(ev core.Event, fam string) {
e.stateOf(a).legit = max(e.stateOf(a).legit, ts)
}
return
case ev.Cat == core.SSHFail:
case ev.Cat == core.SSHFail, ev.Cat == core.SSHProbe:
case ev.Source == "probe" && ev.Cat == core.Scanner:
e.processProbe(a, ev, now)
return
@@ -454,9 +467,12 @@ func (e *Engine) process(ev core.Event, fam string) {
}
cut := now.Add(-Window).Unix()
slug, crit := attackSlug(ev, fam)
if ev.Cat == core.SSHFail {
switch {
case ev.Cat == core.SSHFail:
st.ssh = prune(append(st.ssh, ts), cut)
} else {
case ev.Cat == core.SSHProbe:
st.sshp = prune(append(st.sshp, ts), cut)
default:
st.ev = append(st.ev, aevt{ts, slug})
k := 0
for _, x := range st.ev {
@@ -489,8 +505,13 @@ func (e *Engine) process(ev core.Event, fam string) {
lr.fresh = false
} else if ev.Cat == core.SSHFail {
lr.ssh++
lr.ssh7++
} else if ev.Cat == core.SSHProbe {
lr.probe++
lr.probe7++
} else {
lr.web++
lr.web7++
}
}
crits := 0
@@ -499,17 +520,19 @@ func (e *Engine) process(ev core.Event, fam string) {
crits++
}
}
in := Input{Now: now, Attacks: len(st.ev), Top: topSlug(st.ev), SSHFails: len(st.ssh), Crits: crits,
in := Input{Now: now, Attacks: len(st.ev), Top: topSlug(st.ev), SSHFails: len(st.ssh), SSHProbes: len(st.sshp), 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
in.Known, in.SSH24, in.Web24, in.Probe24 = lr.known, lr.ssh, lr.web, lr.probe
in.SSH7, in.Web7, in.Probe7 = lr.ssh7, lr.web7, lr.probe7
}
in.Neighbor = e.neighborBanned(a, now) >= NeighborIPs
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) {
if d.Action == ActBan && e.cfg.Crawler != nil && e.cfg.Crawler(a.String(), st.uas) {
in.Exclude = SkipCrawler
d = Decide(in, Params{Threshold: e.cfg.Threshold})
}
@@ -624,11 +647,74 @@ func (e *Engine) apply(a netip.Addr, st *ipState, d Decision, src string, now ti
b.Until, b.Last = now.Add(d.TTL).Unix(), now.Unix()
e.bans[a] = b
st.urutauAt = now.Unix()
e.noteBan(a, now.Unix(), now)
e.dirty = true
e.addRecent(a, r)
}
}
// noteBan remembers a ban of a (by any jail or by this engine) for the neighbor
// rule; the lock is held. Memory is bounded: expired entries go, and the table is
// reset past maxNbr prefixes.
func (e *Engine) noteBan(a netip.Addr, ts int64, now time.Time) {
p, ok := neighborPrefix(a)
if !ok {
return
}
if len(e.nbr) >= maxNbr {
cut := now.Add(-NeighborWindow).Unix()
for k, m := range e.nbr {
for ip, t := range m {
if t < cut {
delete(m, ip)
}
}
if len(m) == 0 {
delete(e.nbr, k)
}
}
if len(e.nbr) >= maxNbr {
e.nbr = map[netip.Prefix]map[netip.Addr]int64{}
}
}
m := e.nbr[p]
if m == nil {
m = map[netip.Addr]int64{}
e.nbr[p] = m
}
if len(m) < 256 || m[a] > 0 {
m[a] = max(m[a], ts)
}
}
// neighborBanned counts the addresses other than a banned in the last
// NeighborWindow in a's /24 (v4) or /64 (v6); the lock is held.
func (e *Engine) neighborBanned(a netip.Addr, now time.Time) int {
p, ok := neighborPrefix(a)
if !ok {
return 0
}
cut := now.Add(-NeighborWindow).Unix()
n := 0
for ip, t := range e.nbr[p] {
if ip != a && t >= cut {
n++
}
}
return n
}
// neighborPrefix is the /24 (IPv4) or /64 (IPv6) of a.
func neighborPrefix(a netip.Addr) (netip.Prefix, bool) {
a = a.Unmap()
bits := 64
if a.Is4() {
bits = 24
}
p, err := a.Prefix(bits)
return p, err == nil
}
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())
@@ -710,6 +796,7 @@ func (e *Engine) Report(from int64) Report {
continue
}
cv.AttackIPs++
blocked := true
switch {
case st.f2bAt > 0 && st.f2bAt >= from:
cv.BlockedByFirewall++
@@ -719,6 +806,11 @@ func (e *Engine) Report(from int64) Report {
cv.WouldBlock++
default:
cv.Unblocked++
blocked = false
}
cv.Repeat++ // without the registry only repeated attackers are known
if !blocked {
cv.RepeatUnblocked++
}
}
c := e.counts
+20 -8
View File
@@ -33,7 +33,7 @@ func (e *Engine) prefetch(ev core.Event) {
if e.cfg.Rep == nil && e.cfg.Tally == nil {
return
}
if ev.Cat != core.SSHFail && !CountsAsAttack(ev) {
if ev.Cat != core.SSHFail && ev.Cat != core.SSHProbe && !CountsAsAttack(ev) {
return
}
a, err := netip.ParseAddr(ev.IP)
@@ -59,9 +59,9 @@ func (e *Engine) prefetch(ev core.Event) {
known = IsKnown(sc, lv)
}
}
var ssh, web int
var tl Tally
if stale && e.cfg.Tally != nil {
ssh, web = e.cfg.Tally(a.String(), now.Add(-LongWindow).Unix())
tl = e.cfg.Tally(a.String(), now.Add(-WeekWindow).Unix())
}
e.mu.Lock()
defer e.mu.Unlock()
@@ -83,7 +83,8 @@ func (e *Engine) prefetch(ev core.Event) {
}
lr.known = known
if stale {
lr.ssh, lr.web, lr.at, lr.fresh = ssh, web, now.Unix(), true
lr.ssh, lr.web, lr.probe, lr.ssh7, lr.web7, lr.probe7 = tl.SSH, tl.Web, tl.Probe, max(tl.SSH7, tl.SSH), max(tl.Web7, tl.Web), max(tl.Probe7, tl.Probe)
lr.at, lr.fresh = now.Unix(), true
}
}
@@ -99,7 +100,7 @@ func (e *Engine) Sweep() {
}
defer e.sweeping.Store(false)
now := e.cfg.Now()
from := now.Add(-LongWindow).Unix()
from := now.Add(-WeekWindow).Unix()
roster := e.cfg.Roster(from)
var tallies map[string]Tally
if e.cfg.Tallies != nil {
@@ -120,12 +121,14 @@ func (e *Engine) Sweep() {
a = a.Unmap().WithZone("")
st := e.stateOf(a)
t := tallies[a.String()]
t.SSH, t.Web = max(t.SSH, r.Est.SSH), max(t.Web, r.Est.Web)
in := Input{Now: now, Known: IsKnown(r.Score, r.Level), SSH24: t.SSH, Web24: t.Web,
t = Tally{max(t.SSH, r.Est.SSH), max(t.Web, r.Est.Web), max(t.Probe, r.Est.Probe),
max(t.SSH7, r.Est.SSH7, t.SSH), max(t.Web7, r.Est.Web7, t.Web), max(t.Probe7, r.Est.Probe7, t.Probe)}
in := Input{Now: now, Known: IsKnown(r.Score, r.Level), SSH24: t.SSH, Web24: t.Web, Probe24: t.Probe,
SSH7: t.SSH7, Web7: t.Web7, Probe7: t.Probe7, Neighbor: e.neighborBanned(a, now) >= NeighborIPs && r.Last >= now.Add(-LongWindow).Unix() && r.Last > 0,
Legit: st.legit >= now.Add(-LegitWindow).Unix(), Exclude: e.excl.Excluded(a)}
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) {
if d.Action == ActBan && e.cfg.Crawler != nil && e.cfg.Crawler(a.String(), st.uas) {
in.Exclude = SkipCrawler
d = Decide(in, Params{Threshold: e.cfg.Threshold})
}
@@ -187,6 +190,12 @@ func (e *Engine) coverageOf(roster []Seen, from int64) Coverage {
ours = true
}
st := e.ips[a]
repeat := r.Events >= 2
if repeat {
cv.Repeat++
} else {
cv.OneShot++
}
switch {
case f2b:
cv.BlockedByFirewall++
@@ -196,6 +205,9 @@ func (e *Engine) coverageOf(roster []Seen, from int64) Coverage {
cv.WouldBlock++
default:
cv.Unblocked++
if repeat {
cv.RepeatUnblocked++
}
}
}
return cv
+2 -2
View File
@@ -61,7 +61,7 @@ func contains(s, sub string) bool {
func TestSlowSSH24h(t *testing.T) {
r := histRig(t, func(c *Config) {
c.Tally = func(ip string, from int64) (int, int) { return 9, 0 } // 9 already in the registry
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 {
@@ -77,7 +77,7 @@ func TestSlowSSH24h(t *testing.T) {
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) (int, int) { return 500, 500 }
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}}
}
+51 -21
View File
@@ -35,13 +35,16 @@ const (
ReasonLog4Shell = "log4shell"
ReasonPortScan = "port-scan"
ReasonKnownAttacker = "known-attacker"
// ReasonNeighbor: another address of a /24 (v4) or /64 (v6) where several
// addresses were banned in the last 24 h attacked again.
ReasonNeighbor = "neighbor-campaign"
)
var reasons = map[string]bool{
ReasonScannerFlood: true, ReasonExploitFlood: true, ReasonWebBrute: true, ReasonWPBrute: true,
ReasonSSHBrute: true, ReasonRCE: true, ReasonTraversal: true, ReasonEnvProbe: true,
ReasonVCSProbe: true, ReasonWebshell: true, ReasonSQLi: true, ReasonLog4Shell: true,
ReasonPortScan: true, ReasonKnownAttacker: true,
ReasonPortScan: true, ReasonKnownAttacker: true, ReasonNeighbor: true,
}
// ValidReason reports whether s is one of the fixed slugs.
@@ -72,6 +75,17 @@ const (
SSH24Threshold = 10
Web24Threshold = 20
LongWindow = 24 * time.Hour
// WeekWindow is the slow-attacker window: SSH7Threshold SSH failures (an
// ssh-probe counts half), or Web7Threshold web scan/exploit events without a
// legitimate visit, in 7 days justify a ban.
WeekWindow = 7 * 24 * time.Hour
SSH7Threshold = 10
Web7Threshold = 10
// ProbeWeight is the weight of one ssh-probe against the SSH rules (in halves).
// NeighborIPs distinct banned addresses of one prefix in NeighborWindow make
// the prefix a campaign: one attack event of another address of it is enough.
NeighborIPs = 3
NeighborWindow = 24 * time.Hour
// KnownSuspiciousScore: a "suspicious" address at or above this score counts as a known attacker.
KnownSuspiciousScore = 100
)
@@ -113,23 +127,32 @@ const (
// Input is everything Decide needs about one address.
type Input struct {
Now time.Time
Attacks int // counted attack events in the window
Top string // reason slug of the dominant attack in the window
SSHFails int // failed SSH logins in the window
Probes int // distinct (proto, port) probed in the window
Crit string // reason of a critical family hit just seen, "" if none
Crits int // critical events of the address in the window (a single hit is not enough)
Legit bool // a document 2xx from a browser within the last 24 h
Exclude string // Excluded() result or "crawler"
Banned bool // fail2ban already blocks it
Active bool // an advisory ban is still valid
Offences int
Known bool // the store's verdict is hostile (or suspicious with a high score)
SSH24 int // failed SSH logins in LongWindow
Web24 int // web scan/exploit events in LongWindow
Now time.Time
Attacks int // counted attack events in the window
Top string // reason slug of the dominant attack in the window
SSHFails int // failed SSH logins in the window
SSHProbes int // ssh-probe events in the window (each counts half a failure)
Probes int // distinct (proto, port) probed in the window
Crit string // reason of a critical family hit just seen, "" if none
Crits int // critical events of the address in the window (a single hit is not enough)
Legit bool // a document 2xx from a browser within the last 24 h
Exclude string // Excluded() result or "crawler"
Banned bool // fail2ban already blocks it
Active bool // an advisory ban is still valid
Offences int
Known bool // the store's verdict is hostile (or suspicious with a high score)
SSH24 int // failed SSH logins in LongWindow
Web24 int // web scan/exploit events in LongWindow
Probe24 int // ssh-probe events in LongWindow
SSH7 int // failed SSH logins in WeekWindow
Probe7 int // ssh-probe events in WeekWindow
Web7 int // web scan/exploit events in WeekWindow
Neighbor bool // an attack event just seen, in a prefix with NeighborIPs banned addresses
}
// sshEff is failures plus half the probes.
func sshEff(fails, probes int) int { return fails + probes/2 }
// Params are the thresholds.
type Params struct{ Threshold int }
@@ -156,8 +179,9 @@ func Decide(in Input, p Params) Decision {
switch {
case in.Crit != "" && in.Crits >= CritHits:
reason, score = in.Crit, 90
case in.SSHFails >= sshTh:
reason, score = ReasonSSHBrute, min(100, 60+(in.SSHFails-sshTh)*5)
case sshEff(in.SSHFails, in.SSHProbes) >= sshTh:
n := sshEff(in.SSHFails, in.SSHProbes)
reason, score = ReasonSSHBrute, min(100, 60+(n-sshTh)*5)
case in.Probes >= PortScanPorts:
reason, score = ReasonPortScan, min(100, 60+(in.Probes-PortScanPorts)*3)
case in.Attacks >= th:
@@ -165,12 +189,18 @@ func Decide(in Input, p Params) Decision {
if !ValidReason(reason) {
reason = ReasonScannerFlood
}
case in.Neighbor && !in.Legit:
reason, score = ReasonNeighbor, 70
case in.Known:
reason, score = ReasonKnownAttacker, 80
case in.SSH24 >= SSH24Threshold:
reason, score = ReasonSSHBrute, min(100, 60+(in.SSH24-SSH24Threshold))
case sshEff(in.SSH24, in.Probe24) >= SSH24Threshold:
reason, score = ReasonSSHBrute, min(100, 60+(sshEff(in.SSH24, in.Probe24)-SSH24Threshold))
case in.Web24 >= Web24Threshold:
reason, score = ReasonScannerFlood, min(100, 55+(in.Web24-Web24Threshold)/2)
case sshEff(in.SSH7, in.Probe7) >= SSH7Threshold:
reason, score = ReasonSSHBrute, min(100, 60+(sshEff(in.SSH7, in.Probe7)-SSH7Threshold)/2)
case in.Web7 >= Web7Threshold && !in.Legit:
reason, score = ReasonScannerFlood, min(100, 55+(in.Web7-Web7Threshold)/2)
default:
return Decision{}
}
@@ -264,7 +294,7 @@ func (x Exclusions) Excluded(a netip.Addr) string {
// attackSlug is the reason slug of one attack event, and whether it is critical.
func attackSlug(ev core.Event, fam string) (slug string, crit bool) {
if ev.Cat == core.SSHFail {
if ev.Cat == core.SSHFail || ev.Cat == core.SSHProbe {
return ReasonSSHBrute, false
}
if r, ok := criticalFam[fam]; ok {
+215
View File
@@ -0,0 +1,215 @@
package enforce
import (
"net/netip"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
)
func TestDecideSlowRules(t *testing.T) {
p := Params{Threshold: 5}
cases := []struct {
name string
in Input
act string
why string
}{
{"10 probes in window = 5 fails", Input{SSHProbes: 10}, ActBan, ReasonSSHBrute},
{"9 probes", Input{SSHProbes: 9}, ActNone, ""},
{"fails and probes mix", Input{SSHFails: 3, SSHProbes: 4}, ActBan, ReasonSSHBrute},
{"ssh 7 days", Input{SSH7: 14}, ActBan, ReasonSSHBrute},
{"ssh 7 days below", Input{SSH7: 9}, ActNone, ""},
{"23.132.164.185 profile", Input{SSH7: 18, Probe7: 10}, ActBan, ReasonSSHBrute},
{"77.239.124.130 profile", Input{Probe7: 28}, ActBan, ReasonSSHBrute},
{"probes 24h", Input{Probe24: 20}, ActBan, ReasonSSHBrute},
{"web 7 days", Input{Web7: 10}, ActBan, ReasonScannerFlood},
{"web 7 days below", Input{Web7: 9}, ActNone, ""},
{"web 7 days with a legit visit", Input{Web7: 30, Legit: true}, ActNone, ""},
{"neighbor", Input{Neighbor: true}, ActBan, ReasonNeighbor},
{"neighbor legit", Input{Neighbor: true, Legit: true}, ActNone, ""},
{"neighbor trusted", Input{Neighbor: true, Exclude: SkipTrusted}, ActSkip, ""},
{"neighbor crawler", Input{Neighbor: true, Exclude: SkipCrawler}, ActSkip, ""},
{"neighbor operator", Input{Neighbor: true, Exclude: SkipOperator}, ActSkip, ""},
{"neighbor already banned", Input{Neighbor: true, Banned: true}, ActAlready, ""},
}
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)
}
}
if !ValidReason(ReasonNeighbor) || ReasonNeighbor != "neighbor-campaign" {
t.Fatal("slug")
}
}
func probeEv(ip string, at time.Time) core.Event {
return core.Event{Time: at, IP: ip, Cat: core.SSHProbe, Source: "ssh"}
}
func TestSSHProbesBanLive(t *testing.T) {
r := histRig(t, nil)
for i := 0; i < 9; i++ {
r.e.handle(probeEv("203.0.114.70", r.now.Add(-time.Duration(i)*time.Second)), "")
}
if len(r.lines(t)) != 0 {
t.Fatal("9 probes must not ban")
}
r.e.handle(probeEv("203.0.114.70", r.now), "")
if l := r.lines(t); len(l) != 1 || !contains(l[0], "ssh-bruteforce") {
t.Fatalf("%v", l)
}
}
func TestSlowWeekLive(t *testing.T) {
r := histRig(t, func(c *Config) {
c.Tally = func(string, int64) Tally { return Tally{SSH: 2, SSH7: 13} } // 144.22.238.238: 14 in 7 days
})
r.e.handle(sshEv("203.0.114.71", r.now), "")
if l := r.lines(t); len(l) != 1 || !contains(l[0], "ssh-bruteforce") {
t.Fatalf("%v", l)
}
}
func TestSweepWeekAndNeighbors(t *testing.T) {
r := histRig(t, func(c *Config) {
c.Roster = func(from int64) []Seen {
if from > r0(t0).Add(-6*24*time.Hour).Unix() {
t.Errorf("sweep must look back 7 days, from=%d", from)
}
return []Seen{
{IP: "203.0.114.80", Score: 20, Level: core.LevelSuspicious, Events: 14, Last: t0.Add(-2 * 24 * time.Hour).Unix()},
{IP: "203.0.114.81", Score: 20, Level: core.LevelSuspicious, Events: 3, Last: t0.Add(-2 * 24 * time.Hour).Unix()},
}
}
c.Tallies = func(int64) map[string]Tally {
return map[string]Tally{"203.0.114.80": {SSH7: 14}, "203.0.114.81": {SSH7: 3}}
}
})
r.e.Sweep()
r.e.drain()
if l := r.lines(t); len(l) != 1 || !contains(l[0], "203.0.114.80") {
t.Fatalf("%v", l)
}
}
func r0(t time.Time) time.Time { return t }
func ban(ip string, at time.Time, jail string) core.Event {
return core.Event{Time: at, IP: ip, Cat: core.Ban, Source: "fail2ban", Jail: jail}
}
func TestNeighborCampaign(t *testing.T) {
r := histRig(t, nil)
for _, ip := range []string{"203.0.114.1", "203.0.114.2"} {
r.e.process(ban(ip, r.now.Add(-time.Hour), "sshd"), "")
}
r.e.process(atk("203.0.114.9", r.now, "/x", 404), "")
if len(r.lines(t)) != 0 {
t.Fatal("two banned neighbors are not a campaign")
}
r.e.process(ban("203.0.114.3", r.now.Add(-time.Hour), "sshd"), "")
r.e.process(atk("203.0.114.9", r.now, "/x", 404), "")
l := r.lines(t)
if len(l) != 1 || !contains(l[0], "ip=203.0.114.9") || !contains(l[0], "neighbor-campaign") {
t.Fatalf("%v", l)
}
// another /24 is untouched
r.e.process(atk("203.0.115.9", r.now, "/x", 404), "")
if len(r.lines(t)) != 1 {
t.Fatal("other prefix banned")
}
// bans older than 24 h expire
r.now = r.now.Add(25 * time.Hour)
r.e.process(atk("203.0.114.77", r.now, "/x", 404), "")
if len(r.lines(t)) != 1 {
t.Fatal("expired campaign banned")
}
}
func TestNeighborRespectsExclusions(t *testing.T) {
r := histRig(t, func(c *Config) { c.Crawler = func(ip string, _ []string) bool { return ip == "203.0.114.9" } })
for _, ip := range []string{"203.0.114.1", "203.0.114.2", "203.0.114.3"} {
r.e.process(ban(ip, r.now.Add(-time.Hour), "sshd"), "")
}
r.e.process(atk("203.0.114.9", r.now, "/x", 404), "") // verified crawler, no UA at all
if len(r.lines(t)) != 0 {
t.Fatalf("crawler banned: %v", r.lines(t))
}
r.e.process(atk("203.0.114.10", r.now, "/x", 404), "")
if len(r.lines(t)) != 1 {
t.Fatal("expected one ban")
}
// operator allowance
if err := r.e.Unban(mustAddr("203.0.114.11"), 3600, "t"); err != nil && err != ErrNoUnbanLog {
t.Fatal(err)
}
// trusted prefix inside the campaign
r.e.process(ban("168.196.85.1", r.now, "sshd"), "")
r.e.process(ban("168.196.85.2", r.now, "sshd"), "")
r.e.process(ban("168.196.85.3", r.now, "sshd"), "")
r.e.process(atk("168.196.85.9", r.now, "/x", 404), "")
for _, l := range r.lines(t) {
if contains(l, "168.196.85.9") {
t.Fatal("trusted banned")
}
}
}
func TestNeighborV6AndPeers(t *testing.T) {
r := histRig(t, nil)
for _, ip := range []string{"2606:4701:1:2::1", "2606:4701:1:2::2", "2606:4701:1:2::3"} {
r.e.process(ban(ip, r.now.Add(-time.Hour), "sshd"), "")
}
r.e.process(atk("2606:4701:1:2::99", r.now, "/x", 404), "")
if l := r.lines(t); len(l) != 1 || !contains(l[0], "neighbor-campaign") {
t.Fatalf("%v", l)
}
// a peer may send the slug; this node must have seen the address attack
r.e.process(atk("203.0.114.200", r.now, "/x", 404), "")
acc, inv := r.e.AcceptPeer("hub", []Wire{{T: r.now.Unix(), IP: "203.0.114.200", Reason: ReasonNeighbor, Score: 70, TTL: 3600}})
if acc != 1 || inv != 0 {
t.Fatalf("accepted %d invalid %d", acc, inv)
}
}
func TestOwnJailBanDoesNotChangeAttackLogic(t *testing.T) {
r := histRig(t, nil)
r.e.process(ban("203.0.114.5", r.now, "urutau"), "")
if st := r.e.ips[mustAddr("203.0.114.5")]; st == nil || st.f2bAt != 0 || st.urutauAt == 0 {
t.Fatalf("%+v", st)
}
}
func TestCrawlerExcludedWithoutUA(t *testing.T) {
r := histRig(t, func(c *Config) { c.Crawler = func(string, []string) bool { return true } })
e := atk("203.0.114.40", r.now, "/.env", 404)
e.UA = ""
for i := 0; i < 10; i++ {
e.Time = r.now.Add(-time.Duration(i) * time.Second)
r.e.process(e, "env-credentials")
}
if len(r.lines(t)) != 0 || r.e.counts.Skipped[SkipCrawler] == 0 {
t.Fatalf("%v %v", r.lines(t), r.e.counts.Skipped)
}
}
func TestCoverageOneShot(t *testing.T) {
r := histRig(t, func(c *Config) {
c.Roster = func(int64) []Seen {
return []Seen{
{IP: "203.0.114.90", Events: 1},
{IP: "203.0.114.91", Events: 5},
{IP: "203.0.114.92", Events: 5, Jails: []string{"sshd"}},
}
}
})
cv := r.e.Report(0).Coverage
if cv.AttackIPs != 3 || cv.OneShot != 1 || cv.Repeat != 2 || cv.RepeatUnblocked != 1 || cv.Unblocked != 2 {
t.Fatalf("%+v", cv)
}
}
func mustAddr(s string) netip.Addr { return netip.MustParseAddr(s) }