Merge branch 'perf/long-range-studies' into release/2.3.0

# Conflicts:
#	CHANGELOG.md
This commit is contained in:
Lucas Rayan committed 2026-11-23 09:13:32 -03:00
commit f9a6783a1f
16 files changed
+846 -83

No files matched your search

+371
View File
@@ -0,0 +1,371 @@
package evlog
import (
"bytes"
"encoding/json"
"sync"
)
// Closed days never change, so the studies decode each of them once into a
// compact form (strings interned per day, fields as indexes) and keep it in
// memory under a byte cap. A day is reloaded when the size or modification
// time of its files changes. The current day is always read live.
const (
defaultCacheMem = 96 << 20
loadParallel = 3
crecSize = 112
)
type crec struct {
id uint64
bytes, durMS, t int64
s [15]uint32 // ip cat source host domain method path ua user jail cc fam marker flags proto
status, port int32
tech0, techN uint32
unban bool
}
type cday struct {
day int64
sig [4]int64
recs []crec
strs []string
tech []uint32
mem int64
last uint64
}
type dayLoad struct {
done chan struct{}
d *cday
}
type dayCache struct {
mu sync.Mutex
m map[int64]*cday
fl map[int64]*dayLoad
mem int64
tick uint64
loads int64 // days decoded from disk (for tests and diagnostics)
}
func sigOf(f dayFiles) [4]int64 { return [4]int64{f.gsize, f.gmod, f.jsize, f.jmod} }
type interner struct {
m map[string]uint32
strs []string
mem int64
}
func (in *interner) id(s string) uint32 {
if v, ok := in.m[s]; ok {
return v
}
v := uint32(len(in.strs))
in.m[s] = v
in.strs = append(in.strs, s)
in.mem += int64(len(s)) + 48
return v
}
type dayBuilder struct {
d *cday
in *interner
}
func newBuilder(day int64, sig [4]int64) *dayBuilder {
return &dayBuilder{d: &cday{day: day, sig: sig}, in: &interner{m: map[string]uint32{"": 0}, strs: []string{""}}}
}
func (b *dayBuilder) add(r *Rec) {
in, d := b.in, b.d
c := crec{id: r.ID, t: r.T, bytes: r.Bytes, durMS: r.DurMS, status: int32(r.Status), port: int32(r.Port), unban: r.Unban}
c.s = [15]uint32{in.id(r.IP), in.id(r.Cat), in.id(r.Source), in.id(r.Host), in.id(r.Domain), in.id(r.Method), in.id(r.Path),
in.id(r.UA), in.id(r.User), in.id(r.Jail), in.id(r.CC), in.id(r.Fam), in.id(r.Marker), in.id(r.Flags), in.id(r.Proto)}
if len(r.Tech) > 0 {
c.tech0, c.techN = uint32(len(d.tech)), uint32(len(r.Tech))
for _, t := range r.Tech {
d.tech = append(d.tech, in.id(t))
}
}
d.recs = append(d.recs, c)
}
func (b *dayBuilder) done() *cday {
d := b.d
d.recs = append([]crec(nil), d.recs...) // trim the slack
d.strs = b.in.strs
d.mem = int64(len(d.recs))*crecSize + int64(len(d.tech))*4 + b.in.mem
return d
}
// decodeDay reads a whole day into compact form.
func (l *Log) decodeDay(f dayFiles) *cday {
b := newBuilder(f.day, sigOf(f))
l.readDay(f, func(line []byte) bool {
var r Rec
if json.Unmarshal(line, &r) == nil && r.IP != "" {
b.add(&r)
}
return true
}, nil, nil, nil)
return b.done()
}
// Ref points at one event of a decoded day without copying it.
type Ref struct {
d *cday
i uint32
}
// Rec rebuilds the event.
func (r Ref) Rec() Rec { return r.d.rec(&r.d.recs[r.i]) }
// IP is the address of the event, without rebuilding the rest.
func (r Ref) IP() string { return r.d.strs[r.d.recs[r.i].s[0]] }
// T is the time of the event.
func (r Ref) T() int64 { return r.d.recs[r.i].t }
// ScanRefs visits the matching events as references into the decoded days
// (the live day is decoded into a private one), so a long study keeps 16 bytes
// per event instead of a copy. The references keep their days alive.
func (l *Log) ScanRefs(f Filter, maxBytes int64, fn func(Ref) bool) ScanInfo {
var info ScanInfo
var live *dayBuilder
var liveDay int64 = -1
flush := func(stop bool) bool {
if live == nil {
return stop
}
d := live.done()
live = nil
for i := range d.recs {
if !fn(Ref{d, uint32(i)}) {
return true
}
}
return stop
}
info = l.scanDays(f, maxBytes, func(d *cday, idx []uint32) bool {
for _, i := range idx {
if !fn(Ref{d, i}) {
return false
}
}
return true
}, func(day int64, r *Rec) bool {
if live == nil || liveDay != day {
flush(false)
live, liveDay = newBuilder(day, [4]int64{}), day
}
live.add(r)
return true
})
flush(false)
return info
}
func (d *cday) rec(c *crec) Rec {
s := d.strs
r := Rec{ID: c.id, T: c.t, IP: s[c.s[0]], Cat: s[c.s[1]], Source: s[c.s[2]], Host: s[c.s[3]], Domain: s[c.s[4]],
Method: s[c.s[5]], Path: s[c.s[6]], Status: int(c.status), UA: s[c.s[7]], User: s[c.s[8]], Jail: s[c.s[9]], CC: s[c.s[10]],
Unban: c.unban, Fam: s[c.s[11]], Marker: s[c.s[12]], Bytes: c.bytes, DurMS: c.durMS, Flags: s[c.s[13]], Port: int(c.port), Proto: s[c.s[14]]}
if c.techN > 0 {
r.Tech = make([]string, c.techN)
for i := range r.Tech {
r.Tech[i] = s[d.tech[c.tech0+uint32(i)]]
}
}
return r
}
// day returns the decoded day, from memory when its files did not change.
func (l *Log) day(f dayFiles) *cday {
c := &l.dc
for {
c.mu.Lock()
if d, ok := c.m[f.day]; ok && d.sig == sigOf(f) {
c.tick++
d.last = c.tick
c.mu.Unlock()
return d
}
if fl, ok := c.fl[f.day]; ok {
c.mu.Unlock()
<-fl.done
if fl.d != nil && fl.d.sig == sigOf(f) {
return fl.d
}
continue
}
fl := &dayLoad{done: make(chan struct{})}
if c.fl == nil {
c.fl = map[int64]*dayLoad{}
}
c.fl[f.day] = fl
c.mu.Unlock()
d := l.decodeDay(f)
c.mu.Lock()
c.loads++
delete(c.fl, f.day)
fl.d = d
if cap := l.cacheCap(); cap > 0 && d.mem <= cap {
if c.m == nil {
c.m = map[int64]*cday{}
}
if old, ok := c.m[f.day]; ok {
c.mem -= old.mem
}
c.tick++
d.last = c.tick
c.m[f.day], c.mem = d, c.mem+d.mem
for c.mem > cap { // evict the least recently used other days
var victim *cday
for _, x := range c.m {
if x != d && (victim == nil || x.last < victim.last) {
victim = x
}
}
if victim == nil {
break
}
delete(c.m, victim.day)
c.mem -= victim.mem
}
}
c.mu.Unlock()
close(fl.done)
return d
}
}
func (l *Log) cacheCap() int64 {
switch {
case l.opt.CacheMem < 0:
return 0
case l.opt.CacheMem == 0:
return defaultCacheMem
}
return l.opt.CacheMem
}
// CacheStats reports the decoded days held and their approximate size.
func (l *Log) CacheStats() (days int, mem, loads int64) {
l.dc.mu.Lock()
defer l.dc.mu.Unlock()
return len(l.dc.m), l.dc.mem, l.dc.loads
}
// ScanRecs is Scan for callers that do not need the raw line. Closed days are
// served from the decoded day cache, so a repeated study of a long window does
// not decompress and parse the registry again; the current day is read live.
// The byte budget counts only what is read from disk: a cached day is bounded
// by the cache itself.
func (l *Log) ScanRecs(f Filter, maxBytes int64, newestFirst bool, fn func(Rec) bool) ScanInfo {
if l.cacheCap() <= 0 || newestFirst {
return l.Scan(f, maxBytes, newestFirst, func(r Rec, _ []byte) bool { return fn(r) })
}
return l.scanDays(f, maxBytes, func(d *cday, idx []uint32) bool {
for _, i := range idx {
if !fn(d.rec(&d.recs[i])) {
return false
}
}
return true
}, func(_ int64, r *Rec) bool { return fn(*r) })
}
// scanDays walks the days of the window in order: closed days through the
// cache (day and the indexes of its matching events), the live day line by
// line (live).
func (l *Log) scanDays(f Filter, maxBytes int64, closed func(*cday, []uint32) bool, live func(day int64, r *Rec) bool) ScanInfo {
if maxBytes <= 0 {
maxBytes = 512 << 20
}
f.Prepare()
files := l.daysIn(f.From, f.To)
today := l.opt.Now().Unix() / 86400
var info ScanInfo
var snap map[int64]jsnap
for i := 0; i < len(files); {
if info.Bytes >= maxBytes {
info.Truncated = true
break
}
if files[i].day >= today || l.cacheCap() <= 0 { // live day: read the files
if snap == nil {
snap = l.begin()
}
stop := false
rng := &[2]int64{f.From, f.To}
day := files[i].day
l.readDay(files[i], func(line []byte) bool {
if info.Bytes >= maxBytes {
info.Truncated, stop = true, true
return false
}
info.Lines++
if f.ipText != nil && !bytes.Contains(line, f.ipText) {
return true
}
var r Rec
if json.Unmarshal(line, &r) != nil || r.IP == "" || !f.Match(&r) {
return true
}
info.Matched++
if !live(day, &r) {
stop = true
return false
}
return true
}, &info.Bytes, rng, snap)
if stop {
break
}
i++
continue
}
// a batch of closed days, decoded in parallel
j := i
for j < len(files) && j-i < loadParallel && files[j].day < today {
j++
}
days := make([]*cday, j-i)
var wg sync.WaitGroup
for k := range days {
wg.Add(1)
go func() {
defer wg.Done()
days[k] = l.day(files[i+k])
}()
}
wg.Wait()
for _, d := range days {
var idx []uint32
for x := range d.recs {
c := &d.recs[x]
info.Lines++
if c.t < f.From || (f.To != 0 && c.t > f.To) {
continue
}
if f.Host != "" || len(f.Cats) > 0 || f.Fam != "" || f.IP != "" || f.qLower != "" {
r := d.rec(c)
if !f.Match(&r) {
continue
}
}
idx = append(idx, uint32(x))
}
info.Matched += int64(len(idx))
if !closed(d, idx) {
return info
}
}
i = j
}
return info
}
+6 -2
View File
@@ -94,6 +94,7 @@ type Options struct {
SyncEvery time.Duration // flush+fsync period (default 2 s)
Now func() time.Time
Log *slog.Logger
CacheMem int64 // bytes of decoded closed days kept in memory (default 96 MB, <0 off)
}
type file interface {
@@ -123,6 +124,7 @@ type Log struct {
gidx map[string]*dayIdx // hour index of compressed day files (sidecar .idx)
jidx map[int64]*jIdx // hour runs of plain day files written by this process
needNL map[int64]bool
dc dayCache
}
type blk struct {
@@ -396,6 +398,8 @@ type dayFiles struct {
gsize int64
hasJSONL bool
hasGZ bool
gmod int64 // modification times (ns), part of the cache signature
jmod int64
}
// list returns the day files in the directory, oldest first.
@@ -432,9 +436,9 @@ func (l *Log) list() []dayFiles {
continue
}
if gz {
f.gz, f.gsize, f.hasGZ = filepath.Join(l.opt.Dir, name), info.Size(), true
f.gz, f.gsize, f.hasGZ, f.gmod = filepath.Join(l.opt.Dir, name), info.Size(), true, info.ModTime().UnixNano()
} else {
f.jsonl, f.jsize, f.hasJSONL = filepath.Join(l.opt.Dir, name), info.Size(), true
f.jsonl, f.jsize, f.hasJSONL, f.jmod = filepath.Join(l.opt.Dir, name), info.Size(), true, info.ModTime().UnixNano()
}
}
out := make([]dayFiles, 0, len(by))
+24
View File
@@ -8,6 +8,8 @@ import (
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
)
@@ -58,6 +60,28 @@ var (
// NormPath normalises a path for signatures: query dropped, lowercase, uuids
// and long hex runs become {id}, digit runs become {n}.
func NormPath(p string) string {
if v, ok := normMemo.Load(p); ok {
return v.(string)
}
n := normPath(p)
if normMemoN.Add(1) > normMemoMax { // bounded: paths come from attackers
normMemo.Clear()
normMemoN.Store(1)
}
normMemo.Store(p, n)
return n
}
// Paths repeat heavily in a study and the three regular expressions are the
// costliest step of a signature, so results are memoised.
const normMemoMax = 50000
var (
normMemo sync.Map
normMemoN atomic.Int64
)
func normPath(p string) string {
if i := strings.IndexAny(p, "?#"); i >= 0 {
p = p[:i]
}
+52 -13
View File
@@ -3,8 +3,10 @@ package intel
import (
"crypto/sha256"
"encoding/hex"
"runtime"
"sort"
"strconv"
"sync"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
@@ -158,20 +160,57 @@ func Sessions(events []Ev, gap time.Duration) []Session {
for _, e := range events {
byIP[e.IP] = append(byIP[e.IP], e)
}
var out []Session
for ip, evs := range byIP {
sort.SliceStable(evs, func(i, j int) bool { return evs[i].T.Before(evs[j].T) })
priorFail := false
start := 0
for i := 1; i <= len(evs); i++ {
if i < len(evs) && evs[i].T.Sub(evs[i-1].T) <= gap {
continue
return SessionsByIP(byIP, gap)
}
// SessionsByIP is Sessions for events already grouped by address (the lists
// are sorted in place by time), which spares the second copy of a long study.
func SessionsByIP(byIP map[string][]Ev, gap time.Duration) []Session {
ips := make([]string, 0, len(byIP))
for ip := range byIP {
ips = append(ips, ip)
}
return SessionsLazy(ips, func(ip string) []Ev { return byIP[ip] }, gap)
}
// SessionsLazy builds the sessions of the listed addresses, asking load for the
// events of one address at a time so a long study never holds them all.
func SessionsLazy(ips []string, load func(ip string) []Ev, gap time.Duration) []Session {
if gap <= 0 {
gap = DefaultGap
}
// addresses are independent of each other: build their sessions in parallel
workers := min(runtime.GOMAXPROCS(0), 8, 1+len(ips)/256)
parts := make([][]Session, workers)
var wg sync.WaitGroup
for w := 0; w < workers; w++ {
wg.Add(1)
go func() {
defer wg.Done()
var out []Session
for i := w; i < len(ips); i += workers {
ip := ips[i]
evs := load(ip)
sort.SliceStable(evs, func(i, j int) bool { return evs[i].T.Before(evs[j].T) })
priorFail := false
start := 0
for i := 1; i <= len(evs); i++ {
if i < len(evs) && evs[i].T.Sub(evs[i-1].T) <= gap {
continue
}
s, pf := buildSession(ip, evs[start:i], priorFail)
priorFail = pf
out = append(out, s)
start = i
}
}
s, pf := buildSession(ip, evs[start:i], priorFail)
priorFail = pf
out = append(out, s)
start = i
}
parts[w] = out
}()
}
wg.Wait()
var out []Session
for _, p := range parts {
out = append(out, p...)
}
sort.Slice(out, func(i, j int) bool {
if !out[i].Start.Equal(out[j].Start) {
+11 -3
View File
@@ -301,9 +301,17 @@
if (r.status >= 500) { showError(t('error.load')); throw mkErr('HTTP ' + r.status, r.status); }
if (!r.ok) throw mkErr('HTTP ' + r.status, r.status);
hideError();
return r.json();
return r.json().then(function (j) { if (j && j.truncated === true) noteTruncated(); return j; });
}, function (e) { showError(t('error.load')); throw e; });
}
// A study that hit a real limit (event count, byte budget or time) says so; shown at most once per 20 s.
var truncAt = 0;
function noteTruncated() {
var now = Date.now();
if (now - truncAt < 20000) return;
truncAt = now;
toast(t('study.truncated'), 9000);
}
function qs(extra) {
var o = Object.assign({ host: state.host }, rangeParams());
for (var k in extra) o[k] = extra[k];
@@ -982,12 +990,12 @@
});
}
var toastBox = null;
function toast(msg) {
function toast(msg, ms) {
if (!toastBox) toastBox = $('#toasts');
if (!toastBox) return;
var n = h('div', 'toast', String(msg));
toastBox.appendChild(n);
setTimeout(function () { if (n.parentNode) n.parentNode.removeChild(n); }, 2600);
setTimeout(function () { if (n.parentNode) n.parentNode.removeChild(n); }, ms || 2600);
}
// POST/DELETE with a JSON body (same-origin cookie session); resolves with the parsed answer or rejects with its status.
+2
View File
@@ -43,6 +43,7 @@ window.URUTAU_I18N = {
'range.widen': 'Choose another period',
'timeline.bucket': '{n}-minute buckets',
'toast.copied': 'Copied',
'study.truncated': 'This period is too large to read in full: the figures cover only part of the events. Pick a shorter range for exact numbers.',
'unban.btn': 'Unban',
'unban.title': 'Unban {ip}',
'unban.explain': 'This lifts the block on this address in the server firewall (fail2ban) right away. Use it when the block was a mistake or when you are testing your own system.',
@@ -595,6 +596,7 @@ window.URUTAU_I18N = {
'range.widen': 'Escolher outro período',
'timeline.bucket': 'caixas de {n} min',
'toast.copied': 'Copiado',
'study.truncated': 'Este período é grande demais para ser lido por inteiro: os números cobrem só parte dos eventos. Escolha um intervalo menor para valores exatos.',
'unban.btn': 'Desbanir',
'unban.title': 'Desbanir {ip}',
'unban.explain': 'Isto libera agora o bloqueio deste endereço no firewall do servidor (fail2ban). Use quando o bloqueio foi um engano ou quando você está testando o seu próprio sistema.',
+1 -1
View File
@@ -225,7 +225,7 @@ func anQuant(v []int64, q float64) int64 {
func (s *Store) anScan(from, to int64, host string, fn func(evlog.Rec) bool) (truncated bool) {
deadline := time.Now().Add(studyDead)
n := 0
info := s.elog.Scan(evlog.Filter{From: from, To: to, Host: host}, studyBudget, false, func(r evlog.Rec, _ []byte) bool {
info := s.elog.ScanRecs(evlog.Filter{From: from, To: to, Host: host}, studyBudget, false, func(r evlog.Rec) bool {
if n++; n%4096 == 0 && time.Now().After(deadline) {
truncated = true
return false
+3 -25
View File
@@ -1,11 +1,8 @@
package store
import (
"context"
"sort"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
)
@@ -207,28 +204,9 @@ func (s *Store) countStages(q PeriodQuery) StageCounts {
if s.elog == nil {
return out
}
gap := time.Duration(q.Gap) * time.Second
if q.Gap < 60 {
gap = intel.DefaultGap
if q.Gap > 0 {
gap = 60 * time.Second
}
}
deadline := time.Now().Add(studyDead)
ctx, cancel := context.WithDeadline(context.Background(), deadline)
defer cancel()
var evs []intel.Ev
info := s.elog.Scan(evlog.Filter{From: q.From, To: q.To, Host: q.Host, IP: q.IP, Cats: catSet(q.Cat), Fam: q.Fam}, studyBudget, false,
func(r evlog.Rec, _ []byte) bool {
if len(evs) >= maxStudyEvents || len(evs)%4096 == 0 && ctx.Err() != nil {
out.Truncated = true
return false
}
evs = append(evs, toEv(r))
return true
})
out.Truncated = out.Truncated || info.Truncated
for _, ss := range intel.Sessions(evs, gap) {
st := s.sessionStudy(q)
out.Truncated = st.truncated
for _, ss := range st.sessions {
out.Add(ss.Stage, ss.Success)
}
return out
+2 -2
View File
@@ -133,8 +133,8 @@ func (s *Store) defense(q PeriodQuery) DefenseOut {
users := map[string]int{}
sshSrc := map[string]struct{}{}
n, malN := 0, 0
info := s.elog.Scan(evlog.Filter{From: q.From, To: q.To, Host: q.Host}, studyBudget, false,
func(r evlog.Rec, _ []byte) bool {
info := s.elog.ScanRecs(evlog.Filter{From: q.From, To: q.To, Host: q.Host}, studyBudget, false,
func(r evlog.Rec) bool {
if n++; n > maxStudyEvents || n%4096 == 0 && time.Now().After(deadline) {
out.Truncated = true
return false
+80 -34
View File
@@ -180,6 +180,65 @@ type evLite struct {
ua string
}
// sessStudy is the part of a period study that several views share: the
// events of the window grouped by address and the sessions made from them.
type sessStudy struct {
byIP map[string][]evlog.Ref
sessions []intel.Session
events int
truncated bool
}
// evs rebuilds the events of one address.
func (st *sessStudy) evs(ip string) []intel.Ev {
refs := st.byIP[ip]
out := make([]intel.Ev, len(refs))
for i, r := range refs {
out[i] = toEv(r.Rec())
}
return out
}
func normGap(g int64) time.Duration {
switch {
case g <= 0:
return intel.DefaultGap
case g < 60:
return 60 * time.Second
}
return time.Duration(g) * time.Second
}
// sessionStudy scans the window once and builds its sessions; period, funnel
// and metrics of the same window (and filters) share the result for the cache
// lifetime instead of each decoding and grouping the same events.
func (s *Store) sessionStudy(q PeriodQuery) *sessStudy {
run := func() *sessStudy {
st := &sessStudy{byIP: map[string][]evlog.Ref{}}
deadline := time.Now().Add(studyDead)
info := s.elog.ScanRefs(evlog.Filter{From: q.From, To: q.To, Host: q.Host, IP: q.IP, Cats: catSet(q.Cat), Fam: q.Fam}, studyBudget,
func(ref evlog.Ref) bool {
if st.events >= maxStudyEvents || st.events%4096 == 0 && time.Now().After(deadline) {
st.truncated = true
return false
}
ip := KeyOf(ref.IP())
st.byIP[ip] = append(st.byIP[ip], ref)
st.events++
return true
})
st.truncated = st.truncated || info.Truncated
ips := make([]string, 0, len(st.byIP))
for ip := range st.byIP {
ips = append(ips, ip)
}
st.sessions = intel.SessionsLazy(ips, st.evs, normGap(q.Gap))
return st
}
k := studyKey{"sess", q.From, q.To, q.Host, q.IP, q.Cat, q.Fam, int64(normGap(q.Gap) / time.Second)}
return s.cached(k, func() any { return run() }).(*sessStudy)
}
// Period studies [From, To] from the registry: sessions with stages,
// campaigns, first sightings, escalations, spikes and tops. At most 256 MB of
// registry is read and 10 s spent; the result is cached for 30 s.
@@ -206,38 +265,31 @@ func (s *Store) period(q PeriodQuery) PeriodOut {
return out
}
out.Enabled = true
gap := time.Duration(q.Gap) * time.Second
switch {
case q.Gap <= 0:
gap = intel.DefaultGap
case q.Gap < 60:
gap = 60 * time.Second
}
deadline := time.Now().Add(studyDead)
ctx, cancel := context.WithDeadline(context.Background(), deadline)
defer cancel()
var evs []intel.Ev
st := s.sessionStudy(q)
out.Truncated = st.truncated
byIP := map[string][]evLite{}
fams, techs, users, asns := map[string]uint32{}, map[string]uint32{}, map[string]uint32{}, map[string]uint32{}
tgt := map[[2]string]int{}
firstT := map[string]FirstTech{}
ipSeen := map[string]bool{}
info := s.elog.Scan(evlog.Filter{From: q.From, To: q.To, Host: q.Host, IP: q.IP, Cats: catSet(q.Cat), Fam: q.Fam}, studyBudget, false,
func(r evlog.Rec, _ []byte) bool {
if len(evs) >= maxStudyEvents || len(evs)%4096 == 0 && time.Now().After(deadline) {
out.Truncated = true
n := 0
info := s.elog.ScanRecs(evlog.Filter{From: q.From, To: q.To, Host: q.Host, IP: q.IP, Cats: catSet(q.Cat), Fam: q.Fam}, studyBudget, false,
func(r evlog.Rec) bool {
if n++; n > maxStudyEvents || n%4096 == 0 && time.Now().After(deadline) {
return false
}
e := toEv(r)
evs = append(evs, e)
ip := KeyOf(r.IP)
if r.Source == "traefik" {
byIP[e.IP] = append(byIP[e.IP], evLite{r.T, r.Path, r.UA})
byIP[ip] = append(byIP[ip], evLite{r.T, r.Path, r.UA})
}
bumpMap(fams, r.Fam)
for _, t := range r.Tech {
bumpMap(techs, t)
if f, ok := firstT[t]; !ok || r.T < f.T {
firstT[t] = FirstTech{ID: t, Name: intel.TechniqueName(t), T: r.T, IP: e.IP}
firstT[t] = FirstTech{ID: t, Name: intel.TechniqueName(t), T: r.T, IP: ip}
}
}
if r.Cat == string(core.SSHFail) {
@@ -248,12 +300,12 @@ func (s *Store) period(q PeriodQuery) PeriodOut {
tgt[[2]string{r.Host, r.Domain}]++
}
}
ipSeen[e.IP] = true
ipSeen[ip] = true
return true
})
out.Truncated = out.Truncated || info.Truncated
out.Events = len(evs)
sessions := intel.Sessions(evs, gap)
out.Events = st.events
sessions := append([]intel.Session(nil), st.sessions...)
out.SessionsN = len(sessions)
// signatures and campaigns: events and sessions of an address are both in
@@ -327,16 +379,12 @@ func (s *Store) period(q PeriodQuery) PeriodOut {
sort.SliceStable(order, func(a, b int) bool {
return intel.StageRank(sessions[order[a]].Stage) > intel.StageRank(sessions[order[b]].Stage)
})
evByIP := map[string][]intel.Ev{}
for _, e := range evs {
evByIP[e.IP] = append(evByIP[e.IP], e)
}
for _, i := range order {
ss := sessions[i]
if intel.StageRank(ss.Stage) < intel.StageRank(intel.StageExploit) || len(out.Escalations) >= maxEscalations {
break
}
out.Escalations = append(out.Escalations, EscalationOut{Session: ss.ID, IP: ss.IP, Stage: ss.Stage, Steps: intel.Escalation(ss, evByIP[ss.IP])})
out.Escalations = append(out.Escalations, EscalationOut{Session: ss.ID, IP: ss.IP, Stage: ss.Stage, Steps: intel.Escalation(ss, st.evs(ss.IP))})
}
// sessions list: the heaviest, in time order
if len(sessions) > maxPeriodSessions {
@@ -358,7 +406,10 @@ func (s *Store) period(q PeriodQuery) PeriodOut {
if out.TopTargets[i].N != out.TopTargets[j].N {
return out.TopTargets[i].N > out.TopTargets[j].N
}
return out.TopTargets[i].Domain < out.TopTargets[j].Domain
if out.TopTargets[i].Domain != out.TopTargets[j].Domain {
return out.TopTargets[i].Domain < out.TopTargets[j].Domain
}
return out.TopTargets[i].Host < out.TopTargets[j].Host
})
if len(out.TopTargets) > 20 {
out.TopTargets = out.TopTargets[:20]
@@ -612,15 +663,10 @@ func (s *Store) metrics(rg Range) MetricsOut {
// from the registry: sessions, exposure, refused exploits, ssh login after brute force
out.SessionsPerDay, out.ExposureRate, out.ExploitsRefused, out.SSH.OKAfterFail = mk(0, 0, nil), mk(0, 0, nil), mk(0, 0, nil), mk(0, 0, nil)
if s.elog != nil {
var evs []intel.Ev
var expl, refused int
deadline := time.Now().Add(studyDead)
info := s.elog.Scan(evlog.Filter{From: from, To: to}, studyBudget, false, func(r evlog.Rec, _ []byte) bool {
if len(evs) >= maxStudyEvents || len(evs)%4096 == 0 && time.Now().After(deadline) {
out.Truncated = true
return false
}
evs = append(evs, toEv(r))
st := s.sessionStudy(PeriodQuery{From: from, To: to})
out.Truncated = st.truncated
info := s.elog.ScanRecs(evlog.Filter{From: from, To: to, Cats: map[string]bool{string(core.Exploit): true}}, studyBudget, false, func(r evlog.Rec) bool {
if r.Cat == string(core.Exploit) && r.Status > 0 {
expl++
if r.Status >= 400 {
@@ -630,7 +676,7 @@ func (s *Store) metrics(rg Range) MetricsOut {
return true
})
out.Truncated = out.Truncated || info.Truncated
sess := intel.Sessions(evs, 0)
sess := st.sessions
perDay := map[int64]int{}
succ, okAfter := 0, 0
for _, ss := range sess {
+275
View File
@@ -0,0 +1,275 @@
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)
}
}
+2 -2
View File
@@ -97,8 +97,8 @@ func (s *Store) techniques(q PeriodQuery) TechniquesOut {
deadline := time.Now().Add(studyDead)
acc := map[string]*techAcc{}
n := 0
info := s.elog.Scan(evlog.Filter{From: q.From - span, To: q.To, Host: q.Host}, studyBudget, false,
func(r evlog.Rec, _ []byte) bool {
info := s.elog.ScanRecs(evlog.Filter{From: q.From - span, To: q.To, Host: q.Host}, studyBudget, false,
func(r evlog.Rec) bool {
if n++; n > maxStudyEvents || n%4096 == 0 && time.Now().After(deadline) {
out.Truncated = true
return false