package store import ( "compress/gzip" "encoding/json" "fmt" "math/rand" "os" "path/filepath" "reflect" "runtime" "testing" "time" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog" ) var synthCats = []string{"scanner", "scanner", "exploit", "notfound", "ssh-fail", "ssh-fail", "bruteforce", "ssh-ok", "ban"} var synthFams = []string{"", "traversal", "sqli", "wordpress", "vcs", "env-credentials", "webshell", "rce-injection"} // writeSynthDays writes days of bursty traffic from two hosts into dir: closed // days gzip compressed, the day of now plain. Some bursts cross midnight. func writeSynthDays(t testing.TB, dir string, days, perDay int, now time.Time, seed int64) { rng := rand.New(rand.NewSource(seed)) if err := os.MkdirAll(dir, 0o700); err != nil { t.Fatal(err) } ips := make([]string, 4000) for i := range ips { ips[i] = fmt.Sprintf("%d.%d.%d.%d", 20+i%200, rng.Intn(250), rng.Intn(250), 1+rng.Intn(250)) } paths := make([]string, 600) for i := range paths { paths[i] = fmt.Sprintf("/wp-content/plugins/p%d/readme.%d.php", rng.Intn(80), i) } uas := make([]string, 40) for i := range uas { uas[i] = fmt.Sprintf("Mozilla/5.0 (X11; rv:%d.0) Gecko/20100101 Firefox/%d.0", 60+i, 60+i) } uas[3], uas[4] = "sqlmap/1.7", "Nuclei - Open-source project" today := now.Unix() / 86400 var id uint64 for d := today - int64(days) + 1; d <= today; d++ { var lines [][]byte emit := func(tt int64, ip string, burstCat string) { id++ host := []string{"oracle", "hostinger"}[rng.Intn(2)] c := burstCat if c == "" { c = synthCats[rng.Intn(len(synthCats))] } r := evlog.Rec{ID: id, T: tt, IP: ip, Cat: c, Source: "traefik", Host: host, Domain: fmt.Sprintf("site%d.example.org", rng.Intn(6)), Method: "GET", Path: paths[rng.Intn(len(paths))], Status: []int{200, 301, 403, 404, 500}[rng.Intn(5)], UA: uas[rng.Intn(len(uas))], CC: "BR", Bytes: int64(rng.Intn(5000)), DurMS: int64(rng.Intn(300))} if c == "ssh-fail" || c == "ssh-ok" || c == "bruteforce" { r.Source, r.Path, r.UA, r.Domain, r.Status, r.Method = "ssh", "", "", "", 0, "" r.User = []string{"root", "admin", "ubuntu", "test"}[rng.Intn(4)] } if c == "exploit" || c == "scanner" { r.Fam = synthFams[rng.Intn(len(synthFams))] if r.Fam != "" { r.Tech = []string{"T1190", "T1595"}[:1+rng.Intn(2)] } } b, _ := json.Marshal(r) lines = append(lines, b) } base := d * 86400 for len(lines) < perDay { ip := ips[int(float64(len(ips))*rng.Float64()*rng.Float64())] start := base + int64(rng.Intn(86400)) n := 1 + rng.Intn(30) for k := 0; k < n && start < base+86400 && len(lines) < perDay; k++ { emit(start, ip, "") start += int64(1 + rng.Intn(20)) } } // bursts that cross midnight into the next day (and from the previous one) for k := 0; k < 25; k++ { ip := ips[rng.Intn(60)] for tt := base + 86400 - 90; tt < base+86400+90; tt += int64(5 + rng.Intn(20)) { if tt < base+86400 { emit(tt, ip, "scanner") } } } // the next day gets the tail of last night's bursts _ = lines name := time.Unix(d*86400, 0).UTC().Format("2006-01-02") var out []byte for _, l := range lines { out = append(out, l...) out = append(out, '\n') } if d == today { os.WriteFile(filepath.Join(dir, name+".jsonl"), out, 0o600) continue } f, _ := os.Create(filepath.Join(dir, name+".jsonl.gz")) zw := gzip.NewWriter(f) zw.Write(out) zw.Close() f.Close() } // tails of midnight bursts: events just after midnight into each following day file for d := today - int64(days) + 1; d < today; d++ { appendTail(t, dir, d+1, rng, ips[:60], d+1 == today) } } // appendTail adds events shortly after midnight of day d for the first // addresses, whose bursts began before midnight. func appendTail(t testing.TB, dir string, d int64, rng *rand.Rand, ips []string, plain bool) { name := filepath.Join(dir, time.Unix(d*86400, 0).UTC().Format("2006-01-02")) var add []byte for i := 0; i < 25; i++ { ip := ips[i%len(ips)] for tt := d * 86400; tt < d*86400+90; tt += int64(5 + rng.Intn(20)) { b, _ := json.Marshal(evlog.Rec{ID: uint64(1e9) + uint64(tt)*100 + uint64(i), T: tt, IP: ip, Cat: "scanner", Source: "traefik", Host: "oracle", Domain: "site1.example.org", Method: "GET", Path: "/.env", Status: 404, UA: "sqlmap/1.7"}) add = append(add, b...) add = append(add, '\n') } } if plain { f, _ := os.OpenFile(name+".jsonl", os.O_APPEND|os.O_WRONLY, 0o600) f.Write(add) f.Close() return } // a second gzip member appended to the day file is valid gzip f, _ := os.OpenFile(name+".jsonl.gz", os.O_APPEND|os.O_WRONLY, 0o600) zw := gzip.NewWriter(f) zw.Write(add) zw.Close() f.Close() } func synthStore(t testing.TB, days, perDay int, cacheMem int64) (*Store, *evlog.Log, string) { dir := filepath.Join(t.TempDir(), "events") writeSynthDays(t, dir, days, perDay, t0, 1) l, err := evlog.Open(evlog.Options{Dir: dir, Now: func() time.Time { return t0 }, MaxBytes: 4 << 30, CacheMem: cacheMem}) if err != nil { t.Fatal(err) } s := store30("oracle") s.SetEventLog(l) return s, l, dir } func pq(days int) PeriodQuery { return PeriodQuery{From: t0.Unix() - int64(days)*86400, To: t0.Unix()} } func BenchmarkStudy30d(b *testing.B) { s, l, _ := synthStore(b, 30, 25000, 0) q := pq(30) run := func(name string) { st := time.Now() p := s.period(q) c := s.countStages(q) m := s.metrics(Range{Name: "custom", From: q.From, To: q.To}) var ms runtime.MemStats runtime.ReadMemStats(&ms) b.Logf("%s: %v events=%d trunc=%v/%v/%v sessions=%d heap=%dMB", name, time.Since(st), p.Events, p.Truncated, c.Truncated, m.Truncated, p.SessionsN, ms.HeapAlloc>>20) } run("cold") for i := 0; i < b.N; i++ { s.study.mu.Lock() s.study.m = nil // the 30 s result cache expired; the decoded days stay s.study.mu.Unlock() run("warm") } d, mem, loads := l.CacheStats() b.Logf("cache days=%d mem=%dMB loads=%d", d, mem>>20, loads) } // studyDigest is everything the views show of a window, for equality checks. func studyDigest(s *Store, q PeriodQuery) map[string]any { p := s.period(q) c := s.countStages(q) m := s.metrics(Range{Name: "custom", From: q.From, To: q.To}) p.Range = RangeInfo{} m.Generated = 0 return map[string]any{"period": p, "funnel": c, "metrics": m} } func TestDayCacheEqualsFullScan(t *testing.T) { dir := filepath.Join(t.TempDir(), "events") writeSynthDays(t, dir, 6, 3000, t0, 7) open := func(mem int64) *Store { l, err := evlog.Open(evlog.Options{Dir: dir, Now: func() time.Time { return t0 }, CacheMem: mem}) if err != nil { t.Fatal(err) } s := store30("oracle") s.SetEventLog(l) return s } cached, plain := open(0), open(-1) for _, days := range []int{1, 3, 6} { q := pq(days) a, b := studyDigest(cached, q), studyDigest(plain, q) for k := range a { if !reflect.DeepEqual(a[k], b[k]) { t.Errorf("%dd: %s differs", days, k) } } if p, q := a["period"].(PeriodOut), b["period"].(PeriodOut); !reflect.DeepEqual(p, q) { v1, v2 := reflect.ValueOf(p), reflect.ValueOf(q) for i := 0; i < v1.NumField(); i++ { if !reflect.DeepEqual(v1.Field(i).Interface(), v2.Field(i).Interface()) { t.Errorf("period field %s differs", v1.Type().Field(i).Name) } } } if !reflect.DeepEqual(a, b) { t.Fatalf("%dd: cached study differs from the full scan", days) } if a["period"].(PeriodOut).SessionsN == 0 || len(a["period"].(PeriodOut).TopFams) == 0 { t.Fatalf("%dd: empty study", days) } } // sessions that cross midnight stay whole: the burst of 23:58 to 00:01 is one session per address p := cached.period(pq(6)) crossing := 0 for _, ss := range p.Sessions { if ss.Start.Unix()/86400 != ss.End.Unix()/86400 { crossing++ } } if crossing == 0 { t.Fatal("no session crosses midnight in the fixture") } if p.Truncated { t.Fatal("a small study must not be truncated") } } func TestDayCacheInvalidatesOnChange(t *testing.T) { dir := filepath.Join(t.TempDir(), "events") writeSynthDays(t, dir, 3, 500, t0, 3) l, err := evlog.Open(evlog.Options{Dir: dir, Now: func() time.Time { return t0 }}) if err != nil { t.Fatal(err) } count := func() int { n := 0 l.ScanRecs(evlog.Filter{From: t0.Unix() - 3*86400, To: t0.Unix()}, 0, false, func(evlog.Rec) bool { n++; return true }) return n } n1 := count() if d, _, loads := l.CacheStats(); d != 2 || loads != 2 { t.Fatalf("closed days cached: days=%d loads=%d", d, loads) } if count() != n1 { t.Fatal("second scan differs") } if _, _, loads := l.CacheStats(); loads != 2 { t.Fatalf("unchanged days must not reload: %d", loads) } // a late line lands in a closed day: its signature changes and it is read again day := time.Unix(t0.Unix()/86400*86400-86400, 0).UTC().Format("2006-01-02") f, err := os.OpenFile(filepath.Join(dir, day+".jsonl.gz"), os.O_APPEND|os.O_WRONLY, 0o600) if err != nil { t.Fatal(err) } zw := gzip.NewWriter(f) zw.Write([]byte(`{"id":99999999,"t":` + fmt.Sprint(t0.Unix()-86400) + `,"ip":"9.9.9.9","cat":"scanner","source":"traefik","host":"oracle"}` + "\n")) zw.Close() f.Close() if n2 := count(); n2 != n1+1 { t.Fatalf("changed day not reloaded: %d vs %d", n2, n1+1) } }