# 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//`, 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|[,]` 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
`/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 `/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 `/enforce.json`.
Unban: `POST /api/v1/enforce/unban` appends `