Files
urutau/internal/store/traffic.go
T
Lucas RayanandClaude Opus 5.5 b4a2c2c9ec
Release / Plan (reuse the published image?) (push) Successful in 4s
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 1m29s
CI / Tests (Linux, race detector) (push) Failing after 1m48s
CI / Dependency audit (push) Successful in 21s
Release / ci (push) Failing after 1m50s
Release / Build image (amd64) (push) Skipped
Release / Build image (arm64) (push) Skipped
Release / Publish tags (push) Skipped
Release / Gitea release (push) Skipped
feat: Urutau 1.0.0, lightweight threat intelligence and web analytics
Always-on Go service (stdlib only) that follows the Traefik JSON access
log, the sshd log and the fail2ban log of a host, classifies attacks,
scores sources, keeps bounded aggregates with snapshots, and serves an
embedded dashboard with live updates, offline geolocation (DB-IP Lite),
privacy-friendly traffic analytics, an exportable blocklist and
token-authenticated federation between instances.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 16:13:34 -03:00

555 lines
15 KiB
Go

package store
import (
"crypto/rand"
"crypto/sha256"
"net/url"
"regexp"
"sort"
"strings"
"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.
const (
anMinutes = 24 * 60
maxDomains = 24
visCap = 20000
anTop = 40
latN = 12
otherDom = "(other)"
)
var latBounds = [latN - 1]float64{5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000}
type anHour struct {
Hour int64
Req, Pages, Bots uint32
Bytes uint64
S [4]uint32 // 2xx 3xx 4xx 5xx
Lat [latN]uint32
}
type anDay struct {
Day int64
Visitors uint32
Pages, Refs, Countries, Cities, Browsers, OSes, Devices, Bots map[string]uint32
}
type domData struct {
MinSt [anMinutes]int64
MinReq [anMinutes]uint32
MinPages [anMinutes]uint32
Hours [hourSlots]anHour
Days [8]anDay
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{}
visDay int64
}
type trafficState struct {
dom map[string]*domData
salt [16]byte
saltDay int64
}
var assetExt = map[string]bool{
"js": true, "mjs": true, "css": true, "png": true, "jpg": true, "jpeg": true, "gif": true, "svg": true, "ico": true,
"webp": true, "avif": true, "woff": true, "woff2": true, "ttf": true, "otf": true, "eot": true, "map": true,
"json": true, "xml": true, "txt": true, "mp4": true, "webm": true, "mp3": true, "ogg": true, "pdf": true,
"zip": true, "gz": true, "wasm": true, "bmp": true, "webmanifest": true, "rss": true, "atom": true,
}
func isPageView(ev core.Event) bool {
if ev.Method != "GET" || ev.Status < 200 || ev.Status > 299 {
return false
}
p := ev.Path
if i := strings.IndexAny(p, "?#"); i >= 0 {
p = p[:i]
}
if i := strings.LastIndexByte(p, '.'); i >= 0 && i > strings.LastIndexByte(p, '/') {
return !assetExt[strings.ToLower(p[i+1:])]
}
return true
}
func normDomain(d string) string {
d = strings.ToLower(strings.TrimSpace(d))
if i := strings.LastIndexByte(d, ':'); i > 0 && !strings.Contains(d[i:], "]") {
d = d[:i]
}
if d == "" {
return "-"
}
return d
}
func refHost(ref, domain string) string {
if ref == "" || ref == "-" {
return ""
}
u, err := url.Parse(ref)
if err != nil || u.Host == "" {
return ""
}
h := strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.")
if h == "" || h == domain || h == strings.TrimPrefix(domain, "www.") || strings.HasSuffix(h, "."+strings.TrimPrefix(domain, "www.")) {
return ""
}
return h
}
func latBucket(ns int64) int {
ms := float64(ns) / 1e6
for i, b := range latBounds {
if ms <= b {
return i
}
}
return latN - 1
}
// SetDomains restricts the analytics to these domains (exact names, or
// "*.example.com" for a whole subtree). Empty means: any domain that has
// answered a request successfully.
func (s *Store) SetDomains(list []string) {
s.mu.Lock()
defer s.mu.Unlock()
s.allow = nil
for _, d := range list {
if d = strings.ToLower(strings.TrimSpace(d)); d != "" {
s.allow = append(s.allow, d)
}
}
}
func (s *Store) domainAllowed(name string) bool {
if len(s.allow) == 0 {
return true
}
for _, a := range s.allow {
if a == name || strings.HasPrefix(a, "*.") && strings.HasSuffix(name, a[1:]) {
return true
}
}
return false
}
// domLocked returns the slot of a domain. A new slot is only opened for a
// domain that has served a 2xx: Host headers sent by scanners (random names
// answered with 404, or with the catch-all http->https 301) cannot take slots
// from real sites.
func (s *Store) domLocked(name string, status int) *domData {
if s.tr.dom == nil {
s.tr.dom = map[string]*domData{}
}
if d := s.tr.dom[name]; d != nil {
return d
}
if status < 200 || status > 299 || !s.domainAllowed(name) {
return nil
}
if len(s.tr.dom) >= maxDomains {
name = otherDom
if d := s.tr.dom[name]; d != nil {
return d
}
}
d := &domData{}
s.tr.dom[name] = d
return d
}
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}$`)
// 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 {
if len(seg) >= 16 && uuidRe.MatchString(seg) {
parts[i] = ":id"
continue
}
if len(seg) >= 16 && !strings.ContainsAny(seg, "-_.") && strings.ContainsAny(seg, "0123456789") && alnum(seg) {
parts[i] = ":id"
continue
}
if len(seg) >= 8 && allDigits(seg) {
parts[i] = ":id"
}
}
return strings.Join(parts, "/")
}
func alnum(s string) bool {
for _, r := range s {
if !(r >= '0' && r <= '9' || r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z') {
return false
}
}
return true
}
func allDigits(s string) bool {
for _, r := range s {
if r < '0' || r > '9' {
return false
}
}
return true
}
// Traffic records one legitimate request (category ok or notfound) for the
// analytics view. Attack traffic, monitoring probes and forged monitors must
// not be passed here.
func (s *Store) Traffic(ev core.Event) {
now := s.now()
if ev.Time.Before(now.Add(-s.cfg.Retention)) || ev.Source != "traefik" {
return
}
ts := ev.Time.Unix()
if max := now.Unix() + 300; ts > max {
ts = max
}
dom := normDomain(ev.Domain)
day := ts / 86400
s.mu.Lock()
defer s.mu.Unlock()
d := s.domLocked(dom, ev.Status)
if d == nil {
return
}
d.Last = ts
m := ts / 60
mi := int(m % anMinutes)
if d.MinSt[mi] != m {
d.MinSt[mi], d.MinReq[mi], d.MinPages[mi] = m, 0, 0
}
d.MinReq[mi]++
h := ts / 3600
hs := &d.Hours[int(h%hourSlots)]
if hs.Hour != h {
*hs = anHour{Hour: h}
}
hs.Req++
hs.Bytes += uint64(max64(ev.Bytes, 0))
if c := ev.Status/100 - 2; c >= 0 && c < 4 {
hs.S[c]++
}
if ev.DurationNS > 0 {
hs.Lat[latBucket(ev.DurationNS)]++
}
dd := &d.Days[int(day%8)]
if dd.Day != day {
*dd = anDay{Day: day}
}
if ev.E.Bot {
hs.Bots++
name := ev.E.BotName
if name == "" {
name = "bot"
}
bumpCap(&dd.Bots, name, anTop)
return
}
if !isPageView(ev) {
return
}
hs.Pages++
d.MinPages[mi]++
p := ev.Path
if i := strings.IndexAny(p, "?#"); i >= 0 {
p = p[:i]
}
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
}
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 {
return
}
d.vis[key] = struct{}{}
dd.Visitors++
if ev.E.CC != "" {
bumpCap(&dd.Countries, ev.E.CC, 300)
}
if ev.E.City != "" {
city := ev.E.City
if ev.E.CC != "" {
city += ", " + ev.E.CC
}
bumpCap(&dd.Cities, city, anTop)
}
bumpCap(&dd.Browsers, orUnknown(ev.E.Browser), anTop)
bumpCap(&dd.OSes, orUnknown(ev.E.OS), anTop)
bumpCap(&dd.Devices, orUnknown(ev.E.Device), 10)
}
func max64(a, b int64) int64 {
if a > b {
return a
}
return b
}
func orUnknown(s string) string {
if s == "" {
return "unknown"
}
return s
}
// TrafficData is the mergeable analytics payload.
type TrafficData struct {
Host string `json:"host"`
Range string `json:"range"`
Domain string `json:"domain"`
Generated int64 `json:"generated"`
Domains []Count `json:"domains"`
Requests uint64 `json:"requests"`
Pages uint64 `json:"pages"`
Visitors uint64 `json:"visitors"`
Bots uint64 `json:"bots"`
Bytes uint64 `json:"bytes"`
Status [4]uint64 `json:"status"`
Lat [latN]uint64 `json:"lat"`
P50 float64 `json:"p50_ms"`
P95 float64 `json:"p95_ms"`
Timeline struct {
Start int64 `json:"start"`
Step int64 `json:"step"`
Req []uint32 `json:"req"`
Pages []uint32 `json:"pages"`
} `json:"timeline"`
TopPages []Count `json:"top_pages"`
Referrers []Count `json:"referrers"`
Countries []Count `json:"countries"`
Cities []Count `json:"cities"`
Browsers []Count `json:"browsers"`
OSes []Count `json:"oses"`
Devices []Count `json:"devices"`
BotNames []Count `json:"bot_names"`
}
func quantile(h [latN]uint64, q float64) float64 {
var total uint64
for _, v := range h {
total += v
}
if total == 0 {
return 0
}
target := q * float64(total)
var cum float64
lower := 0.0
for i, v := range h {
upper := 20000.0
if i < len(latBounds) {
upper = latBounds[i]
}
if cum+float64(v) >= target && v > 0 {
return lower + (upper-lower)*(target-cum)/float64(v)
}
cum += float64(v)
lower = upper
}
return lower
}
// Finish recomputes derived values (percentiles) after a merge.
func (t *TrafficData) Finish() {
t.P50, t.P95 = round1(quantile(t.Lat, 0.5)), round1(quantile(t.Lat, 0.95))
}
// Traffic returns the analytics of one domain ("" or "all": every domain).
func (s *Store) TrafficSummary(rangeName, domain string) TrafficData {
rg := ParseRange(rangeName)
now := s.now().Unix()
out := TrafficData{Host: s.cfg.Name, Range: rg.Name, Domain: domain, Generated: now}
if out.Domain == "" {
out.Domain = "all"
}
// timeline grid
var nb int
var step int64
switch rg.Name {
case "1h":
nb, step = 60, 60
case "24h":
nb, step = 96, 900
default:
nb, step = 168, 3600
}
endB := now / step
start := (endB - int64(nb) + 1) * step
out.Timeline.Start, out.Timeline.Step = start, step
out.Timeline.Req, out.Timeline.Pages = make([]uint32, nb), make([]uint32, nb)
firstHour := (now - int64(rg.Dur.Seconds())) / 3600
firstDay := (now - int64(rg.Dur.Seconds())) / 86400
maps := [8]map[string]uint32{{}, {}, {}, {}, {}, {}, {}, {}}
domReq := map[string]uint32{}
s.mu.RLock()
for name, d := range s.tr.dom {
var reqRange uint32
for i := range d.Hours {
h := &d.Hours[i]
if h.Hour == 0 || h.Hour < firstHour || h.Hour > now/3600+1 {
continue
}
reqRange += h.Req
if out.Domain != "all" && out.Domain != name {
continue
}
if rg.Name == "7d" {
out.Requests += uint64(h.Req)
out.Pages += uint64(h.Pages)
if b := (h.Hour*3600 - start) / step; b >= 0 && b < int64(nb) {
out.Timeline.Req[b] += h.Req
out.Timeline.Pages[b] += h.Pages
}
}
out.Bots += uint64(h.Bots)
out.Bytes += h.Bytes
for k, v := range h.S {
out.Status[k] += uint64(v)
}
for k, v := range h.Lat {
out.Lat[k] += uint64(v)
}
}
domReq[name] = reqRange
if out.Domain != "all" && out.Domain != name {
continue
}
if rg.Name != "7d" {
for m := start / 60; m <= now/60; m++ {
i := int(m % anMinutes)
if d.MinSt[i] != m {
continue
}
out.Requests += uint64(d.MinReq[i])
out.Pages += uint64(d.MinPages[i])
if b := (m*60 - start) / step; b >= 0 && b < int64(nb) {
out.Timeline.Req[b] += d.MinReq[i]
out.Timeline.Pages[b] += d.MinPages[i]
}
}
}
for i := range d.Days {
dd := &d.Days[i]
if dd.Day == 0 || dd.Day < firstDay || dd.Day > now/86400 {
continue
}
out.Visitors += uint64(dd.Visitors)
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
}
}
}
}
s.mu.RUnlock()
for name, n := range domReq {
if n > 0 {
out.Domains = append(out.Domains, Count{Key: name, N: n})
}
}
sort.Slice(out.Domains, func(i, j int) bool {
if out.Domains[i].N != out.Domains[j].N {
return out.Domains[i].N > out.Domains[j].N
}
return out.Domains[i].Key < out.Domains[j].Key
})
out.TopPages, out.Referrers, out.Countries, out.Cities = topN(maps[0], anTop), topN(maps[1], anTop), topN(maps[2], 120), topN(maps[3], anTop)
out.Browsers, out.OSes, out.Devices, out.BotNames = topN(maps[4], anTop), topN(maps[5], anTop), topN(maps[6], 10), topN(maps[7], anTop)
// Visitors come from daily buckets, pages from exact minutes: never report more visitors than page views.
if out.Visitors > out.Pages {
out.Visitors = out.Pages
}
out.Finish()
return out
}
// MergeTraffic combines per-host analytics of the same range and domain.
func MergeTraffic(host string, parts []TrafficData) TrafficData {
if len(parts) == 0 {
return TrafficData{Host: host}
}
out := TrafficData{Host: host, Range: parts[0].Range, Domain: parts[0].Domain, Generated: parts[0].Generated}
out.Timeline.Start, out.Timeline.Step = parts[0].Timeline.Start, parts[0].Timeline.Step
nb := len(parts[0].Timeline.Req)
out.Timeline.Req, out.Timeline.Pages = make([]uint32, nb), make([]uint32, nb)
var doms, pages, refs, ctry, cities, br, oses, dev, bots [][]Count
for _, p := range parts {
out.Requests += p.Requests
out.Pages += p.Pages
out.Visitors += p.Visitors
out.Bots += p.Bots
out.Bytes += p.Bytes
for i := range p.Status {
out.Status[i] += p.Status[i]
}
for i := range p.Lat {
out.Lat[i] += p.Lat[i]
}
if p.Timeline.Step == out.Timeline.Step && out.Timeline.Step > 0 {
shift := (p.Timeline.Start - out.Timeline.Start) / out.Timeline.Step
for i := range p.Timeline.Req {
if j := int64(i) + shift; j >= 0 && j < int64(nb) {
out.Timeline.Req[j] += p.Timeline.Req[i]
out.Timeline.Pages[j] += p.Timeline.Pages[i]
}
}
}
doms, pages, refs = append(doms, p.Domains), append(pages, p.TopPages), append(refs, p.Referrers)
ctry, cities, br = append(ctry, p.Countries), append(cities, p.Cities), append(br, p.Browsers)
oses, dev, bots = append(oses, p.OSes), append(dev, p.Devices), append(bots, p.BotNames)
}
out.Domains, out.TopPages, out.Referrers = mergeCounts(maxDomains+1, doms...), mergeCounts(anTop, pages...), mergeCounts(anTop, refs...)
out.Countries, out.Cities, out.Browsers = mergeCounts(120, ctry...), mergeCounts(anTop, cities...), mergeCounts(anTop, br...)
out.OSes, out.Devices, out.BotNames = mergeCounts(anTop, oses...), mergeCounts(10, dev...), mergeCounts(anTop, bots...)
out.Finish()
return out
}