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>
This commit is contained in:
Lucas RayanandClaude Sonnet 5.5 committed 2026-11-23 09:09:16 -03:00
1 parent 4143bf599e
commit aefdcea8d2
40 files changed
+1684 -11

No files matched your search

+1
View File
@@ -65,6 +65,7 @@ func Doctor(c Config, w io.Writer, asJSON bool) bool {
add("data-dir", "ok", fmt.Sprintf("%s writable", filepath.Clean(c.DataDir)))
}
doctorEnforce(c, add)
doctorIngress(c, add)
geoInfo := doctorGeo(c, add)
stateInfo := doctorState(c, add)
ok := true
+35
View File
@@ -0,0 +1,35 @@
package app
import (
"log/slog"
"path/filepath"
"strconv"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/ingress"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
// IngressPath is the aggregate of the firewall telemetry inside a node directory.
func IngressPath(dir string) string { return filepath.Join(dir, "ingress.json") }
// newIngress builds the firewall telemetry aggregate of one node. A source
// address is "banned" by the node's own ban state (the jails it has read from
// fail2ban.log, the urutau jail included). The aggregate only reads that state:
// it has no way to write an event, a score or a decision, so attempts from a
// banned address never become evidence.
func newIngress(st *store.Store, dir string, log *slog.Logger) *ingress.Agg {
a := ingress.New()
a.Banned = st.Banned
a.Geo = func(ip string) (string, string, string) {
g := st.GeoOf(ip)
asn := ""
if g.ASN != 0 {
asn = "AS" + strconv.FormatUint(uint64(g.ASN), 10)
}
return g.CC, asn, g.ASOrg
}
if err := a.Load(IngressPath(dir)); err != nil {
log.Warn("ingress state ignored", "dir", dir, "err", err)
}
return a
}
+60
View File
@@ -0,0 +1,60 @@
package app
import (
"fmt"
"os"
"path/filepath"
"sort"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/ingress"
)
// ingressFresh is how old the last counters line may be before the firewall
// telemetry of a host counts as stale: the kit writes one every minute.
const ingressFresh = 5 * time.Minute
// doctorIngress reports, per host that ever sent it, whether the firewall
// telemetry (host kit --ingress) is present and fresh. It reads the saved
// aggregate of each node; no host sending it is "off", not a failure.
func doctorIngress(c Config, add func(name, status, detail string)) {
dirs := map[string]string{c.Name: c.DataDir}
if ents, err := os.ReadDir(filepath.Join(c.DataDir, "probes")); err == nil {
for _, e := range ents {
if e.IsDir() {
dirs[e.Name()] = filepath.Join(c.DataDir, "probes", e.Name())
}
}
}
names := make([]string, 0, len(dirs))
for n := range dirs {
names = append(names, n)
}
sort.Strings(names)
any := false
for _, n := range names {
p := IngressPath(dirs[n])
if _, err := os.Stat(p); err != nil {
continue
}
a := ingress.New()
if err := a.Load(p); err != nil {
add("ingress "+n, "warn", err.Error())
any = true
continue
}
in := a.Info()
any = true
switch {
case in.LastCounters == 0:
add("ingress "+n, "warn", "sampled log seen but no counters yet: check ingress.counters and urutau-ingress-tick.timer")
case time.Since(time.Unix(in.LastCounters, 0)) > ingressFresh:
add("ingress "+n, "warn", fmt.Sprintf("stale: last counters %s ago (is urutau-ingress-tick.timer running?)", time.Since(time.Unix(in.LastCounters, 0)).Round(time.Second)))
default:
add("ingress "+n, "ok", fmt.Sprintf("fresh: counters %s ago, %d sampled lines", time.Since(time.Unix(in.LastCounters, 0)).Round(time.Second), in.Lines))
}
}
if !any {
add("ingress", "off", "no firewall telemetry received (host kit: install.sh --ingress)")
}
}
+77
View File
@@ -0,0 +1,77 @@
package app
import (
"fmt"
"io"
"log/slog"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
func ingressNode(t *testing.T) (*Runner, *store.Store) {
t.Helper()
st := store.New(store.Config{Name: "t", Version: "t", Retention: 30 * 24 * time.Hour})
log := slog.New(slog.NewTextHandler(io.Discard, nil))
r, err := NewRemoteRunner(Config{DataDir: t.TempDir()}, st, log, t.TempDir())
if err != nil {
t.Fatal(err)
}
r.StartRemote(nil, nil)
r.IngressFeed = newIngress(st, t.TempDir(), log).Ingest
return r, st
}
func lines(src string, ls ...string) []wire.Line {
var out []wire.Line
for i, l := range ls {
out = append(out, wire.Line{Src: src, Text: l, End: wire.Pos{Inode: 7, Offset: int64(i+1) * 100}})
}
return out
}
// Attempts from a banned address are classified from the node's ban state and
// never become events, scores or evidence: the store learns nothing from them.
func TestIngressNeverFeedsTheStore(t *testing.T) {
r, st := ingressNode(t)
// the node knows 203.0.113.9 is banned by a jail
r.ApplyBatch(lines(wire.SrcFail2ban, "2026-11-20 10:00:00,100 fail2ban.actions [1]: NOTICE [sshd] Ban 203.0.113.9"))
if !st.Banned("203.0.113.9") || st.Banned("198.51.100.1") {
t.Fatal("ban state not read")
}
before := st.IPCount()
now := time.Now().UTC().Format("2006-01-02T15:04:05+00:00")
var in []string
for i := 0; i < 500; i++ {
in = append(in, fmt.Sprintf("%s h kernel: URUTAU-IN: IN=eth0 OUT= SRC=203.0.113.9 DST=10.0.0.5 PROTO=TCP SPT=1 DPT=%d SYN", now, 1000+i%40))
in = append(in, fmt.Sprintf("%s h kernel: URUTAU-IN: IN=eth0 OUT= SRC=198.51.100.%d DST=10.0.0.5 PROTO=TCP SPT=1 DPT=23 SYN", now, 1+i%200))
}
acc, _ := r.ApplyBatch(lines(wire.SrcIngress, in...))
if acc != 1000 {
t.Fatalf("accepted %d", acc)
}
r.ApplyBatch(lines(wire.SrcIngressCnt, "ts=1 total=oops"))
if st.IPCount() != before {
t.Fatalf("ingress created IP records: %d -> %d", before, st.IPCount())
}
if st.KnownHostile("198.51.100.1") {
t.Fatal("an ingress attempt became evidence")
}
// the sources are not events: no runner source exists for them
if r.find("ingress") != nil || r.find("ingresscnt") != nil {
t.Fatal("ingress sources must not be event sources")
}
}
func TestIngressDuplicateLinesAreDropped(t *testing.T) {
r, _ := ingressNode(t)
l := lines(wire.SrcIngress, "x URUTAU-IN: SRC=198.51.100.1 DST=1.1.1.1 PROTO=TCP DPT=23 SYN")
if a, _ := r.ApplyBatch(l); a != 1 {
t.Fatal("first not accepted")
}
if a, d := r.ApplyBatch(l); a != 0 || d != 1 {
t.Fatalf("replay accepted %d dup %d", a, d)
}
}
+11
View File
@@ -16,6 +16,7 @@ import (
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/hub"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/incidents"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/ingress"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/rdns"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/server"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
@@ -57,6 +58,8 @@ type Node struct {
Inc *incidents.Store
Enf *enforce.Engine
Q *hub.CmdQueue
// Ing aggregates the firewall telemetry (ingress.log and ingress.counters).
Ing *ingress.Agg
sh *shared
egr atomic.Pointer[egress.Engine]
@@ -113,6 +116,8 @@ func (sh *shared) newNode(name string, primary bool, rec hub.Probe) (*Node, erro
e.Ingest(l)
}
}
n.Ing = newIngress(st, dir, sh.log)
run.IngressFeed = n.Ing.Ingest
if n.Inc, err = incidents.Open(filepath.Join(dir, "incidents.json"), sh.log); err != nil {
return nil, err
}
@@ -169,6 +174,9 @@ func (n *Node) maintain() {
if err := n.Run.Save(); err != nil {
n.sh.log.Warn("snapshot failed", "node", n.name, "err", err)
}
if err := n.Ing.Save(IngressPath(n.Dir)); err != nil {
n.sh.log.Warn("ingress state not saved", "node", n.name, "err", err)
}
case <-prune.C:
if k := n.St.Prune(); k > 0 {
n.sh.log.Info("pruned old IPs", "node", n.name, "n", k)
@@ -179,6 +187,9 @@ func (n *Node) maintain() {
// Close writes the final snapshot and flushes the queue and the tickets.
func (n *Node) Close() {
if err := n.Ing.Save(IngressPath(n.Dir)); err != nil {
n.sh.log.Warn("final ingress state not saved", "node", n.name, "err", err)
}
if err := n.Run.Save(); err != nil {
n.sh.log.Warn("final snapshot failed", "node", n.name, "err", err)
}
+8
View File
@@ -23,6 +23,7 @@ import (
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/geo"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/hub"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/incidents"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/ingress"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/rdns"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/server"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
@@ -78,6 +79,13 @@ func (n nodeSet) Egress(h string) *egress.Engine {
return nil
}
func (n nodeSet) Ingress(h string) *ingress.Agg {
if nd := n.node(h); nd != nil {
return nd.Ing
}
return nil
}
func (n nodeSet) Incidents(h string) *incidents.Store {
if nd := n.node(h); nd != nil {
return nd.Inc
+10
View File
@@ -115,6 +115,9 @@ type Runner struct {
Log *slog.Logger
// EgressFeed receives the "egress" lines of a probe (nil: they are only counted).
EgressFeed func(line []byte)
// IngressFeed receives the "ingress" and "ingresscnt" lines of a probe
// (nil: they are only counted). They never become events.
IngressFeed func(src string, line []byte)
mu sync.Mutex // commit mutex: held while a line is applied and by snapshots
@@ -236,6 +239,13 @@ func (r *Runner) feedLocked(src string, text []byte, end store.Offset) bool {
r.EgressFeed(text)
}()
}
} else if src == wire.SrcIngress || src == wire.SrcIngressCnt {
if r.IngressFeed != nil {
func() {
defer func() { recover() }()
r.IngressFeed(src, text)
}()
}
} else if s := r.find(name); s != nil {
r.handle(s)(text)
}
+529
View File
@@ -0,0 +1,529 @@
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
}
+236
View File
@@ -0,0 +1,236 @@
package ingress
import (
"fmt"
"path/filepath"
"strings"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
var t0 = time.Date(2026, 11, 20, 10, 5, 0, 0, time.UTC)
func hitLine(marker, src, proto string, dpt int, flags string) string {
return fmt.Sprintf("2026-11-20T10:05:00+00:00 host kernel: %s IN=eth0 OUT= MAC=aa SRC=%s DST=10.0.0.5 LEN=60 PROTO=%s SPT=4444 DPT=%d %s", marker, src, proto, dpt, flags)
}
func newAgg() *Agg {
a := New()
a.Now = func() time.Time { return t0 }
return a
}
func TestParseHit(t *testing.T) {
h, err := ParseHit([]byte(hitLine("URUTAU-IN:", "203.0.113.9", "TCP", 3389, "SYN")), t0)
if err != nil || h.Proto != "tcp" || h.DPort != 3389 || h.Open || h.Src.String() != "203.0.113.9" {
t.Fatalf("closed tcp: %+v %v", h, err)
}
h, err = ParseHit([]byte(hitLine("URUTAU-INO:", "203.0.113.9", "TCP", 22, "SYN")), t0)
if err != nil || !h.Open {
t.Fatalf("open tcp: %+v %v", h, err)
}
h, err = ParseHit([]byte(hitLine("URUTAU-IN:", "203.0.113.9", "ICMP", 0, "")), t0)
if err != nil || h.Proto != "icmp" || h.DPort != 0 {
t.Fatalf("icmp: %+v %v", h, err)
}
}
func TestParseHitRejects(t *testing.T) {
bad := map[string]string{
"not ours": "Nov 20 kernel: something else",
"ack": hitLine("URUTAU-IN:", "203.0.113.9", "TCP", 80, "SYN ACK"),
"no syn": hitLine("URUTAU-IN:", "203.0.113.9", "TCP", 80, "ACK"),
"no port": hitLine("URUTAU-IN:", "203.0.113.9", "TCP", 0, "SYN"),
"private src": hitLine("URUTAU-IN:", "192.168.1.5", "TCP", 80, "SYN"),
"loopback src": hitLine("URUTAU-IN:", "127.0.0.1", "TCP", 80, "SYN"),
"link-local": hitLine("URUTAU-IN:", "169.254.1.1", "TCP", 80, "SYN"),
"multicast": hitLine("URUTAU-IN:", "224.0.0.1", "UDP", 80, ""),
"bad src": "kernel: URUTAU-IN: SRC=999.1.1.1 DST=1.2.3.4 PROTO=TCP DPT=1 SYN",
"gre": hitLine("URUTAU-IN:", "203.0.113.9", "GRE", 0, ""),
"no proto": "kernel: URUTAU-IN: SRC=203.0.113.9 DST=1.2.3.4",
"injection": "kernel: URUTAU-IN: SRC=203.0.113.9;rm DST=1.2.3.4 PROTO=TCP DPT=1 SYN",
"oversize line": hitLine("URUTAU-IN:", "203.0.113.9", "TCP", 80, "SYN") + strings.Repeat(" X=1", 1000),
}
for name, l := range bad {
if _, err := ParseHit([]byte(l), t0); err == nil {
t.Errorf("%s: accepted", name)
}
}
}
func TestParseCounters(t *testing.T) {
c, err := ParseCounters([]byte("ts=1767225600 total=120 tcp=100 udp=15 icmp=5 open=30 future=7"))
if err != nil || c.Total != 120 || c.Open != 30 || c.TS != 1767225600 {
t.Fatalf("%+v %v", c, err)
}
for name, l := range map[string]string{
"empty": "",
"missing": "ts=1 total=1 tcp=1 udp=0 icmp=0",
"duplicate": "ts=1 total=1 tcp=1 tcp=1 udp=0 icmp=0 open=0",
"negative": "ts=1 total=-1 tcp=0 udp=0 icmp=0 open=0",
"text": "ts=1 total=abc tcp=0 udp=0 icmp=0 open=0",
"huge": "ts=1 total=99999999999999999999 tcp=0 udp=0 icmp=0 open=0",
"no equals": "ts=1 total=1 tcp=1 udp=0 icmp=0 open=0 junk",
"zero ts": "ts=0 total=1 tcp=1 udp=0 icmp=0 open=0",
"open > l4": "ts=5 total=10 tcp=1 udp=0 icmp=0 open=9",
"parts > total": "ts=5 total=10 tcp=100000 udp=0 icmp=0 open=0",
"oversize": "ts=1 total=1 tcp=1 udp=0 icmp=0 open=0 " + strings.Repeat("x=1 ", 100),
} {
if _, err := ParseCounters([]byte(l)); err == nil {
t.Errorf("%s: accepted", name)
}
}
}
func cnt(ts int64, total, tcp, udp, icmp, open int) []byte {
return []byte(fmt.Sprintf("ts=%d total=%d tcp=%d udp=%d icmp=%d open=%d", ts, total, tcp, udp, icmp, open))
}
func TestExactTotalsFromCounterDeltas(t *testing.T) {
a := newAgg()
base := t0.Unix() - 600
a.Ingest(wire.SrcIngressCnt, cnt(base, 1000, 900, 90, 10, 100)) // baseline: no delta
a.Ingest(wire.SrcIngressCnt, cnt(base+60, 1100, 980, 110, 10, 130))
a.Ingest(wire.SrcIngressCnt, cnt(base+120, 1160, 1030, 120, 10, 140))
a.Ingest(wire.SrcIngressCnt, cnt(base+120, 5000, 1030, 120, 10, 140)) // same ts: ignored
r := a.Report(base-3600, t0.Unix()+3600)
if r.Totals.Attempts != 160 || r.Totals.TCP != 130 || r.Totals.UDP != 30 || r.Totals.ICMP != 0 || r.Totals.Open != 40 {
t.Fatalf("totals %+v", r.Totals)
}
if r.Totals.Closed != 120 || r.Totals.ClosedPct != 75 {
t.Fatalf("closed %+v", r.Totals)
}
if !r.Enabled || r.Source.State != "following" {
t.Fatalf("source %+v", r.Source)
}
}
func TestCounterResetCountsFromZero(t *testing.T) {
a := newAgg()
base := t0.Unix() - 300
a.Ingest(wire.SrcIngressCnt, cnt(base, 1000, 1000, 0, 0, 0))
a.Ingest(wire.SrcIngressCnt, cnt(base+60, 40, 40, 0, 0, 5)) // table reloaded
r := a.Report(base-3600, t0.Unix()+3600)
if r.Totals.Attempts != 40 {
t.Fatalf("reset: %+v", r.Totals)
}
}
func TestCounterAbsurdDeltaAndTimesDropped(t *testing.T) {
a := newAgg()
base := t0.Unix() - 300
a.Ingest(wire.SrcIngressCnt, cnt(base, 1, 1, 0, 0, 0))
a.Ingest(wire.SrcIngressCnt, cnt(base+60, 1<<45, 1<<45, 0, 0, 0))
a.Ingest(wire.SrcIngressCnt, cnt(t0.Unix()+86400*5, 10, 10, 0, 0, 0)) // far future
a.Ingest(wire.SrcIngressCnt, cnt(t0.Unix()-86400*400, 10, 10, 0, 0, 0))
if r := a.Report(0, t0.Unix()+86400*10); r.Totals.Attempts != 0 {
t.Fatalf("absurd: %+v", r.Totals)
}
if a.Info().Malformed < 3 {
t.Fatalf("malformed %d", a.Info().Malformed)
}
}
func TestSampleDetailsRatioAndBannedShare(t *testing.T) {
a := newAgg()
banned := map[string]bool{"203.0.113.9": true}
a.Banned = func(ip string) bool { return banned[ip] }
a.Geo = func(ip string) (string, string, string) { return "RU", "AS64500", "Example Net" }
base := t0.Unix() - 300
a.Ingest(wire.SrcIngressCnt, cnt(base, 0, 0, 0, 0, 0))
a.Ingest(wire.SrcIngressCnt, cnt(base+60, 1000, 1000, 0, 0, 0))
for i := 0; i < 6; i++ {
a.Ingest(wire.SrcIngress, []byte(hitLine("URUTAU-IN:", "203.0.113.9", "TCP", 3389, "SYN")))
}
for i := 0; i < 4; i++ {
a.Ingest(wire.SrcIngress, []byte(hitLine("URUTAU-INO:", "198.51.100.7", "TCP", 22, "SYN")))
}
r := a.Report(base-3600, t0.Unix()+3600)
if r.Sample.Logged != 10 || r.Sample.LoggedBanned != 6 || r.Sample.BannedPct != 60 {
t.Fatalf("sample %+v", r.Sample)
}
if r.Sample.Ratio != 0.01 || r.Sample.BannedEst != 600 {
t.Fatalf("ratio %+v", r.Sample)
}
if len(r.Ports) != 2 || r.Ports[0].Port != 3389 || r.Ports[0].Served || r.Ports[0].N != 6 || !r.Ports[1].Served {
t.Fatalf("ports %+v", r.Ports)
}
if len(r.ASNs) != 1 || r.ASNs[0].ASN != "AS64500" || r.ASNs[0].N != 10 || len(r.CCs) != 1 || r.CCs[0].CC != "RU" {
t.Fatalf("origins %+v %+v", r.ASNs, r.CCs)
}
// the ban state is read at the time of the line: unbanning later changes nothing retroactively
delete(banned, "203.0.113.9")
if r2 := a.Report(base-3600, t0.Unix()+3600); r2.Sample.LoggedBanned != 6 {
t.Fatalf("retroactive: %+v", r2.Sample)
}
}
func TestBucketsAreBounded(t *testing.T) {
a := newAgg()
a.Geo = func(ip string) (string, string, string) { return "", "", "" }
for i := 0; i < maxPorts*3; i++ {
a.Ingest(wire.SrcIngress, []byte(hitLine("URUTAU-IN:", "203.0.113.9", "TCP", 1000+i, "SYN")))
}
a.mu.Lock()
n := len(a.hours[hourOf(t0.Unix())].Ports)
a.mu.Unlock()
if n != maxPorts {
t.Fatalf("ports kept %d, want %d", n, maxPorts)
}
}
func TestHostileLinesNeverPanic(t *testing.T) {
a := newAgg()
for _, l := range []string{"", "\x00\x01", strings.Repeat("A", 100000), "URUTAU-IN:", "URUTAU-INO: SRC= DST= PROTO=", "URUTAU-IN: SRC=::ffff:203.0.113.1 DST=1.1.1.1 PROTO=TCP DPT=99999 SYN"} {
a.Ingest(wire.SrcIngress, []byte(l))
a.Ingest(wire.SrcIngressCnt, []byte(l))
}
a.Ingest("bogus", []byte("x"))
}
func TestSaveLoadAndRetention(t *testing.T) {
a := newAgg()
base := t0.Unix() - 300
a.Ingest(wire.SrcIngressCnt, cnt(base, 0, 0, 0, 0, 0))
a.Ingest(wire.SrcIngressCnt, cnt(base+60, 50, 50, 0, 0, 0))
p := filepath.Join(t.TempDir(), "ingress.json")
if err := a.Save(p); err != nil {
t.Fatal(err)
}
b := newAgg()
if err := b.Load(p); err != nil {
t.Fatal(err)
}
if r := b.Report(0, t0.Unix()+3600); r.Totals.Attempts != 50 {
t.Fatalf("loaded %+v", r.Totals)
}
// a later clock prunes the old hour
b.Now = func() time.Time { return t0.Add(Retention + 2*time.Hour) }
b.Ingest(wire.SrcIngressCnt, cnt(b.Now().Unix(), 1, 1, 0, 0, 0))
if r := b.Report(0, b.Now().Unix()+3600); r.Totals.Attempts != 1 { // only the new hour (the counters restarted)
t.Fatalf("not pruned: %+v", r.Totals)
}
}
func TestReportOfMergesHosts(t *testing.T) {
mk := func(n int) *Agg {
a := newAgg()
base := t0.Unix() - 300
a.Ingest(wire.SrcIngressCnt, cnt(base, 0, 0, 0, 0, 0))
a.Ingest(wire.SrcIngressCnt, cnt(base+60, n, n, 0, 0, 0))
return a
}
r := ReportOf([]*Agg{mk(10), mk(32), nil}, 0, t0.Unix()+3600)
if r.Totals.Attempts != 42 || len(r.Hourly) != 1 {
t.Fatalf("%+v", r)
}
}
func TestWaitingWithoutData(t *testing.T) {
r := newAgg().Report(0, t0.Unix())
if r.Enabled || r.Source.State != "waiting" || r.Hourly == nil || r.Ports == nil {
t.Fatalf("%+v", r)
}
}
+152
View File
@@ -0,0 +1,152 @@
// Package ingress aggregates the firewall telemetry of the host kit: the exact
// once-a-minute counters of the inbound observation table and a rate-limited
// sample of the connection attempts it saw.
//
// It is telemetry only. Nothing in this package emits an event, a score or a
// ban decision: attempts, banned sources included, are never evidence (a ban
// would otherwise feed on its own dropped packets). It deliberately does not
// import the store, the intelligence or the enforce packages.
package ingress
import (
"errors"
"net/netip"
"strconv"
"strings"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
)
// Kernel log prefixes written by deploy/host/urutau-ingress.nft: IN for a port
// the host does not serve, INO for one it does.
const (
markerClosed = "URUTAU-IN:"
markerOpen = "URUTAU-INO:"
)
// Hostile input limits.
const (
maxLogLine = 2048
maxCounterLine = 256
maxCounter = 1 << 50 // packets since the table was loaded; far beyond any real count
)
var (
ErrNotIngress = errors.New("not an ingress line")
ErrTooLong = errors.New("line too long")
ErrBadLine = errors.New("invalid ingress line")
)
// Hit is one sampled inbound attempt.
type Hit struct {
Time time.Time
Src netip.Addr
Proto string // tcp, udp, icmp
DPort uint16 // 0 for icmp
Open bool // the host serves this port
}
// ParseHit parses one line of ingress.log. now is the fallback time of a line
// whose timestamp is unreadable.
func ParseHit(b []byte, now time.Time) (Hit, error) {
if len(b) > maxLogLine {
return Hit{}, ErrTooLong
}
line := string(b)
open := false
marker := markerClosed
switch {
case strings.Contains(line, markerOpen):
open, marker = true, markerOpen
case strings.Contains(line, markerClosed):
default:
return Hit{}, ErrNotIngress
}
k, err := egress.ParseKernel(b, marker, now)
if err != nil {
return Hit{}, ErrBadLine
}
switch k.Proto {
case "tcp":
if !k.SYN || k.ACK || k.DPort == 0 {
return Hit{}, ErrBadLine
}
case "udp":
if k.DPort == 0 {
return Hit{}, ErrBadLine
}
case "icmp":
k.DPort, open = 0, false
default:
return Hit{}, ErrBadLine
}
// Defense in depth: the kit already skips these, a forged line must not
// attribute traffic to a local or reserved address either.
a := k.Src
if !a.IsValid() || !a.IsGlobalUnicast() || a.IsPrivate() || a.IsLoopback() || a.IsLinkLocalUnicast() || a.IsMulticast() {
return Hit{}, ErrBadLine
}
return Hit{Time: k.Time, Src: a, Proto: k.Proto, DPort: k.DPort, Open: open}, nil
}
// Counters is one line of ingress.counters. Values are cumulative since the
// nftables table was loaded.
type Counters struct {
TS int64
Total, TCP, UDP, ICMP, Open uint64
}
// ParseCounters parses "ts=1767225600 total=120 tcp=100 udp=15 icmp=5 open=30".
// Unknown keys are ignored (a newer kit); a missing key, a duplicate or a value
// out of range makes the line invalid.
func ParseCounters(b []byte) (Counters, error) {
if len(b) > maxCounterLine {
return Counters{}, ErrTooLong
}
var c Counters
seen := 0
for _, f := range strings.Fields(string(b)) {
k, v, ok := strings.Cut(f, "=")
if !ok {
return Counters{}, ErrBadLine
}
n, err := strconv.ParseUint(v, 10, 64)
if err != nil || n > maxCounter {
if k == "ts" || k == "total" || k == "tcp" || k == "udp" || k == "icmp" || k == "open" {
return Counters{}, ErrBadLine
}
continue
}
bit := 0
switch k {
case "ts":
c.TS, bit = int64(n), 1
case "total":
c.Total, bit = n, 2
case "tcp":
c.TCP, bit = n, 4
case "udp":
c.UDP, bit = n, 8
case "icmp":
c.ICMP, bit = n, 16
case "open":
c.Open, bit = n, 32
}
if bit == 0 {
continue
}
if seen&bit != 0 {
return Counters{}, ErrBadLine
}
seen |= bit
}
if seen != 63 || c.TS <= 0 {
return Counters{}, ErrBadLine
}
// A line that contradicts itself is not trusted.
if c.TCP+c.UDP+c.ICMP > c.Total+1000 || c.Open > c.TCP+c.UDP {
return Counters{}, ErrBadLine
}
return c, nil
}
+2
View File
@@ -48,6 +48,8 @@ func Main(args []string, version string) int {
{wire.SrcFail2ban, "URUTAU_FAIL2BAN_LOG", "", "fail2ban log"},
{wire.SrcProbe, "URUTAU_PROBE_LOG", "", "kernel log of network probes"},
{wire.SrcEgress, "URUTAU_EGRESS_LOG", "", "kernel log of outbound connections"},
{wire.SrcIngress, "URUTAU_INGRESS_LOG", "", "sampled kernel log of inbound attempts"},
{wire.SrcIngressCnt, "URUTAU_INGRESS_COUNTERS", "", "exact inbound counters of the host kit"},
} {
v := new(string)
paths[p.src] = v
+75
View File
@@ -0,0 +1,75 @@
package server
import (
"net/http"
"strings"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/ingress"
)
func init() {
registerUserRoute("GET /api/v1/ingress", func(s *Server) http.HandlerFunc { return s.ingressAPI })
}
type ingressOut struct {
Hosts []string `json:"hosts"`
ingress.Report
}
// ingressAPI: GET /api/v1/ingress?range=24h&host=all|<name>[,<name>]. The
// firewall telemetry of the hosts that send it: exact totals from the host kit
// counters, the details (ports, origins, banned share) from its sampled log.
// Only the probes of this hub are covered (the telemetry is not relayed to
// peers).
func (s *Server) ingressAPI(w http.ResponseWriter, r *http.Request) {
rg, ok := s.rangeOf(w, r)
if !ok {
return
}
host := strings.TrimSpace(r.URL.Query().Get("host"))
if len(host) > 64*maxHostSel {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "bad host"})
return
}
var all []string
if s.opt.Nodes != nil {
all = s.opt.Nodes.Hosts()
}
var names []string
switch host {
case "", "all":
names = all
default:
for _, n := range strings.Split(host, ",") {
n = strings.TrimSpace(n)
if n == "" {
continue
}
if !contains(all, n) {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "unknown host"})
return
}
names = append(names, n)
}
}
aggs := make([]*ingress.Agg, 0, len(names))
for _, n := range names {
if a := s.opt.Nodes.Ingress(n); a != nil {
aggs = append(aggs, a)
}
}
from, to := rg.Bounds(s.opt.Store.Now().Unix())
if names == nil {
names = []string{}
}
writeJSON(w, 200, ingressOut{Hosts: names, Report: ingress.ReportOf(aggs, from, to)})
}
func contains(l []string, s string) bool {
for _, x := range l {
if x == s {
return true
}
}
return false
}
+77
View File
@@ -0,0 +1,77 @@
package server
import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/incidents"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/ingress"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
type fakeNodes struct{ m map[string]*ingress.Agg }
func (f fakeNodes) Hosts() []string {
return []string{"oracle", "hostinger"}
}
func (f fakeNodes) Enforce(string) *enforce.Engine { return nil }
func (f fakeNodes) Egress(string) *egress.Engine { return nil }
func (f fakeNodes) Incidents(string) *incidents.Store { return nil }
func (f fakeNodes) Ingress(h string) *ingress.Agg { return f.m[h] }
func TestIngressAPI(t *testing.T) {
st := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour})
now := time.Now()
mk := func(n int) *ingress.Agg {
a := ingress.New()
ts := now.Add(-10 * time.Minute).Unix()
a.Ingest(wire.SrcIngressCnt, []byte(fmt.Sprintf("ts=%d total=0 tcp=0 udp=0 icmp=0 open=0", ts)))
a.Ingest(wire.SrcIngressCnt, []byte(fmt.Sprintf("ts=%d total=%d tcp=%d udp=0 icmp=0 open=%d", ts+60, n, n, n/4)))
return a
}
nodes := fakeNodes{m: map[string]*ingress.Agg{"oracle": mk(400), "hostinger": mk(100)}}
h := New(Options{Token: userTok, Version: "t", Store: st, Nodes: nodes})
auth := map[string]string{"Authorization": "Bearer " + userTok}
d := getJSON(t, h, "/api/v1/ingress?range=24h", auth)
tot := d["totals"].(map[string]any)
if tot["attempts"] != float64(500) || tot["open"] != float64(125) || tot["closed"] != float64(375) || tot["closed_pct"] != float64(75) || d["enabled"] != true {
t.Fatalf("all: %v", d)
}
for _, k := range []string{"hosts", "source", "sample", "hourly", "ports", "asns", "countries"} {
if d[k] == nil {
t.Errorf("missing %q", k)
}
}
d = getJSON(t, h, "/api/v1/ingress?range=24h&host=hostinger", auth)
if d["totals"].(map[string]any)["attempts"] != float64(100) {
t.Fatalf("one host: %v", d)
}
for _, path := range []string{"/api/v1/ingress?host=nope", "/api/v1/ingress?range=bogus"} {
rec := httptest.NewRecorder()
req := httptest.NewRequest("GET", path, nil)
req.Header.Set("Authorization", "Bearer "+userTok)
h.ServeHTTP(rec, req)
if rec.Code != http.StatusNotFound && rec.Code != http.StatusBadRequest {
t.Errorf("%s: %d", path, rec.Code)
}
}
// no auth
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("GET", "/api/v1/ingress", nil))
if rec.Code != http.StatusUnauthorized {
t.Errorf("unauthenticated: %d", rec.Code)
}
// standalone (no nodes): empty, not an error
h2 := New(Options{Token: userTok, Version: "t", Store: st})
d = getJSON(t, h2, "/api/v1/ingress", auth)
if d["enabled"] != false || len(d["hosts"].([]any)) != 0 {
t.Fatalf("standalone: %v", d)
}
}
+2
View File
@@ -11,6 +11,7 @@ import (
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/hub"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/incidents"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/ingress"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
@@ -34,6 +35,7 @@ type NodeSet interface {
Hosts() []string
Enforce(host string) *enforce.Engine
Egress(host string) *egress.Engine
Ingress(host string) *ingress.Agg
Incidents(host string) *incidents.Store
}
+2
View File
@@ -23,3 +23,5 @@
@media (max-width: 900px) { .df-en .span-4, .df-en .span-8 { grid-column: 1 / -1; } }
.df-nowrap { white-space: nowrap; }
@media (max-width: 700px) { .df-table { min-width: 640px; } .df-table td, .df-table th { overflow-wrap: normal; } }
/* Firewall: inbound attempts */
.df-en + .df-en { margin-top: var(--grid-gap, 16px); }
+125 -4
View File
@@ -126,7 +126,34 @@
'df.en.reason.port-scan': 'Scanning many network ports on the server',
'df.en.reason.known-attacker': 'Known attacker returning (hostile verdict)',
'df.en.reason.neighbor-campaign': 'Part of a campaign: several neighbours in the same network range were already banned',
'df.en.error': 'Could not load the second firewall data.'
'df.en.error': 'Could not load the second firewall data.',
'df.fw.title': 'Firewall: inbound attempts',
'df.fw.hint': 'New connection attempts that reached this host from the internet, counted by the firewall before any ban drops them. What a provider firewall (for example a cloud security list) blocks earlier never gets here.',
'df.fw.lead': '{n} inbound attempts {range}',
'df.fw.lead.sub': 'The totals are exact (counters of the host kit). Ports and origins come from a sample of {r} of them.',
'df.fw.kpi.total': 'Attempts',
'df.fw.kpi.total.sub': '{n} per hour on average',
'df.fw.kpi.closed': 'To closed ports',
'df.fw.kpi.closed.sub': '{n} to ports nothing serves',
'df.fw.kpi.banned': 'From banned sources',
'df.fw.kpi.banned.sub': 'about {n} attempts; estimated from the sample',
'df.fw.kpi.ratio': 'Sampled',
'df.fw.kpi.ratio.sub': '{n} logged attempts of the total',
'df.fw.hourly': 'Attempts per hour',
'df.fw.hourly.closed': 'Closed ports',
'df.fw.hourly.open': 'Served ports',
'df.fw.ports': 'Top destination ports',
'df.fw.ports.hint': 'Sampled. A red bar is a port this host does not serve.',
'df.fw.asns': 'Top origin networks',
'df.fw.asns.hint': 'Sampled, by the ASN of the source address.',
'df.fw.ccs': 'Top origin countries',
'df.fw.ccs.hint': 'Sampled, by the country of the source address.',
'df.fw.sampled': 'Sampled: these details cover about {r} of the attempts; the totals above are exact.',
'df.fw.banned.note': 'Banned means the source was in a jail (fail2ban or Urutau) when its attempt was logged. Those attempts are dropped by the firewall and never count as new evidence against the address.',
'df.fw.none': 'No inbound telemetry yet',
'df.fw.none.sub': 'Install the host kit with "sudo sh deploy/host/install.sh --ingress" and let the probe send ingress.log and ingress.counters.',
'df.fw.nodata': 'No attempts counted in this window',
'df.fw.error': 'Could not load the firewall data.'
},
'pt-BR': {
'df.title': 'Defesa',
@@ -243,7 +270,34 @@
'df.en.reason.port-scan': 'Varredura de muitas portas de rede do servidor',
'df.en.reason.known-attacker': 'Atacante conhecido voltando (veredito hostil)',
'df.en.reason.neighbor-campaign': 'Parte de uma campanha: vários vizinhos da mesma faixa de rede já foram banidos',
'df.en.error': 'Não foi possível carregar os dados do segundo firewall.'
'df.en.error': 'Não foi possível carregar os dados do segundo firewall.',
'df.fw.title': 'Firewall: tentativas de entrada',
'df.fw.hint': 'Tentativas novas de conexão que chegaram a este host pela internet, contadas pelo firewall antes de qualquer banimento descartá-las. O que um firewall do provedor (por exemplo uma lista de segurança na nuvem) barra antes nunca chega aqui.',
'df.fw.lead': '{n} tentativas de entrada {range}',
'df.fw.lead.sub': 'Os totais são exatos (contadores do kit do host). Portas e origens vêm de uma amostra de {r} delas.',
'df.fw.kpi.total': 'Tentativas',
'df.fw.kpi.total.sub': '{n} por hora em média',
'df.fw.kpi.closed': 'Para portas fechadas',
'df.fw.kpi.closed.sub': '{n} para portas em que nada escuta',
'df.fw.kpi.banned': 'De origens banidas',
'df.fw.kpi.banned.sub': 'cerca de {n} tentativas; estimado pela amostra',
'df.fw.kpi.ratio': 'Amostrado',
'df.fw.kpi.ratio.sub': '{n} tentativas registradas do total',
'df.fw.hourly': 'Tentativas por hora',
'df.fw.hourly.closed': 'Portas fechadas',
'df.fw.hourly.open': 'Portas com serviço',
'df.fw.ports': 'Portas de destino mais visadas',
'df.fw.ports.hint': 'Amostrado. Barra vermelha é uma porta que este host não serve.',
'df.fw.asns': 'Redes de origem mais frequentes',
'df.fw.asns.hint': 'Amostrado, pelo ASN do endereço de origem.',
'df.fw.ccs': 'Países de origem mais frequentes',
'df.fw.ccs.hint': 'Amostrado, pelo país do endereço de origem.',
'df.fw.sampled': 'Amostrado: estes detalhes cobrem cerca de {r} das tentativas; os totais acima são exatos.',
'df.fw.banned.note': 'Banida quer dizer que a origem estava numa jaula (fail2ban ou Urutau) quando a tentativa foi registrada. Essas tentativas são descartadas pelo firewall e nunca contam como nova evidência contra o endereço.',
'df.fw.none': 'Ainda sem telemetria de entrada',
'df.fw.none.sub': 'Instale o kit do host com "sudo sh deploy/host/install.sh --ingress" e deixe a sonda enviar ingress.log e ingress.counters.',
'df.fw.nodata': 'Nenhuma tentativa contada nesta janela',
'df.fw.error': 'Não foi possível carregar os dados do firewall.'
}
});
@@ -465,8 +519,75 @@
});
}
var fwData = null, fwSeq = 0, fwBox = null;
function ratioTxt(r) { var v = (r || 0) * 100; return (v > 0 && v < 10 ? v.toFixed(1) : Math.round(v)) + '%'; }
function paintFirewall() {
if (!fwBox) return;
clear(fwBox);
if (!fwData) return;
var d = fwData, tt = d.totals || {}, sm = d.sample || {}, range = U.rangeLabel({ inline: true });
var head = el('div', { class: 'df-en-head' });
head.appendChild(el('h2', { class: 'df-en-title' }, t('df.fw.title')));
head.appendChild(el('p', { class: 'hint' }, t('df.fw.hint')));
fwBox.appendChild(head);
if (!d.enabled) { fwBox.appendChild(U.ui.empty(t('df.fw.none'), t('df.fw.none.sub'))); return; }
if (!tt.attempts) { fwBox.appendChild(U.ui.empty(t('df.fw.nodata'))); return; }
fwBox.appendChild(U.ui.lead(t('df.fw.lead', { n: nf(tt.attempts), range: range }), t('df.fw.lead.sub', { r: ratioTxt(sm.ratio) }), 'info'));
var kp = el('div', { class: 'grid-12 df-kpis' });
function k(node) { node.classList.add('span-3'); kp.appendChild(node); }
k(U.ui.metric(t('df.fw.kpi.total'), nf(tt.attempts), { sub: t('df.fw.kpi.total.sub', { n: nf(Math.round(tt.per_hour || 0)) }) }));
k(U.ui.metric(t('df.fw.kpi.closed'), pctTxt(tt.closed_pct || 0), { sub: t('df.fw.kpi.closed.sub', { n: nf(tt.closed || 0) }) }));
k(U.ui.metric(t('df.fw.kpi.banned'), pctTxt(sm.banned_pct || 0), { sub: t('df.fw.kpi.banned.sub', { n: nf(sm.banned_est || 0) }), tone: (sm.banned_pct || 0) >= 50 ? 'warn' : 'neutral' }));
k(U.ui.metric(t('df.fw.kpi.ratio'), ratioTxt(sm.ratio), { sub: t('df.fw.kpi.ratio.sub', { n: nf(sm.logged || 0) }) }));
fwBox.appendChild(kp);
var grid = el('div', { class: 'grid-12' });
var hours = d.hourly || [];
var hp = U.ui.panel({ title: t('df.fw.hourly'), cls: 'span-12' });
if (U.charts && U.charts.stackedArea && hours.length) {
var step = 3600, start = hours[0].t, last = hours[hours.length - 1].t;
var n = Math.min(MAX_BUCKETS, Math.floor((last - start) / step) + 1);
if (n < 2) { n = 2; }
var cl = new Array(n).fill(0), op = new Array(n).fill(0);
hours.forEach(function (h) { var i = Math.round((h.t - start) / step); if (i >= 0 && i < n) { cl[i] += h.closed; op[i] += h.open; } });
hp.body.appendChild(U.charts.stackedArea([{ key: 'closed', label: t('df.fw.hourly.closed'), values: cl }, { key: 'open', label: t('df.fw.hourly.open'), values: op }], step, { start: start, title: t('df.fw.hourly') }));
} else hp.body.appendChild(U.ui.empty(t('df.fw.nodata')));
grid.appendChild(hp);
function barsPanel(title, hint, rows, cls) {
var p = U.ui.panel({ title: title, hint: hint, cls: cls });
if (!rows.length) p.body.appendChild(U.ui.empty(t('df.fw.nodata')));
else if (U.charts && U.charts.bars) p.body.appendChild(U.charts.bars(rows, { title: title, format: nf }));
grid.appendChild(p);
}
barsPanel(t('df.fw.ports'), t('df.fw.ports.hint'), (d.ports || []).slice(0, 10).map(function (p) {
return { key: p.proto + '/' + p.port, label: p.proto + '/' + p.port, value: p.n, color: p.served ? '--viz-1' : '--danger' };
}), 'span-4');
barsPanel(t('df.fw.asns'), t('df.fw.asns.hint'), (d.asns || []).slice(0, 10).map(function (a) {
return { key: a.asn, label: a.asn + (a.org ? ' ' + a.org : ''), value: a.n };
}), 'span-4');
barsPanel(t('df.fw.ccs'), t('df.fw.ccs.hint'), (d.countries || []).slice(0, 10).map(function (c) {
return { key: c.cc, label: (U.fmt.flag ? U.fmt.flag(c.cc) + ' ' : '') + c.cc, value: c.n };
}), 'span-4');
fwBox.appendChild(grid);
fwBox.appendChild(el('p', { class: 'hint' }, t('df.fw.sampled', { r: ratioTxt(sm.ratio) })));
fwBox.appendChild(el('p', { class: 'hint' }, t('df.fw.banned.note')));
}
function loadFirewall() {
var my = ++fwSeq;
U.api('/api/v1/ingress', Object.assign(U.rangeParams(), ctx && ctx.host && ctx.host !== 'all' ? { host: ctx.host } : {})).then(function (d) {
if (!alive || my !== fwSeq) return;
fwData = d; paintFirewall();
}).catch(function () {
if (!alive || my !== fwSeq || fwData || !fwBox) return;
clear(fwBox);
fwBox.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('df.fw.error'))));
});
}
function load() {
loadEnforce();
loadFirewall();
var my = ++seq;
U.api('/api/v1/defense', Object.assign(U.rangeParams(), ctx && ctx.host && ctx.host !== 'all' ? { host: ctx.host } : {})).then(function (d) {
if (!alive || my !== seq) return;
@@ -481,10 +602,10 @@
U.registerPage({
id: 'defense', group: 'operate', titleKey: 'df.title',
icon: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M12 3l8 3v6c0 4.5-3.2 7.8-8 9-4.8-1.2-8-4.5-8-9V6z"/><path d="M9 12l2 2 4-4"/></svg>',
mount: function (node, cx) { root = el('div', { class: 'df-page' }); node.appendChild(root); enBox = el('div', { class: 'df-page df-en' }); node.appendChild(enBox); ctx = cx; alive = true; data = null; enData = null; paint(); load(); },
mount: function (node, cx) { root = el('div', { class: 'df-page' }); node.appendChild(root); enBox = el('div', { class: 'df-page df-en' }); node.appendChild(enBox); fwBox = el('div', { class: 'df-page df-en' }); node.appendChild(fwBox); ctx = cx; alive = true; data = null; enData = null; fwData = null; paint(); load(); },
update: function (cx) { ctx = cx; load(); },
refresh: function () { load(); },
unmount: function () { alive = false; seq++; enSeq++; if (root && root.parentNode) root.parentNode.removeChild(root); if (enBox && enBox.parentNode) enBox.parentNode.removeChild(enBox); root = null; enBox = null; data = null; enData = null; }
unmount: function () { alive = false; seq++; enSeq++; fwSeq++; if (root && root.parentNode) root.parentNode.removeChild(root); if (enBox && enBox.parentNode) enBox.parentNode.removeChild(enBox); if (fwBox && fwBox.parentNode) fwBox.parentNode.removeChild(fwBox); root = null; enBox = null; fwBox = null; data = null; enData = null; fwData = null; }
});
return true;
}
+10
View File
@@ -0,0 +1,10 @@
package store
// Banned reports whether a jail (fail2ban or Urutau's own) currently bans the
// address, according to the ban and unban lines this instance has read.
func (s *Store) Banned(ip string) bool {
s.mu.RLock()
defer s.mu.RUnlock()
r := s.ips[KeyOf(ip)]
return r != nil && len(r.Jails) > 0
}
+5 -1
View File
@@ -33,6 +33,10 @@ const (
SrcFail2ban = "fail2ban"
SrcProbe = "probe"
SrcEgress = "egress"
// SrcIngress is the sampled kernel log of new inbound attempts (ingress.log)
// and SrcIngressCnt the exact once-a-minute counters (ingress.counters).
SrcIngress = "ingress"
SrcIngressCnt = "ingresscnt"
)
// File names carried whole.
@@ -41,7 +45,7 @@ const (
FileResolv = "resolv.conf"
)
var Sources = []string{SrcTraefik, SrcAuth, SrcFail2ban, SrcProbe, SrcEgress}
var Sources = []string{SrcTraefik, SrcAuth, SrcFail2ban, SrcProbe, SrcEgress, SrcIngress, SrcIngressCnt}
func ValidSource(s string) bool {
for _, x := range Sources {