Files
Lucas RayanandClaude Sonnet 5.5 aefdcea8d2 feat(ingress): firewall telemetry of inbound attempts (host kit --ingress)
Observation-only nftables table (prerouting -150, counters and a
rate-limited log, never drops or modifies), a per-minute counters file,
probe sources ingress and ingresscnt, a per-host hourly aggregate in the
hub (exact totals, sampled ports/ASNs/countries, banned share by the
hub's own ban state, no ban feedback loop), GET /api/v1/ingress, a
Defense section, doctor check, docs EN/pt-BR and tests.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 09:09:16 -03:00

181 lines
6.3 KiB
Go

package probeagent
import (
"context"
"errors"
"flag"
"fmt"
"log/slog"
"math"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"unicode"
"unicode/utf8"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
func envOr(k, def string) string {
if v, ok := os.LookupEnv(k); ok {
return v
}
return def
}
// Main is the `urutau probe` command line (also the whole urutau-probe
// binary): flags with URUTAU_* environment defaults, then Run. It returns the
// process exit code. A leading "probe" argument is accepted and skipped.
func Main(args []string, version string) int {
if len(args) > 0 && args[0] == "probe" {
args = args[1:]
}
fs := flag.NewFlagSet("probe", flag.ContinueOnError)
var c Config
var tokenFile, spool, loc string
check := fs.Bool("check", false, "exit 0 when the probe in --state-dir is alive (container HEALTHCHECK)")
fs.StringVar(&c.Hub, "hub", envOr("URUTAU_HUB", ""), "hub URL (URUTAU_HUB)")
fs.StringVar(&c.Name, "name", envOr("URUTAU_PROBE_NAME", ""), "probe name (URUTAU_PROBE_NAME)")
fs.StringVar(&c.Token, "token", "", "probe token; prefer URUTAU_PROBE_TOKEN or URUTAU_PROBE_TOKEN_FILE")
fs.StringVar(&tokenFile, "token-file", envOr("URUTAU_PROBE_TOKEN_FILE", ""), "file with the probe token (URUTAU_PROBE_TOKEN_FILE)")
fs.StringVar(&c.StateDir, "state-dir", envOr("URUTAU_STATE_DIR", "/state"), "spool and state directory (URUTAU_STATE_DIR)")
paths := map[string]*string{}
for _, p := range []struct{ src, env, def, help string }{
{wire.SrcTraefik, "URUTAU_TRAEFIK_LOG", "", "Traefik JSON access log"},
{wire.SrcAuth, "URUTAU_AUTH_LOG", "", "sshd auth log"},
{wire.SrcFail2ban, "URUTAU_FAIL2BAN_LOG", "", "fail2ban log"},
{wire.SrcProbe, "URUTAU_PROBE_LOG", "", "kernel log of network probes"},
{wire.SrcEgress, "URUTAU_EGRESS_LOG", "", "kernel log of outbound connections"},
{wire.SrcIngress, "URUTAU_INGRESS_LOG", "", "sampled kernel log of inbound attempts"},
{wire.SrcIngressCnt, "URUTAU_INGRESS_COUNTERS", "", "exact inbound counters of the host kit"},
} {
v := new(string)
paths[p.src] = v
fs.StringVar(v, p.src+"-log", envOr(p.env, p.def), p.help+", empty disables ("+p.env+")")
}
fs.StringVar(&c.Containers, "egress-containers", envOr("URUTAU_EGRESS_CONTAINERS", ""), "containers.map written by the host kit (URUTAU_EGRESS_CONTAINERS)")
fs.StringVar(&c.Resolv, "resolv", envOr("URUTAU_RESOLV", "/etc/resolv.conf"), "resolv.conf of the host (URUTAU_RESOLV)")
fs.StringVar(&c.DecisionsLog, "enforce-log", envOr("URUTAU_ENFORCE_LOG", ""), "decisions file the host fail2ban reads, empty ignores decisions (URUTAU_ENFORCE_LOG)")
fs.StringVar(&c.UnbanLog, "enforce-unban-log", envOr("URUTAU_ENFORCE_UNBAN_LOG", ""), "unban requests file, empty ignores unbans (URUTAU_ENFORCE_UNBAN_LOG)")
fs.StringVar(&spool, "spool-max", envOr("URUTAU_PROBE_SPOOL_MAX", "64MiB"), "spool size cap (URUTAU_PROBE_SPOOL_MAX)")
fs.StringVar(&loc, "location", envOr("URUTAU_LOCATION", ""), `"lat,lon[,label]"; the hub configuration wins (URUTAU_LOCATION)`)
if err := fs.Parse(args); err != nil {
if errors.Is(err, flag.ErrHelp) {
return 0
}
return 2
}
if *check {
if err := Check(c.StateDir); err != nil {
fmt.Fprintln(os.Stderr, "urutau probe:", err)
return 1
}
return 0
}
fail := func(m string) int { fmt.Fprintln(os.Stderr, "urutau probe:", m); return 2 }
if c.Hub == "" || c.Name == "" {
return fail("URUTAU_HUB and URUTAU_PROBE_NAME are required")
}
if !wire.ValidName(c.Name) {
return fail("invalid probe name")
}
if _, err := wire.CheckHubURL(c.Hub); err != nil {
return fail(err.Error())
}
if c.Token == "" {
c.Token = os.Getenv("URUTAU_PROBE_TOKEN")
}
if c.Token == "" && tokenFile != "" {
b, err := os.ReadFile(tokenFile)
if err != nil {
return fail("URUTAU_PROBE_TOKEN_FILE: " + err.Error())
}
c.Token = strings.TrimSpace(string(b))
}
if c.Token == "" {
return fail("URUTAU_PROBE_TOKEN or URUTAU_PROBE_TOKEN_FILE is required")
}
n, err := parseSize(spool)
if err != nil {
return fail("--spool-max: " + err.Error())
}
c.SpoolMax = n
if l, err := parseLocation(loc); err != nil {
return fail(err.Error())
} else if l != nil {
c.Location = l
}
c.Paths = map[string]string{}
for src, p := range paths {
if *p != "" {
c.Paths[src] = *p
}
}
c.Version = version
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
defer stop()
if err := Run(ctx, c, slog.New(slog.NewTextHandler(os.Stderr, nil))); err != nil &&
!errors.Is(err, context.Canceled) {
fmt.Fprintln(os.Stderr, "urutau probe:", err)
if errors.Is(err, ErrUnauthorized) || errors.Is(err, ErrIncompatible) {
return 3
}
return 1
}
return 0
}
// parseSize reads sizes such as "64MiB", "512k" or "1g" (same rules as the hub).
func parseSize(v string) (int64, error) {
v = strings.TrimSpace(strings.ToLower(v))
if v == "" {
return 0, errors.New("empty size")
}
mult := int64(1)
for _, u := range []struct {
suf string
m int64
}{{"gib", 1 << 30}, {"mib", 1 << 20}, {"kib", 1 << 10}, {"gb", 1 << 30}, {"mb", 1 << 20}, {"kb", 1 << 10}, {"g", 1 << 30}, {"m", 1 << 20}, {"k", 1 << 10}, {"b", 1}} {
if strings.HasSuffix(v, u.suf) {
mult, v = u.m, strings.TrimSpace(strings.TrimSuffix(v, u.suf))
break
}
}
n, err := strconv.ParseFloat(v, 64)
if err != nil || n < 0 || n > 1<<40 {
return 0, fmt.Errorf("invalid size %q", v)
}
return int64(n * float64(mult)), nil
}
// parseLocation reads "lat,lon[,label]" (same rules as the hub).
func parseLocation(s string) (*wire.Location, error) {
s = strings.TrimSpace(s)
if s == "" {
return nil, nil
}
p := strings.SplitN(s, ",", 3)
if len(p) < 2 {
return nil, errors.New("location: expected lat,lon or lat,lon,label")
}
lat, e1 := strconv.ParseFloat(strings.TrimSpace(p[0]), 64)
lon, e2 := strconv.ParseFloat(strings.TrimSpace(p[1]), 64)
if e1 != nil || e2 != nil || math.IsNaN(lat) || math.IsNaN(lon) || lat < -90 || lat > 90 || lon < -180 || lon > 180 {
return nil, errors.New("location: lat must be within [-90,90] and lon within [-180,180]")
}
l := &wire.Location{Lat: lat, Lon: lon}
if len(p) == 3 {
l.Label = strings.TrimSpace(p[2])
bad := utf8.RuneCountInString(l.Label) > 64 || !utf8.ValidString(l.Label)
for _, r := range l.Label {
bad = bad || unicode.IsControl(r)
}
if bad {
return nil, errors.New("location: label must have at most 64 characters and no control characters")
}
}
return l, nil
}