Compare commits

...
7 Commits
Author SHA1 Message Date
Lucas RayanandClaude Opus 5.5 c33cca22e3 feat: 1.4.0 second firewall, egress analysis and HTML report
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 28s
CI / Dependency audit (push) Successful in 16s
CI / Tests (Linux, race detector) (push) Successful in 1m3s
Release / Plan (reuse the published image?) (push) Successful in 4s
Release / ci (push) Skipped
Release / Build image (amd64) (push) Skipped
Release / Build image (arm64) (push) Skipped
Release / Publish tags (push) Successful in 13s
Release / Gitea release (push) Successful in 3s
Optional second firewall (URUTAU_ENFORCE off/observe/on) through the host
fail2ban, outbound traffic analysis (beaconing, mining, spam, DNS bypass,
unauthorised scans) with authorised scanner workloads, host kit in
deploy/host and a printable HTML report.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 23:35:34 -03:00
Lucas RayanandClaude Opus 5.5 3adaa007ec docs: 1.3.0 pages, error classes, visitors and APIs
Release / Plan (reuse the published image?) (push) Successful in 4s
Release / ci (push) Skipped
Release / Build image (amd64) (push) Skipped
Release / Build image (arm64) (push) Skipped
Release / Publish tags (push) Successful in 12s
Release / Gitea release (push) Successful in 3s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 22:42:38 -03:00
Lucas RayanandClaude Opus 5.5 2ebda1e4d7 feat: 1.3.0 thirteen new pages, charts, tooltips and error analysis
Release / Plan (reuse the published image?) (push) Successful in 3s
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 28s
CI / Dependency audit (push) Successful in 20s
CI / Tests (Linux, race detector) (push) Successful in 1m10s
Release / ci (push) Successful in 1m10s
Release / Build image (arm64) (push) Successful in 55s
Release / Build image (amd64) (push) Successful in 1m16s
Release / Publish tags (push) Successful in 14s
Release / Gitea release (push) Skipped
New pages grouped in the rail (Monitor, Investigate, Analyze, Operate,
Reports): Services (SLO, Apdex, latency app vs proxy), Sessions (stage
funnel), Campaigns, Event search, MITRE ATT&CK matrix, Evolution,
Concentration (Pareto, Gini), Survival (Kaplan-Meier per attack
episode, recidivists), Where errors come from (application vs failed
attack vs proxy vs client), Protocols and TLS, Defense (fail2ban, SSH,
blocklist), Integrity, and a printable executive report.

Chart library (donut, radar, stacked area, bars, heatmap, gauge),
glossary with accessible "?" tooltips, self-explanatory category names
(nonexistent page 404), page loader through pages.json.

Unique visitors fixed: real browsers opening a page, one per IP per day,
deduplicated across domains, with non-human clients counted apart.
Anonymous legitimate visits on the Live page (?visits=1, no IP).
Traefik origin, service, protocol and TLS fields parsed. Paths and
Referer paths drop e-mail and token segments.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 22:39:33 -03:00
Lucas RayanandClaude Opus 5.5 b7462c14fa feat: 1.2.0 attack intelligence, replay, 30-day history and new interface
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 27s
CI / Dependency audit (push) Successful in 18s
CI / Tests (Linux, race detector) (push) Successful in 58s
Release / Plan (reuse the published image?) (push) Successful in 4s
Release / ci (push) Skipped
Release / Build image (amd64) (push) Skipped
Release / Build image (arm64) (push) Skipped
Release / Publish tags (push) Successful in 13s
Release / Gitea release (push) Successful in 5s
Intelligence: attack families mapped to MITRE ATT&CK, network type from
ASN/rDNS without external APIs, request cadence, sessions with
recon/probe/exploit/access/banned stages, campaigns across IPs, verdict
with reasons, recommended actions, exposure detection (2xx with a body
on sensitive paths), STIX 2.1 export, FCrDNS for search engine bots,
optional Tor exit list.

Data: 30-day retention, twelve ranges plus custom from/to, an on-disk
event log (daily files, hourly gzip members, size cap, corruption and
disk-full tolerant), /events, /period, /metrics with stable per-hour
metrics, an extended /ip/{ip}, and peer /period merged on the hub.

Interface: layout system with fixed card sizes, range picker in the
URL, IP analysis page, Replay page, Geography down to state and city
(Natural Earth admin-1), Live page redesigned with stable metrics and a
reusable attack map. Demo data and documentation screenshots.

Security: bounded and deadline-limited period computations, linear
campaign clustering, singleflight caches, sanitized peer studies, event
query budgets, gzip bomb guard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 21:45:59 -03:00
Lucas RayanandClaude Opus 5.5 8f1ac462d1 fix(live): globe sea and land colors, world map antimeridian rings
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 22s
CI / Tests (Linux, race detector) (push) Successful in 33s
CI / Dependency audit (push) Successful in 13s
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 14s
Release / Gitea release (push) Successful in 3s
The globe clipped country rings by pushing hidden vertices to the limb
and closing them with chords, so the fill flipped between sea and land
as it turned. Rings are now clipped at the horizon and closed along the
limb in their own orientation; the path parser returns to the subpath
start after z; long edges follow the map projection.

gen-world.mjs unwraps longitudes and clips rings that cross the 180th
meridian (Russia, Fiji) at the map edge instead of leaving them open,
which filled the Sea of Okhotsk as land.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 19:27:57 -03:00
Lucas RayanandClaude Opus 5.5 783b0cba3e 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>
2026-11-14 18:10:54 -03:00
Lucas RayanandClaude Opus 5.5 f4b295f582 feat: 1.1.0 interface, geography drill-down and live attack map
Release / Plan (reuse the published image?) (push) Successful in 4s
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 19s
CI / Tests (Linux, race detector) (push) Successful in 35s
CI / Dependency audit (push) Successful in 16s
Release / ci (push) Successful in 35s
Release / Build image (arm64) (push) Successful in 51s
Release / Build image (amd64) (push) Successful in 1m11s
Release / Publish tags (push) Successful in 13s
Release / Gitea release (push) Skipped
A new console interface (side rail, seven pages, opening sentence and
active slice on every page, IP drawer, light and dark design tokens);
a Geography page that drills from the world to a country's regions and
cities; a Live page drawing attacks as arcs on a flat map or a globe.

Backend: GET /api/v1/geo, GET /api/v1/live/recent, host/src/dst on live
events, --location, a strict static file pattern, and live federation
through GET /api/v1/peer/stream (peer token only, bounded and sanitized
relay on the hub).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 17:47:28 -03:00
436 changed files with 40271 additions and 1391 deletions

No files matched your search

+7
View File
@@ -47,3 +47,10 @@ URUTAU_DOMAINS=
URUTAU_MONITOR_FROM=
# Time zone of the host: fail2ban.log timestamps are local time.
TZ=UTC
# Event registry size cap in <data-dir>/events (0 turns it off). Not passed by the
# compose file as is: add it to the `environment` block to change the 512MB default.
URUTAU_EVENTS_MAX=512MB
# Retention, up to 720h (30 days); same note as above.
URUTAU_RETENTION=720h
# File with Tor exit addresses (one per line); same note as above.
URUTAU_TOR_EXITS=
+4
View File
@@ -22,3 +22,7 @@ __pycache__/
/.superpowers
/.superset
/graphify-out
# Runtime pid files left by local test scripts
*.pid
pid
+69 -1
View File
@@ -6,6 +6,74 @@ Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versio
## [Unreleased]
## [1.4.0] - 2026-11-15
### Added
- Second firewall (optional, `URUTAU_ENFORCE=off|observe|on`): Urutau decides which attacking addresses to block and writes the decisions to a file; the host fail2ban (jail `urutau`) applies them. Urutau gets no privileges. Observe mode shows what would be blocked. Optional decision sharing between hub and peers (`URUTAU_ENFORCE_SHARE`), applied only when the receiving server also saw the address attack. Never blocks trusted addresses, private ranges, CDN (Cloudflare) and public resolver ranges, peers or the server itself. The ban only drops connections the address starts, so replies to the server's own connections keep flowing.
- Egress analysis (`URUTAU_EGRESS`): new outbound connections of the host and containers, logged by nftables, are checked for beaconing (regular conversations with one destination), mining, IRC and SMTP ports, contact with addresses that attacked the server or Tor exits, DNS outside the allowed resolvers, unauthorised outbound scans and new countries. Workloads by network or container name (`URUTAU_EGRESS_WORKLOADS`); a `scanner` workload (an authorised surface scanner) has only its scan-shaped traffic summarised, everything else is judged like any other workload, so its beaconing is still detected.
- Host kit in `deploy/host` (nftables table, rsyslog, logrotate, container map, fail2ban filter, action and jail, `install.sh`).
- New page Outbound traffic and a Second firewall section in Defense.
- HTML report (`/api/v1/report?format=html`): cover, executive summary in plain language, rule-based recommendations, threats, geography, errors and health, visitors, defense, second firewall and outbound traffic, printable on A4. The Reports page downloads or prints it.
- Screenshot script covers every page.
## [1.3.0] - 2026-11-14
### Added
- **Many more pages**, grouped in the side rail: Monitor (Overview, Live, Services), Investigate (IPs, Sessions, Campaigns, Replay, Event search), Analyze (Threats, MITRE ATT&CK, Geography, Evolution, Concentration, Survival, Traffic, Where errors come from, Protocols and TLS), Operate (Defense, Sources and hosts, Integrity) and Reports. A glossary: a "?" button next to metrics and categories explains what each one means and what to do about it.
- **Service health:** per-service SLO (target 99.5%), error budget, burn rate (1 h and 6 h) and Apdex, from the Traefik router and service names.
- **Error classes:** every error is classified as `app`, `proxy`, `blocked`, `attack`, `bot`, `client` or `unknown`, so a 5xx from your app is told apart from a broken link or a scanner. The Traefik fields `OriginStatus`, `OriginDuration`, `Overhead`, `OriginContentSize`, `RetryAttempts`, `RouterName`, `ServiceName`, `RequestProtocol`, `RequestScheme`, `TLSVersion` and `TLSCipher` are read when present.
- **Episodes and survival:** time to ban and Kaplan-Meier survival curves computed over attack episodes.
- **New routes** (user only, never the peer token): `GET /api/v1/techniques`, `/evolution`, `/concentration`, `/survival`, `/sessions/funnel`, `/campaigns`, `/campaigns/{id}`, `/defense`, `/errors`, `/integrity`, `/report`, `/services`, `/services/{svc}` and `/protocols`.
- **Legitimate visits stream:** `GET /api/v1/events/stream?visits=1` also sends anonymous visit events (no address, User-Agent or referrer; city-level position), at most 20 per second, never written to disk.
- Documentation of the geolocation refresh: Urutau checks every 24 hours (`--geo-update`) while DB-IP publishes once a month.
### Changed
- **Unique visitors were corrected.** A visitor is now a person with a real browser: a successful GET of a document by a browser User-Agent (not a bot, tool or unknown client, not a prefetch), one per IP per day, deduplicated globally. Bots, tools and unknown clients are counted apart as "non-human clients". The number is lower than before, and lower than Coolify's, which counts every distinct IP with HyperLogLog and no filter.
- Paths and `Referer` values that contain an e-mail address or a token are normalized to `:id`.
## [1.2.0] - 2026-11-14
### Added
- **Longer memory and any period:** the default and maximum retention is now 30 days (720h). Twelve ranges (`1h`, `2h`, `3h`, `6h`, `12h`, `24h`, `2d`, `3d`, `5d`, `7d`, `15d`, `30d`) and a custom period with `from` and `to` (unix seconds, at most 30 days). An invalid `range` answers 400, and `range` in the responses is now an object `{name,from,to,step,clipped}`; the timeline `step` (granularity) follows the window length.
- **Event registry** in `<data-dir>/events/`: one JSON line per event (the live-stream format), one file per UTC day, older days gzip compressed, bounded by age (the retention) and size (`--events-max` / `URUTAU_EVENTS_MAX`, default 512 MB, `0` turns it off). It keeps malicious events, ban and unban, successful SSH logins, a 404 to an attack tool, and `ok`/`notfound` answers only for addresses already suspicious or hostile; never a legitimate visitor. A full disk, the size cap or the daily line cap drop events (counted, never fatal), and a corrupted line is skipped.
- **Investigation API:** `GET /api/v1/events`, `/api/v1/events/sessions`, `/api/v1/period`, `/api/v1/period/events`, `/api/v1/metrics`, the new summarized `GET /api/v1/ip/{ip}` and `GET /api/v1/ip/{ip}/stix`; and the peer route `GET /api/v1/peer/period`, so the peer token now opens three routes (export, stream and period).
- **Intelligence:** attack families, MITRE ATT&CK techniques, network type (VPN, hosting, mobile, residential, Tor, research scanner; no external API), request cadence (automated, human-like, mixed), sessions with stages (recon, probe, exploit, access, banned), campaigns (several IPs doing the same thing), a verdict with reasons, recommended actions, exposure (a 2xx on a sensitive path), STIX 2.1 export, forward-confirmed reverse DNS for Googlebot and Bingbot, `--tor-exits` / `URUTAU_TOR_EXITS` (a file of Tor exit addresses) and SSH users from `--admin-users` marked as such.
- **Stable metrics** (no per-minute rates) in `/api/v1/metrics`: attacks per hour, trend, active and new attackers, returning rate, sessions per day, exposure rate, refused exploits, time to ban, ban and blocklist coverage and leak, SSH failures, and concentration by IP and ASN.
- **Interface:** a period selector (named ranges and a custom period), the IP analysis page (`#/ip/<ip>`), the Replay page (`#/replay`), Geography down to state and city (`#/geo/BR/Pernambuco/Recife`, state boundaries from Natural Earth, public domain) and a metrics column on the Live page.
### Changed
- The soft memory limit is 256 MiB (worst case measured: about 54 MiB of heap and a snapshot of about 27 MB). In Docker, `mem_limit: 384m` is recommended.
## [1.1.1] - 2026-11-14
### Fixed
- Live page, globe mode: sea and land colors no longer swap while the globe turns. Each country ring is now clipped at the horizon and closed along the edge of the globe, and long edges follow the map projection.
- World map data: countries crossing the 180th meridian (Russia, Fiji) are closed along the map edge, so the Sea of Okhotsk is no longer filled as land on the flat maps.
## [1.1.0] - 2026-11-14
### Added
- **New interface:** a side rail with seven pages (Overview, Threats, Geography, Live, Traffic, IPs, Sources and hosts), an opening sentence on every page with the number that matters, the active slice (range, host, domain) always written under the title, an IP detail drawer, and light and dark themes from design tokens.
- **Geography page:** a world map by attacker country; select a country to see its states or regions and cities (cities as circles on the zoomed country), the categories and the top IPs; select a region to narrow cities and IPs. The view lives in the URL (`#/geo/BR/Pernambuco`).
- **Live page:** attacks drawn as animated arcs from their origin to the server that saw them, on a flat map or a 3D globe, with rate, categories, servers, recent origins and the latest events; filters, pause and full screen. It opens by replaying the latest events, so it is never still on a quiet server.
- **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
First release.
@@ -22,7 +90,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`.
+69 -1
View File
@@ -6,6 +6,74 @@ Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/);
## [Unreleased]
## [1.4.0] - 2026-11-15
### Adicionado
- Segundo firewall (opcional, `URUTAU_ENFORCE=off|observe|on`): o Urutau decide quais endereços atacantes bloquear e grava as decisões num arquivo; o fail2ban do host (jail `urutau`) as aplica. O Urutau não ganha privilégios. O modo observação mostra o que seria bloqueado. Compartilhamento opcional de decisões entre hub e peers (`URUTAU_ENFORCE_SHARE`), aplicado só quando o servidor que recebe também viu o endereço atacar. Nunca bloqueia endereços confiáveis, redes privadas, faixas de CDN (Cloudflare) e de resolvedores públicos, peers nem o próprio servidor. O banimento só derruba conexões que o endereço inicia, então as respostas às conexões do próprio servidor continuam passando.
- Análise do tráfego de saída (`URUTAU_EGRESS`): as conexões novas de saída do host e dos contêineres, registradas pelo nftables, são analisadas em busca de beaconing (conversa regular com um destino), mineração, portas de IRC e SMTP, contato com endereços que atacaram o servidor ou saídas Tor, DNS fora dos resolvedores permitidos, varreduras de saída não autorizadas e países novos. Workloads por rede ou nome de contêiner (`URUTAU_EGRESS_WORKLOADS`); um workload `scanner` (scanner de superfície autorizado) só tem resumido o tráfego em formato de varredura, todo o resto é julgado como o de qualquer workload, então o beaconing dele continua sendo detectado.
- Kit de host em `deploy/host` (tabela nftables, rsyslog, logrotate, mapa de contêineres, filtro, ação e jail do fail2ban, `install.sh`).
- Página nova Tráfego de saída e seção Segundo firewall em Defesa.
- Relatório HTML (`/api/v1/report?format=html`): capa, sumário executivo em linguagem leiga, recomendações por regras, ameaças, geografia, erros e saúde, visitantes, defesa, segundo firewall e tráfego de saída, imprimível em A4. A página Relatórios baixa ou imprime.
- O script de capturas cobre todas as páginas.
## [1.3.0] - 2026-11-14
### Adicionado
- **Muitas páginas novas**, agrupadas na barra lateral: Monitorar (Visão geral, Ao vivo, Serviços), Investigar (IPs, Sessões, Campanhas, Replay, Busca de eventos), Analisar (Ameaças, MITRE ATT&CK, Geografia, Evolução, Concentração, Sobrevivência, Tráfego, De onde vêm os erros, Protocolos e TLS), Operar (Defesa, Fontes e hosts, Integridade) e Relatórios. Um glossário: um botão "?" ao lado de métricas e categorias explica o que cada uma significa e o que fazer.
- **Saúde dos serviços:** SLO por serviço (meta de 99,5%), orçamento de erro, burn rate (1 h e 6 h) e Apdex, a partir dos nomes de router e service do Traefik.
- **Classes de erro:** todo erro é classificado como `app`, `proxy`, `blocked`, `attack`, `bot`, `client` ou `unknown`, para distinguir um 5xx do seu app de um link quebrado ou de um scanner. Os campos do Traefik `OriginStatus`, `OriginDuration`, `Overhead`, `OriginContentSize`, `RetryAttempts`, `RouterName`, `ServiceName`, `RequestProtocol`, `RequestScheme`, `TLSVersion` e `TLSCipher` são lidos quando presentes.
- **Episódios e sobrevivência:** tempo até o ban e curvas de sobrevivência de Kaplan-Meier calculadas sobre episódios de ataque.
- **Rotas novas** (só usuário, nunca o token de peer): `GET /api/v1/techniques`, `/evolution`, `/concentration`, `/survival`, `/sessions/funnel`, `/campaigns`, `/campaigns/{id}`, `/defense`, `/errors`, `/integrity`, `/report`, `/services`, `/services/{svc}` e `/protocols`.
- **Stream de visitas legítimas:** `GET /api/v1/events/stream?visits=1` também envia eventos anônimos de visita (sem endereço, User-Agent nem referrer; posição no nível da cidade), no máximo 20 por segundo, nunca gravados em disco.
- Documentação da atualização da geolocalização: o Urutau confere a cada 24 horas (`--geo-update`), enquanto a DB-IP publica uma vez por mês.
### Alterado
- **Os visitantes únicos foram corrigidos.** Um visitante agora é uma pessoa com navegador real: um GET bem-sucedido de um documento por um User-Agent de navegador (não bot, ferramenta nem cliente desconhecido, nem prefetch), um por IP por dia, deduplicado globalmente. Bots, ferramentas e clientes desconhecidos são contados à parte como "clientes não humanos". O número é menor que antes, e menor que o do Coolify, que conta todo IP distinto com HyperLogLog e sem filtro.
- Caminhos e valores de `Referer` que contêm e-mail ou token são normalizados para `:id`.
## [1.2.0] - 2026-11-14
### Adicionado
- **Memória maior e qualquer período:** a retenção padrão e máxima agora é 30 dias (720h). Doze intervalos (`1h`, `2h`, `3h`, `6h`, `12h`, `24h`, `2d`, `3d`, `5d`, `7d`, `15d`, `30d`) e um período personalizado com `from` e `to` (segundos unix, no máximo 30 dias). Um `range` inválido responde 400, e `range` nas respostas agora é um objeto `{name,from,to,step,clipped}`; o `step` (granularidade) da linha do tempo acompanha o tamanho da janela.
- **Registro de eventos** em `<data-dir>/events/`: uma linha JSON por evento (o formato do stream ao vivo), um arquivo por dia UTC, dias antigos compactados com gzip, limitado por idade (a retenção) e por tamanho (`--events-max` / `URUTAU_EVENTS_MAX`, padrão 512 MB, `0` desliga). Guarda eventos maliciosos, ban e unban, logins SSH bem-sucedidos, um 404 para uma ferramenta de ataque, e respostas `ok`/`notfound` só de endereços já suspeitos ou hostis; nunca um visitante legítimo. Disco cheio, o teto de tamanho ou o teto diário de linhas descartam eventos (contados, nunca fatais), e uma linha corrompida é ignorada.
- **API de investigação:** `GET /api/v1/events`, `/api/v1/events/sessions`, `/api/v1/period`, `/api/v1/period/events`, `/api/v1/metrics`, o novo `GET /api/v1/ip/{ip}` resumido e `GET /api/v1/ip/{ip}/stix`; e a rota de peer `GET /api/v1/peer/period`, então o token de peer agora abre três rotas (export, stream e period).
- **Inteligência:** famílias de ataque, técnicas MITRE ATT&CK, tipo de rede (VPN, hospedagem, móvel, residencial, Tor, scanner de pesquisa; sem API externa), cadência das requisições (automatizada, humana, mista), sessões com estágios (recon, probe, exploit, access, banned), campanhas (vários IPs fazendo a mesma coisa), um veredito com razões, ações recomendadas, exposição (um 2xx em caminho sensível), exportação STIX 2.1, DNS reverso confirmado para Googlebot e Bingbot, `--tor-exits` / `URUTAU_TOR_EXITS` (um arquivo com endereços de saída do Tor) e usuários SSH de `--admin-users` marcados como tal.
- **Métricas estáveis** (sem taxa por minuto) em `/api/v1/metrics`: ataques por hora, tendência, atacantes ativos e novos, taxa de retorno, sessões por dia, taxa de exposição, exploits recusados, tempo até o ban, cobertura e vazamento de ban e blocklist, falhas SSH e concentração por IP e ASN.
- **Interface:** seletor de período (intervalos nomeados e período personalizado), página de análise de IP (`#/ip/<ip>`), página Replay (`#/replay`), Geografia até estado e cidade (`#/geo/BR/Pernambuco/Recife`, limites dos estados do Natural Earth, domínio público) e uma coluna de métricas na página Ao vivo.
### Alterado
- O limite suave de memória é 256 MiB (pior caso medido: cerca de 54 MiB de heap e um snapshot de cerca de 27 MB). No Docker, recomenda-se `mem_limit: 384m`.
## [1.1.1] - 2026-11-14
### Corrigido
- Página Ao vivo, modo globo: as cores do mar e da terra não se trocam mais enquanto o globo gira. Cada contorno de país agora é recortado no horizonte e fechado ao longo da borda do globo, e as arestas longas seguem a projeção do mapa.
- Dados do mapa-múndi: países que cruzam o meridiano 180 (Rússia, Fiji) são fechados ao longo da borda do mapa, então o Mar de Okhotsk não é mais pintado como terra nos mapas planos.
## [1.1.0] - 2026-11-14
### Adicionado
- **Interface nova:** trilho lateral com sete páginas (Visão geral, Ameaças, Geografia, Ao vivo, Tráfego, IPs, Fontes e hosts), uma frase de abertura em cada página com o número que importa, o recorte ativo (intervalo, host, domínio) sempre escrito sob o título, painel de detalhe de IP e temas claro e escuro a partir de tokens de design.
- **Página Geografia:** mapa-múndi por país de origem dos ataques; selecione um país para ver estados ou regiões e cidades (cidades como círculos no país ampliado), as categorias e os IPs principais; selecione uma região para filtrar cidades e IPs. A vista fica na URL (`#/geo/BR/Pernambuco`).
- **Página Ao vivo:** ataques desenhados como arcos animados da origem até o servidor que os viu, em mapa plano ou globo 3D, com ritmo, categorias, servidores, origens recentes e os últimos eventos; filtros, pausa e tela cheia. Ela abre reproduzindo os últimos eventos, então nunca fica parada num servidor calmo.
- **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
Primeira versão.
@@ -22,7 +90,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`.
+33 -8
View File
@@ -8,6 +8,12 @@
---
<p align="center"><img src="docs/img/overview-dark.png" width="900" alt="Urutau overview page: headline sentence, KPI cards, activity by category timeline"><br><sub>The Overview page: hostile IPs, attack rate and activity by category (demo data).</sub></p>
<p align="center"><img src="docs/img/live-globe-dark.png" width="900" alt="Urutau live page on the 3D globe: animated arcs from attacker cities to the servers edge-1 and edge-2"><br><sub>Live: attacks as animated arcs on a 3D globe (demo data, reserved addresses only).</sub></p>
<p align="center"><img src="docs/img/ip-analysis-dark.png" width="900" alt="Urutau IP analysis page: verdict, score, critical exposure and recommended actions for one attacker"><br><sub>IP analysis: verdict, evidence and recommended actions for one address.</sub></p>
**Status: stable, v1.0.0.** See [CHANGELOG.md](CHANGELOG.md) for exactly what shipped.
Urutau is a small panel that runs on each of your servers (as a container), reads the logs the server already writes, and answers one question: who is attacking me right now? It classifies hostile activity, scores every source IP, keeps a rolling window on disk and serves an embedded dashboard, a JSON API and an exportable blocklist.
@@ -17,11 +23,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.
- **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.
- **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 256 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, with nine 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 +45,28 @@ 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
```
## Investigation
Beyond live numbers, Urutau remembers and explains. It keeps 30 days of state and an event registry on disk (`<data-dir>/events/`, capped by `--events-max`, 512 MB by default), so you can pick any period (twelve named ranges or a custom `from`/`to`), replay it, and open an IP analysis page with a verdict and its reasons, attack families, MITRE ATT&CK techniques, network type, cadence, sessions, campaigns and recommended actions, with a STIX 2.1 export. The registry holds attackers only: never the address of a legitimate visitor. See [docs/architecture.md](docs/architecture.md).
## Interface
Pages are grouped in a side rail, with the view kept in the URL hash. A "?" button next to metrics and categories explains what they mean and what to do.
- **Monitor:** Overview (headline numbers, timeline, top IPs; a period selector applies everywhere), Live (attacks as animated arcs on a flat map or a 3D globe, including your peers; `--location` sets where this server sits on the map), Services (SLO, error budget and Apdex per service).
- **Investigate:** IPs (the scored table and the IP analysis page, `#/ip/<ip>`), Sessions, Campaigns, Replay (a period played back on the map) and Event search.
- **Analyze:** Threats, MITRE ATT&CK, Geography (country, state, city, `#/geo/BR/Pernambuco/Recife`), Evolution, Concentration, Survival (time to ban), Traffic (privacy-friendly analytics for legitimate visitors), Where errors come from (app, proxy, blocked, attack, bot, client) and Protocols and TLS.
- **Operate:** Defense, Sources and hosts (log sources, peers and the blocklist) and Integrity.
- **Reports.**
See [docs/interface.md](docs/interface.md).
## Install
Run it with Docker Compose (recommended):
@@ -87,7 +111,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
@@ -95,7 +119,7 @@ Urutau shows country, city and ASN for every IP using the free **DB-IP Lite** da
> IP geolocation data by [DB-IP](https://db-ip.com), licensed under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/).
The attribution is also shown in the dashboard. If you redistribute the databases or anything derived from them, keep it.
The attribution is also shown in the dashboard. The state and city boundaries drawn on the Geography page come from [Natural Earth](https://www.naturalearthdata.com) (public domain). If you redistribute the databases or anything derived from them, keep it.
## Privacy
@@ -161,7 +185,7 @@ See **[CONTRIBUTING.md](CONTRIBUTING.md)** and **[docs/architecture.md](docs/arc
## Known limits
- Only three sources: Traefik JSON access log, sshd lines from `auth.log` (ISO timestamps) and `fail2ban.log`.
- State is kept for 7 days at most (`--retention`), with up to 20,000 tracked IPs.
- State is kept for 30 days at most (`--retention`), with up to 20,000 tracked IPs; the event registry is capped by `--events-max`.
- The dashboard login is a single shared token; there are no user accounts.
- Scores are heuristics, not proof of malicious intent.
@@ -172,8 +196,9 @@ Summary of the [ROADMAP](ROADMAP.md):
| | |
|---|---|
| **Done (1.0.0)** | Log collection, classification and scoring, offline geolocation, User-Agent parsing, privacy-friendly web analytics, snapshot persistence, dashboard with SSE, token login, blocklist, federation, Docker image and CI/CD |
| **Done (1.2.0)** | 30-day retention, any period, on-disk event registry, replay, IP analysis with verdict, MITRE ATT&CK, campaigns, STIX 2.1 and stable metrics |
| **Next** | More log sources, webhook alerts, Prometheus metrics |
| **Later** | IP reputation enrichment, longer retention |
| **Later** | IP reputation enrichment |
| **Not planned** | Active scanning or counterattack, mandatory cloud services, telemetry |
## License
+34 -9
View File
@@ -8,6 +8,12 @@
---
<p align="center"><img src="docs/img/overview-dark-pt.png" width="900" alt="Página Visão geral do Urutau: frase de destaque, cartões de KPI e linha do tempo por categoria"><br><sub>A página Visão geral: IPs hostis, taxa de ataques e atividade por categoria (dados de demonstração).</sub></p>
<p align="center"><img src="docs/img/live-globe-dark-pt.png" width="900" alt="Página Ao vivo do Urutau no globo 3D: arcos animados das cidades dos atacantes até os servidores edge-1 e edge-2"><br><sub>Ao vivo: ataques como arcos animados num globo 3D (dados de demonstração, só endereços reservados).</sub></p>
<p align="center"><img src="docs/img/ip-analysis-dark-pt.png" width="900" alt="Página de análise de IP do Urutau: veredito, pontuação, exposição crítica e ações recomendadas para um atacante"><br><sub>Análise de IP: veredito, evidências e ações recomendadas para um endereço.</sub></p>
**Status: estável, v1.0.0.** Veja o [CHANGELOG.pt-BR.md](CHANGELOG.pt-BR.md) para saber exatamente o que foi entregue.
O Urutau é um painel pequeno que roda em cada um dos seus servidores (como container), lê os logs que o servidor já escreve e responde a uma pergunta: quem está me atacando agora? Ele classifica a atividade hostil, pontua cada IP de origem, mantém uma janela móvel em disco e serve um dashboard embutido, uma API JSON e uma blocklist exportável.
@@ -17,11 +23,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.
- **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.
- **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 256 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, com nove 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 +45,28 @@ 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
```
## Investigação
Além dos números ao vivo, o Urutau lembra e explica. Ele guarda 30 dias de estado e um registro de eventos em disco (`<data-dir>/events/`, limitado por `--events-max`, 512 MB por padrão), então você pode escolher qualquer período (doze intervalos nomeados ou um `from`/`to` personalizado), reproduzi-lo e abrir uma página de análise de IP com um veredito e suas razões, famílias de ataque, técnicas MITRE ATT&CK, tipo de rede, cadência, sessões, campanhas e ações recomendadas, com exportação STIX 2.1. O registro guarda só atacantes: nunca o endereço de um visitante legítimo. Veja [docs/pt-BR/arquitetura.md](docs/pt-BR/arquitetura.md).
## Interface
As páginas são agrupadas numa barra lateral, com a visão guardada no hash da URL. Um botão "?" ao lado de métricas e categorias explica o que significam e o que fazer.
- **Monitorar:** Visão geral (números principais, linha do tempo, principais IPs; um seletor de período vale em todo lugar), Ao vivo (ataques como arcos animados em mapa plano ou globo 3D, incluindo seus peers; `--location` define onde este servidor fica no mapa), Serviços (SLO, orçamento de erro e Apdex por serviço).
- **Investigar:** IPs (a tabela pontuada e a página de análise de IP, `#/ip/<ip>`), Sessões, Campanhas, Replay (um período reproduzido no mapa) e Busca de eventos.
- **Analisar:** Ameaças, MITRE ATT&CK, Geografia (país, estado, cidade, `#/geo/BR/Pernambuco/Recife`), Evolução, Concentração, Sobrevivência (tempo até o ban), Tráfego (analytics amigável à privacidade para visitantes legítimos), De onde vêm os erros (app, proxy, blocked, attack, bot, client) e Protocolos e TLS.
- **Operar:** Defesa, Fontes e hosts (fontes de log, peers e a blocklist) e Integridade.
- **Relatórios.**
Veja [docs/pt-BR/interface.md](docs/pt-BR/interface.md).
## Instalação
Rode com Docker Compose (recomendado):
@@ -87,7 +111,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
@@ -95,11 +119,11 @@ O Urutau mostra país, cidade e ASN de cada IP usando as bases gratuitas **DB-IP
> Dados de geolocalização de IP por [DB-IP](https://db-ip.com), licenciados sob [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/).
A atribuição também aparece no dashboard. Se você redistribuir as bases ou algo derivado delas, mantenha-a.
A atribuição também aparece no dashboard. Os limites de estados e cidades desenhados na página Geografia vêm do [Natural Earth](https://www.naturalearthdata.com) (domínio público). Se você redistribuir as bases ou algo derivado delas, mantenha-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
@@ -161,7 +185,7 @@ Veja **[CONTRIBUTING.pt-BR.md](CONTRIBUTING.pt-BR.md)** e **[docs/pt-BR/arquitet
## Limites conhecidos
- Só três fontes: access log JSON do Traefik, linhas do sshd no `auth.log` (timestamps ISO) e `fail2ban.log`.
- O estado é mantido por no máximo 7 dias (`--retention`), com até 20.000 IPs rastreados.
- O estado é mantido por no máximo 30 dias (`--retention`), com até 20.000 IPs rastreados; o registro de eventos é limitado por `--events-max`.
- O login do dashboard é um token único compartilhado; não há contas de usuário.
- Pontuações são heurísticas, não prova de intenção maliciosa.
@@ -172,8 +196,9 @@ Resumo do [ROADMAP](ROADMAP.pt-BR.md):
| | |
|---|---|
| **Feito (1.0.0)** | Coleta de logs, classificação e pontuação, geolocalização offline, parse de User-Agent, web analytics amigável à privacidade, snapshot em disco, dashboard com SSE, login por token, blocklist, federação, imagem Docker e CI/CD |
| **Feito (1.2.0)** | Retenção de 30 dias, qualquer período, registro de eventos em disco, replay, análise de IP com veredito, MITRE ATT&CK, campanhas, STIX 2.1 e métricas estáveis |
| **Próximo** | Mais fontes de log, alertas por webhook, métricas Prometheus |
| **Depois** | Enriquecimento com reputação de IP, retenção maior |
| **Depois** | Enriquecimento com reputação de IP |
| **Fora do plano** | Varredura ativa ou contra-ataque, serviços de nuvem obrigatórios, telemetria |
## Licença
+4 -1
View File
@@ -17,6 +17,10 @@ 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`.
- **Investigation (1.2.0):** 30-day retention, twelve ranges and custom periods, an on-disk event registry, replay, IP analysis with verdict and reasons, attack families, MITRE ATT&CK, campaigns, STIX 2.1 export and stable metrics.
## Next
- **More log sources:** other web servers and proxies (nginx, Caddy), and more daemons' auth failures.
@@ -26,7 +30,6 @@ Urutau is lightweight, always-on threat intelligence for self-hosted servers: it
## Later
- **IP reputation enrichment:** optional lookups, off by default, to respect the local-first rule.
- **Longer retention:** an optional on-disk history beyond 7 days.
- **Per-user tokens:** more than one access token with separate revocation.
## Non-Goals
+4 -1
View File
@@ -17,6 +17,10 @@ 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`.
- **Investigação (1.2.0):** retenção de 30 dias, doze intervalos e períodos personalizados, registro de eventos em disco, replay, análise de IP com veredito e razões, famílias de ataque, MITRE ATT&CK, campanhas, exportação STIX 2.1 e métricas estáveis.
## Próximo
- **Mais fontes de log:** outros servidores web e proxies (nginx, Caddy) e falhas de autenticação de mais daemons.
@@ -26,7 +30,6 @@ O Urutau é threat intelligence leve e sempre ligado para servidores self-hosted
## Depois
- **Enriquecimento com reputação de IP:** consultas opcionais, desligadas por padrão, para respeitar o local-first.
- **Retenção maior:** histórico opcional em disco além de 7 dias.
- **Tokens por usuário:** mais de um token de acesso, com revogação separada.
## Fora do plano
+6 -3
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 `GET /api/v1/peer/export`; every other route answers 403 to it, and `URUTAU_TOKEN` is refused (401) on the export. Without a peer token the export is a 404. `--peer-allow` restricts the export 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 the export, 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. Treat a peer as able to read the top 500 IPs, paths and traffic figures its export carries.
- **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 three federation routes, `GET /api/v1/peer/export`, the live stream `GET /api/v1/peer/stream` (at most 10 connections, malicious events only) and `GET /api/v1/peer/period` (the study a hub merges; at most two run at once); every other route answers 403 to it, and `URUTAU_TOKEN` is refused (401) on all three. Without a peer token they are a 404. `--peer-allow` restricts them 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,8 +22,11 @@ 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.
- **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.
- **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.
- **Anonymous visits:** legitimate visitors are never stored. The optional `?visits=1` stream carries no address, User-Agent or referrer (city-level position only, at most 20 per second) and is never written to disk. Paths and `Referer` values are normalized to `:id` when they carry an e-mail address, a token or a long identifier, so personal data in a URL does not reach the lists. The newer analysis routes (`/api/v1/techniques`, `/evolution`, `/concentration`, `/survival`, `/sessions/funnel`, `/campaigns`, `/defense`, `/errors`, `/integrity`, `/report`, `/services`, `/protocols`) are user-only: the peer token gets 403 on them.
- **Event registry (privacy):** `<data-dir>/events/` keeps one line per event for replay and investigation, but only about attackers: malicious events, bans, successful SSH logins, a 404 to an attack tool, and answers to addresses that are already suspicious or hostile. The address of a legitimate visitor is never written. Files are removed after the retention (30 days at most) and the total is capped by `--events-max` (512 MB by default, `0` turns the registry off). Treat the directory as personal data under the LGPD and the GDPR: same retention, same access control as the rest of the data volume. A full disk or the size cap drops events instead of stopping the service, and a corrupted line is skipped.
- **Outbound lookups for verdicts:** the network type is inferred locally from the ASN, organisation and reverse DNS (no external API). Forward-confirmed reverse DNS is used only to confirm a claimed Googlebot or Bingbot. The optional Tor exit list is a local file (`--tor-exits`).
- **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. The state and city boundaries on the Geography page are from Natural Earth, public domain.
## Known limitation
+6 -3
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 `GET /api/v1/peer/export`; todas as outras rotas respondem 403 a ele, e o `URUTAU_TOKEN` é recusado (401) no export. Sem token de peer o export é 404. `--peer-allow` restringe o export 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 o export, 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. Trate um peer como alguém que pode ler os 500 IPs principais, caminhos e números de tráfego que o export carrega.
- **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` o fluxo ao vivo `GET /api/v1/peer/stream` (no máximo 10 conexões, só eventos maliciosos) e `GET /api/v1/peer/period` (o estudo que um hub mescla; no máximo dois ao mesmo tempo); todas as outras rotas respondem 403 a ele, e o `URUTAU_TOKEN` é recusado (401) nas três. Sem token de peer elas são 404. `--peer-allow` restringe as três 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,8 +22,11 @@ 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.
- **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.
- **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.
- **Visitas anônimas:** visitantes legítimos nunca são armazenados. O stream opcional `?visits=1` não carrega endereço, User-Agent nem referrer (só posição no nível da cidade, no máximo 20 por segundo) e nunca é gravado em disco. Caminhos e valores de `Referer` são normalizados para `:id` quando carregam e-mail, token ou identificador longo, para que dado pessoal numa URL não chegue às listas. As rotas de análise mais novas (`/api/v1/techniques`, `/evolution`, `/concentration`, `/survival`, `/sessions/funnel`, `/campaigns`, `/defense`, `/errors`, `/integrity`, `/report`, `/services`, `/protocols`) são só de usuário: o token de peer recebe 403 nelas.
- **Registro de eventos (privacidade):** `<data-dir>/events/` guarda uma linha por evento para replay e investigação, mas só de atacantes: eventos maliciosos, bans, logins SSH bem-sucedidos, um 404 para uma ferramenta de ataque, e respostas a endereços já suspeitos ou hostis. O endereço de um visitante legítimo nunca é gravado. Os arquivos são removidos após a retenção (30 dias no máximo) e o total é limitado por `--events-max` (512 MB por padrão, `0` desliga o registro). Trate o diretório como dado pessoal perante a LGPD e o GDPR: mesma retenção e mesmo controle de acesso do resto do volume de dados. Disco cheio ou o teto de tamanho descartam eventos em vez de parar o serviço, e uma linha corrompida é ignorada.
- **Consultas para os vereditos:** o tipo de rede é inferido localmente a partir do ASN, da organização e do DNS reverso (sem API externa). O DNS reverso confirmado serve apenas para confirmar um Googlebot ou Bingbot declarado. A lista opcional de saídas do Tor é um arquivo local (`--tor-exits`).
- **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. Os limites de estados e cidades da página Geografia são do Natural Earth, domínio público.
## Limitação conhecida
+7
View File
@@ -0,0 +1,7 @@
# Urutau: kernel log lines of the egress table go to their own file and stay
# out of the general syslog (an authorised scan would flood it).
if ($syslogfacility-text == "kern" and $msg contains "URUTAU-EGRESS: ") then {
action(type="omfile" file="/var/log/urutau/egress.log" template="RSYSLOG_FileFormat"
fileOwner="syslog" fileGroup="adm" fileCreateMode="0640")
stop
}
+10
View File
@@ -0,0 +1,10 @@
# Urutau "second firewall" action: like iptables-allports, but it only drops
# connections the banned address STARTS (conntrack original direction). The
# replies to connections this host opened (DNS, ACME, image pulls, apt) keep
# flowing even if a decision ever names an address the host depends on.
[INCLUDES]
before = iptables-allports.conf
[Definition]
actionban = <iptables> -I f2b-<name> 1 -s <ip> -m conntrack --ctdir ORIGINAL -j <blocktype>
actionunban = <iptables> -D f2b-<name> -s <ip> -m conntrack --ctdir ORIGINAL -j <blocktype>
+7
View File
@@ -0,0 +1,7 @@
# Urutau "second firewall": one line per decision written by Urutau in
# enforce=on mode, e.g.
# 2026-11-14T22:00:00Z urutau decision=ban ip=203.0.113.7 reason=wp-bruteforce score=95 ttl=3600 host=oracle src=local
[Definition]
datepattern = ^%%Y-%%m-%%dT%%H:%%M:%%SZ
failregex = ^\s*urutau decision=ban ip=<HOST> reason=[a-z0-9-]+
ignoreregex =
+14
View File
@@ -0,0 +1,14 @@
# Urutau "second firewall". Urutau never gets privileges: it only writes its
# decisions to this file and fail2ban applies them, with its own ignoreip
# (the [DEFAULT] of the host still protects trusted addresses).
[urutau]
enabled = true
backend = polling
filter = urutau
logpath = /var/log/urutau-enforce/decisions.log
maxretry = 1
findtime = 1h
bantime = 1h
# ignoreip and ignoreself come from the host [DEFAULT] (never override them here)
action = urutau-allports[name=urutau-in, chain=INPUT, protocol=all]
urutau-allports[name=urutau-docker, chain=DOCKER-USER, protocol=all]
+63
View File
@@ -0,0 +1,63 @@
#!/bin/sh
# Urutau host kit: egress logging (nftables + rsyslog), the container map and,
# optionally, the fail2ban jail of the "second firewall".
#
# sudo sh install.sh # egress logging + container map
# sudo sh install.sh --enforce # also the fail2ban jail for URUTAU_ENFORCE=on
# sudo sh install.sh --remove # undo everything
#
# Idempotent. Urutau itself never gets privileges: it only reads these logs and
# writes its ban decisions to /var/log/urutau-enforce/decisions.log.
set -eu
here=$(cd "$(dirname "$0")" && pwd)
uid=${URUTAU_UID:-10001}
[ "$(id -u)" = 0 ] || { echo "run as root" >&2; exit 1; }
if [ "${1:-}" = "--remove" ]; then
systemctl disable --now urutau-egress.service urutau-containers-map.timer urutau-logrotate.timer 2>/dev/null || true
rm -f /etc/systemd/system/urutau-egress.service /etc/systemd/system/urutau-containers-map.service \
/etc/systemd/system/urutau-containers-map.timer /usr/local/sbin/urutau-containers-map \
/etc/rsyslog.d/41-urutau-egress.conf /etc/logrotate.d/urutau-egress \
/etc/fail2ban/jail.d/urutau.local /etc/fail2ban/filter.d/urutau.conf /etc/fail2ban/action.d/urutau-allports.conf \
/etc/systemd/system/urutau-logrotate.service /etc/systemd/system/urutau-logrotate.timer
rm -rf /etc/urutau
systemctl daemon-reload
systemctl restart rsyslog
fail2ban-client reload >/dev/null 2>&1 || true
echo "removed (logs under /var/log/urutau kept)"
exit 0
fi
wan=${URUTAU_WAN:-$(ip -o route get 1.1.1.1 | sed -n 's/.* dev \([^ ]*\).*/\1/p')}
[ -n "$wan" ] || { echo "cannot detect the uplink interface; set URUTAU_WAN" >&2; exit 1; }
case "$wan" in *[!A-Za-z0-9_.-]*) echo "bad interface name: $wan" >&2; exit 1 ;; esac
install -d -m 0750 -o syslog -g adm /var/log/urutau 2>/dev/null || install -d -m 0750 -g adm /var/log/urutau
install -d -m 0755 /etc/urutau
sed "s/@WAN@/$wan/g" "$here/urutau-egress.nft" > /etc/urutau/egress.nft
nft -c -f /etc/urutau/egress.nft
install -m 0644 "$here/41-urutau-egress.conf" /etc/rsyslog.d/41-urutau-egress.conf
install -m 0644 "$here/urutau.logrotate" /etc/logrotate.d/urutau-egress
install -m 0755 "$here/urutau-containers-map" /usr/local/sbin/urutau-containers-map
install -m 0644 "$here/urutau-egress.service" "$here/urutau-containers-map.service" \
"$here/urutau-containers-map.timer" "$here/urutau-logrotate.service" "$here/urutau-logrotate.timer" /etc/systemd/system/
systemctl daemon-reload
systemctl restart rsyslog
systemctl enable urutau-egress.service urutau-containers-map.timer urutau-logrotate.timer >/dev/null
systemctl start urutau-logrotate.timer
systemctl restart urutau-egress.service
systemctl start urutau-containers-map.service urutau-containers-map.timer
echo "egress logging on $wan: /var/log/urutau/egress.log, map: /var/log/urutau/containers.map"
if [ "${1:-}" = "--enforce" ]; then
install -d -m 0750 -o "$uid" -g adm /var/log/urutau-enforce
[ -e /var/log/urutau-enforce/decisions.log ] || install -m 0640 -o "$uid" -g adm /dev/null /var/log/urutau-enforce/decisions.log
install -m 0644 "$here/fail2ban-filter-urutau.conf" /etc/fail2ban/filter.d/urutau.conf
install -m 0644 "$here/fail2ban-action-urutau.conf" /etc/fail2ban/action.d/urutau-allports.conf
install -m 0644 "$here/fail2ban-jail-urutau.local" /etc/fail2ban/jail.d/urutau.local
fail2ban-client -t >/dev/null
fail2ban-client reload
echo "fail2ban jail 'urutau' on; mount /var/log/urutau-enforce:/logs/enforce (rw) in the container"
fi
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
# Urutau: writes "<ip> <container name>" for every running container, so the
# egress analysis can name workloads whose address changes on each redeploy.
set -eu
out=/var/log/urutau/containers.map
tmp=$(mktemp /var/log/urutau/.containers.map.XXXXXX)
trap 'rm -f "$tmp"' EXIT
docker ps -q | xargs -r docker inspect -f '{{$n := .Name}}{{range .NetworkSettings.Networks}}{{if .IPAddress}}{{.IPAddress}} {{$n}}
{{end}}{{if .GlobalIPv6Address}}{{.GlobalIPv6Address}} {{$n}}
{{end}}{{end}}' | sed 's# /# #' | grep -E '^[0-9a-fA-F.:]+ [A-Za-z0-9_.-]{1,128}$' > "$tmp" || true
chgrp adm "$tmp"; chmod 0640 "$tmp"
mv -f "$tmp" "$out"
trap - EXIT
@@ -0,0 +1,7 @@
[Unit]
Description=Urutau: map container addresses to names
After=docker.service
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/urutau-containers-map
+10
View File
@@ -0,0 +1,10 @@
[Unit]
Description=Urutau: refresh the container map every minute
[Timer]
OnBootSec=30s
OnUnitActiveSec=60s
AccuracySec=5s
[Install]
WantedBy=timers.target
+44
View File
@@ -0,0 +1,44 @@
#!/usr/sbin/nft -f
# Urutau: logs NEW outbound connections (host and containers) so the egress
# analysis can spot beaconing, mining, spam and unauthorised scans.
# Lives in its own table: it never touches the iptables-nft tables of Docker
# or fail2ban, and it only logs (policy accept, no drop).
# @WAN@ is replaced by the uplink interface by install.sh.
#
# Volume control without blinding the beacon detector:
# - a (source, destination, protocol, port) seen in the last 2 h is ALWAYS
# logged (a beacon repeats the same pair, so a ceiling never hides it);
# - a NEW pair is logged under a per-source ceiling of 20/s (burst 100): an
# authorised scan (thousands of new pairs) is capped, and one noisy
# workload never eats the budget of the others.
table inet urutau_egress
delete table inet urutau_egress
table inet urutau_egress {
set rl4 { type ipv4_addr; flags dynamic; timeout 2m; size 65535; }
set rl6 { type ipv6_addr; flags dynamic; timeout 2m; size 65535; }
set seen4 { type ipv4_addr . ipv4_addr . inet_proto . inet_service; flags dynamic, timeout; timeout 2h; size 131072; }
set seen6 { type ipv6_addr . ipv6_addr . inet_proto . inet_service; flags dynamic, timeout; timeout 2h; size 131072; }
chain egress {
# known pair: always log, refresh its timer
meta nfproto ipv4 meta l4proto { tcp, udp } ip saddr . ip daddr . meta l4proto . th dport @seen4 update @seen4 { ip saddr . ip daddr . meta l4proto . th dport } log prefix "URUTAU-EGRESS: " level info return
meta nfproto ipv6 meta l4proto { tcp, udp } ip6 saddr . ip6 daddr . meta l4proto . th dport @seen6 update @seen6 { ip6 saddr . ip6 daddr . meta l4proto . th dport } log prefix "URUTAU-EGRESS: " level info return
# new pair: per-source ceiling, then remember it
meta nfproto ipv4 meta l4proto { tcp, udp } add @rl4 { ip saddr limit rate 20/second burst 100 packets } add @seen4 { ip saddr . ip daddr . meta l4proto . th dport } log prefix "URUTAU-EGRESS: " level info return
meta nfproto ipv6 meta l4proto { tcp, udp } add @rl6 { ip6 saddr limit rate 20/second burst 100 packets } add @seen6 { ip6 saddr . ip6 daddr . meta l4proto . th dport } log prefix "URUTAU-EGRESS: " level info return
# other protocols (ICMP...) under the same ceiling, not remembered
meta nfproto ipv4 meta l4proto != { tcp, udp } add @rl4 { ip saddr limit rate 20/second burst 100 packets } log prefix "URUTAU-EGRESS: " level info
meta nfproto ipv6 meta l4proto != { tcp, udp } add @rl6 { ip6 saddr limit rate 20/second burst 100 packets } log prefix "URUTAU-EGRESS: " level info
}
chain forward_log {
type filter hook forward priority filter - 10; policy accept;
ct state new oifname "@WAN@" iifname != "@WAN@" jump egress
}
chain output_log {
type filter hook output priority filter - 10; policy accept;
ct state new oifname "@WAN@" jump egress
}
}
+13
View File
@@ -0,0 +1,13 @@
[Unit]
Description=Urutau: egress connection log (nftables)
After=network-online.target docker.service
Wants=network-online.target
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/sbin/nft -f /etc/urutau/egress.nft
ExecStop=/usr/sbin/nft delete table inet urutau_egress
[Install]
WantedBy=multi-user.target
+6
View File
@@ -0,0 +1,6 @@
[Unit]
Description=Urutau: rotate the egress log by size
[Service]
Type=oneshot
ExecStart=/usr/sbin/logrotate -s /var/lib/logrotate/urutau-egress.status /etc/logrotate.d/urutau-egress
+9
View File
@@ -0,0 +1,9 @@
[Unit]
Description=Urutau: check the egress log size every 10 minutes
[Timer]
OnBootSec=5m
OnUnitActiveSec=10m
[Install]
WantedBy=timers.target
+14
View File
@@ -0,0 +1,14 @@
/var/log/urutau/egress.log {
daily
rotate 7
maxsize 200M
maxage 7
compress
delaycompress
missingok
notifempty
create 0640 syslog adm
postrotate
/usr/lib/rsyslog/rsyslog-rotate
endscript
}
+1 -1
View File
@@ -60,7 +60,7 @@ services:
cap_drop: [ALL]
security_opt:
- no-new-privileges:true
mem_limit: 256m
mem_limit: 384m # the Go soft limit is 256 MiB (30 days of history)
cpus: 0.5
restart: unless-stopped
+98 -5
View File
@@ -10,7 +10,9 @@ internal/app flags, wiring, the log runner, doctor
internal/tail rotation-aware file follower and rotated-file reader
internal/core event model, parsers (Traefik, sshd, fail2ban), classifier
internal/store in-memory state, summaries, merge, snapshot
internal/rdns reverse DNS cache
internal/rdns reverse DNS cache and forward-confirmed reverse DNS
internal/evlog on-disk event registry
internal/intel families, MITRE, network type, cadence, sessions, campaigns, verdicts, STIX, metrics
internal/fed hub that polls peers
internal/server HTTP handler, auth, embedded dashboard (web/)
```
@@ -83,19 +85,110 @@ 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.
## Periods and granularity
Every view takes a range: one of twelve named windows (`1h`, `2h`, `3h`, `6h`, `12h`, `24h`, `2d`, `3d`, `5d`, `7d`, `15d`, `30d`) or a custom period with `from` and `to` (unix seconds, at most 30 days, clipped to the retention; `clipped` says when it was). An invalid range answers 400. Responses carry `range` as an object `{name,from,to,step,clipped}`, where `step` is the timeline granularity in seconds: 60 up to 3 hours, 120 up to 6, 300 up to 12, 900 up to 48 hours and 3600 beyond. Minute buckets exist for the latest 48 hours; older data is hourly.
## Error classes and Traefik fields
Besides the client, path, status and User-Agent, Urutau reads these Traefik access log fields when they are present: `OriginStatus`, `OriginDuration`, `Overhead`, `OriginContentSize`, `RetryAttempts`, `RouterName`, `ServiceName`, `RequestProtocol`, `RequestScheme`, `TLSVersion` and `TLSCipher`. With them every error is classified:
| Class | Meaning |
|---|---|
| `app` | the backend itself answered 5xx |
| `proxy` | the proxy could not reach the backend, or the client gave up |
| `blocked` | refused by a middleware or a rate limit before the app |
| `attack` | the request is an attack (see the categories above) |
| `bot` | a crawler or tool |
| `client` | an ordinary client mistake (broken link, authentication, bad input) |
| `unknown` | none of the above could be told |
## Services, SLO and Apdex
Requests are grouped per Traefik service (`ServiceName`, with its router). For each service Urutau keeps hourly counters by error class and latency histograms, and shows: the **SLI** (share of requests that did not end in an error that counts against the service), the **SLO** (target 99.5%), the **error budget** left, the **burn rate** over 1 hour and 6 hours (error rate divided by `1 - SLO`; above 1 the budget is being spent faster than allowed) and the **Apdex**. Attacks, blocked requests and bots do not count against a service. Apdex uses a threshold T of 500 ms (1 s for API paths): a request answered within T is satisfied, within 4T tolerating, and a 5xx or a slower one is frustrated; Apdex is (satisfied + tolerating/2) / total.
## Episodes and survival
An attack **episode** is the run of activity of one address, closed after a quiet gap. From episodes Urutau measures the time from the first sighting to the ban and draws **Kaplan-Meier** survival curves (the probability that an address is still not banned after a given time, with addresses never banned counted as censored), with the median and the 90th percentile.
## Unique visitors
A **visitor** is a person with a real browser: a successful (2xx) GET of a document by a browser User-Agent (not a bot, tool or unknown client), not a prefetch and, when the browser says so, with `Sec-Fetch-Dest: document`. It is counted once per IP per UTC day, deduplicated globally across domains (a per-domain figure and an all-domains total). The key is a hash of a daily salt, the IP and the domain, and leaves the User-Agent out on purpose, because scrapers rotate it per request from one address (a measured 2.7x inflation). Everything else that talks to a site (bots, tools, unknown or empty User-Agents) is counted apart as **non-human clients**.
This is why the number differs from Coolify's analytics, which counts every distinct IP through HyperLogLog with no filter: bots, scanners and health checks inflate it. Urutau's figure is lower and closer to people.
## Legitimate visits stream
`GET /api/v1/events/stream?visits=1` adds anonymous visit events to the live stream. A visit carries no address, User-Agent or referrer; its place is the city, with coordinates rounded to one decimal (about 11 km). At most 20 visit events per second per instance are sent (the excess is summarised once a second as a batch), and visits are only broadcast to subscribers: never written to the event log, a snapshot or `live/recent`.
## Event registry
`<data-dir>/events/` holds one JSON line per event, in the same format as the live stream, one file per UTC day. The current day is appended to and synced every 2 seconds; older days are gzip compressed. Files older than the retention are deleted, and the total is capped by `--events-max` (512 MB by default, `0` disables the registry). A day holds at most 200,000 lines; beyond that, events are only counted.
What enters: malicious events (scanner, exploit, bruteforce, ssh-fail, ssh-probe), ban and unban, successful SSH logins, a 404 answered to an attack tool, and `ok` or `notfound` answers only for addresses that are already suspicious or hostile (to show what they got). Never a legitimate visitor. Events relayed from peers are registered with the peer name as host.
Failure behavior: a full disk, the size cap or the day cap drop events (counted, logged at most once in a while, never fatal); a corrupted line is skipped when reading; a partial line left by an earlier failure is terminated before the next write.
## Intelligence
The investigation layer is computed from the IP table and the registry, with no external API:
- **Attack families** (`traversal`, `log4shell`, `sqli`, `xss`, `rce-injection`, `webshell`, `env-credentials`, `vcs`, `backup`, `wordpress`, `phpmyadmin-db`, `actuator-debug`, `iot-cgi`, `admin-panel`, `generic-404`) and the **MITRE ATT&CK** techniques they map to.
- **Network type** from the ASN, the AS organisation and reverse DNS: `vpn`, `research-scanner`, `isp-cn`, `hosting`, `mobile`, `isp/mobile`, `residential`, `unknown`, and `tor` when the address is in the `--tor-exits` file (reloaded every 24 hours when it changes).
- **Cadence** of the requests of one IP: `automated`, `human-like`, `mixed` or `insufficient` (fewer than 3 requests).
- **Sessions:** bursts of one IP separated by a gap (30 minutes by default), each with a stage in increasing severity: `recon`, `probe`, `exploit`, `access`, `banned`.
- **Campaigns:** at least 3 IPs whose sessions have the same signature (similar normalized paths, Jaccard 0.6 or more, same tool) within a window; the signature id is `c-` plus 8 hex characters.
- **Exposure:** a 2xx answer to a request on a sensitive path.
- **Verdict with reasons**, each reason a stable code with a weight (`exploits_refused`, `tool_ua`, `banned_jail`, `multi_category`, `exposure`, `ssh_login_after_bruteforce`, `admin`, `immune`), and **recommended actions** (`block`, `report`, `investigate`, `incident`); administrators and immune sources get none.
- **STIX 2.1** export of an IP (`/api/v1/ip/{ip}/stix`), with deterministic UUIDv5 ids.
- **Crawlers:** a User-Agent claiming Googlebot or Bingbot is confirmed by forward-confirmed reverse DNS; a fake one stays an attacker.
- SSH users listed in `--admin-users` are marked as administrators.
## Metrics
`GET /api/v1/metrics` returns stable figures (no per-minute rates), each with its value, the previous value and a sparkline where it applies:
| Metric | Formula |
|---|---|
| `attacks_per_hour_24h` | malicious events in the last 24 h / 24 |
| `moving_avg_7d_per_hour` | malicious events in the last 7 days / 168 |
| `trend` | percent change of malicious events in the range against the previous range of the same length |
| `active_attackers_24h`, `_1h` | attacker IPs seen in the last 24 h, in the last hour |
| `new_attackers` | IPs first seen inside the range (and the previous range) |
| `returning_rate` | IPs seen in the range but first seen before it / all IPs seen in the range, in percent |
| `sessions_per_day` | sessions in the range / days of the range (at least 1) |
| `exposure_rate` | sessions that got a successful answer / sessions, in percent |
| `exploits_refused_pct` | exploit requests answered 4xx or 5xx / exploit requests with a status, in percent |
| `mttb` | median and 90th percentile of the time from first sighting to ban |
| `ban_coverage` | hostile IPs banned / hostile IPs, in percent |
| `blocklist_coverage` | hostile IPs that are listable (global addresses) / hostile IPs, in percent |
| `blocklist_leak` | hostile IPs neither banned nor listable (a count) |
| `ssh.fails_24h`, `ssh.users_distinct`, `ssh.ok_after_fail` | SSH failures in 24 h, distinct users tried in 24 h, sessions with a failure and then a successful login |
| `concentration.top10_ips`, `top5_asns` | share of malicious events from the 10 busiest IPs and the 5 busiest ASNs, in percent |
Sessions, exposure, refused exploits and `ok_after_fail` need the event registry and read at most a bounded number of events (`truncated` says when the window was cut).
## State and persistence
The state lives in memory: minute buckets for 7 days, hourly top lists (paths, domains, User-Agents, users), a table of up to 20,000 IPs (when full, the 10% with the lowest score are evicted; banned IPs are kept), a feed of the latest 500 events and the active bans. `--retention` (1h to 168h) bounds how long IPs are kept; old IPs are pruned every 10 minutes.
The state lives in memory: minute buckets for the latest 48 hours and hourly data up to 30 days, hourly top lists (paths, domains, User-Agents, users), a table of up to 20,000 IPs (when full, the 10% with the lowest score are evicted; banned IPs are kept), a feed of the latest 500 events and the active bans. `--retention` (1h to 168h) bounds how long IPs are kept; old IPs are pruned every 10 minutes.
Every 60 seconds, and on shutdown, the state is written to `urutau-state.gob` in the data directory together with the inode and offset of every source. On start it is restored and each source resumes exactly where it stopped, so a restart never counts a log twice. A snapshot is skipped while a backfill runs. An unreadable snapshot is moved to `urutau-state.gob.corrupt` and the service starts empty, reading the logs again (including the rotated copies).
The process sets a soft memory limit of 160 MiB unless `GOMEMLIMIT` is set.
The process sets a soft memory limit of 256 MiB unless `GOMEMLIMIT` is set. The worst case measured is about 54 MiB of heap and a snapshot of about 27 MB.
## Federation
A hub is an ordinary instance started with `--peer name=https://url`, and it needs `URUTAU_PEER_TOKEN`. Every 15 seconds it calls each peer's `GET /api/v1/peer/export?range=...` (for `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.
A hub is an ordinary instance started with `--peer name=https://url`, and it needs `URUTAU_PEER_TOKEN`. Every 15 seconds it calls each peer's `GET /api/v1/peer/export?range=...` (for the background ranges `1h`, `24h`, `7d` and `30d`; any other range or custom period is fetched on demand) with the peer token and keeps the latest answer. The export is `{"v":1,"summary":...,"traffic":{...}}` with the top 500 IPs and their detail, cached for 5 seconds on the peer. The peer token opens three routes: the export, the live stream and `GET /api/v1/peer/period`, the study (sessions, campaigns, metrics) the hub merges for a period or an IP; a peer runs at most two studies at once. The hub never follows redirects, requires `https` outside loopback, uses a 4 second timeout, caps the body at 8 MB and sanitizes and caps whatever a peer sends. A peer that fails is marked offline and the others carry on. The dashboard host selector then offers `all`, the hub itself and each peer; summaries, traffic and IP tables are merged, and every row carries the host it came from.
### Live relay
Besides the export, a hub keeps one `GET /api/v1/peer/stream` connection open per peer (a subscription per peer, with the peer's own token) and relays the live malicious events to its dashboard. What comes from a peer is bounded and sanitized: at most about 50 events per second per peer, lines of at most 16 KB, a buffer of the latest 500 relayed events (served by `/api/v1/live/recent`), and reconnection with backoff from 1 s up to 60 s. A peer serves at most 10 stream connections.
### Geography aggregation
`GET /api/v1/geo` is computed from the IP table (local and the peers' exports) joined with the geolocation databases: countries first, then, for one country, its regions, cities and top IPs. Results are cached for 5 seconds, in a cache of at most 256 keys.
## HTTP layer
+7 -3
View File
@@ -32,12 +32,16 @@ The access token is never a flag: `urutau serve` reads it from the `URUTAU_TOKEN
| `--peer` | `URUTAU_PEERS` | none | peer `name=https://url`; repeat the flag, or comma separate the variable |
| `--peer-token` | `URUTAU_PEER_TOKEN` | empty | token shared with the peers; prefer the variable or `URUTAU_PEER_TOKEN_FILE` (a flag shows up in the process list). Per-peer: `URUTAU_PEER_TOKEN_<NAME>` |
| `--admin-users` | `URUTAU_ADMIN_USERS` | empty | SSH users whose successful login keeps their IP out of the blocklist for 24 h; the immunity is off unless set |
| `--peer-allow` | `URUTAU_PEER_ALLOW` | empty | source CIDRs allowed to call the export; empty accepts any source with the token |
| `--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) |
| `--retention` | `URUTAU_RETENTION` | `720h` | how long data is kept (1h to 720h, that is 30 days) |
| `--events-max` | `URUTAU_EVENTS_MAX` | `512MB` | size cap of the event registry in `<data-dir>/events`; `0` turns it off |
| `--tor-exits` | `URUTAU_TOR_EXITS` | empty | file with Tor exit addresses, one per line, reloaded every 24 h when it changes; empty disables |
| `--insecure-no-auth` | none | off | disable authentication; only on a loopback bind |
Validation at start: peers must be `name=https://host` (plain `http` only on loopback), `URUTAU_PEER_TOKEN` must be set and different from `URUTAU_TOKEN`, names must be unique and cannot be `all` or the instance's own name, `--retention` must be at least 1h, and `URUTAU_TOKEN` and every peer token must have at least 32 characters and about 128 bits of estimated entropy; each peer needs a client token (`URUTAU_PEER_TOKEN_<NAME>` or the general `URUTAU_PEER_TOKEN` as fallback), and peer names must not collide in that variable name (unless `--insecure-no-auth` on a loopback address).
Validation at start: peers must be `name=https://host` (plain `http` only on loopback), `URUTAU_PEER_TOKEN` must be set and different from `URUTAU_TOKEN`, names must be unique and cannot be `all` or the instance's own name, `--retention` must be at least 1h (and at most 720h), and `URUTAU_TOKEN` and every peer token must have at least 32 characters and about 128 bits of estimated entropy; each peer needs a client token (`URUTAU_PEER_TOKEN_<NAME>` or the general `URUTAU_PEER_TOKEN` as fallback), and peer names must not collide in that variable name (unless `--insecure-no-auth` on a loopback address).
```bash
export URUTAU_TOKEN=$(openssl rand -base64 48)
+15 -5
View File
@@ -10,7 +10,7 @@ Urutau has no configuration file. Everything is a flag with a `URUTAU_*` environ
|---|---|
| `URUTAU_TOKEN` | **Required.** Access token of the dashboard and the API: at least 32 characters and about 128 bits of estimated entropy (length times Shannon entropy; periodic or sequential tokens are refused). Generate one with `openssl rand -base64 48` (`openssl rand -hex 32` also works; `-hex 16` is refused by the entropy estimate). |
| `URUTAU_TOKEN_FILE` | Path of a file holding the token (whitespace trimmed), instead of the variable. The variable wins when both are set. |
| `URUTAU_PEER_TOKEN` | Optional. The server token of this instance: the only token its `GET /api/v1/peer/export` accepts, and it opens nothing else. Same strength rules as `URUTAU_TOKEN` (32+ characters, about 128 bits of estimated entropy, not periodic or sequential), and it must differ from it. When this instance is a hub, it is also the fallback client token sent to peers that have no token of their own. |
| `URUTAU_PEER_TOKEN` | Optional. The server token of this instance: the only token its federation routes (`GET /api/v1/peer/export` and `GET /api/v1/peer/stream`) accept, and it opens nothing else. Same strength rules as `URUTAU_TOKEN` (32+ characters, about 128 bits of estimated entropy, not periodic or sequential), and it must differ from it. When this instance is a hub, it is also the fallback client token sent to peers that have no token of their own. |
| `URUTAU_PEER_TOKEN_FILE` | Path of a file holding the general peer token. |
| `URUTAU_PEER_TOKEN_<NAME>` and `..._<NAME>_FILE` | The client credential a hub sends to that one peer; it must equal the peer's own `URUTAU_PEER_TOKEN`. `<NAME>` is the peer name uppercased with every character other than a letter or digit turned into `_` (`my-peer` becomes `MY_PEER`). It does **not** open the local export. Two peer names that collapse to the same variable (`my-peer` and `my_peer`) are refused. A hub with a peer and no token for it refuses to start. |
@@ -31,14 +31,18 @@ Keep both in `.env` (never versioned) or in your orchestrator's secret store.
| `URUTAU_MONITOR_UA` | `(?i)^(Uptime-Kuma/\|Beszel\|Coolify\|kube-probe/\|Go-http-client/.*healthcheck)` | regular expression of monitoring User-Agents |
| `URUTAU_GEO_DIR` | `<data-dir>/geo` | where the DB-IP Lite databases live |
| `URUTAU_GEO_UPDATE` | `24h` | interval between checks for a newer database; `0` disables the download |
| `URUTAU_PEER_ALLOW` | empty | CIDRs allowed to call the export; empty accepts any source that has the token |
| `URUTAU_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 |
| `URUTAU_MONITOR_FROM` | empty | CIDRs the monitors really come from; when set, the monitoring User-Agent only counts from them |
| `URUTAU_ADMIN_USERS` | empty | SSH users whose successful login keeps their IP out of the blocklist for 24 h after the last login (a later strong signal cancels it); the immunity is off unless this is set |
| `URUTAU_PEERS` | empty | peers to aggregate, comma separated `name=https://url` |
| `URUTAU_RETENTION` | `168h` | retention as a Go duration, from `1h` to `168h` |
| `GOMEMLIMIT` | 160 MiB soft limit | standard Go memory limit; set it to override the default |
| `URUTAU_RETENTION` | `720h` | retention as a Go duration, from `1h` to `720h` (30 days) |
| `URUTAU_EVENTS_MAX` | `512MB` | size cap of the event registry (`<data-dir>/events`); `0` turns it off |
| `URUTAU_TOR_EXITS` | empty | file of Tor exit addresses, one per line, reloaded every 24 h when it changes |
| `GOMEMLIMIT` | 256 MiB soft limit | standard Go memory limit; set it to override the default |
| `TZ` | UTC | time zone of `fail2ban.log` timestamps, which carry no zone |
In the container image the three log paths default to `/logs/traefik/access.log`, `/logs/host/auth.log` and `/logs/host/fail2ban.log` (the compose file mounts the host logs there). The compose file adds `URUTAU_VERSION` (image tag), `URUTAU_IMAGE` and `URUTAU_PUBLISH` (host address and port), see `.env.example`.
@@ -54,7 +58,9 @@ 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 geolocation databases are checked every 24 hours (`--geo-update`), but DB-IP publishes a new one only once a month, so most checks find nothing new; the file is replaced after it is verified.
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)
@@ -69,6 +75,10 @@ On each peer, set the same `URUTAU_PEER_TOKEN`. The hub calls only `GET /api/v1/
The snapshot file holds the aggregated state and the log offsets. Mount `URUTAU_DATA_DIR` on a volume to keep it across restarts. Delete the file to start from zero (the rotated logs will be read again). Retention limits how long an IP is kept, at most 168 hours; the dashboard ranges are `1h`, `24h` and `7d`.
## Event registry
`<data-dir>/events/` keeps one line per attacker event, one file per UTC day, older days gzip compressed, deleted after `URUTAU_RETENTION`, and capped in total by `URUTAU_EVENTS_MAX` (a number with an optional unit, `0` turns the registry off). It never holds a legitimate visitor. It lives in the same volume as the snapshot, so plan for the cap on top of the snapshot (about 27 MB in the worst case measured). A full disk or the cap drops events and never stops the service. See [architecture.md](architecture.md).
## Authentication and exposure
The default bind is `0.0.0.0` because the container is behind a proxy. Outside a container, bind to `127.0.0.1` or put a TLS reverse proxy in front. `--insecure-no-auth` exists only for local tests and is refused on non-loopback binds.
+2 -2
View File
@@ -13,7 +13,7 @@ volume urutau-data ── read and write ─► /data (snapsho
The compose file follows this layout. The Traefik log directory is mounted outside `/data` so it does not collide with the snapshot volume. Only the dedicated `logs` directory of the proxy is mounted, never the whole `/data/coolify/proxy` (which holds `acme.json` and the dynamic configuration).
The image runs as the unprivileged user `urutau` (uid 10001) on Alpine. Its `HEALTHCHECK` is the binary itself (`urutau healthcheck`, which asks the local daemon for `/api/health`), so there is no `curl` in the image. The compose file sets `mem_limit: 256m` and `cpus: 0.5`, a read-only root filesystem, `cap_drop: [ALL]` and `no-new-privileges`, and passes from `.env` to the container: `URUTAU_TOKEN`, `URUTAU_NAME`, `URUTAU_TRUSTED`, `URUTAU_PEERS`, `URUTAU_PEER_TOKEN`, `URUTAU_PEER_ALLOW`, `URUTAU_TRUSTED_PROXY`, `URUTAU_DOMAINS`, `URUTAU_MONITOR_FROM`, `URUTAU_ADMIN_USERS`, `URUTAU_GEO_UPDATE` and `TZ`. To set any other `URUTAU_*` variable (`URUTAU_MONITOR_UA`, `URUTAU_RETENTION`, `URUTAU_TOKEN_FILE`, per-peer tokens, ...), add it to the `environment` block.
The image runs as the unprivileged user `urutau` (uid 10001) on Alpine. Its `HEALTHCHECK` is the binary itself (`urutau healthcheck`, which asks the local daemon for `/api/health`), so there is no `curl` in the image. The compose file sets a memory limit (`mem_limit`); the soft Go limit is 256 MiB and the worst case measured is about 54 MiB of heap plus a snapshot of about 27 MB, so `mem_limit: 384m` is recommended. The data volume also holds the event registry (`/data/events`, capped by `URUTAU_EVENTS_MAX`, 512 MB by default). The compose file sets and `cpus: 0.5`, a read-only root filesystem, `cap_drop: [ALL]` and `no-new-privileges`, and passes from `.env` to the container: `URUTAU_TOKEN`, `URUTAU_NAME`, `URUTAU_TRUSTED`, `URUTAU_PEERS`, `URUTAU_PEER_TOKEN`, `URUTAU_PEER_ALLOW`, `URUTAU_TRUSTED_PROXY`, `URUTAU_DOMAINS`, `URUTAU_MONITOR_FROM`, `URUTAU_ADMIN_USERS`, `URUTAU_GEO_UPDATE` and `TZ`. To set any other `URUTAU_*` variable (`URUTAU_MONITOR_UA`, `URUTAU_RETENTION`, `URUTAU_TOKEN_FILE`, per-peer tokens, ...), add it to the `environment` block.
## Quick start
@@ -150,7 +150,7 @@ Run one Urutau per server with its own `URUTAU_NAME`. Every instance that is pol
URUTAU_PEER_TOKEN_SERVER_3: ${TOKEN_FOR_SERVER_3}
```
The hub calls only `GET /api/v1/peer/export` on each peer (three ranges every 15 seconds) with that peer's token, which opens nothing else on the peer and is refused over plain `http` outside loopback. Set `URUTAU_PEER_ALLOW` on a peer to the hub's address to restrict who may call the export. Each peer keeps its own login token for its own dashboard.
The hub calls only `GET /api/v1/peer/export` on each peer (three ranges every 15 seconds) and keeps one `GET /api/v1/peer/stream` open for the live events, with that peer's token, which opens nothing else on the peer and is refused over plain `http` outside loopback. Set `URUTAU_PEER_ALLOW` on a peer to the hub's address to restrict who may call the export. Each peer keeps its own login token for its own dashboard.
## Hardening
Binary file not shown.

After

Width:  |  Height:  |  Size: 154 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 175 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 166 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 168 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 164 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 238 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 236 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 241 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 169 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 170 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 222 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 372 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 368 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 310 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 596 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 593 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 173 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 163 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 167 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 221 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 207 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 207 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 154 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 148 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 181 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 162 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 244 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 180 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 172 KiB

+79 -18
View File
@@ -8,31 +8,70 @@ 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`.
<p align="center"><img src="img/login-dark.png" width="900" alt="Login page"><br><sub>Login: paste the access token.</sub></p>
## Navigation
A side rail (a tab bar on phones) holds the 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`, `#/replay`, `#/traffic`, `#/ips`, `#/ip/<ip>`, `#/sources`), so a view can be bookmarked or shared; the Geography page goes deeper, as in `#/geo/BR/Pernambuco/Recife` (country, state, city). 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).
- The **host** selector: `all`, this instance and every peer of a hub.
- The **range** selector: `1h`, `24h` or `7d`.
- The **period** selector: twelve ranges (`1h`, `2h`, `3h`, `6h`, `12h`, `24h`, `2d`, `3d`, `5d`, `7d`, `15d`, `30d`) or a custom period (`from` and `to`, at most 30 days). It applies to every page.
- 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.
- **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.
## Traffic tab
<p align="center"><img src="img/overview-dark.png" width="900" alt="Overview page"><br><sub>Overview (demo data).</sub></p>
- **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.
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).
<p align="center"><img src="img/threats-dark.png" width="900" alt="Threats page"><br><sub>Threats: categories over time, KPIs and the latest events.</sub></p>
- **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>`.
<p align="center"><img src="img/geo-world-dark.png" width="900" alt="Geography page: world map by attacker country"><br><sub>Geography: the world by attacker country.</sub></p>
<p align="center"><img src="img/geo-brazil-dark.png" width="900" alt="Geography page zoomed on Brazil, by state"><br><sub>Geography: a country, by state and city.</sub></p>
<p align="center"><img src="img/geo-pernambuco-dark.png" width="900" alt="Geography page zoomed on the state of Pernambuco, with its city"><br><sub>Geography: a region, with its cities and top IPs.</sub></p>
- **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, a metrics column 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`.
<p align="center"><img src="img/live-flat-dark.png" width="900" alt="Live page on the flat map"><br><sub>Live: flat map.</sub></p>
<p align="center"><img src="img/live-globe-dark.png" width="900" alt="Live page on the 3D globe"><br><sub>Live: 3D globe.</sub></p>
<p align="center"><img src="img/replay-dark.png" width="900" alt="Replay page: a period replayed on the map with the ordered event list and the incident timeline"><br><sub>Replay: a period played back, with incidents on the timeline.</sub></p>
- **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).
<p align="center"><img src="img/traffic-dark.png" width="900" alt="Traffic page: web analytics of legitimate visitors"><br><sub>Traffic: privacy-friendly web analytics.</sub></p>
- **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.
<p align="center"><img src="img/ips-dark.png" width="900" alt="IPs page: table of addresses with score, level, origin and ban state"><br><sub>IPs: every address with score and level.</sub></p>
<p align="center"><img src="img/ip-analysis-dark.png" width="900" alt="IP analysis page for one attacker"><br><sub>IP analysis: verdict, evidence and recommended actions.</sub></p>
- **IP analysis** (`#/ip/<ip>`, opened from any IP): the verdict with its reasons, recommended actions, attack families and MITRE ATT&CK techniques, network type, cadence, sessions with their stage, campaigns, exposure, the event history and a STIX 2.1 download.
- **Replay** (`#/replay`): a period played back on the map with the ordered event list and the incident timeline, from the event registry.
- **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`.
<p align="center"><img src="img/sources-dark.png" width="900" alt="Sources and hosts page: instances, log sources and blocklist"><br><sub>Sources and hosts.</sub></p>
<p align="center"><img src="img/overview-light.png" width="620" alt="Overview in the light theme"> <img src="img/overview-mobile.png" height="420" alt="Overview on a phone"><br><sub>The light theme on a desktop and the phone layout (a tab bar replaces the side rail).</sub></p>
## Page groups
The side rail groups the pages:
- **Monitor:** Overview, Live, Services (per-service SLO, error budget, burn rate and Apdex; `#/slo`).
- **Investigate:** IPs, Sessions (the funnel from recon to access), Campaigns (and a page per campaign), Replay and Event search.
- **Analyze:** Threats, MITRE ATT&CK (techniques seen and when first seen), Geography, Evolution (change over time), Concentration (how much comes from few IPs or ASNs), Survival (time to ban, Kaplan-Meier), Traffic, Where errors come from (classes `app`, `proxy`, `blocked`, `attack`, `bot`, `client`, `unknown`) and Protocols and TLS (HTTP versions and TLS versions in use).
- **Operate:** Defense (ban and blocklist coverage and leaks), Sources and hosts, Integrity (health of the data: sources, registry, snapshot).
- **Reports:** a summary of a period, from `GET /api/v1/report`.
## Glossary and tooltips
A small **"?"** button sits next to metrics, categories and column titles. It is keyboard focusable and opens a short explanation (what the figure means) and a "what to do" line, in English or Portuguese. The text comes from one central glossary, so the same term reads the same on every page.
## Attribution
IP geolocation data by [DB-IP](https://db-ip.com), licensed under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). The credit also appears in the footer of the dashboard.
State and city boundaries on the Geography page are from [Natural Earth](https://www.naturalearthdata.com), public domain. IP geolocation data by [DB-IP](https://db-ip.com), licensed under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). The credit also appears in the footer of the dashboard.
## HTTP routes
@@ -41,13 +80,35 @@ IP geolocation data by [DB-IP](https://db-ip.com), licensed under [CC BY 4.0](ht
| `GET /api/health` | none | `{"status":"ok"}` |
| `GET /login`, `POST /login`, `POST /logout` | none | session |
| `GET /` and the static files | session | the dashboard |
| `GET /api/v1/summary` | session or bearer | everything the dashboard shows. Query: `range` (`1h`, `24h`, `7d`), `host` (`all`, a name) |
| `GET /api/v1/summary` | session or bearer | everything the dashboard shows. Query: `range` (any named range) or `from` and `to`, `host` (`all`, a name) |
| `GET /api/v1/traffic` | session or bearer | web analytics of legitimate traffic. Query: `range`, `domain` (`all` or one domain), `host`. Returns visitors, pages, requests, bots, bytes, status classes, `p50_ms`, `p95_ms`, a timeline, top pages, referrers, countries, cities, browsers, operating systems, devices and bot names |
| `GET /api/v1/peer/export` | peer token only | federation: `{"v":1,"summary":...,"traffic":{...}}` with the top 500 IPs and their detail. Query: `range` (`1h`, `24h`, `7d`). Cached for 5 s. 404 when no peer token is set, 401 for `URUTAU_TOKEN`, 403 from a source outside `--peer-allow` |
| `GET /api/v1/geo` | session or `URUTAU_TOKEN` | attacker geography. Without `cc`: `{"countries":[{"cc","events","ips","hostile","suspicious","cats"}]}` (up to 250). With `cc=XX` (and optionally `region`): `{"cc","events","ips","hostile","suspicious","cats","regions":[...],"cities":[{"name","region","lat","lon","events","ips"}],"top_ips":[...]}` (64 regions, 200 cities, 50 IPs). Query: `range`, `host`. Cached for 5 s |
| `GET /api/v1/live/recent` | session or `URUTAU_TOKEN` | `{"events":[...]}`: the latest malicious events of this instance and its peers, newest first, in the stream format. Query: `limit` (default 200, at most 500) |
| `GET /api/v1/peer/stream` | peer token only | live federation: server-sent malicious events of this instance. At most 10 connections; same 404/401/403 rules as the export |
| `GET /api/v1/peer/export` | peer token only | federation: `{"v":1,"summary":...,"traffic":{...}}` with the top 500 IPs and their detail. Query: `range` or `from`/`to`. Cached for 5 s. 404 when no peer token is set, 401 for `URUTAU_TOKEN`, 403 from a source outside `--peer-allow` |
| `GET /api/v1/events` | session or bearer | events of the registry, newest first. Query: `range` or `from`/`to`, `host`, `ip`, `cat`, `fam`, `q`, `order`, `limit`, `cursor` |
| `GET /api/v1/events/sessions` | session or bearer | sessions (bursts with a stage) of the period, optionally for one `ip` |
| `GET /api/v1/period` | session or bearer | the study of a period: sessions, campaigns, first-seen techniques, escalations, spikes, new vs returning, top targets, families, techniques, users and ASNs. Query: `range` or `from`/`to`, `host`, `gap` (seconds between sessions, 30 to 86400) |
| `GET /api/v1/period/events` | session or bearer | the events of a period in the stream format, for replay |
| `GET /api/v1/metrics` | session or bearer | stable metrics (see [architecture.md](architecture.md)). Query: `range` or `from`/`to`, `host` |
| `GET /api/v1/ip/{ip}/stix` | session or bearer | STIX 2.1 bundle of one IP |
| `GET /api/v1/peer/period` | peer token only | federation: the study a hub merges. At most two at once (503 with `Retry-After` otherwise) |
| `GET /api/v1/techniques` | session or bearer | MITRE ATT&CK techniques seen in the period |
| `GET /api/v1/evolution`, `/concentration`, `/survival` | session or bearer | analytics of the period: change over time, concentration by IP and ASN, and time to ban with the Kaplan-Meier curve |
| `GET /api/v1/sessions/funnel` | session or bearer | sessions by stage (recon, probe, exploit, access, banned) |
| `GET /api/v1/campaigns`, `/api/v1/campaigns/{id}` | session or bearer | campaigns of the period, and one campaign with its IPs |
| `GET /api/v1/defense` | session or bearer | ban and blocklist coverage and leaks |
| `GET /api/v1/errors` | session or bearer | errors by class (`app`, `proxy`, `blocked`, `attack`, `bot`, `client`, `unknown`) |
| `GET /api/v1/integrity` | session or bearer | health of the data: sources, registry, snapshot |
| `GET /api/v1/report` | session or bearer | summary of a period (requests, attacks, hostile IPs, bans, visitors, non-human clients, page views, top IPs) |
| `GET /api/v1/services`, `/api/v1/services/{svc}` | session or bearer | per-service SLI, SLO, error budget, burn rate and Apdex |
| `GET /api/v1/protocols` | session or bearer | HTTP and TLS versions in use |
| `GET /api/v1/ips` | session or bearer | IP table. Query: `range`, `host`, `min_score`, `level`, `q`, `banned=1`, `sort` (`score`, `last`, `first`, `events`, `ip`), `order=asc`, `per` (1 to 200, default 50), `page` |
| `GET /api/v1/ip/{ip}` | session or bearer | detail of one IP, merged with the peers' exports |
| `GET /api/v1/events/stream` | session or bearer | Server-Sent Events, event `ev`, a ping every 20 s |
| `GET /api/v1/ip/{ip}` | session or bearer | summarized analysis of one IP: verdict with reasons, actions, families, techniques, network type, cadence, sessions and exposure; merged with the peers. Query: `range` or `from`/`to` (default 30d) |
| `GET /api/v1/events/stream` | session or bearer | Server-Sent Events, event `ev`, a ping every 20 s. With `visits=1` it also sends anonymous `visit` events (no address, at most 20 per second) |
| `GET /api/v1/blocklist.txt` | session or bearer | one IP per line. Query: `min_score` (default 50), `range` (default `7d`), `host`, `family` (`4`, `6`; default both; `4` suits `ipset hash:ip`), `download=1` |
| `GET /api/v1/blocklist.json` | session or bearer | `{"generated","min_score","count","ips":[{"ip","score","last","hosts"}]}`; the `ip` of an IPv6 entry is a `/64` prefix |
API clients send `Authorization: Bearer <URUTAU_TOKEN>`. The peer token is accepted only by `/api/v1/peer/export`; every other route answers 403 to it.
An invalid `range` or period answers 400, and `range` in the responses is an object `{name,from,to,step,clipped}` (`step` is the timeline granularity in seconds).
API clients send `Authorization: Bearer <URUTAU_TOKEN>`. The peer token is accepted only by `/api/v1/peer/export`, `/api/v1/peer/stream` and `/api/v1/peer/period`; every other route answers 403 to it.
+98 -5
View File
@@ -10,7 +10,9 @@ internal/app flags, ligação das peças, runner dos logs, doctor
internal/tail seguidor de arquivo que tolera rotação e leitor de rotacionados
internal/core modelo de evento, parsers (Traefik, sshd, fail2ban), classificador
internal/store estado em memória, resumos, merge, snapshot
internal/rdns cache de DNS reverso
internal/rdns cache de DNS reverso e DNS reverso confirmado
internal/evlog registro de eventos em disco
internal/intel famílias, MITRE, tipo de rede, cadência, sessões, campanhas, vereditos, STIX, métricas
internal/fed hub que consulta os peers
internal/server handler HTTP, autenticação, dashboard embutido (web/)
```
@@ -83,19 +85,110 @@ 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.
## Períodos e granularidade
Toda visão recebe um intervalo: uma das doze janelas nomeadas (`1h`, `2h`, `3h`, `6h`, `12h`, `24h`, `2d`, `3d`, `5d`, `7d`, `15d`, `30d`) ou um período personalizado com `from` e `to` (segundos unix, no máximo 30 dias, cortado pela retenção; `clipped` indica quando foi). Um intervalo inválido responde 400. As respostas trazem `range` como objeto `{name,from,to,step,clipped}`, em que `step` é a granularidade da linha do tempo em segundos: 60 até 3 horas, 120 até 6, 300 até 12, 900 até 48 horas e 3600 acima disso. Buckets por minuto existem para as últimas 48 horas; dados mais antigos são por hora.
## Classes de erro e campos do Traefik
Além de cliente, caminho, status e User-Agent, o Urutau lê estes campos do access log do Traefik quando presentes: `OriginStatus`, `OriginDuration`, `Overhead`, `OriginContentSize`, `RetryAttempts`, `RouterName`, `ServiceName`, `RequestProtocol`, `RequestScheme`, `TLSVersion` e `TLSCipher`. Com eles todo erro é classificado:
| Classe | Significado |
|---|---|
| `app` | o próprio backend respondeu 5xx |
| `proxy` | o proxy não alcançou o backend, ou o cliente desistiu |
| `blocked` | recusado por um middleware ou limite de taxa antes do app |
| `attack` | a requisição é um ataque (veja as categorias acima) |
| `bot` | um crawler ou ferramenta |
| `client` | um erro comum de cliente (link quebrado, autenticação, entrada inválida) |
| `unknown` | nenhuma das anteriores pôde ser identificada |
## Serviços, SLO e Apdex
As requisições são agrupadas por serviço do Traefik (`ServiceName`, com seu router). Para cada serviço o Urutau guarda contadores por hora por classe de erro e histogramas de latência, e mostra: o **SLI** (parcela das requisições que não terminaram em um erro que conta contra o serviço), o **SLO** (meta de 99,5%), o **orçamento de erro** restante, o **burn rate** em 1 hora e 6 horas (taxa de erro dividida por `1 - SLO`; acima de 1 o orçamento está sendo gasto mais rápido que o permitido) e o **Apdex**. Ataques, requisições bloqueadas e bots não contam contra um serviço. O Apdex usa um limite T de 500 ms (1 s para caminhos de API): uma requisição respondida dentro de T é satisfeita, dentro de 4T tolerada, e um 5xx ou uma mais lenta é frustrada; o Apdex é (satisfeitas + toleradas/2) / total.
## Episódios e sobrevivência
Um **episódio** de ataque é a sequência de atividade de um endereço, encerrada após uma pausa. A partir dos episódios o Urutau mede o tempo entre o primeiro avistamento e o ban e desenha curvas de sobrevivência de **Kaplan-Meier** (a probabilidade de um endereço ainda não estar banido após certo tempo, com endereços nunca banidos tratados como censurados), com a mediana e o percentil 90.
## Visitantes únicos
Um **visitante** é uma pessoa com navegador real: um GET bem-sucedido (2xx) de um documento por um User-Agent de navegador (não bot, ferramenta nem cliente desconhecido), que não seja prefetch e, quando o navegador informa, com `Sec-Fetch-Dest: document`. É contado uma vez por IP por dia UTC, deduplicado globalmente entre domínios (um número por domínio e um total de todos os domínios). A chave é um hash de um sal diário, do IP e do domínio, e deixa o User-Agent de fora de propósito, porque scrapers o trocam a cada requisição a partir de um endereço (uma inflação medida de 2,7 vezes). Todo o resto que fala com um site (bots, ferramentas, User-Agents desconhecidos ou vazios) é contado à parte como **clientes não humanos**.
É por isso que o número difere do analytics do Coolify, que conta todo IP distinto por HyperLogLog sem filtro: bots, scanners e health checks o inflam. O número do Urutau é menor e mais próximo de pessoas.
## Stream de visitas legítimas
`GET /api/v1/events/stream?visits=1` acrescenta eventos anônimos de visita ao stream ao vivo. Uma visita não carrega endereço, User-Agent nem referrer; o lugar é a cidade, com coordenadas arredondadas a uma casa decimal (cerca de 11 km). No máximo 20 eventos de visita por segundo por instância são enviados (o excesso é resumido uma vez por segundo em um lote), e visitas só são transmitidas a assinantes: nunca gravadas no registro de eventos, em um snapshot nem em `live/recent`.
## Registro de eventos
`<data-dir>/events/` guarda uma linha JSON por evento, no mesmo formato do stream ao vivo, um arquivo por dia UTC. O dia corrente recebe appends e é sincronizado a cada 2 segundos; dias anteriores são compactados com gzip. Arquivos mais antigos que a retenção são apagados, e o total é limitado por `--events-max` (512 MB por padrão, `0` desativa o registro). Um dia guarda no máximo 200.000 linhas; acima disso os eventos só são contados.
O que entra: eventos maliciosos (scanner, exploit, bruteforce, ssh-fail, ssh-probe), ban e unban, logins SSH bem-sucedidos, um 404 respondido a uma ferramenta de ataque, e respostas `ok` ou `notfound` só de endereços já suspeitos ou hostis (para mostrar o que receberam). Nunca um visitante legítimo. Eventos repassados por peers são registrados com o nome do peer como host.
Comportamento em falha: disco cheio, o teto de tamanho ou o teto diário descartam eventos (contados, registrados no log no máximo de vez em quando, nunca fatais); uma linha corrompida é ignorada na leitura; uma linha parcial deixada por uma falha anterior é terminada antes da próxima escrita.
## Inteligência
A camada de investigação é calculada a partir da tabela de IPs e do registro, sem API externa:
- **Famílias de ataque** (`traversal`, `log4shell`, `sqli`, `xss`, `rce-injection`, `webshell`, `env-credentials`, `vcs`, `backup`, `wordpress`, `phpmyadmin-db`, `actuator-debug`, `iot-cgi`, `admin-panel`, `generic-404`) e as técnicas **MITRE ATT&CK** a que correspondem.
- **Tipo de rede** a partir do ASN, da organização do AS e do DNS reverso: `vpn`, `research-scanner`, `isp-cn`, `hosting`, `mobile`, `isp/mobile`, `residential`, `unknown`, e `tor` quando o endereço está no arquivo `--tor-exits` (recarregado a cada 24 horas quando muda).
- **Cadência** das requisições de um IP: `automated`, `human-like`, `mixed` ou `insufficient` (menos de 3 requisições).
- **Sessões:** rajadas de um IP separadas por uma pausa (30 minutos por padrão), cada uma com um estágio em severidade crescente: `recon`, `probe`, `exploit`, `access`, `banned`.
- **Campanhas:** pelo menos 3 IPs cujas sessões têm a mesma assinatura (caminhos normalizados parecidos, Jaccard 0,6 ou mais, mesma ferramenta) em uma janela; o id da assinatura é `c-` mais 8 caracteres hexadecimais.
- **Exposição:** uma resposta 2xx a uma requisição em caminho sensível.
- **Veredito com razões**, cada razão um código estável com peso (`exploits_refused`, `tool_ua`, `banned_jail`, `multi_category`, `exposure`, `ssh_login_after_bruteforce`, `admin`, `immune`), e **ações recomendadas** (`block`, `report`, `investigate`, `incident`); administradores e fontes imunes não recebem nenhuma.
- Exportação **STIX 2.1** de um IP (`/api/v1/ip/{ip}/stix`), com ids UUIDv5 determinísticos.
- **Crawlers:** um User-Agent que se diz Googlebot ou Bingbot é confirmado por DNS reverso confirmado; um falso continua sendo atacante.
- Usuários SSH listados em `--admin-users` são marcados como administradores.
## Métricas
`GET /api/v1/metrics` devolve números estáveis (sem taxa por minuto), cada um com seu valor, o valor anterior e um sparkline quando se aplica:
| Métrica | Fórmula |
|---|---|
| `attacks_per_hour_24h` | eventos maliciosos nas últimas 24 h / 24 |
| `moving_avg_7d_per_hour` | eventos maliciosos nos últimos 7 dias / 168 |
| `trend` | variação percentual dos eventos maliciosos no intervalo contra o intervalo anterior do mesmo tamanho |
| `active_attackers_24h`, `_1h` | IPs atacantes vistos nas últimas 24 h, na última hora |
| `new_attackers` | IPs vistos pela primeira vez dentro do intervalo (e do intervalo anterior) |
| `returning_rate` | IPs vistos no intervalo mas vistos antes dele / todos os IPs vistos no intervalo, em percentual |
| `sessions_per_day` | sessões no intervalo / dias do intervalo (pelo menos 1) |
| `exposure_rate` | sessões que receberam resposta de sucesso / sessões, em percentual |
| `exploits_refused_pct` | requisições de exploit respondidas 4xx ou 5xx / requisições de exploit com status, em percentual |
| `mttb` | mediana e percentil 90 do tempo entre o primeiro avistamento e o ban |
| `ban_coverage` | IPs hostis banidos / IPs hostis, em percentual |
| `blocklist_coverage` | IPs hostis listáveis (endereços globais) / IPs hostis, em percentual |
| `blocklist_leak` | IPs hostis nem banidos nem listáveis (uma contagem) |
| `ssh.fails_24h`, `ssh.users_distinct`, `ssh.ok_after_fail` | falhas SSH em 24 h, usuários distintos tentados em 24 h, sessões com falha e depois login bem-sucedido |
| `concentration.top10_ips`, `top5_asns` | parcela dos eventos maliciosos dos 10 IPs mais ativos e dos 5 ASNs mais ativos, em percentual |
Sessões, exposição, exploits recusados e `ok_after_fail` precisam do registro de eventos e leem um número limitado de eventos (`truncated` indica quando a janela foi cortada).
## Estado e persistência
O estado vive em memória: buckets por minuto de 7 dias, listas de top por hora (caminhos, domínios, User-Agents, usuários), uma tabela de até 20.000 IPs (quando cheia, 10% com a menor pontuação são removidos; IPs banidos são mantidos), um feed dos últimos 500 eventos e os bans ativos. `--retention` (1h a 168h) limita quanto tempo os IPs ficam; IPs antigos são podados a cada 10 minutos.
O estado vive em memória: buckets por minuto das últimas 48 horas e dados por hora até 30 dias, listas de top por hora (caminhos, domínios, User-Agents, usuários), uma tabela de até 20.000 IPs (quando cheia, 10% com a menor pontuação são removidos; IPs banidos são mantidos), um feed dos últimos 500 eventos e os bans ativos. `--retention` (1h a 168h) limita quanto tempo os IPs ficam; IPs antigos são podados a cada 10 minutos.
A cada 60 segundos, e no desligamento, o estado é gravado em `urutau-state.gob` no diretório de dados junto com o inode e a posição de cada fonte. Na inicialização ele é restaurado e cada fonte retoma exatamente de onde parou, então um reinício nunca conta um log duas vezes. O snapshot é pulado enquanto um backfill roda. Um snapshot ilegível é movido para `urutau-state.gob.corrupt` e o serviço sobe vazio, lendo os logs de novo (incluindo as cópias rotacionadas).
O processo define um limite suave de memória de 160 MiB, a menos que `GOMEMLIMIT` esteja definido.
O processo define um limite suave de memória de 256 MiB, a menos que `GOMEMLIMIT` esteja definido. O pior caso medido é cerca de 54 MiB de heap e um snapshot de cerca de 27 MB.
## Federação
Um hub é uma instância comum iniciada com `--peer nome=https://url`, e precisa de `URUTAU_PEER_TOKEN`. A cada 15 segundos ele chama `GET /api/v1/peer/export?range=...` de cada peer (para `1h`, `24h` e `7d`) com o token de peer e guarda a última resposta. O export é `{"v":1,"summary":...,"traffic":{...}}` com os 500 IPs principais e seus detalhes, em cache de 5 segundos no peer. É a única rota que o token de peer abre. O hub nunca segue redirects, exige `https` fora de loopback, usa timeout de 4 segundos, limita o corpo a 8 MB e sanitiza e limita o que um peer enviar. Um peer que falha é marcado offline e os demais seguem. O seletor de host do dashboard passa a oferecer `all`, o próprio hub e cada peer; resumos, tráfego e tabelas de IPs são mesclados, e cada linha carrega o host de origem.
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 os intervalos de fundo `1h`, `24h`, `7d` e `30d`; qualquer outro intervalo ou período personalizado é buscado sob demanda) 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. O token de peer abre três rotas: o export, o stream ao vivo e `GET /api/v1/peer/period`, o estudo (sessões, campanhas, métricas) que o hub mescla para um período ou um IP; um peer executa no máximo dois estudos ao mesmo tempo. 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
+7 -3
View File
@@ -32,12 +32,16 @@ O token de acesso nunca é uma flag: `urutau serve` o lê da variável de ambien
| `--peer` | `URUTAU_PEERS` | nenhum | peer `nome=https://url`; repita a flag ou separe a variável por vírgula |
| `--peer-token` | `URUTAU_PEER_TOKEN` | vazio | token compartilhado com os peers; prefira a variável ou `URUTAU_PEER_TOKEN_FILE` (uma flag aparece na lista de processos). Por peer: `URUTAU_PEER_TOKEN_<NOME>` |
| `--admin-users` | `URUTAU_ADMIN_USERS` | vazio | usuários SSH cujo login bem-sucedido mantém o IP fora da blocklist por 24 h; a imunidade fica desligada se não definido |
| `--peer-allow` | `URUTAU_PEER_ALLOW` | vazio | CIDRs de origem autorizados a chamar o export; vazio aceita qualquer origem com o token |
| `--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) |
| `--retention` | `URUTAU_RETENTION` | `720h` | por quanto tempo os dados ficam (1h a 720h, ou seja, 30 dias) |
| `--events-max` | `URUTAU_EVENTS_MAX` | `512MB` | teto de tamanho do registro de eventos em `<data-dir>/events`; `0` desliga |
| `--tor-exits` | `URUTAU_TOR_EXITS` | vazio | arquivo com endereços de saída do Tor, um por linha, recarregado a cada 24 h quando muda; vazio desativa |
| `--insecure-no-auth` | nenhuma | desligado | desativa a autenticação; só em bind loopback |
Validação na inicialização: peers devem ser `nome=https://host` (`http` simples só em loopback), `URUTAU_PEER_TOKEN` deve estar definido e ser diferente de `URUTAU_TOKEN`, os nomes devem ser únicos e não podem ser `all` nem o nome da própria instância, `--retention` deve ser de pelo menos 1h e `URUTAU_TOKEN` e todo token de peer devem ter pelo menos 32 caracteres e cerca de 128 bits de entropia estimada; cada peer precisa de um token de cliente (`URUTAU_PEER_TOKEN_<NOME>` ou o geral `URUTAU_PEER_TOKEN` como reserva), e os nomes de peer não podem colidir nesse nome de variável (salvo `--insecure-no-auth` em endereço loopback).
Validação na inicialização: peers devem ser `nome=https://host` (`http` simples só em loopback), `URUTAU_PEER_TOKEN` deve estar definido e ser diferente de `URUTAU_TOKEN`, os nomes devem ser únicos e não podem ser `all` nem o nome da própria instância, `--retention` deve ser de pelo menos 1h (e no máximo 720h) e `URUTAU_TOKEN` e todo token de peer devem ter pelo menos 32 caracteres e cerca de 128 bits de entropia estimada; cada peer precisa de um token de cliente (`URUTAU_PEER_TOKEN_<NOME>` ou o geral `URUTAU_PEER_TOKEN` como reserva), e os nomes de peer não podem colidir nesse nome de variável (salvo `--insecure-no-auth` em endereço loopback).
```bash
export URUTAU_TOKEN=$(openssl rand -base64 48)
+15 -5
View File
@@ -10,7 +10,7 @@ O Urutau não tem arquivo de configuração. Tudo é uma flag com padrão em var
|---|---|
| `URUTAU_TOKEN` | **Obrigatória.** Token de acesso do dashboard e da API: no mínimo 32 caracteres e cerca de 128 bits de entropia estimada (comprimento vezes entropia de Shannon; tokens periódicos ou sequenciais são recusados). Gere um com `openssl rand -base64 48` (`openssl rand -hex 32` também serve; `-hex 16` é recusado pela estimativa de entropia). |
| `URUTAU_TOKEN_FILE` | Caminho de um arquivo com o token (espaços nas pontas são removidos), no lugar da variável. A variável vence quando as duas existem. |
| `URUTAU_PEER_TOKEN` | Opcional. O token de servidor desta instância: o único que o `GET /api/v1/peer/export` dela aceita, e não abre mais nada. Mesmas regras de força do `URUTAU_TOKEN` (32+ caracteres, cerca de 128 bits de entropia estimada, sem padrão periódico nem sequencial), e deve ser diferente dele. Quando esta instância é um hub, também é o token de cliente de reserva enviado aos peers que não têm o seu. |
| `URUTAU_PEER_TOKEN` | Opcional. O token de servidor desta instância: o único que as rotas de federação dela (`GET /api/v1/peer/export` e `GET /api/v1/peer/stream`) aceitam, e não abre mais nada. Mesmas regras de força do `URUTAU_TOKEN` (32+ caracteres, cerca de 128 bits de entropia estimada, sem padrão periódico nem sequencial), e deve ser diferente dele. Quando esta instância é um hub, também é o token de cliente de reserva enviado aos peers que não têm o seu. |
| `URUTAU_PEER_TOKEN_FILE` | Caminho de um arquivo com o token de peer geral. |
| `URUTAU_PEER_TOKEN_<NOME>` e `..._<NOME>_FILE` | A credencial de cliente que um hub envia àquele peer; deve ser igual ao `URUTAU_PEER_TOKEN` do próprio peer. `<NOME>` é o nome do peer em maiúsculas, com todo caractere que não seja letra ou dígito virando `_` (`my-peer` vira `MY_PEER`). Ela **não** abre o export local. Dois nomes de peer que viram a mesma variável (`my-peer` e `my_peer`) são recusados. Um hub com um peer sem token para ele se recusa a iniciar. |
@@ -31,14 +31,18 @@ Guarde os dois no `.env` (nunca versionado) ou no cofre de segredos do seu orque
| `URUTAU_MONITOR_UA` | `(?i)^(Uptime-Kuma/\|Beszel\|Coolify\|kube-probe/\|Go-http-client/.*healthcheck)` | expressão regular de User-Agents de monitoramento |
| `URUTAU_GEO_DIR` | `<data-dir>/geo` | onde ficam as bases DB-IP Lite |
| `URUTAU_GEO_UPDATE` | `24h` | intervalo entre buscas por uma base mais nova; `0` desativa o download |
| `URUTAU_PEER_ALLOW` | vazio | CIDRs autorizados a chamar o export; vazio aceita qualquer origem que tenha o token |
| `URUTAU_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 |
| `URUTAU_MONITOR_FROM` | vazio | CIDRs de onde os monitores realmente vêm; quando definido, o User-Agent de monitoramento só vale vindo deles |
| `URUTAU_ADMIN_USERS` | vazio | usuários SSH cujo login bem-sucedido mantém o IP fora da blocklist por 24 h após o último login (um sinal forte posterior anula); a imunidade fica desligada a menos que seja definido |
| `URUTAU_PEERS` | vazio | peers a agregar, `nome=https://url` separados por vírgula |
| `URUTAU_RETENTION` | `168h` | retenção como duração do Go, de `1h` a `168h` |
| `GOMEMLIMIT` | limite suave de 160 MiB | limite de memória padrão do Go; defina para sobrescrever |
| `URUTAU_RETENTION` | `720h` | retenção como duração do Go, de `1h` a `720h` (30 dias) |
| `URUTAU_EVENTS_MAX` | `512MB` | teto de tamanho do registro de eventos (`<data-dir>/events`); `0` desliga |
| `URUTAU_TOR_EXITS` | vazio | arquivo de endereços de saída do Tor, um por linha, recarregado a cada 24 h quando muda |
| `GOMEMLIMIT` | limite suave de 256 MiB | limite de memória padrão do Go; defina para sobrescrever |
| `TZ` | UTC | fuso dos timestamps do `fail2ban.log`, que não trazem fuso |
Na imagem do container os três caminhos de log têm como padrão `/logs/traefik/access.log`, `/logs/host/auth.log` e `/logs/host/fail2ban.log` (o compose monta os logs do host ali). O compose acrescenta `URUTAU_VERSION` (tag da imagem), `URUTAU_IMAGE` e `URUTAU_PUBLISH` (endereço e porta no host), veja o `.env.example`.
@@ -54,7 +58,9 @@ 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).
As bases de geolocalização são conferidas a cada 24 horas (`--geo-update`), mas a DB-IP publica uma nova só uma vez por mês, então a maioria das conferências não acha nada novo; o arquivo é substituído depois de verificado.
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)
@@ -69,6 +75,10 @@ Em cada peer, defina o mesmo `URUTAU_PEER_TOKEN`. O hub chama apenas `GET /api/v
O arquivo de snapshot guarda o estado agregado e as posições dos logs. Monte `URUTAU_DATA_DIR` em um volume para mantê-lo entre reinícios. Apague o arquivo para começar do zero (os logs rotacionados serão lidos de novo). A retenção limita por quanto tempo um IP fica, no máximo 168 horas; os intervalos do dashboard são `1h`, `24h` e `7d`.
## Registro de eventos
`<data-dir>/events/` guarda uma linha por evento de atacante, um arquivo por dia UTC, dias antigos compactados com gzip, apagados após `URUTAU_RETENTION`, e limitado no total por `URUTAU_EVENTS_MAX` (um número com unidade opcional, `0` desliga o registro). Nunca guarda um visitante legítimo. Ele vive no mesmo volume do snapshot, então planeje o teto além do snapshot (cerca de 27 MB no pior caso medido). Disco cheio ou o teto descartam eventos e nunca param o serviço. Veja [arquitetura.md](arquitetura.md).
## Autenticação e exposição
O bind padrão é `0.0.0.0` porque o container fica atrás de um proxy. Fora de um container, faça bind em `127.0.0.1` ou coloque um proxy reverso com TLS na frente. `--insecure-no-auth` existe só para testes locais e é recusado em binds que não sejam loopback.
+2 -2
View File
@@ -13,7 +13,7 @@ volume urutau-data ── leitura e escrita ► /data (snapshot,
O compose segue esse layout. O diretório de logs do Traefik é montado fora de `/data` para não colidir com o volume do snapshot. Só o diretório `logs` dedicado do proxy é montado, nunca o `/data/coolify/proxy` inteiro (que guarda `acme.json` e a configuração dinâmica).
A imagem roda com o usuário sem privilégios `urutau` (uid 10001) em Alpine. O `HEALTHCHECK` é o próprio binário (`urutau healthcheck`, que pergunta `/api/health` ao daemon local), então não há `curl` na imagem. O compose define `mem_limit: 256m` e `cpus: 0.5`, sistema de arquivos raiz somente leitura, `cap_drop: [ALL]` e `no-new-privileges`, e repassa do `.env` ao container: `URUTAU_TOKEN`, `URUTAU_NAME`, `URUTAU_TRUSTED`, `URUTAU_PEERS`, `URUTAU_PEER_TOKEN`, `URUTAU_PEER_ALLOW`, `URUTAU_TRUSTED_PROXY`, `URUTAU_DOMAINS`, `URUTAU_MONITOR_FROM`, `URUTAU_ADMIN_USERS`, `URUTAU_GEO_UPDATE` e `TZ`. Para definir qualquer outra variável `URUTAU_*` (`URUTAU_MONITOR_UA`, `URUTAU_RETENTION`, `URUTAU_TOKEN_FILE`, tokens por peer, ...), acrescente-a ao bloco `environment`.
A imagem roda com o usuário sem privilégios `urutau` (uid 10001) em Alpine. O `HEALTHCHECK` é o próprio binário (`urutau healthcheck`, que pergunta `/api/health` ao daemon local), então não há `curl` na imagem. O compose define um limite de memória (`mem_limit`); o limite suave do Go é 256 MiB e o pior caso medido é cerca de 54 MiB de heap mais um snapshot de cerca de 27 MB, então recomenda-se `mem_limit: 384m`. O volume de dados também guarda o registro de eventos (`/data/events`, limitado por `URUTAU_EVENTS_MAX`, 512 MB por padrão). O compose define e `cpus: 0.5`, sistema de arquivos raiz somente leitura, `cap_drop: [ALL]` e `no-new-privileges`, e repassa do `.env` ao container: `URUTAU_TOKEN`, `URUTAU_NAME`, `URUTAU_TRUSTED`, `URUTAU_PEERS`, `URUTAU_PEER_TOKEN`, `URUTAU_PEER_ALLOW`, `URUTAU_TRUSTED_PROXY`, `URUTAU_DOMAINS`, `URUTAU_MONITOR_FROM`, `URUTAU_ADMIN_USERS`, `URUTAU_GEO_UPDATE` e `TZ`. Para definir qualquer outra variável `URUTAU_*` (`URUTAU_MONITOR_UA`, `URUTAU_RETENTION`, `URUTAU_TOKEN_FILE`, tokens por peer, ...), acrescente-a ao bloco `environment`.
## Início rápido
@@ -150,7 +150,7 @@ Rode um Urutau por servidor, cada um com seu `URUTAU_NAME`. Toda instância cons
URUTAU_PEER_TOKEN_SERVER_3: ${TOKEN_FOR_SERVER_3}
```
O hub chama apenas `GET /api/v1/peer/export` em cada peer (três intervalos a cada 15 segundos) com o token daquele peer, que não abre mais nada no peer e é recusado em `http` simples fora de loopback. Defina `URUTAU_PEER_ALLOW` em um peer com o endereço do hub para restringir quem pode chamar o export. Cada peer mantém seu próprio token de login para o próprio dashboard.
O hub chama apenas `GET /api/v1/peer/export` em cada peer (três intervalos a cada 15 segundos) e mantém um `GET /api/v1/peer/stream` aberto para os eventos ao vivo, com o token daquele peer, que não abre mais nada no peer e é recusado em `http` simples fora de loopback. Defina `URUTAU_PEER_ALLOW` em um peer com o endereço do hub para restringir quem pode chamar o export. Cada peer mantém seu próprio token de login para o próprio dashboard.
## Endurecimento
+76 -18
View File
@@ -8,31 +8,67 @@ 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.
<p align="center"><img src="../img/login-dark-pt.png" width="900" alt="Página de login"><br><sub>Login: cole o token de acesso.</sub></p>
## Navegação
Uma barra lateral (barra de abas no celular) reúne as 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`, `#/replay`, `#/traffic`, `#/ips`, `#/ip/<ip>`, `#/sources`), então uma visão pode ser salva ou compartilhada; a página Geografia vai mais fundo, como em `#/geo/BR/Pernambuco/Recife` (país, estado, cidade). 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).
- O seletor de **host**: `all`, esta instância e cada peer de um hub.
- O seletor de **intervalo**: `1h`, `24h` ou `7d`.
- O seletor de **período**: doze intervalos (`1h`, `2h`, `3h`, `6h`, `12h`, `24h`, `2d`, `3d`, `5d`, `7d`, `15d`, `30d`) ou um período personalizado (`from` e `to`, no máximo 30 dias). Vale para todas as páginas.
- 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.
- **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.
## Aba Tráfego
<p align="center"><img src="../img/overview-dark-pt.png" width="900" alt="Página Visão geral"><br><sub>Visão geral (dados de demonstração).</sub></p>
- **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.
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).
<p align="center"><img src="../img/threats-dark-pt.png" width="900" alt="Página Ameaças"><br><sub>Ameaças: categorias ao longo do tempo, KPIs e os últimos eventos.</sub></p>
- **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>`.
<p align="center"><img src="../img/geo-world-dark-pt.png" width="900" alt="Página Geografia: mapa-múndi por país do atacante"><br><sub>Geografia: o mundo por país do atacante.</sub></p>
- **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, uma coluna de métricas 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`.
<p align="center"><img src="../img/live-globe-dark-pt.png" width="900" alt="Página Ao vivo no globo 3D"><br><sub>Ao vivo: globo 3D.</sub></p>
<p align="center"><img src="../img/replay-dark-pt.png" width="900" alt="Página Replay: um período reproduzido no mapa, com a lista ordenada de eventos e a linha do tempo de incidentes"><br><sub>Replay: um período reproduzido, com os incidentes na linha do tempo.</sub></p>
- **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).
<p align="center"><img src="../img/traffic-dark-pt.png" width="900" alt="Página Tráfego: web analytics dos visitantes legítimos"><br><sub>Tráfego: web analytics amigável à privacidade.</sub></p>
- **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.
<p align="center"><img src="../img/ips-dark-pt.png" width="900" alt="Página IPs: tabela de endereços com pontuação, nível, origem e estado de ban"><br><sub>IPs: cada endereço com pontuação e nível.</sub></p>
<p align="center"><img src="../img/ip-analysis-dark-pt.png" width="900" alt="Página de análise de IP de um atacante"><br><sub>Análise de IP: veredito, evidências e ações recomendadas.</sub></p>
- **Análise de IP** (`#/ip/<ip>`, aberta a partir de qualquer IP): o veredito com suas razões, ações recomendadas, famílias de ataque e técnicas MITRE ATT&CK, tipo de rede, cadência, sessões com seu estágio, campanhas, exposição, o histórico de eventos e um download STIX 2.1.
- **Replay** (`#/replay`): um período reproduzido no mapa com a lista ordenada de eventos e a linha do tempo do incidente, a partir do registro de eventos.
- **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`.
<p align="center"><img src="../img/sources-dark-pt.png" width="900" alt="Página Fontes e hosts: instâncias, fontes de log e blocklist"><br><sub>Fontes e hosts.</sub></p>
<p align="center"><img src="../img/overview-light.png" width="620" alt="Visão geral no tema claro"> <img src="../img/overview-mobile.png" height="420" alt="Visão geral no celular"><br><sub>O tema claro no desktop e o layout de celular (uma barra de abas substitui a lateral).</sub></p>
## Grupos de páginas
A barra lateral agrupa as páginas:
- **Monitorar:** Visão geral, Ao vivo, Serviços (SLO por serviço, orçamento de erro, burn rate e Apdex; `#/slo`).
- **Investigar:** IPs, Sessões (o funil de recon até acesso), Campanhas (e uma página por campanha), Replay e Busca de eventos.
- **Analisar:** Ameaças, MITRE ATT&CK (técnicas vistas e quando foram vistas pela primeira vez), Geografia, Evolução (mudança ao longo do tempo), Concentração (quanto vem de poucos IPs ou ASNs), Sobrevivência (tempo até o ban, Kaplan-Meier), Tráfego, De onde vêm os erros (classes `app`, `proxy`, `blocked`, `attack`, `bot`, `client`, `unknown`) e Protocolos e TLS (versões de HTTP e de TLS em uso).
- **Operar:** Defesa (cobertura e vazamentos de ban e blocklist), Fontes e hosts, Integridade (saúde dos dados: fontes, registro, snapshot).
- **Relatórios:** um resumo de um período, de `GET /api/v1/report`.
## Glossário e dicas
Um pequeno botão **"?"** fica ao lado de métricas, categorias e títulos de coluna. Ele recebe foco pelo teclado e abre uma explicação curta (o que o número significa) e uma linha "o que fazer", em inglês ou português. O texto vem de um glossário central, então o mesmo termo aparece igual em todas as páginas.
## Atribuição
Dados de geolocalização de IP por [DB-IP](https://db-ip.com), licenciados sob [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). O crédito também aparece no rodapé do dashboard.
Os limites de estados e cidades da página Geografia são do [Natural Earth](https://www.naturalearthdata.com), domínio público. Dados de geolocalização de IP por [DB-IP](https://db-ip.com), licenciados sob [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). O crédito também aparece no rodapé do dashboard.
## Rotas HTTP
@@ -41,13 +77,35 @@ Dados de geolocalização de IP por [DB-IP](https://db-ip.com), licenciados sob
| `GET /api/health` | nenhuma | `{"status":"ok"}` |
| `GET /login`, `POST /login`, `POST /logout` | nenhuma | sessão |
| `GET /` e os arquivos estáticos | sessão | o dashboard |
| `GET /api/v1/summary` | sessão ou bearer | tudo o que o dashboard mostra. Query: `range` (`1h`, `24h`, `7d`), `host` (`all`, um nome) |
| `GET /api/v1/summary` | sessão ou bearer | tudo o que o dashboard mostra. Query: `range` (qualquer intervalo nomeado) ou `from` e `to`, `host` (`all`, um nome) |
| `GET /api/v1/traffic` | sessão ou bearer | web analytics do tráfego legítimo. Query: `range`, `domain` (`all` ou um domínio), `host`. Retorna visitantes, páginas, requisições, bots, bytes, classes de status, `p50_ms`, `p95_ms`, linha do tempo, top de páginas, referrers, países, cidades, navegadores, sistemas operacionais, dispositivos e nomes de bots |
| `GET /api/v1/peer/export` | só token de peer | federação: `{"v":1,"summary":...,"traffic":{...}}` com os 500 IPs principais e seus detalhes. Query: `range` (`1h`, `24h`, `7d`). Cache de 5 s. 404 sem token de peer, 401 para `URUTAU_TOKEN`, 403 de origem fora de `--peer-allow` |
| `GET /api/v1/geo` | sessão ou `URUTAU_TOKEN` | geografia dos atacantes. Sem `cc`: `{"countries":[{"cc","events","ips","hostile","suspicious","cats"}]}` (até 250). Com `cc=XX` (e opcionalmente `region`): `{"cc","events","ips","hostile","suspicious","cats","regions":[...],"cities":[{"name","region","lat","lon","events","ips"}],"top_ips":[...]}` (64 regiões, 200 cidades, 50 IPs). Query: `range`, `host`. Cache de 5 s |
| `GET /api/v1/live/recent` | sessão ou `URUTAU_TOKEN` | `{"events":[...]}`: os últimos eventos maliciosos desta instância e dos peers, do mais novo ao mais velho, no formato do stream. Query: `limit` (padrão 200, máximo 500) |
| `GET /api/v1/peer/stream` | só token de peer | federação ao vivo: eventos maliciosos desta instância por SSE. No máximo 10 conexões; mesmas regras 404/401/403 do export |
| `GET /api/v1/peer/export` | só token de peer | federação: `{"v":1,"summary":...,"traffic":{...}}` com os 500 IPs principais e seus detalhes. Query: `range` ou `from`/`to`. Cache de 5 s. 404 sem token de peer, 401 para `URUTAU_TOKEN`, 403 de origem fora de `--peer-allow` |
| `GET /api/v1/events` | sessão ou bearer | eventos do registro, do mais novo ao mais antigo. Query: `range` ou `from`/`to`, `host`, `ip`, `cat`, `fam`, `q`, `order`, `limit`, `cursor` |
| `GET /api/v1/events/sessions` | sessão ou bearer | sessões (rajadas com estágio) do período, opcionalmente de um `ip` |
| `GET /api/v1/period` | sessão ou bearer | o estudo de um período: sessões, campanhas, técnicas vistas pela primeira vez, escaladas, picos, novos vs recorrentes, principais alvos, famílias, técnicas, usuários e ASNs. Query: `range` ou `from`/`to`, `host`, `gap` (segundos entre sessões, 30 a 86400) |
| `GET /api/v1/period/events` | sessão ou bearer | os eventos de um período no formato do stream, para o replay |
| `GET /api/v1/metrics` | sessão ou bearer | métricas estáveis (veja [arquitetura.md](arquitetura.md)). Query: `range` ou `from`/`to`, `host` |
| `GET /api/v1/ip/{ip}/stix` | sessão ou bearer | bundle STIX 2.1 de um IP |
| `GET /api/v1/peer/period` | só token de peer | federação: o estudo que um hub mescla. No máximo dois ao mesmo tempo (503 com `Retry-After` caso contrário) |
| `GET /api/v1/techniques` | sessão ou bearer | técnicas MITRE ATT&CK vistas no período |
| `GET /api/v1/evolution`, `/concentration`, `/survival` | sessão ou bearer | análises do período: mudança ao longo do tempo, concentração por IP e ASN, e tempo até o ban com a curva de Kaplan-Meier |
| `GET /api/v1/sessions/funnel` | sessão ou bearer | sessões por estágio (recon, probe, exploit, access, banned) |
| `GET /api/v1/campaigns`, `/api/v1/campaigns/{id}` | sessão ou bearer | campanhas do período, e uma campanha com seus IPs |
| `GET /api/v1/defense` | sessão ou bearer | cobertura e vazamentos de ban e blocklist |
| `GET /api/v1/errors` | sessão ou bearer | erros por classe (`app`, `proxy`, `blocked`, `attack`, `bot`, `client`, `unknown`) |
| `GET /api/v1/integrity` | sessão ou bearer | saúde dos dados: fontes, registro, snapshot |
| `GET /api/v1/report` | sessão ou bearer | resumo de um período (requisições, ataques, IPs hostis, bans, visitantes, clientes não humanos, páginas vistas, principais IPs) |
| `GET /api/v1/services`, `/api/v1/services/{svc}` | sessão ou bearer | SLI, SLO, orçamento de erro, burn rate e Apdex por serviço |
| `GET /api/v1/protocols` | sessão ou bearer | versões de HTTP e TLS em uso |
| `GET /api/v1/ips` | sessão ou bearer | tabela de IPs. Query: `range`, `host`, `min_score`, `level`, `q`, `banned=1`, `sort` (`score`, `last`, `first`, `events`, `ip`), `order=asc`, `per` (1 a 200, padrão 50), `page` |
| `GET /api/v1/ip/{ip}` | sessão ou bearer | detalhe de um IP, mesclado com os exports dos peers |
| `GET /api/v1/events/stream` | sessão ou bearer | Server-Sent Events, evento `ev`, um ping a cada 20 s |
| `GET /api/v1/ip/{ip}` | sessão ou bearer | análise resumida de um IP: veredito com razões, ações, famílias, técnicas, tipo de rede, cadência, sessões e exposição; mesclada com os peers. Query: `range` ou `from`/`to` (padrão 30d) |
| `GET /api/v1/events/stream` | sessão ou bearer | Server-Sent Events, evento `ev`, um ping a cada 20 s. Com `visits=1` também envia eventos `visit` anônimos (sem endereço, no máximo 20 por segundo) |
| `GET /api/v1/blocklist.txt` | sessão ou bearer | um IP por linha. Query: `min_score` (padrão 50), `range` (padrão `7d`), `host`, `family` (`4`, `6`; padrão ambos; `4` serve ao `ipset hash:ip`), `download=1` |
| `GET /api/v1/blocklist.json` | sessão ou bearer | `{"generated","min_score","count","ips":[{"ip","score","last","hosts"}]}`; o `ip` de uma entrada IPv6 é um prefixo `/64` |
Clientes da API enviam `Authorization: Bearer <URUTAU_TOKEN>`. O token de peer só é aceito por `/api/v1/peer/export`; todas as outras rotas respondem 403 a ele.
Um `range` ou período inválido responde 400, e `range` nas respostas é um objeto `{name,from,to,step,clipped}` (`step` é a granularidade da linha do tempo em segundos).
Clientes da API enviam `Authorization: Bearer <URUTAU_TOKEN>`. O token de peer só é aceito por `/api/v1/peer/export`, `/api/v1/peer/stream` e `/api/v1/peer/period`; todas as outras rotas respondem 403 a ele.
+15
View File
@@ -413,3 +413,18 @@ func TestDefaultIgnoreCoversPrivateRanges(t *testing.T) {
}
}
}
func TestLocationFlagIsValidated(t *testing.T) {
for _, tc := range []struct {
v string
ok bool
}{{"", true}, {"-8.05,-34.9", true}, {"-8.05,-34.9,Recife", true}, {"95,0", false}, {"x", false}} {
c, err := ParseFlags("t", []string{"--location", tc.v})
if err != nil {
t.Fatal(err)
}
if _, err := c.Validate("zK3vQ9xT2mLp7WdR4nYb8HsJ6cFg1UaE5oXi0VtN"); (err == nil) != tc.ok {
t.Errorf("%q: %v", tc.v, err)
}
}
}
+129 -26
View File
@@ -9,37 +9,82 @@ import (
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"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"
)
// 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
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
TorExits string // file with Tor exit addresses, one per line; empty disables the check
EventsMax string // size cap of the event registry ("512MB", "0" disables it)
NoAuth bool
// Second firewall (see internal/enforce).
Enforce string // off (default), observe or on
EnforceLog string // decision file read by the host fail2ban
EnforceShare string // off (default) or on: exchange decisions with peers
EnforceThreshold int // attack events in 10 minutes that justify a ban
EnforceMaxPerMin int // decisions per minute; the excess is dropped
// Egress analysis (see internal/egress).
Egress string // auto (default: on when the log exists), on or off
EgressLog string // kernel log of new outbound connections
EgressWorkloads string // "name=CIDR|name:<prefix>[,...][:role];..."
EgressResolvers string // DNS resolvers allowed (empty: the usual public ones)
EgressContainers string // "<ip> <container>" map written by the host kit
}
// DefaultEventsMax is the default size cap of the event registry.
const DefaultEventsMax = "512MB"
// ParseSize reads "512MB", "1GiB", "2g", "1048576" (bytes) into bytes.
func ParseSize(v string) (int64, error) {
v = strings.TrimSpace(strings.ToLower(v))
if v == "" {
return 0, fmt.Errorf("empty size")
}
mult := int64(1)
for _, u := range []struct {
suf string
m int64
}{{"gib", 1 << 30}, {"mib", 1 << 20}, {"kib", 1 << 10}, {"gb", 1 << 30}, {"mb", 1 << 20}, {"kb", 1 << 10}, {"g", 1 << 30}, {"m", 1 << 20}, {"k", 1 << 10}, {"b", 1}} {
if strings.HasSuffix(v, u.suf) {
mult, v = u.m, strings.TrimSpace(strings.TrimSuffix(v, u.suf))
break
}
}
n, err := strconv.ParseFloat(v, 64)
if err != nil || n < 0 || n > 1<<40 {
return 0, fmt.Errorf("invalid size %q", v)
}
return int64(n * float64(mult)), nil
}
type listFlag []string
@@ -54,6 +99,15 @@ func env(key, def string) string {
return def
}
func envInt(key string, def int) int {
if v, ok := os.LookupEnv(key); ok {
if n, err := strconv.Atoi(strings.TrimSpace(v)); err == nil {
return n
}
}
return def
}
// csvFlag accumulates comma separated values; the first use replaces the default.
type csvFlag struct {
val string
@@ -103,7 +157,7 @@ func ParseFlags(name string, args []string) (Config, error) {
mfrom := &csvFlag{val: env("URUTAU_MONITOR_FROM", "")}
doms := &csvFlag{val: env("URUTAU_DOMAINS", "")}
admins := &csvFlag{val: env("URUTAU_ADMIN_USERS", "")}
fs.Var(admins, "admin-users", "SSH users whose successful logins keep their IP out of the blocklist for 24 h; empty means any user (URUTAU_ADMIN_USERS)")
fs.Var(admins, "admin-users", "SSH users whose successful logins keep their IP out of the blocklist for 24 h; empty means nobody is immune (URUTAU_ADMIN_USERS)")
fs.Var(mfrom, "monitor-from", "networks the monitoring User-Agents come from; empty trusts the User-Agent alone for benign hits (URUTAU_MONITOR_FROM)")
fs.Var(doms, "domains", "analytics domain allowlist, exact names or *.example.com; empty tracks every domain that answers 2xx/3xx (URUTAU_DOMAINS)")
fs.StringVar(&c.GeoDir, "geo-dir", env("URUTAU_GEO_DIR", ""), "geo database directory, default <data-dir>/geo (URUTAU_GEO_DIR)")
@@ -115,7 +169,21 @@ func ParseFlags(name string, args []string) (Config, error) {
tproxy := &csvFlag{val: env("URUTAU_TRUSTED_PROXY", DefaultTrustedProxy)}
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.DurationVar(&c.Retention, "retention", 7*24*time.Hour, "how long data is kept, at most 168h (URUTAU_RETENTION)")
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", store.DefaultRetention, "how long data is kept, at most 720h (URUTAU_RETENTION)")
fs.StringVar(&c.TorExits, "tor-exits", env("URUTAU_TOR_EXITS", ""), "file with Tor exit node addresses, one per line, reloaded every 24 h when it changes; empty disables (URUTAU_TOR_EXITS)")
fs.StringVar(&c.EventsMax, "events-max", env("URUTAU_EVENTS_MAX", DefaultEventsMax), "size cap of the event registry in <data-dir>/events, 0 disables it (URUTAU_EVENTS_MAX)")
fs.StringVar(&c.Enforce, "enforce", env("URUTAU_ENFORCE", "off"), "second firewall: off, observe (decide in memory only) or on (write decisions for the host fail2ban) (URUTAU_ENFORCE)")
fs.StringVar(&c.EnforceLog, "enforce-log", env("URUTAU_ENFORCE_LOG", "/logs/enforce/decisions.log"), "decision file appended in --enforce=on (URUTAU_ENFORCE_LOG)")
fs.StringVar(&c.EnforceShare, "enforce-share", env("URUTAU_ENFORCE_SHARE", "off"), "on: exchange decisions with peers, each side applies its own exclusions (URUTAU_ENFORCE_SHARE)")
fs.IntVar(&c.EnforceThreshold, "enforce-threshold", envInt("URUTAU_ENFORCE_THRESHOLD", 5), "attack events in 10 minutes that justify a ban (URUTAU_ENFORCE_THRESHOLD)")
fs.StringVar(&c.Egress, "egress", env("URUTAU_EGRESS", "auto"), "egress analysis: auto (on when --egress-log exists), on or off (URUTAU_EGRESS)")
fs.StringVar(&c.EgressLog, "egress-log", env("URUTAU_EGRESS_LOG", "/logs/host/egress.log"), "kernel log of new outbound connections written by the host kit (URUTAU_EGRESS_LOG)")
fs.StringVar(&c.EgressWorkloads, "egress-workloads", env("URUTAU_EGRESS_WORKLOADS", ""), "workloads: \"ciberlab=name:<container prefix>:scanner;mail=10.0.7.0/24:mail\" (URUTAU_EGRESS_WORKLOADS)")
fs.StringVar(&c.EgressResolvers, "egress-resolvers", env("URUTAU_EGRESS_RESOLVERS", ""), "DNS resolvers allowed, comma separated; empty: the usual public ones (URUTAU_EGRESS_RESOLVERS)")
fs.StringVar(&c.EgressContainers, "egress-containers", env("URUTAU_EGRESS_CONTAINERS", "/logs/host/containers.map"), "\"<ip> <container>\" map written by the host kit (URUTAU_EGRESS_CONTAINERS)")
fs.IntVar(&c.EnforceMaxPerMin, "enforce-max-per-min", envInt("URUTAU_ENFORCE_MAX_PER_MIN", 60), "most decisions per minute, the excess is dropped and counted (URUTAU_ENFORCE_MAX_PER_MIN)")
fs.BoolVar(&c.NoAuth, "insecure-no-auth", false, "disable authentication; only allowed on a loopback bind")
if v := os.Getenv("URUTAU_GEO_UPDATE"); v != "" {
if d, err := time.ParseDuration(v); err == nil {
@@ -168,6 +236,36 @@ func ParseFlags(name string, args []string) (Config, error) {
// Validate checks the configuration and returns the parsed peers.
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")
}
if c.Enforce != "" || c.EnforceShare != "" { // a Config built by hand may leave them unset
switch strings.ToLower(c.Enforce) {
case "", "off", "observe", "on":
default:
return nil, fmt.Errorf("--enforce must be off, observe or on")
}
if v := strings.ToLower(c.EnforceShare); v != "" && v != "off" && v != "on" {
return nil, fmt.Errorf("--enforce-share must be on or off")
}
if c.EnforceThreshold < 1 || c.EnforceThreshold > 1000 {
return nil, fmt.Errorf("--enforce-threshold must be between 1 and 1000")
}
if c.EnforceMaxPerMin < 1 || c.EnforceMaxPerMin > 10000 {
return nil, fmt.Errorf("--enforce-max-per-min must be between 1 and 10000")
}
}
switch strings.ToLower(c.Egress) {
case "", "auto", "on", "off":
default:
return nil, fmt.Errorf("--egress must be auto, on or off")
}
if strings.EqualFold(c.Enforce, "on") && c.EnforceLog == "" {
return nil, fmt.Errorf("--enforce=on needs --enforce-log")
}
var peers []fed.Peer
seen := map[string]bool{}
envSeen := map[string]string{}
@@ -194,8 +292,13 @@ func (c Config) Validate(token string) ([]fed.Peer, error) {
return nil, fmt.Errorf("--monitor-ua: %w", err)
}
}
if c.Retention < time.Hour {
return nil, fmt.Errorf("--retention must be at least 1h")
if c.Retention < time.Hour || c.Retention > store.DefaultRetention {
return nil, fmt.Errorf("--retention must be between 1h and 720h")
}
if c.EventsMax != "" {
if _, err := ParseSize(c.EventsMax); err != nil {
return nil, fmt.Errorf("--events-max: %w", err)
}
}
if c.NoAuth {
if !loopbackBind(c.Bind) {
+1
View File
@@ -56,6 +56,7 @@ func Doctor(c Config, w io.Writer, asJSON bool) bool {
os.Remove(f.Name())
add("data-dir", "ok", fmt.Sprintf("%s writable", filepath.Clean(c.DataDir)))
}
doctorEnforce(c, add)
geoInfo := doctorGeo(c, add)
stateInfo := doctorState(c, add)
ok := true
+98
View File
@@ -0,0 +1,98 @@
package app
import (
"log/slog"
"net/netip"
"net/url"
"os"
"strconv"
"strings"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/server"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
// newEgress builds the egress analysis, or returns nil when it is off (or in
// auto mode without the host log).
func newEgress(c Config, st *store.Store, log *slog.Logger) (*egress.Source, error) {
mode := strings.ToLower(c.Egress)
if mode == "off" || c.EgressLog == "" {
return nil, nil
}
if mode == "" || mode == "auto" {
if _, err := os.Stat(c.EgressLog); err != nil {
return nil, nil
}
}
var allow []netip.Prefix
if nets, err := core.ParseCIDRs(c.Trusted); err == nil {
for _, n := range nets {
if p, err := netip.ParsePrefix(n.String()); err == nil {
allow = append(allow, p)
}
}
}
allow = append(allow, egressExtraAllow(c)...)
eng, err := egress.New(egress.Config{
Workloads: c.EgressWorkloads,
Resolvers: c.EgressResolvers,
Allow: allow,
Containers: c.EgressContainers,
Geo: func(ip string) (string, string, string) {
g := st.GeoOf(ip)
asn := ""
if g.ASN != 0 {
asn = "AS" + strconv.FormatUint(uint64(g.ASN), 10)
}
return g.CC, asn, g.ASOrg
},
BadDst: func(a netip.Addr) (bool, string) {
if intel.IsTorExit(a) {
return true, "tor-exit"
}
if st.KnownHostile(a.String()) {
return true, "attacked-us"
}
return false, ""
},
})
if err != nil {
return nil, err
}
server.SetEgress(eng)
log.Info("egress analysis on", "log", c.EgressLog)
return egress.NewSource(c.EgressLog, eng, log), nil
}
// egressExtraAllow adds to the egress Allow list the addresses of the peers and
// the CIDRs of URUTAU_EGRESS_ALLOW (legitimate periodic pollers).
func egressExtraAllow(c Config) []netip.Prefix {
var out []netip.Prefix
for _, ps := range c.Peers {
p, err := fed.ParsePeer(ps)
if err != nil {
continue
}
if u, err := url.Parse(p.URL); err == nil && u.Hostname() != "" {
for _, a := range resolveHost(u.Hostname()) {
out = append(out, netip.PrefixFrom(a, a.BitLen()))
}
}
}
for _, s := range strings.Split(os.Getenv("URUTAU_EGRESS_ALLOW"), ",") {
if s = strings.TrimSpace(s); s == "" {
continue
}
if p, err := netip.ParsePrefix(s); err == nil {
out = append(out, p.Masked())
} else if a, err := netip.ParseAddr(s); err == nil {
a = a.Unmap()
out = append(out, netip.PrefixFrom(a, a.BitLen()))
}
}
return out
}
+164
View File
@@ -0,0 +1,164 @@
package app
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"net"
"net/netip"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
// newEnforce builds the second firewall and hooks it into the store; nil when off.
func newEnforce(c Config, st *store.Store, peers []fed.Peer, en enricher) *enforce.Engine {
mode := strings.ToLower(c.Enforce)
if mode != enforce.ModeObserve && mode != enforce.ModeOn {
return nil
}
trusted, _ := core.ParseCIDRs(c.Ignore + "," + c.Trusted)
var hosts []string
for _, p := range peers {
if u, err := url.Parse(p.URL); err == nil && u.Hostname() != "" {
hosts = append(hosts, u.Hostname())
}
}
e := enforce.New(enforce.Config{
Mode: mode, Path: c.EnforceLog, StatePath: filepath.Join(c.DataDir, "enforce.json"), Host: c.Name,
Threshold: c.EnforceThreshold, MaxPerMin: c.EnforceMaxPerMin, Share: strings.EqualFold(c.EnforceShare, "on"),
Trusted: trusted, PeerHosts: hosts, InfraHosts: hosts, Resolve: resolveHost,
Crawler: func(ip string, uas []string) bool { v := st.FCrDNS(ip, uas); return v != nil && *v },
Geo: func(ip string) (string, uint32, string) {
if en.g == nil {
return "", 0, ""
}
g := en.Geo(ip)
return g.CC, g.ASN, g.ASOrg
},
})
st.SetIngestHook(e.Observe)
return e
}
func resolveHost(h string) []netip.Addr {
if a, err := netip.ParseAddr(h); err == nil {
return []netip.Addr{a.Unmap()}
}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
ips, err := net.DefaultResolver.LookupNetIP(ctx, "ip", h)
if err != nil {
return nil
}
for i := range ips {
ips[i] = ips[i].Unmap()
}
return ips
}
// shareDecisions pulls the decisions of every peer and pushes the local ones, every 30 s.
func shareDecisions(ctx context.Context, hub *fed.Hub, e *enforce.Engine, log *slog.Logger) {
pulled := map[string]int64{}
pushed := map[string]int64{}
t := time.NewTicker(30 * time.Second)
defer t.Stop()
for {
for _, p := range hub.Peers {
start := time.Now().Unix()
var in struct {
Decisions []enforce.Wire `json:"decisions"`
}
if err := hub.Get(ctx, p, fmt.Sprintf("/api/v1/peer/decisions?since=%d", pulled[p.Name]), &in); err == nil {
e.AcceptPeer(p.Name, in.Decisions)
pulled[p.Name] = start - 5
} else if ctx.Err() == nil {
log.Debug("enforce: pull failed", "peer", p.Name, "err", err)
}
if mine := e.LocalSince(pushed[p.Name]); len(mine) > 0 {
if err := hub.PostJSON(ctx, p, "/api/v1/peer/decisions?from="+url.QueryEscape(e.Host()), map[string]any{"decisions": mine}); err == nil {
pushed[p.Name] = start
} else if ctx.Err() == nil {
log.Debug("enforce: push failed", "peer", p.Name, "err", err)
}
}
}
select {
case <-ctx.Done():
return
case <-t.C:
}
}
}
// doctorEnforce reports the mode of the second firewall and its file.
func doctorEnforce(c Config, add func(name, status, detail string)) {
mode := strings.ToLower(c.Enforce)
if mode == "" || mode == "off" {
add("enforce", "off", "disabled (--enforce=off)")
return
}
w := enforce.Writable(c.EnforceLog)
detail := fmt.Sprintf("mode=%s share=%s threshold=%d file=%s writable=%v", mode, strings.ToLower(orDefault(c.EnforceShare, "off")), c.EnforceThreshold, c.EnforceLog, w)
switch {
case mode == "on" && !w:
add("enforce", "fail", detail)
case !w:
add("enforce", "warn", detail)
default:
add("enforce", "ok", detail)
}
if mode == "on" {
if n, tot := cloudflareClients(c.TraefikLog); n > 0 {
add("enforce-cdn", "warn", fmt.Sprintf("%d of the last %d requests in %s come from Cloudflare addresses: Traefik is not "+
"restoring the real client IP (set entryPoints.*.forwardedHeaders.trustedIPs to the Cloudflare ranges); "+
"Cloudflare is never banned, but the real attackers stay invisible", n, tot, c.TraefikLog))
}
}
}
// cloudflareClients counts, in the tail of the Traefik JSON access log, the
// requests whose ClientHost is a Cloudflare address.
func cloudflareClients(path string) (cf, total int) {
if path == "" {
return 0, 0
}
f, err := os.Open(path)
if err != nil {
return 0, 0
}
defer f.Close()
const tail = 512 << 10
if fi, err := f.Stat(); err == nil && fi.Size() > tail {
f.Seek(fi.Size()-tail, io.SeekStart)
}
sc := bufio.NewScanner(f)
sc.Buffer(make([]byte, 0, 64<<10), 1<<20)
for sc.Scan() {
var l struct {
ClientHost string `json:"ClientHost"`
}
if json.Unmarshal(sc.Bytes(), &l) != nil || l.ClientHost == "" {
continue
}
a, err := netip.ParseAddr(l.ClientHost)
if err != nil {
continue
}
total++
if enforce.IsCloudflare(a) {
cf++
}
}
return cf, total
}
+70 -3
View File
@@ -9,6 +9,7 @@ import (
"net/http"
"os"
"os/signal"
"path/filepath"
"runtime/debug"
"strings"
"sync"
@@ -16,6 +17,7 @@ import (
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/geo"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/rdns"
@@ -35,13 +37,24 @@ func Serve(c Config) error {
return err
}
if os.Getenv("GOMEMLIMIT") == "" {
debug.SetMemoryLimit(160 << 20)
debug.SetMemoryLimit(SoftMemoryLimit)
}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
defer stop()
st := store.New(store.Config{Name: c.Name, Version: Version, Retention: c.Retention, AdminUsers: c.AdminUserList()})
loc, _ := store.ParseLocation(c.Location) // validated above
st := store.New(store.Config{Name: c.Name, Version: Version, Retention: c.Retention, AdminUsers: c.AdminUserList(), Location: loc})
st.SetDomains(splitList(c.Domains))
watchTorExits(ctx, c.TorExits, 24*time.Hour, log)
var elog *evlog.Log
if max, err := ParseSize(orDefault(c.EventsMax, DefaultEventsMax)); err == nil && max > 0 {
if elog, err = evlog.Open(evlog.Options{Dir: filepath.Join(c.DataDir, "events"), MaxBytes: max, Retention: c.Retention, Log: log}); err != nil {
log.Warn("event registry unavailable, replay disabled", "err", err)
elog = nil
} else {
st.SetEventLog(elog)
}
}
rd := rdns.New()
st.SetRDNS(rd)
offsets := LoadState(st, c.DataDir, log)
@@ -59,16 +72,44 @@ func Serve(c Config) error {
st.SetEnricher(en)
st.SetAttribution(Attribution)
runner.Extra = func() []store.SourceStatus { return []store.SourceStatus{geoStatus(gr, c.GeoDir)} }
// Real build dates of the geo databases for /api/v1/integrity (0 = unknown).
store.GeoBuilds = func() (int64, int64) {
if gr == nil {
return 0, 0
}
s := gr.Status()
var city, asn int64
if !s.City.Build.IsZero() {
city = s.City.Build.Unix()
}
if !s.ASN.Build.IsZero() {
asn = s.ASN.Build.Unix()
}
return city, asn
}
var hub *fed.Hub
if len(peers) > 0 {
hub = fed.NewHub(peers, c.PeerToken)
hub.OnLive = st.RecordPeerEvent
}
allow, _ := core.ParseCIDRs(c.PeerAllow)
tproxy, _ := core.ParseCIDRs(c.TrustedProxy)
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})
egressSrc, err := newEgress(c, st, log)
if err != nil {
return err
}
if egressSrc != nil {
extra := runner.Extra
runner.Extra = func() []store.SourceStatus { return append(extra(), egressSrc.Status()) }
}
eng := newEnforce(c, st, peers, en)
if eng != nil {
server.SetEnforce(eng)
}
ln, err := net.Listen("tcp", c.Bind)
if err != nil {
return err
@@ -76,7 +117,14 @@ func Serve(c Config) error {
srv := server.HTTPServer(h, ctx)
var wg sync.WaitGroup
if elog != nil {
wg.Add(1)
go func() { defer wg.Done(); elog.Run(ctx) }()
}
runner.Start(ctx, offsets, &wg)
if egressSrc != nil {
egressSrc.Start(ctx, &wg)
}
wg.Add(2)
go func() { defer wg.Done(); rd.Run(ctx) }()
go func() {
@@ -107,6 +155,14 @@ func Serve(c Config) error {
wg.Add(1)
go func() { defer wg.Done(); hub.Run(ctx) }()
}
if eng != nil {
wg.Add(1)
go func() { defer wg.Done(); eng.Run(ctx) }()
if hub != nil && eng.Share() {
wg.Add(1)
go func() { defer wg.Done(); shareDecisions(ctx, hub, eng, log) }()
}
}
log.Info("urutau started", "version", Version, "name", c.Name, "bind", ln.Addr().String(), "peers", len(peers), "auth", !c.NoAuth)
errc := make(chan error, 1)
go func() { errc <- srv.Serve(ln) }()
@@ -159,3 +215,14 @@ func splitList(s string) []string {
}
return out
}
// SoftMemoryLimit is the Go soft memory limit when GOMEMLIMIT is not set; see
// the worst case measurements in the store tests.
const SoftMemoryLimit = 256 << 20
func orDefault(v, def string) string {
if v == "" {
return def
}
return v
}
+1
View File
@@ -172,6 +172,7 @@ func (r *Runner) handle(s *source) func([]byte) {
ev.Soft, ev.Strong = ev.Status < 400, ev.Status >= 400
}
r.St.Ingest(ev)
r.St.ObserveService(ev)
if ev.Source == "traefik" && !ev.Forged && (ev.Cat == core.OK || ev.Cat == core.NotFound) {
r.St.Traffic(ev)
}
+89
View File
@@ -0,0 +1,89 @@
package app
import (
"bufio"
"context"
"errors"
"fmt"
"log/slog"
"net/netip"
"os"
"strings"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
)
const (
maxTorFile = 8 << 20
maxTorExits = 100000
)
// LoadTorExits reads a file with one address per line (blank lines and #
// comments are skipped, invalid lines ignored, at most 100000 addresses).
func LoadTorExits(path string) ([]netip.Addr, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
if st, err := f.Stat(); err != nil || !st.Mode().IsRegular() {
return nil, errors.New("not a regular file")
} else if st.Size() > maxTorFile {
return nil, fmt.Errorf("file larger than %d bytes", maxTorFile)
}
var out []netip.Addr
sc := bufio.NewScanner(f)
sc.Buffer(make([]byte, 0, 4096), 4096)
for sc.Scan() && len(out) < maxTorExits {
l := strings.TrimSpace(sc.Text())
if i := strings.IndexByte(l, '#'); i >= 0 {
l = strings.TrimSpace(l[:i])
}
if a, err := netip.ParseAddr(l); err == nil && a.Zone() == "" {
out = append(out, a.Unmap())
}
}
return out, sc.Err()
}
// watchTorExits loads the list now and again every interval when the file
// changed. An empty path keeps the feature off.
func watchTorExits(ctx context.Context, path string, every time.Duration, log *slog.Logger) {
if path == "" {
return
}
var lastMod time.Time
var lastSize int64 = -1
load := func() {
st, err := os.Stat(path)
if err != nil {
log.Warn("tor exit list unavailable", "err", err)
return
}
if st.ModTime().Equal(lastMod) && st.Size() == lastSize {
return
}
addrs, err := LoadTorExits(path)
if err != nil {
log.Warn("tor exit list unreadable", "err", err)
return
}
intel.SetTorExits(addrs)
lastMod, lastSize = st.ModTime(), st.Size()
log.Info("tor exit list loaded", "n", len(addrs))
}
load()
go func() {
t := time.NewTicker(every)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
load()
}
}
}()
}
+45
View File
@@ -0,0 +1,45 @@
package app
import (
"testing"
"time"
)
func TestRetentionEventsMaxFlags(t *testing.T) {
c, err := ParseFlags("serve", nil)
if err != nil || c.Retention != 720*time.Hour || c.EventsMax != "512MB" {
t.Fatalf("defaults %v %+v", err, c)
}
c, _ = ParseFlags("serve", []string{"--events-max", "1GiB", "--retention", "100h"})
if n, err := ParseSize(c.EventsMax); err != nil || n != 1<<30 || c.Retention != 100*time.Hour {
t.Fatal(c.EventsMax, c.Retention)
}
t.Setenv("URUTAU_EVENTS_MAX", "64m")
c, _ = ParseFlags("serve", nil)
if n, _ := ParseSize(c.EventsMax); n != 64<<20 {
t.Fatal("env")
}
tok := "tok-0123456789-abcdefghijklmnopqrstuvwxyz-QWERTY"
base := Config{Bind: "0.0.0.0:1", Ignore: DefaultIgnore, TrustedProxy: DefaultTrustedProxy, Retention: 720 * time.Hour}
if _, err := base.Validate(tok); err != nil {
t.Fatal(err)
}
base.Retention = 721 * time.Hour
if _, err := base.Validate(tok); err == nil {
t.Fatal("retention over 720h must be refused")
}
base.Retention, base.EventsMax = 720*time.Hour, "lots"
if _, err := base.Validate(tok); err == nil {
t.Fatal("bad --events-max must be refused")
}
for in, want := range map[string]int64{"512MB": 512 << 20, "0": 0, "2g": 2 << 30, "1048576": 1 << 20, "1.5kb": 1536} {
if n, err := ParseSize(in); err != nil || n != want {
t.Errorf("%s: %d %v", in, n, err)
}
}
for _, bad := range []string{"", "-1", "x", "1xb"} {
if _, err := ParseSize(bad); err == nil {
t.Errorf("%q must fail", bad)
}
}
}
+106
View File
@@ -0,0 +1,106 @@
package app
import (
"context"
"encoding/json"
"log/slog"
"net/http"
"net/http/httptest"
"net/netip"
"os"
"path/filepath"
"strings"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/geo"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/server"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
const realGeo = "/tmp/claude-1000/-home-lucas-Documents-Pessoal-keys/cd25aef5-8f8d-45f2-8ce0-f6644a45cb62/scratchpad/geo/real"
// Known addresses against the real DB-IP Lite databases: the ASN is filled and
// the network type follows. Skipped where the databases are not available.
func TestNetTypeWithRealGeoDatabases(t *testing.T) {
if _, err := os.Stat(realGeo); err != nil {
t.Skip("real geo databases not available")
}
gr, err := geo.Open(realGeo)
if err != nil {
t.Fatal(err)
}
st := store.New(store.Config{Name: "o", Retention: 720 * time.Hour})
st.SetEnricher(enricher{g: gr})
h := server.New(server.Options{Token: "user-token-0123456789-abcdefghijklmnop", Version: "t", Store: st})
cases := []struct {
ip string
asn float64
typ string
orgPart string
}{
{"159.89.1.1", 14061, "hosting", "DigitalOcean"},
{"78.46.1.1", 24940, "hosting", "Hetzner"},
{"129.146.1.1", 31898, "hosting", "Oracle"},
{"189.6.1.1", 28573, "isp/mobile", "Claro"}, // Brazilian residential/mobile operator
{"71.6.135.131", 10439, "research-scanner", "CariNet"},
}
for _, c := range cases {
st.Ingest(core.Event{Time: time.Now(), IP: c.ip, Cat: core.Scanner, Source: "traefik", Method: "GET", Path: "/.env", Status: 404})
r := httptest.NewRequest("GET", "/api/v1/ip/"+c.ip, nil)
r.Header.Set("Authorization", "Bearer user-token-0123456789-abcdefghijklmnop")
r.RemoteAddr = "198.51.100.1:1"
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
var d map[string]any
if err := json.Unmarshal(w.Body.Bytes(), &d); err != nil || w.Code != 200 {
t.Fatalf("%s: %d %s", c.ip, w.Code, w.Body)
}
id := d["identity"].(map[string]any)
if id["asn"].(float64) != c.asn || id["net_type"] != c.typ || !strings.Contains(id["as_org"].(string), c.orgPart) || id["net_type_reason"] == "" {
t.Errorf("%s: %v", c.ip, id)
}
if d["geo"].(map[string]any)["cc"] == "" {
t.Errorf("%s: no country", c.ip)
}
}
// the Tor exit list changes the type of a listed address
a := netip.MustParseAddr("159.89.1.1")
intel.SetTorExits([]netip.Addr{a})
defer intel.SetTorExits(nil)
if typ, _ := intel.NetTypeIP(a, 14061, "DigitalOcean, LLC", ""); typ != "tor" {
t.Fatalf("tor exit: %s", typ)
}
}
func TestTorExitsFile(t *testing.T) {
p := filepath.Join(t.TempDir(), "tor.txt")
os.WriteFile(p, []byte("# exits\n185.220.101.1\n\n 2001:db8::5 # v6\nnot-an-ip\n10.0.0.1%eth0\n185.220.101.2\n"), 0o600)
l, err := LoadTorExits(p)
if err != nil || len(l) != 3 {
t.Fatalf("%v %v", l, err)
}
big := filepath.Join(t.TempDir(), "big.txt")
os.WriteFile(big, []byte(strings.Repeat("1.2.3.4\n", 2<<20)), 0o600)
if _, err := LoadTorExits(big); err == nil {
t.Fatal("oversized file must be refused")
}
if _, err := LoadTorExits(t.TempDir()); err == nil {
t.Fatal("a directory is not a list")
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
defer intel.SetTorExits(nil)
watchTorExits(ctx, p, time.Hour, slog.New(slog.NewTextHandler(os.Stderr, nil)))
if !intel.IsTorExit(netip.MustParseAddr("185.220.101.1")) {
t.Fatal("exit list not applied")
}
watchTorExits(ctx, "", time.Hour, nil) // off: nothing happens
c, _ := ParseFlags("serve", []string{"--tor-exits", p})
if c.TorExits != p {
t.Fatal("flag")
}
_ = http.StatusOK
}
+259
View File
@@ -0,0 +1,259 @@
package app
import (
"encoding/json"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/server"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/tail"
)
const (
scratch = "/tmp/claude-1000/-home-lucas-Documents-Pessoal-keys/cd25aef5-8f8d-45f2-8ce0-f6644a45cb62/scratchpad"
tokV4 = "user-token-0123456789-abcdefghijklmnop"
)
// ingestLogs feeds the three log files through the runner, like a backfill.
func ingestLogs(t *testing.T, st *store.Store, dir string) {
t.Helper()
c := Config{Name: st.Name(), Ignore: DefaultIgnore, MonitorUA: DefaultMonitorUA, Retention: 720 * time.Hour, TrustedProxy: DefaultTrustedProxy,
TraefikLog: filepath.Join(dir, "access.log"), AuthLog: filepath.Join(dir, "auth.log"), Fail2banLog: filepath.Join(dir, "fail2ban.log")}
r, err := NewRunner(c, st, slog.New(slog.NewTextHandler(io.Discard, nil)))
if err != nil {
t.Fatal(err)
}
for _, s := range r.Sources {
if _, err := os.Stat(s.path); err != nil {
continue
}
if err := tail.ReadAll(s.path, maxLine, r.handle(s), func() {}); err != nil {
t.Fatal(err)
}
}
}
func newLogged(t *testing.T) *store.Store {
st := store.New(store.Config{Name: "edge-1", Version: "t", Retention: 720 * time.Hour})
l, err := evlog.Open(evlog.Options{Dir: filepath.Join(t.TempDir(), "events")})
if err != nil {
t.Fatal(err)
}
st.SetEventLog(l)
return st
}
func detail(t *testing.T, st *store.Store, ip string) map[string]any {
h := server.New(server.Options{Token: tokV4, Version: "t", Store: st})
r := httptest.NewRequest("GET", "/api/v1/ip/"+ip, nil)
r.Header.Set("Authorization", "Bearer "+tokV4)
r.RemoteAddr = "198.51.100.1:1"
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
if w.Code != http.StatusOK {
t.Fatalf("%s: %d %s", ip, w.Code, w.Body)
}
var m map[string]any
if err := json.Unmarshal(w.Body.Bytes(), &m); err != nil {
t.Fatal(err)
}
return m
}
func sum(series map[string]any) (total float64, buckets int) {
var rows [][]any
for _, v := range series {
rows = append(rows, v.([]any))
}
if len(rows) == 0 {
return
}
for i := range rows[0] {
var b float64
for _, r := range rows {
b += r[i].(float64)
}
total += b
if b > 0 {
buckets++
}
}
return
}
func num(m map[string]any, k string) float64 { f, _ := m[k].(float64); return f }
// checkConsistent asserts that every section of the detail view of the most
// hostile address of a data set tells the same story.
func checkConsistent(t *testing.T, st *store.Store, wantEvents bool) {
t.Helper()
ips := st.AllIPs(store.Ranges["30d"], false)
if len(ips) == 0 {
t.Fatal("no addresses")
}
top := ips[0].IP
d := detail(t, st, top)
counts := d["counts"].(map[string]any)
first, last := num(d, "first"), num(d, "last")
tm := d["time"].(map[string]any)
if ad, span := num(tm, "active_days"), num(tm, "span_days"); ad < 1 || ad > span || span != float64(int((last-first)/86400)+1) {
t.Errorf("%s: active_days %v span_days %v first %v last %v", top, ad, span, first, last)
}
ssh := d["ssh"].(map[string]any)
if num(ssh, "fails") != num(counts, "ssh-fail") {
t.Errorf("%s: ssh.fails %v vs counter %v", top, ssh["fails"], counts["ssh-fail"])
}
if num(counts, "ssh-fail") > 0 && len(ssh["users"].([]any)) == 0 && num(d, "events") == 0 {
t.Errorf("%s: ssh failures but no users", top)
}
if jails, _ := d["jails"].([]any); len(jails) > 0 {
active := 0
for _, b := range d["bans"].([]any) {
if b.(map[string]any)["active"] == true {
active++
}
}
if active != len(jails) {
t.Errorf("%s: %d active bans for %d jails: %v", top, active, len(jails), d["bans"])
}
}
if len(d["sessions"].([]any)) == 0 {
t.Errorf("%s: no sessions for an address with %v events", top, counts)
}
if len(d["techniques"].([]any)) == 0 || len(d["families"].([]any)) == 0 {
t.Errorf("%s: techniques/families empty: %v / %v", top, d["techniques"], d["families"])
}
if len(d["events"].([]any)) == 0 {
t.Errorf("%s: events empty", top)
}
tl := d["timeline"].(map[string]any)
total, buckets := sum(tl["series"].(map[string]any))
if total == 0 {
t.Errorf("%s: timeline is empty", top)
}
if wantEvents {
if d["timeline_source"] != "events" || d["sessions_source"] != "events" || d["events_source"] != "events" {
t.Errorf("%s: sources %v %v %v", top, d["timeline_source"], d["sessions_source"], d["events_source"])
}
lg := d["log"].(map[string]any)
logEvents, n := num(lg, "events"), num(lg, "sessions_events")
if n != logEvents || total != logEvents || num(tm, "sessions_n") != num(lg, "sessions_n") {
t.Errorf("%s: sessions %v timeline %v log %v must agree", top, n, total, logEvents)
}
if tm["active_days"].(float64) > 1 && buckets < 2 {
t.Errorf("%s: timeline in %d bucket(s) for %v active days", top, buckets, tm["active_days"])
}
// the timeline sits at the hours of the events, not at the time of the ingestion
step, start := num(tl, "step"), num(tl, "start")
for i, v := range tl["series"].(map[string]any)["scanner"].([]any) {
if v.(float64) > 0 {
if at := start + float64(i)*step; at < first-3600 || at > last+3600 {
t.Errorf("%s: bar at %v outside [%v, %v]", top, at, first, last)
}
}
}
} else if d["sessions_source"] != "counters" || d["events_source"] != "counters" {
t.Errorf("%s: without a registry the sections must say counters: %v %v", top, d["sessions_source"], d["events_source"])
}
// a snapshot restored next to an empty registry (events before the registry existed)
if wantEvents {
p := filepath.Join(t.TempDir(), "s.gob")
if err := st.Save(p, nil); err != nil {
t.Fatal(err)
}
st2 := newLogged(t)
if _, err := st2.Load(p); err != nil {
t.Fatal(err)
}
checkConsistent(t, st2, false)
}
}
func TestIPDetailConsistentOnSyntheticLogs(t *testing.T) {
dirs := map[string]string{"ui-shell": scratch + "/ui-shell/logs", "demo": scratch + "/demo/logs"}
ran := 0
for name, dir := range dirs {
if _, err := os.Stat(filepath.Join(dir, "access.log")); err != nil {
continue
}
ran++
t.Run(name, func(t *testing.T) {
st := newLogged(t)
ingestLogs(t, st, dir)
checkConsistent(t, st, true)
})
}
if ran == 0 {
t.Skip("synthetic data sets not available")
}
}
func TestEnforceConfig(t *testing.T) {
c, err := ParseFlags("x", []string{"--insecure-no-auth", "--bind", "127.0.0.1:1"})
if err != nil || c.Enforce != "off" || c.EnforceLog != "/logs/enforce/decisions.log" || c.EnforceShare != "off" || c.EnforceThreshold != 5 || c.EnforceMaxPerMin != 60 {
t.Fatalf("%+v %v", c, err)
}
for _, bad := range [][]string{{"--enforce=maybe"}, {"--enforce-share=x"}, {"--enforce-threshold=0"}, {"--enforce-max-per-min=0"}} {
c, err := ParseFlags("x", append([]string{"--insecure-no-auth", "--bind", "127.0.0.1:1", "--data-dir", t.TempDir()}, bad...))
if err != nil {
continue
}
if _, err := c.Validate(""); err == nil {
t.Errorf("%v accepted", bad)
}
}
t.Setenv("URUTAU_ENFORCE", "observe")
t.Setenv("URUTAU_ENFORCE_THRESHOLD", "9")
c, _ = ParseFlags("x", nil)
if c.Enforce != "observe" || c.EnforceThreshold != 9 {
t.Fatalf("env %+v", c)
}
}
func TestDoctorEnforce(t *testing.T) {
var got []Check
add := func(n, s, d string) { got = append(got, Check{n, s, d}) }
doctorEnforce(Config{Enforce: "on", EnforceLog: t.TempDir() + "/x/d.log", EnforceThreshold: 5}, add)
doctorEnforce(Config{Enforce: "on", EnforceLog: "/proc/nope/d.log"}, add)
doctorEnforce(Config{Enforce: "off"}, add)
if got[0].Status != "ok" || !strings.Contains(got[0].Detail, "mode=on") || got[1].Status != "fail" || got[2].Status != "off" {
t.Fatalf("%+v", got)
}
}
func TestDoctorEnforceCloudflare(t *testing.T) {
lg := filepath.Join(t.TempDir(), "access.log")
os.WriteFile(lg, []byte(`{"ClientHost":"104.16.1.1"}`+"\n"+`{"ClientHost":"203.0.114.5"}`+"\n"), 0o600)
var got []Check
add := func(n, s, d string) { got = append(got, Check{n, s, d}) }
doctorEnforce(Config{Enforce: "on", EnforceLog: t.TempDir() + "/x/d.log", TraefikLog: lg}, add)
if len(got) != 2 || got[1].Name != "enforce-cdn" || got[1].Status != "warn" {
t.Fatalf("%+v", got)
}
got = nil
doctorEnforce(Config{Enforce: "observe", EnforceLog: t.TempDir() + "/x/d.log", TraefikLog: lg}, add)
if len(got) != 1 {
t.Fatalf("%+v", got)
}
}
func TestEgressExtraAllow(t *testing.T) {
t.Setenv("URUTAU_EGRESS_ALLOW", "203.0.113.0/24, 198.51.100.7 ,bad")
got := egressExtraAllow(Config{Peers: []string{"p=https://192.0.2.9:8443"}})
var s []string
for _, p := range got {
s = append(s, p.String())
}
if strings.Join(s, " ") != "192.0.2.9/32 203.0.113.0/24 198.51.100.7/32" {
t.Fatalf("%v", s)
}
}
+1 -1
View File
@@ -2,4 +2,4 @@ package app
// Version is the release version (SemVer). Release builds may override it with
// -ldflags "-X .../internal/app.Version=...".
var Version = "1.0.0"
var Version = "1.4.0"
+198
View File
@@ -0,0 +1,198 @@
package core
import (
"net"
"net/url"
"regexp"
"strings"
)
// Error classes: where a 4xx/5xx comes from. The answer to "is this a bug in my
// application or a failed attack?".
const (
ClassAttack = "attack" // a probe, exploit or scanner: a frustrated attack
ClassBlocked = "blocked" // refused by a middleware or rate limit before the app
ClassProxy = "proxy" // the proxy could not reach the backend, or the client gave up
ClassApp = "app" // the backend itself answered 5xx
ClassBot = "bot" // a known crawler asking for something that is not there
ClassClient = "client" // an ordinary client mistake (broken link, auth, bad input)
ClassUnknown = "unknown"
)
// Subtypes of the client class.
const (
SubBrokenLink = "broken_link"
SubExternalLink = "external_link"
SubAuth = "auth"
SubAuthChallenge = "auth_challenge"
SubValidation = "validation"
SubCancelled = "cancelled"
SubOther = "other"
)
var okMethods = map[string]bool{"GET": true, "HEAD": true, "POST": true, "PUT": true, "PATCH": true, "DELETE": true, "OPTIONS": true}
var toolUARe = regexp.MustCompile(`(?i)(^|[^a-z])(curl|wget|python-requests|python-urllib|aiohttp|go-http-client|libwww-perl|okhttp|httpie|scrapy|sqlmap|nikto|nmap|masscan|zgrab|nuclei|dirbuster|gobuster|feroxbuster|wfuzz|hydra|httpx|fasthttp|java/|axios|node-fetch)([^a-z]|$)`)
var crawlerUARe = regexp.MustCompile(`(?i)(bot|crawler|spider|slurp|bingpreview|facebookexternalhit|embedly|ia_archiver|archive\.org|mediapartners|headlesschrome|lighthouse|pingdom|uptime|monitor)`)
var registryUARe = regexp.MustCompile(`(?i)(docker|containerd|buildkit|act_runner|gitea-runner|connect-go|skopeo|podman|go-containerregistry|oras|crane)`)
// rich reports whether the log line carried the origin fields. Without them
// (older Traefik, demo data) OriginStatus is unknown and is taken as equal to
// the downstream status.
func rich(ev Event) bool {
return ev.Proto != "" || ev.Scheme != "" || ev.Router != "" || ev.Service != ""
}
func originOf(ev Event) int {
if !rich(ev) {
return ev.Status
}
return ev.OriginStatus
}
func isIPHost(h string) bool {
if i := strings.LastIndexByte(h, ':'); i > 0 && !strings.Contains(h[i:], "]") {
h = h[:i]
}
h = strings.Trim(h, "[]")
return net.ParseIP(h) != nil
}
// NoRouter: the request matched no application router (the catch-all answered,
// or Traefik had nothing for the host): internet noise by definition.
func NoRouter(ev Event) bool {
if isIPHost(ev.Domain) {
return true
}
if !rich(ev) {
return false
}
return ev.Router == "" || strings.HasPrefix(ev.Router, "catchall") || strings.HasPrefix(ev.Service, "error-pages")
}
// AuthChallenge: the normal 401 a container registry or CI runner gets before
// presenting a token. Never an attack.
func AuthChallenge(ev Event) bool {
if ev.Status != 401 && ev.Status != 403 {
return false
}
p := ev.Path
if !(p == "/v2" || strings.HasPrefix(p, "/v2/") || strings.HasPrefix(p, "/api/actions")) {
return false
}
return registryUARe.MatchString(ev.UA)
}
// RunnerCall: a CI runner polling the forge API (never an attack, whatever the
// status): act_runner, gitea-runner or connect-go under /api/actions/.
func RunnerCall(ev Event) bool {
return strings.HasPrefix(ev.Path, "/api/actions") && registryUARe.MatchString(ev.UA)
}
func sameSite(ev Event) bool {
if ev.FetchSite == "same-origin" {
return true
}
if ev.Referer == "" || ev.Referer == "-" {
return false
}
u, err := url.Parse(ev.Referer)
if err != nil || u.Host == "" {
return false
}
h := strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.")
d := strings.TrimPrefix(strings.ToLower(ev.Domain), "www.")
if i := strings.LastIndexByte(d, ':'); i > 0 {
d = d[:i]
}
return h == d || strings.HasSuffix(h, "."+d) || strings.HasSuffix(d, "."+h)
}
var botPaths = []string{"/robots.txt", "/sitemap", "/favicon", "/apple-touch-icon", "/.well-known/"}
func isBotPath(p string) bool {
p = strings.ToLower(p)
for _, b := range botPaths {
if strings.HasPrefix(p, b) {
return true
}
}
return false
}
func browserLike(ev Event) bool {
switch ev.E.Device {
case "desktop", "mobile", "tablet":
return !ev.E.Bot
}
return ev.E.Device == "" && strings.HasPrefix(ev.UA, "Mozilla/") && !crawlerUARe.MatchString(ev.UA) && !toolUARe.MatchString(ev.UA)
}
// ErrorClass classifies a 4xx/5xx answer; "" for anything else. susp says the
// source address is suspicious, hostile or banned.
func ErrorClass(ev Event, susp bool) string {
c, _, _ := ErrorClassify(ev, susp)
return c
}
// ErrorClassify is ErrorClass with the client subtype and the under_attack mark
// (a real application failure on a request that looks like an attack).
func ErrorClassify(ev Event, susp bool) (class, sub string, underAttack bool) {
st := ev.Status
if st < 400 || st > 599 {
return "", "", false
}
origin := originOf(ev)
challenge := AuthChallenge(ev) || (RunnerCall(ev) && st < 500)
if challenge {
return ClassClient, SubAuthChallenge, false
}
attackish := ev.Cat == Scanner || ev.Cat == Exploit || ev.Cat == BruteForce ||
(ev.Method != "" && !okMethods[strings.ToUpper(ev.Method)]) ||
ev.UA == "" || ev.E.Tool || (toolUARe.MatchString(ev.UA) && !registryUARe.MatchString(ev.UA)) ||
susp || NoRouter(ev)
if RunnerCall(ev) {
attackish = false
}
// the backend really failed: an application error, even if an attacker caused it
if ev.Retries > 0 && st >= 500 && !NoRouter(ev) {
return ClassProxy, "", false
}
if origin >= 500 && st >= 500 && !NoRouter(ev) {
return ClassApp, "", attackish
}
if attackish {
return ClassAttack, "", false
}
if st == 429 || ((st == 403 || st == 401) && origin == 0) {
return ClassBlocked, "", false
}
if ((st == 502 || st == 503 || st == 504) && origin == 0) || (ev.Retries > 0 && st >= 500) {
return ClassProxy, "", false
}
if st >= 500 {
return ClassProxy, "", false // a 5xx the backend did not produce
}
if st == 499 {
return ClassClient, SubCancelled, false // the client gave up: not a server error
}
if ev.E.Bot || crawlerUARe.MatchString(ev.UA) || (st == 404 && isBotPath(ev.Path)) {
return ClassBot, "", false
}
switch st {
case 404:
if sameSite(ev) {
return ClassClient, SubBrokenLink, false
}
if ev.Referer != "" && ev.Referer != "-" {
return ClassClient, SubExternalLink, false
}
case 401, 403:
if origin == st && browserLike(ev) {
return ClassClient, SubAuth, false
}
case 400, 405, 413, 422:
return ClassClient, SubValidation, false
}
return ClassClient, SubOther, false
}
+61
View File
@@ -0,0 +1,61 @@
package core
import "testing"
func TestErrorClass(t *testing.T) {
rich := func(e Event) Event {
e.Proto, e.Scheme = "HTTP/2.0", "https"
if e.Router == "" {
e.Router, e.Service = "https-0-abc-gitea@docker", "https-0-abc-gitea@docker"
}
return e
}
moz := "Mozilla/5.0 (Windows NT 10.0) Chrome/120"
cases := []struct {
name string
ev Event
susp bool
class string
sub string
attack bool
}{
{"catchall env probe", Event{Status: 503, OriginStatus: 503, Method: "GET", Path: "/.env", UA: moz, Domain: "blog.example.com", Router: "catchall@file", Service: "error-pages@file", Proto: "HTTP/2.0"}, false, "attack", "", false},
{"no router 404", Event{Status: 404, Method: "GET", Path: "/x", UA: moz, Domain: "a.example.com", Proto: "HTTP/1.1"}, false, "attack", "", false},
{"ip host", Event{Status: 404, OriginStatus: 404, Method: "GET", Path: "/", UA: moz, Domain: "136.0.0.1", Router: "x@docker", Proto: "HTTP/1.1"}, false, "attack", "", false},
{"scanner cat", rich(Event{Status: 404, OriginStatus: 404, Method: "GET", Path: "/wp-login.php", UA: moz, Cat: Scanner}), false, "attack", "", false},
{"weird method", rich(Event{Status: 405, OriginStatus: 405, Method: "PROPFIND", UA: moz}), false, "attack", "", false},
{"empty ua", rich(Event{Status: 404, OriginStatus: 404, Method: "GET", Path: "/a"}), false, "attack", "", false},
{"curl", rich(Event{Status: 404, OriginStatus: 404, Method: "GET", Path: "/a", UA: "curl/8.1"}), false, "attack", "", false},
{"suspicious ip", rich(Event{Status: 404, OriginStatus: 404, Method: "GET", Path: "/a", UA: moz}), true, "attack", "", false},
{"429", rich(Event{Status: 429, Method: "GET", UA: moz}), false, "blocked", "", false},
{"401 origin 0", rich(Event{Status: 401, OriginStatus: 0, Method: "GET", UA: moz, Path: "/x"}), false, "blocked", "", false},
{"504 origin 0", rich(Event{Status: 504, OriginStatus: 0, Method: "GET", UA: moz, Path: "/x"}), false, "proxy", "", false},
{"499 is the client", rich(Event{Status: 499, OriginStatus: 0, Method: "GET", UA: moz, Path: "/x"}), false, "client", "cancelled", false},
{"runner poll", rich(Event{Status: 404, OriginStatus: 404, Method: "POST", UA: "connect-go/1.16 (go1.22)", Path: "/api/actions/runner.v1.RunnerService/FetchTask", Cat: Scanner}), true, "client", "auth_challenge", false},
{"gitea-runner", rich(Event{Status: 401, OriginStatus: 0, Method: "POST", UA: "gitea-runner/0.2", Path: "/api/actions/x"}), true, "client", "auth_challenge", false},
{"502 retry", rich(Event{Status: 502, OriginStatus: 502, Retries: 2, Method: "GET", UA: moz}), false, "proxy", "", false},
{"app 500", rich(Event{Status: 500, OriginStatus: 500, Method: "POST", UA: moz, Path: "/api/x"}), false, "app", "", false},
{"app 500 under attack", rich(Event{Status: 500, OriginStatus: 500, Method: "GET", UA: moz, Path: "/a?x=../", Cat: Exploit}), false, "app", "", true},
{"crawler 404", rich(Event{Status: 404, OriginStatus: 404, Method: "GET", UA: "Mozilla/5.0 (compatible; ElevenlabsCrawler/1.0)", Path: "/z"}), false, "bot", "", false},
{"robots 404", rich(Event{Status: 404, OriginStatus: 404, Method: "GET", UA: moz, Path: "/robots.txt"}), false, "bot", "", false},
{"broken link", rich(Event{Status: 404, OriginStatus: 404, Method: "GET", UA: moz, Path: "/old", Domain: "a.example.com", Referer: "https://a.example.com/index"}), false, "client", "broken_link", false},
{"fetch same-origin", rich(Event{Status: 404, OriginStatus: 404, Method: "GET", UA: moz, Path: "/old", FetchSite: "same-origin"}), false, "client", "broken_link", false},
{"external link", rich(Event{Status: 404, OriginStatus: 404, Method: "GET", UA: moz, Path: "/old", Domain: "a.example.com", Referer: "https://news.ycombinator.com/"}), false, "client", "external_link", false},
{"auth browser", rich(Event{Status: 401, OriginStatus: 401, Method: "GET", UA: moz, Path: "/admin", E: Enrich{Device: "desktop"}}), false, "client", "auth", false},
{"registry challenge", rich(Event{Status: 401, OriginStatus: 401, Method: "GET", UA: "docker/27.0 go/go1.22", Path: "/v2/"}), true, "client", "auth_challenge", false},
{"actions challenge", rich(Event{Status: 401, OriginStatus: 401, Method: "GET", UA: "act_runner/0.2", Path: "/api/actions/x"}), false, "client", "auth_challenge", false},
{"validation", rich(Event{Status: 422, OriginStatus: 422, Method: "POST", UA: moz, Path: "/api/x"}), false, "client", "validation", false},
{"404 plain", rich(Event{Status: 404, OriginStatus: 404, Method: "GET", UA: moz, Path: "/nope"}), false, "client", "other", false},
{"legacy log 500", Event{Status: 500, Method: "GET", UA: moz, Path: "/x", Domain: "a.example.com"}, false, "app", "", false},
{"200", Event{Status: 200}, false, "", "", false},
}
for _, c := range cases {
cl, sub, ua := ErrorClassify(c.ev, c.susp)
if cl != c.class || sub != c.sub || ua != c.attack {
t.Errorf("%s: got %q/%q/%v want %q/%q/%v", c.name, cl, sub, ua, c.class, c.sub, c.attack)
}
if ErrorClass(c.ev, c.susp) != c.class {
t.Errorf("%s: ErrorClass mismatch", c.name)
}
}
}
+14 -1
View File
@@ -149,7 +149,20 @@ type Event struct {
DurationNS int64
Bytes int64
Referer string
E Enrich
// FetchDest is Sec-Fetch-Dest ("document", "empty", "image"...), "" when the
// browser did not send it. Prefetch: Sec-Purpose / Purpose said prefetch.
FetchDest string
Prefetch bool
// Origin details (Traefik only, empty on older logs): what the backend
// answered and where the time went.
OriginStatus int
OriginNS, OverheadNS int64
OriginBytes int64
Retries int
Router, Service string
Proto, Scheme, TLSVer, TLSCiph string
EntryPoint, FetchSite string
E Enrich
}
// Enrich holds what the geo and user-agent databases say about an event. It is
+24
View File
@@ -51,8 +51,23 @@ type traefikLine struct {
Referer string `json:"request_Referer"`
FetchSite string `json:"request_Sec-Fetch-Site"`
FetchDest string `json:"request_Sec-Fetch-Dest"`
SecPurpose string `json:"request_Sec-Purpose"`
Purpose string `json:"request_Purpose"`
Duration int64 `json:"Duration"`
Size int64 `json:"DownstreamContentSize"`
OriginStatus int `json:"OriginStatus"`
OriginDur int64 `json:"OriginDuration"`
Overhead int64 `json:"Overhead"`
OriginSize int64 `json:"OriginContentSize"`
Retries int `json:"RetryAttempts"`
Router string `json:"RouterName"`
Service string `json:"ServiceName"`
Proto string `json:"RequestProtocol"`
Scheme string `json:"RequestScheme"`
TLSVer string `json:"TLSVersion"`
TLSCipher string `json:"TLSCipher"`
EntryPoint string `json:"entryPointName"`
}
// ParseTraefik parses one Traefik JSON access log line.
@@ -82,6 +97,15 @@ func ParseTraefik(line []byte) (Event, error) {
DurationNS: l.Duration, Bytes: l.Size, Referer: clip(l.Referer, 300),
}
ev.Framed = Framed(l.FetchSite, l.FetchDest)
ev.OriginStatus, ev.OriginNS, ev.OverheadNS, ev.OriginBytes, ev.Retries = l.OriginStatus, l.OriginDur, l.Overhead, l.OriginSize, l.Retries
ev.Router, ev.Service = clip(l.Router, 64), clip(l.Service, 64)
ev.Proto, ev.Scheme, ev.TLSVer, ev.TLSCiph = clip(l.Proto, 12), clip(l.Scheme, 8), clip(l.TLSVer, 8), clip(l.TLSCipher, 64)
ev.EntryPoint, ev.FetchSite = clip(l.EntryPoint, 64), clip(strings.ToLower(l.FetchSite), 16)
ev.FetchDest = strings.ToLower(strings.TrimSpace(l.FetchDest))
if len(ev.FetchDest) > 20 {
ev.FetchDest = ev.FetchDest[:20]
}
ev.Prefetch = strings.Contains(strings.ToLower(l.SecPurpose+" "+l.Purpose), "prefetch")
c := Classify(l.Method, l.Path, l.Status)
ev.Cat, ev.Soft, ev.Strong, ev.Weak = c.Cat, c.Soft, c.Strong, c.Weak
return ev, nil
+20
View File
@@ -31,3 +31,23 @@ func TestTraefikSecFetchFraming(t *testing.T) {
}
}
}
func TestTraefikFetchDestAndPrefetch(t *testing.T) {
base := `{"ClientHost":"8.8.8.8","RequestHost":"a.example","RequestMethod":"GET","RequestPath":"/","DownstreamStatus":200,"StartUTC":"2026-11-14T10:00:00Z"`
for _, tc := range []struct {
extra string
dest string
prefetch bool
}{
{``, "", false},
{`,"request_Sec-Fetch-Dest":"Document"`, "document", false},
{`,"request_Sec-Fetch-Dest":"empty"`, "empty", false},
{`,"request_Sec-Purpose":"prefetch;prerender"`, "", true},
{`,"request_Purpose":"prefetch"`, "", true},
} {
ev, err := ParseTraefik([]byte(base + tc.extra + `}`))
if err != nil || ev.FetchDest != tc.dest || ev.Prefetch != tc.prefetch {
t.Errorf("%s: dest=%q prefetch=%v err=%v", tc.extra, ev.FetchDest, ev.Prefetch, err)
}
}
}
+514
View File
@@ -0,0 +1,514 @@
package egress
import (
"fmt"
"math/rand"
"net/netip"
"os"
"path/filepath"
"sort"
"testing"
"time"
)
var t0 = time.Date(2026, 11, 14, 0, 0, 0, 0, time.UTC)
func ip(s string) netip.Addr { return netip.MustParseAddr(s) }
func mk(t time.Time, src, dst, proto string, dport uint16) Event {
return Event{Time: t, Src: ip(src), Dst: ip(dst), Proto: proto, SPort: 40000, DPort: dport, In: "br-1", Out: "enp0s6"}
}
func newEng(t *testing.T, c Config) *Engine {
t.Helper()
if c.Now == nil {
c.Now = func() time.Time { return t0.Add(30 * 24 * time.Hour) }
}
e, err := New(c)
if err != nil {
t.Fatal(err)
}
return e
}
func kinds(r Report, kind string) []Finding {
var o []Finding
for _, f := range r.Findings {
if f.Kind == kind {
o = append(o, f)
}
}
return o
}
func rep(e *Engine) Report { return e.Report(t0.Unix()-86400, t0.Add(14*24*time.Hour).Unix()) }
func TestParse(t *testing.T) {
now := time.Date(2026, 11, 14, 23, 0, 0, 0, time.UTC)
v4 := `2026-11-14T22:01:02.123456+00:00 oracle kernel: [123.4] URUTAU-EGRESS: IN=br-1a2b OUT=enp0s6 MAC=aa SRC=10.0.3.5 DST=93.184.216.34 LEN=60 TOS=0x00 PREC=0x00 TTL=63 ID=1 DF PROTO=TCP SPT=40000 DPT=443 WINDOW=64240 RES=0x00 SYN URGP=0`
ev, err := ParseLine([]byte(v4), now)
if err != nil || ev.Proto != "tcp" || ev.DPort != 443 || ev.SPort != 40000 || ev.Dst.String() != "93.184.216.34" || ev.Host || ev.Time.Hour() != 22 || ev.In != "br-1a2b" {
t.Fatalf("v4: %+v %v", ev, err)
}
v6 := `2026-11-14T22:01:02+00:00 oracle kernel: URUTAU-EGRESS: IN=br-1 OUT=enp0s6 SRC=fd00::5 DST=2606:4700:4700::1111 LEN=80 TC=0 HOPLIMIT=63 FLOWLBL=0 PROTO=UDP SPT=5353 DPT=53 LEN=40`
ev, err = ParseLine([]byte(v6), now)
if err != nil || ev.Proto != "udp" || ev.DPort != 53 || !ev.Dst.Is6() {
t.Fatalf("v6: %+v %v", ev, err)
}
ic := `Nov 14 22:01:02 oracle kernel: [1.0] URUTAU-EGRESS: IN=br-1 OUT=enp0s6 SRC=10.0.3.5 DST=1.1.1.1 LEN=84 PROTO=ICMP TYPE=8 CODE=0 ID=1`
ev, err = ParseLine([]byte(ic), now)
if err != nil || ev.Proto != "icmp" || ev.DPort != 0 || ev.Time.Year() != 2026 || ev.Time.Month() != 11 {
t.Fatalf("icmp: %+v %v", ev, err)
}
ic6 := `Nov 4 22:01:02 oracle kernel: URUTAU-EGRESS: IN=br-1 OUT=x SRC=fd00::5 DST=fd00::6 PROTO=ICMPv6 TYPE=128 CODE=0`
if ev, err = ParseLine([]byte(ic6), now); err != nil || ev.Proto != "icmp" || ev.Time.Day() != 4 {
t.Fatalf("icmp6: %+v %v", ev, err)
}
host := `2026-11-14T22:01:02+00:00 oracle kernel: URUTAU-EGRESS: IN= OUT=enp0s6 SRC=10.0.0.2 DST=8.8.8.8 PROTO=TCP SPT=1 DPT=443 SYN`
if ev, err = ParseLine([]byte(host), now); err != nil || !ev.Host || ev.In != "" {
t.Fatalf("host: %+v %v", ev, err)
}
// December line read in January belongs to the previous year
dec := `Dec 31 23:59:00 h kernel: URUTAU-EGRESS: IN=a OUT=b SRC=1.2.3.4 DST=5.6.7.8 PROTO=TCP DPT=1`
if ev, err = ParseLine([]byte(dec), time.Date(2027, 1, 1, 0, 5, 0, 0, time.UTC)); err != nil || ev.Time.Year() != 2026 {
t.Fatalf("year: %+v %v", ev, err)
}
for _, bad := range []string{"", "garbage", "URUTAU-EGRESS: IN=a OUT=b SRC=nope DST=1.1.1.1 PROTO=TCP", "URUTAU-EGRESS: IN=a SRC=1.1.1.1 DST=2.2.2.2", "\x00\xff URUTAU-EGRESS: ===", "sshd: Accepted publickey"} {
if _, err := ParseLine([]byte(bad), now); err == nil {
t.Fatalf("expected error for %q", bad)
}
}
e := newEng(t, Config{})
e.Ingest([]byte("garbage"))
e.Ingest([]byte(v4))
if e.malformed.Load() != 1 || e.lines.Load() != 1 {
t.Fatalf("counters %d %d", e.malformed.Load(), e.lines.Load())
}
}
func TestWorkloadsAndContainers(t *testing.T) {
e := newEng(t, Config{Workloads: "ciberlab=name:jhxint9g9uz91:scanner;mail=10.0.7.0/24,10.0.8.4/32:mail;lab=10.0.5.0/24"})
e.SetContainers(map[netip.Addr]string{ip("172.18.0.4"): "jhxint9g9uz91-20260101123456", ip("172.18.0.9"): "runner-q620o15zg7-1700000000000"})
cases := []struct {
ev Event
name, role string
}{
{mk(t0, "172.18.0.4", "1.1.1.1", "tcp", 1), "ciberlab", RoleScanner},
{mk(t0, "172.18.0.9", "1.1.1.1", "tcp", 1), "runner-q620o15zg7", RoleDefault},
{mk(t0, "10.0.8.4", "1.1.1.1", "tcp", 1), "mail", RoleMail},
{mk(t0, "10.0.5.77", "1.1.1.1", "tcp", 1), "lab", RoleDefault},
{mk(t0, "10.0.9.9", "1.1.1.1", "tcp", 1), "container 10.0.9.9", RoleDefault},
{Event{Time: t0, Src: ip("10.0.0.2"), Dst: ip("1.1.1.1"), Proto: "tcp", Host: true}, "host", RoleDefault},
}
for _, c := range cases {
if n, r := e.resolve(c.ev); n != c.name || r != c.role {
t.Errorf("%v: got %s/%s want %s/%s", c.ev.Src, n, r, c.name, c.role)
}
}
// IP changes: the map in force at Ingest wins
e.SetContainers(map[netip.Addr]string{ip("172.18.0.5"): "jhxint9g9uz91-20260102000000"})
if n, _ := e.resolve(mk(t0, "172.18.0.5", "1.1.1.1", "tcp", 1)); n != "ciberlab" {
t.Errorf("remap: %s", n)
}
for _, bad := range []string{"x", "a=", "a=notip:scanner", "a=name:bad name"} {
if _, err := ParseWorkloads(bad); err == nil {
t.Errorf("expected error for %q", bad)
}
}
// containers.map file: invalid lines skipped, reload on mtime change
dir := t.TempDir()
p := filepath.Join(dir, "containers.map")
os.WriteFile(p, []byte("172.18.0.4 jhxint9g9uz91-1700000000\nbad line here\n999.1.1.1 x\nfd00::7 six-node\n1.2.3.4 bad/name\n"), 0o644)
m, err := LoadContainers(p)
if err != nil || len(m) != 2 || m[ip("fd00::7")] != "six-node" {
t.Fatalf("map: %v %v", m, err)
}
clock := t0
e2 := newEng(t, Config{Containers: p, Workloads: "c=name:jhxint9g9uz91:scanner", Now: func() time.Time { return clock }})
e2.IngestEvent(mk(t0, "172.18.0.4", "5.5.5.5", "tcp", 443))
if _, ok := e2.ws["c"]; !ok {
t.Fatalf("map file not applied: %v", e2.ws)
}
os.WriteFile(p, []byte("172.18.0.4 other-1700000000\n"), 0o644)
os.Chtimes(p, clock.Add(time.Hour), clock.Add(time.Hour))
clock = clock.Add(time.Minute)
e2.IngestEvent(mk(t0.Add(time.Minute), "172.18.0.4", "5.5.5.5", "tcp", 443))
if _, ok := e2.ws["other"]; !ok {
t.Fatalf("map file not reloaded: %v", e2.ws)
}
}
func feedBeacon(e *Engine, src, dst string, dport uint16, start time.Time, n int, step time.Duration, jitter float64, rnd *rand.Rand) {
t := start
for i := 0; i < n; i++ {
pr := "tcp"
if dport == 123 {
pr = "udp"
}
e.IngestEvent(mk(t, src, dst, pr, dport))
j := 1 + (rnd.Float64()*2-1)*jitter
t = t.Add(time.Duration(float64(step) * j))
}
}
func TestBeaconPositive(t *testing.T) {
bad := func(a netip.Addr) (bool, string) { return a == ip("198.51.100.99"), "known attacker" }
e := newEng(t, Config{BadDst: bad})
rnd := rand.New(rand.NewSource(1))
feedBeacon(e, "10.0.3.5", "203.0.113.7", 443, t0, 50, 60*time.Second, 0.05, rnd)
feedBeacon(e, "10.0.3.5", "198.51.100.99", 8443, t0, 50, 60*time.Second, 0.05, rnd)
r := rep(e)
var got, hi *Finding
for i, f := range kinds(r, "beacon") {
if f.Dst == "203.0.113.7" {
got = &kinds(r, "beacon")[i]
}
if f.Dst == "198.51.100.99" {
hi = &kinds(r, "beacon")[i]
}
}
if got == nil || got.Severity != "medium" || got.IntervalS < 55 || got.IntervalS > 65 || got.Jitter > 0.1 || got.Count < 40 || got.Last <= got.First {
t.Fatalf("beacon: %+v", got)
}
if hi == nil || hi.Severity != "high" {
t.Fatalf("attacker beacon: %+v", hi)
}
}
func TestBeaconNegatives(t *testing.T) {
e := newEng(t, Config{Workloads: "sc=10.0.5.0/24:scanner", Allow: []netip.Prefix{netip.MustParsePrefix("192.0.2.0/24")}})
rnd := rand.New(rand.NewSource(2))
// random intervals
tt := t0
for i := 0; i < 60; i++ {
e.IngestEvent(mk(tt, "10.0.3.5", "203.0.113.8", "tcp", 443))
tt = tt.Add(time.Duration(5+rnd.Intn(600)) * time.Second)
}
// NTP, allowed dst, allowed resolver
feedBeacon(e, "10.0.3.5", "203.0.113.9", 123, t0, 50, 128*time.Second, 0, rnd)
feedBeacon(e, "10.0.3.5", "192.0.2.4", 443, t0, 50, 60*time.Second, 0, rnd)
for i := 0; i < 50; i++ {
ev := mk(t0.Add(time.Duration(i)*time.Minute), "10.0.3.5", "1.1.1.1", "udp", 53)
e.IngestEvent(ev)
}
// daily scan: 8 days, 60 targets each, scanner role; and hourly scan
for d := 0; d < 8; d++ {
for i := 0; i < 60; i++ {
e.IngestEvent(mk(t0.Add(time.Duration(d)*24*time.Hour+time.Duration(i)*time.Second), "10.0.5.2", fmt.Sprintf("203.0.113.%d", 100+i), "tcp", 22))
}
}
for h := 0; h < 12; h++ {
for i := 0; i < 60; i++ {
e.IngestEvent(mk(t0.Add(10*24*time.Hour+time.Duration(h)*time.Hour+time.Duration(i)*time.Second), "10.0.5.2", fmt.Sprintf("198.18.0.%d", 1+i), "tcp", 22))
}
}
if f := kinds(rep(e), "beacon"); len(f) != 0 {
t.Fatalf("unexpected beacons: %+v", f)
}
if f := kinds(rep(e), "dns_bypass"); len(f) != 0 {
t.Fatalf("usual resolver flagged: %+v", f)
}
}
func fanOut(e *Engine, src string, start time.Time, n int, port uint16) {
fanOutNet(e, src, "198.18", start, n, port)
}
func fanOutNet(e *Engine, src, net string, start time.Time, n int, port uint16) {
for i := 0; i < n; i++ {
e.IngestEvent(mk(start.Add(time.Duration(i)*time.Second), src, fmt.Sprintf("%s.%d.%d", net, i/200, 1+i%200), "tcp", port))
}
}
func TestScannerSuppressedVsDefault(t *testing.T) {
bad := func(a netip.Addr) (bool, string) { return a == ip("198.18.0.5"), "attacker" }
e := newEng(t, Config{Workloads: "ciberlab=10.0.5.0/24:scanner", BadDst: bad})
fanOut(e, "10.0.5.2", t0, 300, 80)
fanOutNet(e, "10.0.9.9", "198.19", t0, 300, 80) // default workload
r := rep(e)
var sc, df WorkloadOut
for _, w := range r.Workloads {
switch w.Name {
case "ciberlab":
sc = w
case "container 10.0.9.9":
df = w
}
}
if sc.Suppressed < 240 || sc.Conns > 60 {
t.Fatalf("scanner not suppressed: %+v", sc)
}
if df.Suppressed != 0 || df.Conns != 300 {
t.Fatalf("default must not be suppressed: %+v", df)
}
scan := kinds(r, "scan")
if len(scan) != 1 || scan[0].Workload != "container 10.0.9.9" || scan[0].Severity != "high" {
t.Fatalf("scan findings: %+v", scan)
}
if len(r.Scanner.Bursts) != 1 {
t.Fatalf("bursts: %+v", r.Scanner.Bursts)
}
b := r.Scanner.Bursts[0]
if b.Workload != "ciberlab" || b.Targets < 240 || len(b.Nets) == 0 || b.Ports[0] != 80 || b.BadDstHit != 1 {
t.Fatalf("burst: %+v", b)
}
for _, f := range kinds(r, "bad_dst") {
if f.Workload == "ciberlab" {
t.Fatalf("bad_dst of scanner inside a burst must only be counted: %+v", f)
}
}
for _, d := range r.TopDst {
for _, w := range d.Workloads {
if w == "ciberlab" {
t.Fatalf("scanner burst flow in top_dst: %+v", d)
}
}
}
// the burst closes after 5 minutes of quiet and a later flow is normal
e.IngestEvent(mk(t0.Add(time.Hour), "10.0.5.2", "203.0.113.50", "tcp", 443))
r = rep(e)
if len(r.Scanner.Bursts) != 1 || r.Scanner.Bursts[0].End > t0.Add(10*time.Minute).Unix() {
t.Fatalf("burst end: %+v", r.Scanner.Bursts)
}
}
func TestScannerBeaconStillDetectedDuringBurst(t *testing.T) {
e := newEng(t, Config{Workloads: "ciberlab=10.0.5.0/24:scanner"})
rnd := rand.New(rand.NewSource(3))
// beacon every 60 s for 60 min, scan from minute 10 for 150 s; ordered by time
var evs []Event
for i := 0; i < 60; i++ {
evs = append(evs, mk(t0.Add(time.Duration(i)*time.Minute+time.Duration(rnd.Intn(3))*time.Second), "10.0.5.2", "203.0.113.77", "tcp", 8443))
}
for i := 0; i < 150; i++ {
evs = append(evs, mk(t0.Add(10*time.Minute+10*time.Second+time.Duration(i)*time.Second), "10.0.5.2", fmt.Sprintf("198.18.0.%d", 1+i), "tcp", 443))
}
sort.SliceStable(evs, func(i, j int) bool { return evs[i].Time.Before(evs[j].Time) })
for _, ev := range evs {
e.IngestEvent(ev)
}
r := rep(e)
var found bool
for _, f := range kinds(r, "beacon") {
found = found || f.Dst == "203.0.113.77"
}
if !found {
t.Fatalf("beacon of the scanner lost: %+v", r.Findings)
}
if len(r.Scanner.Bursts) == 0 {
t.Fatal("expected a burst")
}
for _, w := range r.Workloads {
if w.Name == "ciberlab" && (w.Conns < 55 || w.Suppressed < 140) {
t.Fatalf("beacon flows must stay in normal accounting: %+v", w)
}
}
}
func TestSuspiciousPorts(t *testing.T) {
e := newEng(t, Config{Workloads: "mail=10.0.7.0/24:mail"})
at := func(i int) time.Time { return t0.Add(time.Duration(i) * time.Minute) }
e.IngestEvent(mk(at(0), "10.0.3.5", "203.0.113.1", "tcp", 25))
e.IngestEvent(mk(at(1), "10.0.7.5", "203.0.113.2", "tcp", 25)) // mail role: fine
e.IngestEvent(mk(at(2), "10.0.3.5", "203.0.113.3", "tcp", 6667))
e.IngestEvent(mk(at(3), "10.0.3.5", "203.0.113.4", "tcp", 3333))
e.IngestEvent(mk(at(4), "10.0.3.5", "203.0.113.5", "tcp", 9001))
e.IngestEvent(mk(at(5), "10.0.3.5", "203.0.113.6", "udp", 3333)) // udp: ignored
e.IngestEvent(mk(at(6), "10.0.3.5", "203.0.113.7", "udp", 853))
e.IngestEvent(mk(at(7), "10.0.3.5", "93.184.216.34", "udp", 53))
e.IngestEvent(mk(at(8), "10.0.3.5", "10.9.9.9", "udp", 53)) // private: not bypass
r := rep(e)
by := map[string]string{}
for _, f := range kinds(r, "port") {
by[f.Dst] = f.Severity
}
if len(by) != 4 || by["203.0.113.1"] != "medium" || by["203.0.113.4"] != "high" || by["203.0.113.2"] != "" {
t.Fatalf("ports: %v", by)
}
if d := kinds(r, "dns_bypass"); len(d) != 1 || d[0].Dst != "93.184.216.34" {
t.Fatalf("dns_bypass (DoT is tcp-only, 53 to unusual public): %+v", d)
}
// custom resolver list: Google no longer allowed
e2 := newEng(t, Config{Resolvers: "10.0.0.53"})
e2.IngestEvent(mk(t0, "10.0.3.5", "8.8.8.8", "udp", 53))
e2.IngestEvent(mk(t0, "10.0.3.5", "10.0.0.53", "udp", 53))
if d := kinds(rep(e2), "dns_bypass"); len(d) != 1 || d[0].Dst != "8.8.8.8" {
t.Fatalf("custom resolvers: %+v", d)
}
}
func TestBadDstAndNewGeo(t *testing.T) {
geo := func(s string) (string, string, string) {
if s == "203.0.113.50" {
return "RU", "AS1", "x"
}
return "BR", "AS2", "y"
}
bad := func(a netip.Addr) (bool, string) { return a == ip("203.0.113.9"), "Tor exit" }
e := newEng(t, Config{Geo: geo, BadDst: bad, Workloads: "sc=10.0.5.0/24:scanner"})
e.IngestEvent(mk(t0, "10.0.3.5", "203.0.113.1", "tcp", 443))
e.IngestEvent(mk(t0.Add(25*time.Hour), "10.0.3.5", "203.0.113.2", "tcp", 443)) // known country
e.IngestEvent(mk(t0.Add(26*time.Hour), "10.0.3.5", "203.0.113.50", "tcp", 443))
e.IngestEvent(mk(t0.Add(27*time.Hour), "10.0.3.5", "203.0.113.9", "tcp", 443))
e.IngestEvent(mk(t0, "10.0.5.2", "203.0.113.1", "tcp", 443))
e.IngestEvent(mk(t0.Add(26*time.Hour), "10.0.5.2", "203.0.113.50", "tcp", 443)) // scanner ignored
r := rep(e)
g := kinds(r, "new_geo")
if len(g) != 1 || g[0].Workload != "container 10.0.3.5" || g[0].Dst != "203.0.113.50" || g[0].Severity != "low" {
t.Fatalf("new_geo: %+v", g)
}
if b := kinds(r, "bad_dst"); len(b) != 1 || b[0].Severity != "high" || b[0].Detail != "Tor exit" {
t.Fatalf("bad_dst: %+v", b)
}
if len(r.TopDst) == 0 || r.TopDst[0].CC == "" {
t.Fatalf("top_dst not enriched: %+v", r.TopDst)
}
}
func TestMemoryLimits(t *testing.T) {
e := newEng(t, Config{})
// 60k distinct pairs, 15 s apart (never a fan-out) and spam findings
for i := 0; i < 60000; i++ {
dst := fmt.Sprintf("%d.%d.%d.%d", 20+i/65536, (i/256)%256, i%256, 1)
port := uint16(443)
if i < 3000 {
port = 25
}
e.IngestEvent(mk(t0.Add(time.Duration(i)*15*time.Second), "10.0.3.5", dst, "tcp", port))
}
if e.pairs.len() > MaxPairs || e.dsts.len() > MaxDsts || len(e.findings) > MaxFindings {
t.Fatalf("limits: %d %d %d", e.pairs.len(), e.dsts.len(), len(e.findings))
}
if len(e.findings) != MaxFindings {
t.Fatalf("findings should be capped at the limit, got %d", len(e.findings))
}
w := e.ws["container 10.0.3.5"]
n := 0
for i := range w.hours {
if w.hours[i].hour != 0 {
n++
}
if len(w.hours[i].dsts) > setCap {
t.Fatal("hour set not capped")
}
}
if n > HourBuckets {
t.Fatal("buckets")
}
// dedupe: same key updates count
e2 := newEng(t, Config{})
for i := 0; i < 5; i++ {
e2.IngestEvent(mk(t0.Add(time.Duration(i)*time.Minute), "10.0.3.5", "203.0.113.1", "tcp", 6667))
}
if f := kinds(rep(e2), "port"); len(f) != 1 || f[0].Count != 5 {
t.Fatalf("dedupe: %+v", f)
}
}
func TestReportMergeSanitize(t *testing.T) {
e := newEng(t, Config{})
e.IngestEvent(mk(t0, "10.0.3.5", "203.0.113.1", "tcp", 6667))
local := e.Report(t0.Unix()-3600, t0.Unix()+3600)
peer := e.Report(t0.Unix()-7200, t0.Unix()+3600)
peer.Sanitize("oracle")
local.Merge(peer, "oracle")
if len(local.Findings) != 2 || local.Findings[1].Host != "oracle" && local.Findings[0].Host != "oracle" {
t.Fatalf("merge: %+v", local.Findings)
}
if _, ok := local.Timeline.Series["oracle/container 10.0.3.5"]; !ok {
t.Fatalf("series: %v", local.Timeline.Series)
}
}
func TestNameMatchExactAndPrefix(t *testing.T) {
e := newEng(t, Config{Workloads: "a=name:web:default;b=name:api*:default;c=name:pay:default"})
e.SetContainers(map[netip.Addr]string{ip("172.18.0.1"): "web-1700000000000", ip("172.18.0.2"): "webshell-1700000000000",
ip("172.18.0.3"): "apigw-17", ip("172.18.0.4"): "pay", ip("172.18.0.5"): "payroll"})
for src, want := range map[string]string{"172.18.0.1": "a", "172.18.0.2": "webshell", "172.18.0.3": "b", "172.18.0.4": "c", "172.18.0.5": "payroll"} {
if n, _ := e.resolve(mk(t0, src, "1.1.1.1", "tcp", 1)); n != want {
t.Errorf("%s: %s want %s", src, n, want)
}
}
}
func TestHostWorkloadRole(t *testing.T) {
e := newEng(t, Config{Workloads: "host=host:mail"})
n, r := e.resolve(Event{Time: t0, Src: ip("10.0.0.2"), Dst: ip("1.1.1.1"), Proto: "tcp", Host: true})
if n != "host" || r != RoleMail {
t.Fatalf("%s/%s", n, r)
}
e.IngestEvent(Event{Time: t0, Src: ip("10.0.0.2"), Dst: ip("203.0.113.5"), Proto: "tcp", DPort: 25, Host: true})
if f := kinds(rep(e), "port"); len(f) != 0 {
t.Fatalf("mail host flagged: %+v", f)
}
}
func TestResolvConfAllowed(t *testing.T) {
p := filepath.Join(t.TempDir(), "resolv.conf")
os.WriteFile(p, []byte("# x\nnameserver 203.0.113.53\nnameserver fe80::1%eth0\nsearch x\n"), 0o644)
e := newEng(t, Config{ResolvConf: []string{p, "/nonexistent"}})
for i := 0; i < 3; i++ {
e.IngestEvent(mk(t0.Add(time.Duration(i)*time.Second), "10.0.3.5", "203.0.113.53", "udp", 53))
}
if f := kinds(rep(e), "dns_bypass"); len(f) != 0 {
t.Fatalf("resolv.conf nameserver flagged: %+v", f)
}
e.IngestEvent(mk(t0, "10.0.3.5", "203.0.113.54", "udp", 53))
if f := kinds(rep(e), "dns_bypass"); len(f) != 1 {
t.Fatalf("other resolver not flagged: %+v", f)
}
}
func TestAllowedPollerNoBeacon(t *testing.T) {
e := newEng(t, Config{Allow: []netip.Prefix{netip.MustParsePrefix("203.0.113.0/24")}})
feedBeacon(e, "10.0.3.5", "203.0.113.7", 443, t0, 60, 60*time.Second, 0, rand.New(rand.NewSource(1)))
if f := kinds(rep(e), "beacon"); len(f) != 0 {
t.Fatalf("%+v", f)
}
}
func TestNTPExemption(t *testing.T) {
bad := func(a netip.Addr) (bool, string) { return a == ip("203.0.113.99"), "known attacker" }
e := newEng(t, Config{BadDst: bad})
rnd := rand.New(rand.NewSource(1))
feedBeacon(e, "10.0.3.5", "203.0.113.10", 123, t0, 50, 128*time.Second, 0, rnd) // normal poll: exempt
feedBeacon(e, "10.0.3.5", "203.0.113.11", 123, t0, 50, 60*time.Second, 0, rnd) // fast NTP: not exempt
feedBeacon(e, "10.0.3.5", "203.0.113.99", 123, t0, 50, 128*time.Second, 0, rnd) // bad dst: never exempt
got := map[string]bool{}
for _, f := range kinds(rep(e), "beacon") {
got[f.Dst] = true
}
if got["203.0.113.10"] || !got["203.0.113.11"] || !got["203.0.113.99"] {
t.Fatalf("%v", got)
}
}
func TestBeaconDuringContinuousScan(t *testing.T) {
e := newEng(t, Config{Workloads: "ciberlab=10.0.5.0/24:scanner"})
// a light scan every 4 min (each opens or keeps the burst alive) for 2 h; the C2
// is contacted every 60 s starting 12 min AFTER the first burst opened
var evs []Event
for k := 0; k < 30; k++ {
for i := 0; i < 60; i++ {
evs = append(evs, mk(t0.Add(time.Duration(k)*4*time.Minute+time.Duration(i)*time.Second), "10.0.5.2",
fmt.Sprintf("198.18.%d.%d", k, 1+i), "tcp", 443))
}
}
for i := 0; i < 100; i++ {
evs = append(evs, mk(t0.Add(12*time.Minute+time.Duration(i)*time.Minute+30*time.Second), "10.0.5.2", "203.0.113.77", "tcp", 8443))
}
sort.SliceStable(evs, func(i, j int) bool { return evs[i].Time.Before(evs[j].Time) })
for _, ev := range evs {
e.IngestEvent(ev)
}
var found bool
for _, f := range kinds(rep(e), "beacon") {
found = found || f.Dst == "203.0.113.77"
}
if !found {
t.Fatalf("C2 invisible during the continuous scan: %+v", rep(e).Findings)
}
if e.fanSeen.len() > maxFanSeen {
t.Fatal("fanSeen unbounded")
}
}
+869
View File
@@ -0,0 +1,869 @@
package egress
import (
"container/list"
"fmt"
"hash/fnv"
"math"
"net/netip"
"os"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
)
// Limits and thresholds.
const (
MaxPairs = 50000
MaxDsts = 50000
MaxFindings = 2000
HourBuckets = 720 // 30 days
maxWorkloads = 256
maxClosedBurst = 200
maxFanSeen = 20000 // (workload,dst,port,proto) tuples seen only as fan-out
fanPromoteN = 3 // hits within fanPromoteWin that turn a fan-out flow into a pair
fanPromoteWin = 3600
fanDsts = 50
fanPorts = 100
fanWindow = 600 // seconds
burstQuiet = 300 // a burst closes after 5 min without fan-out
maxWin = 8192
ringSize = 64
beaconMinN = 8
beaconSpan = 1800
beaconMinIv = 10
beaconMaxIv = 6 * 3600
beaconCV = 0.25
beaconMAD = 0.20
setCap = 64
ntpMinIv = 64
)
// Config of the engine.
type Config struct {
// Workloads: "ciberlab=10.0.5.0/24:scanner;mail=name:protocols:mail".
Workloads string
// Resolvers lists the allowed DNS resolvers (comma separated IPs). Rule:
// DNS (53 tcp/udp) or DoT (853) from a non-resolver workload to a public
// address that is not an allowed resolver is "dns_bypass". When the list is
// empty the allowed set is the usual public resolvers (Cloudflare, Google,
// Quad9, OpenDNS), so only DoT and port 53 to unusual public IPs alert.
Resolvers string
// Allow lists destinations that never produce a finding (peers, own servers).
Allow []netip.Prefix
// Containers is the path of the containers.map file (optional); it is
// reloaded when its mtime changes.
Containers string
// Geo enriches a destination (cc, asn, org); BadDst says whether a
// destination is a known attacker or Tor exit (and why).
Geo func(ip string) (cc, asn, org string)
BadDst func(netip.Addr) (bool, string)
Now func() time.Time
// Learn is the per-workload learning time before new_geo (default 24h).
Learn time.Duration
// ResolvConf lists resolv.conf files whose nameservers are allowed resolvers
// (default: /etc/resolv.conf and /logs/host/resolv.conf, both optional).
ResolvConf []string
}
var usualResolvers = []string{"1.1.1.1", "1.0.0.1", "8.8.8.8", "8.8.4.4", "9.9.9.9", "149.112.112.112",
"208.67.222.222", "208.67.220.220", "2606:4700:4700::1111", "2606:4700:4700::1001",
"2001:4860:4860::8888", "2001:4860:4860::8844", "2620:fe::fe"}
type lru[K comparable, V any] struct {
cap int
l *list.List
m map[K]*list.Element
}
type lent[K comparable, V any] struct {
k K
v V
}
func newLRU[K comparable, V any](n int) *lru[K, V] {
return &lru[K, V]{cap: n, l: list.New(), m: map[K]*list.Element{}}
}
func (c *lru[K, V]) get(k K) (v V, ok bool) {
el, ok := c.m[k]
if !ok {
return v, false
}
c.l.MoveToFront(el)
return el.Value.(*lent[K, V]).v, true
}
func (c *lru[K, V]) put(k K, v V) {
if el, ok := c.m[k]; ok {
el.Value.(*lent[K, V]).v = v
c.l.MoveToFront(el)
return
}
c.m[k] = c.l.PushFront(&lent[K, V]{k, v})
if c.l.Len() > c.cap {
el := c.l.Back()
delete(c.m, el.Value.(*lent[K, V]).k)
c.l.Remove(el)
}
}
func (c *lru[K, V]) len() int { return c.l.Len() }
type pairKey struct {
wl string
dst netip.Addr
dport uint16
proto string
}
type pairState struct {
ts [ringSize]uint32
n int
total uint32
fan, nonFan uint32
first, last int64
flagged bool
fkey string
interval, cv float64
}
func (p *pairState) add(t int64, fan bool) {
if p.total == 0 {
p.first = t
}
p.total++
if fan {
p.fan++
} else {
p.nonFan++
}
if p.n > 0 && t-int64(p.ts[p.n-1]) < 2 {
p.last = t
return // retries of the same second are one beat
}
if p.n == ringSize {
copy(p.ts[:], p.ts[1:])
p.n--
}
p.ts[p.n] = uint32(t)
p.n++
p.last = t
}
type dayN struct {
day int32
n uint32
}
type dstStat struct {
ip netip.Addr
cc, asn, og string
days []dayN
wls []string
ports []uint16
}
type hbucket struct {
hour int64
conns, supp uint32
dsts, ports []uint32
}
type burstState struct {
start, lastFan int64
conns, badHits uint32
targets map[netip.Addr]struct{}
nets map[netip.Prefix]uint32
ports map[uint16]uint32
}
type wstate struct {
name, role string
first int64
hours [HourBuckets]hbucket
win map[netip.Addr]int64
wports map[uint16]int64
lastPrune int64
burst *burstState
geo map[string]struct{}
// recent are the normal flows of the fan-out window: when a burst opens
// they are re-read as part of it (the first 49 probes of a scan).
recent []winFlow
}
type winFlow struct {
pk pairKey
t int64
badKey string // bad_dst finding this flow raised, if any
}
// Engine analyses egress events. Safe for concurrent use.
type Engine struct {
mu sync.Mutex
cfg Config
wls []workloadDef
resolvers map[netip.Addr]bool
now func() time.Time
containers map[netip.Addr]string
mapMod time.Time
mapCheck time.Time
ws map[string]*wstate
pairs *lru[pairKey, *pairState]
dsts *lru[netip.Addr, *dstStat]
fanSeen *lru[pairKey, *fanRec]
findings map[string]*Finding
closed []BurstOut
maxT int64
lines, malformed atomic.Uint64
last atomic.Int64
stateFn atomic.Pointer[func() string]
}
// New builds an engine.
func New(c Config) (*Engine, error) {
wls, err := ParseWorkloads(c.Workloads)
if err != nil {
return nil, err
}
e := &Engine{cfg: c, wls: wls, now: c.Now, resolvers: map[netip.Addr]bool{}, containers: map[netip.Addr]string{},
ws: map[string]*wstate{}, pairs: newLRU[pairKey, *pairState](MaxPairs), dsts: newLRU[netip.Addr, *dstStat](MaxDsts),
findings: map[string]*Finding{}, fanSeen: newLRU[pairKey, *fanRec](maxFanSeen)}
if e.now == nil {
e.now = time.Now
}
if e.cfg.Learn <= 0 {
e.cfg.Learn = 24 * time.Hour
}
list := strings.Split(c.Resolvers, ",")
if strings.TrimSpace(c.Resolvers) == "" {
list = usualResolvers
}
for _, s := range list {
if s = strings.TrimSpace(s); s == "" {
continue
}
a, err := netip.ParseAddr(s)
if err != nil {
return nil, fmt.Errorf("resolver %q: %w", s, err)
}
e.resolvers[a.Unmap()] = true
}
rc := c.ResolvConf
if rc == nil {
rc = []string{"/etc/resolv.conf", "/logs/host/resolv.conf"}
}
for _, p := range rc {
for _, a := range readNameservers(p) {
e.resolvers[a] = true
}
}
return e, nil
}
// readNameservers returns the nameserver addresses of a resolv.conf (missing file: none).
func readNameservers(path string) []netip.Addr {
b, err := os.ReadFile(path)
if err != nil {
return nil
}
var out []netip.Addr
for _, ln := range strings.Split(string(b), "\n") {
f := strings.Fields(ln)
if len(f) >= 2 && f[0] == "nameserver" {
if a, err := netip.ParseAddr(f[1]); err == nil {
out = append(out, a.WithZone("").Unmap())
}
}
if len(out) >= 16 {
break
}
}
return out
}
// fanRec accumulates the sightings of a flow that was only ever seen as fan-out.
type fanRec struct{ ts []int64 }
// fanPromote records one fan-out sighting; when the same flow shows up
// fanPromoteN times within the hour it is a real pair (a C2 contacted during a
// continuous scan), returned with its accumulated timestamps.
func (e *Engine) fanPromote(pk pairKey, t int64) *pairState {
r, ok := e.fanSeen.get(pk)
if !ok {
r = &fanRec{}
e.fanSeen.put(pk, r)
}
k := 0
for _, x := range r.ts {
if t-x <= fanPromoteWin {
r.ts[k] = x
k++
}
}
r.ts = r.ts[:k]
if n := len(r.ts); n == 0 || t-r.ts[n-1] >= 2 { // retries of the same second are one beat
r.ts = append(r.ts, t)
}
if len(r.ts) < fanPromoteN {
return nil
}
p := &pairState{}
for _, x := range r.ts[:len(r.ts)-1] {
p.add(x, false)
}
if el, ok := e.fanSeen.m[pk]; ok {
e.fanSeen.l.Remove(el)
delete(e.fanSeen.m, pk)
}
return p
}
// SetContainers replaces the address to container-name map (tests, wiring).
func (e *Engine) SetContainers(m map[netip.Addr]string) {
e.mu.Lock()
e.containers = m
e.mu.Unlock()
}
func (e *Engine) reloadMap() {
if e.cfg.Containers == "" {
return
}
n := e.now()
if n.Sub(e.mapCheck) < 5*time.Second {
return
}
e.mapCheck = n
fi, err := os.Stat(e.cfg.Containers)
if err != nil || fi.ModTime().Equal(e.mapMod) {
return
}
if m, err := LoadContainers(e.cfg.Containers); err == nil {
e.containers, e.mapMod = m, fi.ModTime()
}
}
// Ingest parses and analyses one log line.
func (e *Engine) Ingest(line []byte) {
ev, err := ParseLine(line, e.now())
if err != nil {
if len(line) > 0 {
e.malformed.Add(1)
}
return
}
e.lines.Add(1)
e.last.Store(e.now().Unix())
e.IngestEvent(ev)
}
// IngestEvent analyses one parsed event.
func (e *Engine) IngestEvent(ev Event) {
e.mu.Lock()
defer e.mu.Unlock()
e.ingest(ev)
}
func (e *Engine) allowed(a netip.Addr) bool {
for _, p := range e.cfg.Allow {
if p.Contains(a) {
return true
}
}
return false
}
func fanCounts(role string, ev Event) bool {
switch {
case role == RoleMail && (ev.DPort == 25 || ev.DPort == 465 || ev.DPort == 587):
return false // a mail server legitimately talks to many MX
case role == RoleResolver && ev.DPort == 53:
return false // a recursive resolver talks to many authoritative servers
}
return true
}
func (e *Engine) wstate(name, role string, t int64) *wstate {
if w, ok := e.ws[name]; ok {
return w
}
if len(e.ws) >= maxWorkloads {
name, role = "container other", RoleDefault
if w, ok := e.ws[name]; ok {
return w
}
}
w := &wstate{name: name, role: role, first: t, win: map[netip.Addr]int64{}, wports: map[uint16]int64{}, geo: map[string]struct{}{}}
e.ws[name] = w
return w
}
func h32(a netip.Addr) uint32 {
b := a.As16()
h := fnv.New32a()
h.Write(b[:])
return h.Sum32()
}
func addSet(s []uint32, v uint32) []uint32 {
for _, x := range s {
if x == v {
return s
}
}
if len(s) >= setCap {
return s
}
return append(s, v)
}
func (w *wstate) bucket(t int64) *hbucket {
h := t / 3600
b := &w.hours[h%HourBuckets]
if b.hour != h {
*b = hbucket{hour: h}
}
return b
}
func (e *Engine) ingest(ev Event) {
t := ev.Time.Unix()
if t <= 0 {
return
}
if t > e.maxT {
e.maxT = t
}
e.reloadMap()
name, role := e.resolve(ev)
ws := e.wstate(name, role, t)
role = ws.role
allowed := e.allowed(ev.Dst)
dport := ev.DPort
if ev.Proto == "icmp" {
dport = 0
}
counts := !allowed && fanCounts(role, ev)
if ws.burst != nil && t-ws.burst.lastFan > burstQuiet {
e.closeBurst(ws)
}
if counts && ws.burst == nil {
e.window(ws, ev.Dst, dport, t)
}
inBurst := counts && ws.burst != nil
pk := pairKey{ws.name, ev.Dst, dport, ev.Proto}
p, _ := e.pairs.get(pk)
fan := inBurst && (p == nil || p.nonFan < 3)
if p == nil && fan && !allowed {
if np := e.fanPromote(pk, t); np != nil {
p, fan = np, false
e.pairs.put(pk, p)
}
}
if p == nil && !fan && !allowed {
p = &pairState{}
e.pairs.put(pk, p) // fan-out flows create pairs only when repeated: a scan must not evict real ones
}
if p != nil {
p.add(t, fan)
}
scanner := role == RoleScanner
if fan {
e.burstFlow(ws, ev, dport, t, scanner)
if scanner {
ws.bucket(t).supp++
return
}
}
b := ws.bucket(t)
b.conns++
if counts && ws.burst == nil && len(ws.recent) < maxWin {
ws.recent = append(ws.recent, winFlow{pk: pk, t: t})
}
b.dsts = addSet(b.dsts, h32(ev.Dst))
b.ports = addSet(b.ports, uint32(dport))
ds := e.dstStat(ws.name, ev.Dst, dport, t)
if allowed {
return
}
e.checks(ws, ev, dport, t, ds, p, fan)
if n := len(ws.recent); n > 0 && ws.recent[n-1].t == t && ws.recent[n-1].pk == pk {
if f := e.findings[fmt.Sprintf("bad_dst|%s|%s|%d", ws.name, ev.Dst, dport)]; f != nil {
ws.recent[n-1].badKey = fmt.Sprintf("bad_dst|%s|%s|%d", ws.name, ev.Dst, dport)
}
}
}
// retro re-reads the flows seen before the burst opened as part of it.
func (e *Engine) retro(ws *wstate) {
cnt := map[pairKey]uint32{}
for _, f := range ws.recent {
cnt[f.pk]++
}
moved := map[pairKey]bool{}
for pk, n := range cnt {
// a pair established before the window, or hit 4+ times inside it (a probe is hit once or retried), stays normal
if p, ok := e.pairs.get(pk); ok && n < 4 && p.nonFan >= n && p.nonFan-n < 3 {
p.fan += n
p.nonFan -= n
moved[pk] = true
} else if !ok && n < 4 {
moved[pk] = true // evicted pair: still a probe
}
}
for _, f := range ws.recent {
if !moved[f.pk] {
continue
}
if ws.role != RoleScanner {
continue
}
b := &ws.hours[(f.t/3600)%HourBuckets]
if b.hour == f.t/3600 && b.conns > 0 {
b.conns--
b.supp++
}
if ds, ok := e.dsts.get(f.pk.dst); ok {
for i := range ds.days {
if ds.days[i].day == int32(f.t/86400) && ds.days[i].n > 0 {
ds.days[i].n--
}
}
}
if f.badKey != "" {
if fd := e.findings[f.badKey]; fd != nil {
if fd.Count--; fd.Count <= 0 {
delete(e.findings, f.badKey)
}
ws.burst.badHits++
}
}
}
ws.recent = ws.recent[:0]
}
func (e *Engine) window(ws *wstate, dst netip.Addr, dport uint16, t int64) {
if t-ws.lastPrune >= 10 {
for k, v := range ws.win {
if t-v > fanWindow {
delete(ws.win, k)
}
}
for k, v := range ws.wports {
if t-v > fanWindow {
delete(ws.wports, k)
}
}
ws.lastPrune = t
k := 0
for _, f := range ws.recent {
if t-f.t <= fanWindow {
ws.recent[k] = f
k++
}
}
ws.recent = ws.recent[:k]
}
if _, ok := ws.win[dst]; ok || len(ws.win) < maxWin {
ws.win[dst] = t
}
if dport != 0 {
ws.wports[dport] = t
}
if len(ws.win) >= fanDsts || len(ws.wports) >= fanPorts {
start := t
for _, v := range ws.win {
if v < start {
start = v
}
}
ws.burst = &burstState{start: start, lastFan: t, targets: map[netip.Addr]struct{}{},
nets: map[netip.Prefix]uint32{}, ports: map[uint16]uint32{}}
clear(ws.win)
clear(ws.wports)
e.retro(ws)
}
}
func (e *Engine) burstFlow(ws *wstate, ev Event, dport uint16, t int64, scanner bool) {
bs := ws.burst
bs.lastFan = t
bs.conns++
if len(bs.targets) < 50000 {
bs.targets[ev.Dst] = struct{}{}
}
bits := 24
if ev.Dst.Is6() {
bits = 48
}
np, _ := ev.Dst.Prefix(bits)
if _, ok := bs.nets[np]; ok || len(bs.nets) < 512 {
bs.nets[np]++
}
if dport != 0 {
if _, ok := bs.ports[dport]; ok || len(bs.ports) < 1024 {
bs.ports[dport]++
}
}
if scanner {
if e.cfg.BadDst != nil {
if bad, _ := e.cfg.BadDst(ev.Dst); bad {
bs.badHits++
}
}
return
}
if bs.conns%32 == 1 {
e.addFinding("scan", "high", ws.name, "", 0, "", t, 0, 0, bs.detail(), 1)
} else {
e.addFinding("scan", "high", ws.name, "", 0, "", t, 0, 0, "", 1)
}
}
func (bs *burstState) detail() string {
return fmt.Sprintf("fan-out: %d targets, %d ports, %d connections", len(bs.targets), len(bs.ports), bs.conns)
}
func (e *Engine) closeBurst(ws *wstate) {
bs := ws.burst
ws.burst = nil
ws.recent = ws.recent[:0]
clear(ws.win)
clear(ws.wports)
if ws.role != RoleScanner {
e.addFinding("scan", "high", ws.name, "", 0, "", bs.lastFan, 0, 0, bs.detail(), 0)
return
}
e.closed = append(e.closed, bs.out(ws.name, bs.lastFan))
if len(e.closed) > maxClosedBurst {
e.closed = e.closed[len(e.closed)-maxClosedBurst:]
}
}
func (e *Engine) dstStat(wl string, dst netip.Addr, dport uint16, t int64) *dstStat {
ds, ok := e.dsts.get(dst)
if !ok {
ds = &dstStat{ip: dst}
if e.cfg.Geo != nil && isGlobal(dst) {
ds.cc, ds.asn, ds.og = e.cfg.Geo(dst.String())
}
e.dsts.put(dst, ds)
}
day := int32(t / 86400)
if n := len(ds.days); n > 0 && ds.days[n-1].day == day {
ds.days[n-1].n++
} else if n == 0 || ds.days[n-1].day < day {
ds.days = append(ds.days, dayN{day, 1})
if len(ds.days) > 30 {
ds.days = ds.days[1:]
}
}
has := false
for _, w := range ds.wls {
has = has || w == wl
}
if !has && len(ds.wls) < 8 {
ds.wls = append(ds.wls, wl)
}
hp := false
for _, p := range ds.ports {
hp = hp || p == dport
}
if !hp && len(ds.ports) < 8 {
ds.ports = append(ds.ports, dport)
}
return ds
}
func isGlobal(a netip.Addr) bool {
return a.IsValid() && !a.IsPrivate() && !a.IsLoopback() && !a.IsLinkLocalUnicast() && !a.IsMulticast() &&
!a.IsUnspecified() && !a.IsLinkLocalMulticast() && !isCGNAT(a)
}
var cgnat = netip.MustParsePrefix("100.64.0.0/10")
func isCGNAT(a netip.Addr) bool { return cgnat.Contains(a) }
func (e *Engine) isResolver(a netip.Addr) bool { return e.resolvers[a] }
func (e *Engine) checks(ws *wstate, ev Event, dport uint16, t int64, ds *dstStat, p *pairState, fan bool) {
dst := ev.Dst.String()
if e.cfg.BadDst != nil {
if bad, why := e.cfg.BadDst(ev.Dst); bad {
e.addFinding("bad_dst", "high", ws.name, dst, dport, ev.Proto, t, 0, 0, why, 1)
}
}
if ev.Proto == "tcp" {
if sev, why := suspiciousPort(dport, ws.role); why != "" {
e.addFinding("port", sev, ws.name, dst, dport, ev.Proto, t, 0, 0, why, 1)
}
}
dns := dport == 53 && (ev.Proto == "udp" || ev.Proto == "tcp") || dport == 853 && ev.Proto == "tcp"
if dns && ws.role != RoleResolver && isGlobal(ev.Dst) && !e.isResolver(ev.Dst) {
e.addFinding("dns_bypass", "medium", ws.name, dst, dport, ev.Proto, t, 0, 0, "DNS to a resolver that is not allowed", 1)
}
if p != nil {
e.beacon(ws, ev, dport, dns, p, ds)
}
if ws.role != RoleScanner && !fan && ds.cc != "" && isGlobal(ev.Dst) {
if _, seen := ws.geo[ds.cc]; !seen {
ws.geo[ds.cc] = struct{}{}
if t-ws.first >= int64(e.cfg.Learn/time.Second) {
e.addFinding("new_geo", "low", ws.name, dst, dport, ev.Proto, t, 0, 0, "first contact with country "+ds.cc+" "+ds.asn, 1)
}
} else if len(ws.geo) > 300 {
ws.geo = map[string]struct{}{}
}
}
}
func suspiciousPort(port uint16, role string) (sev, why string) {
switch port {
case 25, 465, 587:
if role != RoleMail {
return "medium", "SMTP from a non-mail workload (spam)"
}
case 6667, 6697:
return "medium", "IRC (classic botnet C2)"
case 3333, 14444, 45700:
return "high", "mining pool (stratum)"
case 4444, 5555, 7777:
return "medium", "probable mining pool (stratum) or reverse shell"
case 9001, 9030:
return "medium", "Tor ORPort"
}
return "", ""
}
func (e *Engine) beacon(ws *wstate, ev Event, dport uint16, dns bool, p *pairState, ds *dstStat) {
if p.flagged {
e.addFinding("beacon", "", ws.name, ev.Dst.String(), dport, ev.Proto, p.last, p.interval, p.cv, "", 1)
return
}
ntp := ev.Proto == "udp" && dport == 123
switch {
case dns && e.isResolver(ev.Dst):
return
case ws.role == RoleResolver && dport == 53:
return
case p.n < beaconMinN || int64(p.ts[p.n-1])-int64(p.ts[0]) < beaconSpan:
return
case p.fan > p.nonFan:
return // mostly a fan-out target (a daily scan target is not a beacon)
case p.total%4 != 0:
return // evaluate every fourth flow: the statistics allocate
}
iv := make([]float64, p.n-1)
var sum float64
for i := range iv {
iv[i] = float64(p.ts[i+1] - p.ts[i])
sum += iv[i]
}
med := median(iv)
if med < beaconMinIv || med > beaconMaxIv {
return
}
if ntp { // NTP is exempt only at a normal poll rate and never towards a bad destination
bad := false
if e.cfg.BadDst != nil {
bad, _ = e.cfg.BadDst(ev.Dst)
}
if !bad && med >= ntpMinIv {
return
}
}
mean := sum / float64(len(iv))
var ss float64
dev := make([]float64, len(iv))
for i, v := range iv {
ss += (v - mean) * (v - mean)
dev[i] = math.Abs(v - med)
}
cv := math.Sqrt(ss/float64(len(iv))) / mean
mad := median(dev) / med
if cv > beaconCV && mad > beaconMAD {
return
}
jit := cv
if mad < cv {
jit = mad
}
sev := "medium"
why := fmt.Sprintf("regular connections every %.0f s (jitter %.0f%%)", med, jit*100)
if e.cfg.BadDst != nil {
if bad, r := e.cfg.BadDst(ev.Dst); bad {
sev, why = "high", why+"; destination: "+r
}
}
p.flagged, p.interval, p.cv = true, med, jit
f := e.addFinding("beacon", sev, ws.name, ev.Dst.String(), dport, ev.Proto, p.last, med, jit, why, 0)
if f != nil {
f.Count, f.First = int(p.total), p.first
}
}
func median(v []float64) float64 {
s := append([]float64(nil), v...)
sort.Float64s(s)
n := len(s)
if n == 0 {
return 0
}
if n%2 == 1 {
return s[n/2]
}
return (s[n/2-1] + s[n/2]) / 2
}
var sevRank = map[string]int{"low": 1, "medium": 2, "high": 3}
func (e *Engine) addFinding(kind, sev, wl, dst string, dport uint16, proto string, t int64, iv, jit float64, detail string, inc int) *Finding {
key := fmt.Sprintf("%s|%s|%s|%d", kind, wl, dst, dport)
if f, ok := e.findings[key]; ok {
f.Count += inc
if t > f.Last {
f.Last = t
}
if sevRank[sev] > sevRank[f.Severity] {
f.Severity = sev
}
if detail != "" {
f.Detail = detail
}
if iv > 0 {
f.IntervalS, f.Jitter = iv, jit
}
return f
}
if sev == "" {
return nil // an update for a finding that was evicted
}
if len(e.findings) >= MaxFindings {
var worst string
var wf *Finding
for k, f := range e.findings {
if wf == nil || sevRank[f.Severity] < sevRank[wf.Severity] || sevRank[f.Severity] == sevRank[wf.Severity] && f.Last < wf.Last {
worst, wf = k, f
}
}
delete(e.findings, worst)
}
h := fnv.New64a()
h.Write([]byte(key))
f := &Finding{ID: fmt.Sprintf("e%016x", h.Sum64()), Kind: kind, Severity: sev, Workload: wl, Dst: dst, DPort: dport, Proto: proto,
Count: inc, IntervalS: iv, Jitter: jit, First: t, Last: t, Detail: detail}
e.findings[key] = f
return f
}
// Counters for the source status.
func (e *Engine) counters() (lines, malformed uint64, last int64) {
return e.lines.Load(), e.malformed.Load(), e.last.Load()
}
+105
View File
@@ -0,0 +1,105 @@
// Package egress analyses the outbound connections of the host and its
// containers (nftables "URUTAU-EGRESS: " log lines) to spot a compromised
// workload: beaconing, C2, mining, spam, unauthorised scanning.
//
// Central principle: traffic shaped like a scan (fan-out) is suppressed only
// for workloads with role=scanner. Traffic that is not scan shaped is judged
// the same for every workload, the scanner included.
package egress
import (
"errors"
"net/netip"
"strconv"
"strings"
"time"
)
const marker = "URUTAU-EGRESS:"
// Event is one new outbound connection.
type Event struct {
Time time.Time
Src, Dst netip.Addr
Proto string // tcp, udp, icmp, or the lowercased PROTO value
SPort, DPort uint16
In, Out string
Host bool // IN= empty: output of the host itself
}
// ErrNotEgress marks a line that is not an egress log line.
var ErrNotEgress = errors.New("not an egress line")
// ParseLine parses a kernel/rsyslog line. now is only used to infer the year
// of the "Nov 14 22:01:02" rsyslog format (and as the time of a line whose
// timestamp is unreadable).
func ParseLine(b []byte, now time.Time) (Event, error) {
line := string(b)
i := strings.Index(line, marker)
if i < 0 {
return Event{}, ErrNotEgress
}
ev := Event{Time: parseTS(line[:i], now)}
var haveSrc, haveDst bool
for _, f := range strings.Fields(line[i+len(marker):]) {
k, v, ok := strings.Cut(f, "=")
if !ok {
continue
}
switch k {
case "IN":
ev.In = v
case "OUT":
ev.Out = v
case "SRC":
a, err := netip.ParseAddr(v)
if err != nil {
return Event{}, errors.New("bad SRC")
}
ev.Src, haveSrc = a.Unmap(), true
case "DST":
a, err := netip.ParseAddr(v)
if err != nil {
return Event{}, errors.New("bad DST")
}
ev.Dst, haveDst = a.Unmap(), true
case "PROTO":
p := strings.ToLower(v)
if strings.HasPrefix(p, "icmp") {
p = "icmp"
}
ev.Proto = p
case "SPT":
n, _ := strconv.ParseUint(v, 10, 16)
ev.SPort = uint16(n)
case "DPT":
n, _ := strconv.ParseUint(v, 10, 16)
ev.DPort = uint16(n)
}
}
if !haveSrc || !haveDst || ev.Proto == "" {
return Event{}, errors.New("incomplete egress line")
}
ev.Host = ev.In == ""
return ev, nil
}
func parseTS(prefix string, now time.Time) time.Time {
f := strings.Fields(prefix)
if len(f) == 0 {
return now
}
if t, err := time.Parse(time.RFC3339Nano, f[0]); err == nil {
return t
}
if len(f) >= 3 {
if t, err := time.ParseInLocation("Jan 2 15:04:05", f[0]+" "+f[1]+" "+f[2], now.Location()); err == nil {
t = t.AddDate(now.Year(), 0, 0)
if t.After(now.Add(48 * time.Hour)) {
t = t.AddDate(-1, 0, 0)
}
return t
}
}
return now
}
+371
View File
@@ -0,0 +1,371 @@
package egress
import (
"net/netip"
"sort"
"strings"
)
// Finding is one alert; repeated observations update it.
type Finding struct {
ID string `json:"id"`
Kind string `json:"kind"`
Severity string `json:"severity"`
Workload string `json:"workload"`
Dst string `json:"dst"`
DPort uint16 `json:"dport"`
Proto string `json:"proto"`
Count int `json:"count"`
IntervalS float64 `json:"interval_s"`
Jitter float64 `json:"jitter"`
First int64 `json:"first"`
Last int64 `json:"last"`
Detail string `json:"detail"`
Host string `json:"host,omitempty"`
}
// WorkloadOut summarises a workload over the window.
type WorkloadOut struct {
Name string `json:"name"`
Role string `json:"role"`
Conns uint64 `json:"conns"`
Dsts int `json:"dsts"`
Ports int `json:"ports"`
Findings int `json:"findings"`
Suppressed uint64 `json:"suppressed_scan_conns"`
Host string `json:"host,omitempty"`
}
// Timeline holds hourly connection counts per workload.
type Timeline struct {
Start int64 `json:"start"`
Step int64 `json:"step"`
Series map[string][]uint32 `json:"series"`
}
// DstOut is a top destination.
type DstOut struct {
IP string `json:"ip"`
CC string `json:"cc"`
ASN string `json:"asn"`
Org string `json:"org"`
Conns uint64 `json:"conns"`
Workloads []string `json:"workloads"`
Ports []uint16 `json:"ports"`
}
// BurstOut summarises a scanner fan-out burst.
type BurstOut struct {
Workload string `json:"workload"`
Start int64 `json:"start"`
End int64 `json:"end"`
Targets int `json:"targets"`
Nets []string `json:"nets"`
Ports []uint16 `json:"ports"`
Conns uint32 `json:"conns"`
BadDstHit uint32 `json:"bad_dst_hits"`
Host string `json:"host,omitempty"`
}
// ScannerOut groups the scanner bursts.
type ScannerOut struct {
Bursts []BurstOut `json:"bursts"`
}
// Report is the egress analysis of a window.
type Report struct {
Workloads []WorkloadOut `json:"workloads"`
Timeline Timeline `json:"timeline"`
TopDst []DstOut `json:"top_dst"`
Findings []Finding `json:"findings"`
Scanner ScannerOut `json:"scanner"`
}
func (bs *burstState) out(wl string, end int64) BurstOut {
o := BurstOut{Workload: wl, Start: bs.start, End: end, Targets: len(bs.targets), Conns: bs.conns, BadDstHit: bs.badHits,
Nets: []string{}, Ports: []uint16{}}
type nc struct {
p netip.Prefix
n uint32
}
var ns []nc
for p, n := range bs.nets {
ns = append(ns, nc{p, n})
}
sort.Slice(ns, func(i, j int) bool {
if ns[i].n != ns[j].n {
return ns[i].n > ns[j].n
}
return ns[i].p.String() < ns[j].p.String()
})
for i := 0; i < len(ns) && i < 10; i++ {
o.Nets = append(o.Nets, ns[i].p.String())
}
type pc struct {
p uint16
n uint32
}
var ps []pc
for p, n := range bs.ports {
ps = append(ps, pc{p, n})
}
sort.Slice(ps, func(i, j int) bool {
if ps[i].n != ps[j].n {
return ps[i].n > ps[j].n
}
return ps[i].p < ps[j].p
})
for i := 0; i < len(ps) && i < 10; i++ {
o.Ports = append(o.Ports, ps[i].p)
}
return o
}
// Report builds the analysis of [from, to] (unix seconds).
func (e *Engine) Report(from, to int64) Report {
e.mu.Lock()
defer e.mu.Unlock()
if to <= from {
to = from + 1
}
startH, endH := from/3600, to/3600
if endH-startH > HourBuckets-1 {
startH = endH - (HourBuckets - 1)
}
nb := int(endH-startH) + 1
r := Report{Workloads: []WorkloadOut{}, TopDst: []DstOut{}, Findings: []Finding{},
Timeline: Timeline{Start: startH * 3600, Step: 3600, Series: map[string][]uint32{}},
Scanner: ScannerOut{Bursts: []BurstOut{}}}
fc := map[string]int{}
for _, f := range e.findings {
if f.Last >= from && f.First <= to {
r.Findings = append(r.Findings, *f)
fc[f.Workload]++
}
}
sort.Slice(r.Findings, func(i, j int) bool {
a, b := r.Findings[i], r.Findings[j]
if sevRank[a.Severity] != sevRank[b.Severity] {
return sevRank[a.Severity] > sevRank[b.Severity]
}
if a.Last != b.Last {
return a.Last > b.Last
}
return a.ID < b.ID
})
names := make([]string, 0, len(e.ws))
for n := range e.ws {
names = append(names, n)
}
sort.Strings(names)
for _, n := range names {
w := e.ws[n]
o := WorkloadOut{Name: n, Role: w.role, Findings: fc[n]}
series := make([]uint32, nb)
ds, ps := map[uint32]struct{}{}, map[uint32]struct{}{}
for h := startH; h <= endH; h++ {
b := &w.hours[h%HourBuckets]
if b.hour != h {
continue
}
series[h-startH] = b.conns
o.Conns += uint64(b.conns)
o.Suppressed += uint64(b.supp)
for _, x := range b.dsts {
ds[x] = struct{}{}
}
for _, x := range b.ports {
ps[x] = struct{}{}
}
}
o.Dsts, o.Ports = len(ds), len(ps)
if o.Conns == 0 && o.Suppressed == 0 && o.Findings == 0 {
continue
}
r.Workloads = append(r.Workloads, o)
r.Timeline.Series[n] = series
}
type scored struct {
ds *dstStat
n uint64
}
var all []scored
d0, d1 := int32(from/86400), int32(to/86400)
for el := e.dsts.l.Front(); el != nil; el = el.Next() {
ds := el.Value.(*lent[netip.Addr, *dstStat]).v
var n uint64
for _, d := range ds.days {
if d.day >= d0 && d.day <= d1 {
n += uint64(d.n)
}
}
if n > 0 {
all = append(all, scored{ds, n})
}
}
sort.Slice(all, func(i, j int) bool {
if all[i].n != all[j].n {
return all[i].n > all[j].n
}
return all[i].ds.ip.Compare(all[j].ds.ip) < 0
})
for i := 0; i < len(all) && i < 50; i++ {
ds := all[i].ds
ports := append([]uint16(nil), ds.ports...)
sort.Slice(ports, func(a, b int) bool { return ports[a] < ports[b] })
r.TopDst = append(r.TopDst, DstOut{IP: ds.ip.String(), CC: ds.cc, ASN: ds.asn, Org: ds.og, Conns: all[i].n,
Workloads: append([]string{}, ds.wls...), Ports: ports})
}
for _, b := range e.closed {
if b.End >= from && b.Start <= to {
r.Scanner.Bursts = append(r.Scanner.Bursts, b)
}
}
for _, n := range names {
if w := e.ws[n]; w.burst != nil && w.role == RoleScanner && w.burst.lastFan >= from && w.burst.start <= to {
r.Scanner.Bursts = append(r.Scanner.Bursts, w.burst.out(n, w.burst.lastFan))
}
}
return r
}
const (
maxPeerWorkloads = 256
maxPeerFindings = MaxFindings
maxStr = 200
)
func clip(s string) string {
if len(s) > maxStr {
return s[:maxStr]
}
return strings.ToValidUTF8(s, "")
}
// Sanitize bounds an untrusted peer report and stamps it with the peer name.
func (r *Report) Sanitize(host string) {
if len(r.Workloads) > maxPeerWorkloads {
r.Workloads = r.Workloads[:maxPeerWorkloads]
}
if len(r.Findings) > maxPeerFindings {
r.Findings = r.Findings[:maxPeerFindings]
}
if len(r.TopDst) > 50 {
r.TopDst = r.TopDst[:50]
}
if len(r.Scanner.Bursts) > maxClosedBurst+maxPeerWorkloads {
r.Scanner.Bursts = r.Scanner.Bursts[:maxClosedBurst+maxPeerWorkloads]
}
for i := range r.Workloads {
w := &r.Workloads[i]
w.Name, w.Role, w.Host = clip(w.Name), clip(w.Role), host
}
for i := range r.Findings {
f := &r.Findings[i]
f.ID, f.Kind, f.Severity = host+":"+clip(f.ID), clip(f.Kind), clip(f.Severity)
f.Workload, f.Dst, f.Proto, f.Detail, f.Host = clip(f.Workload), clip(f.Dst), clip(f.Proto), clip(f.Detail), host
}
for i := range r.TopDst {
d := &r.TopDst[i]
d.IP, d.CC, d.ASN, d.Org = clip(d.IP), clip(d.CC), clip(d.ASN), clip(d.Org)
if len(d.Workloads) > 8 {
d.Workloads = d.Workloads[:8]
}
for j := range d.Workloads {
d.Workloads[j] = clip(d.Workloads[j])
}
if len(d.Ports) > 8 {
d.Ports = d.Ports[:8]
}
}
for i := range r.Scanner.Bursts {
b := &r.Scanner.Bursts[i]
b.Workload, b.Host = clip(b.Workload), host
if len(b.Nets) > 10 {
b.Nets = b.Nets[:10]
}
for j := range b.Nets {
b.Nets[j] = clip(b.Nets[j])
}
if len(b.Ports) > 10 {
b.Ports = b.Ports[:10]
}
}
for k, v := range r.Timeline.Series {
if len(v) > HourBuckets {
r.Timeline.Series[k] = v[:HourBuckets]
}
}
if len(r.Timeline.Series) > maxPeerWorkloads {
r.Timeline.Series = map[string][]uint32{}
}
}
// Merge adds a sanitized peer report to r (the hub view). Series are keyed
// "host/workload" and placed on r's hourly grid.
func (r *Report) Merge(o Report, host string) {
r.Workloads = append(r.Workloads, o.Workloads...)
r.Findings = append(r.Findings, o.Findings...)
r.Scanner.Bursts = append(r.Scanner.Bursts, o.Scanner.Bursts...)
r.TopDst = append(r.TopDst, o.TopDst...)
sort.SliceStable(r.TopDst, func(i, j int) bool { return r.TopDst[i].Conns > r.TopDst[j].Conns })
if len(r.TopDst) > 50 {
r.TopDst = r.TopDst[:50]
}
sort.SliceStable(r.Findings, func(i, j int) bool {
a, b := r.Findings[i], r.Findings[j]
if sevRank[a.Severity] != sevRank[b.Severity] {
return sevRank[a.Severity] > sevRank[b.Severity]
}
return a.Last > b.Last
})
if len(r.Findings) > MaxFindings {
r.Findings = r.Findings[:MaxFindings]
}
if r.Timeline.Step == 0 {
r.Timeline.Step = 3600
}
for k, v := range o.Timeline.Series {
if r.Timeline.Start == 0 {
r.Timeline.Start = o.Timeline.Start
}
n := len(v)
off := int((o.Timeline.Start - r.Timeline.Start) / 3600)
for _, ex := range r.Timeline.Series {
n = len(ex)
break
}
dst := make([]uint32, n)
for i, x := range v {
if j := i + off; j >= 0 && j < n {
dst[j] = x
}
}
r.Timeline.Series[host+"/"+k] = dst
}
}
// Stamp marks the items of a trusted (local) report with its host name, as
// Sanitize does for a peer, so that a hub view can tell them apart.
func (r *Report) Stamp(host string) {
for i := range r.Workloads {
r.Workloads[i].Host = host
}
for i := range r.Findings {
r.Findings[i].Host = host
r.Findings[i].ID = host + ":" + r.Findings[i].ID
}
for i := range r.Scanner.Bursts {
r.Scanner.Bursts[i].Host = host
}
}
// EmptyReport is a well-formed report without data.
func EmptyReport() Report {
return Report{Workloads: []WorkloadOut{}, TopDst: []DstOut{}, Findings: []Finding{}, Scanner: ScannerOut{Bursts: []BurstOut{}},
Timeline: Timeline{Step: 3600, Series: map[string][]uint32{}}}
}
+110
View File
@@ -0,0 +1,110 @@
package egress
import (
"context"
"errors"
"log/slog"
"os"
"sync"
"sync/atomic"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/tail"
)
const maxLine = 16 * 1024
// Source follows the egress log file and feeds the engine. State is in memory
// only: on start the rotated backups and the live file are replayed from the
// beginning, which rebuilds the beacon history deterministically.
type Source struct {
Path string
E *Engine
Log *slog.Logger
backfilling atomic.Bool
fol atomic.Pointer[tail.Follower]
}
// NewSource creates the source of e reading path.
func NewSource(path string, e *Engine, log *slog.Logger) *Source {
if log == nil {
log = slog.Default()
}
s := &Source{Path: path, E: e, Log: log}
f := s.state
e.stateFn.Store(&f)
return s
}
func (s *Source) state() string {
switch f := s.fol.Load(); {
case s.backfilling.Load():
return "backfill"
case f == nil:
return "waiting"
default:
if err := f.Err(); err != nil {
if errors.Is(err, os.ErrNotExist) {
return "waiting"
}
return "error"
}
}
return "following"
}
// Status is the source line for the sources panel.
func (s *Source) Status() store.SourceStatus {
l, m, last := s.E.counters()
st := store.SourceStatus{Name: "egress", Path: s.Path, State: s.state(), Lines: l, Malformed: m, LastEvent: last}
if st.State == "error" {
st.Error = "read error"
}
return st
}
// Start launches the single goroutine of the source; it stops with ctx.
func (s *Source) Start(ctx context.Context, wg *sync.WaitGroup) {
wg.Add(1)
go func() {
defer wg.Done()
defer func() {
if p := recover(); p != nil {
s.Log.Error("egress source stopped by a panic", "panic", p)
}
}()
s.backfilling.Store(true)
for _, b := range tail.Backups(s.Path) {
if ctx.Err() != nil {
break
}
if err := tail.ReadAll(b, maxLine, s.E.Ingest, func() { s.E.malformed.Add(1) }); err != nil {
s.Log.Warn("egress backfill failed", "file", b, "err", err)
}
}
s.backfilling.Store(false)
f := tail.NewFollower(s.Path, tail.Pos{})
f.MaxLine, f.Handle = maxLine, s.E.Ingest
f.Oversize = func() { s.E.malformed.Add(1) }
s.fol.Store(f)
f.Run(ctx)
}()
}
// SourceInfo is the "source" object of the API.
type SourceInfo struct {
State string `json:"state"`
Lines uint64 `json:"lines"`
Malformed uint64 `json:"malformed"`
Last int64 `json:"last"`
}
// Info reports the source state (state "disabled" when no source is attached).
func (e *Engine) Info() SourceInfo {
l, m, last := e.counters()
st := "disabled"
if f := e.stateFn.Load(); f != nil {
st = (*f)()
}
return SourceInfo{State: st, Lines: l, Malformed: m, Last: last}
}
+169
View File
@@ -0,0 +1,169 @@
package egress
import (
"bufio"
"fmt"
"net/netip"
"os"
"regexp"
"strings"
)
// Roles of a workload.
const (
RoleDefault = "default"
RoleScanner = "scanner"
RoleMail = "mail"
RoleResolver = "resolver"
)
func validRole(r string) bool {
return r == RoleDefault || r == RoleScanner || r == RoleMail || r == RoleResolver
}
type matcher struct {
prefix netip.Prefix // valid when name == "" and !host
name string // container name: exact base name, or a prefix when pfx
pfx bool
host bool // the host's own output ("host")
}
type workloadDef struct {
name, role string
m []matcher
}
// ParseWorkloads parses "name=ITEM,ITEM:role;name2=...". An ITEM is a CIDR, an
// IP, "host" (the host's own output, so it can take a role such as mail),
// "name:<container name>" (exact base name, without the -<digits> suffix) or
// "name:<prefix>*" (explicit prefix); the role (scanner, mail, resolver,
// default) follows the last colon.
func ParseWorkloads(s string) ([]workloadDef, error) {
var out []workloadDef
for _, part := range strings.Split(s, ";") {
part = strings.TrimSpace(part)
if part == "" {
continue
}
name, rest, ok := strings.Cut(part, "=")
name, rest = strings.TrimSpace(name), strings.TrimSpace(rest)
if !ok || name == "" || rest == "" {
return nil, fmt.Errorf("workload %q: expected name=items[:role]", part)
}
role := RoleDefault
if i := strings.LastIndex(rest, ":"); i >= 0 && validRole(rest[i+1:]) {
role, rest = rest[i+1:], rest[:i]
}
w := workloadDef{name: name, role: role}
for _, it := range strings.Split(rest, ",") {
it = strings.TrimSpace(it)
switch {
case it == "":
case it == "host":
w.m = append(w.m, matcher{host: true})
case strings.HasPrefix(it, "name:"):
p := strings.TrimPrefix(it, "name:")
pfx := strings.HasSuffix(p, "*")
p = strings.TrimSuffix(p, "*")
if !nameRe.MatchString(p) {
return nil, fmt.Errorf("workload %q: bad container name %q", name, p)
}
w.m = append(w.m, matcher{name: p, pfx: pfx})
default:
pf, err := netip.ParsePrefix(it)
if err != nil {
a, err2 := netip.ParseAddr(it)
if err2 != nil {
return nil, fmt.Errorf("workload %q: bad address %q", name, it)
}
pf = netip.PrefixFrom(a.Unmap(), a.Unmap().BitLen())
}
w.m = append(w.m, matcher{prefix: pf.Masked()})
}
}
if len(w.m) == 0 {
return nil, fmt.Errorf("workload %q: no addresses", name)
}
out = append(out, w)
}
return out, nil
}
var nameRe = regexp.MustCompile(`^[A-Za-z0-9_.-]{1,128}$`)
var tsSuffix = regexp.MustCompile(`-\d{9,}$`)
var digitSuffix = regexp.MustCompile(`-\d+$`)
// ContainerBase strips the "-<timestamp>" suffix of a container name.
func ContainerBase(n string) string { return tsSuffix.ReplaceAllString(n, "") }
const maxMapLines = 10000
// LoadContainers reads a containers.map file ("<ip> <name>" per line; invalid
// lines are skipped, at most 10k lines).
func LoadContainers(path string) (map[netip.Addr]string, error) {
fh, err := os.Open(path)
if err != nil {
return nil, err
}
defer fh.Close()
m := map[netip.Addr]string{}
sc := bufio.NewScanner(fh)
sc.Buffer(make([]byte, 0, 4096), 4096)
for n := 0; sc.Scan() && n < maxMapLines; n++ {
f := strings.Fields(sc.Text())
if len(f) != 2 || !nameRe.MatchString(f[1]) {
continue
}
a, err := netip.ParseAddr(f[0])
if err != nil {
continue
}
m[a.Unmap()] = f[1]
}
return m, sc.Err()
}
// resolve names the workload of an event: host output is "host"; a container
// address matches the configured workloads (CIDR or container name from the
// current map); otherwise it is named after its mapped container (without the
// timestamp suffix) or "container <ip>".
func (e *Engine) resolve(ev Event) (name, role string) {
if ev.Host {
for _, w := range e.wls {
for _, m := range w.m {
if m.host {
return w.name, w.role
}
}
}
return "host", RoleDefault
}
cname := e.containers[ev.Src]
for _, w := range e.wls {
for _, m := range w.m {
if m.host {
continue
}
if m.name != "" {
if cname != "" && m.matchName(cname) {
return w.name, w.role
}
} else if m.prefix.Contains(ev.Src) {
return w.name, w.role
}
}
}
if cname != "" {
return ContainerBase(cname), RoleDefault
}
return "container " + ev.Src.String(), RoleDefault
}
// matchName compares a container name: the exact base name (the full name or
// without a -<digits> suffix), or a prefix when the item ended in "*".
func (m matcher) matchName(cname string) bool {
if m.pfx {
return strings.HasPrefix(cname, m.name)
}
return cname == m.name || digitSuffix.ReplaceAllString(cname, "") == m.name
}
+497
View File
@@ -0,0 +1,497 @@
package enforce
import (
"fmt"
"net/netip"
"os"
"path/filepath"
"strings"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
)
var t0 = time.Date(2026, 11, 14, 22, 0, 0, 0, time.UTC)
func TestDecide(t *testing.T) {
p := Params{Threshold: 5}
cases := []struct {
name string
in Input
act string
why string
}{
{"below", Input{Attacks: 4, Top: ReasonScannerFlood}, ActNone, ""},
{"threshold", Input{Attacks: 5, Top: ReasonWPBrute}, ActBan, ReasonWPBrute},
{"critical single hit", Input{Crit: ReasonEnvProbe, Crits: 1, Attacks: 1}, ActNone, ""},
{"critical two hits", Input{Crit: ReasonEnvProbe, Crits: 2, Attacks: 2}, ActBan, ReasonEnvProbe},
{"ssh", Input{SSHFails: 5}, ActBan, ReasonSSHBrute},
{"ssh below", Input{SSHFails: 4}, ActNone, ""},
{"trusted", Input{Attacks: 9, Exclude: SkipTrusted}, ActSkip, ""},
{"crawler", Input{Crit: ReasonRCE, Crits: 2, Exclude: SkipCrawler}, ActSkip, ""},
{"infra", Input{Crit: ReasonRCE, Crits: 2, Exclude: SkipInfra}, ActSkip, ""},
{"legit doubles", Input{Attacks: 9, Legit: true, Top: ReasonScannerFlood}, ActNone, ""},
{"legit doubles ok", Input{Attacks: 10, Legit: true, Top: ReasonScannerFlood}, ActBan, ReasonScannerFlood},
{"legit never stops crit", Input{Crit: ReasonRCE, Crits: 2, Attacks: 2, Legit: true}, ActBan, ReasonRCE},
{"legit one crit", Input{Crit: ReasonRCE, Crits: 1, Attacks: 1, Legit: true}, ActNone, ""},
{"legit ssh", Input{SSHFails: 9, Legit: true}, ActNone, ""},
{"already", Input{Attacks: 5, Top: ReasonScannerFlood, Banned: true}, ActAlready, ""},
{"active", Input{Attacks: 5, Top: ReasonScannerFlood, Active: true}, ActActive, ""},
}
for _, c := range cases {
d := Decide(c.in, p)
if d.Action != c.act || (c.why != "" && d.Reason != c.why) {
t.Errorf("%s: %+v", c.name, d)
}
}
}
func TestTTLEscalation(t *testing.T) {
want := []time.Duration{time.Hour, 6 * time.Hour, 24 * time.Hour, 7 * 24 * time.Hour, 7 * 24 * time.Hour}
for i, w := range want {
if TTLFor(i) != w {
t.Errorf("offence %d: %v", i, TTLFor(i))
}
}
}
func TestExclusions(t *testing.T) {
x := Exclusions{Trusted: []netip.Prefix{netip.MustParsePrefix("45.0.0.0/8")}, Peers: map[netip.Addr]bool{netip.MustParseAddr("46.1.1.1"): true},
Infra: map[netip.Addr]bool{netip.MustParseAddr("47.1.1.1"): true}}
for ip, want := range map[string]string{
"10.1.2.3": SkipPrivate, "127.0.0.1": SkipPrivate, "169.254.1.1": SkipPrivate, "100.64.1.1": SkipPrivate,
"::1": SkipPrivate, "fe80::1": SkipPrivate, "fc00::1": SkipPrivate, "ff02::1": SkipPrivate, "224.0.0.1": SkipPrivate,
"240.0.0.1": SkipPrivate, "0.0.0.0": SkipPrivate, "::ffff:10.0.0.1": SkipPrivate, "2001:db8::1": SkipPrivate,
"45.9.9.9": SkipTrusted, "47.1.1.1": SkipInfra, "46.1.1.1": SkipPeer, "::ffff:46.1.1.1": SkipPeer,
"8.8.8.8": SkipInfra, "2606:4700::1111": SkipInfra, "104.16.1.1": SkipInfra, "2a06:98c0::1": SkipInfra, "93.184.216.34": "",
} {
if got := x.Excluded(netip.MustParseAddr(ip)); got != want {
t.Errorf("%s: %q want %q", ip, got, want)
}
}
}
func atk(ip string, at time.Time, path string, st int) core.Event {
return core.Event{Time: at, IP: ip, Cat: core.Scanner, Source: "traefik", Method: "GET", Path: path, Status: st, UA: "x"}
}
type rig struct {
e *Engine
now time.Time
log string
}
func newRig(t *testing.T, mode string, mod func(*Config)) *rig {
r := &rig{now: t0, log: filepath.Join(t.TempDir(), "enf", "decisions.log")}
c := Config{Mode: mode, Path: r.log, StatePath: filepath.Join(t.TempDir(), "enforce.json"), Host: "oracle", Threshold: 5, MaxPerMin: 60,
Trusted: []netip.Prefix{netip.MustParsePrefix("45.0.0.0/8")}, Now: func() time.Time { return r.now }}
if mod != nil {
mod(&c)
}
r.e = New(c)
return r
}
func (r *rig) lines(t *testing.T) []string {
b, err := os.ReadFile(r.log)
if err != nil {
return nil
}
return strings.Split(strings.TrimSpace(string(b)), "\n")
}
func (r *rig) hits(ip string, n int, path string, st int) {
for i := 0; i < n; i++ {
r.e.process(atk(ip, r.now.Add(-time.Duration(i)*time.Second), path, st), "")
}
}
func TestEngineThresholdAndLine(t *testing.T) {
r := newRig(t, ModeOn, nil)
r.hits("203.0.114.7", 4, "/x", 404)
if len(r.lines(t)) != 0 {
t.Fatal("banned below threshold")
}
r.hits("203.0.114.7", 1, "/x", 404)
l := r.lines(t)
if len(l) != 1 || !strings.HasPrefix(l[0], "2026-11-14T22:00:00Z urutau decision=ban ip=203.0.114.7 reason=scanner-flood score=") ||
!strings.HasSuffix(l[0], " ttl=3600 host=oracle src=local") {
t.Fatalf("line %q", l)
}
// dedupe: more hits while the TTL holds write nothing
r.hits("203.0.114.7", 10, "/x", 404)
if len(r.lines(t)) != 1 {
t.Fatal("rewrote during TTL")
}
// escalation after the TTL: 6 h, persisted
r.now = r.now.Add(61 * time.Minute)
r.hits("203.0.114.7", 5, "/x", 404)
l = r.lines(t)
if len(l) != 2 || !strings.Contains(l[1], "ttl=21600") {
t.Fatalf("escalation %q", l)
}
r.e.saveState()
e2 := New(r.e.cfg)
if e2.bans[netip.MustParseAddr("203.0.114.7")].Offences != 2 {
t.Fatalf("state %+v", e2.bans)
}
if fi, err := os.Stat(r.log); err != nil || fi.Mode().Perm() != 0o640 {
t.Fatalf("mode %v %v", fi, err)
}
}
func TestEngineCriticalAndFamily(t *testing.T) {
r := newRig(t, ModeOn, nil)
ev := atk("203.0.114.8", r.now, "/.env", 404)
ev.Cat = core.Exploit
r.e.process(ev, intel.FamEnvCreds)
if len(r.lines(t)) != 0 {
t.Fatal("a single critical hit banned")
}
ev.Time = r.now.Add(time.Second)
r.e.process(ev, intel.FamEnvCreds)
ev2 := atk("203.0.114.9", r.now, "/wp-login.php", 404)
r.e.process(ev2, intel.FamWordPress)
l := r.lines(t)
if len(l) != 1 || !strings.Contains(l[0], "reason=env-probe") {
t.Fatalf("%q", l)
}
}
func TestEngineNeverCounts(t *testing.T) {
r := newRig(t, ModeOn, nil)
for _, st := range []int{404, 400, 405, 500, 502} {
ev := atk("203.0.114.10", r.now, "/x", st)
ev.Cat = core.NotFound // a plain 404 is not an attack category
for i := 0; i < 20; i++ {
r.e.process(ev, "")
}
}
// app and proxy errors on attack-category requests do not count either
for i := 0; i < 20; i++ {
ev := atk("203.0.114.11", r.now, "/x", 500)
ev.Proto, ev.Router, ev.OriginStatus = "HTTP/2", "r@docker", 500
r.e.process(ev, "")
ev = atk("203.0.114.11", r.now, "/x", 502)
ev.Proto, ev.Router, ev.Retries = "HTTP/2", "r@docker", 2
r.e.process(ev, "")
fr := atk("203.0.114.11", r.now, "/x", 404)
fr.Framed = true
r.e.process(fr, "")
}
if len(r.lines(t)) != 0 {
t.Fatalf("banned: %q", r.lines(t))
}
}
func TestEngineExclusionsAndCounts(t *testing.T) {
r := newRig(t, ModeOn, func(c *Config) {
c.Crawler = func(ip string, uas []string) bool { return ip == "66.249.66.1" }
c.PeerHosts = []string{"46.1.1.1"}
})
r.hits("45.1.1.1", 6, "/x", 404)
r.hits("10.0.0.5", 6, "/x", 404)
r.hits("46.1.1.1", 6, "/x", 404)
r.hits("66.249.66.1", 6, "/x", 404)
if len(r.lines(t)) != 0 {
t.Fatalf("banned excluded: %q", r.lines(t))
}
rep := r.e.Report(0)
for _, k := range []string{SkipTrusted, SkipPrivate, SkipPeer, SkipCrawler} {
if rep.Counts.Skipped[k] != 1 {
t.Errorf("skip %s: %v", k, rep.Counts.Skipped)
}
}
// the skip is reported once, not once per event
r.hits("45.1.1.1", 30, "/x", 404)
if r.e.Report(0).Counts.Skipped[SkipTrusted] != 1 {
t.Fatal("skip spam")
}
}
func TestEngineLegitVisitor(t *testing.T) {
r := newRig(t, ModeOn, nil)
vis := core.Event{Time: r.now.Add(-time.Hour), IP: "203.0.114.20", Cat: core.OK, Source: "traefik", Status: 200, FetchDest: "document"}
r.e.process(vis, "")
ev := atk("203.0.114.20", r.now, "/.env", 404)
ev.Cat = core.Exploit
r.e.process(ev, intel.FamEnvCreds)
r.hits("203.0.114.20", 7, "/x", 404)
if len(r.lines(t)) != 0 {
t.Fatalf("legit banned: %q", r.lines(t))
}
r.hits("203.0.114.20", 2, "/y", 404)
if len(r.lines(t)) != 1 {
t.Fatalf("legit double threshold: %q", r.lines(t))
}
}
func TestEngineAlreadyBlocked(t *testing.T) {
r := newRig(t, ModeOn, nil)
r.e.process(core.Event{Time: r.now, IP: "203.0.114.30", Cat: core.Ban, Source: "fail2ban", Jail: "sshd"}, "")
r.hits("203.0.114.30", 8, "/x", 404)
if len(r.lines(t)) != 0 || r.e.Report(0).Counts.AlreadyBlocked != 1 {
t.Fatalf("%q %+v", r.lines(t), r.e.Report(0).Counts)
}
rep := r.e.Report(0)
if rep.Coverage.AttackIPs != 1 || rep.Coverage.BlockedByFirewall != 1 {
t.Fatalf("coverage %+v", rep.Coverage)
}
}
func TestEngineSSH(t *testing.T) {
r := newRig(t, ModeOn, nil)
for i := 0; i < 5; i++ {
r.e.process(core.Event{Time: r.now.Add(-time.Duration(i) * time.Minute), IP: "203.0.114.40", Cat: core.SSHFail, Source: "ssh", User: "root"}, "")
}
if l := r.lines(t); len(l) != 1 || !strings.Contains(l[0], "reason=ssh-bruteforce") {
t.Fatalf("%q", l)
}
}
func TestEngineRateCapAndObserve(t *testing.T) {
r := newRig(t, ModeOn, func(c *Config) { c.MaxPerMin = 3 })
for i := 0; i < 6; i++ {
r.hits(fmt.Sprintf("203.0.114.%d", 50+i), 5, "/x", 404)
}
rep := r.e.Report(0)
if len(r.lines(t)) != 3 || rep.Counts.Written != 3 || rep.Counts.DroppedRate != 3 || rep.Counts.Decided != 6 {
t.Fatalf("%q %+v", r.lines(t), rep.Counts)
}
o := newRig(t, ModeObserve, nil)
o.hits("203.0.114.60", 5, "/x", 404)
rep = o.e.Report(0)
if _, err := os.Stat(o.log); err == nil {
t.Fatal("observe wrote the file")
}
if len(rep.Recent) != 1 || rep.Recent[0].Action != "would_ban" || rep.Coverage.WouldBlock != 1 || rep.Counts.Written != 0 {
t.Fatalf("%+v", rep)
}
}
func TestOldEventsDoNotBan(t *testing.T) {
r := newRig(t, ModeOn, nil)
for i := 0; i < 20; i++ {
r.e.process(atk("203.0.114.70", r.now.Add(-3*time.Hour), "/x", 404), "")
}
if len(r.lines(t)) != 0 {
t.Fatal("replayed events banned")
}
if r.e.Report(0).Coverage.AttackIPs != 1 {
t.Fatal("coverage lost old events")
}
}
func TestObserveNeverBlocks(t *testing.T) {
e := New(Config{Mode: ModeOn, Path: filepath.Join(t.TempDir(), "d.log")})
for i := 0; i < 10000; i++ {
e.Observe(atk("203.0.114.1", t0, "/x", 404), "")
}
if e.dropQ.Load() == 0 {
t.Fatal("full queue must drop and count")
}
}
func (r *rig) seen(ip string) { r.hits(ip, 2, "/x", 404) }
func TestAcceptPeer(t *testing.T) {
r := newRig(t, ModeOn, nil)
r.seen("203.0.114.80")
acc, bad := r.e.AcceptPeer("hostinger", []Wire{
{T: t0.Unix(), IP: "203.0.114.80", Reason: ReasonRCE, Score: 90, TTL: 3600},
{T: t0.Unix(), IP: "203.0.114.81", Reason: "evil\nreason", Score: 90, TTL: 3600},
{T: t0.Unix(), IP: "10.0.0.1", Reason: ReasonRCE, TTL: 3600},
{T: t0.Unix(), IP: "45.2.2.2", Reason: ReasonRCE, TTL: 3600},
{T: t0.Unix(), IP: "nope", Reason: ReasonRCE, TTL: 3600},
})
l := r.lines(t)
if acc != 1 || bad != 3 || len(l) != 1 || !strings.HasSuffix(l[0], "src=peer:hostinger") {
t.Fatalf("%d %d %q", acc, bad, l)
}
if len(r.e.LocalSince(0)) != 0 {
t.Fatal("peer decisions must not be re-shared")
}
if r.e.Report(0).Counts.Skipped[SkipTrusted] != 1 {
t.Fatalf("%+v", r.e.Report(0).Counts)
}
}
func TestAcceptPeerUnconfirmedTTLAndInfra(t *testing.T) {
r := newRig(t, ModeOn, nil)
r.seen("203.0.114.90")
r.seen("1.1.1.1")
r.seen("104.16.5.5")
acc, _ := r.e.AcceptPeer("h", []Wire{
{T: t0.Unix(), IP: "203.0.114.99", Reason: ReasonRCE, Score: 90, TTL: 3600}, // never seen here
{T: t0.Unix(), IP: "203.0.114.90", Reason: ReasonRCE, Score: 90, TTL: 7 * 24 * 3600},
{T: t0.Unix(), IP: "1.1.1.1", Reason: ReasonRCE, Score: 90, TTL: 3600},
{T: t0.Unix(), IP: "104.16.5.5", Reason: ReasonRCE, Score: 90, TTL: 3600},
})
l := r.lines(t)
if acc != 1 || len(l) != 1 || !strings.Contains(l[0], "ip=203.0.114.90") || !strings.Contains(l[0], "ttl=21600") {
t.Fatalf("%d %q", acc, l)
}
sk := r.e.Report(0).Counts.Skipped
if sk[SkipUnconfirmed] != 1 || sk[SkipInfra] < 2 {
t.Fatalf("%v", sk)
}
// an attack seen only long ago does not confirm
r2 := newRig(t, ModeOn, nil)
for i := 0; i < 3; i++ {
r2.e.process(atk("203.0.114.91", r2.now.Add(-8*24*time.Hour), "/x", 404), "")
}
if acc, _ := r2.e.AcceptPeer("h", []Wire{{T: t0.Unix(), IP: "203.0.114.91", Reason: ReasonRCE, TTL: 60}}); acc != 0 {
t.Fatal("stale confirmation accepted")
}
}
func TestInfraNeverBannedLocally(t *testing.T) {
r := newRig(t, ModeOn, func(c *Config) {
c.PeerHosts = []string{"hub.example"}
c.InfraHosts = []string{"hub.example"}
c.LocalAddrs = func() []netip.Addr { return []netip.Addr{netip.MustParseAddr("203.0.114.200")} }
c.Resolve = func(string) []netip.Addr { return []netip.Addr{netip.MustParseAddr("203.0.114.201")} }
})
for _, ip := range []string{"104.16.9.9", "8.8.4.4", "2606:4700:4700::1001", "203.0.114.200", "203.0.114.201"} {
r.hits(ip, 9, "/x", 404)
}
if len(r.lines(t)) != 0 {
t.Fatalf("infra banned: %q", r.lines(t))
}
}
func TestPeerResolutionKeepsLastGood(t *testing.T) {
fail := false
r := newRig(t, ModeOn, func(c *Config) {
c.PeerHosts = []string{"peer.example"}
c.Resolve = func(string) []netip.Addr {
if fail {
return nil
}
return []netip.Addr{netip.MustParseAddr("203.0.114.210")}
}
})
fail = true
r.e.refreshPeers()
r.hits("203.0.114.210", 9, "/x", 404)
if len(r.lines(t)) != 0 {
t.Fatal("peer banned after DNS failure")
}
}
func TestCriticalNeedsTwoHits(t *testing.T) {
r := newRig(t, ModeOn, nil)
mk := func(at time.Time) {
ev := atk("203.0.114.220", at, "/.env", 404)
ev.Cat = core.Exploit
r.e.process(ev, intel.FamEnvCreds)
}
mk(r.now)
if len(r.lines(t)) != 0 {
t.Fatal("one hit")
}
// a forged legitimate visit does not cancel a critical ban
r.e.process(core.Event{Time: r.now, IP: "203.0.114.220", Cat: core.OK, Source: "traefik", Status: 200, FetchDest: "document"}, "")
mk(r.now.Add(time.Second))
if len(r.lines(t)) != 1 {
t.Fatalf("legit visit blocked crit ban: %q", r.lines(t))
}
}
func TestWouldAndBansPruned(t *testing.T) {
r := newRig(t, ModeObserve, nil)
r.e.mu.Lock()
for i := 0; i < maxTracked+10; i++ {
a := netip.AddrFrom4([4]byte{50, byte(i >> 16), byte(i >> 8), byte(i)})
r.e.would[a] = r.now.Add(time.Hour).Unix()
r.e.bans[a] = banRec{Until: r.now.Unix(), Last: r.now.Unix(), Offences: 1}
}
r.e.would[netip.MustParseAddr("51.0.0.1")] = r.now.Add(-48 * time.Hour).Unix()
r.e.trimMaps(r.now)
nw, nb := len(r.e.would), len(r.e.bans)
_, old := r.e.would[netip.MustParseAddr("51.0.0.1")]
r.e.mu.Unlock()
if nw > maxTracked || nb > maxTracked || old {
t.Fatalf("not pruned: %d %d %v", nw, nb, old)
}
}
func TestSaveStateThrottled(t *testing.T) {
r := newRig(t, ModeOn, nil)
r.hits("203.0.114.230", 5, "/x", 404)
r.e.maybeSave()
st := r.e.cfg.StatePath
os.Remove(st)
r.hits("203.0.114.231", 5, "/x", 404)
r.e.maybeSave() // same instant: throttled
if _, err := os.Stat(st); err == nil {
t.Fatal("saved within 30s")
}
r.now = r.now.Add(31 * time.Second)
r.e.maybeSave()
if _, err := os.Stat(st); err != nil {
t.Fatal("not saved after 30s")
}
}
func TestRotation(t *testing.T) {
l := &logFile{path: filepath.Join(t.TempDir(), "d.log")}
line := strings.Repeat("x", 1<<20-1) + "\n"
for i := 0; i < 21; i++ {
if err := l.write(line); err != nil {
t.Fatal(err)
}
}
if _, err := os.Stat(l.path + ".1"); err != nil {
t.Fatal("no rotation")
}
if fi, _ := os.Stat(l.path); fi.Size() > MaxLogBytes {
t.Fatal("too big")
}
}
func TestFormatLineInjection(t *testing.T) {
ip := netip.MustParseAddr("8.8.8.8")
for _, evil := range []string{"x\ny", "a b\r\nurutau decision=ban ip=1.1.1.1", "peer:\x00\n", "\n\n", strings.Repeat("a", 500)} {
if _, err := FormatLine(t0, ip, evil, 90, time.Hour, "h", "local"); err == nil {
t.Errorf("reason %q accepted", evil)
}
l, err := FormatLine(t0, ip, ReasonRCE, 90, time.Hour, evil, "peer:"+evil)
if err != nil || strings.Count(l, "\n") != 1 || !strings.HasSuffix(l, "\n") || strings.ContainsAny(strings.TrimSuffix(l, "\n"), "\r\x00") ||
len(strings.Fields(l)) != 9 {
t.Errorf("host/src %q -> %q", evil, l)
}
}
if _, err := FormatLine(t0, netip.Addr{}, ReasonRCE, 1, time.Hour, "h", "local"); err == nil {
t.Error("invalid ip accepted")
}
}
func FuzzFormatLine(f *testing.F) {
f.Add("h", "peer:x", ReasonRCE)
f.Add("a\nb", "\r\n", "x\ny")
f.Fuzz(func(t *testing.T, host, src, reason string) {
l, err := FormatLine(t0, netip.MustParseAddr("2606:4700::1111"), reason, 5, time.Hour, host, src)
if err != nil {
return
}
if strings.Count(l, "\n") != 1 || len(strings.Fields(l)) != 9 {
t.Fatalf("%q", l)
}
})
}
func TestWritable(t *testing.T) {
d := t.TempDir()
if !Writable(filepath.Join(d, "sub", "x.log")) || !Writable(filepath.Join(d, "x.log")) {
t.Fatal("should be writable")
}
if _, err := os.Stat(filepath.Join(d, "x.log")); err == nil {
t.Fatal("Writable must not create the file")
}
if Writable("") {
t.Fatal("empty path")
}
}
+723
View File
@@ -0,0 +1,723 @@
package enforce
import (
"context"
"encoding/json"
"net/netip"
"os"
"path/filepath"
"sort"
"sync"
"sync/atomic"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
)
// Config configures the engine. Mode must be observe or on (off means no engine).
type Config struct {
Mode string
Path string // decision file
StatePath string // enforce.json, empty: no persistence
Host string // name of this instance, written in every line
Threshold int // attack events in Window
MaxPerMin int
Share bool
Trusted []netip.Prefix
PeerHosts []string // host names or addresses of the peers
InfraHosts []string // hub and other infrastructure hosts, never banned
LocalAddrs func() []netip.Addr // default: the addresses of the local interfaces
Resolve func(host string) []netip.Addr // default: literal parse only
Crawler func(ip string, uas []string) bool // FCrDNS verified crawler
Geo func(ip string) (string, uint32, string) // cc, asn, org
Now func() time.Time
}
// Wire is a decision as exchanged between peers.
type Wire struct {
T int64 `json:"t"`
IP string `json:"ip"`
Reason string `json:"reason"`
Score int `json:"score"`
TTL int `json:"ttl"`
}
// MaxWire is the most decisions accepted or returned in one exchange.
const MaxWire = 500
// Recent is one row of the report.
type Recent struct {
T int64 `json:"t"`
IP string `json:"ip"`
Reason string `json:"reason"`
Score int `json:"score"`
TTL int `json:"ttl"`
Action string `json:"action"` // ban, would_ban, skip
SkipReason string `json:"skip_reason"`
Src string `json:"src"`
CC string `json:"cc"`
ASN uint32 `json:"asn"`
Org string `json:"org"`
}
// Counts are the cumulative counters since start.
type Counts struct {
Decided int `json:"decided"`
Written int `json:"written"`
DroppedRate int `json:"dropped_rate"`
AlreadyBlocked int `json:"already_blocked"`
Skipped map[string]int `json:"skipped"`
DroppedQueue int64 `json:"dropped_queue"`
WriteErrors int `json:"write_errors"`
}
// Coverage tells how many attacking addresses were stopped, by whom.
type Coverage struct {
AttackIPs int `json:"attack_ips"`
BlockedByFirewall int `json:"blocked_by_firewall"`
BlockedByUrutau int `json:"blocked_by_urutau"`
WouldBlock int `json:"would_block"`
Unblocked int `json:"unblocked"`
}
// Report is what the API serves (mode and file status are added by the handler).
type Report struct {
Coverage Coverage `json:"coverage"`
Counts Counts `json:"counts"`
Recent []Recent `json:"recent"`
}
type aevt struct {
ts int64
slug string
}
type ipState struct {
ev []aevt
ssh []int64
legit int64
uas []string
lastAttack int64
f2bAt int64
urutauAt int64
wouldAt int64
banned int64 // fail2ban holds it until (unix), 0 none
}
type banRec struct {
Until int64 `json:"until"`
Offences int `json:"offences"`
Last int64 `json:"last"`
}
type item struct {
ev core.Event
fam string
}
const (
maxIPs = 50000
maxEvents = 128
maxRecent = 200
skipQuiet = 10 * time.Minute
banAssume = 24 * time.Hour
peerRefresh = 10 * time.Minute
maxPeerTTL = 6 * time.Hour
peerConfirmAge = 7 * 24 * time.Hour
maxTracked = 50000 // would and bans
saveEvery = 30 * time.Second
)
// Engine is the second firewall.
type Engine struct {
cfg Config
log *logFile
ch chan item
dropQ atomic.Int64
mu sync.Mutex
ips map[netip.Addr]*ipState
bans map[netip.Addr]banRec
would map[netip.Addr]int64
skipSeen map[netip.Addr]int64
excl Exclusions
counts Counts
recent []Recent
shared []Wire
minute int64
inMinute int
dirty bool
lastSave time.Time
hostIPs map[string][]netip.Addr // last good resolution per host
}
// New builds an engine and loads its state.
func New(c Config) *Engine {
if c.Now == nil {
c.Now = time.Now
}
if c.Threshold < 1 {
c.Threshold = 5
}
if c.MaxPerMin < 1 {
c.MaxPerMin = 60
}
if c.Resolve == nil {
c.Resolve = func(h string) []netip.Addr {
if a, err := netip.ParseAddr(h); err == nil {
return []netip.Addr{a.Unmap()}
}
return nil
}
}
e := &Engine{cfg: c, log: &logFile{path: c.Path}, ch: make(chan item, 4096), ips: map[netip.Addr]*ipState{},
bans: map[netip.Addr]banRec{}, would: map[netip.Addr]int64{}, skipSeen: map[netip.Addr]int64{},
counts: Counts{Skipped: map[string]int{}}}
e.hostIPs = map[string][]netip.Addr{}
e.excl = Exclusions{Trusted: c.Trusted, Peers: map[netip.Addr]bool{}, Infra: map[netip.Addr]bool{}}
e.refreshPeers()
e.loadState()
return e
}
// Mode returns the mode of the engine.
func (e *Engine) Mode() string { return e.cfg.Mode }
// Host is the name of this instance.
func (e *Engine) Host() string { return e.cfg.Host }
// Share reports whether decisions are exchanged with peers.
func (e *Engine) Share() bool { return e.cfg.Share }
// Threshold is the attack-event threshold in use.
func (e *Engine) Threshold() int { return e.cfg.Threshold }
// LogPath is the decision file.
func (e *Engine) LogPath() string { return e.cfg.Path }
// Observe is the ingestion hook: cheap, never blocks; a full queue drops the
// event and counts it.
func (e *Engine) Observe(ev core.Event, fam string) {
switch ev.Cat {
case core.Ban, core.SSHFail, core.Scanner, core.Exploit, core.BruteForce:
case core.OK:
if ev.FetchDest != "document" || ev.Status < 200 || ev.Status > 299 {
return
}
default:
return
}
select {
case e.ch <- item{ev, fam}:
default:
e.dropQ.Add(1)
}
}
// Run processes events until ctx is done.
func (e *Engine) Run(ctx context.Context) {
flush := time.NewTicker(5 * time.Second)
peers := time.NewTicker(peerRefresh)
defer flush.Stop()
defer peers.Stop()
defer e.log.close()
for {
select {
case <-ctx.Done():
e.saveState()
return
case it := <-e.ch:
e.process(it.ev, it.fam)
case <-flush.C:
e.maybeSave()
case <-peers.C:
e.refreshPeers()
}
}
}
// resolveKeep resolves h; an empty answer (DNS failure) keeps the last good one.
func (e *Engine) resolveKeep(h string, into map[netip.Addr]bool) {
as := e.cfg.Resolve(h)
e.mu.Lock()
if len(as) == 0 {
as = e.hostIPs[h]
} else {
e.hostIPs[h] = as
}
e.mu.Unlock()
for _, a := range as {
into[a.Unmap()] = true
}
}
func (e *Engine) refreshPeers() {
m := map[netip.Addr]bool{}
for _, h := range e.cfg.PeerHosts {
e.resolveKeep(h, m)
}
infra := map[netip.Addr]bool{}
for _, h := range e.cfg.InfraHosts {
e.resolveKeep(h, infra)
}
la := e.cfg.LocalAddrs
if la == nil {
la = interfaceAddrs
}
for _, a := range la() {
infra[a.Unmap()] = true
}
e.mu.Lock()
e.excl.Peers = m
e.excl.Infra = infra
e.mu.Unlock()
}
func (e *Engine) stateOf(a netip.Addr) *ipState {
st := e.ips[a]
if st == nil {
if len(e.ips) >= maxIPs {
e.evict()
}
st = &ipState{}
e.ips[a] = st
}
return st
}
func (e *Engine) evict() {
cut := e.cfg.Now().Add(-24 * time.Hour).Unix()
for a, st := range e.ips {
if max(st.lastAttack, st.f2bAt, st.legit) < cut {
delete(e.ips, a)
}
}
for a := range e.ips {
if len(e.ips) < maxIPs/2 {
break
}
delete(e.ips, a)
}
if len(e.skipSeen) > 10000 {
e.skipSeen = map[netip.Addr]int64{}
}
}
// trimMaps prunes would (expired or older than 24 h) and bans (older than 30 d)
// and caps both at maxTracked, dropping the least recent first; the lock is held.
func (e *Engine) trimMaps(now time.Time) {
cutW := now.Unix()
for a, u := range e.would {
if u < cutW || u < now.Add(-24*time.Hour).Unix() {
delete(e.would, a)
}
}
if len(e.would) > maxTracked {
type kv struct {
a netip.Addr
t int64
}
l := make([]kv, 0, len(e.would))
for a, u := range e.would {
l = append(l, kv{a, u})
}
sort.Slice(l, func(i, j int) bool { return l[i].t < l[j].t })
for _, x := range l[:len(l)-maxTracked/2] {
delete(e.would, x.a)
}
}
cutB := now.Add(-30 * 24 * time.Hour).Unix()
for a, b := range e.bans {
if b.Last < cutB {
delete(e.bans, a)
}
}
if len(e.bans) > maxTracked {
type kv struct {
a netip.Addr
t int64
}
l := make([]kv, 0, len(e.bans))
for a, b := range e.bans {
l = append(l, kv{a, b.Last})
}
sort.Slice(l, func(i, j int) bool { return l[i].t < l[j].t })
for _, x := range l[:len(l)-maxTracked/2] {
delete(e.bans, x.a)
}
}
}
// process handles one classified event (called by Run, or directly by tests).
func (e *Engine) process(ev core.Event, fam string) {
a, err := netip.ParseAddr(ev.IP)
if err != nil {
return
}
a = a.Unmap().WithZone("")
now := e.cfg.Now()
ts := ev.Time.Unix()
e.mu.Lock()
defer e.mu.Unlock()
switch {
case ev.Cat == core.Ban:
if ts < now.Add(-30*24*time.Hour).Unix() {
return
}
st := e.stateOf(a)
switch {
case ev.Unban:
st.banned = 0
default:
if ev.Jail == "urutau" { // our own decision, enforced by the host jail
st.urutauAt = max(st.urutauAt, ts)
} else {
st.banned = max(st.banned, ev.Time.Add(banAssume).Unix())
st.f2bAt = max(st.f2bAt, ts)
}
}
return
case LegitVisit(ev):
if ts >= now.Add(-LegitWindow).Unix() {
e.stateOf(a).legit = max(e.stateOf(a).legit, ts)
}
return
case ev.Cat == core.SSHFail:
case CountsAsAttack(ev):
default:
return
}
if ts < now.Add(-30*24*time.Hour).Unix() {
return
}
st := e.stateOf(a)
st.lastAttack = max(st.lastAttack, ts)
if ts < now.Add(-Window).Unix() { // a replayed old event: coverage only
return
}
cut := now.Add(-Window).Unix()
slug, crit := attackSlug(ev, fam)
if ev.Cat == core.SSHFail {
st.ssh = prune(append(st.ssh, ts), cut)
} else {
st.ev = append(st.ev, aevt{ts, slug})
k := 0
for _, x := range st.ev {
if x.ts >= cut {
st.ev[k] = x
k++
}
}
st.ev = st.ev[:k]
if len(st.ev) > maxEvents {
st.ev = st.ev[len(st.ev)-maxEvents:]
}
}
if ev.UA != "" && len(st.uas) < 3 {
ua := ev.UA
if len(ua) > 200 {
ua = ua[:200]
}
dup := false
for _, u := range st.uas {
dup = dup || u == ua
}
if !dup {
st.uas = append(st.uas, ua)
}
}
crits := 0
for _, x := range st.ev {
if criticalReasons[x.slug] {
crits++
}
}
in := Input{Now: now, Attacks: len(st.ev), Top: topSlug(st.ev), SSHFails: len(st.ssh), Crits: crits,
Legit: st.legit >= now.Add(-LegitWindow).Unix(), Exclude: e.excl.Excluded(a)}
if crit {
in.Crit = slug
}
e.fill(a, st, &in, now)
d := Decide(in, Params{Threshold: e.cfg.Threshold})
if d.Action == ActBan && e.cfg.Crawler != nil && len(st.uas) > 0 && e.cfg.Crawler(a.String(), st.uas) {
in.Exclude = SkipCrawler
d = Decide(in, Params{Threshold: e.cfg.Threshold})
}
e.apply(a, st, d, "local", now)
}
func (e *Engine) fill(a netip.Addr, st *ipState, in *Input, now time.Time) {
in.Banned = st.banned > now.Unix()
if b, ok := e.bans[a]; ok {
in.Offences = b.Offences
if b.Until > now.Unix() && e.cfg.Mode == ModeOn {
in.Active = true
}
if now.Unix() > b.Until+30*24*3600 {
in.Offences = 0
}
}
if u, ok := e.would[a]; ok && u > now.Unix() && e.cfg.Mode == ModeObserve {
in.Active = true
}
}
func prune(l []int64, cut int64) []int64 {
k := 0
for _, t := range l {
if t >= cut {
l[k] = t
k++
}
}
l = l[:k]
if len(l) > maxEvents {
l = l[len(l)-maxEvents:]
}
return l
}
func topSlug(evs []aevt) string {
cnt := map[string]int{}
best, bn := "", 0
for _, x := range evs {
cnt[x.slug]++
if cnt[x.slug] >= bn {
best, bn = x.slug, cnt[x.slug]
}
}
return best
}
// apply records the outcome of a decision; the lock is held.
func (e *Engine) apply(a netip.Addr, st *ipState, d Decision, src string, now time.Time) {
switch d.Action {
case ActSkip, ActAlready:
if until, ok := e.skipSeen[a]; ok && until > now.Unix() {
return
}
e.skipSeen[a] = now.Add(skipQuiet).Unix()
r := Recent{T: now.Unix(), IP: a.String(), Action: "skip", SkipReason: d.Skip, Src: src}
if d.Action == ActAlready {
e.counts.AlreadyBlocked++
r.SkipReason = "already_blocked"
} else {
e.counts.Skipped[d.Skip]++
}
e.addRecent(a, r)
case ActBan:
e.counts.Decided++
m := now.Unix() / 60
if m != e.minute {
e.minute, e.inMinute = m, 0
}
if e.inMinute >= e.cfg.MaxPerMin {
e.counts.DroppedRate++
return
}
e.inMinute++
r := Recent{T: now.Unix(), IP: a.String(), Reason: d.Reason, Score: d.Score, TTL: int(d.TTL / time.Second), Src: src}
if e.cfg.Mode != ModeOn {
r.Action = "would_ban"
if len(e.would) >= maxTracked {
e.trimMaps(now)
}
e.would[a] = now.Add(d.TTL).Unix()
st.wouldAt = now.Unix()
e.addRecent(a, r)
return
}
line, err := FormatLine(now, a, d.Reason, d.Score, d.TTL, e.cfg.Host, src)
if err == nil {
err = e.log.write(line)
}
if err != nil {
e.counts.WriteErrors++
return
}
r.Action = "ban"
e.counts.Written++
if len(e.bans) >= maxTracked {
e.trimMaps(now)
}
b := e.bans[a]
if now.Unix() > b.Until+30*24*3600 {
b.Offences = 0
}
if src == "local" {
b.Offences++
e.shared = append(e.shared, Wire{T: now.Unix(), IP: a.String(), Reason: d.Reason, Score: d.Score, TTL: r.TTL})
if len(e.shared) > MaxWire {
e.shared = e.shared[len(e.shared)-MaxWire:]
}
}
b.Until, b.Last = now.Add(d.TTL).Unix(), now.Unix()
e.bans[a] = b
st.urutauAt = now.Unix()
e.dirty = true
e.addRecent(a, r)
}
}
func (e *Engine) addRecent(a netip.Addr, r Recent) {
if e.cfg.Geo != nil {
r.CC, r.ASN, r.Org = e.cfg.Geo(a.String())
}
e.recent = append(e.recent, r)
if len(e.recent) > maxRecent*2 {
e.recent = append([]Recent(nil), e.recent[len(e.recent)-maxRecent:]...)
}
}
// LocalSince returns the decisions this instance wrote since the unix time.
func (e *Engine) LocalSince(since int64) []Wire {
e.mu.Lock()
defer e.mu.Unlock()
out := []Wire{}
for _, w := range e.shared {
if w.T >= since {
out = append(out, w)
}
}
return out
}
// AcceptPeer applies decisions received from a peer, after this instance's own
// exclusions. It returns how many were accepted for the policy (written or
// would-ban) and how many were refused as malformed.
func (e *Engine) AcceptPeer(name string, in []Wire) (accepted, invalid int) {
if len(in) > MaxWire {
in = in[:MaxWire]
}
src := "peer:" + token(name, "peer")
now := e.cfg.Now()
e.mu.Lock()
defer e.mu.Unlock()
for _, w := range in {
a, err := netip.ParseAddr(w.IP)
if err != nil || !ValidReason(w.Reason) || !Public(a) {
invalid++
continue
}
a = a.Unmap().WithZone("")
ttl := min(time.Duration(min(max(w.TTL, 60), 7*24*3600))*time.Second, maxPeerTTL)
if w.T > 0 && w.T+int64(ttl/time.Second) < now.Unix() {
continue // already expired
}
st := e.stateOf(a)
in := Input{Now: now, Crit: w.Reason, Crits: CritHits, Exclude: e.excl.Excluded(a)}
if in.Exclude == "" && st.lastAttack < now.Add(-peerConfirmAge).Unix() {
in.Exclude = SkipUnconfirmed // a peer's word alone never bans: this node must have seen the address attack
}
e.fill(a, st, &in, now)
d := Decide(in, Params{})
if d.Action == ActBan {
d.Reason, d.Score, d.TTL = w.Reason, max(0, min(100, w.Score)), ttl
accepted++
}
e.apply(a, st, d, src, now)
}
return accepted, invalid
}
// Report summarizes the activity since the unix time from.
func (e *Engine) Report(from int64) Report {
e.mu.Lock()
defer e.mu.Unlock()
var cv Coverage
for _, st := range e.ips {
if st.lastAttack < from {
continue
}
cv.AttackIPs++
switch {
case st.f2bAt > 0 && st.f2bAt >= from:
cv.BlockedByFirewall++
case st.urutauAt > 0 && st.urutauAt >= from:
cv.BlockedByUrutau++
case st.wouldAt > 0 && st.wouldAt >= from:
cv.WouldBlock++
default:
cv.Unblocked++
}
}
c := e.counts
c.Skipped = map[string]int{SkipTrusted: 0, SkipPrivate: 0, SkipCrawler: 0, SkipLegit: 0, SkipPeer: 0, SkipInfra: 0, SkipUnconfirmed: 0}
for k, v := range e.counts.Skipped {
c.Skipped[k] = v
}
c.DroppedQueue = e.dropQ.Load()
rec := []Recent{}
for i := len(e.recent) - 1; i >= 0 && len(rec) < maxRecent; i-- {
if e.recent[i].T >= from {
rec = append(rec, e.recent[i])
}
}
return Report{Coverage: cv, Counts: c, Recent: rec}
}
type stateFile struct {
V int `json:"v"`
Bans map[string]banRec `json:"bans"`
}
func (e *Engine) loadState() {
if e.cfg.StatePath == "" {
return
}
b, err := os.ReadFile(e.cfg.StatePath)
if err != nil {
return
}
var sf stateFile
if json.Unmarshal(b, &sf) != nil {
return
}
cut := e.cfg.Now().Add(-30 * 24 * time.Hour).Unix()
for k, v := range sf.Bans {
if a, err := netip.ParseAddr(k); err == nil && v.Last >= cut && v.Offences >= 0 && v.Offences < 1000 {
e.bans[a.Unmap()] = v
}
}
}
// maybeSave writes the state at most every saveEvery.
func (e *Engine) maybeSave() {
if e.cfg.Now().Sub(e.lastSave) < saveEvery {
return
}
e.saveState()
}
// saveState writes enforce.json atomically when something changed.
func (e *Engine) saveState() {
if e.cfg.StatePath == "" {
return
}
e.mu.Lock()
if !e.dirty {
e.mu.Unlock()
return
}
e.lastSave = e.cfg.Now()
e.trimMaps(e.lastSave)
sf := stateFile{V: 1, Bans: map[string]banRec{}}
for a, b := range e.bans {
sf.Bans[a.String()] = b
}
e.dirty = false
e.mu.Unlock()
b, _ := json.Marshal(sf)
tmp := e.cfg.StatePath + ".tmp"
if err := os.MkdirAll(filepath.Dir(tmp), 0o700); err == nil {
if err = os.WriteFile(tmp, b, 0o600); err == nil {
if err = os.Rename(tmp, e.cfg.StatePath); err == nil {
return
}
}
}
e.mu.Lock()
e.dirty = true
e.mu.Unlock()
}
+78
View File
@@ -0,0 +1,78 @@
package enforce
import (
"net"
"net/netip"
)
// SkipInfra is the skip reason of the fixed infrastructure allowlist.
const SkipInfra = "infrastructure"
func mustPrefixes(l ...string) []netip.Prefix {
out := make([]netip.Prefix, 0, len(l))
for _, s := range l {
out = append(out, netip.MustParsePrefix(s))
}
return out
}
// cloudflare are the published Cloudflare ranges (https://www.cloudflare.com/ips/).
// They are never banned: behind the CDN the "client" of a request is an edge
// address shared by thousands of innocent visitors.
var cloudflare = mustPrefixes(
"173.245.48.0/20", "103.21.244.0/22", "103.22.200.0/22", "103.31.4.0/22", "141.101.64.0/18",
"108.162.192.0/18", "190.93.240.0/20", "188.114.96.0/20", "197.234.240.0/22", "198.41.128.0/17",
"162.158.0.0/15", "104.16.0.0/13", "104.24.0.0/14", "172.64.0.0/13", "131.0.72.0/22",
"2400:cb00::/32", "2606:4700::/32", "2803:f800::/32", "2405:b500::/32", "2405:8100::/32",
"2a06:98c0::/29", "2c0f:f248::/32")
// publicResolvers are the well known public DNS resolvers.
var publicResolvers = func() map[netip.Addr]bool {
m := map[netip.Addr]bool{}
for _, s := range []string{"1.1.1.1", "1.0.0.1", "8.8.8.8", "8.8.4.4", "9.9.9.9", "149.112.112.112",
"208.67.222.222", "208.67.220.220", "2606:4700:4700::1111", "2606:4700:4700::1001",
"2001:4860:4860::8888", "2001:4860:4860::8844", "2620:fe::fe", "2620:fe::9",
"2620:119:35::35", "2620:119:53::53"} {
m[netip.MustParseAddr(s)] = true
}
return m
}()
// IsCloudflare reports whether a belongs to a Cloudflare range.
func IsCloudflare(a netip.Addr) bool {
a = a.Unmap()
for _, p := range cloudflare {
if p.Contains(a) {
return true
}
}
return false
}
// IsInfrastructure reports whether a is in the fixed allowlist (Cloudflare, public resolvers).
func IsInfrastructure(a netip.Addr) bool {
a = a.Unmap()
return publicResolvers[a] || IsCloudflare(a)
}
// interfaceAddrs lists the addresses of the local interfaces.
func interfaceAddrs() []netip.Addr {
var out []netip.Addr
addrs, err := net.InterfaceAddrs()
if err != nil {
return nil
}
for _, x := range addrs {
var ip net.IP
switch v := x.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
if a, ok := netip.AddrFromSlice(ip); ok {
out = append(out, a.Unmap())
}
}
return out
}
+145
View File
@@ -0,0 +1,145 @@
package enforce
import (
"errors"
"fmt"
"net/netip"
"os"
"path/filepath"
"strings"
"sync"
"time"
)
// MaxLogBytes is the size at which the decision file is rotated (one .1 kept).
const MaxLogBytes = 20 << 20
// token reduces s to [A-Za-z0-9._-] (at most 32 bytes); fallback if nothing is left.
func token(s, fallback string) string {
var b strings.Builder
for i := 0; i < len(s) && b.Len() < 32; i++ {
c := s[i]
if c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '.' || c == '_' || c == '-' {
b.WriteByte(c)
}
}
if b.Len() == 0 {
return fallback
}
return b.String()
}
// FormatLine renders one decision. Nothing the attacker controls enters it:
// the address is re-formatted by netip, the reason must be a fixed slug and the
// host and source names are reduced to a safe alphabet.
func FormatLine(t time.Time, ip netip.Addr, reason string, score int, ttl time.Duration, host, src string) (string, error) {
ip = ip.Unmap().WithZone("")
if !ip.IsValid() {
return "", errors.New("invalid ip")
}
if !ValidReason(reason) {
return "", errors.New("invalid reason")
}
score = max(0, min(100, score))
secs := max(1, int64(ttl/time.Second))
if src != "local" {
src = "peer:" + token(strings.TrimPrefix(src, "peer:"), "peer")
}
return fmt.Sprintf("%s urutau decision=ban ip=%s reason=%s score=%d ttl=%d host=%s src=%s\n",
t.UTC().Format("2006-01-02T15:04:05Z"), ip.String(), reason, score, secs, token(host, "urutau"), src), nil
}
// logFile appends to the decision file, rotating by size.
type logFile struct {
mu sync.Mutex
path string
f *os.File
size int64
}
func (l *logFile) open() error {
if err := os.MkdirAll(filepath.Dir(l.path), 0o750); err != nil {
return err
}
f, err := os.OpenFile(l.path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o640)
if err != nil {
return err
}
fi, err := f.Stat()
if err != nil {
f.Close()
return err
}
l.f, l.size = f, fi.Size()
return nil
}
func (l *logFile) write(line string) error {
l.mu.Lock()
defer l.mu.Unlock()
if l.f == nil {
if err := l.open(); err != nil {
return err
}
}
if l.size+int64(len(line)) > MaxLogBytes {
l.f.Close()
l.f = nil
if err := os.Rename(l.path, l.path+".1"); err != nil {
return err
}
if err := l.open(); err != nil {
return err
}
}
n, err := l.f.WriteString(line)
l.size += int64(n)
if err != nil {
l.f.Close()
l.f = nil
}
return err
}
func (l *logFile) close() {
l.mu.Lock()
defer l.mu.Unlock()
if l.f != nil {
l.f.Close()
l.f = nil
}
}
// Writable reports whether the decision file can be appended to, without
// creating anything: an existing file is opened for writing, otherwise a
// temporary file is created next to where it would live.
func Writable(path string) bool {
if path == "" {
return false
}
if _, err := os.Stat(path); err == nil {
f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND, 0)
if err != nil {
return false
}
f.Close()
return true
}
dir := filepath.Dir(path)
if _, err := os.Stat(dir); err != nil {
// the directory is created on first write: check the nearest parent
for dir != "/" && dir != "." {
dir = filepath.Dir(dir)
if _, err := os.Stat(dir); err == nil {
break
}
}
}
f, err := os.CreateTemp(dir, ".urutau-w-*")
if err != nil {
return false
}
f.Close()
os.Remove(f.Name())
return true
}
+280
View File
@@ -0,0 +1,280 @@
// Package enforce is the optional "second firewall": it decides which source
// addresses deserve a ban and appends one line per decision to a file. The
// process never gains privileges: a host side fail2ban jail reads the file.
package enforce
import (
"net/netip"
"os"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
)
// Modes.
const (
ModeOff = "off"
ModeObserve = "observe"
ModeOn = "on"
)
// Fixed reason slugs. Anything else is refused (also from peers).
const (
ReasonScannerFlood = "scanner-flood"
ReasonExploitFlood = "exploit-flood"
ReasonWebBrute = "web-bruteforce"
ReasonWPBrute = "wp-bruteforce"
ReasonSSHBrute = "ssh-bruteforce"
ReasonRCE = "rce"
ReasonTraversal = "path-traversal"
ReasonEnvProbe = "env-probe"
ReasonVCSProbe = "vcs-probe"
ReasonWebshell = "webshell"
ReasonSQLi = "sqli"
ReasonLog4Shell = "log4shell"
)
var reasons = map[string]bool{
ReasonScannerFlood: true, ReasonExploitFlood: true, ReasonWebBrute: true, ReasonWPBrute: true,
ReasonSSHBrute: true, ReasonRCE: true, ReasonTraversal: true, ReasonEnvProbe: true,
ReasonVCSProbe: true, ReasonWebshell: true, ReasonSQLi: true, ReasonLog4Shell: true,
}
// ValidReason reports whether s is one of the fixed slugs.
func ValidReason(s string) bool { return reasons[s] }
// criticalFam maps the attack families that justify a ban on one hit.
var criticalFam = map[string]string{
intel.FamRCE: ReasonRCE,
intel.FamTraversal: ReasonTraversal,
intel.FamEnvCreds: ReasonEnvProbe,
intel.FamVCS: ReasonVCSProbe,
intel.FamWebshell: ReasonWebshell,
intel.FamSQLi: ReasonSQLi,
intel.FamLog4Shell: ReasonLog4Shell,
}
// Policy constants.
const (
Window = 10 * time.Minute
LegitWindow = 24 * time.Hour
SSHThreshold = 5
// CritHits is how many critical events of one address (in Window) justify a ban.
CritHits = 2
)
// ttls is the advisory duration by number of previous bans.
var ttls = []time.Duration{time.Hour, 6 * time.Hour, 24 * time.Hour, 7 * 24 * time.Hour}
// TTLFor is the advisory TTL of a ban preceded by n earlier bans.
func TTLFor(offences int) time.Duration {
if offences < 0 {
offences = 0
}
if offences >= len(ttls) {
offences = len(ttls) - 1
}
return ttls[offences]
}
// Skip reasons, also the keys of Counts.Skipped.
const (
SkipTrusted = "trusted"
SkipPrivate = "private"
SkipCrawler = "crawler"
SkipLegit = "legit_visitor"
SkipPeer = "peer"
// SkipUnconfirmed: a peer's decision about an address this node never saw attacking.
SkipUnconfirmed = "peer_unconfirmed"
)
// Actions of a Decision.
const (
ActNone = "" // nothing to do
ActBan = "ban" // write (or would write)
ActSkip = "skip" // excluded
ActAlready = "already" // fail2ban already blocks it
ActActive = "active" // an advisory ban is still valid
)
// Input is everything Decide needs about one address.
type Input struct {
Now time.Time
Attacks int // counted attack events in the window
Top string // reason slug of the dominant attack in the window
SSHFails int // failed SSH logins in the window
Crit string // reason of a critical family hit just seen, "" if none
Crits int // critical events of the address in the window (a single hit is not enough)
Legit bool // a document 2xx from a browser within the last 24 h
Exclude string // Excluded() result or "crawler"
Banned bool // fail2ban already blocks it
Active bool // an advisory ban is still valid
Offences int
}
// Params are the thresholds.
type Params struct{ Threshold int }
// Decision is the verdict of Decide.
type Decision struct {
Action string
Reason string
Score int
TTL time.Duration
Skip string
}
// Decide is the pure policy. It returns ActNone while nothing justifies a ban.
func Decide(in Input, p Params) Decision {
th, sshTh := p.Threshold, SSHThreshold
if th < 1 {
th = 5
}
if in.Legit { // a (forgeable) legitimate visit only relaxes the volumetric thresholds
th, sshTh = th*2, sshTh*2
}
var reason string
score := 0
switch {
case in.Crit != "" && in.Crits >= CritHits:
reason, score = in.Crit, 90
case in.SSHFails >= sshTh:
reason, score = ReasonSSHBrute, min(100, 60+(in.SSHFails-sshTh)*5)
case in.Attacks >= th:
reason, score = in.Top, min(100, 55+(in.Attacks-th)*5)
if !ValidReason(reason) {
reason = ReasonScannerFlood
}
default:
return Decision{}
}
switch {
case in.Exclude != "":
return Decision{Action: ActSkip, Skip: in.Exclude}
case in.Banned:
return Decision{Action: ActAlready}
case in.Active:
return Decision{Action: ActActive}
}
return Decision{Action: ActBan, Reason: reason, Score: score, TTL: TTLFor(in.Offences)}
}
// reservedV4/V6 are special purpose ranges not covered by netip helpers.
var reserved = func() []netip.Prefix {
var out []netip.Prefix
for _, s := range []string{"0.0.0.0/8", "100.64.0.0/10", "192.0.0.0/24", "192.0.2.0/24", "198.18.0.0/15",
"198.51.100.0/24", "203.0.113.0/24", "240.0.0.0/4", "2001:db8::/32", "100::/64", "fc00::/7", "fe80::/10", "ff00::/8"} {
out = append(out, netip.MustParsePrefix(s))
}
return out
}()
// demoReservedPublic is a hidden switch ONLY for the documentation screenshots
// (scripts/screenshots.sh): the demo data uses reserved documentation ranges, which
// production policy rightly treats as private. Never set URUTAU_DEMO_RESERVED_PUBLIC
// outside the screenshot run.
var demoReservedPublic = os.Getenv("URUTAU_DEMO_RESERVED_PUBLIC") == "1"
func demoRanges(p netip.Prefix) bool {
switch p.String() {
case "198.18.0.0/15", "203.0.113.0/24", "198.51.100.0/24", "192.0.2.0/24", "2001:db8::/32":
return true
}
return false
}
// Public reports whether a is a routable unicast address worth blocking.
func Public(a netip.Addr) bool {
a = a.Unmap()
if !a.IsValid() || a.Zone() != "" || a.IsUnspecified() || a.IsLoopback() || a.IsPrivate() || a.IsMulticast() ||
a.IsLinkLocalUnicast() || a.IsLinkLocalMulticast() || a.IsInterfaceLocalMulticast() {
return false
}
for _, p := range reserved {
if demoReservedPublic && demoRanges(p) {
continue
}
if p.Contains(a) {
return false
}
}
return true
}
// Exclusions are the addresses that are never banned.
type Exclusions struct {
Trusted []netip.Prefix // --trusted and --ignore
Peers map[netip.Addr]bool // addresses of the peers
Infra map[netip.Addr]bool // hub, local interfaces (resolved at runtime)
}
var criticalReasons = func() map[string]bool {
m := map[string]bool{}
for _, r := range criticalFam {
m[r] = true
}
return m
}()
// Excluded returns the skip reason of a, or "".
func (x Exclusions) Excluded(a netip.Addr) string {
a = a.Unmap()
if !Public(a) {
return SkipPrivate
}
if x.Peers[a] {
return SkipPeer
}
for _, p := range x.Trusted {
if p.Contains(a) {
return SkipTrusted
}
}
if x.Infra[a] || IsInfrastructure(a) {
return SkipInfra
}
return ""
}
// attackSlug is the reason slug of one attack event, and whether it is critical.
func attackSlug(ev core.Event, fam string) (slug string, crit bool) {
if ev.Cat == core.SSHFail {
return ReasonSSHBrute, false
}
if r, ok := criticalFam[fam]; ok {
return r, true
}
switch {
case fam == intel.FamWordPress:
return ReasonWPBrute, false
case ev.Cat == core.BruteForce:
return ReasonWebBrute, false
case ev.Cat == core.Exploit:
return ReasonExploitFlood, false
}
return ReasonScannerFlood, false
}
// CountsAsAttack reports whether an HTTP event is an attack the policy counts:
// an attack category that was not merely framed, and whose answer is not a
// client, application or proxy error.
func CountsAsAttack(ev core.Event) bool {
if ev.Source != "traefik" || ev.Framed {
return false
}
if ev.Cat != core.Scanner && ev.Cat != core.Exploit && ev.Cat != core.BruteForce {
return false
}
if ev.Status >= 400 {
c := core.ErrorClass(ev, false)
return c == core.ClassAttack || c == core.ClassBlocked
}
return true
}
// LegitVisit reports whether ev is a browser loading a page successfully.
func LegitVisit(ev core.Event) bool {
return ev.Source == "traefik" && ev.Cat == core.OK && ev.Status >= 200 && ev.Status < 300 &&
ev.FetchDest == "document" && !ev.E.Tool && !ev.E.Bot && !ev.Prefetch
}
File diff suppressed because it is too large. Load diff
+236
View File
@@ -0,0 +1,236 @@
package evlog
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
var base = time.Date(2026, 11, 14, 12, 0, 0, 0, time.UTC)
func line(t int64, id uint64, ip, cat string) []byte {
return []byte(fmt.Sprintf(`{"id":%d,"t":%d,"ip":"%s","cat":"%s","source":"traefik","host":"h","domain":"a.example","path":"/.env","status":404}`, id, t, ip, cat))
}
func open(t *testing.T, now *time.Time, max int64) *Log {
t.Helper()
l, err := Open(Options{Dir: filepath.Join(t.TempDir(), "events"), MaxBytes: max, Now: func() time.Time { return *now }})
if err != nil {
t.Fatal(err)
}
return l
}
func TestAppendQueryPaginationAndOrder(t *testing.T) {
now := base
l := open(t, &now, 0)
for i := 0; i < 25; i++ {
l.Append(base.Unix()-int64(i), line(base.Unix()-int64(i), uint64(i+1), "1.2.3.4", "exploit"))
}
l.Append(base.Unix(), line(base.Unix(), 100, "5.6.7.8", "scanner"))
f := Filter{From: base.Unix() - 3600, To: base.Unix() + 10}
var all []uint64
cur := ""
for page := 0; page < 10; page++ {
r, err := l.Query(Query{Filter: f, Limit: 10, Cursor: cur, Desc: true})
if err != nil {
t.Fatal(err)
}
for _, it := range r.Items {
all = append(all, it.Rec.ID)
}
if r.Next == "" {
break
}
cur = r.Next
}
if len(all) != 26 {
t.Fatalf("pagination returned %d events", len(all))
}
seen := map[uint64]bool{}
for _, id := range all {
if seen[id] {
t.Fatal("duplicate across pages")
}
seen[id] = true
}
asc, _ := l.Query(Query{Filter: f, Limit: 5})
for i := 1; i < len(asc.Items); i++ {
if asc.Items[i].Rec.T < asc.Items[i-1].Rec.T {
t.Fatal("ascending order broken")
}
}
if r, _ := l.Query(Query{Filter: Filter{From: f.From, To: f.To, IP: "5.6.7.8"}}); len(r.Items) != 1 {
t.Fatalf("ip filter: %d", len(r.Items))
}
if r, _ := l.Query(Query{Filter: Filter{From: f.From, To: f.To, Cats: map[string]bool{"scanner": true}}}); len(r.Items) != 1 {
t.Fatal("cat filter")
}
if r, _ := l.Query(Query{Filter: Filter{From: f.From, To: f.To, Q: "ENV"}, Limit: 100}); len(r.Items) != 26 || r.TotalEstimate != 26 {
t.Fatalf("q filter %d est %d", len(r.Items), r.TotalEstimate)
}
if _, err := l.Query(Query{Cursor: "!!!"}); !errors.Is(err, ErrCursor) {
t.Fatal("bad cursor must fail")
}
}
func TestRotationCompressionRangeIndexAndRetention(t *testing.T) {
now := base
l := open(t, &now, 0)
old := base.Add(-72 * time.Hour)
for h := 0; h < 24; h++ {
ts := old.Truncate(24 * time.Hour).Add(time.Duration(h) * time.Hour).Unix()
l.Append(ts, line(ts, uint64(h+1), "9.9.9.9", "exploit"))
}
l.Append(base.Unix(), line(base.Unix(), 500, "1.1.1.1", "scanner"))
l.Flush()
now = base.Add(time.Minute)
l.Close()
l.Maintain()
ents, _ := os.ReadDir(l.opt.Dir)
var names []string
for _, e := range ents {
names = append(names, e.Name())
}
joined := strings.Join(names, " ")
if !strings.Contains(joined, ".jsonl.gz") || !strings.Contains(joined, ".idx") {
t.Fatalf("old day must be compressed with an index: %v", names)
}
oldDay := old.Format("2006-01-02")
if _, err := os.Stat(filepath.Join(l.opt.Dir, oldDay+".jsonl")); err == nil {
t.Fatal("plain file of the old day must be gone")
}
day := old.Truncate(24 * time.Hour).Unix()
// whole day, then one hour only (index)
if r, _ := l.Query(Query{Filter: Filter{From: day, To: day + 86399}, Limit: 100}); len(r.Items) != 24 {
t.Fatalf("whole day %d", len(r.Items))
}
var info ScanInfo
n := 0
info = l.Scan(Filter{From: day + 5*3600, To: day + 5*3600 + 100}, 0, false, func(Rec, []byte) bool { n++; return true })
if n != 1 || info.Lines > 2 {
t.Fatalf("hour index must avoid reading the whole day: matched %d lines read %d", n, info.Lines)
}
// a late event for the compressed day is appended as a new member
late := day + 7*3600 + 5
l.Append(late, line(late, 900, "8.8.8.8", "exploit"))
l.Close()
now = base.Add(2 * time.Minute)
l.Maintain()
if r, _ := l.Query(Query{Filter: Filter{From: day, To: day + 86399}, Limit: 100}); len(r.Items) != 25 {
t.Fatalf("late event lost: %d", len(r.Items))
}
if r, _ := l.Query(Query{Filter: Filter{From: day + 7*3600, To: day + 7*3600 + 60}, Limit: 100}); len(r.Items) != 2 {
t.Fatalf("index after append: %d", len(r.Items))
}
// retention
now = base.Add(31 * 24 * time.Hour)
l.Maintain()
if r, _ := l.Query(Query{Filter: Filter{From: day, To: day + 86399}}); len(r.Items) != 0 {
t.Fatal("expired day must be deleted")
}
}
func TestSizeCapDeletesOldestDays(t *testing.T) {
now := base
l := open(t, &now, 700)
for d := 6; d >= 1; d-- {
ts := base.Add(-time.Duration(d) * 24 * time.Hour).Unix()
for i := 0; i < 8; i++ {
l.Append(ts+int64(i), line(ts+int64(i), uint64(d*100+i), "1.1.1.1", "exploit"))
}
l.Close()
l.Maintain()
}
if sz := l.dirSize(); sz > 700 {
t.Fatalf("size %d over the cap", sz)
}
fs := l.list()
if len(fs) == 0 || len(fs) == 6 {
t.Fatalf("expected some, not all, days to remain: %d", len(fs))
}
if fs[len(fs)-1].day != (base.Unix()-86400)/86400 {
t.Fatal("the newest days must survive")
}
}
func TestCorruptedLinesAreIgnored(t *testing.T) {
now := base
l := open(t, &now, 0)
l.Append(base.Unix(), line(base.Unix(), 1, "1.1.1.1", "exploit"))
l.Close()
p := l.path(base.Unix() / 86400)
f, _ := os.OpenFile(p, os.O_APPEND|os.O_WRONLY, 0o600)
f.WriteString("{not json\n\x00\x01garbage\n" + strings.Repeat("x", 300<<10) + "\n")
f.Close()
l2, _ := Open(Options{Dir: l.opt.Dir, Now: func() time.Time { return now }})
l2.Append(base.Unix()+1, line(base.Unix()+1, 2, "1.1.1.1", "exploit"))
if r, err := l2.Query(Query{Filter: Filter{From: base.Unix() - 10, To: base.Unix() + 10}}); err != nil || len(r.Items) != 2 {
t.Fatalf("corruption must be skipped: %v %d", err, len(r.Items))
}
if l2.LastID() != 1 {
t.Fatalf("last id %d", l2.LastID())
}
// a truncated gzip tail is tolerated too
now = base.Add(48 * time.Hour)
l2.Close()
l2.Maintain()
gz := filepath.Join(l.opt.Dir, base.Format("2006-01-02")+".jsonl.gz")
b, _ := os.ReadFile(gz)
os.WriteFile(gz, b[:len(b)-6], 0o600)
l2.Query(Query{Filter: Filter{From: base.Unix() - 10, To: base.Unix() + 10}})
}
type failFile struct{}
func (failFile) Write([]byte) (int, error) { return 0, errors.New("no space left on device") }
func (failFile) Sync() error { return errors.New("no space") }
func (failFile) Close() error { return nil }
func TestDiskFullDoesNotStopTheService(t *testing.T) {
now := base
l := open(t, &now, 0)
l.create = func(string) (file, error) { return failFile{}, nil }
for i := 0; i < 5000; i++ { // more than the bufio buffer: the write error surfaces
l.Append(base.Unix(), line(base.Unix(), uint64(i+1), "1.1.1.1", "exploit"))
}
if l.Dropped() == 0 {
t.Fatal("events must be counted as dropped")
}
l.create = func(string) (file, error) { return nil, errors.New("disk full") }
l.Append(base.Unix(), line(base.Unix(), 1, "1.1.1.1", "exploit"))
l.Flush()
l.Close()
// recovery: the disk works again
l.create = func(p string) (file, error) { return os.OpenFile(p, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600) }
l.Append(base.Unix(), line(base.Unix(), 7777, "2.2.2.2", "exploit"))
if r, _ := l.Query(Query{Filter: Filter{From: base.Unix() - 5, To: base.Unix() + 5, IP: "2.2.2.2"}}); len(r.Items) != 1 {
t.Fatalf("log must recover: %d", len(r.Items))
}
}
func TestDayCapOnlyCounts(t *testing.T) {
now := base
l, _ := Open(Options{Dir: filepath.Join(t.TempDir(), "e"), DayCap: 10, Now: func() time.Time { return now }})
for i := 0; i < 30; i++ {
l.Append(base.Unix(), line(base.Unix(), uint64(i+1), "1.1.1.1", "exploit"))
}
if r, _ := l.Query(Query{Filter: Filter{From: base.Unix() - 5, To: base.Unix() + 5}, Limit: 100}); len(r.Items) != 10 || l.Dropped() != 20 {
t.Fatalf("stored %d dropped %d", len(r.Items), l.Dropped())
}
}
func TestIDsSurviveRestart(t *testing.T) {
now := base
l := open(t, &now, 0)
l.Append(base.Unix(), line(base.Unix(), 41, "1.1.1.1", "exploit"))
l.Close()
l2, _ := Open(Options{Dir: l.opt.Dir})
if l2.NextID() != 42 {
t.Fatal("ids must continue after a restart")
}
}
+64
View File
@@ -0,0 +1,64 @@
package evlog
import (
"bytes"
"strings"
"testing"
"time"
)
func TestQueryBudgetDeadlineAndSemaphore(t *testing.T) {
now := base
l := open(t, &now, 0)
for i := 0; i < 400; i++ {
l.Append(base.Unix()-int64(i), line(base.Unix()-int64(i), uint64(i+1), "1.2.3.4", "exploit"))
}
f := Filter{From: base.Unix() - 3600, To: base.Unix() + 10}
defer func(b int64, d time.Duration) { queryBudget, queryDeadline = b, d }(queryBudget, queryDeadline)
queryBudget = 2000 // a few lines: the budget is checked per line
r, err := l.Query(Query{Filter: f, Limit: 1000})
if err != nil || !r.Truncated || len(r.Items) >= 400 || len(r.Items) == 0 {
t.Fatalf("budget: %v truncated %v items %d", err, r.Truncated, len(r.Items))
}
queryBudget = 256 << 20
queryDeadline = time.Nanosecond
if r, _ = l.Query(Query{Filter: f, Limit: 1000}); !r.Truncated {
t.Fatal("a query past its deadline must come back truncated")
}
queryDeadline = 10 * time.Second
for i := 0; i < cap(querySem); i++ {
querySem <- struct{}{}
}
if _, err = l.Query(Query{Filter: f}); err != ErrBusy {
t.Fatalf("busy: %v", err)
}
for i := 0; i < cap(querySem); i++ {
<-querySem
}
if r, err = l.Query(Query{Filter: f, Limit: 1000}); err != nil || len(r.Items) != 400 || r.Truncated {
t.Fatalf("normal: %v %d", err, len(r.Items))
}
}
func TestOversizedLinesCountAgainstTheBudget(t *testing.T) {
big := strings.Repeat("x", 3*maxLine)
var in bytes.Buffer
for i := 0; i < 10; i++ {
in.WriteString(big + "\n")
}
in.WriteString(`{"t":1,"ip":"1.1.1.1"}` + "\n")
var nb int64
lines := 0
eachLine(&in, func([]byte) bool { lines++; return true }, &nb)
if lines != 1 || nb < 10*3*maxLine {
t.Fatalf("discarded lines must be counted: lines %d bytes %d", lines, nb)
}
// a stream of oversized lines is cut at the hard stop, not read forever
var nb2 int64 = hardStop - 10
var in2 bytes.Buffer
in2.WriteString(big + "\n")
if eachLine(&in2, func([]byte) bool { return true }, &nb2) {
t.Fatal("must stop past the hard limit")
}
}
+46
View File
@@ -0,0 +1,46 @@
package fed
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
)
// Get fetches a peer path with the peer token and decodes the JSON answer.
func (h *Hub) Get(ctx context.Context, p Peer, path string, out any) error {
_, err := h.get(ctx, p, path, out)
return err
}
// PostJSON sends v as JSON to a peer path with the peer token.
func (h *Hub) PostJSON(ctx context.Context, p Peer, path string, v any) error {
b, err := json.Marshal(v)
if err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, p.URL+path, bytes.NewReader(b))
if err != nil {
return err
}
tok := h.Token
if p.Token != "" {
tok = p.Token
}
if tok != "" {
req.Header.Set("Authorization", "Bearer "+tok)
}
req.Header.Set("Content-Type", "application/json")
resp, err := h.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
if resp.StatusCode/100 != 2 {
return fmt.Errorf("HTTP %d", resp.StatusCode)
}
return nil
}
+42
View File
@@ -0,0 +1,42 @@
package fed
import (
"context"
"encoding/json"
"fmt"
"sync"
)
// EgressFor asks the online peers (or one) for their egress analysis of the
// window [from, to] (unix seconds). The raw answers are untrusted: the caller
// decodes and sanitizes them.
func (h *Hub) EgressFor(ctx context.Context, from, to int64, only string) map[string]json.RawMessage {
out := map[string]json.RawMessage{}
var mu sync.Mutex
var wg sync.WaitGroup
for _, p := range h.Peers {
if only != "" && only != p.Name {
continue
}
h.mu.RLock()
st := h.state[p.Name]
online := st != nil && st.online
h.mu.RUnlock()
if !online {
continue
}
wg.Add(1)
go func(p Peer) {
defer wg.Done()
var raw json.RawMessage
if _, err := h.get(ctx, p, fmt.Sprintf("/api/v1/peer/egress?from=%d&to=%d", from, to), &raw); err != nil {
return
}
mu.Lock()
out[p.Name] = raw
mu.Unlock()
}(p)
}
wg.Wait()
return out
}
+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() }
Loaded 100 of 436 files, more files were not shown because too many files have changed in this diff. Show more