package store import ( "context" "net/netip" "sort" "strconv" "strings" "sync" "time" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel" ) // IntelClassifier fills the family, techniques and marker of an event. func IntelClassifier(ev core.Event) (string, []string, string) { fam, marker := "", "" if ev.Source == "traefik" { fam = intel.Family(ev.Path, ev.Cat, ev.Status, ev.E.Tool) if fam != "" { marker = intel.Marker(ev.Path) } } if ev.Source == "probe" { fam = intel.FamPortScan } tech := intel.Techniques(string(ev.Cat), fam, intel.TechCtx{Tool: ev.UA, Path: ev.Path}) return fam, tech, marker } const studyTTL = 30 * time.Second // Variables so tests can shrink them. var ( studyBudget int64 = 256 << 20 studyDead = 10 * time.Second ) type studyKey struct { kind string from, to int64 host, ip, cat, fam string gap int64 } type studyEntry struct { at time.Time v any } type studyCache struct { mu sync.Mutex m map[studyKey]studyEntry flights map[studyKey]*flight } type flight struct { done chan struct{} v any } func (s *Store) cached(k studyKey, f func() any) any { return s.cachedTTL(k, studyTTL, f) } // cachedTTL returns a fresh cached value, or computes it once: concurrent // callers of the same key wait for the one computation (singleflight). func (s *Store) cachedTTL(k studyKey, ttl time.Duration, f func() any) any { s.study.mu.Lock() if e, ok := s.study.m[k]; ok && time.Since(e.at) < ttl { s.study.mu.Unlock() return e.v } if fl, ok := s.study.flights[k]; ok { s.study.mu.Unlock() <-fl.done return fl.v } fl := &flight{done: make(chan struct{})} if s.study.flights == nil { s.study.flights = map[studyKey]*flight{} } s.study.flights[k] = fl s.study.mu.Unlock() defer func() { s.study.mu.Lock() delete(s.study.flights, k) s.study.mu.Unlock() close(fl.done) }() fl.v = f() s.study.mu.Lock() if s.study.m == nil || len(s.study.m) >= 32 { s.study.m = map[studyKey]studyEntry{} } s.study.m[k] = studyEntry{time.Now(), fl.v} s.study.mu.Unlock() return fl.v } // HourlyMal returns malicious events per hour for the hours of [from, to]. func (s *Store) HourlyMal(from, to int64) (counts []int, at []time.Time) { s.mu.RLock() defer s.mu.RUnlock() for h := from / 3600; h <= to/3600; h++ { n := 0 if hs := &s.hours[int(h%hourSlots)]; hs.Hour == h { n = int(malOf(hs.C)) } counts = append(counts, n) at = append(at, time.Unix(h*3600, 0)) } return } // ---- period ---- // PeriodQuery selects what a period study covers. type PeriodQuery struct { From, To int64 Host, IP, Cat, Fam string Gap int64 } // FirstTech is the first sighting of a technique in the period. type FirstTech struct { ID string `json:"id"` Name string `json:"name"` T int64 `json:"t"` IP string `json:"ip"` } // Escalation is the stage chain of one session. type EscalationOut struct { Session string `json:"session"` Host string `json:"host,omitempty"` IP string `json:"ip"` Stage string `json:"stage"` Steps []intel.Step `json:"steps"` } // Target is a targeted host and domain. type Target struct { Host string `json:"host"` Domain string `json:"domain"` N int `json:"n"` } // PeriodOut is the study of a time window made from the event registry. type PeriodOut struct { Range RangeInfo `json:"range"` Enabled bool `json:"enabled"` Events int `json:"events"` Truncated bool `json:"truncated,omitempty"` SessionsN int `json:"sessions_n"` Sessions []intel.Session `json:"sessions"` Campaigns []intel.Campaign `json:"campaigns"` FirstSeenTech []FirstTech `json:"first_seen_technique"` Escalations []EscalationOut `json:"escalations"` Spikes []intel.Spike `json:"spikes"` NewVsReturning map[string]int `json:"new_vs_returning"` TopTargets []Target `json:"top_targets"` TopFams []Count `json:"top_fams"` TopTechs []Count `json:"top_techs"` TopUsers []Count `json:"top_users"` TopASNs []Count `json:"top_asns"` EventsCursor string `json:"events_cursor"` } const ( maxPeriodSessions = 200 maxPeriodCampaigns = 50 maxEscalations = 20 maxStudyEvents = 1_500_000 ) type evLite struct { t int64 path string ua string } // 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. func (s *Store) Period(q PeriodQuery) PeriodOut { k := studyKey{"period", q.From, q.To, q.Host, q.IP, q.Cat, q.Fam, q.Gap} return s.cached(k, func() any { return s.period(q) }).(PeriodOut) } // PeriodSlow is Period with a longer cache (5 minutes), for views that only // need the campaign context of an address and must not recompute the whole // study on every visit. func (s *Store) PeriodSlow(q PeriodQuery) PeriodOut { k := studyKey{"period-slow", q.From, q.To, q.Host, q.IP, q.Cat, q.Fam, q.Gap} return s.cachedTTL(k, 5*time.Minute, func() any { return s.period(q) }).(PeriodOut) } func (s *Store) period(q PeriodQuery) PeriodOut { now := s.now().Unix() out := PeriodOut{Range: RangeInfo{Name: "custom", From: q.From, To: q.To, Step: 3600}, Sessions: []intel.Session{}, Campaigns: []intel.Campaign{}, FirstSeenTech: []FirstTech{}, Escalations: []EscalationOut{}, Spikes: []intel.Spike{}, NewVsReturning: map[string]int{"new": 0, "returning": 0}, TopTargets: []Target{}, TopFams: []Count{}, TopTechs: []Count{}, TopUsers: []Count{}, TopASNs: []Count{}, EventsCursor: evlog.StartCursor(q.From)} if s.elog == nil { 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 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 return false } e := toEv(r) evs = append(evs, e) if r.Source == "traefik" { byIP[e.IP] = append(byIP[e.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} } } if r.Cat == string(core.SSHFail) { bumpMap(users, r.User) } if r.Domain != "" && core.Category(r.Cat).IsMalicious() { if len(tgt) < 5000 || tgt[[2]string{r.Host, r.Domain}] > 0 { tgt[[2]string{r.Host, r.Domain}]++ } } ipSeen[e.IP] = true return true }) out.Truncated = out.Truncated || info.Truncated out.Events = len(evs) sessions := intel.Sessions(evs, gap) out.SessionsN = len(sessions) // signatures and campaigns: events and sessions of an address are both in // time order, so one pass with two pointers pairs them sigs := map[string]intel.Signature{} sessByIP := map[string][]int{} for i, ss := range sessions { sessByIP[ss.IP] = append(sessByIP[ss.IP], i) } nIP := 0 for ip, idx := range sessByIP { if nIP++; nIP%64 == 0 && ctx.Err() != nil { out.Truncated = true break } lite := byIP[ip] sort.Slice(lite, func(a, b int) bool { return lite[a].t < lite[b].t }) j := 0 for _, i := range idx { ss := sessions[i] st, en := ss.Start.Unix(), ss.End.Unix() for j < len(lite) && lite[j].t < st { j++ } var paths []string tool := "" for k := j; k < len(lite) && lite[k].t <= en; k++ { paths = append(paths, lite[k].path) if tool == "" { if l := s.UALabel(lite[k].ua); strings.HasSuffix(l, "(tool)") { tool = l } } } if len(paths) == 0 { continue } sg := intel.SignatureFrom(paths, tool) g := s.GeoOf(ss.IP) sg.ASN, sg.CC = g.ASN, g.CC if a, err := netip.ParseAddr(ss.IP); err == nil { sg.NetType, _ = intel.NetTypeIP(a, g.ASN, g.ASOrg, "") } else { sg.NetType, _ = intel.NetType(g.ASN, g.ASOrg, "") } sigs[ss.ID] = sg if g.ASN != 0 { asns["AS"+strconv.Itoa(int(g.ASN))+" "+g.ASOrg]++ } } } var camps []intel.Campaign if ctx.Err() == nil { camps = intel.CampaignsCtx(ctx, sessions, sigs, 0) } if ctx.Err() != nil { out.Truncated = true } if len(camps) > maxPeriodCampaigns { sort.SliceStable(camps, func(i, j int) bool { return camps[i].IPsN > camps[j].IPsN }) camps = camps[:maxPeriodCampaigns] } if camps != nil { out.Campaigns = camps } // escalations (highest stages first) order := make([]int, len(sessions)) for i := range order { order[i] = i } 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])}) } // sessions list: the heaviest, in time order if len(sessions) > maxPeriodSessions { sort.SliceStable(sessions, func(i, j int) bool { return sessions[i].N > sessions[j].N }) sessions = sessions[:maxPeriodSessions] sort.SliceStable(sessions, func(i, j int) bool { return sessions[i].Start.Before(sessions[j].Start) }) } if sessions != nil { out.Sessions = sessions } for _, f := range firstT { out.FirstSeenTech = append(out.FirstSeenTech, f) } sort.Slice(out.FirstSeenTech, func(i, j int) bool { return out.FirstSeenTech[i].T < out.FirstSeenTech[j].T }) for k, n := range tgt { out.TopTargets = append(out.TopTargets, Target{k[0], k[1], n}) } sort.Slice(out.TopTargets, func(i, j int) bool { 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 len(out.TopTargets) > 20 { out.TopTargets = out.TopTargets[:20] } out.TopFams, out.TopTechs, out.TopUsers, out.TopASNs = topN(fams, 20), topN(techs, 20), topN(users, 20), topN(asns, 20) for i := range out.TopTechs { out.TopTechs[i].Label = intel.TechniqueName(out.TopTechs[i].Key) } // new vs returning: an address first seen inside the period is new s.mu.RLock() for ip := range ipSeen { if r := s.ips[ip]; r != nil && r.First < q.From { out.NewVsReturning["returning"]++ } else { out.NewVsReturning["new"]++ } } s.mu.RUnlock() // spikes: hourly malicious counts with 7 days of history before the period hf := q.From - 7*86400 if cut := now - int64(s.cfg.Retention/time.Second); hf < cut { hf = cut } hc, at := s.HourlyMal(hf, q.To) for _, sp := range intel.Spikes(hc, at) { if sp.At.Unix() >= q.From/3600*3600 && sp.At.Unix() <= q.To { out.Spikes = append(out.Spikes, sp) } } return out } // ---- metrics ---- // Metric is a value with the previous period and a sparkline. type Metric struct { Value float64 `json:"value"` Prev float64 `json:"prev"` DeltaPct *float64 `json:"delta_pct"` Spark []float64 `json:"spark"` } func mk(v, prev float64, spark []float64) Metric { m := Metric{Value: round1(v), Prev: round1(prev), Spark: spark} if m.Spark == nil { m.Spark = []float64{} } if prev > 0 { d := round1((v - prev) / prev * 100) m.DeltaPct = &d } return m } // MetricsOut holds the stable investigation metrics (per hour or per day, // never per minute). type MetricsOut struct { Range RangeInfo `json:"range"` Generated int64 `json:"generated"` AttacksPerHour24h Metric `json:"attacks_per_hour_24h"` MovingAvg7d Metric `json:"moving_avg_7d_per_hour"` Trend Metric `json:"trend"` // percent change of the range against the previous one Active24h Metric `json:"active_attackers_24h"` Active1h Metric `json:"active_attackers_1h"` NewAttackers Metric `json:"new_attackers"` ReturningRate Metric `json:"returning_rate"` SessionsPerDay Metric `json:"sessions_per_day"` ExposureRate Metric `json:"exposure_rate"` ExploitsRefused Metric `json:"exploits_refused_pct"` MTTB struct { MedianS float64 `json:"median_s"` P90S float64 `json:"p90_s"` PrevMed float64 `json:"prev_median_s"` N int `json:"n"` } `json:"mttb"` BanCoverage Metric `json:"ban_coverage"` BlocklistCoverage Metric `json:"blocklist_coverage"` BlocklistLeak Metric `json:"blocklist_leak"` SSH struct { Fails24h Metric `json:"fails_24h"` UsersDistinct Metric `json:"users_distinct"` OKAfterFail Metric `json:"ok_after_fail"` } `json:"ssh"` Concentration struct { Top10IPs Metric `json:"top10_ips"` Top5ASNs Metric `json:"top5_asns"` } `json:"concentration"` Truncated bool `json:"truncated,omitempty"` } func floats(c []int) []float64 { out := make([]float64, len(c)) for i, v := range c { out[i] = float64(v) } return out } func downsample(c []int, n int) []float64 { if len(c) <= n { return floats(c) } out := make([]float64, n) for i := 0; i < n; i++ { lo, hi := i*len(c)/n, (i+1)*len(c)/n var sum int for _, v := range c[lo:hi] { sum += v } out[i] = float64(sum) } return out } // Metrics computes the metric set for a window (cached for 30 s). func (s *Store) Metrics(rg Range) MetricsOut { now := s.now().Unix() from, to := rg.bounds(now) k := studyKey{kind: "metrics", from: from / 60, to: to / 60} return s.cached(k, func() any { return s.metrics(rg) }).(MetricsOut) } func (s *Store) metrics(rg Range) MetricsOut { now := s.now().Unix() from, to := rg.bounds(now) span := to - from out := MetricsOut{Range: rg.Info(now), Generated: now} retCut := now - int64(s.cfg.Retention/time.Second) s.mu.RLock() last24 := s.malLocked(now-86400, now+1, now) prev24 := s.malLocked(now-2*86400, now-86400, now) last7 := s.malLocked(now-7*86400, now+1, now) var prev7 uint64 if now-14*86400 >= retCut { prev7 = s.malLocked(now-14*86400, now-7*86400, now) } cur := s.malLocked(from, to+1, now) var prev uint64 if from-span >= retCut { prev = s.malLocked(from-span, from, now) } var fails24, failsPrev uint64 for h := (now - 86400) / 3600; h <= now/3600; h++ { if hs := &s.hours[int(h%hourSlots)]; hs.Hour == h { fails24 += uint64(hs.C[core.SSHFail.Index()]) } } for h := (now - 2*86400) / 3600; h < (now-86400)/3600; h++ { if hs := &s.hours[int(h%hourSlots)]; hs.Hour == h { failsPrev += uint64(hs.C[core.SSHFail.Index()]) } } users := map[string]bool{} for h := (now - 86400) / 3600; h <= now/3600; h++ { if hs := &s.hours[int(h%hourSlots)]; hs.Hour == h { for u := range hs.Users { users[u] = true } } } var act24, act1, newN, retN, newPrev int var hostile, hostileBanned, hostileListed, leak int var pairs, pairsPrev [][2]time.Time ipEv := map[string]int{} asnEv := map[string]int{} for ip, r := range s.ips { if !isAttacker(r) { continue } if r.Last >= now-86400 { act24++ } if r.Last >= now-3600 { act1++ } if r.Last >= from && r.First <= to { if r.First >= from { newN++ } else { retN++ } ipEv[ip] += int(malOf(r.Counts)) asnEv["AS"+strconv.Itoa(int(s.GeoOf(ip).ASN))] += int(malOf(r.Counts)) strong := r.Strong || attackKinds(r.Counts) >= 2 if core.LevelOf(r.Score, strong, r.adminAt(now)) == core.LevelHostile { hostile++ banned := len(r.Jails) > 0 listed := false if a, err := netip.ParseAddr(strings.SplitN(ip, "/", 2)[0]); err == nil { listed = core.IsGlobal(a) } if banned { hostileBanned++ } if listed { hostileListed++ } if !banned && !listed { leak++ } } } if r.First >= from-span && r.First < from { newPrev++ } if r.TTB > 0 && r.FirstMal >= from && r.FirstMal <= to { pairs = append(pairs, [2]time.Time{time.Unix(0, 0), time.Unix(r.TTB, 0)}) } else if r.TTB > 0 && r.FirstMal >= from-span && r.FirstMal < from { pairsPrev = append(pairsPrev, [2]time.Time{time.Unix(0, 0), time.Unix(r.TTB, 0)}) } } s.mu.RUnlock() h24, _ := s.HourlyMal(now-86400+3600, now) out.AttacksPerHour24h = mk(float64(last24)/24, float64(prev24)/24, floats(h24)) var days []float64 for d := 6; d >= 0; d-- { days = append(days, round1(float64(s.malRange(now-int64(d+1)*86400, now-int64(d)*86400, now))/24)) } out.MovingAvg7d = mk(float64(last7)/168, float64(prev7)/168, days) hr, _ := s.HourlyMal(from, to) tr := intel.Trend(float64(cur), float64(prev)) * 100 out.Trend = mk(tr, 0, downsample(hr, 48)) out.Trend.Prev, out.Trend.DeltaPct = float64(prev), nil out.Active24h, out.Active1h = mk(float64(act24), 0, nil), mk(float64(act1), 0, nil) out.NewAttackers = mk(float64(newN), float64(newPrev), nil) if t := newN + retN; t > 0 { out.ReturningRate = mk(float64(retN)/float64(t)*100, 0, nil) } else { out.ReturningRate = mk(0, 0, nil) } if hostile > 0 { out.BanCoverage = mk(float64(hostileBanned)/float64(hostile)*100, 0, nil) out.BlocklistCoverage = mk(float64(hostileListed)/float64(hostile)*100, 0, nil) } else { out.BanCoverage, out.BlocklistCoverage = mk(0, 0, nil), mk(0, 0, nil) } out.BlocklistLeak = mk(float64(leak), 0, nil) out.SSH.Fails24h = mk(float64(fails24), float64(failsPrev), nil) out.SSH.UsersDistinct = mk(float64(len(users)), 0, nil) med, p90 := intel.MTTB(pairs) pm, _ := intel.MTTB(pairsPrev) out.MTTB.MedianS, out.MTTB.P90S, out.MTTB.PrevMed, out.MTTB.N = med.Seconds(), p90.Seconds(), pm.Seconds(), len(pairs) out.Concentration.Top10IPs = mk(intel.Concentration(ipEv, 10)*100, 0, nil) delete(asnEv, "AS0") out.Concentration.Top5ASNs = mk(intel.Concentration(asnEv, 5)*100, 0, nil) // 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)) if r.Cat == string(core.Exploit) && r.Status > 0 { expl++ if r.Status >= 400 { refused++ } } return true }) out.Truncated = out.Truncated || info.Truncated sess := intel.Sessions(evs, 0) perDay := map[int64]int{} succ, okAfter := 0, 0 for _, ss := range sess { perDay[ss.Start.Unix()/86400]++ if ss.Success { succ++ } if ss.Cats[string(core.SSHOK)] > 0 && ss.Cats[string(core.SSHFail)] > 0 { okAfter++ } } if len(sess) > 0 { ndays := float64(span) / 86400 if ndays < 1 { ndays = 1 } var spark []float64 for d := from / 86400; d <= to/86400; d++ { spark = append(spark, float64(perDay[d])) } out.SessionsPerDay = mk(float64(len(sess))/ndays, 0, spark) out.ExposureRate = mk(float64(succ)/float64(len(sess))*100, 0, nil) } if expl > 0 { out.ExploitsRefused = mk(float64(refused)/float64(expl)*100, 0, nil) } out.SSH.OKAfterFail = mk(float64(okAfter), 0, nil) } return out } func (s *Store) malRange(a, b, nowU int64) uint64 { s.mu.RLock() defer s.mu.RUnlock() return s.malLocked(a, b, nowU) }