package store import ( "context" "sort" "time" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel" ) // Caps of the campaign views. const ( MaxCampaignsOut = 200 MaxMembersOut = 500 ) // CampaignsOut is the campaign list derived from a period study. type CampaignsOut struct { Range RangeInfo `json:"range"` Enabled bool `json:"enabled"` Truncated bool `json:"truncated,omitempty"` Total int `json:"total"` IPsN int `json:"ips_n"` Campaigns []intel.Campaign `json:"campaigns"` } // Member is one address of a campaign with its sessions in the period. type Member struct { IP string `json:"ip"` First int64 `json:"first"` Last int64 `json:"last"` Stage string `json:"stage"` Sessions []intel.Session `json:"sessions"` } // CampaignDetail is one campaign with its members and ordered sessions. type CampaignDetail struct { Range RangeInfo `json:"range"` Truncated bool `json:"truncated,omitempty"` Campaign intel.Campaign `json:"campaign"` Members []Member `json:"members"` } var stageRank = map[string]int{intel.StageRecon: 1, intel.StageProbe: 2, intel.StageExploit: 3, intel.StageAccess: 4, intel.StageBanned: 5} // StageRank orders the escalation stages (0 for an unknown one). func StageRank(s string) int { return stageRank[s] } // CampaignsOf lists the campaigns of a period study (at most MaxCampaignsOut, // most addresses first) and the number of distinct addresses they group. func CampaignsOf(p PeriodOut) CampaignsOut { list := append([]intel.Campaign(nil), p.Campaigns...) sort.SliceStable(list, func(i, j int) bool { if list[i].IPsN != list[j].IPsN { return list[i].IPsN > list[j].IPsN } if !list[i].First.Equal(list[j].First) { return list[i].First.Before(list[j].First) } return list[i].ID < list[j].ID }) out := CampaignsOut{Range: p.Range, Enabled: p.Enabled, Truncated: p.Truncated, Total: len(list)} seen := map[string]bool{} n := 0 for _, c := range list { n += c.IPsN for _, ip := range c.IPs { seen[ip] = true } } out.IPsN = max(len(seen), 0) if n > 0 && len(seen) == 0 { out.IPsN = n } if len(list) > MaxCampaignsOut { list = list[:MaxCampaignsOut] } out.Campaigns = list out.Total = len(list) // what can be paged through (the cap above applies) if out.Campaigns == nil { out.Campaigns = []intel.Campaign{} } return out } // CampaignOf returns the detail of one campaign of a period study. func CampaignOf(p PeriodOut, id string) (CampaignDetail, bool) { for _, c := range p.Campaigns { if c.ID != id { continue } d := CampaignDetail{Range: p.Range, Truncated: p.Truncated, Campaign: c, Members: []Member{}} by := map[string]*Member{} for _, ip := range c.IPs { by[ip] = &Member{IP: ip, Stage: "", Sessions: []intel.Session{}} } total := 0 for _, s := range p.Sessions { if s.CampaignID != id || total >= MaxMembersOut { continue } m := by[s.IP] if m == nil { m = &Member{IP: s.IP, Sessions: []intel.Session{}} by[s.IP] = m } total++ st, en := s.Start.Unix(), s.End.Unix() if m.First == 0 || st < m.First { m.First = st } if en > m.Last { m.Last = en } if StageRank(s.Stage) > StageRank(m.Stage) { m.Stage = s.Stage } m.Sessions = append(m.Sessions, s) } for _, m := range by { sort.Slice(m.Sessions, func(i, j int) bool { return m.Sessions[i].Start.Before(m.Sessions[j].Start) }) d.Members = append(d.Members, *m) } sort.Slice(d.Members, func(i, j int) bool { a, b := d.Members[i], d.Members[j] if (a.First == 0) != (b.First == 0) { return a.First != 0 } if a.First != b.First { return a.First < b.First } return a.IP < b.IP }) if len(d.Members) > MaxMembersOut { d.Members = d.Members[:MaxMembersOut] } return d, true } return CampaignDetail{}, false } // FunnelOut is the escalation funnel of a period study. type FunnelOut struct { Range RangeInfo `json:"range"` Enabled bool `json:"enabled"` Truncated bool `json:"truncated,omitempty"` SessionsN int `json:"sessions_n"` Sampled bool `json:"sampled,omitempty"` Stages map[string]int `json:"stages"` Reached map[string]int `json:"reached"` Exploited int `json:"exploited"` Sessions []intel.Session `json:"sessions"` Escalations []EscalationOut `json:"escalations"` } // StageCounts is the funnel over every session of a study. type StageCounts struct { SessionsN int Truncated bool Stages map[string]int Reached map[string]int Exploited int } func newCounts() StageCounts { z := func() map[string]int { return map[string]int{"recon": 0, "probe": 0, "exploit": 0, "access": 0, "banned": 0} } return StageCounts{Stages: z(), Reached: z()} } // Add counts one session. A ban says nothing about how far the session got: // it counts as recon and probe. func (c *StageCounts) Add(stage string, success bool) { if _, ok := c.Stages[stage]; !ok { return } c.SessionsN++ c.Stages[stage]++ r := StageRank(stage) if stage == intel.StageBanned { c.Reached["recon"]++ c.Reached["probe"]++ c.Reached[intel.StageBanned]++ } else { for k, v := range stageRank { if v <= r { c.Reached[k]++ } } } if r == 3 || r == 4 || success { c.Exploited++ } } // CountStages studies [q.From, q.To] and counts ALL its sessions by stage // (the period study keeps only 200). Cached 30 s like the other studies. func (s *Store) CountStages(q PeriodQuery) StageCounts { k := studyKey{"funnel", q.From, q.To, q.Host, q.IP, q.Cat, q.Fam, q.Gap} return s.cached(k, func() any { return s.countStages(q) }).(StageCounts) } func (s *Store) countStages(q PeriodQuery) StageCounts { out := newCounts() 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) { out.Add(ss.Stage, ss.Success) } return out } // FunnelOf builds the funnel: the counts cover every session when counts is // given (nil: only the listed ones), the list holds the most severe sessions // of the study (the study keeps at most 200). func FunnelOf(p PeriodOut, counts *StageCounts) FunnelOut { f := FunnelOut{Range: p.Range, Enabled: p.Enabled, Truncated: p.Truncated, SessionsN: p.SessionsN} c := newCounts() if counts != nil { c = *counts f.SessionsN = c.SessionsN f.Truncated = f.Truncated || c.Truncated } else { for _, s := range p.Sessions { c.Add(s.Stage, s.Success) } } f.Stages, f.Reached, f.Exploited = c.Stages, c.Reached, c.Exploited f.Sessions = append([]intel.Session{}, p.Sessions...) f.Escalations = p.Escalations if f.Escalations == nil { f.Escalations = []EscalationOut{} } f.Sampled = f.SessionsN > len(f.Sessions) sort.SliceStable(f.Sessions, func(i, j int) bool { a, b := StageRank(f.Sessions[i].Stage), StageRank(f.Sessions[j].Stage) if a != b { return a > b } x, y := f.Sessions[i], f.Sessions[j] if !x.Start.Equal(y.Start) { return x.Start.After(y.Start) } if x.IP != y.IP { return x.IP < y.IP } return x.End.After(y.End) }) return f }