feat!: Urutau 2.0.0, ultralight probes and a single analysis hub
CI / Format and vet (pull_request) Failing after 53s
CI / Dependency audit (pull_request) Successful in 33s
CI / Tests (Linux, race detector) (pull_request) Successful in 2m1s
CI / Docker images (build and smoke test) (pull_request) Failing after 47s

Each server runs an ultralight probe (scratch image, ~7 MiB RSS) that
tails the logs, ships raw lines to the hub over HTTPS with an on-disk
spool, and applies enforce decisions locally. The hub keeps one node per
probe (primary node = the 1.x data dir, unchanged), does all analysis and
serves the UI. Peer federation is removed. 'urutau import' brings 1.x
data dirs in with hash and count verification. UI: probes page, host
qualified incidents, IPs never wrap, egress heatmap labels, live and
replay globes no longer auto-rotate, replay repeat, live traffic metrics.

BREAKING CHANGE: URUTAU_PEERS, URUTAU_PEER_* and /api/v1/peer/* are gone;
log path variables move from the hub to the probe. See docs/migration-2.0.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lucas RayanandClaude Opus 5.5 committed 2026-11-15 22:14:50 -03:00
1 parent 23a7a5963a
commit 8546d14cef
130 files changed
+9396 -3311

No files matched your search

+41 -95
View File
@@ -89,17 +89,17 @@ func TestFlagsTrustedAndIgnoreAlias(t *testing.T) {
t.Fatalf("%+v", c)
}
c.Bind = "0.0.0.0:1"
if _, err := c.Validate(tok); err != nil {
if err := c.Validate(tok); err != nil {
t.Fatal(err)
}
c.MonitorUA = "("
if _, err := c.Validate(tok); err == nil {
if err := c.Validate(tok); err == nil {
t.Fatal("bad regex must be rejected")
}
if _, err := (Config{Ignore: "nonsense", MonitorUA: "", Retention: 168 * time.Hour}).Validate(tok); err == nil {
if err := (Config{Ignore: "nonsense", MonitorUA: "", Retention: 168 * time.Hour}).Validate(tok); err == nil {
t.Fatal("bad cidr must be rejected")
}
if _, err := (Config{NoAuth: true, Bind: "0.0.0.0:1", Retention: 168 * time.Hour}).Validate(""); err == nil {
if err := (Config{NoAuth: true, Bind: "0.0.0.0:1", Retention: 168 * time.Hour}).Validate(""); err == nil {
t.Fatal("no-auth must require loopback")
}
}
@@ -143,48 +143,45 @@ func TestEnrichmentFeedsThreatAndTraffic(t *testing.T) {
func TestTokenAndFederationValidation(t *testing.T) {
base := Config{Bind: "0.0.0.0:1", Retention: 168 * time.Hour, MonitorUA: "", Ignore: DefaultIgnore, TrustedProxy: DefaultTrustedProxy}
peerTok := "peer-token-0123456789-abcdefghijklmnopq"
if _, err := base.Validate("short-token-1234567890"); err == nil {
if err := base.Validate("short-token-1234567890"); err == nil {
t.Fatal("URUTAU_TOKEN under 32 characters must be refused")
}
if _, err := base.Validate(tok); err != nil {
if err := base.Validate(tok); err != nil {
t.Fatal(err)
}
c := base
c.PeerToken = "short-peer"
if _, err := c.Validate(tok); err == nil {
t.Fatal("peer token under 32 characters must be refused")
}
c.PeerToken = tok
if _, err := c.Validate(tok); err == nil {
t.Fatal("peer token equal to URUTAU_TOKEN must be refused")
}
c.PeerToken = peerTok
if _, err := c.Validate(tok); err != nil {
t.Fatal(err)
}
c.Peers = []string{"hostinger=https://urutau.example.org"}
c.PeerToken = ""
if _, err := c.Validate(tok); err == nil {
t.Fatal("peers without a peer token must be refused")
}
c.PeerToken = peerTok
c.Peers = []string{"hostinger=http://urutau.example.org"}
if _, err := c.Validate(tok); err == nil {
t.Fatal("plain http to a non-loopback peer must be refused")
}
c.Peers = []string{"h=http://127.0.0.1:8791"}
if _, err := c.Validate(tok); err != nil {
t.Fatalf("http is fine on loopback: %v", err)
}
c.PeerAllow, c.Peers = "not-a-cidr", nil
if _, err := c.Validate(tok); err == nil {
t.Fatal("bad --peer-allow must be refused")
}
cfg, err := ParseFlags("serve", []string{"--peer-allow", "203.0.113.0/24", "--peer-allow", "198.51.100.7", "--trusted-proxy", "10.0.0.0/8"})
if err != nil || cfg.PeerAllow != "203.0.113.0/24,198.51.100.7" || cfg.TrustedProxy != "10.0.0.0/8" {
cfg, err := ParseFlags("serve", []string{"--trusted-proxy", "10.0.0.0/8"})
if err != nil || cfg.TrustedProxy != "10.0.0.0/8" {
t.Fatalf("%+v %v", cfg, err)
}
bad := base
bad.Name = "Not Valid"
if err := bad.Validate(tok); err == nil {
t.Fatal("the primary probe name must follow wire.ValidName")
}
}
func TestRemovedEnvIsFatal(t *testing.T) {
t.Setenv("URUTAU_PEERS", "hostinger=https://x.example.org")
_, err := CheckRemovedEnv(os.LookupEnv)
if err == nil || !strings.Contains(err.Error(), "URUTAU_PEERS") || !strings.Contains(err.Error(), "migration-2.0") {
t.Fatalf("PEERS must stop the hub with a pointer to the guide: %v", err)
}
t.Setenv("URUTAU_PEERS", "")
os.Unsetenv("URUTAU_PEERS")
t.Setenv("URUTAU_PEER_TOKEN_HOSTINGER", "x")
if _, err := CheckRemovedEnv(os.LookupEnv); err == nil {
t.Fatal("per peer token must stop the hub")
}
os.Unsetenv("URUTAU_PEER_TOKEN_HOSTINGER")
t.Setenv("URUTAU_TRAEFIK_LOG", "/x")
warn, err := CheckRemovedEnv(os.LookupEnv)
if err != nil || len(warn) != 1 {
t.Fatalf("the 1.x image variables only warn: %v %v", warn, err)
}
t.Setenv("URUTAU_ENFORCE_LOG", "/x")
if _, err := CheckRemovedEnv(os.LookupEnv); err == nil {
t.Fatal("URUTAU_ENFORCE_LOG must be fatal")
}
}
func TestCorruptSnapshotDoesNotStopStartup(t *testing.T) {
@@ -306,13 +303,13 @@ func (panicEnr) UA(string) core.UAInfo { return core.UAInfo{} }
func TestTokenQualityAndFiles(t *testing.T) {
base := Config{Bind: "0.0.0.0:1", Retention: 168 * time.Hour, Ignore: DefaultIgnore, TrustedProxy: DefaultTrustedProxy}
if _, err := base.Validate(strings.Repeat("a", 40)); err == nil {
if err := base.Validate(strings.Repeat("a", 40)); err == nil {
t.Fatal("aaaa... must be refused: too few distinct characters")
}
if _, err := base.Validate("abababababababababababababababab"); err == nil {
if err := base.Validate("abababababababababababababababab"); err == nil {
t.Fatal("two distinct characters must be refused")
}
if _, err := base.Validate(tok); err != nil {
if err := base.Validate(tok); err != nil {
t.Fatal(err)
}
dir := t.TempDir()
@@ -329,57 +326,6 @@ func TestTokenQualityAndFiles(t *testing.T) {
}
}
func TestPerPeerTokens(t *testing.T) {
t.Setenv("URUTAU_PEER_TOKEN", "")
t.Setenv("URUTAU_PEER_TOKEN_HOSTINGER", "hostinger-token-0123456789-abcdefghijklmn")
f := filepath.Join(t.TempDir(), "o")
os.WriteFile(f, []byte("oracle-token-0123456789-abcdefghijklmnopq\n"), 0o600)
t.Setenv("URUTAU_PEER_TOKEN_MY_ORACLE_FILE", f)
c, err := ParseFlags("serve", []string{"--peer", "hostinger=https://h.example.org", "--peer", "my-oracle=https://o.example.org"})
if err != nil {
t.Fatal(err)
}
peers, err := c.Validate(tok)
if err != nil {
t.Fatal(err)
}
if peers[0].Token != "hostinger-token-0123456789-abcdefghijklmn" || peers[1].Token != "oracle-token-0123456789-abcdefghijklmnopq" {
t.Fatalf("per peer tokens: %+v", peers)
}
// Client tokens sent to peers never open the local export: a compromised
// peer knows its own token and must not read this instance with it.
if len(c.PeerTokens) != 0 {
t.Fatalf("per peer client tokens must not open the local export: %v", c.PeerTokens)
}
c.Peers = append(c.Peers, "nobody=https://n.example.org")
if _, err := c.Validate(tok); err == nil {
t.Fatal("a peer without any token must be refused")
}
}
func TestPeerServerTokenOnlyOpensExport(t *testing.T) {
t.Setenv("URUTAU_PEER_TOKEN", "server-side-token-Zq8vN3pL0xK7mR2wT5yB9cD")
t.Setenv("URUTAU_PEER_TOKEN_HOSTINGER", "client-side-token-Hj4kL9mN2pQ7rS1tV6wX3yZ")
c, err := ParseFlags("serve", []string{"--peer", "hostinger=https://h.example.org"})
if err != nil {
t.Fatal(err)
}
if len(c.PeerTokens) != 1 || c.PeerTokens[0] != "server-side-token-Zq8vN3pL0xK7mR2wT5yB9cD" {
t.Fatalf("export tokens: %v", c.PeerTokens)
}
}
func TestPeerNameTokenCollision(t *testing.T) {
t.Setenv("URUTAU_PEER_TOKEN", "server-side-token-Zq8vN3pL0xK7mR2wT5yB9cD")
c, err := ParseFlags("serve", []string{"--peer", "my-peer=https://a.example.org", "--peer", "my_peer=https://b.example.org"})
if err != nil {
t.Fatal(err)
}
if _, err := c.Validate(tok); err == nil || !strings.Contains(err.Error(), "share the token variable") {
t.Fatalf("colliding peer names must be refused, got %v", err)
}
}
// Without explicit configuration, X-Forwarded-For is only believed from loopback.
func TestTrustedProxyDefaultIsLoopback(t *testing.T) {
os.Unsetenv("URUTAU_TRUSTED_PROXY")
@@ -423,7 +369,7 @@ func TestLocationFlagIsValidated(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if _, err := c.Validate("zK3vQ9xT2mLp7WdR4nYb8HsJ6cFg1UaE5oXi0VtN"); (err == nil) != tc.ok {
if err := c.Validate("zK3vQ9xT2mLp7WdR4nYb8HsJ6cFg1UaE5oXi0VtN"); (err == nil) != tc.ok {
t.Errorf("%q: %v", tc.v, err)
}
}
+85 -167
View File
@@ -14,34 +14,31 @@ import (
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
// Config is the runtime configuration of `urutau serve` and `urutau doctor`.
type Config struct {
Bind string
Name string
DataDir string
Bind string
Name string
DataDir string
// Log paths: the hub no longer reads files (the probes do); these fields
// only serve tests and the file based Runner, they have no flag.
TraefikLog string
AuthLog string
Fail2banLog string
ProbeLog string // kernel log of new connections to unserved ports
Ignore string // networks whose events are dropped (--ignore, alias of --trusted)
Trusted string // trusted sources, e.g. the servers themselves (--trusted)
MonitorUA string // regex of monitoring User-Agents
MonitorFrom string // networks monitors come from (empty: any source)
Domains string // optional allowlist of analytics domains
AdminUsers string // SSH users whose logins grant admin immunity (empty: any user)
PeerTokens []string // tokens accepted by /api/v1/peer/export
PeerTokenFor map[string]string // per peer name (upper case) token used by the hub
GeoDir string // directory of the geo databases (default <data-dir>/geo)
ProbeLog string
Ignore string // networks whose events are dropped (--ignore, alias of --trusted)
Trusted string // trusted sources, e.g. the servers themselves (--trusted)
MonitorUA string // regex of monitoring User-Agents
MonitorFrom string // networks monitors come from (empty: any source)
Domains string // optional allowlist of analytics domains
AdminUsers string // SSH users whose logins grant admin immunity (empty: any user)
GeoDir string // directory of the geo databases (default <data-dir>/geo)
GeoUpdate time.Duration
Peers []string
PeerToken string
Location string // "lat,lon" or "lat,lon,label" (--location)
Location string // "lat,lon" or "lat,lon,label" (--location): default location of the primary probe
PeerBlocklist string // "on" (default) or "off"
PeerAllow string // CIDRs allowed to call /api/v1/peer/export (empty: any source with the token)
TrustedProxy string // proxies whose X-Forwarded-For is believed
Retention time.Duration
TorAuto string // on (default) or off: download the official Tor lists every 6 h
@@ -50,18 +47,19 @@ type Config struct {
NoAuth bool
// Second firewall (see internal/enforce).
Enforce string // off (default), observe or on
EnforceLog string // decision file read by the host fail2ban
EnforceUnbanLog string // unban requests (UI button) read by the host; default: unban.log next to --enforce-log
EnforceShare string // off (default) or on: exchange decisions with peers
EnforceLog string // decision file (tests only: in the hub decisions go to the probe)
EnforceUnbanLog string // unban file (tests only)
EnforceShare string // off (default) or on: a decision of one probe also reaches the others
EnforceThreshold int // attack events in 10 minutes that justify a ban
EnforceMaxPerMin int // decisions per minute; the excess is dropped
// Egress analysis (see internal/egress).
Egress string // auto (default: on when the log exists), on or off
EgressLog string // kernel log of new outbound connections
EgressLog string // kernel log of new outbound connections (tests only)
EgressWorkloads string // "name=CIDR|name:<prefix>[,...][:role];..."
EgressResolvers string // DNS resolvers allowed (empty: the usual public ones)
EgressContainers string // "<ip> <container>" map written by the host kit
EgressContainers string // "<ip> <container>" map (tests only)
EgressAllow string // URUTAU_EGRESS_ALLOW: default for the primary probe
}
// DefaultEventsMax is the default size cap of the event registry.
@@ -146,14 +144,9 @@ func ParseFlags(name string, args []string) (Config, error) {
fs := flag.NewFlagSet(name, flag.ContinueOnError)
var c Config
host, _ := os.Hostname()
var peers listFlag
fs.StringVar(&c.Bind, "bind", env("URUTAU_BIND", "0.0.0.0:8790"), "listen address (URUTAU_BIND)")
fs.StringVar(&c.Name, "name", env("URUTAU_NAME", host), "name of this instance (URUTAU_NAME)")
fs.StringVar(&c.DataDir, "data-dir", env("URUTAU_DATA_DIR", "/data"), "snapshot directory (URUTAU_DATA_DIR)")
fs.StringVar(&c.TraefikLog, "traefik-log", env("URUTAU_TRAEFIK_LOG", "/data/coolify/proxy/access.log"), "Traefik JSON access log, empty disables (URUTAU_TRAEFIK_LOG)")
fs.StringVar(&c.AuthLog, "auth-log", env("URUTAU_AUTH_LOG", "/var/log/auth.log"), "sshd auth log, empty disables (URUTAU_AUTH_LOG)")
fs.StringVar(&c.ProbeLog, "probe-log", env("URUTAU_PROBE_LOG", "/logs/host/probe.log"), "kernel log of network probes (unserved ports) written by the host kit, empty disables (URUTAU_PROBE_LOG)")
fs.StringVar(&c.Fail2banLog, "fail2ban-log", env("URUTAU_FAIL2BAN_LOG", "/var/log/fail2ban.log"), "fail2ban log, empty disables (URUTAU_FAIL2BAN_LOG)")
ign := &csvFlag{val: env("URUTAU_IGNORE", DefaultIgnore)}
trusted := &csvFlag{val: env("URUTAU_TRUSTED", "")}
fs.Var(ign, "ignore", "CIDRs/IPs whose events are dropped, repeatable or comma separated (URUTAU_IGNORE)")
@@ -167,28 +160,21 @@ func ParseFlags(name string, args []string) (Config, error) {
fs.StringVar(&c.GeoDir, "geo-dir", env("URUTAU_GEO_DIR", ""), "geo database directory, default <data-dir>/geo (URUTAU_GEO_DIR)")
fs.DurationVar(&c.GeoUpdate, "geo-update", 24*time.Hour, "how often the geo database is refreshed, 0 disables downloads (URUTAU_GEO_UPDATE)")
fs.StringVar(&c.MonitorUA, "monitor-ua", env("URUTAU_MONITOR_UA", DefaultMonitorUA), "regex of monitoring User-Agents; benign hits are counted apart, empty disables (URUTAU_MONITOR_UA)")
fs.Var(&peers, "peer", "peer instance name=https://url, repeatable (URUTAU_PEERS, comma separated)")
fs.StringVar(&c.PeerToken, "peer-token", "", "bearer token shared with peers; prefer URUTAU_PEER_TOKEN or URUTAU_PEER_TOKEN_FILE")
allow := &csvFlag{val: env("URUTAU_PEER_ALLOW", "")}
tproxy := &csvFlag{val: env("URUTAU_TRUSTED_PROXY", DefaultTrustedProxy)}
fs.Var(allow, "peer-allow", "CIDRs allowed to call /api/v1/peer/export, empty allows any source with the token (URUTAU_PEER_ALLOW)")
fs.Var(tproxy, "trusted-proxy", "reverse proxies whose X-Forwarded-For is trusted for the real client IP (URUTAU_TRUSTED_PROXY)")
fs.StringVar(&c.Location, "location", env("URUTAU_LOCATION", ""), `where this instance lives, "lat,lon" or "lat,lon,label"; shown as the destination of live arcs (URUTAU_LOCATION)`)
fs.StringVar(&c.PeerBlocklist, "peer-blocklist", env("URUTAU_PEER_BLOCKLIST", "on"), "on: the blocklist also lists strong hostile IPs seen only by peers; off: local IPs only (URUTAU_PEER_BLOCKLIST)")
fs.StringVar(&c.PeerBlocklist, "blocklist-scope", "on", "on: the blocklist lists the strong hostile IPs of every probe; off: the primary probe only")
fs.DurationVar(&c.Retention, "retention", store.DefaultRetention, "how long data is kept, at most 720h (URUTAU_RETENTION)")
fs.StringVar(&c.TorAuto, "tor-auto", env("URUTAU_TOR_AUTO", "on"), "download the official Tor exit and relay lists every 6 h into <data-dir>/tor: on or off (URUTAU_TOR_AUTO)")
fs.StringVar(&c.TorExits, "tor-exits", env("URUTAU_TOR_EXITS", ""), "file with Tor exit node addresses, one per line, reloaded every 24 h when it changes; empty disables (URUTAU_TOR_EXITS)")
fs.StringVar(&c.EventsMax, "events-max", env("URUTAU_EVENTS_MAX", DefaultEventsMax), "size cap of the event registry in <data-dir>/events, 0 disables it (URUTAU_EVENTS_MAX)")
fs.StringVar(&c.Enforce, "enforce", env("URUTAU_ENFORCE", "off"), "second firewall: off, observe (decide in memory only) or on (write decisions for the host fail2ban) (URUTAU_ENFORCE)")
fs.StringVar(&c.EnforceLog, "enforce-log", env("URUTAU_ENFORCE_LOG", "/logs/enforce/decisions.log"), "decision file appended in --enforce=on (URUTAU_ENFORCE_LOG)")
fs.StringVar(&c.EnforceUnbanLog, "enforce-unban-log", env("URUTAU_ENFORCE_UNBAN_LOG", ""), "unban request file written by the Unban button (URUTAU_ENFORCE_UNBAN_LOG); default unban.log next to --enforce-log")
fs.StringVar(&c.EnforceShare, "enforce-share", env("URUTAU_ENFORCE_SHARE", "off"), "on: exchange decisions with peers, each side applies its own exclusions (URUTAU_ENFORCE_SHARE)")
fs.StringVar(&c.Enforce, "enforce", env("URUTAU_ENFORCE", "off"), "second firewall: off, observe (decide in memory only) or on (queue decisions for each probe's host fail2ban) (URUTAU_ENFORCE)")
fs.StringVar(&c.EnforceShare, "enforce-share", env("URUTAU_ENFORCE_SHARE", "off"), "on: a decision of one probe also reaches the others, each applies its own exclusions (URUTAU_ENFORCE_SHARE)")
fs.IntVar(&c.EnforceThreshold, "enforce-threshold", envInt("URUTAU_ENFORCE_THRESHOLD", 5), "attack events in 10 minutes that justify a ban (URUTAU_ENFORCE_THRESHOLD)")
fs.StringVar(&c.Egress, "egress", env("URUTAU_EGRESS", "auto"), "egress analysis: auto (on when --egress-log exists), on or off (URUTAU_EGRESS)")
fs.StringVar(&c.EgressLog, "egress-log", env("URUTAU_EGRESS_LOG", "/logs/host/egress.log"), "kernel log of new outbound connections written by the host kit (URUTAU_EGRESS_LOG)")
fs.StringVar(&c.EgressWorkloads, "egress-workloads", env("URUTAU_EGRESS_WORKLOADS", ""), "workloads: \"ciberlab=name:<container prefix>:scanner;mail=10.0.7.0/24:mail\" (URUTAU_EGRESS_WORKLOADS)")
c.EgressAllow = env("URUTAU_EGRESS_ALLOW", "")
fs.StringVar(&c.EgressWorkloads, "egress-workloads", env("URUTAU_EGRESS_WORKLOADS", ""), "default workloads of the primary probe: \"ciberlab=name:<container prefix>:scanner;mail=10.0.7.0/24:mail\" (URUTAU_EGRESS_WORKLOADS)")
fs.StringVar(&c.EgressResolvers, "egress-resolvers", env("URUTAU_EGRESS_RESOLVERS", ""), "DNS resolvers allowed, comma separated; empty: the usual public ones (URUTAU_EGRESS_RESOLVERS)")
fs.StringVar(&c.EgressContainers, "egress-containers", env("URUTAU_EGRESS_CONTAINERS", "/logs/host/containers.map"), "\"<ip> <container>\" map written by the host kit (URUTAU_EGRESS_CONTAINERS)")
fs.IntVar(&c.EnforceMaxPerMin, "enforce-max-per-min", envInt("URUTAU_ENFORCE_MAX_PER_MIN", 60), "most decisions per minute, the excess is dropped and counted (URUTAU_ENFORCE_MAX_PER_MIN)")
fs.BoolVar(&c.NoAuth, "insecure-no-auth", false, "disable authentication; only allowed on a loopback bind")
if v := os.Getenv("URUTAU_GEO_UPDATE"); v != "" {
@@ -204,33 +190,9 @@ func ParseFlags(name string, args []string) (Config, error) {
if err := fs.Parse(args); err != nil {
return c, err
}
c.Peers = peers
c.Ignore, c.Trusted = ign.val, trusted.val
c.PeerAllow, c.TrustedProxy = allow.val, tproxy.val
c.TrustedProxy = tproxy.val
c.MonitorFrom, c.Domains, c.AdminUsers = mfrom.val, doms.val, admins.val
if c.PeerToken == "" {
var err error
if c.PeerToken, err = Secret("URUTAU_PEER_TOKEN"); err != nil {
return c, err
}
}
var err error
if c.PeerTokenFor, err = perPeerTokens(); err != nil {
return c, err
}
// Only the server token opens the local export. URUTAU_PEER_TOKEN_<NAME>
// are client credentials sent to that peer: a compromised peer learns
// them, so they must never open this instance's export.
if c.PeerToken != "" {
c.PeerTokens = append(c.PeerTokens, c.PeerToken)
}
if len(c.Peers) == 0 {
for _, p := range strings.Split(os.Getenv("URUTAU_PEERS"), ",") {
if p = strings.TrimSpace(p); p != "" {
c.Peers = append(c.Peers, p)
}
}
}
if c.GeoDir == "" {
c.GeoDir = filepath.Join(c.DataDir, "geo")
}
@@ -240,109 +202,104 @@ func ParseFlags(name string, args []string) (Config, error) {
return c, nil
}
// Validate checks the configuration and returns the parsed peers.
func (c Config) Validate(token string) ([]fed.Peer, error) {
// Validate checks the configuration.
func (c Config) Validate(token string) error {
if _, err := store.ParseLocation(c.Location); err != nil {
return nil, err
return err
}
if c.Name != "" && !wire.ValidName(c.Name) {
return fmt.Errorf("--name %q must be lowercase letters, digits and dashes, at most 32 characters: it is the name of the primary probe", c.Name)
}
if v := strings.ToLower(c.PeerBlocklist); v != "" && v != "on" && v != "off" {
return nil, fmt.Errorf("--peer-blocklist must be on or off")
return fmt.Errorf("--blocklist-scope must be on or off")
}
if c.Enforce != "" || c.EnforceShare != "" { // a Config built by hand may leave them unset
switch strings.ToLower(c.Enforce) {
case "", "off", "observe", "on":
default:
return nil, fmt.Errorf("--enforce must be off, observe or on")
return fmt.Errorf("--enforce must be off, observe or on")
}
if v := strings.ToLower(c.EnforceShare); v != "" && v != "off" && v != "on" {
return nil, fmt.Errorf("--enforce-share must be on or off")
return fmt.Errorf("--enforce-share must be on or off")
}
if c.EnforceThreshold < 1 || c.EnforceThreshold > 1000 {
return nil, fmt.Errorf("--enforce-threshold must be between 1 and 1000")
return fmt.Errorf("--enforce-threshold must be between 1 and 1000")
}
if c.EnforceMaxPerMin < 1 || c.EnforceMaxPerMin > 10000 {
return nil, fmt.Errorf("--enforce-max-per-min must be between 1 and 10000")
return fmt.Errorf("--enforce-max-per-min must be between 1 and 10000")
}
}
switch strings.ToLower(c.Egress) {
case "", "auto", "on", "off":
default:
return nil, fmt.Errorf("--egress must be auto, on or off")
}
if strings.EqualFold(c.Enforce, "on") && c.EnforceLog == "" {
return nil, fmt.Errorf("--enforce=on needs --enforce-log")
}
if c.EnforceUnbanLog == "" && c.EnforceLog != "" {
c.EnforceUnbanLog = filepath.Join(filepath.Dir(c.EnforceLog), "unban.log")
}
var peers []fed.Peer
seen := map[string]bool{}
envSeen := map[string]string{}
for _, s := range c.Peers {
p, err := fed.ParsePeer(s)
if err != nil {
return nil, err
}
if seen[p.Name] || p.Name == c.Name || p.Name == "all" {
return nil, fmt.Errorf("peer name %q is duplicated or reserved", p.Name)
}
if other, dup := envSeen[tokenEnvName(p.Name)]; dup {
return nil, fmt.Errorf("peer names %q and %q share the token variable URUTAU_PEER_TOKEN_%s", other, p.Name, tokenEnvName(p.Name))
}
envSeen[tokenEnvName(p.Name)] = p.Name
seen[p.Name] = true
peers = append(peers, p)
return fmt.Errorf("--egress must be auto, on or off")
}
if _, err := core.ParseCIDRs(c.Ignore + "," + c.Trusted); err != nil {
return nil, fmt.Errorf("--ignore/--trusted: %w", err)
return fmt.Errorf("--ignore/--trusted: %w", err)
}
if c.MonitorUA != "" {
if _, err := regexp.Compile(c.MonitorUA); err != nil {
return nil, fmt.Errorf("--monitor-ua: %w", err)
return fmt.Errorf("--monitor-ua: %w", err)
}
}
if c.Retention < time.Hour || c.Retention > store.DefaultRetention {
return nil, fmt.Errorf("--retention must be between 1h and 720h")
return fmt.Errorf("--retention must be between 1h and 720h")
}
if c.EventsMax != "" {
if _, err := ParseSize(c.EventsMax); err != nil {
return nil, fmt.Errorf("--events-max: %w", err)
return fmt.Errorf("--events-max: %w", err)
}
}
if c.NoAuth {
if !loopbackBind(c.Bind) {
return nil, fmt.Errorf("--insecure-no-auth is only allowed on a loopback bind (got %q)", c.Bind)
return fmt.Errorf("--insecure-no-auth is only allowed on a loopback bind (got %q)", c.Bind)
}
} else if err := checkToken("URUTAU_TOKEN", token); err != nil {
return nil, err
return err
}
all := append([]string(nil), c.PeerTokens...)
if c.PeerToken != "" && !contains(all, c.PeerToken) {
all = append(all, c.PeerToken)
}
for _, t := range c.PeerTokenFor {
all = append(all, t)
}
for _, t := range all {
if err := checkToken("URUTAU_PEER_TOKEN", t); err != nil {
return nil, err
}
if t == token {
return nil, fmt.Errorf("a peer token must differ from URUTAU_TOKEN")
}
}
for i := range peers {
peers[i].Token = c.PeerTokenFor[tokenEnvName(peers[i].Name)]
if peers[i].Token == "" && c.PeerToken == "" {
return nil, fmt.Errorf("peer %q has no token: set URUTAU_PEER_TOKEN or URUTAU_PEER_TOKEN_%s", peers[i].Name, tokenEnvName(peers[i].Name))
}
}
for _, l := range []struct{ name, v string }{{"--peer-allow", c.PeerAllow}, {"--trusted-proxy", c.TrustedProxy}, {"--monitor-from", c.MonitorFrom}} {
for _, l := range []struct{ name, v string }{{"--trusted-proxy", c.TrustedProxy}, {"--monitor-from", c.MonitorFrom}} {
if _, err := core.ParseCIDRs(l.v); err != nil {
return nil, fmt.Errorf("%s: %w", l.name, err)
return fmt.Errorf("%s: %w", l.name, err)
}
}
return peers, nil
return nil
}
// MigrationGuide is where the removed 1.x variables are explained.
const MigrationGuide = "docs/migration-2.0.md"
// removedEnv are the 1.x variables that make the 2.0 hub refuse to start. The
// log path variables moved to the probe (URUTAU_*_LOG there).
var removedEnv = []string{"URUTAU_PEERS", "URUTAU_PEER_TOKEN", "URUTAU_PEER_TOKEN_FILE", "URUTAU_PEER_ALLOW", "URUTAU_PEER_BLOCKLIST",
"URUTAU_TRAEFIK_LOG", "URUTAU_AUTH_LOG", "URUTAU_FAIL2BAN_LOG", "URUTAU_PROBE_LOG", "URUTAU_EGRESS_LOG", "URUTAU_EGRESS_CONTAINERS",
"URUTAU_ENFORCE_LOG", "URUTAU_ENFORCE_UNBAN_LOG"}
// softEnv are set by the 1.x image: only a warning.
var softEnv = map[string]bool{"URUTAU_TRAEFIK_LOG": true, "URUTAU_AUTH_LOG": true, "URUTAU_FAIL2BAN_LOG": true}
// CheckRemovedEnv returns an error naming the removed variables that are set
// (the old image's TRAEFIK/AUTH/FAIL2BAN defaults only produce warnings).
func CheckRemovedEnv(lookup func(string) (string, bool)) (warn []string, err error) {
var bad []string
for _, k := range removedEnv {
if _, ok := lookup(k); ok {
if softEnv[k] {
warn = append(warn, k)
} else {
bad = append(bad, k)
}
}
}
// URUTAU_PEER_TOKEN_<NAME>[_FILE]
for _, kv := range os.Environ() {
if k, _, _ := strings.Cut(kv, "="); strings.HasPrefix(k, "URUTAU_PEER_TOKEN_") && !contains(bad, k) {
bad = append(bad, k)
}
}
if len(bad) > 0 {
return warn, fmt.Errorf("these variables were removed in Urutau 2.0 (the federation and the log paths moved to probes): %s; see %s", strings.Join(bad, ", "), MigrationGuide)
}
return warn, nil
}
func loopbackBind(bind string) bool {
@@ -448,45 +405,6 @@ func Secret(name string) (string, error) {
return "", nil
}
// tokenEnvName turns a peer name into its environment suffix: "hostinger" ->
// "HOSTINGER", "my-peer" -> "MY_PEER".
func tokenEnvName(name string) string {
return strings.Map(func(r rune) rune {
switch {
case r >= 'a' && r <= 'z':
return r - 32
case r >= 'A' && r <= 'Z', r >= '0' && r <= '9':
return r
}
return '_'
}, name)
}
// perPeerTokens collects URUTAU_PEER_TOKEN_<NAME> and URUTAU_PEER_TOKEN_<NAME>_FILE.
func perPeerTokens() (map[string]string, error) {
const prefix = "URUTAU_PEER_TOKEN_"
out := map[string]string{}
for _, kv := range os.Environ() {
k, v, _ := strings.Cut(kv, "=")
if !strings.HasPrefix(k, prefix) || k == prefix+"FILE" || v == "" {
continue
}
name := strings.TrimPrefix(k, prefix)
if strings.HasSuffix(name, "_FILE") {
b, err := os.ReadFile(v)
if err != nil {
return nil, fmt.Errorf("%s: %w", k, err)
}
out[strings.TrimSuffix(name, "_FILE")] = strings.TrimSpace(string(b))
continue
}
if _, set := out[name]; !set {
out[name] = v
}
}
return out, nil
}
// AdminUserList splits --admin-users into names.
func (c Config) AdminUserList() []string {
var out []string
+2 -2
View File
@@ -31,10 +31,10 @@ func Doctor(c Config, w io.Writer, asJSON bool) bool {
token, terr := Secret("URUTAU_TOKEN")
if terr != nil {
add("config", "fail", terr.Error())
} else if _, err := c.Validate(token); err != nil {
} else if err := c.Validate(token); err != nil {
add("config", "fail", err.Error())
} else {
add("config", "ok", "token, peers and bind are valid")
add("config", "ok", "token and bind are valid")
}
for _, s := range []struct{ name, path string }{{"traefik", c.TraefikLog}, {"ssh", c.AuthLog}, {"fail2ban", c.Fail2banLog}} {
if s.path == "" {
+24 -46
View File
@@ -1,10 +1,8 @@
package app
import (
"log/slog"
"net"
"net/netip"
"net/url"
"os"
"strconv"
"strings"
@@ -12,25 +10,23 @@ import (
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/hub"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/server"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
// newEgress builds the egress analysis, or returns nil when it is off (or in
// auto mode without the host log).
func newEgress(c Config, st *store.Store, log *slog.Logger) (*egress.Source, error) {
mode := strings.ToLower(c.Egress)
if mode == "off" || c.EgressLog == "" {
return nil, nil
// egressMode reports whether the egress analysis may exist at all.
func egressOff(c Config) bool { return strings.ToLower(c.Egress) == "off" }
// newEgressEngine builds the egress engine of one node from its own
// configuration (workloads, resolvers, allow); the primary probe falls back
// to the URUTAU_EGRESS_* defaults of the hub.
func newEgressEngine(c Config, st *store.Store, eg hub.Egress, primary bool) (*egress.Engine, error) {
workloads, resolvers, extra := eg.Workloads, eg.Resolvers, eg.Allow
if primary {
workloads, resolvers = orDefault(workloads, c.EgressWorkloads), orDefault(resolvers, c.EgressResolvers)
extra = orDefault(extra, c.EgressAllow)
}
if mode == "" || mode == "auto" {
if _, err := os.Stat(c.EgressLog); err != nil {
return nil, nil
}
}
allow := egressAllow(c)
var provMu sync.Mutex
var provCache []string
provider := func() []string {
@@ -41,11 +37,11 @@ func newEgress(c Config, st *store.Store, log *slog.Logger) (*egress.Source, err
}
return provCache
}
eng, err := egress.New(egress.Config{
Workloads: c.EgressWorkloads,
Resolvers: c.EgressResolvers,
Allow: allow,
Containers: c.EgressContainers,
return egress.New(egress.Config{
Workloads: workloads,
Resolvers: resolvers,
Allow: egressAllow(c, extra),
ResolvConf: []string{}, // the probe sends its own resolv.conf
TorRelay: func(a netip.Addr) bool { return intel.IsTorRelay(a) && !intel.IsTorExit(a) },
ProviderASNs: provider,
Geo: func(ip string) (string, string, string) {
@@ -66,30 +62,13 @@ func newEgress(c Config, st *store.Store, log *slog.Logger) (*egress.Source, err
return false, ""
},
})
if err != nil {
return nil, err
}
server.SetEgress(eng)
log.Info("egress analysis on", "log", c.EgressLog)
return egress.NewSource(c.EgressLog, eng, log), nil
}
// egressExtraAllow adds to the egress Allow list the addresses of the peers and
// the CIDRs of URUTAU_EGRESS_ALLOW (legitimate periodic pollers).
func egressExtraAllow(c Config) []netip.Prefix {
// egressExtraAllow parses a comma separated list of CIDRs and addresses
// (URUTAU_EGRESS_ALLOW: legitimate periodic pollers).
func egressExtraAllow(spec string) []netip.Prefix {
var out []netip.Prefix
for _, ps := range c.Peers {
p, err := fed.ParsePeer(ps)
if err != nil {
continue
}
if u, err := url.Parse(p.URL); err == nil && u.Hostname() != "" {
for _, a := range resolveHost(u.Hostname()) {
out = append(out, netip.PrefixFrom(a, a.BitLen()))
}
}
}
for _, s := range strings.Split(os.Getenv("URUTAU_EGRESS_ALLOW"), ",") {
for _, s := range strings.Split(spec, ",") {
if s = strings.TrimSpace(s); s == "" {
continue
}
@@ -166,15 +145,14 @@ func providerASNs(explicit string, asnOf func(ip string) uint32) []string {
// egressAllow is the list of destinations that never produce a finding: the
// trusted origins (our own servers, an invalid item does not discard the
// others), the federation peers, URUTAU_EGRESS_ALLOW and the local public
// addresses.
func egressAllow(c Config) []netip.Prefix {
// others), the extra list of the probe and the local public addresses.
func egressAllow(c Config, extra string) []netip.Prefix {
var allow []netip.Prefix
for _, part := range strings.Split(c.Trusted, ",") {
if nets, err := core.ParseCIDRs(part); err == nil {
allow = append(allow, nets...)
}
}
allow = append(allow, egressExtraAllow(c)...)
allow = append(allow, egressExtraAllow(extra)...)
return append(allow, ownPublicPrefixes()...)
}
+29 -110
View File
@@ -1,43 +1,31 @@
package app
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"net"
"net/netip"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
// newEnforce builds the second firewall and hooks it into the store; nil when off.
func newEnforce(c Config, st *store.Store, peers []fed.Peer, en enricher, ready func() bool) *enforce.Engine {
// newEnforce builds the second firewall of one node and hooks it into the
// node's store; nil when off. The decisions go to sink (the probe's queue).
func newEnforce(c Config, st *store.Store, name, dir string, sink func(kind, line string) error, en enricher, ready func() bool) *enforce.Engine {
mode := strings.ToLower(c.Enforce)
if mode != enforce.ModeObserve && mode != enforce.ModeOn {
return nil
}
trusted, _ := core.ParseCIDRs(c.Ignore + "," + c.Trusted)
var hosts []string
for _, p := range peers {
if u, err := url.Parse(p.URL); err == nil && u.Hostname() != "" {
hosts = append(hosts, u.Hostname())
}
}
e := enforce.New(enforce.Config{
Mode: mode, Path: c.EnforceLog, UnbanPath: unbanLogPath(c), StatePath: filepath.Join(c.DataDir, "enforce.json"), Host: c.Name,
Mode: mode, Sink: sink, StatePath: filepath.Join(dir, "enforce.json"), Host: name,
Threshold: c.EnforceThreshold, MaxPerMin: c.EnforceMaxPerMin, Share: strings.EqualFold(c.EnforceShare, "on"),
Trusted: trusted, PeerHosts: hosts, InfraHosts: hosts, Resolve: resolveHost,
Trusted: trusted, Resolve: resolveHost,
Crawler: func(ip string, uas []string) bool {
if v := st.FCrDNS(ip, uas); v != nil && *v {
return true
@@ -91,41 +79,33 @@ func resolveHost(h string) []netip.Addr {
return ips
}
// shareDecisions pulls the decisions of every peer and pushes the local ones, every 30 s.
func shareDecisions(ctx context.Context, hub *fed.Hub, e *enforce.Engine, log *slog.Logger) {
pulled := map[string]int64{}
pushed := map[string]int64{}
pushedUn := map[string]int64{}
// shareDecisions relays, every 30 s, the decisions and unbans of each node to
// the others (ENFORCE_SHARE=on); each receiver applies its own exclusions.
func shareDecisions(ctx context.Context, nodes func() []*Node) {
type mark struct{ dec, un int64 }
last := map[[2]string]mark{} // [from, to]
t := time.NewTicker(30 * time.Second)
defer t.Stop()
for {
for _, p := range hub.Peers {
start := time.Now().Unix()
var in struct {
Decisions []enforce.Wire `json:"decisions"`
all := nodes()
for _, from := range all {
if from.Enf == nil {
continue
}
if err := hub.Get(ctx, p, fmt.Sprintf("/api/v1/peer/decisions?since=%d", pulled[p.Name]), &in); err == nil {
e.AcceptPeer(p.Name, in.Decisions)
pulled[p.Name] = start - 5
} else if ctx.Err() == nil {
log.Debug("enforce: pull failed", "peer", p.Name, "err", err)
}
if mine := e.LocalSince(pushed[p.Name]); len(mine) > 0 {
if err := hub.PostJSON(ctx, p, "/api/v1/peer/decisions?from="+url.QueryEscape(e.Host()), map[string]any{"decisions": mine}); err == nil {
pushed[p.Name] = start
} else if ctx.Err() == nil {
log.Debug("enforce: push failed", "peer", p.Name, "err", err)
for _, to := range all {
if to == from || to.Enf == nil {
continue
}
}
}
for _, p := range hub.Peers {
if mine := e.UnbansSince(pushedUn[p.Name]); len(mine) > 0 {
k := [2]string{from.name, to.name}
m := last[k]
start := time.Now().Unix()
if err := hub.PostJSON(ctx, p, "/api/v1/peer/unban?from="+url.QueryEscape(e.Host()), map[string]any{"unbans": mine}); err == nil {
pushedUn[p.Name] = start
} else if ctx.Err() == nil {
log.Debug("enforce: unban push failed", "peer", p.Name, "err", err)
if d := from.Enf.LocalSince(m.dec); len(d) > 0 {
to.Enf.AcceptPeer(from.name, d)
}
if u := from.Enf.UnbansSince(m.un); len(u) > 0 {
to.Enf.AcceptPeerUnban(from.name, u)
}
last[k] = mark{start - 5, start}
}
}
select {
@@ -136,77 +116,16 @@ func shareDecisions(ctx context.Context, hub *fed.Hub, e *enforce.Engine, log *s
}
}
// doctorEnforce reports the mode of the second firewall and its file.
// doctorEnforce reports the mode of the second firewall. Decisions are queued
// for the probes, which write them on their hosts (the probe reports a
// command that cannot be written as cmd_errors).
func doctorEnforce(c Config, add func(name, status, detail string)) {
mode := strings.ToLower(c.Enforce)
if mode == "" || mode == "off" {
add("enforce", "off", "disabled (--enforce=off)")
return
}
w := enforce.Writable(c.EnforceLog)
detail := fmt.Sprintf("mode=%s share=%s threshold=%d file=%s writable=%v", mode, strings.ToLower(orDefault(c.EnforceShare, "off")), c.EnforceThreshold, c.EnforceLog, w)
switch {
case mode == "on" && !w:
add("enforce", "fail", detail)
case !w:
add("enforce", "warn", detail)
default:
add("enforce", "ok", detail)
}
if mode == "on" {
if n, tot := cloudflareClients(c.TraefikLog); n > 0 {
add("enforce-cdn", "warn", fmt.Sprintf("%d of the last %d requests in %s come from Cloudflare addresses: Traefik is not "+
"restoring the real client IP (set entryPoints.*.forwardedHeaders.trustedIPs to the Cloudflare ranges); "+
"Cloudflare is never banned, but the real attackers stay invisible", n, tot, c.TraefikLog))
}
}
}
// cloudflareClients counts, in the tail of the Traefik JSON access log, the
// requests whose ClientHost is a Cloudflare address.
func cloudflareClients(path string) (cf, total int) {
if path == "" {
return 0, 0
}
f, err := os.Open(path)
if err != nil {
return 0, 0
}
defer f.Close()
const tail = 512 << 10
if fi, err := f.Stat(); err == nil && fi.Size() > tail {
f.Seek(fi.Size()-tail, io.SeekStart)
}
sc := bufio.NewScanner(f)
sc.Buffer(make([]byte, 0, 64<<10), 1<<20)
for sc.Scan() {
var l struct {
ClientHost string `json:"ClientHost"`
}
if json.Unmarshal(sc.Bytes(), &l) != nil || l.ClientHost == "" {
continue
}
a, err := netip.ParseAddr(l.ClientHost)
if err != nil {
continue
}
total++
if enforce.IsCloudflare(a) {
cf++
}
}
return cf, total
}
// unbanLogPath is --enforce-unban-log, or unban.log next to --enforce-log.
func unbanLogPath(c Config) string {
if c.EnforceUnbanLog != "" {
return c.EnforceUnbanLog
}
if c.EnforceLog == "" {
return ""
}
return filepath.Join(filepath.Dir(c.EnforceLog), "unban.log")
add("enforce", "ok", fmt.Sprintf("mode=%s share=%s threshold=%d (decisions are queued for each probe)", mode, strings.ToLower(orDefault(c.EnforceShare, "off")), c.EnforceThreshold))
}
func tallyOf(t store.Tally24) enforce.Tally {
+795
View File
@@ -0,0 +1,795 @@
package app
// Import of a 1.x data directory into a 2.0 hub (see docs/migration-2.0.md).
//
// The rule that shapes everything here: no byte registered in production may
// be lost. So the import never merges, never rewrites and never deletes: it
// copies the whole directory (every file, known or not) into the node
// directory of the probe, byte for byte, and proves the copy with sha256 of
// every file plus counts loaded with the real store, evlog and incident code.
import (
"bufio"
"bytes"
"compress/gzip"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"sort"
"strings"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/incidents"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
// ManifestName is the proof of a finished import, written inside the node
// directory (and so renamed into place together with the data).
const ManifestName = "import-manifest.json"
// lockName is the lock the hub holds on its data directory while it runs.
const lockName = ".lock"
// ImportOptions tune Import.
type ImportOptions struct {
// DryRun reads and compares everything but writes nothing at all.
DryRun bool
// Force replaces a divergent destination by moving it to <dest>.bak-<ts>
// (it is never deleted).
Force bool
// IncludeGeo also copies geo/ (the databases are re-downloaded by the hub,
// so by default they are skipped with a warning).
IncludeGeo bool
}
// FileCopy is one entry of the copy.
type FileCopy struct {
Path string `json:"path"` // relative, slash separated
Kind string `json:"kind"` // file, dir or symlink
Size int64 `json:"size"` // bytes (files)
Mode uint32 `json:"mode"` // permission bits
MTime int64 `json:"mtime_ns"` // modification time, unix ns
SHA256 string `json:"sha256,omitempty"` // files: content; symlinks: of the target text
Target string `json:"target,omitempty"` // symlinks
}
// Counts is what a data directory holds, measured by loading it with the real
// code of the 1.x store, evlog and incidents.
type Counts struct {
Events int `json:"events"` // lines of events/*.jsonl and *.jsonl.gz
EventFiles int `json:"event_files"` // day files in events/
IPs int `json:"ips"` // addresses of the snapshot
Offsets int `json:"offsets"` // saved read positions of the snapshot
Incidents int `json:"incidents"` // tickets of incidents.json
Comments int `json:"comments"` // comments over all tickets
Suppressed int `json:"suppressed"` // tickets with an active suppression
EnforceBans int `json:"enforce_bans"` // bans (with history) of enforce.json
EnforceAllow int `json:"enforce_allow"` // allows of enforce.json
}
// ImportReport is the result of Import and VerifyImport.
type ImportReport struct {
Counts
Files []FileCopy `json:"files"`
Skipped bool `json:"skipped"` // already imported, nothing done
DryRun bool `json:"dry_run"` // nothing was written
Dest string `json:"dest"` // node directory
Backup string `json:"backup,omitempty"` // where --force moved the old destination
Warnings []string `json:"warnings,omitempty"`
}
type manifest struct {
Version int `json:"version"`
Host string `json:"host"`
From string `json:"from"`
ImportedAt string `json:"imported_at"`
Files []FileCopy `json:"files"`
Counts Counts `json:"counts"`
}
// importDest is where the files of a probe live: <data-dir>/probes/<host>.
func importDest(dataDir, host string) string { return NodeDir(dataDir, host, false) }
// FormatCounts is the stable text of `urutau import --count`.
func FormatCounts(c Counts) string {
return fmt.Sprintf("events=%d event_files=%d ips=%d offsets=%d incidents=%d comments=%d suppressed=%d enforce_bans=%d enforce_allow=%d\n",
c.Events, c.EventFiles, c.IPs, c.Offsets, c.Incidents, c.Comments, c.Suppressed, c.EnforceBans, c.EnforceAllow)
}
// ---------------------------------------------------------------------------
// counting
// CountDir loads a data directory read-only and counts what is in it. The
// directory is never modified: the incident store is opened on a private copy
// because Open renames a corrupt file.
func CountDir(dir string) (Counts, error) {
var c Counts
fi, err := os.Stat(dir)
if err != nil {
return c, err
}
if !fi.IsDir() {
return c, fmt.Errorf("%s is not a directory", dir)
}
// snapshot, with the real store code (no IP cap: the snapshot is measured, not trimmed)
snap := SnapshotPath(dir)
if _, err := os.Stat(snap); err == nil {
st := store.New(store.Config{Name: "count", MaxIPs: 1 << 30})
offs, err := st.Load(snap)
if err != nil {
return c, fmt.Errorf("snapshot %s: %w", snap, err)
}
c.IPs, c.Offsets = st.IPCount(), len(offs)
}
// event registry
ents, err := os.ReadDir(filepath.Join(dir, "events"))
if err != nil && !errors.Is(err, os.ErrNotExist) {
return c, err
}
for _, e := range ents {
n := e.Name()
if e.IsDir() || !(strings.HasSuffix(n, ".jsonl") || strings.HasSuffix(n, ".jsonl.gz")) {
continue
}
k, err := countLines(filepath.Join(dir, "events", n), strings.HasSuffix(n, ".gz"))
if err != nil {
return c, fmt.Errorf("events/%s: %w", n, err)
}
c.Events += k
c.EventFiles++
}
// incidents, with the real incident code on a private copy
if b, err := os.ReadFile(filepath.Join(dir, "incidents.json")); err == nil {
if !json.Valid(b) {
return c, errors.New("incidents.json is not valid JSON")
}
tmp, err := os.MkdirTemp("", "urutau-count-")
if err != nil {
return c, err
}
defer os.RemoveAll(tmp)
p := filepath.Join(tmp, "incidents.json")
if err := os.WriteFile(p, b, 0o600); err != nil {
return c, err
}
is, err := incidents.Open(p, nil)
if err != nil {
return c, err
}
c.Incidents = is.Stats().Size
now := time.Now().Unix()
for _, s := range is.All(incidents.Query{}) {
c.Comments += s.CommentCount
if s.Suppress && (s.SuppressUntil == 0 || s.SuppressUntil > now) {
c.Suppressed++
}
}
} else if !errors.Is(err, os.ErrNotExist) {
return c, err
}
// enforce.json (ban history)
if b, err := os.ReadFile(filepath.Join(dir, "enforce.json")); err == nil {
var sf struct {
Bans map[string]json.RawMessage `json:"bans"`
Allows map[string]json.RawMessage `json:"allows"`
}
if err := json.Unmarshal(b, &sf); err != nil {
return c, fmt.Errorf("enforce.json: %w", err)
}
c.EnforceBans, c.EnforceAllow = len(sf.Bans), len(sf.Allows)
} else if !errors.Is(err, os.ErrNotExist) {
return c, err
}
return c, nil
}
func countLines(path string, gz bool) (int, error) {
f, err := os.Open(path)
if err != nil {
return 0, err
}
defer f.Close()
var r io.Reader = f
if gz {
zr, err := gzip.NewReader(f)
if err != nil {
return 0, err
}
defer zr.Close()
r = zr
}
br := bufio.NewReaderSize(r, 256*1024)
n := 0
for {
line, err := br.ReadBytes('\n')
if len(bytes.TrimSpace(line)) > 0 {
n++
}
if err == io.EOF {
return n, nil
}
if err != nil {
return n, err
}
}
}
// ---------------------------------------------------------------------------
// tree
type tree struct {
entries []FileCopy
warnings []string
}
// scanTree lists root (without hashes). Symlinks are kept as symlinks and
// never followed; sockets and devices are skipped with a warning.
func scanTree(root string, includeGeo, dest bool) (*tree, error) {
t := &tree{}
err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
rel, _ := filepath.Rel(root, p)
if rel == "." {
return nil
}
rel = filepath.ToSlash(rel)
top := strings.SplitN(rel, "/", 2)[0]
switch {
case rel == lockName:
t.warnings = append(t.warnings, ".lock of the source is not copied")
return nil
case rel == ManifestName && dest:
t.entries = append(t.entries, FileCopy{Path: rel, Kind: "file"})
return nil
case rel == ManifestName:
return fmt.Errorf("the source already holds %s: it is an import destination, not a 1.x data directory", ManifestName)
case top == "geo" && !includeGeo:
if rel == "geo" {
t.warnings = append(t.warnings, "geo/ skipped (the hub downloads its own databases; use --include-geo to copy it)")
}
if d.IsDir() {
return fs.SkipDir
}
return nil
}
fi, err := d.Info()
if err != nil {
return err
}
e := FileCopy{Path: rel, Mode: uint32(fi.Mode().Perm()), MTime: fi.ModTime().UnixNano(), Size: fi.Size()}
switch m := fi.Mode(); {
case m.IsDir():
e.Kind, e.Size = "dir", 0
case m.IsRegular():
e.Kind = "file"
case m&fs.ModeSymlink != 0:
tg, err := os.Readlink(p)
if err != nil {
return err
}
sum := sha256.Sum256([]byte(tg))
e.Kind, e.Target, e.SHA256, e.Size = "symlink", tg, hex.EncodeToString(sum[:]), 0
default:
t.warnings = append(t.warnings, fmt.Sprintf("%s: special file skipped", rel))
return nil
}
t.entries = append(t.entries, e)
return nil
})
sort.Slice(t.entries, func(i, j int) bool { return t.entries[i].Path < t.entries[j].Path })
return t, err
}
func hashFile(path string) (string, int64, error) {
f, err := os.Open(path)
if err != nil {
return "", 0, err
}
defer f.Close()
h := sha256.New()
n, err := io.Copy(h, f)
return hex.EncodeToString(h.Sum(nil)), n, err
}
// hashTree fills the sha256 of every regular file of t.
func hashTree(root string, t *tree) error {
for i := range t.entries {
e := &t.entries[i]
if e.Kind != "file" {
continue
}
sum, n, err := hashFile(filepath.Join(root, filepath.FromSlash(e.Path)))
if err != nil {
return err
}
e.SHA256, e.Size = sum, n
}
return nil
}
// sameContent compares what the files hold (path, kind, size, hash, target).
func sameContent(a, b []FileCopy) []string {
bm := make(map[string]FileCopy, len(b))
for _, e := range b {
bm[e.Path] = e
}
var diff []string
seen := map[string]bool{}
for _, x := range a {
seen[x.Path] = true
y, ok := bm[x.Path]
switch {
case !ok:
diff = append(diff, "missing: "+x.Path)
case x.Kind != y.Kind:
diff = append(diff, "kind differs: "+x.Path)
case x.SHA256 != y.SHA256 || x.Size != y.Size || x.Target != y.Target:
diff = append(diff, "content differs: "+x.Path)
}
}
for _, y := range b {
if !seen[y.Path] {
diff = append(diff, "extra: "+y.Path)
}
}
sort.Strings(diff)
return diff
}
// sameMeta compares mode and mtime (files and dirs; symlinks have no own mtime we keep).
func sameMeta(a, b []FileCopy) []string {
bm := make(map[string]FileCopy, len(b))
for _, e := range b {
bm[e.Path] = e
}
var diff []string
for _, x := range a {
if x.Kind == "symlink" {
continue
}
if y, ok := bm[x.Path]; ok && (x.Mode != y.Mode || x.MTime != y.MTime) {
diff = append(diff, "mode or mtime differs: "+x.Path)
}
}
return diff
}
// ---------------------------------------------------------------------------
// import
func checkArgs(from, dataDir, host string) (src, dst string, err error) {
if !wire.ValidName(host) {
return "", "", fmt.Errorf("invalid host name %q (lowercase letters, digits and dashes, up to 32)", host)
}
if src, err = filepath.Abs(from); err != nil {
return
}
fi, serr := os.Stat(src)
if serr != nil {
return "", "", serr
}
if !fi.IsDir() {
return "", "", fmt.Errorf("--from %s is not a directory", from)
}
dd, err := filepath.Abs(dataDir)
if err != nil {
return
}
dst = importDest(dd, host)
if within(src, dd) || within(dd, src) {
return "", "", fmt.Errorf("--from %s and the data dir %s must not contain one another", src, dd)
}
return src, dst, nil
}
func within(a, b string) bool {
r, err := filepath.Rel(b, a)
return err == nil && (r == "." || (r != ".." && !strings.HasPrefix(r, ".."+string(filepath.Separator))))
}
// Import copies the whole 1.x data directory `from` into the node directory of
// `host` under dataDir and verifies the copy. See the package comment.
func Import(from, dataDir, host string, opt ImportOptions) (ImportReport, error) {
rep := ImportReport{DryRun: opt.DryRun}
src, dst, err := checkArgs(from, dataDir, host)
if err != nil {
return rep, err
}
dataDir, _ = filepath.Abs(dataDir)
rep.Dest = dst
lock := filepath.Join(dataDir, lockName)
if _, err := os.Lstat(lock); err == nil {
return rep, fmt.Errorf("%s exists: the hub (or another import) is running on this data dir; stop it first (if it is stale, remove the file)", lock)
}
// read the source twice, around the copy, to catch a writer
t, err := scanTree(src, opt.IncludeGeo, false)
if err != nil {
return rep, err
}
rep.Warnings = append(rep.Warnings, t.warnings...)
if err := hashTree(src, t); err != nil {
return rep, err
}
rep.Files = t.entries
srcCounts, err := CountDir(src)
if err != nil {
return rep, fmt.Errorf("source does not load: %w", err)
}
rep.Counts = srcCounts
// destination state
if _, err := os.Lstat(dst); err == nil {
prev, merr := readManifest(dst)
if merr == nil && len(sameContent(t.entries, prev.Files)) == 0 {
rep.Skipped = true
if cur, err := scanTree(dst, true, true); err == nil {
_ = hashTree(dst, cur)
if d := sameContent(prev.Files, dropManifest(cur.entries)); len(d) > 0 {
rep.Warnings = append(rep.Warnings, fmt.Sprintf("destination changed since the import (%d files; the hub already ran?); nothing was touched", len(d)))
}
}
return rep, nil
}
if !opt.Force {
return rep, fmt.Errorf("%s already exists with different content (or no manifest); nothing was changed. Compare with --verify, or use --force to move it to %s.bak-<timestamp> (never deleted)", dst, dst)
}
} else if !errors.Is(err, os.ErrNotExist) {
return rep, err
}
if opt.DryRun {
return rep, nil
}
// from here on we write: take the data-dir lock so the hub cannot start in the middle
if err := os.MkdirAll(dataDir, 0o700); err != nil {
return rep, err
}
lf, err := os.OpenFile(lock, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
if err != nil {
return rep, fmt.Errorf("cannot take %s: %w", lock, err)
}
fmt.Fprintf(lf, "import pid=%d\n", os.Getpid())
lf.Close()
defer os.Remove(lock)
parent := filepath.Dir(dst)
if err := os.MkdirAll(parent, 0o700); err != nil {
return rep, err
}
stamp := time.Now().UTC().Format("20060102T150405")
tmp := filepath.Join(parent, fmt.Sprintf(".import-%s-%d.tmp", host, os.Getpid()))
if err := os.RemoveAll(tmp); err != nil { // our own leftover of this very pid
return rep, err
}
ok := false
defer func() {
if !ok {
os.RemoveAll(tmp)
}
}()
if err := copyTree(src, tmp, t.entries); err != nil {
return rep, err
}
// verify the copy: hashes of what was written, counts through the real loaders, and the source unchanged
got, err := scanTree(tmp, true, true)
if err != nil {
return rep, err
}
if err := hashTree(tmp, got); err != nil {
return rep, err
}
if d := sameContent(t.entries, got.entries); len(d) > 0 {
return rep, fmt.Errorf("copy verification failed (%d differences, first: %s); nothing was installed", len(d), d[0])
}
if d := sameMeta(t.entries, got.entries); len(d) > 0 {
return rep, fmt.Errorf("copy verification failed (%s); nothing was installed", d[0])
}
dstCounts, err := CountDir(tmp)
if err != nil {
return rep, fmt.Errorf("copy does not load: %w", err)
}
if dstCounts != srcCounts {
return rep, fmt.Errorf("counts differ after the copy: source %+v, copy %+v; nothing was installed", srcCounts, dstCounts)
}
after, err := scanTree(src, opt.IncludeGeo, false)
if err != nil {
return rep, err
}
if err := hashTree(src, after); err != nil {
return rep, err
}
if d := sameContent(t.entries, after.entries); len(d) > 0 {
return rep, fmt.Errorf("the source changed while it was being copied (%s): stop the 1.x instance and run again; nothing was installed", d[0])
}
m := manifest{Version: 1, Host: host, From: src, ImportedAt: time.Now().UTC().Format(time.RFC3339), Files: t.entries, Counts: srcCounts}
mb, _ := json.MarshalIndent(m, "", " ")
if err := writeFileSync(filepath.Join(tmp, ManifestName), mb, 0o600); err != nil {
return rep, err
}
syncDir(tmp)
if opt.Force {
if _, err := os.Lstat(dst); err == nil {
bak := dst + ".bak-" + stamp
for i := 2; ; i++ { // never overwrite an earlier backup
if _, err := os.Lstat(bak); errors.Is(err, os.ErrNotExist) {
break
}
bak = fmt.Sprintf("%s.bak-%s-%d", dst, stamp, i)
}
if err := os.Rename(dst, bak); err != nil {
return rep, err
}
rep.Backup = bak
}
}
if err := os.Rename(tmp, dst); err != nil {
return rep, err
}
ok = true
syncDir(parent)
return rep, nil
}
func dropManifest(in []FileCopy) []FileCopy {
out := make([]FileCopy, 0, len(in))
for _, e := range in {
if e.Path != ManifestName {
out = append(out, e)
}
}
return out
}
func readManifest(dir string) (manifest, error) {
var m manifest
b, err := os.ReadFile(filepath.Join(dir, ManifestName))
if err != nil {
return m, err
}
return m, json.Unmarshal(b, &m)
}
// copyTree copies entries (already listed under src) to dst, preserving mode
// and mtime. Directories get their times last, children first.
func copyTree(src, dst string, entries []FileCopy) error {
if err := os.MkdirAll(dst, 0o700); err != nil {
return err
}
var dirs []FileCopy
for _, e := range entries {
from, to := filepath.Join(src, filepath.FromSlash(e.Path)), filepath.Join(dst, filepath.FromSlash(e.Path))
switch e.Kind {
case "dir":
if err := os.MkdirAll(to, 0o700); err != nil {
return err
}
dirs = append(dirs, e)
case "symlink":
if err := os.Symlink(e.Target, to); err != nil {
return err
}
case "file":
if err := copyFile(from, to, e); err != nil {
return fmt.Errorf("%s: %w", e.Path, err)
}
}
}
for i := len(dirs) - 1; i >= 0; i-- {
e := dirs[i]
to := filepath.Join(dst, filepath.FromSlash(e.Path))
if err := os.Chmod(to, fs.FileMode(e.Mode)); err != nil {
return err
}
syncDir(to)
if err := os.Chtimes(to, time.Unix(0, e.MTime), time.Unix(0, e.MTime)); err != nil {
return err
}
}
return nil
}
func copyFile(from, to string, e FileCopy) error {
in, err := os.Open(from)
if err != nil {
return err
}
defer in.Close()
out, err := os.OpenFile(to, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
if err != nil {
return err
}
_, err = io.Copy(out, in)
if err == nil {
err = out.Sync()
}
if cerr := out.Close(); err == nil {
err = cerr
}
if err != nil {
return err
}
if err := os.Chmod(to, fs.FileMode(e.Mode)); err != nil {
return err
}
return os.Chtimes(to, time.Unix(0, e.MTime), time.Unix(0, e.MTime))
}
func writeFileSync(path string, b []byte, mode fs.FileMode) error {
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, mode)
if err != nil {
return err
}
_, err = f.Write(b)
if err == nil {
err = f.Sync()
}
if cerr := f.Close(); err == nil {
err = cerr
}
return err
}
func syncDir(p string) {
if f, err := os.Open(p); err == nil {
_ = f.Sync()
f.Close()
}
}
// ---------------------------------------------------------------------------
// verify
// VerifyImport compares the source with the imported node directory (it
// writes nothing): sha256, size, mode and mtime of every file, then the counts.
// Run it before the hub starts on the destination; once the hub runs, its
// files change by design.
func VerifyImport(from, dataDir, host string) (ImportReport, error) {
rep := ImportReport{DryRun: true}
src, dst, err := checkArgs(from, dataDir, host)
if err != nil {
return rep, err
}
rep.Dest = dst
m, err := readManifest(dst)
if err != nil {
return rep, fmt.Errorf("%s has no readable %s (not imported yet?): %w", dst, ManifestName, err)
}
// geo/ was in the copy iff the manifest lists it
withGeo := false
for _, e := range m.Files {
if e.Path == "geo" || strings.HasPrefix(e.Path, "geo/") {
withGeo = true
break
}
}
s, err := scanTree(src, withGeo, false)
if err != nil {
return rep, err
}
rep.Warnings = append(rep.Warnings, s.warnings...)
if err := hashTree(src, s); err != nil {
return rep, err
}
d, err := scanTree(dst, true, true)
if err != nil {
return rep, err
}
if err := hashTree(dst, d); err != nil {
return rep, err
}
rep.Files = s.entries
var bad []string
bad = append(bad, sameContent(s.entries, dropManifest(d.entries))...)
bad = append(bad, sameMeta(s.entries, d.entries)...)
sc, err := CountDir(src)
if err != nil {
return rep, err
}
rep.Counts = sc
dc, err := CountDir(dst)
if err != nil {
return rep, err
}
if sc != dc {
bad = append(bad, fmt.Sprintf("counts differ: source %+v, destination %+v", sc, dc))
}
if len(bad) > 0 {
n := len(bad)
if n > 10 {
bad = append(bad[:10], fmt.Sprintf("... and %d more", n-10))
}
return rep, fmt.Errorf("verification FAILED (%d problems):\n %s", n, strings.Join(bad, "\n "))
}
return rep, nil
}
// ---------------------------------------------------------------------------
// command line
// ImportCLI runs `urutau import ...` (args after the word "import") and
// returns the exit code.
//
// urutau import --from DIR --host NAME [--data-dir D] [--dry-run] [--force] [--include-geo]
// urutau import --verify --from DIR --host NAME [--data-dir D]
// urutau import --count DIR
func ImportCLI(args []string, out, errw io.Writer) int {
fs := flag.NewFlagSet("import", flag.ContinueOnError)
fs.SetOutput(errw)
from := fs.String("from", "", "1.x data directory to import (stopped instance)")
host := fs.String("host", "", "name of the probe that receives it")
dataDir := fs.String("data-dir", env("URUTAU_DATA_DIR", "/data"), "hub data directory (URUTAU_DATA_DIR)")
dry := fs.Bool("dry-run", false, "compare and report, write nothing")
force := fs.Bool("force", false, "move a divergent destination to .bak-<ts> (never deleted)")
geo := fs.Bool("include-geo", false, "also copy geo/")
verify := fs.Bool("verify", false, "only compare --from with the imported copy")
count := fs.String("count", "", "print the counts of this data directory and exit")
if err := fs.Parse(args); err != nil {
return 2
}
if *count != "" {
c, err := CountDir(*count)
if err != nil {
fmt.Fprintln(errw, "error:", err)
return 1
}
fmt.Fprint(out, FormatCounts(c))
return 0
}
if *from == "" || *host == "" {
fmt.Fprintln(errw, "usage: urutau import --from DIR --host NAME [--data-dir D] [--dry-run] [--force] [--include-geo] | --verify ... | --count DIR")
return 2
}
if *verify {
rep, err := VerifyImport(*from, *dataDir, *host)
for _, w := range rep.Warnings {
fmt.Fprintln(errw, "warning:", w)
}
if err != nil {
fmt.Fprintln(errw, "error:", err)
return 1
}
fmt.Fprintf(out, "verified: %d files identical (sha256, mode, mtime) in %s\n%s", len(rep.Files), rep.Dest, FormatCounts(rep.Counts))
return 0
}
rep, err := Import(*from, *dataDir, *host, ImportOptions{DryRun: *dry, Force: *force, IncludeGeo: *geo})
for _, w := range rep.Warnings {
fmt.Fprintln(errw, "warning:", w)
}
if err != nil {
fmt.Fprintln(errw, "error:", err)
return 1
}
switch {
case rep.Skipped:
fmt.Fprintf(out, "already imported into %s, nothing done\n", rep.Dest)
case rep.DryRun:
fmt.Fprintf(out, "dry run: %d entries would be copied to %s\n", len(rep.Files), rep.Dest)
default:
fmt.Fprintf(out, "imported %d entries into %s\n", len(rep.Files), rep.Dest)
if rep.Backup != "" {
fmt.Fprintf(out, "previous destination kept at %s\n", rep.Backup)
}
}
fmt.Fprint(out, FormatCounts(rep.Counts))
return 0
}
+537
View File
@@ -0,0 +1,537 @@
package app
import (
"bytes"
"context"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/incidents"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
// fixture is a data directory as written by Urutau 1.6 on the Hostinger host.
// Regenerate it (and expected.json) with:
//
// URUTAU_REGEN_FIXTURE=1 go test ./internal/app -run TestRegenFixture16 -count=1
const fixture = "testdata/hostinger-1.6"
func TestRegenFixture16(t *testing.T) {
if os.Getenv("URUTAU_REGEN_FIXTURE") != "1" {
t.Skip("set URUTAU_REGEN_FIXTURE=1 to regenerate " + fixture)
}
dir, _ := filepath.Abs(fixture)
if err := os.RemoveAll(dir); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(dir, 0o700); err != nil {
t.Fatal(err)
}
now := time.Now()
// store + evlog: the same wiring as serve.go
elog, err := evlog.Open(evlog.Options{Dir: filepath.Join(dir, "events"), Retention: 30 * 24 * time.Hour})
if err != nil {
t.Fatal(err)
}
st := store.New(store.Config{Name: "hostinger", Version: "1.6.0", Retention: 7 * 24 * time.Hour})
st.SetEventLog(elog)
type ev struct {
ip string
cat core.Category
src string
path string
st int
ago time.Duration
n int
}
for _, e := range []ev{
{"203.0.114.7", core.Scanner, "traefik", "/.env", 404, 3 * time.Hour, 6},
{"203.0.114.8", core.Exploit, "traefik", "/cgi-bin/../../etc/passwd", 400, 2 * time.Hour, 4},
{"198.51.101.20", core.SSHFail, "ssh", "", 0, 50 * time.Hour, 5},
{"198.51.101.21", core.OK, "traefik", "/", 200, 26 * time.Hour, 3},
{"192.0.2.99", core.Scanner, "traefik", "/wp-login.php", 404, 90 * time.Hour, 2},
} {
for i := 0; i < e.n; i++ {
c := core.Event{Time: now.Add(-e.ago + time.Duration(i)*time.Second), IP: e.ip, Cat: e.cat, Source: e.src, Domain: "a.example", Method: "GET", Path: e.path, Status: e.st, UA: "fixture"}
if e.src == "ssh" {
c.User = "root"
}
st.Ingest(c)
}
}
elog.Flush()
elog.Close()
if err := st.Save(SnapshotPath(dir), map[string]store.Offset{
"traefik": {Inode: 4242, Offset: 1048576},
"auth": {Inode: 4243, Offset: 22000},
"egress": {Inode: 4244, Offset: 90210},
}); err != nil {
t.Fatal(err)
}
// incidents: INC-1 suppressed, INC-2 with comments, INC-3 manual
is, err := incidents.Open(filepath.Join(dir, "incidents.json"), nil)
if err != nil {
t.Fatal(err)
}
is.Sync([]incidents.Finding{
{Host: "hostinger", Kind: "new-destination", Severity: "medium", Workload: "app-a", Dst: "198.51.100.5", Proto: "tcp", DPort: 443, First: now.Add(-48 * time.Hour).Unix(), Last: now.Add(-time.Hour).Unix(), Count: 12, Detail: "first contact"},
{Host: "hostinger", Kind: "exfil", Severity: "high", Workload: "app-b", Dst: "203.0.113.50", Proto: "tcp", DPort: 4444, First: now.Add(-24 * time.Hour).Unix(), Last: now.Add(-time.Hour).Unix(), Count: 40, Detail: "large upload"},
})
if _, err := is.Create(incidents.NewManual{Title: "Manual review of the proxy", Detail: "opened by the operator", Host: "hostinger", Severity: "low", Author: "lucas"}); err != nil {
t.Fatal(err)
}
fp, yes := "false_positive", true
if _, err := is.Update("INC-1", incidents.Patch{Status: &fp, Suppress: &yes, Author: "lucas"}); err != nil {
t.Fatal(err)
}
for _, c := range []string{"Looks like the nightly backup.", "Confirmed with the app owner; keep watching."} {
if _, err := is.AddComment("INC-2", c, "lucas", ""); err != nil {
t.Fatal(err)
}
}
is.Flush()
// enforce.json: real bans through the real engine
decisions := filepath.Join(t.TempDir(), "decisions.log")
eng := enforce.New(enforce.Config{Mode: enforce.ModeOn, Path: decisions, StatePath: filepath.Join(dir, "enforce.json"), Host: "hostinger", Threshold: 5, MaxPerMin: 60})
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() { eng.Run(ctx); close(done) }()
for _, ip := range []string{"203.0.114.7", "203.0.114.8"} {
for i := 0; i < 6; i++ {
eng.Observe(core.Event{Time: time.Now().Add(-time.Duration(i) * time.Second), IP: ip, Cat: core.Scanner, Source: "traefik", Method: "GET", Path: "/x", Status: 404, UA: "x"}, "")
}
}
for i := 0; i < 100; i++ {
if b, _ := os.ReadFile(decisions); strings.Count(string(b), "\n") >= 2 {
break
}
time.Sleep(100 * time.Millisecond)
}
cancel()
<-done
// files the contract does not name: tor cache, a note, and geo (skipped by default)
must := func(p, s string) {
p = filepath.Join(dir, p)
if err := os.MkdirAll(filepath.Dir(p), 0o750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(p, []byte(s), 0o640); err != nil {
t.Fatal(err)
}
}
must("tor/exit-addresses.txt", "198.51.100.200\n198.51.100.201\n")
must("tor/relays.json", `{"relays":[]}`)
must("operator-notes.txt", "unknown file kept verbatim\n")
must("geo/GeoLite2-City.mmdb", "not a real database")
// fixed mtimes, so the preservation check is meaningful
old := time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC)
for _, p := range []string{"operator-notes.txt", "tor/relays.json", "tor/exit-addresses.txt"} {
_ = os.Chtimes(filepath.Join(dir, p), old, old)
}
c, err := CountDir(dir)
if err != nil {
t.Fatal(err)
}
b, _ := json.MarshalIndent(c, "", " ")
if err := os.WriteFile(filepath.Join(filepath.Dir(dir), "hostinger-1.6.expected.json"), append(b, '\n'), 0o644); err != nil {
t.Fatal(err)
}
t.Logf("fixture regenerated: %+v", c)
}
func expectedCounts(t *testing.T) Counts {
b, err := os.ReadFile("testdata/hostinger-1.6.expected.json")
if err != nil {
t.Fatal(err)
}
var c Counts
if err := json.Unmarshal(b, &c); err != nil {
t.Fatal(err)
}
return c
}
func TestFixtureCounts(t *testing.T) {
c, err := CountDir(fixture)
if err != nil {
t.Fatal(err)
}
if want := expectedCounts(t); c != want {
t.Fatalf("counts %+v want %+v", c, want)
}
if c.Events < 10 || c.IPs < 4 || c.Incidents != 3 || c.Comments < 2 || c.Suppressed < 1 || c.EnforceBans < 2 || c.Offsets != 3 {
t.Fatalf("fixture is not realistic enough: %+v", c)
}
}
func mustImport(t *testing.T, from, dd, host string, o ImportOptions) ImportReport {
t.Helper()
r, err := Import(from, dd, host, o)
if err != nil {
t.Fatal(err)
}
return r
}
func copyDir(t *testing.T, from string) string {
t.Helper()
to := filepath.Join(t.TempDir(), "src")
tr, err := scanTree(from, true, false)
if err != nil {
t.Fatal(err)
}
if err := copyTree(from, to, tr.entries); err != nil {
t.Fatal(err)
}
return to
}
func TestImportCountsAndHashes(t *testing.T) {
dd := t.TempDir()
fixture := copyDir(t, fixture) // git does not keep mtimes: pin one
old := time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC)
os.Chtimes(filepath.Join(fixture, "operator-notes.txt"), old, old)
rep := mustImport(t, fixture, dd, "hostinger", ImportOptions{})
dest := filepath.Join(dd, "probes", "hostinger")
if rep.Dest != dest || rep.Skipped || rep.DryRun {
t.Fatalf("report %+v", rep)
}
if want := expectedCounts(t); rep.Counts != want {
t.Fatalf("counts %+v want %+v", rep.Counts, want)
}
got, err := CountDir(dest)
if err != nil || got != rep.Counts {
t.Fatalf("destination counts %+v %v", got, err)
}
// byte for byte: hashes, mode, mtime of every file; unknown files included; geo skipped
srcT, _ := scanTree(fixture, false, false)
hashTree(fixture, srcT)
dstT, _ := scanTree(dest, true, true)
hashTree(dest, dstT)
if d := sameContent(srcT.entries, dropManifest(dstT.entries)); len(d) > 0 {
t.Fatal(d)
}
if d := sameMeta(srcT.entries, dstT.entries); len(d) > 0 {
t.Fatal(d)
}
for _, must := range []string{"urutau-state.gob", "incidents.json", "enforce.json", "operator-notes.txt", "tor/relays.json", ManifestName} {
if _, err := os.Stat(filepath.Join(dest, must)); err != nil {
t.Errorf("%s missing: %v", must, err)
}
}
if _, err := os.Stat(filepath.Join(dest, "geo")); err == nil {
t.Error("geo/ must be skipped by default")
}
found := false
for _, w := range rep.Warnings {
found = found || strings.Contains(w, "geo/")
}
if !found {
t.Errorf("no geo warning: %v", rep.Warnings)
}
if fi, _ := os.Stat(filepath.Join(dest, "operator-notes.txt")); fi.ModTime().UTC().Year() != 2026 || fi.ModTime().UTC().Month() != 11 || fi.ModTime().UTC().Day() != 1 {
t.Errorf("mtime not preserved: %v", fi.ModTime())
}
if _, err := os.Stat(filepath.Join(dd, lockName)); err == nil {
t.Error("the import lock was left behind")
}
if ents, _ := os.ReadDir(filepath.Join(dd, "probes")); len(ents) != 1 {
t.Errorf("temporary directory left behind: %v", ents)
}
// the real loaders on the copy: the INC-2 comments, the suppression, the evlog lines
is, err := incidents.Open(filepath.Join(dest, "incidents.json"), nil)
if err != nil {
t.Fatal(err)
}
tk, err := is.Get("INC-2")
if err != nil || len(tk.Comments) != 2 {
t.Fatalf("INC-2 %+v %v", tk, err)
}
if tk1, _ := is.Get("INC-1"); !tk1.Suppress {
t.Error("INC-1 lost its suppression")
}
el, err := evlog.Open(evlog.Options{Dir: filepath.Join(dest, "events"), Retention: 30 * 24 * time.Hour})
if err != nil {
t.Fatal(err)
}
n := 0
el.Scan(evlog.Filter{}, 0, false, func(evlog.Rec, []byte) bool { n++; return true })
el.Close()
if n != rep.Events {
t.Errorf("evlog scan sees %d events, count says %d", n, rep.Events)
}
st := store.New(store.Config{Name: "hostinger", MaxIPs: 1 << 20})
if offs, err := st.Load(SnapshotPath(dest)); err != nil || len(offs) != 3 || st.IPCount() != rep.IPs {
t.Errorf("snapshot of the copy: %v %d %v", offs, st.IPCount(), err)
}
// verify passes
if _, err := VerifyImport(fixture, dd, "hostinger"); err != nil {
t.Fatal(err)
}
}
func TestImportIdempotentAndDivergent(t *testing.T) {
dd := t.TempDir()
src := copyDir(t, fixture)
mustImport(t, src, dd, "hostinger", ImportOptions{})
if r := mustImport(t, src, dd, "hostinger", ImportOptions{}); !r.Skipped {
t.Fatalf("second run must be skipped: %+v", r)
}
// a hub that already ran changes the destination: still skipped, with a warning, nothing touched
dest := filepath.Join(dd, "probes", "hostinger")
if err := os.WriteFile(filepath.Join(dest, "incidents.json"), []byte(`{"next":9,"tickets":[]}`), 0o600); err != nil {
t.Fatal(err)
}
r := mustImport(t, src, dd, "hostinger", ImportOptions{})
if !r.Skipped || len(r.Warnings) == 0 {
t.Fatalf("drifted destination: %+v", r)
}
if b, _ := os.ReadFile(filepath.Join(dest, "incidents.json")); !strings.Contains(string(b), `"next":9`) {
t.Fatal("skipped import touched the destination")
}
// the source changes: divergent, refuse without --force
if err := os.WriteFile(filepath.Join(src, "operator-notes.txt"), []byte("changed\n"), 0o640); err != nil {
t.Fatal(err)
}
if _, err := Import(src, dd, "hostinger", ImportOptions{}); err == nil || !strings.Contains(err.Error(), "--force") {
t.Fatalf("divergent without --force must fail: %v", err)
}
if b, _ := os.ReadFile(filepath.Join(dest, "incidents.json")); !strings.Contains(string(b), `"next":9`) {
t.Fatal("a refused import touched the destination")
}
// --force: old destination kept as .bak, new one in place
r = mustImport(t, src, dd, "hostinger", ImportOptions{Force: true})
if r.Backup == "" || !strings.Contains(r.Backup, ".bak-") {
t.Fatalf("backup %+v", r)
}
if b, _ := os.ReadFile(filepath.Join(r.Backup, "incidents.json")); !strings.Contains(string(b), `"next":9`) {
t.Fatal("backup lost the old destination")
}
if _, err := os.Stat(filepath.Join(r.Backup, ManifestName)); err != nil {
t.Fatal("backup lost the old manifest")
}
if b, _ := os.ReadFile(filepath.Join(dest, "operator-notes.txt")); string(b) != "changed\n" {
t.Fatal("new content not installed")
}
// a second --force keeps the first backup too
if err := os.WriteFile(filepath.Join(src, "operator-notes.txt"), []byte("changed again\n"), 0o640); err != nil {
t.Fatal(err)
}
r2 := mustImport(t, src, dd, "hostinger", ImportOptions{Force: true})
if r2.Backup == r.Backup {
t.Fatal("backups collided")
}
if _, err := os.Stat(r.Backup); err != nil {
t.Fatal("first backup was deleted")
}
}
func TestImportDestWithoutManifestIsDivergent(t *testing.T) {
dd := t.TempDir()
dest := filepath.Join(dd, "probes", "hostinger")
os.MkdirAll(dest, 0o700)
os.WriteFile(filepath.Join(dest, "urutau-state.gob"), []byte("something"), 0o600)
if _, err := Import(fixture, dd, "hostinger", ImportOptions{}); err == nil {
t.Fatal("must not import over an existing unknown directory")
}
if b, _ := os.ReadFile(filepath.Join(dest, "urutau-state.gob")); string(b) != "something" {
t.Fatal("destination changed")
}
}
func TestImportDryRunWritesNothing(t *testing.T) {
dd := t.TempDir()
rep := mustImport(t, fixture, dd, "hostinger", ImportOptions{DryRun: true})
if !rep.DryRun || len(rep.Files) == 0 || rep.Events == 0 {
t.Fatalf("report %+v", rep)
}
if ents, _ := os.ReadDir(dd); len(ents) != 0 {
t.Fatalf("dry run wrote %v", ents)
}
// also on top of an existing, divergent destination with --force
mustImport(t, fixture, dd, "hostinger", ImportOptions{})
src := copyDir(t, fixture)
os.WriteFile(filepath.Join(src, "operator-notes.txt"), []byte("x"), 0o640)
before := treeSums(t, dd)
if _, err := Import(src, dd, "hostinger", ImportOptions{DryRun: true, Force: true}); err != nil {
t.Fatal(err)
}
if after := treeSums(t, dd); after != before {
t.Fatal("dry run changed the data dir")
}
}
func treeSums(t *testing.T, root string) string {
tr, err := scanTree(root, true, true)
if err != nil {
t.Fatal(err)
}
if err := hashTree(root, tr); err != nil {
t.Fatal(err)
}
b, _ := json.Marshal(tr.entries)
return string(b)
}
func TestImportRefusesWithLock(t *testing.T) {
dd := t.TempDir()
if err := os.WriteFile(filepath.Join(dd, lockName), []byte("12345\n"), 0o600); err != nil {
t.Fatal(err)
}
for _, o := range []ImportOptions{{}, {DryRun: true}, {Force: true}} {
if _, err := Import(fixture, dd, "hostinger", o); err == nil || !strings.Contains(err.Error(), lockName) {
t.Fatalf("lock must refuse (%+v): %v", o, err)
}
}
if _, err := os.Stat(filepath.Join(dd, "probes")); err == nil {
t.Fatal("wrote something despite the lock")
}
if _, err := os.Stat(filepath.Join(dd, lockName)); err != nil {
t.Fatal("removed a lock that was not ours")
}
}
func TestVerifyDetectsDamage(t *testing.T) {
dd := t.TempDir()
src := copyDir(t, fixture)
if _, err := VerifyImport(src, dd, "hostinger"); err == nil {
t.Fatal("verify before import must fail")
}
old := time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC)
os.Chtimes(filepath.Join(src, "operator-notes.txt"), old, old)
mustImport(t, src, dd, "hostinger", ImportOptions{})
if _, err := VerifyImport(src, dd, "hostinger"); err != nil {
t.Fatal(err)
}
dest := filepath.Join(dd, "probes", "hostinger")
os.WriteFile(filepath.Join(dest, "operator-notes.txt"), []byte("unknown file kept verbatim\n"), 0o640) // same bytes, new mtime
if _, err := VerifyImport(src, dd, "hostinger"); err == nil {
t.Fatal("mtime damage not detected")
}
os.Chtimes(filepath.Join(dest, "operator-notes.txt"), old, old)
if _, err := VerifyImport(src, dd, "hostinger"); err != nil {
t.Fatal(err)
}
b, _ := os.ReadFile(filepath.Join(dest, "urutau-state.gob"))
b[len(b)/2] ^= 0xff
os.WriteFile(filepath.Join(dest, "urutau-state.gob"), b, 0o600)
if _, err := VerifyImport(src, dd, "hostinger"); err == nil || !strings.Contains(err.Error(), "urutau-state.gob") {
t.Fatalf("corruption not detected: %v", err)
}
}
func TestCountDirDoesNotModify(t *testing.T) {
src := copyDir(t, fixture)
before := treeSums(t, src)
if _, err := CountDir(src); err != nil {
t.Fatal(err)
}
if treeSums(t, src) != before {
t.Fatal("counting changed the directory")
}
// a corrupt incidents.json is an error and stays where it is (the real Open would rename it)
os.WriteFile(filepath.Join(src, "incidents.json"), []byte("{broken"), 0o600)
if _, err := CountDir(src); err == nil {
t.Fatal("corrupt incidents.json must be an error")
}
if _, err := os.Stat(filepath.Join(src, "incidents.json")); err != nil {
t.Fatal("corrupt file was moved")
}
}
func TestImportArgs(t *testing.T) {
dd := t.TempDir()
if _, err := Import(fixture, dd, "Bad_Name", ImportOptions{}); err == nil {
t.Fatal("invalid host accepted")
}
if _, err := Import(filepath.Join(dd, "missing"), dd, "hostinger", ImportOptions{}); err == nil {
t.Fatal("missing source accepted")
}
src := filepath.Join(dd, "inside")
os.MkdirAll(src, 0o700)
if _, err := Import(src, dd, "hostinger", ImportOptions{}); err == nil {
t.Fatal("source inside the data dir accepted")
}
if _, err := Import(fixture, fixture, "hostinger", ImportOptions{}); err == nil {
t.Fatal("data dir equal to the source accepted")
}
// a source that is itself an import destination is not a 1.x directory
mustImport(t, fixture, dd, "hostinger", ImportOptions{})
if _, err := Import(filepath.Join(dd, "probes", "hostinger"), t.TempDir(), "other", ImportOptions{}); err == nil {
t.Fatal("manifest in the source must be refused")
}
}
func TestImportGeoOptIn(t *testing.T) {
dd := t.TempDir()
mustImport(t, fixture, dd, "hostinger", ImportOptions{IncludeGeo: true})
if _, err := os.Stat(filepath.Join(dd, "probes", "hostinger", "geo", "GeoLite2-City.mmdb")); err != nil {
t.Fatal(err)
}
if _, err := VerifyImport(fixture, dd, "hostinger"); err != nil {
t.Fatal(err)
}
}
func TestImportEmptyAndSymlink(t *testing.T) {
src := t.TempDir()
os.WriteFile(filepath.Join(src, "extra.bin"), []byte{0, 1, 2}, 0o600)
os.MkdirAll(filepath.Join(src, "sub", "deep"), 0o750)
os.WriteFile(filepath.Join(src, "sub", "deep", "x"), []byte("x"), 0o600)
os.Symlink("extra.bin", filepath.Join(src, "link"))
dd := t.TempDir()
rep := mustImport(t, src, dd, "bare", ImportOptions{})
if rep.Events != 0 || rep.IPs != 0 {
t.Fatalf("%+v", rep.Counts)
}
if tg, err := os.Readlink(filepath.Join(dd, "probes", "bare", "link")); err != nil || tg != "extra.bin" {
t.Fatalf("symlink: %q %v", tg, err)
}
if _, err := VerifyImport(src, dd, "bare"); err != nil {
t.Fatal(err)
}
}
func TestImportCLI(t *testing.T) {
var out, errb bytes.Buffer
if code := ImportCLI([]string{"--count", fixture}, &out, &errb); code != 0 || !strings.Contains(out.String(), "incidents=3") {
t.Fatalf("count: %d %q %q", code, out.String(), errb.String())
}
dd := t.TempDir()
out.Reset()
if code := ImportCLI([]string{"--from", fixture, "--host", "hostinger", "--data-dir", dd, "--dry-run"}, &out, &errb); code != 0 || !strings.Contains(out.String(), "dry run") {
t.Fatalf("dry: %d %q %q", code, out.String(), errb.String())
}
out.Reset()
if code := ImportCLI([]string{"--from", fixture, "--host", "hostinger", "--data-dir", dd}, &out, &errb); code != 0 || !strings.Contains(out.String(), "imported") {
t.Fatalf("import: %d %q %q", code, out.String(), errb.String())
}
out.Reset()
if code := ImportCLI([]string{"--verify", "--from", fixture, "--host", "hostinger", "--data-dir", dd}, &out, &errb); code != 0 || !strings.Contains(out.String(), "verified") {
t.Fatalf("verify: %d %q %q", code, out.String(), errb.String())
}
out.Reset()
if code := ImportCLI([]string{"--from", fixture, "--host", "hostinger", "--data-dir", dd}, &out, &errb); code != 0 || !strings.Contains(out.String(), "already imported") {
t.Fatalf("again: %d %q", code, out.String())
}
if code := ImportCLI([]string{"--host", "x"}, &out, &errb); code != 2 {
t.Fatalf("usage code %d", code)
}
}
+357
View File
@@ -0,0 +1,357 @@
package app
import (
"context"
"encoding/json"
"log/slog"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/hub"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/incidents"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/rdns"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/server"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
// NodeDir is where the data of a probe lives: the primary probe uses the root
// of the data directory (exactly the 1.x layout), the others probes/<name>.
func NodeDir(dataDir, name string, primary bool) string {
if primary {
return dataDir
}
return filepath.Join(dataDir, "probes", name)
}
// shared holds what every node of the hub uses together.
type shared struct {
c Config
log *slog.Logger
en enricher
rd *rdns.Resolver
ctx context.Context
wg *sync.WaitGroup
mgr func() *hub.Manager
prim *Node
mu sync.Mutex
all []*Node
}
// Node is the store, the runner and the engines of one probe. It implements
// hub.Node and fed.Backend.
type Node struct {
name string
Dir string
Primary bool
St *store.Store
Run *Runner
Elog *evlog.Log
Inc *incidents.Store
Enf *enforce.Engine
Q *hub.CmdQueue
sh *shared
egr atomic.Pointer[egress.Engine]
egrSrc atomic.Pointer[egress.Source]
egrActive atomic.Bool
sources atomic.Pointer[[]string]
}
func (sh *shared) newNode(name string, primary bool, rec hub.Probe) (*Node, error) {
c := sh.c
dir := NodeDir(c.DataDir, name, primary)
if err := os.MkdirAll(dir, 0o700); err != nil {
return nil, err
}
loc, _ := store.ParseLocation(c.Location)
if !primary {
loc = nil
}
st := store.New(store.Config{Name: name, Version: Version, Retention: c.Retention, AdminUsers: c.AdminUserList(), Location: loc})
if rec.Location != nil {
st.SetLocation(&store.Location{Lat: rec.Location.Lat, Lon: rec.Location.Lon, Label: rec.Location.Label})
}
st.SetDomains(splitList(c.Domains))
n := &Node{name: name, Dir: dir, Primary: primary, St: st, sh: sh}
if max, err := ParseSize(orDefault(c.EventsMax, DefaultEventsMax)); err == nil && max > 0 {
el, err := evlog.Open(evlog.Options{Dir: filepath.Join(dir, "events"), MaxBytes: max, Retention: c.Retention, Log: sh.log})
if err != nil {
sh.log.Warn("event registry unavailable, replay disabled", "node", name, "err", err)
} else {
n.Elog = el
st.SetEventLog(el)
sh.wg.Add(1)
go func() { defer sh.wg.Done(); el.Run(sh.ctx) }()
}
}
st.SetRDNS(sh.rd)
offsets := LoadState(st, dir, sh.log)
run, err := NewRemoteRunner(c, st, sh.log, dir)
if err != nil {
return nil, err
}
run.Enr = sh.en
st.SetEnricher(sh.en)
st.SetAttribution(Attribution)
run.StartRemote(sh.ctx, offsets)
n.Run = run
run.EgressFeed = func(l []byte) {
if e := n.egr.Load(); e != nil {
e.Ingest(l)
}
}
if n.Inc, err = incidents.Open(filepath.Join(dir, "incidents.json"), sh.log); err != nil {
return nil, err
}
if n.Q, err = hub.OpenQueue(filepath.Join(dir, "commands.json")); err != nil {
return nil, err
}
n.Enf = newEnforce(c, st, name, dir, n.Q.Enqueue, sh.en, func() bool { return true })
if n.Enf != nil {
sh.wg.Add(1)
go func() { defer sh.wg.Done(); n.Enf.Run(sh.ctx) }()
}
if !egressOff(c) {
if err := n.buildEgress(rec.Egress); err != nil {
return nil, err
}
if strings.EqualFold(c.Egress, "on") {
n.activateEgress()
}
}
run.Extra = func() []store.SourceStatus {
out := []store.SourceStatus{}
if n.Primary {
out = append(out, geoStatus(sh.en.g, c.GeoDir))
}
return out
}
// save every minute, prune every 10
sh.wg.Add(1)
go n.maintain()
sh.mu.Lock()
sh.all = append(sh.all, n)
if primary {
sh.prim = n
}
sh.mu.Unlock()
return n, nil
}
func (n *Node) maintain() {
defer n.sh.wg.Done()
c := n.sh.c
_ = c
save := time.NewTicker(60 * time.Second)
prune := time.NewTicker(10 * time.Minute)
defer save.Stop()
defer prune.Stop()
for {
select {
case <-n.sh.ctx.Done():
n.Close()
return
case <-save.C:
if err := n.Run.Save(); err != nil {
n.sh.log.Warn("snapshot failed", "node", n.name, "err", err)
}
case <-prune.C:
if k := n.St.Prune(); k > 0 {
n.sh.log.Info("pruned old IPs", "node", n.name, "n", k)
}
}
}
}
// Close writes the final snapshot and flushes the queue and the tickets.
func (n *Node) Close() {
if err := n.Run.Save(); err != nil {
n.sh.log.Warn("final snapshot failed", "node", n.name, "err", err)
}
if n.Inc != nil {
n.Inc.Flush()
}
if n.Q != nil {
n.Q.Close()
}
}
func (n *Node) buildEgress(eg hub.Egress) error {
eng, err := newEgressEngine(n.sh.c, n.St, eg, n.Primary)
if err != nil {
return err
}
n.egr.Store(eng)
n.egrSrc.Store(egress.NewRemoteSource(eng, n.sh.log))
n.egrSrc.Load().SetState("waiting")
if n.egrActive.Load() && n.Primary {
server.SetEgress(eng)
}
return nil
}
func (n *Node) activateEgress() {
e := n.egr.Load()
if e == nil {
return
}
n.egrActive.Store(true)
if s := n.egrSrc.Load(); s != nil {
s.SetState("following")
}
if n.Primary {
server.SetEgress(e)
}
}
// Egress returns the engine when the node has egress analysis active.
func (n *Node) EgressEngine() *egress.Engine {
if !n.egrActive.Load() {
return nil
}
return n.egr.Load()
}
// ResetEgress rebuilds the engine with a new configuration (its in-memory
// history starts over).
func (n *Node) ResetEgress(eg hub.Egress) {
if egressOff(n.sh.c) {
return
}
if err := n.buildEgress(eg); err != nil {
n.sh.log.Warn("egress configuration rejected", "node", n.name, "err", err)
}
}
// ---- hub.Node ----
func (n *Node) Name() string { return n.name }
func (n *Node) Ready() bool { return true }
func (n *Node) Offsets() map[string]wire.Pos { return n.Run.RemoteOffsets() }
func (n *Node) Apply(b wire.Batch) (int, int) {
acc, dup := n.Run.ApplyBatch(b.Lines)
if acc > 0 {
for _, l := range b.Lines {
if l.Src == wire.SrcEgress {
n.activateEgress()
break
}
}
}
for _, f := range b.Files {
e := n.egr.Load()
if e == nil {
continue
}
switch f.Name {
case wire.FileContainers:
e.SetContainers([]byte(f.Data))
case wire.FileResolv:
e.SetResolv([]byte(f.Data))
}
}
return acc, dup
}
func (n *Node) Hello(h wire.Hello) {
n.sources.Store(&h.Sources)
for _, s := range h.Sources {
if s == wire.SrcEgress {
n.activateEgress()
}
}
}
func (n *Node) Queue() *hub.CmdQueue { return n.Q }
func (n *Node) SetStatus(st wire.Status, connected bool) { n.Run.SetRemoteStatus(st, connected) }
func (n *Node) SetLocation(l *wire.Location) {
if l == nil {
n.St.SetLocation(nil)
return
}
n.St.SetLocation(&store.Location{Lat: l.Lat, Lon: l.Lon, Label: l.Label})
}
// ---- fed.Backend ----
func (n *Node) connected() bool {
if m := n.sh.mgr(); m != nil {
return m.Connected(n.name)
}
return false
}
func (n *Node) Online() bool { return n.connected() }
func (n *Node) Location() *store.Location { return n.St.Location() }
func (n *Node) Export(rg store.Range) store.PeerExport { return n.St.ExportFor(rg) }
func (n *Node) Study(q store.PeriodQuery) store.PeerStudy { return n.St.StudyFor(q) }
func (n *Node) EgressReport(from, to int64) (egress.Report, bool) {
e := n.EgressEngine()
if e == nil {
return egress.Report{}, false
}
return e.Report(from, to), true
}
func (n *Node) Egress(from, to int64) json.RawMessage {
rep, ok := n.EgressReport(from, to)
if !ok {
return nil
}
b, _ := json.Marshal(rep)
return b
}
func (n *Node) Subscribe() (<-chan store.LiveEvent, func()) {
in, stop := n.St.Subscribe()
out := make(chan store.LiveEvent, 64)
done := make(chan struct{})
go func() {
for {
select {
case <-done:
return
case fe := <-in:
le := n.St.Live(fe)
select {
case out <- le:
default:
}
}
}
}()
return out, func() { close(done); stop() }
}
func (n *Node) SubscribeVisits() (<-chan store.VisitMsg, func()) { return n.St.SubscribeVisits() }
// HostInfo feeds fed.Hub.Hosts with the connection state of the probe.
func (n *Node) HostInfo() store.HostInfo {
hi := store.HostInfo{Name: n.name, Online: n.connected(), Live: n.connected(), Location: n.St.Location()}
if m := n.sh.mgr(); m != nil {
if in, ok := m.Info(n.name); ok {
hi.Version, hi.LastSeen, hi.LatencyMS = in.Version, in.LastSeen, in.LagMS
if !in.Connected && in.LastSeen > 0 {
hi.Error = "probe offline"
}
}
}
return hi
}
+166 -121
View File
@@ -17,65 +17,107 @@ import (
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/geo"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/hub"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/incidents"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/rdns"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/server"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
// Serve runs the daemon until SIGTERM/SIGINT; it returns nil on a clean stop.
func Serve(c Config) error {
log := slog.New(slog.NewTextHandler(os.Stderr, nil))
token, terr := Secret("URUTAU_TOKEN")
if terr != nil {
return terr
// acquireLock creates <data-dir>/.lock exclusively: its presence means "hub
// running" and makes `urutau import` refuse. It is removed on a normal stop.
func acquireLock(dir string) (release func(), err error) {
if err := os.MkdirAll(dir, 0o700); err != nil {
return nil, err
}
peers, err := c.Validate(token)
path := filepath.Join(dir, lockName)
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
if err != nil {
return err
if errors.Is(err, os.ErrExist) {
pid, _ := os.ReadFile(path)
return nil, fmt.Errorf("%s exists (pid %s): another hub uses this data directory; if none is running, remove the file", path, strings.TrimSpace(string(pid)))
}
return nil, err
}
if os.Getenv("GOMEMLIMIT") == "" {
debug.SetMemoryLimit(SoftMemoryLimit)
}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
defer stop()
fmt.Fprintf(f, "%d\n", os.Getpid())
f.Close()
return func() { os.Remove(path) }, nil
}
loc, _ := store.ParseLocation(c.Location) // validated above
st := store.New(store.Config{Name: c.Name, Version: Version, Retention: c.Retention, AdminUsers: c.AdminUserList(), Location: loc})
st.SetDomains(splitList(c.Domains))
// nodeSet implements server.NodeSet over the manager.
type nodeSet struct{ m *hub.Manager }
func (n nodeSet) node(host string) *Node {
nd, _ := n.m.Get(host).(*Node)
return nd
}
func (n nodeSet) Hosts() []string {
var out []string
for _, x := range n.m.Nodes() {
out = append(out, x.Name())
}
return out
}
func (n nodeSet) Enforce(h string) *enforce.Engine {
if nd := n.node(h); nd != nil {
return nd.Enf
}
return nil
}
func (n nodeSet) Egress(h string) *egress.Engine {
if nd := n.node(h); nd != nil {
return nd.EgressEngine()
}
return nil
}
func (n nodeSet) Incidents(h string) *incidents.Store {
if nd := n.node(h); nd != nil {
return nd.Inc
}
return nil
}
// Hub is a running hub without its listener: Serve and the tests build one.
type Hub struct {
Handler http.Handler
Mgr *hub.Manager
Primary *Node
Fed *fed.Hub
wg *sync.WaitGroup
}
// Wait blocks until every background goroutine stopped (cancel the context
// first); the nodes then have saved their snapshots.
func (h *Hub) Wait() {
h.wg.Wait()
h.Mgr.Close()
}
// NewHub validates c and starts the nodes and the background work until ctx is done.
func NewHub(ctx context.Context, c Config, token string, log *slog.Logger) (*Hub, error) {
if err := c.Validate(token); err != nil {
return nil, err
}
wg := &sync.WaitGroup{}
watchTorExits(ctx, c.TorExits, 24*time.Hour, log)
if !strings.EqualFold(c.TorAuto, "off") {
watchTorLists(ctx, filepath.Join(c.DataDir, "tor"), torExitURL, torRelayURL, 6*time.Hour, log)
}
var elog *evlog.Log
if max, err := ParseSize(orDefault(c.EventsMax, DefaultEventsMax)); err == nil && max > 0 {
if elog, err = evlog.Open(evlog.Options{Dir: filepath.Join(c.DataDir, "events"), MaxBytes: max, Retention: c.Retention, Log: log}); err != nil {
log.Warn("event registry unavailable, replay disabled", "err", err)
elog = nil
} else {
st.SetEventLog(elog)
}
}
rd := rdns.New()
st.SetRDNS(rd)
offsets := LoadState(st, c.DataDir, log)
runner, err := NewRunner(c, st, log)
if err != nil {
return err
}
gr, gerr := geo.Open(c.GeoDir)
if gerr != nil {
log.Warn("geo databases unavailable, locations disabled until they are downloaded", "dir", c.GeoDir, "err", gerr)
gr = nil
}
en := enricher{g: gr}
runner.Enr = en
st.SetEnricher(en)
st.SetAttribution(Attribution)
runner.Extra = func() []store.SourceStatus { return []store.SourceStatus{geoStatus(gr, c.GeoDir)} }
// Real build dates of the geo databases for /api/v1/integrity (0 = unknown).
store.GeoBuilds = func() (int64, int64) {
if gr == nil {
@@ -91,102 +133,109 @@ func Serve(c Config) error {
}
return city, asn
}
var hub *fed.Hub
if len(peers) > 0 {
hub = fed.NewHub(peers, c.PeerToken)
hub.OnLive = st.RecordPeerEvent
var mgr *hub.Manager
sh := &shared{c: c, log: log, en: en, rd: rd, ctx: ctx, wg: wg, mgr: func() *hub.Manager { return mgr }}
mgr, err := hub.NewManager(c.DataDir, c.Name, Version, func(name string, primary bool, rec hub.Probe) (hub.Node, error) {
return sh.newNode(name, primary, rec)
}, log)
if err != nil {
return nil, err
}
allow, _ := core.ParseCIDRs(c.PeerAllow)
if err := mgr.Load(); err != nil {
return nil, err
}
prim, _ := mgr.Get(c.Name).(*Node)
if prim == nil {
return nil, fmt.Errorf("primary node %q was not created", c.Name)
}
if prim.Enf != nil {
server.SetEnforce(prim.Enf)
}
fh := fed.NewHub(func() []fed.Backend {
var out []fed.Backend
for _, n := range mgr.Nodes() {
if nd, ok := n.(*Node); ok && !nd.Primary {
out = append(out, nd)
}
}
return out
})
tproxy, _ := core.ParseCIDRs(c.TrustedProxy)
ign, _ := core.ParseCIDRs(c.Ignore + "," + c.Trusted)
bindHost, _, _ := net.SplitHostPort(c.Bind)
incStore, err := incidents.Open(filepath.Join(c.DataDir, "incidents.json"), log)
if err != nil {
return err
}
h := server.New(server.Options{Token: token, PeerTokens: c.PeerTokens, PeerAllow: allow, TrustedProxy: tproxy, Ignore: ign,
AllowHosts: []string{bindHost}, NoAuth: c.NoAuth, LocalBlocklist: strings.EqualFold(c.PeerBlocklist, "off"), Version: Version, Store: st, Hub: hub,
Incidents: incStore})
egressSrc, err := newEgress(c, st, log)
if err != nil {
return err
}
if egressSrc != nil {
extra := runner.Extra
runner.Extra = func() []store.SourceStatus { return append(extra(), egressSrc.Status()) }
}
eng := newEnforce(c, st, peers, en, func() bool {
for _, s := range runner.Sources {
if s.backfilling.Load() {
return false
}
}
return true
})
if eng != nil {
server.SetEnforce(eng)
}
ln, err := net.Listen("tcp", c.Bind)
if err != nil {
return err
}
srv := server.HTTPServer(h, ctx)
var wg sync.WaitGroup
if elog != nil {
wg.Add(1)
go func() { defer wg.Done(); elog.Run(ctx) }()
}
runner.Start(ctx, offsets, &wg)
server.StartIncidentSync(ctx, &wg)
if egressSrc != nil {
egressSrc.Start(ctx, &wg)
}
h := server.New(server.Options{Token: token, TrustedProxy: tproxy, Ignore: ign,
AllowHosts: []string{bindHost}, NoAuth: c.NoAuth, LocalBlocklist: strings.EqualFold(c.PeerBlocklist, "off"), Version: Version, Store: prim.St, Hub: fh,
Incidents: prim.Inc, Probes: mgr, Nodes: nodeSet{mgr}})
server.StartIncidentSync(ctx, wg)
wg.Add(2)
go func() { defer wg.Done(); rd.Run(ctx) }()
go func() {
defer wg.Done()
save := time.NewTicker(60 * time.Second)
prune := time.NewTicker(10 * time.Minute)
defer save.Stop()
defer prune.Stop()
for {
select {
case <-ctx.Done():
return
case <-save.C:
if err := runner.Save(); err != nil {
log.Warn("snapshot failed", "err", err)
}
case <-prune.C:
if n := st.Prune(); n > 0 {
log.Info("pruned old IPs", "n", n)
}
}
}
}()
go func() { defer wg.Done(); fh.Run(ctx) }()
if gr != nil && c.GeoUpdate > 0 {
gr.StartUpdater(ctx, c.GeoUpdate, &http.Client{Timeout: 10 * time.Minute})
}
if hub != nil {
if strings.EqualFold(c.EnforceShare, "on") {
wg.Add(1)
go func() { defer wg.Done(); hub.Run(ctx) }()
go func() {
defer wg.Done()
shareDecisions(ctx, func() []*Node {
var out []*Node
for _, n := range mgr.Nodes() {
if nd, ok := n.(*Node); ok {
out = append(out, nd)
}
}
return out
})
}()
}
if eng != nil {
wg.Add(1)
go func() { defer wg.Done(); eng.Run(ctx) }()
if hub != nil && eng.Share() {
wg.Add(1)
go func() { defer wg.Done(); shareDecisions(ctx, hub, eng, log) }()
}
return &Hub{Handler: h, Mgr: mgr, Primary: prim, Fed: fh, wg: wg}, nil
}
// Serve runs the daemon until SIGTERM/SIGINT; it returns nil on a clean stop.
func Serve(c Config) error {
log := slog.New(slog.NewTextHandler(os.Stderr, nil))
warn, err := CheckRemovedEnv(os.LookupEnv)
if err != nil {
return err
}
log.Info("urutau started", "version", Version, "name", c.Name, "bind", ln.Addr().String(), "peers", len(peers), "auth", !c.NoAuth)
for _, k := range warn {
log.Warn("variable of the 1.x image ignored: the log paths belong to the probe now", "var", k)
}
token, terr := Secret("URUTAU_TOKEN")
if terr != nil {
return terr
}
if err := c.Validate(token); err != nil {
return err
}
if os.Getenv("GOMEMLIMIT") == "" {
debug.SetMemoryLimit(SoftMemoryLimit)
}
release, err := acquireLock(c.DataDir)
if err != nil {
return err
}
defer release()
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
defer stop()
hb, err := NewHub(ctx, c, token, log)
if err != nil {
return err
}
ln, err := net.Listen("tcp", c.Bind)
if err != nil {
stop()
hb.Wait()
return err
}
srv := server.HTTPServer(hb.Handler, ctx)
log.Info("urutau started", "version", Version, "name", c.Name, "bind", ln.Addr().String(), "probes", len(hb.Mgr.Nodes()), "auth", !c.NoAuth)
errc := make(chan error, 1)
go func() { errc <- srv.Serve(ln) }()
select {
case err := <-errc:
stop()
wg.Wait()
hb.Wait()
return err
case <-ctx.Done():
}
@@ -194,12 +243,8 @@ func Serve(c Config) error {
sctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = srv.Shutdown(sctx)
wg.Wait()
if err := runner.Save(); err != nil {
log.Warn("final snapshot failed", "err", err)
} else {
log.Info("snapshot saved")
}
hb.Wait() // every node saves its snapshot and flushes its tickets
log.Info("snapshot saved")
if err := <-errc; err != nil && !errors.Is(err, http.ErrServerClosed) {
return fmt.Errorf("server: %w", err)
}
+162 -3
View File
@@ -14,6 +14,7 @@ import (
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/tail"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
const maxLine = 64 * 1024
@@ -112,8 +113,16 @@ type Runner struct {
Sources []*source
DataDir string
Log *slog.Logger
// EgressFeed receives the "egress" lines of a probe (nil: they are only counted).
EgressFeed func(line []byte)
mu sync.Mutex // commit mutex: held while a line is applied and by snapshots
remote map[string]store.Offset // hub-committed offsets of the sources fed by a probe
isRemote bool
rstatus atomic.Pointer[wire.Status]
connected atomic.Bool
egLines atomic.Uint64
}
// NewRunner builds the runner for the enabled sources.
@@ -143,10 +152,157 @@ func NewRunner(c Config, st *store.Store, log *slog.Logger) (*Runner, error) {
return r, nil
}
func (r *Runner) statuses() []store.SourceStatus {
out := make([]store.SourceStatus, 0, len(r.Sources))
// NewRemoteRunner builds the runner of a node whose sources are fed by a probe
// through Feed: the four parsed sources exist, none follows a file.
func NewRemoteRunner(c Config, st *store.Store, log *slog.Logger, dataDir string) (*Runner, error) {
c.TraefikLog, c.AuthLog, c.Fail2banLog, c.ProbeLog = "", "", "", ""
r, err := NewRunner(c, st, log)
if err != nil {
return nil, err
}
r.DataDir, r.isRemote, r.remote = dataDir, true, map[string]store.Offset{}
for _, name := range []string{"traefik", "ssh", "fail2ban", "probe"} {
parse := map[string]func([]byte) (core.Event, error){"traefik": traefikParse, "ssh": authParse, "fail2ban": f2bParse, "probe": newProbeParser().parse}[name]
r.Sources = append(r.Sources, &source{name: name, parse: parse})
}
return r, nil
}
// runnerSource maps a wire source name to the runner's (and snapshot's) name.
func runnerSource(src string) string {
if src == wire.SrcAuth {
return "ssh"
}
return src
}
// wireSource is the inverse of runnerSource.
func wireSource(name string) string {
if name == "ssh" {
return wire.SrcAuth
}
return name
}
func (r *Runner) find(name string) *source {
for _, s := range r.Sources {
out = append(out, s.status())
if s.name == name {
return s
}
}
return nil
}
// StartRemote sets the committed offsets of a probe-fed runner (from the
// snapshot); there are no followers to start.
func (r *Runner) StartRemote(ctx context.Context, offsets map[string]store.Offset) {
r.mu.Lock()
defer r.mu.Unlock()
for k, v := range offsets {
r.remote[k] = v
}
}
// RemoteOffsets returns the committed positions keyed by wire source name.
func (r *Runner) RemoteOffsets() map[string]wire.Pos {
r.mu.Lock()
defer r.mu.Unlock()
out := map[string]wire.Pos{}
for k, v := range r.remote {
out[wireSource(k)] = wire.Pos{Inode: v.Inode, Offset: v.Offset, FP: v.FP, FPLen: v.FPLen}
}
return out
}
// Feed applies one line of a probe (src is a wire source name): it is dropped
// when its end position is not past the committed one in the same file, else
// handled and committed. It reports whether the line was new.
func (r *Runner) Feed(src string, text []byte, end store.Offset) bool {
r.mu.Lock()
defer r.mu.Unlock()
return r.feedLocked(src, text, end)
}
func (r *Runner) feedLocked(src string, text []byte, end store.Offset) bool {
name := runnerSource(src)
if saved, ok := r.remote[name]; ok && end.Inode == saved.Inode && end.Offset <= saved.Offset {
return false
}
if src == wire.SrcEgress {
r.egLines.Add(1)
if r.EgressFeed != nil {
func() {
defer func() { recover() }() // one hostile line must never take the node down
r.EgressFeed(text)
}()
}
} else if s := r.find(name); s != nil {
r.handle(s)(text)
}
r.remote[name] = end
return true
}
// ApplyBatch applies the lines of a batch under the commit mutex.
func (r *Runner) ApplyBatch(lines []wire.Line) (accepted, dup int) {
r.mu.Lock()
defer r.mu.Unlock()
for _, l := range lines {
if r.feedLocked(l.Src, []byte(l.Text), store.Offset{Inode: l.End.Inode, Offset: l.End.Offset, FP: l.End.FP, FPLen: l.End.FPLen}) {
accepted++
} else {
dup++
}
}
return accepted, dup
}
// SetRemoteStatus stores the last status reported by the probe.
func (r *Runner) SetRemoteStatus(st wire.Status, connected bool) {
r.rstatus.Store(&st)
r.connected.Store(connected)
}
func (r *Runner) remoteStatuses() []store.SourceStatus {
ws := r.rstatus.Load()
var out []store.SourceStatus
seen := map[string]bool{}
if ws != nil {
for _, w := range ws.Sources {
name := runnerSource(w.Src)
seen[name] = true
row := store.SourceStatus{Name: name, State: w.State, Error: w.Error, Lines: w.Lines, Malformed: w.Oversize, LastEvent: w.LastLine}
if s := r.find(name); s != nil {
row.Lines, row.Malformed = max(row.Lines, s.lines.Load()), max(w.Oversize, s.malformed.Load())
if row.LastEvent == 0 {
row.LastEvent = s.lastEvent.Load()
}
if row.State == "following" && s.win.degraded() {
row.State, row.Error = "degraded", degradedMsg
}
}
out = append(out, row)
}
}
for _, s := range r.Sources { // sources the probe has not reported
if !seen[s.name] {
if ws == nil {
out = append(out, store.SourceStatus{Name: s.name, State: "waiting", Lines: s.lines.Load(), Malformed: s.malformed.Load(), LastEvent: s.lastEvent.Load()})
}
}
}
return out
}
func (r *Runner) statuses() []store.SourceStatus {
var out []store.SourceStatus
if r.isRemote {
out = r.remoteStatuses()
} else {
out = make([]store.SourceStatus, 0, len(r.Sources))
for _, s := range r.Sources {
out = append(out, s.status())
}
}
if r.Extra != nil {
out = append(out, r.Extra()...)
@@ -297,6 +453,9 @@ func (r *Runner) Save() error {
r.mu.Lock()
defer r.mu.Unlock()
offs := map[string]store.Offset{}
for k, v := range r.remote {
offs[k] = v
}
for _, s := range r.Sources {
if f := s.fol.Load(); f != nil {
p := f.Pos()
+11
View File
@@ -0,0 +1,11 @@
{
"events": 17,
"event_files": 3,
"ips": 4,
"offsets": 3,
"incidents": 3,
"comments": 2,
"suppressed": 1,
"enforce_bans": 2,
"enforce_allow": 0
}
+1
View File
@@ -0,0 +1 @@
{"v":1,"bans":{"203.0.114.7":{"until":1794794051,"offences":1,"last":1794790451},"203.0.114.8":{"until":1794794051,"offences":1,"last":1794790451}}}
@@ -0,0 +1,2 @@
{"t":1794466451,"ip":"192.0.2.99","cat":"scanner","source":"traefik","host":"hostinger","domain":"a.example","method":"GET","path":"/wp-login.php","status":404,"ua":"fixture","id":16,"fam":"wordpress","tech":["T1110.001","T1595"],"marker":"/wp-login.php"}
{"t":1794466452,"ip":"192.0.2.99","cat":"scanner","source":"traefik","host":"hostinger","domain":"a.example","method":"GET","path":"/wp-login.php","status":404,"ua":"fixture","id":17,"fam":"wordpress","tech":["T1110.001","T1595"],"marker":"/wp-login.php"}
@@ -0,0 +1,5 @@
{"t":1794610451,"ip":"198.51.101.20","cat":"ssh-fail","source":"ssh","host":"hostinger","domain":"a.example","method":"GET","user":"root","ua":"fixture","id":11,"tech":["T1110.001"]}
{"t":1794610452,"ip":"198.51.101.20","cat":"ssh-fail","source":"ssh","host":"hostinger","domain":"a.example","method":"GET","user":"root","ua":"fixture","id":12,"tech":["T1110.001"]}
{"t":1794610453,"ip":"198.51.101.20","cat":"ssh-fail","source":"ssh","host":"hostinger","domain":"a.example","method":"GET","user":"root","ua":"fixture","id":13,"tech":["T1110.001"]}
{"t":1794610454,"ip":"198.51.101.20","cat":"ssh-fail","source":"ssh","host":"hostinger","domain":"a.example","method":"GET","user":"root","ua":"fixture","id":14,"tech":["T1110.001"]}
{"t":1794610455,"ip":"198.51.101.20","cat":"ssh-fail","source":"ssh","host":"hostinger","domain":"a.example","method":"GET","user":"root","ua":"fixture","id":15,"tech":["T1110.001"]}
@@ -0,0 +1,10 @@
{"t":1794779651,"ip":"203.0.114.7","cat":"scanner","source":"traefik","host":"hostinger","domain":"a.example","method":"GET","path":"/.env","status":404,"ua":"fixture","id":1,"fam":"env-credentials","tech":["T1552.001","T1595"],"marker":"/.env"}
{"t":1794779652,"ip":"203.0.114.7","cat":"scanner","source":"traefik","host":"hostinger","domain":"a.example","method":"GET","path":"/.env","status":404,"ua":"fixture","id":2,"fam":"env-credentials","tech":["T1552.001","T1595"],"marker":"/.env"}
{"t":1794779653,"ip":"203.0.114.7","cat":"scanner","source":"traefik","host":"hostinger","domain":"a.example","method":"GET","path":"/.env","status":404,"ua":"fixture","id":3,"fam":"env-credentials","tech":["T1552.001","T1595"],"marker":"/.env"}
{"t":1794779654,"ip":"203.0.114.7","cat":"scanner","source":"traefik","host":"hostinger","domain":"a.example","method":"GET","path":"/.env","status":404,"ua":"fixture","id":4,"fam":"env-credentials","tech":["T1552.001","T1595"],"marker":"/.env"}
{"t":1794779655,"ip":"203.0.114.7","cat":"scanner","source":"traefik","host":"hostinger","domain":"a.example","method":"GET","path":"/.env","status":404,"ua":"fixture","id":5,"fam":"env-credentials","tech":["T1552.001","T1595"],"marker":"/.env"}
{"t":1794779656,"ip":"203.0.114.7","cat":"scanner","source":"traefik","host":"hostinger","domain":"a.example","method":"GET","path":"/.env","status":404,"ua":"fixture","id":6,"fam":"env-credentials","tech":["T1552.001","T1595"],"marker":"/.env"}
{"t":1794783251,"ip":"203.0.114.8","cat":"exploit","source":"traefik","host":"hostinger","domain":"a.example","method":"GET","path":"/cgi-bin/../../etc/passwd","status":400,"ua":"fixture","id":7,"fam":"traversal","tech":["T1083","T1190"],"marker":"../"}
{"t":1794783252,"ip":"203.0.114.8","cat":"exploit","source":"traefik","host":"hostinger","domain":"a.example","method":"GET","path":"/cgi-bin/../../etc/passwd","status":400,"ua":"fixture","id":8,"fam":"traversal","tech":["T1083","T1190"],"marker":"../"}
{"t":1794783253,"ip":"203.0.114.8","cat":"exploit","source":"traefik","host":"hostinger","domain":"a.example","method":"GET","path":"/cgi-bin/../../etc/passwd","status":400,"ua":"fixture","id":9,"fam":"traversal","tech":["T1083","T1190"],"marker":"../"}
{"t":1794783254,"ip":"203.0.114.8","cat":"exploit","source":"traefik","host":"hostinger","domain":"a.example","method":"GET","path":"/cgi-bin/../../etc/passwd","status":400,"ua":"fixture","id":10,"fam":"traversal","tech":["T1083","T1190"],"marker":"../"}
@@ -0,0 +1 @@
not a real database
+1
View File
@@ -0,0 +1 @@
{"next":4,"tickets":[{"id":"INC-1","key":"7d824cc0ddaef8d29ea98a1aa71a3c644a7af995db3500cb7b0e2fbbb1f342d4","source":"egress","host":"hostinger","kind":"new-destination","severity":"medium","max_severity":"medium","workload":"app-a","dst":"198.51.100.5","dport":443,"proto":"tcp","title":"new-destination app-a -\u003e 198.51.100.5:443/tcp","detail":"first contact","first_seen":1794617651,"last_seen":1794786851,"count":12,"status":"false_positive","verdict":"","assignee":"","tags":[],"suppress":true,"created_at":1794790451,"updated_at":1794790451,"suppressed_sev":"medium","suppressed_at":1794790451,"suppress_until":1797382451,"severity_manual":false,"comments":[],"history":[{"at":1794790451,"author":"urutau","field":"created","from":"","to":"medium"},{"at":1794790451,"author":"lucas","field":"status","from":"open","to":"false_positive"},{"at":1794790451,"author":"lucas","field":"suppress","from":"false","to":"true"}]},{"id":"INC-2","key":"77f910eb3c3c828f18e7683a1828419903f282d7a8a6584f4a48092c6b49190e","source":"egress","host":"hostinger","kind":"exfil","severity":"high","max_severity":"high","workload":"app-b","dst":"203.0.113.50","dport":4444,"proto":"tcp","title":"exfil app-b -\u003e 203.0.113.50:4444/tcp","detail":"large upload","first_seen":1794704051,"last_seen":1794786851,"count":40,"status":"open","verdict":"","assignee":"","tags":[],"suppress":false,"created_at":1794790451,"updated_at":1794790451,"suppressed_sev":"","suppressed_at":0,"suppress_until":0,"severity_manual":false,"comments":[{"id":1,"at":1794790451,"author":"lucas","text":"Looks like the nightly backup."},{"id":2,"at":1794790451,"author":"lucas","text":"Confirmed with the app owner; keep watching."}],"history":[{"at":1794790451,"author":"urutau","field":"created","from":"","to":"high"}]},{"id":"INC-3","key":"manual|3","source":"manual","host":"hostinger","kind":"manual","severity":"low","max_severity":"low","workload":"","dst":"","dport":0,"proto":"","title":"Manual review of the proxy","detail":"opened by the operator","first_seen":1794790451,"last_seen":1794790451,"count":1,"status":"open","verdict":"","assignee":"","tags":[],"suppress":false,"created_at":1794790451,"updated_at":1794790451,"suppressed_sev":"","suppressed_at":0,"suppress_until":0,"severity_manual":false,"comments":[],"history":[{"at":1794790451,"author":"lucas","field":"created","from":"","to":"low"}]}]}
@@ -0,0 +1 @@
unknown file kept verbatim
@@ -0,0 +1,2 @@
198.51.100.200
198.51.100.201
+1
View File
@@ -0,0 +1 @@
{"relays":[]}
Binary file not shown.
+1 -1
View File
@@ -97,7 +97,7 @@ func TestEgressOwnAllowAndProvider(t *testing.T) {
}
// the peer has no URUTAU_PEERS: URUTAU_TRUSTED carries both servers, and a
// bad item does not discard the others
al := egressAllow(Config{Trusted: "136.248.78.83,lixo,195.200.0.252/32"})
al := egressAllow(Config{Trusted: "136.248.78.83,lixo,195.200.0.252/32"}, "")
for _, ipS := range []string{"136.248.78.83", "195.200.0.252"} {
ok := false
for _, p := range al {
+3 -3
View File
@@ -21,15 +21,15 @@ func TestRetentionEventsMaxFlags(t *testing.T) {
}
tok := "tok-0123456789-abcdefghijklmnopqrstuvwxyz-QWERTY"
base := Config{Bind: "0.0.0.0:1", Ignore: DefaultIgnore, TrustedProxy: DefaultTrustedProxy, Retention: 720 * time.Hour}
if _, err := base.Validate(tok); err != nil {
if err := base.Validate(tok); err != nil {
t.Fatal(err)
}
base.Retention = 721 * time.Hour
if _, err := base.Validate(tok); err == nil {
if err := base.Validate(tok); err == nil {
t.Fatal("retention over 720h must be refused")
}
base.Retention, base.EventsMax = 720*time.Hour, "lots"
if _, err := base.Validate(tok); err == nil {
if err := base.Validate(tok); err == nil {
t.Fatal("bad --events-max must be refused")
}
for in, want := range map[string]int64{"512MB": 512 << 20, "0": 0, "2g": 2 << 30, "1048576": 1 << 20, "1.5kb": 1536} {
+2 -51
View File
@@ -8,7 +8,6 @@ import (
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
@@ -199,7 +198,7 @@ func TestIPDetailConsistentOnSyntheticLogs(t *testing.T) {
func TestEnforceConfig(t *testing.T) {
c, err := ParseFlags("x", []string{"--insecure-no-auth", "--bind", "127.0.0.1:1"})
if err != nil || c.Enforce != "off" || c.EnforceLog != "/logs/enforce/decisions.log" || c.EnforceShare != "off" || c.EnforceThreshold != 5 || c.EnforceMaxPerMin != 60 {
if err != nil || c.Enforce != "off" || c.EnforceShare != "off" || c.EnforceThreshold != 5 || c.EnforceMaxPerMin != 60 {
t.Fatalf("%+v %v", c, err)
}
for _, bad := range [][]string{{"--enforce=maybe"}, {"--enforce-share=x"}, {"--enforce-threshold=0"}, {"--enforce-max-per-min=0"}} {
@@ -207,7 +206,7 @@ func TestEnforceConfig(t *testing.T) {
if err != nil {
continue
}
if _, err := c.Validate(""); err == nil {
if err := c.Validate(""); err == nil {
t.Errorf("%v accepted", bad)
}
}
@@ -219,45 +218,6 @@ func TestEnforceConfig(t *testing.T) {
}
}
func TestDoctorEnforce(t *testing.T) {
var got []Check
add := func(n, s, d string) { got = append(got, Check{n, s, d}) }
doctorEnforce(Config{Enforce: "on", EnforceLog: t.TempDir() + "/x/d.log", EnforceThreshold: 5}, add)
doctorEnforce(Config{Enforce: "on", EnforceLog: "/proc/nope/d.log"}, add)
doctorEnforce(Config{Enforce: "off"}, add)
if got[0].Status != "ok" || !strings.Contains(got[0].Detail, "mode=on") || got[1].Status != "fail" || got[2].Status != "off" {
t.Fatalf("%+v", got)
}
}
func TestDoctorEnforceCloudflare(t *testing.T) {
lg := filepath.Join(t.TempDir(), "access.log")
os.WriteFile(lg, []byte(`{"ClientHost":"104.16.1.1"}`+"\n"+`{"ClientHost":"203.0.114.5"}`+"\n"), 0o600)
var got []Check
add := func(n, s, d string) { got = append(got, Check{n, s, d}) }
doctorEnforce(Config{Enforce: "on", EnforceLog: t.TempDir() + "/x/d.log", TraefikLog: lg}, add)
if len(got) != 2 || got[1].Name != "enforce-cdn" || got[1].Status != "warn" {
t.Fatalf("%+v", got)
}
got = nil
doctorEnforce(Config{Enforce: "observe", EnforceLog: t.TempDir() + "/x/d.log", TraefikLog: lg}, add)
if len(got) != 1 {
t.Fatalf("%+v", got)
}
}
func TestEgressExtraAllow(t *testing.T) {
t.Setenv("URUTAU_EGRESS_ALLOW", "203.0.113.0/24, 198.51.100.7 ,bad")
got := egressExtraAllow(Config{Peers: []string{"p=https://192.0.2.9:8443"}})
var s []string
for _, p := range got {
s = append(s, p.String())
}
if strings.Join(s, " ") != "192.0.2.9/32 203.0.113.0/24 198.51.100.7/32" {
t.Fatalf("%v", s)
}
}
func TestSourceDegradedWindow(t *testing.T) {
var w window
for i := 0; i < 100; i++ {
@@ -279,12 +239,3 @@ func TestSourceDegradedWindow(t *testing.T) {
t.Fatal("window must recover")
}
}
func TestUnbanLogPathDefault(t *testing.T) {
if got := unbanLogPath(Config{EnforceLog: "/logs/enforce/decisions.log"}); got != "/logs/enforce/unban.log" {
t.Fatalf("default unban log = %q", got)
}
if got := unbanLogPath(Config{EnforceLog: "/a/d.log", EnforceUnbanLog: "/b/u.log"}); got != "/b/u.log" {
t.Fatalf("explicit unban log = %q", got)
}
}
+1 -1
View File
@@ -2,4 +2,4 @@ package app
// Version is the release version (SemVer). Release builds may override it with
// -ldflags "-X .../internal/app.Version=...".
var Version = "1.6.0"
var Version = "2.0.0"