feat: Urutau 1.0.0, lightweight threat intelligence and web analytics
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
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
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>
This commit is contained in:
commit
b4a2c2c9ec
99 files changed
+15403
No files matched your search
@@ -0,0 +1,102 @@
|
||||
<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.
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
<p align="center"><a href="../README.md">◂ Back to README</a></p>
|
||||
|
||||
# Terminal
|
||||
|
||||
```
|
||||
urutau serve [flags] run the daemon and the dashboard
|
||||
urutau doctor [--json] [flags] check the sources and the data directory
|
||||
urutau healthcheck [flags] exit 0 when the local daemon answers /api/health
|
||||
urutau version print the version
|
||||
urutau help print the usage
|
||||
```
|
||||
|
||||
The access token is never a flag: `urutau serve` reads it from the `URUTAU_TOKEN` environment variable, or from the file named by `URUTAU_TOKEN_FILE`, so it does not show up in the process list. Tokens need at least 32 characters and about 128 bits of estimated entropy (length times Shannon entropy; periodic or sequential tokens are refused) (`openssl rand -base64 48` is recommended (`-hex 32` also works)). Every flag below has a `URUTAU_*` environment default; a flag wins over the variable. See [configuration.md](configuration.md).
|
||||
|
||||
## `urutau serve`
|
||||
|
||||
| Flag | Variable | Default | Meaning |
|
||||
|---|---|---|---|
|
||||
| `--bind` | `URUTAU_BIND` | `0.0.0.0:8790` | listen address |
|
||||
| `--name` | `URUTAU_NAME` | hostname | name of this instance |
|
||||
| `--data-dir` | `URUTAU_DATA_DIR` | `/data` | directory of the snapshot (`urutau-state.gob`) |
|
||||
| `--traefik-log` | `URUTAU_TRAEFIK_LOG` | `/data/coolify/proxy/access.log` | Traefik JSON access log; empty disables |
|
||||
| `--auth-log` | `URUTAU_AUTH_LOG` | `/var/log/auth.log` | sshd log; empty disables |
|
||||
| `--fail2ban-log` | `URUTAU_FAIL2BAN_LOG` | `/var/log/fail2ban.log` | fail2ban log; empty disables |
|
||||
| `--trusted` | `URUTAU_TRUSTED` | empty | CIDRs of trusted origins; their events are dropped entirely. `--ignore` / `URUTAU_IGNORE` is an alias |
|
||||
| `--ignore` | `URUTAU_IGNORE` | `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` | same effect as `--trusted`, with the private ranges as default |
|
||||
| `--monitor-ua` | `URUTAU_MONITOR_UA` | `(?i)^(Uptime-Kuma/\|Beszel\|Coolify\|kube-probe/\|Go-http-client/.*healthcheck)` | regular expression of monitoring User-Agents |
|
||||
| `--monitor-from` | `URUTAU_MONITOR_FROM` | empty | CIDRs the monitors come from; when set, the monitoring User-Agent only counts from them. Empty: only `ok` answers are filtered |
|
||||
| `--domains` | `URUTAU_DOMAINS` | empty | allowlist of analytics domains (exact or `*.example.com`); empty tracks every domain that answers 2xx; recommended when a backend answers 2xx for any Host |
|
||||
| `--geo-dir` | `URUTAU_GEO_DIR` | `<data-dir>/geo` | directory of the DB-IP Lite databases (city and ASN) |
|
||||
| `--geo-update` | `URUTAU_GEO_UPDATE` | `24h` | how often to check for a newer database; `0` turns the download off |
|
||||
| `--peer` | `URUTAU_PEERS` | none | peer `name=https://url`; repeat the flag, or comma separate the variable |
|
||||
| `--peer-token` | `URUTAU_PEER_TOKEN` | empty | token shared with the peers; prefer the variable or `URUTAU_PEER_TOKEN_FILE` (a flag shows up in the process list). Per-peer: `URUTAU_PEER_TOKEN_<NAME>` |
|
||||
| `--admin-users` | `URUTAU_ADMIN_USERS` | empty | SSH users whose successful login keeps their IP out of the blocklist for 24 h; the immunity is off unless set |
|
||||
| `--peer-allow` | `URUTAU_PEER_ALLOW` | empty | source CIDRs allowed to call the export; empty accepts any source with the token |
|
||||
| `--trusted-proxy` | `URUTAU_TRUSTED_PROXY` | `127.0.0.0/8,::1` (the compose file sets `10.250.0.0/24`) | proxies whose `X-Forwarded-For` is trusted, read right to left (login rate limit, `--peer-allow`) |
|
||||
| `--retention` | `URUTAU_RETENTION` | `168h` | how long data is kept (1h to 168h) |
|
||||
| `--insecure-no-auth` | none | off | disable authentication; only on a loopback bind |
|
||||
|
||||
Validation at start: peers must be `name=https://host` (plain `http` only on loopback), `URUTAU_PEER_TOKEN` must be set and different from `URUTAU_TOKEN`, names must be unique and cannot be `all` or the instance's own name, `--retention` must be at least 1h, and `URUTAU_TOKEN` and every peer token must have at least 32 characters and about 128 bits of estimated entropy; each peer needs a client token (`URUTAU_PEER_TOKEN_<NAME>` or the general `URUTAU_PEER_TOKEN` as fallback), and peer names must not collide in that variable name (unless `--insecure-no-auth` on a loopback address).
|
||||
|
||||
```bash
|
||||
export URUTAU_TOKEN=$(openssl rand -base64 48)
|
||||
urutau serve --bind 127.0.0.1:8790 --data-dir ./data \
|
||||
--traefik-log "" --auth-log /var/log/auth.log
|
||||
```
|
||||
|
||||
The daemon logs to stderr, saves a snapshot on `SIGTERM` or `SIGINT` and exits 0 on a clean stop.
|
||||
|
||||
## Noise and monitoring
|
||||
|
||||
```bash
|
||||
urutau serve --trusted "10.0.0.0/8,203.0.113.7" \
|
||||
--monitor-ua '(?i)uptime-kuma|statuscake'
|
||||
```
|
||||
|
||||
`--trusted` drops every event from those origins. `--monitor-ua` matches the User-Agent of benign requests (`ok` or `notfound`) and counts them apart as "monitoring"; a request that is a `scanner`, `exploit` or `bruteforce` still counts as an attack.
|
||||
|
||||
## Geolocation
|
||||
|
||||
```bash
|
||||
urutau serve --geo-dir /data/geo --geo-update 24h
|
||||
```
|
||||
|
||||
Urutau downloads the DB-IP Lite city and ASN databases into `--geo-dir` when they are missing or older than 35 days, then checks every `--geo-update` for the current month's file. The file is verified before it replaces the old one, and a failed download never stops the service. Data by [DB-IP](https://db-ip.com), CC BY 4.0.
|
||||
|
||||
## `urutau doctor`
|
||||
|
||||
Checks the configuration (token, peers, bind), each log source (readable, size), that the data directory is writable, the geolocation databases and the snapshot. Statuses are `ok`, `warn` (a source that cannot be opened yet), `fail` and `off` (disabled). The exit code is 1 when any check is `fail`, which makes it usable in a healthcheck or a deploy script.
|
||||
|
||||
```bash
|
||||
urutau doctor
|
||||
docker exec urutau urutau doctor --json
|
||||
```
|
||||
|
||||
`--json` prints `{"version", "name", "ok", "checks": [{"name", "status", "detail"}], "geo", "state"}`. `geo` reports the directory, update interval, attribution and the build dates of the loaded databases; `state` reports the snapshot (path, size, IPs, domains and requests in 7 days) or that none exists yet. A snapshot that cannot be read shows up as `warn`.
|
||||
|
||||
## `urutau healthcheck`
|
||||
|
||||
Calls `/api/health` on the local bind address and exits 0 when it answers `{"status":"ok"}`, 1 otherwise. It is the container `HEALTHCHECK`, which is why the image has no `curl`. It accepts the same flags as `serve` (for a non-default `--bind`).
|
||||
|
||||
## `urutau version`
|
||||
|
||||
Prints `urutau <version>`. `--version` and `-v` work too.
|
||||
@@ -0,0 +1,74 @@
|
||||
<p align="center"><a href="../README.md">◂ Back to README</a></p>
|
||||
|
||||
# Configuration
|
||||
|
||||
Urutau has no configuration file. Everything is a flag with a `URUTAU_*` environment default ([cli.md](cli.md)), which suits a container. The secrets are environment variables only.
|
||||
|
||||
## Secrets
|
||||
|
||||
| Variable | Meaning |
|
||||
|---|---|
|
||||
| `URUTAU_TOKEN` | **Required.** Access token of the dashboard and the API: at least 32 characters and about 128 bits of estimated entropy (length times Shannon entropy; periodic or sequential tokens are refused). Generate one with `openssl rand -base64 48` (`openssl rand -hex 32` also works; `-hex 16` is refused by the entropy estimate). |
|
||||
| `URUTAU_TOKEN_FILE` | Path of a file holding the token (whitespace trimmed), instead of the variable. The variable wins when both are set. |
|
||||
| `URUTAU_PEER_TOKEN` | Optional. The server token of this instance: the only token its `GET /api/v1/peer/export` accepts, and it opens nothing else. Same strength rules as `URUTAU_TOKEN` (32+ characters, about 128 bits of estimated entropy, not periodic or sequential), and it must differ from it. When this instance is a hub, it is also the fallback client token sent to peers that have no token of their own. |
|
||||
| `URUTAU_PEER_TOKEN_FILE` | Path of a file holding the general peer token. |
|
||||
| `URUTAU_PEER_TOKEN_<NAME>` and `..._<NAME>_FILE` | The client credential a hub sends to that one peer; it must equal the peer's own `URUTAU_PEER_TOKEN`. `<NAME>` is the peer name uppercased with every character other than a letter or digit turned into `_` (`my-peer` becomes `MY_PEER`). It does **not** open the local export. Two peer names that collapse to the same variable (`my-peer` and `my_peer`) are refused. A hub with a peer and no token for it refuses to start. |
|
||||
|
||||
Keep both in `.env` (never versioned) or in your orchestrator's secret store.
|
||||
|
||||
## Settings
|
||||
|
||||
| Variable | Default | Meaning |
|
||||
|---|---|---|
|
||||
| `URUTAU_BIND` | `0.0.0.0:8790` | listen address |
|
||||
| `URUTAU_NAME` | container hostname | name shown in the dashboard and used by the hub |
|
||||
| `URUTAU_DATA_DIR` | `/data` | where the snapshot `urutau-state.gob` is written |
|
||||
| `URUTAU_TRAEFIK_LOG` | `/data/coolify/proxy/access.log` | Traefik JSON access log, empty disables |
|
||||
| `URUTAU_AUTH_LOG` | `/var/log/auth.log` | sshd log, empty disables |
|
||||
| `URUTAU_FAIL2BAN_LOG` | `/var/log/fail2ban.log` | fail2ban log, empty disables |
|
||||
| `URUTAU_TRUSTED` | empty | trusted CIDRs or IPs, comma separated; their events are dropped entirely |
|
||||
| `URUTAU_IGNORE` | `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` | same effect, kept as the alias that carries the private ranges as default |
|
||||
| `URUTAU_MONITOR_UA` | `(?i)^(Uptime-Kuma/\|Beszel\|Coolify\|kube-probe/\|Go-http-client/.*healthcheck)` | regular expression of monitoring User-Agents |
|
||||
| `URUTAU_GEO_DIR` | `<data-dir>/geo` | where the DB-IP Lite databases live |
|
||||
| `URUTAU_GEO_UPDATE` | `24h` | interval between checks for a newer database; `0` disables the download |
|
||||
| `URUTAU_PEER_ALLOW` | empty | CIDRs allowed to call the export; empty accepts any source that has the token |
|
||||
| `URUTAU_TRUSTED_PROXY` | `127.0.0.0/8,::1` (the compose file sets `10.250.0.0/24`) | reverse proxies whose `X-Forwarded-For` is trusted (read right to left); used by the login rate limit and by `URUTAU_PEER_ALLOW` |
|
||||
| `URUTAU_DOMAINS` | empty | allowlist of analytics domains, exact names or `*.example.com`; empty tracks every domain that answers 2xx; recommended, in practice required, when any backend answers 2xx for every Host (catch-all or wildcard), otherwise random Hosts can fill the 24 domain slots |
|
||||
| `URUTAU_MONITOR_FROM` | empty | CIDRs the monitors really come from; when set, the monitoring User-Agent only counts from them |
|
||||
| `URUTAU_ADMIN_USERS` | empty | SSH users whose successful login keeps their IP out of the blocklist for 24 h after the last login (a later strong signal cancels it); the immunity is off unless this is set |
|
||||
| `URUTAU_PEERS` | empty | peers to aggregate, comma separated `name=https://url` |
|
||||
| `URUTAU_RETENTION` | `168h` | retention as a Go duration, from `1h` to `168h` |
|
||||
| `GOMEMLIMIT` | 160 MiB soft limit | standard Go memory limit; set it to override the default |
|
||||
| `TZ` | UTC | time zone of `fail2ban.log` timestamps, which carry no zone |
|
||||
|
||||
In the container image the three log paths default to `/logs/traefik/access.log`, `/logs/host/auth.log` and `/logs/host/fail2ban.log` (the compose file mounts the host logs there). The compose file adds `URUTAU_VERSION` (image tag), `URUTAU_IMAGE` and `URUTAU_PUBLISH` (host address and port), see `.env.example`.
|
||||
|
||||
## Noise and monitoring
|
||||
|
||||
- **Traefik headers.** Log `Sec-Fetch-Site`, `Sec-Fetch-Dest` and `Referer` so Urutau can tell a page framing your site from a real visit: `--accesslog.fields.headers.names.Sec-Fetch-Site=keep`, `--accesslog.fields.headers.names.Sec-Fetch-Dest=keep` and `--accesslog.fields.headers.names.Referer=keep`. A request framed by another page (`Sec-Fetch-Site` of `cross-site` or `same-site`, or a sub-resource `Sec-Fetch-Dest` such as `image` or `script`) appears in the timeline and creates an IP record like any other, but weighs 0.25 per event, with at most 30 points per IP coming from such requests (below the hostile threshold), and never counts as a strong signal. With an attack-tool User-Agent the headers are ignored.
|
||||
- **Trusted origins** (`URUTAU_TRUSTED`): your own network, offices, monitors and other servers. `URUTAU_IGNORE` already drops loopback and the private ranges by default, so internal traffic never scores. Add your public monitor IPs. If your proxy reports the Docker gateway as the client, that address is private and already dropped; fix the proxy to pass the real client address instead.
|
||||
- **Monitoring User-Agent** (`URUTAU_MONITOR_UA`): a Go regular expression. A request that matches and is benign is counted as "monitoring" instead of traffic. If the request is a `scanner`, `exploit` or `bruteforce` it counts as an attack: a User-Agent is trivial to forge, so it never grants immunity.
|
||||
- **Where monitors come from** (`URUTAU_MONITOR_FROM`): CIDRs of your monitors. When set, the monitoring User-Agent is honored only from those networks and benign requests (`ok` or `notfound`) are filtered. When empty, only `ok` answers are filtered: a `notfound` carrying a monitor User-Agent still counts, because anyone can send that header.
|
||||
|
||||
## Geolocation and analytics
|
||||
|
||||
Country, city and ASN come from the DB-IP Lite databases (city and ASN), which Urutau downloads and refreshes by itself into `URUTAU_GEO_DIR`. Without them (for example on an air-gapped host) the dashboard works and the geographic fields stay empty; to run offline, place the `dbip-city-lite-YYYY-MM.mmdb` and `dbip-asn-lite-YYYY-MM.mmdb` files in that directory and set `URUTAU_GEO_UPDATE=0`. The databases are licensed CC BY 4.0: keep the attribution (the dashboard footer and the README already carry it).
|
||||
|
||||
The Traffic tab needs no setting. `URUTAU_DOMAINS` restricts which domains it tracks (exact names or `*.example.com`); a domain only gets a slot after a 2xx answer and inactive domains are pruned, so forged `Host` headers cannot fill the analytics. Top pages normalize token-looking path segments (ids, hashes, long random strings) to `:id`. It uses the Traefik log, counts unique visitors by a daily-salted hash and never persists the IP address of a legitimate visitor. See [SECURITY.md](../SECURITY.md).
|
||||
|
||||
## Peers (hub mode)
|
||||
|
||||
```
|
||||
URUTAU_PEERS=web1=https://urutau.web1.example,db1=https://urutau.db1.example
|
||||
URUTAU_PEER_TOKEN=<shared secret>
|
||||
```
|
||||
|
||||
On each peer, set the same `URUTAU_PEER_TOKEN`. The hub calls only `GET /api/v1/peer/export` (once per range, `1h`, `24h` and `7d`, every 15 seconds). Peer URLs must be `https` (plain `http` is accepted only for loopback): the peer token travels in a header. To restrict who may call the export, set `URUTAU_PEER_ALLOW` on the peer to the hub's address. Peer names must be unique and cannot be `all` or the hub's own name.
|
||||
|
||||
## Snapshot and retention
|
||||
|
||||
The snapshot file holds the aggregated state and the log offsets. Mount `URUTAU_DATA_DIR` on a volume to keep it across restarts. Delete the file to start from zero (the rotated logs will be read again). Retention limits how long an IP is kept, at most 168 hours; the dashboard ranges are `1h`, `24h` and `7d`.
|
||||
|
||||
## Authentication and exposure
|
||||
|
||||
The default bind is `0.0.0.0` because the container is behind a proxy. Outside a container, bind to `127.0.0.1` or put a TLS reverse proxy in front. `--insecure-no-auth` exists only for local tests and is refused on non-loopback binds.
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
<p align="center"><a href="../README.md">◂ Back to README</a></p>
|
||||
|
||||
# Docker
|
||||
|
||||
Urutau ships as one small container image (`linux/amd64` and `linux/arm64`, about 28 MB, no `curl`), defined in [`docker-compose.yml`](../docker-compose.yml). It only needs to read log files and to write one snapshot.
|
||||
|
||||
```
|
||||
host container urutau
|
||||
/data/coolify/proxy/logs ── :ro ────────────► /logs/traefik (access.log of Traefik)
|
||||
/var/log/urutau ── :ro ────────────► /logs/host (auth.log, fail2ban.log)
|
||||
volume urutau-data ── read and write ─► /data (snapshot, geo databases)
|
||||
```
|
||||
|
||||
The compose file follows this layout. The Traefik log directory is mounted outside `/data` so it does not collide with the snapshot volume. Only the dedicated `logs` directory of the proxy is mounted, never the whole `/data/coolify/proxy` (which holds `acme.json` and the dynamic configuration).
|
||||
|
||||
The image runs as the unprivileged user `urutau` (uid 10001) on Alpine. Its `HEALTHCHECK` is the binary itself (`urutau healthcheck`, which asks the local daemon for `/api/health`), so there is no `curl` in the image. The compose file sets `mem_limit: 256m` and `cpus: 0.5`, a read-only root filesystem, `cap_drop: [ALL]` and `no-new-privileges`, and passes from `.env` to the container: `URUTAU_TOKEN`, `URUTAU_NAME`, `URUTAU_TRUSTED`, `URUTAU_PEERS`, `URUTAU_PEER_TOKEN`, `URUTAU_PEER_ALLOW`, `URUTAU_TRUSTED_PROXY`, `URUTAU_DOMAINS`, `URUTAU_MONITOR_FROM`, `URUTAU_ADMIN_USERS`, `URUTAU_GEO_UPDATE` and `TZ`. To set any other `URUTAU_*` variable (`URUTAU_MONITOR_UA`, `URUTAU_RETENTION`, `URUTAU_TOKEN_FILE`, per-peer tokens, ...), add it to the `environment` block.
|
||||
|
||||
## Quick start
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
sed -i "s|^URUTAU_TOKEN=.*|URUTAU_TOKEN=$(openssl rand -base64 48 | tr -d '\n')|" .env
|
||||
docker compose pull && docker compose up -d # published image
|
||||
# or, building locally:
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
The token needs at least 32 characters and about 128 bits of estimated entropy (length times Shannon entropy; periodic or sequential tokens are refused). `openssl rand -base64 48` is recommended (`openssl rand -hex 32` also qualifies). To keep the secret out of the environment, mount a file and set `URUTAU_TOKEN_FILE` (same for `URUTAU_PEER_TOKEN_FILE`).
|
||||
|
||||
The dashboard comes up at `http://127.0.0.1:8790` by default (`URUTAU_PUBLISH` in `.env` changes the address and port). Check the sources:
|
||||
|
||||
```bash
|
||||
docker compose exec urutau urutau doctor
|
||||
docker compose logs urutau
|
||||
```
|
||||
|
||||
## Reading the logs
|
||||
|
||||
- **Traefik:** the access log must be JSON and written to a dedicated directory. In Traefik's static configuration set `--accesslog=true`, `--accesslog.format=json` and `--accesslog.filepath=/traefik/logs/access.log`. On Coolify the host directory `/data/coolify/proxy` is `/traefik` inside the proxy container, so that file appears on the host as `/data/coolify/proxy/logs/access.log`, which is what the compose file mounts. In the Coolify UI open Servers, the server, Proxy, and add those three lines to the `command` list of the proxy configuration, then restart the proxy. In the same place add the headers Urutau uses to tell real visits from framed requests: `--accesslog.fields.headers.names.Sec-Fetch-Site=keep`, `--accesslog.fields.headers.names.Sec-Fetch-Dest=keep` and `--accesslog.fields.headers.names.Referer=keep`.
|
||||
- **auth.log and fail2ban.log:** the dedicated host directory `/var/log/urutau` is mounted read-only at `/logs/host` as a directory, because logrotate recreates these files by rename and a single-file mount would keep following the old inode. Prepare it as shown in [Preparing the host logs](#preparing-the-host-logs). The files are owned by `syslog:adm`, so the container adds the host's `adm` group (GID 4) with `group_add: ["4"]`, as the compose file does. Nothing else from the host `/var/log` is exposed.
|
||||
- **Read-only:** all log mounts are `:ro`. Urutau never writes to a log.
|
||||
- **Rotation:** the follower reopens the file when logrotate replaces or truncates it.
|
||||
|
||||
## Preparing the host logs
|
||||
|
||||
Urutau reads a dedicated directory, `/var/log/urutau`, instead of the whole `/var/log`. Prepare it once on each server (the original `/var/log/auth.log` stays untouched):
|
||||
|
||||
```bash
|
||||
sudo install -d -m 0750 -o syslog -g adm /var/log/urutau
|
||||
|
||||
# rsyslog: copy sshd lines into their own file
|
||||
sudo tee /etc/rsyslog.d/40-urutau.conf >/dev/null <<'EOF'
|
||||
if $programname == 'sshd' or $programname == 'sshd-session' then {
|
||||
action(type="omfile" file="/var/log/urutau/auth.log" template="RSYSLOG_FileFormat"
|
||||
fileOwner="syslog" fileGroup="adm" fileCreateMode="0640")
|
||||
}
|
||||
EOF
|
||||
sudo systemctl restart rsyslog
|
||||
|
||||
# fail2ban: write its log there too
|
||||
sudo tee /etc/fail2ban/fail2ban.d/urutau.local >/dev/null <<'EOF'
|
||||
[Definition]
|
||||
logtarget = /var/log/urutau/fail2ban.log
|
||||
EOF
|
||||
sudo systemctl restart fail2ban
|
||||
|
||||
# logrotate for both files
|
||||
sudo tee /etc/logrotate.d/urutau >/dev/null <<'EOF'
|
||||
/var/log/urutau/*.log {
|
||||
weekly
|
||||
rotate 4
|
||||
compress
|
||||
delaycompress
|
||||
missingok
|
||||
notifempty
|
||||
create 0640 syslog adm
|
||||
postrotate
|
||||
systemctl kill -s HUP rsyslog.service 2>/dev/null || true
|
||||
fail2ban-client flushlogs >/dev/null 2>&1 || true
|
||||
endscript
|
||||
}
|
||||
EOF
|
||||
```
|
||||
|
||||
`RSYSLOG_FileFormat` writes ISO timestamps, which is the format Urutau parses. Check the `adm` GID with `getent group adm`. Known limitation: a local user of the host can forge sshd lines with `logger -t sshd`. Urutau limits the damage (a hostile level needs a strong signal and the admin immunity lasts 24 hours), but anyone with a shell on the host is already inside your trust boundary.
|
||||
|
||||
## Example: Coolify
|
||||
|
||||
Create a Docker Compose resource on the Coolify server whose logs you want to watch, with this compose file:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
urutau:
|
||||
image: git.lucasrguerra.dev.br/ciberfauna/urutau:latest
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
URUTAU_TOKEN: ${URUTAU_TOKEN}
|
||||
URUTAU_NAME: server-1
|
||||
URUTAU_AUTH_LOG: /logs/host/auth.log
|
||||
URUTAU_FAIL2BAN_LOG: /logs/host/fail2ban.log
|
||||
URUTAU_TRUSTED_PROXY: 10.250.0.0/24
|
||||
TZ: UTC # the host's time zone (fail2ban.log has none)
|
||||
group_add: ["4"] # adm: read auth.log and fail2ban.log
|
||||
read_only: true
|
||||
cap_drop: [ALL]
|
||||
security_opt: ["no-new-privileges:true"]
|
||||
volumes:
|
||||
- /data/coolify/proxy/logs:/logs/traefik:ro
|
||||
- /var/log/urutau:/logs/host:ro
|
||||
- urutau-data:/data
|
||||
networks: [urutau-edge]
|
||||
labels:
|
||||
- traefik.enable=true
|
||||
- traefik.docker.network=urutau-edge
|
||||
- traefik.http.routers.urutau.rule=Host(`urutau.example.com`)
|
||||
- traefik.http.routers.urutau.entrypoints=https
|
||||
- traefik.http.routers.urutau.tls=true
|
||||
- traefik.http.routers.urutau.tls.certresolver=letsencrypt
|
||||
- traefik.http.services.urutau.loadbalancer.server.port=8790
|
||||
|
||||
volumes:
|
||||
urutau-data:
|
||||
|
||||
networks:
|
||||
urutau-edge:
|
||||
external: true
|
||||
```
|
||||
|
||||
Notes:
|
||||
|
||||
- **A network shared only with Traefik.** `--trusted-proxy` defaults to loopback only, so by default `X-Forwarded-For` is ignored. The compose file creates the `urutau-edge` network (`10.250.0.0/24`) and sets `URUTAU_TRUSTED_PROXY=10.250.0.0/24`, so only the proxy on that network is believed (any other container there could forge client IPs, so keep it to the proxy). Connect the proxy once: `docker network connect urutau-edge coolify-proxy`. In a standalone compose like the example below, declare the network the same way and set the variable. The `traefik.docker.network` label tells Traefik to use it. Adapt the entrypoint and certificate resolver names to your proxy.
|
||||
- The image already points the sources at `/logs/traefik/access.log`, `/logs/host/auth.log` and `/logs/host/fail2ban.log` (its `URUTAU_*_LOG` defaults). The binary's own defaults (`/data/coolify/proxy/access.log`, `/var/log/...`) are for running it directly on the host.
|
||||
- Set `URUTAU_TOKEN` in the Coolify environment. Behind the proxy the dashboard is served over HTTPS, so the session cookie is `Secure`.
|
||||
- Do not publish port 8790 on the host when the proxy already routes it.
|
||||
- If the Traefik access log is missing or not JSON, the source stays at zero lines or `malformed` grows.
|
||||
- Urutau needs no `tmpfs`: the root filesystem is read-only and its only write target is the `/data` volume.
|
||||
|
||||
## Geolocation database
|
||||
|
||||
The DB-IP Lite databases are downloaded into the data volume (`/data/geo`) on first start, so the container needs outbound HTTPS to `download.db-ip.com` once, and then once a month. If the host cannot reach the internet, copy the two `.mmdb` files into the volume and set `URUTAU_GEO_UPDATE=0` ([configuration.md](configuration.md)). Data by [DB-IP](https://db-ip.com), CC BY 4.0.
|
||||
|
||||
## Federation across servers
|
||||
|
||||
Run one Urutau per server with its own `URUTAU_NAME`. Every instance that is polled sets its own server token, `URUTAU_PEER_TOKEN` (or `_FILE`), and that is the only token its export accepts. The hub holds a client credential for each peer, equal to that peer's server token: one `URUTAU_PEER_TOKEN_<NAME>` per peer (the peer name uppercased, other characters turned into `_`, for example `URUTAU_PEER_TOKEN_SERVER_2`), with the hub's general `URUTAU_PEER_TOKEN` as fallback. A client credential does not open the hub's own export, and peer names that collapse to the same variable (`my-peer` and `my_peer`) are refused. Tokens need 32+ characters and about 128 bits of entropy, different from `URUTAU_TOKEN` (`openssl rand -base64 48`), and can come from `..._FILE`. On the server that hosts the shared dashboard (the hub) add:
|
||||
|
||||
```yaml
|
||||
environment:
|
||||
URUTAU_PEERS: server-2=https://urutau.server2.example.com,server-3=https://urutau.server3.example.com
|
||||
URUTAU_PEER_TOKEN_SERVER_2: ${TOKEN_FOR_SERVER_2}
|
||||
URUTAU_PEER_TOKEN_SERVER_3: ${TOKEN_FOR_SERVER_3}
|
||||
```
|
||||
|
||||
The hub calls only `GET /api/v1/peer/export` on each peer (three ranges every 15 seconds) with that peer's token, which opens nothing else on the peer and is refused over plain `http` outside loopback. Set `URUTAU_PEER_ALLOW` on a peer to the hub's address to restrict who may call the export. Each peer keeps its own login token for its own dashboard.
|
||||
|
||||
## Hardening
|
||||
|
||||
`read_only: true`, `cap_drop: [ALL]`, `no-new-privileges` and read-only log mounts leave the container able to do one thing: read the logs and write its snapshot. Keep the image on a pinned tag (`X.Y.Z`) in production and `latest` only where you accept updates.
|
||||
|
||||
## Health and shutdown
|
||||
|
||||
`GET /api/health` answers `{"status":"ok"}` without authentication. `urutau healthcheck` calls it locally and exits 0 when the daemon is healthy; the image uses it as its `HEALTHCHECK`. On `SIGTERM` the daemon stops accepting requests, saves the snapshot and exits.
|
||||
@@ -0,0 +1,53 @@
|
||||
<p align="center"><a href="../README.md">◂ Back to README</a></p>
|
||||
|
||||
# Interface
|
||||
|
||||
The dashboard is embedded in the binary: plain HTML, CSS and JavaScript, no build step and no external request (fonts, scripts and styles are all served by Urutau, which the Content-Security-Policy enforces). It follows the system light or dark theme, can be switched by hand, and speaks English or Portuguese (button in the header; the choice is remembered in the browser).
|
||||
|
||||
## Login
|
||||
|
||||
Open the address of the instance. Without a session you are sent to `/login`: paste `URUTAU_TOKEN`. The session lasts 12 hours (`urutau_session` cookie, `HttpOnly`, `SameSite=Strict`) and is revocable: it holds a random id kept in memory, **Log out** revokes it (and closes its live stream), and a restart of the daemon invalidates every session. Login and logout reject cross-site requests. After 5 failures from the same address (IPv6 counted per /64) in 10 minutes the login answers 429, and a correct token is still accepted but after a 1 second delay, so the limiter cannot lock the owner out. Wrong bearer tokens on the API count as failures too. The address is the real client behind the proxies listed in `--trusted-proxy`.
|
||||
|
||||
## Header
|
||||
|
||||
- A live indicator showing whether the event stream (SSE) is connected (an instance serves at most 20 stream clients at once).
|
||||
- The **host** selector: `all`, this instance and every peer of a hub.
|
||||
- The **range** selector: `1h`, `24h` or `7d`.
|
||||
- Language, theme and logout buttons.
|
||||
|
||||
## Threats tab
|
||||
|
||||
- **KPIs:** requests, malicious events, hostile IPs, suspicious IPs, bans and the "monitoring" counter (benign requests from monitor User-Agents, kept out of the traffic numbers).
|
||||
- **Timeline:** stacked counters per category over the selected range.
|
||||
- **IPs:** a table with score, level (`hostile`, `suspicious`, `low`), categories, hosts, reverse DNS, country, city and ASN, last seen and ban state. It has a search box (IP or reverse DNS), a level filter, a "banned only" filter, sorting by IP, score or last seen, and paging. Click a row for the detail drawer: first and last seen, per-category counts, sample paths, User-Agents (parsed into browser, OS, device, bot or attack tool), domains, users and jails.
|
||||
- **Live feed:** the latest events as they arrive. Fields from the logs are shown as text, never as markup.
|
||||
- **Top lists:** attacked paths, domains, User-Agents and targeted users.
|
||||
- **Blocklist:** pick a minimum score (default 50), copy the list or download it. It only lists hostile, globally routable addresses (never `--ignore` or `--trusted` ranges, never an IP with a successful SSH login); IPv6 appears as its /64, written `x:x:x:x::/64`.
|
||||
- **Map:** a world map of the origin countries of hostile activity.
|
||||
- **Hosts and sources:** every instance with its state (online, latency, version) and every log source with its state (`following`, `waiting`, `backfill`, `error`), lines read, malformed lines and last event. The file paths are not shown.
|
||||
|
||||
## Traffic tab
|
||||
|
||||
Privacy-friendly web analytics for legitimate traffic, built from the same Traefik log and replacing the analytics of the proxy: unique visitors, pages, referrers, countries, browsers, operating systems and devices, response latency (p50 and p95), bytes sent, and a world map of visitor countries. Unique visitors are counted by a hash with a daily salt; the IP of a legitimate visitor is never stored. See [SECURITY.md](../SECURITY.md).
|
||||
|
||||
## Attribution
|
||||
|
||||
IP geolocation data by [DB-IP](https://db-ip.com), licensed under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). The credit also appears in the footer of the dashboard.
|
||||
|
||||
## HTTP routes
|
||||
|
||||
| Route | Auth | Purpose |
|
||||
|---|---|---|
|
||||
| `GET /api/health` | none | `{"status":"ok"}` |
|
||||
| `GET /login`, `POST /login`, `POST /logout` | none | session |
|
||||
| `GET /` and the static files | session | the dashboard |
|
||||
| `GET /api/v1/summary` | session or bearer | everything the dashboard shows. Query: `range` (`1h`, `24h`, `7d`), `host` (`all`, a name) |
|
||||
| `GET /api/v1/traffic` | session or bearer | web analytics of legitimate traffic. Query: `range`, `domain` (`all` or one domain), `host`. Returns visitors, pages, requests, bots, bytes, status classes, `p50_ms`, `p95_ms`, a timeline, top pages, referrers, countries, cities, browsers, operating systems, devices and bot names |
|
||||
| `GET /api/v1/peer/export` | peer token only | federation: `{"v":1,"summary":...,"traffic":{...}}` with the top 500 IPs and their detail. Query: `range` (`1h`, `24h`, `7d`). Cached for 5 s. 404 when no peer token is set, 401 for `URUTAU_TOKEN`, 403 from a source outside `--peer-allow` |
|
||||
| `GET /api/v1/ips` | session or bearer | IP table. Query: `range`, `host`, `min_score`, `level`, `q`, `banned=1`, `sort` (`score`, `last`, `first`, `events`, `ip`), `order=asc`, `per` (1 to 200, default 50), `page` |
|
||||
| `GET /api/v1/ip/{ip}` | session or bearer | detail of one IP, merged with the peers' exports |
|
||||
| `GET /api/v1/events/stream` | session or bearer | Server-Sent Events, event `ev`, a ping every 20 s |
|
||||
| `GET /api/v1/blocklist.txt` | session or bearer | one IP per line. Query: `min_score` (default 50), `range` (default `7d`), `host`, `family` (`4`, `6`; default both; `4` suits `ipset hash:ip`), `download=1` |
|
||||
| `GET /api/v1/blocklist.json` | session or bearer | `{"generated","min_score","count","ips":[{"ip","score","last","hosts"}]}`; the `ip` of an IPv6 entry is a `/64` prefix |
|
||||
|
||||
API clients send `Authorization: Bearer <URUTAU_TOKEN>`. The peer token is accepted only by `/api/v1/peer/export`; every other route answers 403 to it.
|
||||
@@ -0,0 +1,102 @@
|
||||
<p align="center"><a href="../../README.pt-BR.md">◂ Voltar ao README</a></p>
|
||||
|
||||
# Arquitetura
|
||||
|
||||
O Urutau é um único binário Go sem dependência de terceiros. Tudo roda em um processo.
|
||||
|
||||
```
|
||||
cmd/urutau ponto de entrada: serve, doctor, version
|
||||
internal/app flags, ligação das peças, runner dos logs, doctor
|
||||
internal/tail seguidor de arquivo que tolera rotação e leitor de rotacionados
|
||||
internal/core modelo de evento, parsers (Traefik, sshd, fail2ban), classificador
|
||||
internal/store estado em memória, resumos, merge, snapshot
|
||||
internal/rdns cache de DNS reverso
|
||||
internal/fed hub que consulta os peers
|
||||
internal/server handler HTTP, autenticação, dashboard embutido (web/)
|
||||
```
|
||||
|
||||
## Fluxo de dados
|
||||
|
||||
```
|
||||
access.log do Traefik auth.log fail2ban.log
|
||||
│ │ │
|
||||
└──── tail.Follower (uma goroutine por fonte) ────┐
|
||||
▼
|
||||
parse (core.ParseTraefik / ParseAuth / ParseFail2ban) → Event
|
||||
▼
|
||||
origem confiável? descarta. UA de monitor e benigno? conta à parte.
|
||||
▼
|
||||
store.Ingest: contadores, registro por IP, feed ao vivo
|
||||
▼
|
||||
snapshot a cada 60 s ◄── estado ──► resumos / tabela de IPs / SSE
|
||||
```
|
||||
|
||||
## Fontes
|
||||
|
||||
Cada fonte é seguida por sua própria goroutine e reporta um estado: `following`, `waiting` (o arquivo ainda não existe), `backfill` (primeira inicialização, lendo as cópias rotacionadas) ou `error`. Uma linha maior que 64 KiB é descartada e contada como malformada. Na primeira inicialização sem snapshot, as cópias rotacionadas (`path.1`, `path.N.gz` até 9) são lidas da mais antiga para a mais nova, para que a janela não comece vazia.
|
||||
|
||||
As linhas são decodificadas assim:
|
||||
|
||||
- **Traefik:** um objeto JSON por linha. Lê-se endereço do cliente, host, método, caminho, status e User-Agent; caminhos e User-Agents são cortados.
|
||||
- **sshd:** as linhas do `auth.log` com timestamps ISO. Senhas e chaves recusadas, usuários inválidos, conexões fechadas antes da autenticação e logins `Accepted`; erros de negociação, falhas de banner e versões de protocolo incompatíveis contam como sondagens.
|
||||
- **fail2ban:** linhas `Ban`, `Unban` e `Restore Ban`. Um ban restaurado (reaplicado após um reinício do fail2ban) atualiza o estado de ban e não é pontuado.
|
||||
|
||||
Os caminhos dos arquivos de log nunca são expostos: nem o dashboard nem o export de um peer mostram de onde uma fonte lê, só o nome e o estado dela.
|
||||
|
||||
Linhas válidas que não trazem nada a registrar são ignoradas em silêncio; linhas que não dá para interpretar são contadas como malformadas e aparecem por fonte no dashboard.
|
||||
|
||||
## Classificação e pontuação
|
||||
|
||||
Uma requisição web é classificada pelo caminho decodificado (decodificação percentual até duas vezes, contra dupla codificação), método e status.
|
||||
|
||||
| Categoria | Significado | Peso |
|
||||
|---|---|---|
|
||||
| `exploit` | traversal, `${jndi:`, injeção de script, SQL union, sondas de shell e de leitura de arquivo | 8 |
|
||||
| `ban` | o fail2ban baniu o IP | 10 |
|
||||
| `scanner` | sondas de `.env`, `.git`, `wp-config`, phpMyAdmin, backups e arquivos compactados, varredura de plugins | 3 |
|
||||
| `bruteforce` | `xmlrpc.php`, `wp-login.php` com falha, `POST` respondido com 401 | 2 |
|
||||
| `ssh-fail` | falha de autenticação no sshd | 2 |
|
||||
| `ssh-probe` | sondagem de negociação ou banner do sshd | 1 |
|
||||
| `notfound` | demais respostas 4xx | 0,2 |
|
||||
| `ok`, `ssh-ok` | tráfego benigno e logins bem-sucedidos | 0 |
|
||||
|
||||
A pontuação de um IP é a soma dos pesos dos seus eventos na janela retida. Uma requisição `scanner` ou `exploit` que o servidor respondeu com 2xx ou 3xx (a sonda provavelmente não achou nada, ou a página é pública) pesa só 0,5. Unbans e bans restaurados não somam nada.
|
||||
|
||||
O nível combina a pontuação com evidência:
|
||||
|
||||
- **Suspeito:** pontuação 10 ou mais.
|
||||
- **Hostil:** pontuação 50 ou mais **e** um sinal forte: uma ferramenta de ataque conhecida no User-Agent, duas ou mais categorias de ataque, um ban do fail2ban, ou uma tentativa clara de exploit recusada (4xx ou 5xx). Uma pontuação alta feita só de sinais fracos (um crawler que bate em muitos 404) continua suspeita.
|
||||
- **Nunca hostil:** um IP com login SSH bem-sucedido (`ssh-ok`), que provavelmente é você.
|
||||
- Caso contrário, **baixo**.
|
||||
|
||||
Clientes IPv6 são rastreados pelo prefixo /64, já que um assinante tem um /64 inteiro e chaves por endereço deixariam um atacante inundar a tabela. São rastreados até 20.000 IPs.
|
||||
|
||||
As categorias maliciosas (`scanner`, `exploit`, `bruteforce`, `ssh-fail`, `ssh-probe`) alimentam os totais de "malicioso".
|
||||
|
||||
## Filtro de ruído
|
||||
|
||||
Eventos de uma origem confiável (`--trusted`, mais as faixas privadas de `--ignore`) são descartados antes de qualquer registro. Uma requisição cujo User-Agent casa com `--monitor-ua` e que é benigna vai para um contador "monitoring" à parte e não entra no tráfego, na pontuação nem nas listas. Com `--monitor-from` o User-Agent só vale vindo dessas redes; sem ele, só respostas `ok` são filtradas. Se a requisição for classificada como `scanner`, `exploit` ou `bruteforce`, é um ataque normal, já que um User-Agent pode ser forjado.
|
||||
|
||||
## Geolocalização e User-Agents
|
||||
|
||||
`internal/geo` é um leitor MMDB sem dependências. Ele abre as bases DB-IP Lite de cidade e ASN, responde país, cidade e ASN de qualquer IP público (endereços privados e loopback não retornam nada) atrás de um pequeno cache, e troca um arquivo mais novo sem reiniciar. O atualizador baixa os arquivos de `download.db-ip.com` quando faltam ou têm mais de 35 dias, e depois confere no intervalo de `--geo-update`, verificando cada arquivo ao abri-lo antes de substituir o antigo. `internal/ua` interpreta um User-Agent em navegador, sistema operacional, classe de dispositivo, bot (buscadores, crawlers) ou ferramenta de ataque (scanners e kits de exploração). Dados por [DB-IP](https://db-ip.com), CC BY 4.0.
|
||||
|
||||
## Web analytics
|
||||
|
||||
Requisições benignas (`ok`, e os `notfound` que não são varredura) também alimentam a visão Tráfego. Um domínio só ganha vaga depois de uma resposta 2xx (e `--domains` pode restringi-los a uma lista), domínios inativos são podados e o top de páginas normaliza segmentos com cara de token para `:id`: visitantes únicos, páginas, referrers, países, navegadores, sistemas operacionais, dispositivos, latência (p50 e p95) e bytes. Um visitante único é um hash calculado com um sal que gira todo dia, então não pode ser seguido entre dias, e o endereço IP de um visitante legítimo nunca é persistido. O tráfego de ataque fica na visão Ameaças, onde o IP é o assunto. Requisições de monitoramento ficam fora das duas.
|
||||
|
||||
## Estado e persistência
|
||||
|
||||
O estado vive em memória: buckets por minuto de 7 dias, listas de top por hora (caminhos, domínios, User-Agents, usuários), uma tabela de até 20.000 IPs (quando cheia, 10% com a menor pontuação são removidos; IPs banidos são mantidos), um feed dos últimos 500 eventos e os bans ativos. `--retention` (1h a 168h) limita quanto tempo os IPs ficam; IPs antigos são podados a cada 10 minutos.
|
||||
|
||||
A cada 60 segundos, e no desligamento, o estado é gravado em `urutau-state.gob` no diretório de dados junto com o inode e a posição de cada fonte. Na inicialização ele é restaurado e cada fonte retoma exatamente de onde parou, então um reinício nunca conta um log duas vezes. O snapshot é pulado enquanto um backfill roda. Um snapshot ilegível é movido para `urutau-state.gob.corrupt` e o serviço sobe vazio, lendo os logs de novo (incluindo as cópias rotacionadas).
|
||||
|
||||
O processo define um limite suave de memória de 160 MiB, a menos que `GOMEMLIMIT` esteja definido.
|
||||
|
||||
## Federação
|
||||
|
||||
Um hub é uma instância comum iniciada com `--peer nome=https://url`, e precisa de `URUTAU_PEER_TOKEN`. A cada 15 segundos ele chama `GET /api/v1/peer/export?range=...` de cada peer (para `1h`, `24h` e `7d`) com o token de peer e guarda a última resposta. O export é `{"v":1,"summary":...,"traffic":{...}}` com os 500 IPs principais e seus detalhes, em cache de 5 segundos no peer. É a única rota que o token de peer abre. O hub nunca segue redirects, exige `https` fora de loopback, usa timeout de 4 segundos, limita o corpo a 8 MB e sanitiza e limita o que um peer enviar. Um peer que falha é marcado offline e os demais seguem. O seletor de host do dashboard passa a oferecer `all`, o próprio hub e cada peer; resumos, tráfego e tabelas de IPs são mesclados, e cada linha carrega o host de origem.
|
||||
|
||||
## Camada HTTP
|
||||
|
||||
O servidor define timeouts de leitura, escrita e ociosidade, `MaxHeaderBytes` de 16 KB, limita `POST /login` a 4 KB e aceita no máximo 20 clientes simultâneos do stream ao vivo (SSE) (o 21º recebe 503 com `Retry-After`; cada stream envia heartbeat a cada 20 s). O handler usa o mux padrão do `net/http`. Toda resposta leva uma Content-Security-Policy estrita (`default-src 'self'`), `X-Content-Type-Options`, `X-Frame-Options: DENY`, `Referrer-Policy: no-referrer`, cabeçalhos de isolamento de origem cruzada e, em HTTPS, HSTS. As respostas da API são `Cache-Control: no-store`. Os arquivos do dashboard são embutidos no binário. Veja [interface.md](interface.md) para as rotas e [configuracao.md](configuracao.md) para os ajustes.
|
||||
@@ -0,0 +1,84 @@
|
||||
<p align="center"><a href="../../README.pt-BR.md">◂ Voltar ao README</a></p>
|
||||
|
||||
# Terminal
|
||||
|
||||
```
|
||||
urutau serve [flags] roda o daemon e o dashboard
|
||||
urutau doctor [--json] [flags] confere as fontes e o diretório de dados
|
||||
urutau healthcheck [flags] sai com 0 quando o daemon local responde /api/health
|
||||
urutau version imprime a versão
|
||||
urutau help imprime o uso
|
||||
```
|
||||
|
||||
O token de acesso nunca é uma flag: `urutau serve` o lê da variável de ambiente `URUTAU_TOKEN`, ou do arquivo indicado por `URUTAU_TOKEN_FILE`, para que não apareça na lista de processos. Tokens precisam de pelo menos 32 caracteres e cerca de 128 bits de entropia estimada (comprimento vezes entropia de Shannon; tokens periódicos ou sequenciais são recusados) (`openssl rand -base64 48` é o recomendado (`-hex 32` também serve)). Toda flag abaixo tem um padrão por variável `URUTAU_*`; a flag vence a variável. Veja [configuracao.md](configuracao.md).
|
||||
|
||||
## `urutau serve`
|
||||
|
||||
| Flag | Variável | Padrão | Significado |
|
||||
|---|---|---|---|
|
||||
| `--bind` | `URUTAU_BIND` | `0.0.0.0:8790` | endereço de escuta |
|
||||
| `--name` | `URUTAU_NAME` | hostname | nome desta instância |
|
||||
| `--data-dir` | `URUTAU_DATA_DIR` | `/data` | diretório do snapshot (`urutau-state.gob`) |
|
||||
| `--traefik-log` | `URUTAU_TRAEFIK_LOG` | `/data/coolify/proxy/access.log` | access log JSON do Traefik; vazio desativa |
|
||||
| `--auth-log` | `URUTAU_AUTH_LOG` | `/var/log/auth.log` | log do sshd; vazio desativa |
|
||||
| `--fail2ban-log` | `URUTAU_FAIL2BAN_LOG` | `/var/log/fail2ban.log` | log do fail2ban; vazio desativa |
|
||||
| `--trusted` | `URUTAU_TRUSTED` | vazio | CIDRs de origens confiáveis; os eventos delas são descartados por completo. `--ignore` / `URUTAU_IGNORE` é um alias |
|
||||
| `--ignore` | `URUTAU_IGNORE` | `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` | mesma função de `--trusted`, com as faixas privadas como padrão |
|
||||
| `--monitor-ua` | `URUTAU_MONITOR_UA` | `(?i)^(Uptime-Kuma/\|Beszel\|Coolify\|kube-probe/\|Go-http-client/.*healthcheck)` | expressão regular de User-Agents de monitoramento; vazio desativa |
|
||||
| `--monitor-from` | `URUTAU_MONITOR_FROM` | vazio | CIDRs de onde vêm os monitores; quando definido, o User-Agent de monitoramento só vale vindo deles. Vazio: só respostas `ok` são filtradas |
|
||||
| `--domains` | `URUTAU_DOMAINS` | vazio | lista de domínios do analytics (exatos ou `*.exemplo.com`); vazio acompanha todo domínio que responde 2xx; recomendado quando um backend responde 2xx para qualquer Host |
|
||||
| `--geo-dir` | `URUTAU_GEO_DIR` | `<data-dir>/geo` | diretório das bases DB-IP Lite (cidade e ASN) |
|
||||
| `--geo-update` | `URUTAU_GEO_UPDATE` | `24h` | de quanto em quanto tempo procurar uma base mais nova; `0` desliga o download |
|
||||
| `--peer` | `URUTAU_PEERS` | nenhum | peer `nome=https://url`; repita a flag ou separe a variável por vírgula |
|
||||
| `--peer-token` | `URUTAU_PEER_TOKEN` | vazio | token compartilhado com os peers; prefira a variável ou `URUTAU_PEER_TOKEN_FILE` (uma flag aparece na lista de processos). Por peer: `URUTAU_PEER_TOKEN_<NOME>` |
|
||||
| `--admin-users` | `URUTAU_ADMIN_USERS` | vazio | usuários SSH cujo login bem-sucedido mantém o IP fora da blocklist por 24 h; a imunidade fica desligada se não definido |
|
||||
| `--peer-allow` | `URUTAU_PEER_ALLOW` | vazio | CIDRs de origem autorizados a chamar o export; vazio aceita qualquer origem com o token |
|
||||
| `--trusted-proxy` | `URUTAU_TRUSTED_PROXY` | `127.0.0.0/8,::1` (o compose define `10.250.0.0/24`) | proxies cujo `X-Forwarded-For` é confiável, lido da direita para a esquerda (limite de login, `--peer-allow`) |
|
||||
| `--retention` | `URUTAU_RETENTION` | `168h` | por quanto tempo os dados ficam (1h a 168h) |
|
||||
| `--insecure-no-auth` | nenhuma | desligado | desativa a autenticação; só em bind loopback |
|
||||
|
||||
Validação na inicialização: peers devem ser `nome=https://host` (`http` simples só em loopback), `URUTAU_PEER_TOKEN` deve estar definido e ser diferente de `URUTAU_TOKEN`, os nomes devem ser únicos e não podem ser `all` nem o nome da própria instância, `--retention` deve ser de pelo menos 1h e `URUTAU_TOKEN` e todo token de peer devem ter pelo menos 32 caracteres e cerca de 128 bits de entropia estimada; cada peer precisa de um token de cliente (`URUTAU_PEER_TOKEN_<NOME>` ou o geral `URUTAU_PEER_TOKEN` como reserva), e os nomes de peer não podem colidir nesse nome de variável (salvo `--insecure-no-auth` em endereço loopback).
|
||||
|
||||
```bash
|
||||
export URUTAU_TOKEN=$(openssl rand -base64 48)
|
||||
urutau serve --bind 127.0.0.1:8790 --data-dir ./data \
|
||||
--traefik-log "" --auth-log /var/log/auth.log
|
||||
```
|
||||
|
||||
O daemon registra logs no stderr, salva um snapshot em `SIGTERM` ou `SIGINT` e sai com 0 numa parada limpa.
|
||||
|
||||
## Ruído e monitoramento
|
||||
|
||||
```bash
|
||||
urutau serve --trusted "10.0.0.0/8,203.0.113.7" \
|
||||
--monitor-ua '(?i)uptime-kuma|statuscake'
|
||||
```
|
||||
|
||||
`--trusted` descarta todo evento dessas origens. `--monitor-ua` casa com o User-Agent de requisições benignas (`ok` ou `notfound`) e as conta à parte como "monitoring"; uma requisição que seja `scanner`, `exploit` ou `bruteforce` continua contando como ataque.
|
||||
|
||||
## Geolocalização
|
||||
|
||||
```bash
|
||||
urutau serve --geo-dir /data/geo --geo-update 24h
|
||||
```
|
||||
|
||||
O Urutau baixa as bases DB-IP Lite de cidade e ASN em `--geo-dir` quando faltam ou têm mais de 35 dias, e depois confere a cada `--geo-update` o arquivo do mês corrente. O arquivo é verificado antes de substituir o antigo, e um download que falha nunca interrompe o serviço. Dados por [DB-IP](https://db-ip.com), CC BY 4.0.
|
||||
|
||||
## `urutau doctor`
|
||||
|
||||
Confere a configuração (token, peers, bind), cada fonte de log (legível, tamanho), se o diretório de dados é gravável, as bases de geolocalização e o snapshot. Os status são `ok`, `warn` (uma fonte que ainda não pode ser aberta), `fail` e `off` (desativada). O código de saída é 1 quando algum teste é `fail`, o que o torna utilizável em um healthcheck ou script de deploy.
|
||||
|
||||
```bash
|
||||
urutau doctor
|
||||
docker exec urutau urutau doctor --json
|
||||
```
|
||||
|
||||
`--json` imprime `{"version", "name", "ok", "checks": [{"name", "status", "detail"}], "geo", "state"}`. `geo` informa o diretório, o intervalo de atualização, a atribuição e as datas de build das bases carregadas; `state` informa o snapshot (caminho, tamanho, IPs, domínios e requisições em 7 dias) ou que ainda não existe. Um snapshot ilegível aparece como `warn`.
|
||||
|
||||
## `urutau healthcheck`
|
||||
|
||||
Chama `/api/health` no endereço de bind local e sai com 0 quando responde `{"status":"ok"}`, 1 caso contrário. É o `HEALTHCHECK` do container, e por isso a imagem não tem `curl`. Aceita as mesmas flags do `serve` (para um `--bind` diferente do padrão).
|
||||
|
||||
## `urutau version`
|
||||
|
||||
Imprime `urutau <versão>`. `--version` e `-v` também funcionam.
|
||||
@@ -0,0 +1,74 @@
|
||||
<p align="center"><a href="../../README.pt-BR.md">◂ Voltar ao README</a></p>
|
||||
|
||||
# Configuração
|
||||
|
||||
O Urutau não tem arquivo de configuração. Tudo é uma flag com padrão em variável de ambiente `URUTAU_*` ([cli.md](cli.md)), o que combina com um container. Os segredos são apenas variáveis de ambiente.
|
||||
|
||||
## Segredos
|
||||
|
||||
| Variável | Significado |
|
||||
|---|---|
|
||||
| `URUTAU_TOKEN` | **Obrigatória.** Token de acesso do dashboard e da API: no mínimo 32 caracteres e cerca de 128 bits de entropia estimada (comprimento vezes entropia de Shannon; tokens periódicos ou sequenciais são recusados). Gere um com `openssl rand -base64 48` (`openssl rand -hex 32` também serve; `-hex 16` é recusado pela estimativa de entropia). |
|
||||
| `URUTAU_TOKEN_FILE` | Caminho de um arquivo com o token (espaços nas pontas são removidos), no lugar da variável. A variável vence quando as duas existem. |
|
||||
| `URUTAU_PEER_TOKEN` | Opcional. O token de servidor desta instância: o único que o `GET /api/v1/peer/export` dela aceita, e não abre mais nada. Mesmas regras de força do `URUTAU_TOKEN` (32+ caracteres, cerca de 128 bits de entropia estimada, sem padrão periódico nem sequencial), e deve ser diferente dele. Quando esta instância é um hub, também é o token de cliente de reserva enviado aos peers que não têm o seu. |
|
||||
| `URUTAU_PEER_TOKEN_FILE` | Caminho de um arquivo com o token de peer geral. |
|
||||
| `URUTAU_PEER_TOKEN_<NOME>` e `..._<NOME>_FILE` | A credencial de cliente que um hub envia àquele peer; deve ser igual ao `URUTAU_PEER_TOKEN` do próprio peer. `<NOME>` é o nome do peer em maiúsculas, com todo caractere que não seja letra ou dígito virando `_` (`my-peer` vira `MY_PEER`). Ela **não** abre o export local. Dois nomes de peer que viram a mesma variável (`my-peer` e `my_peer`) são recusados. Um hub com um peer sem token para ele se recusa a iniciar. |
|
||||
|
||||
Guarde os dois no `.env` (nunca versionado) ou no cofre de segredos do seu orquestrador.
|
||||
|
||||
## Ajustes
|
||||
|
||||
| Variável | Padrão | Significado |
|
||||
|---|---|---|
|
||||
| `URUTAU_BIND` | `0.0.0.0:8790` | endereço de escuta |
|
||||
| `URUTAU_NAME` | hostname do container | nome exibido no dashboard e usado pelo hub |
|
||||
| `URUTAU_DATA_DIR` | `/data` | onde o snapshot `urutau-state.gob` é gravado |
|
||||
| `URUTAU_TRAEFIK_LOG` | `/data/coolify/proxy/access.log` | access log JSON do Traefik, vazio desativa |
|
||||
| `URUTAU_AUTH_LOG` | `/var/log/auth.log` | log do sshd, vazio desativa |
|
||||
| `URUTAU_FAIL2BAN_LOG` | `/var/log/fail2ban.log` | log do fail2ban, vazio desativa |
|
||||
| `URUTAU_TRUSTED` | vazio | CIDRs ou IPs confiáveis, separados por vírgula; os eventos deles são descartados por completo |
|
||||
| `URUTAU_IGNORE` | `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` | mesmo efeito, mantido como o alias que traz as faixas privadas como padrão |
|
||||
| `URUTAU_MONITOR_UA` | `(?i)^(Uptime-Kuma/\|Beszel\|Coolify\|kube-probe/\|Go-http-client/.*healthcheck)` | expressão regular de User-Agents de monitoramento |
|
||||
| `URUTAU_GEO_DIR` | `<data-dir>/geo` | onde ficam as bases DB-IP Lite |
|
||||
| `URUTAU_GEO_UPDATE` | `24h` | intervalo entre buscas por uma base mais nova; `0` desativa o download |
|
||||
| `URUTAU_PEER_ALLOW` | vazio | CIDRs autorizados a chamar o export; vazio aceita qualquer origem que tenha o token |
|
||||
| `URUTAU_TRUSTED_PROXY` | `127.0.0.0/8,::1` (o compose define `10.250.0.0/24`) | proxies reversos cujo `X-Forwarded-For` é confiável (lido da direita para a esquerda); usado no limite de tentativas de login e em `URUTAU_PEER_ALLOW` |
|
||||
| `URUTAU_DOMAINS` | vazio | lista de domínios permitidos no analytics, nomes exatos ou `*.exemplo.com`; vazio acompanha todo domínio que responde 2xx; recomendado, na prática obrigatório, quando algum backend responde 2xx para qualquer Host (catch-all ou wildcard), senão Hosts aleatórios podem ocupar as 24 vagas de domínio |
|
||||
| `URUTAU_MONITOR_FROM` | vazio | CIDRs de onde os monitores realmente vêm; quando definido, o User-Agent de monitoramento só vale vindo deles |
|
||||
| `URUTAU_ADMIN_USERS` | vazio | usuários SSH cujo login bem-sucedido mantém o IP fora da blocklist por 24 h após o último login (um sinal forte posterior anula); a imunidade fica desligada a menos que seja definido |
|
||||
| `URUTAU_PEERS` | vazio | peers a agregar, `nome=https://url` separados por vírgula |
|
||||
| `URUTAU_RETENTION` | `168h` | retenção como duração do Go, de `1h` a `168h` |
|
||||
| `GOMEMLIMIT` | limite suave de 160 MiB | limite de memória padrão do Go; defina para sobrescrever |
|
||||
| `TZ` | UTC | fuso dos timestamps do `fail2ban.log`, que não trazem fuso |
|
||||
|
||||
Na imagem do container os três caminhos de log têm como padrão `/logs/traefik/access.log`, `/logs/host/auth.log` e `/logs/host/fail2ban.log` (o compose monta os logs do host ali). O compose acrescenta `URUTAU_VERSION` (tag da imagem), `URUTAU_IMAGE` e `URUTAU_PUBLISH` (endereço e porta no host), veja o `.env.example`.
|
||||
|
||||
## Ruído e monitoramento
|
||||
|
||||
- **Cabeçalhos do Traefik.** Registre `Sec-Fetch-Site`, `Sec-Fetch-Dest` e `Referer` para o Urutau distinguir uma página que embute seu site de uma visita real: `--accesslog.fields.headers.names.Sec-Fetch-Site=keep`, `--accesslog.fields.headers.names.Sec-Fetch-Dest=keep` e `--accesslog.fields.headers.names.Referer=keep`. Uma requisição enquadrada por outra página (`Sec-Fetch-Site` `cross-site` ou `same-site`, ou `Sec-Fetch-Dest` de subrecurso como `image` ou `script`) aparece na linha do tempo e cria registro de IP como qualquer outra, mas pesa 0,25 por evento, com no máximo 30 pontos por IP vindos delas (abaixo do limiar hostil), e nunca conta como sinal forte. Com User-Agent de ferramenta de ataque os cabeçalhos são ignorados.
|
||||
- **Origens confiáveis** (`URUTAU_TRUSTED`): sua própria rede, escritórios, monitores e outros servidores. `URUTAU_IGNORE` já descarta loopback e as faixas privadas por padrão, então o tráfego interno nunca pontua. Acrescente os IPs públicos dos seus monitores. Se o proxy informa o gateway do Docker como cliente, esse endereço é privado e já é descartado; corrija o proxy para repassar o endereço real do cliente.
|
||||
- **User-Agent de monitoramento** (`URUTAU_MONITOR_UA`): uma expressão regular do Go. Uma requisição que casa e é benigna é contada como "monitoring" em vez de tráfego. Se a requisição for `scanner`, `exploit` ou `bruteforce`, conta como ataque: um User-Agent é trivial de forjar, então nunca concede imunidade.
|
||||
- **De onde vêm os monitores** (`URUTAU_MONITOR_FROM`): CIDRs dos seus monitores. Quando definido, o User-Agent de monitoramento só vale vindo dessas redes e requisições benignas (`ok` ou `notfound`) são filtradas. Quando vazio, só respostas `ok` são filtradas: um `notfound` com User-Agent de monitor ainda conta, porque qualquer um pode enviar esse cabeçalho.
|
||||
|
||||
## Geolocalização e analytics
|
||||
|
||||
País, cidade e ASN vêm das bases DB-IP Lite (cidade e ASN), que o Urutau baixa e atualiza sozinho em `URUTAU_GEO_DIR`. Sem elas (por exemplo num host isolado da internet) o dashboard funciona e os campos geográficos ficam vazios; para operar offline, coloque os arquivos `dbip-city-lite-AAAA-MM.mmdb` e `dbip-asn-lite-AAAA-MM.mmdb` nesse diretório e defina `URUTAU_GEO_UPDATE=0`. As bases são licenciadas CC BY 4.0: mantenha a atribuição (o rodapé do dashboard e o README já a trazem).
|
||||
|
||||
A aba Tráfego não precisa de ajuste. `URUTAU_DOMAINS` restringe quais domínios ela acompanha (nomes exatos ou `*.exemplo.com`); um domínio só ganha vaga depois de uma resposta 2xx e domínios inativos são podados, então `Host` forjados não enchem o analytics. O top de páginas normaliza segmentos de caminho com cara de token (ids, hashes, strings aleatórias longas) para `:id`. Ela usa o log do Traefik, conta visitantes únicos por um hash com sal diário e nunca persiste o endereço IP de um visitante legítimo. Veja o [SECURITY.pt-BR.md](../../SECURITY.pt-BR.md).
|
||||
|
||||
## Peers (modo hub)
|
||||
|
||||
```
|
||||
URUTAU_PEERS=web1=https://urutau.web1.example,db1=https://urutau.db1.example
|
||||
URUTAU_PEER_TOKEN=<segredo compartilhado>
|
||||
```
|
||||
|
||||
Em cada peer, defina o mesmo `URUTAU_PEER_TOKEN`. O hub chama apenas `GET /api/v1/peer/export` (uma vez por intervalo, `1h`, `24h` e `7d`, a cada 15 segundos). As URLs dos peers devem ser `https` (`http` simples só é aceito em loopback): o token de peer viaja em um cabeçalho. Para restringir quem pode chamar o export, defina `URUTAU_PEER_ALLOW` no peer com o endereço do hub. Os nomes dos peers devem ser únicos e não podem ser `all` nem o nome do próprio hub.
|
||||
|
||||
## Snapshot e retenção
|
||||
|
||||
O arquivo de snapshot guarda o estado agregado e as posições dos logs. Monte `URUTAU_DATA_DIR` em um volume para mantê-lo entre reinícios. Apague o arquivo para começar do zero (os logs rotacionados serão lidos de novo). A retenção limita por quanto tempo um IP fica, no máximo 168 horas; os intervalos do dashboard são `1h`, `24h` e `7d`.
|
||||
|
||||
## Autenticação e exposição
|
||||
|
||||
O bind padrão é `0.0.0.0` porque o container fica atrás de um proxy. Fora de um container, faça bind em `127.0.0.1` ou coloque um proxy reverso com TLS na frente. `--insecure-no-auth` existe só para testes locais e é recusado em binds que não sejam loopback.
|
||||
@@ -0,0 +1,161 @@
|
||||
<p align="center"><a href="../../README.pt-BR.md">◂ Voltar ao README</a></p>
|
||||
|
||||
# Docker
|
||||
|
||||
O Urutau é distribuído como uma imagem de container pequena (`linux/amd64` e `linux/arm64`, cerca de 28 MB, sem `curl`), definida no [`docker-compose.yml`](../../docker-compose.yml). Ele só precisa ler arquivos de log e gravar um snapshot.
|
||||
|
||||
```
|
||||
host container urutau
|
||||
/data/coolify/proxy/logs ── :ro ────────────► /logs/traefik (access.log do Traefik)
|
||||
/var/log/urutau ── :ro ────────────► /logs/host (auth.log, fail2ban.log)
|
||||
volume urutau-data ── leitura e escrita ► /data (snapshot, bases de geolocalização)
|
||||
```
|
||||
|
||||
O compose segue esse layout. O diretório de logs do Traefik é montado fora de `/data` para não colidir com o volume do snapshot. Só o diretório `logs` dedicado do proxy é montado, nunca o `/data/coolify/proxy` inteiro (que guarda `acme.json` e a configuração dinâmica).
|
||||
|
||||
A imagem roda com o usuário sem privilégios `urutau` (uid 10001) em Alpine. O `HEALTHCHECK` é o próprio binário (`urutau healthcheck`, que pergunta `/api/health` ao daemon local), então não há `curl` na imagem. O compose define `mem_limit: 256m` e `cpus: 0.5`, sistema de arquivos raiz somente leitura, `cap_drop: [ALL]` e `no-new-privileges`, e repassa do `.env` ao container: `URUTAU_TOKEN`, `URUTAU_NAME`, `URUTAU_TRUSTED`, `URUTAU_PEERS`, `URUTAU_PEER_TOKEN`, `URUTAU_PEER_ALLOW`, `URUTAU_TRUSTED_PROXY`, `URUTAU_DOMAINS`, `URUTAU_MONITOR_FROM`, `URUTAU_ADMIN_USERS`, `URUTAU_GEO_UPDATE` e `TZ`. Para definir qualquer outra variável `URUTAU_*` (`URUTAU_MONITOR_UA`, `URUTAU_RETENTION`, `URUTAU_TOKEN_FILE`, tokens por peer, ...), acrescente-a ao bloco `environment`.
|
||||
|
||||
## Início rápido
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
sed -i "s|^URUTAU_TOKEN=.*|URUTAU_TOKEN=$(openssl rand -base64 48 | tr -d '\n')|" .env
|
||||
docker compose pull && docker compose up -d # imagem publicada
|
||||
# ou, construindo localmente:
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
O token precisa de pelo menos 32 caracteres e cerca de 128 bits de entropia estimada (comprimento vezes entropia de Shannon; tokens periódicos ou sequenciais são recusados). `openssl rand -base64 48` é o recomendado (`openssl rand -hex 32` também serve). Para manter o segredo fora do ambiente, monte um arquivo e defina `URUTAU_TOKEN_FILE` (o mesmo vale para `URUTAU_PEER_TOKEN_FILE`).
|
||||
|
||||
O dashboard sobe em `http://127.0.0.1:8790` por padrão (`URUTAU_PUBLISH` no `.env` muda o endereço e a porta). Confira as fontes:
|
||||
|
||||
```bash
|
||||
docker compose exec urutau urutau doctor
|
||||
docker compose logs urutau
|
||||
```
|
||||
|
||||
## Lendo os logs
|
||||
|
||||
- **Traefik:** o access log precisa ser JSON e gravado em um diretório dedicado. Na configuração estática do Traefik defina `--accesslog=true`, `--accesslog.format=json` e `--accesslog.filepath=/traefik/logs/access.log`. No Coolify o diretório do host `/data/coolify/proxy` é `/traefik` dentro do container do proxy, então esse arquivo aparece no host como `/data/coolify/proxy/logs/access.log`, que é o que o compose monta. Na interface do Coolify abra Servers, o servidor, Proxy, e acrescente essas três linhas à lista `command` da configuração do proxy, depois reinicie o proxy. No mesmo lugar acrescente os cabeçalhos que o Urutau usa para distinguir visitas reais de requisições enquadradas: `--accesslog.fields.headers.names.Sec-Fetch-Site=keep`, `--accesslog.fields.headers.names.Sec-Fetch-Dest=keep` e `--accesslog.fields.headers.names.Referer=keep`.
|
||||
- **auth.log e fail2ban.log:** o diretório dedicado do host `/var/log/urutau` é montado somente leitura em `/logs/host` como diretório, porque o logrotate recria esses arquivos por renomeação e uma montagem de arquivo único continuaria seguindo o inode antigo. Prepare-o como em [Preparando os logs do host](#preparando-os-logs-do-host). Os arquivos pertencem a `syslog:adm`, então o container adiciona o grupo `adm` do host (GID 4) com `group_add: ["4"]`, como o compose faz. Nada mais do `/var/log` do host é exposto.
|
||||
- **Somente leitura:** todas as montagens de log são `:ro`. O Urutau nunca escreve em um log.
|
||||
- **Rotação:** o seguidor reabre o arquivo quando o logrotate o substitui ou trunca.
|
||||
|
||||
## Preparando os logs do host
|
||||
|
||||
O Urutau lê um diretório dedicado, `/var/log/urutau`, e não o `/var/log` inteiro. Prepare-o uma vez em cada servidor (o `/var/log/auth.log` original continua intacto):
|
||||
|
||||
```bash
|
||||
sudo install -d -m 0750 -o syslog -g adm /var/log/urutau
|
||||
|
||||
# rsyslog: copia as linhas do sshd para um arquivo próprio
|
||||
sudo tee /etc/rsyslog.d/40-urutau.conf >/dev/null <<'EOF'
|
||||
if $programname == 'sshd' or $programname == 'sshd-session' then {
|
||||
action(type="omfile" file="/var/log/urutau/auth.log" template="RSYSLOG_FileFormat"
|
||||
fileOwner="syslog" fileGroup="adm" fileCreateMode="0640")
|
||||
}
|
||||
EOF
|
||||
sudo systemctl restart rsyslog
|
||||
|
||||
# fail2ban: grava o log dele ali também
|
||||
sudo tee /etc/fail2ban/fail2ban.d/urutau.local >/dev/null <<'EOF'
|
||||
[Definition]
|
||||
logtarget = /var/log/urutau/fail2ban.log
|
||||
EOF
|
||||
sudo systemctl restart fail2ban
|
||||
|
||||
# logrotate para os dois arquivos
|
||||
sudo tee /etc/logrotate.d/urutau >/dev/null <<'EOF'
|
||||
/var/log/urutau/*.log {
|
||||
weekly
|
||||
rotate 4
|
||||
compress
|
||||
delaycompress
|
||||
missingok
|
||||
notifempty
|
||||
create 0640 syslog adm
|
||||
postrotate
|
||||
systemctl kill -s HUP rsyslog.service 2>/dev/null || true
|
||||
fail2ban-client flushlogs >/dev/null 2>&1 || true
|
||||
endscript
|
||||
}
|
||||
EOF
|
||||
```
|
||||
|
||||
O `RSYSLOG_FileFormat` grava timestamps ISO, que é o formato que o Urutau interpreta. Confira o GID do `adm` com `getent group adm`. Limitação conhecida: um usuário local do host pode forjar linhas do sshd com `logger -t sshd`. O Urutau limita o dano (o nível hostil exige sinal forte e a imunidade de admin dura 24 horas), mas quem tem shell no host já está dentro do seu limite de confiança.
|
||||
|
||||
## Exemplo: Coolify
|
||||
|
||||
Crie um recurso Docker Compose no servidor Coolify cujos logs você quer observar, com este compose:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
urutau:
|
||||
image: git.lucasrguerra.dev.br/ciberfauna/urutau:latest
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
URUTAU_TOKEN: ${URUTAU_TOKEN}
|
||||
URUTAU_NAME: server-1
|
||||
URUTAU_AUTH_LOG: /logs/host/auth.log
|
||||
URUTAU_FAIL2BAN_LOG: /logs/host/fail2ban.log
|
||||
URUTAU_TRUSTED_PROXY: 10.250.0.0/24
|
||||
TZ: UTC # o fuso do host (fail2ban.log não tem fuso)
|
||||
group_add: ["4"] # adm: lê auth.log e fail2ban.log
|
||||
read_only: true
|
||||
cap_drop: [ALL]
|
||||
security_opt: ["no-new-privileges:true"]
|
||||
volumes:
|
||||
- /data/coolify/proxy/logs:/logs/traefik:ro
|
||||
- /var/log/urutau:/logs/host:ro
|
||||
- urutau-data:/data
|
||||
networks: [urutau-edge]
|
||||
labels:
|
||||
- traefik.enable=true
|
||||
- traefik.docker.network=urutau-edge
|
||||
- traefik.http.routers.urutau.rule=Host(`urutau.example.com`)
|
||||
- traefik.http.routers.urutau.entrypoints=https
|
||||
- traefik.http.routers.urutau.tls=true
|
||||
- traefik.http.routers.urutau.tls.certresolver=letsencrypt
|
||||
- traefik.http.services.urutau.loadbalancer.server.port=8790
|
||||
|
||||
volumes:
|
||||
urutau-data:
|
||||
|
||||
networks:
|
||||
urutau-edge:
|
||||
external: true
|
||||
```
|
||||
|
||||
Notas:
|
||||
|
||||
- **Uma rede compartilhada só com o Traefik.** `--trusted-proxy` tem como padrão só o loopback, então por padrão o `X-Forwarded-For` é ignorado. O compose cria a rede `urutau-edge` (`10.250.0.0/24`) e define `URUTAU_TRUSTED_PROXY=10.250.0.0/24`, então só o proxy dessa rede é acreditado (qualquer outro container ali poderia forjar IPs de cliente, então deixe só o proxy). Conecte o proxy uma vez: `docker network connect urutau-edge coolify-proxy`. Em um compose avulso como o exemplo abaixo, declare a rede do mesmo jeito e defina a variável. O label `traefik.docker.network` diz ao Traefik para usá-la. Adapte os nomes do entrypoint e do certresolver ao seu proxy.
|
||||
- A imagem já aponta as fontes para `/logs/traefik/access.log`, `/logs/host/auth.log` e `/logs/host/fail2ban.log` (seus padrões `URUTAU_*_LOG`). Os padrões do próprio binário (`/data/coolify/proxy/access.log`, `/var/log/...`) servem para rodá-lo direto no host.
|
||||
- Defina `URUTAU_TOKEN` no ambiente do Coolify. Atrás do proxy o dashboard é servido por HTTPS, então o cookie de sessão é `Secure`.
|
||||
- Não publique a porta 8790 no host quando o proxy já a roteia.
|
||||
- Se o access log do Traefik não existir ou não for JSON, a fonte fica em zero linhas ou `malformed` cresce.
|
||||
- O Urutau não precisa de `tmpfs`: o sistema de arquivos raiz é somente leitura e seu único destino de escrita é o volume `/data`.
|
||||
|
||||
## Base de geolocalização
|
||||
|
||||
As bases DB-IP Lite são baixadas no volume de dados (`/data/geo`) na primeira inicialização, então o container precisa de HTTPS de saída para `download.db-ip.com` uma vez, e depois uma vez por mês. Se o host não alcança a internet, copie os dois arquivos `.mmdb` para o volume e defina `URUTAU_GEO_UPDATE=0` ([configuracao.md](configuracao.md)). Dados por [DB-IP](https://db-ip.com), CC BY 4.0.
|
||||
|
||||
## Federação entre servidores
|
||||
|
||||
Rode um Urutau por servidor, cada um com seu `URUTAU_NAME`. Toda instância consultada define o próprio token de servidor, `URUTAU_PEER_TOKEN` (ou `_FILE`), e esse é o único token que o export dela aceita. O hub guarda uma credencial de cliente para cada peer, igual ao token de servidor desse peer: um `URUTAU_PEER_TOKEN_<NOME>` por peer (o nome do peer em maiúsculas, outros caracteres viram `_`, por exemplo `URUTAU_PEER_TOKEN_SERVER_2`), com o `URUTAU_PEER_TOKEN` geral do hub como reserva. Uma credencial de cliente não abre o export do próprio hub, e nomes de peer que viram a mesma variável (`my-peer` e `my_peer`) são recusados. Os tokens precisam de 32+ caracteres e cerca de 128 bits de entropia, diferentes de `URUTAU_TOKEN` (`openssl rand -base64 48`), e podem vir de `..._FILE`. No servidor que hospeda o dashboard compartilhado (o hub) acrescente:
|
||||
|
||||
```yaml
|
||||
environment:
|
||||
URUTAU_PEERS: server-2=https://urutau.server2.example.com,server-3=https://urutau.server3.example.com
|
||||
URUTAU_PEER_TOKEN_SERVER_2: ${TOKEN_FOR_SERVER_2}
|
||||
URUTAU_PEER_TOKEN_SERVER_3: ${TOKEN_FOR_SERVER_3}
|
||||
```
|
||||
|
||||
O hub chama apenas `GET /api/v1/peer/export` em cada peer (três intervalos a cada 15 segundos) com o token daquele peer, que não abre mais nada no peer e é recusado em `http` simples fora de loopback. Defina `URUTAU_PEER_ALLOW` em um peer com o endereço do hub para restringir quem pode chamar o export. Cada peer mantém seu próprio token de login para o próprio dashboard.
|
||||
|
||||
## Endurecimento
|
||||
|
||||
`read_only: true`, `cap_drop: [ALL]`, `no-new-privileges` e montagens de log somente leitura deixam o container capaz de uma coisa só: ler os logs e gravar seu snapshot. Mantenha a imagem em uma tag fixa (`X.Y.Z`) em produção e `latest` só onde você aceita atualizações.
|
||||
|
||||
## Saúde e desligamento
|
||||
|
||||
`GET /api/health` responde `{"status":"ok"}` sem autenticação. `urutau healthcheck` o chama localmente e sai com 0 quando o daemon está saudável; a imagem o usa como `HEALTHCHECK`. Em `SIGTERM` o daemon para de aceitar requisições, salva o snapshot e sai.
|
||||
@@ -0,0 +1,53 @@
|
||||
<p align="center"><a href="../../README.pt-BR.md">◂ Voltar ao README</a></p>
|
||||
|
||||
# Interface
|
||||
|
||||
O dashboard é embutido no binário: HTML, CSS e JavaScript puros, sem etapa de build e sem requisição externa (fontes, scripts e estilos são todos servidos pelo Urutau, o que a Content-Security-Policy garante). Segue o tema claro ou escuro do sistema, pode ser alternado à mão e fala inglês ou português (botão no cabeçalho; a escolha fica guardada no navegador).
|
||||
|
||||
## Login
|
||||
|
||||
Abra o endereço da instância. Sem sessão você é enviado a `/login`: cole o `URUTAU_TOKEN`. A sessão dura 12 horas (cookie `urutau_session`, `HttpOnly`, `SameSite=Strict`) e é revogável: ela guarda um id aleatório em memória, **Sair** a revoga (e fecha o stream ao vivo dela), e um reinício do daemon invalida todas as sessões. Login e logout rejeitam requisições cross-site. Após 5 falhas do mesmo endereço (IPv6 contado por /64) em 10 minutos o login responde 429, e um token correto ainda é aceito, mas com 1 segundo de atraso, para que o limitador não tranque o dono do lado de fora. Bearer tokens errados na API também contam como falha (o endereço é o do cliente real atrás dos proxies de `--trusted-proxy`). **Sair** encerra a sessão.
|
||||
|
||||
## Cabeçalho
|
||||
|
||||
- Um indicador ao vivo mostrando se o stream de eventos (SSE) está conectado (uma instância atende no máximo 20 clientes do stream ao mesmo tempo).
|
||||
- O seletor de **host**: `all`, esta instância e cada peer de um hub.
|
||||
- O seletor de **intervalo**: `1h`, `24h` ou `7d`.
|
||||
- Botões de idioma, tema e sair.
|
||||
|
||||
## Aba Ameaças
|
||||
|
||||
- **KPIs:** requisições, eventos maliciosos, IPs hostis, IPs suspeitos, bans e o contador "monitoring" (requisições benignas de User-Agents de monitor, fora dos números de tráfego).
|
||||
- **Linha do tempo:** contadores empilhados por categoria no intervalo escolhido.
|
||||
- **IPs:** uma tabela com pontuação, nível (`hostile`, `suspicious`, `low`), categorias, hosts, DNS reverso, país, cidade e ASN, último evento e estado de ban. Tem busca (IP ou DNS reverso), filtro de nível, filtro "só banidos", ordenação por IP, pontuação ou último evento e paginação. Clique numa linha para o painel de detalhe: primeiro e último evento, contagem por categoria, caminhos de exemplo, User-Agents (interpretados em navegador, SO, dispositivo, bot ou ferramenta de ataque), domínios, usuários e jails.
|
||||
- **Feed ao vivo:** os últimos eventos conforme chegam. Os campos dos logs são mostrados como texto, nunca como marcação.
|
||||
- **Listas de top:** caminhos atacados, domínios, User-Agents e usuários visados.
|
||||
- **Blocklist:** escolha uma pontuação mínima (padrão 50), copie a lista ou baixe. Ela só lista endereços hostis e globalmente roteáveis (nunca faixas de `--ignore` ou `--trusted`, nunca um IP com login SSH bem-sucedido); o IPv6 aparece como o /64, escrito `x:x:x:x::/64`.
|
||||
- **Mapa:** um mapa-múndi dos países de origem da atividade hostil.
|
||||
- **Hosts e fontes:** cada instância com seu estado (online, latência, versão) e cada fonte de log com seu estado (`following`, `waiting`, `backfill`, `error`), linhas lidas, linhas malformadas e último evento. Os caminhos dos arquivos não são mostrados.
|
||||
|
||||
## Aba Tráfego
|
||||
|
||||
Web analytics amigável à privacidade para o tráfego legítimo, construído do mesmo log do Traefik e substituindo o analytics do proxy: visitantes únicos, páginas, referrers, países, navegadores, sistemas operacionais e dispositivos, latência de resposta (p50 e p95), bytes enviados e um mapa-múndi dos países dos visitantes. Visitantes únicos são contados por um hash com sal diário; o IP de um visitante legítimo nunca é gravado. Veja o [SECURITY.pt-BR.md](../../SECURITY.pt-BR.md).
|
||||
|
||||
## Atribuição
|
||||
|
||||
Dados de geolocalização de IP por [DB-IP](https://db-ip.com), licenciados sob [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). O crédito também aparece no rodapé do dashboard.
|
||||
|
||||
## Rotas HTTP
|
||||
|
||||
| Rota | Auth | Finalidade |
|
||||
|---|---|---|
|
||||
| `GET /api/health` | nenhuma | `{"status":"ok"}` |
|
||||
| `GET /login`, `POST /login`, `POST /logout` | nenhuma | sessão |
|
||||
| `GET /` e os arquivos estáticos | sessão | o dashboard |
|
||||
| `GET /api/v1/summary` | sessão ou bearer | tudo o que o dashboard mostra. Query: `range` (`1h`, `24h`, `7d`), `host` (`all`, um nome) |
|
||||
| `GET /api/v1/traffic` | sessão ou bearer | web analytics do tráfego legítimo. Query: `range`, `domain` (`all` ou um domínio), `host`. Retorna visitantes, páginas, requisições, bots, bytes, classes de status, `p50_ms`, `p95_ms`, linha do tempo, top de páginas, referrers, países, cidades, navegadores, sistemas operacionais, dispositivos e nomes de bots |
|
||||
| `GET /api/v1/peer/export` | só token de peer | federação: `{"v":1,"summary":...,"traffic":{...}}` com os 500 IPs principais e seus detalhes. Query: `range` (`1h`, `24h`, `7d`). Cache de 5 s. 404 sem token de peer, 401 para `URUTAU_TOKEN`, 403 de origem fora de `--peer-allow` |
|
||||
| `GET /api/v1/ips` | sessão ou bearer | tabela de IPs. Query: `range`, `host`, `min_score`, `level`, `q`, `banned=1`, `sort` (`score`, `last`, `first`, `events`, `ip`), `order=asc`, `per` (1 a 200, padrão 50), `page` |
|
||||
| `GET /api/v1/ip/{ip}` | sessão ou bearer | detalhe de um IP, mesclado com os exports dos peers |
|
||||
| `GET /api/v1/events/stream` | sessão ou bearer | Server-Sent Events, evento `ev`, um ping a cada 20 s |
|
||||
| `GET /api/v1/blocklist.txt` | sessão ou bearer | um IP por linha. Query: `min_score` (padrão 50), `range` (padrão `7d`), `host`, `family` (`4`, `6`; padrão ambos; `4` serve ao `ipset hash:ip`), `download=1` |
|
||||
| `GET /api/v1/blocklist.json` | sessão ou bearer | `{"generated","min_score","count","ips":[{"ip","score","last","hosts"}]}`; o `ip` de uma entrada IPv6 é um prefixo `/64` |
|
||||
|
||||
Clientes da API enviam `Authorization: Bearer <URUTAU_TOKEN>`. O token de peer só é aceito por `/api/v1/peer/export`; todas as outras rotas respondem 403 a ele.
|
||||
@@ -0,0 +1,46 @@
|
||||
<p align="center"><a href="../../README.pt-BR.md">◂ Voltar ao README</a></p>
|
||||
|
||||
# Suporte
|
||||
|
||||
[English](../support.md) · **Português**
|
||||
|
||||
O Urutau é distribuído como uma única imagem de container. A forma mais rápida de conseguir ajuda é abrir uma issue no repositório Gitea.
|
||||
|
||||
## Antes de abrir uma issue
|
||||
|
||||
1. Rode `docker exec urutau urutau doctor --json` (ou `urutau doctor --json` no binário do host) e anexe a saída.
|
||||
2. Confirme a versão com `urutau version`.
|
||||
3. Revise [`configuracao.md`](configuracao.md), [`docker.md`](docker.md) e [`arquitetura.md`](arquitetura.md), principalmente as montagens de log e o grupo `adm`.
|
||||
|
||||
## O que incluir
|
||||
|
||||
- SO do host, arquitetura (`uname -m`) e versão do Urutau ou tag da imagem.
|
||||
- O `docker-compose.yml` (ou a linha de comando) em uso, sem tokens.
|
||||
- Os logs do container: `docker compose logs urutau`.
|
||||
- O estado de cada fonte no dashboard (`following`, `waiting`, `backfill`, `error`), com as contagens de linhas e malformadas.
|
||||
- Uma ou duas linhas de log de exemplo classificadas errado ou rejeitadas, com os IPs ocultados.
|
||||
|
||||
Não anexe tokens, IPs reais de clientes nem logs de sistemas que você não está autorizado a tratar.
|
||||
|
||||
## Questões de segurança
|
||||
|
||||
Não inclua detalhes de exploração numa issue pública. Siga o [SECURITY.pt-BR.md](../../SECURITY.pt-BR.md) e peça um canal de comunicação privado.
|
||||
|
||||
## Situações comuns
|
||||
|
||||
| Sintoma | O que checar |
|
||||
|---|---|
|
||||
| O container sai ao iniciar com `URUTAU_TOKEN is required` | Defina `URUTAU_TOKEN` com no mínimo 32 caracteres e cerca de 128 bits de entropia estimada (comprimento vezes entropia de Shannon; tokens periódicos ou sequenciais são recusados) (`openssl rand -base64 48`), ou aponte `URUTAU_TOKEN_FILE` para um arquivo que o contenha |
|
||||
| Uma fonte fica em `waiting` | O arquivo não existe nesse caminho dentro do container; confira a montagem e o caminho `URUTAU_*_LOG` |
|
||||
| Uma fonte mostra `error` com `permission denied` | Adicione o grupo `adm` do host com `group_add: ["4"]` (`getent group adm`) e monte o arquivo com `:ro` |
|
||||
| A fonte do Traefik tem muitas linhas malformadas | O access log não é JSON; defina `accessLog.format: json` no Traefik |
|
||||
| Linhas são contadas mas nada aparece | A origem está em `URUTAU_TRUSTED` ou `URUTAU_IGNORE` (as faixas privadas são descartadas por padrão), ou a requisição é de um User-Agent de monitoramento |
|
||||
| Todos os acessos vêm de um endereço interno | O proxy esconde o cliente real; repasse o endereço do cliente ao Traefik |
|
||||
| Os horários do fail2ban estão deslocados em horas | O `fail2ban.log` não tem fuso; defina `TZ` com o fuso do host |
|
||||
| As contagens parecem duplicadas após um reinício | O snapshot não foi salvo ou foi perdido; monte `/data` em um volume |
|
||||
| O dashboard fica inacessível de outro host | Ele faz bind em `127.0.0.1` via `URUTAU_PUBLISH`; confira o proxy reverso |
|
||||
| Um hub se recusa a iniciar com `has no token` | Todo peer precisa de um token: defina `URUTAU_PEER_TOKEN` ou `URUTAU_PEER_TOKEN_<NOME>` (o nome do peer em maiúsculas, outros caracteres como `_`) |
|
||||
| O login responde 429 | Falhas demais daquele endereço; espere a janela (10 minutos) ou tente depois, o token correto ainda entra após 1 segundo de atraso |
|
||||
| A fonte do Traefik fica em `waiting` no Coolify | O Traefik não está gravando `/traefik/logs/access.log`; veja a seção do Coolify em [docker.md](docker.md) |
|
||||
| Um peer aparece offline | URL ou `URUTAU_PEER_TOKEN` errados, ou o peer não é alcançável pelo hub; o erro aparece no cartão do host |
|
||||
| `--insecure-no-auth` é recusado | Só funciona em bind loopback; use um token |
|
||||
@@ -0,0 +1,46 @@
|
||||
<p align="center"><a href="../README.md">◂ Back to README</a></p>
|
||||
|
||||
# Support
|
||||
|
||||
**English** · [Português](pt-BR/suporte.md)
|
||||
|
||||
Urutau is distributed as a single container image. The fastest way to get help is opening an issue in the Gitea repository.
|
||||
|
||||
## Before opening an issue
|
||||
|
||||
1. Run `docker exec urutau urutau doctor --json` (or `urutau doctor --json` on the host binary) and attach the output.
|
||||
2. Confirm the version with `urutau version`.
|
||||
3. Review [`configuration.md`](configuration.md), [`docker.md`](docker.md) and [`architecture.md`](architecture.md), especially the log mounts and the `adm` group.
|
||||
|
||||
## What to include
|
||||
|
||||
- Host OS, architecture (`uname -m`) and Urutau version or image tag.
|
||||
- The `docker-compose.yml` (or the command line) in use, without tokens.
|
||||
- The container logs: `docker compose logs urutau`.
|
||||
- The state of each source on the dashboard (`following`, `waiting`, `backfill`, `error`), with the lines and malformed counts.
|
||||
- One or two example log lines that are misclassified or rejected, with IPs redacted.
|
||||
|
||||
Do not attach tokens, real client IPs or logs of systems you are not authorized to handle.
|
||||
|
||||
## Security issues
|
||||
|
||||
Do not include exploit details in a public issue. Follow [SECURITY.md](../SECURITY.md) and request a private communication channel.
|
||||
|
||||
## Common situations
|
||||
|
||||
| Symptom | What to check |
|
||||
|---|---|
|
||||
| The container exits at start with `URUTAU_TOKEN is required` | Set `URUTAU_TOKEN` with at least 32 characters and about 128 bits of estimated entropy (length times Shannon entropy; periodic or sequential tokens are refused) (`openssl rand -base64 48`), or point `URUTAU_TOKEN_FILE` at a file that holds it |
|
||||
| A source stays at `waiting` | The file does not exist at that path inside the container; check the mount and the `URUTAU_*_LOG` path |
|
||||
| A source shows `error` with `permission denied` | Add the host `adm` group with `group_add: ["4"]` (`getent group adm`) and mount the file `:ro` |
|
||||
| The Traefik source has many malformed lines | The access log is not JSON; set `accessLog.format: json` in Traefik |
|
||||
| Lines count but nothing appears | The origin is in `URUTAU_TRUSTED` or `URUTAU_IGNORE` (private ranges are dropped by default), or the request is a monitoring User-Agent |
|
||||
| All hits come from one internal address | The proxy hides the real client; pass the client address through to Traefik |
|
||||
| fail2ban times are off by hours | `fail2ban.log` has no time zone; set `TZ` to the host's zone |
|
||||
| Counts look duplicated after a restart | The snapshot was not saved or was lost; mount `/data` on a volume |
|
||||
| The dashboard is unreachable from another host | It binds to `127.0.0.1` through `URUTAU_PUBLISH`; check the reverse proxy |
|
||||
| A hub refuses to start with `has no token` | Every peer needs a token: set `URUTAU_PEER_TOKEN` or `URUTAU_PEER_TOKEN_<NAME>` (the peer name uppercased, other characters as `_`) |
|
||||
| The login answers 429 | Too many failures from that address; wait for the window (10 minutes) or retry later, the correct token still gets in after a 1 second delay |
|
||||
| The Traefik source stays at `waiting` on Coolify | Traefik is not writing `/traefik/logs/access.log`; see the Coolify section of [docker.md](docker.md) |
|
||||
| A peer shows offline | Wrong URL or `URUTAU_PEER_TOKEN`, or the peer is not reachable from the hub; the error is shown on the host card |
|
||||
| `--insecure-no-auth` is refused | It only works on a loopback bind; use a token |
|
||||
Reference in new issue
Block a user