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

+14 -5
View File
@@ -38,14 +38,19 @@ func newEnforce(c Config, st *store.Store, peers []fed.Peer, en enricher, ready
Mode: mode, Path: c.EnforceLog, UnbanPath: unbanLogPath(c), StatePath: filepath.Join(c.DataDir, "enforce.json"), Host: c.Name,
Threshold: c.EnforceThreshold, MaxPerMin: c.EnforceMaxPerMin, Share: strings.EqualFold(c.EnforceShare, "on"),
Trusted: trusted, PeerHosts: hosts, InfraHosts: hosts, Resolve: resolveHost,
Crawler: func(ip string, uas []string) bool { v := st.FCrDNS(ip, uas); return v != nil && *v },
Rep: st.Reputation,
Tally: func(ip string, from int64) (int, int) { t := st.AttackTally(ip, from); return t.SSH, t.Web },
Crawler: func(ip string, uas []string) bool {
if v := st.FCrDNS(ip, uas); v != nil && *v {
return true
}
return st.VerifiedCrawler(ip) // forward-confirmed rDNS excludes it whatever the User-Agent says
},
Rep: st.Reputation,
Tally: func(ip string, from int64) enforce.Tally { return tallyOf(st.AttackTally(ip, from)) },
Roster: func(from int64) []enforce.Seen {
rows := st.AttackRoster(from)
out := make([]enforce.Seen, len(rows))
for i, r := range rows {
out[i] = enforce.Seen{IP: r.IP, Score: r.Score, Level: r.Level, Jails: r.Jails, Est: enforce.Tally{SSH: r.Est.SSH, Web: r.Est.Web}}
out[i] = enforce.Seen{IP: r.IP, Score: r.Score, Level: r.Level, Jails: r.Jails, Events: r.Events, Last: r.Last, Est: tallyOf(r.Est)}
}
return out
},
@@ -53,7 +58,7 @@ func newEnforce(c Config, st *store.Store, peers []fed.Peer, en enricher, ready
m := st.AttackTallies(from)
out := make(map[string]enforce.Tally, len(m))
for k, v := range m {
out[k] = enforce.Tally{SSH: v.SSH, Web: v.Web}
out[k] = tallyOf(v)
}
return out
},
@@ -203,3 +208,7 @@ func unbanLogPath(c Config) string {
}
return filepath.Join(filepath.Dir(c.EnforceLog), "unban.log")
}
func tallyOf(t store.Tally24) enforce.Tally {
return enforce.Tally{SSH: t.SSH, Web: t.Web, Probe: t.Probe, SSH7: t.SSH7, Web7: t.Web7, Probe7: t.Probe7}
}
+1 -1
View File
@@ -2,4 +2,4 @@ package app
// Version is the release version (SemVer). Release builds may override it with
// -ldflags "-X .../internal/app.Version=...".
var Version = "1.5.7"
var Version = "1.6.0"
+39
View File
@@ -103,7 +103,46 @@ func refusedProbe(path string) bool {
return false
}
var forgeGitea = map[string]bool{"src": true, "raw": true, "blame": true, "commits": true, "commit": true, "media": true, "history": true}
var forgeRef = map[string]bool{"branch": true, "commit": true, "tag": true}
var forgeGeneric = map[string]bool{"blob": true, "tree": true, "raw": true, "blame": true, "commits": true}
// ForgeBrowse reports whether the (decoded, lowercase, query-less) path is a
// code forge page that shows repository content: Gitea/Forgejo
// /{owner}/{repo}/(src|raw|blame|commits|commit|media|history)/(branch|commit|tag)/<ref>/<file>,
// GitHub style /{owner}/{repo}/(blob|tree|raw|blame|commits)/<ref>/<file> and
// GitLab style /{group}/{project}/-/(blob|tree|raw|blame|commits)/<ref>/<file>.
// A file named ".env" inside a repository is content, not a probe of the host.
// It needs an owner and a repo that are not dot names, so "/.env", "/.git/config"
// or "/app/.env" are never forge paths. Traversal markers are checked before.
func ForgeBrowse(path string) bool {
if len(path) == 0 || path[0] != '/' {
return false
}
seg := strings.Split(path[1:], "/")
if len(seg) < 4 || seg[0] == "" || seg[1] == "" || seg[0][0] == '.' || seg[1][0] == '.' {
return false
}
for i := 2; i+3 < len(seg); i++ { // GitLab: /group/project/-/blob/<ref>/<file>
if seg[i] == "-" && forgeGeneric[seg[i+1]] && seg[i+2] != "" && seg[i+3] != "" {
return true
}
}
if seg[2] != "" && seg[3] != "" && len(seg) >= 5 && seg[4] != "" {
if forgeGitea[seg[2]] && forgeRef[seg[3]] {
return true // Gitea: /owner/repo/src/commit/<sha>/<file>
}
if forgeGeneric[seg[2]] {
return true // GitHub: /owner/repo/blob/<ref>/<file>
}
}
return false
}
func isScanner(path string, status int) bool {
if ForgeBrowse(path) {
return false
}
for _, m := range sensitive {
if segment(path, m) {
return true
+32
View File
@@ -0,0 +1,32 @@
package core
import "testing"
func TestForgeBrowseIsNotScanner(t *testing.T) {
for _, p := range []string{
"/ciberfauna/sabia/src/commit/0123abcd/.gitignore",
"/ciberfauna/sabia/raw/commit/0123abcd/.gitignore",
"/lucasrguerra/LambdaMail/src/commit/0123abcd/.env.example",
"/ciberfauna/guara/blame/commit/0123abcd/.gitignore",
"/ciberfauna/acaua/commits/commit/0123abcd/.gitignore",
"/ciberfauna/acaua/src/branch/main/.gitignore",
"/ciberfauna/acaua/src/tag/v1.0.0/.env.example",
"/org/repo/blob/main/.gitignore",
"/org/repo/tree/main/.github/workflows",
"/group/proj/-/blob/main/.env.example",
} {
c := Classify("GET", p, 200)
if c.Cat != OK {
t.Errorf("%s: %+v", p, c)
}
}
}
func TestForgeBrowseKeepsRealProbes(t *testing.T) {
for _, p := range []string{"/.env", "/.git/config", "/app/.env", "/.gitignore", "/app/.git/config", "/x/y/.env",
"/ciberfauna/sabia/src/commit/abc/../../../.env", "/.git/src/commit/abc/x", "/a/b/src/main/.env", "/wp-config.php"} {
if c := Classify("GET", p, 200); c.Cat == OK {
t.Errorf("%s must stay a probe: %+v", p, c)
}
}
}
+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) }
+10
View File
@@ -148,6 +148,13 @@ func vcsMarker(dec string) string {
return firstSub(dec, vcsRules)
}
func pathOnly(p string) string {
if i := strings.IndexAny(p, "?#"); i >= 0 {
return p[:i]
}
return p
}
func backupMarker(dec string) string {
p := dec
if i := strings.IndexAny(p, "?#"); i >= 0 {
@@ -185,6 +192,9 @@ func matchFamily(raw, dec string) (fam, marker string) {
if m := firstSub(sp, rceRules); m != "" {
return FamRCE, m
}
if core.ForgeBrowse(pathOnly(dec)) { // repository content on a code forge, not a probe
return "", ""
}
if m := webshellMarker(dec); m != "" {
return FamWebshell, m
}
+24
View File
@@ -0,0 +1,24 @@
package intel
import (
"testing"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
)
func TestForgeBrowseHasNoFamily(t *testing.T) {
for _, p := range []string{"/ciberfauna/sabia/src/commit/0123abcd/.gitignore", "/lucasrguerra/LambdaMail/src/commit/0123abcd/.env.example",
"/ciberfauna/guara/blame/commit/0123abcd/.gitignore"} {
if f := Family(p, core.OK, 200, false); f != "" {
t.Errorf("%s: %q", p, f)
}
if f := PathFamily(p); f != "" {
t.Errorf("PathFamily %s: %q", p, f)
}
}
for p, want := range map[string]string{"/.env": FamEnvCreds, "/.git/config": FamVCS, "/app/.env": FamEnvCreds} {
if f := PathFamily(p); f != want {
t.Errorf("%s: %q want %q", p, f, want)
}
}
}
+1 -1
View File
@@ -140,7 +140,7 @@ var reportText = map[string][2]string{
"d.refused": {"Exploits recusados", "Exploits refused"},
"d.cover.m": {"Parte dos IPs hostis que já estava banida.", "Share of hostile IPs that were already banned."},
"d.mttb.m": {"Quanto menor, melhor: é a janela entre o primeiro ataque e o bloqueio.", "Lower is better: the window between the first attack and the block."},
"d.block.m": {"Parte dos atacantes que já constava em listas públicas de bloqueio.", "Share of attackers already in public blocklists."},
"d.block.m": {"Parte dos atacantes hostis protegidos: na lista de bloqueio publicada ou já banidos por algum jail.", "Share of hostile attackers protected: on the published blocklist or already banned by a jail."},
"d.expo.m": {"Parte dos ataques que recebeu resposta de sucesso. Deve ficar perto de zero.", "Share of attacks that got a success answer. Should stay near zero."},
"d.refused.m": {"Parte das tentativas de exploração recusada pelo servidor.", "Share of exploit attempts refused by the server."},
"e.mode": {"Modo", "Mode"},
+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 {