Files
urutau/docs/architecture.md
T
Lucas RayanandClaude Opus 5.5 b7462c14fa
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
feat: 1.2.0 attack intelligence, replay, 30-day history and new interface
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>
2026-11-14 21:45:59 -03:00

15 KiB

◂ Back to README

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 and forward-confirmed reverse DNS
internal/evlog        on-disk event registry
internal/intel        families, MITRE, network type, cadence, sessions, campaigns, verdicts, STIX, metrics
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, 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.

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. Events relayed from peers are registered with the peer name 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).
  • 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 or Bingbot is confirmed by forward-confirmed reverse DNS; a fake one stays an attacker.
  • 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 listable (global addresses) / hostile IPs, in percent
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).

State and persistence

The state lives 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 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 256 MiB unless GOMEMLIMIT is set. The worst case measured is about 54 MiB of heap and a snapshot of about 27 MB.

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 the background ranges 1h, 24h, 7d and 30d; any other range or custom period is fetched on demand) 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. The peer token opens three routes: the export, the live stream and GET /api/v1/peer/period, the study (sessions, campaigns, metrics) the hub merges for a period or an IP; a peer runs at most two studies at once. 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.

Live relay

Besides the export, a hub keeps one GET /api/v1/peer/stream connection open per peer (a subscription per peer, with the peer's own token) and relays the live malicious events to its dashboard. What comes from a peer is bounded and sanitized: at most about 50 events per second per peer, lines of at most 16 KB, a buffer of the latest 500 relayed events (served by /api/v1/live/recent), and reconnection with backoff from 1 s up to 60 s. A peer serves at most 10 stream connections.

Geography aggregation

GET /api/v1/geo is computed from the IP table (local and the peers' exports) 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: 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 for the routes and configuration.md for the settings.