fix(fed): sanitize peer rows, cap peer bytes, add --peer-blocklist
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 24s
CI / Tests (Linux, race detector) (push) Successful in 34s
CI / Dependency audit (push) Successful in 14s
Release / Plan (reuse the published image?) (push) Successful in 3s
Release / ci (push) Skipped
Release / Build image (amd64) (push) Skipped
Release / Build image (arm64) (push) Skipped
Release / Publish tags (push) Successful in 13s
Release / Gitea release (push) Successful in 4s

Peer events and summary rows are rebuilt from validated fields (address,
country code, category) and the forged/unban flags from peers are
ignored. The live relay drops a peer that exceeds about 1 MB/s, also
within a single window. --peer-blocklist=off keeps the hub's blocklist
to local observations. UI polish: plural forms, blocklist preview and
downloads follow the active slice, compact IP cards on phones. Docs for
the 1.1.0 interface.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lucas RayanandClaude Opus 5.5 committed 2026-11-14 18:10:54 -03:00
1 parent f4b295f582
commit 783b0cba3e
31 files changed
+355 -127

No files matched your search

+7 -1
View File
@@ -16,6 +16,12 @@ Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versio
- **API:** `GET /api/v1/geo` (countries, or one country with regions, cities and `top_ips`), `GET /api/v1/live/recent`, and `host`, `src` and `dst` on every live event.
- **Live federation:** the hub keeps `GET /api/v1/peer/stream` open on each peer and relays their live events, bounded and sanitized.
- **`--location` / `URUTAU_LOCATION`:** the position of the instance on the map.
- **`--peer-blocklist` / `URUTAU_PEER_BLOCKLIST`** (`on` by default): `off` keeps the hub's blocklist to local observations.
### Security
- Events and summary rows from peers are rebuilt from validated fields (address, country code, category); `forged` and `unban` flags from peers are ignored.
- The live relay disconnects a peer that sends more than about 1 MB/s, on top of the event rate cap.
- Static files are served from the embedded directory by a strict name pattern.
## [1.0.0] - 2026-11-14
@@ -34,7 +40,7 @@ First release.
- Federation: `--peer name=https://url` aggregates other instances. A hub only calls `GET /api/v1/peer/export?range=1h|24h|7d` (`{"v":1,"summary":...,"traffic":{...}}`, top 500 IPs with detail, cached 5 s) every 15 s, with a 4 s timeout, an 8 MB limit, no redirects, `https` required outside loopback, and sanitized, capped peer data. `--peer-allow` / `URUTAU_PEER_ALLOW` limits the source CIDRs of the export.
- Offline geolocation (country, city, ASN) from the DB-IP Lite databases (CC BY 4.0), downloaded and refreshed by Urutau (`--geo-dir`, `--geo-update`) and read by a built-in, dependency-free MMDB reader.
- User-Agent parsing into browser, operating system, device, bots and attack tools.
- Privacy-friendly web analytics for legitimate traffic (Traffic tab): unique visitors by a daily-salted hash, pages, referrers, countries, browsers, devices, latency p50 and p95, bytes and a world map. The IP of a legitimate visitor is never persisted. Threats and Traffic are separate tabs.
- Privacy-friendly web analytics for legitimate traffic (Traffic page): unique visitors by a daily-salted hash, pages, referrers, countries, browsers, devices, latency p50 and p95, bytes and a world map. The IP of a legitimate visitor is never persisted. Threats and Traffic are separate pages.
- Reverse DNS enrichment of listed IPs.
- Noise filters: `--trusted` / `URUTAU_TRUSTED` (alias `--ignore`) drops events from trusted CIDRs, and `--monitor-ua` / `URUTAU_MONITOR_UA` keeps benign monitoring requests (such as Uptime-Kuma) out of the traffic numbers.
- `urutau doctor [--json]` to check the configuration, the sources, the data directory, the geolocation databases and the snapshot; the JSON output carries `geo` and `state`.
+7 -1
View File
@@ -16,6 +16,12 @@ Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/);
- **API:** `GET /api/v1/geo` (países, ou um país com regiões, cidades e `top_ips`), `GET /api/v1/live/recent`, e `host`, `src` e `dst` em cada evento ao vivo.
- **Federação ao vivo:** o hub mantém `GET /api/v1/peer/stream` aberto em cada peer e repassa os eventos ao vivo deles, com limites e sanitização.
- **`--location` / `URUTAU_LOCATION`:** a posição da instância no mapa.
- **`--peer-blocklist` / `URUTAU_PEER_BLOCKLIST`** (`on` por padrão): `off` restringe a blocklist do hub às observações locais.
### Segurança
- Eventos e linhas de resumo vindos de peers são reconstruídos a partir de campos validados (endereço, código de país, categoria); os sinalizadores `forged` e `unban` vindos de peers são ignorados.
- O repasse ao vivo desconecta um peer que mande mais de cerca de 1 MB/s, além do teto de eventos.
- Os arquivos estáticos são servidos do diretório embutido por um padrão de nome estrito.
## [1.0.0] - 2026-11-14
@@ -34,7 +40,7 @@ Primeira versão.
- Federação: `--peer nome=https://url` agrega outras instâncias. Um hub só chama `GET /api/v1/peer/export?range=1h|24h|7d` (`{"v":1,"summary":...,"traffic":{...}}`, 500 IPs principais com detalhe, cache de 5 s) a cada 15 s, com timeout de 4 s, limite de 8 MB, sem redirects, `https` obrigatório fora de loopback e dados do peer sanitizados e limitados. `--peer-allow` / `URUTAU_PEER_ALLOW` limita os CIDRs de origem do export.
- Geolocalização offline (país, cidade, ASN) a partir das bases DB-IP Lite (CC BY 4.0), baixadas e atualizadas pelo Urutau (`--geo-dir`, `--geo-update`) e lidas por um leitor MMDB embutido e sem dependências.
- Interpretação de User-Agent em navegador, sistema operacional, dispositivo, bots e ferramentas de ataque.
- Web analytics amigável à privacidade para o tráfego legítimo (aba Tráfego): visitantes únicos por hash com sal diário, páginas, referrers, países, navegadores, dispositivos, latência p50 e p95, bytes e mapa-múndi. O IP de um visitante legítimo nunca é persistido. Ameaças e Tráfego são abas separadas.
- Web analytics amigável à privacidade para o tráfego legítimo (página Tráfego): visitantes únicos por hash com sal diário, páginas, referrers, países, navegadores, dispositivos, latência p50 e p95, bytes e mapa-múndi. O IP de um visitante legítimo nunca é persistido. Ameaças e Tráfego são páginas separadas.
- Enriquecimento com DNS reverso dos IPs listados.
- Filtros de ruído: `--trusted` / `URUTAU_TRUSTED` (alias `--ignore`) descarta eventos de CIDRs confiáveis, e `--monitor-ua` / `URUTAU_MONITOR_UA` mantém requisições benignas de monitoramento (como o Uptime-Kuma) fora dos números de tráfego.
- `urutau doctor [--json]` para conferir a configuração, as fontes, o diretório de dados, as bases de geolocalização e o snapshot; a saída JSON traz `geo` e `state`.
+20 -4
View File
@@ -17,11 +17,11 @@ Urutau is a small panel that runs on each of your servers (as a container), read
- **Scores IPs:** every event adds weight to its source IP. A score of 10 or more is **suspicious**; **hostile** needs 50 or more **and** a strong signal (an attack tool, two or more attack categories, a ban, or a clear exploit attempt that was refused). Scanner and exploit probes that got a 2xx or 3xx answer weigh only 0.5. An IP with a successful SSH login is never hostile and never reaches the blocklist.
- **Geolocation, offline:** country, city and ASN for every IP from the free DB-IP Lite databases, downloaded and refreshed by Urutau itself, read by a built-in MMDB reader with no dependency. Nothing is looked up online.
- **Understands User-Agents:** browser, operating system, device, bots and attack tools.
- **Web analytics for legitimate traffic:** unique visitors, pages, referrers, countries, browsers, devices, latency (p50 and p95) and bytes, with a world map, replacing your proxy's analytics. Separate **Threats** and **Traffic** tabs.
- **Web analytics for legitimate traffic:** unique visitors, pages, referrers, countries, browsers, devices, latency (p50 and p95) and bytes, with a world map, replacing your proxy's analytics. Separate **Threats** and **Traffic** pages.
- **Lightweight:** Go standard library only, one static binary, a soft memory limit of 160 MiB, state in a single snapshot file. No database.
- **Live dashboard:** embedded vanilla UI (English and Portuguese, light and dark), updated through Server-Sent Events.
- **Live dashboard:** embedded vanilla UI (English and Portuguese, light and dark), updated through Server-Sent Events, with seven pages (see below).
- **Blocklist:** hostile, globally routable IPs as plain text or JSON, ready for fail2ban, ipset, nginx or a firewall. IPv6 is aggregated by /64 and exported as `x:x:x:x::/64`.
- **Federation:** one instance (the hub) aggregates others with `--peer name=url`, pulling `/api/v1/peer/export`.
- **Federation:** one instance (the hub) aggregates others with `--peer name=url`, pulling `/api/v1/peer/export` and relaying their live events through `/api/v1/peer/stream`.
## How it works
@@ -39,10 +39,26 @@ Urutau is a small panel that runs on each of your servers (as a container), read
dashboard (SSE) /api/v1/* JSON blocklist.txt / .json
hub ── GET /api/v1/peer/export (peer token) ──► peer A
│ ── GET /api/v1/peer/stream (live events) ──► peer A
│ ── GET /api/v1/peer/export (peer token) ──► peer B
│ ── GET /api/v1/peer/stream (live events) ──► peer B
└──► one dashboard for the whole fleet
```
## Interface
Seven pages, in a side rail, with the view kept in the URL hash:
- **Overview:** the headline numbers, the timeline and the top IPs.
- **Threats:** categories over time, the live feed and the top attacked paths, domains, User-Agents and users.
- **Geography:** a world map by attacker country; drill down country, states or regions, cities (`#/geo/BR/Pernambuco`).
- **Live:** attacks as animated arcs from their origin to the server that saw them, on a flat map or a 3D globe, including the events of your peers. `--location` (`URUTAU_LOCATION`, `"lat,lon"` or `"lat,lon,label"`) sets where this server sits on the map.
- **Traffic:** privacy-friendly web analytics for legitimate visitors.
- **IPs:** the scored IP table with an IP detail drawer.
- **Sources and hosts:** log sources, peers and the blocklist.
See [docs/interface.md](docs/interface.md).
## Install
Run it with Docker Compose (recommended):
@@ -87,7 +103,7 @@ Your own infrastructure produces events too. Two filters keep it out of the pict
- `--trusted` / `URUTAU_TRUSTED`: CIDRs of trusted origins (your office, your monitors, your other servers). Their events are dropped entirely. `--ignore` remains as an alias.
- `--monitor-ua` / `URUTAU_MONITOR_UA`: a regular expression matching monitoring User-Agents (the default includes Uptime-Kuma). A request that matches and is benign is not counted as traffic; it feeds a separate "monitoring" counter. If the same request is a `scanner`, `exploit` or `bruteforce`, it counts as an attack, because a User-Agent is trivial to forge.
- `--monitor-from` / `URUTAU_MONITOR_FROM`: CIDRs the monitors really come from. When set, the monitoring User-Agent is honored only from those networks. Without it, only `ok` answers are filtered (a `notfound` from a monitor User-Agent still counts), since anyone can forge the header.
- `--domains` / `URUTAU_DOMAINS`: an allowlist of domains for the Traffic tab (exact names or `*.example.com`). A domain only gets a slot after a 2xx answer, and inactive domains are pruned, so random `Host` headers cannot fill the analytics.
- `--domains` / `URUTAU_DOMAINS`: an allowlist of domains for the Traffic page (exact names or `*.example.com`). A domain only gets a slot after a 2xx answer, and inactive domains are pruned, so random `Host` headers cannot fill the analytics.
## Geolocation and attribution
+21 -5
View File
@@ -17,11 +17,11 @@ O Urutau é um painel pequeno que roda em cada um dos seus servidores (como cont
- **Pontua IPs:** cada evento soma peso ao IP de origem. Pontuação 10 ou mais é **suspeito**; **hostil** exige 50 ou mais **e** um sinal forte (uma ferramenta de ataque, duas ou mais categorias de ataque, um ban ou uma tentativa clara de exploit recusada). Sondas de scanner e exploit que receberam resposta 2xx ou 3xx pesam só 0,5. Um IP com login SSH bem-sucedido nunca é hostil e nunca vai para a blocklist.
- **Geolocalização offline:** país, cidade e ASN de todo IP a partir das bases gratuitas DB-IP Lite, baixadas e atualizadas pelo próprio Urutau, lidas por um leitor MMDB embutido e sem dependências. Nada é consultado online.
- **Entende User-Agents:** navegador, sistema operacional, dispositivo, bots e ferramentas de ataque.
- **Web analytics do tráfego legítimo:** visitantes únicos, páginas, referrers, países, navegadores, dispositivos, latência (p50 e p95) e bytes, com mapa-múndi, no lugar do analytics do seu proxy. Abas **Ameaças** e **Tráfego** separadas.
- **Web analytics do tráfego legítimo:** visitantes únicos, páginas, referrers, países, navegadores, dispositivos, latência (p50 e p95) e bytes, com mapa-múndi, no lugar do analytics do seu proxy. Páginas **Ameaças** e **Tráfego** separadas.
- **Leve:** só biblioteca padrão do Go, um binário estático, limite suave de memória de 160 MiB, estado em um único arquivo de snapshot. Sem banco de dados.
- **Dashboard ao vivo:** UI vanilla embutida (inglês e português, claro e escuro), atualizada por Server-Sent Events.
- **Dashboard ao vivo:** UI vanilla embutida (inglês e português, claro e escuro), atualizada por Server-Sent Events, com sete páginas (veja abaixo).
- **Blocklist:** IPs hostis e globalmente roteáveis em texto ou JSON, prontos para fail2ban, ipset, nginx ou firewall. O IPv6 é agregado por /64 e exportado como `x:x:x:x::/64`.
- **Federação:** uma instância (o hub) agrega outras com `--peer nome=url`, puxando `/api/v1/peer/export`.
- **Federação:** uma instância (o hub) agrega outras com `--peer nome=url`, puxando `/api/v1/peer/export` e repassando os eventos ao vivo deles por `/api/v1/peer/stream`.
## Como funciona
@@ -39,10 +39,26 @@ O Urutau é um painel pequeno que roda em cada um dos seus servidores (como cont
dashboard (SSE) /api/v1/* JSON blocklist.txt / .json
hub ── GET /api/v1/peer/export (token de peer) ──► peer A
│ ── GET /api/v1/peer/stream (eventos ao vivo) ──► peer A
│ ── GET /api/v1/peer/export (token de peer) ──► peer B
│ ── GET /api/v1/peer/stream (eventos ao vivo) ──► peer B
└──► um dashboard para a frota inteira
```
## Interface
Sete páginas, numa barra lateral, com a visão guardada no hash da URL:
- **Visão geral:** os números principais, a linha do tempo e os principais IPs.
- **Ameaças:** categorias ao longo do tempo, o feed ao vivo e os principais caminhos atacados, domínios, User-Agents e usuários.
- **Geografia:** um mapa-múndi por país do atacante; detalhamento país, estados ou regiões, cidades (`#/geo/BR/Pernambuco`).
- **Ao vivo:** ataques como arcos animados da origem até o servidor que os viu, em mapa plano ou globo 3D, incluindo os eventos dos seus peers. `--location` (`URUTAU_LOCATION`, `"lat,lon"` ou `"lat,lon,rótulo"`) define onde este servidor fica no mapa.
- **Tráfego:** web analytics amigável à privacidade para visitantes legítimos.
- **IPs:** a tabela de IPs pontuados com painel de detalhe do IP.
- **Fontes e hosts:** fontes de log, peers e a blocklist.
Veja [docs/pt-BR/interface.md](docs/pt-BR/interface.md).
## Instalação
Rode com Docker Compose (recomendado):
@@ -87,7 +103,7 @@ Sua própria infraestrutura também gera eventos. Dois filtros a tiram do quadro
- `--trusted` / `URUTAU_TRUSTED`: CIDRs de origens confiáveis (seu escritório, seus monitores, seus outros servidores). Os eventos delas são descartados por completo. `--ignore` continua como alias.
- `--monitor-ua` / `URUTAU_MONITOR_UA`: expressão regular de User-Agents de monitoramento (o padrão inclui Uptime-Kuma). Uma requisição que casa e é benigna não conta como tráfego; ela alimenta um contador "monitoring" à parte. Se a mesma requisição for `scanner`, `exploit` ou `bruteforce`, conta como ataque, porque um User-Agent é trivial de forjar.
- `--monitor-from` / `URUTAU_MONITOR_FROM`: CIDRs de onde os monitores realmente vêm. Quando definido, o User-Agent de monitoramento só vale vindo dessas redes. Sem ele, só respostas `ok` são filtradas (um `notfound` com User-Agent de monitor ainda conta), já que qualquer um pode forjar o cabeçalho.
- `--domains` / `URUTAU_DOMAINS`: uma lista de domínios permitidos para a aba Tráfego (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` aleatórios não enchem o analytics.
- `--domains` / `URUTAU_DOMAINS`: uma lista de domínios permitidos para a página Tráfego (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` aleatórios não enchem o analytics.
## Geolocalização e atribuição
@@ -99,7 +115,7 @@ A atribuição também aparece no dashboard. Se você redistribuir as bases ou a
## Privacidade
A aba **Tráfego** conta visitantes legítimos sem rastreá-los. Um visitante único é um hash calculado com um sal que muda todo dia, então não acompanha uma pessoa de um dia para o outro, e o endereço IP de um visitante legítimo nunca é persistido: nem no snapshot, nem em log, nem em exportação. Endereços IP são guardados apenas para atividade classificada como hostil, que é o que uma ferramenta de segurança existe para registrar. Sem cookies, fingerprinting nem requisições a terceiros, o desenho dispensa banner de consentimento, mas a licitude do seu uso perante a LGPD ou o GDPR continua sendo decisão sua, como controlador. Veja [SECURITY.pt-BR.md](SECURITY.pt-BR.md).
A página **Tráfego** conta visitantes legítimos sem rastreá-los. Um visitante único é um hash calculado com um sal que muda todo dia, então não acompanha uma pessoa de um dia para o outro, e o endereço IP de um visitante legítimo nunca é persistido: nem no snapshot, nem em log, nem em exportação. Endereços IP são guardados apenas para atividade classificada como hostil, que é o que uma ferramenta de segurança existe para registrar. Sem cookies, fingerprinting nem requisições a terceiros, o desenho dispensa banner de consentimento, mas a licitude do seu uso perante a LGPD ou o GDPR continua sendo decisão sua, como controlador. Veja [SECURITY.pt-BR.md](SECURITY.pt-BR.md).
## Usando a blocklist
+2
View File
@@ -17,6 +17,8 @@ Urutau is lightweight, always-on threat intelligence for self-hosted servers: it
- **Container and CI/CD (1.0.0):** multi-arch image, Coolify deployment, Gitea CI with an image-reuse release workflow, weekly audit.
- **Bilingual documentation (1.0.0).**
- **Interface and live federation (1.1.0):** seven pages, Geography with country, region and city drill-down, Live arcs on a flat map or a 3D globe, `/api/v1/geo`, `/api/v1/live/recent`, relayed live events from peers (`/api/v1/peer/stream`) and `--location`.
## Next
- **More log sources:** other web servers and proxies (nginx, Caddy), and more daemons' auth failures.
+2
View File
@@ -17,6 +17,8 @@ O Urutau é threat intelligence leve e sempre ligado para servidores self-hosted
- **Container e CI/CD (1.0.0):** imagem multi-arquitetura, deploy no Coolify, CI no Gitea com release que reaproveita imagem, auditoria semanal.
- **Documentação bilíngue (1.0.0).**
- **Interface e federação ao vivo (1.1.0):** sete páginas, Geografia com detalhamento por país, região e cidade, arcos Ao vivo em mapa plano ou globo 3D, `/api/v1/geo`, `/api/v1/live/recent`, eventos ao vivo dos peers repassados (`/api/v1/peer/stream`) e `--location`.
## Próximo
- **Mais fontes de log:** outros servidores web e proxies (nginx, Caddy) e falhas de autenticação de mais daemons.
+2 -2
View File
@@ -12,7 +12,7 @@ Do not open a public issue with exploit details. Open a minimal issue asking for
- **Hostile log fields:** paths, User-Agents, user names, hosts and jails are length-limited when parsed, kept as data, and escaped when rendered. A malformed, oversized or crafted line must be counted as malformed, never crash the daemon, exhaust memory or inject markup, a command or a script into the dashboard. The dashboard ships a Content-Security-Policy that forbids inline script and style.
- **Authentication:** the dashboard and every API route except `/api/health` need `URUTAU_TOKEN` (at least 32 characters and about 128 bits of estimated entropy, compared in constant time; it can come from `URUTAU_TOKEN_FILE`), either as a bearer token or through a login that sets a session cookie (`HttpOnly`, `SameSite=Strict`, `Secure` over HTTPS) valid for 12 hours. The session is revocable: it is a random id kept in memory, logout revokes it and closes its live stream, and a restart invalidates all sessions. Login and logout reject cross-site requests. After 5 failures per 10 minutes from a client (IPv6 counted per /64) the login answers 429, yet the correct token still gets in after a 1 second delay, so an attacker cannot lock the owner out; wrong bearer tokens count as failures too. The client IP comes from the TCP peer; `X-Forwarded-For` is honored only when the peer is in `--trusted-proxy` (default: the private networks), read from right to left, so it cannot be spoofed from outside. Generate tokens with `openssl rand -base64 48` (`-hex 32` also works).
- **Peer token:** The server token (`URUTAU_PEER_TOKEN`, also as `_FILE`; 32+ characters, about 128 bits of estimated entropy, not periodic or sequential, different from `URUTAU_TOKEN`) is the only credential the local export accepts, and it only opens the two federation routes, `GET /api/v1/peer/export` and the live stream `GET /api/v1/peer/stream` (at most 10 connections, malicious events only); every other route answers 403 to it, and `URUTAU_TOKEN` is refused (401) on both. Without a peer token they are a 404. `--peer-allow` restricts both to source CIDRs. `URUTAU_PEER_TOKEN_<NAME>` values are client credentials a hub sends to that peer; they never open the local export, and peer names that collide in the variable name are refused. A hub refuses to start with a peer that has no token, only talks to those two routes, requires `https` outside loopback, does not follow redirects, uses a 4 s timeout and an 8 MB limit, and sanitizes and caps everything a peer sends: an `admin` flag coming from a peer is ignored and a peer's `Strong` flag only counts with a score of 50 or more. The live relay from each peer is capped at about 50 events per second, lines of at most 16 KB, a 500-event buffer, reconnection with exponential backoff up to 60 s, and every relayed event is rebuilt from validated fields (address, known category, clipped strings without control characters, valid coordinates; the `host` is always the configured peer name). Treat a peer as able to read the top 500 IPs, paths and traffic figures its export carries, and its live attack events.
- **Peer token:** The server token (`URUTAU_PEER_TOKEN`, also as `_FILE`; 32+ characters, about 128 bits of estimated entropy, not periodic or sequential, different from `URUTAU_TOKEN`) is the only credential the local export accepts, and it only opens the two federation routes, `GET /api/v1/peer/export` and the live stream `GET /api/v1/peer/stream` (at most 10 connections, malicious events only); every other route answers 403 to it, and `URUTAU_TOKEN` is refused (401) on both. Without a peer token they are a 404. `--peer-allow` restricts both to source CIDRs. `URUTAU_PEER_TOKEN_<NAME>` values are client credentials a hub sends to that peer; they never open the local export, and peer names that collide in the variable name are refused. A hub refuses to start with a peer that has no token, only talks to those two routes, requires `https` outside loopback, does not follow redirects, uses a 4 s timeout and an 8 MB limit, and sanitizes and caps everything a peer sends: an `admin` flag coming from a peer is ignored and a peer's `Strong` flag only counts with a score of 50 or more. The live relay from each peer is capped at about 50 events per second and about 1 MB/s (a peer that sends more is disconnected), lines of at most 16 KB, a 500-event buffer, reconnection with exponential backoff up to 60 s, and every relayed event is rebuilt from validated fields (address, known category, clipped strings without control characters, valid coordinates; the `host` is always the configured peer name). A compromised peer can still add hostile-looking global IPs to the hub's blocklist (only with score 50+ and a strong signal; `admin` and `forged` flags from peers are ignored); set `URUTAU_PEER_BLOCKLIST=off` to keep the blocklist to local observations. Treat a peer as able to read the top 500 IPs, paths and traffic figures its export carries, and its live attack events.
- **HTTP server limits:** header and body timeouts, `MaxHeaderBytes` of 16 KB, `POST /login` capped at 4 KB, and at most 20 simultaneous live-stream clients (a 21st gets 503 with `Retry-After`; the stream sends a heartbeat every 20 s).
- **Information exposure:** `/api/health` returns only `{"status":"ok"}` (no version), log file paths are never shown in the dashboard or to peers, responses carry `Referrer-Policy: same-origin` and a strict Content-Security-Policy.
- **Framed requests:** with the `Sec-Fetch-Site`, `Sec-Fetch-Dest` and `Referer` headers in the Traefik log, a request embedded by another page (cross-site or same-site, or a sub-resource destination such as image or script) creates an IP record like any other but weighs 0.25 per event, with at most 30 points per IP from such requests (below the hostile threshold), and never counts as a strong signal. With an attack-tool User-Agent the headers are ignored. The headers come from the client, so a framed visitor never becomes hostile, and a scanner that forges them shows up as suspicious instead of vanishing.
@@ -22,7 +22,7 @@ Do not open a public issue with exploit details. Open a minimal issue asking for
- **Container hardening:** the image runs as an unprivileged user (no `curl` or shell tools needed: its `HEALTHCHECK` is `urutau healthcheck`) with a read-only root filesystem and no capabilities. Logs are mounted read-only, and only the Traefik log directory is mounted from the proxy, never `acme.json` or its configuration. Logs come from a dedicated host directory, `/var/log/urutau`, not the whole `/var/log`. `--trusted-proxy` defaults to loopback only; the compose file creates the `urutau-edge` network (`10.250.0.0/24`) and trusts just that, so keep only the reverse proxy on it, since another container there could forge `X-Forwarded-For`. The only write target is the data volume (snapshot, mode `0700` directory).
- **Read-only by design:** Urutau reads logs and never sends traffic to the IPs it lists. The only outbound connections are reverse DNS lookups, the periodic download of the DB-IP Lite databases from `download.db-ip.com` (verified by opening the file before it replaces the old one; a failure never stops the service) and, on a hub, the polls to the configured peers. Geolocation lookups are local.
- **Privacy and local-first:** there is no telemetry. IPs and request details stay on your servers (and on the hub you configure).
- **Visitor privacy (LGPD and GDPR):** the Traffic tab counts unique visitors with a hash computed with a daily salt, so a visitor cannot be followed across days, and the IP address of a legitimate visitor is never persisted. There are no cookies for visitors, no fingerprinting and no request to third parties. IPs are retained only for hostile activity, for at most the retention period (7 days). Whether this is enough for your legal basis and notices is your responsibility as the controller.
- **Visitor privacy (LGPD and GDPR):** the Traffic page counts unique visitors with a hash computed with a daily salt, so a visitor cannot be followed across days, and the IP address of a legitimate visitor is never persisted. There are no cookies for visitors, no fingerprinting and no request to third parties. IPs are retained only for hostile activity, for at most the retention period (7 days). Whether this is enough for your legal basis and notices is your responsibility as the controller.
- **Third-party data:** the geolocation databases are DB-IP Lite, CC BY 4.0, and the attribution must be kept where the data is shown.
## Known limitation
+2 -2
View File
@@ -12,7 +12,7 @@ Não abra uma issue pública com detalhes de exploração. Abra uma issue mínim
- **Campos hostis de log:** caminhos, User-Agents, usuários, hosts e jails têm tamanho limitado no parse, são mantidos como dado e escapados ao renderizar. Uma linha malformada, gigante ou forjada deve ser contada como malformada, nunca derrubar o daemon, esgotar memória ou injetar marcação, comando ou script no dashboard. O dashboard envia uma Content-Security-Policy que proíbe script e estilo inline.
- **Autenticação:** o dashboard e toda rota da API, exceto `/api/health`, exigem `URUTAU_TOKEN` (no mínimo 32 caracteres e cerca de 128 bits de entropia estimada, comparado em tempo constante; pode vir de `URUTAU_TOKEN_FILE`), como bearer token ou por um login que define um cookie de sessão (`HttpOnly`, `SameSite=Strict`, `Secure` em HTTPS) válido por 12 horas. A sessão é revogável: é um id aleatório guardado em memória, o logout a revoga e fecha o stream ao vivo dela, e um reinício invalida todas as sessões. Login e logout rejeitam requisições cross-site. Após 5 falhas a cada 10 minutos de um cliente (IPv6 contado por /64) o login responde 429, mas o token correto ainda entra após 1 segundo de atraso, para que um atacante não tranque o dono do lado de fora; bearer tokens errados também contam como falha. O IP do cliente vem do peer TCP; `X-Forwarded-For` só vale quando o peer está em `--trusted-proxy` (padrão: as redes privadas), lido da direita para a esquerda, então não pode ser forjado de fora. Gere tokens com `openssl rand -base64 48` (`-hex 32` também serve).
- **Token de peer:** O token de servidor (`URUTAU_PEER_TOKEN`, também via `_FILE`; 32+ caracteres, cerca de 128 bits de entropia estimada, sem padrão periódico nem sequencial, diferente de `URUTAU_TOKEN`) é a única credencial que o export local aceita, e só abre as duas rotas de federação, `GET /api/v1/peer/export` e o fluxo ao vivo `GET /api/v1/peer/stream` (no máximo 10 conexões, só eventos maliciosos); todas as outras rotas respondem 403 a ele, e o `URUTAU_TOKEN` é recusado (401) nas duas. Sem token de peer elas são 404. `--peer-allow` restringe as duas a CIDRs de origem. Os valores `URUTAU_PEER_TOKEN_<NOME>` são credenciais de cliente que um hub envia àquele peer; nunca abrem o export local, e nomes de peer que colidem no nome da variável são recusados. Um hub se recusa a iniciar com um peer sem token, só fala com essas duas rotas, exige `https` fora de loopback, não segue redirects, usa timeout de 4 s e limite de 8 MB, e sanitiza e limita tudo o que um peer envia: um sinalizador `admin` vindo de um peer é ignorado e o `Strong` de um peer só vale com pontuação 50 ou mais. O repasse ao vivo de cada peer é limitado a cerca de 50 eventos por segundo, linhas de no máximo 16 KB, buffer de 500 eventos e reconexão com backoff exponencial até 60 s, e cada evento repassado é reconstruído a partir de campos validados (endereço, categoria conhecida, textos cortados e sem caracteres de controle, coordenadas válidas; o `host` é sempre o nome configurado do peer). Trate um peer como alguém que pode ler os 500 IPs principais, caminhos e números de tráfego que o export carrega, e os seus eventos de ataque ao vivo.
- **Token de peer:** O token de servidor (`URUTAU_PEER_TOKEN`, também via `_FILE`; 32+ caracteres, cerca de 128 bits de entropia estimada, sem padrão periódico nem sequencial, diferente de `URUTAU_TOKEN`) é a única credencial que o export local aceita, e só abre as duas rotas de federação, `GET /api/v1/peer/export` e o fluxo ao vivo `GET /api/v1/peer/stream` (no máximo 10 conexões, só eventos maliciosos); todas as outras rotas respondem 403 a ele, e o `URUTAU_TOKEN` é recusado (401) nas duas. Sem token de peer elas são 404. `--peer-allow` restringe as duas a CIDRs de origem. Os valores `URUTAU_PEER_TOKEN_<NOME>` são credenciais de cliente que um hub envia àquele peer; nunca abrem o export local, e nomes de peer que colidem no nome da variável são recusados. Um hub se recusa a iniciar com um peer sem token, só fala com essas duas rotas, exige `https` fora de loopback, não segue redirects, usa timeout de 4 s e limite de 8 MB, e sanitiza e limita tudo o que um peer envia: um sinalizador `admin` vindo de um peer é ignorado e o `Strong` de um peer só vale com pontuação 50 ou mais. O repasse ao vivo de cada peer é limitado a cerca de 50 eventos por segundo e cerca de 1 MB/s (um peer que manda mais é desconectado), linhas de no máximo 16 KB, buffer de 500 eventos e reconexão com backoff exponencial até 60 s, e cada evento repassado é reconstruído a partir de campos validados (endereço, categoria conhecida, textos cortados e sem caracteres de controle, coordenadas válidas; o `host` é sempre o nome configurado do peer). Um peer comprometido ainda pode pôr IPs globais com cara de hostis na blocklist do hub (só com pontuação 50+ e sinal forte; os sinalizadores `admin` e `forged` vindos de peers são ignorados); defina `URUTAU_PEER_BLOCKLIST=off` para restringir a blocklist às observações locais. Trate um peer como alguém que pode ler os 500 IPs principais, caminhos e números de tráfego que o export carrega, e os seus eventos de ataque ao vivo.
- **Limites do servidor HTTP:** timeouts de cabeçalho e corpo, `MaxHeaderBytes` de 16 KB, `POST /login` limitado a 4 KB e no máximo 20 clientes simultâneos no stream ao vivo (o 21º recebe 503 com `Retry-After`; o stream envia heartbeat a cada 20 s).
- **Exposição de informação:** `/api/health` devolve só `{"status":"ok"}` (sem versão), os caminhos dos arquivos de log nunca aparecem no dashboard nem para peers, e as respostas levam `Referrer-Policy: same-origin` e uma Content-Security-Policy estrita.
- **Requisições enquadradas:** com os cabeçalhos `Sec-Fetch-Site`, `Sec-Fetch-Dest` e `Referer` no log do Traefik, uma requisição embutida por outra página (cross-site ou same-site, ou destino 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. Os cabeçalhos vêm do cliente, então um visitante enquadrado nunca vira hostil, e um scanner que os forja aparece como suspeito em vez de sumir.
@@ -22,7 +22,7 @@ Não abra uma issue pública com detalhes de exploração. Abra uma issue mínim
- **Endurecimento do container:** a imagem roda com usuário sem privilégios (sem `curl` nem ferramentas de shell: o `HEALTHCHECK` é `urutau healthcheck`), sistema de arquivos raiz somente leitura e sem capabilities. Os logs são montados somente leitura, e do proxy só o diretório de logs do Traefik é montado, nunca o `acme.json` nem a configuração. Os logs vêm de um diretório dedicado do host, `/var/log/urutau`, não do `/var/log` inteiro. `--trusted-proxy` tem como padrão só o loopback; o compose cria a rede `urutau-edge` (`10.250.0.0/24`) e confia só nela, então deixe nela apenas o proxy reverso, pois outro container ali poderia forjar o `X-Forwarded-For`. O único destino de escrita é o volume de dados (snapshot, diretório com modo `0700`).
- **Somente leitura por desenho:** o Urutau lê logs e nunca envia tráfego aos IPs que lista. As únicas conexões de saída são as consultas de DNS reverso, o download periódico das bases DB-IP Lite em `download.db-ip.com` (verificado abrindo o arquivo antes de substituir o antigo; uma falha nunca interrompe o serviço) e, em um hub, as consultas aos peers configurados. As consultas de geolocalização são locais.
- **Privacidade e local-first:** não há telemetria. IPs e detalhes de requisições ficam nos seus servidores (e no hub que você configurar).
- **Privacidade dos visitantes (LGPD e GDPR):** a aba Tráfego conta visitantes únicos com um hash calculado com sal diário, então um visitante não pode ser seguido entre dias, e o endereço IP de um visitante legítimo nunca é persistido. Não há cookies para visitantes, fingerprinting nem requisição a terceiros. IPs são retidos apenas para atividade hostil, por no máximo o período de retenção (7 dias). Se isso basta para a sua base legal e seus avisos é responsabilidade sua, como controlador.
- **Privacidade dos visitantes (LGPD e GDPR):** a página Tráfego conta visitantes únicos com um hash calculado com sal diário, então um visitante não pode ser seguido entre dias, e o endereço IP de um visitante legítimo nunca é persistido. Não há cookies para visitantes, fingerprinting nem requisição a terceiros. IPs são retidos apenas para atividade hostil, por no máximo o período de retenção (7 dias). Se isso basta para a sua base legal e seus avisos é responsabilidade sua, como controlador.
- **Dados de terceiros:** as bases de geolocalização são DB-IP Lite, CC BY 4.0, e a atribuição deve ser mantida onde os dados são exibidos.
## Limitação conhecida
+9 -1
View File
@@ -83,7 +83,7 @@ Events from a trusted origin (`--trusted`, plus the private ranges of `--ignore`
## 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.
Benign requests (`ok`, and the `notfound` that are not scanning) also feed the Traffic page. A domain only gets a slot after a 2xx answer (and `--domains` can restrict them to an allowlist), inactive domains are pruned, and top pages normalize token-looking path segments to `:id`: unique visitors, pages, referrers, countries, browsers, operating systems, devices, latency (p50 and p95) and bytes. A unique visitor is a hash computed with a salt that rotates daily, so it cannot be followed across days, and the IP address of a legitimate visitor is never persisted. Attack traffic stays in the Threats view, where the IP is the subject. Monitoring requests are kept out of both.
## State and persistence
@@ -97,6 +97,14 @@ The process sets a soft memory limit of 160 MiB unless `GOMEMLIMIT` is set.
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.
### Live relay
Besides the export, a hub keeps one `GET /api/v1/peer/stream` connection open per peer (a subscription per peer, with the peer's own token) and relays the live malicious events to its dashboard. What comes from a peer is bounded and sanitized: at most about 50 events per second per peer, lines of at most 16 KB, a buffer of the latest 500 relayed events (served by `/api/v1/live/recent`), and reconnection with backoff from 1 s up to 60 s. A peer serves at most 10 stream connections.
### Geography aggregation
`GET /api/v1/geo` is computed from the IP table (local and the peers' exports) joined with the geolocation databases: countries first, then, for one country, its regions, cities and top IPs. Results are cached for 5 seconds, in a cache of at most 256 keys.
## HTTP layer
The server sets read, write and idle timeouts, `MaxHeaderBytes` of 16 KB, caps `POST /login` at 4 KB and accepts at most 20 simultaneous live-stream (SSE) clients (the 21st gets 503 with `Retry-After`; each stream sends a heartbeat every 20 s). The handler uses the standard `net/http` mux. Every response carries a strict Content-Security-Policy (`default-src 'self'`), `X-Content-Type-Options`, `X-Frame-Options: DENY`, `Referrer-Policy: no-referrer`, cross-origin isolation headers and, over HTTPS, HSTS. API answers are `Cache-Control: no-store`. The dashboard files are embedded in the binary. See [interface.md](interface.md) for the routes and [configuration.md](configuration.md) for the settings.
+1
View File
@@ -33,6 +33,7 @@ The access token is never a flag: `urutau serve` reads it from the `URUTAU_TOKEN
| `--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 federation routes; empty accepts any source with the token |
| `--peer-blocklist` | `URUTAU_PEER_BLOCKLIST` | `on` | `on` lists in the hub's blocklist the hostile IPs seen only by peers (score 50+ and a strong signal); `off` keeps the blocklist to this instance's own IPs |
| `--location` | `URUTAU_LOCATION` | empty | map position of this instance, `"lat,lon"` or `"lat,lon,Label"` |
| `--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) |
+2 -1
View File
@@ -32,6 +32,7 @@ Keep both in `.env` (never versioned) or in your orchestrator's secret store.
| `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 federation routes; empty accepts any source that has the token |
| `URUTAU_PEER_BLOCKLIST` | `on` | `on`: the hub's blocklist includes hostile IPs seen only by peers (score 50+ and a strong signal); `off`: only this instance's own IPs |
| `URUTAU_LOCATION` | empty | where this instance is on the map, `"lat,lon"` or `"lat,lon,Label"` (validated at start). It is the destination of the arcs on the Live page and is shared with the hub; empty lets the page fall back to an estimated destination |
| `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 |
@@ -55,7 +56,7 @@ In the container image the three log paths default to `/logs/traefik/access.log`
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).
The Traffic page 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)
+12 -13
View File
@@ -8,6 +8,10 @@ The dashboard is embedded in the binary: plain HTML, CSS and JavaScript, no buil
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`.
## Navigation
A side rail (a tab bar on phones) holds seven pages. Each page opens with a sentence carrying the number that matters, and the active slice (range, host, domain) is always written under the title. The page lives in the URL hash (`#/overview`, `#/threats`, `#/geo`, `#/live`, `#/traffic`, `#/ips`, `#/sources`), so a view can be bookmarked or shared; the Geography page goes deeper, as in `#/geo/BR/Pernambuco`. An IP detail drawer opens from any IP.
## Header
- A live indicator showing whether the event stream (SSE) is connected (an instance serves at most 20 stream clients at once).
@@ -15,20 +19,15 @@ Open the address of the instance. Without a session you are sent to `/login`: pa
- The **range** selector: `1h`, `24h` or `7d`.
- Language, theme and logout buttons.
## Threats tab
## Pages
- **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).
- **Overview:** the headline numbers (requests, malicious events, hostile and suspicious IPs, bans, the "monitoring" counter of benign monitor requests kept out of the traffic numbers), the timeline and the top IPs.
- **Threats:** stacked counters per category, the live feed of the latest events (log fields are shown as text, never as markup) and the top attacked paths, domains, User-Agents and targeted users.
- **Geography:** a world map by attacker country. Select a country to see its states or regions and its cities (drawn as circles on the zoomed country), the categories and the top IPs; select a region to narrow cities and IPs. The view is `#/geo/<CC>/<region>`.
- **Live:** attacks drawn as animated arcs from their origin to the server that saw them, on a flat map or a 3D globe, with the rate, categories, servers, recent origins and latest events, filters, pause and full screen. It opens by replaying the latest events (`/api/v1/live/recent`), so it is not still on a quiet server. On a hub it also shows the events of every peer. The position of each server comes from `--location`.
- **Traffic:** privacy-friendly web analytics for legitimate traffic, built from the same Traefik log: unique visitors, pages, referrers, countries, browsers, operating systems, devices, response latency (p50 and p95), bytes sent and a world map of visitor countries, per domain. 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).
- **IPs:** a table with score, level (`hostile`, `suspicious`, `low`), categories, hosts, reverse DNS, country, city and ASN, last seen and ban state, with a search box (IP or reverse DNS), a level filter, a "banned only" filter, sorting and paging. The detail drawer shows first and last seen, per-category counts, sample paths, User-Agents (parsed into browser, OS, device, bot or attack tool), domains, users and jails.
- **Sources and hosts:** every instance with its state (online, latency, version), every log source with its state (`following`, `waiting`, `backfill`, `error`), lines read, malformed lines and last event (file paths are not shown), and the **blocklist**: pick a minimum score (default 50), copy 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`.
## Attribution
+9 -1
View File
@@ -83,7 +83,7 @@ Eventos de uma origem confiável (`--trusted`, mais as faixas privadas de `--ign
## 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.
Requisições benignas (`ok`, e os `notfound` que não são varredura) também alimentam a página 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
@@ -97,6 +97,14 @@ O processo define um limite suave de memória de 160 MiB, a menos que `GOMEMLIMI
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.
### Repasse ao vivo
Além do export, um hub mantém uma conexão `GET /api/v1/peer/stream` aberta por peer (uma assinatura por peer, com o token do próprio peer) e repassa os eventos maliciosos ao vivo para o dashboard. O que vem de um peer é limitado e sanitizado: no máximo cerca de 50 eventos por segundo por peer, linhas de no máximo 16 KB, um buffer dos últimos 500 eventos repassados (servido por `/api/v1/live/recent`) e reconexão com backoff de 1 s até 60 s. Um peer atende no máximo 10 conexões de stream.
### Agregação de geografia
`GET /api/v1/geo` é calculado a partir da tabela de IPs (local e os exports dos peers) combinada com as bases de geolocalização: primeiro os países e, para um país, suas regiões, cidades e principais IPs. Os resultados ficam em cache por 5 segundos, num cache de no máximo 256 chaves.
## 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.
+1
View File
@@ -33,6 +33,7 @@ O token de acesso nunca é uma flag: `urutau serve` o lê da variável de ambien
| `--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 as rotas de federação; vazio aceita qualquer origem com o token |
| `--peer-blocklist` | `URUTAU_PEER_BLOCKLIST` | `on` | `on` lista na blocklist do hub os IPs hostis vistos só pelos peers (pontuação 50+ e sinal forte); `off` restringe a blocklist aos IPs da própria instância |
| `--location` | `URUTAU_LOCATION` | vazio | posição desta instância no mapa, `"lat,lon"` ou `"lat,lon,Rótulo"` |
| `--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) |
+2 -1
View File
@@ -32,6 +32,7 @@ Guarde os dois no `.env` (nunca versionado) ou no cofre de segredos do seu orque
| `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 as rotas de federação; vazio aceita qualquer origem que tenha o token |
| `URUTAU_PEER_BLOCKLIST` | `on` | `on`: a blocklist do hub inclui IPs hostis vistos só pelos peers (pontuação 50+ e sinal forte); `off`: só os IPs da própria instância |
| `URUTAU_LOCATION` | vazio | onde esta instância fica no mapa, `"lat,lon"` ou `"lat,lon,Rótulo"` (validado na partida). É o destino dos arcos da página Ao vivo e é repassado ao hub; vazio faz a página usar um destino estimado |
| `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 |
@@ -55,7 +56,7 @@ Na imagem do container os três caminhos de log têm como padrão `/logs/traefik
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).
A página 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)
+12 -13
View File
@@ -8,6 +8,10 @@ O dashboard é embutido no binário: HTML, CSS e JavaScript puros, sem etapa de
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.
## Navegação
Uma barra lateral (barra de abas no celular) reúne sete páginas. Cada página abre com uma frase com o número que importa, e o recorte ativo (intervalo, host, domínio) fica sempre escrito sob o título. A página vive no hash da URL (`#/overview`, `#/threats`, `#/geo`, `#/live`, `#/traffic`, `#/ips`, `#/sources`), então uma visão pode ser salva ou compartilhada; a página Geografia vai mais fundo, como em `#/geo/BR/Pernambuco`. Um painel de detalhe do IP abre a partir de qualquer IP.
## 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).
@@ -15,20 +19,15 @@ Abra o endereço da instância. Sem sessão você é enviado a `/login`: cole o
- O seletor de **intervalo**: `1h`, `24h` ou `7d`.
- Botões de idioma, tema e sair.
## Aba Ameaças
## Páginas
- **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).
- **Visão geral:** os números principais (requisições, eventos maliciosos, IPs hostis e suspeitos, bans, o contador "monitoring" de requisições benignas de monitores, fora dos números de tráfego), a linha do tempo e os principais IPs.
- **Ameaças:** contadores empilhados por categoria, o feed ao vivo dos últimos eventos (campos dos logs são mostrados como texto, nunca como marcação) e os principais caminhos atacados, domínios, User-Agents e usuários visados.
- **Geografia:** um mapa-múndi por país do atacante. Selecione um país para ver seus estados ou regiões e suas cidades (desenhadas como círculos no país ampliado), as categorias e os principais IPs; selecione uma região para restringir cidades e IPs. A visão é `#/geo/<CC>/<região>`.
- **Ao vivo:** ataques desenhados como arcos animados da origem até o servidor que os viu, em mapa plano ou globo 3D, com taxa, categorias, servidores, origens recentes e últimos eventos, filtros, pausa e tela cheia. Abre reproduzindo os últimos eventos (`/api/v1/live/recent`), então não fica parada num servidor calmo. Em um hub mostra também os eventos de cada peer. A posição de cada servidor vem de `--location`.
- **Tráfego:** web analytics amigável à privacidade para o tráfego legítimo, construído do mesmo log do Traefik: visitantes únicos, páginas, referrers, países, navegadores, sistemas operacionais, dispositivos, latência de resposta (p50 e p95), bytes enviados e um mapa-múndi dos países dos visitantes, por domínio. 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).
- **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, com busca (IP ou DNS reverso), filtro de nível, filtro "só banidos", ordenação e paginação. O painel de detalhe mostra 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.
- **Fontes e hosts:** cada instância com seu estado (online, latência, versão), 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), e a **blocklist**: escolha uma pontuação mínima (padrão 50), copie 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`.
## Atribuição
+28 -23
View File
@@ -19,29 +19,30 @@ import (
// Config is the runtime configuration of `urutau serve` and `urutau doctor`.
type Config struct {
Bind string
Name string
DataDir string
TraefikLog string
AuthLog string
Fail2banLog string
Ignore string // networks whose events are dropped (--ignore, alias of --trusted)
Trusted string // trusted sources, e.g. the servers themselves (--trusted)
MonitorUA string // regex of monitoring User-Agents
MonitorFrom string // networks monitors come from (empty: any source)
Domains string // optional allowlist of analytics domains
AdminUsers string // SSH users whose logins grant admin immunity (empty: any user)
PeerTokens []string // tokens accepted by /api/v1/peer/export
PeerTokenFor map[string]string // per peer name (upper case) token used by the hub
GeoDir string // directory of the geo databases (default <data-dir>/geo)
GeoUpdate time.Duration
Peers []string
PeerToken string
Location string // "lat,lon" or "lat,lon,label" (--location)
PeerAllow string // CIDRs allowed to call /api/v1/peer/export (empty: any source with the token)
TrustedProxy string // proxies whose X-Forwarded-For is believed
Retention time.Duration
NoAuth bool
Bind string
Name string
DataDir string
TraefikLog string
AuthLog string
Fail2banLog string
Ignore string // networks whose events are dropped (--ignore, alias of --trusted)
Trusted string // trusted sources, e.g. the servers themselves (--trusted)
MonitorUA string // regex of monitoring User-Agents
MonitorFrom string // networks monitors come from (empty: any source)
Domains string // optional allowlist of analytics domains
AdminUsers string // SSH users whose logins grant admin immunity (empty: any user)
PeerTokens []string // tokens accepted by /api/v1/peer/export
PeerTokenFor map[string]string // per peer name (upper case) token used by the hub
GeoDir string // directory of the geo databases (default <data-dir>/geo)
GeoUpdate time.Duration
Peers []string
PeerToken string
Location string // "lat,lon" or "lat,lon,label" (--location)
PeerBlocklist string // "on" (default) or "off"
PeerAllow string // CIDRs allowed to call /api/v1/peer/export (empty: any source with the token)
TrustedProxy string // proxies whose X-Forwarded-For is believed
Retention time.Duration
NoAuth bool
}
type listFlag []string
@@ -118,6 +119,7 @@ func ParseFlags(name string, args []string) (Config, error) {
fs.Var(allow, "peer-allow", "CIDRs allowed to call /api/v1/peer/export, empty allows any source with the token (URUTAU_PEER_ALLOW)")
fs.Var(tproxy, "trusted-proxy", "reverse proxies whose X-Forwarded-For is trusted for the real client IP (URUTAU_TRUSTED_PROXY)")
fs.StringVar(&c.Location, "location", env("URUTAU_LOCATION", ""), `where this instance lives, "lat,lon" or "lat,lon,label"; shown as the destination of live arcs (URUTAU_LOCATION)`)
fs.StringVar(&c.PeerBlocklist, "peer-blocklist", env("URUTAU_PEER_BLOCKLIST", "on"), "on: the blocklist also lists strong hostile IPs seen only by peers; off: local IPs only (URUTAU_PEER_BLOCKLIST)")
fs.DurationVar(&c.Retention, "retention", 7*24*time.Hour, "how long data is kept, at most 168h (URUTAU_RETENTION)")
fs.BoolVar(&c.NoAuth, "insecure-no-auth", false, "disable authentication; only allowed on a loopback bind")
if v := os.Getenv("URUTAU_GEO_UPDATE"); v != "" {
@@ -174,6 +176,9 @@ func (c Config) Validate(token string) ([]fed.Peer, error) {
if _, err := store.ParseLocation(c.Location); err != nil {
return nil, err
}
if v := strings.ToLower(c.PeerBlocklist); v != "" && v != "on" && v != "off" {
return nil, fmt.Errorf("--peer-blocklist must be on or off")
}
var peers []fed.Peer
seen := map[string]bool{}
envSeen := map[string]string{}
+1 -1
View File
@@ -69,7 +69,7 @@ func Serve(c Config) error {
ign, _ := core.ParseCIDRs(c.Ignore + "," + c.Trusted)
bindHost, _, _ := net.SplitHostPort(c.Bind)
h := server.New(server.Options{Token: token, PeerTokens: c.PeerTokens, PeerAllow: allow, TrustedProxy: tproxy, Ignore: ign,
AllowHosts: []string{bindHost}, NoAuth: c.NoAuth, Version: Version, Store: st, Hub: hub})
AllowHosts: []string{bindHost}, NoAuth: c.NoAuth, LocalBlocklist: strings.EqualFold(c.PeerBlocklist, "off"), Version: Version, Store: st, Hub: hub})
ln, err := net.Listen("tcp", c.Bind)
if err != nil {
return err
+13
View File
@@ -0,0 +1,13 @@
package fed
import "time"
// SetLiveLimits shrinks the flood window, the byte ceiling and the first backoff; it returns the restore func.
func SetLiveLimits(window time.Duration, bytesPerSec int, backoff time.Duration) func() {
w, b, k := liveByteWindow, maxLiveBytes, liveBackoff0
liveByteWindow, maxLiveBytes, liveBackoff0 = window, bytesPerSec, backoff
return func() { liveByteWindow, maxLiveBytes, liveBackoff0 = w, b, k }
}
// WaitStream blocks until the live stream goroutines have returned (after ctx is cancelled).
func (h *Hub) WaitStream() { h.swg.Wait() }
+1
View File
@@ -72,6 +72,7 @@ type Hub struct {
client *http.Client
stream *http.Client // long-lived SSE: no overall timeout, no redirects
swg sync.WaitGroup // live stream goroutines
lmu sync.Mutex
live liveState
+20 -2
View File
@@ -18,10 +18,16 @@ const (
maxLiveRate = 50 // events per second accepted from one peer
liveBuffer = 500 // events kept for /api/v1/live/recent
liveIdle = 70 * time.Second
liveBackoff0 = time.Second
liveBackoffTo = 60 * time.Second
)
// Variables so tests can shrink them.
var (
maxLiveBytes = 1 << 20 // sustained bytes per second accepted from one peer
liveByteWindow = 10 * time.Second
liveBackoff0 = time.Second
)
type liveState struct {
recent []store.LiveEvent // ring of the newest peer events
head int
@@ -97,7 +103,8 @@ func (h *Hub) peerLocation(name string) *store.Location {
// with an exponential backoff (1 s up to 60 s).
func (h *Hub) Stream(ctx context.Context) {
for _, p := range h.Peers {
go h.streamPeer(ctx, p)
h.swg.Add(1)
go func() { defer h.swg.Done(); h.streamPeer(ctx, p) }()
}
}
@@ -152,6 +159,7 @@ func (h *Hub) consume(ctx context.Context, p Peer) error {
rd := bufio.NewReaderSize(resp.Body, maxLiveLine)
var evName string
var tokens = float64(maxLiveRate)
winStart, winBytes := time.Now(), 0
last := time.Now()
for {
line, err := rd.ReadSlice('\n') // ErrBufferFull: a line over 16 KB ends the stream
@@ -159,6 +167,16 @@ func (h *Hub) consume(ctx context.Context, p Peer) error {
return err
}
idle.Reset(liveIdle)
winBytes += len(line)
if float64(winBytes) > float64(maxLiveBytes)*liveByteWindow.Seconds() {
return errLive // a window's worth of budget burned already: flooding
}
if el := time.Since(winStart); el >= liveByteWindow {
if float64(winBytes)/el.Seconds() > float64(maxLiveBytes) {
return errLive // flooding: drop the connection, the backoff applies
}
winStart, winBytes = time.Now(), 0
}
line = bytes.TrimRight(line, "\r\n")
switch {
case bytes.HasPrefix(line, []byte("event:")):
+28 -3
View File
@@ -56,7 +56,7 @@ func TestLiveRelaySanitizesAndDrops(t *testing.T) {
ch, stop := h.Subscribe()
defer stop()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
defer func() { cancel(); h.WaitStream() }()
h.Stream(ctx)
var got []store.LiveEvent
@@ -110,7 +110,7 @@ func TestLiveRateLimitAndFlag(t *testing.T) {
p, _ := fed.ParsePeer("edge=" + srv.URL)
h := fed.NewHub([]fed.Peer{p}, "tok")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
defer func() { cancel(); h.WaitStream() }()
h.Stream(ctx)
deadline := time.Now().Add(5 * time.Second)
for len(h.Recent(500)) == 0 && time.Now().Before(deadline) {
@@ -133,7 +133,7 @@ func TestLiveWithRealPeerServer(t *testing.T) {
p, _ := fed.ParsePeer("edge=" + srv.URL)
h := fed.NewHub([]fed.Peer{p}, "peer-secret-0123456789-abcdefghijklmnopqr")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
defer func() { cancel(); h.WaitStream() }()
h.Refresh(ctx)
h.Stream(ctx)
deadline := time.Now().Add(5 * time.Second)
@@ -153,3 +153,28 @@ func TestLiveWithRealPeerServer(t *testing.T) {
t.Fatalf("hosts %+v", hs)
}
}
func TestLiveByteFloodDropsConnection(t *testing.T) {
defer fed.SetLiveLimits(200*time.Millisecond, 10_000, 100*time.Millisecond)()
start := time.Now()
var conns atomic.Int32
pad := strings.Repeat("a", 1000)
srv := fakeStream(t, &conns, func(w http.ResponseWriter) {
for i := 0; i < 200; i++ { // ~200 KB at once: far above 10 KB/s
fmt.Fprintf(w, ": %s\n", pad)
}
})
defer srv.Close()
p, _ := fed.ParsePeer("edge=" + srv.URL)
h := fed.NewHub([]fed.Peer{p}, "tok")
ctx, cancel := context.WithCancel(context.Background())
defer func() { cancel(); h.WaitStream() }()
h.Stream(ctx)
// the flood ends the connection (window check), then the hub reconnects after the backoff
for conns.Load() < 2 {
if time.Since(start) > 2500*time.Millisecond {
t.Fatalf("no drop and reconnection (%d connections)", conns.Load())
}
time.Sleep(20 * time.Millisecond)
}
}
+31
View File
@@ -2,6 +2,7 @@ package server
import (
"bufio"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
@@ -10,6 +11,7 @@ import (
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
@@ -240,3 +242,32 @@ func TestPeerStreamIsPeerOnly(t *testing.T) {
t.Fatal("no event")
}
}
func TestPeerBlocklistOffUsesLocalOnly(t *testing.T) {
const ptk = "peer-secret-0123456789-abcdefghijklmnopqr"
strongHits := func(st *store.Store, ip string) {
for i := 0; i < 8; i++ {
st.Ingest(core.Event{Time: time.Now(), IP: ip, Cat: core.Exploit, Strong: true, Source: "traefik", Method: "GET", Path: "/x"})
}
}
remote := store.New(store.Config{Name: "remote"})
strongHits(remote, "45.94.31.7") // only the peer saw it
rs := httptest.NewServer(New(Options{Token: utok, PeerTokens: []string{ptk}, Store: remote}))
defer rs.Close()
p, _ := fed.ParsePeer("edge=" + rs.URL)
hub := fed.NewHub([]fed.Peer{p}, ptk)
hub.Refresh(context.Background())
for _, off := range []bool{false, true} {
st := store.New(store.Config{Name: "o"})
strongHits(st, "45.94.31.5")
hh := New(Options{Token: utok, Store: st, Hub: hub, LocalBlocklist: off})
w := do(hh, "GET", "/api/v1/blocklist.txt", map[string]string{"Authorization": "Bearer " + utok}, nil)
b := w.Body.String()
if w.Code != 200 || !strings.Contains(b, "45.94.31.5") {
t.Fatalf("off=%v: local IP missing: %d %s", off, w.Code, b)
}
if has := strings.Contains(b, "45.94.31.7"); has == off {
t.Fatalf("off=%v: peer-only IP listed=%v: %s", off, has, b)
}
}
}
+12 -6
View File
@@ -62,10 +62,12 @@ type Options struct {
PeerAllow []netip.Prefix
TrustedProxy []netip.Prefix
NoAuth bool
Version string
Store *store.Store
Hub *fed.Hub
Now func() time.Time
// LocalBlocklist makes the blocklist use only this instance's IPs (--peer-blocklist=off).
LocalBlocklist bool
Version string
Store *store.Store
Hub *fed.Hub
Now func() time.Time
}
// Server is the HTTP handler.
@@ -464,13 +466,17 @@ func (s *Server) summary(w http.ResponseWriter, r *http.Request) {
// allIPs returns the merged IP table for the requested host selection.
func (s *Server) allIPs(rangeName, host string) []store.IPSummary {
return s.ipsOf(rangeName, host, false)
}
func (s *Server) ipsOf(rangeName, host string, localOnly bool) []store.IPSummary {
rg := store.ParseRange(rangeName)
var lists [][]store.IPSummary
self := s.opt.Store.Name()
if host == "" || host == "all" || host == self {
lists = append(lists, s.opt.Store.AllIPs(rg, false))
}
if s.opt.Hub != nil && host != self {
if s.opt.Hub != nil && host != self && !localOnly {
only := ""
if host != "" && host != "all" {
only = host
@@ -711,7 +717,7 @@ func (s *Server) blocklist(asJSON bool) http.HandlerFunc {
family = "all"
}
var out []store.IPSummary
for _, x := range s.allIPs(rangeName, q.Get("host")) {
for _, x := range s.ipsOf(rangeName, q.Get("host"), s.opt.LocalBlocklist) {
if x.Score < min || !x.Strong || x.Admin {
continue
}
+14 -12
View File
@@ -54,6 +54,8 @@
if (typeof vars !== 'object') vars = { n: vars };
return s.replace(/\{(\w+)\}/g, function (m, k) { return Object.prototype.hasOwnProperty.call(vars, k) ? String(vars[k]) : m; });
}
// plural: picks key.one when count is 1, key.other otherwise
function pl(key, count, vars) { vars = vars || {}; if (vars.n === undefined) vars.n = nf(count); return t(key + (count === 1 ? '.one' : '.other'), vars); }
function registerI18n(dict) {
Object.keys(dict || {}).forEach(function (l) {
if (!D[l]) D[l] = {};
@@ -485,7 +487,7 @@
// ---------------------------------------------------------------- IP table
function sumCounts(c) { var s = 0; for (var k in c) s += c[k]; return s; }
function ipTable(full) {
var st = { sort: 'score', order: 'desc', page: 1, per: full ? 50 : 25, q: '', level: '', banned: false, total: 0, sig: '', ctxKey: '', multi: false, headSig: '' };
var st = { sort: 'score', order: 'desc', page: 1, per: window.innerWidth <= 720 ? 25 : (full ? 50 : 25), q: '', level: '', banned: false, total: 0, sig: '', ctxKey: '', multi: false, headSig: '' };
var timer = 0, alive = true, onTotal = null;
var search = el('input', { type: 'search', autocomplete: 'off', placeholder: t('ips.search'), 'aria-label': t('ips.search') });
var levelSel = el('select', { 'aria-label': t('ips.level') });
@@ -574,7 +576,7 @@
cell('cats', chips, 'nw'); break;
}
case 'origin': {
var org = h('span', 'origin', x.cc ? (flag(x.cc) + ' ' + (x.city ? x.city + ', ' : '') + (x.country || countryName(x.cc))) : '-');
var org = h('span', 'origin', x.cc ? (flag(x.cc) + ' ' + (x.city ? x.city + ', ' : '') + countryName(x.cc)) : '-');
var tip = [x.asn ? 'AS' + x.asn + (x.as_org ? ' ' + x.as_org : '') : '', x.rdns || ''].filter(Boolean);
if (x.cc) tip.unshift(org.textContent);
if (tip.length) org.title = tip.join('\n');
@@ -592,7 +594,7 @@
tbody.appendChild(tr);
});
var pages = Math.max(1, Math.ceil(st.total / st.per));
count.textContent = t('pager.count', nf(st.total));
count.textContent = pl('pager.count', st.total, { n: nf(st.total) });
page.textContent = full ? t('pager.page', { n: nf(st.page), m: nf(pages) }) : '';
prev.disabled = st.page <= 1;
next.disabled = st.page >= pages;
@@ -847,7 +849,7 @@
if (n > bestN) { bestN = n; best = c; }
});
if (!best) return lead(t('th.lead.none'), t('th.lead.noneBody'), 'neutral');
var body = [t('th.lead.body', { n: nf(bestN), m: nf(total), p: pct(bestN, total) })];
var body = [pl('th.lead.body', total, { n: nf(bestN), m: nf(total), p: pct(bestN, total) })];
if (s.top_domains && s.top_domains.length) body.push(t('th.lead.domain', { name: s.top_domains[0].key }));
if (s.countries && s.countries.length) body.push(t('th.lead.origin', { name: countryLabel(s.countries[0].key) }));
return lead(t('th.lead.top', { cat: t('cat.' + best) }), body.join(' '), s.totals.hostile_ips > 0 ? 'danger' : 'ok');
@@ -971,7 +973,7 @@
var v = {};
v.lead = h('div');
v.tbl = ipTable(true);
v.tbl.onTotal(function (n) { setSliceNote(t('slice.ips', nf(n))); });
v.tbl.onTotal(function (n) { setSliceNote(pl('slice.ips', n, { n: nf(n) })); });
v.ips = panel({ title: t('ips.title'), hint: t('ips.hint') }, v.tbl.node);
root.appendChild(v.lead); root.appendChild(v.ips);
return v;
@@ -986,7 +988,7 @@
render: function (v, s) {
var T = s.totals;
clear(v.lead);
v.lead.appendChild(lead(t('ips.lead', { n: nf(T.unique_ips), h: nf(T.hostile_ips), s: nf(T.suspicious_ips) }), t('ips.lead.body', { b: nf(T.active_bans) }), T.hostile_ips > 0 ? 'danger' : T.unique_ips ? 'ok' : 'neutral'));
v.lead.appendChild(lead(pl('ips.lead', T.unique_ips, { n: nf(T.unique_ips), h: nf(T.hostile_ips), s: nf(T.suspicious_ips) }), t('ips.lead.body', { b: nf(T.active_bans) }), T.hostile_ips > 0 ? 'danger' : T.unique_ips ? 'ok' : 'neutral'));
},
dispose: function (v) { v.tbl.dispose(); setSliceNote(''); }
});
@@ -1005,7 +1007,7 @@
h('div', 'toolbar', h('label', 'check', h('span', null, t('blocklist.minScore')), minScore), fam, copy, dlTxt, dlJson), count, msg);
var timer = 0, alive = true;
function query(extra) {
var o = { host: state.host, min_score: minScore.value || '50', family: fam.value };
var o = { host: state.host, range: state.range, min_score: minScore.value || '50', family: fam.value };
for (var k in extra) o[k] = extra[k];
return new URLSearchParams(o).toString();
}
@@ -1014,10 +1016,10 @@
dlJson.setAttribute('href', '/api/v1/blocklist.json?' + query({ download: '1' }));
clearTimeout(timer);
timer = setTimeout(function () {
api('/api/v1/blocklist.json', { host: state.host, min_score: minScore.value || '50', family: fam.value }).then(function (j) {
api('/api/v1/blocklist.json', { host: state.host, range: state.range, min_score: minScore.value || '50', family: fam.value }).then(function (j) {
if (!alive) return;
var arr = Array.isArray(j) ? j : (j.items || j.ips || []);
count.textContent = t('blocklist.count', nf(typeof j.count === 'number' ? j.count : arr.length));
count.textContent = pl('blocklist.count', typeof j.count === 'number' ? j.count : arr.length, { n: nf(typeof j.count === 'number' ? j.count : arr.length) });
}).catch(function () { /* optional preview */ });
}, 250);
}
@@ -1029,7 +1031,7 @@
return r.text();
}).then(function (txt) {
var n = txt.split('\n').filter(Boolean).length;
return copyText(txt).then(function () { msg.textContent = t('blocklist.copied', nf(n)); });
return copyText(txt).then(function () { msg.textContent = pl('blocklist.copied', n, { n: nf(n) }); });
}).catch(function () { msg.textContent = t('blocklist.failed'); });
});
return { node: node, sync: sync, dispose: function () { alive = false; clearTimeout(timer); } };
@@ -1073,7 +1075,7 @@
var lines = 0, bad = 0;
srcs.forEach(function (r) { lines += r.lines || 0; bad += r.malformed || 0; });
var online = hosts.filter(function (x) { return x.online; }).length;
var title = !srcs.length ? t('src.lead.none') : following === srcs.length ? t('src.lead.all', { n: nf(srcs.length) }) : t('src.lead.some', { a: nf(following), n: nf(srcs.length), x: nf(srcs.length - following) });
var title = !srcs.length ? t('src.lead.none') : following === srcs.length ? pl('src.lead.all', srcs.length, { n: nf(srcs.length) }) : t('src.lead.some', { a: nf(following), n: nf(srcs.length), x: nf(srcs.length - following) });
clear(v.lead);
v.lead.appendChild(lead(title, t('src.lead.body', { h: nf(online), m: nf(hosts.length), l: nf(lines), f: nf(bad) }), !srcs.length ? 'neutral' : following === srcs.length && online === hosts.length ? 'ok' : 'danger'));
clear(v.hostsBox);
@@ -1278,7 +1280,7 @@
}
window.Urutau = {
registerPage: registerPage, registerI18n: registerI18n, t: t, api: api, onEvent: onEvent, openIP: openIP,
registerPage: registerPage, registerI18n: registerI18n, t: t, pl: pl, api: api, onEvent: onEvent, openIP: openIP,
fmt: { num: nf, pct: pct, ago: ago, bytes: fmtBytes, flag: flag, country: countryName, clock: clock, date: dateTime },
world: world, el: el, css: cssVar, setSliceNote: setSliceNote,
ui: { panel: panel, stat: stat, lead: lead, empty: empty, badge: badge, bars: bars, chart: chart }
+46 -32
View File
@@ -42,7 +42,8 @@ window.URUTAU_I18N = {
'slice.host': 'host {name}',
'slice.allDomains': 'all domains',
'slice.domain': 'domain {name}',
'slice.ips': '{n} IPs',
'slice.ips.one': '{n} IP',
'slice.ips.other': '{n} IPs',
'kpi.requests': 'Requests',
'kpi.malicious': 'Malicious events',
'kpi.hostile': 'Hostile IPs',
@@ -50,7 +51,7 @@ window.URUTAU_I18N = {
'kpi.bans': 'Active bans',
'kpi.ips': 'Distinct IPs',
'kpi.monitoring': '{n} monitoring requests filtered out.',
'kpi.sub.hosts': '{n} of {m} hosts online',
'kpi.sub.hosts': 'hosts online: {n} of {m}',
'kpi.sub.malicious': 'HTTP and SSH events',
'kpi.sub.share': '{p} of {n} distinct IPs',
'kpi.sub.bans': 'reported by fail2ban',
@@ -59,7 +60,7 @@ window.URUTAU_I18N = {
'ov.lead.hostile.one': '1 hostile IP in the selected slice',
'ov.lead.calm': 'No hostile IPs in the selected slice',
'ov.lead.empty': 'No events recorded in the selected slice',
'ov.lead.body': '{m} malicious events against {r} requests, from {ips} distinct IPs; {b} active bans.',
'ov.lead.body': 'Malicious events: {m}; requests: {r}; distinct IPs: {ips}; active bans: {b}.',
'ov.lead.bodyEmpty': 'Widen the time range or choose another host. Sources report their state under Sources and hosts.',
'ov.countries': 'Top countries',
'ov.countries.hint': 'Origin of the events in the slice, by number of events.',
@@ -71,19 +72,22 @@ window.URUTAU_I18N = {
'th.lead.top': 'Most activity is classified as "{cat}"',
'th.lead.none': 'No attack activity in the selected slice',
'th.lead.noneBody': 'No scanner, exploit, brute force or SSH events were classified in this slice.',
'th.lead.body': '{n} of {m} classified events ({p}).',
'th.lead.body.one': '{n} of {m} classified event ({p}).',
'th.lead.body.other': '{n} of {m} classified events ({p}).',
'th.lead.domain': 'Most targeted domain: {name}.',
'th.lead.origin': 'Main origin: {name}.',
'tr.lead.some': '{n} visitors viewed {p} pages',
'tr.lead.some': 'Visitors: {n} · page views: {p}',
'tr.lead.none': 'No traffic recorded in the selected slice',
'tr.lead.noneBody': 'Analytics count only successful responses to non-bot clients on the configured domains.',
'tr.lead.body': '{r} requests, {b} from search and AI bots; latency p50 {a} ms and p95 {c} ms.',
'ips.lead': '{n} distinct IPs, {h} hostile and {s} suspicious',
'ips.lead.body': '{b} IPs are banned. Select a row for the full history of an IP.',
'src.lead.all': 'All {n} sources are following',
'src.lead.some': '{a} of {n} sources following; {x} need attention',
'tr.lead.body': 'Requests: {r}, of which {b} from search and AI bots; latency p50 {a} ms and p95 {c} ms.',
'ips.lead.one': '{n} distinct IP: {h} hostile, {s} suspicious',
'ips.lead.other': '{n} distinct IPs: {h} hostile, {s} suspicious',
'ips.lead.body': 'Banned IPs: {b}. Select a row for the full history of an IP.',
'src.lead.all.one': 'The only source is being followed',
'src.lead.all.other': 'All {n} sources are being followed',
'src.lead.some': 'Sources following: {a} of {n}; needing attention: {x}',
'src.lead.none': 'No log sources reported',
'src.lead.body': '{h} of {m} hosts online; {l} lines read, {f} malformed.',
'src.lead.body': 'Hosts online: {h} of {m}; lines read: {l}; malformed: {f}.',
'feed.forged': 'forged monitor user agent',
'timeline.title': 'Activity by category',
'timeline.hint': 'Events per time bucket, stacked by category. Select a legend item to hide it.',
@@ -116,7 +120,8 @@ window.URUTAU_I18N = {
'col.lastEvent': 'Last event',
'pager.prev': 'Previous',
'pager.next': 'Next',
'pager.count': '{n} IPs',
'pager.count.one': '{n} IP',
'pager.count.other': '{n} IPs',
'pager.page': 'Page {n} of {m}',
'feed.title': 'Live feed',
'feed.empty': 'Waiting for events.',
@@ -135,9 +140,11 @@ window.URUTAU_I18N = {
'blocklist.copy': 'Copy list',
'blocklist.download': 'Download .txt',
'blocklist.downloadJson': 'Download .json',
'blocklist.copied': '{n} IPs copied.',
'blocklist.copied.one': '{n} IP copied.',
'blocklist.copied.other': '{n} IPs copied.',
'blocklist.failed': 'Could not copy the list.',
'blocklist.count': '{n} IPs would be listed (last 7 days).',
'blocklist.count.one': '{n} IP would be listed (selected range).',
'blocklist.count.other': '{n} IPs would be listed (selected range).',
'hosts.title': 'Hosts and peers',
'hosts.hint': 'This instance and the peers it federates with.',
'host.online': 'online',
@@ -154,8 +161,8 @@ window.URUTAU_I18N = {
'sources.empty': 'No log source configured on the reporting hosts.',
'src.geo.title': 'Geolocation',
'src.geo.hint': 'Country, city and network of each IP come from a local database; nothing is queried online.',
'src.geo.known': '{n} of {m} listed IPs have a known origin',
'src.geo.countries': '{n} countries in the slice',
'src.geo.known': 'Listed IPs with a known origin: {n} of {m}',
'src.geo.countries': 'Countries in the slice: {n}',
'src.geo.attrib': 'Data attribution',
'src.geo.none': 'No attribution reported by the geo database.',
'state.following': 'following',
@@ -271,7 +278,8 @@ window.URUTAU_I18N = {
'slice.host': 'host {name}',
'slice.allDomains': 'todos os domínios',
'slice.domain': 'domínio {name}',
'slice.ips': '{n} IPs',
'slice.ips.one': '{n} IP',
'slice.ips.other': '{n} IPs',
'kpi.requests': 'Requisições',
'kpi.malicious': 'Eventos maliciosos',
'kpi.hostile': 'IPs hostis',
@@ -279,7 +287,7 @@ window.URUTAU_I18N = {
'kpi.bans': 'Bans ativos',
'kpi.ips': 'IPs distintos',
'kpi.monitoring': '{n} requisições de monitoramento filtradas.',
'kpi.sub.hosts': '{n} de {m} hosts online',
'kpi.sub.hosts': 'hosts online: {n} de {m}',
'kpi.sub.malicious': 'eventos HTTP e SSH',
'kpi.sub.share': '{p} dos {n} IPs distintos',
'kpi.sub.bans': 'informados pelo fail2ban',
@@ -288,7 +296,7 @@ window.URUTAU_I18N = {
'ov.lead.hostile.one': '1 IP hostil no recorte selecionado',
'ov.lead.calm': 'Nenhum IP hostil no recorte selecionado',
'ov.lead.empty': 'Nenhum evento registrado no recorte selecionado',
'ov.lead.body': '{m} eventos maliciosos frente a {r} requisições, de {ips} IPs distintos; {b} bans ativos.',
'ov.lead.body': 'Eventos maliciosos: {m}; requisições: {r}; IPs distintos: {ips}; bans ativos: {b}.',
'ov.lead.bodyEmpty': 'Recomenda-se ampliar o período ou escolher outro host. O estado das fontes está em Fontes e hosts.',
'ov.countries': 'Principais países',
'ov.countries.hint': 'Origem dos eventos do recorte, por número de eventos.',
@@ -300,19 +308,22 @@ window.URUTAU_I18N = {
'th.lead.top': 'A maior parte da atividade é classificada como "{cat}"',
'th.lead.none': 'Nenhuma atividade de ataque no recorte selecionado',
'th.lead.noneBody': 'Nenhum evento de scanner, exploit, força bruta ou SSH foi classificado neste recorte.',
'th.lead.body': '{n} de {m} eventos classificados ({p}).',
'th.lead.body.one': '{n} de {m} evento classificado ({p}).',
'th.lead.body.other': '{n} de {m} eventos classificados ({p}).',
'th.lead.domain': 'Domínio mais visado: {name}.',
'th.lead.origin': 'Origem principal: {name}.',
'tr.lead.some': '{n} visitantes em {p} páginas vistas',
'tr.lead.some': 'Visitantes: {n} · páginas vistas: {p}',
'tr.lead.none': 'Nenhum tráfego registrado no recorte selecionado',
'tr.lead.noneBody': 'A análise de tráfego conta apenas respostas bem-sucedidas a clientes que não são bots, nos domínios configurados.',
'tr.lead.body': '{r} requisições, {b} de bots de busca e de IA; latência p50 de {a} ms e p95 de {c} ms.',
'ips.lead': '{n} IPs distintos, {h} hostis e {s} suspeitos',
'ips.lead.body': '{b} IPs estão banidos. Selecione uma linha para ver o histórico completo do IP.',
'src.lead.all': 'As {n} fontes estão sendo acompanhadas',
'src.lead.some': '{a} de {n} fontes acompanhadas; {x} exigem atenção',
'tr.lead.body': 'Requisições: {r}, das quais {b} de bots de busca e de IA; latência p50 de {a} ms e p95 de {c} ms.',
'ips.lead.one': '{n} IP distinto: {h} hostis, {s} suspeitos',
'ips.lead.other': '{n} IPs distintos: {h} hostis, {s} suspeitos',
'ips.lead.body': 'IPs banidos: {b}. Selecione uma linha para ver o histórico completo do IP.',
'src.lead.all.one': 'A única fonte está sendo acompanhada',
'src.lead.all.other': 'As {n} fontes estão sendo acompanhadas',
'src.lead.some': 'Fontes acompanhadas: {a} de {n}; exigem atenção: {x}',
'src.lead.none': 'Nenhuma fonte de log informada',
'src.lead.body': '{h} de {m} hosts online; {l} linhas lidas, {f} malformadas.',
'src.lead.body': 'Hosts online: {h} de {m}; linhas lidas: {l}; malformadas: {f}.',
'feed.forged': 'user-agent de monitor forjado',
'timeline.title': 'Atividade por categoria',
'timeline.hint': 'Eventos por intervalo de tempo, empilhados por categoria. Selecione um item da legenda para ocultá-lo.',
@@ -345,7 +356,8 @@ window.URUTAU_I18N = {
'col.lastEvent': 'Último evento',
'pager.prev': 'Anterior',
'pager.next': 'Próxima',
'pager.count': '{n} IPs',
'pager.count.one': '{n} IP',
'pager.count.other': '{n} IPs',
'pager.page': 'Página {n} de {m}',
'feed.title': 'Feed ao vivo',
'feed.empty': 'Aguardando eventos.',
@@ -364,9 +376,11 @@ window.URUTAU_I18N = {
'blocklist.copy': 'Copiar lista',
'blocklist.download': 'Baixar .txt',
'blocklist.downloadJson': 'Baixar .json',
'blocklist.copied': '{n} IPs copiados.',
'blocklist.copied.one': '{n} IP copiado.',
'blocklist.copied.other': '{n} IPs copiados.',
'blocklist.failed': 'Não foi possível copiar a lista.',
'blocklist.count': '{n} IPs seriam listados (últimos 7 dias).',
'blocklist.count.one': '{n} IP seria listado (período selecionado).',
'blocklist.count.other': '{n} IPs seriam listados (período selecionado).',
'hosts.title': 'Hosts e pares',
'hosts.hint': 'Esta instância e os pares com os quais ela se federa.',
'host.online': 'online',
@@ -383,8 +397,8 @@ window.URUTAU_I18N = {
'sources.empty': 'Nenhuma fonte de log configurada nos hosts informantes.',
'src.geo.title': 'Geolocalização',
'src.geo.hint': 'País, cidade e rede de cada IP vêm de uma base local; nenhuma consulta é feita online.',
'src.geo.known': '{n} de {m} IPs listados têm origem conhecida',
'src.geo.countries': '{n} países no recorte',
'src.geo.known': 'IPs listados com origem conhecida: {n} de {m}',
'src.geo.countries': 'Países no recorte: {n}',
'src.geo.attrib': 'Atribuição dos dados',
'src.geo.none': 'Nenhuma atribuição informada pela base de geolocalização.',
'state.following': 'acompanhando',
+6
View File
@@ -412,6 +412,12 @@ aside#detail li { overflow-wrap: anywhere; margin-bottom: 2px; }
table.stack td::before { content: attr(data-label); color: var(--ink-muted); font-size: .75rem; text-transform: uppercase; letter-spacing: .06em; text-align: left; flex: none; }
table.stack td > * { min-width: 0; }
table.stack td.nw, table.stack td.nw * { white-space: normal; }
table.stack tr.row { display: grid; grid-template-columns: 1fr 1fr; gap: 2px 12px; padding: 8px 10px; margin: 6px 0; border: 1px solid var(--line); border-radius: var(--radius-sm); background: var(--surface-raised); }
table.stack tr.row td { display: block; text-align: left; min-width: 0; padding: 0; }
table.stack tr.row td::before { display: block; margin-bottom: 0; }
table.stack tr.row td:first-child { grid-column: 1 / -1; font-weight: 600; }
table.stack tr.row td:first-child::before { display: none; }
table.stack tr.row td:nth-child(4), table.stack tr.row td:nth-child(5) { grid-column: 1 / -1; }
.origin { max-width: none; white-space: normal; }
.kv { grid-template-columns: 1fr; gap: 0; }
.kv dt { margin-top: 8px; }
+9 -2
View File
@@ -149,7 +149,7 @@ func (e *PeerExport) Sanitize(rangeName string) error {
x.Domains, x.Samples = clipList(x.Domains, maxDomain, 120), clipList(x.Samples, maxSample, 300)
x.UAs, x.UALabels = clipList(x.UAs, maxUAs, 200), clipList(x.UALabels, maxUAs, 120)
x.Jails = clipList(x.Jails, maxJails, 40)
x.RDNS, x.CC, x.Country, x.City, x.ASOrg = clipS(x.RDNS, 200), clipS(x.CC, 2), clipS(x.Country, 80), clipS(x.City, 80), clipS(x.ASOrg, 120)
x.RDNS, x.CC, x.Country, x.City, x.ASOrg = clipS(x.RDNS, 200), validCC2(clipS(x.CC, 2)), clipS(x.Country, 80), clipS(x.City, 80), clipS(x.ASOrg, 120)
ips = append(ips, x)
}
s.IPs = ips
@@ -170,8 +170,15 @@ func (e *PeerExport) Sanitize(rangeName string) error {
r := &s.Recent[i]
r.IP, r.Cat, r.Source = clipS(r.IP, 45), clipS(r.Cat, 20), clipS(r.Source, 20)
r.Domain, r.Method, r.Path = clipS(r.Domain, 100), clipS(r.Method, 12), clipS(r.Path, 240)
r.User, r.Jail, r.CC = clipS(r.User, 64), clipS(r.Jail, 40), clipS(r.CC, 2)
r.User, r.Jail = clipS(r.User, 64), clipS(r.Jail, 40)
}
kept := s.Recent[:0]
for _, r := range s.Recent {
if SanitizeFeed(&r) {
kept = append(kept, r)
}
}
s.Recent = kept
if len(s.Sources) > 16 {
s.Sources = s.Sources[:16]
}
+13 -1
View File
@@ -136,7 +136,7 @@ func (e *LiveEvent) Sanitize(now int64) bool {
if e.Status < 0 || e.Status > 999 {
e.Status = 0
}
e.Unban = false
e.Unban, e.Forged = false, false
e.CC = validCC2(clipS(e.CC, 2))
if e.Src != nil {
if !validLatLon(e.Src.Lat, e.Src.Lon) {
@@ -158,3 +158,15 @@ func validCC2(cc string) string {
// String is for debugging.
func (l Location) String() string { return fmt.Sprintf("%.4f,%.4f %s", l.Lat, l.Lon, l.Label) }
// SanitizeFeed validates a feed row that came from a peer's summary; false drops it.
func SanitizeFeed(r *FeedEvent) bool {
a, err := netip.ParseAddr(r.IP)
if err != nil || a.Zone() != "" {
return false
}
r.IP = a.Unmap().String()
r.CC = validCC2(clipS(r.CC, 2))
r.Unban, r.Forged = false, false
return true
}
+21
View File
@@ -35,3 +35,24 @@ func TestPeerLocationAndLiveSanitize(t *testing.T) {
t.Fatalf("%+v", le)
}
}
func TestPeerRowsAreSanitized(t *testing.T) {
le := LiveEvent{FeedEvent: FeedEvent{IP: "1.2.3.4", Cat: "scanner", T: 1, Forged: true, Unban: true, CC: "<s"}}
if !le.Sanitize(1_800_000_000) || le.Forged || le.Unban || le.CC != "" {
t.Fatalf("%+v", le)
}
e := PeerExport{V: ExportVersion, Summary: Summary{
Recent: []FeedEvent{{IP: "<script>", Cat: "scanner"}, {IP: "5.6.7.8", Cat: "scanner", CC: "<s", Forged: true}},
IPs: []IPSummary{{IP: "9.9.9.9", CC: "<s", Score: 1}},
}}
if err := e.Sanitize("24h"); err != nil {
t.Fatal(err)
}
r := e.Summary.Recent
if len(r) != 1 || r[0].IP != "5.6.7.8" || r[0].CC != "" || r[0].Forged {
t.Fatalf("%+v", r)
}
if e.Summary.IPs[0].CC != "" {
t.Fatal("cc must be validated")
}
}
+1
View File
@@ -96,6 +96,7 @@ for (const f of jsFiles) {
// do not treat the dictionaries themselves as usage
for (const d of dicts) if (d.file === f && d.literal) src = src.replace(d.literal, '');
for (const m of src.matchAll(/\bt\(\s*'([^']+)'/g)) use(m[1], f);
for (const m of src.matchAll(/\bpl\(\s*'([^']+)'/g)) { use(m[1] + '.one', f); use(m[1] + '.other', f); }
for (const m of src.matchAll(/\b(?:titleKey|labelKey)\s*:\s*'([^']+)'/g)) use(m[1], f);
for (const m of src.matchAll(/'([A-Za-z][A-Za-z0-9-]*(?:\.[A-Za-z0-9-]+)*\.?)'/g)) literals.add(m[1]);
}