package store import ( "encoding/json" "net/netip" "sort" "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" ) // SetEventLog attaches the on-disk event registry (nil detaches it). func (s *Store) SetEventLog(l *evlog.Log) { s.elog = l if l != nil { for { cur := s.ids.Load() if l.LastID() <= cur || s.ids.CompareAndSwap(cur, l.LastID()) { break } } } } // EventLog returns the registry, nil when disabled. func (s *Store) EventLog() *evlog.Log { return s.elog } // logEvent writes a local event, in the same JSON format as the live stream. func (s *Store) logEvent(fe FeedEvent) { if s.elog == nil { return } b, err := json.Marshal(s.Live(fe)) if err != nil { return } s.elog.Append(fe.T, b) } // RecordPeerEvent gives a relayed peer event a local id and registers it. The // event must already be sanitized and carry the peer name as its host. func (s *Store) RecordPeerEvent(e *LiveEvent) { e.ID = s.ids.Add(1) if s.elog == nil { return } if b, err := json.Marshal(e); err == nil { s.elog.Append(e.T, b) } } // EventsQuery selects events of the registry. type EventsQuery struct { From, To int64 Host, IP, Cat, Q, Fam string Limit int Cursor string Desc bool } // EventsPage is one page of events. type EventsPage struct { Events []json.RawMessage `json:"events"` Next string `json:"next"` TotalEstimate int64 `json:"total_estimate"` Truncated bool `json:"truncated,omitempty"` Enabled bool `json:"enabled"` } func catSet(list string) map[string]bool { if list == "" { return nil } m := map[string]bool{} start := 0 for i := 0; i <= len(list); i++ { if i == len(list) || list[i] == ',' { if c := list[start:i]; c != "" { m[c] = true } start = i + 1 } } return m } // QueryEvents reads a page from the registry. func (s *Store) QueryEvents(q EventsQuery) (EventsPage, error) { if s.elog == nil { return EventsPage{Events: []json.RawMessage{}}, nil } r, err := s.elog.Query(evlog.Query{Filter: evlog.Filter{From: q.From, To: q.To, Host: q.Host, IP: q.IP, Q: q.Q, Fam: q.Fam, Cats: catSet(q.Cat)}, Limit: q.Limit, Cursor: q.Cursor, Desc: q.Desc}) if err != nil { return EventsPage{}, err } out := EventsPage{Events: make([]json.RawMessage, 0, len(r.Items)), Next: r.Next, TotalEstimate: r.TotalEstimate, Truncated: r.Truncated, Enabled: true} for _, it := range r.Items { out.Events = append(out.Events, json.RawMessage(it.Raw)) } return out, nil } // Session is a burst of activity of one address with no gap longer than the // requested inactivity window. type Session struct { IP string `json:"ip"` Start int64 `json:"start"` End int64 `json:"end"` Events int `json:"events"` Cats map[string]int `json:"cats"` Hosts []string `json:"hosts"` Domains []string `json:"domains"` CC string `json:"cc,omitempty"` ASN uint32 `json:"asn,omitempty"` ASOrg string `json:"as_org,omitempty"` Score float64 `json:"score"` } const ( maxSessionEvents = 2_000_000 maxSessions = 2000 sessionScanBytes = 256 << 20 ) type sev struct { t int64 cat string host string domain string cc string } // Sessions groups the registry events of [from, to] by address (IPv6 by /64) // with an inactivity gap in seconds. truncated reports a cut scan or cap. func (s *Store) Sessions(from, to int64, host, ip string, gap int64) (out []Session, truncated bool) { out = []Session{} if s.elog == nil { return } if gap < 30 { gap = 30 } if gap > 86400 { gap = 86400 } by := map[string][]sev{} n := 0 info := s.elog.Scan(evlog.Filter{From: from, To: to, Host: host, IP: ip}, sessionScanBytes, false, func(r evlog.Rec, _ []byte) bool { if n >= maxSessionEvents { truncated = true return false } n++ k := KeyOf(r.IP) by[k] = append(by[k], sev{r.T, r.Cat, r.Host, r.Domain, r.CC}) return true }) truncated = truncated || info.Truncated for k, evs := range by { sort.Slice(evs, func(i, j int) bool { return evs[i].t < evs[j].t }) var cur *Session for _, e := range evs { if cur == nil || e.t-cur.End > gap { out = append(out, Session{IP: k, Start: e.t, Cats: map[string]int{}}) cur = &out[len(out)-1] } cur.End = e.t cur.Events++ cur.Cats[e.cat]++ cur.Score += core.Category(e.cat).Weight() cur.Hosts = addUnique(cur.Hosts, e.host, 8) cur.Domains = addUnique(cur.Domains, e.domain, 8) if cur.CC == "" { cur.CC = e.cc } } } sort.Slice(out, func(i, j int) bool { if out[i].Start != out[j].Start { return out[i].Start < out[j].Start } return out[i].IP < out[j].IP }) if len(out) > maxSessions { // keep the heaviest, then restore the time order truncated = true sort.SliceStable(out, func(i, j int) bool { return out[i].Events > out[j].Events }) out = out[:maxSessions] sort.Slice(out, func(i, j int) bool { if out[i].Start != out[j].Start { return out[i].Start < out[j].Start } return out[i].IP < out[j].IP }) } for i := range out { g := s.GeoOf(out[i].IP) out[i].ASN, out[i].ASOrg = g.ASN, g.ASOrg if out[i].CC == "" { out[i].CC = g.CC } out[i].Score = round1(out[i].Score) if out[i].Hosts == nil { out[i].Hosts = []string{} } if out[i].Domains == nil { out[i].Domains = []string{} } } return } // ---- per-IP detail from the registry ---- type ipxEntry struct { at time.Time v *IPLog } type ipxCache struct { mu sync.Mutex m map[string]ipxEntry } // BanEvent is one ban or unban of an address. type BanEvent struct { T int64 `json:"t"` Jail string `json:"jail"` Host string `json:"host,omitempty"` Unban bool `json:"unban"` // Active: this ban is in force now (also set for a ban that began before the window) Active bool `json:"active"` } // IPTimeline holds events per hour and category. type IPTimeline struct { Start int64 `json:"start"` Step int64 `json:"step"` Cats []string `json:"cats"` Series map[string][]uint32 `json:"series"` // Estimated: the daily counters were spread from totals (old record) Estimated bool `json:"estimated,omitempty"` } // IPLog is what the registry says about one address. type IPLog struct { Available bool `json:"available"` Events int `json:"events"` Truncated bool `json:"truncated,omitempty"` Timeline *IPTimeline `json:"timeline"` Source string `json:"timeline_source"` // "events" (hourly, from the registry) or "counters" (daily, from the record) Hosts []Count `json:"hosts"` Domains []Count `json:"domains"` Statuses []Count `json:"statuses"` Methods []Count `json:"methods"` Paths []Count `json:"paths"` UAs []Count `json:"uas"` Users []Count `json:"users"` Bans []BanEvent `json:"ban_history"` Sessions []intel.Session `json:"sessions"` Escalation []intel.Step `json:"escalation"` Cadence intel.Cadence `json:"cadence"` Forged bool `json:"forged"` SessionsN int `json:"sessions_n"` // all sessions, the list keeps the latest 50 SessionsEv int `json:"sessions_events"` // events in all sessions Evs []intel.Ev `json:"-"` // for further analysis by the caller } const ( ipScanBytes = 256 << 20 ipxTTL = 30 * time.Second maxDistinct = 5000 ) func bumpMap(m map[string]uint32, k string) { if k == "" { return } if _, ok := m[k]; ok || len(m) < maxDistinct { m[k]++ } } // IPLogOf derives the detail of one address from the registry on demand // (cached for 30 s, at most 256 MB read per call). func (s *Store) IPLogOf(ip string, from, to int64) *IPLog { if s.elog == nil { return &IPLog{} } key := KeyOf(ip) ck := key + "|" + time.Unix(from, 0).Format("20060102150405") + "|" + time.Unix(to, 0).Format("20060102150405") s.ipx.mu.Lock() if e, ok := s.ipx.m[ck]; ok && time.Since(e.at) < ipxTTL { s.ipx.mu.Unlock() return e.v } s.ipx.mu.Unlock() start := from / 3600 * 3600 nb := int((to-start)/3600) + 1 if nb < 1 { nb = 1 } if nb > 722 { nb = 722 } cats := catStrings() tl := &IPTimeline{Start: start, Step: 3600, Cats: cats, Series: map[string][]uint32{}} for _, c := range cats { tl.Series[c] = make([]uint32, nb) } hosts, doms, sts, meths, paths, uas, users := map[string]uint32{}, map[string]uint32{}, map[string]uint32{}, map[string]uint32{}, map[string]uint32{}, map[string]uint32{}, map[string]uint32{} out := &IPLog{Available: true, Timeline: tl, Bans: []BanEvent{}} info := s.elog.Scan(evlog.Filter{From: from, To: to, IP: key}, ipScanBytes, false, func(r evlog.Rec, _ []byte) bool { out.Events++ if strings.Contains(r.Flags, "G") { out.Forged = true } if b := int((r.T - start) / 3600); b >= 0 && b < nb { if sr, ok := tl.Series[r.Cat]; ok { sr[b]++ } } bumpMap(hosts, r.Host) bumpMap(doms, r.Domain) if r.Status != 0 { bumpMap(sts, itoa(r.Status)) } bumpMap(meths, r.Method) if r.Source == "traefik" && r.Cat != "ok" { bumpMap(paths, r.Path) } bumpMap(uas, r.UA) if r.Cat == string(core.SSHFail) { bumpMap(users, r.User) } if r.Cat == string(core.Ban) && len(out.Bans) < 200 { out.Bans = append(out.Bans, BanEvent{T: r.T, Jail: r.Jail, Host: r.Host, Unban: r.Unban}) } if len(out.Evs) < 200000 { out.Evs = append(out.Evs, toEv(r)) } return true }) out.Truncated = info.Truncated out.Source = "events" if out.Events == 0 { if tl2 := s.counterTimeline(key, from, to); tl2 != nil { out.Timeline, out.Source = tl2, "counters" } } out.Hosts, out.Domains, out.Statuses = topN(hosts, 16), topN(doms, 20), topN(sts, 20) out.Methods, out.Paths, out.UAs, out.Users = topN(meths, 12), topN(paths, 50), topN(uas, 20), topN(users, 20) for i := range out.UAs { out.UAs[i].Label = s.UALabel(out.UAs[i].Key) } sort.Slice(out.Bans, func(i, j int) bool { return out.Bans[i].T < out.Bans[j].T }) for i := range out.Evs { out.Evs[i].IP = key } out.Sessions = intel.Sessions(out.Evs, intel.DefaultGap) if out.Sessions == nil { out.Sessions = []intel.Session{} } if len(out.Sessions) > 0 { best := 0 for i, ss := range out.Sessions { if intel.StageRank(ss.Stage) > intel.StageRank(out.Sessions[best].Stage) { best = i } } out.Escalation = intel.Escalation(out.Sessions[best], out.Evs) } if out.Escalation == nil { out.Escalation = []intel.Step{} } var ts []time.Time for _, e := range out.Evs { if core.Category(e.Cat).IsMalicious() { ts = append(ts, e.T) } } out.Cadence = intel.CadenceFrom(ts) out.SessionsN = len(out.Sessions) for _, ss := range out.Sessions { out.SessionsEv += ss.N } if len(out.Sessions) > 50 { out.Sessions = out.Sessions[len(out.Sessions)-50:] } s.ipx.mu.Lock() if s.ipx.m == nil || len(s.ipx.m) >= 64 { s.ipx.m = map[string]ipxEntry{} } s.ipx.m[ck] = ipxEntry{time.Now(), out} s.ipx.mu.Unlock() return out } func itoa(n int) string { b, _ := json.Marshal(n) return string(b) } // Neighbor is another active address near an investigated one. type Neighbor struct { IP string `json:"ip"` Score float64 `json:"score"` Level core.Level `json:"level"` Last int64 `json:"last"` N uint32 `json:"n"` } // Neighbors lists the other active addresses of the same /24 (IPv4) or /48 // (IPv6) and of the same ASN inside the window, top 20 each by score. func (s *Store) Neighbors(key string, from, to int64) (subnet, asn []Neighbor, asnN int) { subnet, asn = []Neighbor{}, []Neighbor{} var pfx netip.Prefix if a, err := netip.ParseAddr(key); err == nil { bits := 24 if !a.Is4() { bits = 48 } pfx, _ = a.Prefix(bits) } else if p, err := netip.ParsePrefix(key); err == nil { pfx, _ = p.Addr().Prefix(48) } myASN := s.GeoOf(key).ASN now := s.now().Unix() s.mu.RLock() var sub, same []Neighbor for k, r := range s.ips { if k == key || r.Last < from || r.First > to || !isAttacker(r) { continue } strong := r.Strong || attackKinds(r.Counts) >= 2 nb := Neighbor{IP: k, Score: round1(r.Score), Level: core.LevelOf(r.Score, strong, r.adminAt(now)), Last: r.Last, N: uint32(malOf(r.Counts))} var a netip.Addr if x, err := netip.ParseAddr(k); err == nil { a = x } else if p, err := netip.ParsePrefix(k); err == nil { a = p.Addr() } if pfx.IsValid() && pfx.Contains(a) { sub = append(sub, nb) continue } if myASN != 0 && s.GeoOf(k).ASN == myASN { same = append(same, nb) } } s.mu.RUnlock() byScore := func(l []Neighbor) []Neighbor { sort.Slice(l, func(i, j int) bool { if l[i].Score != l[j].Score { return l[i].Score > l[j].Score } return l[i].IP < l[j].IP }) if len(l) > 20 { l = l[:20] } return l } asnN = len(same) subnet = append(subnet, byScore(sub)...) asn = append(asn, byScore(same)...) return } // ScoreBreakdown is the score of an address split by category. func (r *IPRec) scoreBreakdown() map[string]float64 { out := map[string]float64{} var sum float64 for i, v := range r.ScoreBy { sum += float64(v) if v > 0 { out[string(core.Categories[i])] = round1(float64(v)) } } if sum == 0 { // record from before the breakdown existed: estimate from the counts for i, n := range r.Counts { if w := core.Categories[i].Weight(); n > 0 && w > 0 { out[string(core.Categories[i])] = round1(float64(n) * w) } } } return out } func strongReasons(r *IPRec) []string { out := []string{} if r.StrongWhy&whyTool != 0 { out = append(out, "attack_tool_user_agent") } if r.StrongWhy&whySignal != 0 { out = append(out, "high_confidence_signal") } if r.StrongWhy&whyBan != 0 { out = append(out, "fail2ban_ban") } if attackKinds(r.Counts) >= 2 { out = append(out, "multiple_attack_categories") } return out } // IPInfo carries the per-record parts of the detail view that need the table. type IPInfo struct { ScoreBreakdown map[string]float64 StrongReasons []string TTB int64 FirstMal int64 ActiveDays int Users []UserN Status [6]uint32 Fams []FamN Techs []TechN Expo []Expo Banned bool ListedSince int64 Samples []string Domains []string Jails []string BanSince int64 First, Last int64 Counts [core.NumCats]uint32 Estimated bool DayBase int64 DayCats [][core.NumCats]uint16 } // IPInfoOf returns the capped per-record detail of an address. func (s *Store) IPInfoOf(ip string) (IPInfo, bool) { key := KeyOf(ip) s.mu.RLock() defer s.mu.RUnlock() r := s.ips[key] if r == nil { return IPInfo{}, false } days := 0 for b := r.Days; b != 0; b &= b - 1 { days++ } return IPInfo{ScoreBreakdown: r.scoreBreakdown(), StrongReasons: strongReasons(r), TTB: r.TTB, FirstMal: r.FirstMal, ActiveDays: days, Users: append([]UserN(nil), r.Users...), Status: r.Status, Fams: append([]FamN(nil), r.Fams...), Techs: append([]TechN(nil), r.Techs...), Expo: append([]Expo(nil), r.Expo...), Banned: len(r.Jails) > 0, ListedSince: r.ListedSince, Samples: append([]string(nil), r.Samples...), Domains: append([]string(nil), r.Domains...), Jails: append([]string(nil), r.Jails...), BanSince: r.BanSince, First: r.First, Last: r.Last, Counts: r.Counts, Estimated: r.DayEst, DayBase: r.DayBase, DayCats: append([][core.NumCats]uint16(nil), r.DayCats...)}, true } func toEv(r evlog.Rec) intel.Ev { return intel.Ev{T: time.Unix(r.T, 0), IP: KeyOf(r.IP), Host: r.Host, Domain: r.Domain, Cat: r.Cat, Fam: r.Fam, Path: r.Path, User: r.User, Jail: r.Jail, Status: r.Status, Strong: strings.Contains(r.Flags, "S"), Unban: r.Unban} } // counterTimeline builds a daily timeline from the per-day counters of the IP // record, for the days the event registry does not cover. func (s *Store) counterTimeline(key string, from, to int64) *IPTimeline { s.mu.RLock() defer s.mu.RUnlock() r := s.ips[key] if r == nil || len(r.DayCats) == 0 { return nil } cats := catStrings() start := from / 86400 * 86400 nb := int((to-start)/86400) + 1 if nb < 1 || nb > 32 { nb = max(1, min(nb, 32)) } tl := &IPTimeline{Start: start, Step: 86400, Cats: cats, Series: map[string][]uint32{}, Estimated: r.DayEst} for _, c := range cats { tl.Series[c] = make([]uint32, nb) } any := false for k, row := range r.DayCats { day := r.DayBase - int64(k) b := int(day - start/86400) if b < 0 || b >= nb { continue } for ci, n := range row { if n > 0 { tl.Series[cats[ci]][b] += uint32(n) any = true } } } if !any { return nil } return tl }