// Package store keeps the bounded in-memory aggregates and their snapshots. package store import ( "net/netip" "sort" "strings" "sync" "sync/atomic" "time" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel" ) const ( slots = 49 * 60 // minute buckets (48 h plus one hour of margin) hourSlots = 30 * 24 // hour buckets, 30 days 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 // Per-IP detail, all small and capped (about 1 KB per IP at the caps). The // rest of the detail view is derived from the event log on demand. ScoreBy [core.NumCats]float32 // score contribution per category StrongWhy uint8 // whyTool | whySignal | whyBan FirstMal int64 // first malicious event TTB int64 // seconds from the first malicious event to the first ban Users []UserN // SSH users tried (<= maxUsers) Status [6]uint32 // answer classes: none, 2xx, 3xx, 4xx, 5xx, other Fams []FamN // attack families (<= maxFams) Techs []TechN // techniques (<= maxTechs) Expo []Expo // successful answers to attack requests (<= maxExpo) CadAcc []float64 // reserved for the cadence accumulator (<= 16 values) DayBase int64 // epoch day of bit 0 of Days Days uint32 // active days: bit k = active on DayBase-k DayEst bool // DayCats was estimated from the totals (record saved before the counters existed) DayCats [][core.NumCats]uint16 // events per day and category, DayCats[k] = DayBase-k (<= 30 days) ListedSince int64 // when the address started to satisfy the blocklist rule (0: not listed) } // Reasons an address is strong (IPRec.StrongWhy). const ( whyTool = 1 whySignal = 2 whyBan = 4 ) const ( maxUsers = 32 maxFams = 16 maxTechs = 16 maxExpo = 8 maxExamp = 3 ) // UserN is one SSH user tried by an address. type UserN struct { U string N uint32 First int64 } // FamN counts one attack family of an address. type FamN struct { Fam string N uint32 S [4]uint32 // 2xx 3xx 4xx 5xx Ex []string } // TechN counts one technique of an address. type TechN struct { ID string N uint32 First, Last int64 } // Expo is a successful answer to an attack request. type Expo struct { T int64 Host string Domain string Path string Status int Bytes int64 Fam string } type hourSlot struct { Hour int64 Paths, Domains, UAs, Users, Countries map[string]uint32 C [core.NumCats]uint32 // events per category in the hour Mon uint32 // monitoring requests in the hour } // 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"` UA string `json:"ua,omitempty"` ID uint64 `json:"id,omitempty"` // Detail for the replay and the investigation views. Fam string `json:"fam,omitempty"` Tech []string `json:"tech,omitempty"` Marker string `json:"marker,omitempty"` Bytes int64 `json:"bytes,omitempty"` DurMS int64 `json:"dur_ms,omitempty"` Flags string `json:"flags,omitempty"` // S strong, W weak, G forged, F framed, X soft } // 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 } // FCrDNSVerifier is implemented by resolvers that can confirm a crawler. type FCrDNSVerifier interface { FCrDNS(ip string, suffixes []string) bool } var crawlerSuffixes = []struct { ua string suffixes []string }{ {"googlebot", []string{"googlebot.com", "google.com"}}, {"bingbot", []string{"search.msn.com"}}, } // FCrDNS verifies an address that claims, through one of its User-Agents, to // be Googlebot or Bingbot. It returns nil when no UA makes the claim (or the // address cannot be checked), true or false otherwise. func (s *Store) FCrDNS(ip string, uas []string) *bool { v, ok := s.rdns.(FCrDNSVerifier) if !ok || s.rdns == nil { return nil } if a, err := netip.ParseAddr(ip); err != nil || a.Zone() != "" { return nil // an IPv6 /64 key is not an address } var want []string for _, ua := range uas { l := strings.ToLower(ua) for _, c := range crawlerSuffixes { if strings.Contains(l, c.ua) { want = append(want, c.suffixes...) } } } if len(want) == 0 { return nil } res := v.FCrDNS(ip, want) return &res } // IsAdminUser reports whether u is listed in --admin-users. func (s *Store) IsAdminUser(u string) bool { s.mu.RLock() defer s.mu.RUnlock() return s.isAdminUser(u) } // 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 sv svcState allow []string ips map[string]*IPRec recent []FeedEvent rhead int started time.Time smu sync.Mutex subs map[chan FeedEvent]struct{} vis visitState rdns RDNS enr core.Enricher attrib string sources func() []SourceStatus cacheMu sync.Mutex cache map[string]cachedSummary ids atomic.Uint64 // event ids, increasing elog *evlog.Log class Classifier ipx ipxCache study studyCache sizes map[string]map[int64]uint32 // per domain: typical 404 / SPA body sizes } // Classifier fills the attack family, the techniques and the marker of an // event (wired to internal/intel); nil or empty results are fine. type Classifier func(core.Event) (fam string, tech []string, marker string) // SetClassifier installs the classifier. func (s *Store) SetClassifier(c Classifier) { s.class = c } 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 // zero value; the daemon always passes --retention } if cfg.Retention > DefaultRetention { cfg.Retention = DefaultRetention } 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(), class: IntelClassifier} } // 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) var fam, marker string var tech []string if s.class != nil && (ev.Cat.IsMalicious() || ev.Cat == core.NotFound || ev.Cat == core.OK) { fam, tech, marker = s.class(ev) } 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} } hs.C[ci]++ 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 } suspicious := false // the address was already suspicious or hostile before this event if r != nil { suspicious = core.LevelOf(r.Score, r.Strong || attackKinds(r.Counts) >= 2, r.adminAt(now.Unix())) != core.LevelLow 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 r.ScoreBy[ci] += float32(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.ScoreBy[ci] += core.ToolBonus r.Strong = true r.StrongWhy |= whyTool r.StrongAt = max(r.StrongAt, ts) } if (ev.Strong && !framed) || ev.Cat == core.Ban { r.Strong = true if ev.Cat == core.Ban { r.StrongWhy |= whyBan } else { r.StrongWhy |= whySignal } r.StrongAt = max(r.StrongAt, ts) } if ev.Cat == core.SSHOK && ts > r.SSHOK && s.isAdminUser(ev.User) { r.SSHOK = ts } s.detailLocked(r, ev, ts, fam, tech, suspicious) updateListed(r, ts, now.Unix()) } 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 // The event log also keeps a 404 of an attack tool and any answer to an // address that is already suspicious or hostile (to show what it got); // never an address that looks like a visitor. record := feed || (!ev.Restore && (ev.Cat == core.NotFound && ev.E.Tool || suspicious && (ev.Cat == core.OK || ev.Cat == core.NotFound))) if record { fe = s.feedOf(ev, ts, fam, tech, marker) if feed { if len(s.recent) < FeedSize { s.recent = append(s.recent, fe) } else { s.recent[s.rhead] = fe s.rhead = (s.rhead + 1) % FeedSize } } } s.noteSizeLocked(ev, fam) // after the decision: an answer never defines its own "typical" size s.mu.Unlock() if record { s.logEvent(fe) } if feed && now.Unix()-ts < 300 { s.broadcast(fe) } } func (s *Store) feedOf(ev core.Event, ts int64, fam string, tech []string, marker string) FeedEvent { flags := "" for _, f := range []struct { on bool c string }{{ev.Strong, "S"}, {ev.Weak, "W"}, {ev.Forged, "G"}, {ev.Framed, "F"}, {ev.Soft, "X"}} { if f.on { flags += f.c } } return 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, UA: clipS(ev.UA, 200), ID: s.ids.Add(1), Fam: clipS(fam, 40), Tech: tech, Marker: clipS(marker, 80), Bytes: ev.Bytes, DurMS: ev.DurationNS / 1e6, Flags: flags} } // listedRule is the blocklist rule: score of 50, a strong signal and not an admin. func listedRule(r *IPRec, now int64) bool { return r.Score >= core.HostileScore && (r.Strong || attackKinds(r.Counts) >= 2) && !r.adminAt(now) } func updateListed(r *IPRec, ts, now int64) { switch ok := listedRule(r, now); { case ok && r.ListedSince == 0: r.ListedSince = ts case !ok && r.ListedSince != 0: r.ListedSince = 0 } } func statusClass(st int) int { switch { case st == 0: return 0 case st >= 200 && st < 300: return 1 case st >= 300 && st < 400: return 2 case st >= 400 && st < 500: return 3 case st >= 500 && st < 600: return 4 } return 5 } // detailLocked updates the capped per-IP detail of an address. func (s *Store) detailLocked(r *IPRec, ev core.Event, ts int64, fam string, tech []string, wasSusp bool) { if ev.Cat.IsMalicious() && (r.FirstMal == 0 || ts < r.FirstMal) { r.FirstMal = ts } if ev.Cat == core.Ban && !ev.Unban && r.FirstMal > 0 && r.TTB == 0 && ts >= r.FirstMal { r.TTB = ts - r.FirstMal } touchDay(r, ts, ev.Cat.Index()) if ev.Source == "traefik" { r.Status[statusClass(ev.Status)]++ } if ev.Cat == core.SSHFail && ev.User != "" { u := clipS(ev.User, 64) found := false for i := range r.Users { if r.Users[i].U == u { r.Users[i].N++ found = true break } } if !found && len(r.Users) < maxUsers { r.Users = append(r.Users, UserN{U: u, N: 1, First: ts}) } } if fam != "" && ev.Source == "traefik" { var f *FamN for i := range r.Fams { if r.Fams[i].Fam == fam { f = &r.Fams[i] break } } if f == nil && len(r.Fams) < maxFams { r.Fams = append(r.Fams, FamN{Fam: fam}) f = &r.Fams[len(r.Fams)-1] } if f != nil { f.N++ if c := statusClass(ev.Status); c >= 1 && c <= 4 { f.S[c-1]++ } if len(f.Ex) < maxExamp { f.Ex = addUnique(f.Ex, clipS(ev.Method+" "+ev.Path, maxText), maxExamp) } } } for _, id := range tech { var t *TechN for i := range r.Techs { if r.Techs[i].ID == id { t = &r.Techs[i] break } } if t == nil && len(r.Techs) < maxTechs { r.Techs = append(r.Techs, TechN{ID: id, First: ts}) t = &r.Techs[len(r.Techs)-1] } if t != nil { t.N++ if ts < t.First { t.First = ts } t.Last = max(t.Last, ts) } } // exposure: a successful answer (2xx, with a body that is not the typical // 404 or SPA page of the domain) to a request for a sensitive family if ev.Source == "traefik" && s.exposedLocked(ev, wasSusp) && len(r.Expo) < maxExpo { r.Expo = append(r.Expo, Expo{T: ts, Host: s.cfg.Name, Domain: clipS(ev.Domain, 100), Path: clipS(ev.Path, 160), Status: ev.Status, Bytes: ev.Bytes, Fam: intel.PathFamily(ev.Path)}) } } // sensitiveFams are the families whose 2xx answer is an exposure. The public // WordPress login page and robots.txt are not. var sensitiveFams = map[string]bool{ intel.FamEnvCreds: true, intel.FamVCS: true, intel.FamBackup: true, intel.FamActuator: true, intel.FamPhpMyAdmin: true, intel.FamAdminPanel: true, } // exposedLocked applies the exposure rule. Admin panels and phpMyAdmin pages // are public by design on some sites, so they also need a strong sign. func (s *Store) exposedLocked(ev core.Event, wasSusp bool) bool { if ev.Status < 200 || ev.Status > 299 || ev.Bytes <= 0 { return false } fam := intel.PathFamily(ev.Path) if !sensitiveFams[fam] { return false } if (fam == intel.FamAdminPanel || fam == intel.FamPhpMyAdmin) && !(ev.Strong || ev.E.Tool || wasSusp) { return false } if t := s.sizes[normDomain(ev.Domain)]; t != nil && t[ev.Bytes] >= 2 { return false // the same body the domain serves for a missing page or for its SPA } return true } // noteSizeLocked remembers the body sizes of 404 answers and of ordinary 2xx // pages per domain (at most 32 domains and 8 sizes each): the typical size of // a "not found" page or of a SPA shell. func (s *Store) noteSizeLocked(ev core.Event, fam string) { if ev.Source != "traefik" || ev.Bytes <= 0 || ev.Domain == "" { return } if ev.Status != 404 && !(ev.Status >= 200 && ev.Status < 300 && fam == "" && intel.PathFamily(ev.Path) == "") { return } d := normDomain(ev.Domain) if s.sizes == nil { s.sizes = map[string]map[int64]uint32{} } m := s.sizes[d] if m == nil { if len(s.sizes) >= 32 { return } m = map[int64]uint32{} s.sizes[d] = m } if _, ok := m[ev.Bytes]; !ok && len(m) >= 8 { var minK int64 var minV uint32 = ^uint32(0) for k, v := range m { if v < minV { minK, minV = k, v } } delete(m, minK) } m[ev.Bytes]++ } // touchDay counts an event on its day: the 30 day bitmap of active days and // the per-day per-category counters (the coarse timeline of an address, kept // for the part of its history the event registry does not cover). func touchDay(r *IPRec, ts int64, ci int) { day := ts / 86400 switch { case r.DayBase == 0: r.DayBase = day case day > r.DayBase: d := int(day - r.DayBase) if d >= 32 { r.Days, r.DayCats = 0, nil } else { r.Days = r.Days << uint(d) & (1<<30 - 1) if len(r.DayCats) > 0 { n := min(len(r.DayCats)+d, 30) nc := make([][core.NumCats]uint16, n) for k := range r.DayCats { if k+d < n { nc[k+d] = r.DayCats[k] } } r.DayCats = nc } } r.DayBase = day } k := int(r.DayBase - day) if k < 0 || k >= 30 { return } r.Days |= 1 << uint(k) for len(r.DayCats) <= k { r.DayCats = append(r.DayCats, [core.NumCats]uint16{}) } if c := &r.DayCats[k][ci]; *c < 65535 { *c++ } } func malHTTPCat(c core.Category) bool { return c == core.Scanner || c == core.Exploit || c == core.BruteForce } // 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) h := ts / 3600 s.mu.Lock() if s.monSt[i] != m { s.monSt[i], s.monN[i] = m, 0 } s.monN[i]++ hs := &s.hours[int(h%hourSlots)] if hs.Hour != h { *hs = hourSlot{Hour: h} } hs.Mon++ s.mu.Unlock() }