package store import ( "errors" "math" "net/netip" "strings" "time" "unicode/utf8" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" ) // ExportVersion is the schema version of PeerExport. const ExportVersion = 1 // PeerExport is the single document a hub pulls from a peer: the threat // summary (IP rows already carry the detail the hub shows), and the traffic // analytics for all domains together and for each domain. type PeerExport struct { V int `json:"v"` Summary Summary `json:"summary"` Traffic map[string]TrafficData `json:"traffic"` } // Export builds the peer document for a named range. func (s *Store) Export(rangeName string) PeerExport { return s.ExportFor(ParseRange(rangeName)) } // ExportFor builds the peer document for a window. func (s *Store) ExportFor(rg Range) PeerExport { all := s.TrafficFor(rg, "all") e := PeerExport{V: ExportVersion, Summary: s.SummaryFor(rg), Traffic: map[string]TrafficData{"all": all}} for _, d := range all.Domains { e.Traffic[d.Key] = s.TrafficFor(rg, d.Key) } return e } var errBadExport = errors.New("invalid peer export") // clipS bounds a string and strips control characters (it may come from a peer). func clipS(s string, n int) string { if strings.IndexFunc(s, func(r rune) bool { return r < 0x20 || r == 0x7f }) >= 0 { s = strings.Map(func(r rune) rune { if r < 0x20 || r == 0x7f { return -1 } return r }, s) } if len(s) <= n { return s } return strings.ToValidUTF8(s[:n], "") } func clipList(l []string, max, n int) []string { if len(l) > max { l = l[:max] } for i := range l { l[i] = clipS(l[i], n) } return l } func clipCounts(l []Count, max int) []Count { if len(l) > max { l = l[:max] } for i := range l { l[i].Key, l[i].Label = clipS(l[i].Key, 300), clipS(l[i].Label, 120) } return l } func finite(f float64) bool { return !math.IsNaN(f) && !math.IsInf(f, 0) && f >= 0 } func fixGrid(series map[string][]uint32, cats []string, nb int) { for _, c := range cats { if len(series[c]) != nb { series[c] = make([]uint32, nb) } } } // Sanitize bounds everything that came from a peer: a compromised peer must // not be able to inflate the hub's memory or break its charts. It rejects // documents of the wrong schema version. func (e *PeerExport) Sanitize(rangeName string) error { return e.SanitizeRange(ParseRange(rangeName)) } // SanitizeRange is Sanitize for any window; the grid is recomputed locally. func (e *PeerExport) SanitizeRange(rg Range) error { if e.V != ExportVersion { return errBadExport } nowU := time.Now().Unix() s := &e.Summary s.Version = clipS(s.Version, 32) s.Range, s.Attribution = rg.Info(nowU), clipS(s.Attribution, 200) s.Rates = sanitizeRates(s.Rates) if len(s.Hosts) > 4 { s.Hosts = s.Hosts[:4] } for i := range s.Hosts { s.Hosts[i].Version, s.Hosts[i].Error = clipS(s.Hosts[i].Version, 32), clipS(s.Hosts[i].Error, 160) s.Hosts[i].Location = sanitizeLocation(s.Hosts[i].Location) } // timeline: the grid is fixed by the range gr := rg.grid(nowU) nb := gr.N s.Timeline.Step, s.Timeline.Cats = gr.Step, catStrings() if s.Timeline.Series == nil { s.Timeline.Series = map[string][]uint32{} } fixGrid(s.Timeline.Series, s.Timeline.Cats, nb) for k := range s.Timeline.Series { known := false for _, c := range s.Timeline.Cats { known = known || c == k } if !known { delete(s.Timeline.Series, k) } } cats := map[string]bool{} for _, c := range core.Categories { cats[string(c)] = true } for k := range s.Totals.Counts { if !cats[k] { delete(s.Totals.Counts, k) } } if len(s.IPs) > summaryIPs { s.IPs = s.IPs[:summaryIPs] } ips := s.IPs[:0] for _, x := range s.IPs { key, ok := sanitizeKey(x.IP) if !ok || math.IsNaN(x.Score) || math.IsInf(x.Score, 0) { continue } x.IP = key x.Score = math.Max(0, math.Min(x.Score, 1e6)) // a peer cannot grant admin immunity, and its strong flag only counts // when its own score for the address is hostile x.Admin = false x.Strong = x.Strong && x.Score >= core.HostileScore x.Level = core.LevelOf(x.Score, x.Strong, x.Admin) for k := range x.Counts { if !cats[k] { delete(x.Counts, k) } } x.Hosts = clipList(x.Hosts, 4, 64) x.Domains, x.Samples = clipList(x.Domains, maxDomain, 120), clipList(x.Samples, maxSample, 300) x.UAs, x.UALabels = clipList(x.UAs, maxUAs, 200), clipList(x.UALabels, maxUAs, 120) x.Jails = clipList(x.Jails, maxJails, 40) x.RDNS, x.CC, x.Country, x.City, x.ASOrg = clipS(x.RDNS, 200), validCC2(clipS(x.CC, 2)), clipS(x.Country, 80), clipS(x.City, 80), clipS(x.ASOrg, 120) ips = append(ips, x) } s.IPs = ips s.TopPaths, s.TopDomains = clipCounts(s.TopPaths, topKeep), clipCounts(s.TopDomains, topKeep) s.TopUAs, s.TopUsers, s.Countries = clipCounts(s.TopUAs, topKeep), clipCounts(s.TopUsers, topKeep), clipCounts(s.Countries, 120) if len(s.Recent) > 60 { s.Recent = s.Recent[:60] } recent := s.Recent[:0] for _, r := range s.Recent { if !cats[r.Cat] { continue // unknown category: it would become a CSS class in the dashboard } recent = append(recent, r) } s.Recent = recent for i := range s.Recent { r := &s.Recent[i] r.IP, r.Cat, r.Source = clipS(r.IP, 45), clipS(r.Cat, 20), clipS(r.Source, 20) r.Domain, r.Method, r.Path = clipS(r.Domain, 100), clipS(r.Method, 12), clipS(r.Path, 240) r.User, r.Jail = clipS(r.User, 64), clipS(r.Jail, 40) sanitizeFeedDetail(r) } kept := s.Recent[:0] for _, r := range s.Recent { if SanitizeFeed(&r) { kept = append(kept, r) } } s.Recent = kept if len(s.Sources) > 16 { s.Sources = s.Sources[:16] } for i := range s.Sources { x := &s.Sources[i] x.Name, x.Path, x.Error = clipS(x.Name, 40), "", clipS(x.Error, 160) if !validStates[x.State] { x.State = "error" } } if e.Traffic == nil { e.Traffic = map[string]TrafficData{} } if len(e.Traffic) > maxDomains+3 { for k := range e.Traffic { if len(e.Traffic) <= maxDomains+3 { break } if k != "all" { delete(e.Traffic, k) } } } for k, t := range e.Traffic { if !utf8.ValidString(k) || len(k) > 253 { delete(e.Traffic, k) continue } t.sanitize(rg, nowU) e.Traffic[k] = t } return nil } func (t *TrafficData) sanitize(rg Range, nowU int64) { gr := rg.grid(nowU) nb, step := gr.N, gr.Step t.Range = rg.Info(nowU) t.Timeline.Start = gr.Start t.Domain = clipS(t.Domain, 253) t.Timeline.Step = step if len(t.Timeline.Req) != nb { t.Timeline.Req = make([]uint32, nb) } if len(t.Timeline.Pages) != nb { t.Timeline.Pages = make([]uint32, nb) } t.Domains = clipCounts(t.Domains, maxDomains+1) t.TopPages, t.Referrers = clipCounts(t.TopPages, anTop), clipCounts(t.Referrers, anTop) t.Countries, t.Cities = clipCounts(t.Countries, 120), clipCounts(t.Cities, anTop) t.Browsers, t.OSes = clipCounts(t.Browsers, anTop), clipCounts(t.OSes, anTop) t.Devices, t.BotNames = clipCounts(t.Devices, 10), clipCounts(t.BotNames, anTop) t.Finish() } // SanitizeTraffic bounds a TrafficData received from elsewhere. func SanitizeTraffic(t *TrafficData, rangeName string) { t.sanitize(ParseRange(rangeName), time.Now().Unix()) } // SanitizeTrafficRange bounds a TrafficData received for any window. func SanitizeTrafficRange(t *TrafficData, rg Range) { t.sanitize(rg, time.Now().Unix()) } // sanitizeFeedDetail bounds the investigation fields of a feed row from a peer. func sanitizeFeedDetail(r *FeedEvent) { r.UA, r.Fam, r.Marker = clipS(r.UA, 200), clipS(r.Fam, 40), clipS(r.Marker, 80) r.ID = 0 if len(r.Tech) > 8 { r.Tech = r.Tech[:8] } for i := range r.Tech { r.Tech[i] = clipS(r.Tech[i], 16) } if r.Bytes < 0 || r.Bytes > 1<<40 { r.Bytes = 0 } if r.DurMS < 0 || r.DurMS > 1<<31 { r.DurMS = 0 } f := "" for _, c := range r.Flags { if strings.ContainsRune("SWGFX", c) && !strings.ContainsRune(f, c) { f += string(c) } } r.Flags = f } func sanitizeRates(r Rates) Rates { capU := func(v uint64) uint64 { return min(v, 1<<40) } r.Last15m, r.Last1h, r.Last24h, r.PrevPeriod = capU(r.Last15m), capU(r.Last1h), capU(r.Last24h), capU(r.PrevPeriod) for _, f := range []*float64{&r.PerHourAvg24h, &r.PerHourAvg7d} { if !finite(*f) || *f > 1e12 { *f = 0 } } if r.ChangePct != nil && (math.IsNaN(*r.ChangePct) || math.IsInf(*r.ChangePct, 0)) { r.ChangePct = nil } if r.PeakHour.T < 0 { r.PeakHour = PeakHour{} } r.NewAttackers, r.ActiveAttackers = max(0, min(r.NewAttackers, 1<<30)), max(0, min(r.ActiveAttackers, 1<<30)) return r } var validStates = map[string]bool{"following": true, "waiting": true, "backfill": true, "error": true, "disabled": true} // sanitizeKey validates a table key received from a peer: a plain address // (no zone) or an IPv6 /64 prefix, normalized. func sanitizeKey(in string) (string, bool) { if a, err := netip.ParseAddr(in); err == nil { if a.Zone() != "" { return "", false } return KeyOf(a.String()), true } if p, err := netip.ParsePrefix(in); err == nil && p.Addr().Is6() && p.Addr().Zone() == "" { return KeyOf(in), true } return "", false }