CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 27s
CI / Dependency audit (push) Successful in 18s
CI / Tests (Linux, race detector) (push) Successful in 58s
Release / Plan (reuse the published image?) (push) Successful in 4s
Release / ci (push) Skipped
Release / Build image (amd64) (push) Skipped
Release / Build image (arm64) (push) Skipped
Release / Publish tags (push) Successful in 13s
Release / Gitea release (push) Successful in 5s
Intelligence: attack families mapped to MITRE ATT&CK, network type from
ASN/rDNS without external APIs, request cadence, sessions with
recon/probe/exploit/access/banned stages, campaigns across IPs, verdict
with reasons, recommended actions, exposure detection (2xx with a body
on sensitive paths), STIX 2.1 export, FCrDNS for search engine bots,
optional Tor exit list.
Data: 30-day retention, twelve ranges plus custom from/to, an on-disk
event log (daily files, hourly gzip members, size cap, corruption and
disk-full tolerant), /events, /period, /metrics with stable per-hour
metrics, an extended /ip/{ip}, and peer /period merged on the hub.
Interface: layout system with fixed card sizes, range picker in the
URL, IP analysis page, Replay page, Geography down to state and city
(Natural Earth admin-1), Live page redesigned with stable metrics and a
reusable attack map. Demo data and documentation screenshots.
Security: bounded and deadline-limited period computations, linear
campaign clustering, singleflight caches, sanitized peer studies, event
query budgets, gzip bomb guard.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
385 lines
15 KiB
Go
385 lines
15 KiB
Go
package store
|
|
|
|
import (
|
|
"encoding/json"
|
|
"math"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
"sync/atomic"
|
|
"testing"
|
|
"time"
|
|
|
|
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
|
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
|
|
)
|
|
|
|
func TestListedSinceAndMigration(t *testing.T) {
|
|
s := store30("x")
|
|
s.SetAdminUsers([]string{"lucas"})
|
|
var at int64
|
|
for i := 0; i < 8; i++ {
|
|
e := ev("1.1.1.1", core.Exploit, time.Duration(8-i)*time.Minute)
|
|
e.Strong = true
|
|
s.Ingest(e) // 8 per event: crosses 50 on the 7th
|
|
if r := s.ips["1.1.1.1"]; r.ListedSince != 0 && at == 0 {
|
|
at = r.ListedSince
|
|
}
|
|
}
|
|
if at != e0(t0, 2*time.Minute) {
|
|
t.Fatalf("ListedSince %d, want the instant of the 7th event", at)
|
|
}
|
|
s.ips["1.1.1.1"].ListedSince = 0 // a record saved before the field existed
|
|
path := filepath.Join(t.TempDir(), "s.gob")
|
|
if err := s.Save(path, nil); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
s2 := store30("x")
|
|
if _, err := s2.Load(path); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if got := s2.ips["1.1.1.1"].ListedSince; got == 0 || got != s2.ips["1.1.1.1"].Last {
|
|
t.Fatalf("migration must estimate it: %d", got)
|
|
}
|
|
if info, _ := s2.IPInfoOf("1.1.1.1"); info.ListedSince == 0 {
|
|
t.Fatal("info")
|
|
}
|
|
// an admin login ends it
|
|
s.ips["1.1.1.1"].ListedSince = at
|
|
s.Ingest(core.Event{Time: t0.Add(time.Second), IP: "1.1.1.1", Cat: core.SSHOK, Source: "ssh", User: "lucas"})
|
|
if s.ips["1.1.1.1"].ListedSince != 0 {
|
|
t.Fatalf("an admin login ends the listing: %d", s.ips["1.1.1.1"].ListedSince)
|
|
}
|
|
if !s.IsAdminUser("lucas") || s.IsAdminUser("root") {
|
|
t.Fatal("IsAdminUser")
|
|
}
|
|
}
|
|
|
|
func e0(t time.Time, ago time.Duration) int64 { return t.Add(-ago).Unix() }
|
|
|
|
func TestIPLogForgedFlag(t *testing.T) {
|
|
s := store30("x")
|
|
s.SetEventLog(openLog(t))
|
|
e := ev("1.1.1.1", core.Exploit, time.Minute)
|
|
e.Forged = true
|
|
s.Ingest(e)
|
|
s.Ingest(ev("2.2.2.2", core.Exploit, time.Minute))
|
|
if !s.IPLogOf("1.1.1.1", t0.Unix()-3600, t0.Unix()).Forged || s.IPLogOf("2.2.2.2", t0.Unix()-3600, t0.Unix()).Forged {
|
|
t.Fatal("forged flag")
|
|
}
|
|
}
|
|
|
|
func samplePeriod(host string, ips ...string) PeriodOut {
|
|
p := PeriodOut{Enabled: true, Events: 10, SessionsN: len(ips), NewVsReturning: map[string]int{"new": len(ips)},
|
|
TopFams: []Count{{Key: "vcs", N: 3}}, TopTechs: []Count{{Key: "T1190", N: 2}}}
|
|
for _, ip := range ips {
|
|
p.Sessions = append(p.Sessions, intel.Session{ID: "s-" + ip, IP: ip, Start: t0.Add(-time.Hour), End: t0, N: 3, Hosts: []string{host}, Stage: "exploit",
|
|
Cats: map[string]int{"exploit": 3}})
|
|
}
|
|
p.FirstSeenTech = []FirstTech{{ID: "T1190", Name: "x", T: t0.Unix() - 100, IP: ips[0]}}
|
|
p.TopTargets = []Target{{Host: host, Domain: "a.example", N: 5}}
|
|
return p
|
|
}
|
|
|
|
func TestSanitizePeerStudyAndMerge(t *testing.T) {
|
|
st := PeerStudy{V: ExportVersion, Period: samplePeriod("EVIL", "1.2.3.4", "not-an-ip", "5.6.7.8"), Metrics: MetricsOut{}}
|
|
st.Period.Sessions[0].Cats = map[string]int{}
|
|
for i := 0; i < 500; i++ {
|
|
st.Period.Sessions[0].Cats[strings.Repeat("c", 1+i)] = i
|
|
st.Period.Sessions = append(st.Period.Sessions, st.Period.Sessions[2])
|
|
}
|
|
st.Period.Sessions[2].Start = time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC)
|
|
st.Period.FirstSeenTech[0].Name = "<script>"
|
|
st.Period.Escalations = []EscalationOut{{Session: "s", IP: "1.2.3.4", Stage: "exploit", Steps: append([]intel.Step{{}}, func() []intel.Step {
|
|
l := make([]intel.Step, 100)
|
|
for i := range l {
|
|
l[i].T = t0
|
|
}
|
|
return l
|
|
}()...)}}
|
|
st.Metrics.AttacksPerHour24h = Metric{Value: math.Inf(1), Spark: make([]float64, 5000)}
|
|
st.Metrics.MTTB.MedianS = math.NaN()
|
|
if !st.Sanitize("hostinger") {
|
|
t.Fatal("rejected")
|
|
}
|
|
if len(st.Period.Sessions) > capSessions || len(st.Period.Sessions[0].Cats) > 12 {
|
|
t.Fatalf("caps: %d sessions, %d cats", len(st.Period.Sessions), len(st.Period.Sessions[0].Cats))
|
|
}
|
|
for _, x := range st.Period.Sessions {
|
|
if x.IP == "not-an-ip" || x.Start.Year() < 2000 || len(x.Hosts) != 1 || x.Hosts[0] != "hostinger" {
|
|
t.Fatalf("bad session kept: %+v", x)
|
|
}
|
|
}
|
|
if st.Period.FirstSeenTech[0].Name == "<script>" || len(st.Period.Escalations[0].Steps) != capSteps || st.Period.Escalations[0].Host != "hostinger" {
|
|
t.Fatalf("names are never taken from a peer: %+v", st.Period.FirstSeenTech)
|
|
}
|
|
if st.Metrics.AttacksPerHour24h.Value != 0 || len(st.Metrics.AttacksPerHour24h.Spark) > capSpark || st.Metrics.MTTB.MedianS != 0 {
|
|
t.Fatalf("metrics %+v", st.Metrics.AttacksPerHour24h.Value)
|
|
}
|
|
if b, _ := json.Marshal(st); len(b) > 4<<20 {
|
|
t.Fatalf("sanitized document is %d bytes", len(b))
|
|
}
|
|
if (&PeerStudy{V: 99}).Sanitize("x") {
|
|
t.Fatal("wrong version")
|
|
}
|
|
|
|
a := samplePeriod("oracle", "1.1.1.1")
|
|
b := samplePeriod("hostinger", "2.2.2.2", "3.3.3.3")
|
|
b.FirstSeenTech[0].T = a.FirstSeenTech[0].T - 50
|
|
m := MergePeriods([]PeriodOut{a, b})
|
|
if m.SessionsN != 3 || m.Events != 20 || len(m.Sessions) != 3 || m.NewVsReturning["new"] != 3 || m.FirstSeenTech[0].T != b.FirstSeenTech[0].T {
|
|
t.Fatalf("merge %+v", m)
|
|
}
|
|
hosts := map[string]bool{}
|
|
for _, x := range m.Sessions {
|
|
hosts[x.Hosts[0]] = true
|
|
}
|
|
if !hosts["oracle"] || !hosts["hostinger"] || m.TopFams[0].N != 6 || len(m.TopTargets) != 2 {
|
|
t.Fatalf("hosts %v fams %v targets %v", hosts, m.TopFams, m.TopTargets)
|
|
}
|
|
ma := MetricsOut{AttacksPerHour24h: mk(2, 1, []float64{1, 2}), ExposureRate: mk(10, 0, nil)}
|
|
mb := MetricsOut{AttacksPerHour24h: mk(4, 3, []float64{3, 4}), ExposureRate: mk(30, 0, nil)}
|
|
ma.MTTB.MedianS, ma.MTTB.N = 10, 1
|
|
mb.MTTB.MedianS, mb.MTTB.N = 40, 3
|
|
mm := MergeMetrics([]MetricsOut{ma, mb})
|
|
if mm.AttacksPerHour24h.Value != 6 || mm.AttacksPerHour24h.Prev != 4 || mm.AttacksPerHour24h.Spark[1] != 6 || mm.ExposureRate.Value != 20 || mm.MTTB.MedianS != 32.5 || mm.MTTB.N != 4 {
|
|
t.Fatalf("metrics merge %+v %+v", mm.AttacksPerHour24h, mm.MTTB)
|
|
}
|
|
}
|
|
|
|
func TestIPTimelineAndActiveDaysWithoutRegistryHistory(t *testing.T) {
|
|
s := store30("x")
|
|
// events from three days, ingested before any registry exists (an upgrade
|
|
// from a snapshot, or a registry that was just enabled)
|
|
for i, d := range []time.Duration{50 * time.Hour, 26 * time.Hour, time.Hour} {
|
|
e := ev("1.1.1.1", core.Scanner, d)
|
|
s.Ingest(e)
|
|
if i == 2 {
|
|
n := ev("1.1.1.1", core.NotFound, d)
|
|
n.E.Tool = true
|
|
s.Ingest(n) // not malicious, still an active day
|
|
}
|
|
}
|
|
s.SetEventLog(openLog(t))
|
|
il := s.IPLogOf("1.1.1.1", t0.Unix()-30*86400, t0.Unix())
|
|
if il.Source != "counters" || il.Timeline.Step != 86400 {
|
|
t.Fatalf("source %q step %d", il.Source, il.Timeline.Step)
|
|
}
|
|
var sc, nf uint32
|
|
for _, v := range il.Timeline.Series["scanner"] {
|
|
sc += v
|
|
}
|
|
for _, v := range il.Timeline.Series["notfound"] {
|
|
nf += v
|
|
}
|
|
if sc != 3 || nf != 1 {
|
|
t.Fatalf("daily counters: scanner %d notfound %d", sc, nf)
|
|
}
|
|
if info, _ := s.IPInfoOf("1.1.1.1"); info.ActiveDays != 3 {
|
|
t.Fatalf("active days %d", info.ActiveDays)
|
|
}
|
|
// once the registry has events, the hourly timeline wins
|
|
s.Ingest(ev("1.1.1.1", core.Exploit, 30*time.Minute))
|
|
s.ipx.m = nil
|
|
il = s.IPLogOf("1.1.1.1", t0.Unix()-30*86400, t0.Unix())
|
|
if il.Source != "events" || il.Timeline.Step != 3600 {
|
|
t.Fatalf("source %q", il.Source)
|
|
}
|
|
if info, _ := s.IPInfoOf("1.1.1.1"); info.ActiveDays != 3 { // same day as an earlier event
|
|
t.Fatalf("active days %d", info.ActiveDays)
|
|
}
|
|
// a record saved by the previous version gets the counters on load
|
|
s.ips["2.2.2.2"] = &IPRec{First: t0.Unix() - 100, Last: t0.Unix() - 50, Score: 3, Counts: func() (c [core.NumCats]uint32) { c[core.Scanner.Index()] = 4; return }()}
|
|
path := filepath.Join(t.TempDir(), "s.gob")
|
|
s.Save(path, nil)
|
|
s2 := store30("x")
|
|
s2.Load(path)
|
|
s2.SetEventLog(openLog(t))
|
|
il = s2.IPLogOf("2.2.2.2", t0.Unix()-30*86400, t0.Unix())
|
|
var tot uint32
|
|
for _, v := range il.Timeline.Series["scanner"] {
|
|
tot += v
|
|
}
|
|
if il.Source != "counters" || tot != 4 {
|
|
t.Fatalf("migrated record: %q %d", il.Source, tot)
|
|
}
|
|
if info, _ := s2.IPInfoOf("2.2.2.2"); info.ActiveDays != 1 {
|
|
t.Fatalf("migrated active days %d", info.ActiveDays)
|
|
}
|
|
// the day ring shifts correctly over many days
|
|
r := &IPRec{}
|
|
for d := int64(0); d < 40; d++ {
|
|
touchDay(r, (20000+d)*86400, core.Scanner.Index())
|
|
}
|
|
if len(r.DayCats) != 30 || r.DayCats[0][core.Scanner.Index()] != 1 || r.Days != 1<<30-1 {
|
|
t.Fatalf("ring: len %d days %b", len(r.DayCats), r.Days)
|
|
}
|
|
}
|
|
|
|
func TestExposureOnlyForSensitiveFamilies(t *testing.T) {
|
|
s := store30("x")
|
|
req := func(ip, path string, status int, bytes int64) {
|
|
e := ev(ip, core.Scanner, time.Minute)
|
|
e.Path, e.Status, e.Bytes, e.Soft = path, status, bytes, status < 400
|
|
e.Strong = true // the address is plainly hostile
|
|
s.Ingest(e)
|
|
}
|
|
// the domain's typical 404 / SPA body is 1200 bytes
|
|
for i := 0; i < 3; i++ {
|
|
nf := ev("30.0.0.1", core.NotFound, time.Minute)
|
|
nf.Path, nf.Status, nf.Bytes = "/nope"+string(rune('a'+i)), 404, 1200
|
|
s.Ingest(nf)
|
|
}
|
|
exposed := func(ip string) int {
|
|
info, _ := s.IPInfoOf(ip)
|
|
return len(info.Expo)
|
|
}
|
|
req("1.0.0.1", "/robots.txt", 200, 80)
|
|
req("1.0.0.2", "/wp-login.php", 200, 5000)
|
|
req("1.0.0.3", "/.env", 200, 0) // empty body
|
|
req("1.0.0.4", "/.env", 200, 1200) // the SPA / typical 404 page
|
|
req("1.0.0.5", "/.env", 200, 412) // a real file
|
|
req("1.0.0.6", "/.git/config", 200, 150)
|
|
req("1.0.0.7", "/.env", 404, 412) // refused
|
|
req("1.0.0.8", "/.env", 302, 412) // redirect
|
|
req("1.0.0.9", "/actuator/env", 200, 3000)
|
|
for ip, want := range map[string]int{"1.0.0.1": 0, "1.0.0.2": 0, "1.0.0.3": 0, "1.0.0.4": 0, "1.0.0.5": 1, "1.0.0.6": 1, "1.0.0.7": 0, "1.0.0.8": 0, "1.0.0.9": 1} {
|
|
if got := exposed(ip); got != want {
|
|
t.Errorf("%s: %d exposures, want %d", ip, got, want)
|
|
}
|
|
}
|
|
info, _ := s.IPInfoOf("1.0.0.5")
|
|
if info.Expo[0].Fam != "env-credentials" || info.Expo[0].Bytes != 412 {
|
|
t.Fatalf("%+v", info.Expo)
|
|
}
|
|
// a plain visitor-like address with no strong sign does not expose an admin page
|
|
e := ev("1.0.0.10", core.Scanner, time.Minute)
|
|
e.Path, e.Status, e.Bytes = "/admin", 200, 900
|
|
s.Ingest(e)
|
|
if exposed("1.0.0.10") != 0 {
|
|
t.Fatal("a public /admin page without a strong sign is not an exposure")
|
|
}
|
|
}
|
|
|
|
func TestStudyDeadlineSingleflightAndGap(t *testing.T) {
|
|
s := store30("x")
|
|
s.SetEventLog(openLog(t))
|
|
for i := 0; i < 40; i++ { // 40 events 30 s apart from one address
|
|
e := ev("1.1.1.1", core.Scanner, time.Duration(40-i)*30*time.Second)
|
|
e.Path = "/wp-login.php"
|
|
s.Ingest(e)
|
|
}
|
|
q := PeriodQuery{From: t0.Unix() - 3600, To: t0.Unix(), Gap: 5} // a gap under 60 s is raised to 60 s
|
|
if p := s.period(q); p.SessionsN != 1 {
|
|
t.Fatalf("gap floor: %d sessions", p.SessionsN)
|
|
}
|
|
old := studyDead
|
|
studyDead = time.Nanosecond
|
|
p := s.period(PeriodQuery{From: t0.Unix() - 3600, To: t0.Unix()})
|
|
studyDead = old
|
|
if !p.Truncated {
|
|
t.Fatal("a study past its deadline must be returned partial with truncated")
|
|
}
|
|
// concurrent callers of one key share one computation
|
|
var calls atomic.Int32
|
|
k := studyKey{kind: "sf"}
|
|
var wg sync.WaitGroup
|
|
for i := 0; i < 8; i++ {
|
|
wg.Add(1)
|
|
go func() {
|
|
defer wg.Done()
|
|
s.cached(k, func() any { calls.Add(1); time.Sleep(80 * time.Millisecond); return 1 })
|
|
}()
|
|
}
|
|
wg.Wait()
|
|
if calls.Load() != 1 {
|
|
t.Fatalf("computed %d times", calls.Load())
|
|
}
|
|
// the slow cache keeps a campaign study for minutes
|
|
a := s.PeriodSlow(PeriodQuery{From: t0.Unix() - 3600, To: t0.Unix()})
|
|
s.Ingest(ev("1.1.1.2", core.Scanner, time.Minute))
|
|
if b := s.PeriodSlow(PeriodQuery{From: t0.Unix() - 3600, To: t0.Unix()}); b.Events != a.Events {
|
|
t.Fatal("PeriodSlow must serve the cached study")
|
|
}
|
|
}
|
|
|
|
func TestPeerStudySanitizeSecurityFields(t *testing.T) {
|
|
c := intel.Campaign{ID: strings.Repeat("i", 100), SignatureID: strings.Repeat("s", 100), First: t0, Last: t0, IPs: []string{"1.2.3.4"}}
|
|
st := PeerStudy{V: ExportVersion, Period: PeriodOut{
|
|
Campaigns: []intel.Campaign{c},
|
|
Escalations: []EscalationOut{{IP: "1.2.3.4", Steps: []intel.Step{{Stage: "recon", T: t0}, {Stage: "x"}, {Stage: "y", T: time.Date(3000, 1, 1, 0, 0, 0, 0, time.UTC)}}}},
|
|
TopTechs: []Count{{Key: "T1190", Label: "<script>", N: 2}},
|
|
Spikes: []intel.Spike{{At: t0, Value: 1 << 40, Baseline: 1, Threshold: 2}, {At: t0, Value: 5, Baseline: 1, Threshold: 2}},
|
|
TopTargets: []Target{{Domain: "a", N: 1 << 40}, {Domain: "b", N: 3}},
|
|
}}
|
|
if !st.Sanitize("p") {
|
|
t.Fatal("rejected")
|
|
}
|
|
p := st.Period
|
|
if len(p.Campaigns[0].ID) != 32 || len(p.Campaigns[0].SignatureID) != 32 {
|
|
t.Fatal("campaign ids must be clipped")
|
|
}
|
|
if len(p.Escalations[0].Steps) != 1 {
|
|
t.Fatalf("steps with an invalid time are dropped: %d", len(p.Escalations[0].Steps))
|
|
}
|
|
if p.TopTechs[0].Label != intel.TechniqueName("T1190") || p.TopTechs[0].Label == "<script>" {
|
|
t.Fatalf("label %q", p.TopTechs[0].Label)
|
|
}
|
|
if len(p.Spikes) != 1 || p.Spikes[0].Value != 5 || len(p.TopTargets) != 1 || p.TopTargets[0].Domain != "b" {
|
|
t.Fatalf("upper bounds: %+v %+v", p.Spikes, p.TopTargets)
|
|
}
|
|
}
|
|
|
|
func TestBanPairingAndOldRecordFallbacks(t *testing.T) {
|
|
s := store30("x")
|
|
s.SetEventLog(openLog(t))
|
|
ban := func(ip, jail string, ago time.Duration, un bool) {
|
|
s.Ingest(core.Event{Time: t0.Add(-ago), IP: ip, Cat: core.Ban, Source: "fail2ban", Jail: jail, Unban: un})
|
|
}
|
|
ban("203.0.113.45", "traefik-botsearch", 3*time.Hour, false)
|
|
ban("203.0.113.45", "traefik-botsearch", 2*time.Hour, true)
|
|
ban("203.0.113.45", "sshd", 90*time.Minute, false)
|
|
ban("203.0.113.45", "sshd", 80*time.Minute, true)
|
|
ban("203.0.113.45", "sshd", 20*time.Minute, false) // banned again, no unban yet
|
|
ban("203.0.113.45", "sshd", 10*time.Minute, false) // a repeat of the same ban (restart): still one ban
|
|
ban("203.0.113.45", "recidive", 5*time.Minute, false)
|
|
il := s.IPLogOf("203.0.113.45", t0.Unix()-86400, t0.Unix())
|
|
info, _ := s.IPInfoOf("203.0.113.45")
|
|
if len(info.Jails) != 2 || len(il.Bans) != 7 {
|
|
t.Fatalf("jails %v bans %d", info.Jails, len(il.Bans))
|
|
}
|
|
// the pairing lives in the server (activeBans); the store gives it jails and history
|
|
for _, b := range il.Bans {
|
|
if b.Jail == "traefik-botsearch" && b.Active {
|
|
t.Fatal("registry rows are never marked active by the store")
|
|
}
|
|
}
|
|
// a record from before the registry/counters existed: only the old fields
|
|
r := s.ips["203.0.113.45"]
|
|
r.Users, r.Fams, r.Techs, r.DayCats, r.Days, r.DayBase, r.DayEst = nil, nil, nil, nil, 0, 0, false
|
|
r.Samples = []string{"GET /.env", "GET /.git/config", "ssh user root"}
|
|
r.First = t0.Unix() - 7*86400
|
|
r.Counts[core.SSHFail.Index()] = 21
|
|
path := filepath.Join(t.TempDir(), "o.gob")
|
|
s.Save(path, nil)
|
|
s2 := store30("x")
|
|
s2.Load(path)
|
|
i2, _ := s2.IPInfoOf("203.0.113.45")
|
|
if len(i2.DayCats) == 0 || i2.ActiveDays < 7 || !i2.Estimated {
|
|
t.Fatalf("migration spreads the totals over first..last: days %d active %d", len(i2.DayCats), i2.ActiveDays)
|
|
}
|
|
var tot uint32
|
|
for _, row := range i2.DayCats {
|
|
for _, v := range row {
|
|
tot += uint32(v)
|
|
}
|
|
}
|
|
var want uint32
|
|
for _, n := range s2.ips["203.0.113.45"].Counts {
|
|
want += n
|
|
}
|
|
if tot != want {
|
|
t.Fatalf("spread must conserve the totals: %d vs %d", tot, want)
|
|
}
|
|
}
|