Compare commits

...
3 Commits
Author SHA1 Message Date
Lucas RayanandClaude Opus 5.5 22ccde539b chore: merge fix-bloqueio (1.6.0) with mobile tables (1.5.8)
Release / ci (push) Successful in 1m44s
Release / Build image (arm64) (push) Successful in 1m15s
Release / Plan (reuse the published image?) (push) Successful in 6s
CI / Docker image (build and smoke test) (push) Skipped
Release / Build image (amd64) (push) Successful in 24s
CI / Format and vet (push) Successful in 1m9s
CI / Tests (Linux, race detector) (push) Successful in 36s
CI / Dependency audit (push) Successful in 35s
Release / Publish tags (push) Successful in 14s
Release / Gitea release (push) Successful in 5s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 20:31:13 -03:00
Lucas RayanandClaude Opus 5.5 bc3ce09088 fix: phones render plain data tables as stacked cards (1.5.8)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 20:30:18 -03:00
Lucas RayanandClaude Opus 5.5 54b9ae65cd 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>
2026-11-15 20:26:56 -03:00
29 changed files with 926 additions and 101 deletions

No files matched your search

+20
View File
@@ -4,6 +4,26 @@
Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versions follow SemVer.
## [1.6.0] - 2026-11-15
### Fixed
- Code forge browsing is no longer an attack: crawlers (a Alibaba range and Googlebot) reading `/owner/repo/src/commit/<sha>/.gitignore`, `/raw/commit/...`, `/blame/...`, `/commits/...`, `.env.example` and similar repository files on a public Gitea (also GitHub and GitLab style `blob`/`tree`/`raw` paths) were classified as scanner, env-probe and vcs-probe, about 58% of the "attackers". Real probes (`/.env`, `/.git/config`, `/app/.env`, traversal) are unchanged.
- The second firewall excluded crawlers only when the User-Agent claimed to be one, so a verified Googlebot ("GoogleOther") got banned. A forward-confirmed reverse DNS (googlebot.com, google.com, search.msn.com, applebot.apple.com) now excludes the address whatever the User-Agent says; more crawler User-Agents (GoogleOther, Google-InspectionTool, AdsBot, Apple) are recognized.
- Feedback loop: bans of the `urutau` jail (our own decisions) and of `recidive` (which only repeats bans) no longer count as evidence: no score, no strong signal, no blocklist listing. Bans of independent jails (sshd, traefik...) still count.
- The blocklist coverage was misleading (3%): it counted only listed attackers.
### Changed
- Coverage (`blocklist.coverage_pct`, `blocklist_coverage`) now counts an attacker as protected when it is listed or banned by any jail. New fields, additive: `blocklist.attackers`, `covered`, `one_shot`, `repeat_ips`, `repeat_covered`, `repeat_coverage_pct` in `/api/v1/defense`, and `one_shot`, `repeat_ips`, `repeat_unblocked` in the enforce `coverage`.
- Enforce policy for slow attackers: `ssh-probe` events count half a failure in the SSH rules; a 7-day window bans at 10 SSH failures (probes count half) or 10 web scan/exploit events without a legitimate visit (bounded memory); new reason `neighbor-campaign`: when 3 or more distinct addresses of a /24 (IPv4) or /64 (IPv6) were banned in the last 24 h, one attack event of another address of the prefix is enough. All exclusions (trusted, private, crawler, infrastructure, legitimate visitor, operator) still apply, and peers accept the new reason.
## [1.5.8] - 2026-11-15
### Fixed
- Phones: plain data tables (Concentration ranking, Errors routes, MITRE techniques, Defense, Integrity sources, and any other table without its own phone layout) rendered as squeezed columns with IPs broken letter by letter or sideways scrolling. Under 768 px their rows now become stacked cards with the column name as label, right-aligned numbers and long text wrapping; desktop is unchanged. One shared rule in `style.css` plus `cardTables()` in `app.js` covers all of them. `TABLES_ONLY=1 scripts/screenshots.sh` captures every table page at 375x812 and checks for horizontal overflow.
## [1.5.7] - 2026-11-15
### Fixed
+20
View File
@@ -4,6 +4,26 @@
Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/); versionamento segue SemVer.
## [1.6.0] - 2026-11-15
### Corrigido
- Navegar em forja de código não é mais ataque: crawlers (uma faixa da Alibaba e o Googlebot) lendo `/dono/repo/src/commit/<sha>/.gitignore`, `/raw/commit/...`, `/blame/...`, `/commits/...`, `.env.example` e arquivos parecidos de repositório num Gitea público (também caminhos `blob`/`tree`/`raw` no estilo GitHub e GitLab) eram classificados como scanner, env-probe e vcs-probe, cerca de 58% dos "atacantes". Sondagens reais (`/.env`, `/.git/config`, `/app/.env`, traversal) não mudam.
- O segundo firewall só excluía crawler quando o User-Agent dizia ser um, então um Googlebot verificado ("GoogleOther") foi banido. Um DNS reverso confirmado nos dois sentidos (googlebot.com, google.com, search.msn.com, applebot.apple.com) agora exclui o endereço qualquer que seja o User-Agent; mais User-Agents de crawler são reconhecidos (GoogleOther, Google-InspectionTool, AdsBot, Apple).
- Laço de retroalimentação: banimentos do jail `urutau` (decisões nossas) e do `recidive` (que só repete bans) deixam de contar como evidência: sem pontuação, sem sinal forte, sem entrar na lista de bloqueio. Bans de jails independentes (sshd, traefik...) continuam valendo.
- A cobertura da lista de bloqueio enganava (3%): contava só os atacantes listados.
### Alterado
- A cobertura (`blocklist.coverage_pct`, `blocklist_coverage`) passa a contar como protegido o atacante listado ou banido por qualquer jail. Campos novos, só adicionados: `blocklist.attackers`, `covered`, `one_shot`, `repeat_ips`, `repeat_covered`, `repeat_coverage_pct` em `/api/v1/defense`, e `one_shot`, `repeat_ips`, `repeat_unblocked` na `coverage` do enforce.
- Política do enforce para atacantes lentos: eventos `ssh-probe` valem meia falha nas regras de SSH; uma janela de 7 dias bane com 10 falhas de SSH (probes valem metade) ou 10 eventos de scan/exploit web sem visita legítima (memória limitada); novo motivo `neighbor-campaign`: com 3 ou mais endereços distintos de um /24 (IPv4) ou /64 (IPv6) banidos nas últimas 24 h, basta um evento de ataque de outro endereço do prefixo. Todas as exclusões (confiável, privado, crawler, infraestrutura, visitante legítimo, operador) seguem valendo, e os peers aceitam o novo motivo.
## [1.5.8] - 2026-11-15
### Corrigido
- Celular: tabelas de dados comuns (ranking da Concentração, rotas de Erros, técnicas MITRE, Defesa, fontes da Integridade e qualquer outra sem layout próprio para celular) apareciam com colunas espremidas, IPs quebrados letra por letra ou rolagem lateral. Abaixo de 768 px as linhas agora viram cartões empilhados com o nome da coluna como rótulo, números alinhados à direita e texto longo quebrando; o desktop não muda. Uma regra única em `style.css` e `cardTables()` em `app.js` cobre todas. `TABLES_ONLY=1 scripts/screenshots.sh` captura todas as páginas com tabela em 375x812 e verifica estouro horizontal.
## [1.5.7] - 2026-11-15
### Corrigido
+1 -1
View File
@@ -163,7 +163,7 @@ The investigation layer is computed from the IP table and the registry, with no
| `exploits_refused_pct` | exploit requests answered 4xx or 5xx / exploit requests with a status, in percent |
| `mttb` | median and 90th percentile of the time from first sighting to ban |
| `ban_coverage` | hostile IPs banned / hostile IPs, in percent |
| `blocklist_coverage` | hostile IPs that are listable (global addresses) / hostile IPs, in percent |
| `blocklist_coverage` | hostile IPs that are protected (on the published blocklist or banned by any jail) / hostile IPs, in percent; `GET /api/v1/defense` also gives `blocklist.attackers`, `covered`, `one_shot` (single-event attackers, impossible to block reactively), `repeat_ips`, `repeat_covered` and `repeat_coverage_pct` |
| `blocklist_leak` | hostile IPs neither banned nor listable (a count) |
| `ssh.fails_24h`, `ssh.users_distinct`, `ssh.ok_after_fail` | SSH failures in 24 h, distinct users tried in 24 h, sessions with a failure and then a successful login |
| `concentration.top10_ips`, `top5_asns` | share of malicious events from the 10 busiest IPs and the 5 busiest ASNs, in percent |
+1 -1
View File
@@ -163,7 +163,7 @@ A camada de investigação é calculada a partir da tabela de IPs e do registro,
| `exploits_refused_pct` | requisições de exploit respondidas 4xx ou 5xx / requisições de exploit com status, em percentual |
| `mttb` | mediana e percentil 90 do tempo entre o primeiro avistamento e o ban |
| `ban_coverage` | IPs hostis banidos / IPs hostis, em percentual |
| `blocklist_coverage` | IPs hostis listáveis (endereços globais) / IPs hostis, em percentual |
| `blocklist_coverage` | IPs hostis protegidos (na lista de bloqueio publicada ou banidos por algum jail) / IPs hostis, em percentual; `GET /api/v1/defense` também traz `blocklist.attackers`, `covered`, `one_shot` (atacantes de um só evento, impossíveis de bloquear de forma reativa), `repeat_ips`, `repeat_covered` e `repeat_coverage_pct` |
| `blocklist_leak` | IPs hostis nem banidos nem listáveis (uma contagem) |
| `ssh.fails_24h`, `ssh.users_distinct`, `ssh.ok_after_fail` | falhas SSH em 24 h, usuários distintos tentados em 24 h, sessões com falha e depois login bem-sucedido |
| `concentration.top10_ips`, `top5_asns` | parcela dos eventos maliciosos dos 10 IPs mais ativos e dos 5 ASNs mais ativos, em percentual |
+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
View File
@@ -2011,6 +2011,39 @@
}
if (current) { try { current.page.unmount(); } catch (e) { console.error(e); } }
var view = $('#view');
// Mobile tables: every plain data table of a page gets data-label on its cells (from the header)
// and the class "mc"; style.css turns those rows into stacked cards under 768 px. Tables that
// already handle phones (stack, tbl-cards, eg-table, ipx-tbl, no-mc) and the sr-only chart tables are skipped.
function cardTables() {
var tabs = view.querySelectorAll('table:not(.sr-only):not(.stack):not(.tbl-cards):not(.eg-table):not(.ipx-tbl):not(.no-mc):not(.mc)');
for (var i = 0; i < tabs.length; i++) {
var tb = tabs[i], hr = tb.querySelector('thead tr');
if (!hr) continue;
var labels = [].map.call(hr.children, function (c) { return (c.textContent || '').trim(); });
[].forEach.call(tb.tBodies, function (body) {
[].forEach.call(body.rows, function (r) {
var k = 0;
[].forEach.call(r.cells, function (c) {
if (!c.hasAttribute('data-label')) c.setAttribute('data-label', labels[k] || '');
if (c.childNodes.length > 1) { // one flex item per cell, so mixed content flows as text
var w = document.createElement('span');
w.className = 'mc-v';
while (c.firstChild) w.appendChild(c.firstChild);
c.appendChild(w);
}
k += c.colSpan || 1;
});
});
});
tb.classList.add('mc');
}
}
var cardQueued = false;
new MutationObserver(function () {
if (cardQueued) return;
cardQueued = true;
requestAnimationFrame(function () { cardQueued = false; cardTables(); });
}).observe(view, { childList: true, subtree: true });
clear(view);
state.note = '';
var page = pages[id];
+2
View File
@@ -125,6 +125,7 @@
'df.en.reason.log4shell': 'Log4Shell exploit attempt',
'df.en.reason.port-scan': 'Scanning many network ports on the server',
'df.en.reason.known-attacker': 'Known attacker returning (hostile verdict)',
'df.en.reason.neighbor-campaign': 'Part of a campaign: several neighbours in the same network range were already banned',
'df.en.error': 'Could not load the second firewall data.'
},
'pt-BR': {
@@ -241,6 +242,7 @@
'df.en.reason.log4shell': 'Tentativa de explorar o Log4Shell',
'df.en.reason.port-scan': 'Varredura de muitas portas de rede do servidor',
'df.en.reason.known-attacker': 'Atacante conhecido voltando (veredito hostil)',
'df.en.reason.neighbor-campaign': 'Parte de uma campanha: vários vizinhos da mesma faixa de rede já foram banidos',
'df.en.error': 'Não foi possível carregar os dados do segundo firewall.'
}
});
+1 -1
View File
@@ -114,7 +114,7 @@
tb.appendChild(el('tr', null, el('td', { class: 'mono' }, m.method, m.odd ? U.ui.badge(t('hl.pr.odd'), 'warn') : null, el('div', { class: 'hl-brk-m' }, brk)), el('td', { class: 'num' }, U.fmt.num(m.n)), el('td', { class: 'num' }, U.fmt.num(errs)),
el('td', { class: 'hl-brk' }, brk)));
});
pm.body.appendChild(el('div', { class: 'hl-scroll' }, el('table', { class: 'hl-table' },
pm.body.appendChild(el('div', { class: 'hl-scroll' }, el('table', { class: 'hl-table no-mc' },
el('thead', null, el('tr', null, el('th', null, t('hl.pr.col.method')), el('th', { class: 'num' }, t('hl.pr.col.n')), el('th', { class: 'num' }, t('hl.pr.col.errs')), el('th', { class: 'hl-brk' }, ''))), tb)));
}
function load() {
+17
View File
@@ -673,3 +673,20 @@ html, body { overflow-x: clip; }
.unban-opt { display: flex; align-items: center; gap: 8px; }
.unban-err { color: var(--bad, #b3261e); margin: 8px 0 0; }
.unban-btns { display: flex; justify-content: flex-end; gap: 8px; margin-top: 16px; }
/* Plain data tables on phones: rows become stacked cards (labels from data-label, set by cardTables() in app.js). */
@media (max-width: 767px) {
.an-scroll, .df-scroll, .hl-scroll { overflow-x: hidden; max-width: 100%; }
.ig-scroll, .mt-tablewrap { overflow: visible; max-width: 100%; }
table.mc { min-width: 0 !important; }
table.mc thead { display: none; }
table.mc, table.mc tbody, table.mc tr, table.mc td { display: block; width: 100%; box-sizing: border-box; }
table.mc tr { margin: 6px 0; padding: 8px 10px; border: 1px solid var(--line); border-radius: var(--radius-sm); background: var(--surface-raised); }
table.mc td { display: flex; justify-content: space-between; align-items: baseline; gap: 12px; border: 0; padding: 2px 0; text-align: right; min-width: 0; overflow-wrap: anywhere; word-break: normal; white-space: normal; }
table.mc td::before { content: attr(data-label); flex: none; max-width: 45%; color: var(--ink-muted); font-size: .75rem; text-transform: uppercase; letter-spacing: .06em; text-align: left; }
table.mc td[data-label=""]::before { display: none; }
table.mc td.num, table.mc td.num * { font-variant-numeric: tabular-nums; }
table.mc td.an-key, table.mc td .mono { overflow-wrap: anywhere; word-break: break-all; }
table.mc td[colspan] { display: block; text-align: left; }
}
@media (max-width: 767px) { table.mc .mc-v { min-width: 0; overflow-wrap: anywhere; word-break: normal; } }
+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 {
+4
View File
@@ -98,6 +98,10 @@ done
pids+=($!)
sleep 6
if [ -n "${TABLES_ONLY:-}" ]; then
# mobile table check (375x812) instead of the documentation pictures: TABLES_ONLY=1 OUT=/tmp/x scripts/screenshots.sh
node "$root/scripts/screenshots/tables.mjs" "http://127.0.0.1:$hub_port" "$out"; exit $?
fi
node "$root/scripts/screenshots/shots.mjs" "http://127.0.0.1:$hub_port" "http://127.0.0.1:$login_port" "$out"
if command -v oxipng >/dev/null; then oxipng -q -o 3 --strip safe "$out"/*.png
+55
View File
@@ -0,0 +1,55 @@
// Mobile table check: node tables.mjs <hub-url> <out-dir>
// Captures every page that has a visible table at 375x812 (plus one desktop control),
// and reports document scrollWidth and tables that overflow their container.
import { execFileSync } from "node:child_process";
import { homedir } from "node:os";
const [hub, out] = process.argv.slice(2);
const core = process.env.PUPPETEER_CORE || `${homedir()}/.claude/tools/node_modules/puppeteer-core/lib/esm/puppeteer/puppeteer-core.js`;
const { default: puppeteer } = await import(core);
const chrome = process.env.CHROME || execFileSync("bash", ["-c", `ls -1d "$HOME"/.cache/puppeteer/chrome/*/chrome-linux64/chrome | sort -V | tail -1`], { encoding: "utf8" }).trim();
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const PHONE = { width: 375, height: 812, deviceScaleFactor: 2, isMobile: true, hasTouch: true };
const DESKTOP = { width: 1440, height: 900, deviceScaleFactor: 1 };
const IP = "203.0.113.45";
async function firstCampaign() {
const j = await (await fetch(`${hub}/api/v1/campaigns?range=30d`)).json();
return encodeURIComponent(((j.campaigns || [])[0] || {}).id || "");
}
const pages = [
["overview", "overview?r=7d"], ["ips", "ips?r=7d"], ["sources", "sources?r=24h"], ["ip-analysis", `ip/${IP}?r=7d`],
["sessions", "sessions?r=7d"], ["campaigns", "campaigns?r=30d"], ["campaign-detail", async () => `campaigns/${await firstCampaign()}?r=30d`],
["search", `search?r=7d&ip=${IP}`], ["mitre", "mitre?r=30d"], ["defense", "defense?r=7d"], ["evolution", "evolution?r=30d"],
["concentration", "concentration?r=30d"], ["survival", "survival?r=30d"], ["errors", "errors?r=7d"], ["slo", "slo?r=7d"],
["protocol", "protocol?r=7d"], ["integrity", "integrity?r=7d"], ["reports", "reports?r=7d"], ["egress", "egress?r=7d"],
["incidents", "incidents"], ["geo", "geo?r=30d"], ["live", "live?r=24h"], ["replay", "replay?r=2d"], ["threats", "threats?r=24h"], ["traffic", "traffic?r=30d"],
];
const browser = await puppeteer.launch({ executablePath: chrome, args: ["--no-sandbox", "--use-gl=angle", "--use-angle=swiftshader", "--enable-unsafe-swiftshader"], defaultViewport: DESKTOP });
let bad = 0;
async function run(id, route, vp, suffix) {
const page = await browser.newPage();
await page.setViewport(vp);
await page.evaluateOnNewDocument(() => { try { localStorage.setItem("urutau.theme", "dark"); localStorage.setItem("urutau.lang", "en"); localStorage.setItem("urutau.host", "all"); } catch {} });
const hash = "#/" + (typeof route === "function" ? await route() : route);
await page.goto(hub + "/", { waitUntil: "domcontentloaded" });
await page.goto(hub + "/" + hash, { waitUntil: "domcontentloaded" });
await page.evaluate((h) => { location.hash = h; }, hash);
try { await page.waitForFunction(() => { const v = document.querySelector("#view"); return v && (v.innerText || "").trim().length > 80 && !v.querySelector(".skeleton"); }, { timeout: 20000, polling: 300 }); } catch {}
await sleep(2500);
const r = await page.evaluate(() => {
const tabs = [...document.querySelectorAll("#view table")].filter((t) => !t.classList.contains("sr-only") && t.offsetParent !== null);
const over = tabs.filter((t) => { let p = t.parentElement; return t.scrollWidth > (p ? p.clientWidth : 0) + 1 || t.getBoundingClientRect().right > innerWidth + 1; }).map((t) => t.className || "(no class)");
return { sw: document.documentElement.scrollWidth, tables: tabs.length, over };
});
const ok = r.sw <= vp.width && (vp.width > 500 || r.over.length === 0);
if (!ok && vp.width < 500) bad++;
console.log(`${suffix} ${id.padEnd(16)} tables=${r.tables} scrollWidth=${r.sw} overflow=[${r.over}] ${ok ? "OK" : "BAD"}`);
if (r.tables > 0) await page.screenshot({ path: `${out}/tbl-${id}-${suffix}.png`, fullPage: true });
await page.close();
}
try {
for (const [id, route] of pages) await run(id, route, PHONE, "m375");
await run("concentration", "concentration?r=30d", DESKTOP, "desktop");
await run("ips", "ips?r=7d", DESKTOP, "desktop");
} finally { await browser.close(); }
process.exit(bad ? 1 : 0);