// Package app wires the sources, the store, the federation hub and the server. package app import ( "flag" "fmt" "math" "net" "os" "path/filepath" "regexp" "strconv" "strings" "time" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" "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 // 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 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 /geo) GeoUpdate time.Duration Location string // "lat,lon" or "lat,lon,label" (--location): default location of the primary probe PeerBlocklist string // "on" (default) or "off" 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 TorExits string // file with Tor exit addresses, one per line; empty disables the check EventsMax string // size cap of the event registry ("512MB", "0" disables it) NoAuth bool // Second firewall (see internal/enforce). Enforce string // off (default), observe or on 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 (tests only) EgressWorkloads string // "name=CIDR|name:[,...][:role];..." EgressResolvers string // DNS resolvers allowed (empty: the usual public ones) EgressContainers string // " " map (tests only) EgressAllow string // URUTAU_EGRESS_ALLOW: default for the primary probe } // DefaultEventsMax is the default size cap of the event registry. const DefaultEventsMax = "512MB" // ParseSize reads "512MB", "1GiB", "2g", "1048576" (bytes) into bytes. func ParseSize(v string) (int64, error) { v = strings.TrimSpace(strings.ToLower(v)) if v == "" { return 0, fmt.Errorf("empty size") } mult := int64(1) for _, u := range []struct { suf string m int64 }{{"gib", 1 << 30}, {"mib", 1 << 20}, {"kib", 1 << 10}, {"gb", 1 << 30}, {"mb", 1 << 20}, {"kb", 1 << 10}, {"g", 1 << 30}, {"m", 1 << 20}, {"k", 1 << 10}, {"b", 1}} { if strings.HasSuffix(v, u.suf) { mult, v = u.m, strings.TrimSpace(strings.TrimSuffix(v, u.suf)) break } } n, err := strconv.ParseFloat(v, 64) if err != nil || n < 0 || n > 1<<40 { return 0, fmt.Errorf("invalid size %q", v) } return int64(n * float64(mult)), nil } type listFlag []string func (l *listFlag) String() string { return strings.Join(*l, ",") } func (l *listFlag) Set(v string) error { *l = append(*l, v); return nil } func env(key, def string) string { if v, ok := os.LookupEnv(key); ok { return v } return def } func envInt(key string, def int) int { if v, ok := os.LookupEnv(key); ok { if n, err := strconv.Atoi(strings.TrimSpace(v)); err == nil { return n } } return def } // csvFlag accumulates comma separated values; the first use replaces the default. type csvFlag struct { val string used bool } func (c *csvFlag) String() string { return c.val } func (c *csvFlag) Set(v string) error { if !c.used { c.val, c.used = v, true } else { c.val += "," + v } return nil } // DefaultMonitorUA matches the usual uptime and health monitors. const DefaultMonitorUA = `(?i)^(Uptime-Kuma/|Beszel|Coolify|kube-probe/|Go-http-client/.*healthcheck)` // DefaultTrustedProxy is loopback only: any other proxy (Traefik on a Docker // network) must be named explicitly, so another container on a shared network // cannot forge X-Forwarded-For. const DefaultTrustedProxy = "127.0.0.0/8,::1" // MinTokenLen is the minimum length of URUTAU_TOKEN and URUTAU_PEER_TOKEN. const MinTokenLen = 32 // DefaultIgnore are the networks whose events are dropped by default. const DefaultIgnore = "127.0.0.0/8,::1,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,fc00::/7,fe80::/10,100.64.0.0/10,169.254.0.0/16" // ParseFlags reads flags (each with a URUTAU_* environment default). func ParseFlags(name string, args []string) (Config, error) { fs := flag.NewFlagSet(name, flag.ContinueOnError) var c Config host, _ := os.Hostname() 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)") 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)") fs.Var(trusted, "trusted", "trusted origins (your own servers) whose events are dropped, same as --ignore (URUTAU_TRUSTED)") mfrom := &csvFlag{val: env("URUTAU_MONITOR_FROM", "")} doms := &csvFlag{val: env("URUTAU_DOMAINS", "")} admins := &csvFlag{val: env("URUTAU_ADMIN_USERS", "")} fs.Var(admins, "admin-users", "SSH users whose successful logins keep their IP out of the blocklist for 24 h; empty means nobody is immune (URUTAU_ADMIN_USERS)") fs.Var(mfrom, "monitor-from", "networks the monitoring User-Agents come from; empty trusts the User-Agent alone for benign hits (URUTAU_MONITOR_FROM)") fs.Var(doms, "domains", "analytics domain allowlist, exact names or *.example.com; empty tracks every domain that answers 2xx/3xx (URUTAU_DOMAINS)") fs.StringVar(&c.GeoDir, "geo-dir", env("URUTAU_GEO_DIR", ""), "geo database directory, default /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)") tproxy := &csvFlag{val: env("URUTAU_TRUSTED_PROXY", DefaultTrustedProxy)} 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, "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 /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 /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 (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)") c.EgressAllow = env("URUTAU_EGRESS_ALLOW", "") fs.StringVar(&c.EgressWorkloads, "egress-workloads", env("URUTAU_EGRESS_WORKLOADS", ""), "default workloads of the primary probe: \"ciberlab=name::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.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 != "" { if d, err := time.ParseDuration(v); err == nil { c.GeoUpdate = d } } if v := os.Getenv("URUTAU_RETENTION"); v != "" { if d, err := time.ParseDuration(v); err == nil { c.Retention = d } } if err := fs.Parse(args); err != nil { return c, err } c.Ignore, c.Trusted = ign.val, trusted.val c.TrustedProxy = tproxy.val c.MonitorFrom, c.Domains, c.AdminUsers = mfrom.val, doms.val, admins.val if c.GeoDir == "" { c.GeoDir = filepath.Join(c.DataDir, "geo") } if c.Name == "" { c.Name = "urutau" } return c, nil } // Validate checks the configuration. func (c Config) Validate(token string) error { if _, err := store.ParseLocation(c.Location); err != nil { 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 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 fmt.Errorf("--enforce must be off, observe or on") } if v := strings.ToLower(c.EnforceShare); v != "" && v != "off" && v != "on" { return fmt.Errorf("--enforce-share must be on or off") } if c.EnforceThreshold < 1 || c.EnforceThreshold > 1000 { return fmt.Errorf("--enforce-threshold must be between 1 and 1000") } if c.EnforceMaxPerMin < 1 || c.EnforceMaxPerMin > 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 fmt.Errorf("--egress must be auto, on or off") } if _, err := core.ParseCIDRs(c.Ignore + "," + c.Trusted); err != nil { return fmt.Errorf("--ignore/--trusted: %w", err) } if c.MonitorUA != "" { if _, err := regexp.Compile(c.MonitorUA); err != nil { return fmt.Errorf("--monitor-ua: %w", err) } } if c.Retention < time.Hour || c.Retention > store.DefaultRetention { return fmt.Errorf("--retention must be between 1h and 720h") } if c.EventsMax != "" { if _, err := ParseSize(c.EventsMax); err != nil { return fmt.Errorf("--events-max: %w", err) } } if c.NoAuth { if !loopbackBind(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 err } for _, l := range []struct{ name, v string }{{"--trusted-proxy", c.TrustedProxy}, {"--monitor-from", c.MonitorFrom}} { if _, err := core.ParseCIDRs(l.v); err != nil { return fmt.Errorf("%s: %w", l.name, err) } } 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_[_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 { host, _, err := net.SplitHostPort(bind) if err != nil || host == "" { return false } if host == "localhost" { return true } ip := net.ParseIP(host) return ip != nil && ip.IsLoopback() } // checkToken enforces a minimum quality on secrets: long, with enough // estimated entropy, not periodic ("abcd...abcd") and not a plain run // ("0123456789..."). Random hex or base64 output always passes. func checkToken(name, t string) error { const hint = " (generate one with: openssl rand -base64 48)" if len(t) < MinTokenLen { return fmt.Errorf("%s must have at least %d characters%s", name, MinTokenLen, hint) } if tokenEntropyBits(t) < MinTokenBits { return fmt.Errorf("%s is too predictable: estimated entropy below %d bits%s", name, MinTokenBits, hint) } if periodic(t) || sequential(t) { return fmt.Errorf("%s is a repeated or sequential pattern%s", name, hint) } return nil } // MinTokenBits is the minimum estimated entropy of a token. const MinTokenBits = 128 // tokenEntropyBits estimates entropy as length times the Shannon entropy of // the token's own character distribution. 64 hex characters give ~250 bits; // "aaaa..." gives 0. func tokenEntropyBits(t string) float64 { freq := map[rune]int{} n := 0 for _, r := range t { freq[r]++ n++ } h := 0.0 for _, c := range freq { p := float64(c) / float64(n) h -= p * math.Log2(p) } return h * float64(n) } // periodic reports whether t is a block repeated (the last copy may be cut). func periodic(t string) bool { for p := 1; p <= len(t)/2; p++ { ok := true for i := p; i < len(t); i++ { if t[i] != t[i-p] { ok = false break } } if ok { return true } } return false } // sequential reports whether most consecutive bytes differ by +1 or -1 // ("0123456789abcdef...", "zyxw..."). func sequential(t string) bool { run := 0 for i := 1; i < len(t); i++ { if d := int(t[i]) - int(t[i-1]); d == 1 || d == -1 { run++ } } return run*4 >= (len(t)-1)*3 } func contains(l []string, v string) bool { for _, x := range l { if x == v { return true } } return false } // Secret reads NAME, or the file named by NAME_FILE (whitespace trimmed). func Secret(name string) (string, error) { if v := os.Getenv(name); v != "" { return v, nil } if f := os.Getenv(name + "_FILE"); f != "" { b, err := os.ReadFile(f) if err != nil { return "", fmt.Errorf("%s_FILE: %w", name, err) } return strings.TrimSpace(string(b)), nil } return "", nil } // AdminUserList splits --admin-users into names. func (c Config) AdminUserList() []string { var out []string for _, u := range strings.Split(c.AdminUsers, ",") { if u = strings.TrimSpace(u); u != "" { out = append(out, u) } } return out }