CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 27s
CI / Dependency audit (push) Successful in 18s
CI / Tests (Linux, race detector) (push) Successful in 58s
Release / Plan (reuse the published image?) (push) Successful in 4s
Release / ci (push) Skipped
Release / Build image (amd64) (push) Skipped
Release / Build image (arm64) (push) Skipped
Release / Publish tags (push) Successful in 13s
Release / Gitea release (push) Successful in 5s
Intelligence: attack families mapped to MITRE ATT&CK, network type from
ASN/rDNS without external APIs, request cadence, sessions with
recon/probe/exploit/access/banned stages, campaigns across IPs, verdict
with reasons, recommended actions, exposure detection (2xx with a body
on sensitive paths), STIX 2.1 export, FCrDNS for search engine bots,
optional Tor exit list.
Data: 30-day retention, twelve ranges plus custom from/to, an on-disk
event log (daily files, hourly gzip members, size cap, corruption and
disk-full tolerant), /events, /period, /metrics with stable per-hour
metrics, an extended /ip/{ip}, and peer /period merged on the hub.
Interface: layout system with fixed card sizes, range picker in the
URL, IP analysis page, Replay page, Geography down to state and city
(Natural Earth admin-1), Live page redesigned with stable metrics and a
reusable attack map. Demo data and documentation screenshots.
Security: bounded and deadline-limited period computations, linear
campaign clustering, singleflight caches, sanitized peer studies, event
query budgets, gzip bomb guard.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
435 lines
16 KiB
Go
435 lines
16 KiB
Go
// 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/fed"
|
|
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
|
)
|
|
|
|
// Config is the runtime configuration of `urutau serve` and `urutau doctor`.
|
|
type Config struct {
|
|
Bind string
|
|
Name string
|
|
DataDir string
|
|
TraefikLog string
|
|
AuthLog string
|
|
Fail2banLog 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)
|
|
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)
|
|
GeoUpdate time.Duration
|
|
Peers []string
|
|
PeerToken string
|
|
Location string // "lat,lon" or "lat,lon,label" (--location)
|
|
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
|
|
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
|
|
}
|
|
|
|
// 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
|
|
}
|
|
|
|
// 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()
|
|
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.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)")
|
|
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 <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.DurationVar(&c.Retention, "retention", store.DefaultRetention, "how long data is kept, at most 720h (URUTAU_RETENTION)")
|
|
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.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.Peers = peers
|
|
c.Ignore, c.Trusted = ign.val, trusted.val
|
|
c.PeerAllow, c.TrustedProxy = allow.val, 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")
|
|
}
|
|
if c.Name == "" {
|
|
c.Name = "urutau"
|
|
}
|
|
return c, nil
|
|
}
|
|
|
|
// Validate checks the configuration and returns the parsed peers.
|
|
func (c Config) Validate(token string) ([]fed.Peer, error) {
|
|
if _, err := store.ParseLocation(c.Location); err != nil {
|
|
return nil, err
|
|
}
|
|
if v := strings.ToLower(c.PeerBlocklist); v != "" && v != "on" && v != "off" {
|
|
return nil, fmt.Errorf("--peer-blocklist must be on or off")
|
|
}
|
|
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)
|
|
}
|
|
if _, err := core.ParseCIDRs(c.Ignore + "," + c.Trusted); err != nil {
|
|
return nil, 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)
|
|
}
|
|
}
|
|
if c.Retention < time.Hour || c.Retention > store.DefaultRetention {
|
|
return nil, 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)
|
|
}
|
|
}
|
|
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)
|
|
}
|
|
} else if err := checkToken("URUTAU_TOKEN", token); err != nil {
|
|
return nil, 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}} {
|
|
if _, err := core.ParseCIDRs(l.v); err != nil {
|
|
return nil, fmt.Errorf("%s: %w", l.name, err)
|
|
}
|
|
}
|
|
return peers, 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
|
|
}
|
|
|
|
// 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
|
|
for _, u := range strings.Split(c.AdminUsers, ",") {
|
|
if u = strings.TrimSpace(u); u != "" {
|
|
out = append(out, u)
|
|
}
|
|
}
|
|
return out
|
|
}
|