Files
urutau/internal/ingress/agg.go
T
Lucas RayanandClaude Sonnet 5.5 aefdcea8d2 feat(ingress): firewall telemetry of inbound attempts (host kit --ingress)
Observation-only nftables table (prerouting -150, counters and a
rate-limited log, never drops or modifies), a per-minute counters file,
probe sources ingress and ingresscnt, a per-host hourly aggregate in the
hub (exact totals, sampled ports/ASNs/countries, banned share by the
hub's own ban state, no ban feedback loop), GET /api/v1/ingress, a
Defense section, doctor check, docs EN/pt-BR and tests.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 09:09:16 -03:00

530 lines
13 KiB
Go

package ingress
import (
"encoding/json"
"errors"
"os"
"sort"
"strconv"
"strings"
"sync"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
// Bounds that keep the memory of one host fixed (30 days of hourly buckets,
// each with capped top lists).
const (
Retention = 30 * 24 * time.Hour
maxPorts = 48
maxASNs = 48
maxCCs = 64
maxOrgLen = 80
maxDelta = 1 << 40 // per-minute counter delta beyond this is a corrupt line
maxFileLen = 64 << 20
)
type asnRec struct {
Org string `json:"o,omitempty"`
N uint32 `json:"n"`
}
// bucket is one hour. The exact totals come from the counters; Logged and the
// top lists come from the sampled log lines.
type bucket struct {
Total uint64 `json:"t"`
TCP uint64 `json:"tcp"`
UDP uint64 `json:"udp"`
ICMP uint64 `json:"icmp"`
Open uint64 `json:"open"`
Logged uint32 `json:"l"`
// of the sample: to a served port, from a source banned at that moment
LoggedOpen uint32 `json:"lo"`
LoggedBanned uint32 `json:"lb"`
Ports map[string]uint32 `json:"ports,omitempty"` // "tcp/22/c": proto, port, c(losed)|o(pen)
ASNs map[string]*asnRec `json:"asns,omitempty"` // "AS16509"
CCs map[string]uint32 `json:"ccs,omitempty"`
}
// Agg aggregates one host. Banned and Geo are injected by the hub wiring, so
// this package knows nothing about the store.
type Agg struct {
// Banned reports whether the address is banned by a jail right now.
Banned func(ip string) bool
// Geo returns the country code, "AS<number>" and the organization.
Geo func(ip string) (cc, asn, org string)
Now func() time.Time
mu sync.Mutex
hours map[int64]*bucket // unix hour
prev *Counters
dirty bool
lines uint64
counts uint64
bad uint64
lastLine int64 // unix seconds of the last accepted sampled line (by arrival)
lastCnt int64 // ts of the last accepted counters line
}
func New() *Agg {
return &Agg{hours: map[int64]*bucket{}, Now: time.Now}
}
func hourOf(ts int64) int64 { return ts - ts%3600 }
func (a *Agg) bucketLocked(h int64) *bucket {
b := a.hours[h]
if b == nil {
b = &bucket{}
a.hours[h] = b
}
return b
}
func (a *Agg) validTime(ts int64) bool {
now := a.Now().Unix()
return ts <= now+3600 && ts >= now-int64(Retention/time.Second)
}
// Ingest applies one line of a probe source (wire.SrcIngress or
// wire.SrcIngressCnt). It never panics on hostile input and never has an
// effect outside this aggregate.
func (a *Agg) Ingest(src string, line []byte) {
defer func() { _ = recover() }()
switch src {
case wire.SrcIngressCnt:
a.ingestCounters(line)
case wire.SrcIngress:
a.ingestHit(line)
}
}
func (a *Agg) ingestCounters(line []byte) {
c, err := ParseCounters(line)
a.mu.Lock()
defer a.mu.Unlock()
if err != nil || !a.validTime(c.TS) {
a.bad++
return
}
a.counts++
a.lastCnt = max(a.lastCnt, c.TS)
p := a.prev
cur := c
a.prev = &cur
a.dirty = true
if p == nil || c.TS <= p.TS {
return // first line (no baseline) or not newer: no delta
}
d := Counters{TS: c.TS, Total: c.Total - p.Total, TCP: c.TCP - p.TCP, UDP: c.UDP - p.UDP, ICMP: c.ICMP - p.ICMP, Open: c.Open - p.Open}
if c.Total < p.Total || c.TCP < p.TCP || c.UDP < p.UDP || c.ICMP < p.ICMP || c.Open < p.Open {
// the table was reloaded (or the host rebooted): the counters restarted
d = Counters{TS: c.TS, Total: c.Total, TCP: c.TCP, UDP: c.UDP, ICMP: c.ICMP, Open: c.Open}
}
if d.Total > maxDelta || d.TCP > maxDelta || d.UDP > maxDelta || d.ICMP > maxDelta || d.Open > maxDelta {
a.bad++
return
}
b := a.bucketLocked(hourOf(c.TS))
b.Total += d.Total
b.TCP += d.TCP
b.UDP += d.UDP
b.ICMP += d.ICMP
b.Open += d.Open
a.pruneLocked()
}
func (a *Agg) ingestHit(line []byte) {
h, err := ParseHit(line, a.Now())
a.mu.Lock()
if err != nil {
if !errors.Is(err, ErrNotIngress) {
a.bad++
}
a.mu.Unlock()
return
}
if !a.validTime(h.Time.Unix()) {
a.bad++
a.mu.Unlock()
return
}
a.mu.Unlock()
ip := h.Src.String()
// the callbacks run outside the lock: the store takes its own
banned := a.Banned != nil && a.Banned(ip)
var cc, asn, org string
if a.Geo != nil {
cc, asn, org = a.Geo(ip)
}
a.mu.Lock()
defer a.mu.Unlock()
a.lines++
a.lastLine = a.Now().Unix()
a.dirty = true
b := a.bucketLocked(hourOf(h.Time.Unix()))
b.Logged++
if h.Open {
b.LoggedOpen++
}
if banned {
b.LoggedBanned++
}
if h.DPort != 0 {
k := h.Proto + "/" + strconv.Itoa(int(h.DPort)) + "/c"
if h.Open {
k = h.Proto + "/" + strconv.Itoa(int(h.DPort)) + "/o"
}
if b.Ports == nil {
b.Ports = map[string]uint32{}
}
if _, ok := b.Ports[k]; ok || len(b.Ports) < maxPorts {
b.Ports[k]++
}
}
if len(asn) > 0 && len(asn) <= 12 {
if b.ASNs == nil {
b.ASNs = map[string]*asnRec{}
}
if r, ok := b.ASNs[asn]; ok {
r.N++
} else if len(b.ASNs) < maxASNs {
if len(org) > maxOrgLen {
org = org[:maxOrgLen]
}
b.ASNs[asn] = &asnRec{Org: toValid(org), N: 1}
}
}
if len(cc) == 2 {
if b.CCs == nil {
b.CCs = map[string]uint32{}
}
if _, ok := b.CCs[cc]; ok || len(b.CCs) < maxCCs {
b.CCs[cc]++
}
}
a.pruneLocked()
}
func toValid(s string) string {
out := make([]rune, 0, len(s))
for _, r := range s {
if r >= 0x20 && r != 0x7f && r != 0xFFFD {
out = append(out, r)
}
}
return string(out)
}
func (a *Agg) pruneLocked() {
cut := hourOf(a.Now().Unix() - int64(Retention/time.Second))
for h := range a.hours {
if h < cut {
delete(a.hours, h)
}
}
}
// ---- report ----
type Source struct {
State string `json:"state"` // waiting|following
LastCounters int64 `json:"last_counters"`
LastLine int64 `json:"last_line"`
Lines uint64 `json:"lines"`
Counters uint64 `json:"counter_lines"`
Malformed uint64 `json:"malformed"`
}
type Totals struct {
Attempts uint64 `json:"attempts"` // exact
TCP uint64 `json:"tcp"`
UDP uint64 `json:"udp"`
ICMP uint64 `json:"icmp"`
Open uint64 `json:"open"` // to a port the host serves (tcp+udp)
Closed uint64 `json:"closed"` // to a port nothing serves (tcp+udp)
ClosedPct float64 `json:"closed_pct"`
PerHour float64 `json:"per_hour"` // exact, over the hours covered by counters
}
type Sample struct {
Logged uint64 `json:"logged"`
LoggedBanned uint64 `json:"logged_banned"`
Ratio float64 `json:"ratio"` // logged / exact attempts: how much of the total the details cover
BannedPct float64 `json:"banned_pct"` // of the sample, from sources banned at that moment
BannedEst uint64 `json:"banned_est"` // BannedPct applied to the exact total (an estimate)
}
type Hour struct {
T int64 `json:"t"`
Total uint64 `json:"total"`
Open uint64 `json:"open"`
Closed uint64 `json:"closed"`
Logged uint32 `json:"logged"`
}
type PortRow struct {
Proto string `json:"proto"`
Port uint16 `json:"port"`
N uint64 `json:"n"` // in the sample
Served bool `json:"served"`
Pct float64 `json:"pct"`
}
type ASNRow struct {
ASN string `json:"asn"`
Org string `json:"org,omitempty"`
N uint64 `json:"n"`
Pct float64 `json:"pct"`
}
type CCRow struct {
CC string `json:"cc"`
N uint64 `json:"n"`
Pct float64 `json:"pct"`
}
// Report is what GET /api/v1/ingress returns for one host and window.
type Report struct {
Enabled bool `json:"enabled"`
From int64 `json:"from"`
To int64 `json:"to"`
Source Source `json:"source"`
Totals Totals `json:"totals"`
Sample Sample `json:"sample"`
Hourly []Hour `json:"hourly"`
Ports []PortRow `json:"ports"`
ASNs []ASNRow `json:"asns"`
CCs []CCRow `json:"countries"`
}
const topN = 15
func pct(n, d uint64) float64 {
if d == 0 {
return 0
}
return float64(int(float64(n)/float64(d)*1000+0.5)) / 10
}
func (a *Agg) Info() Source {
a.mu.Lock()
defer a.mu.Unlock()
return a.infoLocked()
}
func (a *Agg) infoLocked() Source {
s := Source{State: "waiting", LastCounters: a.lastCnt, LastLine: a.lastLine, Lines: a.lines, Counters: a.counts, Malformed: a.bad}
if a.counts > 0 || a.lines > 0 {
s.State = "following"
}
return s
}
// Report builds the report of [from, to) (unix seconds) of one host.
func (a *Agg) Report(from, to int64) Report { return ReportOf([]*Agg{a}, from, to) }
// ReportOf builds one report over several hosts (the "all hosts" view): the
// exact totals add up, the sampled lists are merged before the top is taken.
func ReportOf(aggs []*Agg, from, to int64) Report {
r := Report{From: from, To: to, Source: Source{State: "waiting"}, Hourly: []Hour{}, Ports: []PortRow{}, ASNs: []ASNRow{}, CCs: []CCRow{}}
ports := map[string]uint64{}
asns := map[string]*ASNRow{}
ccs := map[string]uint64{}
hours := map[int64]*Hour{}
var hoursWithCounters int
for _, a := range aggs {
if a == nil {
continue
}
a.mu.Lock()
si := a.infoLocked()
if si.State == "following" {
r.Source.State = "following"
}
r.Source.LastCounters, r.Source.LastLine = max(r.Source.LastCounters, si.LastCounters), max(r.Source.LastLine, si.LastLine)
r.Source.Lines += si.Lines
r.Source.Counters += si.Counters
r.Source.Malformed += si.Malformed
for h, b := range a.hours {
if h+3600 <= from || h >= to {
continue
}
r.Totals.Attempts += b.Total
r.Totals.TCP += b.TCP
r.Totals.UDP += b.UDP
r.Totals.ICMP += b.ICMP
r.Totals.Open += b.Open
r.Sample.Logged += uint64(b.Logged)
r.Sample.LoggedBanned += uint64(b.LoggedBanned)
row := hours[h]
if row == nil {
row = &Hour{T: h}
hours[h] = row
}
row.Total += b.Total
row.Open += b.Open
row.Logged += b.Logged
if b.TCP+b.UDP > b.Open {
row.Closed += b.TCP + b.UDP - b.Open
}
for k, n := range b.Ports {
ports[k] += uint64(n)
}
for k, v := range b.ASNs {
row := asns[k]
if row == nil {
row = &ASNRow{ASN: k, Org: v.Org}
asns[k] = row
}
row.N += uint64(v.N)
}
for k, n := range b.CCs {
ccs[k] += uint64(n)
}
}
a.mu.Unlock()
}
r.Enabled = r.Source.State != "waiting"
for _, h := range hours {
r.Hourly = append(r.Hourly, *h)
if h.Total > 0 {
hoursWithCounters++
}
}
sort.Slice(r.Hourly, func(i, j int) bool { return r.Hourly[i].T < r.Hourly[j].T })
t := &r.Totals
if t.TCP+t.UDP > t.Open {
t.Closed = t.TCP + t.UDP - t.Open
}
t.ClosedPct = pct(t.Closed, t.TCP+t.UDP)
if hoursWithCounters > 0 {
t.PerHour = float64(int(float64(t.Attempts)/float64(hoursWithCounters)*10+0.5)) / 10
}
s := &r.Sample
if t.Attempts > 0 {
s.Ratio = float64(int(float64(s.Logged)/float64(t.Attempts)*10000+0.5)) / 10000
}
s.BannedPct = pct(s.LoggedBanned, s.Logged)
if s.Logged > 0 {
s.BannedEst = uint64(float64(s.LoggedBanned) / float64(s.Logged) * float64(t.Attempts))
}
for k, n := range ports {
var proto, port, class string
if !splitPort(k, &proto, &port, &class) {
continue
}
p, _ := strconv.Atoi(port)
r.Ports = append(r.Ports, PortRow{Proto: proto, Port: uint16(p), N: n, Served: class == "o", Pct: pct(n, s.Logged)})
}
sort.Slice(r.Ports, func(i, j int) bool {
if r.Ports[i].N != r.Ports[j].N {
return r.Ports[i].N > r.Ports[j].N
}
return r.Ports[i].Port < r.Ports[j].Port
})
if len(r.Ports) > topN {
r.Ports = r.Ports[:topN]
}
for _, row := range asns {
row.Pct = pct(row.N, s.Logged)
r.ASNs = append(r.ASNs, *row)
}
sort.Slice(r.ASNs, func(i, j int) bool {
if r.ASNs[i].N != r.ASNs[j].N {
return r.ASNs[i].N > r.ASNs[j].N
}
return r.ASNs[i].ASN < r.ASNs[j].ASN
})
if len(r.ASNs) > topN {
r.ASNs = r.ASNs[:topN]
}
for cc, n := range ccs {
r.CCs = append(r.CCs, CCRow{CC: cc, N: n, Pct: pct(n, s.Logged)})
}
sort.Slice(r.CCs, func(i, j int) bool {
if r.CCs[i].N != r.CCs[j].N {
return r.CCs[i].N > r.CCs[j].N
}
return r.CCs[i].CC < r.CCs[j].CC
})
if len(r.CCs) > topN {
r.CCs = r.CCs[:topN]
}
return r
}
func splitPort(k string, proto, port, class *string) bool {
i, j := strings.Index(k, "/"), strings.LastIndex(k, "/")
if i <= 0 || j <= i || j == len(k)-1 {
return false
}
*proto, *port, *class = k[:i], k[i+1:j], k[j+1:]
return true
}
// ---- persistence ----
type saved struct {
V int `json:"v"`
Prev *Counters `json:"prev,omitempty"`
Hours map[int64]*bucket `json:"hours"`
Lines uint64 `json:"lines"`
Cnts uint64 `json:"cnts"`
Bad uint64 `json:"bad"`
LastL int64 `json:"last_line"`
LastC int64 `json:"last_cnt"`
}
// Save writes the aggregate atomically when it changed since the last save.
func (a *Agg) Save(path string) error {
a.mu.Lock()
if !a.dirty {
a.mu.Unlock()
return nil
}
b, err := json.Marshal(saved{V: 1, Prev: a.prev, Hours: a.hours, Lines: a.lines, Cnts: a.counts, Bad: a.bad, LastL: a.lastLine, LastC: a.lastCnt})
a.dirty = false
a.mu.Unlock()
if err != nil {
return err
}
tmp := path + ".tmp"
if err := os.WriteFile(tmp, b, 0o600); err != nil {
return err
}
return os.Rename(tmp, path)
}
// Load restores a saved aggregate; a missing or damaged file leaves it empty.
func (a *Agg) Load(path string) error {
st, err := os.Stat(path)
if err != nil {
return nil
}
if st.Size() > maxFileLen {
return errors.New("ingress state too large")
}
raw, err := os.ReadFile(path)
if err != nil {
return err
}
var s saved
if err := json.Unmarshal(raw, &s); err != nil || s.V != 1 {
return errors.New("ingress state unreadable")
}
a.mu.Lock()
defer a.mu.Unlock()
a.prev, a.lines, a.counts, a.bad, a.lastLine, a.lastCnt = s.Prev, s.Lines, s.Cnts, s.Bad, s.LastL, s.LastC
for h, b := range s.Hours {
if b == nil || h%3600 != 0 || len(b.Ports) > maxPorts || len(b.ASNs) > maxASNs || len(b.CCs) > maxCCs {
continue
}
a.hours[h] = b
}
a.pruneLocked()
return nil
}