Files
urutau/internal/store/export.go
T
Lucas RayanandClaude Opus 5.5 b4a2c2c9ec
Release / Plan (reuse the published image?) (push) Successful in 4s
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 1m29s
CI / Tests (Linux, race detector) (push) Failing after 1m48s
CI / Dependency audit (push) Successful in 21s
Release / ci (push) Failing after 1m50s
Release / Build image (amd64) (push) Skipped
Release / Build image (arm64) (push) Skipped
Release / Publish tags (push) Skipped
Release / Gitea release (push) Skipped
feat: Urutau 1.0.0, lightweight threat intelligence and web analytics
Always-on Go service (stdlib only) that follows the Traefik JSON access
log, the sshd log and the fail2ban log of a host, classifies attacks,
scores sources, keeps bounded aggregates with snapshots, and serves an
embedded dashboard with live updates, offline geolocation (DB-IP Lite),
privacy-friendly traffic analytics, an exportable blocklist and
token-authenticated federation between instances.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 16:13:34 -03:00

257 lines
7.1 KiB
Go

package store
import (
"errors"
"math"
"net/netip"
"strings"
"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 range.
func (s *Store) Export(rangeName string) PeerExport {
rg := ParseRange(rangeName)
all := s.TrafficSummary(rg.Name, "all")
e := PeerExport{V: ExportVersion, Summary: s.Summary(rg.Name), Traffic: map[string]TrafficData{"all": all}}
for _, d := range all.Domains {
e.Traffic[d.Key] = s.TrafficSummary(rg.Name, 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 {
if e.V != ExportVersion {
return errBadExport
}
rg := ParseRange(rangeName)
s := &e.Summary
s.Version = clipS(s.Version, 32)
s.Range, s.Attribution = rg.Name, clipS(s.Attribution, 200)
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)
}
// timeline: the grid is fixed by the range
nb := int(rg.Dur.Seconds()) / int(rg.Step)
s.Timeline.Step, s.Timeline.Cats = rg.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), 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, r.CC = clipS(r.User, 64), clipS(r.Jail, 40), clipS(r.CC, 2)
}
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)
e.Traffic[k] = t
}
return nil
}
func trafficGrid(rg Range) (int, int64) {
switch rg.Name {
case "1h":
return 60, 60
case "24h":
return 96, 900
}
return 168, 3600
}
func (t *TrafficData) sanitize(rg Range) {
nb, step := trafficGrid(rg)
t.Range = rg.Name
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)) }
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
}