feat: 1.4.0 second firewall, egress analysis and HTML report
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 28s
CI / Dependency audit (push) Successful in 16s
CI / Tests (Linux, race detector) (push) Successful in 1m3s
Release / Plan (reuse the published image?) (push) Successful in 4s
Release / ci (push) Skipped
Release / Build image (amd64) (push) Skipped
Release / Build image (arm64) (push) Skipped
Release / Publish tags (push) Successful in 13s
Release / Gitea release (push) Successful in 3s

Optional second firewall (URUTAU_ENFORCE off/observe/on) through the host
fail2ban, outbound traffic analysis (beaconing, mining, spam, DNS bypass,
unauthorised scans) with authorised scanner workloads, host kit in
deploy/host and a printable HTML report.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lucas RayanandClaude Opus 5.5 committed 2026-11-14 23:35:34 -03:00
1 parent 3adaa007ec
commit c33cca22e3
59 files changed
+7364 -24

No files matched your search

+514
View File
@@ -0,0 +1,514 @@
package egress
import (
"fmt"
"math/rand"
"net/netip"
"os"
"path/filepath"
"sort"
"testing"
"time"
)
var t0 = time.Date(2026, 11, 14, 0, 0, 0, 0, time.UTC)
func ip(s string) netip.Addr { return netip.MustParseAddr(s) }
func mk(t time.Time, src, dst, proto string, dport uint16) Event {
return Event{Time: t, Src: ip(src), Dst: ip(dst), Proto: proto, SPort: 40000, DPort: dport, In: "br-1", Out: "enp0s6"}
}
func newEng(t *testing.T, c Config) *Engine {
t.Helper()
if c.Now == nil {
c.Now = func() time.Time { return t0.Add(30 * 24 * time.Hour) }
}
e, err := New(c)
if err != nil {
t.Fatal(err)
}
return e
}
func kinds(r Report, kind string) []Finding {
var o []Finding
for _, f := range r.Findings {
if f.Kind == kind {
o = append(o, f)
}
}
return o
}
func rep(e *Engine) Report { return e.Report(t0.Unix()-86400, t0.Add(14*24*time.Hour).Unix()) }
func TestParse(t *testing.T) {
now := time.Date(2026, 11, 14, 23, 0, 0, 0, time.UTC)
v4 := `2026-11-14T22:01:02.123456+00:00 oracle kernel: [123.4] URUTAU-EGRESS: IN=br-1a2b OUT=enp0s6 MAC=aa SRC=10.0.3.5 DST=93.184.216.34 LEN=60 TOS=0x00 PREC=0x00 TTL=63 ID=1 DF PROTO=TCP SPT=40000 DPT=443 WINDOW=64240 RES=0x00 SYN URGP=0`
ev, err := ParseLine([]byte(v4), now)
if err != nil || ev.Proto != "tcp" || ev.DPort != 443 || ev.SPort != 40000 || ev.Dst.String() != "93.184.216.34" || ev.Host || ev.Time.Hour() != 22 || ev.In != "br-1a2b" {
t.Fatalf("v4: %+v %v", ev, err)
}
v6 := `2026-11-14T22:01:02+00:00 oracle kernel: URUTAU-EGRESS: IN=br-1 OUT=enp0s6 SRC=fd00::5 DST=2606:4700:4700::1111 LEN=80 TC=0 HOPLIMIT=63 FLOWLBL=0 PROTO=UDP SPT=5353 DPT=53 LEN=40`
ev, err = ParseLine([]byte(v6), now)
if err != nil || ev.Proto != "udp" || ev.DPort != 53 || !ev.Dst.Is6() {
t.Fatalf("v6: %+v %v", ev, err)
}
ic := `Nov 14 22:01:02 oracle kernel: [1.0] URUTAU-EGRESS: IN=br-1 OUT=enp0s6 SRC=10.0.3.5 DST=1.1.1.1 LEN=84 PROTO=ICMP TYPE=8 CODE=0 ID=1`
ev, err = ParseLine([]byte(ic), now)
if err != nil || ev.Proto != "icmp" || ev.DPort != 0 || ev.Time.Year() != 2026 || ev.Time.Month() != 11 {
t.Fatalf("icmp: %+v %v", ev, err)
}
ic6 := `Nov 4 22:01:02 oracle kernel: URUTAU-EGRESS: IN=br-1 OUT=x SRC=fd00::5 DST=fd00::6 PROTO=ICMPv6 TYPE=128 CODE=0`
if ev, err = ParseLine([]byte(ic6), now); err != nil || ev.Proto != "icmp" || ev.Time.Day() != 4 {
t.Fatalf("icmp6: %+v %v", ev, err)
}
host := `2026-11-14T22:01:02+00:00 oracle kernel: URUTAU-EGRESS: IN= OUT=enp0s6 SRC=10.0.0.2 DST=8.8.8.8 PROTO=TCP SPT=1 DPT=443 SYN`
if ev, err = ParseLine([]byte(host), now); err != nil || !ev.Host || ev.In != "" {
t.Fatalf("host: %+v %v", ev, err)
}
// December line read in January belongs to the previous year
dec := `Dec 31 23:59:00 h kernel: URUTAU-EGRESS: IN=a OUT=b SRC=1.2.3.4 DST=5.6.7.8 PROTO=TCP DPT=1`
if ev, err = ParseLine([]byte(dec), time.Date(2027, 1, 1, 0, 5, 0, 0, time.UTC)); err != nil || ev.Time.Year() != 2026 {
t.Fatalf("year: %+v %v", ev, err)
}
for _, bad := range []string{"", "garbage", "URUTAU-EGRESS: IN=a OUT=b SRC=nope DST=1.1.1.1 PROTO=TCP", "URUTAU-EGRESS: IN=a SRC=1.1.1.1 DST=2.2.2.2", "\x00\xff URUTAU-EGRESS: ===", "sshd: Accepted publickey"} {
if _, err := ParseLine([]byte(bad), now); err == nil {
t.Fatalf("expected error for %q", bad)
}
}
e := newEng(t, Config{})
e.Ingest([]byte("garbage"))
e.Ingest([]byte(v4))
if e.malformed.Load() != 1 || e.lines.Load() != 1 {
t.Fatalf("counters %d %d", e.malformed.Load(), e.lines.Load())
}
}
func TestWorkloadsAndContainers(t *testing.T) {
e := newEng(t, Config{Workloads: "ciberlab=name:jhxint9g9uz91:scanner;mail=10.0.7.0/24,10.0.8.4/32:mail;lab=10.0.5.0/24"})
e.SetContainers(map[netip.Addr]string{ip("172.18.0.4"): "jhxint9g9uz91-20260101123456", ip("172.18.0.9"): "runner-q620o15zg7-1700000000000"})
cases := []struct {
ev Event
name, role string
}{
{mk(t0, "172.18.0.4", "1.1.1.1", "tcp", 1), "ciberlab", RoleScanner},
{mk(t0, "172.18.0.9", "1.1.1.1", "tcp", 1), "runner-q620o15zg7", RoleDefault},
{mk(t0, "10.0.8.4", "1.1.1.1", "tcp", 1), "mail", RoleMail},
{mk(t0, "10.0.5.77", "1.1.1.1", "tcp", 1), "lab", RoleDefault},
{mk(t0, "10.0.9.9", "1.1.1.1", "tcp", 1), "container 10.0.9.9", RoleDefault},
{Event{Time: t0, Src: ip("10.0.0.2"), Dst: ip("1.1.1.1"), Proto: "tcp", Host: true}, "host", RoleDefault},
}
for _, c := range cases {
if n, r := e.resolve(c.ev); n != c.name || r != c.role {
t.Errorf("%v: got %s/%s want %s/%s", c.ev.Src, n, r, c.name, c.role)
}
}
// IP changes: the map in force at Ingest wins
e.SetContainers(map[netip.Addr]string{ip("172.18.0.5"): "jhxint9g9uz91-20260102000000"})
if n, _ := e.resolve(mk(t0, "172.18.0.5", "1.1.1.1", "tcp", 1)); n != "ciberlab" {
t.Errorf("remap: %s", n)
}
for _, bad := range []string{"x", "a=", "a=notip:scanner", "a=name:bad name"} {
if _, err := ParseWorkloads(bad); err == nil {
t.Errorf("expected error for %q", bad)
}
}
// containers.map file: invalid lines skipped, reload on mtime change
dir := t.TempDir()
p := filepath.Join(dir, "containers.map")
os.WriteFile(p, []byte("172.18.0.4 jhxint9g9uz91-1700000000\nbad line here\n999.1.1.1 x\nfd00::7 six-node\n1.2.3.4 bad/name\n"), 0o644)
m, err := LoadContainers(p)
if err != nil || len(m) != 2 || m[ip("fd00::7")] != "six-node" {
t.Fatalf("map: %v %v", m, err)
}
clock := t0
e2 := newEng(t, Config{Containers: p, Workloads: "c=name:jhxint9g9uz91:scanner", Now: func() time.Time { return clock }})
e2.IngestEvent(mk(t0, "172.18.0.4", "5.5.5.5", "tcp", 443))
if _, ok := e2.ws["c"]; !ok {
t.Fatalf("map file not applied: %v", e2.ws)
}
os.WriteFile(p, []byte("172.18.0.4 other-1700000000\n"), 0o644)
os.Chtimes(p, clock.Add(time.Hour), clock.Add(time.Hour))
clock = clock.Add(time.Minute)
e2.IngestEvent(mk(t0.Add(time.Minute), "172.18.0.4", "5.5.5.5", "tcp", 443))
if _, ok := e2.ws["other"]; !ok {
t.Fatalf("map file not reloaded: %v", e2.ws)
}
}
func feedBeacon(e *Engine, src, dst string, dport uint16, start time.Time, n int, step time.Duration, jitter float64, rnd *rand.Rand) {
t := start
for i := 0; i < n; i++ {
pr := "tcp"
if dport == 123 {
pr = "udp"
}
e.IngestEvent(mk(t, src, dst, pr, dport))
j := 1 + (rnd.Float64()*2-1)*jitter
t = t.Add(time.Duration(float64(step) * j))
}
}
func TestBeaconPositive(t *testing.T) {
bad := func(a netip.Addr) (bool, string) { return a == ip("198.51.100.99"), "known attacker" }
e := newEng(t, Config{BadDst: bad})
rnd := rand.New(rand.NewSource(1))
feedBeacon(e, "10.0.3.5", "203.0.113.7", 443, t0, 50, 60*time.Second, 0.05, rnd)
feedBeacon(e, "10.0.3.5", "198.51.100.99", 8443, t0, 50, 60*time.Second, 0.05, rnd)
r := rep(e)
var got, hi *Finding
for i, f := range kinds(r, "beacon") {
if f.Dst == "203.0.113.7" {
got = &kinds(r, "beacon")[i]
}
if f.Dst == "198.51.100.99" {
hi = &kinds(r, "beacon")[i]
}
}
if got == nil || got.Severity != "medium" || got.IntervalS < 55 || got.IntervalS > 65 || got.Jitter > 0.1 || got.Count < 40 || got.Last <= got.First {
t.Fatalf("beacon: %+v", got)
}
if hi == nil || hi.Severity != "high" {
t.Fatalf("attacker beacon: %+v", hi)
}
}
func TestBeaconNegatives(t *testing.T) {
e := newEng(t, Config{Workloads: "sc=10.0.5.0/24:scanner", Allow: []netip.Prefix{netip.MustParsePrefix("192.0.2.0/24")}})
rnd := rand.New(rand.NewSource(2))
// random intervals
tt := t0
for i := 0; i < 60; i++ {
e.IngestEvent(mk(tt, "10.0.3.5", "203.0.113.8", "tcp", 443))
tt = tt.Add(time.Duration(5+rnd.Intn(600)) * time.Second)
}
// NTP, allowed dst, allowed resolver
feedBeacon(e, "10.0.3.5", "203.0.113.9", 123, t0, 50, 128*time.Second, 0, rnd)
feedBeacon(e, "10.0.3.5", "192.0.2.4", 443, t0, 50, 60*time.Second, 0, rnd)
for i := 0; i < 50; i++ {
ev := mk(t0.Add(time.Duration(i)*time.Minute), "10.0.3.5", "1.1.1.1", "udp", 53)
e.IngestEvent(ev)
}
// daily scan: 8 days, 60 targets each, scanner role; and hourly scan
for d := 0; d < 8; d++ {
for i := 0; i < 60; i++ {
e.IngestEvent(mk(t0.Add(time.Duration(d)*24*time.Hour+time.Duration(i)*time.Second), "10.0.5.2", fmt.Sprintf("203.0.113.%d", 100+i), "tcp", 22))
}
}
for h := 0; h < 12; h++ {
for i := 0; i < 60; i++ {
e.IngestEvent(mk(t0.Add(10*24*time.Hour+time.Duration(h)*time.Hour+time.Duration(i)*time.Second), "10.0.5.2", fmt.Sprintf("198.18.0.%d", 1+i), "tcp", 22))
}
}
if f := kinds(rep(e), "beacon"); len(f) != 0 {
t.Fatalf("unexpected beacons: %+v", f)
}
if f := kinds(rep(e), "dns_bypass"); len(f) != 0 {
t.Fatalf("usual resolver flagged: %+v", f)
}
}
func fanOut(e *Engine, src string, start time.Time, n int, port uint16) {
fanOutNet(e, src, "198.18", start, n, port)
}
func fanOutNet(e *Engine, src, net string, start time.Time, n int, port uint16) {
for i := 0; i < n; i++ {
e.IngestEvent(mk(start.Add(time.Duration(i)*time.Second), src, fmt.Sprintf("%s.%d.%d", net, i/200, 1+i%200), "tcp", port))
}
}
func TestScannerSuppressedVsDefault(t *testing.T) {
bad := func(a netip.Addr) (bool, string) { return a == ip("198.18.0.5"), "attacker" }
e := newEng(t, Config{Workloads: "ciberlab=10.0.5.0/24:scanner", BadDst: bad})
fanOut(e, "10.0.5.2", t0, 300, 80)
fanOutNet(e, "10.0.9.9", "198.19", t0, 300, 80) // default workload
r := rep(e)
var sc, df WorkloadOut
for _, w := range r.Workloads {
switch w.Name {
case "ciberlab":
sc = w
case "container 10.0.9.9":
df = w
}
}
if sc.Suppressed < 240 || sc.Conns > 60 {
t.Fatalf("scanner not suppressed: %+v", sc)
}
if df.Suppressed != 0 || df.Conns != 300 {
t.Fatalf("default must not be suppressed: %+v", df)
}
scan := kinds(r, "scan")
if len(scan) != 1 || scan[0].Workload != "container 10.0.9.9" || scan[0].Severity != "high" {
t.Fatalf("scan findings: %+v", scan)
}
if len(r.Scanner.Bursts) != 1 {
t.Fatalf("bursts: %+v", r.Scanner.Bursts)
}
b := r.Scanner.Bursts[0]
if b.Workload != "ciberlab" || b.Targets < 240 || len(b.Nets) == 0 || b.Ports[0] != 80 || b.BadDstHit != 1 {
t.Fatalf("burst: %+v", b)
}
for _, f := range kinds(r, "bad_dst") {
if f.Workload == "ciberlab" {
t.Fatalf("bad_dst of scanner inside a burst must only be counted: %+v", f)
}
}
for _, d := range r.TopDst {
for _, w := range d.Workloads {
if w == "ciberlab" {
t.Fatalf("scanner burst flow in top_dst: %+v", d)
}
}
}
// the burst closes after 5 minutes of quiet and a later flow is normal
e.IngestEvent(mk(t0.Add(time.Hour), "10.0.5.2", "203.0.113.50", "tcp", 443))
r = rep(e)
if len(r.Scanner.Bursts) != 1 || r.Scanner.Bursts[0].End > t0.Add(10*time.Minute).Unix() {
t.Fatalf("burst end: %+v", r.Scanner.Bursts)
}
}
func TestScannerBeaconStillDetectedDuringBurst(t *testing.T) {
e := newEng(t, Config{Workloads: "ciberlab=10.0.5.0/24:scanner"})
rnd := rand.New(rand.NewSource(3))
// beacon every 60 s for 60 min, scan from minute 10 for 150 s; ordered by time
var evs []Event
for i := 0; i < 60; i++ {
evs = append(evs, mk(t0.Add(time.Duration(i)*time.Minute+time.Duration(rnd.Intn(3))*time.Second), "10.0.5.2", "203.0.113.77", "tcp", 8443))
}
for i := 0; i < 150; i++ {
evs = append(evs, mk(t0.Add(10*time.Minute+10*time.Second+time.Duration(i)*time.Second), "10.0.5.2", fmt.Sprintf("198.18.0.%d", 1+i), "tcp", 443))
}
sort.SliceStable(evs, func(i, j int) bool { return evs[i].Time.Before(evs[j].Time) })
for _, ev := range evs {
e.IngestEvent(ev)
}
r := rep(e)
var found bool
for _, f := range kinds(r, "beacon") {
found = found || f.Dst == "203.0.113.77"
}
if !found {
t.Fatalf("beacon of the scanner lost: %+v", r.Findings)
}
if len(r.Scanner.Bursts) == 0 {
t.Fatal("expected a burst")
}
for _, w := range r.Workloads {
if w.Name == "ciberlab" && (w.Conns < 55 || w.Suppressed < 140) {
t.Fatalf("beacon flows must stay in normal accounting: %+v", w)
}
}
}
func TestSuspiciousPorts(t *testing.T) {
e := newEng(t, Config{Workloads: "mail=10.0.7.0/24:mail"})
at := func(i int) time.Time { return t0.Add(time.Duration(i) * time.Minute) }
e.IngestEvent(mk(at(0), "10.0.3.5", "203.0.113.1", "tcp", 25))
e.IngestEvent(mk(at(1), "10.0.7.5", "203.0.113.2", "tcp", 25)) // mail role: fine
e.IngestEvent(mk(at(2), "10.0.3.5", "203.0.113.3", "tcp", 6667))
e.IngestEvent(mk(at(3), "10.0.3.5", "203.0.113.4", "tcp", 3333))
e.IngestEvent(mk(at(4), "10.0.3.5", "203.0.113.5", "tcp", 9001))
e.IngestEvent(mk(at(5), "10.0.3.5", "203.0.113.6", "udp", 3333)) // udp: ignored
e.IngestEvent(mk(at(6), "10.0.3.5", "203.0.113.7", "udp", 853))
e.IngestEvent(mk(at(7), "10.0.3.5", "93.184.216.34", "udp", 53))
e.IngestEvent(mk(at(8), "10.0.3.5", "10.9.9.9", "udp", 53)) // private: not bypass
r := rep(e)
by := map[string]string{}
for _, f := range kinds(r, "port") {
by[f.Dst] = f.Severity
}
if len(by) != 4 || by["203.0.113.1"] != "medium" || by["203.0.113.4"] != "high" || by["203.0.113.2"] != "" {
t.Fatalf("ports: %v", by)
}
if d := kinds(r, "dns_bypass"); len(d) != 1 || d[0].Dst != "93.184.216.34" {
t.Fatalf("dns_bypass (DoT is tcp-only, 53 to unusual public): %+v", d)
}
// custom resolver list: Google no longer allowed
e2 := newEng(t, Config{Resolvers: "10.0.0.53"})
e2.IngestEvent(mk(t0, "10.0.3.5", "8.8.8.8", "udp", 53))
e2.IngestEvent(mk(t0, "10.0.3.5", "10.0.0.53", "udp", 53))
if d := kinds(rep(e2), "dns_bypass"); len(d) != 1 || d[0].Dst != "8.8.8.8" {
t.Fatalf("custom resolvers: %+v", d)
}
}
func TestBadDstAndNewGeo(t *testing.T) {
geo := func(s string) (string, string, string) {
if s == "203.0.113.50" {
return "RU", "AS1", "x"
}
return "BR", "AS2", "y"
}
bad := func(a netip.Addr) (bool, string) { return a == ip("203.0.113.9"), "Tor exit" }
e := newEng(t, Config{Geo: geo, BadDst: bad, Workloads: "sc=10.0.5.0/24:scanner"})
e.IngestEvent(mk(t0, "10.0.3.5", "203.0.113.1", "tcp", 443))
e.IngestEvent(mk(t0.Add(25*time.Hour), "10.0.3.5", "203.0.113.2", "tcp", 443)) // known country
e.IngestEvent(mk(t0.Add(26*time.Hour), "10.0.3.5", "203.0.113.50", "tcp", 443))
e.IngestEvent(mk(t0.Add(27*time.Hour), "10.0.3.5", "203.0.113.9", "tcp", 443))
e.IngestEvent(mk(t0, "10.0.5.2", "203.0.113.1", "tcp", 443))
e.IngestEvent(mk(t0.Add(26*time.Hour), "10.0.5.2", "203.0.113.50", "tcp", 443)) // scanner ignored
r := rep(e)
g := kinds(r, "new_geo")
if len(g) != 1 || g[0].Workload != "container 10.0.3.5" || g[0].Dst != "203.0.113.50" || g[0].Severity != "low" {
t.Fatalf("new_geo: %+v", g)
}
if b := kinds(r, "bad_dst"); len(b) != 1 || b[0].Severity != "high" || b[0].Detail != "Tor exit" {
t.Fatalf("bad_dst: %+v", b)
}
if len(r.TopDst) == 0 || r.TopDst[0].CC == "" {
t.Fatalf("top_dst not enriched: %+v", r.TopDst)
}
}
func TestMemoryLimits(t *testing.T) {
e := newEng(t, Config{})
// 60k distinct pairs, 15 s apart (never a fan-out) and spam findings
for i := 0; i < 60000; i++ {
dst := fmt.Sprintf("%d.%d.%d.%d", 20+i/65536, (i/256)%256, i%256, 1)
port := uint16(443)
if i < 3000 {
port = 25
}
e.IngestEvent(mk(t0.Add(time.Duration(i)*15*time.Second), "10.0.3.5", dst, "tcp", port))
}
if e.pairs.len() > MaxPairs || e.dsts.len() > MaxDsts || len(e.findings) > MaxFindings {
t.Fatalf("limits: %d %d %d", e.pairs.len(), e.dsts.len(), len(e.findings))
}
if len(e.findings) != MaxFindings {
t.Fatalf("findings should be capped at the limit, got %d", len(e.findings))
}
w := e.ws["container 10.0.3.5"]
n := 0
for i := range w.hours {
if w.hours[i].hour != 0 {
n++
}
if len(w.hours[i].dsts) > setCap {
t.Fatal("hour set not capped")
}
}
if n > HourBuckets {
t.Fatal("buckets")
}
// dedupe: same key updates count
e2 := newEng(t, Config{})
for i := 0; i < 5; i++ {
e2.IngestEvent(mk(t0.Add(time.Duration(i)*time.Minute), "10.0.3.5", "203.0.113.1", "tcp", 6667))
}
if f := kinds(rep(e2), "port"); len(f) != 1 || f[0].Count != 5 {
t.Fatalf("dedupe: %+v", f)
}
}
func TestReportMergeSanitize(t *testing.T) {
e := newEng(t, Config{})
e.IngestEvent(mk(t0, "10.0.3.5", "203.0.113.1", "tcp", 6667))
local := e.Report(t0.Unix()-3600, t0.Unix()+3600)
peer := e.Report(t0.Unix()-7200, t0.Unix()+3600)
peer.Sanitize("oracle")
local.Merge(peer, "oracle")
if len(local.Findings) != 2 || local.Findings[1].Host != "oracle" && local.Findings[0].Host != "oracle" {
t.Fatalf("merge: %+v", local.Findings)
}
if _, ok := local.Timeline.Series["oracle/container 10.0.3.5"]; !ok {
t.Fatalf("series: %v", local.Timeline.Series)
}
}
func TestNameMatchExactAndPrefix(t *testing.T) {
e := newEng(t, Config{Workloads: "a=name:web:default;b=name:api*:default;c=name:pay:default"})
e.SetContainers(map[netip.Addr]string{ip("172.18.0.1"): "web-1700000000000", ip("172.18.0.2"): "webshell-1700000000000",
ip("172.18.0.3"): "apigw-17", ip("172.18.0.4"): "pay", ip("172.18.0.5"): "payroll"})
for src, want := range map[string]string{"172.18.0.1": "a", "172.18.0.2": "webshell", "172.18.0.3": "b", "172.18.0.4": "c", "172.18.0.5": "payroll"} {
if n, _ := e.resolve(mk(t0, src, "1.1.1.1", "tcp", 1)); n != want {
t.Errorf("%s: %s want %s", src, n, want)
}
}
}
func TestHostWorkloadRole(t *testing.T) {
e := newEng(t, Config{Workloads: "host=host:mail"})
n, r := e.resolve(Event{Time: t0, Src: ip("10.0.0.2"), Dst: ip("1.1.1.1"), Proto: "tcp", Host: true})
if n != "host" || r != RoleMail {
t.Fatalf("%s/%s", n, r)
}
e.IngestEvent(Event{Time: t0, Src: ip("10.0.0.2"), Dst: ip("203.0.113.5"), Proto: "tcp", DPort: 25, Host: true})
if f := kinds(rep(e), "port"); len(f) != 0 {
t.Fatalf("mail host flagged: %+v", f)
}
}
func TestResolvConfAllowed(t *testing.T) {
p := filepath.Join(t.TempDir(), "resolv.conf")
os.WriteFile(p, []byte("# x\nnameserver 203.0.113.53\nnameserver fe80::1%eth0\nsearch x\n"), 0o644)
e := newEng(t, Config{ResolvConf: []string{p, "/nonexistent"}})
for i := 0; i < 3; i++ {
e.IngestEvent(mk(t0.Add(time.Duration(i)*time.Second), "10.0.3.5", "203.0.113.53", "udp", 53))
}
if f := kinds(rep(e), "dns_bypass"); len(f) != 0 {
t.Fatalf("resolv.conf nameserver flagged: %+v", f)
}
e.IngestEvent(mk(t0, "10.0.3.5", "203.0.113.54", "udp", 53))
if f := kinds(rep(e), "dns_bypass"); len(f) != 1 {
t.Fatalf("other resolver not flagged: %+v", f)
}
}
func TestAllowedPollerNoBeacon(t *testing.T) {
e := newEng(t, Config{Allow: []netip.Prefix{netip.MustParsePrefix("203.0.113.0/24")}})
feedBeacon(e, "10.0.3.5", "203.0.113.7", 443, t0, 60, 60*time.Second, 0, rand.New(rand.NewSource(1)))
if f := kinds(rep(e), "beacon"); len(f) != 0 {
t.Fatalf("%+v", f)
}
}
func TestNTPExemption(t *testing.T) {
bad := func(a netip.Addr) (bool, string) { return a == ip("203.0.113.99"), "known attacker" }
e := newEng(t, Config{BadDst: bad})
rnd := rand.New(rand.NewSource(1))
feedBeacon(e, "10.0.3.5", "203.0.113.10", 123, t0, 50, 128*time.Second, 0, rnd) // normal poll: exempt
feedBeacon(e, "10.0.3.5", "203.0.113.11", 123, t0, 50, 60*time.Second, 0, rnd) // fast NTP: not exempt
feedBeacon(e, "10.0.3.5", "203.0.113.99", 123, t0, 50, 128*time.Second, 0, rnd) // bad dst: never exempt
got := map[string]bool{}
for _, f := range kinds(rep(e), "beacon") {
got[f.Dst] = true
}
if got["203.0.113.10"] || !got["203.0.113.11"] || !got["203.0.113.99"] {
t.Fatalf("%v", got)
}
}
func TestBeaconDuringContinuousScan(t *testing.T) {
e := newEng(t, Config{Workloads: "ciberlab=10.0.5.0/24:scanner"})
// a light scan every 4 min (each opens or keeps the burst alive) for 2 h; the C2
// is contacted every 60 s starting 12 min AFTER the first burst opened
var evs []Event
for k := 0; k < 30; k++ {
for i := 0; i < 60; i++ {
evs = append(evs, mk(t0.Add(time.Duration(k)*4*time.Minute+time.Duration(i)*time.Second), "10.0.5.2",
fmt.Sprintf("198.18.%d.%d", k, 1+i), "tcp", 443))
}
}
for i := 0; i < 100; i++ {
evs = append(evs, mk(t0.Add(12*time.Minute+time.Duration(i)*time.Minute+30*time.Second), "10.0.5.2", "203.0.113.77", "tcp", 8443))
}
sort.SliceStable(evs, func(i, j int) bool { return evs[i].Time.Before(evs[j].Time) })
for _, ev := range evs {
e.IngestEvent(ev)
}
var found bool
for _, f := range kinds(rep(e), "beacon") {
found = found || f.Dst == "203.0.113.77"
}
if !found {
t.Fatalf("C2 invisible during the continuous scan: %+v", rep(e).Findings)
}
if e.fanSeen.len() > maxFanSeen {
t.Fatal("fanSeen unbounded")
}
}
+869
View File
@@ -0,0 +1,869 @@
package egress
import (
"container/list"
"fmt"
"hash/fnv"
"math"
"net/netip"
"os"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
)
// Limits and thresholds.
const (
MaxPairs = 50000
MaxDsts = 50000
MaxFindings = 2000
HourBuckets = 720 // 30 days
maxWorkloads = 256
maxClosedBurst = 200
maxFanSeen = 20000 // (workload,dst,port,proto) tuples seen only as fan-out
fanPromoteN = 3 // hits within fanPromoteWin that turn a fan-out flow into a pair
fanPromoteWin = 3600
fanDsts = 50
fanPorts = 100
fanWindow = 600 // seconds
burstQuiet = 300 // a burst closes after 5 min without fan-out
maxWin = 8192
ringSize = 64
beaconMinN = 8
beaconSpan = 1800
beaconMinIv = 10
beaconMaxIv = 6 * 3600
beaconCV = 0.25
beaconMAD = 0.20
setCap = 64
ntpMinIv = 64
)
// Config of the engine.
type Config struct {
// Workloads: "ciberlab=10.0.5.0/24:scanner;mail=name:protocols:mail".
Workloads string
// Resolvers lists the allowed DNS resolvers (comma separated IPs). Rule:
// DNS (53 tcp/udp) or DoT (853) from a non-resolver workload to a public
// address that is not an allowed resolver is "dns_bypass". When the list is
// empty the allowed set is the usual public resolvers (Cloudflare, Google,
// Quad9, OpenDNS), so only DoT and port 53 to unusual public IPs alert.
Resolvers string
// Allow lists destinations that never produce a finding (peers, own servers).
Allow []netip.Prefix
// Containers is the path of the containers.map file (optional); it is
// reloaded when its mtime changes.
Containers string
// Geo enriches a destination (cc, asn, org); BadDst says whether a
// destination is a known attacker or Tor exit (and why).
Geo func(ip string) (cc, asn, org string)
BadDst func(netip.Addr) (bool, string)
Now func() time.Time
// Learn is the per-workload learning time before new_geo (default 24h).
Learn time.Duration
// ResolvConf lists resolv.conf files whose nameservers are allowed resolvers
// (default: /etc/resolv.conf and /logs/host/resolv.conf, both optional).
ResolvConf []string
}
var usualResolvers = []string{"1.1.1.1", "1.0.0.1", "8.8.8.8", "8.8.4.4", "9.9.9.9", "149.112.112.112",
"208.67.222.222", "208.67.220.220", "2606:4700:4700::1111", "2606:4700:4700::1001",
"2001:4860:4860::8888", "2001:4860:4860::8844", "2620:fe::fe"}
type lru[K comparable, V any] struct {
cap int
l *list.List
m map[K]*list.Element
}
type lent[K comparable, V any] struct {
k K
v V
}
func newLRU[K comparable, V any](n int) *lru[K, V] {
return &lru[K, V]{cap: n, l: list.New(), m: map[K]*list.Element{}}
}
func (c *lru[K, V]) get(k K) (v V, ok bool) {
el, ok := c.m[k]
if !ok {
return v, false
}
c.l.MoveToFront(el)
return el.Value.(*lent[K, V]).v, true
}
func (c *lru[K, V]) put(k K, v V) {
if el, ok := c.m[k]; ok {
el.Value.(*lent[K, V]).v = v
c.l.MoveToFront(el)
return
}
c.m[k] = c.l.PushFront(&lent[K, V]{k, v})
if c.l.Len() > c.cap {
el := c.l.Back()
delete(c.m, el.Value.(*lent[K, V]).k)
c.l.Remove(el)
}
}
func (c *lru[K, V]) len() int { return c.l.Len() }
type pairKey struct {
wl string
dst netip.Addr
dport uint16
proto string
}
type pairState struct {
ts [ringSize]uint32
n int
total uint32
fan, nonFan uint32
first, last int64
flagged bool
fkey string
interval, cv float64
}
func (p *pairState) add(t int64, fan bool) {
if p.total == 0 {
p.first = t
}
p.total++
if fan {
p.fan++
} else {
p.nonFan++
}
if p.n > 0 && t-int64(p.ts[p.n-1]) < 2 {
p.last = t
return // retries of the same second are one beat
}
if p.n == ringSize {
copy(p.ts[:], p.ts[1:])
p.n--
}
p.ts[p.n] = uint32(t)
p.n++
p.last = t
}
type dayN struct {
day int32
n uint32
}
type dstStat struct {
ip netip.Addr
cc, asn, og string
days []dayN
wls []string
ports []uint16
}
type hbucket struct {
hour int64
conns, supp uint32
dsts, ports []uint32
}
type burstState struct {
start, lastFan int64
conns, badHits uint32
targets map[netip.Addr]struct{}
nets map[netip.Prefix]uint32
ports map[uint16]uint32
}
type wstate struct {
name, role string
first int64
hours [HourBuckets]hbucket
win map[netip.Addr]int64
wports map[uint16]int64
lastPrune int64
burst *burstState
geo map[string]struct{}
// recent are the normal flows of the fan-out window: when a burst opens
// they are re-read as part of it (the first 49 probes of a scan).
recent []winFlow
}
type winFlow struct {
pk pairKey
t int64
badKey string // bad_dst finding this flow raised, if any
}
// Engine analyses egress events. Safe for concurrent use.
type Engine struct {
mu sync.Mutex
cfg Config
wls []workloadDef
resolvers map[netip.Addr]bool
now func() time.Time
containers map[netip.Addr]string
mapMod time.Time
mapCheck time.Time
ws map[string]*wstate
pairs *lru[pairKey, *pairState]
dsts *lru[netip.Addr, *dstStat]
fanSeen *lru[pairKey, *fanRec]
findings map[string]*Finding
closed []BurstOut
maxT int64
lines, malformed atomic.Uint64
last atomic.Int64
stateFn atomic.Pointer[func() string]
}
// New builds an engine.
func New(c Config) (*Engine, error) {
wls, err := ParseWorkloads(c.Workloads)
if err != nil {
return nil, err
}
e := &Engine{cfg: c, wls: wls, now: c.Now, resolvers: map[netip.Addr]bool{}, containers: map[netip.Addr]string{},
ws: map[string]*wstate{}, pairs: newLRU[pairKey, *pairState](MaxPairs), dsts: newLRU[netip.Addr, *dstStat](MaxDsts),
findings: map[string]*Finding{}, fanSeen: newLRU[pairKey, *fanRec](maxFanSeen)}
if e.now == nil {
e.now = time.Now
}
if e.cfg.Learn <= 0 {
e.cfg.Learn = 24 * time.Hour
}
list := strings.Split(c.Resolvers, ",")
if strings.TrimSpace(c.Resolvers) == "" {
list = usualResolvers
}
for _, s := range list {
if s = strings.TrimSpace(s); s == "" {
continue
}
a, err := netip.ParseAddr(s)
if err != nil {
return nil, fmt.Errorf("resolver %q: %w", s, err)
}
e.resolvers[a.Unmap()] = true
}
rc := c.ResolvConf
if rc == nil {
rc = []string{"/etc/resolv.conf", "/logs/host/resolv.conf"}
}
for _, p := range rc {
for _, a := range readNameservers(p) {
e.resolvers[a] = true
}
}
return e, nil
}
// readNameservers returns the nameserver addresses of a resolv.conf (missing file: none).
func readNameservers(path string) []netip.Addr {
b, err := os.ReadFile(path)
if err != nil {
return nil
}
var out []netip.Addr
for _, ln := range strings.Split(string(b), "\n") {
f := strings.Fields(ln)
if len(f) >= 2 && f[0] == "nameserver" {
if a, err := netip.ParseAddr(f[1]); err == nil {
out = append(out, a.WithZone("").Unmap())
}
}
if len(out) >= 16 {
break
}
}
return out
}
// fanRec accumulates the sightings of a flow that was only ever seen as fan-out.
type fanRec struct{ ts []int64 }
// fanPromote records one fan-out sighting; when the same flow shows up
// fanPromoteN times within the hour it is a real pair (a C2 contacted during a
// continuous scan), returned with its accumulated timestamps.
func (e *Engine) fanPromote(pk pairKey, t int64) *pairState {
r, ok := e.fanSeen.get(pk)
if !ok {
r = &fanRec{}
e.fanSeen.put(pk, r)
}
k := 0
for _, x := range r.ts {
if t-x <= fanPromoteWin {
r.ts[k] = x
k++
}
}
r.ts = r.ts[:k]
if n := len(r.ts); n == 0 || t-r.ts[n-1] >= 2 { // retries of the same second are one beat
r.ts = append(r.ts, t)
}
if len(r.ts) < fanPromoteN {
return nil
}
p := &pairState{}
for _, x := range r.ts[:len(r.ts)-1] {
p.add(x, false)
}
if el, ok := e.fanSeen.m[pk]; ok {
e.fanSeen.l.Remove(el)
delete(e.fanSeen.m, pk)
}
return p
}
// SetContainers replaces the address to container-name map (tests, wiring).
func (e *Engine) SetContainers(m map[netip.Addr]string) {
e.mu.Lock()
e.containers = m
e.mu.Unlock()
}
func (e *Engine) reloadMap() {
if e.cfg.Containers == "" {
return
}
n := e.now()
if n.Sub(e.mapCheck) < 5*time.Second {
return
}
e.mapCheck = n
fi, err := os.Stat(e.cfg.Containers)
if err != nil || fi.ModTime().Equal(e.mapMod) {
return
}
if m, err := LoadContainers(e.cfg.Containers); err == nil {
e.containers, e.mapMod = m, fi.ModTime()
}
}
// Ingest parses and analyses one log line.
func (e *Engine) Ingest(line []byte) {
ev, err := ParseLine(line, e.now())
if err != nil {
if len(line) > 0 {
e.malformed.Add(1)
}
return
}
e.lines.Add(1)
e.last.Store(e.now().Unix())
e.IngestEvent(ev)
}
// IngestEvent analyses one parsed event.
func (e *Engine) IngestEvent(ev Event) {
e.mu.Lock()
defer e.mu.Unlock()
e.ingest(ev)
}
func (e *Engine) allowed(a netip.Addr) bool {
for _, p := range e.cfg.Allow {
if p.Contains(a) {
return true
}
}
return false
}
func fanCounts(role string, ev Event) bool {
switch {
case role == RoleMail && (ev.DPort == 25 || ev.DPort == 465 || ev.DPort == 587):
return false // a mail server legitimately talks to many MX
case role == RoleResolver && ev.DPort == 53:
return false // a recursive resolver talks to many authoritative servers
}
return true
}
func (e *Engine) wstate(name, role string, t int64) *wstate {
if w, ok := e.ws[name]; ok {
return w
}
if len(e.ws) >= maxWorkloads {
name, role = "container other", RoleDefault
if w, ok := e.ws[name]; ok {
return w
}
}
w := &wstate{name: name, role: role, first: t, win: map[netip.Addr]int64{}, wports: map[uint16]int64{}, geo: map[string]struct{}{}}
e.ws[name] = w
return w
}
func h32(a netip.Addr) uint32 {
b := a.As16()
h := fnv.New32a()
h.Write(b[:])
return h.Sum32()
}
func addSet(s []uint32, v uint32) []uint32 {
for _, x := range s {
if x == v {
return s
}
}
if len(s) >= setCap {
return s
}
return append(s, v)
}
func (w *wstate) bucket(t int64) *hbucket {
h := t / 3600
b := &w.hours[h%HourBuckets]
if b.hour != h {
*b = hbucket{hour: h}
}
return b
}
func (e *Engine) ingest(ev Event) {
t := ev.Time.Unix()
if t <= 0 {
return
}
if t > e.maxT {
e.maxT = t
}
e.reloadMap()
name, role := e.resolve(ev)
ws := e.wstate(name, role, t)
role = ws.role
allowed := e.allowed(ev.Dst)
dport := ev.DPort
if ev.Proto == "icmp" {
dport = 0
}
counts := !allowed && fanCounts(role, ev)
if ws.burst != nil && t-ws.burst.lastFan > burstQuiet {
e.closeBurst(ws)
}
if counts && ws.burst == nil {
e.window(ws, ev.Dst, dport, t)
}
inBurst := counts && ws.burst != nil
pk := pairKey{ws.name, ev.Dst, dport, ev.Proto}
p, _ := e.pairs.get(pk)
fan := inBurst && (p == nil || p.nonFan < 3)
if p == nil && fan && !allowed {
if np := e.fanPromote(pk, t); np != nil {
p, fan = np, false
e.pairs.put(pk, p)
}
}
if p == nil && !fan && !allowed {
p = &pairState{}
e.pairs.put(pk, p) // fan-out flows create pairs only when repeated: a scan must not evict real ones
}
if p != nil {
p.add(t, fan)
}
scanner := role == RoleScanner
if fan {
e.burstFlow(ws, ev, dport, t, scanner)
if scanner {
ws.bucket(t).supp++
return
}
}
b := ws.bucket(t)
b.conns++
if counts && ws.burst == nil && len(ws.recent) < maxWin {
ws.recent = append(ws.recent, winFlow{pk: pk, t: t})
}
b.dsts = addSet(b.dsts, h32(ev.Dst))
b.ports = addSet(b.ports, uint32(dport))
ds := e.dstStat(ws.name, ev.Dst, dport, t)
if allowed {
return
}
e.checks(ws, ev, dport, t, ds, p, fan)
if n := len(ws.recent); n > 0 && ws.recent[n-1].t == t && ws.recent[n-1].pk == pk {
if f := e.findings[fmt.Sprintf("bad_dst|%s|%s|%d", ws.name, ev.Dst, dport)]; f != nil {
ws.recent[n-1].badKey = fmt.Sprintf("bad_dst|%s|%s|%d", ws.name, ev.Dst, dport)
}
}
}
// retro re-reads the flows seen before the burst opened as part of it.
func (e *Engine) retro(ws *wstate) {
cnt := map[pairKey]uint32{}
for _, f := range ws.recent {
cnt[f.pk]++
}
moved := map[pairKey]bool{}
for pk, n := range cnt {
// a pair established before the window, or hit 4+ times inside it (a probe is hit once or retried), stays normal
if p, ok := e.pairs.get(pk); ok && n < 4 && p.nonFan >= n && p.nonFan-n < 3 {
p.fan += n
p.nonFan -= n
moved[pk] = true
} else if !ok && n < 4 {
moved[pk] = true // evicted pair: still a probe
}
}
for _, f := range ws.recent {
if !moved[f.pk] {
continue
}
if ws.role != RoleScanner {
continue
}
b := &ws.hours[(f.t/3600)%HourBuckets]
if b.hour == f.t/3600 && b.conns > 0 {
b.conns--
b.supp++
}
if ds, ok := e.dsts.get(f.pk.dst); ok {
for i := range ds.days {
if ds.days[i].day == int32(f.t/86400) && ds.days[i].n > 0 {
ds.days[i].n--
}
}
}
if f.badKey != "" {
if fd := e.findings[f.badKey]; fd != nil {
if fd.Count--; fd.Count <= 0 {
delete(e.findings, f.badKey)
}
ws.burst.badHits++
}
}
}
ws.recent = ws.recent[:0]
}
func (e *Engine) window(ws *wstate, dst netip.Addr, dport uint16, t int64) {
if t-ws.lastPrune >= 10 {
for k, v := range ws.win {
if t-v > fanWindow {
delete(ws.win, k)
}
}
for k, v := range ws.wports {
if t-v > fanWindow {
delete(ws.wports, k)
}
}
ws.lastPrune = t
k := 0
for _, f := range ws.recent {
if t-f.t <= fanWindow {
ws.recent[k] = f
k++
}
}
ws.recent = ws.recent[:k]
}
if _, ok := ws.win[dst]; ok || len(ws.win) < maxWin {
ws.win[dst] = t
}
if dport != 0 {
ws.wports[dport] = t
}
if len(ws.win) >= fanDsts || len(ws.wports) >= fanPorts {
start := t
for _, v := range ws.win {
if v < start {
start = v
}
}
ws.burst = &burstState{start: start, lastFan: t, targets: map[netip.Addr]struct{}{},
nets: map[netip.Prefix]uint32{}, ports: map[uint16]uint32{}}
clear(ws.win)
clear(ws.wports)
e.retro(ws)
}
}
func (e *Engine) burstFlow(ws *wstate, ev Event, dport uint16, t int64, scanner bool) {
bs := ws.burst
bs.lastFan = t
bs.conns++
if len(bs.targets) < 50000 {
bs.targets[ev.Dst] = struct{}{}
}
bits := 24
if ev.Dst.Is6() {
bits = 48
}
np, _ := ev.Dst.Prefix(bits)
if _, ok := bs.nets[np]; ok || len(bs.nets) < 512 {
bs.nets[np]++
}
if dport != 0 {
if _, ok := bs.ports[dport]; ok || len(bs.ports) < 1024 {
bs.ports[dport]++
}
}
if scanner {
if e.cfg.BadDst != nil {
if bad, _ := e.cfg.BadDst(ev.Dst); bad {
bs.badHits++
}
}
return
}
if bs.conns%32 == 1 {
e.addFinding("scan", "high", ws.name, "", 0, "", t, 0, 0, bs.detail(), 1)
} else {
e.addFinding("scan", "high", ws.name, "", 0, "", t, 0, 0, "", 1)
}
}
func (bs *burstState) detail() string {
return fmt.Sprintf("fan-out: %d targets, %d ports, %d connections", len(bs.targets), len(bs.ports), bs.conns)
}
func (e *Engine) closeBurst(ws *wstate) {
bs := ws.burst
ws.burst = nil
ws.recent = ws.recent[:0]
clear(ws.win)
clear(ws.wports)
if ws.role != RoleScanner {
e.addFinding("scan", "high", ws.name, "", 0, "", bs.lastFan, 0, 0, bs.detail(), 0)
return
}
e.closed = append(e.closed, bs.out(ws.name, bs.lastFan))
if len(e.closed) > maxClosedBurst {
e.closed = e.closed[len(e.closed)-maxClosedBurst:]
}
}
func (e *Engine) dstStat(wl string, dst netip.Addr, dport uint16, t int64) *dstStat {
ds, ok := e.dsts.get(dst)
if !ok {
ds = &dstStat{ip: dst}
if e.cfg.Geo != nil && isGlobal(dst) {
ds.cc, ds.asn, ds.og = e.cfg.Geo(dst.String())
}
e.dsts.put(dst, ds)
}
day := int32(t / 86400)
if n := len(ds.days); n > 0 && ds.days[n-1].day == day {
ds.days[n-1].n++
} else if n == 0 || ds.days[n-1].day < day {
ds.days = append(ds.days, dayN{day, 1})
if len(ds.days) > 30 {
ds.days = ds.days[1:]
}
}
has := false
for _, w := range ds.wls {
has = has || w == wl
}
if !has && len(ds.wls) < 8 {
ds.wls = append(ds.wls, wl)
}
hp := false
for _, p := range ds.ports {
hp = hp || p == dport
}
if !hp && len(ds.ports) < 8 {
ds.ports = append(ds.ports, dport)
}
return ds
}
func isGlobal(a netip.Addr) bool {
return a.IsValid() && !a.IsPrivate() && !a.IsLoopback() && !a.IsLinkLocalUnicast() && !a.IsMulticast() &&
!a.IsUnspecified() && !a.IsLinkLocalMulticast() && !isCGNAT(a)
}
var cgnat = netip.MustParsePrefix("100.64.0.0/10")
func isCGNAT(a netip.Addr) bool { return cgnat.Contains(a) }
func (e *Engine) isResolver(a netip.Addr) bool { return e.resolvers[a] }
func (e *Engine) checks(ws *wstate, ev Event, dport uint16, t int64, ds *dstStat, p *pairState, fan bool) {
dst := ev.Dst.String()
if e.cfg.BadDst != nil {
if bad, why := e.cfg.BadDst(ev.Dst); bad {
e.addFinding("bad_dst", "high", ws.name, dst, dport, ev.Proto, t, 0, 0, why, 1)
}
}
if ev.Proto == "tcp" {
if sev, why := suspiciousPort(dport, ws.role); why != "" {
e.addFinding("port", sev, ws.name, dst, dport, ev.Proto, t, 0, 0, why, 1)
}
}
dns := dport == 53 && (ev.Proto == "udp" || ev.Proto == "tcp") || dport == 853 && ev.Proto == "tcp"
if dns && ws.role != RoleResolver && isGlobal(ev.Dst) && !e.isResolver(ev.Dst) {
e.addFinding("dns_bypass", "medium", ws.name, dst, dport, ev.Proto, t, 0, 0, "DNS to a resolver that is not allowed", 1)
}
if p != nil {
e.beacon(ws, ev, dport, dns, p, ds)
}
if ws.role != RoleScanner && !fan && ds.cc != "" && isGlobal(ev.Dst) {
if _, seen := ws.geo[ds.cc]; !seen {
ws.geo[ds.cc] = struct{}{}
if t-ws.first >= int64(e.cfg.Learn/time.Second) {
e.addFinding("new_geo", "low", ws.name, dst, dport, ev.Proto, t, 0, 0, "first contact with country "+ds.cc+" "+ds.asn, 1)
}
} else if len(ws.geo) > 300 {
ws.geo = map[string]struct{}{}
}
}
}
func suspiciousPort(port uint16, role string) (sev, why string) {
switch port {
case 25, 465, 587:
if role != RoleMail {
return "medium", "SMTP from a non-mail workload (spam)"
}
case 6667, 6697:
return "medium", "IRC (classic botnet C2)"
case 3333, 14444, 45700:
return "high", "mining pool (stratum)"
case 4444, 5555, 7777:
return "medium", "probable mining pool (stratum) or reverse shell"
case 9001, 9030:
return "medium", "Tor ORPort"
}
return "", ""
}
func (e *Engine) beacon(ws *wstate, ev Event, dport uint16, dns bool, p *pairState, ds *dstStat) {
if p.flagged {
e.addFinding("beacon", "", ws.name, ev.Dst.String(), dport, ev.Proto, p.last, p.interval, p.cv, "", 1)
return
}
ntp := ev.Proto == "udp" && dport == 123
switch {
case dns && e.isResolver(ev.Dst):
return
case ws.role == RoleResolver && dport == 53:
return
case p.n < beaconMinN || int64(p.ts[p.n-1])-int64(p.ts[0]) < beaconSpan:
return
case p.fan > p.nonFan:
return // mostly a fan-out target (a daily scan target is not a beacon)
case p.total%4 != 0:
return // evaluate every fourth flow: the statistics allocate
}
iv := make([]float64, p.n-1)
var sum float64
for i := range iv {
iv[i] = float64(p.ts[i+1] - p.ts[i])
sum += iv[i]
}
med := median(iv)
if med < beaconMinIv || med > beaconMaxIv {
return
}
if ntp { // NTP is exempt only at a normal poll rate and never towards a bad destination
bad := false
if e.cfg.BadDst != nil {
bad, _ = e.cfg.BadDst(ev.Dst)
}
if !bad && med >= ntpMinIv {
return
}
}
mean := sum / float64(len(iv))
var ss float64
dev := make([]float64, len(iv))
for i, v := range iv {
ss += (v - mean) * (v - mean)
dev[i] = math.Abs(v - med)
}
cv := math.Sqrt(ss/float64(len(iv))) / mean
mad := median(dev) / med
if cv > beaconCV && mad > beaconMAD {
return
}
jit := cv
if mad < cv {
jit = mad
}
sev := "medium"
why := fmt.Sprintf("regular connections every %.0f s (jitter %.0f%%)", med, jit*100)
if e.cfg.BadDst != nil {
if bad, r := e.cfg.BadDst(ev.Dst); bad {
sev, why = "high", why+"; destination: "+r
}
}
p.flagged, p.interval, p.cv = true, med, jit
f := e.addFinding("beacon", sev, ws.name, ev.Dst.String(), dport, ev.Proto, p.last, med, jit, why, 0)
if f != nil {
f.Count, f.First = int(p.total), p.first
}
}
func median(v []float64) float64 {
s := append([]float64(nil), v...)
sort.Float64s(s)
n := len(s)
if n == 0 {
return 0
}
if n%2 == 1 {
return s[n/2]
}
return (s[n/2-1] + s[n/2]) / 2
}
var sevRank = map[string]int{"low": 1, "medium": 2, "high": 3}
func (e *Engine) addFinding(kind, sev, wl, dst string, dport uint16, proto string, t int64, iv, jit float64, detail string, inc int) *Finding {
key := fmt.Sprintf("%s|%s|%s|%d", kind, wl, dst, dport)
if f, ok := e.findings[key]; ok {
f.Count += inc
if t > f.Last {
f.Last = t
}
if sevRank[sev] > sevRank[f.Severity] {
f.Severity = sev
}
if detail != "" {
f.Detail = detail
}
if iv > 0 {
f.IntervalS, f.Jitter = iv, jit
}
return f
}
if sev == "" {
return nil // an update for a finding that was evicted
}
if len(e.findings) >= MaxFindings {
var worst string
var wf *Finding
for k, f := range e.findings {
if wf == nil || sevRank[f.Severity] < sevRank[wf.Severity] || sevRank[f.Severity] == sevRank[wf.Severity] && f.Last < wf.Last {
worst, wf = k, f
}
}
delete(e.findings, worst)
}
h := fnv.New64a()
h.Write([]byte(key))
f := &Finding{ID: fmt.Sprintf("e%016x", h.Sum64()), Kind: kind, Severity: sev, Workload: wl, Dst: dst, DPort: dport, Proto: proto,
Count: inc, IntervalS: iv, Jitter: jit, First: t, Last: t, Detail: detail}
e.findings[key] = f
return f
}
// Counters for the source status.
func (e *Engine) counters() (lines, malformed uint64, last int64) {
return e.lines.Load(), e.malformed.Load(), e.last.Load()
}
+105
View File
@@ -0,0 +1,105 @@
// Package egress analyses the outbound connections of the host and its
// containers (nftables "URUTAU-EGRESS: " log lines) to spot a compromised
// workload: beaconing, C2, mining, spam, unauthorised scanning.
//
// Central principle: traffic shaped like a scan (fan-out) is suppressed only
// for workloads with role=scanner. Traffic that is not scan shaped is judged
// the same for every workload, the scanner included.
package egress
import (
"errors"
"net/netip"
"strconv"
"strings"
"time"
)
const marker = "URUTAU-EGRESS:"
// Event is one new outbound connection.
type Event struct {
Time time.Time
Src, Dst netip.Addr
Proto string // tcp, udp, icmp, or the lowercased PROTO value
SPort, DPort uint16
In, Out string
Host bool // IN= empty: output of the host itself
}
// ErrNotEgress marks a line that is not an egress log line.
var ErrNotEgress = errors.New("not an egress line")
// ParseLine parses a kernel/rsyslog line. now is only used to infer the year
// of the "Nov 14 22:01:02" rsyslog format (and as the time of a line whose
// timestamp is unreadable).
func ParseLine(b []byte, now time.Time) (Event, error) {
line := string(b)
i := strings.Index(line, marker)
if i < 0 {
return Event{}, ErrNotEgress
}
ev := Event{Time: parseTS(line[:i], now)}
var haveSrc, haveDst bool
for _, f := range strings.Fields(line[i+len(marker):]) {
k, v, ok := strings.Cut(f, "=")
if !ok {
continue
}
switch k {
case "IN":
ev.In = v
case "OUT":
ev.Out = v
case "SRC":
a, err := netip.ParseAddr(v)
if err != nil {
return Event{}, errors.New("bad SRC")
}
ev.Src, haveSrc = a.Unmap(), true
case "DST":
a, err := netip.ParseAddr(v)
if err != nil {
return Event{}, errors.New("bad DST")
}
ev.Dst, haveDst = a.Unmap(), true
case "PROTO":
p := strings.ToLower(v)
if strings.HasPrefix(p, "icmp") {
p = "icmp"
}
ev.Proto = p
case "SPT":
n, _ := strconv.ParseUint(v, 10, 16)
ev.SPort = uint16(n)
case "DPT":
n, _ := strconv.ParseUint(v, 10, 16)
ev.DPort = uint16(n)
}
}
if !haveSrc || !haveDst || ev.Proto == "" {
return Event{}, errors.New("incomplete egress line")
}
ev.Host = ev.In == ""
return ev, nil
}
func parseTS(prefix string, now time.Time) time.Time {
f := strings.Fields(prefix)
if len(f) == 0 {
return now
}
if t, err := time.Parse(time.RFC3339Nano, f[0]); err == nil {
return t
}
if len(f) >= 3 {
if t, err := time.ParseInLocation("Jan 2 15:04:05", f[0]+" "+f[1]+" "+f[2], now.Location()); err == nil {
t = t.AddDate(now.Year(), 0, 0)
if t.After(now.Add(48 * time.Hour)) {
t = t.AddDate(-1, 0, 0)
}
return t
}
}
return now
}
+371
View File
@@ -0,0 +1,371 @@
package egress
import (
"net/netip"
"sort"
"strings"
)
// Finding is one alert; repeated observations update it.
type Finding struct {
ID string `json:"id"`
Kind string `json:"kind"`
Severity string `json:"severity"`
Workload string `json:"workload"`
Dst string `json:"dst"`
DPort uint16 `json:"dport"`
Proto string `json:"proto"`
Count int `json:"count"`
IntervalS float64 `json:"interval_s"`
Jitter float64 `json:"jitter"`
First int64 `json:"first"`
Last int64 `json:"last"`
Detail string `json:"detail"`
Host string `json:"host,omitempty"`
}
// WorkloadOut summarises a workload over the window.
type WorkloadOut struct {
Name string `json:"name"`
Role string `json:"role"`
Conns uint64 `json:"conns"`
Dsts int `json:"dsts"`
Ports int `json:"ports"`
Findings int `json:"findings"`
Suppressed uint64 `json:"suppressed_scan_conns"`
Host string `json:"host,omitempty"`
}
// Timeline holds hourly connection counts per workload.
type Timeline struct {
Start int64 `json:"start"`
Step int64 `json:"step"`
Series map[string][]uint32 `json:"series"`
}
// DstOut is a top destination.
type DstOut struct {
IP string `json:"ip"`
CC string `json:"cc"`
ASN string `json:"asn"`
Org string `json:"org"`
Conns uint64 `json:"conns"`
Workloads []string `json:"workloads"`
Ports []uint16 `json:"ports"`
}
// BurstOut summarises a scanner fan-out burst.
type BurstOut struct {
Workload string `json:"workload"`
Start int64 `json:"start"`
End int64 `json:"end"`
Targets int `json:"targets"`
Nets []string `json:"nets"`
Ports []uint16 `json:"ports"`
Conns uint32 `json:"conns"`
BadDstHit uint32 `json:"bad_dst_hits"`
Host string `json:"host,omitempty"`
}
// ScannerOut groups the scanner bursts.
type ScannerOut struct {
Bursts []BurstOut `json:"bursts"`
}
// Report is the egress analysis of a window.
type Report struct {
Workloads []WorkloadOut `json:"workloads"`
Timeline Timeline `json:"timeline"`
TopDst []DstOut `json:"top_dst"`
Findings []Finding `json:"findings"`
Scanner ScannerOut `json:"scanner"`
}
func (bs *burstState) out(wl string, end int64) BurstOut {
o := BurstOut{Workload: wl, Start: bs.start, End: end, Targets: len(bs.targets), Conns: bs.conns, BadDstHit: bs.badHits,
Nets: []string{}, Ports: []uint16{}}
type nc struct {
p netip.Prefix
n uint32
}
var ns []nc
for p, n := range bs.nets {
ns = append(ns, nc{p, n})
}
sort.Slice(ns, func(i, j int) bool {
if ns[i].n != ns[j].n {
return ns[i].n > ns[j].n
}
return ns[i].p.String() < ns[j].p.String()
})
for i := 0; i < len(ns) && i < 10; i++ {
o.Nets = append(o.Nets, ns[i].p.String())
}
type pc struct {
p uint16
n uint32
}
var ps []pc
for p, n := range bs.ports {
ps = append(ps, pc{p, n})
}
sort.Slice(ps, func(i, j int) bool {
if ps[i].n != ps[j].n {
return ps[i].n > ps[j].n
}
return ps[i].p < ps[j].p
})
for i := 0; i < len(ps) && i < 10; i++ {
o.Ports = append(o.Ports, ps[i].p)
}
return o
}
// Report builds the analysis of [from, to] (unix seconds).
func (e *Engine) Report(from, to int64) Report {
e.mu.Lock()
defer e.mu.Unlock()
if to <= from {
to = from + 1
}
startH, endH := from/3600, to/3600
if endH-startH > HourBuckets-1 {
startH = endH - (HourBuckets - 1)
}
nb := int(endH-startH) + 1
r := Report{Workloads: []WorkloadOut{}, TopDst: []DstOut{}, Findings: []Finding{},
Timeline: Timeline{Start: startH * 3600, Step: 3600, Series: map[string][]uint32{}},
Scanner: ScannerOut{Bursts: []BurstOut{}}}
fc := map[string]int{}
for _, f := range e.findings {
if f.Last >= from && f.First <= to {
r.Findings = append(r.Findings, *f)
fc[f.Workload]++
}
}
sort.Slice(r.Findings, func(i, j int) bool {
a, b := r.Findings[i], r.Findings[j]
if sevRank[a.Severity] != sevRank[b.Severity] {
return sevRank[a.Severity] > sevRank[b.Severity]
}
if a.Last != b.Last {
return a.Last > b.Last
}
return a.ID < b.ID
})
names := make([]string, 0, len(e.ws))
for n := range e.ws {
names = append(names, n)
}
sort.Strings(names)
for _, n := range names {
w := e.ws[n]
o := WorkloadOut{Name: n, Role: w.role, Findings: fc[n]}
series := make([]uint32, nb)
ds, ps := map[uint32]struct{}{}, map[uint32]struct{}{}
for h := startH; h <= endH; h++ {
b := &w.hours[h%HourBuckets]
if b.hour != h {
continue
}
series[h-startH] = b.conns
o.Conns += uint64(b.conns)
o.Suppressed += uint64(b.supp)
for _, x := range b.dsts {
ds[x] = struct{}{}
}
for _, x := range b.ports {
ps[x] = struct{}{}
}
}
o.Dsts, o.Ports = len(ds), len(ps)
if o.Conns == 0 && o.Suppressed == 0 && o.Findings == 0 {
continue
}
r.Workloads = append(r.Workloads, o)
r.Timeline.Series[n] = series
}
type scored struct {
ds *dstStat
n uint64
}
var all []scored
d0, d1 := int32(from/86400), int32(to/86400)
for el := e.dsts.l.Front(); el != nil; el = el.Next() {
ds := el.Value.(*lent[netip.Addr, *dstStat]).v
var n uint64
for _, d := range ds.days {
if d.day >= d0 && d.day <= d1 {
n += uint64(d.n)
}
}
if n > 0 {
all = append(all, scored{ds, n})
}
}
sort.Slice(all, func(i, j int) bool {
if all[i].n != all[j].n {
return all[i].n > all[j].n
}
return all[i].ds.ip.Compare(all[j].ds.ip) < 0
})
for i := 0; i < len(all) && i < 50; i++ {
ds := all[i].ds
ports := append([]uint16(nil), ds.ports...)
sort.Slice(ports, func(a, b int) bool { return ports[a] < ports[b] })
r.TopDst = append(r.TopDst, DstOut{IP: ds.ip.String(), CC: ds.cc, ASN: ds.asn, Org: ds.og, Conns: all[i].n,
Workloads: append([]string{}, ds.wls...), Ports: ports})
}
for _, b := range e.closed {
if b.End >= from && b.Start <= to {
r.Scanner.Bursts = append(r.Scanner.Bursts, b)
}
}
for _, n := range names {
if w := e.ws[n]; w.burst != nil && w.role == RoleScanner && w.burst.lastFan >= from && w.burst.start <= to {
r.Scanner.Bursts = append(r.Scanner.Bursts, w.burst.out(n, w.burst.lastFan))
}
}
return r
}
const (
maxPeerWorkloads = 256
maxPeerFindings = MaxFindings
maxStr = 200
)
func clip(s string) string {
if len(s) > maxStr {
return s[:maxStr]
}
return strings.ToValidUTF8(s, "")
}
// Sanitize bounds an untrusted peer report and stamps it with the peer name.
func (r *Report) Sanitize(host string) {
if len(r.Workloads) > maxPeerWorkloads {
r.Workloads = r.Workloads[:maxPeerWorkloads]
}
if len(r.Findings) > maxPeerFindings {
r.Findings = r.Findings[:maxPeerFindings]
}
if len(r.TopDst) > 50 {
r.TopDst = r.TopDst[:50]
}
if len(r.Scanner.Bursts) > maxClosedBurst+maxPeerWorkloads {
r.Scanner.Bursts = r.Scanner.Bursts[:maxClosedBurst+maxPeerWorkloads]
}
for i := range r.Workloads {
w := &r.Workloads[i]
w.Name, w.Role, w.Host = clip(w.Name), clip(w.Role), host
}
for i := range r.Findings {
f := &r.Findings[i]
f.ID, f.Kind, f.Severity = host+":"+clip(f.ID), clip(f.Kind), clip(f.Severity)
f.Workload, f.Dst, f.Proto, f.Detail, f.Host = clip(f.Workload), clip(f.Dst), clip(f.Proto), clip(f.Detail), host
}
for i := range r.TopDst {
d := &r.TopDst[i]
d.IP, d.CC, d.ASN, d.Org = clip(d.IP), clip(d.CC), clip(d.ASN), clip(d.Org)
if len(d.Workloads) > 8 {
d.Workloads = d.Workloads[:8]
}
for j := range d.Workloads {
d.Workloads[j] = clip(d.Workloads[j])
}
if len(d.Ports) > 8 {
d.Ports = d.Ports[:8]
}
}
for i := range r.Scanner.Bursts {
b := &r.Scanner.Bursts[i]
b.Workload, b.Host = clip(b.Workload), host
if len(b.Nets) > 10 {
b.Nets = b.Nets[:10]
}
for j := range b.Nets {
b.Nets[j] = clip(b.Nets[j])
}
if len(b.Ports) > 10 {
b.Ports = b.Ports[:10]
}
}
for k, v := range r.Timeline.Series {
if len(v) > HourBuckets {
r.Timeline.Series[k] = v[:HourBuckets]
}
}
if len(r.Timeline.Series) > maxPeerWorkloads {
r.Timeline.Series = map[string][]uint32{}
}
}
// Merge adds a sanitized peer report to r (the hub view). Series are keyed
// "host/workload" and placed on r's hourly grid.
func (r *Report) Merge(o Report, host string) {
r.Workloads = append(r.Workloads, o.Workloads...)
r.Findings = append(r.Findings, o.Findings...)
r.Scanner.Bursts = append(r.Scanner.Bursts, o.Scanner.Bursts...)
r.TopDst = append(r.TopDst, o.TopDst...)
sort.SliceStable(r.TopDst, func(i, j int) bool { return r.TopDst[i].Conns > r.TopDst[j].Conns })
if len(r.TopDst) > 50 {
r.TopDst = r.TopDst[:50]
}
sort.SliceStable(r.Findings, func(i, j int) bool {
a, b := r.Findings[i], r.Findings[j]
if sevRank[a.Severity] != sevRank[b.Severity] {
return sevRank[a.Severity] > sevRank[b.Severity]
}
return a.Last > b.Last
})
if len(r.Findings) > MaxFindings {
r.Findings = r.Findings[:MaxFindings]
}
if r.Timeline.Step == 0 {
r.Timeline.Step = 3600
}
for k, v := range o.Timeline.Series {
if r.Timeline.Start == 0 {
r.Timeline.Start = o.Timeline.Start
}
n := len(v)
off := int((o.Timeline.Start - r.Timeline.Start) / 3600)
for _, ex := range r.Timeline.Series {
n = len(ex)
break
}
dst := make([]uint32, n)
for i, x := range v {
if j := i + off; j >= 0 && j < n {
dst[j] = x
}
}
r.Timeline.Series[host+"/"+k] = dst
}
}
// Stamp marks the items of a trusted (local) report with its host name, as
// Sanitize does for a peer, so that a hub view can tell them apart.
func (r *Report) Stamp(host string) {
for i := range r.Workloads {
r.Workloads[i].Host = host
}
for i := range r.Findings {
r.Findings[i].Host = host
r.Findings[i].ID = host + ":" + r.Findings[i].ID
}
for i := range r.Scanner.Bursts {
r.Scanner.Bursts[i].Host = host
}
}
// EmptyReport is a well-formed report without data.
func EmptyReport() Report {
return Report{Workloads: []WorkloadOut{}, TopDst: []DstOut{}, Findings: []Finding{}, Scanner: ScannerOut{Bursts: []BurstOut{}},
Timeline: Timeline{Step: 3600, Series: map[string][]uint32{}}}
}
+110
View File
@@ -0,0 +1,110 @@
package egress
import (
"context"
"errors"
"log/slog"
"os"
"sync"
"sync/atomic"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/tail"
)
const maxLine = 16 * 1024
// Source follows the egress log file and feeds the engine. State is in memory
// only: on start the rotated backups and the live file are replayed from the
// beginning, which rebuilds the beacon history deterministically.
type Source struct {
Path string
E *Engine
Log *slog.Logger
backfilling atomic.Bool
fol atomic.Pointer[tail.Follower]
}
// NewSource creates the source of e reading path.
func NewSource(path string, e *Engine, log *slog.Logger) *Source {
if log == nil {
log = slog.Default()
}
s := &Source{Path: path, E: e, Log: log}
f := s.state
e.stateFn.Store(&f)
return s
}
func (s *Source) state() string {
switch f := s.fol.Load(); {
case s.backfilling.Load():
return "backfill"
case f == nil:
return "waiting"
default:
if err := f.Err(); err != nil {
if errors.Is(err, os.ErrNotExist) {
return "waiting"
}
return "error"
}
}
return "following"
}
// Status is the source line for the sources panel.
func (s *Source) Status() store.SourceStatus {
l, m, last := s.E.counters()
st := store.SourceStatus{Name: "egress", Path: s.Path, State: s.state(), Lines: l, Malformed: m, LastEvent: last}
if st.State == "error" {
st.Error = "read error"
}
return st
}
// Start launches the single goroutine of the source; it stops with ctx.
func (s *Source) Start(ctx context.Context, wg *sync.WaitGroup) {
wg.Add(1)
go func() {
defer wg.Done()
defer func() {
if p := recover(); p != nil {
s.Log.Error("egress source stopped by a panic", "panic", p)
}
}()
s.backfilling.Store(true)
for _, b := range tail.Backups(s.Path) {
if ctx.Err() != nil {
break
}
if err := tail.ReadAll(b, maxLine, s.E.Ingest, func() { s.E.malformed.Add(1) }); err != nil {
s.Log.Warn("egress backfill failed", "file", b, "err", err)
}
}
s.backfilling.Store(false)
f := tail.NewFollower(s.Path, tail.Pos{})
f.MaxLine, f.Handle = maxLine, s.E.Ingest
f.Oversize = func() { s.E.malformed.Add(1) }
s.fol.Store(f)
f.Run(ctx)
}()
}
// SourceInfo is the "source" object of the API.
type SourceInfo struct {
State string `json:"state"`
Lines uint64 `json:"lines"`
Malformed uint64 `json:"malformed"`
Last int64 `json:"last"`
}
// Info reports the source state (state "disabled" when no source is attached).
func (e *Engine) Info() SourceInfo {
l, m, last := e.counters()
st := "disabled"
if f := e.stateFn.Load(); f != nil {
st = (*f)()
}
return SourceInfo{State: st, Lines: l, Malformed: m, Last: last}
}
+169
View File
@@ -0,0 +1,169 @@
package egress
import (
"bufio"
"fmt"
"net/netip"
"os"
"regexp"
"strings"
)
// Roles of a workload.
const (
RoleDefault = "default"
RoleScanner = "scanner"
RoleMail = "mail"
RoleResolver = "resolver"
)
func validRole(r string) bool {
return r == RoleDefault || r == RoleScanner || r == RoleMail || r == RoleResolver
}
type matcher struct {
prefix netip.Prefix // valid when name == "" and !host
name string // container name: exact base name, or a prefix when pfx
pfx bool
host bool // the host's own output ("host")
}
type workloadDef struct {
name, role string
m []matcher
}
// ParseWorkloads parses "name=ITEM,ITEM:role;name2=...". An ITEM is a CIDR, an
// IP, "host" (the host's own output, so it can take a role such as mail),
// "name:<container name>" (exact base name, without the -<digits> suffix) or
// "name:<prefix>*" (explicit prefix); the role (scanner, mail, resolver,
// default) follows the last colon.
func ParseWorkloads(s string) ([]workloadDef, error) {
var out []workloadDef
for _, part := range strings.Split(s, ";") {
part = strings.TrimSpace(part)
if part == "" {
continue
}
name, rest, ok := strings.Cut(part, "=")
name, rest = strings.TrimSpace(name), strings.TrimSpace(rest)
if !ok || name == "" || rest == "" {
return nil, fmt.Errorf("workload %q: expected name=items[:role]", part)
}
role := RoleDefault
if i := strings.LastIndex(rest, ":"); i >= 0 && validRole(rest[i+1:]) {
role, rest = rest[i+1:], rest[:i]
}
w := workloadDef{name: name, role: role}
for _, it := range strings.Split(rest, ",") {
it = strings.TrimSpace(it)
switch {
case it == "":
case it == "host":
w.m = append(w.m, matcher{host: true})
case strings.HasPrefix(it, "name:"):
p := strings.TrimPrefix(it, "name:")
pfx := strings.HasSuffix(p, "*")
p = strings.TrimSuffix(p, "*")
if !nameRe.MatchString(p) {
return nil, fmt.Errorf("workload %q: bad container name %q", name, p)
}
w.m = append(w.m, matcher{name: p, pfx: pfx})
default:
pf, err := netip.ParsePrefix(it)
if err != nil {
a, err2 := netip.ParseAddr(it)
if err2 != nil {
return nil, fmt.Errorf("workload %q: bad address %q", name, it)
}
pf = netip.PrefixFrom(a.Unmap(), a.Unmap().BitLen())
}
w.m = append(w.m, matcher{prefix: pf.Masked()})
}
}
if len(w.m) == 0 {
return nil, fmt.Errorf("workload %q: no addresses", name)
}
out = append(out, w)
}
return out, nil
}
var nameRe = regexp.MustCompile(`^[A-Za-z0-9_.-]{1,128}$`)
var tsSuffix = regexp.MustCompile(`-\d{9,}$`)
var digitSuffix = regexp.MustCompile(`-\d+$`)
// ContainerBase strips the "-<timestamp>" suffix of a container name.
func ContainerBase(n string) string { return tsSuffix.ReplaceAllString(n, "") }
const maxMapLines = 10000
// LoadContainers reads a containers.map file ("<ip> <name>" per line; invalid
// lines are skipped, at most 10k lines).
func LoadContainers(path string) (map[netip.Addr]string, error) {
fh, err := os.Open(path)
if err != nil {
return nil, err
}
defer fh.Close()
m := map[netip.Addr]string{}
sc := bufio.NewScanner(fh)
sc.Buffer(make([]byte, 0, 4096), 4096)
for n := 0; sc.Scan() && n < maxMapLines; n++ {
f := strings.Fields(sc.Text())
if len(f) != 2 || !nameRe.MatchString(f[1]) {
continue
}
a, err := netip.ParseAddr(f[0])
if err != nil {
continue
}
m[a.Unmap()] = f[1]
}
return m, sc.Err()
}
// resolve names the workload of an event: host output is "host"; a container
// address matches the configured workloads (CIDR or container name from the
// current map); otherwise it is named after its mapped container (without the
// timestamp suffix) or "container <ip>".
func (e *Engine) resolve(ev Event) (name, role string) {
if ev.Host {
for _, w := range e.wls {
for _, m := range w.m {
if m.host {
return w.name, w.role
}
}
}
return "host", RoleDefault
}
cname := e.containers[ev.Src]
for _, w := range e.wls {
for _, m := range w.m {
if m.host {
continue
}
if m.name != "" {
if cname != "" && m.matchName(cname) {
return w.name, w.role
}
} else if m.prefix.Contains(ev.Src) {
return w.name, w.role
}
}
}
if cname != "" {
return ContainerBase(cname), RoleDefault
}
return "container " + ev.Src.String(), RoleDefault
}
// matchName compares a container name: the exact base name (the full name or
// without a -<digits> suffix), or a prefix when the item ended in "*".
func (m matcher) matchName(cname string) bool {
if m.pfx {
return strings.HasPrefix(cname, m.name)
}
return cname == m.name || digitSuffix.ReplaceAllString(cname, "") == m.name
}