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
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:
1 parent
3adaa007ec
commit
c33cca22e3
59 files changed
+7364
-24
No files matched your search
@@ -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()
|
||||
}
|
||||
Reference in new issue
Block a user