// Package store keeps the bounded in-memory aggregates and their snapshots. package store import ( "net/netip" "sort" "strings" "sync" "time" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" ) const ( slots = 7 * 24 * 60 // minute buckets hourSlots = 7 * 24 topCap = 64 // entries kept per top-list per hour maxSample = 4 maxUAs = 2 maxDomain = 3 maxText = 120 // bytes kept per sample, UA or domain of an IP maxJails = 8 FeedSize = 500 maxBans = 5000 ) // Config of a Store. type Config struct { Name string Version string Retention time.Duration MaxIPs int // AdminUsers, when not empty, limits the admin immunity to successful SSH // logins of these users (wired to --admin-users / URUTAU_ADMIN_USERS). AdminUsers []string // Location is where this instance lives (--location); nil when unset. Location *Location } // AdminWindow is how long a successful SSH login keeps an address immune. const AdminWindow = 24 * time.Hour // IPRec is the per-IP aggregate. type IPRec struct { First, Last int64 Counts [core.NumCats]uint32 Score float64 Domains []string Samples []string UAs []string Jails []string BanSince int64 // Strong: a high confidence signal was seen (attack tool UA, refused exploit, ban). Strong bool // SSHOK: unix time of the last successful SSH login from this address (an admin). SSHOK int64 // StrongAt: unix time of the last strong signal; one after the last SSHOK // cancels the admin immunity. StrongAt int64 // FramedScore: the part of Score that came from framed requests (bounded by framedCap). FramedScore float64 } type hourSlot struct { Hour int64 Paths, Domains, UAs, Users, Countries map[string]uint32 } // FeedEvent is one entry of the live feed. type FeedEvent struct { T int64 `json:"t"` IP string `json:"ip"` Cat string `json:"cat"` Source string `json:"source"` Host string `json:"host"` Domain string `json:"domain,omitempty"` Method string `json:"method,omitempty"` Path string `json:"path,omitempty"` User string `json:"user,omitempty"` Jail string `json:"jail,omitempty"` Status int `json:"status,omitempty"` Unban bool `json:"unban,omitempty"` Forged bool `json:"forged,omitempty"` CC string `json:"cc,omitempty"` } // SetAttribution sets the credit line shown in the dashboard footer (geo data licence). func (s *Store) SetAttribution(a string) { s.attrib = a } // SetEnricher installs the geo and User-Agent resolver used to decorate IPs on output. func (s *Store) SetEnricher(e core.Enricher) { s.enr = e } // RDNS resolves addresses asynchronously; Lookup never blocks. type RDNS interface{ Lookup(ip string) string } // Store is the whole in-memory state of one instance. type Store struct { cfg Config now func() time.Time mu sync.RWMutex stamps [slots]int64 counts [slots][core.NumCats]uint32 hours [hourSlots]hourSlot monSt [slots]int64 monN [slots]uint32 tr trafficState allow []string ips map[string]*IPRec recent []FeedEvent rhead int started time.Time smu sync.Mutex subs map[chan FeedEvent]struct{} rdns RDNS enr core.Enricher attrib string sources func() []SourceStatus cacheMu sync.Mutex cache map[string]cachedSummary } type cachedSummary struct { at time.Time s Summary } // New creates an empty store. func New(cfg Config) *Store { if cfg.Retention <= 0 || cfg.Retention > 7*24*time.Hour { cfg.Retention = 7 * 24 * time.Hour } if cfg.MaxIPs <= 0 { cfg.MaxIPs = 20000 } return &Store{cfg: cfg, now: time.Now, ips: make(map[string]*IPRec), subs: map[chan FeedEvent]struct{}{}, cache: map[string]cachedSummary{}, started: time.Now()} } // Name of this instance. func (s *Store) Name() string { return s.cfg.Name } // SetRDNS installs the reverse DNS resolver. func (s *Store) SetRDNS(r RDNS) { s.rdns = r } // SetSources installs the provider of source status rows. func (s *Store) SetSources(f func() []SourceStatus) { s.sources = f } func bump(m *map[string]uint32, key string) { bumpCap(m, key, topCap) } func bumpCap(m *map[string]uint32, key string, capN int) { if key == "" { return } if *m == nil { *m = make(map[string]uint32, 8) } mm := *m if _, ok := mm[key]; ok || len(mm) < capN { mm[key]++ return } // Full: replace the smallest entry (space-saving style) so new heavy hitters can enter. var minK string var minV uint32 = ^uint32(0) for k, v := range mm { if v < minV { minK, minV = k, v } } delete(mm, minK) mm[key] = minV + 1 } func addUnique(list []string, v string, max int) []string { if v == "" { return list } for _, x := range list { if x == v { return list } } if len(list) >= max { copy(list, list[1:]) list[len(list)-1] = v return list } return append(list, v) } func sample(ev core.Event) string { switch ev.Source { case "traefik": if ev.Forged { return ev.Method + " " + ev.Path + " [forged monitor UA]" } return ev.Method + " " + ev.Path case "ssh": if ev.User != "" { return "ssh user " + ev.User } return "ssh probe" case "fail2ban": return "ban " + ev.Jail } return "" } const softWeight = 0.5 // Framed requests (Sec-Fetch-* says a browser was made to send them by another // page) weigh little and are capped below the hostile level: a visitor framed // by a third party never becomes hostile. They are still recorded, because the // headers come from the client and a scanner can forge them to hide: such a // scanner shows up as suspicious instead of disappearing. const ( framedWeight = 0.25 framedCap = 30.0 ) // KeyOf is the table key of an address: IPv4 as is, IPv6 aggregated by /64 // (one customer holds a whole /64, so per-address keys would be a memory attack). func KeyOf(ip string) string { a, err := netip.ParseAddr(ip) if err != nil { if p, err := netip.ParsePrefix(ip); err == nil && p.Addr().Is6() { return netip.PrefixFrom(p.Addr(), 64).Masked().String() } return ip } a = a.WithZone("").Unmap() if a.Is4() { return a.String() } return netip.PrefixFrom(a, 64).Masked().String() } // Ingest records one event. func (s *Store) Ingest(ev core.Event) { now := s.now() if ev.Time.Before(now.Add(-s.cfg.Retention)) || ev.IP == "" { return } ts := ev.Time.Unix() if max := now.Unix() + 300; ts > max { ts = max } ci := ev.Cat.Index() if ci < 0 { return } scored := !(ev.Cat == core.Ban && (ev.Unban || ev.Restore)) malHTTP := ev.Source == "traefik" && (ev.Cat == core.Scanner || ev.Cat == core.Exploit || ev.Cat == core.BruteForce) s.mu.Lock() if scored { m := ts / 60 i := int(m % slots) if s.stamps[i] != m { s.stamps[i] = m s.counts[i] = [core.NumCats]uint32{} } s.counts[i][ci]++ } if scored { h := ts / 3600 hs := &s.hours[int(h%hourSlots)] if hs.Hour != h { *hs = hourSlot{Hour: h} } switch { case malHTTP: bump(&hs.Paths, ev.Path) bump(&hs.Domains, ev.Domain) bump(&hs.UAs, ev.UA) case ev.Cat == core.SSHFail: bump(&hs.Users, ev.User) } if ev.Cat.IsMalicious() || ev.Cat == core.Ban && !ev.Unban && !ev.Restore { bumpCap(&hs.Countries, ev.E.CC, 300) } } key := KeyOf(ev.IP) r := s.ips[key] // 4xx alone never creates an IP record (legitimate visitors hit 404s too); // only attack tools do. IPs already tracked keep accumulating them. create := ev.Cat != core.OK && !ev.Unban && (ev.Cat != core.NotFound || ev.E.Tool) // An attack tool User-Agent never comes from a framed browser: the framing // headers are then ignored. framed := ev.Framed && !ev.E.Tool if r == nil && create { if len(s.ips) >= s.cfg.MaxIPs { s.evictLocked() } r = &IPRec{First: ts, Last: ts} s.ips[key] = r } if r != nil { if ts < r.First { r.First = ts } if ts > r.Last { r.Last = ts } if scored { r.Counts[ci]++ w := ev.Cat.Weight() if ev.Soft && (ev.Cat == core.Scanner || ev.Cat == core.Exploit) { w = softWeight // answered 2xx/3xx: probably nothing was found } if framed && w > 0 { w = min(framedWeight, framedCap-r.FramedScore) if w < 0 { w = 0 } r.FramedScore += w } r.Score += w if framed { // never a strong signal: the headers prove nothing either way } else if ev.E.Tool && ev.Cat != core.OK && ev.Cat != core.SSHOK && ev.Cat != core.Ban { r.Score += core.ToolBonus r.Strong = true r.StrongAt = max(r.StrongAt, ts) } if (ev.Strong && !framed) || ev.Cat == core.Ban { r.Strong = true r.StrongAt = max(r.StrongAt, ts) } if ev.Cat == core.SSHOK && ts > r.SSHOK && s.isAdminUser(ev.User) { r.SSHOK = ts } } if malHTTP { r.Domains = addUnique(r.Domains, clipS(ev.Domain, maxText), maxDomain) r.UAs = addUnique(r.UAs, clipS(ev.UA, maxText), maxUAs) } if ev.Cat != core.OK && ev.Cat != core.NotFound && scored { r.Samples = addUnique(r.Samples, clipS(sample(ev), maxText), maxSample) } if ev.Cat == core.Ban && ev.Jail != "" { if ev.Unban { for i, j := range r.Jails { if j == ev.Jail { r.Jails = append(r.Jails[:i], r.Jails[i+1:]...) break } } } else if len(r.Jails) < maxJails { r.Jails = addUnique(r.Jails, ev.Jail, maxJails) if r.BanSince == 0 || ts > r.BanSince { r.BanSince = ts } } } } var fe FeedEvent feed := ev.Cat != core.OK && ev.Cat != core.NotFound && !ev.Restore if feed { fe = FeedEvent{T: ts, IP: ev.IP, Cat: string(ev.Cat), Source: ev.Source, Host: s.cfg.Name, Domain: ev.Domain, Method: ev.Method, Path: ev.Path, User: ev.User, Jail: ev.Jail, Status: ev.Status, Unban: ev.Unban, Forged: ev.Forged, CC: ev.E.CC} if len(s.recent) < FeedSize { s.recent = append(s.recent, fe) } else { s.recent[s.rhead] = fe s.rhead = (s.rhead + 1) % FeedSize } } s.mu.Unlock() if feed && now.Unix()-ts < 300 { s.broadcast(fe) } } // isAdminUser: without an explicit --admin-users list nobody is immune (a // local user can forge an sshd "Accepted" line with logger). func (s *Store) isAdminUser(u string) bool { if len(s.cfg.AdminUsers) == 0 { return false } for _, a := range s.cfg.AdminUsers { if a == u { return true } } return false } // SetAdminUsers sets Config.AdminUsers (empty: no address is immune). func (s *Store) SetAdminUsers(users []string) { var l []string for _, u := range users { if u = strings.TrimSpace(u); u != "" { l = append(l, u) } } s.mu.Lock() s.cfg.AdminUsers = l s.mu.Unlock() s.invalidate() } // adminAt reports whether r is an admin at time now: a successful SSH login // in the last AdminWindow and no strong signal after it. func (r *IPRec) adminAt(now int64) bool { return r.SSHOK > 0 && r.SSHOK >= now-int64(AdminWindow/time.Second) && r.StrongAt < r.SSHOK } func (r *IPRec) protected() bool { return len(r.Jails) > 0 || r.SSHOK > 0 } // evictLocked makes room: the lowest score (then oldest) go first. Banned IPs // and admin logins are only evicted, oldest first, when nothing else is left, // so the cap is hard. func (s *Store) evictLocked() { type kv struct { ip string prot bool score float64 last int64 } all := make([]kv, 0, len(s.ips)) for ip, r := range s.ips { last := r.Last if r.protected() && r.BanSince > last { last = r.BanSince } all = append(all, kv{ip, r.protected(), r.Score, last}) } sort.Slice(all, func(i, j int) bool { if all[i].prot != all[j].prot { return !all[i].prot } if all[i].prot { return all[i].last < all[j].last } if all[i].score != all[j].score { return all[i].score < all[j].score } return all[i].last < all[j].last }) n := len(s.ips) / 10 if n < 1 { n = 1 } if n > len(all) { n = len(all) } for _, e := range all[:n] { delete(s.ips, e.ip) } } // Prune drops IPs not seen within the retention window (bans excepted while // they are younger than it). func (s *Store) Prune() int { cut := s.now().Add(-s.cfg.Retention).Unix() s.mu.Lock() defer s.mu.Unlock() n := 0 for name, d := range s.tr.dom { if d.Last < cut { delete(s.tr.dom, name) // no activity for the whole retention window } } for ip, r := range s.ips { if r.Last >= cut { continue } if len(r.Jails) > 0 && r.BanSince >= cut { continue } if r.SSHOK >= cut { continue } delete(s.ips, ip) n++ } return n } // IPCount is the size of the IP table. func (s *Store) IPCount() int { s.mu.RLock(); defer s.mu.RUnlock(); return len(s.ips) } // Subscribe returns a channel of live feed events; call the returned func to stop. func (s *Store) Subscribe() (<-chan FeedEvent, func()) { ch := make(chan FeedEvent, 64) s.smu.Lock() s.subs[ch] = struct{}{} s.smu.Unlock() return ch, func() { s.smu.Lock() delete(s.subs, ch) s.smu.Unlock() } } func (s *Store) broadcast(e FeedEvent) { s.smu.Lock() for ch := range s.subs { select { case ch <- e: default: // slow client: drop } } s.smu.Unlock() } // Recent returns the newest n feed events, newest first. func (s *Store) Recent(n int) []FeedEvent { s.mu.RLock() defer s.mu.RUnlock() total := len(s.recent) out := make([]FeedEvent, 0, n) for i := 0; i < total && len(out) < n; i++ { idx := (s.rhead - 1 - i) % total if idx < 0 { idx += total } out = append(out, s.recent[idx]) } return out } func (s *Store) invalidate() { s.cacheMu.Lock() s.cache = map[string]cachedSummary{} s.cacheMu.Unlock() } func containsFold(h, n string) bool { return strings.Contains(strings.ToLower(h), strings.ToLower(n)) } // RDNSOf returns the cached reverse name of ip and queues a lookup. func (s *Store) RDNSOf(ip string) string { if s.rdns == nil { return "" } return s.rdns.Lookup(ip) } // Monitoring counts a benign request from a monitoring client. It is kept // apart from every attack aggregate and never scores an IP. func (s *Store) Monitoring(t time.Time) { now := s.now() if t.Before(now.Add(-s.cfg.Retention)) { return } ts := t.Unix() if max := now.Unix() + 300; ts > max { ts = max } m := ts / 60 i := int(m % slots) s.mu.Lock() if s.monSt[i] != m { s.monSt[i], s.monN[i] = m, 0 } s.monN[i]++ s.mu.Unlock() }