Files
urutau/internal/egress/workload.go
T
Lucas RayanandClaude Opus 5.5 c33cca22e3
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
feat: 1.4.0 second firewall, egress analysis and HTML report
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>
2026-11-14 23:35:34 -03:00

170 lines
4.6 KiB
Go

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
}