Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
629 lines
16 KiB
Go
629 lines
16 KiB
Go
package store
|
|
|
|
import (
|
|
"math"
|
|
"sort"
|
|
"strconv"
|
|
"time"
|
|
|
|
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
|
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
|
|
)
|
|
|
|
// Temporal analytics (evolution, concentration, survival), all derived from
|
|
// the event registry in one bounded scan (study budget and deadline, 30 s cache).
|
|
|
|
const (
|
|
anMaxKeys = 200000 // distinct keys held by a concentration scan
|
|
anMaxItems = 200
|
|
anMaxIPs = 300000 // distinct addresses held by a survival scan
|
|
anKMPoints = 200
|
|
anMaxRecid = 50
|
|
anMaxFamilies = 12
|
|
anMaxDays = 62
|
|
)
|
|
|
|
// AnDay is one UTC day of the evolution chart.
|
|
type AnDay struct {
|
|
D string `json:"d"`
|
|
Total uint32 `json:"total"`
|
|
ByCat map[string]uint32 `json:"by_cat"`
|
|
ByFam map[string]uint32 `json:"by_fam"`
|
|
}
|
|
|
|
// AnFam is a family with its event count.
|
|
type AnFam struct {
|
|
Fam string `json:"fam"`
|
|
N uint32 `json:"n"`
|
|
}
|
|
|
|
// EvolutionOut answers "are we getting better or worse".
|
|
type EvolutionOut struct {
|
|
Enabled bool `json:"enabled"`
|
|
Truncated bool `json:"truncated"`
|
|
Days []AnDay `json:"days"`
|
|
HourDow [7][24]uint32 `json:"hour_dow"`
|
|
NewFamilies []AnFam `json:"new_families"`
|
|
GoneFamilies []AnFam `json:"gone_families"`
|
|
Total uint64 `json:"total"`
|
|
Prev uint64 `json:"prev"`
|
|
DeltaPct *float64 `json:"delta_pct"`
|
|
}
|
|
|
|
// AnItem is one row of a concentration curve.
|
|
type AnItem struct {
|
|
Key string `json:"key"`
|
|
Label string `json:"label,omitempty"`
|
|
N uint32 `json:"n"`
|
|
CumPct float64 `json:"cum_pct"`
|
|
}
|
|
|
|
// ConcentrationOut answers "do a few generate most of it".
|
|
type ConcentrationOut struct {
|
|
Enabled bool `json:"enabled"`
|
|
Truncated bool `json:"truncated"`
|
|
Dim string `json:"dim"`
|
|
Total uint64 `json:"total"`
|
|
Distinct int `json:"distinct"`
|
|
Gini float64 `json:"gini"`
|
|
Top10Pct float64 `json:"top10_pct"`
|
|
Items []AnItem `json:"items"`
|
|
}
|
|
|
|
// KMPoint is one step of a Kaplan-Meier curve.
|
|
type KMPoint struct {
|
|
T int64 `json:"t_s"`
|
|
Survival float64 `json:"survival"`
|
|
}
|
|
|
|
// FamTTB is the time-to-ban quartiles of one family.
|
|
type FamTTB struct {
|
|
Fam string `json:"fam"`
|
|
P25 int64 `json:"p25"`
|
|
P50 int64 `json:"p50"`
|
|
P75 int64 `json:"p75"`
|
|
N int `json:"n"`
|
|
}
|
|
|
|
// Recidivist is an address banned more than once.
|
|
type Recidivist struct {
|
|
IP string `json:"ip"`
|
|
Bans int `json:"bans"`
|
|
Last int64 `json:"last"`
|
|
}
|
|
|
|
// SurvivalOut answers "how long until the ban, and who comes back".
|
|
type SurvivalOut struct {
|
|
Enabled bool `json:"enabled"`
|
|
Truncated bool `json:"truncated"`
|
|
Attackers int `json:"attackers"`
|
|
Banned int `json:"banned"`
|
|
Episodes int `json:"episodes"`
|
|
MedianToBanS *int64 `json:"median_to_ban_s"`
|
|
P90ToBanS *int64 `json:"p90_to_ban_s"`
|
|
KM []KMPoint `json:"km"`
|
|
ByFamily []FamTTB `json:"by_family"`
|
|
ByBlocker []BlockerTTB `json:"by_blocker"`
|
|
Recidivists []Recidivist `json:"recidivists"`
|
|
RecidivismPct float64 `json:"recidivism_pct"`
|
|
}
|
|
|
|
// ---- pure math ----
|
|
|
|
// anGini is the Gini coefficient (0 equal .. 1 concentrated) of non-negative counts.
|
|
func anGini(v []float64) float64 {
|
|
n := len(v)
|
|
if n == 0 {
|
|
return 0
|
|
}
|
|
x := append([]float64(nil), v...)
|
|
sort.Float64s(x)
|
|
var sum, w float64
|
|
for i, f := range x {
|
|
sum += f
|
|
w += float64(i+1) * f
|
|
}
|
|
if sum == 0 {
|
|
return 0
|
|
}
|
|
g := 2*w/(float64(n)*sum) - float64(n+1)/float64(n)
|
|
if g < 0 {
|
|
g = 0
|
|
}
|
|
return math.Round(g*1000) / 1000
|
|
}
|
|
|
|
// anPareto turns descending-sorted counts into rows with the cumulative percentage.
|
|
func anPareto(sorted []AnItem, total uint64) []AnItem {
|
|
var cum uint64
|
|
for i := range sorted {
|
|
cum += uint64(sorted[i].N)
|
|
if total > 0 {
|
|
sorted[i].CumPct = math.Round(float64(cum)/float64(total)*1000) / 10
|
|
}
|
|
}
|
|
return sorted
|
|
}
|
|
|
|
// anSubject is one observed address for Kaplan-Meier: time to the event, and
|
|
// whether the event (a ban) happened (false: censored at T).
|
|
type anSubject struct {
|
|
T int64
|
|
Event bool
|
|
Ban int64 // time of the ban that ended the episode (Event only)
|
|
}
|
|
|
|
// anKaplanMeier returns the survival curve (starting at t=0, S=1) with one
|
|
// point per distinct event time, plus the first times S drops to <= 0.5 and <= 0.1.
|
|
func anKaplanMeier(subs []anSubject) (curve []KMPoint, median, p90 *int64) {
|
|
curve = []KMPoint{{0, 1}}
|
|
if len(subs) == 0 {
|
|
return
|
|
}
|
|
s := append([]anSubject(nil), subs...)
|
|
sort.Slice(s, func(i, j int) bool {
|
|
if s[i].T != s[j].T {
|
|
return s[i].T < s[j].T
|
|
}
|
|
return s[i].Event && !s[j].Event // events before censors at a tie
|
|
})
|
|
atRisk := len(s)
|
|
surv := 1.0
|
|
for i := 0; i < len(s); {
|
|
t := s[i].T
|
|
d, c := 0, 0
|
|
for i < len(s) && s[i].T == t {
|
|
if s[i].Event {
|
|
d++
|
|
} else {
|
|
c++
|
|
}
|
|
i++
|
|
}
|
|
if d > 0 && atRisk > 0 {
|
|
surv *= 1 - float64(d)/float64(atRisk)
|
|
curve = append(curve, KMPoint{t, math.Round(surv*10000) / 10000})
|
|
if median == nil && surv <= 0.5 {
|
|
v := t
|
|
median = &v
|
|
}
|
|
if p90 == nil && surv <= 0.1 {
|
|
v := t
|
|
p90 = &v
|
|
}
|
|
}
|
|
atRisk -= d + c
|
|
}
|
|
if len(curve) > anKMPoints {
|
|
step := float64(len(curve)-1) / float64(anKMPoints-1)
|
|
out := make([]KMPoint, 0, anKMPoints)
|
|
for k := 0; k < anKMPoints; k++ {
|
|
out = append(out, curve[int(math.Round(float64(k)*step))])
|
|
}
|
|
curve = out
|
|
}
|
|
return
|
|
}
|
|
|
|
// anQuant is the q-quantile of ascending values (nearest rank).
|
|
func anQuant(v []int64, q float64) int64 {
|
|
if len(v) == 0 {
|
|
return 0
|
|
}
|
|
i := int(math.Ceil(q*float64(len(v)))) - 1
|
|
if i < 0 {
|
|
i = 0
|
|
}
|
|
if i >= len(v) {
|
|
i = len(v) - 1
|
|
}
|
|
return v[i]
|
|
}
|
|
|
|
// ---- scans ----
|
|
|
|
func (s *Store) anScan(from, to int64, host string, fn func(evlog.Rec) bool) (truncated bool) {
|
|
deadline := time.Now().Add(studyDead)
|
|
n := 0
|
|
info := s.elog.ScanRecs(evlog.Filter{From: from, To: to, Host: host}, studyBudget, false, func(r evlog.Rec) bool {
|
|
if n++; n%4096 == 0 && time.Now().After(deadline) {
|
|
truncated = true
|
|
return false
|
|
}
|
|
return fn(r)
|
|
})
|
|
return truncated || info.Truncated
|
|
}
|
|
|
|
func anHostKey(h string) string {
|
|
if h == "all" {
|
|
return ""
|
|
}
|
|
return h
|
|
}
|
|
|
|
// Evolution compares [from, to] with the period of equal length before it.
|
|
func (s *Store) Evolution(from, to int64, host string) EvolutionOut {
|
|
host = anHostKey(host)
|
|
k := studyKey{kind: "an-evolution", from: from, to: to, host: host}
|
|
return s.cached(k, func() any { return s.evolution(from, to, host) }).(EvolutionOut)
|
|
}
|
|
|
|
func (s *Store) evolution(from, to int64, host string) EvolutionOut {
|
|
out := EvolutionOut{Days: []AnDay{}, NewFamilies: []AnFam{}, GoneFamilies: []AnFam{}}
|
|
if s.elog == nil || to <= from {
|
|
return out
|
|
}
|
|
out.Enabled = true
|
|
span := to - from + 1
|
|
prevFrom := from - span
|
|
days := map[int64]*AnDay{}
|
|
cur, prev := map[string]uint32{}, map[string]uint32{}
|
|
out.Truncated = s.anScan(prevFrom, to, host, func(r evlog.Rec) bool {
|
|
if !core.Category(r.Cat).IsMalicious() {
|
|
return true
|
|
}
|
|
fam := r.Fam
|
|
if fam == "" {
|
|
fam = "other"
|
|
}
|
|
if r.T < from {
|
|
out.Prev++
|
|
prev[fam]++
|
|
return true
|
|
}
|
|
out.Total++
|
|
cur[fam]++
|
|
d := r.T / 86400
|
|
a := days[d]
|
|
if a == nil {
|
|
a = &AnDay{D: time.Unix(d*86400, 0).UTC().Format("2006-01-02"), ByCat: map[string]uint32{}, ByFam: map[string]uint32{}}
|
|
days[d] = a
|
|
}
|
|
a.Total++
|
|
a.ByCat[r.Cat]++
|
|
a.ByFam[fam]++
|
|
t := time.Unix(r.T, 0).UTC()
|
|
out.HourDow[int(t.Weekday())][t.Hour()]++
|
|
return true
|
|
})
|
|
first, last := from/86400, to/86400
|
|
if last-first >= anMaxDays {
|
|
first = last - anMaxDays + 1
|
|
}
|
|
for d := first; d <= last; d++ {
|
|
a := days[d]
|
|
if a == nil {
|
|
a = &AnDay{D: time.Unix(d*86400, 0).UTC().Format("2006-01-02"), ByCat: map[string]uint32{}, ByFam: map[string]uint32{}}
|
|
}
|
|
out.Days = append(out.Days, *a)
|
|
}
|
|
if out.Prev > 0 {
|
|
v := math.Round((float64(out.Total)-float64(out.Prev))/float64(out.Prev)*1000) / 10
|
|
out.DeltaPct = &v
|
|
for f, n := range cur {
|
|
if prev[f] == 0 {
|
|
out.NewFamilies = append(out.NewFamilies, AnFam{f, n})
|
|
}
|
|
}
|
|
for f, n := range prev {
|
|
if cur[f] == 0 {
|
|
out.GoneFamilies = append(out.GoneFamilies, AnFam{f, n})
|
|
}
|
|
}
|
|
for _, l := range []*[]AnFam{&out.NewFamilies, &out.GoneFamilies} {
|
|
sort.Slice(*l, func(i, j int) bool {
|
|
if (*l)[i].N != (*l)[j].N {
|
|
return (*l)[i].N > (*l)[j].N
|
|
}
|
|
return (*l)[i].Fam < (*l)[j].Fam
|
|
})
|
|
if len(*l) > 20 {
|
|
*l = (*l)[:20]
|
|
}
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// ConcentrationDims are the accepted dimensions.
|
|
var ConcentrationDims = map[string]bool{"ip": true, "asn": true, "country": true, "path": true, "domain": true}
|
|
|
|
// Concentration measures how unevenly malicious events spread over a dimension.
|
|
func (s *Store) Concentration(from, to int64, host, dim string) ConcentrationOut {
|
|
host = anHostKey(host)
|
|
k := studyKey{kind: "an-conc", from: from, to: to, host: host, cat: dim}
|
|
return s.cached(k, func() any { return s.concentration(from, to, host, dim) }).(ConcentrationOut)
|
|
}
|
|
|
|
func (s *Store) concentration(from, to int64, host, dim string) ConcentrationOut {
|
|
out := ConcentrationOut{Dim: dim, Items: []AnItem{}}
|
|
if s.elog == nil || to <= from || !ConcentrationDims[dim] {
|
|
return out
|
|
}
|
|
out.Enabled = true
|
|
counts := map[string]uint32{}
|
|
labels := map[string]string{}
|
|
geo := map[string]core.GeoInfo{}
|
|
out.Truncated = s.anScan(from, to, host, func(r evlog.Rec) bool {
|
|
if !core.Category(r.Cat).IsMalicious() {
|
|
return true
|
|
}
|
|
key, label := "", ""
|
|
switch dim {
|
|
case "ip":
|
|
key = r.IP
|
|
case "path":
|
|
if r.Source != "traefik" {
|
|
return true
|
|
}
|
|
key = r.Path
|
|
if len(key) > 200 {
|
|
key = key[:200]
|
|
}
|
|
case "domain":
|
|
key = r.Domain
|
|
case "country":
|
|
key = r.CC
|
|
if key == "" {
|
|
g, ok := geo[r.IP]
|
|
if !ok {
|
|
g = s.GeoOf(r.IP)
|
|
if len(geo) < 50000 {
|
|
geo[r.IP] = g
|
|
}
|
|
}
|
|
key = g.CC
|
|
}
|
|
case "asn":
|
|
g, ok := geo[r.IP]
|
|
if !ok {
|
|
g = s.GeoOf(r.IP)
|
|
if len(geo) < 50000 {
|
|
geo[r.IP] = g
|
|
}
|
|
}
|
|
if g.ASN != 0 {
|
|
key, label = "AS"+strconv.Itoa(int(g.ASN)), g.ASOrg
|
|
}
|
|
}
|
|
if key == "" {
|
|
return true
|
|
}
|
|
if _, seen := counts[key]; !seen && len(counts) >= anMaxKeys {
|
|
out.Truncated = true
|
|
return true
|
|
}
|
|
counts[key]++
|
|
if label != "" {
|
|
labels[key] = label
|
|
}
|
|
return true
|
|
})
|
|
all := make([]AnItem, 0, len(counts))
|
|
vals := make([]float64, 0, len(counts))
|
|
for k, n := range counts {
|
|
all = append(all, AnItem{Key: k, Label: labels[k], N: n})
|
|
vals = append(vals, float64(n))
|
|
out.Total += uint64(n)
|
|
}
|
|
sort.Slice(all, func(i, j int) bool {
|
|
if all[i].N != all[j].N {
|
|
return all[i].N > all[j].N
|
|
}
|
|
return all[i].Key < all[j].Key
|
|
})
|
|
out.Distinct = len(all)
|
|
out.Gini = anGini(vals)
|
|
if len(all) > anMaxItems {
|
|
all = all[:anMaxItems]
|
|
}
|
|
out.Items = anPareto(all, out.Total)
|
|
if len(out.Items) > 0 {
|
|
i := 9
|
|
if len(out.Items) <= i {
|
|
i = len(out.Items) - 1
|
|
}
|
|
out.Top10Pct = out.Items[i].CumPct
|
|
}
|
|
return out
|
|
}
|
|
|
|
// Survival studies the time from an attacker's first malicious event to its
|
|
// ban (Kaplan-Meier, censoring the ones never banned) and the ones banned again.
|
|
func (s *Store) Survival(from, to int64, host string) SurvivalOut {
|
|
host = anHostKey(host)
|
|
k := studyKey{kind: "an-survival", from: from, to: to, host: host}
|
|
return s.cached(k, func() any { return s.survival(from, to, host) }).(SurvivalOut)
|
|
}
|
|
|
|
type anIPState struct {
|
|
mal []int64
|
|
bans []int64
|
|
banJail map[int64]string
|
|
fam string
|
|
}
|
|
|
|
// BlockerTTB is the time to ban of the bans applied by one blocker: the host
|
|
// fail2ban jails, or Urutau's second firewall (its "urutau" jail).
|
|
type BlockerTTB struct {
|
|
Blocker string `json:"blocker"` // "fail2ban" or "urutau"
|
|
Bans int `json:"bans"`
|
|
MedianS int64 `json:"median_s"`
|
|
P90S int64 `json:"p90_s"`
|
|
}
|
|
|
|
func blockerOf(jail string) string {
|
|
if jail == "urutau" {
|
|
return "urutau"
|
|
}
|
|
return "fail2ban"
|
|
}
|
|
|
|
// anEpisodes splits the activity of one address into attack episodes. An
|
|
// episode starts at the first malicious event after the previous ban, runs
|
|
// through events with gaps of at most episodeGap, and ends at the ban (event
|
|
// observed, T = ban - start) or, with no ban, at its last event + episodeGap
|
|
// (censored, capped at end).
|
|
func anEpisodes(mal, bans []int64, end int64) []anSubject {
|
|
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 []anSubject
|
|
prev := int64(-1)
|
|
bi := 0
|
|
for i := 0; i < len(mal); {
|
|
if mal[i] <= prev {
|
|
i++
|
|
continue
|
|
}
|
|
start, last := mal[i], mal[i]
|
|
for bi < len(bans) && bans[bi] < start {
|
|
bi++
|
|
}
|
|
next := int64(-1)
|
|
if bi < len(bans) {
|
|
next = bans[bi]
|
|
}
|
|
j := i + 1
|
|
for j < len(mal) && mal[j]-last <= episodeGap && (next < 0 || mal[j] <= next) {
|
|
last = mal[j]
|
|
j++
|
|
}
|
|
i = j
|
|
if next >= 0 && next-last <= episodeGap {
|
|
out = append(out, anSubject{T: next - start, Event: true, Ban: next})
|
|
prev = next
|
|
bi++
|
|
continue
|
|
}
|
|
stop := last + episodeGap
|
|
if stop > end {
|
|
stop = end
|
|
}
|
|
d := stop - start
|
|
if d < 0 {
|
|
d = 0
|
|
}
|
|
out = append(out, anSubject{T: d})
|
|
prev = last
|
|
}
|
|
return out
|
|
}
|
|
|
|
func (s *Store) survival(from, to int64, host string) SurvivalOut {
|
|
out := SurvivalOut{KM: []KMPoint{{0, 1}}, ByFamily: []FamTTB{}, Recidivists: []Recidivist{}}
|
|
if s.elog == nil || to <= from {
|
|
return out
|
|
}
|
|
out.Enabled = true
|
|
ips := map[string]*anIPState{}
|
|
out.Truncated = s.anScan(from, to, host, func(r evlog.Rec) bool {
|
|
c := core.Category(r.Cat)
|
|
isBan := c == core.Ban && !r.Unban
|
|
if !isBan && !c.IsMalicious() {
|
|
return true
|
|
}
|
|
st := ips[r.IP]
|
|
if st == nil {
|
|
if len(ips) >= anMaxIPs {
|
|
return true
|
|
}
|
|
st = &anIPState{}
|
|
ips[r.IP] = st
|
|
}
|
|
if isBan {
|
|
st.bans = append(st.bans, r.T)
|
|
if r.Jail != "" {
|
|
if st.banJail == nil {
|
|
st.banJail = map[int64]string{}
|
|
}
|
|
st.banJail[r.T] = r.Jail
|
|
}
|
|
return true
|
|
}
|
|
if len(st.mal) < 5000 {
|
|
st.mal = append(st.mal, r.T)
|
|
}
|
|
if st.fam == "" && r.Fam != "" {
|
|
st.fam = r.Fam
|
|
}
|
|
return true
|
|
})
|
|
end := to
|
|
if now := s.now().Unix(); now < end {
|
|
end = now
|
|
}
|
|
var subs []anSubject
|
|
famT := map[string][]int64{}
|
|
blockT := map[string][]int64{}
|
|
var banned, recid, attackers int
|
|
var rec []Recidivist
|
|
for ip, st := range ips {
|
|
if len(st.mal) == 0 {
|
|
continue
|
|
}
|
|
attackers++
|
|
eps := anEpisodes(st.mal, st.bans, end)
|
|
subs = append(subs, eps...)
|
|
for _, e := range eps {
|
|
if e.Event {
|
|
b := blockerOf(st.banJail[e.Ban])
|
|
blockT[b] = append(blockT[b], e.T)
|
|
}
|
|
if e.Event && st.fam != "" {
|
|
famT[st.fam] = append(famT[st.fam], e.T)
|
|
}
|
|
}
|
|
if n := len(st.bans); n > 0 {
|
|
banned++
|
|
if n >= 2 {
|
|
recid++
|
|
rec = append(rec, Recidivist{ip, n, st.bans[len(st.bans)-1]})
|
|
}
|
|
}
|
|
}
|
|
out.Attackers, out.Banned, out.Episodes = attackers, banned, len(subs)
|
|
out.KM, out.MedianToBanS, out.P90ToBanS = anKaplanMeier(subs)
|
|
if banned > 0 {
|
|
out.RecidivismPct = math.Round(float64(recid)/float64(banned)*1000) / 10
|
|
}
|
|
out.ByBlocker = []BlockerTTB{}
|
|
for _, b := range []string{"fail2ban", "urutau"} {
|
|
v := blockT[b]
|
|
if len(v) == 0 {
|
|
continue
|
|
}
|
|
sort.Slice(v, func(i, j int) bool { return v[i] < v[j] })
|
|
out.ByBlocker = append(out.ByBlocker, BlockerTTB{b, len(v), anQuant(v, .5), anQuant(v, .9)})
|
|
}
|
|
for f, v := range famT {
|
|
sort.Slice(v, func(i, j int) bool { return v[i] < v[j] })
|
|
out.ByFamily = append(out.ByFamily, FamTTB{f, anQuant(v, .25), anQuant(v, .5), anQuant(v, .75), len(v)})
|
|
}
|
|
sort.Slice(out.ByFamily, func(i, j int) bool {
|
|
if out.ByFamily[i].N != out.ByFamily[j].N {
|
|
return out.ByFamily[i].N > out.ByFamily[j].N
|
|
}
|
|
return out.ByFamily[i].Fam < out.ByFamily[j].Fam
|
|
})
|
|
if len(out.ByFamily) > anMaxFamilies {
|
|
out.ByFamily = out.ByFamily[:anMaxFamilies]
|
|
}
|
|
sort.Slice(rec, func(i, j int) bool {
|
|
if rec[i].Bans != rec[j].Bans {
|
|
return rec[i].Bans > rec[j].Bans
|
|
}
|
|
if rec[i].Last != rec[j].Last {
|
|
return rec[i].Last > rec[j].Last
|
|
}
|
|
return rec[i].IP < rec[j].IP
|
|
})
|
|
if len(rec) > anMaxRecid {
|
|
rec = rec[:anMaxRecid]
|
|
}
|
|
if rec != nil {
|
|
out.Recidivists = rec
|
|
}
|
|
return out
|
|
}
|