package egress import ( "net/netip" "sort" "strings" ) // Finding is one alert; repeated observations update it. type Finding struct { ID string `json:"id"` Kind string `json:"kind"` Severity string `json:"severity"` Workload string `json:"workload"` Dst string `json:"dst"` DPort uint16 `json:"dport"` Proto string `json:"proto"` Count int `json:"count"` IntervalS float64 `json:"interval_s"` Jitter float64 `json:"jitter"` First int64 `json:"first"` Last int64 `json:"last"` Detail string `json:"detail"` Host string `json:"host,omitempty"` // Ticket fields are filled by the server from the incident store. TicketID string `json:"ticket_id"` TicketStatus string `json:"ticket_status"` Suppressed bool `json:"suppressed"` // Samples are the unix times of the last connections (beacons only, at most MaxSamples). Samples []int64 `json:"samples,omitempty"` } // MaxSamples bounds Finding.Samples. const MaxSamples = 64 // CountryOut sums the destinations of one country. type CountryOut struct { CC string `json:"cc"` Conns uint64 `json:"conns"` Dsts int `json:"dsts"` } // WorkloadOut summarises a workload over the window. type WorkloadOut struct { Name string `json:"name"` Role string `json:"role"` Conns uint64 `json:"conns"` Dsts int `json:"dsts"` Ports int `json:"ports"` Findings int `json:"findings"` Suppressed uint64 `json:"suppressed_scan_conns"` Host string `json:"host,omitempty"` } // Timeline holds hourly connection counts per workload. type Timeline struct { Start int64 `json:"start"` Step int64 `json:"step"` Series map[string][]uint32 `json:"series"` } // DstOut is a top destination. type DstOut struct { IP string `json:"ip"` CC string `json:"cc"` ASN string `json:"asn"` Org string `json:"org"` Conns uint64 `json:"conns"` Workloads []string `json:"workloads"` Ports []uint16 `json:"ports"` } // BurstOut summarises a scanner fan-out burst. type BurstOut struct { Workload string `json:"workload"` Start int64 `json:"start"` End int64 `json:"end"` Targets int `json:"targets"` Nets []string `json:"nets"` Ports []uint16 `json:"ports"` Conns uint32 `json:"conns"` BadDstHit uint32 `json:"bad_dst_hits"` Host string `json:"host,omitempty"` } // ScannerOut groups the scanner bursts. type ScannerOut struct { Bursts []BurstOut `json:"bursts"` } // Report is the egress analysis of a window. type Report struct { Workloads []WorkloadOut `json:"workloads"` Timeline Timeline `json:"timeline"` TopDst []DstOut `json:"top_dst"` Findings []Finding `json:"findings"` Scanner ScannerOut `json:"scanner"` ByCountry []CountryOut `json:"by_country"` } func (bs *burstState) out(wl string, end int64) BurstOut { o := BurstOut{Workload: wl, Start: bs.start, End: end, Targets: len(bs.targets), Conns: bs.conns, BadDstHit: bs.badHits, Nets: []string{}, Ports: []uint16{}} type nc struct { p netip.Prefix n uint32 } var ns []nc for p, n := range bs.nets { ns = append(ns, nc{p, n}) } sort.Slice(ns, func(i, j int) bool { if ns[i].n != ns[j].n { return ns[i].n > ns[j].n } return ns[i].p.String() < ns[j].p.String() }) for i := 0; i < len(ns) && i < 10; i++ { o.Nets = append(o.Nets, ns[i].p.String()) } type pc struct { p uint16 n uint32 } var ps []pc for p, n := range bs.ports { ps = append(ps, pc{p, n}) } sort.Slice(ps, func(i, j int) bool { if ps[i].n != ps[j].n { return ps[i].n > ps[j].n } return ps[i].p < ps[j].p }) for i := 0; i < len(ps) && i < 10; i++ { o.Ports = append(o.Ports, ps[i].p) } return o } // Report builds the analysis of [from, to] (unix seconds). func (e *Engine) Report(from, to int64) Report { e.mu.Lock() defer e.mu.Unlock() if to <= from { to = from + 1 } startH, endH := from/3600, to/3600 if endH-startH > HourBuckets-1 { startH = endH - (HourBuckets - 1) } nb := int(endH-startH) + 1 r := Report{Workloads: []WorkloadOut{}, TopDst: []DstOut{}, Findings: []Finding{}, ByCountry: []CountryOut{}, Timeline: Timeline{Start: startH * 3600, Step: 3600, Series: map[string][]uint32{}}, Scanner: ScannerOut{Bursts: []BurstOut{}}} fc := map[string]int{} for _, f := range e.findings { if f.Last >= from && f.First <= to { c := *f c.Samples = append([]int64(nil), f.Samples...) r.Findings = append(r.Findings, c) fc[f.Workload]++ } } sort.Slice(r.Findings, func(i, j int) bool { a, b := r.Findings[i], r.Findings[j] if sevRank[a.Severity] != sevRank[b.Severity] { return sevRank[a.Severity] > sevRank[b.Severity] } if a.Last != b.Last { return a.Last > b.Last } return a.ID < b.ID }) names := make([]string, 0, len(e.ws)) for n := range e.ws { names = append(names, n) } sort.Strings(names) for _, n := range names { w := e.ws[n] o := WorkloadOut{Name: n, Role: w.role, Findings: fc[n]} series := make([]uint32, nb) ds, ps := map[uint32]struct{}{}, map[uint32]struct{}{} for h := startH; h <= endH; h++ { b := &w.hours[h%HourBuckets] if b.hour != h { continue } series[h-startH] = b.conns o.Conns += uint64(b.conns) o.Suppressed += uint64(b.supp) for _, x := range b.dsts { ds[x] = struct{}{} } for _, x := range b.ports { ps[x] = struct{}{} } } o.Dsts, o.Ports = len(ds), len(ps) if o.Conns == 0 && o.Suppressed == 0 && o.Findings == 0 { continue } r.Workloads = append(r.Workloads, o) r.Timeline.Series[n] = series } type scored struct { ds *dstStat n uint64 } var all []scored d0, d1 := int32(from/86400), int32(to/86400) for el := e.dsts.l.Front(); el != nil; el = el.Next() { ds := el.Value.(*lent[netip.Addr, *dstStat]).v var n uint64 for _, d := range ds.days { if d.day >= d0 && d.day <= d1 { n += uint64(d.n) } } if n > 0 { all = append(all, scored{ds, n}) } } sort.Slice(all, func(i, j int) bool { if all[i].n != all[j].n { return all[i].n > all[j].n } return all[i].ds.ip.Compare(all[j].ds.ip) < 0 }) bc := map[string]*CountryOut{} for _, a := range all { c := bc[a.ds.cc] if c == nil { c = &CountryOut{CC: a.ds.cc} bc[a.ds.cc] = c } c.Conns += a.n c.Dsts++ } for _, c := range bc { r.ByCountry = append(r.ByCountry, *c) } sortCountries(r.ByCountry) for i := 0; i < len(all) && i < 50; i++ { ds := all[i].ds ports := append([]uint16(nil), ds.ports...) sort.Slice(ports, func(a, b int) bool { return ports[a] < ports[b] }) r.TopDst = append(r.TopDst, DstOut{IP: ds.ip.String(), CC: ds.cc, ASN: ds.asn, Org: ds.og, Conns: all[i].n, Workloads: append([]string{}, ds.wls...), Ports: ports}) } for _, b := range e.closed { if b.End >= from && b.Start <= to { r.Scanner.Bursts = append(r.Scanner.Bursts, b) } } for _, n := range names { if w := e.ws[n]; w.burst != nil && w.role == RoleScanner && w.burst.lastFan >= from && w.burst.start <= to { r.Scanner.Bursts = append(r.Scanner.Bursts, w.burst.out(n, w.burst.lastFan)) } } return r } const ( maxPeerWorkloads = 256 maxPeerFindings = MaxFindings maxStr = 200 maxCountries = 300 ) func sortCountries(cs []CountryOut) { sort.Slice(cs, func(i, j int) bool { if cs[i].Conns != cs[j].Conns { return cs[i].Conns > cs[j].Conns } return cs[i].CC < cs[j].CC }) } func clip(s string) string { if len(s) > maxStr { return s[:maxStr] } return strings.ToValidUTF8(s, "") } // Sanitize bounds an untrusted peer report and stamps it with the peer name. // KnownKind reports whether k is a finding kind produced by the engine. func KnownKind(k string) bool { switch k { case "scan", "bad_dst", "tor", "port", "dns_bypass", "new_geo", "beacon", "infra": return true } return false } func (r *Report) Sanitize(host string) { if len(r.Workloads) > maxPeerWorkloads { r.Workloads = r.Workloads[:maxPeerWorkloads] } if len(r.Findings) > maxPeerFindings { r.Findings = r.Findings[:maxPeerFindings] } if len(r.TopDst) > 50 { r.TopDst = r.TopDst[:50] } if len(r.Scanner.Bursts) > maxClosedBurst+maxPeerWorkloads { r.Scanner.Bursts = r.Scanner.Bursts[:maxClosedBurst+maxPeerWorkloads] } for i := range r.Workloads { w := &r.Workloads[i] w.Name, w.Role, w.Host = clip(w.Name), clip(w.Role), host } // a peer may send only the kinds this package produces; the rest is dropped kept := r.Findings[:0] for _, f := range r.Findings { if KnownKind(f.Kind) { kept = append(kept, f) } } r.Findings = kept for i := range r.Findings { f := &r.Findings[i] f.ID, f.Kind, f.Severity = host+":"+clip(f.ID), clip(f.Kind), clip(f.Severity) f.Workload, f.Dst, f.Proto, f.Detail, f.Host = clip(f.Workload), clip(f.Dst), clip(f.Proto), clip(f.Detail), host if len(f.Samples) > MaxSamples { f.Samples = f.Samples[len(f.Samples)-MaxSamples:] } } if len(r.ByCountry) > maxCountries { r.ByCountry = r.ByCountry[:maxCountries] } for i := range r.ByCountry { r.ByCountry[i].CC = clip(r.ByCountry[i].CC) } for i := range r.TopDst { d := &r.TopDst[i] d.IP, d.CC, d.ASN, d.Org = clip(d.IP), clip(d.CC), clip(d.ASN), clip(d.Org) if len(d.Workloads) > 8 { d.Workloads = d.Workloads[:8] } for j := range d.Workloads { d.Workloads[j] = clip(d.Workloads[j]) } if len(d.Ports) > 8 { d.Ports = d.Ports[:8] } } for i := range r.Scanner.Bursts { b := &r.Scanner.Bursts[i] b.Workload, b.Host = clip(b.Workload), host if len(b.Nets) > 10 { b.Nets = b.Nets[:10] } for j := range b.Nets { b.Nets[j] = clip(b.Nets[j]) } if len(b.Ports) > 10 { b.Ports = b.Ports[:10] } } for k, v := range r.Timeline.Series { if len(v) > HourBuckets { r.Timeline.Series[k] = v[:HourBuckets] } } if len(r.Timeline.Series) > maxPeerWorkloads { r.Timeline.Series = map[string][]uint32{} } } // Merge adds a sanitized peer report to r (the hub view). Series are keyed // "host/workload" and placed on r's hourly grid. func (r *Report) Merge(o Report, host string) { r.Workloads = append(r.Workloads, o.Workloads...) r.Findings = append(r.Findings, o.Findings...) r.Scanner.Bursts = append(r.Scanner.Bursts, o.Scanner.Bursts...) r.TopDst = append(r.TopDst, o.TopDst...) if len(o.ByCountry) > 0 { idx := map[string]int{} for i, c := range r.ByCountry { idx[c.CC] = i } for _, c := range o.ByCountry { if i, ok := idx[c.CC]; ok { r.ByCountry[i].Conns += c.Conns r.ByCountry[i].Dsts += c.Dsts // a destination reached by two hosts counts twice continue } idx[c.CC] = len(r.ByCountry) r.ByCountry = append(r.ByCountry, c) } sortCountries(r.ByCountry) } sort.SliceStable(r.TopDst, func(i, j int) bool { return r.TopDst[i].Conns > r.TopDst[j].Conns }) if len(r.TopDst) > 50 { r.TopDst = r.TopDst[:50] } sort.SliceStable(r.Findings, func(i, j int) bool { a, b := r.Findings[i], r.Findings[j] if sevRank[a.Severity] != sevRank[b.Severity] { return sevRank[a.Severity] > sevRank[b.Severity] } return a.Last > b.Last }) if len(r.Findings) > MaxFindings { r.Findings = r.Findings[:MaxFindings] } if r.Timeline.Step == 0 { r.Timeline.Step = 3600 } for k, v := range o.Timeline.Series { if r.Timeline.Start == 0 { r.Timeline.Start = o.Timeline.Start } n := len(v) off := int((o.Timeline.Start - r.Timeline.Start) / 3600) for _, ex := range r.Timeline.Series { n = len(ex) break } dst := make([]uint32, n) for i, x := range v { if j := i + off; j >= 0 && j < n { dst[j] = x } } r.Timeline.Series[host+"/"+k] = dst } } // Stamp marks the items of a trusted (local) report with its host name, as // Sanitize does for a peer, so that a hub view can tell them apart. func (r *Report) Stamp(host string) { for i := range r.Workloads { r.Workloads[i].Host = host } for i := range r.Findings { r.Findings[i].Host = host r.Findings[i].ID = host + ":" + r.Findings[i].ID } for i := range r.Scanner.Bursts { r.Scanner.Bursts[i].Host = host } } // EmptyReport is a well-formed report without data. func EmptyReport() Report { return Report{Workloads: []WorkloadOut{}, TopDst: []DstOut{}, Findings: []Finding{}, ByCountry: []CountryOut{}, Scanner: ScannerOut{Bursts: []BurstOut{}}, Timeline: Timeline{Step: 3600, Series: map[string][]uint32{}}} } // Dst looks one destination up in the dst table (not limited to the top 50): // its connections in [from, to] and the findings that target it. ok is false // when the window holds neither. func (e *Engine) Dst(from, to int64, ip netip.Addr) (DstOut, []Finding, bool) { e.mu.Lock() defer e.mu.Unlock() if to <= from { to = from + 1 } fs := []Finding{} for _, f := range e.findings { if f.Last >= from && f.First <= to && f.Dst == ip.String() { c := *f c.Samples = append([]int64(nil), f.Samples...) fs = append(fs, c) } } sort.Slice(fs, func(i, j int) bool { if fs[i].Last != fs[j].Last { return fs[i].Last > fs[j].Last } return fs[i].ID < fs[j].ID }) out := DstOut{IP: ip.String(), Workloads: []string{}, Ports: []uint16{}} if el, ok := e.dsts.m[ip]; ok { // read-only: no LRU promotion ds := el.Value.(*lent[netip.Addr, *dstStat]).v d0, d1 := int32(from/86400), int32(to/86400) for _, d := range ds.days { if d.day >= d0 && d.day <= d1 { out.Conns += uint64(d.n) } } out.CC, out.ASN, out.Org = ds.cc, ds.asn, ds.og out.Workloads = append(out.Workloads, ds.wls...) out.Ports = append(out.Ports, ds.ports...) sort.Slice(out.Ports, func(a, b int) bool { return out.Ports[a] < out.Ports[b] }) } if out.Conns == 0 && len(fs) == 0 { return DstOut{}, nil, false } return out, fs, true }