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:
1 parent
4143bf599e
commit
aefdcea8d2
40 files changed
+1684
-11
No files matched your search
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
Reference in new issue
Block a user