feat: 1.3.0 thirteen new pages, charts, tooltips and error analysis
Release / Plan (reuse the published image?) (push) Successful in 3s
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 28s
CI / Dependency audit (push) Successful in 20s
CI / Tests (Linux, race detector) (push) Successful in 1m10s
Release / ci (push) Successful in 1m10s
Release / Build image (arm64) (push) Successful in 55s
Release / Build image (amd64) (push) Successful in 1m16s
Release / Publish tags (push) Successful in 14s
Release / Gitea release (push) Skipped

New pages grouped in the rail (Monitor, Investigate, Analyze, Operate,
Reports): Services (SLO, Apdex, latency app vs proxy), Sessions (stage
funnel), Campaigns, Event search, MITRE ATT&CK matrix, Evolution,
Concentration (Pareto, Gini), Survival (Kaplan-Meier per attack
episode, recidivists), Where errors come from (application vs failed
attack vs proxy vs client), Protocols and TLS, Defense (fail2ban, SSH,
blocklist), Integrity, and a printable executive report.

Chart library (donut, radar, stacked area, bars, heatmap, gauge),
glossary with accessible "?" tooltips, self-explanatory category names
(nonexistent page 404), page loader through pages.json.

Unique visitors fixed: real browsers opening a page, one per IP per day,
deduplicated across domains, with non-human clients counted apart.
Anonymous legitimate visits on the Live page (?visits=1, no IP).
Traefik origin, service, protocol and TLS fields parsed. Paths and
Referer paths drop e-mail and token segments.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lucas RayanandClaude Opus 5.5 committed 2026-11-14 22:39:33 -03:00
1 parent b7462c14fa
commit 2ebda1e4d7
79 files changed
+9091 -171

No files matched your search

+589
View File
@@ -0,0 +1,589 @@
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"`
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
}
// 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.Scan(evlog.Filter{From: from, To: to, Host: host}, studyBudget, false, func(r evlog.Rec, _ []byte) 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
fam string
}
// 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{next - start, true})
prev = next
bi++
continue
}
stop := last + episodeGap
if stop > end {
stop = end
}
d := stop - start
if d < 0 {
d = 0
}
out = append(out, anSubject{d, false})
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)
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{}
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 && 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
}
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
}
+185
View File
@@ -0,0 +1,185 @@
package store
import (
"math"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
)
func TestGini(t *testing.T) {
if g := anGini(nil); g != 0 {
t.Fatalf("empty %v", g)
}
if g := anGini([]float64{5, 5, 5, 5}); g != 0 {
t.Fatalf("equal %v", g)
}
// one holds everything among 4: (n-1)/n = 0.75
if g := anGini([]float64{0, 0, 0, 100}); math.Abs(g-0.75) > 1e-9 {
t.Fatalf("concentrated %v", g)
}
if g := anGini([]float64{0, 0}); g != 0 {
t.Fatalf("zeros %v", g)
}
}
func TestPareto(t *testing.T) {
items := anPareto([]AnItem{{Key: "a", N: 60}, {Key: "b", N: 30}, {Key: "c", N: 10}}, 100)
if items[0].CumPct != 60 || items[1].CumPct != 90 || items[2].CumPct != 100 {
t.Fatalf("%+v", items)
}
if e := anPareto(nil, 0); len(e) != 0 {
t.Fatal("empty")
}
}
func TestKaplanMeierCensoring(t *testing.T) {
// times 10(ban) 20(censored) 30(ban) 40(ban): S(10)=3/4, at 30 risk=2 -> 3/4*1/2, at 40 risk=1 -> 0
c, med, p90 := anKaplanMeier([]anSubject{{10, true}, {20, false}, {30, true}, {40, true}})
want := []KMPoint{{0, 1}, {10, 0.75}, {30, 0.375}, {40, 0}}
if len(c) != len(want) {
t.Fatalf("%+v", c)
}
for i := range want {
if c[i] != want[i] {
t.Fatalf("%d: %+v want %+v", i, c[i], want[i])
}
}
if med == nil || *med != 30 || p90 == nil || *p90 != 40 {
t.Fatalf("median %v p90 %v", med, p90)
}
// everybody censored: no event, no median
c, med, p90 = anKaplanMeier([]anSubject{{5, false}, {9, false}})
if len(c) != 1 || med != nil || p90 != nil {
t.Fatalf("censored %+v", c)
}
c, med, _ = anKaplanMeier(nil)
if len(c) != 1 || med != nil {
t.Fatal("empty")
}
var many []anSubject
for i := 1; i <= 1000; i++ {
many = append(many, anSubject{int64(i), true})
}
if c, _, _ := anKaplanMeier(many); len(c) != anKMPoints || c[len(c)-1].Survival != 0 {
t.Fatalf("downsample %d", len(c))
}
}
func TestAnalyticsEmpty(t *testing.T) {
s := store30("oracle")
f, to := t0.Unix()-86400, t0.Unix()
if e := s.Evolution(f, to, ""); e.Enabled || e.Days == nil {
t.Fatalf("no registry: %+v", e)
}
s = store30("oracle")
s.SetEventLog(openLog(t))
if e := s.Evolution(f, to, ""); !e.Enabled || e.Total != 0 || e.DeltaPct != nil || len(e.Days) < 2 {
t.Fatalf("empty evolution: %+v", e)
}
if c := s.Concentration(f, to, "", "ip"); !c.Enabled || c.Total != 0 || c.Items == nil || c.Gini != 0 {
t.Fatalf("empty concentration: %+v", c)
}
if c := s.Concentration(f, to, "", "bogus"); c.Enabled {
t.Fatal("bad dim")
}
if v := s.Survival(f, to, ""); !v.Enabled || v.MedianToBanS != nil || len(v.KM) != 1 || v.RecidivismPct != 0 {
t.Fatalf("empty survival: %+v", v)
}
}
func TestAnalyticsData(t *testing.T) {
s := store30("oracle")
s.SetEventLog(openLog(t))
at := func(d time.Duration) time.Time { return t0.Add(-d) }
mal := func(ip, path string, cat core.Category, d time.Duration) {
s.Ingest(core.Event{Time: at(d), IP: ip, Cat: cat, Source: "traefik", Domain: "a.example", Method: "GET", Path: path, Status: 404, UA: "curl/8"})
}
// 1.1.1.1 is the heavy hitter now; 2.2.2.2 and 3.3.3.3 are light; 9.9.9.9 only existed the day before
for i := 0; i < 8; i++ {
mal("1.1.1.1", "/.env", core.Scanner, time.Hour+time.Duration(i)*time.Minute)
}
mal("2.2.2.2", "/wp-login.php", core.Scanner, 2*time.Hour)
mal("3.3.3.3", "/xmlrpc.php", core.Scanner, 3*time.Hour)
mal("9.9.9.9", "/.git/config", core.Exploit, 30*time.Hour)
// bans: 1.1.1.1 twice (recidivist), 2.2.2.2 once; 3.3.3.3 never (censored)
ban := func(ip string, d time.Duration) {
s.Ingest(core.Event{Time: at(d), IP: ip, Cat: core.Ban, Source: "fail2ban", Jail: "sshd"})
}
ban("1.1.1.1", 50*time.Minute)
ban("1.1.1.1", 20*time.Minute)
ban("2.2.2.2", 2*time.Hour-300*time.Second)
f, to := t0.Unix()-86400, t0.Unix()
c := s.Concentration(f, to, "", "ip")
if c.Total != 10 || c.Distinct != 3 || c.Items[0].Key != "1.1.1.1" || c.Items[0].CumPct != 80 || c.Gini <= 0.3 {
t.Fatalf("concentration %+v", c)
}
if c.Top10Pct != 100 {
t.Fatalf("top10 %v", c.Top10Pct)
}
if p := s.Concentration(f, to, "", "path"); p.Items[0].Key != "/.env" || p.Items[0].N != 8 {
t.Fatalf("path %+v", p)
}
if d := s.Concentration(f, to, "", "domain"); d.Distinct != 1 || d.Gini != 0 {
t.Fatalf("domain %+v", d)
}
v := s.Survival(f, to, "")
if v.Attackers != 3 || v.Banned != 2 || v.RecidivismPct != 50 || len(v.Recidivists) != 1 || v.Recidivists[0].IP != "1.1.1.1" || v.Recidivists[0].Bans != 2 {
t.Fatalf("survival %+v", v)
}
// 1.1.1.1: first malicious 8m before the ban...: first event at -67m, ban at -50m = 1020 s; 2.2.2.2: 300 s; 3.3.3.3 censored at 3 h
if v.MedianToBanS == nil || *v.MedianToBanS != 1020 {
t.Fatalf("median %v km %+v", v.MedianToBanS, v.KM)
}
if v.P90ToBanS != nil {
t.Fatalf("p90 must be unknown with a censored attacker: %v", *v.P90ToBanS)
}
e := s.Evolution(f, to, "")
if e.Total != 10 || e.Prev != 1 || e.DeltaPct == nil || *e.DeltaPct != 900 {
t.Fatalf("evolution %+v", e)
}
var tot uint32
for _, d := range e.Days {
tot += d.Total
}
if tot != 10 {
t.Fatalf("days sum %d", tot)
}
var hd uint32
for _, r := range e.HourDow {
for _, n := range r {
hd += n
}
}
if hd != 10 {
t.Fatalf("hour_dow %d", hd)
}
}
func TestAnEpisodes(t *testing.T) {
end := int64(100000)
// episode 1: 0..60, banned at 100 (observed 100); episode 2: 200 alone, silent until 10000 (censored 200+1800-200);
// episode 3: 10000, 10100 then end of data (censored at last+30min)
got := anEpisodes([]int64{0, 60, 200, 10000, 10100}, []int64{100}, end)
want := []anSubject{{100, true}, {1800, false}, {1900, false}}
if len(got) != len(want) {
t.Fatalf("%+v", got)
}
for i := range want {
if got[i] != want[i] {
t.Fatalf("%d: %+v want %+v", i, got[i], want[i])
}
}
// a ban long after the last event does not end that episode; censoring is capped at the window end
got = anEpisodes([]int64{0}, []int64{5000}, 600)
if len(got) != 1 || got[0] != (anSubject{600, false}) {
t.Fatalf("%+v", got)
}
if len(anEpisodes(nil, []int64{5}, end)) != 0 {
t.Fatal("ban without events")
}
}
+263
View File
@@ -0,0 +1,263 @@
package store
import (
"context"
"sort"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
)
// Caps of the campaign views.
const (
MaxCampaignsOut = 200
MaxMembersOut = 500
)
// CampaignsOut is the campaign list derived from a period study.
type CampaignsOut struct {
Range RangeInfo `json:"range"`
Enabled bool `json:"enabled"`
Truncated bool `json:"truncated,omitempty"`
Total int `json:"total"`
IPsN int `json:"ips_n"`
Campaigns []intel.Campaign `json:"campaigns"`
}
// Member is one address of a campaign with its sessions in the period.
type Member struct {
IP string `json:"ip"`
First int64 `json:"first"`
Last int64 `json:"last"`
Stage string `json:"stage"`
Sessions []intel.Session `json:"sessions"`
}
// CampaignDetail is one campaign with its members and ordered sessions.
type CampaignDetail struct {
Range RangeInfo `json:"range"`
Truncated bool `json:"truncated,omitempty"`
Campaign intel.Campaign `json:"campaign"`
Members []Member `json:"members"`
}
var stageRank = map[string]int{intel.StageRecon: 1, intel.StageProbe: 2, intel.StageExploit: 3, intel.StageAccess: 4, intel.StageBanned: 5}
// StageRank orders the escalation stages (0 for an unknown one).
func StageRank(s string) int { return stageRank[s] }
// CampaignsOf lists the campaigns of a period study (at most MaxCampaignsOut,
// most addresses first) and the number of distinct addresses they group.
func CampaignsOf(p PeriodOut) CampaignsOut {
list := append([]intel.Campaign(nil), p.Campaigns...)
sort.SliceStable(list, func(i, j int) bool {
if list[i].IPsN != list[j].IPsN {
return list[i].IPsN > list[j].IPsN
}
return list[i].First.Before(list[j].First)
})
out := CampaignsOut{Range: p.Range, Enabled: p.Enabled, Truncated: p.Truncated, Total: len(list)}
seen := map[string]bool{}
n := 0
for _, c := range list {
n += c.IPsN
for _, ip := range c.IPs {
seen[ip] = true
}
}
out.IPsN = max(len(seen), 0)
if n > 0 && len(seen) == 0 {
out.IPsN = n
}
if len(list) > MaxCampaignsOut {
list = list[:MaxCampaignsOut]
}
out.Campaigns = list
if out.Campaigns == nil {
out.Campaigns = []intel.Campaign{}
}
return out
}
// CampaignOf returns the detail of one campaign of a period study.
func CampaignOf(p PeriodOut, id string) (CampaignDetail, bool) {
for _, c := range p.Campaigns {
if c.ID != id {
continue
}
d := CampaignDetail{Range: p.Range, Truncated: p.Truncated, Campaign: c, Members: []Member{}}
by := map[string]*Member{}
for _, ip := range c.IPs {
by[ip] = &Member{IP: ip, Stage: "", Sessions: []intel.Session{}}
}
total := 0
for _, s := range p.Sessions {
if s.CampaignID != id || total >= MaxMembersOut {
continue
}
m := by[s.IP]
if m == nil {
m = &Member{IP: s.IP, Sessions: []intel.Session{}}
by[s.IP] = m
}
total++
st, en := s.Start.Unix(), s.End.Unix()
if m.First == 0 || st < m.First {
m.First = st
}
if en > m.Last {
m.Last = en
}
if StageRank(s.Stage) > StageRank(m.Stage) {
m.Stage = s.Stage
}
m.Sessions = append(m.Sessions, s)
}
for _, m := range by {
sort.Slice(m.Sessions, func(i, j int) bool { return m.Sessions[i].Start.Before(m.Sessions[j].Start) })
d.Members = append(d.Members, *m)
}
sort.Slice(d.Members, func(i, j int) bool {
a, b := d.Members[i], d.Members[j]
if (a.First == 0) != (b.First == 0) {
return a.First != 0
}
if a.First != b.First {
return a.First < b.First
}
return a.IP < b.IP
})
if len(d.Members) > MaxMembersOut {
d.Members = d.Members[:MaxMembersOut]
}
return d, true
}
return CampaignDetail{}, false
}
// FunnelOut is the escalation funnel of a period study.
type FunnelOut struct {
Range RangeInfo `json:"range"`
Enabled bool `json:"enabled"`
Truncated bool `json:"truncated,omitempty"`
SessionsN int `json:"sessions_n"`
Sampled bool `json:"sampled,omitempty"`
Stages map[string]int `json:"stages"`
Reached map[string]int `json:"reached"`
Exploited int `json:"exploited"`
Sessions []intel.Session `json:"sessions"`
Escalations []EscalationOut `json:"escalations"`
}
// StageCounts is the funnel over every session of a study.
type StageCounts struct {
SessionsN int
Truncated bool
Stages map[string]int
Reached map[string]int
Exploited int
}
func newCounts() StageCounts {
z := func() map[string]int {
return map[string]int{"recon": 0, "probe": 0, "exploit": 0, "access": 0, "banned": 0}
}
return StageCounts{Stages: z(), Reached: z()}
}
// Add counts one session. A ban says nothing about how far the session got:
// it counts as recon and probe.
func (c *StageCounts) Add(stage string, success bool) {
if _, ok := c.Stages[stage]; !ok {
return
}
c.SessionsN++
c.Stages[stage]++
r := StageRank(stage)
if stage == intel.StageBanned {
c.Reached["recon"]++
c.Reached["probe"]++
c.Reached[intel.StageBanned]++
} else {
for k, v := range stageRank {
if v <= r {
c.Reached[k]++
}
}
}
if r == 3 || r == 4 || success {
c.Exploited++
}
}
// CountStages studies [q.From, q.To] and counts ALL its sessions by stage
// (the period study keeps only 200). Cached 30 s like the other studies.
func (s *Store) CountStages(q PeriodQuery) StageCounts {
k := studyKey{"funnel", q.From, q.To, q.Host, q.IP, q.Cat, q.Fam, q.Gap}
return s.cached(k, func() any { return s.countStages(q) }).(StageCounts)
}
func (s *Store) countStages(q PeriodQuery) StageCounts {
out := newCounts()
if s.elog == nil {
return out
}
gap := time.Duration(q.Gap) * time.Second
if q.Gap < 60 {
gap = intel.DefaultGap
if q.Gap > 0 {
gap = 60 * time.Second
}
}
deadline := time.Now().Add(studyDead)
ctx, cancel := context.WithDeadline(context.Background(), deadline)
defer cancel()
var evs []intel.Ev
info := s.elog.Scan(evlog.Filter{From: q.From, To: q.To, Host: q.Host, IP: q.IP, Cats: catSet(q.Cat), Fam: q.Fam}, studyBudget, false,
func(r evlog.Rec, _ []byte) bool {
if len(evs) >= maxStudyEvents || len(evs)%4096 == 0 && ctx.Err() != nil {
out.Truncated = true
return false
}
evs = append(evs, toEv(r))
return true
})
out.Truncated = out.Truncated || info.Truncated
for _, ss := range intel.Sessions(evs, gap) {
out.Add(ss.Stage, ss.Success)
}
return out
}
// FunnelOf builds the funnel: the counts cover every session when counts is
// given (nil: only the listed ones), the list holds the most severe sessions
// of the study (the study keeps at most 200).
func FunnelOf(p PeriodOut, counts *StageCounts) FunnelOut {
f := FunnelOut{Range: p.Range, Enabled: p.Enabled, Truncated: p.Truncated, SessionsN: p.SessionsN}
c := newCounts()
if counts != nil {
c = *counts
f.SessionsN = c.SessionsN
f.Truncated = f.Truncated || c.Truncated
} else {
for _, s := range p.Sessions {
c.Add(s.Stage, s.Success)
}
}
f.Stages, f.Reached, f.Exploited = c.Stages, c.Reached, c.Exploited
f.Sessions = append([]intel.Session{}, p.Sessions...)
f.Escalations = p.Escalations
if f.Escalations == nil {
f.Escalations = []EscalationOut{}
}
f.Sampled = f.SessionsN > len(f.Sessions)
sort.SliceStable(f.Sessions, func(i, j int) bool {
a, b := StageRank(f.Sessions[i].Stage), StageRank(f.Sessions[j].Stage)
if a != b {
return a > b
}
return f.Sessions[i].Start.After(f.Sessions[j].Start)
})
return f
}
+34
View File
@@ -0,0 +1,34 @@
package store
import (
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
)
func TestCampaignViewsAndFunnel(t *testing.T) {
now := time.Now()
p := PeriodOut{Enabled: true, SessionsN: 4, Campaigns: []intel.Campaign{
{ID: "a", IPsN: 2, IPs: []string{"1.1.1.1", "1.1.1.2"}}, {ID: "b", IPsN: 3, IPs: []string{"2.2.2.1", "2.2.2.2", "1.1.1.1"}}},
Sessions: []intel.Session{
{ID: "s1", IP: "1.1.1.1", Start: now, End: now, Stage: "recon", CampaignID: "a"},
{ID: "s2", IP: "1.1.1.2", Start: now, End: now, Stage: "exploit", CampaignID: "a"},
{ID: "s3", IP: "9.9.9.9", Start: now, End: now, Stage: "access"},
{ID: "s4", IP: "9.9.9.8", Start: now, End: now, Stage: "banned"}}}
c := CampaignsOf(p)
if c.Total != 2 || c.Campaigns[0].ID != "b" || c.IPsN != 4 {
t.Fatalf("%+v", c)
}
d, ok := CampaignOf(p, "a")
if !ok || len(d.Members) != 2 || d.Members[1].Stage != "exploit" {
t.Fatalf("%+v", d)
}
if _, ok := CampaignOf(p, "zz"); ok {
t.Fatal("unknown id")
}
f := FunnelOf(p, nil)
if f.Stages["banned"] != 1 || f.Reached["recon"] != 4 || f.Exploited != 2 || f.Sessions[0].Stage != "banned" {
t.Fatalf("%+v", f)
}
}
+328
View File
@@ -0,0 +1,328 @@
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
}
+32
View File
@@ -0,0 +1,32 @@
package store
import "testing"
func TestTacticOfAndStep(t *testing.T) {
for id, want := range map[string]string{"T1595.002": "TA0043", "T1110.001": "TA0006", "T1190": "TA0001", "T9999": ""} {
if got := TacticOf(id); got != want {
t.Fatalf("%s: %q want %q", id, got, want)
}
}
if s := defenseStep(86400); s%300 != 0 || s < 300 {
t.Fatalf("step %d", s)
}
if defenseStep(60) != 300 {
t.Fatal("step floor")
}
}
func TestEpisodeTTB(t *testing.T) {
day := int64(86400)
// three days: attack for 10 minutes, banned; again next days
mal := []int64{100, 400, 700, day + 50, day + 350, 3*day + 10}
bans := []int64{700 + 60, day + 350 + 120, 3*day + 10 + 30}
got := episodeTTB(mal, bans)
want := []float64{660, 420, 30}
if len(got) != 3 || got[0] != want[0] || got[1] != want[1] || got[2] != want[2] {
t.Fatalf("got %v want %v", got, want)
}
if len(episodeTTB(nil, []int64{5})) != 0 {
t.Fatal("a ban with no earlier event is ignored")
}
}
+118
View File
@@ -0,0 +1,118 @@
package store
import (
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
)
// Gap is a stretch of hours with no event at all from a source that usually has some.
type Gap struct {
From int64 `json:"from"`
To int64 `json:"to"`
}
// MinGapHours is the shortest silence reported as a hole.
const MinGapHours = 2
// HourlyFromTimeline folds a timeline (any step up to one hour, or exactly
// one hour) into events per hour for the hours [fromHour, toHour] (hour numbers,
// unix/3600). Hours outside the timeline stay zero.
func HourlyFromTimeline(tl Timeline, fromHour, toHour int64) []uint32 {
if toHour < fromHour {
return []uint32{}
}
n := int(toHour-fromHour) + 1
if n > 24*31 {
n = 24 * 31
fromHour = toHour - int64(n) + 1
}
out := make([]uint32, n)
if tl.Step <= 0 {
return out
}
for _, vals := range tl.Series {
for i, v := range vals {
if v == 0 {
continue
}
h := (tl.Start + int64(i)*tl.Step) / 3600
if h < fromHour || h > toHour {
continue
}
out[h-fromHour] += v
}
}
return out
}
// FindGaps lists runs of at least MinGapHours empty hours after the first
// busy hour, provided the source is a regular one (at least three busy hours).
// Gaps are returned as unix seconds [from, to).
func FindGaps(hourly []uint32, fromHour int64) []Gap {
busy, first := 0, -1
for i, v := range hourly {
if v > 0 {
busy++
if first < 0 {
first = i
}
}
}
gaps := []Gap{}
if busy < 3 {
return gaps
}
run := -1
flush := func(end int) {
if run >= 0 && end-run >= MinGapHours {
gaps = append(gaps, Gap{From: (fromHour + int64(run)) * 3600, To: (fromHour + int64(end)) * 3600})
}
run = -1
}
for i := first; i < len(hourly); i++ {
if hourly[i] == 0 {
if run < 0 {
run = i
}
} else {
flush(i)
}
}
flush(len(hourly))
return gaps
}
// LogStats describes the event log on disk.
type LogStats struct {
Enabled bool `json:"enabled"`
Days int `json:"days"`
Bytes int64 `json:"bytes"`
Dropped uint64 `json:"dropped"`
}
// LogStats counts the days with events (scan cached for five minutes), the
// size on disk and the events dropped by the writer.
func (s *Store) LogStats() LogStats {
if s.elog == nil {
return LogStats{}
}
k := studyKey{kind: "integrity-log"}
d := s.cachedTTL(k, 5*time.Minute, func() any {
days := map[int64]bool{}
now := s.now().Unix()
s.elog.Scan(evlog.Filter{From: now - int64(s.cfg.Retention/time.Second) - 86400, To: now + 86400}, studyBudget, false, func(r evlog.Rec, _ []byte) bool {
days[r.T/86400] = true
return true
})
return len(days)
}).(int)
return LogStats{Enabled: true, Days: d, Bytes: s.elog.Size(), Dropped: s.elog.Dropped()}
}
// GeoBuilds, when set by the application (serve.go: geo.Resolver.Status() ->
// City.Build / ASN.Build, as `urutau doctor` shows them), returns the build
// time of the city and ASN databases in unix seconds (0 when unknown). The
// source list the dashboard receives hides paths, so the server cannot open the
// geo directory itself.
var GeoBuilds func() (city, asn int64)
+27
View File
@@ -0,0 +1,27 @@
package store
import "testing"
func TestHourlyFromTimelineAndGaps(t *testing.T) {
tl := Timeline{Start: 0, Step: 1800, Series: map[string][]uint32{
"a": {1, 1, 0, 0, 0, 0, 0, 0, 2, 0},
"b": {0, 1, 0, 0, 0, 0, 0, 0, 0, 0},
}}
h := HourlyFromTimeline(tl, 0, 5)
want := []uint32{3, 0, 0, 0, 2, 0}
for i := range want {
if h[i] != want[i] {
t.Fatalf("hourly %v", h)
}
}
g := FindGaps([]uint32{0, 2, 1, 0, 0, 0, 4, 0, 5, 0}, 10)
if len(g) != 1 || g[0].From != 13*3600 || g[0].To != 16*3600 {
t.Fatalf("gaps %+v", g)
}
if g := FindGaps([]uint32{0, 0, 5, 0, 0, 0}, 0); len(g) != 0 {
t.Fatalf("irregular source has no gaps: %+v", g)
}
if len(HourlyFromTimeline(tl, 5, 1)) != 0 {
t.Fatal("empty window")
}
}
+34
View File
@@ -0,0 +1,34 @@
package store
import (
"strings"
"testing"
)
// Paths and Referer paths kept in aggregates (top pages, broken links, error
// routes) and sent in live visit events must not carry e-mail addresses or
// secret tokens (reset links, invites).
func TestNormalizePathDropsPersonalSegments(t *testing.T) {
for in, want := range map[string]string{
"/reset/secrettoken_abc-DEF.ghi/joao@mail.com": "/reset/:id/:id",
"/conta/joao.silva@mail.com/reset-tok_ab.cd": "/conta/:id/:id",
"/invite/aZ93kd02LmQp": "/invite/:id",
"/u/" + strings.Repeat("x", 30): "/u/:id",
"/blog/post-1": "/blog/post-1",
"/ciberfauna/guara/actions/runs/36/jobs/397": "/ciberfauna/guara/actions/runs/36/jobs/397",
"/sobre": "/sobre",
"/": "/",
} {
if got := normalizePath(in); got != want {
t.Errorf("normalizePath(%q) = %q, want %q", in, got, want)
}
}
if got := urlPath("https://site.example/reset/secrettoken_abc-DEF.ghi/joao@mail.com?token=SECRET"); strings.Contains(got, "@") || strings.Contains(got, "secrettoken") || strings.Contains(got, "SECRET") {
t.Fatalf("referer path kept personal data: %q", got)
}
m := VisitMsg{Kind: "visit", Path: "/conta/joao@mail.com", T: 1}
m.Sanitize(1)
if strings.Contains(m.Path, "@") {
t.Fatalf("peer visit path not normalized: %q", m.Path)
}
}
+510
View File
@@ -0,0 +1,510 @@
package store
import (
"net/url"
"sort"
"strings"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
)
// Per-service health: for every backend service, per hour, the request mix,
// the error classes (see core.ErrorClass), latency histograms, Apdex and the
// protocol/TLS mix; per day the top failing routes, broken links and so on.
const (
svcCap = 64
svcOther = "(other)"
svcRoutes = 200
svcCiphers = 50
svcLatN = latN + 1 // the existing bounds plus a 30 s bound
)
// Class slots of svcHour.Cls.
const (
ClsApp = iota
ClsProxy
ClsBlocked
ClsAttack
ClsBot
ClsClientBroken
ClsClientAuth
ClsClientOther
NumCls
)
// ClsNames names the Cls slots.
var ClsNames = [NumCls]string{"app", "proxy", "blocked", "attack", "bot", "client_broken", "client_auth", "client_other"}
// SvcBounds are the upper bounds (ms) of the latency histograms; the last
// bucket is everything above.
var SvcBounds = [svcLatN - 1]float64{5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 30000}
func svcBucket(ns int64) int {
ms := float64(ns) / 1e6
for i, b := range SvcBounds {
if ms <= b {
return i
}
}
return svcLatN - 1
}
type svcHour struct {
Hour int64
Req, Legit uint32
Cls [NumCls]uint32
S [5]uint32 // 2xx 3xx 4xx 5xx other
Dur, Org, Ov [svcLatN]uint32
ApSat, ApTol uint32 // Apdex satisfied / tolerating
ApN uint32
Retries uint32
Proto [4]uint32 // HTTP/1.x HTTP/2 HTTP/3 other
TLS [4]uint32 // 1.3 1.2 older none
BytesMax uint32
}
type svcDay struct {
Day int64
ErrRoutes map[string]uint32 // "class|METHOD path"
Broken404 map[string]uint32 // "path\x00referer path"
Methods map[string]uint32 // "METHOD|class"
Ciphers map[string]uint32
ProtoCls map[string]uint32 // "proto|class"
TLSCls map[string]uint32 // "tls|class"
Last404 map[string]int64 // broken link key -> last seen
}
type svcData struct {
Hours [hourSlots]svcHour
Days [anDays]svcDay
Doms map[string]uint32
Last int64
}
type svcState struct {
m map[string]*svcData
}
// ServiceKey names the service of an event: the Traefik service without the
// provider suffix, else the router, else the host.
func ServiceKey(ev core.Event) string {
k := ev.Service
if k == "" || strings.HasPrefix(k, "noop@") || strings.HasPrefix(k, "api@") {
k = ev.Router
}
if i := strings.IndexByte(k, '@'); i >= 0 {
k = k[:i]
}
if k == "" {
k = normDomain(ev.Domain)
}
return clipS(k, 64)
}
func isAPIPath(p string) bool {
return strings.HasPrefix(p, "/api") || strings.HasPrefix(p, "/v2/") || p == "/v2" || strings.HasPrefix(p, "/graphql") || strings.HasPrefix(p, "/trpc")
}
func urlPath(ref string) string {
u, err := url.Parse(ref)
if err != nil || u.Host == "" {
return ""
}
p := u.EscapedPath()
if p == "" {
p = "/"
}
// a Referer path can carry personal data or secrets (reset links, e-mail)
return clipS(normalizePath(p), 120)
}
func clsSlot(class, sub string) int {
switch class {
case core.ClassApp:
return ClsApp
case core.ClassProxy:
return ClsProxy
case core.ClassBlocked:
return ClsBlocked
case core.ClassAttack:
return ClsAttack
case core.ClassBot:
return ClsBot
case core.ClassClient:
switch sub {
case core.SubBrokenLink, core.SubExternalLink:
return ClsClientBroken
case core.SubAuth, core.SubAuthChallenge:
return ClsClientAuth
}
return ClsClientOther
}
return -1
}
func protoSlot(p string) int {
switch {
case strings.HasPrefix(p, "HTTP/1"):
return 0
case strings.HasPrefix(p, "HTTP/2"):
return 1
case strings.HasPrefix(p, "HTTP/3"):
return 2
}
return 3
}
func protoName(i int) string { return [...]string{"http1", "http2", "http3", "other"}[i] }
func tlsSlot(ev core.Event) int {
switch ev.TLSVer {
case "1.3":
return 0
case "1.2":
return 1
case "":
if ev.Scheme == "http" || ev.Scheme == "" {
return 3
}
}
return 2
}
// TLSName names the TLS slots.
func TLSName(i int) string { return [...]string{"tls13", "tls12", "tls_old", "none"}[i] }
// ObserveService records one Traefik request for the service health views. It
// takes every request (attacks too: the error classes need them) but only
// those that carry the origin fields feed the latency and protocol parts.
func (s *Store) ObserveService(ev core.Event) {
if ev.Source != "traefik" {
return
}
now := s.now()
if ev.Time.Before(now.Add(-s.cfg.Retention)) {
return
}
ts := ev.Time.Unix()
if max := now.Unix() + 300; ts > max {
ts = max
}
key := ServiceKey(ev)
dom := normDomain(ev.Domain)
s.mu.Lock()
defer s.mu.Unlock()
susp := false
if r := s.ips[ev.IP]; r != nil {
susp = r.BanSince > 0 || core.LevelOf(r.Score, r.Strong || attackKinds(r.Counts) >= 2, r.adminAt(now.Unix())) != core.LevelLow
}
if s.sv.m == nil {
s.sv.m = map[string]*svcData{}
}
d := s.sv.m[key]
if d == nil {
if len(s.sv.m) >= svcCap {
key = svcOther
d = s.sv.m[key]
}
if d == nil {
d = &svcData{}
s.sv.m[key] = d
}
}
d.Last = ts
bumpCap(&d.Doms, dom, 8)
h := ts / 3600
hs := &d.Hours[int(h%hourSlots)]
if hs.Hour != h {
*hs = svcHour{Hour: h}
}
day := ts / 86400
dd := &d.Days[int(day%anDays)]
if dd.Day != day {
*dd = svcDay{Day: day}
}
hs.Req++
switch c := ev.Status / 100; {
case c >= 2 && c <= 5:
hs.S[c-2]++
default:
hs.S[4]++
}
class, sub, _ := core.ErrorClassify(ev, susp)
slot := clsSlot(class, sub)
attackish := ev.Cat == core.Scanner || ev.Cat == core.Exploit || ev.Cat == core.BruteForce || susp
if slot >= 0 {
hs.Cls[slot]++
}
if slot != ClsAttack && slot != ClsBlocked && slot != ClsBot && !(slot < 0 && attackish) {
hs.Legit++
}
if ev.Retries > 0 {
hs.Retries += uint32(ev.Retries)
}
if ev.DurationNS > 0 {
hs.Dur[svcBucket(ev.DurationNS)]++
}
if ev.OriginNS > 0 {
hs.Org[svcBucket(ev.OriginNS)]++
}
if ev.OverheadNS > 0 {
hs.Ov[svcBucket(ev.OverheadNS)]++
}
if ev.Bytes > 0 {
b := uint32(min64(ev.Bytes, 1<<32-1))
if b > hs.BytesMax {
hs.BytesMax = b
}
}
// Apdex over the requests that count for the service
if slot != ClsAttack && slot != ClsBlocked && slot != ClsBot && ev.DurationNS > 0 {
t := int64(500e6)
if isAPIPath(ev.Path) {
t = 1000e6
}
hs.ApN++
switch {
case ev.Status >= 500:
case ev.DurationNS <= t:
hs.ApSat++
case ev.DurationNS <= 4*t:
hs.ApTol++
}
}
if ev.Proto != "" {
hs.Proto[protoSlot(ev.Proto)]++
hs.TLS[tlsSlot(ev)]++
if ev.TLSCiph != "" {
bumpCap(&dd.Ciphers, ev.TLSCiph, svcCiphers)
}
}
cn := class
if cn == "" {
cn = "ok"
}
if ev.Method != "" {
bumpCap(&dd.Methods, strings.ToUpper(ev.Method)+"|"+cn, svcCiphers*2)
}
if ev.Proto != "" {
bumpCap(&dd.ProtoCls, protoName(protoSlot(ev.Proto))+"|"+cn, 40)
bumpCap(&dd.TLSCls, TLSName(tlsSlot(ev))+"|"+cn, 40)
}
if class == "" {
return
}
p := ev.Path
if i := strings.IndexAny(p, "?#"); i >= 0 {
p = p[:i]
}
np := normalizePath(p)
bumpCap(&dd.ErrRoutes, class+"|"+strings.ToUpper(ev.Method)+" "+clipS(np, 120), svcRoutes)
if class == core.ClassClient && ev.Status == 404 && (sub == core.SubBrokenLink || sub == core.SubExternalLink) {
rp := urlPath(ev.Referer)
if rp == "" {
rp = "-"
}
k := clipS(np, 120) + "\x00" + rp
if sub == core.SubExternalLink {
if u, err := url.Parse(ev.Referer); err == nil {
rp = u.Hostname()
}
k = clipS(np, 120) + "\x00" + "@" + rp
}
bumpCap(&dd.Broken404, k, svcRoutes)
if dd.Last404 == nil {
dd.Last404 = map[string]int64{}
}
if _, ok := dd.Broken404[k]; ok {
dd.Last404[k] = ts
}
if len(dd.Last404) > 2*svcRoutes {
for kk := range dd.Last404 {
if _, ok := dd.Broken404[kk]; !ok {
delete(dd.Last404, kk)
}
}
}
}
}
func min64(a, b int64) int64 {
if a < b {
return a
}
return b
}
// SvcView is one service over a window.
type SvcView struct {
Key, Alias string
Hours []SvcHourOut // hours in the window, ascending (only those with traffic)
Tot SvcHourOut // the sum
ErrRoutes map[string]uint32
Broken map[string]uint32
BrokenLast map[string]int64
Methods map[string]uint32
Ciphers map[string]uint32
ProtoCls map[string]uint32
TLSCls map[string]uint32
}
// SvcHourOut is an exported copy of an hour (or of a sum of hours).
type SvcHourOut struct {
Hour int64
Req, Legit uint32
Cls [NumCls]uint32
S [5]uint32
Dur, Org, Ov [svcLatN]uint32
ApSat, ApTol uint32
ApN uint32
Retries uint32
Proto [4]uint32
TLS [4]uint32
BytesMax uint32
}
func (o *SvcHourOut) add(h *svcHour) {
o.Req += h.Req
o.Legit += h.Legit
o.ApSat += h.ApSat
o.ApTol += h.ApTol
o.ApN += h.ApN
o.Retries += h.Retries
if h.BytesMax > o.BytesMax {
o.BytesMax = h.BytesMax
}
for i := range h.Cls {
o.Cls[i] += h.Cls[i]
}
for i := range h.S {
o.S[i] += h.S[i]
}
for i := range h.Dur {
o.Dur[i] += h.Dur[i]
o.Org[i] += h.Org[i]
o.Ov[i] += h.Ov[i]
}
for i := range h.Proto {
o.Proto[i] += h.Proto[i]
o.TLS[i] += h.TLS[i]
}
}
func mergeMap(dst *map[string]uint32, src map[string]uint32) {
if len(src) == 0 {
return
}
if *dst == nil {
*dst = make(map[string]uint32, len(src))
}
for k, v := range src {
(*dst)[k] += v
}
}
// Services returns every service with traffic in [from, to] (unix seconds),
// busiest first. svc filters by key or alias, host by served domain; both may be "".
func (s *Store) Services(from, to int64, svc, host string) []SvcView {
fh, lh := from/3600, to/3600
fd, ld := from/86400, to/86400
s.mu.RLock()
defer s.mu.RUnlock()
var out []SvcView
for key, d := range s.sv.m {
v := SvcView{Key: key, Alias: svcAlias(key, d)}
if svc != "" && svc != key && svc != v.Alias {
continue
}
if host != "" {
if _, ok := d.Doms[host]; !ok {
continue
}
}
for i := range d.Hours {
h := &d.Hours[i]
if h.Hour == 0 || h.Hour < fh || h.Hour > lh || h.Req == 0 {
continue
}
var o SvcHourOut
o.Hour = h.Hour
o.add(h)
v.Hours = append(v.Hours, o)
v.Tot.add(h)
}
if v.Tot.Req == 0 {
continue
}
sort.Slice(v.Hours, func(a, b int) bool { return v.Hours[a].Hour < v.Hours[b].Hour })
for i := range d.Days {
dd := &d.Days[i]
if dd.Day == 0 || dd.Day < fd || dd.Day > ld {
continue
}
mergeMap(&v.ErrRoutes, dd.ErrRoutes)
mergeMap(&v.Broken, dd.Broken404)
mergeMap(&v.Methods, dd.Methods)
mergeMap(&v.Ciphers, dd.Ciphers)
mergeMap(&v.ProtoCls, dd.ProtoCls)
mergeMap(&v.TLSCls, dd.TLSCls)
for k, t := range dd.Last404 {
if v.BrokenLast == nil {
v.BrokenLast = map[string]int64{}
}
if t > v.BrokenLast[k] {
v.BrokenLast[k] = t
}
}
}
out = append(out, v)
}
sort.Slice(out, func(a, b int) bool {
if out[a].Tot.Req != out[b].Tot.Req {
return out[a].Tot.Req > out[b].Tot.Req
}
return out[a].Key < out[b].Key
})
return out
}
// svcAlias is the most frequent domain of the service, or the key itself.
func svcAlias(key string, d *svcData) string {
best, n := "", uint32(0)
for dom, c := range d.Doms {
if c > n || c == n && dom < best {
best, n = dom, c
}
}
if best == "" || best == "-" {
return key
}
return best
}
// Quantile estimates the q-quantile (0..1) in milliseconds from a latency
// histogram laid out by SvcBounds (linear inside the bucket); 0 when empty.
func Quantile(h [svcLatN]uint32, q float64) float64 {
var tot float64
for _, c := range h {
tot += float64(c)
}
if tot == 0 {
return 0
}
target := q * tot
var acc float64
lo := 0.0
for i, c := range h {
up := SvcBounds[len(SvcBounds)-1] * 2
if i < len(SvcBounds) {
up = SvcBounds[i]
}
if acc+float64(c) >= target && c > 0 {
return lo + (up-lo)*(target-acc)/float64(c)
}
acc += float64(c)
lo = up
}
return lo
}
+95
View File
@@ -0,0 +1,95 @@
package store
import (
"path/filepath"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
)
func svcEv(status, origin int, path, ref string, ago time.Duration) core.Event {
return core.Event{Time: t0.Add(-ago), IP: "200.1.1.1", Cat: core.OK, Source: "traefik", Domain: "app.example.com", Method: "GET", Path: path,
UA: "Mozilla/5.0 x", Status: status, OriginStatus: origin, DurationNS: 40e6, OriginNS: 35e6, OverheadNS: 1e6, Referer: ref,
Router: "https-0-abc-app@docker", Service: "https-0-abc-app@docker", Proto: "HTTP/2.0", Scheme: "https", TLSVer: "1.3", TLSCiph: "TLS_AES_128_GCM_SHA256",
E: core.Enrich{Device: "desktop"}}
}
func TestServicesAggregateAndSnapshot(t *testing.T) {
s := newStore("oracle", 100)
for i := 0; i < 10; i++ {
s.ObserveService(svcEv(200, 200, "/", "", time.Duration(i)*time.Minute))
}
s.ObserveService(svcEv(500, 500, "/api/x/123456789012345678", "", time.Minute))
s.ObserveService(svcEv(404, 404, "/old", "https://app.example.com/home", time.Minute))
s.ObserveService(svcEv(404, 404, "/old", "https://app.example.com/home", time.Minute))
atk := svcEv(404, 404, "/.env", "", time.Minute)
atk.Cat = core.Scanner
s.ObserveService(atk)
s.ObserveService(core.Event{Time: t0, Source: "ssh", IP: "1.1.1.1"}) // ignored
now := t0.Unix()
v := s.Services(now-86400, now, "", "")
if len(v) != 1 || v[0].Key != "https-0-abc-app" || v[0].Alias != "app.example.com" {
t.Fatalf("services %+v", v)
}
tot := v[0].Tot
if tot.Req != 14 || tot.Cls[ClsApp] != 1 || tot.Cls[ClsAttack] != 1 || tot.Cls[ClsClientBroken] != 2 || tot.Legit != 13 {
t.Fatalf("tot %+v", tot)
}
if tot.Proto[1] != 14 || tot.TLS[0] != 14 || tot.ApN == 0 {
t.Fatalf("proto/tls/apdex %+v", tot)
}
if q := Quantile(tot.Dur, 0.5); q < 25 || q > 50 {
t.Fatalf("p50 %v", q)
}
if len(v[0].Broken) != 1 || v[0].ErrRoutes["app|GET /api/x/:id"] != 1 {
t.Fatalf("maps %v %v", v[0].Broken, v[0].ErrRoutes)
}
if got := s.Services(now-86400, now, "nope", ""); len(got) != 0 {
t.Fatal("filter")
}
if got := s.Services(now-86400, now, "", "app.example.com"); len(got) != 1 {
t.Fatal("host filter")
}
path := filepath.Join(t.TempDir(), "snap")
if err := s.Save(path, nil); err != nil {
t.Fatal(err)
}
s2 := newStore("oracle", 100)
if _, err := s2.Load(path); err != nil {
t.Fatal(err)
}
if v2 := s2.Services(now-86400, now, "", ""); len(v2) != 1 || v2[0].Tot.Req != 14 {
t.Fatalf("after load %+v", v2)
}
}
func TestServiceCap(t *testing.T) {
s := newStore("oracle", 100)
for i := 0; i < svcCap+10; i++ {
e := svcEv(200, 200, "/", "", time.Minute)
e.Service = "svc" + string(rune('a'+i%26)) + string(rune('a'+i/26))
s.ObserveService(e)
}
if n := len(s.sv.m); n > svcCap+1 {
t.Fatalf("services %d", n)
}
}
func TestCancelledIsNotServerError(t *testing.T) {
s := newStore("oracle", 100)
for i := 0; i < 5; i++ {
s.ObserveService(svcEv(499, 0, "/x", "", time.Minute))
}
e := svcEv(200, 200, "/", "", time.Minute)
s.ObserveService(e)
run := svcEv(404, 404, "/api/actions/runner.v1.RunnerService/FetchTask", "", time.Minute)
run.Method, run.UA, run.Cat = "POST", "connect-go/1.16", core.Scanner
s.ObserveService(run)
now := t0.Unix()
v := s.Services(now-86400, now, "", "")
tot := v[0].Tot
if tot.Cls[ClsApp] != 0 || tot.Cls[ClsProxy] != 0 || tot.Cls[ClsAttack] != 0 || tot.Cls[ClsClientOther] != 5 || tot.Cls[ClsClientAuth] != 1 {
t.Fatalf("cls %+v", tot.Cls)
}
}
+5 -2
View File
@@ -29,6 +29,8 @@ type snapshot struct {
MonSt [slots]int64
MonN [slots]uint32
Dom map[string]*domData
GDays [anDays]gDay
Svc map[string]*svcData // service health (optional: older snapshots lack it)
IPs map[string]*IPRec
Recent []FeedEvent
Rhead int
@@ -71,7 +73,7 @@ func (s *Store) Save(path string, offsets map[string]Offset) error {
}
bw := bufio.NewWriterSize(f, 256*1024)
s.mu.RLock()
snap := snapshot{V: snapshotVersion, Saved: s.now().Unix(), Stamps: s.stamps, Counts: s.counts, Hours: s.hours, MonSt: s.monSt, MonN: s.monN, Dom: s.tr.dom,
snap := snapshot{V: snapshotVersion, Saved: s.now().Unix(), Stamps: s.stamps, Counts: s.counts, Hours: s.hours, MonSt: s.monSt, MonN: s.monN, Dom: s.tr.dom, GDays: s.tr.gdays, Svc: s.sv.m,
IPs: s.ips, Recent: s.recent, Rhead: s.rhead, Offsets: offsets, IDSeq: s.ids.Load()}
err = gob.NewEncoder(bw).Encode(&snap)
s.mu.RUnlock()
@@ -122,7 +124,8 @@ func (s *Store) Load(path string) (map[string]Offset, error) {
s.mu.Lock()
s.stamps, s.counts, s.hours = snap.Stamps, snap.Counts, snap.Hours
s.monSt, s.monN = snap.MonSt, snap.MonN
s.tr.dom = snap.Dom
s.tr.dom, s.tr.gdays = snap.Dom, snap.GDays
s.sv.m = snap.Svc
for _, d := range s.tr.dom {
if d != nil && d.Last == 0 {
// snapshot written before Last existed: never prune on the first pass
+2
View File
@@ -232,6 +232,7 @@ type Store struct {
monSt [slots]int64
monN [slots]uint32
tr trafficState
sv svcState
allow []string
ips map[string]*IPRec
recent []FeedEvent
@@ -240,6 +241,7 @@ type Store struct {
smu sync.Mutex
subs map[chan FeedEvent]struct{}
vis visitState
rdns RDNS
enr core.Enricher
+169
View File
@@ -0,0 +1,169 @@
package store
import (
"sort"
"strings"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
)
// TechniqueRow is one MITRE ATT&CK technique seen in the window.
type TechniqueRow struct {
ID string `json:"id"`
Name string `json:"name"`
Events int `json:"events"`
IPs int `json:"ips"`
First int64 `json:"first"`
Last int64 `json:"last"`
TrendPct *float64 `json:"trend_pct"` // against the previous window of the same length; null without one
}
// TacticRow groups the techniques of one tactic.
type TacticRow struct {
ID string `json:"id"`
Name string `json:"name"`
Techniques []TechniqueRow `json:"techniques"`
}
// TechniquesOut is the matrix behind GET /api/v1/techniques.
type TechniquesOut struct {
Enabled bool `json:"enabled"`
Truncated bool `json:"truncated,omitempty"`
Tactics []TacticRow `json:"tactics"`
Total int `json:"total"` // events that carry at least one technique
}
type tactic struct{ id, name string }
// ATT&CK enterprise tactics in matrix order.
var tacticOrder = []tactic{
{"TA0043", "Reconnaissance"}, {"TA0042", "Resource Development"}, {"TA0001", "Initial Access"},
{"TA0002", "Execution"}, {"TA0003", "Persistence"}, {"TA0004", "Privilege Escalation"},
{"TA0005", "Defense Evasion"}, {"TA0006", "Credential Access"}, {"TA0007", "Discovery"},
{"TA0008", "Lateral Movement"}, {"TA0009", "Collection"}, {"TA0011", "Command and Control"},
{"TA0010", "Exfiltration"}, {"TA0040", "Impact"},
}
// techTactic maps a technique id to the tactic id the matrix puts it under.
var techTactic = map[string]string{
"T1190": "TA0001", "T1078": "TA0001", "T1133": "TA0001", "T1566": "TA0001",
"T1059": "TA0002", "T1203": "TA0002",
"T1505": "TA0003", "T1098": "TA0003",
"T1110": "TA0006", "T1552": "TA0006", "T1555": "TA0006", "T1528": "TA0006",
"T1083": "TA0007", "T1087": "TA0007", "T1082": "TA0007", "T1046": "TA0007", "T1018": "TA0007",
"T1213": "TA0009", "T1005": "TA0009", "T1530": "TA0009",
"T1595": "TA0043", "T1592": "TA0043", "T1590": "TA0043", "T1589": "TA0043", "T1593": "TA0043",
"T1105": "TA0011", "T1071": "TA0011",
"T1499": "TA0040", "T1498": "TA0040",
}
// TacticOf returns the tactic id of a technique or sub-technique ("" when unknown).
func TacticOf(id string) string {
if t, ok := techTactic[id]; ok {
return t
}
if i := strings.IndexByte(id, '.'); i > 0 {
return techTactic[id[:i]]
}
return ""
}
type techAcc struct {
cur, prev int
ips map[string]struct{}
first, last int64
}
// Techniques groups the techniques observed in [q.From, q.To] by MITRE
// tactic, with the trend against the previous window of the same length.
// Same caps, deadline and 30 s cache as Period.
func (s *Store) Techniques(q PeriodQuery) TechniquesOut {
k := studyKey{kind: "techniques", from: q.From, to: q.To, host: q.Host}
return s.cached(k, func() any { return s.techniques(q) }).(TechniquesOut)
}
func (s *Store) techniques(q PeriodQuery) TechniquesOut {
out := TechniquesOut{Tactics: []TacticRow{}}
if s.elog == nil {
return out
}
out.Enabled = true
span := q.To - q.From
if span < 1 {
span = 1
}
deadline := time.Now().Add(studyDead)
acc := map[string]*techAcc{}
n := 0
info := s.elog.Scan(evlog.Filter{From: q.From - span, 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
}
if len(r.Tech) == 0 {
return true
}
inCur := r.T >= q.From
if inCur {
out.Total++
}
for _, id := range r.Tech {
a := acc[id]
if a == nil {
a = &techAcc{ips: map[string]struct{}{}}
acc[id] = a
}
if !inCur {
a.prev++
continue
}
a.cur++
a.ips[KeyOf(r.IP)] = struct{}{}
if a.first == 0 || r.T < a.first {
a.first = r.T
}
if r.T > a.last {
a.last = r.T
}
}
return true
})
out.Truncated = out.Truncated || info.Truncated
by := map[string][]TechniqueRow{}
for id, a := range acc {
if a.cur == 0 {
continue
}
name := intel.TechniqueName(id)
if name == "" {
name = id
}
row := TechniqueRow{ID: id, Name: name, Events: a.cur, IPs: len(a.ips), First: a.first, Last: a.last}
if a.prev > 0 {
v := float64(a.cur-a.prev) / float64(a.prev) * 100
row.TrendPct = &v
}
by[TacticOf(id)] = append(by[TacticOf(id)], row)
}
add := func(t tactic) {
rows := by[t.id]
if len(rows) == 0 {
return
}
sort.Slice(rows, func(i, j int) bool {
if rows[i].Events != rows[j].Events {
return rows[i].Events > rows[j].Events
}
return rows[i].ID < rows[j].ID
})
out.Tactics = append(out.Tactics, TacticRow{ID: t.id, Name: t.name, Techniques: rows})
}
for _, t := range tacticOrder {
add(t)
}
add(tactic{"", "Other"})
return out
}
+196 -40
View File
@@ -11,10 +11,19 @@ import (
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
)
// Privacy: legitimate visitors are never stored. A visitor is the 64-bit
// prefix of SHA-256(salt | ip | user-agent | domain) kept in memory only while
// its UTC day lasts; the salt is random per process and per day, so hashes
// cannot be linked across days, and nothing here reaches a snapshot or the API.
// Privacy: visitors are never stored. A visitor is the 64-bit prefix of
// SHA-256(salt | ip | domain) (SHA-256(salt | ip) for the all-domains total)
// kept in memory only while its UTC day lasts; the salt is random per process
// and per day, so hashes cannot be linked across days, and nothing here
// reaches a snapshot or the API.
//
// A visitor is a person with a real browser: a GET 2xx of a document by a
// browser User-Agent (not a bot, tool or unknown client), not a prefetch and,
// when the browser says so, with Sec-Fetch-Dest "document". The key leaves the
// User-Agent out on purpose: scrapers rotate it per request from one address
// (a measured 2.7x inflation), a person's browser does not. Everything else
// that talks to a site (bots, tools, unknown or empty User-Agents) is counted
// apart as non-human clients.
const (
anMinutes = 49 * 60 // minute buckets (48 h plus one hour of margin)
@@ -38,7 +47,7 @@ type anHour struct {
type anDay struct {
Day int64
Visitors uint32
Visitors, NonHuman uint32
Pages, Refs, Countries, Cities, Browsers, OSes, Devices, Bots map[string]uint32
}
@@ -51,13 +60,24 @@ type domData struct {
Last int64 // unix time of the last request, for pruning idle domains
// in memory only, never in a snapshot (unexported fields are skipped by gob)
vis map[uint64]struct{}
nh map[uint64]struct{}
visDay int64
}
// gDay is the all-domains daily total: one person on two sites counts once.
type gDay struct {
Day int64
Visitors, NonHuman uint32
}
type trafficState struct {
dom map[string]*domData
gdays [anDays]gDay
salt [16]byte
saltDay int64
// in memory only
gvis, gnh map[uint64]struct{}
gvisDay int64
}
var assetExt = map[string]bool{
@@ -67,8 +87,33 @@ var assetExt = map[string]bool{
"zip": true, "gz": true, "wasm": true, "bmp": true, "webmanifest": true, "rss": true, "atom": true,
}
// isHuman reports whether the User-Agent belongs to a real browser.
func isHuman(e core.Enrich) bool {
if e.Bot || e.Tool {
return false
}
switch e.Device {
case "desktop", "mobile", "tablet":
return true
}
return false
}
func isAssetPath(p string) bool {
if i := strings.IndexAny(p, "?#"); i >= 0 {
p = p[:i]
}
i := strings.LastIndexByte(p, '.')
return i >= 0 && i > strings.LastIndexByte(p, '/') && assetExt[strings.ToLower(p[i+1:])]
}
func isPageView(ev core.Event) bool {
if ev.Method != "GET" || ev.Status < 200 || ev.Status > 299 {
if ev.Method != "GET" || ev.Status < 200 || ev.Status > 299 || ev.Prefetch {
return false
}
// A browser that says what it is fetching: only a navigation is a page
// (fetch/XHR is "empty", frames "iframe"). No header: cannot tell, accept.
if d := ev.FetchDest; d != "" && d != "document" {
return false
}
p := ev.Path
@@ -170,15 +215,59 @@ func (s *Store) domLocked(name string, status int) *domData {
var uuidRe = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`)
// readableSlug reports a human URL slug: lowercase words and numbers joined by
// "-" (blog-post-title-2024). Those are kept even when long.
func readableSlug(s string) bool {
for _, word := range strings.Split(s, "-") {
if word == "" || len(word) > 16 {
return false
}
for _, r := range word {
if !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9') {
return false
}
}
}
return true
}
// mixedToken reports the shape of a token or opaque identifier: letters and
// "-_." only, and either digits mixed with letters, mixed case, or "_"/".".
func mixedToken(s string) bool {
var lower, upper, digits, punct bool
for _, r := range s {
switch {
case r >= '0' && r <= '9':
digits = true
case r >= 'a' && r <= 'z':
lower = true
case r >= 'A' && r <= 'Z':
upper = true
case r == '_' || r == '.':
punct = true
case r == '-':
default:
return false
}
}
letters := lower || upper
return letters && (digits || (lower && upper) || punct)
}
// normalizePath turns token-like path segments (UUIDs, long hex or mixed
// alphanumeric ids, long numbers) into ":id" so a top-pages list is not
// filled by one-off URLs and a token in a URL is not kept.
func normalizePath(p string) string {
if !strings.ContainsAny(p, "0123456789") {
return p
}
parts := strings.Split(p, "/")
for i, seg := range parts {
// personal or secret-looking segments: e-mail addresses, long opaque
// values, and mixed letter+digit tokens (reset links, invites, ids)
if strings.Contains(seg, "@") || len(seg) >= 48 ||
(len(seg) >= 24 && !readableSlug(seg)) ||
(len(seg) >= 12 && !readableSlug(seg) && mixedToken(seg)) {
parts[i] = ":id"
continue
}
if len(seg) >= 16 && uuidRe.MatchString(seg) {
parts[i] = ":id"
continue
@@ -233,6 +322,9 @@ func (s *Store) Traffic(ev core.Event) {
return
}
d.Last = ts
if !isAssetPath(ev.Path) {
s.emitVisit(ts, dom, ev.Path, ev.IP, ev.Status, ev.E.Device, ev.E.Bot, ev.E.Tool)
}
m := ts / 60
mi := int(m % anMinutes)
@@ -259,13 +351,54 @@ func (s *Store) Traffic(ev core.Event) {
if dd.Day != day {
*dd = anDay{Day: day}
}
if ev.E.Bot {
hs.Bots++
name := ev.E.BotName
if name == "" {
name = "bot"
// per-day hash state (the salt changes every UTC day)
if s.tr.saltDay != day {
rand.Read(s.tr.salt[:])
s.tr.saltDay = day
}
fresh := d.visDay == day && d.vis != nil
if !fresh {
if day < d.visDay {
fresh = false // older than the day being counted (out of order)
} else {
d.vis, d.nh, d.visDay = make(map[uint64]struct{}, 64), make(map[uint64]struct{}, 16), day
fresh = true
}
}
gfresh := s.tr.gvisDay == day && s.tr.gvis != nil
if !gfresh && day >= s.tr.gvisDay {
s.tr.gvis, s.tr.gnh, s.tr.gvisDay = make(map[uint64]struct{}, 256), make(map[uint64]struct{}, 64), day
gfresh = true
}
gd := &s.tr.gdays[int(day%anDays)]
if gd.Day != day {
*gd = gDay{Day: day}
}
kd, kg := s.visitorKey(ev.IP, dom), s.visitorKey(ev.IP, "")
human := isHuman(ev.E)
if !human {
// bots, tools, unknown or empty User-Agents: never a visitor or a page
if ev.E.Bot {
hs.Bots++
name := ev.E.BotName
if name == "" {
name = "bot"
}
bumpCap(&dd.Bots, name, anTop)
}
if fresh {
if _, seen := d.nh[kd]; !seen && len(d.nh) < visCap {
d.nh[kd] = struct{}{}
dd.NonHuman++
}
}
if gfresh {
if _, seen := s.tr.gnh[kg]; !seen && len(s.tr.gnh) < visCap*4 {
s.tr.gnh[kg] = struct{}{}
gd.NonHuman++
}
}
bumpCap(&dd.Bots, name, anTop)
return
}
if !isPageView(ev) {
@@ -280,34 +413,19 @@ func (s *Store) Traffic(ev core.Event) {
bumpCap(&dd.Pages, normalizePath(p), anTop)
bumpCap(&dd.Refs, refHost(ev.Referer, dom), anTop)
// unique visitor, today's salt
if s.tr.saltDay != day {
rand.Read(s.tr.salt[:])
s.tr.saltDay = day
}
if d.visDay != day || d.vis == nil {
if day < d.visDay {
return // older than the day being counted (out of order): no visitor accounting
if gfresh {
if _, seen := s.tr.gvis[kg]; !seen && len(s.tr.gvis) < visCap*4 {
s.tr.gvis[kg] = struct{}{}
gd.Visitors++
}
d.vis, d.visDay = make(map[uint64]struct{}, 64), day
}
hsum := sha256.New()
hsum.Write(s.tr.salt[:])
hsum.Write([]byte(ev.IP))
hsum.Write([]byte{0})
hsum.Write([]byte(ev.UA))
hsum.Write([]byte{0})
hsum.Write([]byte(dom))
var sum [32]byte
hsum.Sum(sum[:0])
var key uint64
for i := 0; i < 8; i++ {
key = key<<8 | uint64(sum[i])
}
if _, seen := d.vis[key]; seen || len(d.vis) >= visCap {
if !fresh {
return
}
d.vis[key] = struct{}{}
if _, seen := d.vis[kd]; seen || len(d.vis) >= visCap {
return
}
d.vis[kd] = struct{}{}
dd.Visitors++
if ev.E.CC != "" {
bumpCap(&dd.Countries, ev.E.CC, 300)
@@ -324,6 +442,22 @@ func (s *Store) Traffic(ev core.Event) {
bumpCap(&dd.Devices, orUnknown(ev.E.Device), 10)
}
// visitorKey is the 64-bit prefix of SHA-256(salt | ip | domain) with today's salt.
func (s *Store) visitorKey(ip, dom string) uint64 {
h := sha256.New()
h.Write(s.tr.salt[:])
h.Write([]byte(ip))
h.Write([]byte{0})
h.Write([]byte(dom))
var sum [32]byte
h.Sum(sum[:0])
var key uint64
for i := 0; i < 8; i++ {
key = key<<8 | uint64(sum[i])
}
return key
}
func max64(a, b int64) int64 {
if a > b {
return a
@@ -348,6 +482,7 @@ type TrafficData struct {
Requests uint64 `json:"requests"`
Pages uint64 `json:"pages"`
Visitors uint64 `json:"visitors"`
NonHuman uint64 `json:"nonhuman"` // distinct non-human clients (bots, tools, unknown), apart from visitors
Bots uint64 `json:"bots"`
Bytes uint64 `json:"bytes"`
Status [4]uint64 `json:"status"`
@@ -422,6 +557,7 @@ func (s *Store) TrafficFor(rg Range, domain string) TrafficData {
firstDay, lastDay := from/86400, to/86400
maps := [8]map[string]uint32{{}, {}, {}, {}, {}, {}, {}, {}}
domReq := map[string]uint32{}
domVis, domNH := map[int64]uint64{}, map[int64]uint64{}
s.mu.RLock()
for name, d := range s.tr.dom {
@@ -475,7 +611,8 @@ func (s *Store) TrafficFor(rg Range, domain string) TrafficData {
if dd.Day == 0 || dd.Day < firstDay || dd.Day > lastDay {
continue
}
out.Visitors += uint64(dd.Visitors)
domVis[dd.Day] += uint64(dd.Visitors)
domNH[dd.Day] += uint64(dd.NonHuman)
for k, src := range [8]map[string]uint32{dd.Pages, dd.Refs, dd.Countries, dd.Cities, dd.Browsers, dd.OSes, dd.Devices, dd.Bots} {
for key, v := range src {
maps[k][key] += v
@@ -483,6 +620,24 @@ func (s *Store) TrafficFor(rg Range, domain string) TrafficData {
}
}
}
if out.Domain == "all" {
// all domains: a person (or bot) seen on two sites the same day counts once
for day := firstDay; day <= lastDay; day++ {
gd := s.tr.gdays[int(day%anDays)]
if gd.Day == day {
out.Visitors += uint64(gd.Visitors)
out.NonHuman += uint64(gd.NonHuman)
} else { // day recorded before the global total existed
out.Visitors += domVis[day]
out.NonHuman += domNH[day]
}
}
} else {
for day := firstDay; day <= lastDay; day++ {
out.Visitors += domVis[day]
out.NonHuman += domNH[day]
}
}
s.mu.RUnlock()
for name, n := range domReq {
@@ -520,6 +675,7 @@ func MergeTraffic(host string, parts []TrafficData) TrafficData {
out.Requests += p.Requests
out.Pages += p.Pages
out.Visitors += p.Visitors
out.NonHuman += p.NonHuman
out.Bots += p.Bots
out.Bytes += p.Bytes
for i := range p.Status {
+148
View File
@@ -141,3 +141,151 @@ func TestToolBonusAndCountries(t *testing.T) {
t.Fatalf("countries %+v", c)
}
}
func browser(ip, dom, path string) core.Event {
return visit(ip, dom, path, "", 200, time.Minute)
}
func TestVisitorsAreRealBrowsersCountedByAddress(t *testing.T) {
s := newStore("oracle", 100)
// a scraper rotating the User-Agent from one address is one visitor, not five
for i := 0; i < 5; i++ {
ev := browser("200.100.50.30", "a.example", "/p")
ev.UA = "Mozilla/5.0 rotating " + string(rune('a'+i))
s.Traffic(ev)
}
// the same person on two sites counts once in the all-domains total
s.Traffic(browser("200.100.50.31", "a.example", "/"))
s.Traffic(browser("200.100.50.31", "b.example", "/"))
// fetch/XHR, prefetch, HEAD: not pages, not visitors
api := browser("200.100.50.32", "a.example", "/api/v1/summary")
api.FetchDest = "empty"
s.Traffic(api)
pre := browser("200.100.50.33", "a.example", "/next")
pre.Prefetch = true
s.Traffic(pre)
head := browser("200.100.50.34", "a.example", "/")
head.Method = "HEAD"
s.Traffic(head)
doc := browser("200.100.50.35", "a.example", "/doc")
doc.FetchDest = "document"
s.Traffic(doc)
// tools, unknown and empty User-Agents, and bots: non-human clients
for i, e := range []core.Enrich{
{Device: "tool", Tool: true}, {Device: "unknown"}, {}, {Bot: true, BotName: "Googlebot", Device: "bot"},
} {
ev := browser("66.249.66."+string(rune('1'+i)), "a.example", "/")
ev.E = e
s.Traffic(ev)
}
other := browser("66.249.66.1", "b.example", "/") // same bot on a second site
other.E = core.Enrich{Bot: true, Device: "bot"}
s.Traffic(other)
all := s.TrafficSummary("24h", "all")
if all.Visitors != 3 { // .30, .31, .35
t.Fatalf("all visitors = %d, want 3", all.Visitors)
}
if all.NonHuman != 4 { // four distinct addresses; the bot seen on two sites counts once
t.Fatalf("all non-human = %d, want 4", all.NonHuman)
}
if a := s.TrafficSummary("24h", "a.example"); a.Visitors != 3 || a.NonHuman != 4 || a.Pages != 7 {
t.Fatalf("a.example: visitors=%d nonhuman=%d pages=%d", a.Visitors, a.NonHuman, a.Pages)
}
if b := s.TrafficSummary("24h", "b.example"); b.Visitors != 1 || b.NonHuman != 1 {
t.Fatalf("b.example: visitors=%d nonhuman=%d", b.Visitors, b.NonHuman)
}
}
func TestNonHumanSurvivesSnapshotAndMerge(t *testing.T) {
s := newStore("oracle", 100)
bot := browser("66.249.66.9", "a.example", "/")
bot.E = core.Enrich{Device: "tool", Tool: true}
s.Traffic(bot)
s.Traffic(browser("200.100.50.40", "a.example", "/"))
a := s.TrafficSummary("24h", "all")
m := MergeTraffic("all", []TrafficData{a, a})
if a.NonHuman != 1 || a.Visitors != 1 || m.NonHuman != 2 || m.Visitors != 2 {
t.Fatalf("a=%+v m=%+v", a, m)
}
}
type visGeo struct{}
func (visGeo) Geo(ip string) core.GeoInfo {
return core.GeoInfo{CC: "BR", City: "Recife", Lat: -8.0476, Lon: -34.877}
}
func (visGeo) UA(string) core.UAInfo { return core.UAInfo{} }
func TestVisitEventsHaveNoAddressAndAreRateLimited(t *testing.T) {
s := newStore("oracle", 100)
s.SetEnricher(visGeo{})
// without subscribers nothing is built or kept
s.Traffic(browser("200.100.50.60", "a.example", "/x"))
ch, stop := s.SubscribeVisits()
defer stop()
ev := browser("200.100.50.61", "a.example", "/u/123e4567-e89b-12d3-a456-426614174000?token=secret")
ev.Referer = "https://ref.example/?q=1"
s.Traffic(ev)
asset := browser("200.100.50.61", "a.example", "/s.css")
s.Traffic(asset) // assets are not visits
m := <-ch
b, _ := json.Marshal(m)
for _, bad := range []string{"200.100.50", `"ip"`, "Mozilla", "ref.example", "secret", "123e4567"} {
if bytes.Contains(b, []byte(bad)) {
t.Fatalf("visit leaks %q: %s", bad, b)
}
}
if m.Kind != "visit" || m.Host != "oracle" || m.Domain != "a.example" || m.Device != "desktop" || m.Status != 200 ||
m.Path != "/u/:id" || m.Src == nil || m.Src.Lat != -8.0 || m.Src.Lon != -34.9 || m.Src.CC != "BR" {
t.Fatalf("visit %s", b)
}
select {
case x := <-ch:
t.Fatalf("unexpected extra event %+v", x)
default:
}
// 50 in one second: 20 pass (the first already used 1), the rest is dropped, then a batch
for i := 0; i < 50; i++ {
s.Traffic(browser("200.100.50.62", "a.example", "/p"))
}
s.now = func() time.Time { return t0.Add(time.Hour) }
late := browser("200.100.50.63", "a.example", "/p")
late.Time = t0.Add(time.Hour)
s.Traffic(late)
visits, batch := 0, 0
for len(ch) > 0 {
x := <-ch
bb, _ := json.Marshal(x)
if bytes.Contains(bb, []byte(`"ip"`)) {
t.Fatalf("ip in %s", bb)
}
switch x.Kind {
case "visit":
visits++
case "visit_batch":
batch += x.N
}
}
if visits != 20 || batch != 31 { // 19 left of the first second + 1 new second; 31 dropped
t.Fatalf("visits=%d dropped=%d", visits, batch)
}
}
func TestVisitSanitizeFromPeer(t *testing.T) {
m := VisitMsg{Kind: "visit", T: 1, Domain: "d", Path: "/a\x01b", Device: "<x>", Src: &GeoPoint{Lat: 500}}
if !m.Sanitize(t0.Unix()) || m.Device != "unknown" || m.Src != nil || m.Path != "/ab" {
t.Fatalf("%+v", m)
}
if (&VisitMsg{Kind: "ev"}).Sanitize(1) {
t.Fatal("unknown kind accepted")
}
var raw map[string]any
json.Unmarshal([]byte(`{"kind":"visit","ip":"1.2.3.4"}`), &raw)
var v VisitMsg
json.Unmarshal([]byte(`{"kind":"visit","ip":"1.2.3.4"}`), &v)
b, _ := json.Marshal(v)
if bytes.Contains(b, []byte("1.2.3.4")) {
t.Fatal("ip survived a round trip")
}
}
+145
View File
@@ -0,0 +1,145 @@
package store
import (
"math"
"strings"
"sync"
)
// Live legitimate visits. Privacy: a visit event carries NO address, User-Agent
// or referrer; the source is the aggregated geography of the city (coordinates
// rounded to one decimal, about 11 km). It is only broadcast to subscribers
// (SSE ?visits=1), never written to the event log, a snapshot or live/recent.
// visitRate is the ceiling of visit events per second and instance; the excess
// is dropped and summarised by one visit_batch per second.
const visitRate = 20
// VisitMsg is a "visit" (one request) or a "visit_batch" (n dropped).
type VisitMsg struct {
Kind string `json:"kind"`
T int64 `json:"t"`
N int `json:"n,omitempty"`
Host string `json:"host,omitempty"`
Domain string `json:"domain,omitempty"`
Path string `json:"path,omitempty"`
Status int `json:"status,omitempty"`
Device string `json:"device,omitempty"`
Src *GeoPoint `json:"src,omitempty"`
Dst *Location `json:"dst,omitempty"`
}
type visitState struct {
mu sync.Mutex
subs map[chan VisitMsg]struct{}
sec int64
sent int
dropped int
}
// SubscribeVisits returns the live visit events of this instance.
func (s *Store) SubscribeVisits() (<-chan VisitMsg, func()) {
ch := make(chan VisitMsg, 64)
s.vis.mu.Lock()
if s.vis.subs == nil {
s.vis.subs = map[chan VisitMsg]struct{}{}
}
s.vis.subs[ch] = struct{}{}
s.vis.mu.Unlock()
return ch, func() {
s.vis.mu.Lock()
delete(s.vis.subs, ch)
s.vis.mu.Unlock()
}
}
func roundCoord(v float64) float64 { return math.Round(v*10) / 10 }
var visitDevices = map[string]bool{"desktop": true, "mobile": true, "tablet": true, "bot": true, "tool": true}
func visitPath(p string) string {
if i := strings.IndexAny(p, "?#"); i >= 0 {
p = p[:i]
}
return clipS(normalizePath(p), 120)
}
// emitVisit broadcasts one legitimate request to the visit subscribers.
// Called with s.mu held; it never blocks and costs nothing without subscribers.
func (s *Store) emitVisit(ts int64, dom, path, ip string, status int, device string, bot, tool bool) {
v := &s.vis
v.mu.Lock()
defer v.mu.Unlock()
if len(v.subs) == 0 {
return
}
if ts != v.sec {
if v.dropped > 0 {
s.fanVisit(VisitMsg{Kind: "visit_batch", T: v.sec, N: v.dropped, Host: s.cfg.Name})
}
v.sec, v.sent, v.dropped = ts, 0, 0
}
if v.sent >= visitRate {
v.dropped++
return
}
v.sent++
switch {
case bot:
device = "bot"
case tool:
device = "tool"
case !visitDevices[device]:
device = "unknown"
}
m := VisitMsg{Kind: "visit", T: ts, Host: s.cfg.Name, Domain: clipS(dom, 100), Path: visitPath(path), Status: status, Device: device, Dst: s.Location()}
if g := s.GeoOf(ip); (g.Lat != 0 || g.Lon != 0) && validLatLon(g.Lat, g.Lon) {
m.Src = &GeoPoint{Lat: roundCoord(g.Lat), Lon: roundCoord(g.Lon), CC: validCC2(g.CC), City: clipS(g.City, 80)}
}
s.fanVisit(m)
}
func (s *Store) fanVisit(m VisitMsg) {
for ch := range s.vis.subs {
select {
case ch <- m:
default: // slow client: drop
}
}
}
// Sanitize validates a visit event received from a peer (it has no address
// field, and anything unknown is dropped); false means: discard it.
func (m *VisitMsg) Sanitize(now int64) bool {
if m.Kind != "visit" && m.Kind != "visit_batch" {
return false
}
if m.T <= 0 || m.T > now+300 || m.T < now-3600 {
m.T = now
}
if m.Kind == "visit_batch" {
if m.N < 0 || m.N > 1<<20 {
return false
}
*m = VisitMsg{Kind: m.Kind, T: m.T, N: m.N}
return true
}
m.N = 0
// a peer's visit path is normalized again here: never trust it to have done so
m.Domain, m.Path = clipS(m.Domain, 100), clipS(normalizePath(m.Path), 120)
if m.Status < 0 || m.Status > 999 {
m.Status = 0
}
if !visitDevices[m.Device] {
m.Device = "unknown"
}
if m.Src != nil {
if !validLatLon(m.Src.Lat, m.Src.Lon) {
m.Src = nil
} else {
m.Src = &GeoPoint{Lat: roundCoord(m.Src.Lat), Lon: roundCoord(m.Src.Lon), CC: validCC2(clipS(m.Src.CC, 2)), City: clipS(m.Src.City, 80)}
}
}
m.Dst = sanitizeLocation(m.Dst)
return true
}