Files
urutau/docs/architecture.md
T
2026-11-23 09:09:54 -03:00

359 lines
38 KiB
Markdown

<p align="center"><a href="../README.md">◂ Back to README</a></p>
# Architecture
Urutau is one Go binary with no third-party dependency. It runs in two roles: the **hub**, which holds the data and serves the dashboard and the API, and the **probe**, a tiny process on each monitored server that only reads log files and sends them to the hub. The same binary does both (`urutau serve` and `urutau probe`); a separate scratch image carries the probe.
```
cmd/urutau entry point: serve (hub), probe, probes, import, doctor, healthcheck, version
internal/app flags, wiring, the log runner (fed by the probes), probe-log parser, Tor lists, enforce and egress wiring, import, doctor
internal/tail rotation-aware file follower and rotated-file reader
internal/core event model, parsers (Traefik JSON and text, sshd, fail2ban), classifier, error classes
internal/store in-memory state, summaries, merge, snapshot, analytics, services, defense, roster
internal/rdns reverse DNS cache and forward-confirmed reverse DNS
internal/evlog on-disk event registry
internal/intel families, MITRE, network type, cadence, sessions, campaigns, verdicts, STIX, metrics
internal/geo dependency-free MMDB reader and database updater (DB-IP Lite)
internal/ua User-Agent parser (browser, system, device, bot, attack tool)
internal/enforce second firewall: ban decisions, decision file, unban requests, operator allowances
internal/egress outbound connection analysis: workloads, findings (beacon, C2, mining, scan...)
internal/incidents tickets opened from egress findings or by hand, stored in incidents.json
internal/hub one node per probe: ingestion, commands queue, probe registry (probes.json)
internal/wire probe-hub protocol: messages, limits, command-line validation
internal/probeagent the probe: tailers, spool, client, command application
internal/fed in-process aggregation of the nodes (summaries, IP tables, live, study, geography)
internal/server HTTP handler, auth, API routes, HTML report, embedded dashboard (web/)
deploy/host host kit: nftables table, rsyslog, logrotate, container map, fail2ban jail, installer
```
The only dependency is the Go standard library.
## Data flow
```
── on each monitored server: the probe (urutau probe) ──────────────────────
Traefik access.log auth.log fail2ban.log probe.log egress.log
│ │ │ │ │
└──── tail.Follower (one goroutine per source, rotation-aware) ┘
containers.map and resolv.conf: whole file when it changes (sha256)
▼
batch (up to 5000 lines / 1 MiB / 1 s) ──► disk spool ──► HTTPS push
│
── on the hub (urutau serve) ───────────────────────────────────────▼─────
one node per probe (own store, evlog, incidents, enforce, egress)
offset check (inode or end > saved offset) ──► duplicate lines dropped
▼
parse (core.ParseTraefik / ParseAuth / ParseFail2ban / probe parser) → Event
▼
trusted CIDRs? drop. monitoring UA and benign? count aside.
▼
classify (core): category, error class, forge browsing exempt
▼
store.Ingest: counters, per-IP record, live feed ──► evlog (events/)
▼
intel (computed on demand): family, MITRE, network type, cadence, sessions,
campaigns, verdict ──► dashboard, API, STIX, blocklist, HTML report
▼
enforce (optional): decision per attacking IP ──► command queue of the node
▼
probe long-poll receives it, validates the line, appends to decisions.log
▼
host fail2ban jail "urutau" reads decisions.log and bans in the firewall
▼
fail2ban.log "Ban urutau" returns as an event (not counted as evidence)
egress lines ──► egress.Source ──► findings
findings ──► incidents (tickets INC-n, suppression) ──► API and report
```
Snapshot every 60 s: `state` ◄──► summaries, IP table, SSE. Neither the hub nor the probe gains privileges: the probe only appends lines to a file that a jail on the host reads, and only after validating that each line has exactly the shape the hub's ban code produces.
## Sources
Each source is followed by its own goroutine **in the probe** and the hub reports its state: `following`, `waiting` (the file does not exist yet), `backfill` (first start, reading rotated copies), `degraded` (more than 20% of the last 1000 lines are unreadable, with at least 50 samples) or `error`. A line larger than 64 KiB is dropped and counted as malformed. On the first start without a snapshot, the rotated copies (`path.1`, `path.N.gz` up to 9) are read oldest first so the window is not empty.
Lines are decoded as follows:
- **Traefik:** one JSON object per line; the default text format is read too, with fewer fields (no host or service). Client address, host, method, path, status and User-Agent are read; paths and User-Agents are clipped.
- **sshd:** the lines of `auth.log` with ISO timestamps. Failed passwords and keys, invalid users, closed-before-auth connections and `Accepted` logins; negotiation errors, banner exchange failures and protocol mismatches count as probes.
- **probe:** the `URUTAU-PROBE:` lines that the host kit logs for inbound connections to ports nobody listens on (`--probe-log`). Each becomes a `scanner` event with source `probe` (MITRE T1046), at most one per address, port and protocol per minute.
- **ingress, ingresscnt:** the firewall telemetry of the host kit (`--ingress`), described under "Firewall telemetry". They are not event sources: nothing is parsed into an event.
- **fail2ban:** `Ban`, `Unban` and `Restore Ban` lines. A restored ban (replayed after a fail2ban restart) updates the ban state and is not scored.
The egress log (`--egress-log`) has its own source, described in the egress section. Log file paths never leave the probe, and the hub never shows them: the dashboard shows only the name and state of a source. The hub reads no log file at all.
Lines that are valid but carry nothing to record are ignored silently; lines that cannot be parsed are counted as malformed and shown per source in the dashboard.
## Classification and scoring
A web request is classified by its decoded path (percent-decoded up to twice, to defeat double encoding), method and status.
| Category | Meaning | Weight |
|---|---|---|
| `exploit` | traversal, `${jndi:`, script injection, SQL union, shell and file-read probes | 8 |
| `ban` | fail2ban banned the IP | 10 |
| `scanner` | probes for `.env`, `.git`, `wp-config`, phpMyAdmin, backups and archives, plugin scans | 3 |
| `bruteforce` | `xmlrpc.php`, failed `wp-login.php`, `POST` answered with 401 | 2 |
| `ssh-fail` | failed sshd authentication | 2 |
| `ssh-probe` | sshd negotiation or banner probing | 1 |
| `notfound` | other 4xx answers | 0.2 |
| `ok`, `ssh-ok` | benign traffic and successful logins | 0 |
An IP's score is the sum of the weights of its events in the retained window. A `scanner` or `exploit` request that the server answered with 2xx or 3xx (the probe probably found nothing, or the page is public) weighs only 0.5. Unbans and restored bans add nothing.
The level combines the score with evidence:
- **Suspicious:** a score of 10 or more.
- **Hostile:** a score of 50 or more **and** a strong signal: a known attack tool in the User-Agent, two or more attack categories, a fail2ban ban, or a clear exploit attempt that was refused (4xx or 5xx). A big score made only of weak signals (a crawler that hits many 404s) stays suspicious.
- **Never hostile:** an IP with a successful SSH login (`ssh-ok`), which is most likely you.
- Otherwise **low**.
Pages of a code forge that show repository content (Gitea or Forgejo `/owner/repo/src/commit/<sha>/<file>`, GitHub and GitLab `blob`, `tree`, `raw`, `blame`, `commits`) are not probes even when the file is called `.env` or `.gitignore`; `/.env`, `/.git/config` and traversal are unchanged. A fail2ban ban made by the `urutau` jail (our own decision) or by `recidive` (which only repeats bans) is not evidence: it adds no score, no strong signal and no blocklist listing. Bans of independent jails (sshd, traefik) count.
IPv6 clients are tracked by their /64 prefix, since one subscriber holds a whole /64 and per-address keys would let one attacker flood the table. IPs are tracked up to 20,000 entries.
The malicious categories (`scanner`, `exploit`, `bruteforce`, `ssh-fail`, `ssh-probe`) feed the "malicious" totals.
## Noise filtering
Events from a trusted origin (`--trusted`, plus the private ranges of `--ignore`) are dropped before anything is recorded. A request whose User-Agent matches `--monitor-ua` and that is benign is counted in a separate "monitoring" counter and does not enter the traffic, the score or the lists. With `--monitor-from` the User-Agent only counts from those networks; without it only `ok` answers are filtered. If the request classifies as `scanner`, `exploit` or `bruteforce` it is a normal attack, since a User-Agent can be forged.
## Geolocation and User-Agents
`internal/geo` is a dependency-free MMDB reader. It opens the DB-IP Lite city and ASN databases, answers country, city and ASN for any public IP (private and loopback addresses return nothing) behind a small cache, and swaps a newer file in without a restart. Its updater downloads the files from `download.db-ip.com` when they are missing or older than 35 days, then checks on the `--geo-update` interval, verifying each file by opening it before it replaces the old one. `internal/ua` parses a User-Agent into browser, operating system, device class, bot (search engines, crawlers) or attack tool (scanners and exploit kits). Data by [DB-IP](https://db-ip.com), CC BY 4.0.
## Web analytics
Benign requests (`ok`, and the `notfound` that are not scanning) also feed the Traffic page. A domain only gets a slot after a 2xx answer (and `--domains` can restrict them to an allowlist), inactive domains are pruned, and top pages normalize token-looking path segments to `:id`: unique visitors, pages, referrers, countries, browsers, operating systems, devices, latency (p50 and p95) and bytes. A unique visitor is a hash computed with a salt that rotates daily, so it cannot be followed across days, and the IP address of a legitimate visitor is never persisted. Attack traffic stays in the Threats view, where the IP is the subject. Monitoring requests are kept out of both.
## Periods and granularity
Every view takes a range: one of twelve named windows (`1h`, `2h`, `3h`, `6h`, `12h`, `24h`, `2d`, `3d`, `5d`, `7d`, `15d`, `30d`) or a custom period with `from` and `to` (unix seconds, at most 30 days, clipped to the retention; `clipped` says when it was). An invalid range answers 400. Responses carry `range` as an object `{name,from,to,step,clipped}`, where `step` is the timeline granularity in seconds: 60 up to 3 hours, 120 up to 6, 300 up to 12, 900 up to 48 hours and 3600 beyond. Minute buckets exist for the latest 48 hours; older data is hourly.
## Error classes and Traefik fields
Besides the client, path, status and User-Agent, Urutau reads these Traefik access log fields when they are present: `OriginStatus`, `OriginDuration`, `Overhead`, `OriginContentSize`, `RetryAttempts`, `RouterName`, `ServiceName`, `RequestProtocol`, `RequestScheme`, `TLSVersion` and `TLSCipher`. With them every error is classified:
| Class | Meaning |
|---|---|
| `app` | the backend itself answered 5xx |
| `proxy` | the proxy could not reach the backend, or the client gave up |
| `blocked` | refused by a middleware or a rate limit before the app |
| `attack` | the request is an attack (see the categories above) |
| `bot` | a crawler or tool |
| `client` | an ordinary client mistake (broken link, authentication, bad input) |
| `unknown` | none of the above could be told |
## Services, SLO and Apdex
Requests are grouped per Traefik service (`ServiceName`, with its router). For each service Urutau keeps hourly counters by error class and latency histograms, and shows: the **SLI** (share of requests that did not end in an error that counts against the service), the **SLO** (target 99.5%), the **error budget** left, the **burn rate** over 1 hour and 6 hours (error rate divided by `1 - SLO`; above 1 the budget is being spent faster than allowed) and the **Apdex**. Attacks, blocked requests and bots do not count against a service. Apdex uses a threshold T of 500 ms (1 s for API paths): a request answered within T is satisfied, within 4T tolerating, and a 5xx or a slower one is frustrated; Apdex is (satisfied + tolerating/2) / total.
## Episodes and survival
An attack **episode** is the run of activity of one address, closed after a quiet gap. From episodes Urutau measures the time from the first sighting to the ban and draws **Kaplan-Meier** survival curves (the probability that an address is still not banned after a given time, with addresses never banned counted as censored), with the median and the 90th percentile.
## Unique visitors
A **visitor** is a person with a real browser: a successful (2xx) GET of a document by a browser User-Agent (not a bot, tool or unknown client), not a prefetch and, when the browser says so, with `Sec-Fetch-Dest: document`. It is counted once per IP per UTC day, deduplicated globally across domains (a per-domain figure and an all-domains total). The key is a hash of a daily salt, the IP and the domain, and leaves the User-Agent out on purpose, because scrapers rotate it per request from one address (a measured 2.7x inflation). Everything else that talks to a site (bots, tools, unknown or empty User-Agents) is counted apart as **non-human clients**.
This is why the number differs from Coolify's analytics, which counts every distinct IP through HyperLogLog with no filter: bots, scanners and health checks inflate it. Urutau's figure is lower and closer to people.
## Legitimate visits stream
`GET /api/v1/events/stream?visits=1` adds anonymous visit events to the live stream. A visit carries no address, User-Agent or referrer; its place is the city, with coordinates rounded to one decimal (about 11 km). At most 20 visit events per second per instance are sent (the excess is summarised once a second as a batch), and visits are only broadcast to subscribers: never written to the event log, a snapshot or `live/recent`.
## Firewall telemetry
`internal/ingress` aggregates what the application logs cannot see: new inbound attempts to the host, including ports where nothing listens and packets from banned addresses that the firewall drops without a log line. The host kit table `urutau_ingress` observes at prerouting priority -150 (before Docker's DNAT) and only counts and logs. The probe tails two files as the wire sources `ingresscnt` (`ingress.counters`: `ts=... total=... tcp=... udp=... icmp=... open=...`, cumulative, one line a minute) and `ingress` (`ingress.log`, the sampled `URUTAU-IN:` and `URUTAU-INO:` kernel lines); it imports nothing of the hub and stays tiny. In the hub each node keeps an `ingress.Agg`: the delta of two counter lines is added to the hourly bucket of its timestamp (a decrease is a table reload and restarts from zero; a delta above 2^40, a timestamp more than an hour ahead or older than 30 days is dropped as malformed), and each sampled line adds to the bucket's logged count, top destination ports, top origin ASNs and countries (hub geo) and to the banned count when the store reports a jail ban on the source at that moment. Every field is length-limited when parsed (log lines over 2 KB and counter lines over 256 bytes are refused, sources must be public unicast, TCP needs SYN without ACK). Buckets are hourly for 30 days, each with top lists capped at 48 ports, 48 networks and 64 countries, saved to `ingress.json` once a minute when changed.
The aggregate is deliberately isolated: it receives the store's ban state and geo as two functions and has no way to emit an event, a score or a decision, so attempts from a banned address are never new evidence (no ban feedback loop with the second firewall, the `port-scan` family included). `GET /api/v1/ingress?range=24h&host=all|<name>[,<name>]` returns `{hosts, enabled, from, to, source{state,last_counters,last_line,lines,counter_lines,malformed}, totals{attempts,tcp,udp,icmp,open,closed,closed_pct,per_hour}, sample{logged,logged_banned,ratio,banned_pct,banned_est}, hourly[{t,total,open,closed,logged}], ports[{proto,port,n,served,pct}], asns[{asn,org,n,pct}], countries[{cc,n,pct}]}`. `totals` is exact; `sample`, `ports`, `asns` and `countries` come from the sample, and `ratio` is `logged / attempts`. `urutau doctor` checks that the last counters line of each host is under 5 minutes old.
## Event registry
`<data-dir>/events/` holds one JSON line per event, in the same format as the live stream, one file per UTC day. The current day is appended to and synced every 2 seconds; older days are gzip compressed. Files older than the retention are deleted, and the total is capped by `--events-max` (512 MB by default, `0` disables the registry). A day holds at most 200,000 lines; beyond that, events are only counted.
What enters: malicious events (scanner, exploit, bruteforce, ssh-fail, ssh-probe), ban and unban, successful SSH logins, a 404 answered to an attack tool, and `ok` or `notfound` answers only for addresses that are already suspicious or hostile (to show what they got). Never a legitimate visitor. Each event is registered with the name of the probe that sent it as host.
Failure behavior: a full disk, the size cap or the day cap drop events (counted, logged at most once in a while, never fatal); a corrupted line is skipped when reading; a partial line left by an earlier failure is terminated before the next write.
## Intelligence
The investigation layer is computed from the IP table and the registry, with no external API:
- **Attack families** (`traversal`, `log4shell`, `sqli`, `xss`, `rce-injection`, `webshell`, `env-credentials`, `vcs`, `backup`, `wordpress`, `phpmyadmin-db`, `actuator-debug`, `iot-cgi`, `admin-panel`, `generic-404`) and the **MITRE ATT&CK** techniques they map to.
- **Network type** from the ASN, the AS organisation and reverse DNS: `vpn`, `research-scanner`, `isp-cn`, `hosting`, `mobile`, `isp/mobile`, `residential`, `unknown`, and `tor` when the address is in the `--tor-exits` file (reloaded every 24 hours when it changes) or in the official lists that `--tor-auto` (on by default) downloads every 6 hours into `<data-dir>/tor`.
- **Cadence** of the requests of one IP: `automated`, `human-like`, `mixed` or `insufficient` (fewer than 3 requests).
- **Sessions:** bursts of one IP separated by a gap (30 minutes by default), each with a stage in increasing severity: `recon`, `probe`, `exploit`, `access`, `banned`.
- **Campaigns:** at least 3 IPs whose sessions have the same signature (similar normalized paths, Jaccard 0.6 or more, same tool) within a window; the signature id is `c-` plus 8 hex characters.
- **Exposure:** a 2xx answer to a request on a sensitive path.
- **Verdict with reasons**, each reason a stable code with a weight (`exploits_refused`, `tool_ua`, `banned_jail`, `multi_category`, `exposure`, `ssh_login_after_bruteforce`, `admin`, `immune`), and **recommended actions** (`block`, `report`, `investigate`, `incident`); administrators and immune sources get none.
- **STIX 2.1** export of an IP (`/api/v1/ip/{ip}/stix`), with deterministic UUIDv5 ids.
- **Crawlers:** a User-Agent claiming Googlebot (and its variants such as GoogleOther), Bingbot or Applebot is confirmed by forward-confirmed reverse DNS (`googlebot.com`, `google.com`, `search.msn.com`, `applebot.apple.com`); a fake one stays an attacker, and a confirmed crawler is excluded from bans whatever its User-Agent says.
- SSH users listed in `--admin-users` are marked as administrators.
## Metrics
`GET /api/v1/metrics` returns stable figures (no per-minute rates), each with its value, the previous value and a sparkline where it applies:
| Metric | Formula |
|---|---|
| `attacks_per_hour_24h` | malicious events in the last 24 h / 24 |
| `moving_avg_7d_per_hour` | malicious events in the last 7 days / 168 |
| `trend` | percent change of malicious events in the range against the previous range of the same length |
| `active_attackers_24h`, `_1h` | attacker IPs seen in the last 24 h, in the last hour |
| `new_attackers` | IPs first seen inside the range (and the previous range) |
| `returning_rate` | IPs seen in the range but first seen before it / all IPs seen in the range, in percent |
| `sessions_per_day` | sessions in the range / days of the range (at least 1) |
| `exposure_rate` | sessions that got a successful answer / sessions, in percent |
| `exploits_refused_pct` | exploit requests answered 4xx or 5xx / exploit requests with a status, in percent |
| `mttb` | median and 90th percentile of the time from first sighting to ban |
| `ban_coverage` | hostile IPs banned / hostile IPs, in percent |
| `blocklist_coverage` | hostile IPs that are protected (on the published blocklist or banned by any jail) / hostile IPs, in percent; `GET /api/v1/defense` also gives `blocklist.attackers`, `covered`, `one_shot` (single-event attackers, impossible to block reactively), `repeat_ips`, `repeat_covered` and `repeat_coverage_pct` |
| `blocklist_leak` | hostile IPs neither banned nor listable (a count) |
| `ssh.fails_24h`, `ssh.users_distinct`, `ssh.ok_after_fail` | SSH failures in 24 h, distinct users tried in 24 h, sessions with a failure and then a successful login |
| `concentration.top10_ips`, `top5_asns` | share of malicious events from the 10 busiest IPs and the 5 busiest ASNs, in percent |
Sessions, exposure, refused exploits and `ok_after_fail` need the event registry and read at most a bounded number of events (`truncated` says when the window was cut).
## Second firewall
`internal/enforce` is optional (`--enforce=off|observe|on`). Urutau decides which attacking addresses deserve a ban and appends one line per decision to `--enforce-log`; the host fail2ban jail `urutau` reads the file and applies the ban. The process gets no privileges. In `observe` mode decisions stay in memory and the interface shows what would be banned.
Rules (the first that matches, per address):
- 2 critical events (traversal, log4shell, sqli, rce, webshell, env, vcs) in 10 minutes.
- SSH: `--enforce-threshold` failures in 10 minutes (default 5); an `ssh-probe` counts half a failure.
- Port scan: 10 distinct ports probed in 10 minutes (reason `port-scan`).
- Web: `--enforce-threshold` attack events in 10 minutes (dominant reason, otherwise `scanner-flood`).
- Neighbor: 3 or more distinct addresses of the same /24 (IPv4) or /64 (IPv6) were banned in the last 24 hours and another address of the prefix attacks (`neighbor-campaign`).
- Known attacker: the verdict is hostile, or suspicious with a score of 100 or more (`known-attacker`).
- Slow attackers: 10 SSH failures or 20 web scan/exploit events in 24 hours; 10 SSH failures or 10 web scan/exploit events in 7 days (the web one only without a legitimate visit).
A sweep every 10 minutes, and after the start-up backfill, applies the same rules to the addresses active in the last 24 hours that nothing blocks yet. At most `--enforce-max-per-min` decisions are written per minute (default 60); the excess is dropped and counted. The advisory TTL grows with the number of earlier bans: 1 h, 6 h, 24 h, 7 d.
Never banned: private and reserved ranges, `--trusted`, the Cloudflare ranges, well known public resolvers, the addresses of the probes and the servers' own addresses, a verified crawler, an address with a legitimate visit in the last 24 hours, and an operator allowance (below). Each skip is counted by reason.
Decision file, one line per ban (`MaxLogBytes` 20 MB, then rotated to `.1`):
```
2026-11-15T10:00:00Z urutau decision=ban ip=203.0.113.9 reason=ssh-bruteforce score=75 ttl=3600 host=web1 src=local
```
Nothing the attacker controls enters the line: the address is re-formatted, the reason must be one of a fixed list of slugs and the host and source names are reduced to `[A-Za-z0-9._-]`. State (bans, allowances, counters) goes to `<data-dir>/enforce.json`.
Unban: `POST /api/v1/enforce/unban` appends `<time> urutau unban ip=<ip> allow=<seconds>` to the unban file (`--enforce-unban-log`, by default `unban.log` next to the decision file); a systemd path unit of the host kit lifts the fail2ban block. With `allow` above zero the engine does not ban the address again for that long (at most 30 days); `DELETE /api/v1/enforce/allow` ends the allowance.
Sharing (`--enforce-share=on`): a decision taken by the node of one probe is also queued for the nodes of the others. Each node applies its own exclusions, accepts only the fixed reason slugs, caps the TTL at 6 hours, and bans on another node's word only an address it also saw attacking in the last 7 days (otherwise the skip is `peer_unconfirmed`).
## Egress analysis
`internal/egress` reads the nftables log of new outbound connections (`--egress=auto|on|off`, `--egress-log`; `auto` turns it on when the file exists). The host kit logs only TCP connection attempts (SYN without ACK) under the prefix `URUTAU-EGRESS:`. The state is in memory: on start the rotated copies and the live file are replayed, which rebuilds the beacon history.
A **workload** is a group of sources (a CIDR, an address, `host` for the host's own traffic, or a container name or prefix from the `containers.map` file the host kit writes) with a role: `default`, `scanner`, `mail` or `resolver` (`--egress-workloads`). The principle: traffic shaped like a scan is suppressed only for `scanner` workloads; everything else is judged the same for all of them.
Findings (`kind`, severity):
| Kind | Meaning |
|---|---|
| `beacon` | regular conversation with one destination: at least 8 connections within 30 minutes with an interval between 10 s and 6 h and a low jitter |
| `infra` | the same pattern toward cloud metadata services, the provider or the servers themselves (informational) |
| `bad_dst` | contact with an address that attacked this server |
| `tor` | connection to a Tor relay |
| `port` | SMTP from a non-mail workload, IRC, mining pool (stratum) or Tor ORPort ports |
| `dns_bypass` | DNS (53) or DoT (853) to a public address that is not an allowed resolver |
| `scan` | fan-out of more than 50 destinations or 100 ports in 10 minutes, outside `scanner` workloads |
| `new_geo` | first contact with a country after the workload's learning time (24 h) |
Destinations of the probes, trusted addresses and the server's own public addresses never raise findings, and regular connections to large CDNs and clouds are low severity unless the destination attacked the server. Limits: 50,000 pairs and destinations, 2,000 findings, 720 hourly buckets. `GET /api/v1/egress` returns the findings, workloads, countries and an hourly timeline; the hub merges the egress report of every node. The egress settings (workloads, resolvers, allowed destinations) are kept per probe on the hub, in `probes.json`.
## Incidents
`internal/incidents` keeps tickets `INC-<n>` in `<data-dir>/incidents.json` (atomic write, 0600; a corrupt file is moved to `.corrupt`). Every egress finding with severity above `info` becomes a ticket keyed by `host|kind|workload|dst|dport|proto`, created by a sync on each merged egress report and every 60 seconds; a resolved ticket reopens when the finding reappears. A ticket has status (`open`, `investigating`, `true_positive`, `false_positive`, `benign`, `resolved`), severity, assignee, up to 10 tags, verdict, comments and a change history. Limits: 5,000 tickets, 200 comments and 500 history entries each. A ticket in `false_positive` or `benign` can suppress exactly its key for 30 days (90 at most); suppressed findings leave `/api/v1/egress` unless `?suppressed=1`. A host with more than 300 active tickets has the excess grouped in one flood ticket. Writes refuse cross-site requests, and every write is logged (id, field, author).
## HTML report
`GET /api/v1/report?format=html` renders one self-contained A4 document (cover, executive summary, recommendations by rule, threats, geography, errors and health, visitors, defense, second firewall and outbound traffic) in the language of `lang`. The text goes through `html/template` and the charts are SVG built from escaped values, so no log text reaches the page unescaped. `format=json` returns the same figures.
## State and persistence
Each node (one per probe) keeps its own state in memory: minute buckets for the latest 48 hours and hourly data up to 30 days, hourly top lists (paths, domains, User-Agents, users), a table of up to 20,000 IPs (when full, the 10% with the lowest score are evicted; banned IPs are kept), a feed of the latest 500 events and the active bans. `--retention` (1h to 720h) bounds how long IPs are kept; old IPs are pruned every 10 minutes.
Every 60 seconds, and on shutdown, each node writes its state to `urutau-state.gob` together with the inode and offset of every source. The primary node (the probe whose name equals `URUTAU_NAME`) uses the data-dir root, exactly the 1.x layout; the others use `<data-dir>/probes/<name>/`. On start the state is restored and the hub tells each probe, in the `hello`, the offsets it has, so a restart of either side never counts a line twice and never loses one. A snapshot is skipped while a backfill runs. An unreadable snapshot is moved to `urutau-state.gob.corrupt` and the service starts empty, reading the logs again (including the rotated copies).
The process sets a soft memory limit of 256 MiB unless `GOMEMLIMIT` is set. The worst case measured is about 54 MiB of heap and a snapshot of about 27 MB.
## Probes and the hub
The probe is a client of the hub: it opens no port. Plain HTTPS, no WebSocket, so any reverse proxy or CDN works (requests are short; the long-poll lasts at most 25 s). Authentication is `Authorization: Bearer urp_...` plus `X-Urutau-Probe: <name>`. The hub keeps only the SHA-256 of each token (`probes.json`) and compares in constant time; a wrong token is a bare 401 under the same attempt limiter as the login. Plain `http://` is accepted only for loopback or private addresses (for example `http://urutau:8790` on the `urutau-edge` network).
| Route | Purpose |
|---|---|
| `POST /api/v1/probe/hello` | start of every session: protocol version in, the offsets the hub holds out (a probe without local state starts from them). 409 on an incompatible version |
| `POST /api/v1/probe/push` | one batch (`seq`, up to 5000 lines, optional gzip, 2 MiB on the wire and 8 MiB inflated, a line of 64 KiB at most) and the probe status. The hub applies the whole batch to the node, then answers `ack = seq`; a repeated `seq` is answered without being applied again. 503 with `Retry-After` while the node loads or its queue is full, 429 for a second concurrent push |
| `GET /api/v1/probe/commands?after=<seq>&wait=<s>` | long-poll (at most 25 s) for ban and unban lines; answers at once when the queue has a command newer than `after` |
**Spool.** Before sending, the probe writes each batch to `<state-dir>/spool/NNNNNNNNNNNN.json` and sends them in order, so a hub outage loses nothing. The spool is capped by `URUTAU_PROBE_SPOOL_MAX` (64 MiB by default); beyond it the oldest batch is deleted and its lines are added to the `dropped` counter of the probe status, which the Sources page shows. `state.json` records the batch sequence, the last command applied and the read position of every source, written atomically after each ack. After an error the probe reconnects with exponential backoff from 1 s to 60 s with a 20% jitter.
**Offsets.** The hub is the authority: it keeps the offset of each source in the snapshot of the node and accepts a line only if its inode differs from the saved one or its end offset is past it. Replaying a spool, or importing a 1.x data directory (`urutau import`), therefore neither duplicates nor skips lines.
**Liveness.** With nothing to send, the probe pushes an empty batch with its status every 15 s; the hub marks it offline after 45 s without a push.
**Commands.** The hub queues up to 10,000 commands per node (`commands.json`); the oldest are dropped and counted. The probe accepts a command only if `wire.ValidCmdLine` passes (the exact format of a ban or unban line, with a valid address, reason slug and TTL), appends it with `O_APPEND` and `fsync`, and records the sequence so that a repeated command is not written twice. An invalid line is counted in `cmd_errors` and never written. A probe whose `URUTAU_ENFORCE_LOG` is empty ignores ban commands and counts the error.
**Footprint.** The probe never calls geolocation, intelligence or the store; its memory target is under 20 MB of RSS, checked by a test, and its image is under 15 MB.
### Aggregation across probes
`internal/fed` joins the nodes in the process (no HTTP any more): the dashboard host selector offers `all` and each probe; summaries, traffic, IP tables, studies and the live feed merge the nodes and every row carries the host it came from. An incident is identified as `host/INC-n` (each node numbers its own); a bare `INC-n` means the primary node.
### Geography aggregation
`GET /api/v1/geo` is computed from the IP table (of every node) joined with the geolocation databases: countries first, then, for one country, its regions, cities and top IPs. Results are cached for 5 seconds, in a cache of at most 256 keys.
## HTTP layer
The server sets read, write and idle timeouts, `MaxHeaderBytes` of 16 KB, caps `POST /login` at 4 KB and accepts at most 20 simultaneous live-stream (SSE) clients (the 21st gets 503 with `Retry-After`; each stream sends a heartbeat every 20 s). The handler uses the standard `net/http` mux. Every response carries a strict Content-Security-Policy (`default-src 'self'`), `X-Content-Type-Options`, `X-Frame-Options: DENY`, `Referrer-Policy: same-origin`, `Permissions-Policy`, cross-origin isolation headers and, over HTTPS, HSTS. API answers are `Cache-Control: no-store`. The dashboard files are embedded in the binary. See [interface.md](interface.md) for the pages and [configuration.md](configuration.md) for the settings.
## API routes
The user routes under `/api/v1/*` need `URUTAU_TOKEN` (bearer) or a session cookie; the `/api/v1/probe/*` routes need a probe token and nothing else opens them. The 1.x `/api/v1/peer/*` routes no longer exist (404). Analysis routes live in `internal/server/api_<name>.go` files and register themselves with `registerUserRoute`. Routes that take a range accept `range`, or `from` and `to`.
| Route | Purpose |
|---|---|
| `GET /api/health` | `{"status":"ok"}`, no authentication |
| `GET /login`, `POST /login`, `POST /logout` | session cookie |
| `GET /api/v1/summary` (also `own`: web requests of `--trusted` and `--ignore` origins, counted apart; `totals.trusted`, `totals.internal` and `totals.requests_all` = `requests` + both; `totals.counts.trusted` and `.internal`), `/traffic`, `/ips`, `/ip/{ip}`, `/ip/{ip}/stix` | totals, web analytics, IP table, one address, STIX 2.1 bundle |
| `GET /api/v1/period`, `/period/events`, `/events`, `/events/sessions` | study of a period, event registry search (cursor), sessions |
| `GET /api/v1/events/stream` | live stream over SSE (`?visits=1` adds anonymous visits) |
| `GET /api/v1/live/recent`, `/geo` | latest live events, geography |
| `GET /api/v1/metrics`, `/evolution`, `/concentration`, `/survival`, `/techniques`, `/sessions/funnel` | stable metrics and analytics |
| `GET /api/v1/campaigns`, `/campaigns/{id}` | campaigns |
| `GET /api/v1/services`, `/services/{svc}`, `/errors`, `/protocols` | SLO, error classes, protocols and TLS |
| `GET /api/v1/defense`, `/integrity` | blocklist coverage, bans, sources and data integrity |
| `GET /api/v1/blocklist.txt`, `/blocklist.json` | exportable blocklist (`?family=4\|6`) |
| `GET /api/v1/enforce`, `POST /enforce/unban`, `DELETE /enforce/allow` | second firewall |
| `GET /api/v1/egress` | outbound findings |
| `GET /api/v1/ingress` | firewall telemetry: inbound attempts per host (`range` and `host` as in the other endpoints; the probes of this hub only) |
| `GET /api/v1/incidents`, `/incidents/export.csv`, `/incidents/{id}`, `POST /incidents`, `PATCH /incidents/{id}`, `POST /incidents/{id}/comments` | tickets |
| `GET /api/v1/report` | report as JSON or HTML (`?format=`) |
| `GET /api/v1/probes`, `POST /probes`, `PUT /probes/{name}`, `DELETE /probes/{name}` | probe registry behind the Sources page: list with status, create (the token is shown once), edit location and egress settings, revoke (the data is kept) |
| `POST /api/v1/probe/hello`, `/probe/push`, `GET /probe/commands` | probe protocol, probe token only |
List endpoints (IPs, sessions, campaigns, events of an address) are paginated by the backend; event search pages by cursor.
## Files
| Where | What |
|---|---|
| `<data-dir>/urutau-state.gob` | snapshot of the primary node with the offset of every source (`.corrupt` when unreadable) |
| `<data-dir>/probes/<name>/` | the same layout (snapshot, `events/`, `incidents.json`, `enforce.json`, `commands.json`) for every other probe |
| `<data-dir>/probes.json` | registry of probes: name, SHA-256 of the token, location, egress settings (never the token) |
| `<data-dir>/events/YYYY-MM-DD.jsonl[.gz]` | event registry, one JSON line per event |
| `<data-dir>/geo/` | DB-IP Lite city and ASN databases |
| `<data-dir>/tor/` | cache of the Tor exit and relay lists |
| `<data-dir>/enforce.json` | state of the second firewall |
| `<data-dir>/incidents.json` | tickets |
| `<state-dir>/spool/`, `<state-dir>/state.json` | **on the probe:** pending batches, sequence, read positions, last command |
| `URUTAU_ENFORCE_LOG`, `URUTAU_ENFORCE_UNBAN_LOG` | **on the probe:** decision file read by the host jail and unban requests read by the host |
| `URUTAU_PROBE_LOG`, `URUTAU_EGRESS_LOG`, `URUTAU_INGRESS_LOG`, `URUTAU_INGRESS_COUNTERS`, `URUTAU_EGRESS_CONTAINERS` | **on the probe:** kernel logs and container map written by the host kit in `deploy/host` |