Release / Publish tags (push) Successful in 18s
Release / Plan (reuse the published image?) (push) Successful in 5s
Release / ci (push) Successful in 1m47s
Release / Build image (amd64) (push) Successful in 21s
Release / Build image (arm64) (push) Successful in 28s
CI / Format and vet (push) Successful in 23s
CI / Tests (Linux, race detector) (push) Successful in 1m24s
CI / Dependency audit (push) Successful in 24s
CI / Docker image (build and smoke test) (push) Skipped
Release / Gitea release (push) Successful in 5s
Backend pagination with one pager for sessions, IPs, campaigns and events; network probe source (port-scan, T1046, second firewall reason port-scan); host kit logs inbound probes; urutau call on the report cover. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
543 lines
15 KiB
Go
543 lines
15 KiB
Go
package store
|
|
|
|
import (
|
|
"sort"
|
|
"time"
|
|
|
|
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
|
)
|
|
|
|
// Count is one top-list row.
|
|
type Count struct {
|
|
Key string `json:"key"`
|
|
N uint32 `json:"n"`
|
|
Label string `json:"label,omitempty"`
|
|
}
|
|
|
|
// Timeline holds per-category counters on a fixed grid.
|
|
type Timeline struct {
|
|
Start int64 `json:"start"`
|
|
Step int64 `json:"step"`
|
|
Cats []string `json:"cats"`
|
|
Series map[string][]uint32 `json:"series"`
|
|
}
|
|
|
|
// Totals are the headline numbers.
|
|
type Totals struct {
|
|
Requests uint64 `json:"requests"`
|
|
Malicious uint64 `json:"malicious"`
|
|
HostileIPs int `json:"hostile_ips"`
|
|
SuspiciousIPs int `json:"suspicious_ips"`
|
|
UniqueIPs int `json:"unique_ips"`
|
|
ActiveBans int `json:"active_bans"`
|
|
Monitoring uint64 `json:"monitoring"`
|
|
Counts map[string]uint64 `json:"counts"`
|
|
}
|
|
|
|
// IPSummary describes one IP. Samples, UAs and Domains are only filled in the
|
|
// detail view and in federation exchanges.
|
|
type IPSummary struct {
|
|
IP string `json:"ip"`
|
|
Score float64 `json:"score"`
|
|
Level core.Level `json:"level"`
|
|
Counts map[string]uint32 `json:"counts"`
|
|
Hosts []string `json:"hosts"`
|
|
Domains []string `json:"domains,omitempty"`
|
|
Samples []string `json:"samples,omitempty"`
|
|
UAs []string `json:"uas,omitempty"`
|
|
First int64 `json:"first"`
|
|
Last int64 `json:"last"`
|
|
Banned bool `json:"banned"`
|
|
Jails []string `json:"jails,omitempty"`
|
|
RDNS string `json:"rdns,omitempty"`
|
|
Strong bool `json:"strong,omitempty"`
|
|
Admin bool `json:"admin,omitempty"`
|
|
CC string `json:"cc,omitempty"`
|
|
Country string `json:"country,omitempty"`
|
|
City string `json:"city,omitempty"`
|
|
ASN uint32 `json:"asn,omitempty"`
|
|
ASOrg string `json:"as_org,omitempty"`
|
|
UALabels []string `json:"ua_labels,omitempty"`
|
|
}
|
|
|
|
// SourceStatus reports one log source.
|
|
type SourceStatus struct {
|
|
Host string `json:"host,omitempty"`
|
|
Name string `json:"name"`
|
|
Path string `json:"path"`
|
|
State string `json:"state"` // following, waiting, backfill, error, disabled
|
|
Lines uint64 `json:"lines"`
|
|
Malformed uint64 `json:"malformed"`
|
|
LastEvent int64 `json:"last_event"`
|
|
Error string `json:"error,omitempty"`
|
|
}
|
|
|
|
// HostInfo is the per-instance card.
|
|
type HostInfo struct {
|
|
Name string `json:"name"`
|
|
Self bool `json:"self"`
|
|
Online bool `json:"online"`
|
|
Version string `json:"version,omitempty"`
|
|
Error string `json:"error,omitempty"`
|
|
LastSeen int64 `json:"last_seen"`
|
|
Requests uint64 `json:"requests"`
|
|
Malicious uint64 `json:"malicious"`
|
|
HostileIPs int `json:"hostile_ips"`
|
|
ActiveBans int `json:"active_bans"`
|
|
LatencyMS int64 `json:"latency_ms,omitempty"`
|
|
// Live: this instance is streaming events (always true for the local one).
|
|
Live bool `json:"live"`
|
|
Location *Location `json:"location,omitempty"`
|
|
}
|
|
|
|
// Summary is the mergeable dashboard payload.
|
|
type Summary struct {
|
|
Version string `json:"version"`
|
|
Host string `json:"host"`
|
|
Range RangeInfo `json:"range"`
|
|
Generated int64 `json:"generated"`
|
|
Hosts []HostInfo `json:"hosts"`
|
|
Totals Totals `json:"totals"`
|
|
Timeline Timeline `json:"timeline"`
|
|
Rates Rates `json:"rates"`
|
|
IPs []IPSummary `json:"ips"`
|
|
TopPaths []Count `json:"top_paths"`
|
|
TopDomains []Count `json:"top_domains"`
|
|
TopUAs []Count `json:"top_uas"`
|
|
TopUsers []Count `json:"top_users"`
|
|
Countries []Count `json:"countries"`
|
|
Recent []FeedEvent `json:"recent"`
|
|
Sources []SourceStatus `json:"sources"`
|
|
Attribution string `json:"attribution,omitempty"`
|
|
}
|
|
|
|
// PeakHour is the busiest hour of a window.
|
|
type PeakHour struct {
|
|
T int64 `json:"t"`
|
|
N uint32 `json:"n"`
|
|
}
|
|
|
|
// Rates are the stable headline rates: counts of malicious events, per hour
|
|
// (never per minute), independent of the chart granularity.
|
|
type Rates struct {
|
|
Last15m uint64 `json:"last15m"`
|
|
Last1h uint64 `json:"last1h"`
|
|
Last24h uint64 `json:"last24h"`
|
|
PerHourAvg24h float64 `json:"per_hour_avg_24h"`
|
|
PerHourAvg7d float64 `json:"per_hour_avg_7d"`
|
|
PrevPeriod uint64 `json:"prev_period"`
|
|
ChangePct *float64 `json:"change_pct"` // null when there is no comparable previous period
|
|
PeakHour PeakHour `json:"peak_hour"`
|
|
NewAttackers int `json:"new_attackers"`
|
|
ActiveAttackers int `json:"active_attackers"`
|
|
}
|
|
|
|
const (
|
|
summaryIPs = 500
|
|
topKeep = 50
|
|
)
|
|
|
|
func catStrings() []string {
|
|
out := make([]string, len(core.Categories))
|
|
for i, c := range core.Categories {
|
|
out[i] = string(c)
|
|
}
|
|
return out
|
|
}
|
|
|
|
func attackKinds(c [core.NumCats]uint32) int {
|
|
n := 0
|
|
for _, cat := range []core.Category{core.Scanner, core.Exploit, core.BruteForce, core.SSHFail, core.SSHProbe} {
|
|
if c[cat.Index()] > 0 {
|
|
n++
|
|
}
|
|
}
|
|
return n
|
|
}
|
|
|
|
// rowOf builds the output row of one table entry.
|
|
func (s *Store) rowOf(ip string, r *IPRec, detail bool) IPSummary {
|
|
cm := make(map[string]uint32, 4)
|
|
for i, n := range r.Counts {
|
|
if n > 0 {
|
|
cm[string(core.Categories[i])] = n
|
|
}
|
|
}
|
|
strong := r.Strong || attackKinds(r.Counts) >= 2
|
|
admin := r.adminAt(s.now().Unix())
|
|
out := IPSummary{IP: ip, Score: round1(r.Score), Level: core.LevelOf(r.Score, strong, admin), Counts: cm, Hosts: []string{s.cfg.Name},
|
|
First: r.First, Last: r.Last, Banned: len(r.Jails) > 0, Strong: strong, Admin: admin}
|
|
if len(r.Jails) > 0 {
|
|
out.Jails = append([]string(nil), r.Jails...)
|
|
}
|
|
if detail {
|
|
out.Domains = append([]string(nil), r.Domains...)
|
|
out.Samples = append([]string(nil), r.Samples...)
|
|
out.UAs = append([]string(nil), r.UAs...)
|
|
}
|
|
return out
|
|
}
|
|
|
|
func round1(f float64) float64 { return float64(int64(f*10+0.5)) / 10 }
|
|
|
|
// AllIPs returns every IP seen inside the range, highest score first.
|
|
func (s *Store) AllIPs(rg Range, detail bool) []IPSummary {
|
|
from, to := rg.bounds(s.now().Unix())
|
|
s.mu.RLock()
|
|
out := make([]IPSummary, 0, len(s.ips))
|
|
for ip, r := range s.ips {
|
|
if r.Last >= from && r.First <= to {
|
|
out = append(out, s.rowOf(ip, r, detail))
|
|
}
|
|
}
|
|
s.mu.RUnlock()
|
|
SortIPs(out, "score", true)
|
|
return out
|
|
}
|
|
|
|
// SortIPs orders in place by key (score, last, first, events, ip).
|
|
func SortIPs(l []IPSummary, key string, desc bool) {
|
|
ev := func(x IPSummary) uint32 {
|
|
var n uint32
|
|
for _, v := range x.Counts {
|
|
n += v
|
|
}
|
|
return n
|
|
}
|
|
less := func(a, b IPSummary) bool {
|
|
switch key {
|
|
case "last":
|
|
return a.Last < b.Last
|
|
case "first":
|
|
return a.First < b.First
|
|
case "events":
|
|
return ev(a) < ev(b)
|
|
case "ip":
|
|
return a.IP < b.IP
|
|
}
|
|
if a.Score != b.Score {
|
|
return a.Score < b.Score
|
|
}
|
|
return a.Last < b.Last
|
|
}
|
|
sort.SliceStable(l, func(i, j int) bool {
|
|
a, b := l[i], l[j]
|
|
if lt, gt := less(a, b), less(b, a); lt || gt { // equal keys fall back to the address: pages never shuffle
|
|
return lt != desc
|
|
}
|
|
return a.IP < b.IP
|
|
})
|
|
}
|
|
|
|
// IP returns the detail of one address.
|
|
func (s *Store) IP(ip string) (IPSummary, bool) {
|
|
ip = KeyOf(ip)
|
|
s.mu.RLock()
|
|
r := s.ips[ip]
|
|
var out IPSummary
|
|
if r != nil {
|
|
out = s.rowOf(ip, r, true)
|
|
}
|
|
s.mu.RUnlock()
|
|
if r == nil {
|
|
return IPSummary{}, false
|
|
}
|
|
if s.rdns != nil {
|
|
out.RDNS = s.rdns.Lookup(ip)
|
|
}
|
|
s.Enrich(&out)
|
|
for _, ua := range out.UAs {
|
|
if l := s.UALabel(ua); l != "" {
|
|
out.UALabels = append(out.UALabels, l)
|
|
}
|
|
}
|
|
return out, true
|
|
}
|
|
|
|
func topN(m map[string]uint32, n int) []Count {
|
|
out := make([]Count, 0, len(m))
|
|
for k, v := range m {
|
|
out = append(out, Count{Key: k, N: v})
|
|
}
|
|
sort.Slice(out, func(i, j int) bool {
|
|
if out[i].N != out[j].N {
|
|
return out[i].N > out[j].N
|
|
}
|
|
return out[i].Key < out[j].Key
|
|
})
|
|
if len(out) > n {
|
|
out = out[:n]
|
|
}
|
|
return out
|
|
}
|
|
|
|
// Summary builds the local summary for a named range.
|
|
func (s *Store) Summary(rangeName string) Summary { return s.SummaryFor(ParseRange(rangeName)) }
|
|
|
|
// SummaryFor builds the local summary for a window (cached for two seconds).
|
|
func (s *Store) SummaryFor(rg Range) Summary {
|
|
key := rg.Key()
|
|
s.cacheMu.Lock()
|
|
if c, ok := s.cache[key]; ok && time.Since(c.at) < 2*time.Second {
|
|
s.cacheMu.Unlock()
|
|
return c.s
|
|
}
|
|
s.cacheMu.Unlock()
|
|
sum := s.buildSummary(rg)
|
|
s.cacheMu.Lock()
|
|
if len(s.cache) >= 64 {
|
|
s.cache = map[string]cachedSummary{}
|
|
}
|
|
s.cache[key] = cachedSummary{time.Now(), sum}
|
|
s.cacheMu.Unlock()
|
|
return sum
|
|
}
|
|
|
|
var malIdx = func() []int {
|
|
var l []int
|
|
for i, c := range core.Categories {
|
|
if c.IsMalicious() {
|
|
l = append(l, i)
|
|
}
|
|
}
|
|
return l
|
|
}()
|
|
|
|
func malOf(c [core.NumCats]uint32) uint64 {
|
|
var n uint64
|
|
for _, i := range malIdx {
|
|
n += uint64(c[i])
|
|
}
|
|
return n
|
|
}
|
|
|
|
// malLocked counts malicious events in [a, b): minute buckets when the window
|
|
// is within the last 48 h, hour buckets otherwise (edge hours count whole).
|
|
func (s *Store) malLocked(a, b, nowU int64) uint64 {
|
|
if a < 0 {
|
|
a = 0
|
|
}
|
|
if b <= a {
|
|
return 0
|
|
}
|
|
var n uint64
|
|
if a >= nowU-int64(minuteKeep/time.Second) {
|
|
for m := a / 60; m <= (b-1)/60; m++ {
|
|
if i := int(m % slots); s.stamps[i] == m {
|
|
n += malOf(s.counts[i])
|
|
}
|
|
}
|
|
return n
|
|
}
|
|
for h := a / 3600; h <= (b-1)/3600; h++ {
|
|
if hs := &s.hours[int(h%hourSlots)]; hs.Hour == h {
|
|
n += malOf(hs.C)
|
|
}
|
|
}
|
|
return n
|
|
}
|
|
|
|
func avg1(n uint64, hours float64) float64 { return round1(float64(n) / hours) }
|
|
|
|
func isAttacker(r *IPRec) bool { return malOf(r.Counts) > 0 || r.Counts[core.Ban.Index()] > 0 }
|
|
|
|
// PeakOf finds the busiest hour in a timeline (malicious categories only).
|
|
func PeakOf(tl Timeline) PeakHour {
|
|
byHour := map[int64]uint32{}
|
|
for i := range tl.Series[string(core.Scanner)] {
|
|
var n uint32
|
|
for _, ci := range malIdx {
|
|
if sr := tl.Series[string(core.Categories[ci])]; i < len(sr) {
|
|
n += sr[i]
|
|
}
|
|
}
|
|
byHour[(tl.Start+int64(i)*tl.Step)/3600] += n
|
|
}
|
|
var best PeakHour
|
|
for h, n := range byHour {
|
|
if n > best.N || n == best.N && n > 0 && h*3600 < best.T {
|
|
best = PeakHour{T: h * 3600, N: n}
|
|
}
|
|
}
|
|
return best
|
|
}
|
|
|
|
func pct(cur, prev uint64) *float64 {
|
|
if prev == 0 {
|
|
return nil
|
|
}
|
|
v := round1((float64(cur) - float64(prev)) / float64(prev) * 100)
|
|
return &v
|
|
}
|
|
|
|
func (s *Store) buildSummary(rg Range) Summary {
|
|
now := s.now()
|
|
nowU := now.Unix()
|
|
cats := catStrings()
|
|
from, to := rg.bounds(nowU)
|
|
g := rg.grid(nowU)
|
|
nb, start := g.N, g.Start
|
|
tl := Timeline{Start: start, Step: g.Step, Cats: cats, Series: make(map[string][]uint32, len(cats))}
|
|
for _, c := range cats {
|
|
tl.Series[c] = make([]uint32, nb)
|
|
}
|
|
tot := Totals{Counts: map[string]uint64{}}
|
|
var rates Rates
|
|
|
|
add := func(b int, counts [core.NumCats]uint32) {
|
|
for ci, n := range counts {
|
|
if n == 0 {
|
|
continue
|
|
}
|
|
tl.Series[cats[ci]][b] += n
|
|
tot.Counts[cats[ci]] += uint64(n)
|
|
c := core.Categories[ci]
|
|
if c.IsHTTP() {
|
|
tot.Requests += uint64(n)
|
|
}
|
|
if c.IsMalicious() {
|
|
tot.Malicious += uint64(n)
|
|
}
|
|
}
|
|
}
|
|
s.mu.RLock()
|
|
if g.minute() {
|
|
for m := start / 60; m <= to/60; m++ {
|
|
i := int(m % slots)
|
|
if s.stamps[i] != m {
|
|
continue
|
|
}
|
|
if b := int((m*60 - start) / g.Step); b >= 0 && b < nb {
|
|
add(b, s.counts[i])
|
|
}
|
|
}
|
|
for m := start / 60; m <= to/60; m++ {
|
|
if i := int(m % slots); s.monSt[i] == m {
|
|
tot.Monitoring += uint64(s.monN[i])
|
|
}
|
|
}
|
|
} else {
|
|
for h := start / 3600; h <= to/3600; h++ {
|
|
hs := &s.hours[int(h%hourSlots)]
|
|
if hs.Hour != h {
|
|
continue
|
|
}
|
|
if b := int(h - start/3600); b >= 0 && b < nb {
|
|
add(b, hs.C)
|
|
}
|
|
tot.Monitoring += uint64(hs.Mon)
|
|
}
|
|
}
|
|
paths, doms, uas, users, ctry := map[string]uint32{}, map[string]uint32{}, map[string]uint32{}, map[string]uint32{}, map[string]uint32{}
|
|
firstHour, lastHour := start/3600, to/3600
|
|
for i := range s.hours {
|
|
h := &s.hours[i]
|
|
if h.Hour == 0 || h.Hour < firstHour || h.Hour > lastHour {
|
|
continue
|
|
}
|
|
for _, p := range [...]struct {
|
|
from map[string]uint32
|
|
to map[string]uint32
|
|
}{{h.Paths, paths}, {h.Domains, doms}, {h.UAs, uas}, {h.Users, users}, {h.Countries, ctry}} {
|
|
for k, v := range p.from {
|
|
p.to[k] += v
|
|
}
|
|
}
|
|
}
|
|
ips := make([]IPSummary, 0, 1024)
|
|
for ip, r := range s.ips {
|
|
if len(r.Jails) > 0 {
|
|
tot.ActiveBans++
|
|
}
|
|
if r.Last < from || r.First > to {
|
|
continue
|
|
}
|
|
tot.UniqueIPs++
|
|
if isAttacker(r) {
|
|
rates.ActiveAttackers++
|
|
if r.First >= from {
|
|
rates.NewAttackers++
|
|
}
|
|
}
|
|
row := s.rowOf(ip, r, true)
|
|
switch row.Level {
|
|
case core.LevelHostile:
|
|
tot.HostileIPs++
|
|
case core.LevelSuspicious:
|
|
tot.SuspiciousIPs++
|
|
}
|
|
if r.Score >= 1 || len(r.Jails) > 0 {
|
|
ips = append(ips, row)
|
|
}
|
|
}
|
|
rates.Last15m = s.malLocked(nowU-900, nowU+1, nowU)
|
|
rates.Last1h = s.malLocked(nowU-3600, nowU+1, nowU)
|
|
rates.Last24h = s.malLocked(nowU-86400, nowU+1, nowU)
|
|
rates.PerHourAvg24h = avg1(rates.Last24h, 24)
|
|
rates.PerHourAvg7d = avg1(s.malLocked(nowU-7*86400, nowU+1, nowU), 7*24)
|
|
if span := to - from; from-span >= nowU-int64(s.cfg.Retention/time.Second) {
|
|
rates.PrevPeriod = s.malLocked(from-span, from, nowU)
|
|
rates.ChangePct = pct(tot.Malicious, rates.PrevPeriod)
|
|
}
|
|
rates.PeakHour = PeakOf(tl)
|
|
recent := s.recentLocked(60)
|
|
s.mu.RUnlock()
|
|
|
|
SortIPs(ips, "score", true)
|
|
if len(ips) > summaryIPs {
|
|
ips = ips[:summaryIPs]
|
|
}
|
|
if s.enr != nil {
|
|
for i := range ips {
|
|
s.Enrich(&ips[i])
|
|
for _, ua := range ips[i].UAs {
|
|
if l := s.UALabel(ua); l != "" {
|
|
ips[i].UALabels = append(ips[i].UALabels, l)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
topUAs := topN(uas, topKeep)
|
|
for i := range topUAs {
|
|
topUAs[i].Label = s.UALabel(topUAs[i].Key)
|
|
}
|
|
if s.rdns != nil {
|
|
for i := range ips {
|
|
if i >= 25 {
|
|
break
|
|
}
|
|
ips[i].RDNS = s.rdns.Lookup(ips[i].IP)
|
|
}
|
|
}
|
|
var srcs []SourceStatus
|
|
if s.sources != nil {
|
|
srcs = s.sources()
|
|
for i := range srcs {
|
|
srcs[i].Host = s.cfg.Name
|
|
srcs[i].Path = "" // never leak host paths to the dashboard or to peers
|
|
}
|
|
}
|
|
return Summary{
|
|
Version: s.cfg.Version, Host: s.cfg.Name, Range: rg.Info(nowU), Generated: nowU,
|
|
Hosts: []HostInfo{{Name: s.cfg.Name, Self: true, Online: true, Version: s.cfg.Version, LastSeen: nowU,
|
|
Requests: tot.Requests, Malicious: tot.Malicious, HostileIPs: tot.HostileIPs, ActiveBans: tot.ActiveBans,
|
|
Live: true, Location: s.Location()}},
|
|
Totals: tot, Timeline: tl, Rates: rates, IPs: ips,
|
|
TopPaths: topN(paths, topKeep), TopDomains: topN(doms, topKeep), TopUAs: topUAs, TopUsers: topN(users, topKeep), Countries: topN(ctry, 120),
|
|
Recent: recent, Sources: srcs, Attribution: s.attrib,
|
|
}
|
|
}
|
|
|
|
func (s *Store) recentLocked(n int) []FeedEvent {
|
|
total := len(s.recent)
|
|
out := make([]FeedEvent, 0, n)
|
|
for i := 0; i < total && len(out) < n; i++ {
|
|
idx := (s.rhead - 1 - i) % total
|
|
if idx < 0 {
|
|
idx += total
|
|
}
|
|
out = append(out, s.recent[idx])
|
|
}
|
|
return out
|
|
}
|