package store import ( "sort" "strings" "time" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog" ) // BanPoint is bans of one jail in one bucket of the series. type BanPoint struct { T int64 `json:"t"` Jail string `json:"jail"` N int `json:"n"` } // JailRow counts the bans of one jail. type JailRow struct { Jail string `json:"jail"` Active int `json:"active"` Total int `json:"total"` } // TTBStat is the time from the first malicious event to the first ban. type TTBStat struct { MedianS float64 `json:"median_s"` P90S float64 `json:"p90_s"` N int `json:"n"` } // SSHUser is one SSH user name tried by attackers. type SSHUser struct { User string `json:"user"` N int `json:"n"` Admin bool `json:"admin"` } // SSHDefense summarises the SSH failures of the window. type SSHDefense struct { Fails int `json:"fails"` Users []SSHUser `json:"users"` Sources int `json:"sources"` OKAfterFail int `json:"ok_after_fail"` } // BlocklistStat describes the blocklist the instance would publish. type BlocklistStat struct { Size int `json:"size"` V4 int `json:"v4"` V6 int `json:"v6"` Updated int64 `json:"updated"` CoveragePct float64 `json:"coverage_pct"` // attackers of the window that are listed } // LeakStat counts attackers that kept arriving after a ban or listing. type LeakStat struct { IPs int `json:"ips"` Events int `json:"events"` } // DefenseOut is GET /api/v1/defense. type DefenseOut struct { Enabled bool `json:"enabled"` Truncated bool `json:"truncated,omitempty"` Step int64 `json:"step"` From int64 `json:"from"` BansActive int `json:"bans_active"` BansTotal int `json:"bans_total"` Bans []BanPoint `json:"bans"` ByJail []JailRow `json:"by_jail"` TTB TTBStat `json:"ttb"` SSH SSHDefense `json:"ssh"` Blocklist BlocklistStat `json:"blocklist"` Leak LeakStat `json:"leak"` } const maxDefenseUsers = 50 // defenseStep picks the bucket of the bans series for a window. func defenseStep(span int64) int64 { st := span / 60 if st < 300 { st = 300 } return (st + 299) / 300 * 300 } type ipDef struct { firstMal, firstBan, firstFail int64 okAfter bool mal, bans []int64 } // Defense answers "is fail2ban acting?" for [q.From, q.To]: bans per jail, // time to ban, SSH pressure, blocklist coverage and leak. Same caps, deadline // and 30 s cache as Period. func (s *Store) Defense(q PeriodQuery) DefenseOut { k := studyKey{kind: "defense", from: q.From, to: q.To, host: q.Host} return s.cached(k, func() any { return s.defense(q) }).(DefenseOut) } func (s *Store) defense(q PeriodQuery) DefenseOut { step := defenseStep(q.To - q.From) out := DefenseOut{Step: step, From: q.From / step * step, Bans: []BanPoint{}, ByJail: []JailRow{}, SSH: SSHDefense{Users: []SSHUser{}}} if s.elog == nil { return out } out.Enabled = true deadline := time.Now().Add(studyDead) ips := map[string]*ipDef{} get := func(ip string) *ipDef { d := ips[ip] if d == nil { d = &ipDef{} ips[ip] = d } return d } series := map[[2]any]int{} jailTotal := map[string]int{} users := map[string]int{} sshSrc := map[string]struct{}{} n, malN := 0, 0 info := s.elog.Scan(evlog.Filter{From: q.From, To: q.To, Host: q.Host}, studyBudget, false, func(r evlog.Rec, _ []byte) bool { if n++; n > maxStudyEvents || n%4096 == 0 && time.Now().After(deadline) { out.Truncated = true return false } c := core.Category(r.Cat) key := KeyOf(r.IP) switch { case c == core.Ban: if r.Unban { return true } jail := r.Jail if jail == "" { jail = "?" } out.BansTotal++ jailTotal[jail]++ series[[2]any{(r.T / step) * step, jail}]++ d := get(key) d.bans = append(d.bans, r.T) if d.firstBan == 0 || r.T < d.firstBan { d.firstBan = r.T } case c == core.SSHFail: out.SSH.Fails++ if r.User != "" { if len(users) < 5000 || users[r.User] > 0 { users[r.User]++ } } sshSrc[key] = struct{}{} if d := get(key); d.firstFail == 0 || r.T < d.firstFail { d.firstFail = r.T } fallthrough case c.IsMalicious(): d := get(key) if d.firstMal == 0 || r.T < d.firstMal { d.firstMal = r.T } if malN < maxStudyEvents { d.mal = append(d.mal, r.T) malN++ } case c == core.SSHOK: if d := ips[key]; d != nil && d.firstFail > 0 && r.T >= d.firstFail { d.okAfter = true } } return true }) out.Truncated = out.Truncated || info.Truncated out.SSH.Sources = len(sshSrc) // live state of the registry: active bans, jails, blocklist active := map[string]int{} listed := map[string]int64{} s.mu.RLock() for ip, r := range s.ips { if len(r.Jails) > 0 { out.BansActive++ for _, j := range r.Jails { active[j]++ } } if r.ListedSince > 0 { out.Blocklist.Size++ if strings.Contains(ip, ":") { out.Blocklist.V6++ } else { out.Blocklist.V4++ } if r.ListedSince > out.Blocklist.Updated { out.Blocklist.Updated = r.ListedSince } if ips[ip] != nil { listed[ip] = r.ListedSince } } if d := ips[ip]; d != nil && d.firstBan > 0 && r.TTB > 0 && d.firstMal == 0 { d.firstMal = d.firstBan - r.TTB } } adminOf := map[string]bool{} for u := range users { adminOf[u] = s.isAdminUser(u) } s.mu.RUnlock() for j, t := range jailTotal { out.ByJail = append(out.ByJail, JailRow{Jail: j, Active: active[j], Total: t}) } for j, a := range active { if _, ok := jailTotal[j]; !ok { out.ByJail = append(out.ByJail, JailRow{Jail: j, Active: a}) } } sort.Slice(out.ByJail, func(i, j int) bool { a, b := out.ByJail[i], out.ByJail[j] if a.Total != b.Total { return a.Total > b.Total } return a.Jail < b.Jail }) for k, v := range series { out.Bans = append(out.Bans, BanPoint{T: k[0].(int64), Jail: k[1].(string), N: v}) } sort.Slice(out.Bans, func(i, j int) bool { if out.Bans[i].T != out.Bans[j].T { return out.Bans[i].T < out.Bans[j].T } return out.Bans[i].Jail < out.Bans[j].Jail }) var ttb []float64 attackers, covered := 0, 0 for ip, d := range ips { if d.firstMal == 0 { continue } attackers++ if _, ok := listed[ip]; ok { covered++ } ttb = append(ttb, episodeTTB(d.mal, d.bans)...) cut := d.firstBan if l := listed[ip]; l > 0 && (cut == 0 || l < cut) { cut = l } if cut == 0 { continue } leak := 0 for _, t := range d.mal { if t > cut { leak++ } } if leak > 0 { out.Leak.IPs++ out.Leak.Events += leak } } out.TTB.N = len(ttb) if len(ttb) > 0 { sort.Float64s(ttb) out.TTB.MedianS = ttb[len(ttb)/2] out.TTB.P90S = ttb[min(len(ttb)-1, len(ttb)*9/10)] } if attackers > 0 { out.Blocklist.CoveragePct = float64(covered) / float64(attackers) * 100 } for u, c := range users { out.SSH.Users = append(out.SSH.Users, SSHUser{User: u, N: c, Admin: adminOf[u]}) } sort.Slice(out.SSH.Users, func(i, j int) bool { a, b := out.SSH.Users[i], out.SSH.Users[j] if a.N != b.N { return a.N > b.N } return a.User < b.User }) if len(out.SSH.Users) > maxDefenseUsers { out.SSH.Users = out.SSH.Users[:maxDefenseUsers] } for _, d := range ips { if d.okAfter { out.SSH.OKAfterFail++ } } return out } // episodeGap is the silence that ends a burst of malicious events. const episodeGap = 30 * 60 // episodeTTB measures, for every ban, the time from the start of the attack // episode that led to it: the first malicious event after the previous ban of // the address, extended back through a continuous run (gaps of at most 30 // minutes) that ends at the ban. Bans with no earlier event are ignored. func episodeTTB(mal, bans []int64) []float64 { sort.Slice(mal, func(i, j int) bool { return mal[i] < mal[j] }) sort.Slice(bans, func(i, j int) bool { return bans[i] < bans[j] }) var out []float64 prev := int64(-1) for _, b := range bans { hi := sort.Search(len(mal), func(i int) bool { return mal[i] > b }) - 1 // last event at or before the ban start := int64(-1) for i := hi; i >= 0 && mal[i] > prev; i-- { if start >= 0 && start-mal[i] > episodeGap { break } start = mal[i] } if start >= 0 { out = append(out, float64(b-start)) } prev = b } return out }