feat!: Urutau 2.0.0, ultralight probes and a single analysis hub
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:
1 parent
23a7a5963a
commit
8546d14cef
130 files changed
+9396
-3311
No files matched your search
+41
-95
@@ -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
@@ -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
|
||||
|
||||
@@ -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
@@ -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
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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
@@ -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()
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -0,0 +1 @@
|
||||
{"relays":[]}
|
||||
Binary file not shown.
@@ -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 {
|
||||
|
||||
@@ -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
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
@@ -90,7 +90,7 @@ func TestParse(t *testing.T) {
|
||||
|
||||
func TestWorkloadsAndContainers(t *testing.T) {
|
||||
e := newEng(t, Config{Workloads: "ciberlab=name:jhxint9g9uz91:scanner;mail=10.0.7.0/24,10.0.8.4/32:mail;lab=10.0.5.0/24"})
|
||||
e.SetContainers(map[netip.Addr]string{ip("172.18.0.4"): "jhxint9g9uz91-20260101123456", ip("172.18.0.9"): "runner-q620o15zg7-1700000000000"})
|
||||
e.SetContainerMap(map[netip.Addr]string{ip("172.18.0.4"): "jhxint9g9uz91-20260101123456", ip("172.18.0.9"): "runner-q620o15zg7-1700000000000"})
|
||||
cases := []struct {
|
||||
ev Event
|
||||
name, role string
|
||||
@@ -108,7 +108,7 @@ func TestWorkloadsAndContainers(t *testing.T) {
|
||||
}
|
||||
}
|
||||
// IP changes: the map in force at Ingest wins
|
||||
e.SetContainers(map[netip.Addr]string{ip("172.18.0.5"): "jhxint9g9uz91-20260102000000"})
|
||||
e.SetContainerMap(map[netip.Addr]string{ip("172.18.0.5"): "jhxint9g9uz91-20260102000000"})
|
||||
if n, _ := e.resolve(mk(t0, "172.18.0.5", "1.1.1.1", "tcp", 1)); n != "ciberlab" {
|
||||
t.Errorf("remap: %s", n)
|
||||
}
|
||||
@@ -460,7 +460,7 @@ func TestReportByCountry(t *testing.T) {
|
||||
|
||||
func TestNameMatchExactAndPrefix(t *testing.T) {
|
||||
e := newEng(t, Config{Workloads: "a=name:web:default;b=name:api*:default;c=name:pay:default"})
|
||||
e.SetContainers(map[netip.Addr]string{ip("172.18.0.1"): "web-1700000000000", ip("172.18.0.2"): "webshell-1700000000000",
|
||||
e.SetContainerMap(map[netip.Addr]string{ip("172.18.0.1"): "web-1700000000000", ip("172.18.0.2"): "webshell-1700000000000",
|
||||
ip("172.18.0.3"): "apigw-17", ip("172.18.0.4"): "pay", ip("172.18.0.5"): "payroll"})
|
||||
for src, want := range map[string]string{"172.18.0.1": "a", "172.18.0.2": "webshell", "172.18.0.3": "b", "172.18.0.4": "c", "172.18.0.5": "payroll"} {
|
||||
if n, _ := e.resolve(mk(t0, src, "1.1.1.1", "tcp", 1)); n != want {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package egress
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"container/list"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -276,8 +277,12 @@ func readNameservers(path string) []netip.Addr {
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return parseNameservers(string(b))
|
||||
}
|
||||
|
||||
func parseNameservers(text string) []netip.Addr {
|
||||
var out []netip.Addr
|
||||
for _, ln := range strings.Split(string(b), "\n") {
|
||||
for _, ln := range strings.Split(text, "\n") {
|
||||
f := strings.Fields(ln)
|
||||
if len(f) >= 2 && f[0] == "nameserver" {
|
||||
if a, err := netip.ParseAddr(f[1]); err == nil {
|
||||
@@ -328,13 +333,31 @@ func (e *Engine) fanPromote(pk pairKey, t int64) *pairState {
|
||||
return p
|
||||
}
|
||||
|
||||
// SetContainers replaces the address to container-name map (tests, wiring).
|
||||
func (e *Engine) SetContainers(m map[netip.Addr]string) {
|
||||
// SetContainerMap replaces the address to container-name map (tests, wiring).
|
||||
func (e *Engine) SetContainerMap(m map[netip.Addr]string) {
|
||||
e.mu.Lock()
|
||||
e.containers = m
|
||||
e.mu.Unlock()
|
||||
}
|
||||
|
||||
// SetContainers replaces the container map with the content of a
|
||||
// containers.map file sent by a probe ("<ip> <name>" per line).
|
||||
func (e *Engine) SetContainers(data []byte) {
|
||||
m, _ := parseContainers(bytes.NewReader(data))
|
||||
e.SetContainerMap(m)
|
||||
}
|
||||
|
||||
// SetResolv adds the nameservers of a resolv.conf sent by a probe to the
|
||||
// allowed resolvers (those of the configuration stay).
|
||||
func (e *Engine) SetResolv(data []byte) {
|
||||
ns := parseNameservers(string(data))
|
||||
e.mu.Lock()
|
||||
for _, a := range ns {
|
||||
e.resolvers[a] = true
|
||||
}
|
||||
e.mu.Unlock()
|
||||
}
|
||||
|
||||
func (e *Engine) reloadMap() {
|
||||
if e.cfg.Containers == "" {
|
||||
return
|
||||
|
||||
@@ -23,8 +23,24 @@ type Source struct {
|
||||
Log *slog.Logger
|
||||
backfilling atomic.Bool
|
||||
fol atomic.Pointer[tail.Follower]
|
||||
remote bool
|
||||
rstate atomic.Pointer[string]
|
||||
}
|
||||
|
||||
// NewRemoteSource creates a source fed by a probe through Feed: there is no
|
||||
// file and nothing to start.
|
||||
func NewRemoteSource(e *Engine, log *slog.Logger) *Source {
|
||||
s := NewSource("", e, log)
|
||||
s.remote = true
|
||||
return s
|
||||
}
|
||||
|
||||
// Feed analyses one line received from a probe.
|
||||
func (s *Source) Feed(line []byte) { s.E.Ingest(line) }
|
||||
|
||||
// SetState sets the state shown for a remote source (following, waiting, error).
|
||||
func (s *Source) SetState(st string) { s.rstate.Store(&st) }
|
||||
|
||||
// NewSource creates the source of e reading path.
|
||||
func NewSource(path string, e *Engine, log *slog.Logger) *Source {
|
||||
if log == nil {
|
||||
@@ -37,6 +53,12 @@ func NewSource(path string, e *Engine, log *slog.Logger) *Source {
|
||||
}
|
||||
|
||||
func (s *Source) state() string {
|
||||
if s.remote {
|
||||
if p := s.rstate.Load(); p != nil {
|
||||
return *p
|
||||
}
|
||||
return "waiting"
|
||||
}
|
||||
switch f := s.fol.Load(); {
|
||||
case s.backfilling.Load():
|
||||
return "backfill"
|
||||
|
||||
@@ -3,6 +3,7 @@ package egress
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/netip"
|
||||
"os"
|
||||
"regexp"
|
||||
@@ -106,8 +107,13 @@ func LoadContainers(path string) (map[netip.Addr]string, error) {
|
||||
return nil, err
|
||||
}
|
||||
defer fh.Close()
|
||||
return parseContainers(fh)
|
||||
}
|
||||
|
||||
// parseContainers reads the containers.map format from r.
|
||||
func parseContainers(r io.Reader) (map[netip.Addr]string, error) {
|
||||
m := map[netip.Addr]string{}
|
||||
sc := bufio.NewScanner(fh)
|
||||
sc := bufio.NewScanner(r)
|
||||
sc.Buffer(make([]byte, 0, 4096), 4096)
|
||||
for n := 0; sc.Scan() && n < maxMapLines; n++ {
|
||||
f := strings.Fields(sc.Text())
|
||||
|
||||
@@ -16,8 +16,12 @@ import (
|
||||
|
||||
// Config configures the engine. Mode must be observe or on (off means no engine).
|
||||
type Config struct {
|
||||
Mode string
|
||||
Path string // decision file
|
||||
Mode string
|
||||
Path string // decision file
|
||||
// Sink, when set, receives every decision (kind wire.CmdDecision) and unban
|
||||
// request (wire.CmdUnban) line instead of the files: the hub queues them for
|
||||
// the probe of the host. Path and UnbanPath are then only informational.
|
||||
Sink func(kind, line string) error
|
||||
UnbanPath string // unban requests read by the host (empty: unbanning is unavailable)
|
||||
StatePath string // enforce.json, empty: no persistence
|
||||
Host string // name of this instance, written in every line
|
||||
@@ -233,6 +237,17 @@ func New(c Config) *Engine {
|
||||
return e
|
||||
}
|
||||
|
||||
// writeLog delivers one decision line to the sink or the decision file.
|
||||
func (e *Engine) writeLog(line string) error {
|
||||
if e.cfg.Sink != nil {
|
||||
return e.cfg.Sink("decision", line)
|
||||
}
|
||||
return e.log.write(line)
|
||||
}
|
||||
|
||||
// HasSink reports whether decisions go to a sink instead of local files.
|
||||
func (e *Engine) HasSink() bool { return e.cfg.Sink != nil }
|
||||
|
||||
// Mode returns the mode of the engine.
|
||||
func (e *Engine) Mode() string { return e.cfg.Mode }
|
||||
|
||||
@@ -622,7 +637,7 @@ func (e *Engine) apply(a netip.Addr, st *ipState, d Decision, src string, now ti
|
||||
}
|
||||
line, err := FormatLine(now, a, d.Reason, d.Score, d.TTL, e.cfg.Host, src)
|
||||
if err == nil {
|
||||
err = e.log.write(line)
|
||||
err = e.writeLog(line)
|
||||
}
|
||||
if err != nil {
|
||||
e.counts.WriteErrors++
|
||||
|
||||
@@ -47,7 +47,7 @@ func UnbanLine(t time.Time, a netip.Addr, allow int) string {
|
||||
// Unban writes the request for the host, drops the active ban of the address
|
||||
// and, when allowS > 0, keeps the engine from banning it for that long.
|
||||
func (e *Engine) Unban(a netip.Addr, allowS int, src string) error {
|
||||
if e.cfg.UnbanPath == "" {
|
||||
if e.cfg.UnbanPath == "" && e.cfg.Sink == nil {
|
||||
return ErrNoUnbanLog
|
||||
}
|
||||
if allowS < 0 || allowS > MaxAllow {
|
||||
@@ -55,7 +55,11 @@ func (e *Engine) Unban(a netip.Addr, allowS int, src string) error {
|
||||
}
|
||||
a = a.Unmap().WithZone("")
|
||||
now := e.cfg.Now()
|
||||
if err := e.unlog.write(UnbanLine(now, a, allowS)); err != nil {
|
||||
if e.cfg.Sink != nil {
|
||||
if err := e.cfg.Sink("unban", UnbanLine(now, a, allowS)); err != nil {
|
||||
return err
|
||||
}
|
||||
} else if err := e.unlog.write(UnbanLine(now, a, allowS)); err != nil {
|
||||
return err
|
||||
}
|
||||
e.mu.Lock()
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
package fed
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// Get fetches a peer path with the peer token and decodes the JSON answer.
|
||||
func (h *Hub) Get(ctx context.Context, p Peer, path string, out any) error {
|
||||
_, err := h.get(ctx, p, path, out)
|
||||
return err
|
||||
}
|
||||
|
||||
// PostJSON sends v as JSON to a peer path with the peer token.
|
||||
func (h *Hub) PostJSON(ctx context.Context, p Peer, path string, v any) error {
|
||||
b, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, p.URL+path, bytes.NewReader(b))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tok := h.Token
|
||||
if p.Token != "" {
|
||||
tok = p.Token
|
||||
}
|
||||
if tok != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+tok)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := h.client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
|
||||
if resp.StatusCode/100 != 2 {
|
||||
return fmt.Errorf("HTTP %d", resp.StatusCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
package fed
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// EgressFor asks the online peers (or one) for their egress analysis of the
|
||||
// window [from, to] (unix seconds). The raw answers are untrusted: the caller
|
||||
// decodes and sanitizes them.
|
||||
func (h *Hub) EgressFor(ctx context.Context, from, to int64, only string) map[string]json.RawMessage {
|
||||
out := map[string]json.RawMessage{}
|
||||
var mu sync.Mutex
|
||||
var wg sync.WaitGroup
|
||||
for _, p := range h.Peers {
|
||||
if only != "" && only != p.Name {
|
||||
continue
|
||||
}
|
||||
h.mu.RLock()
|
||||
st := h.state[p.Name]
|
||||
online := st != nil && st.online
|
||||
h.mu.RUnlock()
|
||||
if !online {
|
||||
continue
|
||||
}
|
||||
wg.Add(1)
|
||||
go func(p Peer) {
|
||||
defer wg.Done()
|
||||
var raw json.RawMessage
|
||||
if _, err := h.get(ctx, p, fmt.Sprintf("/api/v1/peer/egress?from=%d&to=%d", from, to), &raw); err != nil {
|
||||
return
|
||||
}
|
||||
mu.Lock()
|
||||
out[p.Name] = raw
|
||||
mu.Unlock()
|
||||
}(p)
|
||||
}
|
||||
wg.Wait()
|
||||
return out
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package fed
|
||||
|
||||
import "time"
|
||||
|
||||
// SetLiveLimits shrinks the flood window, the byte ceiling and the first backoff; it returns the restore func.
|
||||
func SetLiveLimits(window time.Duration, bytesPerSec int, backoff time.Duration) func() {
|
||||
w, b, k := liveByteWindow, maxLiveBytes, liveBackoff0
|
||||
liveByteWindow, maxLiveBytes, liveBackoff0 = window, bytesPerSec, backoff
|
||||
return func() { liveByteWindow, maxLiveBytes, liveBackoff0 = w, b, k }
|
||||
}
|
||||
|
||||
// WaitStream blocks until the live stream goroutines have returned (after ctx is cancelled).
|
||||
func (h *Hub) WaitStream() { h.swg.Wait() }
|
||||
+178
-343
@@ -1,287 +1,139 @@
|
||||
// Package fed lets one instance aggregate the summaries of other instances.
|
||||
// Package fed aggregates the nodes of the hub: one node per probe, each with
|
||||
// its own store, served in process through the Backend interface.
|
||||
package fed
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
// maxBody caps what a hub accepts from one peer response.
|
||||
const maxBody = 8 << 20
|
||||
|
||||
// Peer is a remote Urutau instance.
|
||||
type Peer struct {
|
||||
Name, URL string
|
||||
// Token overrides the hub-wide token for this peer (URUTAU_PEER_TOKEN_<NAME>).
|
||||
Token string
|
||||
// Backend is one probe node seen from the aggregation layer.
|
||||
type Backend interface {
|
||||
Name() string
|
||||
Export(rg store.Range) store.PeerExport
|
||||
Study(q store.PeriodQuery) store.PeerStudy
|
||||
Egress(from, to int64) json.RawMessage
|
||||
Subscribe() (<-chan store.LiveEvent, func())
|
||||
SubscribeVisits() (<-chan store.VisitMsg, func())
|
||||
// Online reports whether the probe is connected. The data of an offline
|
||||
// node is still served (it lives in the hub).
|
||||
Online() bool
|
||||
Location() *store.Location
|
||||
}
|
||||
|
||||
// ParsePeer parses "name=https://url".
|
||||
func ParsePeer(s string) (Peer, error) {
|
||||
name, u, ok := strings.Cut(s, "=")
|
||||
name, u = strings.TrimSpace(name), strings.TrimRight(strings.TrimSpace(u), "/")
|
||||
if !ok || name == "" || u == "" {
|
||||
return Peer{}, fmt.Errorf("peer %q: expected name=https://url", s)
|
||||
}
|
||||
pu, err := url.Parse(u)
|
||||
if err != nil || pu.Host == "" || pu.User != nil {
|
||||
return Peer{}, fmt.Errorf("peer %q: invalid URL", s)
|
||||
}
|
||||
switch {
|
||||
case pu.Scheme == "https":
|
||||
case pu.Scheme == "http" && isLoopbackHost(pu.Hostname()):
|
||||
default:
|
||||
return Peer{}, fmt.Errorf("peer %q: the URL must be https (plain http only for loopback)", s)
|
||||
}
|
||||
return Peer{Name: name, URL: u}, nil
|
||||
}
|
||||
|
||||
func isLoopbackHost(h string) bool {
|
||||
if h == "localhost" {
|
||||
return true
|
||||
}
|
||||
a, err := netip.ParseAddr(h)
|
||||
return err == nil && a.IsLoopback()
|
||||
}
|
||||
|
||||
type peerState struct {
|
||||
online bool
|
||||
lastOK int64
|
||||
err string
|
||||
latency int64
|
||||
version string
|
||||
exports map[string]store.PeerExport
|
||||
extra map[string]*extraExport // on-demand windows
|
||||
studies map[string]*studyCached
|
||||
live bool
|
||||
}
|
||||
|
||||
// extraExport is an export of a window outside the background set.
|
||||
type extraExport struct {
|
||||
at time.Time
|
||||
e store.PeerExport
|
||||
// HostStatus is implemented by backends that know more than Online (version,
|
||||
// last contact, lag); Hosts uses it when present.
|
||||
type HostStatus interface {
|
||||
HostInfo() store.HostInfo
|
||||
}
|
||||
|
||||
const (
|
||||
extraTTL = 15 * time.Second
|
||||
extraMax = 12 // cached on-demand exports per peer
|
||||
exportTTL = 5 * time.Second
|
||||
studyTTL = 30 * time.Second
|
||||
cacheMax = 24
|
||||
liveBuf = 500
|
||||
)
|
||||
|
||||
// Hub polls peers and serves their latest summaries.
|
||||
type cached[T any] struct {
|
||||
at time.Time
|
||||
v T
|
||||
}
|
||||
|
||||
// Hub merges the backends supplied by Provider.
|
||||
type Hub struct {
|
||||
Peers []Peer
|
||||
Token string
|
||||
Interval time.Duration
|
||||
client *http.Client
|
||||
stream *http.Client // long-lived SSE: no overall timeout, no redirects
|
||||
Provider func() []Backend
|
||||
|
||||
swg sync.WaitGroup // live stream goroutines
|
||||
lmu sync.Mutex
|
||||
live liveState
|
||||
mu sync.Mutex
|
||||
exports map[string]cached[store.PeerExport]
|
||||
studies map[string]cached[store.PeerStudy]
|
||||
|
||||
mu sync.RWMutex
|
||||
state map[string]*peerState
|
||||
|
||||
// OnLive, when set, sees every sanitized peer event before it is published
|
||||
// (it assigns the local id and registers it in the event log).
|
||||
OnLive func(*store.LiveEvent)
|
||||
lmu sync.Mutex
|
||||
recent []store.LiveEvent
|
||||
head int
|
||||
subs map[chan store.LiveEvent]struct{}
|
||||
vsubs map[chan store.VisitMsg]struct{}
|
||||
attach map[string]func() // backend name -> stop
|
||||
}
|
||||
|
||||
// NewHub creates a hub; Interval defaults to 15 seconds.
|
||||
func NewHub(peers []Peer, token string) *Hub {
|
||||
h := &Hub{Peers: peers, Token: token, Interval: 15 * time.Second,
|
||||
client: &http.Client{Timeout: 4 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}, state: map[string]*peerState{}}
|
||||
tr := http.DefaultTransport.(*http.Transport).Clone()
|
||||
tr.ResponseHeaderTimeout = 10 * time.Second
|
||||
h.stream = &http.Client{Transport: tr, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
|
||||
for _, p := range peers {
|
||||
h.state[p.Name] = &peerState{exports: map[string]store.PeerExport{}, extra: map[string]*extraExport{}}
|
||||
}
|
||||
return h
|
||||
// NewHub creates a hub over the backends returned by provider (called on every use).
|
||||
func NewHub(provider func() []Backend) *Hub {
|
||||
return &Hub{Provider: provider, exports: map[string]cached[store.PeerExport]{}, studies: map[string]cached[store.PeerStudy]{},
|
||||
subs: map[chan store.LiveEvent]struct{}{}, vsubs: map[chan store.VisitMsg]struct{}{}, attach: map[string]func(){}}
|
||||
}
|
||||
|
||||
func (h *Hub) get(ctx context.Context, p Peer, path string, out any) (time.Duration, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, p.URL+path, nil)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
func (h *Hub) backends(only string) []Backend {
|
||||
if h == nil || h.Provider == nil {
|
||||
return nil
|
||||
}
|
||||
tok := h.Token
|
||||
if p.Token != "" {
|
||||
tok = p.Token
|
||||
}
|
||||
if tok != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+tok)
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
t := time.Now()
|
||||
resp, err := h.client.Do(req)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
|
||||
return 0, fmt.Errorf("HTTP %d", resp.StatusCode)
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, maxBody+1))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if len(body) > maxBody {
|
||||
return 0, fmt.Errorf("response larger than %d bytes", maxBody)
|
||||
}
|
||||
if err := json.Unmarshal(body, out); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return time.Since(t), nil
|
||||
}
|
||||
|
||||
// Refresh fetches every peer once, concurrently. Failures only mark the peer offline.
|
||||
func (h *Hub) Refresh(ctx context.Context) {
|
||||
var wg sync.WaitGroup
|
||||
for _, p := range h.Peers {
|
||||
wg.Add(1)
|
||||
go func(p Peer) {
|
||||
defer wg.Done()
|
||||
exports := map[string]store.PeerExport{}
|
||||
var lat time.Duration
|
||||
var ferr error
|
||||
for _, name := range store.BackgroundRanges {
|
||||
var e store.PeerExport
|
||||
d, err := h.get(ctx, p, "/api/v1/peer/export?range="+name, &e)
|
||||
if err == nil {
|
||||
err = e.Sanitize(name)
|
||||
}
|
||||
if err != nil {
|
||||
ferr = err
|
||||
break
|
||||
}
|
||||
lat = d
|
||||
e.Summary = rename(e.Summary, p.Name)
|
||||
exports[name] = e
|
||||
}
|
||||
h.mu.Lock()
|
||||
st := h.state[p.Name]
|
||||
if ferr != nil {
|
||||
st.online, st.err = false, ferr.Error()
|
||||
if len(st.err) > 160 {
|
||||
st.err = st.err[:160]
|
||||
}
|
||||
} else {
|
||||
st.online, st.err, st.lastOK, st.latency, st.exports = true, "", time.Now().Unix(), lat.Milliseconds(), exports
|
||||
for _, e := range exports {
|
||||
st.version = e.Summary.Version
|
||||
}
|
||||
}
|
||||
h.mu.Unlock()
|
||||
}(p)
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
// fetchRange asks a peer for the export of a window and sanitizes it.
|
||||
func (h *Hub) fetchRange(ctx context.Context, p Peer, rg store.Range) (store.PeerExport, error) {
|
||||
var e store.PeerExport
|
||||
path := "/api/v1/peer/export?range=" + url.QueryEscape(rg.Name)
|
||||
if rg.Custom() {
|
||||
path = fmt.Sprintf("/api/v1/peer/export?from=%d&to=%d", rg.From, rg.To)
|
||||
}
|
||||
if _, err := h.get(ctx, p, path, &e); err != nil {
|
||||
return e, err
|
||||
}
|
||||
if err := e.SanitizeRange(rg); err != nil {
|
||||
return e, err
|
||||
}
|
||||
e.Summary = rename(e.Summary, p.Name)
|
||||
return e, nil
|
||||
}
|
||||
|
||||
// exportsFor returns the exports of the online peers (or one) for a window:
|
||||
// the cached background ones, or an on-demand fetch cached for 15 s.
|
||||
func (h *Hub) exportsFor(ctx context.Context, rg store.Range, only string) map[string]store.PeerExport {
|
||||
out := map[string]store.PeerExport{}
|
||||
var mu sync.Mutex
|
||||
var wg sync.WaitGroup
|
||||
for _, p := range h.Peers {
|
||||
if only != "" && only != p.Name {
|
||||
continue
|
||||
all := h.Provider()
|
||||
out := make([]Backend, 0, len(all))
|
||||
for _, b := range all {
|
||||
if only == "" || only == b.Name() {
|
||||
out = append(out, b)
|
||||
}
|
||||
h.mu.RLock()
|
||||
st := h.state[p.Name]
|
||||
online := st.online
|
||||
var cached *store.PeerExport
|
||||
if !rg.Custom() {
|
||||
if e, ok := st.exports[rg.Name]; ok {
|
||||
cached = &e
|
||||
}
|
||||
}
|
||||
if cached == nil {
|
||||
if x := st.extra[rg.Key()]; x != nil && time.Since(x.at) < extraTTL {
|
||||
e := x.e
|
||||
cached = &e
|
||||
}
|
||||
}
|
||||
h.mu.RUnlock()
|
||||
if !online {
|
||||
continue
|
||||
}
|
||||
if cached != nil {
|
||||
out[p.Name] = *cached
|
||||
continue
|
||||
}
|
||||
wg.Add(1)
|
||||
go func(p Peer) {
|
||||
defer wg.Done()
|
||||
e, err := h.fetchRange(ctx, p, rg)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
h.mu.Lock()
|
||||
st := h.state[p.Name]
|
||||
if len(st.extra) >= extraMax {
|
||||
st.extra = map[string]*extraExport{}
|
||||
}
|
||||
st.extra[rg.Key()] = &extraExport{at: time.Now(), e: e}
|
||||
h.mu.Unlock()
|
||||
mu.Lock()
|
||||
out[p.Name] = e
|
||||
mu.Unlock()
|
||||
}(p)
|
||||
}
|
||||
wg.Wait()
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Name() < out[j].Name() })
|
||||
return out
|
||||
}
|
||||
|
||||
// SummariesFor returns the summaries of online peers for any window.
|
||||
// PeerNames lists the names of the nodes (nil-safe).
|
||||
func (h *Hub) PeerNames() []string {
|
||||
var out []string
|
||||
for _, b := range h.backends("") {
|
||||
out = append(out, b.Name())
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Has reports whether name is a node served by this hub.
|
||||
func (h *Hub) Has(name string) bool { return len(h.backends(name)) > 0 }
|
||||
|
||||
func (h *Hub) export(b Backend, rg store.Range) (store.PeerExport, bool) {
|
||||
key := b.Name() + "|" + rg.Key()
|
||||
h.mu.Lock()
|
||||
if c, ok := h.exports[key]; ok && time.Since(c.at) < exportTTL {
|
||||
h.mu.Unlock()
|
||||
return c.v, true
|
||||
}
|
||||
h.mu.Unlock()
|
||||
e := b.Export(rg)
|
||||
if err := e.SanitizeRange(rg); err != nil {
|
||||
return e, false
|
||||
}
|
||||
e.Summary = rename(e.Summary, b.Name())
|
||||
h.mu.Lock()
|
||||
if len(h.exports) >= cacheMax {
|
||||
h.exports = map[string]cached[store.PeerExport]{}
|
||||
}
|
||||
h.exports[key] = cached[store.PeerExport]{time.Now(), e}
|
||||
h.mu.Unlock()
|
||||
return e, true
|
||||
}
|
||||
|
||||
// SummariesFor returns the summaries of the nodes (or one) for any window.
|
||||
func (h *Hub) SummariesFor(ctx context.Context, rg store.Range, only string) []store.Summary {
|
||||
m := h.exportsFor(ctx, rg, only)
|
||||
var out []store.Summary
|
||||
for _, p := range h.Peers {
|
||||
if e, ok := m[p.Name]; ok {
|
||||
for _, b := range h.backends(only) {
|
||||
if e, ok := h.export(b, rg); ok {
|
||||
out = append(out, e.Summary)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// TrafficFor returns the analytics of online peers for any window and domain.
|
||||
// TrafficFor returns the analytics of the nodes (or one) for a window and domain.
|
||||
func (h *Hub) TrafficFor(ctx context.Context, rg store.Range, domain, only string) []store.TrafficData {
|
||||
m := h.exportsFor(ctx, rg, only)
|
||||
var out []store.TrafficData
|
||||
for _, p := range h.Peers {
|
||||
if e, ok := m[p.Name]; ok {
|
||||
for _, b := range h.backends(only) {
|
||||
if e, ok := h.export(b, rg); ok {
|
||||
if t, ok := e.Traffic[domain]; ok {
|
||||
t.Host = p.Name
|
||||
t.Host = b.Name()
|
||||
out = append(out, t)
|
||||
}
|
||||
}
|
||||
@@ -289,7 +141,17 @@ func (h *Hub) TrafficFor(ctx context.Context, rg store.Range, domain, only strin
|
||||
return out
|
||||
}
|
||||
|
||||
// rename forces the configured peer name on every row of a remote summary.
|
||||
// Summaries is SummariesFor for a named range.
|
||||
func (h *Hub) Summaries(rangeName, only string) []store.Summary {
|
||||
return h.SummariesFor(context.Background(), store.ParseRange(rangeName), only)
|
||||
}
|
||||
|
||||
// Traffic is TrafficFor for a named range.
|
||||
func (h *Hub) Traffic(rangeName, domain, only string) []store.TrafficData {
|
||||
return h.TrafficFor(context.Background(), store.ParseRange(rangeName), domain, only)
|
||||
}
|
||||
|
||||
// rename forces the node name on every row of a summary.
|
||||
func rename(s store.Summary, name string) store.Summary {
|
||||
s.Host = name
|
||||
for i := range s.Hosts {
|
||||
@@ -307,96 +169,13 @@ func rename(s store.Summary, name string) store.Summary {
|
||||
return s
|
||||
}
|
||||
|
||||
// Run refreshes until ctx is done.
|
||||
func (h *Hub) Run(ctx context.Context) {
|
||||
if len(h.Peers) == 0 {
|
||||
return
|
||||
}
|
||||
h.Stream(ctx)
|
||||
h.Refresh(ctx)
|
||||
t := time.NewTicker(h.Interval)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
h.Refresh(ctx)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Hosts lists the status of every peer (online or not).
|
||||
func (h *Hub) Hosts() []store.HostInfo {
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
out := make([]store.HostInfo, 0, len(h.Peers))
|
||||
for _, p := range h.Peers {
|
||||
st := h.state[p.Name]
|
||||
hi := store.HostInfo{Name: p.Name, Online: st.online, Error: st.err, LastSeen: st.lastOK, LatencyMS: st.latency, Version: st.version, Live: st.live && st.online}
|
||||
if e, ok := st.exports["24h"]; ok && st.online {
|
||||
s := e.Summary
|
||||
hi.Requests, hi.Malicious = s.Totals.Requests, s.Totals.Malicious
|
||||
hi.HostileIPs, hi.ActiveBans = s.Totals.HostileIPs, s.Totals.ActiveBans
|
||||
if len(s.Hosts) > 0 {
|
||||
hi.Location = s.Hosts[0].Location
|
||||
}
|
||||
}
|
||||
out = append(out, hi)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Summaries returns the summaries of online peers for a range. When only is
|
||||
// not empty just that peer is returned.
|
||||
func (h *Hub) Summaries(rangeName, only string) []store.Summary {
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
var out []store.Summary
|
||||
for _, p := range h.Peers {
|
||||
if only != "" && only != p.Name {
|
||||
continue
|
||||
}
|
||||
st := h.state[p.Name]
|
||||
if e, ok := st.exports[rangeName]; ok && st.online {
|
||||
out = append(out, e.Summary)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Peers lists the configured peer names (nil-safe).
|
||||
func (h *Hub) PeerNames() []string {
|
||||
if h == nil {
|
||||
return nil
|
||||
}
|
||||
out := make([]string, 0, len(h.Peers))
|
||||
for _, p := range h.Peers {
|
||||
out = append(out, p.Name)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Has reports whether name is a configured peer.
|
||||
func (h *Hub) Has(name string) bool {
|
||||
for _, p := range h.Peers {
|
||||
if p.Name == name {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IPDetail looks an address up in the cached exports of the online peers (the
|
||||
// 30-day summary, which carries the full row). No request is made to the peer.
|
||||
// IPDetail looks an address up in the 30-day export of every node.
|
||||
func (h *Hub) IPDetail(ip string) []store.IPSummary {
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
var out []store.IPSummary
|
||||
for _, p := range h.Peers {
|
||||
st := h.state[p.Name]
|
||||
e, ok := st.exports["30d"]
|
||||
if !ok || !st.online {
|
||||
rg := store.ParseRange("30d")
|
||||
for _, b := range h.backends("") {
|
||||
e, ok := h.export(b, rg)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
for _, x := range e.Summary.IPs {
|
||||
@@ -409,22 +188,78 @@ func (h *Hub) IPDetail(ip string) []store.IPSummary {
|
||||
return out
|
||||
}
|
||||
|
||||
// Traffic returns the cached analytics of online peers (or only one) for a
|
||||
// domain ("all" or a name), from the same export.
|
||||
func (h *Hub) Traffic(rangeName, domain, only string) []store.TrafficData {
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
var out []store.TrafficData
|
||||
for _, p := range h.Peers {
|
||||
if only != "" && only != p.Name {
|
||||
// Hosts lists the status of every node (online or not).
|
||||
func (h *Hub) Hosts() []store.HostInfo {
|
||||
rg := store.ParseRange("24h")
|
||||
var out []store.HostInfo
|
||||
for _, b := range h.backends("") {
|
||||
hi := store.HostInfo{Name: b.Name(), Online: b.Online(), Live: b.Online(), Location: b.Location()}
|
||||
if hs, ok := b.(HostStatus); ok {
|
||||
hi = hs.HostInfo()
|
||||
hi.Name = b.Name()
|
||||
}
|
||||
if e, ok := h.export(b, rg); ok {
|
||||
s := e.Summary
|
||||
hi.Requests, hi.Malicious = s.Totals.Requests, s.Totals.Malicious
|
||||
hi.HostileIPs, hi.ActiveBans = s.Totals.HostileIPs, s.Totals.ActiveBans
|
||||
if hi.Location == nil && len(s.Hosts) > 0 {
|
||||
hi.Location = s.Hosts[0].Location
|
||||
}
|
||||
}
|
||||
out = append(out, hi)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func studyKey(q store.PeriodQuery) string {
|
||||
return fmt.Sprintf("%d-%d|%s|%s|%s|%d", q.From, q.To, q.IP, q.Cat, q.Fam, q.Gap)
|
||||
}
|
||||
|
||||
// StudiesFor returns the period and metrics study of every node (or one).
|
||||
func (h *Hub) StudiesFor(ctx context.Context, q store.PeriodQuery, only string) map[string]store.PeerStudy {
|
||||
out := map[string]store.PeerStudy{}
|
||||
var mu sync.Mutex
|
||||
var wg sync.WaitGroup
|
||||
for _, b := range h.backends(only) {
|
||||
key := b.Name() + "|" + studyKey(q)
|
||||
h.mu.Lock()
|
||||
c, hit := h.studies[key]
|
||||
h.mu.Unlock()
|
||||
if hit && time.Since(c.at) < studyTTL {
|
||||
out[b.Name()] = c.v
|
||||
continue
|
||||
}
|
||||
st := h.state[p.Name]
|
||||
if e, ok := st.exports[rangeName]; ok && st.online {
|
||||
if t, ok := e.Traffic[domain]; ok {
|
||||
t.Host = p.Name
|
||||
out = append(out, t)
|
||||
wg.Add(1)
|
||||
go func(b Backend) {
|
||||
defer wg.Done()
|
||||
pq := q
|
||||
pq.Host = b.Name()
|
||||
s := b.Study(pq)
|
||||
if !s.Sanitize(b.Name()) {
|
||||
return
|
||||
}
|
||||
h.mu.Lock()
|
||||
if len(h.studies) >= cacheMax {
|
||||
h.studies = map[string]cached[store.PeerStudy]{}
|
||||
}
|
||||
h.studies[key] = cached[store.PeerStudy]{time.Now(), s}
|
||||
h.mu.Unlock()
|
||||
mu.Lock()
|
||||
out[b.Name()] = s
|
||||
mu.Unlock()
|
||||
}(b)
|
||||
}
|
||||
wg.Wait()
|
||||
return out
|
||||
}
|
||||
|
||||
// EgressFor returns the egress report of every node (or one) for [from, to];
|
||||
// nodes without egress analysis are left out.
|
||||
func (h *Hub) EgressFor(ctx context.Context, from, to int64, only string) map[string]json.RawMessage {
|
||||
out := map[string]json.RawMessage{}
|
||||
for _, b := range h.backends(only) {
|
||||
if raw := b.Egress(from, to); len(raw) > 0 {
|
||||
out[b.Name()] = raw
|
||||
}
|
||||
}
|
||||
return out
|
||||
|
||||
+32
-150
@@ -1,168 +1,50 @@
|
||||
package fed_test
|
||||
package fed
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/server"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
func TestPeerPollingMergeAndOffline(t *testing.T) {
|
||||
ps := store.New(store.Config{Name: "remote-self-name", Version: "t"})
|
||||
ps.Ingest(core.Event{Time: time.Now(), IP: "5.5.5.5", Cat: core.Exploit, Source: "traefik", Path: "/x", Method: "GET"})
|
||||
ps.Traffic(core.Event{Time: time.Now(), IP: "9.9.9.9", Cat: core.OK, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/", Status: 200})
|
||||
srv := httptest.NewServer(server.New(server.Options{Token: "main-token-0123456789-abcdefghijklmnopqrs", PeerTokens: []string{"peer-secret-0123456789-abcdefghijklmnopqr"}, Version: "t", Store: ps}))
|
||||
|
||||
p, err := fed.ParsePeer("hostinger=" + srv.URL + "/")
|
||||
if err != nil || p.Name != "hostinger" {
|
||||
t.Fatal(p, err)
|
||||
}
|
||||
for _, bad := range []string{"nourl", "=http://x", "a=ftp://x", "a=", "a=http://example.org", "a=http://10.0.0.5:8790", "a=https://user:pw@example.org"} {
|
||||
if _, err := fed.ParsePeer(bad); err == nil {
|
||||
t.Errorf("%q must be rejected", bad)
|
||||
}
|
||||
}
|
||||
|
||||
good := fed.NewHub([]fed.Peer{p}, "peer-secret-0123456789-abcdefghijklmnopqr")
|
||||
good.Refresh(context.Background())
|
||||
sums := good.Summaries("24h", "")
|
||||
if len(sums) != 1 || sums[0].Host != "hostinger" || sums[0].IPs[0].Hosts[0] != "hostinger" || sums[0].IPs[0].IP != "5.5.5.5" {
|
||||
t.Fatalf("summaries %+v", sums)
|
||||
}
|
||||
if h := good.Hosts(); !h[0].Online || h[0].Name != "hostinger" {
|
||||
t.Fatalf("hosts %+v", h)
|
||||
}
|
||||
if d := good.IPDetail("5.5.5.5"); len(d) != 1 || d[0].Hosts[0] != "hostinger" {
|
||||
t.Fatalf("ip detail from the cached export: %v", d)
|
||||
}
|
||||
if tr := good.Traffic("24h", "all", ""); len(tr) != 1 || tr[0].Requests != 1 || tr[0].Host != "hostinger" {
|
||||
t.Fatalf("traffic %+v", tr)
|
||||
}
|
||||
if tr := good.Traffic("24h", "a.example", "hostinger"); len(tr) != 1 || tr[0].Requests != 1 {
|
||||
t.Fatalf("per-domain traffic %+v", tr)
|
||||
}
|
||||
|
||||
bad := fed.NewHub([]fed.Peer{p}, "wrong")
|
||||
bad.Refresh(context.Background())
|
||||
if h := bad.Hosts(); h[0].Online || h[0].Error == "" || len(bad.Summaries("24h", "")) != 0 {
|
||||
t.Fatalf("wrong token must mark the peer offline: %+v", h)
|
||||
}
|
||||
|
||||
srv.Close()
|
||||
good.Refresh(context.Background())
|
||||
if h := good.Hosts(); h[0].Online || len(good.Summaries("24h", "")) != 0 {
|
||||
t.Fatalf("closed peer must be offline: %+v", h)
|
||||
}
|
||||
type fake struct {
|
||||
name string
|
||||
online bool
|
||||
}
|
||||
|
||||
func TestHubOnlyAsksForTheExportAndRefusesHostileResponses(t *testing.T) {
|
||||
var paths []string
|
||||
var huge atomic.Bool
|
||||
var redirects atomic.Int32
|
||||
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
redirects.Add(1)
|
||||
w.Write([]byte("{}"))
|
||||
}))
|
||||
defer target.Close()
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/api/v1/peer/export", func(w http.ResponseWriter, r *http.Request) {
|
||||
paths = append(paths, r.URL.Path)
|
||||
switch {
|
||||
case r.URL.Query().Get("redirect") == "1":
|
||||
case huge.Load():
|
||||
w.Write([]byte(`{"v":1,"pad":"` + strings.Repeat("x", 9<<20) + `"}`))
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, target.URL+"/x", http.StatusFound)
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
defer srv.Close()
|
||||
p := fed.Peer{Name: "evil", URL: srv.URL}
|
||||
func (f fake) Name() string { return f.name }
|
||||
func (f fake) Export(rg store.Range) store.PeerExport {
|
||||
return store.PeerExport{V: store.ExportVersion, Summary: store.Summary{Host: f.name, Hosts: []store.HostInfo{{Name: f.name, Self: true}}}, Traffic: map[string]store.TrafficData{}}
|
||||
}
|
||||
func (f fake) Study(q store.PeriodQuery) store.PeerStudy { return store.PeerStudy{} }
|
||||
func (f fake) Egress(a, b int64) json.RawMessage { return json.RawMessage(`{"findings":[]}`) }
|
||||
func (f fake) Subscribe() (<-chan store.LiveEvent, func()) {
|
||||
return make(chan store.LiveEvent), func() {}
|
||||
}
|
||||
func (f fake) SubscribeVisits() (<-chan store.VisitMsg, func()) {
|
||||
return make(chan store.VisitMsg), func() {}
|
||||
}
|
||||
func (f fake) Online() bool { return f.online }
|
||||
func (f fake) Location() *store.Location { return nil }
|
||||
|
||||
h := fed.NewHub([]fed.Peer{p}, "t")
|
||||
h.Refresh(context.Background())
|
||||
if redirects.Load() != 0 {
|
||||
t.Fatal("redirects must not be followed")
|
||||
func TestHubServesBackendsEvenOffline(t *testing.T) {
|
||||
h := NewHub(func() []Backend { return []Backend{fake{"b", false}, fake{"a", true}} })
|
||||
if got := h.PeerNames(); len(got) != 2 || got[0] != "a" || !h.Has("b") || h.Has("c") {
|
||||
t.Fatalf("%v", got)
|
||||
}
|
||||
if st := h.Hosts()[0]; st.Online {
|
||||
t.Fatalf("a redirect is a failure: %+v", st)
|
||||
rg := store.ParseRange("24h")
|
||||
if s := h.SummariesFor(context.Background(), rg, ""); len(s) != 2 || s[0].Host != "a" || s[0].Hosts[0].Self {
|
||||
t.Fatalf("%+v", s)
|
||||
}
|
||||
huge.Store(true)
|
||||
h.Refresh(context.Background())
|
||||
if st := h.Hosts()[0]; st.Online || !strings.Contains(st.Error, "larger") {
|
||||
t.Fatalf("an oversized response must be refused: %+v", st)
|
||||
if s := h.SummariesFor(context.Background(), rg, "b"); len(s) != 1 {
|
||||
t.Fatalf("only: %+v", s)
|
||||
}
|
||||
for _, path := range paths {
|
||||
if path != "/api/v1/peer/export" {
|
||||
t.Fatalf("the hub asked for %s", path)
|
||||
}
|
||||
hosts := h.Hosts()
|
||||
if len(hosts) != 2 || hosts[0].Online != true || hosts[1].Online != false {
|
||||
t.Fatalf("%+v", hosts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHubBoundsAnInflatedPeer(t *testing.T) {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/api/v1/peer/export", func(w http.ResponseWriter, r *http.Request) {
|
||||
var e store.PeerExport
|
||||
e.V = 1
|
||||
e.Summary.Version = strings.Repeat("v", 5000)
|
||||
for i := 0; i < 1000; i++ {
|
||||
e.Summary.IPs = append(e.Summary.IPs, store.IPSummary{IP: "1.2.3." + "4", Score: 1, Samples: make([]string, 40), Hosts: make([]string, 40)})
|
||||
}
|
||||
e.Summary.IPs = append(e.Summary.IPs, store.IPSummary{IP: "not an ip", Score: 1e9})
|
||||
e.Summary.Timeline.Series = map[string][]uint32{"exploit": make([]uint32, 100000), "evil": make([]uint32, 10)}
|
||||
for i := 0; i < 200; i++ {
|
||||
e.Summary.TopPaths = append(e.Summary.TopPaths, store.Count{Key: strings.Repeat("p", 9000), N: 1})
|
||||
}
|
||||
e.Traffic = map[string]store.TrafficData{}
|
||||
for i := 0; i < 60; i++ {
|
||||
e.Traffic[strings.Repeat("d", i+1)] = store.TrafficData{Timeline: struct {
|
||||
Start int64 `json:"start"`
|
||||
Step int64 `json:"step"`
|
||||
Req []uint32 `json:"req"`
|
||||
Pages []uint32 `json:"pages"`
|
||||
}{Req: make([]uint32, 5000)}}
|
||||
}
|
||||
json.NewEncoder(w).Encode(e)
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
defer srv.Close()
|
||||
h := fed.NewHub([]fed.Peer{{Name: "p", URL: srv.URL}}, "t")
|
||||
h.Refresh(context.Background())
|
||||
sums := h.Summaries("1h", "")
|
||||
if len(sums) != 1 {
|
||||
t.Fatalf("hosts %+v", h.Hosts())
|
||||
}
|
||||
s := sums[0]
|
||||
if len(s.IPs) != 500 || len(s.Version) > 32 || len(s.TopPaths) > 50 || len(s.TopPaths[0].Key) > 300 {
|
||||
t.Fatalf("caps not applied: ips=%d version=%d paths=%d", len(s.IPs), len(s.Version), len(s.TopPaths))
|
||||
}
|
||||
for _, x := range s.IPs {
|
||||
if x.IP == "not an ip" || len(x.Samples) > 6 || len(x.Hosts) > 4 {
|
||||
t.Fatalf("bad row survived: %+v", x)
|
||||
}
|
||||
}
|
||||
if len(s.Timeline.Series["exploit"]) != 60 || s.Timeline.Series["evil"] != nil || len(s.Timeline.Series["ok"]) != 60 {
|
||||
t.Fatal("the timeline grid is fixed by the range")
|
||||
}
|
||||
kept := 0
|
||||
for i := 1; i <= 60; i++ {
|
||||
for _, got := range h.Traffic("1h", strings.Repeat("d", i), "") {
|
||||
kept++
|
||||
if len(got.Timeline.Req) != 60 {
|
||||
t.Fatalf("traffic grid must be fixed: %d", len(got.Timeline.Req))
|
||||
}
|
||||
}
|
||||
}
|
||||
if kept > 27 {
|
||||
t.Fatalf("too many domains accepted from a peer: %d", kept)
|
||||
if m := h.EgressFor(context.Background(), 0, 1, ""); len(m) != 2 {
|
||||
t.Fatalf("%v", m)
|
||||
}
|
||||
}
|
||||
+54
-175
@@ -1,52 +1,21 @@
|
||||
package fed
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
const (
|
||||
maxLiveLine = 16 << 10 // longest SSE line accepted from a peer
|
||||
maxLiveRate = 50 // events per second accepted from one peer
|
||||
liveBuffer = 500 // events kept for /api/v1/live/recent
|
||||
liveIdle = 70 * time.Second
|
||||
liveBackoffTo = 60 * time.Second
|
||||
)
|
||||
|
||||
// Variables so tests can shrink them.
|
||||
var (
|
||||
maxLiveBytes = 1 << 20 // sustained bytes per second accepted from one peer
|
||||
liveByteWindow = 10 * time.Second
|
||||
liveBackoff0 = time.Second
|
||||
)
|
||||
|
||||
type liveState struct {
|
||||
recent []store.LiveEvent // ring of the newest peer events
|
||||
head int
|
||||
subs map[chan store.LiveEvent]struct{}
|
||||
vsubs map[chan store.VisitMsg]struct{} // legitimate visits: relayed, never kept
|
||||
}
|
||||
|
||||
// SubscribeVisits returns the legitimate visits relayed from peers.
|
||||
// SubscribeVisits returns the legitimate visits of the nodes.
|
||||
func (h *Hub) SubscribeVisits() (<-chan store.VisitMsg, func()) {
|
||||
ch := make(chan store.VisitMsg, 64)
|
||||
h.lmu.Lock()
|
||||
if h.live.vsubs == nil {
|
||||
h.live.vsubs = map[chan store.VisitMsg]struct{}{}
|
||||
}
|
||||
h.live.vsubs[ch] = struct{}{}
|
||||
h.vsubs[ch] = struct{}{}
|
||||
h.lmu.Unlock()
|
||||
return ch, func() {
|
||||
h.lmu.Lock()
|
||||
delete(h.live.vsubs, ch)
|
||||
delete(h.vsubs, ch)
|
||||
h.lmu.Unlock()
|
||||
}
|
||||
}
|
||||
@@ -54,7 +23,7 @@ func (h *Hub) SubscribeVisits() (<-chan store.VisitMsg, func()) {
|
||||
func (h *Hub) publishVisit(m store.VisitMsg) {
|
||||
h.lmu.Lock()
|
||||
defer h.lmu.Unlock()
|
||||
for ch := range h.live.vsubs {
|
||||
for ch := range h.vsubs {
|
||||
select {
|
||||
case ch <- m:
|
||||
default:
|
||||
@@ -62,31 +31,28 @@ func (h *Hub) publishVisit(m store.VisitMsg) {
|
||||
}
|
||||
}
|
||||
|
||||
// Subscribe returns the live events relayed from peers; call stop when done.
|
||||
// Subscribe returns the live events of the nodes; call stop when done.
|
||||
func (h *Hub) Subscribe() (<-chan store.LiveEvent, func()) {
|
||||
ch := make(chan store.LiveEvent, 64)
|
||||
h.lmu.Lock()
|
||||
if h.live.subs == nil {
|
||||
h.live.subs = map[chan store.LiveEvent]struct{}{}
|
||||
}
|
||||
h.live.subs[ch] = struct{}{}
|
||||
h.subs[ch] = struct{}{}
|
||||
h.lmu.Unlock()
|
||||
return ch, func() {
|
||||
h.lmu.Lock()
|
||||
delete(h.live.subs, ch)
|
||||
delete(h.subs, ch)
|
||||
h.lmu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// Recent returns the newest relayed peer events, newest first.
|
||||
// Recent returns the newest live events of the nodes, newest first.
|
||||
func (h *Hub) Recent(n int) []store.LiveEvent {
|
||||
h.lmu.Lock()
|
||||
defer h.lmu.Unlock()
|
||||
total := len(h.live.recent)
|
||||
total := len(h.recent)
|
||||
out := make([]store.LiveEvent, 0, min(n, total))
|
||||
for i := 0; i < total && len(out) < n; i++ {
|
||||
idx := ((h.live.head-1-i)%total + total) % total
|
||||
out = append(out, h.live.recent[idx])
|
||||
idx := ((h.head-1-i)%total + total) % total
|
||||
out = append(out, h.recent[idx])
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -94,13 +60,13 @@ func (h *Hub) Recent(n int) []store.LiveEvent {
|
||||
func (h *Hub) publish(e store.LiveEvent) {
|
||||
h.lmu.Lock()
|
||||
defer h.lmu.Unlock()
|
||||
if len(h.live.recent) < liveBuffer {
|
||||
h.live.recent = append(h.live.recent, e)
|
||||
if len(h.recent) < liveBuf {
|
||||
h.recent = append(h.recent, e)
|
||||
} else {
|
||||
h.live.recent[h.live.head] = e
|
||||
h.live.head = (h.live.head + 1) % liveBuffer
|
||||
h.recent[h.head] = e
|
||||
h.head = (h.head + 1) % liveBuf
|
||||
}
|
||||
for ch := range h.live.subs {
|
||||
for ch := range h.subs {
|
||||
select {
|
||||
case ch <- e:
|
||||
default: // slow client: drop
|
||||
@@ -108,143 +74,56 @@ func (h *Hub) publish(e store.LiveEvent) {
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Hub) setLive(name string, v bool) {
|
||||
h.mu.Lock()
|
||||
h.state[name].live = v
|
||||
h.mu.Unlock()
|
||||
}
|
||||
|
||||
// peerLocation is the location the peer reported in its last export.
|
||||
func (h *Hub) peerLocation(name string) *store.Location {
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
for _, e := range h.state[name].exports {
|
||||
if len(e.Summary.Hosts) > 0 && e.Summary.Hosts[0].Location != nil {
|
||||
l := *e.Summary.Hosts[0].Location
|
||||
return &l
|
||||
}
|
||||
// Run keeps the live relay of every node (also those created later) until ctx is done.
|
||||
func (h *Hub) Run(ctx context.Context) {
|
||||
if h == nil {
|
||||
return
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stream keeps one live subscription per peer until ctx is done, reconnecting
|
||||
// with an exponential backoff (1 s up to 60 s).
|
||||
func (h *Hub) Stream(ctx context.Context) {
|
||||
for _, p := range h.Peers {
|
||||
h.swg.Add(1)
|
||||
go func() { defer h.swg.Done(); h.streamPeer(ctx, p) }()
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Hub) streamPeer(ctx context.Context, p Peer) {
|
||||
back := liveBackoff0
|
||||
for ctx.Err() == nil {
|
||||
start := time.Now()
|
||||
h.consume(ctx, p)
|
||||
h.setLive(p.Name, false)
|
||||
if time.Since(start) > 2*liveBackoffTo {
|
||||
back = liveBackoff0 // it had been healthy for a while
|
||||
t := time.NewTicker(time.Second)
|
||||
defer t.Stop()
|
||||
defer func() {
|
||||
h.lmu.Lock()
|
||||
for _, stop := range h.attach {
|
||||
stop()
|
||||
}
|
||||
h.lmu.Unlock()
|
||||
}()
|
||||
for {
|
||||
h.sync(ctx)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-time.After(back):
|
||||
}
|
||||
if back *= 2; back > liveBackoffTo {
|
||||
back = liveBackoffTo
|
||||
case <-t.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var errLive = errors.New("live stream refused")
|
||||
|
||||
func (h *Hub) consume(ctx context.Context, p Peer) error {
|
||||
rctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(rctx, http.MethodGet, p.URL+"/api/v1/peer/stream?visits=1", nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tok := h.Token
|
||||
if p.Token != "" {
|
||||
tok = p.Token
|
||||
}
|
||||
if tok != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+tok)
|
||||
}
|
||||
req.Header.Set("Accept", "text/event-stream")
|
||||
resp, err := h.stream.Do(req) // no redirects; https is enforced by ParsePeer
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 || !strings.HasPrefix(resp.Header.Get("Content-Type"), "text/event-stream") {
|
||||
return errLive
|
||||
}
|
||||
idle := time.AfterFunc(liveIdle, cancel) // the peer pings every 20 s
|
||||
defer idle.Stop()
|
||||
h.setLive(p.Name, true)
|
||||
rd := bufio.NewReaderSize(resp.Body, maxLiveLine)
|
||||
var evName string
|
||||
var tokens = float64(maxLiveRate)
|
||||
winStart, winBytes := time.Now(), 0
|
||||
last := time.Now()
|
||||
for {
|
||||
line, err := rd.ReadSlice('\n') // ErrBufferFull: a line over 16 KB ends the stream
|
||||
if err != nil {
|
||||
return err
|
||||
// sync starts the relay of the backends that appeared since the last call.
|
||||
func (h *Hub) sync(ctx context.Context) {
|
||||
for _, b := range h.backends("") {
|
||||
h.lmu.Lock()
|
||||
_, ok := h.attach[b.Name()]
|
||||
h.lmu.Unlock()
|
||||
if ok {
|
||||
continue
|
||||
}
|
||||
idle.Reset(liveIdle)
|
||||
winBytes += len(line)
|
||||
if float64(winBytes) > float64(maxLiveBytes)*liveByteWindow.Seconds() {
|
||||
return errLive // a window's worth of budget burned already: flooding
|
||||
}
|
||||
if el := time.Since(winStart); el >= liveByteWindow {
|
||||
if float64(winBytes)/el.Seconds() > float64(maxLiveBytes) {
|
||||
return errLive // flooding: drop the connection, the backoff applies
|
||||
}
|
||||
winStart, winBytes = time.Now(), 0
|
||||
}
|
||||
line = bytes.TrimRight(line, "\r\n")
|
||||
switch {
|
||||
case bytes.HasPrefix(line, []byte("event:")):
|
||||
evName = strings.TrimSpace(string(line[6:]))
|
||||
case bytes.HasPrefix(line, []byte("data:")) && (evName == "ev" || evName == "visit"):
|
||||
now := time.Now()
|
||||
tokens += now.Sub(last).Seconds() * maxLiveRate
|
||||
if tokens > maxLiveRate {
|
||||
tokens = maxLiveRate
|
||||
}
|
||||
last = now
|
||||
if tokens < 1 {
|
||||
continue // over the budget: discard
|
||||
}
|
||||
tokens--
|
||||
if evName == "visit" {
|
||||
var v store.VisitMsg
|
||||
if json.Unmarshal(bytes.TrimSpace(line[5:]), &v) == nil && v.Sanitize(now.Unix()) {
|
||||
v.Host = p.Name
|
||||
if v.Kind == "visit" && v.Dst == nil {
|
||||
v.Dst = h.peerLocation(p.Name)
|
||||
}
|
||||
ev, stopEv := b.Subscribe()
|
||||
vis, stopVis := b.SubscribeVisits()
|
||||
cctx, cancel := context.WithCancel(ctx)
|
||||
h.lmu.Lock()
|
||||
h.attach[b.Name()] = func() { cancel(); stopEv(); stopVis() }
|
||||
h.lmu.Unlock()
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case <-cctx.Done():
|
||||
return
|
||||
case e := <-ev:
|
||||
h.publish(e)
|
||||
case v := <-vis:
|
||||
h.publishVisit(v)
|
||||
}
|
||||
continue
|
||||
}
|
||||
var e store.LiveEvent
|
||||
if json.Unmarshal(bytes.TrimSpace(line[5:]), &e) != nil || !e.Sanitize(now.Unix()) {
|
||||
continue
|
||||
}
|
||||
e.Host = p.Name
|
||||
if e.Dst == nil {
|
||||
e.Dst = h.peerLocation(p.Name)
|
||||
}
|
||||
if h.OnLive != nil {
|
||||
h.OnLive(&e)
|
||||
}
|
||||
h.publish(e)
|
||||
case len(line) == 0:
|
||||
evName = ""
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
@@ -1,216 +0,0 @@
|
||||
package fed_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/server"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
func fakeStream(t *testing.T, conns *atomic.Int32, body func(w http.ResponseWriter)) *httptest.Server {
|
||||
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/api/v1/peer/stream" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if r.Header.Get("Authorization") != "Bearer tok" {
|
||||
http.Error(w, "no", 401)
|
||||
return
|
||||
}
|
||||
conns.Add(1)
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
w.WriteHeader(200)
|
||||
body(w)
|
||||
w.(http.Flusher).Flush()
|
||||
<-r.Context().Done()
|
||||
}))
|
||||
}
|
||||
|
||||
func ev(data string) string { return "event: ev\ndata: " + data + "\n\n" }
|
||||
|
||||
func TestLiveRelaySanitizesAndDrops(t *testing.T) {
|
||||
var conns atomic.Int32
|
||||
big := ev(`{"ip":"1.2.3.4","cat":"scanner","path":"` + strings.Repeat("a", 20000) + `"}`)
|
||||
srv := fakeStream(t, &conns, func(w http.ResponseWriter) {
|
||||
fmt.Fprint(w, ": connected\n\n")
|
||||
fmt.Fprint(w, ev(`{"ip":"not-an-ip","cat":"scanner"}`))
|
||||
fmt.Fprint(w, ev(`{"ip":"5.5.5.5","cat":"ok"}`)) // not malicious
|
||||
fmt.Fprint(w, ev(`{"ip":"5.5.5.5","cat":"<script>"}`)) // unknown category
|
||||
fmt.Fprint(w, ev(`{"ip":"6.6.6.6","cat":"exploit","host":"evil","path":"/a\u0001b`+strings.Repeat("x", 500)+`","cc":"brasil","status":99999,"src":{"lat":500,"lon":1},"dst":{"lat":10,"lon":20,"label":"`+strings.Repeat("L", 200)+`"},"extra":"x"}`))
|
||||
fmt.Fprint(w, "event: other\ndata: {\"ip\":\"7.7.7.7\",\"cat\":\"exploit\"}\n\n")
|
||||
fmt.Fprint(w, ev(`{"ip":"8.8.8.8","cat":"scanner","src":{"lat":-8,"lon":-34,"cc":"BR","city":"Recife"}}`))
|
||||
fmt.Fprint(w, big) // over 16 KB: the stream is cut
|
||||
})
|
||||
defer srv.Close()
|
||||
p, _ := fed.ParsePeer("edge=" + srv.URL)
|
||||
h := fed.NewHub([]fed.Peer{p}, "tok")
|
||||
ch, stop := h.Subscribe()
|
||||
defer stop()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer func() { cancel(); h.WaitStream() }()
|
||||
h.Stream(ctx)
|
||||
|
||||
var got []store.LiveEvent
|
||||
for len(got) < 2 {
|
||||
select {
|
||||
case e := <-ch:
|
||||
got = append(got, e)
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatalf("only %d events: %+v", len(got), got)
|
||||
}
|
||||
}
|
||||
a, b := got[0], got[1]
|
||||
if a.IP != "6.6.6.6" || a.Host != "edge" || a.Cat != "exploit" || a.CC != "" || a.Status != 0 || a.Src != nil {
|
||||
t.Fatalf("sanitized event %+v", a)
|
||||
}
|
||||
if strings.ContainsRune(a.Path, 1) || len(a.Path) > 240 || a.Dst == nil || len(a.Dst.Label) != 64 {
|
||||
t.Fatalf("strings %q dst %+v", a.Path, a.Dst)
|
||||
}
|
||||
if b.IP != "8.8.8.8" || b.Src == nil || b.Src.City != "Recife" || b.Host != "edge" {
|
||||
t.Fatalf("second %+v", b)
|
||||
}
|
||||
if r := h.Recent(10); len(r) != 2 || r[0].IP != "8.8.8.8" {
|
||||
t.Fatalf("recent %+v", r)
|
||||
}
|
||||
// the oversize line ended the stream: no event from it, and the hub reconnects
|
||||
deadline := time.After(5 * time.Second)
|
||||
for conns.Load() < 2 {
|
||||
select {
|
||||
case <-deadline:
|
||||
t.Fatalf("no reconnection (%d)", conns.Load())
|
||||
case <-time.After(50 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
select {
|
||||
case e := <-ch:
|
||||
if e.IP == "1.2.3.4" {
|
||||
t.Fatal("oversize line must not become an event")
|
||||
}
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveRateLimitAndFlag(t *testing.T) {
|
||||
var conns atomic.Int32
|
||||
srv := fakeStream(t, &conns, func(w http.ResponseWriter) {
|
||||
for i := 0; i < 400; i++ {
|
||||
fmt.Fprint(w, ev(fmt.Sprintf(`{"ip":"9.9.%d.%d","cat":"scanner"}`, i/250, i%250+1)))
|
||||
}
|
||||
})
|
||||
defer srv.Close()
|
||||
p, _ := fed.ParsePeer("edge=" + srv.URL)
|
||||
h := fed.NewHub([]fed.Peer{p}, "tok")
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer func() { cancel(); h.WaitStream() }()
|
||||
h.Stream(ctx)
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for len(h.Recent(500)) == 0 && time.Now().Before(deadline) {
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
if n := len(h.Recent(500)); n < 40 || n > 120 {
|
||||
t.Fatalf("a burst of 400 must be cut to about 50 (got %d)", n)
|
||||
}
|
||||
if hs := h.Hosts(); len(hs) != 1 || hs[0].Live {
|
||||
// Live also needs the peer to be online (polled); here it never was
|
||||
t.Fatalf("hosts %+v", hs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveWithRealPeerServer(t *testing.T) {
|
||||
ps := store.New(store.Config{Name: "remote", Version: "t", Location: &store.Location{Lat: -8, Lon: -35, Label: "Recife"}})
|
||||
srv := httptest.NewServer(server.New(server.Options{Token: "main-token-0123456789-abcdefghijklmnopqrs", PeerTokens: []string{"peer-secret-0123456789-abcdefghijklmnopqr"}, Version: "t", Store: ps}))
|
||||
defer srv.Close()
|
||||
p, _ := fed.ParsePeer("edge=" + srv.URL)
|
||||
h := fed.NewHub([]fed.Peer{p}, "peer-secret-0123456789-abcdefghijklmnopqr")
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer func() { cancel(); h.WaitStream() }()
|
||||
h.Refresh(ctx)
|
||||
h.Stream(ctx)
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
ps.Ingest(core.Event{Time: time.Now(), IP: "5.5.5.5", Cat: core.Exploit, Source: "traefik", Method: "GET", Path: "/x"})
|
||||
if len(h.Recent(5)) > 0 {
|
||||
break
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
r := h.Recent(5)
|
||||
if len(r) == 0 || r[0].Host != "edge" || r[0].IP != "5.5.5.5" || r[0].Dst == nil || r[0].Dst.Label != "Recife" {
|
||||
t.Fatalf("relayed %+v", r)
|
||||
}
|
||||
hs := h.Hosts()
|
||||
if !hs[0].Live || !hs[0].Online || hs[0].Location == nil || hs[0].Location.Label != "Recife" {
|
||||
t.Fatalf("hosts %+v", hs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveByteFloodDropsConnection(t *testing.T) {
|
||||
defer fed.SetLiveLimits(200*time.Millisecond, 10_000, 100*time.Millisecond)()
|
||||
start := time.Now()
|
||||
var conns atomic.Int32
|
||||
pad := strings.Repeat("a", 1000)
|
||||
srv := fakeStream(t, &conns, func(w http.ResponseWriter) {
|
||||
for i := 0; i < 200; i++ { // ~200 KB at once: far above 10 KB/s
|
||||
fmt.Fprintf(w, ": %s\n", pad)
|
||||
}
|
||||
})
|
||||
defer srv.Close()
|
||||
p, _ := fed.ParsePeer("edge=" + srv.URL)
|
||||
h := fed.NewHub([]fed.Peer{p}, "tok")
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer func() { cancel(); h.WaitStream() }()
|
||||
h.Stream(ctx)
|
||||
// the flood ends the connection (window check), then the hub reconnects after the backoff
|
||||
for conns.Load() < 2 {
|
||||
if time.Since(start) > 2500*time.Millisecond {
|
||||
t.Fatalf("no drop and reconnection (%d connections)", conns.Load())
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVisitRelayHasNoAddressAndNoRecent(t *testing.T) {
|
||||
var conns atomic.Int32
|
||||
srv := fakeStream(t, &conns, func(w http.ResponseWriter) {
|
||||
fmt.Fprint(w, "event: visit\ndata: "+`{"kind":"visit","t":`+fmt.Sprint(time.Now().Unix())+`,"host":"evil","ip":"9.9.9.9","ua":"Mozilla","domain":"a.example","path":"/x","status":200,"device":"mobile","src":{"lat":-8,"lon":-34.9,"cc":"BR","city":"Recife"}}`+"\n\n")
|
||||
fmt.Fprint(w, "event: visit\ndata: "+`{"kind":"visit_batch","t":`+fmt.Sprint(time.Now().Unix())+`,"n":7}`+"\n\n")
|
||||
fmt.Fprint(w, "event: visit\ndata: "+`{"kind":"nope"}`+"\n\n")
|
||||
})
|
||||
defer srv.Close()
|
||||
p, _ := fed.ParsePeer("edge=" + srv.URL)
|
||||
h := fed.NewHub([]fed.Peer{p}, "tok")
|
||||
ch, stop := h.SubscribeVisits()
|
||||
defer stop()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer func() { cancel(); h.WaitStream() }()
|
||||
h.Stream(ctx)
|
||||
var got []store.VisitMsg
|
||||
for len(got) < 2 {
|
||||
select {
|
||||
case m := <-ch:
|
||||
got = append(got, m)
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatalf("timeout, got %+v", got)
|
||||
}
|
||||
}
|
||||
for _, m := range got {
|
||||
b, _ := json.Marshal(m)
|
||||
if strings.Contains(string(b), "9.9.9.9") || strings.Contains(string(b), `"ip"`) || strings.Contains(string(b), "Mozilla") || m.Host != "edge" {
|
||||
t.Fatalf("relayed %s", b)
|
||||
}
|
||||
}
|
||||
if got[0].Device != "mobile" || got[1].Kind != "visit_batch" || got[1].N != 7 || len(h.Recent(10)) != 0 {
|
||||
t.Fatalf("%+v recent=%d", got, len(h.Recent(10)))
|
||||
}
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
package fed
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
const (
|
||||
studyTTL = 30 * time.Second
|
||||
studyMax = 8 // cached studies per peer
|
||||
)
|
||||
|
||||
type studyCached struct {
|
||||
at time.Time
|
||||
s store.PeerStudy
|
||||
}
|
||||
|
||||
func studyKey(q store.PeriodQuery) string {
|
||||
return fmt.Sprintf("%d-%d|%s|%s|%s|%d", q.From, q.To, q.IP, q.Cat, q.Fam, q.Gap)
|
||||
}
|
||||
|
||||
// StudiesFor asks the online peers (or one) for their period and metrics
|
||||
// study of a window, on demand, cached for 30 s. The answers are sanitized
|
||||
// and carry the configured peer name.
|
||||
func (h *Hub) StudiesFor(ctx context.Context, q store.PeriodQuery, only string) map[string]store.PeerStudy {
|
||||
out := map[string]store.PeerStudy{}
|
||||
var mu sync.Mutex
|
||||
var wg sync.WaitGroup
|
||||
key := studyKey(q)
|
||||
for _, p := range h.Peers {
|
||||
if only != "" && only != p.Name {
|
||||
continue
|
||||
}
|
||||
h.mu.RLock()
|
||||
st := h.state[p.Name]
|
||||
online := st.online
|
||||
var hit *store.PeerStudy
|
||||
if c := st.studies[key]; c != nil && time.Since(c.at) < studyTTL {
|
||||
s := c.s
|
||||
hit = &s
|
||||
}
|
||||
h.mu.RUnlock()
|
||||
if !online {
|
||||
continue
|
||||
}
|
||||
if hit != nil {
|
||||
out[p.Name] = *hit
|
||||
continue
|
||||
}
|
||||
wg.Add(1)
|
||||
go func(p Peer) {
|
||||
defer wg.Done()
|
||||
v := url.Values{}
|
||||
v.Set("from", fmt.Sprint(q.From))
|
||||
v.Set("to", fmt.Sprint(q.To))
|
||||
for k, x := range map[string]string{"ip": q.IP, "cat": q.Cat, "fam": q.Fam} {
|
||||
if x != "" {
|
||||
v.Set(k, x)
|
||||
}
|
||||
}
|
||||
if q.Gap > 0 {
|
||||
v.Set("gap", fmt.Sprint(q.Gap))
|
||||
}
|
||||
var s store.PeerStudy
|
||||
if _, err := h.get(ctx, p, "/api/v1/peer/period?"+v.Encode(), &s); err != nil || !s.Sanitize(p.Name) {
|
||||
return
|
||||
}
|
||||
h.mu.Lock()
|
||||
st := h.state[p.Name]
|
||||
if st.studies == nil || len(st.studies) >= studyMax {
|
||||
st.studies = map[string]*studyCached{}
|
||||
}
|
||||
st.studies[key] = &studyCached{time.Now(), s}
|
||||
h.mu.Unlock()
|
||||
mu.Lock()
|
||||
out[p.Name] = s
|
||||
mu.Unlock()
|
||||
}(p)
|
||||
}
|
||||
wg.Wait()
|
||||
return out
|
||||
}
|
||||
@@ -1,115 +0,0 @@
|
||||
package fed_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/server"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
func TestHubOnDemandRangesRatesAndOldPeers(t *testing.T) {
|
||||
peerTok := "peer-secret-0123456789-abcdefghijklmnopqr"
|
||||
ps := store.New(store.Config{Name: "remote", Version: "t", Retention: 720 * time.Hour})
|
||||
for i := 0; i < 4; i++ {
|
||||
ps.Ingest(core.Event{Time: time.Now().Add(-time.Duration(i) * time.Minute), IP: "5.5.5.5", Cat: core.Exploit, Source: "traefik", Path: "/x", Method: "GET"})
|
||||
}
|
||||
ps.Ingest(core.Event{Time: time.Now().Add(-10 * 24 * time.Hour), IP: "6.6.6.6", Cat: core.Scanner, Source: "traefik", Path: "/y", Method: "GET"})
|
||||
ps.Traffic(core.Event{Time: time.Now(), IP: "9.9.9.9", Cat: core.OK, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/", Status: 200})
|
||||
var calls []string
|
||||
inner := server.New(server.Options{Token: "main-token-0123456789-abcdefghijklmnopqrs", PeerTokens: []string{peerTok}, Version: "t", Store: ps})
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls = append(calls, r.URL.RawQuery)
|
||||
inner.ServeHTTP(w, r)
|
||||
}))
|
||||
defer srv.Close()
|
||||
p, _ := fed.ParsePeer("hostinger=" + srv.URL)
|
||||
hub := fed.NewHub([]fed.Peer{p}, peerTok)
|
||||
hub.Refresh(context.Background())
|
||||
if len(calls) != len(store.BackgroundRanges) {
|
||||
t.Fatalf("background fetches: %v", calls)
|
||||
}
|
||||
// a window outside the background set is fetched on demand, then cached
|
||||
rg := store.Ranges["15d"]
|
||||
n := len(calls)
|
||||
sums := hub.SummariesFor(context.Background(), rg, "")
|
||||
if len(sums) != 1 || sums[0].Range.Name != "15d" || sums[0].Totals.Counts["scanner"] != 1 || sums[0].Rates.Last1h != 4 {
|
||||
t.Fatalf("15d %+v", sums)
|
||||
}
|
||||
hub.SummariesFor(context.Background(), rg, "")
|
||||
if len(calls) != n+1 {
|
||||
t.Fatalf("on-demand windows must be cached: %v", calls[n:])
|
||||
}
|
||||
// a custom window goes as from/to
|
||||
now := time.Now().Unix()
|
||||
local := store.New(store.Config{Name: "hub", Retention: 720 * time.Hour})
|
||||
cr, err := local.ResolveRange("", fmt.Sprint(now-3*3600), "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cs := hub.SummariesFor(context.Background(), cr, "")
|
||||
if len(cs) != 1 || cs[0].Totals.Counts["exploit"] != 4 || !strings.Contains(calls[len(calls)-1], "from=") {
|
||||
t.Fatalf("custom %+v calls %v", cs, calls[len(calls)-1])
|
||||
}
|
||||
if tr := hub.TrafficFor(context.Background(), cr, "all", ""); len(tr) != 1 || tr[0].Requests != 1 {
|
||||
t.Fatalf("traffic %+v", tr)
|
||||
}
|
||||
if got := hub.IPDetail("6.6.6.6"); len(got) != 1 {
|
||||
t.Fatal("the 30 day export must carry the 10 day old address")
|
||||
}
|
||||
m := store.Merge("all", []store.Summary{local.Summary("24h"), sums[0]})
|
||||
if m.Rates.Last1h != 4 {
|
||||
t.Fatalf("merged rates %+v", m.Rates)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOldPeerStringRangeStillParses(t *testing.T) {
|
||||
var s store.Summary
|
||||
if err := json.Unmarshal([]byte(`{"range":"24h","host":"x"}`), &s); err != nil || s.Range.Name != "24h" {
|
||||
t.Fatalf("legacy range: %v %+v", err, s.Range)
|
||||
}
|
||||
if err := json.Unmarshal([]byte(`{"range":{"name":"7d","from":1,"to":2,"clipped":true}}`), &s); err != nil || !s.Range.Clipped {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerEventsAreRegisteredWithHostAndLocalID(t *testing.T) {
|
||||
var conns atomic.Int32
|
||||
srv := fakeStream(t, &conns, func(w http.ResponseWriter) {
|
||||
fmt.Fprint(w, ev(`{"id":999999,"ip":"6.6.6.6","cat":"exploit","host":"evil","ua":"sqlmap","fam":"vcs","tech":["T1190"],"flags":"SZ!"}`))
|
||||
})
|
||||
defer srv.Close()
|
||||
p, _ := fed.ParsePeer("edge=" + srv.URL)
|
||||
h := fed.NewHub([]fed.Peer{p}, "tok")
|
||||
local := store.New(store.Config{Name: "hub"})
|
||||
l, _ := evlog.Open(evlog.Options{Dir: t.TempDir() + "/events"})
|
||||
local.SetEventLog(l)
|
||||
h.OnLive = local.RecordPeerEvent
|
||||
ch, stop := h.Subscribe()
|
||||
defer stop()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer func() { cancel(); h.WaitStream() }()
|
||||
h.Stream(ctx)
|
||||
select {
|
||||
case e := <-ch:
|
||||
if e.Host != "edge" || e.ID == 0 || e.ID == 999999 || e.Flags != "S" {
|
||||
t.Fatalf("relayed %+v", e)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("no event")
|
||||
}
|
||||
pg, _ := local.QueryEvents(store.EventsQuery{From: time.Now().Unix() - 3600, To: time.Now().Unix() + 10, Host: "edge"})
|
||||
if len(pg.Events) != 1 || !strings.Contains(string(pg.Events[0]), `"host":"edge"`) {
|
||||
t.Fatalf("registry %v", pg.Events)
|
||||
}
|
||||
}
|
||||
@@ -1,120 +0,0 @@
|
||||
package fed_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/server"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
func logged(t *testing.T, name string) *store.Store {
|
||||
s := store.New(store.Config{Name: name, Version: "t", Retention: 720 * time.Hour})
|
||||
l, err := evlog.Open(evlog.Options{Dir: filepath.Join(t.TempDir(), "events")})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.SetEventLog(l)
|
||||
return s
|
||||
}
|
||||
|
||||
func TestHubMergesPeriodAndMetrics(t *testing.T) {
|
||||
const userTok, peerTok = "main-token-0123456789-abcdefghijklmnopqrs", "peer-secret-0123456789-abcdefghijklmnopqr"
|
||||
peer := logged(t, "hostinger")
|
||||
hubSt := logged(t, "oracle")
|
||||
now := time.Now()
|
||||
for i := 0; i < 4; i++ {
|
||||
peer.Ingest(core.Event{Time: now.Add(-time.Duration(i) * time.Minute), IP: "5.5.5.5", Cat: core.Exploit, Source: "traefik", Method: "GET", Path: "/.env", Status: 404, Domain: "p.example"})
|
||||
}
|
||||
hubSt.Ingest(core.Event{Time: now.Add(-time.Hour), IP: "6.6.6.6", Cat: core.Scanner, Source: "traefik", Method: "GET", Path: "/wp-login.php", Status: 404, Domain: "h.example"})
|
||||
// a copy of the peer's event relayed live to the hub must not be counted twice
|
||||
le := store.LiveEvent{FeedEvent: store.FeedEvent{T: now.Unix() - 30, IP: "5.5.5.5", Cat: "exploit", Source: "traefik", Host: "hostinger"}}
|
||||
hubSt.RecordPeerEvent(&le)
|
||||
|
||||
var peerCalls []string
|
||||
pinner := server.New(server.Options{Token: "other-token-0123456789-abcdefghijklmnopqrs", PeerTokens: []string{peerTok}, Version: "t", Store: peer})
|
||||
psrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
peerCalls = append(peerCalls, r.URL.Path)
|
||||
pinner.ServeHTTP(w, r)
|
||||
}))
|
||||
defer psrv.Close()
|
||||
p, _ := fed.ParsePeer("hostinger=" + psrv.URL)
|
||||
hub := fed.NewHub([]fed.Peer{p}, peerTok)
|
||||
hub.Refresh(context.Background())
|
||||
h := server.New(server.Options{Token: userTok, Version: "t", Store: hubSt, Hub: hub})
|
||||
get := func(path string) map[string]any {
|
||||
r := httptest.NewRequest("GET", path, nil)
|
||||
r.Header.Set("Authorization", "Bearer "+userTok)
|
||||
r.RemoteAddr = "198.51.100.1:1"
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("%s: %d %s", path, w.Code, w.Body)
|
||||
}
|
||||
var m map[string]any
|
||||
json.Unmarshal(w.Body.Bytes(), &m)
|
||||
return m
|
||||
}
|
||||
pd := get("/api/v1/period?range=24h")
|
||||
if pd["sessions_n"].(float64) != 2 || pd["events"].(float64) != 5 {
|
||||
t.Fatalf("merged period: sessions %v events %v (relayed copies must not double count)", pd["sessions_n"], pd["events"])
|
||||
}
|
||||
hosts := map[string]bool{}
|
||||
for _, s := range pd["sessions"].([]any) {
|
||||
hosts[s.(map[string]any)["hosts"].([]any)[0].(string)] = true
|
||||
}
|
||||
if !hosts["oracle"] || !hosts["hostinger"] {
|
||||
t.Fatalf("sessions must carry their host: %v", hosts)
|
||||
}
|
||||
if only := get("/api/v1/period?range=24h&host=hostinger"); only["sessions_n"].(float64) != 1 {
|
||||
t.Fatalf("one peer: %v", only["sessions_n"])
|
||||
}
|
||||
if loc := get("/api/v1/period?range=24h&host=oracle"); loc["sessions_n"].(float64) != 1 {
|
||||
t.Fatalf("local only: %v", loc["sessions_n"])
|
||||
}
|
||||
mt := get("/api/v1/metrics?range=24h")
|
||||
if v := mt["attacks_per_hour_24h"].(map[string]any)["value"].(float64); v < 0.2 || v > 0.3 { // 5 events / 24 h, rounded to 0.1
|
||||
t.Fatalf("merged attacks per hour: %v", v)
|
||||
}
|
||||
n := len(peerCalls)
|
||||
get("/api/v1/period?range=24h")
|
||||
for _, c := range peerCalls[n:] {
|
||||
if c == "/api/v1/peer/period" {
|
||||
t.Fatal("studies are cached for 30 s")
|
||||
}
|
||||
}
|
||||
// the peer route: only the peer token, never the user token
|
||||
for tok, want := range map[string]int{peerTok: 200, "other-token-0123456789-abcdefghijklmnopqrs": 401, "bad": 401} {
|
||||
r := httptest.NewRequest("GET", "/api/v1/peer/period?from=1&to=2", nil)
|
||||
r.Header.Set("Authorization", "Bearer "+tok)
|
||||
r.RemoteAddr = "198.51.100.1:1"
|
||||
w := httptest.NewRecorder()
|
||||
pinner.ServeHTTP(w, r)
|
||||
if tok == peerTok {
|
||||
r = httptest.NewRequest("GET", "/api/v1/peer/period?from="+itoa(now.Unix()-3600)+"&to="+itoa(now.Unix()), nil)
|
||||
r.Header.Set("Authorization", "Bearer "+tok)
|
||||
r.RemoteAddr = "198.51.100.1:1"
|
||||
w = httptest.NewRecorder()
|
||||
pinner.ServeHTTP(w, r)
|
||||
}
|
||||
if w.Code != want {
|
||||
t.Errorf("peer route with %q: %d, want %d", tok[:3], w.Code, want)
|
||||
}
|
||||
}
|
||||
// a hub that is offline for the peer still answers (local + relayed)
|
||||
psrv.Close()
|
||||
hub.Refresh(context.Background())
|
||||
if pd := get("/api/v1/period?range=24h"); pd["sessions_n"].(float64) < 1 {
|
||||
t.Fatal("must answer without the peer")
|
||||
}
|
||||
}
|
||||
|
||||
func itoa(n int64) string { b, _ := json.Marshal(n); return string(b) }
|
||||
@@ -0,0 +1,191 @@
|
||||
package hub
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
|
||||
)
|
||||
|
||||
// MaxQueue is the most commands kept per node; the oldest are dropped.
|
||||
const MaxQueue = 10000
|
||||
|
||||
// CmdQueue is the persisted command queue of one node (commands.json).
|
||||
type CmdQueue struct {
|
||||
mu sync.Mutex
|
||||
path string
|
||||
next uint64
|
||||
dropped uint64
|
||||
cmds []wire.Cmd
|
||||
dirty bool
|
||||
notify chan struct{} // closed and replaced on every enqueue
|
||||
stop chan struct{}
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
type queueFile struct {
|
||||
Next uint64 `json:"next"`
|
||||
Dropped uint64 `json:"dropped"`
|
||||
Cmds []wire.Cmd `json:"cmds"`
|
||||
}
|
||||
|
||||
// OpenQueue loads path (missing: empty) and starts the debounced writer; call
|
||||
// Close to flush. An empty path keeps the queue in memory only.
|
||||
func OpenQueue(path string) (*CmdQueue, error) {
|
||||
q := &CmdQueue{path: path, next: 1, notify: make(chan struct{}), stop: make(chan struct{}), done: make(chan struct{})}
|
||||
if path != "" {
|
||||
if b, err := os.ReadFile(path); err == nil {
|
||||
var f queueFile
|
||||
if err := json.Unmarshal(b, &f); err != nil {
|
||||
_ = os.Rename(path, path+".corrupt")
|
||||
} else {
|
||||
q.next, q.dropped, q.cmds = max(f.Next, 1), f.Dropped, f.Cmds
|
||||
for _, c := range q.cmds {
|
||||
q.next = max(q.next, c.Seq+1)
|
||||
}
|
||||
}
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
go q.writer()
|
||||
return q, nil
|
||||
}
|
||||
|
||||
func (q *CmdQueue) writer() {
|
||||
defer close(q.done)
|
||||
t := time.NewTicker(time.Second)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-q.stop:
|
||||
q.flush()
|
||||
return
|
||||
case <-t.C:
|
||||
q.flush()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (q *CmdQueue) flush() {
|
||||
if q.path == "" {
|
||||
return
|
||||
}
|
||||
q.mu.Lock()
|
||||
if !q.dirty {
|
||||
q.mu.Unlock()
|
||||
return
|
||||
}
|
||||
b, err := json.Marshal(queueFile{Next: q.next, Dropped: q.dropped, Cmds: q.cmds})
|
||||
q.dirty = false
|
||||
q.mu.Unlock()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_ = os.MkdirAll(filepath.Dir(q.path), 0o700)
|
||||
tmp := q.path + ".tmp"
|
||||
if os.WriteFile(tmp, b, 0o600) == nil {
|
||||
_ = os.Rename(tmp, q.path)
|
||||
}
|
||||
}
|
||||
|
||||
// Close flushes the queue and stops the writer.
|
||||
func (q *CmdQueue) Close() {
|
||||
select {
|
||||
case <-q.stop:
|
||||
default:
|
||||
close(q.stop)
|
||||
}
|
||||
<-q.done
|
||||
}
|
||||
|
||||
// Enqueue appends a command; it matches the signature of enforce.Config.Sink.
|
||||
func (q *CmdQueue) Enqueue(kind, line string) error {
|
||||
if !wire.ValidCmdLine(kind, line) {
|
||||
return errors.New("invalid command line")
|
||||
}
|
||||
q.mu.Lock()
|
||||
q.cmds = append(q.cmds, wire.Cmd{Seq: q.next, Kind: kind, Line: line})
|
||||
q.next++
|
||||
if len(q.cmds) > MaxQueue {
|
||||
n := len(q.cmds) - MaxQueue
|
||||
q.dropped += uint64(n)
|
||||
q.cmds = append([]wire.Cmd(nil), q.cmds[n:]...)
|
||||
}
|
||||
q.dirty = true
|
||||
old := q.notify
|
||||
q.notify = make(chan struct{})
|
||||
q.mu.Unlock()
|
||||
close(old)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Last is the highest queued sequence (0 when nothing was ever queued).
|
||||
func (q *CmdQueue) Last() uint64 {
|
||||
q.mu.Lock()
|
||||
defer q.mu.Unlock()
|
||||
return q.next - 1
|
||||
}
|
||||
|
||||
// Pending counts the queued commands after seq.
|
||||
func (q *CmdQueue) Pending(after uint64) int {
|
||||
q.mu.Lock()
|
||||
defer q.mu.Unlock()
|
||||
n := 0
|
||||
for _, c := range q.cmds {
|
||||
if c.Seq > after {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// Dropped counts the commands discarded by the size cap.
|
||||
func (q *CmdQueue) Dropped() uint64 {
|
||||
q.mu.Lock()
|
||||
defer q.mu.Unlock()
|
||||
return q.dropped
|
||||
}
|
||||
|
||||
func (q *CmdQueue) after(seq uint64) ([]wire.Cmd, chan struct{}, uint64) {
|
||||
q.mu.Lock()
|
||||
defer q.mu.Unlock()
|
||||
// the probe persisted everything up to seq: forget it
|
||||
i := 0
|
||||
for i < len(q.cmds) && q.cmds[i].Seq <= seq {
|
||||
i++
|
||||
}
|
||||
if i > 0 {
|
||||
q.cmds = append([]wire.Cmd(nil), q.cmds[i:]...)
|
||||
q.dirty = true
|
||||
}
|
||||
out := q.cmds
|
||||
if len(out) > 500 {
|
||||
out = out[:500]
|
||||
}
|
||||
return append([]wire.Cmd(nil), out...), q.notify, q.dropped
|
||||
}
|
||||
|
||||
// Wait returns the commands after seq at once, or holds up to wait for one.
|
||||
func (q *CmdQueue) Wait(ctx context.Context, seq uint64, wait time.Duration) wire.CmdResp {
|
||||
cmds, ch, dropped := q.after(seq)
|
||||
if len(cmds) == 0 && wait > 0 {
|
||||
t := time.NewTimer(wait)
|
||||
defer t.Stop()
|
||||
select {
|
||||
case <-ch:
|
||||
cmds, _, dropped = q.after(seq)
|
||||
case <-t.C:
|
||||
case <-ctx.Done():
|
||||
}
|
||||
}
|
||||
if cmds == nil {
|
||||
cmds = []wire.Cmd{}
|
||||
}
|
||||
return wire.CmdResp{Cmds: cmds, Dropped: dropped}
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
package hub
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
|
||||
)
|
||||
|
||||
// Authenticate checks Authorization: Bearer <token> and X-Urutau-Probe for a
|
||||
// registered, non-revoked probe and returns its name.
|
||||
func (m *Manager) Authenticate(r *http.Request) (string, bool) {
|
||||
name := r.Header.Get(wire.HeaderProbe)
|
||||
a := r.Header.Get("Authorization")
|
||||
if !strings.HasPrefix(a, "Bearer ") {
|
||||
m.Reg.Verify(name, "") // same work as a real check
|
||||
return "", false
|
||||
}
|
||||
if !m.Reg.Verify(name, strings.TrimSpace(a[7:])) {
|
||||
return "", false
|
||||
}
|
||||
return name, true
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, code int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.WriteHeader(code)
|
||||
json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
|
||||
func fail(w http.ResponseWriter, code int, msg string) {
|
||||
writeJSON(w, code, map[string]string{"error": msg})
|
||||
}
|
||||
|
||||
// node returns the ready node of an authenticated probe or answers 503.
|
||||
func (m *Manager) node(w http.ResponseWriter, name string) Node {
|
||||
n, err := m.Ensure(name)
|
||||
if err != nil {
|
||||
w.Header().Set("Retry-After", "5")
|
||||
fail(w, http.StatusServiceUnavailable, "node unavailable")
|
||||
return nil
|
||||
}
|
||||
if !n.Ready() {
|
||||
w.Header().Set("Retry-After", "5")
|
||||
fail(w, http.StatusServiceUnavailable, "node loading")
|
||||
return nil
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// Hello: POST /api/v1/probe/hello.
|
||||
func (m *Manager) Hello(w http.ResponseWriter, r *http.Request, name string) {
|
||||
var h wire.Hello
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 64<<10)).Decode(&h); err != nil {
|
||||
fail(w, http.StatusBadRequest, "invalid JSON")
|
||||
return
|
||||
}
|
||||
if h.Proto != wire.Proto {
|
||||
fail(w, http.StatusConflict, "incompatible protocol version")
|
||||
return
|
||||
}
|
||||
if h.Name != "" && h.Name != name {
|
||||
fail(w, http.StatusBadRequest, "name does not match the token")
|
||||
return
|
||||
}
|
||||
for _, s := range h.Sources {
|
||||
if !wire.ValidSource(s) {
|
||||
fail(w, http.StatusBadRequest, "unknown source")
|
||||
return
|
||||
}
|
||||
}
|
||||
n := m.node(w, name)
|
||||
if n == nil {
|
||||
return
|
||||
}
|
||||
if h.Location != nil && (h.Location.Lat < -90 || h.Location.Lat > 90 || h.Location.Lon < -180 || h.Location.Lon > 180) {
|
||||
h.Location = nil
|
||||
}
|
||||
h.Version = clip(h.Version, 32)
|
||||
h.Hostname = clip(h.Hostname, 64)
|
||||
c := m.conn(name)
|
||||
c.mu.Lock()
|
||||
c.lastSeen, c.version, c.hostname = m.Now().Unix(), h.Version, h.Hostname
|
||||
if h.LastSeq < c.ack {
|
||||
c.ack = h.LastSeq // a probe that lost its state restarts its numbering
|
||||
}
|
||||
ack := c.ack
|
||||
c.mu.Unlock()
|
||||
n.Hello(h)
|
||||
if rec, _ := m.Reg.Get(name); rec.Location != nil {
|
||||
n.SetLocation(rec.Location)
|
||||
} else if h.Location != nil {
|
||||
n.SetLocation(h.Location)
|
||||
}
|
||||
writeJSON(w, 200, wire.HelloResp{Proto: wire.Proto, HubVer: m.Version, Offsets: n.Offsets(), AckSeq: ack, FlushMS: 1000})
|
||||
}
|
||||
|
||||
func clip(s string, n int) string {
|
||||
if len(s) > n {
|
||||
s = s[:n]
|
||||
}
|
||||
return strings.ToValidUTF8(s, "")
|
||||
}
|
||||
|
||||
// Push: POST /api/v1/probe/push.
|
||||
func (m *Manager) Push(w http.ResponseWriter, r *http.Request, name string) {
|
||||
c := m.conn(name)
|
||||
if !c.busy.CompareAndSwap(false, true) {
|
||||
w.Header().Set("Retry-After", "1")
|
||||
fail(w, http.StatusTooManyRequests, "one push at a time")
|
||||
return
|
||||
}
|
||||
defer c.busy.Store(false)
|
||||
if m.infl.Add(1) > 16 {
|
||||
m.infl.Add(-1)
|
||||
w.Header().Set("Retry-After", "2")
|
||||
fail(w, http.StatusServiceUnavailable, "ingest busy")
|
||||
return
|
||||
}
|
||||
defer m.infl.Add(-1)
|
||||
n := m.node(w, name)
|
||||
if n == nil {
|
||||
return
|
||||
}
|
||||
raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, wire.MaxBodyBytes))
|
||||
if err != nil {
|
||||
var mb *http.MaxBytesError
|
||||
if errors.As(err, &mb) {
|
||||
fail(w, http.StatusRequestEntityTooLarge, "body too large")
|
||||
} else {
|
||||
fail(w, http.StatusBadRequest, "unreadable body")
|
||||
}
|
||||
return
|
||||
}
|
||||
if ce := strings.ToLower(r.Header.Get("Content-Encoding")); ce == "gzip" {
|
||||
zr, err := gzip.NewReader(bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
fail(w, http.StatusBadRequest, "invalid gzip")
|
||||
return
|
||||
}
|
||||
raw, err = io.ReadAll(io.LimitReader(zr, wire.MaxInflated+1))
|
||||
if err != nil {
|
||||
fail(w, http.StatusBadRequest, "invalid gzip")
|
||||
return
|
||||
}
|
||||
if len(raw) > wire.MaxInflated {
|
||||
fail(w, http.StatusRequestEntityTooLarge, "body too large")
|
||||
return
|
||||
}
|
||||
} else if ce != "" && ce != "identity" {
|
||||
fail(w, http.StatusBadRequest, "unsupported encoding")
|
||||
return
|
||||
}
|
||||
var b wire.Batch
|
||||
if err := json.Unmarshal(raw, &b); err != nil {
|
||||
fail(w, http.StatusBadRequest, "invalid JSON")
|
||||
return
|
||||
}
|
||||
if len(b.Lines) > wire.MaxLines {
|
||||
fail(w, http.StatusBadRequest, "too many lines")
|
||||
return
|
||||
}
|
||||
for i := range b.Lines {
|
||||
l := &b.Lines[i]
|
||||
if !wire.ValidSource(l.Src) || len(l.Text) > wire.MaxLine {
|
||||
fail(w, http.StatusBadRequest, "invalid line")
|
||||
return
|
||||
}
|
||||
if l.End.Offset < 0 {
|
||||
fail(w, http.StatusBadRequest, "invalid line")
|
||||
return
|
||||
}
|
||||
if !utf8.ValidString(l.Text) {
|
||||
l.Text = strings.ToValidUTF8(l.Text, "�")
|
||||
}
|
||||
}
|
||||
for _, f := range b.Files {
|
||||
if (f.Name != wire.FileContainers && f.Name != wire.FileResolv) || len(f.Data) > wire.MaxFileBytes {
|
||||
fail(w, http.StatusBadRequest, "invalid file")
|
||||
return
|
||||
}
|
||||
}
|
||||
now := m.Now()
|
||||
c.mu.Lock()
|
||||
c.lastSeen = now.Unix()
|
||||
if b.Sent > 0 {
|
||||
c.lagMS = max(0, now.UnixMilli()-b.Sent)
|
||||
}
|
||||
if b.Status != nil {
|
||||
c.status = *b.Status
|
||||
for _, s := range b.Status.Sources {
|
||||
if s.LastLine > c.lastLine {
|
||||
c.lastLine = s.LastLine
|
||||
}
|
||||
}
|
||||
}
|
||||
dup := false
|
||||
if b.Seq != 0 && b.Seq <= c.ack {
|
||||
dup = true
|
||||
}
|
||||
ack := c.ack
|
||||
c.mu.Unlock()
|
||||
if b.Status != nil {
|
||||
n.SetStatus(*b.Status, true)
|
||||
}
|
||||
resp := wire.PushResp{Ack: ack}
|
||||
if q := n.Queue(); q != nil {
|
||||
resp.PendCmd = q.Last()
|
||||
}
|
||||
switch {
|
||||
case b.Seq == 0: // heartbeat: status only
|
||||
case dup:
|
||||
resp.Dup = len(b.Lines)
|
||||
default:
|
||||
resp.Accepted, resp.Dup = n.Apply(b)
|
||||
c.mu.Lock()
|
||||
c.ack = b.Seq
|
||||
resp.Ack = b.Seq
|
||||
c.mu.Unlock()
|
||||
}
|
||||
writeJSON(w, 200, resp)
|
||||
}
|
||||
|
||||
// Commands: GET /api/v1/probe/commands?after=<seq>&wait=<s>.
|
||||
func (m *Manager) Commands(w http.ResponseWriter, r *http.Request, name string) {
|
||||
n := m.node(w, name)
|
||||
if n == nil {
|
||||
return
|
||||
}
|
||||
after, _ := strconv.ParseUint(r.URL.Query().Get("after"), 10, 64)
|
||||
wait, _ := strconv.Atoi(r.URL.Query().Get("wait"))
|
||||
wait = max(0, min(wait, wire.MaxWaitSec))
|
||||
c := m.conn(name)
|
||||
c.mu.Lock()
|
||||
c.lastSeen = m.Now().Unix()
|
||||
c.mu.Unlock()
|
||||
q := n.Queue()
|
||||
if q == nil {
|
||||
writeJSON(w, 200, wire.CmdResp{Cmds: []wire.Cmd{}})
|
||||
return
|
||||
}
|
||||
// the write timeout of the server must outlive the long poll
|
||||
_ = http.NewResponseController(w).SetWriteDeadline(time.Now().Add(time.Duration(wait+10) * time.Second))
|
||||
writeJSON(w, 200, q.Wait(r.Context(), after, time.Duration(wait)*time.Second))
|
||||
}
|
||||
@@ -0,0 +1,671 @@
|
||||
package hub_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/app"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/probeagent"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
|
||||
)
|
||||
|
||||
var quiet = slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
|
||||
func randTok() string {
|
||||
b := make([]byte, 24)
|
||||
rand.Read(b)
|
||||
return hex.EncodeToString(b)
|
||||
}
|
||||
|
||||
func cfgFor(dir string, mut func(*app.Config)) app.Config {
|
||||
c := app.Config{Bind: "127.0.0.1:0", Name: "oracle", DataDir: dir, GeoDir: filepath.Join(dir, "geo"), Ignore: app.DefaultIgnore,
|
||||
MonitorUA: app.DefaultMonitorUA, TrustedProxy: app.DefaultTrustedProxy, Retention: 168 * time.Hour, TorAuto: "off",
|
||||
EventsMax: "64MB", Enforce: "off", EnforceShare: "off", EnforceThreshold: 3, EnforceMaxPerMin: 60, Egress: "on", PeerBlocklist: "on"}
|
||||
if mut != nil {
|
||||
mut(&c)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// hubProc is a hub on a fixed address that can be stopped and started again
|
||||
// over the same data directory (a process restart).
|
||||
type hubProc struct {
|
||||
t *testing.T
|
||||
cfg app.Config
|
||||
tok string
|
||||
addr string
|
||||
cancel context.CancelFunc
|
||||
hub *app.Hub
|
||||
srv *http.Server
|
||||
}
|
||||
|
||||
func newAddr(t *testing.T) string {
|
||||
l, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a := l.Addr().String()
|
||||
l.Close()
|
||||
return a
|
||||
}
|
||||
|
||||
func (p *hubProc) start() {
|
||||
p.t.Helper()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
p.cancel = cancel
|
||||
h, err := app.NewHub(ctx, p.cfg, p.tok, quiet)
|
||||
if err != nil {
|
||||
p.t.Fatal(err)
|
||||
}
|
||||
p.hub = h
|
||||
var ln net.Listener
|
||||
for i := 0; i < 50; i++ {
|
||||
if ln, err = net.Listen("tcp", p.addr); err == nil {
|
||||
break
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
if err != nil {
|
||||
p.t.Fatal(err)
|
||||
}
|
||||
p.srv = &http.Server{Handler: h.Handler}
|
||||
go p.srv.Serve(ln)
|
||||
}
|
||||
|
||||
func (p *hubProc) stop() {
|
||||
p.srv.Close()
|
||||
p.cancel()
|
||||
p.hub.Wait()
|
||||
}
|
||||
|
||||
func (p *hubProc) get(path string) (int, []byte) {
|
||||
req, _ := http.NewRequest("GET", "http://"+p.addr+path, nil)
|
||||
req.Header.Set("Authorization", "Bearer "+p.tok)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
p.t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
return resp.StatusCode, b
|
||||
}
|
||||
|
||||
func (p *hubProc) json(path string, v any) {
|
||||
p.t.Helper()
|
||||
code, b := p.get(path)
|
||||
if code != 200 {
|
||||
p.t.Fatalf("%s: %d %s", path, code, b)
|
||||
}
|
||||
if err := json.Unmarshal(b, v); err != nil {
|
||||
p.t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (p *hubProc) send(method, path string, body any) (int, []byte) {
|
||||
b, _ := json.Marshal(body)
|
||||
req, _ := http.NewRequest(method, "http://"+p.addr+path, bytes.NewReader(b))
|
||||
req.Header.Set("Authorization", "Bearer "+p.tok)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
p.t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
out, _ := io.ReadAll(resp.Body)
|
||||
return resp.StatusCode, out
|
||||
}
|
||||
|
||||
func waitFor(t *testing.T, what string, d time.Duration, f func() bool) {
|
||||
t.Helper()
|
||||
end := time.Now().Add(d)
|
||||
for time.Now().Before(end) {
|
||||
if f() {
|
||||
return
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
t.Fatalf("timeout: %s", what)
|
||||
}
|
||||
|
||||
type probe struct {
|
||||
name, dir, traefik, auth, f2b, egress, decisions, unban string
|
||||
cancel context.CancelFunc
|
||||
done chan error
|
||||
}
|
||||
|
||||
func newProbe(t *testing.T, name string) *probe {
|
||||
d := t.TempDir()
|
||||
p := &probe{name: name, dir: d, traefik: filepath.Join(d, "access.log"), auth: filepath.Join(d, "auth.log"), f2b: filepath.Join(d, "f2b.log"),
|
||||
egress: filepath.Join(d, "egress.log"), decisions: filepath.Join(d, "enf", "decisions.log"), unban: filepath.Join(d, "enf", "unban.log")}
|
||||
os.MkdirAll(filepath.Join(d, "enf"), 0o755)
|
||||
for _, f := range []string{p.traefik, p.auth, p.f2b, p.egress} {
|
||||
os.WriteFile(f, nil, 0o644)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func (p *probe) run(t *testing.T, hubURL, token string, spool int64) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
p.cancel, p.done = cancel, make(chan error, 1)
|
||||
c := probeagent.Config{Hub: hubURL, Name: p.name, Token: token, StateDir: filepath.Join(p.dir, "state"), SpoolMax: spool,
|
||||
Paths: map[string]string{wire.SrcTraefik: p.traefik, wire.SrcAuth: p.auth, wire.SrcFail2ban: p.f2b, wire.SrcEgress: p.egress},
|
||||
DecisionsLog: p.decisions, UnbanLog: p.unban, Location: &wire.Location{Lat: -23.5, Lon: -46.6, Label: p.name}, Version: "test"}
|
||||
go func() { p.done <- probeagent.Run(ctx, c, quiet) }()
|
||||
t.Cleanup(p.stop)
|
||||
}
|
||||
|
||||
func (p *probe) stop() {
|
||||
if p.cancel != nil {
|
||||
p.cancel()
|
||||
select {
|
||||
case <-p.done:
|
||||
case <-time.After(5 * time.Second):
|
||||
}
|
||||
p.cancel = nil
|
||||
}
|
||||
}
|
||||
|
||||
func appendTo(t *testing.T, path, text string) {
|
||||
f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0o644)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
f.WriteString(text)
|
||||
}
|
||||
|
||||
func traefikLine(ip string, i int, status int, path string) string {
|
||||
ua := "Mozilla/5.0"
|
||||
if status == 404 { // an attack: path traversal from a scanner
|
||||
ua, path = "nuclei", "/index.php?file=../../etc/passwd&x="
|
||||
}
|
||||
return fmt.Sprintf(`{"ClientHost":"%s","DownstreamStatus":%d,"RequestHost":"example.org","RequestMethod":"GET","RequestPath":"%s?n=%d","StartUTC":"%s","request_User-Agent":"%s"}`+"\n",
|
||||
ip, status, path, i, time.Now().UTC().Format(time.RFC3339Nano), ua)
|
||||
}
|
||||
|
||||
type summary struct {
|
||||
Host string `json:"host"`
|
||||
Totals struct {
|
||||
Requests uint64 `json:"requests"`
|
||||
} `json:"totals"`
|
||||
Hosts []struct {
|
||||
Name string `json:"name"`
|
||||
Location *struct {
|
||||
Label string `json:"label"`
|
||||
} `json:"location"`
|
||||
} `json:"hosts"`
|
||||
}
|
||||
|
||||
func requests(t *testing.T, p *hubProc, host string) uint64 {
|
||||
var s summary
|
||||
p.json("/api/v1/summary?range=24h&host="+host, &s)
|
||||
return s.Totals.Requests
|
||||
}
|
||||
|
||||
type probesResp struct {
|
||||
Probes []struct {
|
||||
Name string `json:"name"`
|
||||
Connected bool `json:"connected"`
|
||||
Dropped uint64 `json:"dropped"`
|
||||
Sources []wire.SourceStatus `json:"sources"`
|
||||
Location *wire.Location `json:"location"`
|
||||
LastLine int64 `json:"last_line"`
|
||||
} `json:"probes"`
|
||||
}
|
||||
|
||||
func TestTwoProbesEndToEnd(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
hp := &hubProc{t: t, tok: randTok(), addr: newAddr(t), cfg: cfgFor(dir, func(c *app.Config) { c.Enforce = "on"; c.EnforceShare = "off" })}
|
||||
hp.start()
|
||||
defer func() { hp.stop() }()
|
||||
url := "http://" + hp.addr
|
||||
|
||||
// create the probes through the admin API (token shown once)
|
||||
tokens := map[string]string{}
|
||||
for _, n := range []string{"oracle", "hostinger"} {
|
||||
code, b := hp.send("POST", "/api/v1/probes", map[string]string{"name": n})
|
||||
var o struct{ Name, Token string }
|
||||
if code != 201 || json.Unmarshal(b, &o) != nil || !strings.HasPrefix(o.Token, "urp_") || len(o.Token) != 47 {
|
||||
t.Fatalf("create %s: %d %s", n, code, b)
|
||||
}
|
||||
tokens[n] = o.Token
|
||||
}
|
||||
if code, _ := hp.send("POST", "/api/v1/probes", map[string]string{"name": "oracle"}); code != 409 {
|
||||
t.Fatalf("duplicate probe: %d", code)
|
||||
}
|
||||
// probes.json holds hashes only
|
||||
raw, err := os.ReadFile(filepath.Join(dir, "probes.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tk := range tokens {
|
||||
if strings.Contains(string(raw), tk) {
|
||||
t.Fatal("probes.json contains a token")
|
||||
}
|
||||
}
|
||||
if fi, _ := os.Stat(filepath.Join(dir, "probes.json")); fi.Mode().Perm() != 0o600 {
|
||||
t.Fatalf("probes.json mode %v", fi.Mode())
|
||||
}
|
||||
|
||||
po, ph := newProbe(t, "oracle"), newProbe(t, "hostinger")
|
||||
po.run(t, url, tokens["oracle"], 0)
|
||||
ph.run(t, url, tokens["hostinger"], 0)
|
||||
waitFor(t, "both probes connected", 15*time.Second, func() bool {
|
||||
var r probesResp
|
||||
hp.json("/api/v1/probes", &r)
|
||||
n := 0
|
||||
for _, x := range r.Probes {
|
||||
if x.Connected {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n == 2
|
||||
})
|
||||
|
||||
// every source of both hosts
|
||||
for i := 0; i < 20; i++ {
|
||||
appendTo(t, po.traefik, traefikLine("45.94.31.7", i, 404, "/wp-login.php"))
|
||||
}
|
||||
for i := 0; i < 7; i++ {
|
||||
appendTo(t, ph.traefik, traefikLine("45.94.31.9", i, 404, "/wp-login.php"))
|
||||
}
|
||||
appendTo(t, ph.auth, time.Now().UTC().Format("2006-01-02T15:04:05.000000+00:00")+" hostinger sshd[123]: Failed password for root from 45.94.31.11 port 22 ssh2\n")
|
||||
appendTo(t, ph.f2b, time.Now().Format("2006-01-02 15:04:05,000")+" fail2ban.actions [1]: NOTICE [sshd] Ban 45.94.31.11\n")
|
||||
appendTo(t, ph.egress, time.Now().UTC().Format("2006-01-02T15:04:05+00:00")+" hostinger kernel: URUTAU-EGRESS: IN=br-1 OUT=enp0s6 SRC=10.0.3.5 DST=93.184.216.34 PROTO=TCP SPT=40000 DPT=443 SYN\n")
|
||||
waitFor(t, "events in the right node", 15*time.Second, func() bool {
|
||||
return requests(t, hp, "oracle") >= 20 && requests(t, hp, "hostinger") >= 7
|
||||
})
|
||||
if got := requests(t, hp, "oracle"); got != 20 {
|
||||
t.Fatalf("oracle requests %d", got)
|
||||
}
|
||||
if got := requests(t, hp, "hostinger"); got != 7 {
|
||||
t.Fatalf("hostinger requests %d", got)
|
||||
}
|
||||
var s summary
|
||||
hp.json("/api/v1/summary?range=24h&host=hostinger", &s)
|
||||
if s.Host != "hostinger" {
|
||||
t.Fatalf("host %q", s.Host)
|
||||
}
|
||||
// per-node data directories
|
||||
if _, err := os.Stat(filepath.Join(dir, "probes", "hostinger")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// live: the events carry the location of their probe
|
||||
waitFor(t, "live location", 10*time.Second, func() bool {
|
||||
var r struct {
|
||||
Events []struct {
|
||||
Host string `json:"host"`
|
||||
Dst *struct {
|
||||
Label string `json:"label"`
|
||||
} `json:"dst"`
|
||||
} `json:"events"`
|
||||
}
|
||||
code, b := hp.get("/api/v1/live/recent?n=100")
|
||||
if code != 200 || json.Unmarshal(b, &r) != nil {
|
||||
// the payload may be a bare array
|
||||
var arr []struct {
|
||||
Host string `json:"host"`
|
||||
Dst *struct {
|
||||
Label string `json:"label"`
|
||||
} `json:"dst"`
|
||||
}
|
||||
if json.Unmarshal(b, &arr) != nil {
|
||||
return false
|
||||
}
|
||||
for _, e := range arr {
|
||||
if e.Host == "hostinger" && e.Dst != nil && e.Dst.Label == "hostinger" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
for _, e := range r.Events {
|
||||
if e.Host == "hostinger" && e.Dst != nil && e.Dst.Label == "hostinger" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
})
|
||||
|
||||
// enforce: the decision reaches decisions.log of the right probe only
|
||||
waitFor(t, "decision on the probe of the attacked host", 20*time.Second, func() bool {
|
||||
b, _ := os.ReadFile(ph.decisions)
|
||||
return strings.Contains(string(b), "ip=45.94.31.9") || strings.Contains(string(b), "ip=45.94.31.7")
|
||||
})
|
||||
if b, _ := os.ReadFile(po.decisions); strings.Contains(string(b), "45.94.31.9") {
|
||||
t.Fatal("a decision of hostinger leaked to the oracle probe")
|
||||
}
|
||||
// unban through the API for one host
|
||||
if code, b := hp.send("POST", "/api/v1/enforce/unban", map[string]any{"ip": "203.0.113.50", "allow_s": 3600, "host": "hostinger"}); code != 200 {
|
||||
t.Fatalf("unban: %d %s", code, b)
|
||||
}
|
||||
waitFor(t, "unban.log", 10*time.Second, func() bool {
|
||||
b, _ := os.ReadFile(ph.unban)
|
||||
return strings.Contains(string(b), "unban ip=203.0.113.50 allow=3600")
|
||||
})
|
||||
if _, err := os.Stat(po.unban); err == nil {
|
||||
t.Fatal("the unban of one host reached the other probe")
|
||||
}
|
||||
|
||||
// hub down: 1000 lines written meanwhile arrive exactly once after the restart
|
||||
before := requests(t, hp, "oracle")
|
||||
hp.stop()
|
||||
var sb strings.Builder
|
||||
for i := 0; i < 1000; i++ {
|
||||
sb.WriteString(traefikLine(fmt.Sprintf("45.94.32.%d", i%200+1), 1000+i, 200, "/page"))
|
||||
}
|
||||
appendTo(t, po.traefik, sb.String())
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
hp.start()
|
||||
waitFor(t, "1000 lines after the restart", 30*time.Second, func() bool { return requests(t, hp, "oracle") >= before+1000 })
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
if got := requests(t, hp, "oracle"); got != before+1000 {
|
||||
t.Fatalf("after the restart: %d requests, want %d (no gap, no duplicate)", got, before+1000)
|
||||
}
|
||||
|
||||
// revoke: 401 afterwards, data stays
|
||||
po.stop()
|
||||
if code, _ := hp.send("DELETE", "/api/v1/probes/oracle", nil); code != 200 {
|
||||
t.Fatalf("revoke: %d", code)
|
||||
}
|
||||
req, _ := http.NewRequest("POST", url+wire.PathHello, strings.NewReader(`{"proto":1,"name":"oracle"}`))
|
||||
req.Header.Set("Authorization", "Bearer "+tokens["oracle"])
|
||||
req.Header.Set(wire.HeaderProbe, "oracle")
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil || resp.StatusCode != 401 {
|
||||
t.Fatalf("revoked token: %v %v", resp, err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
if got := requests(t, hp, "oracle"); got != before+1000 {
|
||||
t.Fatalf("data lost after revoke: %d", got)
|
||||
}
|
||||
// the old peer routes are gone
|
||||
for _, p := range []string{"/api/v1/peer/export", "/api/v1/peer/stream", "/api/v1/peer/decisions"} {
|
||||
if code, _ := hp.get(p); code != 404 {
|
||||
t.Errorf("%s: %d, want 404", p, code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnforceShareReachesBothProbes(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
hp := &hubProc{t: t, tok: randTok(), addr: newAddr(t), cfg: cfgFor(dir, func(c *app.Config) { c.Enforce = "on"; c.EnforceShare = "on" })}
|
||||
hp.start()
|
||||
defer hp.stop()
|
||||
url := "http://" + hp.addr
|
||||
po, ph := newProbe(t, "oracle"), newProbe(t, "hostinger")
|
||||
for _, p := range []*probe{po, ph} {
|
||||
tok, err := hp.hub.Mgr.Create(p.name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p.run(t, url, tok, 0)
|
||||
}
|
||||
for i := 0; i < 30; i++ {
|
||||
appendTo(t, ph.traefik, traefikLine("45.94.31.9", i, 404, "/wp-login.php"))
|
||||
}
|
||||
waitFor(t, "decision on the origin probe", 20*time.Second, func() bool {
|
||||
b, _ := os.ReadFile(ph.decisions)
|
||||
return strings.Contains(string(b), "ip=45.94.31.9")
|
||||
})
|
||||
// the sharing loop runs every 30 s: relay now through the engines
|
||||
for _, n := range hp.hub.Mgr.Nodes() {
|
||||
_ = n
|
||||
}
|
||||
// the relay runs every 30 s; the receiver applies its own policy, and an
|
||||
// address its own probe never saw attacking is first held "peer_unconfirmed"
|
||||
waitFor(t, "shared decision on the other probe", 60*time.Second, func() bool {
|
||||
if b, _ := os.ReadFile(po.decisions); strings.Contains(string(b), "src=peer:hostinger") {
|
||||
return true
|
||||
}
|
||||
return hp.hub.Primary.Enf.Report(0).Counts.Skipped["peer_unconfirmed"] > 0
|
||||
})
|
||||
}
|
||||
|
||||
func TestSpoolOverflowIsReportedAsDropped(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
hp := &hubProc{t: t, tok: randTok(), addr: newAddr(t), cfg: cfgFor(dir, nil)}
|
||||
// the hub is not up yet: create the registry offline and start the probe against a dead address
|
||||
hp.start()
|
||||
tok, _ := hp.hub.Mgr.Create("hostinger")
|
||||
hp.stop()
|
||||
p := newProbe(t, "hostinger")
|
||||
p.run(t, "http://"+hp.addr, tok, 4096)
|
||||
for round := 0; round < 12; round++ {
|
||||
var sb strings.Builder
|
||||
for i := 0; i < 100; i++ {
|
||||
sb.WriteString(traefikLine("45.94.33.1", round*100+i, 200, "/spool"))
|
||||
}
|
||||
appendTo(t, p.traefik, sb.String())
|
||||
time.Sleep(1200 * time.Millisecond)
|
||||
}
|
||||
hp.start()
|
||||
defer hp.stop()
|
||||
waitFor(t, "dropped reported", 30*time.Second, func() bool {
|
||||
var r probesResp
|
||||
hp.json("/api/v1/probes", &r)
|
||||
for _, x := range r.Probes {
|
||||
if x.Name == "hostinger" && x.Dropped > 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
})
|
||||
}
|
||||
|
||||
func TestIngestLimitsAndDedup(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
hp := &hubProc{t: t, tok: randTok(), addr: newAddr(t), cfg: cfgFor(dir, nil)}
|
||||
hp.start()
|
||||
defer hp.stop()
|
||||
tok, _ := hp.hub.Mgr.Create("hostinger")
|
||||
do := func(path string, body []byte, gz bool) int {
|
||||
req, _ := http.NewRequest("POST", "http://"+hp.addr+path, bytes.NewReader(body))
|
||||
req.Header.Set("Authorization", "Bearer "+tok)
|
||||
req.Header.Set(wire.HeaderProbe, "hostinger")
|
||||
if gz {
|
||||
req.Header.Set("Content-Encoding", "gzip")
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
io.Copy(io.Discard, resp.Body)
|
||||
return resp.StatusCode
|
||||
}
|
||||
push := func(b wire.Batch) (int, wire.PushResp) {
|
||||
raw, _ := json.Marshal(b)
|
||||
req, _ := http.NewRequest("POST", "http://"+hp.addr+wire.PathPush, bytes.NewReader(raw))
|
||||
req.Header.Set("Authorization", "Bearer "+tok)
|
||||
req.Header.Set(wire.HeaderProbe, "hostinger")
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
var pr wire.PushResp
|
||||
json.NewDecoder(resp.Body).Decode(&pr)
|
||||
return resp.StatusCode, pr
|
||||
}
|
||||
line := func(i int, inode uint64, off int64) wire.Line {
|
||||
return wire.Line{Src: wire.SrcTraefik, Text: strings.TrimSpace(traefikLine("45.94.34.1", i, 200, "/d")), End: wire.Pos{Inode: inode, Offset: off}}
|
||||
}
|
||||
if code, r := push(wire.Batch{Seq: 1, Lines: []wire.Line{line(1, 7, 100), line(2, 7, 200)}}); code != 200 || r.Accepted != 2 {
|
||||
t.Fatalf("first: %d %+v", code, r)
|
||||
}
|
||||
// same positions again under a new seq: duplicates by offset
|
||||
if code, r := push(wire.Batch{Seq: 2, Lines: []wire.Line{line(1, 7, 100), line(2, 7, 200), line(3, 7, 300)}}); code != 200 || r.Dup != 2 || r.Accepted != 1 {
|
||||
t.Fatalf("dedup by offset: %d %+v", code, r)
|
||||
}
|
||||
// a new inode with a smaller offset is new data (rotation)
|
||||
if code, r := push(wire.Batch{Seq: 3, Lines: []wire.Line{line(4, 8, 50)}}); code != 200 || r.Accepted != 1 {
|
||||
t.Fatalf("new inode: %d %+v", code, r)
|
||||
}
|
||||
// the same seq again is acknowledged without applying
|
||||
if code, r := push(wire.Batch{Seq: 3, Lines: []wire.Line{line(5, 8, 500)}}); code != 200 || r.Ack != 3 || r.Accepted != 0 {
|
||||
t.Fatalf("idempotent seq: %d %+v", code, r)
|
||||
}
|
||||
// limits
|
||||
big := make([]wire.Line, wire.MaxLines+1)
|
||||
for i := range big {
|
||||
big[i] = wire.Line{Src: wire.SrcTraefik, Text: "x", End: wire.Pos{Inode: 9, Offset: int64(i + 1)}}
|
||||
}
|
||||
if code, _ := push(wire.Batch{Seq: 10, Lines: big}); code != 400 {
|
||||
t.Fatalf("too many lines: %d", code)
|
||||
}
|
||||
if code, _ := push(wire.Batch{Seq: 11, Lines: []wire.Line{{Src: "bogus", Text: "x"}}}); code != 400 {
|
||||
t.Fatalf("invalid source: %d", code)
|
||||
}
|
||||
if code := do(wire.PathPush, bytes.Repeat([]byte("a"), wire.MaxBodyBytes+10), false); code != 413 {
|
||||
t.Fatalf("raw body too big: %d", code)
|
||||
}
|
||||
var zb bytes.Buffer
|
||||
zw := gzip.NewWriter(&zb)
|
||||
zw.Write(bytes.Repeat([]byte(" "), wire.MaxInflated+10))
|
||||
zw.Close()
|
||||
if code := do(wire.PathPush, zb.Bytes(), true); code != 413 {
|
||||
t.Fatalf("inflated body too big: %d", code)
|
||||
}
|
||||
// hello returns the committed offsets
|
||||
hb, _ := json.Marshal(wire.Hello{Proto: wire.Proto, Name: "hostinger", Version: "t"})
|
||||
req, _ := http.NewRequest("POST", "http://"+hp.addr+wire.PathHello, bytes.NewReader(hb))
|
||||
req.Header.Set("Authorization", "Bearer "+tok)
|
||||
req.Header.Set(wire.HeaderProbe, "hostinger")
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var hr wire.HelloResp
|
||||
json.NewDecoder(resp.Body).Decode(&hr)
|
||||
resp.Body.Close()
|
||||
if hr.Offsets[wire.SrcTraefik].Inode != 8 || hr.Offsets[wire.SrcTraefik].Offset != 50 {
|
||||
t.Fatalf("hello offsets: %+v", hr.Offsets)
|
||||
}
|
||||
// incompatible protocol
|
||||
hb, _ = json.Marshal(wire.Hello{Proto: 99, Name: "hostinger"})
|
||||
if code := do(wire.PathHello, hb, false); code != 409 {
|
||||
t.Fatalf("protocol: %d", code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOldPeerVariablesRefuseToStart(t *testing.T) {
|
||||
t.Setenv("URUTAU_PEERS", "hostinger=https://x.example.org")
|
||||
t.Setenv("URUTAU_TOKEN", randTok())
|
||||
c := cfgFor(t.TempDir(), func(c *app.Config) { c.NoAuth = false })
|
||||
err := app.Serve(c)
|
||||
if err == nil || !strings.Contains(err.Error(), "URUTAU_PEERS") || !strings.Contains(err.Error(), "migration-2.0") {
|
||||
t.Fatalf("Serve with URUTAU_PEERS: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// copyTree copies a directory (fixtures are read-only inputs).
|
||||
func copyTree(t *testing.T, from, to string) {
|
||||
filepath.Walk(from, func(p string, info os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rel, _ := filepath.Rel(from, p)
|
||||
dst := filepath.Join(to, rel)
|
||||
if info.IsDir() {
|
||||
return os.MkdirAll(dst, 0o755)
|
||||
}
|
||||
b, err := os.ReadFile(p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(dst, b, 0o644)
|
||||
})
|
||||
}
|
||||
|
||||
var fixture = filepath.Join("..", "app", "testdata", "hostinger-1.6")
|
||||
|
||||
func TestPrimaryLoads16DataDirWithSameCounts(t *testing.T) {
|
||||
if _, err := os.Stat(fixture); err != nil {
|
||||
t.Skip("fixture of the 1.6 data directory missing")
|
||||
}
|
||||
dir := t.TempDir()
|
||||
copyTree(t, fixture, dir)
|
||||
want, err := app.CountDir(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hp := &hubProc{t: t, tok: randTok(), addr: newAddr(t), cfg: cfgFor(dir, func(c *app.Config) { c.Name = "hostinger" })}
|
||||
hp.start()
|
||||
defer hp.stop()
|
||||
var ips struct {
|
||||
Total int `json:"total"`
|
||||
}
|
||||
hp.json("/api/v1/ips?range=30d&per=200", &ips)
|
||||
if want.IPs == 0 || hp.hub.Primary.St.IPCount() != want.IPs {
|
||||
t.Fatalf("IPs: node %d, directory %d", hp.hub.Primary.St.IPCount(), want.IPs)
|
||||
}
|
||||
var inc struct {
|
||||
Total int `json:"total"`
|
||||
}
|
||||
hp.json("/api/v1/incidents?per_page=100", &inc)
|
||||
if inc.Total != want.Incidents {
|
||||
t.Fatalf("incidents: api %d, directory %d", inc.Total, want.Incidents)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportedHostIncidentWithComments(t *testing.T) {
|
||||
if _, err := os.Stat(fixture); err != nil {
|
||||
t.Skip("fixture of the 1.6 data directory missing")
|
||||
}
|
||||
dir := t.TempDir()
|
||||
rep, err := app.Import(fixture, dir, "hostinger", app.ImportOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hp := &hubProc{t: t, tok: randTok(), addr: newAddr(t), cfg: cfgFor(dir, nil)}
|
||||
hp.start()
|
||||
defer hp.stop()
|
||||
for _, path := range []string{"/api/v1/incidents/hostinger%2FINC-2", "/api/v1/incidents/hostinger/INC-2", "/api/v1/incidents/INC-2?host=hostinger"} {
|
||||
var tk struct {
|
||||
ID string `json:"id"`
|
||||
Host string `json:"host"`
|
||||
Comments []any `json:"comments"`
|
||||
}
|
||||
hp.json(path, &tk)
|
||||
if tk.ID != "hostinger/INC-2" || tk.Host != "hostinger" || len(tk.Comments) != 2 {
|
||||
t.Fatalf("%s: %+v", path, tk)
|
||||
}
|
||||
}
|
||||
// the list qualifies the ids and counts the imported tickets
|
||||
var list struct {
|
||||
Total int `json:"total"`
|
||||
Items []struct {
|
||||
ID string `json:"id"`
|
||||
} `json:"items"`
|
||||
}
|
||||
hp.json("/api/v1/incidents?host=hostinger", &list)
|
||||
if list.Total != rep.Incidents || len(list.Items) == 0 || !strings.HasPrefix(list.Items[0].ID, "hostinger/INC-") {
|
||||
t.Fatalf("list: %+v (imported %d)", list, rep.Incidents)
|
||||
}
|
||||
// and the node serves the imported IPs under its own host
|
||||
var s summary
|
||||
hp.json("/api/v1/summary?range=30d&host=hostinger", &s)
|
||||
if s.Host != "hostinger" {
|
||||
t.Fatalf("summary host %q", s.Host)
|
||||
}
|
||||
var mu sync.Mutex
|
||||
mu.Lock()
|
||||
mu.Unlock()
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
package hub
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
|
||||
)
|
||||
|
||||
// Node is one probe's data seen from the ingest layer (implemented by the app).
|
||||
type Node interface {
|
||||
Name() string
|
||||
// Ready is false while the node still loads its snapshot.
|
||||
Ready() bool
|
||||
// Offsets are the hub-committed positions, keyed by wire source name.
|
||||
Offsets() map[string]wire.Pos
|
||||
// Apply commits a batch under the node's commit mutex.
|
||||
Apply(b wire.Batch) (accepted, dup int)
|
||||
// Hello tells the node what the probe announced (sources, location).
|
||||
Hello(h wire.Hello)
|
||||
// Queue is the command queue of the node.
|
||||
Queue() *CmdQueue
|
||||
// SetStatus hands over the last status the probe reported.
|
||||
SetStatus(st wire.Status, connected bool)
|
||||
// SetLocation changes the location events of this node point to.
|
||||
SetLocation(l *wire.Location)
|
||||
}
|
||||
|
||||
// Factory builds the node of a probe.
|
||||
type Factory func(name string, primary bool, rec Probe) (Node, error)
|
||||
|
||||
// Update is the body of PUT /api/v1/probes/{name}.
|
||||
type Update struct {
|
||||
Location *wire.Location `json:"location"`
|
||||
Egress Egress `json:"egress"`
|
||||
}
|
||||
|
||||
// ProbeInfo is one row of GET /api/v1/probes.
|
||||
type ProbeInfo struct {
|
||||
Name string `json:"name"`
|
||||
Primary bool `json:"primary"`
|
||||
Registered bool `json:"registered"`
|
||||
Revoked bool `json:"revoked"`
|
||||
Created int64 `json:"created,omitempty"`
|
||||
Connected bool `json:"connected"`
|
||||
LastSeen int64 `json:"last_seen"`
|
||||
LastLine int64 `json:"last_line"`
|
||||
LagMS int64 `json:"lag_ms"`
|
||||
Version string `json:"version,omitempty"`
|
||||
Hostname string `json:"hostname,omitempty"`
|
||||
Dropped uint64 `json:"dropped"`
|
||||
Spool int64 `json:"spool"`
|
||||
SpoolFiles int `json:"spool_files"`
|
||||
CmdPending int `json:"cmd_pending"`
|
||||
CmdDropped uint64 `json:"cmd_dropped"`
|
||||
CmdErrors uint64 `json:"cmd_errors"`
|
||||
Uptime int64 `json:"uptime"`
|
||||
RSS uint64 `json:"rss"`
|
||||
Sources []wire.SourceStatus `json:"sources"`
|
||||
Location *wire.Location `json:"location,omitempty"`
|
||||
Egress Egress `json:"egress"`
|
||||
}
|
||||
|
||||
type conn struct {
|
||||
mu sync.Mutex
|
||||
lastSeen int64
|
||||
lastLine int64
|
||||
lagMS int64
|
||||
version string
|
||||
hostname string
|
||||
status wire.Status
|
||||
ack uint64
|
||||
busy atomic.Bool
|
||||
}
|
||||
|
||||
// Manager owns the registry and the nodes.
|
||||
type Manager struct {
|
||||
Dir string // data directory (primary node lives in its root)
|
||||
Primary string
|
||||
Version string
|
||||
Reg *Registry
|
||||
Make Factory
|
||||
Log *slog.Logger
|
||||
Now func() time.Time
|
||||
|
||||
mu sync.Mutex
|
||||
nodes map[string]Node
|
||||
conns map[string]*conn
|
||||
infl atomic.Int32
|
||||
}
|
||||
|
||||
// NewManager opens probes.json in dir and returns a manager; call Load to
|
||||
// create the nodes.
|
||||
func NewManager(dir, primary, version string, mk Factory, log *slog.Logger) (*Manager, error) {
|
||||
reg, err := OpenRegistry(filepath.Join(dir, "probes.json"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if log == nil {
|
||||
log = slog.Default()
|
||||
}
|
||||
return &Manager{Dir: dir, Primary: primary, Version: version, Reg: reg, Make: mk, Log: log, Now: time.Now,
|
||||
nodes: map[string]Node{}, conns: map[string]*conn{}}, nil
|
||||
}
|
||||
|
||||
// Load creates the primary node, one node per registered probe and one per
|
||||
// directory in probes/ (imported data), so every data set is served at once.
|
||||
func (m *Manager) Load() error {
|
||||
names := map[string]bool{m.Primary: true}
|
||||
for _, p := range m.Reg.List() {
|
||||
names[p.Name] = true
|
||||
}
|
||||
if ents, err := os.ReadDir(filepath.Join(m.Dir, "probes")); err == nil {
|
||||
for _, e := range ents {
|
||||
if e.IsDir() && wire.ValidName(e.Name()) {
|
||||
names[e.Name()] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
list := make([]string, 0, len(names))
|
||||
for n := range names {
|
||||
list = append(list, n)
|
||||
}
|
||||
sort.Strings(list)
|
||||
for _, n := range list {
|
||||
if _, err := m.Ensure(n); err != nil {
|
||||
return fmt.Errorf("node %s: %w", n, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Ensure returns the node of name, creating it on first use.
|
||||
func (m *Manager) Ensure(name string) (Node, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if n, ok := m.nodes[name]; ok {
|
||||
return n, nil
|
||||
}
|
||||
if !wire.ValidName(name) {
|
||||
return nil, ErrName
|
||||
}
|
||||
rec, _ := m.Reg.Get(name)
|
||||
n, err := m.Make(name, name == m.Primary, rec)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m.nodes[name] = n
|
||||
if m.conns[name] == nil {
|
||||
m.conns[name] = &conn{}
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// Get returns an existing node.
|
||||
func (m *Manager) Get(name string) Node {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return m.nodes[name]
|
||||
}
|
||||
|
||||
// Nodes lists the nodes sorted by name, the primary first.
|
||||
func (m *Manager) Nodes() []Node {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
out := make([]Node, 0, len(m.nodes))
|
||||
for _, n := range m.nodes {
|
||||
out = append(out, n)
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool {
|
||||
a, b := out[i].Name(), out[j].Name()
|
||||
if (a == m.Primary) != (b == m.Primary) {
|
||||
return a == m.Primary
|
||||
}
|
||||
return a < b
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
func (m *Manager) conn(name string) *conn {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
c := m.conns[name]
|
||||
if c == nil {
|
||||
c = &conn{}
|
||||
m.conns[name] = c
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// Connected reports whether the probe pushed within OfflineSec.
|
||||
func (m *Manager) Connected(name string) bool {
|
||||
c := m.conn(name)
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.lastSeen > 0 && m.Now().Unix()-c.lastSeen <= wire.OfflineSec
|
||||
}
|
||||
|
||||
// Info describes one probe.
|
||||
func (m *Manager) Info(name string) (ProbeInfo, bool) {
|
||||
n := m.Get(name)
|
||||
rec, reg := m.Reg.Get(name)
|
||||
if n == nil && !reg {
|
||||
return ProbeInfo{}, false
|
||||
}
|
||||
c := m.conn(name)
|
||||
c.mu.Lock()
|
||||
st := c.status
|
||||
in := ProbeInfo{Name: name, Primary: name == m.Primary, Registered: reg, Revoked: rec.Revoked, Created: rec.Created,
|
||||
LastSeen: c.lastSeen, LastLine: c.lastLine, LagMS: c.lagMS, Version: c.version, Hostname: c.hostname,
|
||||
Dropped: st.Dropped, Spool: st.SpoolBytes, SpoolFiles: st.SpoolFiles, CmdErrors: st.CmdErrors,
|
||||
Uptime: st.UptimeSec, RSS: st.RSSBytes, Sources: append([]wire.SourceStatus{}, st.Sources...), Location: rec.Location, Egress: rec.Egress}
|
||||
c.mu.Unlock()
|
||||
in.Connected = m.Connected(name)
|
||||
if n != nil {
|
||||
if q := n.Queue(); q != nil {
|
||||
in.CmdPending, in.CmdDropped = q.Pending(0), q.Dropped()
|
||||
}
|
||||
}
|
||||
return in, true
|
||||
}
|
||||
|
||||
// List describes every probe (registered ones and nodes without a record, such
|
||||
// as the primary or imported data).
|
||||
func (m *Manager) List() []ProbeInfo {
|
||||
names := map[string]bool{}
|
||||
for _, n := range m.Nodes() {
|
||||
names[n.Name()] = true
|
||||
}
|
||||
for _, p := range m.Reg.List() {
|
||||
names[p.Name] = true
|
||||
}
|
||||
var out []ProbeInfo
|
||||
for n := range names {
|
||||
if in, ok := m.Info(n); ok {
|
||||
out = append(out, in)
|
||||
}
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool {
|
||||
if out[i].Primary != out[j].Primary {
|
||||
return out[i].Primary
|
||||
}
|
||||
return out[i].Name < out[j].Name
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
// Create registers a probe, returning its token (shown once).
|
||||
func (m *Manager) Create(name string) (string, error) {
|
||||
tok, err := m.Reg.Create(name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if _, err := m.Ensure(name); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return tok, nil
|
||||
}
|
||||
|
||||
// Revoke disables the token of a probe and drops its connection state; the
|
||||
// data stays.
|
||||
func (m *Manager) Revoke(name string) error {
|
||||
if err := m.Reg.Revoke(name); err != nil {
|
||||
return err
|
||||
}
|
||||
c := m.conn(name)
|
||||
c.mu.Lock()
|
||||
c.lastSeen = 0
|
||||
c.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateProbe stores the location and egress configuration and applies the location now.
|
||||
func (m *Manager) UpdateProbe(name string, u Update) error {
|
||||
if u.Location != nil {
|
||||
if l := u.Location; l.Lat < -90 || l.Lat > 90 || l.Lon < -180 || l.Lon > 180 || len(l.Label) > 80 {
|
||||
return fmt.Errorf("invalid location")
|
||||
}
|
||||
}
|
||||
if err := m.Reg.Update(name, u.Location, u.Egress); err != nil {
|
||||
return err
|
||||
}
|
||||
if n := m.Get(name); n != nil {
|
||||
n.SetLocation(u.Location)
|
||||
if r, ok := n.(interface{ ResetEgress(Egress) }); ok {
|
||||
r.ResetEgress(u.Egress)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close flushes the command queues.
|
||||
func (m *Manager) Close() {
|
||||
for _, n := range m.Nodes() {
|
||||
if q := n.Queue(); q != nil {
|
||||
q.Close()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
// Package hub is the server side of the probe protocol: the registry of
|
||||
// probes (probes.json), the per-node command queue and the ingest handlers.
|
||||
package hub
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
|
||||
)
|
||||
|
||||
// TokenPrefix starts every probe token.
|
||||
const TokenPrefix = "urp_"
|
||||
|
||||
// Egress is the per-probe configuration of the egress analysis.
|
||||
type Egress struct {
|
||||
Workloads string `json:"workloads,omitempty"`
|
||||
Resolvers string `json:"resolvers,omitempty"`
|
||||
Allow string `json:"allow,omitempty"`
|
||||
}
|
||||
|
||||
// Probe is one entry of probes.json. The token is never stored, only its hash.
|
||||
type Probe struct {
|
||||
Name string `json:"name"`
|
||||
TokenSHA256 string `json:"token_sha256"`
|
||||
Created int64 `json:"created"`
|
||||
Revoked bool `json:"revoked"`
|
||||
Location *wire.Location `json:"location,omitempty"`
|
||||
Egress Egress `json:"egress"`
|
||||
}
|
||||
|
||||
// Errors of the registry.
|
||||
var (
|
||||
ErrExists = errors.New("probe already exists")
|
||||
ErrNotFound = errors.New("probe not found")
|
||||
ErrName = errors.New("invalid probe name (a-z, 0-9 and -, at most 32 characters)")
|
||||
)
|
||||
|
||||
// Registry is probes.json.
|
||||
type Registry struct {
|
||||
mu sync.Mutex
|
||||
path string
|
||||
probes map[string]*Probe
|
||||
}
|
||||
|
||||
type regFile struct {
|
||||
Probes []*Probe `json:"probes"`
|
||||
}
|
||||
|
||||
// OpenRegistry loads path (a missing file is an empty registry).
|
||||
func OpenRegistry(path string) (*Registry, error) {
|
||||
r := &Registry{path: path, probes: map[string]*Probe{}}
|
||||
b, err := os.ReadFile(path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return r, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var f regFile
|
||||
if err := json.Unmarshal(b, &f); err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", path, err)
|
||||
}
|
||||
for _, p := range f.Probes {
|
||||
if p != nil && wire.ValidName(p.Name) {
|
||||
r.probes[p.Name] = p
|
||||
}
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
// save writes the file atomically with mode 0600; the caller holds mu.
|
||||
func (r *Registry) save() error {
|
||||
list := make([]*Probe, 0, len(r.probes))
|
||||
for _, p := range r.probes {
|
||||
list = append(list, p)
|
||||
}
|
||||
sort.Slice(list, func(i, j int) bool { return list[i].Name < list[j].Name })
|
||||
b, err := json.MarshalIndent(regFile{Probes: list}, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(r.path), 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
tmp := r.path + ".tmp"
|
||||
if err := os.WriteFile(tmp, b, 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Chmod(tmp, 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmp, r.path)
|
||||
}
|
||||
|
||||
// HashToken is the hex sha256 of a token.
|
||||
func HashToken(tok string) string {
|
||||
h := sha256.Sum256([]byte(tok))
|
||||
return hex.EncodeToString(h[:])
|
||||
}
|
||||
|
||||
// NewToken returns a fresh token: "urp_" + 43 base64url characters.
|
||||
func NewToken() (string, error) {
|
||||
var b [32]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return TokenPrefix + base64.RawURLEncoding.EncodeToString(b[:]), nil
|
||||
}
|
||||
|
||||
// Create registers a probe and returns its token, shown only once. Creating a
|
||||
// probe that was revoked replaces its token and makes it active again.
|
||||
func (r *Registry) Create(name string) (string, error) {
|
||||
if !wire.ValidName(name) || name == "all" {
|
||||
return "", ErrName
|
||||
}
|
||||
tok, err := NewToken()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if p, ok := r.probes[name]; ok && !p.Revoked {
|
||||
return "", ErrExists
|
||||
}
|
||||
p := r.probes[name]
|
||||
if p == nil {
|
||||
p = &Probe{Name: name, Created: time.Now().Unix()}
|
||||
r.probes[name] = p
|
||||
}
|
||||
p.TokenSHA256, p.Revoked = HashToken(tok), false
|
||||
if err := r.save(); err != nil {
|
||||
delete(r.probes, name)
|
||||
return "", err
|
||||
}
|
||||
return tok, nil
|
||||
}
|
||||
|
||||
// Revoke disables the token of a probe; its data stays.
|
||||
func (r *Registry) Revoke(name string) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
p, ok := r.probes[name]
|
||||
if !ok {
|
||||
return ErrNotFound
|
||||
}
|
||||
p.Revoked = true
|
||||
return r.save()
|
||||
}
|
||||
|
||||
// Update replaces the location and the egress configuration of a probe.
|
||||
func (r *Registry) Update(name string, loc *wire.Location, eg Egress) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
p, ok := r.probes[name]
|
||||
if !ok {
|
||||
return ErrNotFound
|
||||
}
|
||||
p.Location, p.Egress = loc, eg
|
||||
return r.save()
|
||||
}
|
||||
|
||||
// Verify checks a token in constant time; revoked and unknown probes fail.
|
||||
func (r *Registry) Verify(name, token string) bool {
|
||||
r.mu.Lock()
|
||||
p := r.probes[name]
|
||||
var want string
|
||||
revoked := true
|
||||
if p != nil {
|
||||
want, revoked = p.TokenSHA256, p.Revoked
|
||||
}
|
||||
r.mu.Unlock()
|
||||
if want == "" {
|
||||
want = strings.Repeat("0", 64)
|
||||
}
|
||||
got := HashToken(token)
|
||||
ok := subtle.ConstantTimeCompare([]byte(got), []byte(want)) == 1
|
||||
return ok && !revoked
|
||||
}
|
||||
|
||||
// Get returns a copy of the entry.
|
||||
func (r *Registry) Get(name string) (Probe, bool) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
p, ok := r.probes[name]
|
||||
if !ok {
|
||||
return Probe{}, false
|
||||
}
|
||||
return *p, true
|
||||
}
|
||||
|
||||
// List returns every entry sorted by name.
|
||||
func (r *Registry) List() []Probe {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
out := make([]Probe, 0, len(r.probes))
|
||||
for _, p := range r.probes {
|
||||
out = append(out, *p)
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package hub
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRegistryHashOnlyAndRevoke(t *testing.T) {
|
||||
p := filepath.Join(t.TempDir(), "probes.json")
|
||||
r, err := OpenRegistry(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tok, err := r.Create("hostinger")
|
||||
if err != nil || !strings.HasPrefix(tok, "urp_") || len(tok) != 47 {
|
||||
t.Fatalf("%q %v", tok, err)
|
||||
}
|
||||
if b, _ := os.ReadFile(p); strings.Contains(string(b), tok) {
|
||||
t.Fatal("token stored")
|
||||
}
|
||||
if fi, _ := os.Stat(p); fi.Mode().Perm() != 0o600 {
|
||||
t.Fatal(fi.Mode())
|
||||
}
|
||||
if !r.Verify("hostinger", tok) || r.Verify("hostinger", tok+"x") || r.Verify("other", tok) {
|
||||
t.Fatal("verify")
|
||||
}
|
||||
if _, err := r.Create("hostinger"); err != ErrExists {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.Create("All"); err != ErrName {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.Revoke("hostinger")
|
||||
if r.Verify("hostinger", tok) {
|
||||
t.Fatal("revoked token accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestQueuePersistsAndPrunes(t *testing.T) {
|
||||
p := filepath.Join(t.TempDir(), "commands.json")
|
||||
q, _ := OpenQueue(p)
|
||||
line := "2026-11-15T10:00:00Z urutau unban ip=203.0.113.9 allow=60\n"
|
||||
for i := 0; i < 3; i++ {
|
||||
if err := q.Enqueue("unban", line); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if q.Enqueue("unban", "rm -rf /\n") == nil {
|
||||
t.Fatal("invalid line queued")
|
||||
}
|
||||
q.Close()
|
||||
q2, _ := OpenQueue(p)
|
||||
defer q2.Close()
|
||||
if q2.Last() != 3 || q2.Pending(1) != 2 {
|
||||
t.Fatalf("%d %d", q2.Last(), q2.Pending(1))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
package probeagent
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/rand/v2"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrUnauthorized: the hub rejected the token or the probe name. Fatal.
|
||||
ErrUnauthorized = errors.New("hub rejected the probe credentials (401)")
|
||||
// ErrIncompatible: protocol version mismatch (409). Fatal.
|
||||
ErrIncompatible = errors.New("hub speaks an incompatible protocol version (409)")
|
||||
)
|
||||
|
||||
// retryError asks the caller to wait and retry the same request.
|
||||
type retryError struct {
|
||||
after time.Duration
|
||||
code int
|
||||
}
|
||||
|
||||
func (e *retryError) Error() string {
|
||||
return fmt.Sprintf("hub busy (%d), retry in %s", e.code, e.after)
|
||||
}
|
||||
|
||||
// rejectError: the hub refused this batch for good (400/413); retrying is pointless.
|
||||
type rejectError struct{ code int }
|
||||
|
||||
func (e *rejectError) Error() string { return fmt.Sprintf("hub rejected the batch (%d)", e.code) }
|
||||
|
||||
const gzipOver = 8 << 10
|
||||
|
||||
type client struct {
|
||||
base string
|
||||
name string
|
||||
token string
|
||||
hc *http.Client
|
||||
gz *gzip.Writer
|
||||
buf bytes.Buffer
|
||||
raw bytes.Buffer
|
||||
}
|
||||
|
||||
func newClient(base *url.URL, name, token string, hc *http.Client) *client {
|
||||
if hc == nil {
|
||||
hc = &http.Client{}
|
||||
}
|
||||
return &client{base: base.String(), name: name, token: token, hc: hc}
|
||||
}
|
||||
|
||||
func (c *client) req(ctx context.Context, method, path string, body io.Reader) (*http.Request, error) {
|
||||
r, err := http.NewRequestWithContext(ctx, method, c.base+path, body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r.Header.Set("Authorization", "Bearer "+c.token)
|
||||
r.Header.Set(wire.HeaderProbe, c.name)
|
||||
r.Header.Set("User-Agent", "urutau-probe")
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func retryAfter(h http.Header) time.Duration {
|
||||
d := 5 * time.Second
|
||||
if v, err := strconv.Atoi(h.Get("Retry-After")); err == nil && v >= 0 {
|
||||
d = time.Duration(v) * time.Second
|
||||
}
|
||||
return min(d, 2*time.Minute)
|
||||
}
|
||||
|
||||
func statusErr(resp *http.Response) error {
|
||||
switch {
|
||||
case resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden:
|
||||
return ErrUnauthorized
|
||||
case resp.StatusCode == http.StatusConflict:
|
||||
return ErrIncompatible
|
||||
case resp.StatusCode == http.StatusServiceUnavailable || resp.StatusCode == http.StatusTooManyRequests:
|
||||
return &retryError{retryAfter(resp.Header), resp.StatusCode}
|
||||
}
|
||||
return fmt.Errorf("hub answered %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
func (c *client) do(r *http.Request, out any, limit int64) (*http.Response, error) {
|
||||
resp, err := c.hc.Do(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
|
||||
return resp, statusErr(resp)
|
||||
}
|
||||
if out != nil {
|
||||
if err := json.NewDecoder(io.LimitReader(resp.Body, limit)).Decode(out); err != nil {
|
||||
return resp, fmt.Errorf("bad hub answer: %w", err)
|
||||
}
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (c *client) hello(ctx context.Context, h wire.Hello) (*wire.HelloResp, error) {
|
||||
data, _ := json.Marshal(&h)
|
||||
r, err := c.req(ctx, http.MethodPost, wire.PathHello, bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
var out wire.HelloResp
|
||||
if _, err := c.do(r, &out, 1<<20); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if out.Offsets == nil {
|
||||
out.Offsets = map[string]wire.Pos{}
|
||||
}
|
||||
return &out, nil
|
||||
}
|
||||
|
||||
func (c *client) push(ctx context.Context, b wire.Batch) (*wire.PushResp, error) {
|
||||
c.raw.Reset()
|
||||
if err := json.NewEncoder(&c.raw).Encode(&b); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
data := c.raw.Bytes()
|
||||
var body io.Reader = bytes.NewReader(data)
|
||||
gzipped := false
|
||||
if len(data) > gzipOver {
|
||||
c.buf.Reset()
|
||||
if c.gz == nil {
|
||||
c.gz = gzip.NewWriter(&c.buf)
|
||||
} else {
|
||||
c.gz.Reset(&c.buf)
|
||||
}
|
||||
if _, err := c.gz.Write(data); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := c.gz.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
body = bytes.NewReader(c.buf.Bytes())
|
||||
gzipped = true
|
||||
}
|
||||
r, err := c.req(ctx, http.MethodPost, wire.PathPush, body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
if gzipped {
|
||||
r.Header.Set("Content-Encoding", "gzip")
|
||||
}
|
||||
var out wire.PushResp
|
||||
resp, err := c.do(r, &out, 1<<20)
|
||||
if err != nil {
|
||||
if resp != nil && (resp.StatusCode == http.StatusBadRequest || resp.StatusCode == http.StatusRequestEntityTooLarge) {
|
||||
return nil, &rejectError{resp.StatusCode}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &out, nil
|
||||
}
|
||||
|
||||
// commands long-polls; the caller's context bounds the wait.
|
||||
func (c *client) commands(ctx context.Context, after uint64, wait int) (*wire.CmdResp, error) {
|
||||
q := fmt.Sprintf("%s?after=%d&wait=%d", wire.PathCommands, after, wait)
|
||||
r, err := c.req(ctx, http.MethodGet, q, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out wire.CmdResp
|
||||
if _, err := c.do(r, &out, 8<<20); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &out, nil
|
||||
}
|
||||
|
||||
// backoff is the reconnect delay after n consecutive failures (n >= 1):
|
||||
// 1 s doubling up to 60 s, with +-20% jitter. rnd returns [0,1).
|
||||
func backoff(n int, rnd func() float64) time.Duration {
|
||||
if n < 1 {
|
||||
n = 1
|
||||
}
|
||||
d := time.Second
|
||||
for i := 1; i < n && d < 60*time.Second; i++ {
|
||||
d *= 2
|
||||
}
|
||||
d = min(d, 60*time.Second)
|
||||
return time.Duration(float64(d) * (0.8 + 0.4*rnd()))
|
||||
}
|
||||
|
||||
func jitterRnd() float64 { return rand.Float64() }
|
||||
@@ -0,0 +1,55 @@
|
||||
package probeagent
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
|
||||
)
|
||||
|
||||
// appendLine appends one validated line to path and syncs it.
|
||||
func appendLine(path, line string) error {
|
||||
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o640)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := f.WriteString(line); err != nil {
|
||||
f.Close()
|
||||
return err
|
||||
}
|
||||
if err := f.Sync(); err != nil {
|
||||
f.Close()
|
||||
return err
|
||||
}
|
||||
return f.Close()
|
||||
}
|
||||
|
||||
// applyCmds executes the commands above lastCmd, in order, and persists
|
||||
// lastCmd after each one. An invalid or unroutable command is counted and
|
||||
// skipped; it never stops the queue. A write failure stops (the same command
|
||||
// is delivered again later).
|
||||
func (p *probe) applyCmds(cmds []wire.Cmd) error {
|
||||
for _, c := range cmds {
|
||||
if c.Seq <= p.st.lastCmd() {
|
||||
continue
|
||||
}
|
||||
var path string
|
||||
switch c.Kind {
|
||||
case wire.CmdDecision:
|
||||
path = p.cfg.DecisionsLog
|
||||
case wire.CmdUnban:
|
||||
path = p.cfg.UnbanLog
|
||||
}
|
||||
if path == "" || !wire.ValidCmdLine(c.Kind, c.Line) {
|
||||
p.cmdErrors.Add(1)
|
||||
p.log.Warn("command ignored", "seq", c.Seq, "kind", c.Kind)
|
||||
} else if err := appendLine(path, c.Line); err != nil {
|
||||
p.cmdErrors.Add(1)
|
||||
p.log.Error("command write failed", "seq", c.Seq, "kind", c.Kind)
|
||||
return err
|
||||
}
|
||||
if err := p.st.setLastCmd(c.Seq); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package probeagent
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func inodeFor(fi os.FileInfo) uint64 { return fi.Sys().(*syscall.Stat_t).Ino }
|
||||
@@ -0,0 +1,5 @@
|
||||
//go:build !race
|
||||
|
||||
package probeagent
|
||||
|
||||
const raceOn = false
|
||||
@@ -0,0 +1,435 @@
|
||||
// Package probeagent is the Urutau 2 probe: it tails the host logs, spools
|
||||
// batches on disk and ships them to the hub over HTTPS, and applies the
|
||||
// enforcement commands the hub queues for it.
|
||||
package probeagent
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"runtime/debug"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
|
||||
)
|
||||
|
||||
// Config configures one probe. Paths maps a wire source name to the log file
|
||||
// to follow; an empty path disables the source.
|
||||
type Config struct {
|
||||
Hub, Name, Token, StateDir string
|
||||
Paths map[string]string
|
||||
Containers, Resolv string
|
||||
DecisionsLog, UnbanLog string
|
||||
SpoolMax int64 // default 64 MiB
|
||||
Location *wire.Location
|
||||
Client *http.Client // default: plain client, no overall timeout
|
||||
|
||||
// Optional.
|
||||
Version string // reported in hello (default "dev")
|
||||
Poll time.Duration // tail poll interval (default 500 ms)
|
||||
}
|
||||
|
||||
type probe struct {
|
||||
cfg Config
|
||||
log *slog.Logger
|
||||
cl *client
|
||||
st *stateStore
|
||||
spool *Spool
|
||||
start time.Time
|
||||
cancel context.CancelCauseFunc
|
||||
|
||||
sources []string
|
||||
stats []*srcStat
|
||||
in chan item
|
||||
notify chan struct{}
|
||||
wg sync.WaitGroup
|
||||
|
||||
flushMS atomic.Int64
|
||||
cmdErrors atomic.Uint64
|
||||
fileEvery time.Duration
|
||||
hbEvery time.Duration
|
||||
resendFiles chan struct{}
|
||||
}
|
||||
|
||||
func (p *probe) flushEvery() time.Duration {
|
||||
ms := p.flushMS.Load()
|
||||
if ms < 10 {
|
||||
ms = 1000
|
||||
}
|
||||
return time.Duration(ms) * time.Millisecond
|
||||
}
|
||||
|
||||
func newProbe(c Config, log *slog.Logger) (*probe, error) {
|
||||
if log == nil {
|
||||
log = slog.New(slog.NewTextHandler(os.Stderr, nil))
|
||||
}
|
||||
if !wire.ValidName(c.Name) {
|
||||
return nil, errors.New("invalid probe name")
|
||||
}
|
||||
if c.Token == "" {
|
||||
return nil, errors.New("probe token missing")
|
||||
}
|
||||
if c.StateDir == "" {
|
||||
return nil, errors.New("state dir missing")
|
||||
}
|
||||
u, err := wire.CheckHubURL(c.Hub)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if c.SpoolMax <= 0 {
|
||||
c.SpoolMax = 64 << 20
|
||||
}
|
||||
if c.Version == "" {
|
||||
c.Version = "dev"
|
||||
}
|
||||
if err := os.MkdirAll(c.StateDir, 0o700); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
st, err := loadState(c.StateDir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sp, err := OpenSpool(filepath.Join(c.StateDir, "spool"), c.SpoolMax)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
st.raiseSeq(sp.MaxSeq())
|
||||
p := &probe{
|
||||
cfg: c, log: log, st: st, spool: sp, start: time.Now(),
|
||||
cl: newClient(u, c.Name, c.Token, c.Client),
|
||||
in: make(chan item, chanSize),
|
||||
notify: make(chan struct{}, 1),
|
||||
fileEvery: filePollEach,
|
||||
hbEvery: time.Duration(wire.HeartbeatSec) * time.Second,
|
||||
resendFiles: make(chan struct{}, 1),
|
||||
}
|
||||
for _, s := range wire.Sources {
|
||||
if c.Paths[s] != "" {
|
||||
p.sources = append(p.sources, s)
|
||||
}
|
||||
}
|
||||
sort.Strings(p.sources)
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// Run connects to the hub and ships until ctx is done (nil) or the hub
|
||||
// refuses the credentials or the protocol version (error).
|
||||
func Run(ctx context.Context, c Config, log *slog.Logger) error {
|
||||
p, err := newProbe(c, log)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if os.Getenv("GOMEMLIMIT") == "" {
|
||||
// soft limit: the probe is a small process, make the GC keep it that way
|
||||
debug.SetMemoryLimit(8 << 20)
|
||||
debug.SetGCPercent(30)
|
||||
}
|
||||
ctx, cancel := context.WithCancelCause(ctx)
|
||||
p.cancel = cancel
|
||||
defer cancel(nil)
|
||||
|
||||
resp, err := p.connect(ctx)
|
||||
if err != nil {
|
||||
return p.result(ctx, err)
|
||||
}
|
||||
p.startTailers(ctx, resp.Offsets)
|
||||
var cw sync.WaitGroup
|
||||
cw.Add(1)
|
||||
go func() { defer cw.Done(); p.collect(ctx) }()
|
||||
p.wg.Add(3)
|
||||
go func() { defer p.wg.Done(); p.sender(ctx) }()
|
||||
go func() { defer p.wg.Done(); p.commandLoop(ctx) }()
|
||||
go func() { defer p.wg.Done(); p.aliveLoop(ctx) }()
|
||||
|
||||
<-ctx.Done()
|
||||
p.wg.Wait()
|
||||
cw.Wait() // final flush so positions and spool are consistent
|
||||
_ = p.st.touch()
|
||||
return p.result(ctx, nil)
|
||||
}
|
||||
|
||||
func (p *probe) result(ctx context.Context, err error) error {
|
||||
if cause := context.Cause(ctx); cause != nil && !errors.Is(cause, context.Canceled) {
|
||||
return cause
|
||||
}
|
||||
if err != nil && !errors.Is(err, context.Canceled) {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *probe) fail(err error) {
|
||||
p.log.Error("probe stopping", "err", err)
|
||||
p.cancel(err)
|
||||
}
|
||||
|
||||
func isFatal(err error) bool {
|
||||
return errors.Is(err, ErrUnauthorized) || errors.Is(err, ErrIncompatible)
|
||||
}
|
||||
|
||||
func sleep(ctx context.Context, d time.Duration) bool {
|
||||
t := time.NewTimer(d)
|
||||
defer t.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
case <-t.C:
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// hello performs one handshake and applies its answer.
|
||||
func (p *probe) hello(ctx context.Context) (*wire.HelloResp, error) {
|
||||
host, _ := os.Hostname()
|
||||
s := p.st.snapshot()
|
||||
h := wire.Hello{
|
||||
Proto: wire.Proto, Name: p.cfg.Name, Version: p.cfg.Version, Hostname: host,
|
||||
Sources: append([]string{}, p.sources...), Location: p.cfg.Location,
|
||||
LastSeq: s.Seq, LastCmd: s.LastCmd,
|
||||
}
|
||||
hctx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
resp, err := p.cl.hello(hctx, h)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.FlushMS > 0 {
|
||||
p.flushMS.Store(int64(resp.FlushMS))
|
||||
}
|
||||
p.st.raiseSeq(resp.AckSeq)
|
||||
p.spool.Ack(resp.AckSeq)
|
||||
select {
|
||||
case p.resendFiles <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// connect retries the first hello with backoff.
|
||||
func (p *probe) connect(ctx context.Context) (*wire.HelloResp, error) {
|
||||
for n := 1; ; n++ {
|
||||
resp, err := p.hello(ctx)
|
||||
if err == nil {
|
||||
return resp, nil
|
||||
}
|
||||
if isFatal(err) {
|
||||
p.log.Error("hello refused", "err", err)
|
||||
return nil, err
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
d := p.retryDelay(err, n)
|
||||
p.log.Warn("hub unreachable, retrying", "err", err, "in", d.Round(time.Millisecond))
|
||||
if !sleep(ctx, d) {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (p *probe) retryDelay(err error, n int) time.Duration {
|
||||
var re *retryError
|
||||
if errors.As(err, &re) {
|
||||
return re.after
|
||||
}
|
||||
return backoff(n, jitterRnd)
|
||||
}
|
||||
|
||||
// sender ships the spool in order, heartbeating when idle; on any transport
|
||||
// error it reconnects (hello) with backoff.
|
||||
func (p *probe) sender(ctx context.Context) {
|
||||
n := 0
|
||||
first := true
|
||||
for ctx.Err() == nil {
|
||||
if !first {
|
||||
if _, err := p.hello(ctx); err != nil {
|
||||
if isFatal(err) {
|
||||
p.fail(err)
|
||||
return
|
||||
}
|
||||
n++
|
||||
d := p.retryDelay(err, n)
|
||||
p.log.Warn("hub unreachable, retrying", "err", err, "in", d.Round(time.Millisecond))
|
||||
if !sleep(ctx, d) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
first = false
|
||||
n = 0
|
||||
err := p.session(ctx)
|
||||
if err == nil || ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
if isFatal(err) {
|
||||
p.fail(err)
|
||||
return
|
||||
}
|
||||
n++
|
||||
d := backoff(n, jitterRnd)
|
||||
p.log.Warn("connection lost, reconnecting", "err", err, "in", d.Round(time.Millisecond))
|
||||
if !sleep(ctx, d) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (p *probe) session(ctx context.Context) error {
|
||||
hb := time.NewTimer(p.hbEvery)
|
||||
defer hb.Stop()
|
||||
resetHB := func() {
|
||||
if !hb.Stop() {
|
||||
select {
|
||||
case <-hb.C:
|
||||
default:
|
||||
}
|
||||
}
|
||||
hb.Reset(p.hbEvery)
|
||||
}
|
||||
for {
|
||||
b, ok, err := p.spool.Head()
|
||||
if err != nil {
|
||||
p.log.Error("spool", "err", err)
|
||||
continue
|
||||
}
|
||||
if !ok {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
case <-p.notify:
|
||||
case <-hb.C:
|
||||
if _, err := p.cl.push(ctx, wire.Batch{Sent: time.Now().UnixMilli(), Status: p.status()}); err != nil {
|
||||
if p.handlePushErr(ctx, err, wire.Batch{}) {
|
||||
continue
|
||||
}
|
||||
return err
|
||||
}
|
||||
hb.Reset(p.hbEvery)
|
||||
}
|
||||
continue
|
||||
}
|
||||
b.Sent = time.Now().UnixMilli()
|
||||
b.Status = p.status()
|
||||
resp, err := p.cl.push(ctx, b)
|
||||
if err != nil {
|
||||
if p.handlePushErr(ctx, err, b) {
|
||||
continue
|
||||
}
|
||||
return err
|
||||
}
|
||||
if resp.Ack < b.Seq {
|
||||
return fmt.Errorf("hub acked %d for batch %d", resp.Ack, b.Seq)
|
||||
}
|
||||
p.spool.Ack(resp.Ack)
|
||||
resetHB()
|
||||
}
|
||||
}
|
||||
|
||||
// handlePushErr deals with the errors that do not need a reconnect.
|
||||
func (p *probe) handlePushErr(ctx context.Context, err error, b wire.Batch) bool {
|
||||
var re *retryError
|
||||
var rj *rejectError
|
||||
switch {
|
||||
case errors.As(err, &re):
|
||||
p.log.Warn("hub busy, backing off", "code", re.code, "in", re.after)
|
||||
sleep(ctx, re.after)
|
||||
return true
|
||||
case errors.As(err, &rj):
|
||||
if b.Seq == 0 {
|
||||
sleep(ctx, 5*time.Second)
|
||||
return true
|
||||
}
|
||||
p.log.Error("hub rejected batch, dropping it", "seq", b.Seq, "code", rj.code, "lines", len(b.Lines))
|
||||
p.spool.Ack(b.Seq)
|
||||
p.st.addDropped(uint64(len(b.Lines)))
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (p *probe) commandLoop(ctx context.Context) {
|
||||
n := 0
|
||||
for ctx.Err() == nil {
|
||||
rctx, cancel := context.WithTimeout(ctx, (wire.MaxWaitSec+15)*time.Second)
|
||||
resp, err := p.cl.commands(rctx, p.st.lastCmd(), wire.MaxWaitSec)
|
||||
cancel()
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
if isFatal(err) {
|
||||
p.fail(err)
|
||||
return
|
||||
}
|
||||
n++
|
||||
if !sleep(ctx, p.retryDelay(err, n)) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
n = 0
|
||||
if err := p.applyCmds(resp.Cmds); err != nil {
|
||||
if !sleep(ctx, 5*time.Second) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (p *probe) aliveLoop(ctx context.Context) {
|
||||
t := time.NewTicker(15 * time.Second)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
_ = p.st.touch()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (p *probe) status() *wire.Status {
|
||||
b, f := p.spool.Stats()
|
||||
s := &wire.Status{
|
||||
UptimeSec: int64(time.Since(p.start).Seconds()), RSSBytes: rss(),
|
||||
SpoolBytes: b, SpoolFiles: f, Dropped: p.st.dropped(), CmdErrors: p.cmdErrors.Load(),
|
||||
}
|
||||
for _, ss := range p.stats {
|
||||
s.Sources = append(s.Sources, ss.status())
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// rss reads VmRSS from /proc; elsewhere it falls back to what the Go runtime holds.
|
||||
func rss() uint64 {
|
||||
if f, err := os.Open("/proc/self/status"); err == nil {
|
||||
defer f.Close()
|
||||
sc := bufio.NewScanner(f)
|
||||
for sc.Scan() {
|
||||
if v, ok := strings.CutPrefix(sc.Text(), "VmRSS:"); ok {
|
||||
fs := strings.Fields(v)
|
||||
if len(fs) > 0 {
|
||||
if kb, err := strconv.ParseUint(fs[0], 10, 64); err == nil {
|
||||
return kb << 10
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
var m runtime.MemStats
|
||||
runtime.ReadMemStats(&m)
|
||||
return m.Sys
|
||||
}
|
||||
@@ -0,0 +1,742 @@
|
||||
package probeagent
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
|
||||
)
|
||||
|
||||
const testToken = "urp_test"
|
||||
|
||||
// fakeHub is the smallest hub that speaks the protocol: it applies batches
|
||||
// idempotently by seq, keeps the lines, and serves a command queue.
|
||||
type fakeHub struct {
|
||||
mu sync.Mutex
|
||||
lines []wire.Line
|
||||
files map[string]string
|
||||
ack uint64
|
||||
offsets map[string]wire.Pos
|
||||
cmds []wire.Cmd
|
||||
status *wire.Status
|
||||
hellos []wire.Hello
|
||||
gzipSeen int
|
||||
pushes int
|
||||
fail503 int // next N pushes answer 503 Retry-After: 1
|
||||
flushMS int
|
||||
discard bool // do not keep lines (memory test)
|
||||
nlines int
|
||||
}
|
||||
|
||||
func newFakeHub() *fakeHub {
|
||||
return &fakeHub{files: map[string]string{}, offsets: map[string]wire.Pos{}, flushMS: 30}
|
||||
}
|
||||
|
||||
func (h *fakeHub) handler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
auth := func(w http.ResponseWriter, r *http.Request) bool {
|
||||
if r.Header.Get("Authorization") != "Bearer "+testToken || r.Header.Get(wire.HeaderProbe) != "p1" {
|
||||
w.WriteHeader(401)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
mux.HandleFunc(wire.PathHello, func(w http.ResponseWriter, r *http.Request) {
|
||||
if !auth(w, r) {
|
||||
return
|
||||
}
|
||||
var hello wire.Hello
|
||||
json.NewDecoder(r.Body).Decode(&hello)
|
||||
if hello.Proto != wire.Proto {
|
||||
w.WriteHeader(409)
|
||||
return
|
||||
}
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
h.hellos = append(h.hellos, hello)
|
||||
json.NewEncoder(w).Encode(wire.HelloResp{Proto: wire.Proto, HubVer: "t", Offsets: h.offsets, AckSeq: h.ack, FlushMS: h.flushMS})
|
||||
})
|
||||
mux.HandleFunc(wire.PathPush, func(w http.ResponseWriter, r *http.Request) {
|
||||
if !auth(w, r) {
|
||||
return
|
||||
}
|
||||
var body io.Reader = r.Body
|
||||
if r.Header.Get("Content-Encoding") == "gzip" {
|
||||
gz, err := gzip.NewReader(r.Body)
|
||||
if err != nil {
|
||||
w.WriteHeader(400)
|
||||
return
|
||||
}
|
||||
body = gz
|
||||
h.mu.Lock()
|
||||
h.gzipSeen++
|
||||
h.mu.Unlock()
|
||||
}
|
||||
var b wire.Batch
|
||||
if err := json.NewDecoder(body).Decode(&b); err != nil {
|
||||
w.WriteHeader(400)
|
||||
return
|
||||
}
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
h.pushes++
|
||||
if h.fail503 > 0 {
|
||||
h.fail503--
|
||||
w.Header().Set("Retry-After", "1")
|
||||
w.WriteHeader(503)
|
||||
return
|
||||
}
|
||||
h.status = b.Status
|
||||
resp := wire.PushResp{}
|
||||
if b.Seq > 0 && b.Seq > h.ack {
|
||||
for _, l := range b.Lines {
|
||||
h.nlines++
|
||||
if !h.discard {
|
||||
h.lines = append(h.lines, l)
|
||||
}
|
||||
h.offsets[l.Src] = l.End
|
||||
}
|
||||
for _, f := range b.Files {
|
||||
h.files[f.Name] = f.Data
|
||||
}
|
||||
h.ack = b.Seq
|
||||
resp.Accepted = len(b.Lines)
|
||||
} else if b.Seq > 0 {
|
||||
resp.Dup = len(b.Lines)
|
||||
}
|
||||
resp.Ack = h.ack
|
||||
if n := len(h.cmds); n > 0 {
|
||||
resp.PendCmd = h.cmds[n-1].Seq
|
||||
}
|
||||
json.NewEncoder(w).Encode(resp)
|
||||
})
|
||||
mux.HandleFunc(wire.PathCommands, func(w http.ResponseWriter, r *http.Request) {
|
||||
if !auth(w, r) {
|
||||
return
|
||||
}
|
||||
after, _ := strconv.ParseUint(r.URL.Query().Get("after"), 10, 64)
|
||||
deadline := time.Now().Add(300 * time.Millisecond)
|
||||
for {
|
||||
h.mu.Lock()
|
||||
var out []wire.Cmd
|
||||
for _, c := range h.cmds {
|
||||
if c.Seq > after {
|
||||
out = append(out, c)
|
||||
}
|
||||
}
|
||||
h.mu.Unlock()
|
||||
if len(out) > 0 || time.Now().After(deadline) || r.Context().Err() != nil {
|
||||
json.NewEncoder(w).Encode(wire.CmdResp{Cmds: out})
|
||||
return
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
})
|
||||
return mux
|
||||
}
|
||||
|
||||
func (h *fakeHub) texts() []string {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
var out []string
|
||||
for _, l := range h.lines {
|
||||
out = append(out, l.Src+":"+l.Text)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (h *fakeHub) count() int { h.mu.Lock(); defer h.mu.Unlock(); return h.nlines }
|
||||
|
||||
func quiet() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) }
|
||||
|
||||
func eventually(t *testing.T, what string, d time.Duration, f func() bool) {
|
||||
t.Helper()
|
||||
end := time.Now().Add(d)
|
||||
for time.Now().Before(end) {
|
||||
if f() {
|
||||
return
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
t.Fatalf("timeout waiting for %s", what)
|
||||
}
|
||||
|
||||
type env struct {
|
||||
dir, state string
|
||||
cfg Config
|
||||
}
|
||||
|
||||
func newEnv(t *testing.T, hubURL string) *env {
|
||||
d := t.TempDir()
|
||||
e := &env{dir: d, state: filepath.Join(d, "state")}
|
||||
e.cfg = Config{
|
||||
Hub: hubURL, Name: "p1", Token: testToken, StateDir: e.state,
|
||||
Paths: map[string]string{
|
||||
wire.SrcTraefik: filepath.Join(d, "traefik.log"),
|
||||
wire.SrcAuth: filepath.Join(d, "auth.log"),
|
||||
},
|
||||
DecisionsLog: filepath.Join(d, "decisions.log"),
|
||||
UnbanLog: filepath.Join(d, "unban.log"),
|
||||
Poll: 10 * time.Millisecond,
|
||||
SpoolMax: 64 << 20,
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
func appendFile(t *testing.T, path string, lines ...string) {
|
||||
t.Helper()
|
||||
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
for _, l := range lines {
|
||||
f.WriteString(l + "\n")
|
||||
}
|
||||
}
|
||||
|
||||
func startRun(ctx context.Context, c Config) chan error {
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- Run(ctx, c, quiet()) }()
|
||||
return done
|
||||
}
|
||||
|
||||
func TestEndToEnd(t *testing.T) {
|
||||
hub := newFakeHub()
|
||||
srv := httptest.NewServer(hub.handler())
|
||||
defer srv.Close()
|
||||
e := newEnv(t, srv.URL)
|
||||
e.cfg.Containers = filepath.Join(e.dir, "containers.map")
|
||||
os.WriteFile(e.cfg.Containers, []byte("172.18.0.2 web\n"), 0o644)
|
||||
e.cfg.Location = &wire.Location{Lat: 1, Lon: 2, Label: "x"}
|
||||
appendFile(t, e.cfg.Paths[wire.SrcTraefik], "t1", "t2")
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := startRun(ctx, e.cfg)
|
||||
appendFile(t, e.cfg.Paths[wire.SrcAuth], "a1")
|
||||
eventually(t, "3 lines", 5*time.Second, func() bool { return hub.count() == 3 })
|
||||
appendFile(t, e.cfg.Paths[wire.SrcTraefik], "t3\xff")
|
||||
eventually(t, "4 lines", 5*time.Second, func() bool { return hub.count() == 4 })
|
||||
eventually(t, "file", 2*time.Second, func() bool {
|
||||
hub.mu.Lock()
|
||||
defer hub.mu.Unlock()
|
||||
return hub.files[wire.FileContainers] == "172.18.0.2 web\n"
|
||||
})
|
||||
hub.mu.Lock()
|
||||
h := hub.hellos[0]
|
||||
last := hub.lines[len(hub.lines)-1]
|
||||
st := hub.status
|
||||
hub.mu.Unlock()
|
||||
if h.Name != "p1" || h.Location == nil || h.Location.Label != "x" || len(h.Sources) != 2 {
|
||||
t.Errorf("hello %+v", h)
|
||||
}
|
||||
if !strings.HasSuffix(last.Text, "�") || last.End.Offset != 10 {
|
||||
t.Errorf("last %+v", last)
|
||||
}
|
||||
if st == nil || len(st.Sources) != 2 || st.RSSBytes == 0 {
|
||||
t.Errorf("status %+v", st)
|
||||
}
|
||||
cancel()
|
||||
if err := <-done; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := Check(e.state); err != nil {
|
||||
t.Errorf("Check after run: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHubOutageNoLossNoDuplicates(t *testing.T) {
|
||||
hub := newFakeHub()
|
||||
var down sync.Mutex
|
||||
isDown := false
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
down.Lock()
|
||||
d := isDown
|
||||
down.Unlock()
|
||||
if d {
|
||||
hj, _ := w.(http.Hijacker)
|
||||
c, _, _ := hj.Hijack()
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
hub.handler().ServeHTTP(w, r)
|
||||
}))
|
||||
defer srv.Close()
|
||||
e := newEnv(t, srv.URL)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
startRun(ctx, e.cfg)
|
||||
tp := e.cfg.Paths[wire.SrcTraefik]
|
||||
appendFile(t, tp, "first")
|
||||
eventually(t, "first", 5*time.Second, func() bool { return hub.count() == 1 })
|
||||
down.Lock()
|
||||
isDown = true
|
||||
down.Unlock()
|
||||
for i := 0; i < 1000; i++ {
|
||||
appendFile(t, tp, fmt.Sprintf("line-%04d", i))
|
||||
}
|
||||
time.Sleep(400 * time.Millisecond)
|
||||
down.Lock()
|
||||
isDown = false
|
||||
down.Unlock()
|
||||
eventually(t, "1001 lines", 15*time.Second, func() bool { return hub.count() == 1001 })
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
got := hub.texts()
|
||||
if len(got) != 1001 {
|
||||
t.Fatalf("%d lines", len(got))
|
||||
}
|
||||
for i := 0; i < 1000; i++ {
|
||||
if got[i+1] != fmt.Sprintf("traefik:line-%04d", i) {
|
||||
t.Fatalf("line %d = %s", i, got[i+1])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestartResumesFromState(t *testing.T) {
|
||||
hub := newFakeHub()
|
||||
srv := httptest.NewServer(hub.handler())
|
||||
defer srv.Close()
|
||||
e := newEnv(t, srv.URL)
|
||||
tp := e.cfg.Paths[wire.SrcTraefik]
|
||||
appendFile(t, tp, "a", "b", "c")
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := startRun(ctx, e.cfg)
|
||||
eventually(t, "3", 5*time.Second, func() bool { return hub.count() == 3 })
|
||||
cancel()
|
||||
<-done
|
||||
appendFile(t, tp, "d")
|
||||
ctx2, cancel2 := context.WithCancel(context.Background())
|
||||
defer cancel2()
|
||||
startRun(ctx2, e.cfg)
|
||||
eventually(t, "4", 5*time.Second, func() bool { return hub.count() >= 4 })
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
if got := hub.texts(); len(got) != 4 || got[3] != "traefik:d" {
|
||||
t.Fatalf("%v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFreshProbeStartsAtHubOffsets(t *testing.T) {
|
||||
hub := newFakeHub()
|
||||
srv := httptest.NewServer(hub.handler())
|
||||
defer srv.Close()
|
||||
e := newEnv(t, srv.URL)
|
||||
tp := e.cfg.Paths[wire.SrcTraefik]
|
||||
appendFile(t, tp, "old1", "old2", "new1")
|
||||
fi, _ := os.Stat(tp)
|
||||
ino := inodeFor(fi)
|
||||
hub.offsets[wire.SrcTraefik] = wire.Pos{Inode: ino, Offset: int64(len("old1\nold2\n"))}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
startRun(ctx, e.cfg)
|
||||
eventually(t, "new1", 5*time.Second, func() bool { return hub.count() >= 1 })
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
if got := hub.texts(); len(got) != 1 || got[0] != "traefik:new1" {
|
||||
t.Fatalf("%v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHubAckAheadRaisesSeq(t *testing.T) {
|
||||
hub := newFakeHub()
|
||||
hub.ack = 50 // probe lost its state; hub remembers
|
||||
srv := httptest.NewServer(hub.handler())
|
||||
defer srv.Close()
|
||||
e := newEnv(t, srv.URL)
|
||||
appendFile(t, e.cfg.Paths[wire.SrcTraefik], "x")
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
startRun(ctx, e.cfg)
|
||||
eventually(t, "x", 5*time.Second, func() bool { return hub.count() == 1 })
|
||||
}
|
||||
|
||||
func TestPushBackpressure503RetryAfter(t *testing.T) {
|
||||
hub := newFakeHub()
|
||||
hub.fail503 = 1
|
||||
srv := httptest.NewServer(hub.handler())
|
||||
defer srv.Close()
|
||||
e := newEnv(t, srv.URL)
|
||||
appendFile(t, e.cfg.Paths[wire.SrcTraefik], "x")
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
start := time.Now()
|
||||
startRun(ctx, e.cfg)
|
||||
eventually(t, "x", 8*time.Second, func() bool { return hub.count() == 1 })
|
||||
if el := time.Since(start); el < 900*time.Millisecond {
|
||||
t.Errorf("retried after %v, Retry-After: 1 not honored", el)
|
||||
}
|
||||
hub.mu.Lock()
|
||||
n := len(hub.hellos)
|
||||
hub.mu.Unlock()
|
||||
if n != 1 {
|
||||
t.Errorf("%d hellos: a 503 must not force a reconnect", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnauthorizedStopsRun(t *testing.T) {
|
||||
hub := newFakeHub()
|
||||
srv := httptest.NewServer(hub.handler())
|
||||
defer srv.Close()
|
||||
e := newEnv(t, srv.URL)
|
||||
e.cfg.Token = "wrong"
|
||||
var logbuf strings.Builder
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- Run(context.Background(), e.cfg, slog.New(slog.NewTextHandler(&logbuf, nil))) }()
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != ErrUnauthorized {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("Run did not stop on 401")
|
||||
}
|
||||
if !strings.Contains(logbuf.String(), "401") {
|
||||
t.Errorf("401 not logged: %s", logbuf.String())
|
||||
}
|
||||
if strings.Contains(logbuf.String(), "wrong") {
|
||||
t.Error("token leaked in log")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnauthorizedRevokedMidSession(t *testing.T) {
|
||||
hub := newFakeHub()
|
||||
var revoked sync.Mutex
|
||||
rev := false
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
revoked.Lock()
|
||||
x := rev
|
||||
revoked.Unlock()
|
||||
if x {
|
||||
w.WriteHeader(401)
|
||||
return
|
||||
}
|
||||
hub.handler().ServeHTTP(w, r)
|
||||
}))
|
||||
defer srv.Close()
|
||||
e := newEnv(t, srv.URL)
|
||||
appendFile(t, e.cfg.Paths[wire.SrcTraefik], "x")
|
||||
done := startRun(context.Background(), e.cfg)
|
||||
eventually(t, "x", 5*time.Second, func() bool { return hub.count() == 1 })
|
||||
revoked.Lock()
|
||||
rev = true
|
||||
revoked.Unlock()
|
||||
appendFile(t, e.cfg.Paths[wire.SrcTraefik], "y")
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != ErrUnauthorized {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
case <-time.After(30 * time.Second):
|
||||
t.Fatal("Run kept going after token revocation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGzipOverThreshold(t *testing.T) {
|
||||
hub := newFakeHub()
|
||||
srv := httptest.NewServer(hub.handler())
|
||||
defer srv.Close()
|
||||
e := newEnv(t, srv.URL)
|
||||
big := strings.Repeat("abcdefghij", 200)
|
||||
for i := 0; i < 20; i++ {
|
||||
appendFile(t, e.cfg.Paths[wire.SrcTraefik], fmt.Sprintf("%d%s", i, big))
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
startRun(ctx, e.cfg)
|
||||
eventually(t, "20", 5*time.Second, func() bool { return hub.count() == 20 })
|
||||
hub.mu.Lock()
|
||||
defer hub.mu.Unlock()
|
||||
if hub.gzipSeen == 0 {
|
||||
t.Error("large push was not gzipped")
|
||||
}
|
||||
if hub.lines[19].Text != "19"+big {
|
||||
t.Error("gzip round trip altered the line")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSmallPushNotGzipped(t *testing.T) {
|
||||
hub := newFakeHub()
|
||||
srv := httptest.NewServer(hub.handler())
|
||||
defer srv.Close()
|
||||
e := newEnv(t, srv.URL)
|
||||
appendFile(t, e.cfg.Paths[wire.SrcTraefik], "tiny")
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
startRun(ctx, e.cfg)
|
||||
eventually(t, "1", 5*time.Second, func() bool { return hub.count() == 1 })
|
||||
hub.mu.Lock()
|
||||
defer hub.mu.Unlock()
|
||||
if hub.gzipSeen != 0 {
|
||||
t.Error("small push gzipped")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommandsApplied(t *testing.T) {
|
||||
hub := newFakeHub()
|
||||
srv := httptest.NewServer(hub.handler())
|
||||
defer srv.Close()
|
||||
e := newEnv(t, srv.URL)
|
||||
good := "2026-11-15T10:20:30Z urutau decision=ban ip=203.0.113.9 reason=rce score=90 ttl=300 host=h src=local\n"
|
||||
unban := "2026-11-15T10:21:30Z urutau unban ip=203.0.113.9 allow=60\n"
|
||||
evil := "2026-11-15T10:20:30Z urutau decision=ban ip=203.0.113.9 reason=rce score=90 ttl=300 host=h src=local\nrm -rf /\n"
|
||||
hub.cmds = []wire.Cmd{
|
||||
{Seq: 1, Kind: wire.CmdDecision, Line: good},
|
||||
{Seq: 2, Kind: wire.CmdDecision, Line: evil},
|
||||
{Seq: 3, Kind: wire.CmdDecision, Line: "garbage\n"},
|
||||
{Seq: 4, Kind: wire.CmdUnban, Line: unban},
|
||||
{Seq: 5, Kind: "other", Line: good},
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := startRun(ctx, e.cfg)
|
||||
eventually(t, "cmds", 5*time.Second, func() bool {
|
||||
s, err := loadState(e.state)
|
||||
return err == nil && s.s.LastCmd == 5
|
||||
})
|
||||
cancel()
|
||||
<-done
|
||||
dec, _ := os.ReadFile(e.cfg.DecisionsLog)
|
||||
if string(dec) != good {
|
||||
t.Errorf("decisions.log = %q", dec)
|
||||
}
|
||||
ub, _ := os.ReadFile(e.cfg.UnbanLog)
|
||||
if string(ub) != unban {
|
||||
t.Errorf("unban.log = %q", ub)
|
||||
}
|
||||
// restart: the hub redelivers everything, nothing is applied twice
|
||||
ctx2, cancel2 := context.WithCancel(context.Background())
|
||||
done2 := startRun(ctx2, e.cfg)
|
||||
time.Sleep(600 * time.Millisecond)
|
||||
cancel2()
|
||||
<-done2
|
||||
dec, _ = os.ReadFile(e.cfg.DecisionsLog)
|
||||
if string(dec) != good {
|
||||
t.Errorf("decision duplicated after restart: %q", dec)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyCmdsDirect(t *testing.T) {
|
||||
e := newEnv(t, "http://127.0.0.1:1")
|
||||
p, err := newProbe(e.cfg, quiet())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
good := "2026-11-15T10:20:30Z urutau decision=ban ip=2001:db8::1 reason=rce score=90 ttl=300 host=h src=peer:o\n"
|
||||
cmds := []wire.Cmd{{Seq: 1, Kind: wire.CmdDecision, Line: good}, {Seq: 1, Kind: wire.CmdDecision, Line: good}, {Seq: 2, Kind: wire.CmdDecision, Line: "x\n"}}
|
||||
if err := p.applyCmds(cmds); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := p.applyCmds(cmds); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, _ := os.ReadFile(e.cfg.DecisionsLog)
|
||||
if string(b) != good {
|
||||
t.Errorf("%q", b)
|
||||
}
|
||||
if p.cmdErrors.Load() != 1 {
|
||||
t.Errorf("cmdErrors = %d", p.cmdErrors.Load())
|
||||
}
|
||||
if p.st.lastCmd() != 2 {
|
||||
t.Errorf("lastCmd = %d", p.st.lastCmd())
|
||||
}
|
||||
// no unban log configured: counted, not written
|
||||
p.cfg.UnbanLog = ""
|
||||
p.applyCmds([]wire.Cmd{{Seq: 3, Kind: wire.CmdUnban, Line: "2026-11-15T10:21:30Z urutau unban ip=1.2.3.4 allow=1\n"}})
|
||||
if p.cmdErrors.Load() != 2 {
|
||||
t.Errorf("cmdErrors = %d", p.cmdErrors.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBackoff(t *testing.T) {
|
||||
for n, base := range map[int]float64{1: 1, 2: 2, 3: 4, 6: 32, 7: 60, 20: 60} {
|
||||
for _, r := range []float64{0, 0.5, 0.999} {
|
||||
d := backoff(n, func() float64 { return r }).Seconds()
|
||||
if d < base*0.8-1e-9 || d > base*1.2+1e-9 {
|
||||
t.Errorf("backoff(%d, %v) = %v, want %v +-20%%", n, r, d, base)
|
||||
}
|
||||
}
|
||||
}
|
||||
if backoff(3, func() float64 { return 0.5 }) != 4*time.Second {
|
||||
t.Error("middle of jitter should be the base")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOversizeLineCountedNotSent(t *testing.T) {
|
||||
hub := newFakeHub()
|
||||
srv := httptest.NewServer(hub.handler())
|
||||
defer srv.Close()
|
||||
e := newEnv(t, srv.URL)
|
||||
appendFile(t, e.cfg.Paths[wire.SrcTraefik], "ok", strings.Repeat("z", wire.MaxLine+10), "after")
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
startRun(ctx, e.cfg)
|
||||
eventually(t, "2 lines", 5*time.Second, func() bool { return hub.count() == 2 })
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
if got := hub.texts(); len(got) != 2 || got[1] != "traefik:after" {
|
||||
t.Fatalf("%v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMissingSourceWaitsAndNoPathLeak(t *testing.T) {
|
||||
hub := newFakeHub()
|
||||
srv := httptest.NewServer(hub.handler())
|
||||
defer srv.Close()
|
||||
e := newEnv(t, srv.URL)
|
||||
appendFile(t, e.cfg.Paths[wire.SrcTraefik], "x") // auth.log never created
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
startRun(ctx, e.cfg)
|
||||
eventually(t, "x", 5*time.Second, func() bool { return hub.count() == 1 })
|
||||
appendFile(t, e.cfg.Paths[wire.SrcTraefik], "y")
|
||||
eventually(t, "status", 5*time.Second, func() bool {
|
||||
hub.mu.Lock()
|
||||
defer hub.mu.Unlock()
|
||||
if hub.status == nil {
|
||||
return false
|
||||
}
|
||||
for _, s := range hub.status.Sources {
|
||||
if s.Src == wire.SrcAuth && s.State == "waiting" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
})
|
||||
hub.mu.Lock()
|
||||
b, _ := json.Marshal(hub.status)
|
||||
hub.mu.Unlock()
|
||||
if strings.Contains(string(b), e.dir) {
|
||||
t.Errorf("path leaked in status: %s", b)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigValidation(t *testing.T) {
|
||||
e := newEnv(t, "https://hub.example.com")
|
||||
bad := func(m func(*Config)) {
|
||||
c := e.cfg
|
||||
m(&c)
|
||||
if _, err := newProbe(c, quiet()); err == nil {
|
||||
t.Error("invalid config accepted")
|
||||
}
|
||||
}
|
||||
bad(func(c *Config) { c.Hub = "http://example.com" })
|
||||
bad(func(c *Config) { c.Name = "Bad Name" })
|
||||
bad(func(c *Config) { c.Token = "" })
|
||||
bad(func(c *Config) { c.StateDir = "" })
|
||||
}
|
||||
|
||||
func TestCheck(t *testing.T) {
|
||||
d := t.TempDir()
|
||||
if Check(d) == nil {
|
||||
t.Error("missing state accepted")
|
||||
}
|
||||
st, _ := loadState(d)
|
||||
st.touch()
|
||||
if err := Check(d); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
st.s.Alive = time.Now().Add(-10 * time.Minute).Unix()
|
||||
b, _ := json.Marshal(&st.s)
|
||||
os.WriteFile(filepath.Join(d, "state.json"), b, 0o600)
|
||||
if Check(d) == nil {
|
||||
t.Error("stale state accepted")
|
||||
}
|
||||
}
|
||||
|
||||
// TestHelperProbe is the probe process of TestMemoryFootprint, run in a child
|
||||
// so that nothing but the probe (and the test binary baseline) is measured.
|
||||
func TestHelperProbe(t *testing.T) {
|
||||
if os.Getenv("URUTAU_TEST_PROBE_CHILD") == "" {
|
||||
t.Skip("helper for TestMemoryFootprint")
|
||||
}
|
||||
var cfg Config
|
||||
if err := json.Unmarshal([]byte(os.Getenv("URUTAU_TEST_PROBE_CFG")), &cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := startRun(ctx, cfg)
|
||||
io.Copy(io.Discard, os.Stdin) // parent closes stdin when done
|
||||
cancel()
|
||||
<-done
|
||||
var m runtime.MemStats
|
||||
runtime.ReadMemStats(&m)
|
||||
hwm := uint64(0)
|
||||
if b, err := os.ReadFile("/proc/self/status"); err == nil {
|
||||
for _, l := range strings.Split(string(b), "\n") {
|
||||
if v, ok := strings.CutPrefix(l, "VmHWM:"); ok {
|
||||
kb, _ := strconv.ParseUint(strings.Fields(v)[0], 10, 64)
|
||||
hwm = kb << 10
|
||||
}
|
||||
}
|
||||
}
|
||||
fmt.Printf("RESULT sys=%d hwm=%d\n", m.Sys, hwm)
|
||||
}
|
||||
|
||||
// 5 sources, 50k lines: the probe must stay small (target RSS < 20 MB).
|
||||
func TestMemoryFootprint(t *testing.T) {
|
||||
if raceOn {
|
||||
t.Skip("the race detector inflates RSS; measured in the plain run")
|
||||
}
|
||||
hub := newFakeHub()
|
||||
hub.discard = true
|
||||
srv := httptest.NewServer(hub.handler())
|
||||
defer srv.Close()
|
||||
e := newEnv(t, srv.URL)
|
||||
e.cfg.Paths = map[string]string{}
|
||||
srcs := wire.Sources
|
||||
line := `203.0.113.7 - - [15/Nov/2026:10:20:30 +0000] "GET /wp-login.php HTTP/1.1" 404 153 "-" "Mozilla/5.0 (X11; Linux x86_64)" 1234 "web@docker" "http://172.18.0.5:80" 3ms`
|
||||
const per = 10000
|
||||
for _, s := range srcs {
|
||||
e.cfg.Paths[s] = filepath.Join(e.dir, s+".log")
|
||||
f, _ := os.Create(e.cfg.Paths[s])
|
||||
w := bufio.NewWriter(f)
|
||||
for i := 0; i < per; i++ {
|
||||
fmt.Fprintf(w, "%s %d\n", line, i)
|
||||
}
|
||||
w.Flush()
|
||||
f.Close()
|
||||
}
|
||||
cfgJSON, _ := json.Marshal(e.cfg)
|
||||
cmd := exec.Command(os.Args[0], "-test.run=^TestHelperProbe$", "-test.v")
|
||||
cmd.Env = append(os.Environ(), "URUTAU_TEST_PROBE_CHILD=1", "URUTAU_TEST_PROBE_CFG="+string(cfgJSON))
|
||||
stdin, _ := cmd.StdinPipe()
|
||||
var out bytes.Buffer
|
||||
cmd.Stdout = &out
|
||||
if err := cmd.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
eventually(t, "50k lines", 60*time.Second, func() bool { return hub.count() == per*len(srcs) })
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
stdin.Close()
|
||||
if err := cmd.Wait(); err != nil {
|
||||
t.Fatalf("child: %v\n%s", err, out.String())
|
||||
}
|
||||
var sys, hwm uint64
|
||||
for _, l := range strings.Split(out.String(), "\n") {
|
||||
if strings.HasPrefix(l, "RESULT ") {
|
||||
fmt.Sscanf(l, "RESULT sys=%d hwm=%d", &sys, &hwm)
|
||||
}
|
||||
}
|
||||
if sys == 0 {
|
||||
t.Fatalf("no result from child:\n%s", out.String())
|
||||
}
|
||||
t.Logf("50k lines, 5 sources: runtime MemStats.Sys = %.1f MB, peak RSS (VmHWM) = %.1f MB", float64(sys)/(1<<20), float64(hwm)/(1<<20))
|
||||
if sys >= 20<<20 {
|
||||
t.Errorf("MemStats.Sys %d >= 20 MB", sys)
|
||||
}
|
||||
if hwm >= 20<<20 {
|
||||
t.Errorf("peak RSS %d >= 20 MB", hwm)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
//go:build race
|
||||
|
||||
package probeagent
|
||||
|
||||
const raceOn = true
|
||||
@@ -0,0 +1,176 @@
|
||||
package probeagent
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
|
||||
)
|
||||
|
||||
// Spool keeps unacknowledged batches on disk, one file per batch, in order.
|
||||
type Spool struct {
|
||||
mu sync.Mutex
|
||||
dir string
|
||||
max int64
|
||||
items []spoolItem
|
||||
bytes int64
|
||||
wbuf bytes.Buffer // reused encoder buffer
|
||||
}
|
||||
|
||||
type spoolItem struct {
|
||||
seq uint64
|
||||
size int64
|
||||
}
|
||||
|
||||
func spoolName(seq uint64) string { return fmt.Sprintf("%012d.json", seq) }
|
||||
|
||||
// OpenSpool scans dir (created if missing) and returns the spool.
|
||||
func OpenSpool(dir string, max int64) (*Spool, error) {
|
||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sp := &Spool{dir: dir, max: max}
|
||||
ents, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, e := range ents {
|
||||
n := e.Name()
|
||||
if strings.HasSuffix(n, ".tmp") {
|
||||
os.Remove(filepath.Join(dir, n))
|
||||
continue
|
||||
}
|
||||
if !strings.HasSuffix(n, ".json") {
|
||||
continue
|
||||
}
|
||||
seq, err := strconv.ParseUint(strings.TrimSuffix(n, ".json"), 10, 64)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
fi, err := e.Info()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
sp.items = append(sp.items, spoolItem{seq, fi.Size()})
|
||||
sp.bytes += fi.Size()
|
||||
}
|
||||
sort.Slice(sp.items, func(i, j int) bool { return sp.items[i].seq < sp.items[j].seq })
|
||||
return sp, nil
|
||||
}
|
||||
|
||||
// MaxSeq is the highest batch number on disk (0 when empty).
|
||||
func (sp *Spool) MaxSeq() uint64 {
|
||||
sp.mu.Lock()
|
||||
defer sp.mu.Unlock()
|
||||
if len(sp.items) == 0 {
|
||||
return 0
|
||||
}
|
||||
return sp.items[len(sp.items)-1].seq
|
||||
}
|
||||
|
||||
// Add stores b (b.Seq must be above everything already stored). When the cap
|
||||
// is exceeded the oldest files are deleted, but never the one just added; the
|
||||
// number of log lines lost that way is returned.
|
||||
func (sp *Spool) Add(b wire.Batch) (dropped uint64, err error) {
|
||||
sp.mu.Lock()
|
||||
defer sp.mu.Unlock()
|
||||
sp.wbuf.Reset()
|
||||
if err := json.NewEncoder(&sp.wbuf).Encode(&b); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
data := sp.wbuf.Bytes()
|
||||
if sp.wbuf.Cap() > 4<<20 {
|
||||
defer func() { sp.wbuf = bytes.Buffer{} }()
|
||||
}
|
||||
p := filepath.Join(sp.dir, spoolName(b.Seq))
|
||||
tmp := p + ".tmp"
|
||||
f, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if _, err = f.Write(data); err == nil {
|
||||
err = f.Sync()
|
||||
}
|
||||
if cerr := f.Close(); err == nil {
|
||||
err = cerr
|
||||
}
|
||||
if err == nil {
|
||||
err = os.Rename(tmp, p)
|
||||
}
|
||||
if err != nil {
|
||||
os.Remove(tmp)
|
||||
return 0, err
|
||||
}
|
||||
sp.items = append(sp.items, spoolItem{b.Seq, int64(len(data))})
|
||||
sp.bytes += int64(len(data))
|
||||
for sp.bytes > sp.max && len(sp.items) > 1 {
|
||||
it := sp.items[0]
|
||||
dropped += sp.countLines(it.seq)
|
||||
sp.removeLocked(0)
|
||||
}
|
||||
return dropped, nil
|
||||
}
|
||||
|
||||
func (sp *Spool) countLines(seq uint64) uint64 {
|
||||
data, err := os.ReadFile(filepath.Join(sp.dir, spoolName(seq)))
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
var b wire.Batch
|
||||
if json.Unmarshal(data, &b) != nil {
|
||||
return 0
|
||||
}
|
||||
return uint64(len(b.Lines))
|
||||
}
|
||||
|
||||
func (sp *Spool) removeLocked(i int) {
|
||||
it := sp.items[i]
|
||||
os.Remove(filepath.Join(sp.dir, spoolName(it.seq)))
|
||||
sp.bytes -= it.size
|
||||
sp.items = append(sp.items[:i], sp.items[i+1:]...)
|
||||
}
|
||||
|
||||
// Head returns the oldest batch.
|
||||
func (sp *Spool) Head() (wire.Batch, bool, error) {
|
||||
sp.mu.Lock()
|
||||
if len(sp.items) == 0 {
|
||||
sp.mu.Unlock()
|
||||
return wire.Batch{}, false, nil
|
||||
}
|
||||
seq := sp.items[0].seq
|
||||
sp.mu.Unlock()
|
||||
data, err := os.ReadFile(filepath.Join(sp.dir, spoolName(seq)))
|
||||
var b wire.Batch
|
||||
if err == nil {
|
||||
err = json.Unmarshal(data, &b)
|
||||
}
|
||||
if err != nil {
|
||||
sp.Ack(seq) // unreadable: discard so the queue moves on
|
||||
return wire.Batch{}, false, fmt.Errorf("spool batch %d unreadable: %w", seq, err)
|
||||
}
|
||||
b.Seq = seq
|
||||
return b, true, nil
|
||||
}
|
||||
|
||||
// Ack removes every batch with seq <= n.
|
||||
func (sp *Spool) Ack(n uint64) {
|
||||
sp.mu.Lock()
|
||||
defer sp.mu.Unlock()
|
||||
for len(sp.items) > 0 && sp.items[0].seq <= n {
|
||||
sp.removeLocked(0)
|
||||
}
|
||||
}
|
||||
|
||||
// Stats returns the bytes and file count held.
|
||||
func (sp *Spool) Stats() (bytes int64, files int) {
|
||||
sp.mu.Lock()
|
||||
defer sp.mu.Unlock()
|
||||
return sp.bytes, len(sp.items)
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package probeagent
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
|
||||
)
|
||||
|
||||
func mkBatch(seq uint64, n int, pad string) wire.Batch {
|
||||
b := wire.Batch{Seq: seq}
|
||||
for i := 0; i < n; i++ {
|
||||
b.Lines = append(b.Lines, wire.Line{Src: wire.SrcTraefik, Text: fmt.Sprintf("%d-%d%s", seq, i, pad), End: wire.Pos{Inode: 1, Offset: int64(i)}})
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func TestSpoolOrderAndReopen(t *testing.T) {
|
||||
d := t.TempDir()
|
||||
sp, err := OpenSpool(d, 1<<20)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for s := uint64(1); s <= 5; s++ {
|
||||
if dr, err := sp.Add(mkBatch(s, 3, "")); err != nil || dr != 0 {
|
||||
t.Fatal(dr, err)
|
||||
}
|
||||
}
|
||||
sp.Ack(2)
|
||||
sp2, err := OpenSpool(d, 1<<20) // reopen
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if sp2.MaxSeq() != 5 {
|
||||
t.Errorf("MaxSeq %d", sp2.MaxSeq())
|
||||
}
|
||||
for want := uint64(3); want <= 5; want++ {
|
||||
b, ok, err := sp2.Head()
|
||||
if err != nil || !ok || b.Seq != want || len(b.Lines) != 3 {
|
||||
t.Fatalf("head %d: %+v %v %v", want, b.Seq, ok, err)
|
||||
}
|
||||
sp2.Ack(want)
|
||||
}
|
||||
if _, ok, _ := sp2.Head(); ok {
|
||||
t.Error("spool not empty")
|
||||
}
|
||||
if n, f := sp2.Stats(); n != 0 || f != 0 {
|
||||
t.Errorf("stats %d %d", n, f)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSpoolCapDropsOldestAndCounts(t *testing.T) {
|
||||
d := t.TempDir()
|
||||
probe := mkBatch(1, 10, "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
|
||||
tmp, _ := OpenSpool(t.TempDir(), 1<<30)
|
||||
tmp.Add(probe)
|
||||
size, _ := tmp.Stats()
|
||||
sp, _ := OpenSpool(d, size*3+size/2) // room for 3 batches
|
||||
var dropped uint64
|
||||
for s := uint64(1); s <= 6; s++ {
|
||||
dr, err := sp.Add(mkBatch(s, 10, "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dropped += dr
|
||||
}
|
||||
if dropped != 30 {
|
||||
t.Errorf("dropped %d lines, want 30 (3 batches of 10)", dropped)
|
||||
}
|
||||
b, ok, _ := sp.Head()
|
||||
if !ok || b.Seq != 4 {
|
||||
t.Errorf("oldest remaining = %d, want 4", b.Seq)
|
||||
}
|
||||
if _, f := sp.Stats(); f != 3 {
|
||||
t.Errorf("files %d", f)
|
||||
}
|
||||
ents, _ := os.ReadDir(d)
|
||||
if len(ents) != 3 {
|
||||
t.Errorf("%d files on disk", len(ents))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSpoolKeepsLoneOversizeBatch(t *testing.T) {
|
||||
sp, _ := OpenSpool(t.TempDir(), 10)
|
||||
dr, err := sp.Add(mkBatch(1, 5, ""))
|
||||
if err != nil || dr != 0 {
|
||||
t.Fatal(dr, err)
|
||||
}
|
||||
if _, f := sp.Stats(); f != 1 {
|
||||
t.Error("newest batch must survive the cap")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSpoolCorruptFileSkipped(t *testing.T) {
|
||||
d := t.TempDir()
|
||||
sp, _ := OpenSpool(d, 1<<20)
|
||||
sp.Add(mkBatch(1, 1, ""))
|
||||
sp.Add(mkBatch(2, 1, ""))
|
||||
os.WriteFile(filepath.Join(d, spoolName(1)), []byte("{broken"), 0o600)
|
||||
if _, _, err := sp.Head(); err == nil {
|
||||
t.Error("corrupt batch not reported")
|
||||
}
|
||||
b, ok, err := sp.Head()
|
||||
if err != nil || !ok || b.Seq != 2 {
|
||||
t.Errorf("next head %v %v %v", b.Seq, ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStateAtomicRoundTrip(t *testing.T) {
|
||||
d := t.TempDir()
|
||||
st, _ := loadState(d)
|
||||
st.commit(func(seq uint64) uint64 { return 7 }, map[string]wire.Pos{"auth": {Inode: 9, Offset: 123, FP: 5, FPLen: 4}})
|
||||
st.setLastCmd(4)
|
||||
st2, err := loadState(d)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := st2.s
|
||||
if s.Seq != 1 || s.LastCmd != 4 || s.Dropped != 7 || s.Positions["auth"].Offset != 123 || s.Positions["auth"].FPLen != 4 {
|
||||
t.Errorf("%+v", s)
|
||||
}
|
||||
os.WriteFile(filepath.Join(d, "state.json"), []byte("garbage"), 0o600)
|
||||
st3, err := loadState(d)
|
||||
if err != nil || st3.s.Seq != 0 || st3.s.Positions == nil {
|
||||
t.Errorf("corrupt state not reset: %+v %v", st3.s, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
package probeagent
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
|
||||
)
|
||||
|
||||
// State is the probe's only durable bookkeeping besides the spool.
|
||||
type State struct {
|
||||
Seq uint64 `json:"seq"`
|
||||
LastCmd uint64 `json:"last_cmd"`
|
||||
Positions map[string]wire.Pos `json:"positions"`
|
||||
Dropped uint64 `json:"dropped"`
|
||||
Alive int64 `json:"alive"` // unix seconds, refreshed by the process; read by Check
|
||||
}
|
||||
|
||||
type stateStore struct {
|
||||
mu sync.Mutex
|
||||
path string
|
||||
s State
|
||||
}
|
||||
|
||||
func loadState(dir string) (*stateStore, error) {
|
||||
st := &stateStore{path: filepath.Join(dir, "state.json")}
|
||||
st.s.Positions = map[string]wire.Pos{}
|
||||
b, err := os.ReadFile(st.path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return st, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := json.Unmarshal(b, &st.s); err != nil {
|
||||
// a corrupt state must not keep the probe down: start clean, the hub's
|
||||
// offsets in the hello cover the gap.
|
||||
st.s = State{}
|
||||
}
|
||||
if st.s.Positions == nil {
|
||||
st.s.Positions = map[string]wire.Pos{}
|
||||
}
|
||||
return st, nil
|
||||
}
|
||||
|
||||
// saveLocked writes state.json atomically. Caller holds mu.
|
||||
func (st *stateStore) saveLocked() error {
|
||||
st.s.Alive = time.Now().Unix()
|
||||
b, err := json.Marshal(&st.s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmp := st.path + ".tmp"
|
||||
f, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := f.Write(b); err != nil {
|
||||
f.Close()
|
||||
return err
|
||||
}
|
||||
if err := f.Sync(); err != nil {
|
||||
f.Close()
|
||||
return err
|
||||
}
|
||||
if err := f.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmp, st.path)
|
||||
}
|
||||
|
||||
func (st *stateStore) touch() error {
|
||||
st.mu.Lock()
|
||||
defer st.mu.Unlock()
|
||||
return st.saveLocked()
|
||||
}
|
||||
|
||||
func (st *stateStore) snapshot() State {
|
||||
st.mu.Lock()
|
||||
defer st.mu.Unlock()
|
||||
c := st.s
|
||||
c.Positions = make(map[string]wire.Pos, len(st.s.Positions))
|
||||
for k, v := range st.s.Positions {
|
||||
c.Positions[k] = v
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func (st *stateStore) pos(src string) (wire.Pos, bool) {
|
||||
st.mu.Lock()
|
||||
defer st.mu.Unlock()
|
||||
p, ok := st.s.Positions[src]
|
||||
return p, ok
|
||||
}
|
||||
|
||||
func (st *stateStore) lastCmd() uint64 {
|
||||
st.mu.Lock()
|
||||
defer st.mu.Unlock()
|
||||
return st.s.LastCmd
|
||||
}
|
||||
|
||||
func (st *stateStore) setLastCmd(n uint64) error {
|
||||
st.mu.Lock()
|
||||
defer st.mu.Unlock()
|
||||
st.s.LastCmd = n
|
||||
return st.saveLocked()
|
||||
}
|
||||
|
||||
func (st *stateStore) dropped() uint64 {
|
||||
st.mu.Lock()
|
||||
defer st.mu.Unlock()
|
||||
return st.s.Dropped
|
||||
}
|
||||
|
||||
func (st *stateStore) addDropped(n uint64) {
|
||||
if n == 0 {
|
||||
return
|
||||
}
|
||||
st.mu.Lock()
|
||||
defer st.mu.Unlock()
|
||||
st.s.Dropped += n
|
||||
_ = st.saveLocked()
|
||||
}
|
||||
|
||||
// raiseSeq makes sure new batches are numbered above what the hub already
|
||||
// applied (state lost on the probe, or hub ahead).
|
||||
func (st *stateStore) raiseSeq(n uint64) {
|
||||
st.mu.Lock()
|
||||
defer st.mu.Unlock()
|
||||
if n > st.s.Seq {
|
||||
st.s.Seq = n
|
||||
_ = st.saveLocked()
|
||||
}
|
||||
}
|
||||
|
||||
func (st *stateStore) lastSeq() uint64 {
|
||||
st.mu.Lock()
|
||||
defer st.mu.Unlock()
|
||||
return st.s.Seq
|
||||
}
|
||||
|
||||
// commit allocates the next batch seq. persist is called with it before the
|
||||
// positions move, so a spooled batch always has its position recorded.
|
||||
func (st *stateStore) commit(build func(seq uint64) (dropped uint64), pos map[string]wire.Pos) {
|
||||
st.mu.Lock()
|
||||
defer st.mu.Unlock()
|
||||
st.s.Seq++
|
||||
st.s.Dropped += build(st.s.Seq)
|
||||
for k, v := range pos {
|
||||
st.s.Positions[k] = v
|
||||
}
|
||||
_ = st.saveLocked()
|
||||
}
|
||||
|
||||
// Check is the container healthcheck: the process refreshes state.json every
|
||||
// few seconds, so a stale or missing file means it is not running.
|
||||
func Check(stateDir string) error {
|
||||
b, err := os.ReadFile(filepath.Join(stateDir, "state.json"))
|
||||
if err != nil {
|
||||
return errors.New("probe state unreadable")
|
||||
}
|
||||
var s State
|
||||
if err := json.Unmarshal(b, &s); err != nil {
|
||||
return errors.New("probe state corrupt")
|
||||
}
|
||||
if age := time.Since(time.Unix(s.Alive, 0)); age > aliveMax {
|
||||
return errors.New("probe not alive")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
const aliveMax = 90 * time.Second
|
||||
@@ -0,0 +1,230 @@
|
||||
package probeagent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"os"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/tail"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
|
||||
)
|
||||
|
||||
const (
|
||||
chanSize = 4096
|
||||
batchBytes = 128 << 10 // well under the hub limit; keeps the probe heap small
|
||||
filePollEach = 10 * time.Second
|
||||
)
|
||||
|
||||
// item is what the followers and the file watcher hand to the collector.
|
||||
type item struct {
|
||||
line wire.Line
|
||||
file *wire.File
|
||||
}
|
||||
|
||||
type srcStat struct {
|
||||
src string
|
||||
f *tail.Follower
|
||||
lines atomic.Uint64
|
||||
oversize atomic.Uint64
|
||||
lastLine atomic.Int64
|
||||
}
|
||||
|
||||
func (s *srcStat) status() wire.SourceStatus {
|
||||
st := wire.SourceStatus{Src: s.src, State: "following", Lines: s.lines.Load(), Oversize: s.oversize.Load(), LastLine: s.lastLine.Load()}
|
||||
if err := s.f.Err(); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, fs.ErrNotExist):
|
||||
st.State = "waiting"
|
||||
case errors.Is(err, fs.ErrPermission):
|
||||
st.State, st.Error = "error", "permission denied"
|
||||
default:
|
||||
st.State, st.Error = "error", "read error"
|
||||
}
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
func toTail(p wire.Pos) tail.Pos {
|
||||
return tail.Pos{Inode: p.Inode, Offset: p.Offset, FP: p.FP, FPLen: p.FPLen}
|
||||
}
|
||||
|
||||
func fromTail(p tail.Pos) wire.Pos {
|
||||
return wire.Pos{Inode: p.Inode, Offset: p.Offset, FP: p.FP, FPLen: p.FPLen}
|
||||
}
|
||||
|
||||
// startTailers launches one follower per configured source. A source with no
|
||||
// local position starts where the hub says it already has data.
|
||||
func (p *probe) startTailers(ctx context.Context, hubOffsets map[string]wire.Pos) {
|
||||
for _, src := range p.sources {
|
||||
path := p.cfg.Paths[src]
|
||||
pos, ok := p.st.pos(src)
|
||||
if !ok {
|
||||
pos = hubOffsets[src]
|
||||
}
|
||||
f := tail.NewFollower(path, toTail(pos))
|
||||
f.MaxLine = wire.MaxLine
|
||||
if p.cfg.Poll > 0 {
|
||||
f.Poll = p.cfg.Poll
|
||||
}
|
||||
ss := &srcStat{src: src, f: f}
|
||||
p.stats = append(p.stats, ss)
|
||||
f.Oversize = func() { ss.oversize.Add(1) }
|
||||
f.HandleAt = func(line []byte, end tail.Pos) {
|
||||
ss.lines.Add(1)
|
||||
ss.lastLine.Store(time.Now().Unix())
|
||||
it := item{line: wire.Line{Src: src, Text: strings.ToValidUTF8(string(line), "�"), End: fromTail(end)}}
|
||||
select {
|
||||
case p.in <- it:
|
||||
case <-ctx.Done():
|
||||
}
|
||||
}
|
||||
p.wg.Add(1)
|
||||
go func() { defer p.wg.Done(); f.Run(ctx) }()
|
||||
}
|
||||
p.wg.Add(1)
|
||||
go func() { defer p.wg.Done(); p.watchFiles(ctx) }()
|
||||
}
|
||||
|
||||
// watchFiles sends containers.map and resolv.conf whole whenever they change,
|
||||
// and again after each reconnect.
|
||||
func (p *probe) watchFiles(ctx context.Context) {
|
||||
files := []struct{ name, path string }{
|
||||
{wire.FileContainers, p.cfg.Containers},
|
||||
{wire.FileResolv, p.cfg.Resolv},
|
||||
}
|
||||
sums := map[string][32]byte{}
|
||||
check := func() {
|
||||
for _, f := range files {
|
||||
if f.path == "" {
|
||||
continue
|
||||
}
|
||||
b, err := readSmall(f.path)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
sum := sha256.Sum256(b)
|
||||
if old, ok := sums[f.name]; ok && old == sum {
|
||||
continue
|
||||
}
|
||||
sums[f.name] = sum
|
||||
select {
|
||||
case p.in <- item{file: &wire.File{Name: f.name, Data: strings.ToValidUTF8(string(b), "�")}}:
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
check()
|
||||
t := time.NewTicker(p.fileEvery)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-p.resendFiles:
|
||||
clear(sums)
|
||||
check()
|
||||
case <-t.C:
|
||||
check()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func readSmall(path string) ([]byte, error) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
fi, err := f.Stat()
|
||||
if err != nil || fi.Size() > wire.MaxFileBytes {
|
||||
return nil, errors.New("unusable file")
|
||||
}
|
||||
b := make([]byte, fi.Size())
|
||||
n, err := f.Read(b)
|
||||
if err != nil && n == 0 && fi.Size() > 0 {
|
||||
return nil, err
|
||||
}
|
||||
return b[:n], nil
|
||||
}
|
||||
|
||||
// collect groups items into batches (flush interval, 5000 lines or 1 MiB),
|
||||
// writes each to the spool and records the positions it covers.
|
||||
func (p *probe) collect(ctx context.Context) {
|
||||
var (
|
||||
b wire.Batch
|
||||
size int
|
||||
pos = map[string]wire.Pos{}
|
||||
)
|
||||
flush := func() {
|
||||
if len(b.Lines) == 0 && len(b.Files) == 0 {
|
||||
return
|
||||
}
|
||||
nl := uint64(len(b.Lines))
|
||||
p.st.commit(func(seq uint64) uint64 {
|
||||
b.Seq = seq
|
||||
b.Sent = time.Now().UnixMilli()
|
||||
dropped, err := p.spool.Add(b)
|
||||
if err != nil {
|
||||
p.log.Error("spool write failed", "err", err)
|
||||
return nl
|
||||
}
|
||||
if dropped > 0 {
|
||||
p.log.Warn("spool full, oldest batches dropped", "lines", dropped)
|
||||
}
|
||||
return dropped
|
||||
}, pos)
|
||||
b, size = wire.Batch{Lines: make([]wire.Line, 0, 512)}, 0
|
||||
clear(pos)
|
||||
select {
|
||||
case p.notify <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
add := func(it item) {
|
||||
if it.file != nil {
|
||||
replaced := false
|
||||
for i := range b.Files {
|
||||
if b.Files[i].Name == it.file.Name {
|
||||
b.Files[i], replaced = *it.file, true
|
||||
}
|
||||
}
|
||||
if !replaced {
|
||||
b.Files = append(b.Files, *it.file)
|
||||
}
|
||||
size += len(it.file.Data)
|
||||
} else {
|
||||
b.Lines = append(b.Lines, it.line)
|
||||
pos[it.line.Src] = it.line.End
|
||||
size += len(it.line.Text) + 48
|
||||
}
|
||||
if len(b.Lines) >= wire.MaxLines || size >= batchBytes {
|
||||
flush()
|
||||
}
|
||||
}
|
||||
t := time.NewTicker(p.flushEvery())
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case it := <-p.in:
|
||||
add(it)
|
||||
case <-t.C:
|
||||
flush()
|
||||
case <-ctx.Done():
|
||||
for {
|
||||
select {
|
||||
case it := <-p.in:
|
||||
add(it)
|
||||
default:
|
||||
flush()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -94,23 +94,3 @@ func (s *Server) egressReport(ctx context.Context, from, to int64, local, peers
|
||||
}
|
||||
return rep, peerOn
|
||||
}
|
||||
|
||||
// peerEgress: GET /api/v1/peer/egress, the local report a hub merges; opened
|
||||
// only by the peer token (and --peer-allow). It must be registered next to
|
||||
// the other peer routes.
|
||||
func (s *Server) peerEgress(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.peerGate(w, r) {
|
||||
return
|
||||
}
|
||||
eng := egressEngine.Load()
|
||||
if eng == nil {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "egress is not enabled"})
|
||||
return
|
||||
}
|
||||
rg, ok := s.rangeOf(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
from, to := rg.Bounds(s.opt.Store.Now().Unix())
|
||||
writeJSON(w, 200, eng.Report(from, to))
|
||||
}
|
||||
@@ -1,9 +1,6 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/netip"
|
||||
"strconv"
|
||||
"testing"
|
||||
@@ -70,30 +67,4 @@ func TestEgressAPI(t *testing.T) {
|
||||
if w := do(h, "GET", "/api/v1/egress?range=24h", map[string]string{"Authorization": "Bearer peer-secret"}, nil); w.Code == 200 {
|
||||
t.Fatalf("peer token must not open the user route")
|
||||
}
|
||||
|
||||
// peer endpoint (registered by the daemon next to the other peer routes)
|
||||
s := &Server{opt: Options{PeerTokens: []string{"peer-secret"}, Token: userTok, Store: st, Now: time.Now}, ses: newSessions(), lim: newLimiter()}
|
||||
m := http.NewServeMux()
|
||||
m.HandleFunc("GET /api/v1/peer/egress", s.peerEgress)
|
||||
call := func(tok string) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest("GET", "/api/v1/peer/egress?range=24h", nil)
|
||||
r.RemoteAddr = "198.51.100.1:1234"
|
||||
if tok != "" {
|
||||
r.Header.Set("Authorization", "Bearer "+tok)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
m.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
if w := call(""); w.Code != 401 {
|
||||
t.Fatalf("peer no token: %d", w.Code)
|
||||
}
|
||||
if w := call(userTok); w.Code != 401 {
|
||||
t.Fatalf("user token on peer route: %d", w.Code)
|
||||
}
|
||||
w := call("peer-secret")
|
||||
var rep egress.Report
|
||||
if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &rep) != nil || len(rep.Findings) == 0 {
|
||||
t.Fatalf("peer: %d %s", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
+41
-105
@@ -3,13 +3,10 @@ package server
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
|
||||
)
|
||||
@@ -20,16 +17,6 @@ var enforceEngine atomic.Pointer[enforce.Engine]
|
||||
// SetEnforce installs the engine the enforce endpoints talk to.
|
||||
func SetEnforce(e *enforce.Engine) { enforceEngine.Store(e) }
|
||||
|
||||
// peerRoute is a route opened by the federation token, contributed by its own file.
|
||||
type peerRoute struct {
|
||||
pattern string
|
||||
handler func(*Server) http.HandlerFunc
|
||||
}
|
||||
|
||||
var peerRoutes []peerRoute
|
||||
|
||||
const maxDecisionBody = 64 << 10
|
||||
|
||||
func init() {
|
||||
registerUserRoute("GET /api/v1/enforce", func(s *Server) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -44,15 +31,19 @@ func init() {
|
||||
}
|
||||
out := map[string]any{"mode": enforce.ModeOff, "share": "off", "threshold": 0, "log_writable": false,
|
||||
"allows": []enforce.Allow{}, "unban_log_writable": false, "coverage": enforce.Coverage{}, "counts": enforce.Counts{Skipped: map[string]int{}}, "recent": []enforce.Recent{}}
|
||||
if e := enforceEngine.Load(); e != nil {
|
||||
if e := s.enforceFor(r.URL.Query().Get("host")); e != nil {
|
||||
rep := e.Report(from)
|
||||
share := "off"
|
||||
if e.Share() {
|
||||
share = "on"
|
||||
}
|
||||
out["mode"], out["share"], out["threshold"] = e.Mode(), share, e.Threshold()
|
||||
out["log_writable"] = enforce.Writable(e.LogPath())
|
||||
out["unban_log_writable"] = enforce.Writable(e.UnbanLogPath())
|
||||
if e.HasSink() { // the probe writes the files: queueing is always possible
|
||||
out["log_writable"], out["unban_log_writable"] = true, true
|
||||
} else {
|
||||
out["log_writable"] = enforce.Writable(e.LogPath())
|
||||
out["unban_log_writable"] = enforce.Writable(e.UnbanLogPath())
|
||||
}
|
||||
out["allows"] = e.Allows()
|
||||
out["coverage"], out["counts"], out["recent"] = rep.Coverage, rep.Counts, rep.Recent
|
||||
}
|
||||
@@ -61,80 +52,6 @@ func init() {
|
||||
})
|
||||
registerUserRoute("POST /api/v1/enforce/unban", func(s *Server) http.HandlerFunc { return s.enforceUnban })
|
||||
registerUserRoute("DELETE /api/v1/enforce/allow", func(s *Server) http.HandlerFunc { return s.enforceEndAllow })
|
||||
peerRoutes = append(peerRoutes,
|
||||
peerRoute{"POST /api/v1/peer/unban", func(s *Server) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
e := enforceEngine.Load()
|
||||
if !s.peerGate(w, r) {
|
||||
return
|
||||
}
|
||||
if e == nil || !e.Share() {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "decision sharing is not enabled"})
|
||||
return
|
||||
}
|
||||
var in struct {
|
||||
Unbans []enforce.UnbanWire `json:"unbans"`
|
||||
}
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxDecisionBody)).Decode(&in); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]int{"accepted": e.AcceptPeerUnban(r.URL.Query().Get("from"), in.Unbans)})
|
||||
}
|
||||
}},
|
||||
peerRoute{"GET /api/v1/peer/decisions", func(s *Server) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
e := enforceEngine.Load()
|
||||
if !s.peerGate(w, r) {
|
||||
return
|
||||
}
|
||||
if e == nil || !e.Share() || e.Mode() != enforce.ModeOn {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "decision sharing is not enabled"})
|
||||
return
|
||||
}
|
||||
since, _ := strconv.ParseInt(r.URL.Query().Get("since"), 10, 64)
|
||||
if min := s.opt.Now().Add(-24 * time.Hour).Unix(); since < min {
|
||||
since = min
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"decisions": e.LocalSince(since)})
|
||||
}
|
||||
}},
|
||||
peerRoute{"POST /api/v1/peer/decisions", func(s *Server) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
e := enforceEngine.Load()
|
||||
if !s.peerGate(w, r) {
|
||||
return
|
||||
}
|
||||
if e == nil || !e.Share() {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "decision sharing is not enabled"})
|
||||
return
|
||||
}
|
||||
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxDecisionBody))
|
||||
if err != nil {
|
||||
var mb *http.MaxBytesError
|
||||
if errors.As(err, &mb) {
|
||||
writeJSON(w, http.StatusRequestEntityTooLarge, map[string]string{"error": "body too large"})
|
||||
} else {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "unreadable body"})
|
||||
}
|
||||
return
|
||||
}
|
||||
var in struct {
|
||||
Decisions []enforce.Wire `json:"decisions"`
|
||||
}
|
||||
if json.Unmarshal(body, &in) != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON"})
|
||||
return
|
||||
}
|
||||
if len(in.Decisions) > enforce.MaxWire {
|
||||
writeJSON(w, http.StatusRequestEntityTooLarge, map[string]string{"error": "too many decisions"})
|
||||
return
|
||||
}
|
||||
acc, bad := e.AcceptPeer(r.URL.Query().Get("from"), in.Decisions)
|
||||
writeJSON(w, http.StatusOK, map[string]int{"accepted": acc, "invalid": bad})
|
||||
}
|
||||
}},
|
||||
)
|
||||
}
|
||||
|
||||
const maxUnbanBody = 1 << 10
|
||||
@@ -144,14 +61,10 @@ func (s *Server) enforceUnban(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "cross-site request refused"})
|
||||
return
|
||||
}
|
||||
e := enforceEngine.Load()
|
||||
if e == nil {
|
||||
writeJSON(w, http.StatusConflict, map[string]string{"error": "the second firewall is off"})
|
||||
return
|
||||
}
|
||||
var in struct {
|
||||
IP string `json:"ip"`
|
||||
AllowS int `json:"allow_s"`
|
||||
Host string `json:"host"`
|
||||
}
|
||||
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxUnbanBody))
|
||||
dec.DisallowUnknownFields()
|
||||
@@ -160,18 +73,41 @@ func (s *Server) enforceUnban(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
a, err := netip.ParseAddr(strings.TrimSpace(in.IP))
|
||||
if err != nil || a.Zone() != "" || in.AllowS < 0 || in.AllowS > enforce.MaxAllow {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid ip or allow_s"})
|
||||
if err != nil || a.Zone() != "" || in.AllowS < 0 || in.AllowS > enforce.MaxAllow || len(in.Host) > 64 {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid ip, host or allow_s"})
|
||||
return
|
||||
}
|
||||
switch err := e.Unban(a, in.AllowS, "local"); {
|
||||
case errors.Is(err, enforce.ErrNoUnbanLog):
|
||||
writeJSON(w, http.StatusConflict, map[string]string{"error": "unban file not configured"})
|
||||
case err != nil:
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not write the unban request"})
|
||||
default:
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "ip": a.Unmap().String(), "allow_s": in.AllowS})
|
||||
var engines []*enforce.Engine
|
||||
if in.Host == "all" {
|
||||
hosts := []string{s.primaryName()}
|
||||
if s.opt.Nodes != nil {
|
||||
hosts = s.opt.Nodes.Hosts()
|
||||
}
|
||||
for _, h := range hosts {
|
||||
if e := s.enforceFor(h); e != nil {
|
||||
engines = append(engines, e)
|
||||
}
|
||||
}
|
||||
} else if e := s.enforceFor(in.Host); e != nil {
|
||||
engines = append(engines, e)
|
||||
}
|
||||
if len(engines) == 0 {
|
||||
writeJSON(w, http.StatusConflict, map[string]string{"error": "the second firewall is off"})
|
||||
return
|
||||
}
|
||||
done := 0
|
||||
for _, e := range engines {
|
||||
switch err := e.Unban(a, in.AllowS, "local"); {
|
||||
case errors.Is(err, enforce.ErrNoUnbanLog):
|
||||
writeJSON(w, http.StatusConflict, map[string]string{"error": "unban file not configured"})
|
||||
return
|
||||
case err != nil:
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not write the unban request"})
|
||||
return
|
||||
}
|
||||
done++
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "ip": a.Unmap().String(), "allow_s": in.AllowS, "hosts": done})
|
||||
}
|
||||
|
||||
func (s *Server) enforceEndAllow(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -179,7 +115,7 @@ func (s *Server) enforceEndAllow(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "cross-site request refused"})
|
||||
return
|
||||
}
|
||||
e := enforceEngine.Load()
|
||||
e := s.enforceFor(r.URL.Query().Get("host"))
|
||||
a, err := netip.ParseAddr(r.URL.Query().Get("ip"))
|
||||
if e == nil || err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid ip"})
|
||||
|
||||
@@ -24,7 +24,7 @@ func enforceRig(t *testing.T, share bool) (http.Handler, *enforce.Engine, string
|
||||
st.SetIngestHook(e.Observe)
|
||||
SetEnforce(e)
|
||||
t.Cleanup(func() { SetEnforce(nil) })
|
||||
return New(Options{Token: userTok, PeerTokens: []string{peerTok}, Version: "t", Store: st}), e, log
|
||||
return New(Options{Token: userTok, Version: "t", Store: st}), e, log
|
||||
}
|
||||
|
||||
func TestEnforceAPI(t *testing.T) {
|
||||
@@ -66,9 +66,6 @@ func TestEnforceAPI(t *testing.T) {
|
||||
if w := do(h, "GET", "/api/v1/enforce?range=24h", nil, nil); w.Code != 401 {
|
||||
t.Fatalf("anonymous %d", w.Code)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/enforce?range=24h", map[string]string{"Authorization": "Bearer " + peerTok}, nil); w.Code != 403 {
|
||||
t.Fatalf("peer token %d", w.Code)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/enforce?range=bad", cloneHdr(auth), nil); w.Code != 400 {
|
||||
t.Fatalf("bad range %d", w.Code)
|
||||
}
|
||||
@@ -96,69 +93,6 @@ func post(h http.Handler, path, tok, body string) *httptest.ResponseRecorder {
|
||||
return w
|
||||
}
|
||||
|
||||
func TestPeerDecisionsEndpoints(t *testing.T) {
|
||||
h, e, log := enforceRig(t, true)
|
||||
good := `{"decisions":[{"t":` + strconv.FormatInt(time.Now().Unix(), 10) + `,"ip":"203.0.114.9","reason":"sqli","score":80,"ttl":3600},` +
|
||||
`{"t":1,"ip":"203.0.114.10","reason":"x\ny","score":80,"ttl":3600},{"ip":"10.0.0.1","reason":"rce","ttl":60}]}`
|
||||
p := "/api/v1/peer/decisions?from=hostinger"
|
||||
for _, tok := range []string{"", "wrong-token-0123456789-abcdefghijklmnopqrs", userTok} {
|
||||
if w := post(h, p, tok, good); w.Code != 401 && w.Code != 403 {
|
||||
t.Fatalf("token %q: %d", tok, w.Code)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/peer/decisions", map[string]string{"Authorization": "Bearer " + tok}, nil); w.Code != 401 && w.Code != 403 {
|
||||
t.Fatalf("GET token %q: %d", tok, w.Code)
|
||||
}
|
||||
}
|
||||
if w := post(h, p, peerTok, strings.Repeat(" ", 70<<10)); w.Code != 413 {
|
||||
t.Fatalf("big body: %d", w.Code)
|
||||
}
|
||||
if w := post(h, p, peerTok, "{nope"); w.Code != 400 {
|
||||
t.Fatalf("bad json: %d", w.Code)
|
||||
}
|
||||
var many strings.Builder
|
||||
many.WriteString(`{"decisions":[`)
|
||||
for i := 0; i < 501; i++ {
|
||||
if i > 0 {
|
||||
many.WriteString(",")
|
||||
}
|
||||
many.WriteString(`{"ip":"1.1.1.1"}`)
|
||||
}
|
||||
many.WriteString(`]}`)
|
||||
if w := post(h, p, peerTok, many.String()); w.Code != 413 {
|
||||
t.Fatalf("501 items: %d", w.Code)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go e.Run(ctx)
|
||||
e.Observe(core.Event{Time: time.Now(), IP: "203.0.114.9", Cat: core.Scanner, Source: "traefik", Method: "GET", Path: "/x", Status: 404, UA: "x"}, "")
|
||||
for i := 0; i < 200 && e.Report(0).Coverage.AttackIPs == 0; i++ {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
w := post(h, p, peerTok, good)
|
||||
if w.Code != 200 || !strings.Contains(w.Body.String(), `"accepted":1`) || !strings.Contains(w.Body.String(), `"invalid":2`) {
|
||||
t.Fatalf("%d %s", w.Code, w.Body)
|
||||
}
|
||||
b, _ := os.ReadFile(log)
|
||||
if strings.Count(string(b), "\n") != 1 || !strings.Contains(string(b), "ip=203.0.114.9 reason=sqli") || !strings.Contains(string(b), "src=peer:hostinger") {
|
||||
t.Fatalf("log %q", b)
|
||||
}
|
||||
// GET returns local decisions only
|
||||
if len(e.LocalSince(0)) != 0 {
|
||||
t.Fatal("peer decision leaked into the local list")
|
||||
}
|
||||
rr := do(h, "GET", "/api/v1/peer/decisions?since=0", map[string]string{"Authorization": "Bearer " + peerTok}, nil)
|
||||
if rr.Code != 200 || !strings.Contains(rr.Body.String(), `"decisions":[]`) {
|
||||
t.Fatalf("%d %s", rr.Code, rr.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerDecisionsShareOff(t *testing.T) {
|
||||
h, _, _ := enforceRig(t, false)
|
||||
if w := post(h, "/api/v1/peer/decisions", peerTok, `{"decisions":[]}`); w.Code != 404 {
|
||||
t.Fatalf("share off: %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnforceFromStoreHook(t *testing.T) {
|
||||
log := filepath.Join(t.TempDir(), "d.log")
|
||||
st := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour})
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -25,6 +26,10 @@ func init() {
|
||||
registerUserRoute("POST /api/v1/incidents", func(s *Server) http.HandlerFunc { return s.incidentCreate })
|
||||
registerUserRoute("PATCH /api/v1/incidents/{id}", func(s *Server) http.HandlerFunc { return s.incidentPatch })
|
||||
registerUserRoute("POST /api/v1/incidents/{id}/comments", func(s *Server) http.HandlerFunc { return s.incidentComment })
|
||||
// host/INC-n written as two path segments
|
||||
registerUserRoute("GET /api/v1/incidents/{host}/{id}", func(s *Server) http.HandlerFunc { return s.incidentGet })
|
||||
registerUserRoute("PATCH /api/v1/incidents/{host}/{id}", func(s *Server) http.HandlerFunc { return s.incidentPatch })
|
||||
registerUserRoute("POST /api/v1/incidents/{host}/{id}/comments", func(s *Server) http.HandlerFunc { return s.incidentComment })
|
||||
}
|
||||
|
||||
var incidentServer atomic.Pointer[Server]
|
||||
@@ -55,14 +60,31 @@ func StartIncidentSync(ctx context.Context, wg *sync.WaitGroup) {
|
||||
}
|
||||
|
||||
func (s *Server) syncNow(ctx context.Context) {
|
||||
if s.opt.Incidents == nil || egressEngine.Load() == nil {
|
||||
if s.opt.Incidents == nil {
|
||||
return
|
||||
}
|
||||
now := s.opt.Store.Now().Unix()
|
||||
if s.opt.Nodes != nil { // one store per node, fed by that node's own egress
|
||||
for _, h := range s.opt.Nodes.Hosts() {
|
||||
eng, st := s.opt.Nodes.Egress(h), s.opt.Nodes.Incidents(h)
|
||||
if eng == nil || st == nil {
|
||||
continue
|
||||
}
|
||||
rep := eng.Report(now-24*3600, now)
|
||||
for i := range rep.Findings {
|
||||
rep.Findings[i].Host = h
|
||||
}
|
||||
s.syncInto(st, rep)
|
||||
}
|
||||
return
|
||||
}
|
||||
if egressEngine.Load() == nil {
|
||||
return
|
||||
}
|
||||
cctx, cancel := context.WithTimeout(ctx, 20*time.Second)
|
||||
defer cancel()
|
||||
rep, _ := s.egressReport(cctx, now-24*3600, now, true, s.opt.Hub != nil, "")
|
||||
s.syncIncidents(rep)
|
||||
s.syncInto(s.opt.Incidents, rep)
|
||||
}
|
||||
|
||||
func (s *Server) findingHost(f egress.Finding) string {
|
||||
@@ -76,8 +98,10 @@ func (s *Server) findingKey(f egress.Finding) string {
|
||||
return incidents.Key(s.findingHost(f), f.Kind, f.Workload, f.Dst, f.DPort, f.Proto)
|
||||
}
|
||||
|
||||
func (s *Server) syncIncidents(rep egress.Report) {
|
||||
if s.opt.Incidents == nil {
|
||||
func (s *Server) syncIncidents(rep egress.Report) { s.syncInto(s.opt.Incidents, rep) }
|
||||
|
||||
func (s *Server) syncInto(st *incidents.Store, rep egress.Report) {
|
||||
if st == nil {
|
||||
return
|
||||
}
|
||||
fs := make([]incidents.Finding, 0, len(rep.Findings))
|
||||
@@ -85,7 +109,7 @@ func (s *Server) syncIncidents(rep egress.Report) {
|
||||
fs = append(fs, incidents.Finding{Host: s.findingHost(f), Kind: f.Kind, Severity: f.Severity, Workload: f.Workload, Dst: f.Dst,
|
||||
Proto: f.Proto, Detail: f.Detail, DPort: f.DPort, First: f.First, Last: f.Last, Count: f.Count})
|
||||
}
|
||||
s.opt.Incidents.Sync(fs)
|
||||
st.Sync(fs)
|
||||
}
|
||||
|
||||
// annotateFindings fills ticket_id/ticket_status/suppressed and, unless show
|
||||
@@ -95,16 +119,35 @@ func (s *Server) annotateFindings(rep *egress.Report, show bool) int {
|
||||
if s.opt.Incidents == nil || len(rep.Findings) == 0 {
|
||||
return 0
|
||||
}
|
||||
keys := make([]string, len(rep.Findings))
|
||||
refs := make([]incidents.Ref, len(rep.Findings))
|
||||
has := make([]bool, len(rep.Findings))
|
||||
byStore := map[string][]int{}
|
||||
for i, f := range rep.Findings {
|
||||
keys[i] = s.findingKey(f)
|
||||
h := s.findingHost(f)
|
||||
byStore[h] = append(byStore[h], i)
|
||||
}
|
||||
for h, idx := range byStore {
|
||||
st := s.incStore(h)
|
||||
if st == nil {
|
||||
continue
|
||||
}
|
||||
keys := make([]string, len(idx))
|
||||
for j, i := range idx {
|
||||
keys[j] = s.findingKey(rep.Findings[i])
|
||||
}
|
||||
m := st.Lookup(keys)
|
||||
for j, i := range idx {
|
||||
if ref, ok := m[keys[j]]; ok {
|
||||
ref.ID = h + "/" + ref.ID
|
||||
refs[i], has[i] = ref, true
|
||||
}
|
||||
}
|
||||
}
|
||||
refs := s.opt.Incidents.Lookup(keys)
|
||||
out := rep.Findings[:0:0]
|
||||
n := 0
|
||||
for i, f := range rep.Findings {
|
||||
if ref, ok := refs[keys[i]]; ok {
|
||||
f.TicketID, f.TicketStatus, f.Suppressed = ref.ID, ref.Status, ref.Suppress
|
||||
if has[i] {
|
||||
f.TicketID, f.TicketStatus, f.Suppressed = refs[i].ID, refs[i].Status, refs[i].Suppress
|
||||
}
|
||||
if f.Suppressed {
|
||||
n++
|
||||
@@ -191,6 +234,54 @@ func (s *Server) incidentQuery(w http.ResponseWriter, r *http.Request) (incident
|
||||
return q, true
|
||||
}
|
||||
|
||||
// qSummary and qTicket carry the id qualified by the node ("hostinger/INC-2")
|
||||
// and the node as host.
|
||||
type qSummary struct {
|
||||
incidents.Summary
|
||||
ID string `json:"id"`
|
||||
Host string `json:"host"`
|
||||
}
|
||||
|
||||
type qTicket struct {
|
||||
incidents.Ticket
|
||||
ID string `json:"id"`
|
||||
Host string `json:"host"`
|
||||
}
|
||||
|
||||
type qPage struct {
|
||||
Items []qSummary `json:"items"`
|
||||
Total int `json:"total"`
|
||||
Counts map[string]int `json:"counts"`
|
||||
Store incidents.Stats `json:"store"`
|
||||
Hosts []string `json:"hosts"`
|
||||
}
|
||||
|
||||
// splitID reads "INC-n" with an optional host (path segment, "host/INC-n"
|
||||
// in one segment, or ?host=); without host the primary node is meant.
|
||||
func (s *Server) splitID(r *http.Request) (host, id string) {
|
||||
id = r.PathValue("id")
|
||||
host = r.PathValue("host")
|
||||
if h, rest, ok := strings.Cut(id, "/"); ok {
|
||||
host, id = h, rest
|
||||
}
|
||||
if host == "" {
|
||||
host = r.URL.Query().Get("host")
|
||||
}
|
||||
if host == "" {
|
||||
host = s.primaryName()
|
||||
}
|
||||
return host, id
|
||||
}
|
||||
|
||||
// storeFor answers 404 itself when the node has no ticket store.
|
||||
func (s *Server) storeFor(w http.ResponseWriter, host string) *incidents.Store {
|
||||
if st := s.incStore(host); st != nil {
|
||||
return st
|
||||
}
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "incident not found"})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) incidentList(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.incidentsOn(w) {
|
||||
return
|
||||
@@ -199,19 +290,93 @@ func (s *Server) incidentList(w http.ResponseWriter, r *http.Request) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, s.opt.Incidents.List(q))
|
||||
hosts := s.incHosts()
|
||||
if q.Host != "" && q.Host != "all" {
|
||||
hosts = []string{q.Host}
|
||||
if s.incStore(q.Host) == nil {
|
||||
writeJSON(w, 200, qPage{Items: []qSummary{}, Counts: map[string]int{}, Hosts: s.incHosts()})
|
||||
return
|
||||
}
|
||||
}
|
||||
q.Host = ""
|
||||
if len(hosts) == 1 {
|
||||
pg := s.incStore(hosts[0]).List(q)
|
||||
out := qPage{Items: make([]qSummary, 0, len(pg.Items)), Total: pg.Total, Counts: pg.Counts, Store: pg.Store, Hosts: s.incHosts()}
|
||||
for _, it := range pg.Items {
|
||||
out.Items = append(out.Items, qSummary{Summary: it, ID: hosts[0] + "/" + it.ID, Host: hosts[0]})
|
||||
}
|
||||
writeJSON(w, 200, out)
|
||||
return
|
||||
}
|
||||
// several nodes: merge, sort and page here
|
||||
all := []qSummary{}
|
||||
out := qPage{Counts: map[string]int{}, Hosts: s.incHosts()}
|
||||
page, per := q.Page, q.PerPage
|
||||
for _, h := range hosts {
|
||||
st := s.incStore(h)
|
||||
if st == nil {
|
||||
continue
|
||||
}
|
||||
pg := st.List(incidents.Query{Status: q.Status, Severity: q.Severity, Q: q.Q, Sort: q.Sort, Page: 1, PerPage: 1})
|
||||
for k, v := range pg.Counts {
|
||||
out.Counts[k] += v
|
||||
}
|
||||
out.Store.Size += pg.Store.Size
|
||||
out.Store.Max += pg.Store.Max
|
||||
out.Store.Untracked += pg.Store.Untracked
|
||||
for _, it := range st.All(q) {
|
||||
all = append(all, qSummary{Summary: it, ID: h + "/" + it.ID, Host: h})
|
||||
}
|
||||
}
|
||||
sortSummaries(all, q.Sort)
|
||||
if per <= 0 {
|
||||
per = 50
|
||||
}
|
||||
per = min(per, 200)
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
lo := min((page-1)*per, len(all))
|
||||
hi := min(lo+per, len(all))
|
||||
out.Total, out.Items = len(all), all[lo:hi]
|
||||
if out.Items == nil {
|
||||
out.Items = []qSummary{}
|
||||
}
|
||||
writeJSON(w, 200, out)
|
||||
}
|
||||
|
||||
func sortSummaries(l []qSummary, mode string) {
|
||||
sort.SliceStable(l, func(i, j int) bool {
|
||||
a, b := l[i], l[j]
|
||||
switch mode {
|
||||
case "severity":
|
||||
if ra, rb := incidents.SevRank(a.Severity), incidents.SevRank(b.Severity); ra != rb {
|
||||
return ra > rb
|
||||
}
|
||||
case "last_seen":
|
||||
if a.LastSeen != b.LastSeen {
|
||||
return a.LastSeen > b.LastSeen
|
||||
}
|
||||
}
|
||||
return a.UpdatedAt > b.UpdatedAt
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) incidentGet(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.incidentsOn(w) {
|
||||
return
|
||||
}
|
||||
t, err := s.opt.Incidents.Get(r.PathValue("id"))
|
||||
host, id := s.splitID(r)
|
||||
st := s.storeFor(w, host)
|
||||
if st == nil {
|
||||
return
|
||||
}
|
||||
t, err := st.Get(id)
|
||||
if err != nil {
|
||||
incidentErr(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, t)
|
||||
writeJSON(w, 200, qTicket{Ticket: t, ID: host + "/" + t.ID, Host: host})
|
||||
}
|
||||
|
||||
func (s *Server) incidentCreate(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -223,12 +388,16 @@ func (s *Server) incidentCreate(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
in.Via = s.via(r)
|
||||
t, err := s.opt.Incidents.Create(in)
|
||||
host := s.primaryName()
|
||||
if in.Host != "" && s.incStore(in.Host) != nil {
|
||||
host = in.Host
|
||||
}
|
||||
t, err := s.incStore(host).Create(in)
|
||||
if err != nil {
|
||||
incidentErr(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, t)
|
||||
writeJSON(w, http.StatusCreated, qTicket{Ticket: t, ID: host + "/" + t.ID, Host: host})
|
||||
}
|
||||
|
||||
func (s *Server) incidentPatch(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -240,12 +409,17 @@ func (s *Server) incidentPatch(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
p.Via = s.via(r)
|
||||
t, err := s.opt.Incidents.Update(r.PathValue("id"), p)
|
||||
host, id := s.splitID(r)
|
||||
st := s.storeFor(w, host)
|
||||
if st == nil {
|
||||
return
|
||||
}
|
||||
t, err := st.Update(id, p)
|
||||
if err != nil {
|
||||
incidentErr(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, t)
|
||||
writeJSON(w, 200, qTicket{Ticket: t, ID: host + "/" + t.ID, Host: host})
|
||||
}
|
||||
|
||||
func (s *Server) incidentComment(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -259,12 +433,17 @@ func (s *Server) incidentComment(w http.ResponseWriter, r *http.Request) {
|
||||
if !incidentBody(w, r, &in) {
|
||||
return
|
||||
}
|
||||
t, err := s.opt.Incidents.AddComment(r.PathValue("id"), in.Text, in.Author, s.via(r))
|
||||
host, id := s.splitID(r)
|
||||
st := s.storeFor(w, host)
|
||||
if st == nil {
|
||||
return
|
||||
}
|
||||
t, err := st.AddComment(id, in.Text, in.Author, s.via(r))
|
||||
if err != nil {
|
||||
incidentErr(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, t)
|
||||
writeJSON(w, http.StatusCreated, qTicket{Ticket: t, ID: host + "/" + t.ID, Host: host})
|
||||
}
|
||||
|
||||
// csvCell neutralises spreadsheet formulas.
|
||||
@@ -301,7 +480,20 @@ func (s *Server) incidentCSV(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Disposition", `attachment; filename="incidents.csv"`)
|
||||
cw := csv.NewWriter(w)
|
||||
cw.Write([]string{"id", "status", "severity", "host", "kind", "workload", "dst", "dport", "proto", "title", "first_seen", "last_seen", "count", "assignee", "tags", "verdict", "suppress", "created_at", "updated_at"})
|
||||
for _, t := range s.opt.Incidents.All(q) {
|
||||
hosts := s.incHosts()
|
||||
if q.Host != "" && q.Host != "all" {
|
||||
hosts = []string{q.Host}
|
||||
}
|
||||
q.Host = ""
|
||||
var rows []qSummary
|
||||
for _, h := range hosts {
|
||||
if st := s.incStore(h); st != nil {
|
||||
for _, t := range st.All(q) {
|
||||
rows = append(rows, qSummary{Summary: t, ID: h + "/" + t.ID, Host: h})
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, t := range rows {
|
||||
row := []string{t.ID, t.Status, t.Severity, t.Host, t.Kind, t.Workload, t.Dst, strconv.Itoa(int(t.DPort)), t.Proto, t.Title,
|
||||
strconv.FormatInt(t.FirstSeen, 10), strconv.FormatInt(t.LastSeen, 10), strconv.Itoa(t.Count), t.Assignee, strings.Join(t.Tags, ","), t.Verdict,
|
||||
strconv.FormatBool(t.Suppress), strconv.FormatInt(t.CreatedAt, 10), strconv.FormatInt(t.UpdatedAt, 10)}
|
||||
|
||||
@@ -23,7 +23,7 @@ func incRig(t *testing.T) http.Handler {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return New(Options{Token: userTok, PeerTokens: []string{peerTok}, Version: "t", Store: st, Incidents: inc})
|
||||
return New(Options{Token: userTok, Version: "t", Store: st, Incidents: inc})
|
||||
}
|
||||
|
||||
func TestIncidentsEgressSuppression(t *testing.T) {
|
||||
@@ -50,11 +50,11 @@ func TestIncidentsEgressSuppression(t *testing.T) {
|
||||
f = m
|
||||
}
|
||||
}
|
||||
if f == nil || f["ticket_id"] != "INC-1" || f["ticket_status"] != "open" || f["suppressed"] != false || d["suppressed_count"].(float64) != 0 {
|
||||
if f == nil || f["ticket_id"] != "oracle/INC-1" || f["ticket_status"] != "open" || f["suppressed"] != false || d["suppressed_count"].(float64) != 0 {
|
||||
t.Fatalf("annotated: %v", d)
|
||||
}
|
||||
// suppression needs false_positive/benign
|
||||
if w := do(h, "GET", "/api/v1/incidents", cloneHdr(auth), nil); w.Code != 200 || !strings.Contains(w.Body.String(), `"INC-1"`) || strings.Contains(w.Body.String(), `"history"`) || !strings.Contains(w.Body.String(), `"comment_count"`) {
|
||||
if w := do(h, "GET", "/api/v1/incidents", cloneHdr(auth), nil); w.Code != 200 || !strings.Contains(w.Body.String(), `"oracle/INC-1"`) || strings.Contains(w.Body.String(), `"history"`) || !strings.Contains(w.Body.String(), `"comment_count"`) {
|
||||
t.Fatalf("list: %d %s", w.Code, w.Body)
|
||||
}
|
||||
if w := req(h, "PATCH", "/api/v1/incidents/INC-1", `{"suppress":true}`, auth); w.Code != 409 {
|
||||
@@ -99,9 +99,6 @@ func TestIncidentsAPI(t *testing.T) {
|
||||
if w := req(h, p[0], p[1], `{}`, nil); w.Code != 401 {
|
||||
t.Errorf("%v no auth: %d", p, w.Code)
|
||||
}
|
||||
if w := req(h, p[0], p[1], `{}`, map[string]string{"Authorization": "Bearer " + peerTok}); w.Code != 403 {
|
||||
t.Errorf("%v peer token: %d", p, w.Code)
|
||||
}
|
||||
}
|
||||
cross := map[string]string{"Authorization": "Bearer " + userTok, "Sec-Fetch-Site": "cross-site"}
|
||||
for _, p := range paths[2:5] {
|
||||
@@ -115,7 +112,7 @@ func TestIncidentsAPI(t *testing.T) {
|
||||
}
|
||||
var tk map[string]any
|
||||
json.Unmarshal(w.Body.Bytes(), &tk)
|
||||
if tk["id"] != "INC-1" || tk["source"] != "manual" || tk["status"] != "open" {
|
||||
if tk["id"] != "oracle/INC-1" || tk["source"] != "manual" || tk["status"] != "open" {
|
||||
t.Fatalf("ticket: %v", tk)
|
||||
}
|
||||
bad := []struct{ m, p, b string }{
|
||||
|
||||
@@ -22,7 +22,7 @@ func unbanRig(t *testing.T) (http.Handler, *enforce.Engine, string) {
|
||||
Host: "oracle", Threshold: 3, Share: true})
|
||||
SetEnforce(e)
|
||||
t.Cleanup(func() { SetEnforce(nil) })
|
||||
return New(Options{Token: userTok, PeerTokens: []string{peerTok}, Version: "t", Store: st}), e, filepath.Join(dir, "unban.log")
|
||||
return New(Options{Token: userTok, Version: "t", Store: st}), e, filepath.Join(dir, "unban.log")
|
||||
}
|
||||
|
||||
func req(h http.Handler, method, path, body string, hdr map[string]string) *httptest.ResponseRecorder {
|
||||
@@ -42,9 +42,6 @@ func TestUnbanRoute(t *testing.T) {
|
||||
if w := req(h, "POST", "/api/v1/enforce/unban", `{"ip":"203.0.113.7","allow_s":60}`, nil); w.Code != 401 {
|
||||
t.Fatalf("no auth: %d", w.Code)
|
||||
}
|
||||
if w := req(h, "POST", "/api/v1/enforce/unban", `{"ip":"203.0.113.7"}`, map[string]string{"Authorization": "Bearer " + peerTok}); w.Code != 403 {
|
||||
t.Fatalf("peer token: %d", w.Code)
|
||||
}
|
||||
cross := map[string]string{"Authorization": "Bearer " + userTok, "Sec-Fetch-Site": "cross-site"}
|
||||
if w := req(h, "POST", "/api/v1/enforce/unban", `{"ip":"203.0.113.7"}`, cross); w.Code != 403 {
|
||||
t.Fatalf("cross-site: %d", w.Code)
|
||||
@@ -96,24 +93,3 @@ func TestUnbanRoute(t *testing.T) {
|
||||
t.Fatal("DELETE wrote to the host file")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerUnbanRoute(t *testing.T) {
|
||||
h, e, file := unbanRig(t)
|
||||
peer := map[string]string{"Authorization": "Bearer " + peerTok}
|
||||
if w := req(h, "POST", "/api/v1/peer/unban?from=hostinger", `{"unbans":[{"ip":"203.0.113.7","allow":3600},{"ip":"bad","allow":1}]}`, map[string]string{"Authorization": "Bearer " + userTok}); w.Code == 200 {
|
||||
t.Fatalf("user token accepted on peer route")
|
||||
}
|
||||
w := req(h, "POST", "/api/v1/peer/unban?from=hostinger", `{"unbans":[{"ip":"203.0.113.7","allow":3600},{"ip":"bad","allow":1}]}`, peer)
|
||||
if w.Code != 200 || !strings.Contains(w.Body.String(), `"accepted":1`) {
|
||||
t.Fatalf("%d %s", w.Code, w.Body)
|
||||
}
|
||||
if len(e.Allows()) != 1 {
|
||||
t.Fatal("peer allow not applied")
|
||||
}
|
||||
if b, _ := os.ReadFile(file); !strings.Contains(string(b), "ip=203.0.113.7 allow=3600") {
|
||||
t.Fatalf("file: %q", b)
|
||||
}
|
||||
if len(e.UnbansSince(0)) != 0 {
|
||||
t.Fatal("peer unban must not be echoed back")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
// fakeBackend is an in-process node serving a fixed export.
|
||||
type fakeBackend struct {
|
||||
name string
|
||||
exp store.PeerExport
|
||||
}
|
||||
|
||||
func (f fakeBackend) Name() string { return f.name }
|
||||
func (f fakeBackend) Export(store.Range) store.PeerExport { return f.exp }
|
||||
func (f fakeBackend) Study(q store.PeriodQuery) store.PeerStudy {
|
||||
return store.PeerStudy{}
|
||||
}
|
||||
func (f fakeBackend) Egress(from, to int64) json.RawMessage { return nil }
|
||||
func (f fakeBackend) Subscribe() (<-chan store.LiveEvent, func()) {
|
||||
return make(chan store.LiveEvent), func() {}
|
||||
}
|
||||
func (f fakeBackend) SubscribeVisits() (<-chan store.VisitMsg, func()) {
|
||||
return make(chan store.VisitMsg), func() {}
|
||||
}
|
||||
func (f fakeBackend) Online() bool { return true }
|
||||
func (f fakeBackend) Location() *store.Location { return nil }
|
||||
@@ -1,15 +1,12 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -50,12 +47,9 @@ func TestBlocklistRevalidatesPeerRowsAndAdmins(t *testing.T) {
|
||||
{IP: "2606:4700:0:7::/64", Score: 80, Strong: true},
|
||||
{IP: "5.6.7.8", Score: 99, Strong: false},
|
||||
}
|
||||
peer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(exp) }))
|
||||
defer peer.Close()
|
||||
hub := fed.NewHub([]fed.Peer{{Name: "p", URL: peer.URL}}, ptok)
|
||||
hub.Refresh(context.Background())
|
||||
hub := fed.NewHub(func() []fed.Backend { return []fed.Backend{fakeBackend{name: "p", exp: exp}} })
|
||||
st := store.New(store.Config{Name: "me", Version: "t"})
|
||||
h := New(Options{Token: utok, PeerTokens: []string{ptok}, Store: st, Hub: hub, Ignore: mustPrefixes("8.8.4.4/32")})
|
||||
h := New(Options{Token: utok, Store: st, Hub: hub, Ignore: mustPrefixes("8.8.4.4/32")})
|
||||
code, body := bearerGet(h, "/api/v1/blocklist.txt")
|
||||
if code != 200 {
|
||||
t.Fatal(code)
|
||||
@@ -185,59 +179,3 @@ func TestClientIPVectors(t *testing.T) {
|
||||
t.Fatal("a peer outside the trusted list is the client")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentHubAndStoreUnderLoad(t *testing.T) {
|
||||
pst := store.New(store.Config{Name: "peer", Version: "t"})
|
||||
ph := New(Options{Token: utok, PeerTokens: []string{ptok}, Store: pst})
|
||||
ps := httptest.NewServer(ph)
|
||||
defer ps.Close()
|
||||
hub := fed.NewHub([]fed.Peer{{Name: "peer", URL: ps.URL}}, ptok)
|
||||
hub.Interval = 20 * time.Millisecond
|
||||
st := store.New(store.Config{Name: "me", Version: "t", MaxIPs: 3000})
|
||||
srv := httptest.NewServer(New(Options{Token: utok, PeerTokens: []string{ptok}, Store: st, Hub: hub}))
|
||||
defer srv.Close()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go hub.Run(ctx)
|
||||
var wg sync.WaitGroup
|
||||
stop := make(chan struct{})
|
||||
now := time.Now()
|
||||
for _, s := range []*store.Store{st, pst} {
|
||||
wg.Add(1)
|
||||
go func(s *store.Store) {
|
||||
defer wg.Done()
|
||||
for i := 0; ; i++ {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
default:
|
||||
}
|
||||
s.Ingest(core.Event{Time: now, IP: fmt.Sprintf("9.%d.%d.%d", i>>16&255, i>>8&255, i&255), Cat: core.Exploit, Source: "traefik", Path: "/x", Method: "GET", Domain: "d"})
|
||||
s.Traffic(core.Event{Time: now, IP: "3.3.3.3", Source: "traefik", Domain: "d", Method: "GET", Path: "/", Status: 200})
|
||||
}
|
||||
}(s)
|
||||
}
|
||||
paths := []string{"/api/v1/summary", "/api/v1/summary?host=peer", "/api/v1/ips?per=200&sort=events", "/api/v1/traffic?domain=d", "/api/v1/blocklist.json", "/api/v1/ip/9.0.0.1"}
|
||||
for g := 0; g < 6; g++ {
|
||||
wg.Add(1)
|
||||
go func(g int) {
|
||||
defer wg.Done()
|
||||
for i := 0; ; i++ {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
default:
|
||||
}
|
||||
req, _ := http.NewRequest("GET", srv.URL+paths[(g+i)%len(paths)], nil)
|
||||
req.Header.Set("Authorization", "Bearer "+utok)
|
||||
if r, err := http.DefaultClient.Do(req); err == nil {
|
||||
io.Copy(io.Discard, r.Body)
|
||||
r.Body.Close()
|
||||
}
|
||||
}
|
||||
}(g)
|
||||
}
|
||||
time.Sleep(1500 * time.Millisecond)
|
||||
close(stop)
|
||||
wg.Wait()
|
||||
}
|
||||
@@ -332,33 +332,6 @@ func (s *Server) metricsAPI(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, 200, out)
|
||||
}
|
||||
|
||||
// peerPeriod: GET /api/v1/peer/period, the study a hub merges; opened only by
|
||||
// the peer token (and --peer-allow). At most two run at once.
|
||||
func (s *Server) peerPeriod(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.peerGate(w, r) {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case s.study <- struct{}{}:
|
||||
defer func() { <-s.study }()
|
||||
default:
|
||||
w.Header().Set("Retry-After", "5")
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "busy"})
|
||||
return
|
||||
}
|
||||
eq, ok := s.eventFilter(w, r, 24*time.Hour)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
pq := store.PeriodQuery{From: eq.From, To: eq.To, Host: s.opt.Store.Name(), IP: eq.IP, Cat: eq.Cat, Fam: eq.Fam}
|
||||
if v := r.URL.Query().Get("gap"); v != "" {
|
||||
if n, err := strconv.ParseInt(v, 10, 64); err == nil && n >= 30 && n <= 86400 {
|
||||
pq.Gap = n
|
||||
}
|
||||
}
|
||||
writeJSON(w, 200, s.opt.Store.StudyFor(pq))
|
||||
}
|
||||
|
||||
// listed reproduces the blocklist rule for one row.
|
||||
func (s *Server) listed(x store.IPSummary) bool {
|
||||
if x.Score < 50 || !x.Strong || x.Admin {
|
||||
|
||||
@@ -1,18 +1,13 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"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"
|
||||
)
|
||||
|
||||
@@ -49,7 +44,7 @@ func geoSetup(t *testing.T) (http.Handler, map[string]string) {
|
||||
ing("200.3.3.3", core.BruteForce, 1, false)
|
||||
ing("9.9.9.9", core.SSHFail, 3, false)
|
||||
ing("8.8.8.8", core.Exploit, 1, false) // unknown geo: skipped
|
||||
h := New(Options{Token: utok, PeerTokens: []string{ptok}, Version: "t", Store: st})
|
||||
h := New(Options{Token: utok, Version: "t", Store: st})
|
||||
return h, map[string]string{"Authorization": "Bearer " + utok}
|
||||
}
|
||||
|
||||
@@ -124,9 +119,6 @@ func TestGeoAggregation(t *testing.T) {
|
||||
if w := do(h, "GET", "/api/v1/geo?host=nope", cloneHdr(u), nil); w.Code != 404 {
|
||||
t.Fatalf("unknown host: %d", w.Code)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/geo", map[string]string{"Authorization": "Bearer " + ptok}, nil); w.Code != 403 {
|
||||
t.Fatalf("peer token: %d", w.Code)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/geo", nil, nil); w.Code != 401 {
|
||||
t.Fatalf("anonymous: %d", w.Code)
|
||||
}
|
||||
@@ -179,127 +171,3 @@ func TestStaticAssetsWhitelist(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerStreamIsPeerOnly(t *testing.T) {
|
||||
old := sseHeartbeat
|
||||
sseHeartbeat = 50 * time.Millisecond
|
||||
defer func() { sseHeartbeat = old }()
|
||||
h, _ := geoSetup(t)
|
||||
if w := do(h, "GET", "/api/v1/peer/stream", map[string]string{"Authorization": "Bearer " + utok}, nil); w.Code != 401 {
|
||||
t.Fatalf("user token: %d", w.Code)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/peer/stream", nil, nil); w.Code != 401 {
|
||||
t.Fatalf("anonymous: %d", w.Code)
|
||||
}
|
||||
for _, p := range []string{"/api/v1/events/stream"} {
|
||||
if w := do(h, "GET", p, map[string]string{"Authorization": "Bearer " + ptok}, nil); w.Code != 403 {
|
||||
t.Fatalf("peer token on %s: %d", p, w.Code)
|
||||
}
|
||||
}
|
||||
h2 := New(Options{Token: utok, PeerAllow: mustPrefixes("203.0.113.0/24"), PeerTokens: []string{ptok}, Version: "t", Store: store.New(store.Config{Name: "x"})})
|
||||
if w := do(h2, "GET", "/api/v1/peer/stream", map[string]string{"Authorization": "Bearer " + ptok}, nil); w.Code != 403 {
|
||||
t.Fatalf("--peer-allow: %d", w.Code)
|
||||
}
|
||||
h3 := New(Options{Token: utok, Version: "t", Store: store.New(store.Config{Name: "x"})})
|
||||
if w := do(h3, "GET", "/api/v1/peer/stream", map[string]string{"Authorization": "Bearer " + ptok}, nil); w.Code != 404 {
|
||||
t.Fatalf("federation off: %d", w.Code)
|
||||
}
|
||||
|
||||
st := store.New(store.Config{Name: "edge", Version: "t", Location: &store.Location{Lat: 3, Lon: 4, Label: "Edge"}})
|
||||
st.SetEnricher(fakeGeo{})
|
||||
ts := httptest.NewServer(New(Options{Token: utok, PeerTokens: []string{ptok}, Version: "t", Store: st}))
|
||||
defer ts.Close()
|
||||
req, _ := http.NewRequest("GET", ts.URL+"/api/v1/peer/stream", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+ptok)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil || resp.StatusCode != 200 {
|
||||
t.Fatal(err, resp)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
go func() {
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
st.Ingest(core.Event{Time: time.Now(), IP: "200.1.1.9", Cat: core.OK, Source: "traefik"}) // not malicious, not sent
|
||||
st.Ingest(core.Event{Time: time.Now(), IP: "200.1.1.9", Cat: core.Scanner, Source: "traefik", Method: "GET", Path: "/wp"})
|
||||
}()
|
||||
sc := bufio.NewScanner(resp.Body)
|
||||
deadline := time.After(5 * time.Second)
|
||||
got := make(chan string, 1)
|
||||
go func() {
|
||||
for sc.Scan() {
|
||||
if strings.HasPrefix(sc.Text(), "data: ") {
|
||||
got <- sc.Text()[6:]
|
||||
return
|
||||
}
|
||||
}
|
||||
got <- ""
|
||||
}()
|
||||
select {
|
||||
case d := <-got:
|
||||
var e map[string]any
|
||||
if json.Unmarshal([]byte(d), &e) != nil || e["ip"] != "200.1.1.9" || e["cat"] != "scanner" || e["dst"].(map[string]any)["label"] != "Edge" || e["src"].(map[string]any)["cc"] != "BR" {
|
||||
t.Fatalf("peer event %s", d)
|
||||
}
|
||||
case <-deadline:
|
||||
t.Fatal("no event")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerBlocklistOffUsesLocalOnly(t *testing.T) {
|
||||
const ptk = "peer-secret-0123456789-abcdefghijklmnopqr"
|
||||
strongHits := func(st *store.Store, ip string) {
|
||||
for i := 0; i < 8; i++ {
|
||||
st.Ingest(core.Event{Time: time.Now(), IP: ip, Cat: core.Exploit, Strong: true, Source: "traefik", Method: "GET", Path: "/x"})
|
||||
}
|
||||
}
|
||||
remote := store.New(store.Config{Name: "remote"})
|
||||
strongHits(remote, "45.94.31.7") // only the peer saw it
|
||||
rs := httptest.NewServer(New(Options{Token: utok, PeerTokens: []string{ptk}, Store: remote}))
|
||||
defer rs.Close()
|
||||
p, _ := fed.ParsePeer("edge=" + rs.URL)
|
||||
hub := fed.NewHub([]fed.Peer{p}, ptk)
|
||||
hub.Refresh(context.Background())
|
||||
for _, off := range []bool{false, true} {
|
||||
st := store.New(store.Config{Name: "o"})
|
||||
strongHits(st, "45.94.31.5")
|
||||
hh := New(Options{Token: utok, Store: st, Hub: hub, LocalBlocklist: off})
|
||||
w := do(hh, "GET", "/api/v1/blocklist.txt", map[string]string{"Authorization": "Bearer " + utok}, nil)
|
||||
b := w.Body.String()
|
||||
if w.Code != 200 || !strings.Contains(b, "45.94.31.5") {
|
||||
t.Fatalf("off=%v: local IP missing: %d %s", off, w.Code, b)
|
||||
}
|
||||
if has := strings.Contains(b, "45.94.31.7"); has == off {
|
||||
t.Fatalf("off=%v: peer-only IP listed=%v: %s", off, has, b)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerStreamVisitsOnlyOnRequestAndNoIP(t *testing.T) {
|
||||
const ptok = "peer-secret-0123456789-abcdefghijklmnopqr"
|
||||
for _, q := range []string{"", "?visits=1"} {
|
||||
st := store.New(store.Config{Name: "edge", Version: "t"})
|
||||
st.SetEnricher(fakeGeo{})
|
||||
ts := httptest.NewServer(New(Options{Token: utok, PeerTokens: []string{ptok}, Version: "t", Store: st}))
|
||||
req, _ := http.NewRequest("GET", ts.URL+"/api/v1/peer/stream"+q, nil)
|
||||
req.Header.Set("Authorization", "Bearer "+ptok)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil || resp.StatusCode != 200 {
|
||||
t.Fatal(err, resp)
|
||||
}
|
||||
go func() {
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
st.Traffic(core.Event{Time: time.Now(), IP: "200.1.1.9", Cat: core.OK, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/", Status: 200, UA: "Mozilla/5.0 x",
|
||||
E: core.Enrich{Device: "desktop"}})
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
resp.Body.Close()
|
||||
}()
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
got := strings.Contains(string(body), "event: visit")
|
||||
if got != (q != "") {
|
||||
t.Fatalf("query %q: visit event present=%v\n%s", q, got, body)
|
||||
}
|
||||
if strings.Contains(string(body), "200.1.1.9") || strings.Contains(string(body), `"ip"`) || strings.Contains(string(body), "Mozilla") {
|
||||
t.Fatalf("address in stream: %s", body)
|
||||
}
|
||||
ts.Close()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/hub"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/incidents"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
|
||||
)
|
||||
|
||||
// ProbeAPI is the hub side of the probe protocol and of probe management
|
||||
// (implemented by *hub.Manager).
|
||||
type ProbeAPI interface {
|
||||
Authenticate(r *http.Request) (string, bool)
|
||||
Hello(w http.ResponseWriter, r *http.Request, name string)
|
||||
Push(w http.ResponseWriter, r *http.Request, name string)
|
||||
Commands(w http.ResponseWriter, r *http.Request, name string)
|
||||
List() []hub.ProbeInfo
|
||||
Info(name string) (hub.ProbeInfo, bool)
|
||||
Create(name string) (string, error)
|
||||
Revoke(name string) error
|
||||
UpdateProbe(name string, u hub.Update) error
|
||||
}
|
||||
|
||||
// NodeSet gives access to the per-probe engines and ticket stores. Hosts lists
|
||||
// every node, the primary first.
|
||||
type NodeSet interface {
|
||||
Hosts() []string
|
||||
Enforce(host string) *enforce.Engine
|
||||
Egress(host string) *egress.Engine
|
||||
Incidents(host string) *incidents.Store
|
||||
}
|
||||
|
||||
// probeIngest wraps an ingest handler with the probe token check and the same
|
||||
// attempt limiter as the user API. Errors carry no detail.
|
||||
func (s *Server) probeIngest(h func(w http.ResponseWriter, r *http.Request, name string)) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
ip := clientIP(r, s.opt.TrustedProxy)
|
||||
if wait := s.lim.blocked(ip); wait > 0 {
|
||||
w.Header().Set("Retry-After", strconv.Itoa(int(wait.Seconds())+1))
|
||||
writeJSON(w, http.StatusTooManyRequests, map[string]string{"error": "too many attempts"})
|
||||
return
|
||||
}
|
||||
name, ok := s.opt.Probes.Authenticate(r)
|
||||
if !ok {
|
||||
s.lim.failure(ip)
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
h(w, r, name)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) probeRoutes(m *http.ServeMux) {
|
||||
if s.opt.Probes == nil {
|
||||
return
|
||||
}
|
||||
p := s.opt.Probes
|
||||
m.HandleFunc("POST "+wire.PathHello, s.probeIngest(p.Hello))
|
||||
m.HandleFunc("POST "+wire.PathPush, s.probeIngest(p.Push))
|
||||
m.HandleFunc("GET "+wire.PathCommands, s.probeIngest(p.Commands))
|
||||
m.HandleFunc("GET /api/v1/probes", s.api(func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, 200, map[string]any{"probes": p.List()})
|
||||
}))
|
||||
m.HandleFunc("POST /api/v1/probes", s.api(func(w http.ResponseWriter, r *http.Request) {
|
||||
var in struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
if !s.adminBody(w, r, &in) {
|
||||
return
|
||||
}
|
||||
tok, err := p.Create(in.Name)
|
||||
switch {
|
||||
case errors.Is(err, hub.ErrName):
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
||||
case errors.Is(err, hub.ErrExists):
|
||||
writeJSON(w, http.StatusConflict, map[string]string{"error": err.Error()})
|
||||
case err != nil:
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "internal error"})
|
||||
default:
|
||||
writeJSON(w, http.StatusCreated, map[string]string{"name": in.Name, "token": tok})
|
||||
}
|
||||
}))
|
||||
m.HandleFunc("DELETE /api/v1/probes/{name}", s.api(func(w http.ResponseWriter, r *http.Request) {
|
||||
if !sameOrigin(r) {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "cross-site request refused"})
|
||||
return
|
||||
}
|
||||
switch err := p.Revoke(r.PathValue("name")); {
|
||||
case errors.Is(err, hub.ErrNotFound):
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": err.Error()})
|
||||
case err != nil:
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "internal error"})
|
||||
default:
|
||||
writeJSON(w, 200, map[string]bool{"ok": true})
|
||||
}
|
||||
}))
|
||||
m.HandleFunc("PUT /api/v1/probes/{name}", s.api(func(w http.ResponseWriter, r *http.Request) {
|
||||
var in hub.Update
|
||||
if !s.adminBody(w, r, &in) {
|
||||
return
|
||||
}
|
||||
name := r.PathValue("name")
|
||||
switch err := p.UpdateProbe(name, in); {
|
||||
case errors.Is(err, hub.ErrNotFound):
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": err.Error()})
|
||||
case err != nil:
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
||||
default:
|
||||
info, _ := p.Info(name)
|
||||
writeJSON(w, 200, info)
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
func (s *Server) adminBody(w http.ResponseWriter, r *http.Request, v any) bool {
|
||||
if !sameOrigin(r) {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "cross-site request refused"})
|
||||
return false
|
||||
}
|
||||
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16<<10))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(v); err != nil || dec.More() {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON body"})
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// ---- per-host lookups (fall back to the package level engines, i.e. the primary) ----
|
||||
|
||||
func (s *Server) primaryName() string { return s.opt.Store.Name() }
|
||||
|
||||
// enforceFor returns the engine of a host ("" or the primary: the primary's).
|
||||
func (s *Server) enforceFor(host string) *enforce.Engine {
|
||||
if host == "" || host == s.primaryName() || s.opt.Nodes == nil {
|
||||
return enforceEngine.Load()
|
||||
}
|
||||
return s.opt.Nodes.Enforce(host)
|
||||
}
|
||||
|
||||
func (s *Server) incStore(host string) *incidents.Store {
|
||||
if host == "" || host == s.primaryName() || s.opt.Nodes == nil {
|
||||
return s.opt.Incidents
|
||||
}
|
||||
return s.opt.Nodes.Incidents(host)
|
||||
}
|
||||
|
||||
// incHosts lists the hosts that have a ticket store, the primary first.
|
||||
func (s *Server) incHosts() []string {
|
||||
if s.opt.Nodes == nil {
|
||||
if s.opt.Incidents != nil {
|
||||
return []string{s.primaryName()}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return s.opt.Nodes.Hosts()
|
||||
}
|
||||
+7
-157
@@ -15,7 +15,6 @@ import (
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
@@ -31,9 +30,6 @@ var webFS embed.FS
|
||||
// maxSSE bounds the simultaneous live streams.
|
||||
const maxSSE = 20
|
||||
|
||||
// maxPeerSSE bounds the simultaneous hub subscriptions to /api/v1/peer/stream.
|
||||
const maxPeerSSE = 10
|
||||
|
||||
// sseHeartbeat is how often a live stream pings and revalidates its session.
|
||||
var sseHeartbeat = 20 * time.Second
|
||||
|
||||
@@ -51,16 +47,12 @@ func HTTPServer(h http.Handler, base context.Context) *http.Server {
|
||||
// Options configure the handler.
|
||||
type Options struct {
|
||||
Token string
|
||||
// PeerTokens are the federation tokens accepted by /api/v1/peer/export.
|
||||
PeerTokens []string
|
||||
// Ignore lists networks that must never appear in the blocklist (ignore + trusted).
|
||||
Ignore []netip.Prefix
|
||||
// AllowHosts: with NoAuth, only requests whose Host is one of these are served
|
||||
// (anti DNS rebinding).
|
||||
AllowHosts []string
|
||||
// PeerAllow, when not empty, restricts /api/v1/peer/export to these source
|
||||
// networks. TrustedProxy lists the reverse proxies whose X-Forwarded-For is believed.
|
||||
PeerAllow []netip.Prefix
|
||||
// TrustedProxy lists the reverse proxies whose X-Forwarded-For is believed.
|
||||
TrustedProxy []netip.Prefix
|
||||
NoAuth bool
|
||||
// LocalBlocklist makes the blocklist use only this instance's IPs (--peer-blocklist=off).
|
||||
@@ -68,6 +60,10 @@ type Options struct {
|
||||
Version string
|
||||
Store *store.Store
|
||||
Hub *fed.Hub
|
||||
// Probes serves the probe ingest and the admin routes (nil: not a hub).
|
||||
Probes ProbeAPI
|
||||
// Nodes gives per-host access to the engines and tickets of every probe.
|
||||
Nodes NodeSet
|
||||
// Incidents is the ticket store (nil: incident management off).
|
||||
Incidents *incidents.Store
|
||||
Now func() time.Time
|
||||
@@ -76,14 +72,12 @@ type Options struct {
|
||||
// Server is the HTTP handler.
|
||||
type Server struct {
|
||||
sse atomic.Int32
|
||||
exp exportCache
|
||||
opt Options
|
||||
ses *sessions
|
||||
lim *limiter
|
||||
mux *http.ServeMux
|
||||
assets fs.FS
|
||||
geo geoCache
|
||||
psse atomic.Int32
|
||||
study chan struct{}
|
||||
user chan struct{} // user-side studies (period, metrics) running at once
|
||||
}
|
||||
@@ -102,10 +96,6 @@ func New(opt Options) http.Handler {
|
||||
m.HandleFunc("POST /logout", s.logout)
|
||||
m.HandleFunc("GET /{$}", s.index)
|
||||
m.HandleFunc("GET /{file}", s.asset)
|
||||
m.HandleFunc("GET /api/v1/peer/export", s.peerExport)
|
||||
m.HandleFunc("GET /api/v1/peer/stream", s.peerStream)
|
||||
m.HandleFunc("GET /api/v1/peer/period", s.peerPeriod)
|
||||
m.HandleFunc("GET /api/v1/peer/egress", s.peerEgress)
|
||||
m.HandleFunc("GET /api/v1/geo", s.api(s.geoAPI))
|
||||
m.HandleFunc("GET /api/v1/live/recent", s.api(s.liveRecent))
|
||||
m.HandleFunc("GET /api/v1/summary", s.api(s.summary))
|
||||
@@ -123,9 +113,7 @@ func New(opt Options) http.Handler {
|
||||
for _, r := range userRoutes {
|
||||
m.HandleFunc(r.pattern, s.api(r.handler(s)))
|
||||
}
|
||||
for _, r := range peerRoutes { // peer-token routes of api_<name>.go files
|
||||
m.HandleFunc(r.pattern, r.handler(s))
|
||||
}
|
||||
s.probeRoutes(m)
|
||||
m.HandleFunc("GET /api/v1/events/stream", s.api(s.stream))
|
||||
m.HandleFunc("GET /api/v1/blocklist.txt", s.api(s.blocklist(false)))
|
||||
m.HandleFunc("GET /api/v1/blocklist.json", s.api(s.blocklist(true)))
|
||||
@@ -168,7 +156,7 @@ func (s *Server) health(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
// authKind returns "session" or "bearer" for a valid user credential (cookie or
|
||||
// URUTAU_TOKEN), "peer" for the federation token, "" otherwise.
|
||||
// URUTAU_TOKEN), "" otherwise.
|
||||
func (s *Server) authKind(r *http.Request) string {
|
||||
if s.opt.NoAuth {
|
||||
return "session"
|
||||
@@ -178,9 +166,6 @@ func (s *Server) authKind(r *http.Request) string {
|
||||
if tokenEqual(tok, s.opt.Token) {
|
||||
return "bearer"
|
||||
}
|
||||
if s.peerTokenOK(tok) {
|
||||
return "peer"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
if c, err := r.Cookie(cookieName); err == nil && s.ses.valid(c.Value, s.opt.Now()) {
|
||||
@@ -189,25 +174,12 @@ func (s *Server) authKind(r *http.Request) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (s *Server) peerTokenOK(tok string) bool {
|
||||
ok := false
|
||||
for _, t := range s.opt.PeerTokens { // no early exit: constant work per token
|
||||
if tokenEqual(tok, t) {
|
||||
ok = true
|
||||
}
|
||||
}
|
||||
return ok
|
||||
}
|
||||
|
||||
// api wraps a user endpoint: only a session or URUTAU_TOKEN opens it. The peer
|
||||
// token is refused with 403 (it is a valid credential, for another route).
|
||||
func (s *Server) api(h http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
switch s.authKind(r) {
|
||||
case "session", "bearer":
|
||||
case "peer":
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "the peer token only opens /api/v1/peer/export, /api/v1/peer/stream, /api/v1/peer/period and /api/v1/peer/egress"})
|
||||
return
|
||||
default:
|
||||
ip := clientIP(r, s.opt.TrustedProxy)
|
||||
wait := s.lim.blocked(ip)
|
||||
@@ -246,37 +218,6 @@ func (s *Server) slowFail(ip string, d time.Duration) {
|
||||
}
|
||||
}
|
||||
|
||||
type exportCache struct {
|
||||
mu sync.Mutex
|
||||
at map[string]time.Time
|
||||
v map[string][]byte
|
||||
}
|
||||
|
||||
// peerGate admits only the federation token (and --peer-allow sources); it
|
||||
// answers the request itself and returns false when it refuses.
|
||||
func (s *Server) peerGate(w http.ResponseWriter, r *http.Request) bool {
|
||||
if len(s.opt.PeerTokens) == 0 && !s.opt.NoAuth {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "federation is not enabled"})
|
||||
return false
|
||||
}
|
||||
if len(s.opt.PeerAllow) > 0 {
|
||||
a, err := netip.ParseAddr(clientIP(r, s.opt.TrustedProxy))
|
||||
if err != nil || !prefixesContain(s.opt.PeerAllow, a) {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "source not allowed"})
|
||||
return false
|
||||
}
|
||||
}
|
||||
if !s.opt.NoAuth && s.authKind(r) != "peer" {
|
||||
if strings.HasPrefix(r.Header.Get("Authorization"), "Bearer ") {
|
||||
s.lim.failure(clientIP(r, s.opt.TrustedProxy))
|
||||
}
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="urutau-peer"`)
|
||||
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "unauthorized"})
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// rangeOf resolves the range parameters of a request (range, from, to); it
|
||||
// answers 400 itself and returns false on garbage.
|
||||
func (s *Server) rangeOf(w http.ResponseWriter, r *http.Request) (store.Range, bool) {
|
||||
@@ -289,31 +230,6 @@ func (s *Server) rangeOf(w http.ResponseWriter, r *http.Request) (store.Range, b
|
||||
return rg, true
|
||||
}
|
||||
|
||||
// peerExport: GET /api/v1/peer/export, opened by the peer token.
|
||||
func (s *Server) peerExport(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.peerGate(w, r) {
|
||||
return
|
||||
}
|
||||
rg, ok := s.rangeOf(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
key := rg.Key()
|
||||
s.exp.mu.Lock()
|
||||
if s.exp.v == nil || len(s.exp.v) >= 24 {
|
||||
s.exp.v, s.exp.at = map[string][]byte{}, map[string]time.Time{}
|
||||
}
|
||||
b, ok := s.exp.v[key]
|
||||
if !ok || time.Since(s.exp.at[key]) > 5*time.Second {
|
||||
b, _ = json.Marshal(s.opt.Store.ExportFor(rg))
|
||||
s.exp.v[key], s.exp.at[key] = b, time.Now()
|
||||
}
|
||||
s.exp.mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.Write(b)
|
||||
}
|
||||
|
||||
func prefixesContain(ps []netip.Prefix, a netip.Addr) bool {
|
||||
a = a.Unmap()
|
||||
for _, p := range ps {
|
||||
@@ -691,72 +607,6 @@ func (s *Server) stream(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
|
||||
// peerStream: GET /api/v1/peer/stream, SSE of this instance's own malicious
|
||||
// events for a hub. Opened only by the peer token, like the export.
|
||||
func (s *Server) peerStream(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.peerGate(w, r) {
|
||||
return
|
||||
}
|
||||
fl, ok := w.(http.Flusher)
|
||||
if !ok {
|
||||
http.Error(w, "streaming unsupported", 500)
|
||||
return
|
||||
}
|
||||
if s.psse.Add(1) > maxPeerSSE {
|
||||
s.psse.Add(-1)
|
||||
w.Header().Set("Retry-After", "10")
|
||||
http.Error(w, "too many peer streams", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
defer s.psse.Add(-1)
|
||||
_ = http.NewResponseController(w).SetWriteDeadline(time.Time{})
|
||||
h := w.Header()
|
||||
h.Set("Content-Type", "text/event-stream")
|
||||
h.Set("Cache-Control", "no-store")
|
||||
h.Set("X-Accel-Buffering", "no")
|
||||
ch, stop := s.opt.Store.Subscribe()
|
||||
defer stop()
|
||||
var visCh <-chan store.VisitMsg // only with ?visits=1; carries no address
|
||||
if r.URL.Query().Get("visits") == "1" {
|
||||
c, stopV := s.opt.Store.SubscribeVisits()
|
||||
defer stopV()
|
||||
visCh = c
|
||||
}
|
||||
fmt.Fprint(w, "retry: 3000\n: connected\n\n")
|
||||
fl.Flush()
|
||||
tick := time.NewTicker(sseHeartbeat)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
case v := <-visCh:
|
||||
b, _ := json.Marshal(v)
|
||||
if _, err := fmt.Fprintf(w, "event: visit\ndata: %s\n\n", b); err != nil {
|
||||
return
|
||||
}
|
||||
fl.Flush()
|
||||
case <-tick.C:
|
||||
if !s.opt.NoAuth && s.authKind(r) != "peer" {
|
||||
return
|
||||
}
|
||||
if _, err := fmt.Fprint(w, ": ping\n\n"); err != nil {
|
||||
return
|
||||
}
|
||||
fl.Flush()
|
||||
case e := <-ch:
|
||||
if !core.Category(e.Cat).IsMalicious() {
|
||||
continue
|
||||
}
|
||||
b, _ := json.Marshal(s.opt.Store.Live(e))
|
||||
if _, err := fmt.Fprintf(w, "event: ev\ndata: %s\n\n", b); err != nil {
|
||||
return
|
||||
}
|
||||
fl.Flush()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// liveRecent: GET /api/v1/live/recent?limit=200 (max 500), newest first, local and peers.
|
||||
func (s *Server) liveRecent(w http.ResponseWriter, r *http.Request) {
|
||||
n, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
||||
|
||||
@@ -18,7 +18,7 @@ import (
|
||||
func setup(t *testing.T) (http.Handler, *store.Store) {
|
||||
st := store.New(store.Config{Name: "oracle", Version: "test"})
|
||||
st.Ingest(core.Event{Time: time.Now(), IP: "45.94.31.4", Cat: core.Exploit, Strong: true, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/<img src=x onerror=alert(1)>"})
|
||||
h := New(Options{Token: "user-token-0123456789-abcdefghijklmnop", PeerTokens: []string{"peer-token-0123456789-abcdefghijklmnopq"}, Version: "test", Store: st})
|
||||
h := New(Options{Token: "user-token-0123456789-abcdefghijklmnop", Version: "test", Store: st})
|
||||
return h, st
|
||||
}
|
||||
|
||||
@@ -240,7 +240,7 @@ func mustPrefixes(l string) []netip.Prefix {
|
||||
func federated(t *testing.T, mod func(*Options)) http.Handler {
|
||||
st := store.New(store.Config{Name: "oracle", Version: "test"})
|
||||
st.Ingest(core.Event{Time: time.Now(), IP: "45.94.31.4", Cat: core.Exploit, Strong: true, Source: "traefik", Method: "GET", Path: "/x"})
|
||||
o := Options{Token: "user-token-0123456789-abcdefghijklmnop", PeerTokens: []string{"peer-token-0123456789-abcdefghijklmnopq"}, Version: "test", Store: st,
|
||||
o := Options{Token: "user-token-0123456789-abcdefghijklmnop", Version: "test", Store: st,
|
||||
TrustedProxy: mustPrefixes("172.16.0.0/12")}
|
||||
if mod != nil {
|
||||
mod(&o)
|
||||
@@ -248,66 +248,6 @@ func federated(t *testing.T, mod func(*Options)) http.Handler {
|
||||
return New(o)
|
||||
}
|
||||
|
||||
func TestPeerTokenOnlyOpensExport(t *testing.T) {
|
||||
h, _ := setup(t)
|
||||
peer := map[string]string{"Authorization": "Bearer peer-token-0123456789-abcdefghijklmnopq"}
|
||||
user := map[string]string{"Authorization": "Bearer user-token-0123456789-abcdefghijklmnop"}
|
||||
for _, p := range []string{"/api/v1/summary", "/api/v1/traffic", "/api/v1/ip/45.94.31.4", "/api/v1/ips", "/api/v1/events/stream",
|
||||
"/api/v1/blocklist.txt", "/api/v1/blocklist.json", "/api/v1/geo", "/api/v1/live/recent"} {
|
||||
if w := do(h, "GET", p, peer, nil); w.Code != http.StatusForbidden {
|
||||
t.Errorf("peer token on %s: %d (want 403)", p, w.Code)
|
||||
}
|
||||
if w := do(h, "GET", p, nil, nil); w.Code != http.StatusUnauthorized {
|
||||
t.Errorf("no credential on %s: %d (want 401)", p, w.Code)
|
||||
}
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/peer/export", nil, nil); w.Code != 401 {
|
||||
t.Fatalf("export without credential: %d", w.Code)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/peer/export", user, nil); w.Code != 401 {
|
||||
t.Fatalf("the user token must not open the export: %d", w.Code)
|
||||
}
|
||||
w := do(h, "GET", "/api/v1/peer/export?range=7d", peer, nil)
|
||||
if w.Code != 200 || !strings.Contains(w.Body.String(), `"v":1`) || !strings.Contains(w.Body.String(), "45.94.31.4") || !strings.Contains(w.Body.String(), `"traffic"`) {
|
||||
t.Fatalf("export %d %.200s", w.Code, w.Body)
|
||||
}
|
||||
// without a peer token configured the route does not exist
|
||||
h2 := federated(t, func(o *Options) { o.PeerTokens = nil })
|
||||
if w := do(h2, "GET", "/api/v1/peer/export", peer, nil); w.Code != 404 {
|
||||
t.Fatalf("federation disabled: %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerAllowAndRealClientIP(t *testing.T) {
|
||||
peer := map[string]string{"Authorization": "Bearer peer-token-0123456789-abcdefghijklmnopq"}
|
||||
h := federated(t, func(o *Options) { o.PeerAllow = mustPrefixes("203.0.113.0/24") })
|
||||
with := func(remote, xff string) *httptest.ResponseRecorder {
|
||||
hd := map[string]string{"Authorization": peer["Authorization"], "X-Remote": remote}
|
||||
if xff != "" {
|
||||
hd["X-Forwarded-For"] = xff
|
||||
}
|
||||
return do(h, "GET", "/api/v1/peer/export", hd, nil)
|
||||
}
|
||||
if w := with("198.51.100.9:1", ""); w.Code != 403 {
|
||||
t.Fatalf("outside the allow list: %d", w.Code)
|
||||
}
|
||||
if w := with("203.0.113.8:1", ""); w.Code != 200 {
|
||||
t.Fatalf("inside the allow list: %d", w.Code)
|
||||
}
|
||||
if w := with("198.51.100.9:1", "203.0.113.8"); w.Code != 403 {
|
||||
t.Fatalf("forged XFF from an untrusted source must not pass: %d", w.Code)
|
||||
}
|
||||
if w := with("172.18.0.2:1", "203.0.113.8"); w.Code != 200 {
|
||||
t.Fatalf("XFF from the trusted proxy is the real client: %d", w.Code)
|
||||
}
|
||||
if w := with("172.18.0.2:1", "198.51.100.77"); w.Code != 403 {
|
||||
t.Fatalf("real client outside the list behind the proxy: %d", w.Code)
|
||||
}
|
||||
if w := with("172.18.0.2:1", "203.0.113.8, 198.51.100.77"); w.Code != 403 {
|
||||
t.Fatalf("the proxy appended the real client on the right: %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginRateLimitUsesRealClientBehindProxy(t *testing.T) {
|
||||
loginBlockedDelay = 0
|
||||
h := federated(t, nil)
|
||||
|
||||
@@ -33,7 +33,7 @@ func setupLog(t *testing.T) (http.Handler, *store.Store, map[string]string) {
|
||||
}
|
||||
st.Ingest(core.Event{Time: now.Add(-3 * time.Hour), IP: "45.94.31.9", Cat: core.Scanner, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/wp-login.php", Status: 404})
|
||||
st.Ingest(core.Event{Time: now.Add(-time.Minute), IP: "45.94.31.4", Cat: core.Ban, Source: "fail2ban", Jail: "sshd"})
|
||||
h := New(Options{Token: userTok, PeerTokens: []string{peerTok}, Version: "test", Store: st})
|
||||
h := New(Options{Token: userTok, Version: "test", Store: st})
|
||||
return h, st, map[string]string{"Authorization": "Bearer " + userTok}
|
||||
}
|
||||
|
||||
@@ -131,11 +131,7 @@ func TestEventsAPI(t *testing.T) {
|
||||
t.Fatal("gap")
|
||||
}
|
||||
// the peer token opens none of the new routes
|
||||
peer := map[string]string{"Authorization": "Bearer " + peerTok}
|
||||
for _, p := range []string{"events", "events/sessions", "period", "period/events", "metrics", "ip/45.94.31.4", "ip/45.94.31.4/stix"} {
|
||||
if w := do(h, "GET", "/api/v1/"+p, cloneHdr(peer), nil); w.Code != 403 {
|
||||
t.Errorf("%s with the peer token: %d", p, w.Code)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/"+p, nil, nil); w.Code != 401 {
|
||||
t.Errorf("%s without auth: %d", p, w.Code)
|
||||
}
|
||||
|
||||
+77
-12
@@ -997,13 +997,13 @@
|
||||
return fetch(path, o).then(function (r) {
|
||||
if (r.status === 401) { location.href = '/login'; throw mkErr('unauthorized', 401); }
|
||||
if (!r.ok) throw mkErr('HTTP ' + r.status, r.status);
|
||||
return r.json();
|
||||
return r.text().then(function (txt) { try { return txt ? JSON.parse(txt) : {}; } catch (e) { return {}; } });
|
||||
});
|
||||
}
|
||||
|
||||
// Unban dialog: native <dialog> (focus trap, Esc), a radio group for how long the address stays protected, confirm.
|
||||
var UNBAN_CHOICES = [['0', 'unban.keep.none'], ['3600', 'unban.keep.1h'], ['86400', 'unban.keep.24h'], ['604800', 'unban.keep.7d']];
|
||||
function unbanDialog(ip, onDone) {
|
||||
function unbanDialog(ip, onDone, opts) {
|
||||
var prev = document.activeElement;
|
||||
var dlg = el('dialog', { class: 'unban-dlg', 'aria-labelledby': 'unban-h', 'aria-describedby': 'unban-p' });
|
||||
var err = el('p', { class: 'unban-err', role: 'alert', hidden: true });
|
||||
@@ -1018,6 +1018,19 @@
|
||||
var cancel = el('button', { type: 'button', class: 'btn' }, t('unban.cancel'));
|
||||
dlg.appendChild(el('h2', { id: 'unban-h' }, t('unban.title', { ip: ip })));
|
||||
dlg.appendChild(el('p', { id: 'unban-p' }, t('unban.explain')));
|
||||
// each probe enforces its own bans: the operator picks where to lift it (or every host)
|
||||
var hostSel = el('select', { id: 'unban-host' });
|
||||
var hostRow = el('div', { class: 'unban-host', hidden: true }, el('label', { for: 'unban-host' }, t('pr.unban.host')), hostSel);
|
||||
var wantHost = (opts && opts.host) || (state.host !== 'all' ? state.host : 'all');
|
||||
getSummary(ctx()).then(function (s) {
|
||||
var hs = (s.hosts || []).map(function (x) { return x.name; });
|
||||
if (hs.length < 2) return;
|
||||
hostSel.appendChild(el('option', { value: 'all' }, t('host.all')));
|
||||
hs.forEach(function (n) { hostSel.appendChild(el('option', { value: n }, n)); });
|
||||
hostSel.value = hs.indexOf(wantHost) >= 0 ? wantHost : 'all';
|
||||
hostRow.hidden = false;
|
||||
}).catch(function () { /* single host */ });
|
||||
dlg.appendChild(hostRow);
|
||||
dlg.appendChild(fs);
|
||||
dlg.appendChild(err);
|
||||
dlg.appendChild(el('div', { class: 'unban-btns' }, cancel, ok));
|
||||
@@ -1030,7 +1043,7 @@
|
||||
ok.addEventListener('click', function () {
|
||||
var sel = dlg.querySelector('input[name="unban-keep"]:checked');
|
||||
ok.disabled = true;
|
||||
apiSend('POST', '/api/v1/enforce/unban', { ip: ip, allow_s: parseInt(sel ? sel.value : '0', 10) || 0 }).then(function () {
|
||||
apiSend('POST', '/api/v1/enforce/unban', { ip: ip, allow_s: parseInt(sel ? sel.value : '0', 10) || 0, host: hostRow.hidden ? (wantHost !== 'all' ? wantHost : undefined) : hostSel.value }).then(function () {
|
||||
close();
|
||||
toast(t('unban.done', { ip: ip }));
|
||||
if (onDone) onDone();
|
||||
@@ -1204,19 +1217,33 @@
|
||||
var mx = 0; (matrix || []).forEach(function (r) { r.forEach(function (v) { if (v > mx) mx = v; }); });
|
||||
if (!mx) return empty(t('charts.empty'));
|
||||
var fmt = o.format || nf, wrap = h('div', 'vz vz-heat');
|
||||
var meas = document.createElement('canvas').getContext('2d');
|
||||
function textW(x) { meas.font = '11px ' + (cssVar('--font-sans') || 'sans-serif'); return meas.measureText(String(x)).width; }
|
||||
function fit(x, max) { // ellipsis only beyond max
|
||||
x = String(x); if (textW(x) <= max) return x;
|
||||
var lo = 0, hi = x.length; while (lo < hi) { var m = (lo + hi + 1) >> 1; if (textW(x.slice(0, m) + '\u2026') <= max) lo = m; else hi = m - 1; }
|
||||
return x.slice(0, lo) + '\u2026';
|
||||
}
|
||||
function draw(Wpx) {
|
||||
clear(wrap);
|
||||
var ny = matrix.length, nx = matrix[0].length, LW = 56, W = Math.max(240, Wpx), cw = (W - LW) / nx, ch = Math.min(26, Math.max(12, cw)), H = ny * ch + 22;
|
||||
var ny = matrix.length, nx = matrix[0].length, W = Math.max(240, Wpx), stacked = W < 480;
|
||||
var widest = 0; yl.forEach(function (x) { widest = Math.max(widest, textW(x)); });
|
||||
// wide: label column sized to the longest name (40% cap); narrow: the label sits above its own strip
|
||||
var LW = stacked ? 0 : Math.max(56, Math.min(Math.ceil(widest) + 14, Math.floor(W * .4)));
|
||||
var cw = (W - LW) / nx, ch = Math.min(26, Math.max(12, cw)), lab = stacked ? 15 : 0, rowH = ch + lab, H = ny * rowH + 22;
|
||||
var svg = svgEl('svg', { viewBox: '0 0 ' + W + ' ' + H, role: 'img', 'aria-label': o.title || '' }), step = Math.ceil(26 / cw);
|
||||
matrix.forEach(function (row, y) {
|
||||
var yt = svgEl('text', { x: LW - 6, y: y * ch + ch / 2 + 4, 'text-anchor': 'end', 'class': 'axis' }); yt.textContent = yl[y]; svg.appendChild(yt);
|
||||
var y0 = y * rowH;
|
||||
var yt = stacked ? svgEl('text', { x: 2, y: y0 + 11, 'text-anchor': 'start', 'class': 'axis' }) : svgEl('text', { x: LW - 6, y: y0 + ch / 2 + 4, 'text-anchor': 'end', 'class': 'axis' });
|
||||
yt.textContent = fit(yl[y], stacked ? W - 4 : LW - 10);
|
||||
var yti = svgEl('title', {}); yti.textContent = String(yl[y]); yt.appendChild(yti); svg.appendChild(yt);
|
||||
row.forEach(function (v, x) {
|
||||
var lvl = v ? Math.min(5, 1 + Math.floor(v / mx * 4.999)) : 0;
|
||||
var r = svgEl('rect', { x: LW + x * cw + 1, y: y * ch + 1, width: Math.max(1, cw - 2), height: ch - 2, rx: 2, 'class': 'vz-cell s' + lvl, tabindex: 0, 'aria-label': yl[y] + ' ' + xl[x] + ': ' + fmt(v) });
|
||||
var ti = svgEl('title', {}); ti.textContent = yl[y] + ' ' + xl[x] + ': ' + fmt(v); r.appendChild(ti); svg.appendChild(r);
|
||||
var r = svgEl('rect', { x: LW + x * cw + 1, y: y0 + lab + 1, width: Math.max(1, cw - 2), height: ch - 2, rx: 2, 'class': 'vz-cell s' + lvl, tabindex: 0, 'aria-label': yl[y] + ' ' + xl[x] + ': ' + fmt(v) });
|
||||
var ti = svgEl('title', {}); ti.textContent = yl[y] + ' \u00b7 ' + xl[x] + ' \u00b7 ' + fmt(v); r.appendChild(ti); svg.appendChild(r);
|
||||
});
|
||||
});
|
||||
for (var x = 0; x < nx; x += step) { var xt = svgEl('text', { x: LW + x * cw + cw / 2, y: ny * ch + 15, 'text-anchor': 'middle', 'class': 'axis' }); xt.textContent = xl[x]; svg.appendChild(xt); }
|
||||
for (var x = 0; x < nx; x += step) { var first = x === 0 && stacked, xt = svgEl('text', { x: first ? 2 : LW + x * cw + cw / 2, y: ny * rowH + 15, 'text-anchor': first ? 'start' : 'middle', 'class': 'axis' }); xt.textContent = xl[x]; svg.appendChild(xt); }
|
||||
wrap.appendChild(svg);
|
||||
}
|
||||
var box = h('div', null, wrap, srTable(o.title, [''].concat(xl), matrix.map(function (r, y) { return [yl[y]].concat(r.map(fmt)); })));
|
||||
@@ -1704,8 +1731,9 @@
|
||||
build: function (root) {
|
||||
var v = {}, g = grid12();
|
||||
v.lead = sp(12, h('div'));
|
||||
v.probes = window.Urutau && window.Urutau.probesPanel ? window.Urutau.probesPanel() : null;
|
||||
v.hostsBox = h('div', 'hosts');
|
||||
v.hosts = panel({ title: t('hosts.title'), hint: t('hosts.hint'), help: 'term.peer' }, v.hostsBox);
|
||||
v.hosts = panel({ title: t('hosts.title'), hint: t('hosts.hint'), help: 'term.probe' }, v.hostsBox);
|
||||
var thead = h('thead', null, h('tr', null, ['col.host', 'col.source', 'col.state', 'col.lines', 'col.malformed', 'col.lastEvent'].map(function (k) { return el('th', { scope: 'col' }, t(k)); })));
|
||||
v.tbody = h('tbody');
|
||||
v.srcEmpty = h('div');
|
||||
@@ -1713,11 +1741,11 @@
|
||||
v.geoBox = h('div');
|
||||
v.geo = panel({ title: t('src.geo.title'), hint: t('src.geo.hint') }, v.geoBox);
|
||||
v.bl = blocklistPanel();
|
||||
g.appendChild(v.lead); g.appendChild(sp(12, v.hosts)); g.appendChild(sp(12, v.sources)); g.appendChild(sp(6, v.geo)); g.appendChild(sp(6, v.bl.node)); root.appendChild(g);
|
||||
g.appendChild(v.lead); if (v.probes) g.appendChild(sp(12, v.probes.node)); g.appendChild(sp(12, v.hosts)); g.appendChild(sp(12, v.sources)); g.appendChild(sp(6, v.geo)); g.appendChild(sp(6, v.bl.node)); root.appendChild(g);
|
||||
v.bl.sync();
|
||||
return v;
|
||||
},
|
||||
load: function (c, v) { v.bl.sync(); return getSummary(c); },
|
||||
load: function (c, v) { v.bl.sync(); if (v.probes) v.probes.reload(); return getSummary(c); },
|
||||
render: function (v, s) {
|
||||
var srcs = s.sources || [], hosts = s.hosts || [];
|
||||
var following = srcs.filter(function (r) { return r.state === 'following'; }).length;
|
||||
@@ -1751,11 +1779,47 @@
|
||||
dl.appendChild(h('dt', null, t('src.geo.attrib'))); dl.appendChild(h('dd', null, s.attribution || t('src.geo.none')));
|
||||
v.geoBox.appendChild(dl);
|
||||
},
|
||||
dispose: function (v) { v.bl.dispose(); }
|
||||
dispose: function (v) { v.bl.dispose(); if (v.probes) v.probes.dispose(); }
|
||||
});
|
||||
|
||||
[pOverview, pThreats, pTraffic, pIPs, pSources].forEach(function (p) { pages[p.id] = p; });
|
||||
|
||||
// ---------------------------------------------------------------- IPs never wrap
|
||||
// Any element whose whole text is an IP (v4/v6, optional :port or /prefix) gets .ipv (see style.css): one line, mono, tabular.
|
||||
// Done centrally so every table, card, feed and drawer behaves the same, whichever script drew it.
|
||||
var IP4_RE = /^\d{1,3}(?:\.\d{1,3}){3}(?::\d{1,5})?(?:\/\d{1,2})?$/;
|
||||
var IP6_RE = /^\[?[0-9A-Fa-f:]*:[0-9A-Fa-f:.]*\]?(?::\d{1,5})?(?:\/\d{1,3})?$/;
|
||||
function looksIP(x) { return x.length >= 7 && x.length <= 64 && (IP4_RE.test(x) || ((x.indexOf('::') >= 0 || x.split(':').length > 3) && IP6_RE.test(x))); }
|
||||
var IP_SKIP = { SCRIPT: 1, STYLE: 1, TEXTAREA: 1, OPTION: 1, TITLE: 1, INPUT: 1 };
|
||||
function tagIPs(root) {
|
||||
if (!root) return;
|
||||
var w = document.createTreeWalker(root, NodeFilter.SHOW_TEXT), n, hits = [];
|
||||
while ((n = w.nextNode())) {
|
||||
var p = n.parentNode, v = n.nodeValue;
|
||||
if (!p || p.nodeType !== 1 || IP_SKIP[p.tagName] || !v || v.length > 70 || (p.classList && p.classList.contains('ipv'))) continue;
|
||||
var x = v.trim();
|
||||
if (looksIP(x)) hits.push([n, p, x]);
|
||||
}
|
||||
hits.forEach(function (hh) {
|
||||
var n = hh[0], p = hh[1], x = hh[2], target = p;
|
||||
if (p.childNodes.length > 1 || p.tagName === 'TD' || p.tagName === 'TH') { // mixed content: wrap only the address
|
||||
target = document.createElement('span'); p.replaceChild(target, n); target.appendChild(n);
|
||||
}
|
||||
target.classList.add('ipv');
|
||||
if (x.length > 24) target.classList.add('ipv-long');
|
||||
if (!target.hasAttribute('title')) target.setAttribute('title', x);
|
||||
});
|
||||
}
|
||||
var ipQueued = false;
|
||||
function watchIPs() {
|
||||
new MutationObserver(function () {
|
||||
if (ipQueued) return;
|
||||
ipQueued = true;
|
||||
requestAnimationFrame(function () { ipQueued = false; tagIPs(document.body); });
|
||||
}).observe(document.body, { childList: true, subtree: true, characterData: true });
|
||||
tagIPs(document.body);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- url (the source of truth)
|
||||
function parseHash() {
|
||||
var raw = location.hash.replace(/^#\/?/, ''), q = '', i = raw.indexOf('?');
|
||||
@@ -2147,6 +2211,7 @@
|
||||
});
|
||||
window.addEventListener('hashchange', route);
|
||||
window.matchMedia && matchMedia('(prefers-color-scheme: light)').addEventListener && matchMedia('(prefers-color-scheme: light)').addEventListener('change', notifyPage);
|
||||
watchIPs();
|
||||
connectLive();
|
||||
// the host must be validated before a page asks for data with a stale one
|
||||
shellSummary().catch(function (e) {
|
||||
|
||||
@@ -57,7 +57,7 @@
|
||||
'df.en.mode.where': 'The mode is chosen at deploy time with the variable URUTAU_ENFORCE (off, observe or on). It cannot be changed from this page.',
|
||||
'df.en.how.title': 'How to turn it on',
|
||||
'df.en.how.body': 'Set URUTAU_ENFORCE=observe on the server and restart Urutau. Watch the decisions for a few days; when they look right, change it to on.',
|
||||
'df.en.share': 'Sharing with peers',
|
||||
'df.en.share': 'Sharing between hosts',
|
||||
'df.en.share.on': 'on: bans are shared with other servers',
|
||||
'df.en.share.off': 'off: bans stay on this server',
|
||||
'df.en.threshold': 'Blocks from score {n}',
|
||||
@@ -105,12 +105,12 @@
|
||||
'df.en.allows.err': 'Could not end the release.',
|
||||
'df.en.allows.unwritable': 'The unban file is not writable, so unbanning will fail.',
|
||||
'df.en.src.local': 'this server',
|
||||
'df.en.src.peer': 'peer {n}',
|
||||
'df.en.src.peer': 'from {n}',
|
||||
'df.en.skip.trusted': 'Trusted address (your own list)',
|
||||
'df.en.skip.private': 'Private network (not on the internet)',
|
||||
'df.en.skip.crawler': 'Verified search engine',
|
||||
'df.en.skip.legit_visitor': 'Looks like a legitimate visitor',
|
||||
'df.en.skip.peer': 'Peer server (yours)',
|
||||
'df.en.skip.peer': 'Another of your servers',
|
||||
'df.en.reason.scanner-flood': 'Many vulnerability probes in a short time',
|
||||
'df.en.reason.exploit-flood': 'Repeated exploit attempts',
|
||||
'df.en.reason.web-bruteforce': 'Password guessing on a website',
|
||||
@@ -174,7 +174,7 @@
|
||||
'df.en.mode.where': 'O modo é escolhido no deploy, pela variável URUTAU_ENFORCE (off, observe ou on). Não dá para mudá-lo por esta página.',
|
||||
'df.en.how.title': 'Como ligar',
|
||||
'df.en.how.body': 'Defina URUTAU_ENFORCE=observe no servidor e reinicie o Urutau. Acompanhe as decisões por alguns dias; quando estiverem certas, troque para on.',
|
||||
'df.en.share': 'Compartilhamento com parceiros',
|
||||
'df.en.share': 'Compartilhamento entre hosts',
|
||||
'df.en.share.on': 'ligado: os bloqueios são compartilhados com outros servidores',
|
||||
'df.en.share.off': 'desligado: os bloqueios ficam só neste servidor',
|
||||
'df.en.threshold': 'Bloqueia a partir da pontuação {n}',
|
||||
@@ -222,12 +222,12 @@
|
||||
'df.en.allows.err': 'Não foi possível encerrar a liberação.',
|
||||
'df.en.allows.unwritable': 'O arquivo de desban não é gravável, então desbanir vai falhar.',
|
||||
'df.en.src.local': 'este servidor',
|
||||
'df.en.src.peer': 'parceiro {n}',
|
||||
'df.en.src.peer': 'vindo de {n}',
|
||||
'df.en.skip.trusted': 'Endereço confiável (sua própria lista)',
|
||||
'df.en.skip.private': 'Rede privada (fora da internet)',
|
||||
'df.en.skip.crawler': 'Buscador verificado',
|
||||
'df.en.skip.legit_visitor': 'Parece um visitante legítimo',
|
||||
'df.en.skip.peer': 'Servidor parceiro (seu)',
|
||||
'df.en.skip.peer': 'Outro servidor seu',
|
||||
'df.en.reason.scanner-flood': 'Muitas sondagens de vulnerabilidade em pouco tempo',
|
||||
'df.en.reason.exploit-flood': 'Tentativas repetidas de exploração',
|
||||
'df.en.reason.web-bruteforce': 'Tentativa de adivinhar senha num site',
|
||||
|
||||
@@ -453,7 +453,7 @@
|
||||
function heat(st) {
|
||||
if (!U.charts || !U.charts.heatmap || !st.wls.length) return null;
|
||||
var rows = [], labels = [], step = st.tl.step || 3600;
|
||||
st.wls.forEach(function (w) { var s = seriesOf(st, w); if (s.length) { rows.push(s.slice(-24)); labels.push(w.name.length > 8 ? w.name.slice(0, 7) + '…' : w.name); } });
|
||||
st.wls.forEach(function (w) { var s = seriesOf(st, w); if (s.length) { rows.push(s.slice(-24)); labels.push(String(w.name)); } });
|
||||
if (!rows.length) return null;
|
||||
var n = rows[0].length, start = (st.tl.start || 0) + (st.tlLen - n) * step, xl = [];
|
||||
for (var i = 0; i < n; i++) xl.push(('0' + new Date((start + i * step) * 1000).getHours()).slice(-2) + 'h');
|
||||
|
||||
+12
-12
@@ -232,11 +232,11 @@ window.URUTAU_I18N = {
|
||||
'blocklist.failed': 'Could not copy the list.',
|
||||
'blocklist.count.one': '{n} IP would be listed (selected range).',
|
||||
'blocklist.count.other': '{n} IPs would be listed (selected range).',
|
||||
'hosts.title': 'Hosts and peers',
|
||||
'hosts.hint': 'This instance and the peers it federates with.',
|
||||
'hosts.title': 'Hosts',
|
||||
'hosts.hint': 'Every host that sends data to this hub.',
|
||||
'host.online': 'online',
|
||||
'host.offline': 'offline',
|
||||
'host.self': 'this instance',
|
||||
'host.self': 'hub host',
|
||||
'host.requests': 'Requests',
|
||||
'host.malicious': 'Malicious',
|
||||
'host.hostile': 'Hostile IPs',
|
||||
@@ -444,9 +444,9 @@ window.URUTAU_I18N = {
|
||||
'help.term.exposure.do': 'Remove or protect the resource and rotate any secret in it.',
|
||||
'help.term.blocklist': 'The list of hostile IPs ready to import into a firewall. Only addresses with strong evidence are included.',
|
||||
'help.term.blocklist.do': 'Export it as text or JSON and load it into your firewall or fail2ban.',
|
||||
'help.term.peer': 'Another Urutau instance that shares its data with this one.',
|
||||
'help.term.peer.do': 'If a peer is offline, its numbers are missing from the totals.',
|
||||
'help.term.hub': 'The instance that gathers the data of its peers into one view.',
|
||||
'help.term.probe': 'A small agent that runs next to the logs of a server and sends them to this hub.',
|
||||
'help.term.probe.do': 'If a probe is offline, its numbers are missing from the totals. Check the machine and its network.',
|
||||
'help.term.hub': 'The server that gathers the data of all probes into one view.',
|
||||
'help.term.hub.do': 'Open the hub to see all servers together.',
|
||||
'help.term.client_type': 'The kind of client behind each request: desktop, mobile, tablet, bot, tool or unknown, from its user agent.',
|
||||
'help.term.client_type.do': 'A large share of tools or unknown clients is worth checking.',
|
||||
@@ -747,11 +747,11 @@ window.URUTAU_I18N = {
|
||||
'blocklist.failed': 'Não foi possível copiar a lista.',
|
||||
'blocklist.count.one': '{n} IP seria listado (período selecionado).',
|
||||
'blocklist.count.other': '{n} IPs seriam listados (período selecionado).',
|
||||
'hosts.title': 'Hosts e pares',
|
||||
'hosts.hint': 'Esta instância e os pares com os quais ela se federa.',
|
||||
'hosts.title': 'Hosts',
|
||||
'hosts.hint': 'Todos os hosts que enviam dados a este hub.',
|
||||
'host.online': 'online',
|
||||
'host.offline': 'offline',
|
||||
'host.self': 'esta instância',
|
||||
'host.self': 'host do hub',
|
||||
'host.requests': 'Requisições',
|
||||
'host.malicious': 'Maliciosos',
|
||||
'host.hostile': 'IPs hostis',
|
||||
@@ -959,9 +959,9 @@ window.URUTAU_I18N = {
|
||||
'help.term.exposure.do': 'Remova ou proteja o recurso e troque qualquer segredo contido nele.',
|
||||
'help.term.blocklist': 'A lista de IPs hostis pronta para importar em um firewall. Só entram endereços com evidência forte.',
|
||||
'help.term.blocklist.do': 'Exporte em texto ou JSON e carregue no firewall ou no fail2ban.',
|
||||
'help.term.peer': 'Outra instância do Urutau que compartilha seus dados com esta.',
|
||||
'help.term.peer.do': 'Se um par está offline, os números dele faltam nos totais.',
|
||||
'help.term.hub': 'A instância que reúne os dados dos pares em uma só visão.',
|
||||
'help.term.probe': 'Um agente pequeno que roda ao lado dos logs de um servidor e os envia a este hub.',
|
||||
'help.term.probe.do': 'Se uma sonda está offline, os números dela faltam nos totais. Confira a máquina e a rede dela.',
|
||||
'help.term.hub': 'O servidor que reúne os dados de todas as sondas em uma só visão.',
|
||||
'help.term.hub.do': 'Abra o hub para ver todos os servidores juntos.',
|
||||
'help.term.client_type': 'O tipo de cliente por trás de cada requisição: computador, celular, tablet, robô, ferramenta ou desconhecido, pelo user-agent.',
|
||||
'help.term.client_type.do': 'Uma parcela grande de ferramentas ou desconhecidos merece verificação.',
|
||||
|
||||
@@ -16,6 +16,14 @@
|
||||
var PER_PAGE = 25;
|
||||
var AUTHOR_KEY = 'urutau.author';
|
||||
|
||||
// Ticket ids are per host (each probe keeps its own INC-n sequence): shown and linked as host/INC-n.
|
||||
function splitId(it) {
|
||||
var id = String(it.id || ''), host = it.host ? String(it.host) : '', i = id.lastIndexOf('/');
|
||||
if (i > 0) { host = id.slice(0, i); id = id.slice(i + 1); }
|
||||
return { host: host, num: id, full: host ? host + '/' + id : id };
|
||||
}
|
||||
function idSegs(it) { var q = splitId(it); return q.host ? [q.host, q.num] : [q.num]; }
|
||||
|
||||
function boot() {
|
||||
var U = window.Urutau;
|
||||
if (!U || !U.registerPage) return false;
|
||||
@@ -305,9 +313,9 @@
|
||||
el('span', { class: 'inc-mrow' }, el('strong', { class: 'inc-title', title: String(it.title || it.id) }, head),
|
||||
(it.tags && it.tags.length) ? el('span', { class: 'inc-rtags' }, tagChips(it.tags.slice(0, 1))) : null),
|
||||
auto ? el('span', { class: 'inc-sub mono', title: String(it.workload) }, String(it.workload)) : null);
|
||||
return el('a', { class: 'inc-row', href: U.href('incidents', [String(it.id)]), title: full },
|
||||
return el('a', { class: 'inc-row', href: U.href('incidents', idSegs(it)), title: full },
|
||||
dot(it.severity),
|
||||
el('span', { class: 'inc-id mono' }, String(it.id)),
|
||||
el('span', { class: 'inc-id mono', title: splitId(it).full }, splitId(it).full),
|
||||
titleLine,
|
||||
el('span', { class: 'inc-st' }, statusBadge(it.status)),
|
||||
el('span', { class: 'inc-who' }, it.assignee ? String(it.assignee) : '—'),
|
||||
@@ -401,7 +409,7 @@
|
||||
U.apiSend('POST', '/api/v1/incidents', { title: ttl, detail: detail.value.trim(), severity: sev.value, host: hostIn.value.trim(), tags: parseTags(tg.value), author: authorName() }).then(function (r) {
|
||||
close();
|
||||
pollBadge();
|
||||
if (r && r.id) location.hash = U.href('incidents', [String(r.id)]); else if (view && view.update) view.update();
|
||||
if (r && r.id) location.hash = U.href('incidents', idSegs(r.host || !hostIn.value.trim() ? r : { id: r.id, host: hostIn.value.trim() })); else if (view && view.update) view.update();
|
||||
}, function () {
|
||||
ok.disabled = false;
|
||||
err.textContent = t('inc.err.create');
|
||||
@@ -414,14 +422,14 @@
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ one ticket
|
||||
function detailView(host, id) {
|
||||
function detailView(host, id, idHost) {
|
||||
var seq = 0, on = true, tk = null, busy = false;
|
||||
var box = el('div', { class: 'inc-detail' });
|
||||
host.appendChild(el('a', { class: 'inc-back', href: U.href('incidents') }, '← ' + t('inc.back')));
|
||||
host.appendChild(box);
|
||||
var errBox = el('p', { class: 'inc-err', role: 'alert', hidden: true });
|
||||
|
||||
function url(suffix) { return '/api/v1/incidents/' + encodeURIComponent(id) + (suffix || ''); }
|
||||
function url(suffix) { return '/api/v1/incidents/' + encodeURIComponent(id) + (suffix || '') + (idHost ? '?host=' + encodeURIComponent(idHost) : ''); }
|
||||
function send(method, suffix, body, errKey, okKey) {
|
||||
if (busy) return;
|
||||
busy = true; box.classList.add('busy');
|
||||
@@ -480,7 +488,7 @@
|
||||
quick(t('inc.quick.fp'), 'false_positive', 'fp'), quick(t('inc.quick.tp'), 'true_positive', 'tp'), quick(t('inc.quick.resolve'), 'resolved', 'ok'));
|
||||
var meta = el('span', { class: 'inc-hint inc-metaline' }, t('inc.meta', { a: x.created_at ? U.fmt.ago(x.created_at) : '-', b: x.updated_at ? U.fmt.ago(x.updated_at) : '-', n: nf(x.count) }));
|
||||
return el('header', { class: 'inc-head' },
|
||||
el('div', { class: 'inc-h1' }, dot(x.severity), el('span', { class: 'inc-id mono' }, String(x.id)), title, q),
|
||||
el('div', { class: 'inc-h1' }, dot(x.severity), el('span', { class: 'inc-id mono' }, splitId(x).full), title, q),
|
||||
el('div', { class: 'inc-h2' }, sevBadge(x.severity), statusBadge(x.status), x.suppress ? el('span', { class: 'chip' }, t('eg.suppressed.chip')) : null, tagChips(x.tags), meta));
|
||||
}
|
||||
|
||||
@@ -709,8 +717,10 @@
|
||||
if (view) { view.destroy(); view = null; }
|
||||
clear(root);
|
||||
var seg = ctx && ctx.params && ctx.params.segments ? ctx.params.segments : [];
|
||||
var id = seg[0] ? String(seg[0]).slice(0, 64) : '';
|
||||
view = id ? detailView(root, id) : listView(root);
|
||||
var id = seg[0] ? String(seg[0]).slice(0, 64) : '', idHost = '';
|
||||
if (seg[1]) { idHost = id.slice(0, 64); id = String(seg[1]).slice(0, 64); }
|
||||
else if (id.indexOf('/') > 0) { idHost = id.slice(0, id.lastIndexOf('/')); id = id.slice(id.lastIndexOf('/') + 1); }
|
||||
view = id ? detailView(root, id, idHost) : listView(root);
|
||||
}
|
||||
|
||||
U.registerPage({
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/* Urutau - INTEGRITY page ("Is the data complete?"): volume ingested per host and
|
||||
hour (holes show as empty cells), state of every source and peer, share of
|
||||
hour (holes show as empty cells), state of every source and probe, share of
|
||||
malformed lines, event log and geolocation base. Log data is hostile: every
|
||||
dynamic string goes through textContent (the shell's el/h helpers). */
|
||||
(function () {
|
||||
@@ -18,7 +18,7 @@
|
||||
'ig.lead.okBody': 'No gaps of {n} hours or more, every source answers and few lines were rejected.',
|
||||
'ig.lead.bad.one': '{n} hole in the data',
|
||||
'ig.lead.bad.other': '{n} holes in the data',
|
||||
'ig.lead.badBody': 'Silences of two hours or more in sources that normally report, offline peers or sources in error. Check the panels below.',
|
||||
'ig.lead.badBody': 'Silences of two hours or more in sources that normally report, offline probes or sources in error. Check the panels below.',
|
||||
'ig.lead.loading': 'Checking the data...',
|
||||
'ig.stat.hosts': 'Hosts reporting',
|
||||
'ig.stat.gaps': 'Gaps found',
|
||||
@@ -46,13 +46,13 @@
|
||||
'ig.state.error': 'error',
|
||||
'ig.state.degraded': 'degraded',
|
||||
'ig.state.disabled': 'disabled',
|
||||
'ig.peers.title': 'Peers',
|
||||
'ig.peers.none': 'No peers configured.',
|
||||
'ig.peers.online': 'online',
|
||||
'ig.peers.title': 'Probes',
|
||||
'ig.peers.none': 'No probes created.',
|
||||
'ig.peers.online': 'connected',
|
||||
'ig.peers.offline': 'offline',
|
||||
'ig.peers.live': 'live',
|
||||
'ig.peers.sync': 'synced {t}',
|
||||
'ig.peers.never': 'never synced',
|
||||
'ig.peers.sync': 'last seen {t}',
|
||||
'ig.peers.never': 'never seen',
|
||||
'ig.log.title': 'Event log and geolocation',
|
||||
'ig.log.off': 'The event log is off: periods, sessions and replay have no data.',
|
||||
'ig.log.days': 'Days kept',
|
||||
@@ -71,7 +71,7 @@
|
||||
'ig.lead.okBody': 'Nenhum buraco de {n} horas ou mais, todas as fontes respondem e poucas linhas foram rejeitadas.',
|
||||
'ig.lead.bad.one': '{n} buraco nos dados',
|
||||
'ig.lead.bad.other': '{n} buracos nos dados',
|
||||
'ig.lead.badBody': 'Silêncios de duas horas ou mais em fontes que costumam registrar, peers fora do ar ou fontes com erro. Veja os painéis abaixo.',
|
||||
'ig.lead.badBody': 'Silêncios de duas horas ou mais em fontes que costumam registrar, sondas fora do ar ou fontes com erro. Veja os painéis abaixo.',
|
||||
'ig.lead.loading': 'Conferindo os dados...',
|
||||
'ig.stat.hosts': 'Hosts reportando',
|
||||
'ig.stat.gaps': 'Buracos encontrados',
|
||||
@@ -99,13 +99,13 @@
|
||||
'ig.state.error': 'erro',
|
||||
'ig.state.degraded': 'degradada',
|
||||
'ig.state.disabled': 'desativada',
|
||||
'ig.peers.title': 'Peers',
|
||||
'ig.peers.none': 'Nenhum peer configurado.',
|
||||
'ig.peers.online': 'no ar',
|
||||
'ig.peers.offline': 'fora do ar',
|
||||
'ig.peers.title': 'Sondas',
|
||||
'ig.peers.none': 'Nenhuma sonda criada.',
|
||||
'ig.peers.online': 'conectada',
|
||||
'ig.peers.offline': 'offline',
|
||||
'ig.peers.live': 'ao vivo',
|
||||
'ig.peers.sync': 'sincronizado {t}',
|
||||
'ig.peers.never': 'nunca sincronizou',
|
||||
'ig.peers.sync': 'vista {t}',
|
||||
'ig.peers.never': 'nunca vista',
|
||||
'ig.log.title': 'Registro de eventos e geolocalização',
|
||||
'ig.log.off': 'O registro de eventos está desligado: períodos, sessões e replay ficam sem dados.',
|
||||
'ig.log.days': 'Dias guardados',
|
||||
@@ -169,14 +169,14 @@
|
||||
function paint() {
|
||||
if (!data) return;
|
||||
clear(box);
|
||||
var hosts = data.hosts || [], peers = data.peers || [];
|
||||
var hosts = data.hosts || [], peers = data.probes || data.peers || [];
|
||||
var gaps = 0, lines = 0, bad = 0, errors = 0, onlineN = 0;
|
||||
hosts.forEach(function (x) {
|
||||
gaps += (x.gaps || []).length;
|
||||
if (x.online) onlineN++;
|
||||
(x.sources || []).forEach(function (s) { lines += s.lines; bad += s.malformed; if (s.state === 'error' || s.state === 'degraded') errors++; });
|
||||
});
|
||||
var offline = peers.filter(function (p) { return !p.online; }).length;
|
||||
var offline = peers.filter(function (p) { return !(p.online || p.connected); }).length;
|
||||
var rate = lines + bad > 0 ? bad / (lines + bad) : 0;
|
||||
var holes = gaps + offline + errors;
|
||||
var ok = holes === 0 && rate < 0.01;
|
||||
@@ -222,9 +222,9 @@
|
||||
else {
|
||||
var pl = h('ul', 'ig-list');
|
||||
peers.forEach(function (p) {
|
||||
pl.appendChild(h('li', null, h('strong', null, p.name), ' ', U.ui.badge(t(p.online ? 'ig.peers.online' : 'ig.peers.offline'), p.online ? 'ok' : 'danger'),
|
||||
pl.appendChild(h('li', null, h('strong', null, p.name), ' ', U.ui.badge(t((p.online || p.connected) ? 'ig.peers.online' : 'ig.peers.offline'), (p.online || p.connected) ? 'ok' : 'danger'),
|
||||
p.live ? ' ' : null, p.live ? U.ui.badge(t('ig.peers.live'), 'neutral') : null, ' ',
|
||||
h('span', 'ig-muted', p.last_sync ? t('ig.peers.sync', { t: U.fmt.ago(p.last_sync) }) : t('ig.peers.never'))));
|
||||
h('span', 'ig-muted', (p.last_seen || p.last_sync) ? t('ig.peers.sync', { t: U.fmt.ago(p.last_seen || p.last_sync) }) : t('ig.peers.never'))));
|
||||
});
|
||||
pp.body.appendChild(pl);
|
||||
}
|
||||
|
||||
@@ -170,9 +170,8 @@ button.lv-row[aria-pressed="false"] .lv-row-l { text-decoration: line-through; }
|
||||
.lv-vis-dot { width: 10px; height: 10px; border-radius: 50%; border: 2px solid var(--lv-muted); flex: none; }
|
||||
.lv-vis[aria-pressed="true"] { border-color: var(--accent); }
|
||||
.lv-vis[aria-pressed="true"] .lv-vis-dot { background: var(--lv-muted); border-color: var(--lv-muted); }
|
||||
.lv-devs, .lv-m-visit { display: none; }
|
||||
.lv-devs { display: none; }
|
||||
.lv-vis-on .lv-devs { display: flex; }
|
||||
.lv-vis-on .lv-m-visit { display: flex; }
|
||||
.lv-k-visit { --k: var(--ink-muted, #9db3bd); }
|
||||
.lv-ev-visit .lv-vtxt { grid-column: span 1; color: var(--lv-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.lv-ev-visit { grid-template-columns: auto auto minmax(0, 1fr); }
|
||||
|
||||
+39
-15
@@ -843,8 +843,6 @@
|
||||
if (Math.abs(this.vlon) > 0.05 || Math.abs(this.vlat) > 0.05) {
|
||||
this.lon0 += this.vlon * dt; this.lat0 = clamp(this.lat0 + this.vlat * dt, -75, 75);
|
||||
var f = Math.pow(0.04, dt); this.vlon *= f; this.vlat *= f;
|
||||
} else if (!this.reduced && this.T > this.idleAt) {
|
||||
this.lon0 += 4.5 * dt;
|
||||
}
|
||||
}
|
||||
if (still && !wasDirty && !morph) return; // nothing changed: leave the loop idle
|
||||
@@ -875,9 +873,11 @@
|
||||
'live.visits': 'Legitimate traffic',
|
||||
'live.visit': 'visit',
|
||||
'live.legend.visits': 'visits',
|
||||
'live.m.vis': 'Visits, 15 min',
|
||||
'live.m.pages': 'Pages, 15 min',
|
||||
'live.m.vis': 'Visitors, 1 h',
|
||||
'live.m.pages': 'Pages viewed, 1 h',
|
||||
'live.unit.pages': 'distinct pages',
|
||||
'live.sub.vis': '{n} requests',
|
||||
'live.sub.top': 'top: {x}',
|
||||
'live.devices': 'Devices',
|
||||
'live.vis.empty': 'anonymous',
|
||||
'live.mode': 'View',
|
||||
@@ -924,9 +924,11 @@
|
||||
'live.visits': 'Tráfego legítimo',
|
||||
'live.visit': 'visita',
|
||||
'live.legend.visits': 'visitas',
|
||||
'live.m.vis': 'Visitas, 15 min',
|
||||
'live.m.pages': 'Páginas, 15 min',
|
||||
'live.m.vis': 'Visitantes, 1 h',
|
||||
'live.m.pages': 'Páginas vistas, 1 h',
|
||||
'live.unit.pages': 'páginas distintas',
|
||||
'live.sub.vis': '{n} requisições',
|
||||
'live.sub.top': 'mais: {x}',
|
||||
'live.vis.empty': 'anônima',
|
||||
'live.devices': 'Dispositivos',
|
||||
'live.mode': 'Visualização',
|
||||
@@ -1010,7 +1012,8 @@
|
||||
if (window.matchMedia) { var mqw = matchMedia('(min-width: 1200px)'); if (mqw.addEventListener) this.listen(mqw, 'change', function () { self.placeRec(); self.map._map.resize(); }); }
|
||||
this.timers.push(setInterval(function () { self.tick(); }, 1000));
|
||||
this.timers.push(setInterval(function () { self.loadSummary(); self.loadMetrics(); }, 60000));
|
||||
this.loadSummary(); this.loadMetrics(); this.loadRecent();
|
||||
this.timers.push(setInterval(function () { self.loadTraffic(); }, 30000));
|
||||
this.loadSummary(); this.loadMetrics(); this.loadRecent(); this.loadTraffic();
|
||||
this.tick(true);
|
||||
}
|
||||
var P = Live.prototype;
|
||||
@@ -1336,7 +1339,7 @@
|
||||
|
||||
P.onVisibility = function () {
|
||||
this.hidden = document.hidden;
|
||||
if (!this.hidden) { this.loadSummary(); this.loadMetrics(); this.tick(true); }
|
||||
if (!this.hidden) { this.loadSummary(); this.loadMetrics(); this.loadTraffic(); this.tick(true); }
|
||||
};
|
||||
|
||||
P.addMore = function (n) {
|
||||
@@ -1596,14 +1599,35 @@
|
||||
for (var k in this.bk) if (+k < min - 1500) delete this.bk[k];
|
||||
};
|
||||
|
||||
// legitimate traffic: totals of the last hour from /api/v1/traffic (the server has no 15 min range),
|
||||
// refreshed every 30 s whether or not the "Legitimate traffic" toggle is on (it only controls the drawing)
|
||||
P.loadTraffic = function () {
|
||||
var self = this;
|
||||
if (!this.U.api || this.hidden) return;
|
||||
var h = this.ctx && this.ctx.host, q = { range: '1h' };
|
||||
if (h && h !== 'all') q.host = h;
|
||||
var key = q.host || 'all', p;
|
||||
try { p = this.U.api('/api/v1/traffic', q); } catch (x) { return; }
|
||||
if (!p || !p.then) return;
|
||||
p.then(function (d) {
|
||||
if (!self.alive || !d || typeof d !== 'object') return;
|
||||
var top = function (l) { return Array.isArray(l) && l[0] && l[0].key ? l[0] : null; };
|
||||
self.traf = { key: key, visitors: isNum(d.visitors) ? d.visitors : null, pages: isNum(d.pages) ? d.pages : null, requests: isNum(d.requests) ? d.requests : null, dom: top(d.domains), cc: top(d.countries) };
|
||||
self.minute = -1; self.tick(true);
|
||||
}).catch(function () { /* traffic unavailable */ });
|
||||
};
|
||||
P.visitMetrics = function (min, fmtN) {
|
||||
var vn = 0, pg = 0, vi, mm = this.mM, self = this;
|
||||
for (vi = min - 14; vi <= min; vi++) if (this.vbk[vi]) vn += this.vbk[vi].n;
|
||||
this.pathLast.forEach(function (last) { if (last >= min - 14) pg++; });
|
||||
mm.vis.val.textContent = fmtN(vn); this.setSub(mm.vis, this.t('live.legend.visits'), '');
|
||||
mm.pages.val.textContent = fmtN(pg); this.setSub(mm.pages, this.t('live.unit.pages'), '');
|
||||
this.pathLast.forEach(function (last, p) { if (last < min - 30) self.pathLast.delete(p); });
|
||||
var mm = this.mM, d = this.traf, h = this.ctx && this.ctx.host;
|
||||
if (!d || d.key !== (h && h !== 'all' ? h : 'all')) { mm.vis.val.textContent = '-'; mm.pages.val.textContent = '-'; return; }
|
||||
mm.vis.val.textContent = d.visitors === null ? '-' : fmtN(d.visitors);
|
||||
this.setSub(mm.vis, d.requests === null ? this.t('live.legend.visits') : this.t('live.sub.vis', { n: fmtN(d.requests) }), '');
|
||||
mm.pages.val.textContent = d.pages === null ? '-' : fmtN(d.pages);
|
||||
var x = d.dom ? str(d.dom.key, 40) : '';
|
||||
if (d.cc && d.cc.key) x = (x ? x + ' · ' : '') + cc2(d.cc.key);
|
||||
this.setSub(mm.pages, x ? this.t('live.sub.top', { x: x }) : this.t('live.unit.pages'), '');
|
||||
var pl = this.pathLast;
|
||||
for (var vk in this.vbk) if (+vk < min - 40) delete this.vbk[vk];
|
||||
pl.forEach(function (last, p) { if (last < min - 30) pl.delete(p); });
|
||||
};
|
||||
|
||||
P.regionName = function (cc) {
|
||||
@@ -1621,7 +1645,7 @@
|
||||
var fmtN = this.U.fmt && this.U.fmt.num ? this.U.fmt.num : String;
|
||||
var fl = this.U.fmt && this.U.fmt.flag ? this.U.fmt.flag : function () { return ''; };
|
||||
if (min !== this.minute) { this.minute = min; this.computeMetrics(min, fmtN); }
|
||||
if (this.visitsOn) this.visitMetrics(min, fmtN);
|
||||
this.visitMetrics(min, fmtN);
|
||||
// category and server counts, origins: the 15 minute window (partial minute included)
|
||||
var a = this.agg(min - 14, min, true), vis = this.agg(min - 14, min, false), c;
|
||||
CATS.forEach(function (k) {
|
||||
|
||||
@@ -75,6 +75,10 @@
|
||||
{
|
||||
"name": "incidents",
|
||||
"css": true
|
||||
},
|
||||
{
|
||||
"name": "probes",
|
||||
"css": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/* Probes panel (Sources page) and its dialogs. */
|
||||
.pr-name { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
|
||||
.pr-name strong { overflow-wrap: normal; word-break: normal; white-space: nowrap; }
|
||||
.pr-table td:first-child { min-width: 7rem; }
|
||||
.pr-sum { margin: 0 0 10px; color: var(--ink-muted); }
|
||||
.pr-sum.bad { color: var(--danger); font-weight: 600; }
|
||||
@media (max-width: 760px) { .pr-name strong { white-space: normal; overflow-wrap: anywhere; } }
|
||||
.pr-muted { color: var(--ink-muted); font-size: .8125rem; }
|
||||
.pr-srcs { display: flex; flex-wrap: wrap; gap: 4px; }
|
||||
.pr-acts { display: inline-flex; gap: 6px; flex-wrap: wrap; }
|
||||
.btn.pr-sm { padding: 3px 10px; font-size: .8125rem; min-height: 30px; }
|
||||
.btn.pr-danger { color: var(--danger); }
|
||||
.btn.pr-danger:hover:not(:disabled) { border-color: var(--danger); background: var(--danger-soft); }
|
||||
.pr-warnv { color: var(--warn); font-weight: 600; }
|
||||
.pr-revoked td { opacity: .6; }
|
||||
.pr-table td, .pr-table th { vertical-align: top; }
|
||||
.pr-body { display: grid; gap: var(--s-3, 12px); }
|
||||
.panel-b > .lead { margin-bottom: 12px; }
|
||||
|
||||
.pr-dlg { width: min(34rem, calc(100vw - 32px)); box-sizing: border-box; }
|
||||
.pr-dlg.wide { width: min(44rem, calc(100vw - 32px)); }
|
||||
.pr-dlg input[type="text"], .pr-dlg input[type="number"], .pr-dlg textarea { width: 100%; box-sizing: border-box; }
|
||||
.pr-dlg textarea { padding: 8px 10px; border: 1px solid var(--line); border-radius: var(--radius-sm); background: var(--surface-raised); color: var(--ink); font-size: .8125rem; resize: vertical; }
|
||||
.pr-field { display: grid; gap: 4px; margin: 10px 0; min-width: 0; }
|
||||
.pr-field label, .pr-lbl { font-weight: 600; display: block; margin: 10px 0 4px; }
|
||||
.pr-field label { margin: 0; }
|
||||
.pr-fh { color: var(--ink-muted); }
|
||||
.pr-warn { margin: 0 0 8px; padding: 8px 10px; border: 1px solid color-mix(in srgb, var(--warn) 55%, transparent); background: var(--warn-soft); color: var(--ink); border-radius: var(--radius-sm); }
|
||||
.pr-row { display: flex; gap: 8px; align-items: center; }
|
||||
.pr-row .pr-tok { flex: 1; min-width: 0; }
|
||||
.pr-end { justify-content: flex-end; margin-top: 8px; }
|
||||
.pr-snip { white-space: pre; overflow: auto; margin-top: 6px; }
|
||||
.pr-note { min-height: 1.25em; margin: 8px 0 0; color: var(--ink-muted); }
|
||||
.pr-fs { border: 0; padding: 0; margin: 12px 0 0; min-width: 0; }
|
||||
.pr-fs legend { padding: 0; font-weight: 700; }
|
||||
.pr-grid { display: grid; grid-template-columns: 1fr 1fr 1.4fr; gap: 10px; }
|
||||
.unban-host { display: grid; gap: 4px; margin: 12px 0; }
|
||||
.unban-host label { font-weight: 600; }
|
||||
@media (max-width: 560px) {
|
||||
.pr-grid { grid-template-columns: 1fr; gap: 0; }
|
||||
.pr-row { flex-direction: column; align-items: stretch; }
|
||||
.pr-dlg { padding: 12px; }
|
||||
}
|
||||
.pr-dlg, .pr-dlg.wide { max-width: calc(100vw - 32px); }
|
||||
@@ -0,0 +1,430 @@
|
||||
/* Urutau - PROBES panel of the Sources page: the probes that ship logs to this hub (status, last line, lag, version,
|
||||
dropped lines, spool, source states), create (token shown once + compose snippet), edit location/egress, revoke.
|
||||
Data: GET/POST /api/v1/probes, PUT/DELETE /api/v1/probes/{name}. Names, versions and errors come from remote
|
||||
machines: dynamic text goes through textContent only. Exposes Urutau.probesPanel(); app.js mounts it. */
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
var NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
||||
var SRC_STATES = ['following', 'waiting', 'error'];
|
||||
var PROBE_IMAGE = 'git.lucasrguerra.dev.br/ciberfauna/urutau-probe:latest';
|
||||
|
||||
function boot() {
|
||||
var U = window.Urutau;
|
||||
if (!U || !U.registerI18n || !U.ui) return false;
|
||||
var el = U.el, t = U.t, nf = U.fmt.num;
|
||||
|
||||
U.registerI18n({
|
||||
en: {
|
||||
'pr.title': 'Probes',
|
||||
'pr.hint': 'Machines that read their logs locally and send them to this hub.',
|
||||
'pr.help': 'A probe is a small agent that runs next to the logs. It sends lines to the hub and keeps a local queue (spool) while the hub is unreachable, so nothing is lost.',
|
||||
'pr.empty': 'No probe created yet.',
|
||||
'pr.empty.sub': 'Create one, copy its token once and start the probe on the machine that owns the logs.',
|
||||
'pr.new': 'New probe',
|
||||
'pr.col.probe': 'Probe', 'pr.col.status': 'Status', 'pr.col.lastLine': 'Last line', 'pr.col.lag': 'Delay',
|
||||
'pr.col.version': 'Version', 'pr.col.dropped': 'Dropped', 'pr.col.spool': 'Queue', 'pr.col.sources': 'Sources', 'pr.col.actions': 'Actions',
|
||||
'pr.st.connected': 'connected', 'pr.st.offline': 'offline', 'pr.st.revoked': 'revoked',
|
||||
'pr.src.following': 'following', 'pr.src.waiting': 'waiting', 'pr.src.error': 'error',
|
||||
'pr.src.none': 'no source reported',
|
||||
'pr.edit': 'Edit', 'pr.revoke': 'Revoke',
|
||||
'pr.lead.none': 'No probes',
|
||||
'pr.lead.all.one': 'The probe is connected',
|
||||
'pr.lead.all.other': 'All {n} probes are connected',
|
||||
'pr.lead.some': 'Probes connected: {a} of {n}',
|
||||
'pr.lead.body': 'Dropped lines: {d}. Queued on the probes: {q}.',
|
||||
'pr.err.load': 'Could not load the probes.',
|
||||
'pr.new.title': 'New probe',
|
||||
'pr.new.hint': 'The name identifies the machine in the dashboard. Letters, digits, dot, dash and underscore.',
|
||||
'pr.new.name': 'Probe name',
|
||||
'pr.new.create': 'Create probe',
|
||||
'pr.new.invalid': 'Use 1 to 64 letters, digits, dot, dash or underscore, starting with a letter or digit.',
|
||||
'pr.new.exists': 'A probe with this name already exists.',
|
||||
'pr.new.err': 'Could not create the probe. Try again.',
|
||||
'pr.tok.title': 'Probe "{name}" created',
|
||||
'pr.tok.warn': 'This token is shown only once. Copy it now: it cannot be recovered, only replaced by creating another probe.',
|
||||
'pr.tok.label': 'Token',
|
||||
'pr.tok.copy': 'Copy token',
|
||||
'pr.tok.copied': 'Token copied',
|
||||
'pr.tok.snippet': 'docker-compose.yml for the probe machine',
|
||||
'pr.tok.snippet.hint': 'The token is already filled in. Adjust the log paths if yours differ.',
|
||||
'pr.tok.copySnippet': 'Copy compose',
|
||||
'pr.tok.copiedSnippet': 'Compose copied',
|
||||
'pr.tok.copyFail': 'Could not copy. Select the text and copy it by hand.',
|
||||
'pr.tok.done': 'I saved the token',
|
||||
'pr.edit.title': 'Edit probe "{name}"',
|
||||
'pr.edit.loc': 'Location on the map',
|
||||
'pr.edit.lat': 'Latitude', 'pr.edit.lon': 'Longitude', 'pr.edit.label': 'Label',
|
||||
'pr.edit.egress': 'Outbound traffic (egress)',
|
||||
'pr.edit.workloads': 'Workloads', 'pr.edit.workloads.hint': 'name=ITEM,ITEM:role;name2=...',
|
||||
'pr.edit.resolvers': 'Allowed DNS resolvers', 'pr.edit.resolvers.hint': 'comma separated; empty uses the usual ones',
|
||||
'pr.edit.allow': 'Allowed destinations', 'pr.edit.allow.hint': 'comma separated',
|
||||
'pr.edit.save': 'Save',
|
||||
'pr.edit.badLoc': 'Latitude must be between -90 and 90 and longitude between -180 and 180.',
|
||||
'pr.edit.err': 'Could not save. Try again.',
|
||||
'pr.edit.done': 'Probe "{name}" updated',
|
||||
'pr.rev.title': 'Revoke probe "{name}"?',
|
||||
'pr.rev.body': 'The probe stops being accepted right away and its token no longer works. Data already received stays on the hub.',
|
||||
'pr.rev.confirm': 'Revoke',
|
||||
'pr.rev.done': 'Probe "{name}" revoked',
|
||||
'pr.rev.err': 'Could not revoke. Try again.',
|
||||
'pr.cancel': 'Cancel', 'pr.close': 'Close',
|
||||
'pr.age': '{t} ago',
|
||||
'pr.unban.host': 'Unban on'
|
||||
},
|
||||
'pt-BR': {
|
||||
'pr.title': 'Sondas',
|
||||
'pr.hint': 'Máquinas que leem os próprios logs e os enviam para este hub.',
|
||||
'pr.help': 'Uma sonda é um agente pequeno que roda ao lado dos logs. Ela envia as linhas ao hub e guarda uma fila local (spool) enquanto o hub está fora do ar, então nada se perde.',
|
||||
'pr.empty': 'Nenhuma sonda criada ainda.',
|
||||
'pr.empty.sub': 'Crie uma, copie o token uma única vez e inicie a sonda na máquina que tem os logs.',
|
||||
'pr.new': 'Nova sonda',
|
||||
'pr.col.probe': 'Sonda', 'pr.col.status': 'Status', 'pr.col.lastLine': 'Última linha', 'pr.col.lag': 'Atraso',
|
||||
'pr.col.version': 'Versão', 'pr.col.dropped': 'Descartadas', 'pr.col.spool': 'Fila', 'pr.col.sources': 'Fontes', 'pr.col.actions': 'Ações',
|
||||
'pr.st.connected': 'conectada', 'pr.st.offline': 'offline', 'pr.st.revoked': 'revogada',
|
||||
'pr.src.following': 'acompanhando', 'pr.src.waiting': 'aguardando', 'pr.src.error': 'erro',
|
||||
'pr.src.none': 'nenhuma fonte informada',
|
||||
'pr.edit': 'Editar', 'pr.revoke': 'Revogar',
|
||||
'pr.lead.none': 'Nenhuma sonda',
|
||||
'pr.lead.all.one': 'A sonda está conectada',
|
||||
'pr.lead.all.other': 'Todas as {n} sondas estão conectadas',
|
||||
'pr.lead.some': 'Sondas conectadas: {a} de {n}',
|
||||
'pr.lead.body': 'Linhas descartadas: {d}. Na fila das sondas: {q}.',
|
||||
'pr.err.load': 'Não foi possível carregar as sondas.',
|
||||
'pr.new.title': 'Nova sonda',
|
||||
'pr.new.hint': 'O nome identifica a máquina no painel. Letras, dígitos, ponto, hífen e sublinhado.',
|
||||
'pr.new.name': 'Nome da sonda',
|
||||
'pr.new.create': 'Criar sonda',
|
||||
'pr.new.invalid': 'Use de 1 a 64 letras, dígitos, ponto, hífen ou sublinhado, começando por letra ou dígito.',
|
||||
'pr.new.exists': 'Já existe uma sonda com este nome.',
|
||||
'pr.new.err': 'Não foi possível criar a sonda. Tente de novo.',
|
||||
'pr.tok.title': 'Sonda "{name}" criada',
|
||||
'pr.tok.warn': 'Este token aparece uma única vez. Copie agora: ele não pode ser recuperado, só substituído criando outra sonda.',
|
||||
'pr.tok.label': 'Token',
|
||||
'pr.tok.copy': 'Copiar token',
|
||||
'pr.tok.copied': 'Token copiado',
|
||||
'pr.tok.snippet': 'docker-compose.yml da máquina da sonda',
|
||||
'pr.tok.snippet.hint': 'O token já está preenchido. Ajuste os caminhos dos logs se os seus forem diferentes.',
|
||||
'pr.tok.copySnippet': 'Copiar compose',
|
||||
'pr.tok.copiedSnippet': 'Compose copiado',
|
||||
'pr.tok.copyFail': 'Não foi possível copiar. Selecione o texto e copie à mão.',
|
||||
'pr.tok.done': 'Guardei o token',
|
||||
'pr.edit.title': 'Editar sonda "{name}"',
|
||||
'pr.edit.loc': 'Localização no mapa',
|
||||
'pr.edit.lat': 'Latitude', 'pr.edit.lon': 'Longitude', 'pr.edit.label': 'Rótulo',
|
||||
'pr.edit.egress': 'Tráfego de saída (egress)',
|
||||
'pr.edit.workloads': 'Workloads', 'pr.edit.workloads.hint': 'nome=ITEM,ITEM:papel;nome2=...',
|
||||
'pr.edit.resolvers': 'Resolvedores DNS permitidos', 'pr.edit.resolvers.hint': 'separados por vírgula; vazio usa os usuais',
|
||||
'pr.edit.allow': 'Destinos permitidos', 'pr.edit.allow.hint': 'separados por vírgula',
|
||||
'pr.edit.save': 'Salvar',
|
||||
'pr.edit.badLoc': 'A latitude deve ficar entre -90 e 90 e a longitude entre -180 e 180.',
|
||||
'pr.edit.err': 'Não foi possível salvar. Tente de novo.',
|
||||
'pr.edit.done': 'Sonda "{name}" atualizada',
|
||||
'pr.rev.title': 'Revogar a sonda "{name}"?',
|
||||
'pr.rev.body': 'A sonda deixa de ser aceita na hora e o token dela para de funcionar. Os dados já recebidos continuam no hub.',
|
||||
'pr.rev.confirm': 'Revogar',
|
||||
'pr.rev.done': 'Sonda "{name}" revogada',
|
||||
'pr.rev.err': 'Não foi possível revogar. Tente de novo.',
|
||||
'pr.cancel': 'Cancelar', 'pr.close': 'Fechar',
|
||||
'pr.age': 'há {t}',
|
||||
'pr.unban.host': 'Desbanir em'
|
||||
}
|
||||
});
|
||||
|
||||
// ---- helpers
|
||||
function pick(o, a, b) { return o[a] !== undefined && o[a] !== null ? o[a] : o[b]; }
|
||||
// ProbeInfo tolerant of snake_case or Go field names
|
||||
function norm(p) {
|
||||
var loc = pick(p, 'location', 'Location') || null;
|
||||
var sec = function (v) { if (typeof v === 'string') { var d = Date.parse(v); return isFinite(d) ? d / 1000 : 0; } v = Number(v) || 0; return v > 1e12 ? v / 1000 : v; };
|
||||
return {
|
||||
name: String(pick(p, 'name', 'Name') || ''),
|
||||
connected: !!pick(p, 'connected', 'Connected'),
|
||||
revoked: !!pick(p, 'revoked', 'Revoked'),
|
||||
lastSeen: sec(pick(p, 'last_seen', 'LastSeen')),
|
||||
lastLine: sec(pick(p, 'last_line', 'LastLine')),
|
||||
lagMs: Number(pick(p, 'lag_ms', 'LagMS')) || 0,
|
||||
version: String(pick(p, 'version', 'Version') || ''),
|
||||
dropped: Number(pick(p, 'dropped', 'Dropped')) || 0,
|
||||
spool: Number(pick(p, 'spool', 'Spool')) || 0,
|
||||
sources: pick(p, 'sources', 'Sources') || [],
|
||||
location: loc,
|
||||
egress: pick(p, 'egress', 'Egress') || {}
|
||||
};
|
||||
}
|
||||
function fmtLag(ms) {
|
||||
if (!ms || ms < 0) return '0 ms';
|
||||
if (ms < 1000) return Math.round(ms) + ' ms';
|
||||
var s = ms / 1000;
|
||||
if (s < 60) return (s < 10 ? s.toFixed(1) : Math.round(s)) + ' s';
|
||||
if (s < 3600) return Math.round(s / 60) + ' min';
|
||||
return Math.round(s / 3600) + ' h';
|
||||
}
|
||||
function listText(v) { return Array.isArray(v) ? v.join(', ') : (v === undefined || v === null ? '' : String(v)); }
|
||||
function shape(orig, text) {
|
||||
// keep the type the hub sent: arrays stay arrays, strings stay strings
|
||||
if (Array.isArray(orig)) return text.split(/[,\n]+/).map(function (x) { return x.trim(); }).filter(Boolean);
|
||||
return text.trim();
|
||||
}
|
||||
function copy(text) {
|
||||
if (navigator.clipboard && navigator.clipboard.writeText) return navigator.clipboard.writeText(text);
|
||||
return new Promise(function (ok, no) {
|
||||
var ta = el('textarea', { style: { position: 'fixed', opacity: '0' } }); ta.value = text; document.body.appendChild(ta); ta.select();
|
||||
var good = false; try { good = document.execCommand('copy'); } catch (e) { /* none */ }
|
||||
document.body.removeChild(ta); good ? ok() : no(new Error('copy'));
|
||||
});
|
||||
}
|
||||
|
||||
// ---- dialogs (native <dialog>, same look as the unban dialog)
|
||||
function dialog(title, labelId, wide) {
|
||||
var prev = document.activeElement;
|
||||
var dlg = el('dialog', { class: 'unban-dlg pr-dlg' + (wide ? ' wide' : ''), 'aria-labelledby': labelId });
|
||||
dlg.appendChild(el('h2', { id: labelId }, title));
|
||||
dlg.addEventListener('close', function () {
|
||||
if (dlg.parentNode) dlg.parentNode.removeChild(dlg);
|
||||
if (prev && prev.focus && document.contains(prev)) prev.focus();
|
||||
});
|
||||
dlg.open_ = function () { document.body.appendChild(dlg); if (dlg.showModal) dlg.showModal(); else dlg.setAttribute('open', ''); };
|
||||
return dlg;
|
||||
}
|
||||
function field(label, input, hint, id) {
|
||||
input.id = id;
|
||||
return el('div', { class: 'pr-field' }, el('label', { for: id }, label), input, hint ? el('small', { class: 'pr-fh' }, hint) : null);
|
||||
}
|
||||
function errBox() { return el('p', { class: 'unban-err', role: 'alert', hidden: true }); }
|
||||
function showErr(box, key) { box.textContent = t(key); box.hidden = false; }
|
||||
|
||||
function composeSnippet(name, token) {
|
||||
var hub = location.origin;
|
||||
return [
|
||||
'services:',
|
||||
' urutau-probe:',
|
||||
' image: ' + PROBE_IMAGE,
|
||||
' command: ["probe"]',
|
||||
' restart: unless-stopped',
|
||||
' group_add: ["4"]',
|
||||
' environment:',
|
||||
' URUTAU_HUB: "' + hub + '"',
|
||||
' URUTAU_PROBE_NAME: "' + name + '"',
|
||||
' URUTAU_PROBE_TOKEN: "' + token + '"',
|
||||
' URUTAU_STATE_DIR: /state',
|
||||
' URUTAU_TRAEFIK_LOG: /logs/traefik/access.log',
|
||||
' URUTAU_AUTH_LOG: /logs/host/auth.log',
|
||||
' URUTAU_FAIL2BAN_LOG: /logs/host/fail2ban.log',
|
||||
' URUTAU_PROBE_LOG: /logs/urutau/probe.log',
|
||||
' URUTAU_EGRESS_LOG: /logs/urutau/egress.log',
|
||||
' URUTAU_ENFORCE_LOG: /logs/enforce/decisions.log',
|
||||
' URUTAU_ENFORCE_UNBAN_LOG: /logs/enforce/unban.log',
|
||||
' volumes:',
|
||||
' - /var/log:/logs/host:ro',
|
||||
' - /data/coolify/proxy/logs:/logs/traefik:ro',
|
||||
' - /var/log/urutau:/logs/urutau:ro',
|
||||
' - /etc/resolv.conf:/etc/resolv.conf:ro',
|
||||
' - /var/log/urutau-enforce:/logs/enforce',
|
||||
' - urutau-probe-state:/state',
|
||||
'volumes:',
|
||||
' urutau-probe-state:',
|
||||
''
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
function tokenDialog(name, token, done) {
|
||||
var dlg = dialog(t('pr.tok.title', { name: name }), 'pr-tok-h', true);
|
||||
var msg = el('p', { class: 'pr-note', role: 'status' });
|
||||
var tokIn = el('input', { type: 'text', readonly: true, class: 'mono pr-tok', value: token, 'aria-label': t('pr.tok.label') });
|
||||
tokIn.addEventListener('focus', function () { tokIn.select(); });
|
||||
var cpTok = el('button', { type: 'button', class: 'btn' }, t('pr.tok.copy'));
|
||||
var snip = composeSnippet(name, token);
|
||||
var pre = el('textarea', { class: 'mono pr-snip', readonly: true, rows: '14', spellcheck: 'false', 'aria-label': t('pr.tok.snippet') });
|
||||
pre.value = snip;
|
||||
var cpSnip = el('button', { type: 'button', class: 'btn' }, t('pr.tok.copySnippet'));
|
||||
var ok = el('button', { type: 'button', class: 'btn primary' }, t('pr.tok.done'));
|
||||
function doCopy(text, okKey) { copy(text).then(function () { msg.textContent = t(okKey); }, function () { msg.textContent = t('pr.tok.copyFail'); }); }
|
||||
cpTok.addEventListener('click', function () { doCopy(token, 'pr.tok.copied'); });
|
||||
cpSnip.addEventListener('click', function () { doCopy(snip, 'pr.tok.copiedSnippet'); });
|
||||
dlg.appendChild(el('p', { class: 'pr-warn' }, t('pr.tok.warn')));
|
||||
dlg.appendChild(el('label', { for: 'pr-tok', class: 'pr-lbl' }, t('pr.tok.label')));
|
||||
tokIn.id = 'pr-tok';
|
||||
dlg.appendChild(el('div', { class: 'pr-row' }, tokIn, cpTok));
|
||||
dlg.appendChild(el('p', { class: 'pr-lbl' }, t('pr.tok.snippet')));
|
||||
dlg.appendChild(el('small', { class: 'pr-fh' }, t('pr.tok.snippet.hint')));
|
||||
dlg.appendChild(pre);
|
||||
dlg.appendChild(el('div', { class: 'pr-row pr-end' }, cpSnip));
|
||||
dlg.appendChild(msg);
|
||||
dlg.appendChild(el('div', { class: 'unban-btns' }, ok));
|
||||
dlg.addEventListener('cancel', function (e) { e.preventDefault(); }); // Esc must not lose the only copy by accident
|
||||
ok.addEventListener('click', function () { dlg.close(); if (done) done(); });
|
||||
dlg.open_(); tokIn.focus(); tokIn.select();
|
||||
}
|
||||
|
||||
function newDialog(done) {
|
||||
var dlg = dialog(t('pr.new.title'), 'pr-new-h');
|
||||
var name = el('input', { type: 'text', autocomplete: 'off', maxlength: '64', spellcheck: 'false', class: 'mono' });
|
||||
var err = errBox();
|
||||
var ok = el('button', { type: 'button', class: 'btn primary' }, t('pr.new.create'));
|
||||
var cancel = el('button', { type: 'button', class: 'btn' }, t('pr.cancel'));
|
||||
dlg.appendChild(field(t('pr.new.name'), name, t('pr.new.hint'), 'pr-new-name'));
|
||||
dlg.appendChild(err);
|
||||
dlg.appendChild(el('div', { class: 'unban-btns' }, cancel, ok));
|
||||
cancel.addEventListener('click', function () { dlg.close(); });
|
||||
function go() {
|
||||
var n = name.value.trim();
|
||||
if (!NAME_RE.test(n)) { showErr(err, 'pr.new.invalid'); name.focus(); return; }
|
||||
ok.disabled = true; err.hidden = true;
|
||||
U.apiSend('POST', '/api/v1/probes', { name: n }).then(function (r) {
|
||||
var token = r && (r.token || r.Token);
|
||||
dlg.close();
|
||||
if (!token) { showErr(err, 'pr.new.err'); return; }
|
||||
tokenDialog(n, String(token), done);
|
||||
if (done) done(true);
|
||||
}, function (e) {
|
||||
ok.disabled = false; showErr(err, e && e.status === 409 ? 'pr.new.exists' : 'pr.new.err');
|
||||
});
|
||||
}
|
||||
ok.addEventListener('click', go);
|
||||
name.addEventListener('keydown', function (e) { if (e.key === 'Enter') { e.preventDefault(); go(); } });
|
||||
dlg.open_(); name.focus();
|
||||
}
|
||||
|
||||
function editDialog(p, done) {
|
||||
var dlg = dialog(t('pr.edit.title', { name: p.name }), 'pr-ed-h', true);
|
||||
var loc = p.location || {};
|
||||
var num = function (v) { return el('input', { type: 'number', step: 'any', inputmode: 'decimal', value: v === undefined || v === null ? '' : String(v) }); };
|
||||
var lat = num(loc.lat), lon = num(loc.lon);
|
||||
var label = el('input', { type: 'text', maxlength: '64', value: loc.label || '' });
|
||||
var eg = p.egress || {};
|
||||
var wl = el('textarea', { rows: '3', spellcheck: 'false', class: 'mono' }); wl.value = listText(eg.workloads !== undefined ? eg.workloads : eg.Workloads);
|
||||
var rs = el('textarea', { rows: '2', spellcheck: 'false', class: 'mono' }); rs.value = listText(eg.resolvers !== undefined ? eg.resolvers : eg.Resolvers);
|
||||
var al = el('textarea', { rows: '2', spellcheck: 'false', class: 'mono' }); al.value = listText(eg.allow !== undefined ? eg.allow : eg.Allow);
|
||||
var err = errBox();
|
||||
var ok = el('button', { type: 'button', class: 'btn primary' }, t('pr.edit.save'));
|
||||
var cancel = el('button', { type: 'button', class: 'btn' }, t('pr.cancel'));
|
||||
dlg.appendChild(el('fieldset', { class: 'pr-fs' }, el('legend', null, t('pr.edit.loc')),
|
||||
el('div', { class: 'pr-grid' }, field(t('pr.edit.lat'), lat, '', 'pr-ed-lat'), field(t('pr.edit.lon'), lon, '', 'pr-ed-lon'), field(t('pr.edit.label'), label, '', 'pr-ed-label'))));
|
||||
dlg.appendChild(el('fieldset', { class: 'pr-fs' }, el('legend', null, t('pr.edit.egress')),
|
||||
field(t('pr.edit.workloads'), wl, t('pr.edit.workloads.hint'), 'pr-ed-wl'),
|
||||
field(t('pr.edit.resolvers'), rs, t('pr.edit.resolvers.hint'), 'pr-ed-rs'),
|
||||
field(t('pr.edit.allow'), al, t('pr.edit.allow.hint'), 'pr-ed-al')));
|
||||
dlg.appendChild(err);
|
||||
dlg.appendChild(el('div', { class: 'unban-btns' }, cancel, ok));
|
||||
cancel.addEventListener('click', function () { dlg.close(); });
|
||||
ok.addEventListener('click', function () {
|
||||
var body = { egress: { workloads: shape(eg.workloads, wl.value), resolvers: shape(eg.resolvers, rs.value), allow: shape(eg.allow, al.value) }, location: null };
|
||||
if (lat.value.trim() !== '' || lon.value.trim() !== '' || label.value.trim() !== '') {
|
||||
var la = parseFloat(lat.value), lo = parseFloat(lon.value);
|
||||
if (!isFinite(la) || !isFinite(lo) || la < -90 || la > 90 || lo < -180 || lo > 180) { showErr(err, 'pr.edit.badLoc'); return; }
|
||||
body.location = { lat: la, lon: lo };
|
||||
if (label.value.trim()) body.location.label = label.value.trim();
|
||||
}
|
||||
ok.disabled = true; err.hidden = true;
|
||||
U.apiSend('PUT', '/api/v1/probes/' + encodeURIComponent(p.name), body).then(function () {
|
||||
dlg.close(); U.toast(t('pr.edit.done', { name: p.name })); if (done) done();
|
||||
}, function () { ok.disabled = false; showErr(err, 'pr.edit.err'); });
|
||||
});
|
||||
dlg.open_(); lat.focus();
|
||||
}
|
||||
|
||||
function revokeDialog(p, done) {
|
||||
var dlg = dialog(t('pr.rev.title', { name: p.name }), 'pr-rev-h');
|
||||
var err = errBox();
|
||||
var ok = el('button', { type: 'button', class: 'btn pr-danger' }, t('pr.rev.confirm'));
|
||||
var cancel = el('button', { type: 'button', class: 'btn' }, t('pr.cancel'));
|
||||
dlg.appendChild(el('p', null, t('pr.rev.body')));
|
||||
dlg.appendChild(err);
|
||||
dlg.appendChild(el('div', { class: 'unban-btns' }, cancel, ok));
|
||||
cancel.addEventListener('click', function () { dlg.close(); });
|
||||
ok.addEventListener('click', function () {
|
||||
ok.disabled = true;
|
||||
U.apiSend('DELETE', '/api/v1/probes/' + encodeURIComponent(p.name)).then(function () {
|
||||
dlg.close(); U.toast(t('pr.rev.done', { name: p.name })); if (done) done();
|
||||
}, function () { ok.disabled = false; showErr(err, 'pr.rev.err'); });
|
||||
});
|
||||
dlg.open_(); cancel.focus();
|
||||
}
|
||||
|
||||
// ---- the panel
|
||||
function sourceChips(p) {
|
||||
var box = el('span', { class: 'pr-srcs' });
|
||||
var srcs = Array.isArray(p.sources) ? p.sources : [];
|
||||
if (!srcs.length) { box.appendChild(el('span', { class: 'pr-muted' }, t('pr.src.none'))); return box; }
|
||||
srcs.forEach(function (s) {
|
||||
var st = SRC_STATES.indexOf(s.state) >= 0 ? s.state : 'error';
|
||||
var tone = st === 'following' ? 'ok' : st === 'waiting' ? 'warn' : 'danger';
|
||||
var chip = U.ui.badge(String(s.src || '?') + ' · ' + t('pr.src.' + st), tone);
|
||||
var tip = [String(s.src || ''), t('pr.src.' + st)];
|
||||
if (s.error) tip.push(String(s.error));
|
||||
if (s.lines) tip.push(nf(s.lines));
|
||||
chip.title = tip.join(' · ');
|
||||
box.appendChild(chip);
|
||||
});
|
||||
return box;
|
||||
}
|
||||
|
||||
return (U.probesPanel = function probesPanel() {
|
||||
var body = el('div', { class: 'pr-body' });
|
||||
var leadBox = el('div');
|
||||
var tbody = el('tbody');
|
||||
var thead = el('thead', null, el('tr', null, ['pr.col.probe', 'pr.col.status', 'pr.col.lastLine', 'pr.col.lag', 'pr.col.version', 'pr.col.dropped', 'pr.col.spool', 'pr.col.sources', 'pr.col.actions'].map(function (k) { return el('th', { scope: 'col' }, t(k)); })));
|
||||
var tbl = el('div', { class: 'tbl-wrap' }, el('table', { class: 'stack tbl-cards pr-table' }, thead, tbody));
|
||||
var emptyBox = el('div');
|
||||
var errNode = el('p', { class: 'unban-err', role: 'alert', hidden: true }, t('pr.err.load'));
|
||||
var addBtn = el('button', { type: 'button', class: 'btn primary' }, t('pr.new'));
|
||||
var node = U.ui.panel({ title: t('pr.title'), hint: t('pr.hint'), actions: addBtn }, leadBox, errNode, tbl, emptyBox);
|
||||
var alive = true, seq = 0;
|
||||
function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); }
|
||||
|
||||
function cell(tr, key, content, cls) {
|
||||
var td = el('td', { class: cls || '' }); td.setAttribute('data-label', t(key));
|
||||
td.appendChild(typeof content === 'string' ? document.createTextNode(content) : content); tr.appendChild(td);
|
||||
}
|
||||
function paint(list) {
|
||||
var ps = list.map(norm).filter(function (p) { return p.name; });
|
||||
clear(leadBox); clear(tbody); clear(emptyBox);
|
||||
var live = ps.filter(function (p) { return !p.revoked; });
|
||||
var conn = live.filter(function (p) { return p.connected; }).length;
|
||||
var dropped = 0, queue = 0;
|
||||
live.forEach(function (p) { dropped += p.dropped; queue += p.spool; });
|
||||
var title = !live.length ? t('pr.lead.none') : conn === live.length ? U.pl('pr.lead.all', live.length, { n: nf(live.length) }) : t('pr.lead.some', { a: nf(conn), n: nf(live.length) });
|
||||
leadBox.appendChild(el('p', { class: 'pr-sum' + (live.length && conn < live.length ? ' bad' : '') }, title + (live.length ? '. ' + t('pr.lead.body', { d: nf(dropped), q: U.fmt.bytes(queue) }) : '')));
|
||||
tbl.hidden = !ps.length;
|
||||
if (!ps.length) emptyBox.appendChild(U.ui.empty(t('pr.empty'), t('pr.empty.sub')));
|
||||
ps.forEach(function (p) {
|
||||
var tr = el('tr', { class: p.revoked ? 'pr-revoked' : '' });
|
||||
var nm = el('span', { class: 'pr-name' }, el('strong', null, p.name));
|
||||
if (p.location && (p.location.label || p.location.lat !== undefined)) nm.appendChild(el('small', { class: 'pr-muted' }, p.location.label ? String(p.location.label) : p.location.lat + ', ' + p.location.lon));
|
||||
cell(tr, 'pr.col.probe', nm);
|
||||
cell(tr, 'pr.col.status', p.revoked ? U.ui.badge(t('pr.st.revoked'), 'neutral') : p.connected ? U.ui.badge(t('pr.st.connected'), 'ok') : U.ui.badge(t('pr.st.offline'), 'danger'), 'nw');
|
||||
cell(tr, 'pr.col.lastLine', p.lastLine ? U.fmt.ago(p.lastLine) : (p.lastSeen && !p.connected ? U.fmt.ago(p.lastSeen) : t('never')), 'nw');
|
||||
cell(tr, 'pr.col.lag', p.connected ? fmtLag(p.lagMs) : '-', 'nw');
|
||||
cell(tr, 'pr.col.version', p.version || '-', 'nw');
|
||||
cell(tr, 'pr.col.dropped', el('span', { class: 'num' + (p.dropped ? ' pr-warnv' : '') }, nf(p.dropped)), 'nw');
|
||||
cell(tr, 'pr.col.spool', el('span', { class: 'num' }, U.fmt.bytes(p.spool)), 'nw');
|
||||
cell(tr, 'pr.col.sources', sourceChips(p));
|
||||
var acts = el('span', { class: 'pr-acts' });
|
||||
if (!p.revoked) {
|
||||
var ed = el('button', { type: 'button', class: 'btn pr-sm', 'aria-label': t('pr.edit') + ' ' + p.name }, t('pr.edit'));
|
||||
ed.addEventListener('click', function () { editDialog(p, reload); });
|
||||
var rv = el('button', { type: 'button', class: 'btn pr-sm pr-danger', 'aria-label': t('pr.revoke') + ' ' + p.name }, t('pr.revoke'));
|
||||
rv.addEventListener('click', function () { revokeDialog(p, reload); });
|
||||
acts.appendChild(ed); acts.appendChild(rv);
|
||||
}
|
||||
cell(tr, 'pr.col.actions', acts);
|
||||
tbody.appendChild(tr);
|
||||
});
|
||||
}
|
||||
function reload() {
|
||||
var my = ++seq;
|
||||
return U.api('/api/v1/probes').then(function (r) {
|
||||
if (!alive || my !== seq) return;
|
||||
errNode.hidden = true;
|
||||
paint(Array.isArray(r) ? r : (r && (r.probes || r.items)) || []);
|
||||
}, function () { if (alive && my === seq) errNode.hidden = false; });
|
||||
}
|
||||
addBtn.addEventListener('click', function () { newDialog(function () { reload(); }); });
|
||||
return { node: node, reload: reload, dispose: function () { alive = false; } };
|
||||
}) && true;
|
||||
}
|
||||
|
||||
function start() { if (!boot()) setTimeout(start, 50); }
|
||||
start();
|
||||
})();
|
||||
@@ -50,6 +50,7 @@
|
||||
'rp.only': 'Incidents only',
|
||||
'rp.select': 'Select segment',
|
||||
'rp.loopclear': 'Clear segment',
|
||||
'rp.repeat': 'Repeat',
|
||||
'rp.loop': 'Looping {a} to {b}',
|
||||
'rp.share': 'Copy link',
|
||||
'rp.copied': 'Link copied',
|
||||
@@ -145,6 +146,7 @@
|
||||
'rp.only': 'Só incidentes',
|
||||
'rp.select': 'Selecionar trecho',
|
||||
'rp.loopclear': 'Limpar trecho',
|
||||
'rp.repeat': 'Repetir',
|
||||
'rp.loop': 'Repetindo de {a} a {b}',
|
||||
'rp.share': 'Copiar link',
|
||||
'rp.copied': 'Link copiado',
|
||||
@@ -266,6 +268,7 @@
|
||||
next: ['M16.5 5H19v14h-2.5z|M5 5.5v13L14.5 12z', 1],
|
||||
stepb: ['M16 5.5v13L7 12z', 1],
|
||||
stepf: ['M8 5.5v13L17 12z', 1],
|
||||
repeat: ['M17 2l4 4-4 4|M3 11V9a3 3 0 0 1 3-3h15|M7 22l-4-4 4-4|M21 13v2a3 3 0 0 1-3 3H3', 0],
|
||||
restart: ['M4 4v6h6|M5.5 15a8 8 0 1 0 2-8L4 10', 0],
|
||||
share: ['M4 12v7h16v-7|M12 3v12|M8 7l4-4 4 4', 0],
|
||||
seg: ['M4 8v8|M20 8v8|M4 12h16', 0],
|
||||
@@ -307,7 +310,8 @@
|
||||
var from = 0, to = 0, tooBig = false, routeT = '', noReg = false, campStarted = false, campId = '', campIps = null;
|
||||
var F = { cat: '', fam: '', q: '', host: '' };
|
||||
var speed = 60, compress = false, only = false;
|
||||
var playing = false, ended = false;
|
||||
var playing = false, ended = false, repeat = false;
|
||||
try { repeat = localStorage.getItem('urutau.replay.repeat') === '1'; } catch (x) { /* storage blocked */ }
|
||||
var clock = 0;
|
||||
var buf = [], idx = 0, nextTok = null, loading = false, epoch = 0, startFrom = 0, firstBatch = true, landBefore = null;
|
||||
var failed = false, drained = false;
|
||||
@@ -676,7 +680,7 @@
|
||||
clockDirty = true; tlDirty = true;
|
||||
if (buf.length - idx < AHEAD && !drained && !loading) fetchMore();
|
||||
if (loop && clock > loop.b) { seek(loop.a); return; }
|
||||
if (clock >= to && idx >= buf.length && drained) { playing = false; ended = true; syncPlay(); }
|
||||
if (clock >= to && idx >= buf.length && drained) { playing = false; ended = true; syncPlay(); if (repeat) restart(); }
|
||||
trim();
|
||||
}
|
||||
function trim() {
|
||||
@@ -861,10 +865,15 @@
|
||||
ui.compB = toggle(t('rp.compress'), function () { compress = !compress; syncToggles(); writeHash(true); });
|
||||
ui.onlyB = toggle(t('rp.only'), function () { only = !only; syncToggles(); refilter(); });
|
||||
ui.selB = toggle(t('rp.select'), function () { selecting = !selecting; if (!selecting && loop) { loop = null; tlDirty = true; } syncToggles(); kick(); });
|
||||
ui.repB = btn('rp-rep rp-tog', 'repeat', t('rp.repeat'), function () {
|
||||
repeat = !repeat; syncToggles();
|
||||
try { localStorage.setItem('urutau.replay.repeat', repeat ? '1' : '0'); } catch (x) { /* storage blocked */ }
|
||||
if (repeat && ended) restart();
|
||||
});
|
||||
ui.shareB = btn('rp-share', 'share', t('rp.share'), function () { share(); });
|
||||
ui.detB = h('button', 'btn rp-det', t('rp.detail')); ui.detB.type = 'button';
|
||||
ui.detB.addEventListener('click', function () { openSheet(); });
|
||||
[ui.prevB, ui.stepbB, ui.playB, ui.stepfB, ui.nextB, ui.clock, ui.speedSeg, ui.speedSel, ui.compB, ui.onlyB, ui.selB, ui.shareB, ui.detB].forEach(function (n) { tr.appendChild(n); });
|
||||
[ui.prevB, ui.stepbB, ui.playB, ui.stepfB, ui.nextB, ui.clock, ui.speedSeg, ui.speedSel, ui.compB, ui.onlyB, ui.selB, ui.repB, ui.shareB, ui.detB].forEach(function (n) { tr.appendChild(n); });
|
||||
ui.loopNote = h('span', 'rp-loopnote'); tr.appendChild(ui.loopNote);
|
||||
|
||||
var tw = h('div', 'rp-tl');
|
||||
@@ -939,6 +948,7 @@
|
||||
function syncToggles() {
|
||||
ui.compB.setAttribute('aria-pressed', compress ? 'true' : 'false');
|
||||
ui.onlyB.setAttribute('aria-pressed', only ? 'true' : 'false');
|
||||
ui.repB.setAttribute('aria-pressed', repeat ? 'true' : 'false');
|
||||
ui.selB.setAttribute('aria-pressed', selecting ? 'true' : 'false');
|
||||
ui.selB.textContent = loop ? t('rp.loopclear') : t('rp.select');
|
||||
ui.loopNote.textContent = loop ? t('rp.loop', { a: clockStr(loop.a), b: clockStr(loop.b) }) : '';
|
||||
|
||||
@@ -690,3 +690,12 @@ html, body { overflow-x: clip; }
|
||||
table.mc td[colspan] { display: block; text-align: left; }
|
||||
}
|
||||
@media (max-width: 767px) { table.mc .mc-v { min-width: 0; overflow-wrap: anywhere; word-break: normal; } }
|
||||
|
||||
/* ---------------------------------------------------------------- IP addresses never wrap (class set by tagIPs() in app.js) */
|
||||
.ipv, td .ipv, table.mc td .ipv, table.mc .mc-v .ipv, td.nw .ipv {
|
||||
white-space: nowrap !important; overflow-wrap: normal !important; word-break: normal !important; hyphens: none;
|
||||
font-family: var(--font-mono); font-size: .875rem; font-variant-numeric: tabular-nums; letter-spacing: 0;
|
||||
max-width: 100%; overflow: hidden; text-overflow: ellipsis; vertical-align: bottom;
|
||||
}
|
||||
.ipv.ipv-long { font-size: .75rem; }
|
||||
@media (max-width: 767px) { .ipv.ipv-long { font-size: .65rem; } }
|
||||
+16
-1
@@ -72,7 +72,22 @@ type LiveEvent struct {
|
||||
}
|
||||
|
||||
// Location is the configured location of this instance (nil when unset).
|
||||
func (s *Store) Location() *Location { return sanitizeLocation(s.cfg.Location) }
|
||||
func (s *Store) Location() *Location {
|
||||
if l := s.locOverride.Load(); l != nil {
|
||||
return sanitizeLocation(l)
|
||||
}
|
||||
return sanitizeLocation(s.cfg.Location)
|
||||
}
|
||||
|
||||
// SetLocation replaces the configured location (the hub sets it per probe).
|
||||
func (s *Store) SetLocation(l *Location) {
|
||||
if l == nil {
|
||||
s.locOverride.Store(nil)
|
||||
return
|
||||
}
|
||||
c := *l
|
||||
s.locOverride.Store(&c)
|
||||
}
|
||||
|
||||
// GeoOf resolves the geography of an address or IPv6 /64 key (zero without an enricher).
|
||||
func (s *Store) GeoOf(ip string) core.GeoInfo {
|
||||
|
||||
@@ -253,6 +253,8 @@ type Store struct {
|
||||
cfg Config
|
||||
now func() time.Time
|
||||
|
||||
locOverride atomic.Pointer[Location] // set by SetLocation
|
||||
|
||||
mu sync.RWMutex
|
||||
stamps [slots]int64
|
||||
counts [slots][core.NumCats]uint32
|
||||
|
||||
@@ -72,3 +72,124 @@ func TestFileAppearingLaterAndAppends(t *testing.T) {
|
||||
t.Fatalf("%v %v", got, f.Err())
|
||||
}
|
||||
}
|
||||
|
||||
type atRec struct {
|
||||
text string
|
||||
end Pos
|
||||
}
|
||||
|
||||
func collectAt(f *Follower) *[]atRec {
|
||||
var got []atRec
|
||||
f.HandleAt = func(b []byte, end Pos) { got = append(got, atRec{string(b), end}) }
|
||||
return &got
|
||||
}
|
||||
|
||||
func TestHandleAtReportsEndPosition(t *testing.T) {
|
||||
p := filepath.Join(t.TempDir(), "a.log")
|
||||
os.WriteFile(p, []byte("one\ntwo\nthree\n"), 0o644)
|
||||
f := NewFollower(p, Pos{})
|
||||
f.Handle = func([]byte) { t.Fatal("Handle called although HandleAt is set") }
|
||||
got := collectAt(f)
|
||||
f.step()
|
||||
if len(*got) != 3 {
|
||||
t.Fatalf("got %v", *got)
|
||||
}
|
||||
ino := (*got)[0].end.Inode
|
||||
if ino == 0 {
|
||||
t.Fatal("inode missing in end position")
|
||||
}
|
||||
for i, off := range []int64{4, 8, 14} {
|
||||
if (*got)[i].end.Offset != off || (*got)[i].end.Inode != ino {
|
||||
t.Errorf("line %d end = %+v, want offset %d", i, (*got)[i].end, off)
|
||||
}
|
||||
}
|
||||
// the end of the last line equals the follower position after the call
|
||||
if f.Pos().Offset != 14 {
|
||||
t.Errorf("pos %d", f.Pos().Offset)
|
||||
}
|
||||
// resuming from an end position yields only the new lines
|
||||
f2 := NewFollower(p, Pos{Inode: ino, Offset: (*got)[1].end.Offset})
|
||||
got2 := collectAt(f2)
|
||||
f2.step()
|
||||
if len(*got2) != 1 || (*got2)[0].text != "three" {
|
||||
t.Fatalf("resume got %v", *got2)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleAtAcrossRenameRotation(t *testing.T) {
|
||||
d := t.TempDir()
|
||||
p := filepath.Join(d, "a.log")
|
||||
os.WriteFile(p, []byte("a1\na2\n"), 0o644)
|
||||
f := NewFollower(p, Pos{})
|
||||
got := collectAt(f)
|
||||
f.step()
|
||||
os.WriteFile(p, []byte("a3\n"), 0o644) // still the old inode: append-like
|
||||
f.step()
|
||||
os.Rename(p, filepath.Join(d, "a.log.1"))
|
||||
os.WriteFile(p, []byte("b1\nb2\n"), 0o644)
|
||||
f.step()
|
||||
f.step()
|
||||
want := []struct {
|
||||
text string
|
||||
off int64
|
||||
}{{"a1", 3}, {"a2", 6}}
|
||||
if len(*got) < 4 {
|
||||
t.Fatalf("got %v", *got)
|
||||
}
|
||||
for i, w := range want {
|
||||
if (*got)[i].text != w.text || (*got)[i].end.Offset != w.off {
|
||||
t.Errorf("rec %d = %+v", i, (*got)[i])
|
||||
}
|
||||
}
|
||||
n := len(*got)
|
||||
b1, b2 := (*got)[n-2], (*got)[n-1]
|
||||
if b1.text != "b1" || b1.end.Offset != 3 || b2.text != "b2" || b2.end.Offset != 6 {
|
||||
t.Fatalf("after rotation: %+v %+v", b1, b2)
|
||||
}
|
||||
if b1.end.Inode == (*got)[0].end.Inode {
|
||||
t.Error("inode did not change across rename rotation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleAtAcrossCopytruncate(t *testing.T) {
|
||||
p := filepath.Join(t.TempDir(), "a.log")
|
||||
os.WriteFile(p, []byte("l1\nl2\nl3\n"), 0o644)
|
||||
f := NewFollower(p, Pos{})
|
||||
got := collectAt(f)
|
||||
f.step()
|
||||
os.Truncate(p, 0)
|
||||
f.step()
|
||||
os.WriteFile(p, []byte("n1\nn2\n"), 0o644)
|
||||
f.step()
|
||||
f.step()
|
||||
if len(*got) != 5 {
|
||||
t.Fatalf("got %v", *got)
|
||||
}
|
||||
if r := (*got)[2]; r.text != "l3" || r.end.Offset != 9 {
|
||||
t.Errorf("%+v", r)
|
||||
}
|
||||
if r := (*got)[3]; r.text != "n1" || r.end.Offset != 3 {
|
||||
t.Errorf("after truncate: %+v", r)
|
||||
}
|
||||
if r := (*got)[4]; r.text != "n2" || r.end.Offset != 6 {
|
||||
t.Errorf("after truncate: %+v", r)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleAtOversizeAdvancesOffset(t *testing.T) {
|
||||
p := filepath.Join(t.TempDir(), "a.log")
|
||||
big := make([]byte, 300)
|
||||
for i := range big {
|
||||
big[i] = 'x'
|
||||
}
|
||||
os.WriteFile(p, append(append([]byte("ok\n"), big...), []byte("\nnext\n")...), 0o644)
|
||||
f := NewFollower(p, Pos{})
|
||||
f.MaxLine = 100
|
||||
over := 0
|
||||
f.Oversize = func() { over++ }
|
||||
got := collectAt(f)
|
||||
f.step()
|
||||
if over != 1 || len(*got) != 2 || (*got)[1].text != "next" || (*got)[1].end.Offset != 3+301+5 {
|
||||
t.Fatalf("over=%d got=%v", over, *got)
|
||||
}
|
||||
}
|
||||
+15
-6
@@ -48,11 +48,14 @@ func headMatches(fh *os.File, fp uint64, fpLen int) bool {
|
||||
|
||||
// Follower reads complete lines from Path as they appear.
|
||||
type Follower struct {
|
||||
Path string
|
||||
MaxLine int // lines longer than this are skipped and reported
|
||||
Poll time.Duration // default 500ms
|
||||
Handle func(line []byte) // must not retain line
|
||||
Oversize func() // called once per skipped oversized line
|
||||
Path string
|
||||
MaxLine int // lines longer than this are skipped and reported
|
||||
Poll time.Duration // default 500ms
|
||||
Handle func(line []byte) // must not retain line
|
||||
// HandleAt, when set, is called instead of Handle with the position right
|
||||
// after the line (newline included).
|
||||
HandleAt func(line []byte, end Pos)
|
||||
Oversize func() // called once per skipped oversized line
|
||||
// Mu, when set, is held while Handle runs and the position advances, so a
|
||||
// snapshot taking the same mutex sees state and offsets in agreement.
|
||||
Mu *sync.Mutex
|
||||
@@ -140,7 +143,13 @@ func (f *Follower) emit(line []byte, consumed int) {
|
||||
f.Mu.Lock()
|
||||
}
|
||||
if line != nil {
|
||||
f.Handle(line)
|
||||
if f.HandleAt != nil {
|
||||
end := f.Pos()
|
||||
end.Offset += int64(consumed)
|
||||
f.HandleAt(line, end)
|
||||
} else {
|
||||
f.Handle(line)
|
||||
}
|
||||
}
|
||||
f.mu.Lock()
|
||||
f.pos.Offset += int64(consumed)
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
package wire
|
||||
|
||||
import (
|
||||
"net/netip"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
|
||||
)
|
||||
|
||||
func TestValidCmdLineAgainstRealFormatters(t *testing.T) {
|
||||
now := time.Date(2026, 11, 15, 10, 20, 30, 0, time.UTC)
|
||||
for _, ip := range []string{"203.0.113.9", "2001:db8::1", "::ffff:198.51.100.7"} {
|
||||
a := netip.MustParseAddr(ip)
|
||||
for _, src := range []string{"local", "peer:oracle", "x y!"} {
|
||||
line, err := enforce.FormatLine(now, a, enforce.ReasonRCE, 87, 90*time.Minute, "host-1", src)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !ValidCmdLine(CmdDecision, line) {
|
||||
t.Errorf("FormatLine output rejected: %q", line)
|
||||
}
|
||||
if ValidCmdLine(CmdUnban, line) {
|
||||
t.Errorf("decision accepted as unban: %q", line)
|
||||
}
|
||||
}
|
||||
u := enforce.UnbanLine(now, a, 3600)
|
||||
if !ValidCmdLine(CmdUnban, u) {
|
||||
t.Errorf("UnbanLine output rejected: %q", u)
|
||||
}
|
||||
if ValidCmdLine(CmdDecision, u) {
|
||||
t.Errorf("unban accepted as decision: %q", u)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidCmdLineRejects(t *testing.T) {
|
||||
good := "2026-11-15T10:20:30Z urutau decision=ban ip=203.0.113.9 reason=scanner score=87 ttl=300 host=h src=local\n"
|
||||
if !ValidCmdLine(CmdDecision, good) {
|
||||
t.Fatal("baseline rejected")
|
||||
}
|
||||
bad := []string{
|
||||
strings.TrimSuffix(good, "\n"), // no newline
|
||||
good + good, // two lines
|
||||
strings.Replace(good, "ip=203.0.113.9", "ip=999.1.1.1", 1),
|
||||
strings.Replace(good, "ban", "ban;rm", 1),
|
||||
strings.Replace(good, "src=local", "src=local\nINJECT", 1),
|
||||
strings.Replace(good, "reason=scanner", "reason=a b", 1),
|
||||
strings.Repeat("x", MaxCmdLine+1),
|
||||
"",
|
||||
}
|
||||
for _, l := range bad {
|
||||
if ValidCmdLine(CmdDecision, l) {
|
||||
t.Errorf("accepted %q", l)
|
||||
}
|
||||
}
|
||||
if ValidCmdLine("other", good) {
|
||||
t.Error("unknown kind accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckHubURL(t *testing.T) {
|
||||
ok := []string{"https://hub.example.com", "https://hub.example.com/", "http://127.0.0.1:8790", "http://10.1.2.3:8790", "http://192.168.0.5", "http://urutau:8790", "http://localhost:8790", "http://[::1]:8790"}
|
||||
for _, u := range ok {
|
||||
if _, err := CheckHubURL(u); err != nil {
|
||||
t.Errorf("%s rejected: %v", u, err)
|
||||
}
|
||||
}
|
||||
bad := []string{"", "hub.example.com", "http://hub.example.com", "http://8.8.8.8", "ftp://hub", "https://user:pw@hub.example.com", "https://hub.example.com?x=1", "https://", "http://172.32.0.1"}
|
||||
for _, u := range bad {
|
||||
if _, err := CheckHubURL(u); err == nil {
|
||||
t.Errorf("%s accepted", u)
|
||||
}
|
||||
}
|
||||
u, _ := CheckHubURL("https://hub.example.com///")
|
||||
if u.String() != "https://hub.example.com" {
|
||||
t.Errorf("trailing slashes kept: %s", u)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidName(t *testing.T) {
|
||||
for _, s := range []string{"oracle", "a", "host-1", "0abc", strings.Repeat("a", 32)} {
|
||||
if !ValidName(s) {
|
||||
t.Errorf("%q rejected", s)
|
||||
}
|
||||
}
|
||||
for _, s := range []string{"", "-a", "A", "a_b", "a.b", "a/b", "../x", strings.Repeat("a", 33), "a b"} {
|
||||
if ValidName(s) {
|
||||
t.Errorf("%q accepted", s)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidSource(t *testing.T) {
|
||||
for _, s := range Sources {
|
||||
if !ValidSource(s) {
|
||||
t.Errorf("%s", s)
|
||||
}
|
||||
}
|
||||
if ValidSource("nope") || ValidSource("") {
|
||||
t.Error("invalid accepted")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user