Files
urutau/docs/architecture.md
T
Lucas RayanandClaude Opus 5.5 b4a2c2c9ec
Release / Plan (reuse the published image?) (push) Successful in 4s
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 1m29s
CI / Tests (Linux, race detector) (push) Failing after 1m48s
CI / Dependency audit (push) Successful in 21s
Release / ci (push) Failing after 1m50s
Release / Build image (amd64) (push) Skipped
Release / Build image (arm64) (push) Skipped
Release / Publish tags (push) Skipped
Release / Gitea release (push) Skipped
feat: Urutau 1.0.0, lightweight threat intelligence and web analytics
Always-on Go service (stdlib only) that follows the Traefik JSON access
log, the sshd log and the fail2ban log of a host, classifies attacks,
scores sources, keeps bounded aggregates with snapshots, and serves an
embedded dashboard with live updates, offline geolocation (DB-IP Lite),
privacy-friendly traffic analytics, an exportable blocklist and
token-authenticated federation between instances.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 16:13:34 -03:00

103 lines
8.7 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. Everything runs in one process.
```
cmd/urutau entry point: serve, doctor, version
internal/app flags, wiring, the log runner, doctor
internal/tail rotation-aware file follower and rotated-file reader
internal/core event model, parsers (Traefik, sshd, fail2ban), classifier
internal/store in-memory state, summaries, merge, snapshot
internal/rdns reverse DNS cache
internal/fed hub that polls peers
internal/server HTTP handler, auth, embedded dashboard (web/)
```
## Data flow
```
Traefik access.log auth.log fail2ban.log
│ │ │
└──── tail.Follower (one goroutine per source) ────┐
▼
parse (core.ParseTraefik / ParseAuth / ParseFail2ban) → Event
▼
trusted CIDRs? drop. monitoring UA and benign? count aside.
▼
store.Ingest: counters, per-IP record, live feed
▼
snapshot every 60 s ◄── state ──► summaries / IP table / SSE
```
## Sources
Each source is followed by its own goroutine and reports a state: `following`, `waiting` (the file does not exist yet), `backfill` (first start, reading rotated copies) 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. 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.
- **fail2ban:** `Ban`, `Unban` and `Restore Ban` lines. A restored ban (replayed after a fail2ban restart) updates the ban state and is not scored.
Log file paths are never exposed: neither the dashboard nor a peer export shows where a source reads from, only its name and state.
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**.
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 view. 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.
## State and persistence
The state lives in memory: minute buckets for 7 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 168h) bounds how long IPs are kept; old IPs are pruned every 10 minutes.
Every 60 seconds, and on shutdown, the state is written to `urutau-state.gob` in the data directory together with the inode and offset of every source. On start it is restored and each source resumes exactly where it stopped, so a restart never counts a log twice. 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 160 MiB unless `GOMEMLIMIT` is set.
## Federation
A hub is an ordinary instance started with `--peer name=https://url`, and it needs `URUTAU_PEER_TOKEN`. Every 15 seconds it calls each peer's `GET /api/v1/peer/export?range=...` (for `1h`, `24h` and `7d`) with the peer token and keeps the latest answer. The export is `{"v":1,"summary":...,"traffic":{...}}` with the top 500 IPs and their detail, cached for 5 seconds on the peer. It is the only route the peer token opens. The hub never follows redirects, requires `https` outside loopback, uses a 4 second timeout, caps the body at 8 MB and sanitizes and caps whatever a peer sends. A peer that fails is marked offline and the others carry on. The dashboard host selector then offers `all`, the hub itself and each peer; summaries, traffic and IP tables are merged, and every row carries the host it came from.
## 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: no-referrer`, 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 routes and [configuration.md](configuration.md) for the settings.