Compare commits

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

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

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 22:39:33 -03:00
134 changed files with 16606 additions and 200 deletions

No files matched your search

+1
View File
@@ -25,3 +25,4 @@ __pycache__/
# Runtime pid files left by local test scripts
*.pid
pid
+32 -4
View File
@@ -6,12 +6,33 @@ Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versio
## [Unreleased]
## [1.1.1] - 2026-11-14
## [1.4.0] - 2026-11-15
### Fixed
### Added
- 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.
- Second firewall (optional, `URUTAU_ENFORCE=off|observe|on`): Urutau decides which attacking addresses to block and writes the decisions to a file; the host fail2ban (jail `urutau`) applies them. Urutau gets no privileges. Observe mode shows what would be blocked. Optional decision sharing between hub and peers (`URUTAU_ENFORCE_SHARE`), applied only when the receiving server also saw the address attack. Never blocks trusted addresses, private ranges, CDN (Cloudflare) and public resolver ranges, peers or the server itself. The ban only drops connections the address starts, so replies to the server's own connections keep flowing.
- Egress analysis (`URUTAU_EGRESS`): new outbound connections of the host and containers, logged by nftables, are checked for beaconing (regular conversations with one destination), mining, IRC and SMTP ports, contact with addresses that attacked the server or Tor exits, DNS outside the allowed resolvers, unauthorised outbound scans and new countries. Workloads by network or container name (`URUTAU_EGRESS_WORKLOADS`); a `scanner` workload (an authorised surface scanner) has only its scan-shaped traffic summarised, everything else is judged like any other workload, so its beaconing is still detected.
- Host kit in `deploy/host` (nftables table, rsyslog, logrotate, container map, fail2ban filter, action and jail, `install.sh`).
- New page Outbound traffic and a Second firewall section in Defense.
- HTML report (`/api/v1/report?format=html`): cover, executive summary in plain language, rule-based recommendations, threats, geography, errors and health, visitors, defense, second firewall and outbound traffic, printable on A4. The Reports page downloads or prints it.
- Screenshot script covers every page.
## [1.3.0] - 2026-11-14
### Added
- **Many more pages**, grouped in the side rail: Monitor (Overview, Live, Services), Investigate (IPs, Sessions, Campaigns, Replay, Event search), Analyze (Threats, MITRE ATT&CK, Geography, Evolution, Concentration, Survival, Traffic, Where errors come from, Protocols and TLS), Operate (Defense, Sources and hosts, Integrity) and Reports. A glossary: a "?" button next to metrics and categories explains what each one means and what to do about it.
- **Service health:** per-service SLO (target 99.5%), error budget, burn rate (1 h and 6 h) and Apdex, from the Traefik router and service names.
- **Error classes:** every error is classified as `app`, `proxy`, `blocked`, `attack`, `bot`, `client` or `unknown`, so a 5xx from your app is told apart from a broken link or a scanner. The Traefik fields `OriginStatus`, `OriginDuration`, `Overhead`, `OriginContentSize`, `RetryAttempts`, `RouterName`, `ServiceName`, `RequestProtocol`, `RequestScheme`, `TLSVersion` and `TLSCipher` are read when present.
- **Episodes and survival:** time to ban and Kaplan-Meier survival curves computed over attack episodes.
- **New routes** (user only, never the peer token): `GET /api/v1/techniques`, `/evolution`, `/concentration`, `/survival`, `/sessions/funnel`, `/campaigns`, `/campaigns/{id}`, `/defense`, `/errors`, `/integrity`, `/report`, `/services`, `/services/{svc}` and `/protocols`.
- **Legitimate visits stream:** `GET /api/v1/events/stream?visits=1` also sends anonymous visit events (no address, User-Agent or referrer; city-level position), at most 20 per second, never written to disk.
- Documentation of the geolocation refresh: Urutau checks every 24 hours (`--geo-update`) while DB-IP publishes once a month.
### Changed
- **Unique visitors were corrected.** A visitor is now a person with a real browser: a successful GET of a document by a browser User-Agent (not a bot, tool or unknown client, not a prefetch), one per IP per day, deduplicated globally. Bots, tools and unknown clients are counted apart as "non-human clients". The number is lower than before, and lower than Coolify's, which counts every distinct IP with HyperLogLog and no filter.
- Paths and `Referer` values that contain an e-mail address or a token are normalized to `:id`.
## [1.2.0] - 2026-11-14
@@ -28,6 +49,13 @@ Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versio
- The soft memory limit is 256 MiB (worst case measured: about 54 MiB of heap and a snapshot of about 27 MB). In Docker, `mem_limit: 384m` is recommended.
## [1.1.1] - 2026-11-14
### Fixed
- Live page, globe mode: sea and land colors no longer swap while the globe turns. Each country ring is now clipped at the horizon and closed along the edge of the globe, and long edges follow the map projection.
- World map data: countries crossing the 180th meridian (Russia, Fiji) are closed along the map edge, so the Sea of Okhotsk is no longer filled as land on the flat maps.
## [1.1.0] - 2026-11-14
### Added
+32 -4
View File
@@ -6,12 +6,33 @@ Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/);
## [Unreleased]
## [1.1.1] - 2026-11-14
## [1.4.0] - 2026-11-15
### Corrigido
### Adicionado
- 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.
- Segundo firewall (opcional, `URUTAU_ENFORCE=off|observe|on`): o Urutau decide quais endereços atacantes bloquear e grava as decisões num arquivo; o fail2ban do host (jail `urutau`) as aplica. O Urutau não ganha privilégios. O modo observação mostra o que seria bloqueado. Compartilhamento opcional de decisões entre hub e peers (`URUTAU_ENFORCE_SHARE`), aplicado só quando o servidor que recebe também viu o endereço atacar. Nunca bloqueia endereços confiáveis, redes privadas, faixas de CDN (Cloudflare) e de resolvedores públicos, peers nem o próprio servidor. O banimento só derruba conexões que o endereço inicia, então as respostas às conexões do próprio servidor continuam passando.
- Análise do tráfego de saída (`URUTAU_EGRESS`): as conexões novas de saída do host e dos contêineres, registradas pelo nftables, são analisadas em busca de beaconing (conversa regular com um destino), mineração, portas de IRC e SMTP, contato com endereços que atacaram o servidor ou saídas Tor, DNS fora dos resolvedores permitidos, varreduras de saída não autorizadas e países novos. Workloads por rede ou nome de contêiner (`URUTAU_EGRESS_WORKLOADS`); um workload `scanner` (scanner de superfície autorizado) só tem resumido o tráfego em formato de varredura, todo o resto é julgado como o de qualquer workload, então o beaconing dele continua sendo detectado.
- Kit de host em `deploy/host` (tabela nftables, rsyslog, logrotate, mapa de contêineres, filtro, ação e jail do fail2ban, `install.sh`).
- Página nova Tráfego de saída e seção Segundo firewall em Defesa.
- Relatório HTML (`/api/v1/report?format=html`): capa, sumário executivo em linguagem leiga, recomendações por regras, ameaças, geografia, erros e saúde, visitantes, defesa, segundo firewall e tráfego de saída, imprimível em A4. A página Relatórios baixa ou imprime.
- O script de capturas cobre todas as páginas.
## [1.3.0] - 2026-11-14
### Adicionado
- **Muitas páginas novas**, agrupadas na barra lateral: Monitorar (Visão geral, Ao vivo, Serviços), Investigar (IPs, Sessões, Campanhas, Replay, Busca de eventos), Analisar (Ameaças, MITRE ATT&CK, Geografia, Evolução, Concentração, Sobrevivência, Tráfego, De onde vêm os erros, Protocolos e TLS), Operar (Defesa, Fontes e hosts, Integridade) e Relatórios. Um glossário: um botão "?" ao lado de métricas e categorias explica o que cada uma significa e o que fazer.
- **Saúde dos serviços:** SLO por serviço (meta de 99,5%), orçamento de erro, burn rate (1 h e 6 h) e Apdex, a partir dos nomes de router e service do Traefik.
- **Classes de erro:** todo erro é classificado como `app`, `proxy`, `blocked`, `attack`, `bot`, `client` ou `unknown`, para distinguir um 5xx do seu app de um link quebrado ou de um scanner. Os campos do Traefik `OriginStatus`, `OriginDuration`, `Overhead`, `OriginContentSize`, `RetryAttempts`, `RouterName`, `ServiceName`, `RequestProtocol`, `RequestScheme`, `TLSVersion` e `TLSCipher` são lidos quando presentes.
- **Episódios e sobrevivência:** tempo até o ban e curvas de sobrevivência de Kaplan-Meier calculadas sobre episódios de ataque.
- **Rotas novas** (só usuário, nunca o token de peer): `GET /api/v1/techniques`, `/evolution`, `/concentration`, `/survival`, `/sessions/funnel`, `/campaigns`, `/campaigns/{id}`, `/defense`, `/errors`, `/integrity`, `/report`, `/services`, `/services/{svc}` e `/protocols`.
- **Stream de visitas legítimas:** `GET /api/v1/events/stream?visits=1` também envia eventos anônimos de visita (sem endereço, User-Agent nem referrer; posição no nível da cidade), no máximo 20 por segundo, nunca gravados em disco.
- Documentação da atualização da geolocalização: o Urutau confere a cada 24 horas (`--geo-update`), enquanto a DB-IP publica uma vez por mês.
### Alterado
- **Os visitantes únicos foram corrigidos.** Um visitante agora é uma pessoa com navegador real: um GET bem-sucedido de um documento por um User-Agent de navegador (não bot, ferramenta nem cliente desconhecido, nem prefetch), um por IP por dia, deduplicado globalmente. Bots, ferramentas e clientes desconhecidos são contados à parte como "clientes não humanos". O número é menor que antes, e menor que o do Coolify, que conta todo IP distinto com HyperLogLog e sem filtro.
- Caminhos e valores de `Referer` que contêm e-mail ou token são normalizados para `:id`.
## [1.2.0] - 2026-11-14
@@ -28,6 +49,13 @@ Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/);
- O limite suave de memória é 256 MiB (pior caso medido: cerca de 54 MiB de heap e um snapshot de cerca de 27 MB). No Docker, recomenda-se `mem_limit: 384m`.
## [1.1.1] - 2026-11-14
### Corrigido
- Página Ao vivo, modo globo: as cores do mar e da terra não se trocam mais enquanto o globo gira. Cada contorno de país agora é recortado no horizonte e fechado ao longo da borda do globo, e as arestas longas seguem a projeção do mapa.
- Dados do mapa-múndi: países que cruzam o meridiano 180 (Rússia, Fiji) são fechados ao longo da borda do mapa, então o Mar de Okhotsk não é mais pintado como terra nos mapas planos.
## [1.1.0] - 2026-11-14
### Adicionado
+6 -9
View File
@@ -57,16 +57,13 @@ Beyond live numbers, Urutau remembers and explains. It keeps 30 days of state an
## Interface
Nine pages, in a side rail, with the view kept in the URL hash:
Pages are grouped in a side rail, with the view kept in the URL hash. A "?" button next to metrics and categories explains what they mean and what to do.
- **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.
- **Monitor:** Overview (headline numbers, timeline, top IPs; a period selector applies everywhere), Live (attacks as animated arcs on a flat map or a 3D globe, including your peers; `--location` sets where this server sits on the map), Services (SLO, error budget and Apdex per service).
- **Investigate:** IPs (the scored table and the IP analysis page, `#/ip/<ip>`), Sessions, Campaigns, Replay (a period played back on the map) and Event search.
- **Analyze:** Threats, MITRE ATT&CK, Geography (country, state, city, `#/geo/BR/Pernambuco/Recife`), Evolution, Concentration, Survival (time to ban), Traffic (privacy-friendly analytics for legitimate visitors), Where errors come from (app, proxy, blocked, attack, bot, client) and Protocols and TLS.
- **Operate:** Defense, Sources and hosts (log sources, peers and the blocklist) and Integrity.
- **Reports.**
See [docs/interface.md](docs/interface.md).
+6 -9
View File
@@ -57,16 +57,13 @@ Além dos números ao vivo, o Urutau lembra e explica. Ele guarda 30 dias de est
## Interface
Nove páginas, numa barra lateral, com a visão guardada no hash da URL:
As páginas são agrupadas numa barra lateral, com a visão guardada no hash da URL. Um botão "?" ao lado de métricas e categorias explica o que significam e o que fazer.
- **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.
- **Monitorar:** Visão geral (números principais, linha do tempo, principais IPs; um seletor de período vale em todo lugar), Ao vivo (ataques como arcos animados em mapa plano ou globo 3D, incluindo seus peers; `--location` define onde este servidor fica no mapa), Serviços (SLO, orçamento de erro e Apdex por serviço).
- **Investigar:** IPs (a tabela pontuada e a página de análise de IP, `#/ip/<ip>`), Sessões, Campanhas, Replay (um período reproduzido no mapa) e Busca de eventos.
- **Analisar:** Ameaças, MITRE ATT&CK, Geografia (país, estado, cidade, `#/geo/BR/Pernambuco/Recife`), Evolução, Concentração, Sobrevivência (tempo até o ban), Tráfego (analytics amigável à privacidade para visitantes legítimos), De onde vêm os erros (app, proxy, blocked, attack, bot, client) e Protocolos e TLS.
- **Operar:** Defesa, Fontes e hosts (fontes de log, peers e a blocklist) e Integridade.
- **Relatórios.**
Veja [docs/pt-BR/interface.md](docs/pt-BR/interface.md).
+1
View File
@@ -23,6 +23,7 @@ Do not open a public issue with exploit details. Open a minimal issue asking for
- **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 page counts unique visitors with a hash computed with a daily salt, so a visitor cannot be followed across days, and the IP address of a legitimate visitor is never persisted. There are no cookies for visitors, no fingerprinting and no request to third parties. IPs are retained only for hostile activity, for at most the retention period (7 days). Whether this is enough for your legal basis and notices is your responsibility as the controller.
- **Anonymous visits:** legitimate visitors are never stored. The optional `?visits=1` stream carries no address, User-Agent or referrer (city-level position only, at most 20 per second) and is never written to disk. Paths and `Referer` values are normalized to `:id` when they carry an e-mail address, a token or a long identifier, so personal data in a URL does not reach the lists. The newer analysis routes (`/api/v1/techniques`, `/evolution`, `/concentration`, `/survival`, `/sessions/funnel`, `/campaigns`, `/defense`, `/errors`, `/integrity`, `/report`, `/services`, `/protocols`) are user-only: the peer token gets 403 on them.
- **Event registry (privacy):** `<data-dir>/events/` keeps one line per event for replay and investigation, but only about attackers: malicious events, bans, successful SSH logins, a 404 to an attack tool, and answers to addresses that are already suspicious or hostile. The address of a legitimate visitor is never written. Files are removed after the retention (30 days at most) and the total is capped by `--events-max` (512 MB by default, `0` turns the registry off). Treat the directory as personal data under the LGPD and the GDPR: same retention, same access control as the rest of the data volume. A full disk or the size cap drops events instead of stopping the service, and a corrupted line is skipped.
- **Outbound lookups for verdicts:** the network type is inferred locally from the ASN, organisation and reverse DNS (no external API). Forward-confirmed reverse DNS is used only to confirm a claimed Googlebot or Bingbot. The optional Tor exit list is a local file (`--tor-exits`).
- **Third-party data:** the geolocation databases are DB-IP Lite, CC BY 4.0, and the attribution must be kept where the data is shown. The state and city boundaries on the Geography page are from Natural Earth, public domain.
+1
View File
@@ -23,6 +23,7 @@ Não abra uma issue pública com detalhes de exploração. Abra uma issue mínim
- **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 página Tráfego conta visitantes únicos com um hash calculado com sal diário, então um visitante não pode ser seguido entre dias, e o endereço IP de um visitante legítimo nunca é persistido. Não há cookies para visitantes, fingerprinting nem requisição a terceiros. IPs são retidos apenas para atividade hostil, por no máximo o período de retenção (7 dias). Se isso basta para a sua base legal e seus avisos é responsabilidade sua, como controlador.
- **Visitas anônimas:** visitantes legítimos nunca são armazenados. O stream opcional `?visits=1` não carrega endereço, User-Agent nem referrer (só posição no nível da cidade, no máximo 20 por segundo) e nunca é gravado em disco. Caminhos e valores de `Referer` são normalizados para `:id` quando carregam e-mail, token ou identificador longo, para que dado pessoal numa URL não chegue às listas. As rotas de análise mais novas (`/api/v1/techniques`, `/evolution`, `/concentration`, `/survival`, `/sessions/funnel`, `/campaigns`, `/defense`, `/errors`, `/integrity`, `/report`, `/services`, `/protocols`) são só de usuário: o token de peer recebe 403 nelas.
- **Registro de eventos (privacidade):** `<data-dir>/events/` guarda uma linha por evento para replay e investigação, mas só de atacantes: eventos maliciosos, bans, logins SSH bem-sucedidos, um 404 para uma ferramenta de ataque, e respostas a endereços já suspeitos ou hostis. O endereço de um visitante legítimo nunca é gravado. Os arquivos são removidos após a retenção (30 dias no máximo) e o total é limitado por `--events-max` (512 MB por padrão, `0` desliga o registro). Trate o diretório como dado pessoal perante a LGPD e o GDPR: mesma retenção e mesmo controle de acesso do resto do volume de dados. Disco cheio ou o teto de tamanho descartam eventos em vez de parar o serviço, e uma linha corrompida é ignorada.
- **Consultas para os vereditos:** o tipo de rede é inferido localmente a partir do ASN, da organização e do DNS reverso (sem API externa). O DNS reverso confirmado serve apenas para confirmar um Googlebot ou Bingbot declarado. A lista opcional de saídas do Tor é um arquivo local (`--tor-exits`).
- **Dados de terceiros:** as bases de geolocalização são DB-IP Lite, CC BY 4.0, e a atribuição deve ser mantida onde os dados são exibidos. Os limites de estados e cidades da página Geografia são do Natural Earth, domínio público.
+7
View File
@@ -0,0 +1,7 @@
# Urutau: kernel log lines of the egress table go to their own file and stay
# out of the general syslog (an authorised scan would flood it).
if ($syslogfacility-text == "kern" and $msg contains "URUTAU-EGRESS: ") then {
action(type="omfile" file="/var/log/urutau/egress.log" template="RSYSLOG_FileFormat"
fileOwner="syslog" fileGroup="adm" fileCreateMode="0640")
stop
}
+10
View File
@@ -0,0 +1,10 @@
# Urutau "second firewall" action: like iptables-allports, but it only drops
# connections the banned address STARTS (conntrack original direction). The
# replies to connections this host opened (DNS, ACME, image pulls, apt) keep
# flowing even if a decision ever names an address the host depends on.
[INCLUDES]
before = iptables-allports.conf
[Definition]
actionban = <iptables> -I f2b-<name> 1 -s <ip> -m conntrack --ctdir ORIGINAL -j <blocktype>
actionunban = <iptables> -D f2b-<name> -s <ip> -m conntrack --ctdir ORIGINAL -j <blocktype>
+7
View File
@@ -0,0 +1,7 @@
# Urutau "second firewall": one line per decision written by Urutau in
# enforce=on mode, e.g.
# 2026-11-14T22:00:00Z urutau decision=ban ip=203.0.113.7 reason=wp-bruteforce score=95 ttl=3600 host=oracle src=local
[Definition]
datepattern = ^%%Y-%%m-%%dT%%H:%%M:%%SZ
failregex = ^\s*urutau decision=ban ip=<HOST> reason=[a-z0-9-]+
ignoreregex =
+14
View File
@@ -0,0 +1,14 @@
# Urutau "second firewall". Urutau never gets privileges: it only writes its
# decisions to this file and fail2ban applies them, with its own ignoreip
# (the [DEFAULT] of the host still protects trusted addresses).
[urutau]
enabled = true
backend = polling
filter = urutau
logpath = /var/log/urutau-enforce/decisions.log
maxretry = 1
findtime = 1h
bantime = 1h
# ignoreip and ignoreself come from the host [DEFAULT] (never override them here)
action = urutau-allports[name=urutau-in, chain=INPUT, protocol=all]
urutau-allports[name=urutau-docker, chain=DOCKER-USER, protocol=all]
+63
View File
@@ -0,0 +1,63 @@
#!/bin/sh
# Urutau host kit: egress logging (nftables + rsyslog), the container map and,
# optionally, the fail2ban jail of the "second firewall".
#
# sudo sh install.sh # egress logging + container map
# sudo sh install.sh --enforce # also the fail2ban jail for URUTAU_ENFORCE=on
# sudo sh install.sh --remove # undo everything
#
# Idempotent. Urutau itself never gets privileges: it only reads these logs and
# writes its ban decisions to /var/log/urutau-enforce/decisions.log.
set -eu
here=$(cd "$(dirname "$0")" && pwd)
uid=${URUTAU_UID:-10001}
[ "$(id -u)" = 0 ] || { echo "run as root" >&2; exit 1; }
if [ "${1:-}" = "--remove" ]; then
systemctl disable --now urutau-egress.service urutau-containers-map.timer urutau-logrotate.timer 2>/dev/null || true
rm -f /etc/systemd/system/urutau-egress.service /etc/systemd/system/urutau-containers-map.service \
/etc/systemd/system/urutau-containers-map.timer /usr/local/sbin/urutau-containers-map \
/etc/rsyslog.d/41-urutau-egress.conf /etc/logrotate.d/urutau-egress \
/etc/fail2ban/jail.d/urutau.local /etc/fail2ban/filter.d/urutau.conf /etc/fail2ban/action.d/urutau-allports.conf \
/etc/systemd/system/urutau-logrotate.service /etc/systemd/system/urutau-logrotate.timer
rm -rf /etc/urutau
systemctl daemon-reload
systemctl restart rsyslog
fail2ban-client reload >/dev/null 2>&1 || true
echo "removed (logs under /var/log/urutau kept)"
exit 0
fi
wan=${URUTAU_WAN:-$(ip -o route get 1.1.1.1 | sed -n 's/.* dev \([^ ]*\).*/\1/p')}
[ -n "$wan" ] || { echo "cannot detect the uplink interface; set URUTAU_WAN" >&2; exit 1; }
case "$wan" in *[!A-Za-z0-9_.-]*) echo "bad interface name: $wan" >&2; exit 1 ;; esac
install -d -m 0750 -o syslog -g adm /var/log/urutau 2>/dev/null || install -d -m 0750 -g adm /var/log/urutau
install -d -m 0755 /etc/urutau
sed "s/@WAN@/$wan/g" "$here/urutau-egress.nft" > /etc/urutau/egress.nft
nft -c -f /etc/urutau/egress.nft
install -m 0644 "$here/41-urutau-egress.conf" /etc/rsyslog.d/41-urutau-egress.conf
install -m 0644 "$here/urutau.logrotate" /etc/logrotate.d/urutau-egress
install -m 0755 "$here/urutau-containers-map" /usr/local/sbin/urutau-containers-map
install -m 0644 "$here/urutau-egress.service" "$here/urutau-containers-map.service" \
"$here/urutau-containers-map.timer" "$here/urutau-logrotate.service" "$here/urutau-logrotate.timer" /etc/systemd/system/
systemctl daemon-reload
systemctl restart rsyslog
systemctl enable urutau-egress.service urutau-containers-map.timer urutau-logrotate.timer >/dev/null
systemctl start urutau-logrotate.timer
systemctl restart urutau-egress.service
systemctl start urutau-containers-map.service urutau-containers-map.timer
echo "egress logging on $wan: /var/log/urutau/egress.log, map: /var/log/urutau/containers.map"
if [ "${1:-}" = "--enforce" ]; then
install -d -m 0750 -o "$uid" -g adm /var/log/urutau-enforce
[ -e /var/log/urutau-enforce/decisions.log ] || install -m 0640 -o "$uid" -g adm /dev/null /var/log/urutau-enforce/decisions.log
install -m 0644 "$here/fail2ban-filter-urutau.conf" /etc/fail2ban/filter.d/urutau.conf
install -m 0644 "$here/fail2ban-action-urutau.conf" /etc/fail2ban/action.d/urutau-allports.conf
install -m 0644 "$here/fail2ban-jail-urutau.local" /etc/fail2ban/jail.d/urutau.local
fail2ban-client -t >/dev/null
fail2ban-client reload
echo "fail2ban jail 'urutau' on; mount /var/log/urutau-enforce:/logs/enforce (rw) in the container"
fi
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
# Urutau: writes "<ip> <container name>" for every running container, so the
# egress analysis can name workloads whose address changes on each redeploy.
set -eu
out=/var/log/urutau/containers.map
tmp=$(mktemp /var/log/urutau/.containers.map.XXXXXX)
trap 'rm -f "$tmp"' EXIT
docker ps -q | xargs -r docker inspect -f '{{$n := .Name}}{{range .NetworkSettings.Networks}}{{if .IPAddress}}{{.IPAddress}} {{$n}}
{{end}}{{if .GlobalIPv6Address}}{{.GlobalIPv6Address}} {{$n}}
{{end}}{{end}}' | sed 's# /# #' | grep -E '^[0-9a-fA-F.:]+ [A-Za-z0-9_.-]{1,128}$' > "$tmp" || true
chgrp adm "$tmp"; chmod 0640 "$tmp"
mv -f "$tmp" "$out"
trap - EXIT
@@ -0,0 +1,7 @@
[Unit]
Description=Urutau: map container addresses to names
After=docker.service
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/urutau-containers-map
+10
View File
@@ -0,0 +1,10 @@
[Unit]
Description=Urutau: refresh the container map every minute
[Timer]
OnBootSec=30s
OnUnitActiveSec=60s
AccuracySec=5s
[Install]
WantedBy=timers.target
+44
View File
@@ -0,0 +1,44 @@
#!/usr/sbin/nft -f
# Urutau: logs NEW outbound connections (host and containers) so the egress
# analysis can spot beaconing, mining, spam and unauthorised scans.
# Lives in its own table: it never touches the iptables-nft tables of Docker
# or fail2ban, and it only logs (policy accept, no drop).
# @WAN@ is replaced by the uplink interface by install.sh.
#
# Volume control without blinding the beacon detector:
# - a (source, destination, protocol, port) seen in the last 2 h is ALWAYS
# logged (a beacon repeats the same pair, so a ceiling never hides it);
# - a NEW pair is logged under a per-source ceiling of 20/s (burst 100): an
# authorised scan (thousands of new pairs) is capped, and one noisy
# workload never eats the budget of the others.
table inet urutau_egress
delete table inet urutau_egress
table inet urutau_egress {
set rl4 { type ipv4_addr; flags dynamic; timeout 2m; size 65535; }
set rl6 { type ipv6_addr; flags dynamic; timeout 2m; size 65535; }
set seen4 { type ipv4_addr . ipv4_addr . inet_proto . inet_service; flags dynamic, timeout; timeout 2h; size 131072; }
set seen6 { type ipv6_addr . ipv6_addr . inet_proto . inet_service; flags dynamic, timeout; timeout 2h; size 131072; }
chain egress {
# known pair: always log, refresh its timer
meta nfproto ipv4 meta l4proto { tcp, udp } ip saddr . ip daddr . meta l4proto . th dport @seen4 update @seen4 { ip saddr . ip daddr . meta l4proto . th dport } log prefix "URUTAU-EGRESS: " level info return
meta nfproto ipv6 meta l4proto { tcp, udp } ip6 saddr . ip6 daddr . meta l4proto . th dport @seen6 update @seen6 { ip6 saddr . ip6 daddr . meta l4proto . th dport } log prefix "URUTAU-EGRESS: " level info return
# new pair: per-source ceiling, then remember it
meta nfproto ipv4 meta l4proto { tcp, udp } add @rl4 { ip saddr limit rate 20/second burst 100 packets } add @seen4 { ip saddr . ip daddr . meta l4proto . th dport } log prefix "URUTAU-EGRESS: " level info return
meta nfproto ipv6 meta l4proto { tcp, udp } add @rl6 { ip6 saddr limit rate 20/second burst 100 packets } add @seen6 { ip6 saddr . ip6 daddr . meta l4proto . th dport } log prefix "URUTAU-EGRESS: " level info return
# other protocols (ICMP...) under the same ceiling, not remembered
meta nfproto ipv4 meta l4proto != { tcp, udp } add @rl4 { ip saddr limit rate 20/second burst 100 packets } log prefix "URUTAU-EGRESS: " level info
meta nfproto ipv6 meta l4proto != { tcp, udp } add @rl6 { ip6 saddr limit rate 20/second burst 100 packets } log prefix "URUTAU-EGRESS: " level info
}
chain forward_log {
type filter hook forward priority filter - 10; policy accept;
ct state new oifname "@WAN@" iifname != "@WAN@" jump egress
}
chain output_log {
type filter hook output priority filter - 10; policy accept;
ct state new oifname "@WAN@" jump egress
}
}
+13
View File
@@ -0,0 +1,13 @@
[Unit]
Description=Urutau: egress connection log (nftables)
After=network-online.target docker.service
Wants=network-online.target
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/sbin/nft -f /etc/urutau/egress.nft
ExecStop=/usr/sbin/nft delete table inet urutau_egress
[Install]
WantedBy=multi-user.target
+6
View File
@@ -0,0 +1,6 @@
[Unit]
Description=Urutau: rotate the egress log by size
[Service]
Type=oneshot
ExecStart=/usr/sbin/logrotate -s /var/lib/logrotate/urutau-egress.status /etc/logrotate.d/urutau-egress
+9
View File
@@ -0,0 +1,9 @@
[Unit]
Description=Urutau: check the egress log size every 10 minutes
[Timer]
OnBootSec=5m
OnUnitActiveSec=10m
[Install]
WantedBy=timers.target
+14
View File
@@ -0,0 +1,14 @@
/var/log/urutau/egress.log {
daily
rotate 7
maxsize 200M
maxage 7
compress
delaycompress
missingok
notifempty
create 0640 syslog adm
postrotate
/usr/lib/rsyslog/rsyslog-rotate
endscript
}
+32
View File
@@ -91,6 +91,38 @@ Benign requests (`ok`, and the `notfound` that are not scanning) also feed the T
Every view takes a range: one of twelve named windows (`1h`, `2h`, `3h`, `6h`, `12h`, `24h`, `2d`, `3d`, `5d`, `7d`, `15d`, `30d`) or a custom period with `from` and `to` (unix seconds, at most 30 days, clipped to the retention; `clipped` says when it was). An invalid range answers 400. Responses carry `range` as an object `{name,from,to,step,clipped}`, where `step` is the timeline granularity in seconds: 60 up to 3 hours, 120 up to 6, 300 up to 12, 900 up to 48 hours and 3600 beyond. Minute buckets exist for the latest 48 hours; older data is hourly.
## Error classes and Traefik fields
Besides the client, path, status and User-Agent, Urutau reads these Traefik access log fields when they are present: `OriginStatus`, `OriginDuration`, `Overhead`, `OriginContentSize`, `RetryAttempts`, `RouterName`, `ServiceName`, `RequestProtocol`, `RequestScheme`, `TLSVersion` and `TLSCipher`. With them every error is classified:
| Class | Meaning |
|---|---|
| `app` | the backend itself answered 5xx |
| `proxy` | the proxy could not reach the backend, or the client gave up |
| `blocked` | refused by a middleware or a rate limit before the app |
| `attack` | the request is an attack (see the categories above) |
| `bot` | a crawler or tool |
| `client` | an ordinary client mistake (broken link, authentication, bad input) |
| `unknown` | none of the above could be told |
## Services, SLO and Apdex
Requests are grouped per Traefik service (`ServiceName`, with its router). For each service Urutau keeps hourly counters by error class and latency histograms, and shows: the **SLI** (share of requests that did not end in an error that counts against the service), the **SLO** (target 99.5%), the **error budget** left, the **burn rate** over 1 hour and 6 hours (error rate divided by `1 - SLO`; above 1 the budget is being spent faster than allowed) and the **Apdex**. Attacks, blocked requests and bots do not count against a service. Apdex uses a threshold T of 500 ms (1 s for API paths): a request answered within T is satisfied, within 4T tolerating, and a 5xx or a slower one is frustrated; Apdex is (satisfied + tolerating/2) / total.
## Episodes and survival
An attack **episode** is the run of activity of one address, closed after a quiet gap. From episodes Urutau measures the time from the first sighting to the ban and draws **Kaplan-Meier** survival curves (the probability that an address is still not banned after a given time, with addresses never banned counted as censored), with the median and the 90th percentile.
## Unique visitors
A **visitor** is a person with a real browser: a successful (2xx) GET of a document by a browser User-Agent (not a bot, tool or unknown client), not a prefetch and, when the browser says so, with `Sec-Fetch-Dest: document`. It is counted once per IP per UTC day, deduplicated globally across domains (a per-domain figure and an all-domains total). The key is a hash of a daily salt, the IP and the domain, and leaves the User-Agent out on purpose, because scrapers rotate it per request from one address (a measured 2.7x inflation). Everything else that talks to a site (bots, tools, unknown or empty User-Agents) is counted apart as **non-human clients**.
This is why the number differs from Coolify's analytics, which counts every distinct IP through HyperLogLog with no filter: bots, scanners and health checks inflate it. Urutau's figure is lower and closer to people.
## Legitimate visits stream
`GET /api/v1/events/stream?visits=1` adds anonymous visit events to the live stream. A visit carries no address, User-Agent or referrer; its place is the city, with coordinates rounded to one decimal (about 11 km). At most 20 visit events per second per instance are sent (the excess is summarised once a second as a batch), and visits are only broadcast to subscribers: never written to the event log, a snapshot or `live/recent`.
## Event registry
`<data-dir>/events/` holds one JSON line per event, in the same format as the live stream, one file per UTC day. The current day is appended to and synced every 2 seconds; older days are gzip compressed. Files older than the retention are deleted, and the total is capped by `--events-max` (512 MB by default, `0` disables the registry). A day holds at most 200,000 lines; beyond that, events are only counted.
+2
View File
@@ -58,6 +58,8 @@ 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 geolocation databases are checked every 24 hours (`--geo-update`), but DB-IP publishes a new one only once a month, so most checks find nothing new; the file is replaced after it is verified.
The Traffic page needs no setting. `URUTAU_DOMAINS` restricts which domains it tracks (exact names or `*.example.com`); a domain only gets a slot after a 2xx answer and inactive domains are pruned, so forged `Host` headers cannot fill the analytics. Top pages normalize token-looking path segments (ids, hashes, long random strings) to `:id`. It uses the Traefik log, counts unique visitors by a daily-salted hash and never persists the IP address of a legitimate visitor. See [SECURITY.md](../SECURITY.md).
## Peers (hub mode)
+25 -1
View File
@@ -55,6 +55,20 @@ A side rail (a tab bar on phones) holds the pages. Each page opens with a senten
<p align="center"><img src="img/overview-light.png" width="620" alt="Overview in the light theme"> <img src="img/overview-mobile.png" height="420" alt="Overview on a phone"><br><sub>The light theme on a desktop and the phone layout (a tab bar replaces the side rail).</sub></p>
## Page groups
The side rail groups the pages:
- **Monitor:** Overview, Live, Services (per-service SLO, error budget, burn rate and Apdex; `#/slo`).
- **Investigate:** IPs, Sessions (the funnel from recon to access), Campaigns (and a page per campaign), Replay and Event search.
- **Analyze:** Threats, MITRE ATT&CK (techniques seen and when first seen), Geography, Evolution (change over time), Concentration (how much comes from few IPs or ASNs), Survival (time to ban, Kaplan-Meier), Traffic, Where errors come from (classes `app`, `proxy`, `blocked`, `attack`, `bot`, `client`, `unknown`) and Protocols and TLS (HTTP versions and TLS versions in use).
- **Operate:** Defense (ban and blocklist coverage and leaks), Sources and hosts, Integrity (health of the data: sources, registry, snapshot).
- **Reports:** a summary of a period, from `GET /api/v1/report`.
## Glossary and tooltips
A small **"?"** button sits next to metrics, categories and column titles. It is keyboard focusable and opens a short explanation (what the figure means) and a "what to do" line, in English or Portuguese. The text comes from one central glossary, so the same term reads the same on every page.
## Attribution
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.
@@ -79,9 +93,19 @@ State and city boundaries on the Geography page are from [Natural Earth](https:/
| `GET /api/v1/metrics` | session or bearer | stable metrics (see [architecture.md](architecture.md)). Query: `range` or `from`/`to`, `host` |
| `GET /api/v1/ip/{ip}/stix` | session or bearer | STIX 2.1 bundle of one IP |
| `GET /api/v1/peer/period` | peer token only | federation: the study a hub merges. At most two at once (503 with `Retry-After` otherwise) |
| `GET /api/v1/techniques` | session or bearer | MITRE ATT&CK techniques seen in the period |
| `GET /api/v1/evolution`, `/concentration`, `/survival` | session or bearer | analytics of the period: change over time, concentration by IP and ASN, and time to ban with the Kaplan-Meier curve |
| `GET /api/v1/sessions/funnel` | session or bearer | sessions by stage (recon, probe, exploit, access, banned) |
| `GET /api/v1/campaigns`, `/api/v1/campaigns/{id}` | session or bearer | campaigns of the period, and one campaign with its IPs |
| `GET /api/v1/defense` | session or bearer | ban and blocklist coverage and leaks |
| `GET /api/v1/errors` | session or bearer | errors by class (`app`, `proxy`, `blocked`, `attack`, `bot`, `client`, `unknown`) |
| `GET /api/v1/integrity` | session or bearer | health of the data: sources, registry, snapshot |
| `GET /api/v1/report` | session or bearer | summary of a period (requests, attacks, hostile IPs, bans, visitors, non-human clients, page views, top IPs) |
| `GET /api/v1/services`, `/api/v1/services/{svc}` | session or bearer | per-service SLI, SLO, error budget, burn rate and Apdex |
| `GET /api/v1/protocols` | session or bearer | HTTP and TLS versions in use |
| `GET /api/v1/ips` | session or bearer | IP table. Query: `range`, `host`, `min_score`, `level`, `q`, `banned=1`, `sort` (`score`, `last`, `first`, `events`, `ip`), `order=asc`, `per` (1 to 200, default 50), `page` |
| `GET /api/v1/ip/{ip}` | session or bearer | 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/events/stream` | session or bearer | Server-Sent Events, event `ev`, a ping every 20 s. With `visits=1` it also sends anonymous `visit` events (no address, at most 20 per second) |
| `GET /api/v1/blocklist.txt` | session or bearer | one IP per line. Query: `min_score` (default 50), `range` (default `7d`), `host`, `family` (`4`, `6`; default both; `4` suits `ipset hash:ip`), `download=1` |
| `GET /api/v1/blocklist.json` | session or bearer | `{"generated","min_score","count","ips":[{"ip","score","last","hosts"}]}`; the `ip` of an IPv6 entry is a `/64` prefix |
+32
View File
@@ -91,6 +91,38 @@ Requisições benignas (`ok`, e os `notfound` que não são varredura) também a
Toda visão recebe um intervalo: uma das doze janelas nomeadas (`1h`, `2h`, `3h`, `6h`, `12h`, `24h`, `2d`, `3d`, `5d`, `7d`, `15d`, `30d`) ou um período personalizado com `from` e `to` (segundos unix, no máximo 30 dias, cortado pela retenção; `clipped` indica quando foi). Um intervalo inválido responde 400. As respostas trazem `range` como objeto `{name,from,to,step,clipped}`, em que `step` é a granularidade da linha do tempo em segundos: 60 até 3 horas, 120 até 6, 300 até 12, 900 até 48 horas e 3600 acima disso. Buckets por minuto existem para as últimas 48 horas; dados mais antigos são por hora.
## Classes de erro e campos do Traefik
Além de cliente, caminho, status e User-Agent, o Urutau lê estes campos do access log do Traefik quando presentes: `OriginStatus`, `OriginDuration`, `Overhead`, `OriginContentSize`, `RetryAttempts`, `RouterName`, `ServiceName`, `RequestProtocol`, `RequestScheme`, `TLSVersion` e `TLSCipher`. Com eles todo erro é classificado:
| Classe | Significado |
|---|---|
| `app` | o próprio backend respondeu 5xx |
| `proxy` | o proxy não alcançou o backend, ou o cliente desistiu |
| `blocked` | recusado por um middleware ou limite de taxa antes do app |
| `attack` | a requisição é um ataque (veja as categorias acima) |
| `bot` | um crawler ou ferramenta |
| `client` | um erro comum de cliente (link quebrado, autenticação, entrada inválida) |
| `unknown` | nenhuma das anteriores pôde ser identificada |
## Serviços, SLO e Apdex
As requisições são agrupadas por serviço do Traefik (`ServiceName`, com seu router). Para cada serviço o Urutau guarda contadores por hora por classe de erro e histogramas de latência, e mostra: o **SLI** (parcela das requisições que não terminaram em um erro que conta contra o serviço), o **SLO** (meta de 99,5%), o **orçamento de erro** restante, o **burn rate** em 1 hora e 6 horas (taxa de erro dividida por `1 - SLO`; acima de 1 o orçamento está sendo gasto mais rápido que o permitido) e o **Apdex**. Ataques, requisições bloqueadas e bots não contam contra um serviço. O Apdex usa um limite T de 500 ms (1 s para caminhos de API): uma requisição respondida dentro de T é satisfeita, dentro de 4T tolerada, e um 5xx ou uma mais lenta é frustrada; o Apdex é (satisfeitas + toleradas/2) / total.
## Episódios e sobrevivência
Um **episódio** de ataque é a sequência de atividade de um endereço, encerrada após uma pausa. A partir dos episódios o Urutau mede o tempo entre o primeiro avistamento e o ban e desenha curvas de sobrevivência de **Kaplan-Meier** (a probabilidade de um endereço ainda não estar banido após certo tempo, com endereços nunca banidos tratados como censurados), com a mediana e o percentil 90.
## Visitantes únicos
Um **visitante** é uma pessoa com navegador real: um GET bem-sucedido (2xx) de um documento por um User-Agent de navegador (não bot, ferramenta nem cliente desconhecido), que não seja prefetch e, quando o navegador informa, com `Sec-Fetch-Dest: document`. É contado uma vez por IP por dia UTC, deduplicado globalmente entre domínios (um número por domínio e um total de todos os domínios). A chave é um hash de um sal diário, do IP e do domínio, e deixa o User-Agent de fora de propósito, porque scrapers o trocam a cada requisição a partir de um endereço (uma inflação medida de 2,7 vezes). Todo o resto que fala com um site (bots, ferramentas, User-Agents desconhecidos ou vazios) é contado à parte como **clientes não humanos**.
É por isso que o número difere do analytics do Coolify, que conta todo IP distinto por HyperLogLog sem filtro: bots, scanners e health checks o inflam. O número do Urutau é menor e mais próximo de pessoas.
## Stream de visitas legítimas
`GET /api/v1/events/stream?visits=1` acrescenta eventos anônimos de visita ao stream ao vivo. Uma visita não carrega endereço, User-Agent nem referrer; o lugar é a cidade, com coordenadas arredondadas a uma casa decimal (cerca de 11 km). No máximo 20 eventos de visita por segundo por instância são enviados (o excesso é resumido uma vez por segundo em um lote), e visitas só são transmitidas a assinantes: nunca gravadas no registro de eventos, em um snapshot nem em `live/recent`.
## Registro de eventos
`<data-dir>/events/` guarda uma linha JSON por evento, no mesmo formato do stream ao vivo, um arquivo por dia UTC. O dia corrente recebe appends e é sincronizado a cada 2 segundos; dias anteriores são compactados com gzip. Arquivos mais antigos que a retenção são apagados, e o total é limitado por `--events-max` (512 MB por padrão, `0` desativa o registro). Um dia guarda no máximo 200.000 linhas; acima disso os eventos só são contados.
+2
View File
@@ -58,6 +58,8 @@ 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).
As bases de geolocalização são conferidas a cada 24 horas (`--geo-update`), mas a DB-IP publica uma nova só uma vez por mês, então a maioria das conferências não acha nada novo; o arquivo é substituído depois de verificado.
A página Tráfego não precisa de ajuste. `URUTAU_DOMAINS` restringe quais domínios ela acompanha (nomes exatos ou `*.exemplo.com`); um domínio só ganha vaga depois de uma resposta 2xx e domínios inativos são podados, então `Host` forjados não enchem o analytics. O top de páginas normaliza segmentos de caminho com cara de token (ids, hashes, strings aleatórias longas) para `:id`. Ela usa o log do Traefik, conta visitantes únicos por um hash com sal diário e nunca persiste o endereço IP de um visitante legítimo. Veja o [SECURITY.pt-BR.md](../../SECURITY.pt-BR.md).
## Peers (modo hub)
+25 -1
View File
@@ -52,6 +52,20 @@ Uma barra lateral (barra de abas no celular) reúne as páginas. Cada página ab
<p align="center"><img src="../img/overview-light.png" width="620" alt="Visão geral no tema claro"> <img src="../img/overview-mobile.png" height="420" alt="Visão geral no celular"><br><sub>O tema claro no desktop e o layout de celular (uma barra de abas substitui a lateral).</sub></p>
## Grupos de páginas
A barra lateral agrupa as páginas:
- **Monitorar:** Visão geral, Ao vivo, Serviços (SLO por serviço, orçamento de erro, burn rate e Apdex; `#/slo`).
- **Investigar:** IPs, Sessões (o funil de recon até acesso), Campanhas (e uma página por campanha), Replay e Busca de eventos.
- **Analisar:** Ameaças, MITRE ATT&CK (técnicas vistas e quando foram vistas pela primeira vez), Geografia, Evolução (mudança ao longo do tempo), Concentração (quanto vem de poucos IPs ou ASNs), Sobrevivência (tempo até o ban, Kaplan-Meier), Tráfego, De onde vêm os erros (classes `app`, `proxy`, `blocked`, `attack`, `bot`, `client`, `unknown`) e Protocolos e TLS (versões de HTTP e de TLS em uso).
- **Operar:** Defesa (cobertura e vazamentos de ban e blocklist), Fontes e hosts, Integridade (saúde dos dados: fontes, registro, snapshot).
- **Relatórios:** um resumo de um período, de `GET /api/v1/report`.
## Glossário e dicas
Um pequeno botão **"?"** fica ao lado de métricas, categorias e títulos de coluna. Ele recebe foco pelo teclado e abre uma explicação curta (o que o número significa) e uma linha "o que fazer", em inglês ou português. O texto vem de um glossário central, então o mesmo termo aparece igual em todas as páginas.
## Atribuição
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.
@@ -76,9 +90,19 @@ Os limites de estados e cidades da página Geografia são do [Natural Earth](htt
| `GET /api/v1/metrics` | sessão ou bearer | métricas estáveis (veja [arquitetura.md](arquitetura.md)). Query: `range` ou `from`/`to`, `host` |
| `GET /api/v1/ip/{ip}/stix` | sessão ou bearer | bundle STIX 2.1 de um IP |
| `GET /api/v1/peer/period` | só token de peer | federação: o estudo que um hub mescla. No máximo dois ao mesmo tempo (503 com `Retry-After` caso contrário) |
| `GET /api/v1/techniques` | sessão ou bearer | técnicas MITRE ATT&CK vistas no período |
| `GET /api/v1/evolution`, `/concentration`, `/survival` | sessão ou bearer | análises do período: mudança ao longo do tempo, concentração por IP e ASN, e tempo até o ban com a curva de Kaplan-Meier |
| `GET /api/v1/sessions/funnel` | sessão ou bearer | sessões por estágio (recon, probe, exploit, access, banned) |
| `GET /api/v1/campaigns`, `/api/v1/campaigns/{id}` | sessão ou bearer | campanhas do período, e uma campanha com seus IPs |
| `GET /api/v1/defense` | sessão ou bearer | cobertura e vazamentos de ban e blocklist |
| `GET /api/v1/errors` | sessão ou bearer | erros por classe (`app`, `proxy`, `blocked`, `attack`, `bot`, `client`, `unknown`) |
| `GET /api/v1/integrity` | sessão ou bearer | saúde dos dados: fontes, registro, snapshot |
| `GET /api/v1/report` | sessão ou bearer | resumo de um período (requisições, ataques, IPs hostis, bans, visitantes, clientes não humanos, páginas vistas, principais IPs) |
| `GET /api/v1/services`, `/api/v1/services/{svc}` | sessão ou bearer | SLI, SLO, orçamento de erro, burn rate e Apdex por serviço |
| `GET /api/v1/protocols` | sessão ou bearer | versões de HTTP e TLS em uso |
| `GET /api/v1/ips` | sessão ou bearer | tabela de IPs. Query: `range`, `host`, `min_score`, `level`, `q`, `banned=1`, `sort` (`score`, `last`, `first`, `events`, `ip`), `order=asc`, `per` (1 a 200, padrão 50), `page` |
| `GET /api/v1/ip/{ip}` | sessão ou bearer | 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/events/stream` | sessão ou bearer | Server-Sent Events, evento `ev`, um ping a cada 20 s. Com `visits=1` também envia eventos `visit` anônimos (sem endereço, no máximo 20 por segundo) |
| `GET /api/v1/blocklist.txt` | sessão ou bearer | um IP por linha. Query: `min_score` (padrão 50), `range` (padrão `7d`), `host`, `family` (`4`, `6`; padrão ambos; `4` serve ao `ipset hash:ip`), `download=1` |
| `GET /api/v1/blocklist.json` | sessão ou bearer | `{"generated","min_score","count","ips":[{"ip","score","last","hosts"}]}`; o `ip` de uma entrada IPv6 é um prefixo `/64` |
+56
View File
@@ -46,6 +46,19 @@ type Config struct {
TorExits string // file with Tor exit addresses, one per line; empty disables the check
EventsMax string // size cap of the event registry ("512MB", "0" disables it)
NoAuth bool
// Second firewall (see internal/enforce).
Enforce string // off (default), observe or on
EnforceLog string // decision file read by the host fail2ban
EnforceShare string // off (default) or on: exchange decisions with peers
EnforceThreshold int // attack events in 10 minutes that justify a ban
EnforceMaxPerMin int // decisions per minute; the excess is dropped
// Egress analysis (see internal/egress).
Egress string // auto (default: on when the log exists), on or off
EgressLog string // kernel log of new outbound connections
EgressWorkloads string // "name=CIDR|name:<prefix>[,...][:role];..."
EgressResolvers string // DNS resolvers allowed (empty: the usual public ones)
EgressContainers string // "<ip> <container>" map written by the host kit
}
// DefaultEventsMax is the default size cap of the event registry.
@@ -86,6 +99,15 @@ func env(key, def string) string {
return def
}
func envInt(key string, def int) int {
if v, ok := os.LookupEnv(key); ok {
if n, err := strconv.Atoi(strings.TrimSpace(v)); err == nil {
return n
}
}
return def
}
// csvFlag accumulates comma separated values; the first use replaces the default.
type csvFlag struct {
val string
@@ -152,6 +174,16 @@ func ParseFlags(name string, args []string) (Config, error) {
fs.DurationVar(&c.Retention, "retention", store.DefaultRetention, "how long data is kept, at most 720h (URUTAU_RETENTION)")
fs.StringVar(&c.TorExits, "tor-exits", env("URUTAU_TOR_EXITS", ""), "file with Tor exit node addresses, one per line, reloaded every 24 h when it changes; empty disables (URUTAU_TOR_EXITS)")
fs.StringVar(&c.EventsMax, "events-max", env("URUTAU_EVENTS_MAX", DefaultEventsMax), "size cap of the event registry in <data-dir>/events, 0 disables it (URUTAU_EVENTS_MAX)")
fs.StringVar(&c.Enforce, "enforce", env("URUTAU_ENFORCE", "off"), "second firewall: off, observe (decide in memory only) or on (write decisions for the host fail2ban) (URUTAU_ENFORCE)")
fs.StringVar(&c.EnforceLog, "enforce-log", env("URUTAU_ENFORCE_LOG", "/logs/enforce/decisions.log"), "decision file appended in --enforce=on (URUTAU_ENFORCE_LOG)")
fs.StringVar(&c.EnforceShare, "enforce-share", env("URUTAU_ENFORCE_SHARE", "off"), "on: exchange decisions with peers, each side applies its own exclusions (URUTAU_ENFORCE_SHARE)")
fs.IntVar(&c.EnforceThreshold, "enforce-threshold", envInt("URUTAU_ENFORCE_THRESHOLD", 5), "attack events in 10 minutes that justify a ban (URUTAU_ENFORCE_THRESHOLD)")
fs.StringVar(&c.Egress, "egress", env("URUTAU_EGRESS", "auto"), "egress analysis: auto (on when --egress-log exists), on or off (URUTAU_EGRESS)")
fs.StringVar(&c.EgressLog, "egress-log", env("URUTAU_EGRESS_LOG", "/logs/host/egress.log"), "kernel log of new outbound connections written by the host kit (URUTAU_EGRESS_LOG)")
fs.StringVar(&c.EgressWorkloads, "egress-workloads", env("URUTAU_EGRESS_WORKLOADS", ""), "workloads: \"ciberlab=name:<container prefix>:scanner;mail=10.0.7.0/24:mail\" (URUTAU_EGRESS_WORKLOADS)")
fs.StringVar(&c.EgressResolvers, "egress-resolvers", env("URUTAU_EGRESS_RESOLVERS", ""), "DNS resolvers allowed, comma separated; empty: the usual public ones (URUTAU_EGRESS_RESOLVERS)")
fs.StringVar(&c.EgressContainers, "egress-containers", env("URUTAU_EGRESS_CONTAINERS", "/logs/host/containers.map"), "\"<ip> <container>\" map written by the host kit (URUTAU_EGRESS_CONTAINERS)")
fs.IntVar(&c.EnforceMaxPerMin, "enforce-max-per-min", envInt("URUTAU_ENFORCE_MAX_PER_MIN", 60), "most decisions per minute, the excess is dropped and counted (URUTAU_ENFORCE_MAX_PER_MIN)")
fs.BoolVar(&c.NoAuth, "insecure-no-auth", false, "disable authentication; only allowed on a loopback bind")
if v := os.Getenv("URUTAU_GEO_UPDATE"); v != "" {
if d, err := time.ParseDuration(v); err == nil {
@@ -210,6 +242,30 @@ func (c Config) Validate(token string) ([]fed.Peer, error) {
if v := strings.ToLower(c.PeerBlocklist); v != "" && v != "on" && v != "off" {
return nil, fmt.Errorf("--peer-blocklist must be on or off")
}
if c.Enforce != "" || c.EnforceShare != "" { // a Config built by hand may leave them unset
switch strings.ToLower(c.Enforce) {
case "", "off", "observe", "on":
default:
return nil, fmt.Errorf("--enforce must be off, observe or on")
}
if v := strings.ToLower(c.EnforceShare); v != "" && v != "off" && v != "on" {
return nil, fmt.Errorf("--enforce-share must be on or off")
}
if c.EnforceThreshold < 1 || c.EnforceThreshold > 1000 {
return nil, fmt.Errorf("--enforce-threshold must be between 1 and 1000")
}
if c.EnforceMaxPerMin < 1 || c.EnforceMaxPerMin > 10000 {
return nil, fmt.Errorf("--enforce-max-per-min must be between 1 and 10000")
}
}
switch strings.ToLower(c.Egress) {
case "", "auto", "on", "off":
default:
return nil, fmt.Errorf("--egress must be auto, on or off")
}
if strings.EqualFold(c.Enforce, "on") && c.EnforceLog == "" {
return nil, fmt.Errorf("--enforce=on needs --enforce-log")
}
var peers []fed.Peer
seen := map[string]bool{}
envSeen := map[string]string{}
+1
View File
@@ -56,6 +56,7 @@ func Doctor(c Config, w io.Writer, asJSON bool) bool {
os.Remove(f.Name())
add("data-dir", "ok", fmt.Sprintf("%s writable", filepath.Clean(c.DataDir)))
}
doctorEnforce(c, add)
geoInfo := doctorGeo(c, add)
stateInfo := doctorState(c, add)
ok := true
+98
View File
@@ -0,0 +1,98 @@
package app
import (
"log/slog"
"net/netip"
"net/url"
"os"
"strconv"
"strings"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/server"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
// newEgress builds the egress analysis, or returns nil when it is off (or in
// auto mode without the host log).
func newEgress(c Config, st *store.Store, log *slog.Logger) (*egress.Source, error) {
mode := strings.ToLower(c.Egress)
if mode == "off" || c.EgressLog == "" {
return nil, nil
}
if mode == "" || mode == "auto" {
if _, err := os.Stat(c.EgressLog); err != nil {
return nil, nil
}
}
var allow []netip.Prefix
if nets, err := core.ParseCIDRs(c.Trusted); err == nil {
for _, n := range nets {
if p, err := netip.ParsePrefix(n.String()); err == nil {
allow = append(allow, p)
}
}
}
allow = append(allow, egressExtraAllow(c)...)
eng, err := egress.New(egress.Config{
Workloads: c.EgressWorkloads,
Resolvers: c.EgressResolvers,
Allow: allow,
Containers: c.EgressContainers,
Geo: func(ip string) (string, string, string) {
g := st.GeoOf(ip)
asn := ""
if g.ASN != 0 {
asn = "AS" + strconv.FormatUint(uint64(g.ASN), 10)
}
return g.CC, asn, g.ASOrg
},
BadDst: func(a netip.Addr) (bool, string) {
if intel.IsTorExit(a) {
return true, "tor-exit"
}
if st.KnownHostile(a.String()) {
return true, "attacked-us"
}
return false, ""
},
})
if err != nil {
return nil, err
}
server.SetEgress(eng)
log.Info("egress analysis on", "log", c.EgressLog)
return egress.NewSource(c.EgressLog, eng, log), nil
}
// egressExtraAllow adds to the egress Allow list the addresses of the peers and
// the CIDRs of URUTAU_EGRESS_ALLOW (legitimate periodic pollers).
func egressExtraAllow(c Config) []netip.Prefix {
var out []netip.Prefix
for _, ps := range c.Peers {
p, err := fed.ParsePeer(ps)
if err != nil {
continue
}
if u, err := url.Parse(p.URL); err == nil && u.Hostname() != "" {
for _, a := range resolveHost(u.Hostname()) {
out = append(out, netip.PrefixFrom(a, a.BitLen()))
}
}
}
for _, s := range strings.Split(os.Getenv("URUTAU_EGRESS_ALLOW"), ",") {
if s = strings.TrimSpace(s); s == "" {
continue
}
if p, err := netip.ParsePrefix(s); err == nil {
out = append(out, p.Masked())
} else if a, err := netip.ParseAddr(s); err == nil {
a = a.Unmap()
out = append(out, netip.PrefixFrom(a, a.BitLen()))
}
}
return out
}
+164
View File
@@ -0,0 +1,164 @@
package app
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"net"
"net/netip"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
// newEnforce builds the second firewall and hooks it into the store; nil when off.
func newEnforce(c Config, st *store.Store, peers []fed.Peer, en enricher) *enforce.Engine {
mode := strings.ToLower(c.Enforce)
if mode != enforce.ModeObserve && mode != enforce.ModeOn {
return nil
}
trusted, _ := core.ParseCIDRs(c.Ignore + "," + c.Trusted)
var hosts []string
for _, p := range peers {
if u, err := url.Parse(p.URL); err == nil && u.Hostname() != "" {
hosts = append(hosts, u.Hostname())
}
}
e := enforce.New(enforce.Config{
Mode: mode, Path: c.EnforceLog, StatePath: filepath.Join(c.DataDir, "enforce.json"), Host: c.Name,
Threshold: c.EnforceThreshold, MaxPerMin: c.EnforceMaxPerMin, Share: strings.EqualFold(c.EnforceShare, "on"),
Trusted: trusted, PeerHosts: hosts, InfraHosts: hosts, Resolve: resolveHost,
Crawler: func(ip string, uas []string) bool { v := st.FCrDNS(ip, uas); return v != nil && *v },
Geo: func(ip string) (string, uint32, string) {
if en.g == nil {
return "", 0, ""
}
g := en.Geo(ip)
return g.CC, g.ASN, g.ASOrg
},
})
st.SetIngestHook(e.Observe)
return e
}
func resolveHost(h string) []netip.Addr {
if a, err := netip.ParseAddr(h); err == nil {
return []netip.Addr{a.Unmap()}
}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
ips, err := net.DefaultResolver.LookupNetIP(ctx, "ip", h)
if err != nil {
return nil
}
for i := range ips {
ips[i] = ips[i].Unmap()
}
return ips
}
// shareDecisions pulls the decisions of every peer and pushes the local ones, every 30 s.
func shareDecisions(ctx context.Context, hub *fed.Hub, e *enforce.Engine, log *slog.Logger) {
pulled := map[string]int64{}
pushed := map[string]int64{}
t := time.NewTicker(30 * time.Second)
defer t.Stop()
for {
for _, p := range hub.Peers {
start := time.Now().Unix()
var in struct {
Decisions []enforce.Wire `json:"decisions"`
}
if err := hub.Get(ctx, p, fmt.Sprintf("/api/v1/peer/decisions?since=%d", pulled[p.Name]), &in); err == nil {
e.AcceptPeer(p.Name, in.Decisions)
pulled[p.Name] = start - 5
} else if ctx.Err() == nil {
log.Debug("enforce: pull failed", "peer", p.Name, "err", err)
}
if mine := e.LocalSince(pushed[p.Name]); len(mine) > 0 {
if err := hub.PostJSON(ctx, p, "/api/v1/peer/decisions?from="+url.QueryEscape(e.Host()), map[string]any{"decisions": mine}); err == nil {
pushed[p.Name] = start
} else if ctx.Err() == nil {
log.Debug("enforce: push failed", "peer", p.Name, "err", err)
}
}
}
select {
case <-ctx.Done():
return
case <-t.C:
}
}
}
// doctorEnforce reports the mode of the second firewall and its file.
func doctorEnforce(c Config, add func(name, status, detail string)) {
mode := strings.ToLower(c.Enforce)
if mode == "" || mode == "off" {
add("enforce", "off", "disabled (--enforce=off)")
return
}
w := enforce.Writable(c.EnforceLog)
detail := fmt.Sprintf("mode=%s share=%s threshold=%d file=%s writable=%v", mode, strings.ToLower(orDefault(c.EnforceShare, "off")), c.EnforceThreshold, c.EnforceLog, w)
switch {
case mode == "on" && !w:
add("enforce", "fail", detail)
case !w:
add("enforce", "warn", detail)
default:
add("enforce", "ok", detail)
}
if mode == "on" {
if n, tot := cloudflareClients(c.TraefikLog); n > 0 {
add("enforce-cdn", "warn", fmt.Sprintf("%d of the last %d requests in %s come from Cloudflare addresses: Traefik is not "+
"restoring the real client IP (set entryPoints.*.forwardedHeaders.trustedIPs to the Cloudflare ranges); "+
"Cloudflare is never banned, but the real attackers stay invisible", n, tot, c.TraefikLog))
}
}
}
// cloudflareClients counts, in the tail of the Traefik JSON access log, the
// requests whose ClientHost is a Cloudflare address.
func cloudflareClients(path string) (cf, total int) {
if path == "" {
return 0, 0
}
f, err := os.Open(path)
if err != nil {
return 0, 0
}
defer f.Close()
const tail = 512 << 10
if fi, err := f.Stat(); err == nil && fi.Size() > tail {
f.Seek(fi.Size()-tail, io.SeekStart)
}
sc := bufio.NewScanner(f)
sc.Buffer(make([]byte, 0, 64<<10), 1<<20)
for sc.Scan() {
var l struct {
ClientHost string `json:"ClientHost"`
}
if json.Unmarshal(sc.Bytes(), &l) != nil || l.ClientHost == "" {
continue
}
a, err := netip.ParseAddr(l.ClientHost)
if err != nil {
continue
}
total++
if enforce.IsCloudflare(a) {
cf++
}
}
return cf, total
}
+38
View File
@@ -72,6 +72,21 @@ func Serve(c Config) error {
st.SetEnricher(en)
st.SetAttribution(Attribution)
runner.Extra = func() []store.SourceStatus { return []store.SourceStatus{geoStatus(gr, c.GeoDir)} }
// Real build dates of the geo databases for /api/v1/integrity (0 = unknown).
store.GeoBuilds = func() (int64, int64) {
if gr == nil {
return 0, 0
}
s := gr.Status()
var city, asn int64
if !s.City.Build.IsZero() {
city = s.City.Build.Unix()
}
if !s.ASN.Build.IsZero() {
asn = s.ASN.Build.Unix()
}
return city, asn
}
var hub *fed.Hub
if len(peers) > 0 {
hub = fed.NewHub(peers, c.PeerToken)
@@ -83,6 +98,18 @@ func Serve(c Config) error {
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, LocalBlocklist: strings.EqualFold(c.PeerBlocklist, "off"), Version: Version, Store: st, Hub: hub})
egressSrc, err := newEgress(c, st, log)
if err != nil {
return err
}
if egressSrc != nil {
extra := runner.Extra
runner.Extra = func() []store.SourceStatus { return append(extra(), egressSrc.Status()) }
}
eng := newEnforce(c, st, peers, en)
if eng != nil {
server.SetEnforce(eng)
}
ln, err := net.Listen("tcp", c.Bind)
if err != nil {
return err
@@ -95,6 +122,9 @@ func Serve(c Config) error {
go func() { defer wg.Done(); elog.Run(ctx) }()
}
runner.Start(ctx, offsets, &wg)
if egressSrc != nil {
egressSrc.Start(ctx, &wg)
}
wg.Add(2)
go func() { defer wg.Done(); rd.Run(ctx) }()
go func() {
@@ -125,6 +155,14 @@ func Serve(c Config) error {
wg.Add(1)
go func() { defer wg.Done(); hub.Run(ctx) }()
}
if eng != nil {
wg.Add(1)
go func() { defer wg.Done(); eng.Run(ctx) }()
if hub != nil && eng.Share() {
wg.Add(1)
go func() { defer wg.Done(); shareDecisions(ctx, hub, eng, log) }()
}
}
log.Info("urutau started", "version", Version, "name", c.Name, "bind", ln.Addr().String(), "peers", len(peers), "auth", !c.NoAuth)
errc := make(chan error, 1)
go func() { errc <- srv.Serve(ln) }()
+1
View File
@@ -172,6 +172,7 @@ func (r *Runner) handle(s *source) func([]byte) {
ev.Soft, ev.Strong = ev.Status < 400, ev.Status >= 400
}
r.St.Ingest(ev)
r.St.ObserveService(ev)
if ev.Source == "traefik" && !ev.Forged && (ev.Cat == core.OK || ev.Cat == core.NotFound) {
r.St.Traffic(ev)
}
+62
View File
@@ -8,6 +8,7 @@ import (
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
@@ -195,3 +196,64 @@ func TestIPDetailConsistentOnSyntheticLogs(t *testing.T) {
t.Skip("synthetic data sets not available")
}
}
func TestEnforceConfig(t *testing.T) {
c, err := ParseFlags("x", []string{"--insecure-no-auth", "--bind", "127.0.0.1:1"})
if err != nil || c.Enforce != "off" || c.EnforceLog != "/logs/enforce/decisions.log" || c.EnforceShare != "off" || c.EnforceThreshold != 5 || c.EnforceMaxPerMin != 60 {
t.Fatalf("%+v %v", c, err)
}
for _, bad := range [][]string{{"--enforce=maybe"}, {"--enforce-share=x"}, {"--enforce-threshold=0"}, {"--enforce-max-per-min=0"}} {
c, err := ParseFlags("x", append([]string{"--insecure-no-auth", "--bind", "127.0.0.1:1", "--data-dir", t.TempDir()}, bad...))
if err != nil {
continue
}
if _, err := c.Validate(""); err == nil {
t.Errorf("%v accepted", bad)
}
}
t.Setenv("URUTAU_ENFORCE", "observe")
t.Setenv("URUTAU_ENFORCE_THRESHOLD", "9")
c, _ = ParseFlags("x", nil)
if c.Enforce != "observe" || c.EnforceThreshold != 9 {
t.Fatalf("env %+v", c)
}
}
func TestDoctorEnforce(t *testing.T) {
var got []Check
add := func(n, s, d string) { got = append(got, Check{n, s, d}) }
doctorEnforce(Config{Enforce: "on", EnforceLog: t.TempDir() + "/x/d.log", EnforceThreshold: 5}, add)
doctorEnforce(Config{Enforce: "on", EnforceLog: "/proc/nope/d.log"}, add)
doctorEnforce(Config{Enforce: "off"}, add)
if got[0].Status != "ok" || !strings.Contains(got[0].Detail, "mode=on") || got[1].Status != "fail" || got[2].Status != "off" {
t.Fatalf("%+v", got)
}
}
func TestDoctorEnforceCloudflare(t *testing.T) {
lg := filepath.Join(t.TempDir(), "access.log")
os.WriteFile(lg, []byte(`{"ClientHost":"104.16.1.1"}`+"\n"+`{"ClientHost":"203.0.114.5"}`+"\n"), 0o600)
var got []Check
add := func(n, s, d string) { got = append(got, Check{n, s, d}) }
doctorEnforce(Config{Enforce: "on", EnforceLog: t.TempDir() + "/x/d.log", TraefikLog: lg}, add)
if len(got) != 2 || got[1].Name != "enforce-cdn" || got[1].Status != "warn" {
t.Fatalf("%+v", got)
}
got = nil
doctorEnforce(Config{Enforce: "observe", EnforceLog: t.TempDir() + "/x/d.log", TraefikLog: lg}, add)
if len(got) != 1 {
t.Fatalf("%+v", got)
}
}
func TestEgressExtraAllow(t *testing.T) {
t.Setenv("URUTAU_EGRESS_ALLOW", "203.0.113.0/24, 198.51.100.7 ,bad")
got := egressExtraAllow(Config{Peers: []string{"p=https://192.0.2.9:8443"}})
var s []string
for _, p := range got {
s = append(s, p.String())
}
if strings.Join(s, " ") != "192.0.2.9/32 203.0.113.0/24 198.51.100.7/32" {
t.Fatalf("%v", s)
}
}
+1 -1
View File
@@ -2,4 +2,4 @@ package app
// Version is the release version (SemVer). Release builds may override it with
// -ldflags "-X .../internal/app.Version=...".
var Version = "1.2.0"
var Version = "1.4.0"
+198
View File
@@ -0,0 +1,198 @@
package core
import (
"net"
"net/url"
"regexp"
"strings"
)
// Error classes: where a 4xx/5xx comes from. The answer to "is this a bug in my
// application or a failed attack?".
const (
ClassAttack = "attack" // a probe, exploit or scanner: a frustrated attack
ClassBlocked = "blocked" // refused by a middleware or rate limit before the app
ClassProxy = "proxy" // the proxy could not reach the backend, or the client gave up
ClassApp = "app" // the backend itself answered 5xx
ClassBot = "bot" // a known crawler asking for something that is not there
ClassClient = "client" // an ordinary client mistake (broken link, auth, bad input)
ClassUnknown = "unknown"
)
// Subtypes of the client class.
const (
SubBrokenLink = "broken_link"
SubExternalLink = "external_link"
SubAuth = "auth"
SubAuthChallenge = "auth_challenge"
SubValidation = "validation"
SubCancelled = "cancelled"
SubOther = "other"
)
var okMethods = map[string]bool{"GET": true, "HEAD": true, "POST": true, "PUT": true, "PATCH": true, "DELETE": true, "OPTIONS": true}
var toolUARe = regexp.MustCompile(`(?i)(^|[^a-z])(curl|wget|python-requests|python-urllib|aiohttp|go-http-client|libwww-perl|okhttp|httpie|scrapy|sqlmap|nikto|nmap|masscan|zgrab|nuclei|dirbuster|gobuster|feroxbuster|wfuzz|hydra|httpx|fasthttp|java/|axios|node-fetch)([^a-z]|$)`)
var crawlerUARe = regexp.MustCompile(`(?i)(bot|crawler|spider|slurp|bingpreview|facebookexternalhit|embedly|ia_archiver|archive\.org|mediapartners|headlesschrome|lighthouse|pingdom|uptime|monitor)`)
var registryUARe = regexp.MustCompile(`(?i)(docker|containerd|buildkit|act_runner|gitea-runner|connect-go|skopeo|podman|go-containerregistry|oras|crane)`)
// rich reports whether the log line carried the origin fields. Without them
// (older Traefik, demo data) OriginStatus is unknown and is taken as equal to
// the downstream status.
func rich(ev Event) bool {
return ev.Proto != "" || ev.Scheme != "" || ev.Router != "" || ev.Service != ""
}
func originOf(ev Event) int {
if !rich(ev) {
return ev.Status
}
return ev.OriginStatus
}
func isIPHost(h string) bool {
if i := strings.LastIndexByte(h, ':'); i > 0 && !strings.Contains(h[i:], "]") {
h = h[:i]
}
h = strings.Trim(h, "[]")
return net.ParseIP(h) != nil
}
// NoRouter: the request matched no application router (the catch-all answered,
// or Traefik had nothing for the host): internet noise by definition.
func NoRouter(ev Event) bool {
if isIPHost(ev.Domain) {
return true
}
if !rich(ev) {
return false
}
return ev.Router == "" || strings.HasPrefix(ev.Router, "catchall") || strings.HasPrefix(ev.Service, "error-pages")
}
// AuthChallenge: the normal 401 a container registry or CI runner gets before
// presenting a token. Never an attack.
func AuthChallenge(ev Event) bool {
if ev.Status != 401 && ev.Status != 403 {
return false
}
p := ev.Path
if !(p == "/v2" || strings.HasPrefix(p, "/v2/") || strings.HasPrefix(p, "/api/actions")) {
return false
}
return registryUARe.MatchString(ev.UA)
}
// RunnerCall: a CI runner polling the forge API (never an attack, whatever the
// status): act_runner, gitea-runner or connect-go under /api/actions/.
func RunnerCall(ev Event) bool {
return strings.HasPrefix(ev.Path, "/api/actions") && registryUARe.MatchString(ev.UA)
}
func sameSite(ev Event) bool {
if ev.FetchSite == "same-origin" {
return true
}
if ev.Referer == "" || ev.Referer == "-" {
return false
}
u, err := url.Parse(ev.Referer)
if err != nil || u.Host == "" {
return false
}
h := strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.")
d := strings.TrimPrefix(strings.ToLower(ev.Domain), "www.")
if i := strings.LastIndexByte(d, ':'); i > 0 {
d = d[:i]
}
return h == d || strings.HasSuffix(h, "."+d) || strings.HasSuffix(d, "."+h)
}
var botPaths = []string{"/robots.txt", "/sitemap", "/favicon", "/apple-touch-icon", "/.well-known/"}
func isBotPath(p string) bool {
p = strings.ToLower(p)
for _, b := range botPaths {
if strings.HasPrefix(p, b) {
return true
}
}
return false
}
func browserLike(ev Event) bool {
switch ev.E.Device {
case "desktop", "mobile", "tablet":
return !ev.E.Bot
}
return ev.E.Device == "" && strings.HasPrefix(ev.UA, "Mozilla/") && !crawlerUARe.MatchString(ev.UA) && !toolUARe.MatchString(ev.UA)
}
// ErrorClass classifies a 4xx/5xx answer; "" for anything else. susp says the
// source address is suspicious, hostile or banned.
func ErrorClass(ev Event, susp bool) string {
c, _, _ := ErrorClassify(ev, susp)
return c
}
// ErrorClassify is ErrorClass with the client subtype and the under_attack mark
// (a real application failure on a request that looks like an attack).
func ErrorClassify(ev Event, susp bool) (class, sub string, underAttack bool) {
st := ev.Status
if st < 400 || st > 599 {
return "", "", false
}
origin := originOf(ev)
challenge := AuthChallenge(ev) || (RunnerCall(ev) && st < 500)
if challenge {
return ClassClient, SubAuthChallenge, false
}
attackish := ev.Cat == Scanner || ev.Cat == Exploit || ev.Cat == BruteForce ||
(ev.Method != "" && !okMethods[strings.ToUpper(ev.Method)]) ||
ev.UA == "" || ev.E.Tool || (toolUARe.MatchString(ev.UA) && !registryUARe.MatchString(ev.UA)) ||
susp || NoRouter(ev)
if RunnerCall(ev) {
attackish = false
}
// the backend really failed: an application error, even if an attacker caused it
if ev.Retries > 0 && st >= 500 && !NoRouter(ev) {
return ClassProxy, "", false
}
if origin >= 500 && st >= 500 && !NoRouter(ev) {
return ClassApp, "", attackish
}
if attackish {
return ClassAttack, "", false
}
if st == 429 || ((st == 403 || st == 401) && origin == 0) {
return ClassBlocked, "", false
}
if ((st == 502 || st == 503 || st == 504) && origin == 0) || (ev.Retries > 0 && st >= 500) {
return ClassProxy, "", false
}
if st >= 500 {
return ClassProxy, "", false // a 5xx the backend did not produce
}
if st == 499 {
return ClassClient, SubCancelled, false // the client gave up: not a server error
}
if ev.E.Bot || crawlerUARe.MatchString(ev.UA) || (st == 404 && isBotPath(ev.Path)) {
return ClassBot, "", false
}
switch st {
case 404:
if sameSite(ev) {
return ClassClient, SubBrokenLink, false
}
if ev.Referer != "" && ev.Referer != "-" {
return ClassClient, SubExternalLink, false
}
case 401, 403:
if origin == st && browserLike(ev) {
return ClassClient, SubAuth, false
}
case 400, 405, 413, 422:
return ClassClient, SubValidation, false
}
return ClassClient, SubOther, false
}
+61
View File
@@ -0,0 +1,61 @@
package core
import "testing"
func TestErrorClass(t *testing.T) {
rich := func(e Event) Event {
e.Proto, e.Scheme = "HTTP/2.0", "https"
if e.Router == "" {
e.Router, e.Service = "https-0-abc-gitea@docker", "https-0-abc-gitea@docker"
}
return e
}
moz := "Mozilla/5.0 (Windows NT 10.0) Chrome/120"
cases := []struct {
name string
ev Event
susp bool
class string
sub string
attack bool
}{
{"catchall env probe", Event{Status: 503, OriginStatus: 503, Method: "GET", Path: "/.env", UA: moz, Domain: "blog.example.com", Router: "catchall@file", Service: "error-pages@file", Proto: "HTTP/2.0"}, false, "attack", "", false},
{"no router 404", Event{Status: 404, Method: "GET", Path: "/x", UA: moz, Domain: "a.example.com", Proto: "HTTP/1.1"}, false, "attack", "", false},
{"ip host", Event{Status: 404, OriginStatus: 404, Method: "GET", Path: "/", UA: moz, Domain: "136.0.0.1", Router: "x@docker", Proto: "HTTP/1.1"}, false, "attack", "", false},
{"scanner cat", rich(Event{Status: 404, OriginStatus: 404, Method: "GET", Path: "/wp-login.php", UA: moz, Cat: Scanner}), false, "attack", "", false},
{"weird method", rich(Event{Status: 405, OriginStatus: 405, Method: "PROPFIND", UA: moz}), false, "attack", "", false},
{"empty ua", rich(Event{Status: 404, OriginStatus: 404, Method: "GET", Path: "/a"}), false, "attack", "", false},
{"curl", rich(Event{Status: 404, OriginStatus: 404, Method: "GET", Path: "/a", UA: "curl/8.1"}), false, "attack", "", false},
{"suspicious ip", rich(Event{Status: 404, OriginStatus: 404, Method: "GET", Path: "/a", UA: moz}), true, "attack", "", false},
{"429", rich(Event{Status: 429, Method: "GET", UA: moz}), false, "blocked", "", false},
{"401 origin 0", rich(Event{Status: 401, OriginStatus: 0, Method: "GET", UA: moz, Path: "/x"}), false, "blocked", "", false},
{"504 origin 0", rich(Event{Status: 504, OriginStatus: 0, Method: "GET", UA: moz, Path: "/x"}), false, "proxy", "", false},
{"499 is the client", rich(Event{Status: 499, OriginStatus: 0, Method: "GET", UA: moz, Path: "/x"}), false, "client", "cancelled", false},
{"runner poll", rich(Event{Status: 404, OriginStatus: 404, Method: "POST", UA: "connect-go/1.16 (go1.22)", Path: "/api/actions/runner.v1.RunnerService/FetchTask", Cat: Scanner}), true, "client", "auth_challenge", false},
{"gitea-runner", rich(Event{Status: 401, OriginStatus: 0, Method: "POST", UA: "gitea-runner/0.2", Path: "/api/actions/x"}), true, "client", "auth_challenge", false},
{"502 retry", rich(Event{Status: 502, OriginStatus: 502, Retries: 2, Method: "GET", UA: moz}), false, "proxy", "", false},
{"app 500", rich(Event{Status: 500, OriginStatus: 500, Method: "POST", UA: moz, Path: "/api/x"}), false, "app", "", false},
{"app 500 under attack", rich(Event{Status: 500, OriginStatus: 500, Method: "GET", UA: moz, Path: "/a?x=../", Cat: Exploit}), false, "app", "", true},
{"crawler 404", rich(Event{Status: 404, OriginStatus: 404, Method: "GET", UA: "Mozilla/5.0 (compatible; ElevenlabsCrawler/1.0)", Path: "/z"}), false, "bot", "", false},
{"robots 404", rich(Event{Status: 404, OriginStatus: 404, Method: "GET", UA: moz, Path: "/robots.txt"}), false, "bot", "", false},
{"broken link", rich(Event{Status: 404, OriginStatus: 404, Method: "GET", UA: moz, Path: "/old", Domain: "a.example.com", Referer: "https://a.example.com/index"}), false, "client", "broken_link", false},
{"fetch same-origin", rich(Event{Status: 404, OriginStatus: 404, Method: "GET", UA: moz, Path: "/old", FetchSite: "same-origin"}), false, "client", "broken_link", false},
{"external link", rich(Event{Status: 404, OriginStatus: 404, Method: "GET", UA: moz, Path: "/old", Domain: "a.example.com", Referer: "https://news.ycombinator.com/"}), false, "client", "external_link", false},
{"auth browser", rich(Event{Status: 401, OriginStatus: 401, Method: "GET", UA: moz, Path: "/admin", E: Enrich{Device: "desktop"}}), false, "client", "auth", false},
{"registry challenge", rich(Event{Status: 401, OriginStatus: 401, Method: "GET", UA: "docker/27.0 go/go1.22", Path: "/v2/"}), true, "client", "auth_challenge", false},
{"actions challenge", rich(Event{Status: 401, OriginStatus: 401, Method: "GET", UA: "act_runner/0.2", Path: "/api/actions/x"}), false, "client", "auth_challenge", false},
{"validation", rich(Event{Status: 422, OriginStatus: 422, Method: "POST", UA: moz, Path: "/api/x"}), false, "client", "validation", false},
{"404 plain", rich(Event{Status: 404, OriginStatus: 404, Method: "GET", UA: moz, Path: "/nope"}), false, "client", "other", false},
{"legacy log 500", Event{Status: 500, Method: "GET", UA: moz, Path: "/x", Domain: "a.example.com"}, false, "app", "", false},
{"200", Event{Status: 200}, false, "", "", false},
}
for _, c := range cases {
cl, sub, ua := ErrorClassify(c.ev, c.susp)
if cl != c.class || sub != c.sub || ua != c.attack {
t.Errorf("%s: got %q/%q/%v want %q/%q/%v", c.name, cl, sub, ua, c.class, c.sub, c.attack)
}
if ErrorClass(c.ev, c.susp) != c.class {
t.Errorf("%s: ErrorClass mismatch", c.name)
}
}
}
+14 -1
View File
@@ -149,7 +149,20 @@ type Event struct {
DurationNS int64
Bytes int64
Referer string
E Enrich
// FetchDest is Sec-Fetch-Dest ("document", "empty", "image"...), "" when the
// browser did not send it. Prefetch: Sec-Purpose / Purpose said prefetch.
FetchDest string
Prefetch bool
// Origin details (Traefik only, empty on older logs): what the backend
// answered and where the time went.
OriginStatus int
OriginNS, OverheadNS int64
OriginBytes int64
Retries int
Router, Service string
Proto, Scheme, TLSVer, TLSCiph string
EntryPoint, FetchSite string
E Enrich
}
// Enrich holds what the geo and user-agent databases say about an event. It is
+24
View File
@@ -51,8 +51,23 @@ type traefikLine struct {
Referer string `json:"request_Referer"`
FetchSite string `json:"request_Sec-Fetch-Site"`
FetchDest string `json:"request_Sec-Fetch-Dest"`
SecPurpose string `json:"request_Sec-Purpose"`
Purpose string `json:"request_Purpose"`
Duration int64 `json:"Duration"`
Size int64 `json:"DownstreamContentSize"`
OriginStatus int `json:"OriginStatus"`
OriginDur int64 `json:"OriginDuration"`
Overhead int64 `json:"Overhead"`
OriginSize int64 `json:"OriginContentSize"`
Retries int `json:"RetryAttempts"`
Router string `json:"RouterName"`
Service string `json:"ServiceName"`
Proto string `json:"RequestProtocol"`
Scheme string `json:"RequestScheme"`
TLSVer string `json:"TLSVersion"`
TLSCipher string `json:"TLSCipher"`
EntryPoint string `json:"entryPointName"`
}
// ParseTraefik parses one Traefik JSON access log line.
@@ -82,6 +97,15 @@ func ParseTraefik(line []byte) (Event, error) {
DurationNS: l.Duration, Bytes: l.Size, Referer: clip(l.Referer, 300),
}
ev.Framed = Framed(l.FetchSite, l.FetchDest)
ev.OriginStatus, ev.OriginNS, ev.OverheadNS, ev.OriginBytes, ev.Retries = l.OriginStatus, l.OriginDur, l.Overhead, l.OriginSize, l.Retries
ev.Router, ev.Service = clip(l.Router, 64), clip(l.Service, 64)
ev.Proto, ev.Scheme, ev.TLSVer, ev.TLSCiph = clip(l.Proto, 12), clip(l.Scheme, 8), clip(l.TLSVer, 8), clip(l.TLSCipher, 64)
ev.EntryPoint, ev.FetchSite = clip(l.EntryPoint, 64), clip(strings.ToLower(l.FetchSite), 16)
ev.FetchDest = strings.ToLower(strings.TrimSpace(l.FetchDest))
if len(ev.FetchDest) > 20 {
ev.FetchDest = ev.FetchDest[:20]
}
ev.Prefetch = strings.Contains(strings.ToLower(l.SecPurpose+" "+l.Purpose), "prefetch")
c := Classify(l.Method, l.Path, l.Status)
ev.Cat, ev.Soft, ev.Strong, ev.Weak = c.Cat, c.Soft, c.Strong, c.Weak
return ev, nil
+20
View File
@@ -31,3 +31,23 @@ func TestTraefikSecFetchFraming(t *testing.T) {
}
}
}
func TestTraefikFetchDestAndPrefetch(t *testing.T) {
base := `{"ClientHost":"8.8.8.8","RequestHost":"a.example","RequestMethod":"GET","RequestPath":"/","DownstreamStatus":200,"StartUTC":"2026-11-14T10:00:00Z"`
for _, tc := range []struct {
extra string
dest string
prefetch bool
}{
{``, "", false},
{`,"request_Sec-Fetch-Dest":"Document"`, "document", false},
{`,"request_Sec-Fetch-Dest":"empty"`, "empty", false},
{`,"request_Sec-Purpose":"prefetch;prerender"`, "", true},
{`,"request_Purpose":"prefetch"`, "", true},
} {
ev, err := ParseTraefik([]byte(base + tc.extra + `}`))
if err != nil || ev.FetchDest != tc.dest || ev.Prefetch != tc.prefetch {
t.Errorf("%s: dest=%q prefetch=%v err=%v", tc.extra, ev.FetchDest, ev.Prefetch, err)
}
}
}
+514
View File
@@ -0,0 +1,514 @@
package egress
import (
"fmt"
"math/rand"
"net/netip"
"os"
"path/filepath"
"sort"
"testing"
"time"
)
var t0 = time.Date(2026, 11, 14, 0, 0, 0, 0, time.UTC)
func ip(s string) netip.Addr { return netip.MustParseAddr(s) }
func mk(t time.Time, src, dst, proto string, dport uint16) Event {
return Event{Time: t, Src: ip(src), Dst: ip(dst), Proto: proto, SPort: 40000, DPort: dport, In: "br-1", Out: "enp0s6"}
}
func newEng(t *testing.T, c Config) *Engine {
t.Helper()
if c.Now == nil {
c.Now = func() time.Time { return t0.Add(30 * 24 * time.Hour) }
}
e, err := New(c)
if err != nil {
t.Fatal(err)
}
return e
}
func kinds(r Report, kind string) []Finding {
var o []Finding
for _, f := range r.Findings {
if f.Kind == kind {
o = append(o, f)
}
}
return o
}
func rep(e *Engine) Report { return e.Report(t0.Unix()-86400, t0.Add(14*24*time.Hour).Unix()) }
func TestParse(t *testing.T) {
now := time.Date(2026, 11, 14, 23, 0, 0, 0, time.UTC)
v4 := `2026-11-14T22:01:02.123456+00:00 oracle kernel: [123.4] URUTAU-EGRESS: IN=br-1a2b OUT=enp0s6 MAC=aa SRC=10.0.3.5 DST=93.184.216.34 LEN=60 TOS=0x00 PREC=0x00 TTL=63 ID=1 DF PROTO=TCP SPT=40000 DPT=443 WINDOW=64240 RES=0x00 SYN URGP=0`
ev, err := ParseLine([]byte(v4), now)
if err != nil || ev.Proto != "tcp" || ev.DPort != 443 || ev.SPort != 40000 || ev.Dst.String() != "93.184.216.34" || ev.Host || ev.Time.Hour() != 22 || ev.In != "br-1a2b" {
t.Fatalf("v4: %+v %v", ev, err)
}
v6 := `2026-11-14T22:01:02+00:00 oracle kernel: URUTAU-EGRESS: IN=br-1 OUT=enp0s6 SRC=fd00::5 DST=2606:4700:4700::1111 LEN=80 TC=0 HOPLIMIT=63 FLOWLBL=0 PROTO=UDP SPT=5353 DPT=53 LEN=40`
ev, err = ParseLine([]byte(v6), now)
if err != nil || ev.Proto != "udp" || ev.DPort != 53 || !ev.Dst.Is6() {
t.Fatalf("v6: %+v %v", ev, err)
}
ic := `Nov 14 22:01:02 oracle kernel: [1.0] URUTAU-EGRESS: IN=br-1 OUT=enp0s6 SRC=10.0.3.5 DST=1.1.1.1 LEN=84 PROTO=ICMP TYPE=8 CODE=0 ID=1`
ev, err = ParseLine([]byte(ic), now)
if err != nil || ev.Proto != "icmp" || ev.DPort != 0 || ev.Time.Year() != 2026 || ev.Time.Month() != 11 {
t.Fatalf("icmp: %+v %v", ev, err)
}
ic6 := `Nov 4 22:01:02 oracle kernel: URUTAU-EGRESS: IN=br-1 OUT=x SRC=fd00::5 DST=fd00::6 PROTO=ICMPv6 TYPE=128 CODE=0`
if ev, err = ParseLine([]byte(ic6), now); err != nil || ev.Proto != "icmp" || ev.Time.Day() != 4 {
t.Fatalf("icmp6: %+v %v", ev, err)
}
host := `2026-11-14T22:01:02+00:00 oracle kernel: URUTAU-EGRESS: IN= OUT=enp0s6 SRC=10.0.0.2 DST=8.8.8.8 PROTO=TCP SPT=1 DPT=443 SYN`
if ev, err = ParseLine([]byte(host), now); err != nil || !ev.Host || ev.In != "" {
t.Fatalf("host: %+v %v", ev, err)
}
// December line read in January belongs to the previous year
dec := `Dec 31 23:59:00 h kernel: URUTAU-EGRESS: IN=a OUT=b SRC=1.2.3.4 DST=5.6.7.8 PROTO=TCP DPT=1`
if ev, err = ParseLine([]byte(dec), time.Date(2027, 1, 1, 0, 5, 0, 0, time.UTC)); err != nil || ev.Time.Year() != 2026 {
t.Fatalf("year: %+v %v", ev, err)
}
for _, bad := range []string{"", "garbage", "URUTAU-EGRESS: IN=a OUT=b SRC=nope DST=1.1.1.1 PROTO=TCP", "URUTAU-EGRESS: IN=a SRC=1.1.1.1 DST=2.2.2.2", "\x00\xff URUTAU-EGRESS: ===", "sshd: Accepted publickey"} {
if _, err := ParseLine([]byte(bad), now); err == nil {
t.Fatalf("expected error for %q", bad)
}
}
e := newEng(t, Config{})
e.Ingest([]byte("garbage"))
e.Ingest([]byte(v4))
if e.malformed.Load() != 1 || e.lines.Load() != 1 {
t.Fatalf("counters %d %d", e.malformed.Load(), e.lines.Load())
}
}
func TestWorkloadsAndContainers(t *testing.T) {
e := newEng(t, Config{Workloads: "ciberlab=name:jhxint9g9uz91:scanner;mail=10.0.7.0/24,10.0.8.4/32:mail;lab=10.0.5.0/24"})
e.SetContainers(map[netip.Addr]string{ip("172.18.0.4"): "jhxint9g9uz91-20260101123456", ip("172.18.0.9"): "runner-q620o15zg7-1700000000000"})
cases := []struct {
ev Event
name, role string
}{
{mk(t0, "172.18.0.4", "1.1.1.1", "tcp", 1), "ciberlab", RoleScanner},
{mk(t0, "172.18.0.9", "1.1.1.1", "tcp", 1), "runner-q620o15zg7", RoleDefault},
{mk(t0, "10.0.8.4", "1.1.1.1", "tcp", 1), "mail", RoleMail},
{mk(t0, "10.0.5.77", "1.1.1.1", "tcp", 1), "lab", RoleDefault},
{mk(t0, "10.0.9.9", "1.1.1.1", "tcp", 1), "container 10.0.9.9", RoleDefault},
{Event{Time: t0, Src: ip("10.0.0.2"), Dst: ip("1.1.1.1"), Proto: "tcp", Host: true}, "host", RoleDefault},
}
for _, c := range cases {
if n, r := e.resolve(c.ev); n != c.name || r != c.role {
t.Errorf("%v: got %s/%s want %s/%s", c.ev.Src, n, r, c.name, c.role)
}
}
// IP changes: the map in force at Ingest wins
e.SetContainers(map[netip.Addr]string{ip("172.18.0.5"): "jhxint9g9uz91-20260102000000"})
if n, _ := e.resolve(mk(t0, "172.18.0.5", "1.1.1.1", "tcp", 1)); n != "ciberlab" {
t.Errorf("remap: %s", n)
}
for _, bad := range []string{"x", "a=", "a=notip:scanner", "a=name:bad name"} {
if _, err := ParseWorkloads(bad); err == nil {
t.Errorf("expected error for %q", bad)
}
}
// containers.map file: invalid lines skipped, reload on mtime change
dir := t.TempDir()
p := filepath.Join(dir, "containers.map")
os.WriteFile(p, []byte("172.18.0.4 jhxint9g9uz91-1700000000\nbad line here\n999.1.1.1 x\nfd00::7 six-node\n1.2.3.4 bad/name\n"), 0o644)
m, err := LoadContainers(p)
if err != nil || len(m) != 2 || m[ip("fd00::7")] != "six-node" {
t.Fatalf("map: %v %v", m, err)
}
clock := t0
e2 := newEng(t, Config{Containers: p, Workloads: "c=name:jhxint9g9uz91:scanner", Now: func() time.Time { return clock }})
e2.IngestEvent(mk(t0, "172.18.0.4", "5.5.5.5", "tcp", 443))
if _, ok := e2.ws["c"]; !ok {
t.Fatalf("map file not applied: %v", e2.ws)
}
os.WriteFile(p, []byte("172.18.0.4 other-1700000000\n"), 0o644)
os.Chtimes(p, clock.Add(time.Hour), clock.Add(time.Hour))
clock = clock.Add(time.Minute)
e2.IngestEvent(mk(t0.Add(time.Minute), "172.18.0.4", "5.5.5.5", "tcp", 443))
if _, ok := e2.ws["other"]; !ok {
t.Fatalf("map file not reloaded: %v", e2.ws)
}
}
func feedBeacon(e *Engine, src, dst string, dport uint16, start time.Time, n int, step time.Duration, jitter float64, rnd *rand.Rand) {
t := start
for i := 0; i < n; i++ {
pr := "tcp"
if dport == 123 {
pr = "udp"
}
e.IngestEvent(mk(t, src, dst, pr, dport))
j := 1 + (rnd.Float64()*2-1)*jitter
t = t.Add(time.Duration(float64(step) * j))
}
}
func TestBeaconPositive(t *testing.T) {
bad := func(a netip.Addr) (bool, string) { return a == ip("198.51.100.99"), "known attacker" }
e := newEng(t, Config{BadDst: bad})
rnd := rand.New(rand.NewSource(1))
feedBeacon(e, "10.0.3.5", "203.0.113.7", 443, t0, 50, 60*time.Second, 0.05, rnd)
feedBeacon(e, "10.0.3.5", "198.51.100.99", 8443, t0, 50, 60*time.Second, 0.05, rnd)
r := rep(e)
var got, hi *Finding
for i, f := range kinds(r, "beacon") {
if f.Dst == "203.0.113.7" {
got = &kinds(r, "beacon")[i]
}
if f.Dst == "198.51.100.99" {
hi = &kinds(r, "beacon")[i]
}
}
if got == nil || got.Severity != "medium" || got.IntervalS < 55 || got.IntervalS > 65 || got.Jitter > 0.1 || got.Count < 40 || got.Last <= got.First {
t.Fatalf("beacon: %+v", got)
}
if hi == nil || hi.Severity != "high" {
t.Fatalf("attacker beacon: %+v", hi)
}
}
func TestBeaconNegatives(t *testing.T) {
e := newEng(t, Config{Workloads: "sc=10.0.5.0/24:scanner", Allow: []netip.Prefix{netip.MustParsePrefix("192.0.2.0/24")}})
rnd := rand.New(rand.NewSource(2))
// random intervals
tt := t0
for i := 0; i < 60; i++ {
e.IngestEvent(mk(tt, "10.0.3.5", "203.0.113.8", "tcp", 443))
tt = tt.Add(time.Duration(5+rnd.Intn(600)) * time.Second)
}
// NTP, allowed dst, allowed resolver
feedBeacon(e, "10.0.3.5", "203.0.113.9", 123, t0, 50, 128*time.Second, 0, rnd)
feedBeacon(e, "10.0.3.5", "192.0.2.4", 443, t0, 50, 60*time.Second, 0, rnd)
for i := 0; i < 50; i++ {
ev := mk(t0.Add(time.Duration(i)*time.Minute), "10.0.3.5", "1.1.1.1", "udp", 53)
e.IngestEvent(ev)
}
// daily scan: 8 days, 60 targets each, scanner role; and hourly scan
for d := 0; d < 8; d++ {
for i := 0; i < 60; i++ {
e.IngestEvent(mk(t0.Add(time.Duration(d)*24*time.Hour+time.Duration(i)*time.Second), "10.0.5.2", fmt.Sprintf("203.0.113.%d", 100+i), "tcp", 22))
}
}
for h := 0; h < 12; h++ {
for i := 0; i < 60; i++ {
e.IngestEvent(mk(t0.Add(10*24*time.Hour+time.Duration(h)*time.Hour+time.Duration(i)*time.Second), "10.0.5.2", fmt.Sprintf("198.18.0.%d", 1+i), "tcp", 22))
}
}
if f := kinds(rep(e), "beacon"); len(f) != 0 {
t.Fatalf("unexpected beacons: %+v", f)
}
if f := kinds(rep(e), "dns_bypass"); len(f) != 0 {
t.Fatalf("usual resolver flagged: %+v", f)
}
}
func fanOut(e *Engine, src string, start time.Time, n int, port uint16) {
fanOutNet(e, src, "198.18", start, n, port)
}
func fanOutNet(e *Engine, src, net string, start time.Time, n int, port uint16) {
for i := 0; i < n; i++ {
e.IngestEvent(mk(start.Add(time.Duration(i)*time.Second), src, fmt.Sprintf("%s.%d.%d", net, i/200, 1+i%200), "tcp", port))
}
}
func TestScannerSuppressedVsDefault(t *testing.T) {
bad := func(a netip.Addr) (bool, string) { return a == ip("198.18.0.5"), "attacker" }
e := newEng(t, Config{Workloads: "ciberlab=10.0.5.0/24:scanner", BadDst: bad})
fanOut(e, "10.0.5.2", t0, 300, 80)
fanOutNet(e, "10.0.9.9", "198.19", t0, 300, 80) // default workload
r := rep(e)
var sc, df WorkloadOut
for _, w := range r.Workloads {
switch w.Name {
case "ciberlab":
sc = w
case "container 10.0.9.9":
df = w
}
}
if sc.Suppressed < 240 || sc.Conns > 60 {
t.Fatalf("scanner not suppressed: %+v", sc)
}
if df.Suppressed != 0 || df.Conns != 300 {
t.Fatalf("default must not be suppressed: %+v", df)
}
scan := kinds(r, "scan")
if len(scan) != 1 || scan[0].Workload != "container 10.0.9.9" || scan[0].Severity != "high" {
t.Fatalf("scan findings: %+v", scan)
}
if len(r.Scanner.Bursts) != 1 {
t.Fatalf("bursts: %+v", r.Scanner.Bursts)
}
b := r.Scanner.Bursts[0]
if b.Workload != "ciberlab" || b.Targets < 240 || len(b.Nets) == 0 || b.Ports[0] != 80 || b.BadDstHit != 1 {
t.Fatalf("burst: %+v", b)
}
for _, f := range kinds(r, "bad_dst") {
if f.Workload == "ciberlab" {
t.Fatalf("bad_dst of scanner inside a burst must only be counted: %+v", f)
}
}
for _, d := range r.TopDst {
for _, w := range d.Workloads {
if w == "ciberlab" {
t.Fatalf("scanner burst flow in top_dst: %+v", d)
}
}
}
// the burst closes after 5 minutes of quiet and a later flow is normal
e.IngestEvent(mk(t0.Add(time.Hour), "10.0.5.2", "203.0.113.50", "tcp", 443))
r = rep(e)
if len(r.Scanner.Bursts) != 1 || r.Scanner.Bursts[0].End > t0.Add(10*time.Minute).Unix() {
t.Fatalf("burst end: %+v", r.Scanner.Bursts)
}
}
func TestScannerBeaconStillDetectedDuringBurst(t *testing.T) {
e := newEng(t, Config{Workloads: "ciberlab=10.0.5.0/24:scanner"})
rnd := rand.New(rand.NewSource(3))
// beacon every 60 s for 60 min, scan from minute 10 for 150 s; ordered by time
var evs []Event
for i := 0; i < 60; i++ {
evs = append(evs, mk(t0.Add(time.Duration(i)*time.Minute+time.Duration(rnd.Intn(3))*time.Second), "10.0.5.2", "203.0.113.77", "tcp", 8443))
}
for i := 0; i < 150; i++ {
evs = append(evs, mk(t0.Add(10*time.Minute+10*time.Second+time.Duration(i)*time.Second), "10.0.5.2", fmt.Sprintf("198.18.0.%d", 1+i), "tcp", 443))
}
sort.SliceStable(evs, func(i, j int) bool { return evs[i].Time.Before(evs[j].Time) })
for _, ev := range evs {
e.IngestEvent(ev)
}
r := rep(e)
var found bool
for _, f := range kinds(r, "beacon") {
found = found || f.Dst == "203.0.113.77"
}
if !found {
t.Fatalf("beacon of the scanner lost: %+v", r.Findings)
}
if len(r.Scanner.Bursts) == 0 {
t.Fatal("expected a burst")
}
for _, w := range r.Workloads {
if w.Name == "ciberlab" && (w.Conns < 55 || w.Suppressed < 140) {
t.Fatalf("beacon flows must stay in normal accounting: %+v", w)
}
}
}
func TestSuspiciousPorts(t *testing.T) {
e := newEng(t, Config{Workloads: "mail=10.0.7.0/24:mail"})
at := func(i int) time.Time { return t0.Add(time.Duration(i) * time.Minute) }
e.IngestEvent(mk(at(0), "10.0.3.5", "203.0.113.1", "tcp", 25))
e.IngestEvent(mk(at(1), "10.0.7.5", "203.0.113.2", "tcp", 25)) // mail role: fine
e.IngestEvent(mk(at(2), "10.0.3.5", "203.0.113.3", "tcp", 6667))
e.IngestEvent(mk(at(3), "10.0.3.5", "203.0.113.4", "tcp", 3333))
e.IngestEvent(mk(at(4), "10.0.3.5", "203.0.113.5", "tcp", 9001))
e.IngestEvent(mk(at(5), "10.0.3.5", "203.0.113.6", "udp", 3333)) // udp: ignored
e.IngestEvent(mk(at(6), "10.0.3.5", "203.0.113.7", "udp", 853))
e.IngestEvent(mk(at(7), "10.0.3.5", "93.184.216.34", "udp", 53))
e.IngestEvent(mk(at(8), "10.0.3.5", "10.9.9.9", "udp", 53)) // private: not bypass
r := rep(e)
by := map[string]string{}
for _, f := range kinds(r, "port") {
by[f.Dst] = f.Severity
}
if len(by) != 4 || by["203.0.113.1"] != "medium" || by["203.0.113.4"] != "high" || by["203.0.113.2"] != "" {
t.Fatalf("ports: %v", by)
}
if d := kinds(r, "dns_bypass"); len(d) != 1 || d[0].Dst != "93.184.216.34" {
t.Fatalf("dns_bypass (DoT is tcp-only, 53 to unusual public): %+v", d)
}
// custom resolver list: Google no longer allowed
e2 := newEng(t, Config{Resolvers: "10.0.0.53"})
e2.IngestEvent(mk(t0, "10.0.3.5", "8.8.8.8", "udp", 53))
e2.IngestEvent(mk(t0, "10.0.3.5", "10.0.0.53", "udp", 53))
if d := kinds(rep(e2), "dns_bypass"); len(d) != 1 || d[0].Dst != "8.8.8.8" {
t.Fatalf("custom resolvers: %+v", d)
}
}
func TestBadDstAndNewGeo(t *testing.T) {
geo := func(s string) (string, string, string) {
if s == "203.0.113.50" {
return "RU", "AS1", "x"
}
return "BR", "AS2", "y"
}
bad := func(a netip.Addr) (bool, string) { return a == ip("203.0.113.9"), "Tor exit" }
e := newEng(t, Config{Geo: geo, BadDst: bad, Workloads: "sc=10.0.5.0/24:scanner"})
e.IngestEvent(mk(t0, "10.0.3.5", "203.0.113.1", "tcp", 443))
e.IngestEvent(mk(t0.Add(25*time.Hour), "10.0.3.5", "203.0.113.2", "tcp", 443)) // known country
e.IngestEvent(mk(t0.Add(26*time.Hour), "10.0.3.5", "203.0.113.50", "tcp", 443))
e.IngestEvent(mk(t0.Add(27*time.Hour), "10.0.3.5", "203.0.113.9", "tcp", 443))
e.IngestEvent(mk(t0, "10.0.5.2", "203.0.113.1", "tcp", 443))
e.IngestEvent(mk(t0.Add(26*time.Hour), "10.0.5.2", "203.0.113.50", "tcp", 443)) // scanner ignored
r := rep(e)
g := kinds(r, "new_geo")
if len(g) != 1 || g[0].Workload != "container 10.0.3.5" || g[0].Dst != "203.0.113.50" || g[0].Severity != "low" {
t.Fatalf("new_geo: %+v", g)
}
if b := kinds(r, "bad_dst"); len(b) != 1 || b[0].Severity != "high" || b[0].Detail != "Tor exit" {
t.Fatalf("bad_dst: %+v", b)
}
if len(r.TopDst) == 0 || r.TopDst[0].CC == "" {
t.Fatalf("top_dst not enriched: %+v", r.TopDst)
}
}
func TestMemoryLimits(t *testing.T) {
e := newEng(t, Config{})
// 60k distinct pairs, 15 s apart (never a fan-out) and spam findings
for i := 0; i < 60000; i++ {
dst := fmt.Sprintf("%d.%d.%d.%d", 20+i/65536, (i/256)%256, i%256, 1)
port := uint16(443)
if i < 3000 {
port = 25
}
e.IngestEvent(mk(t0.Add(time.Duration(i)*15*time.Second), "10.0.3.5", dst, "tcp", port))
}
if e.pairs.len() > MaxPairs || e.dsts.len() > MaxDsts || len(e.findings) > MaxFindings {
t.Fatalf("limits: %d %d %d", e.pairs.len(), e.dsts.len(), len(e.findings))
}
if len(e.findings) != MaxFindings {
t.Fatalf("findings should be capped at the limit, got %d", len(e.findings))
}
w := e.ws["container 10.0.3.5"]
n := 0
for i := range w.hours {
if w.hours[i].hour != 0 {
n++
}
if len(w.hours[i].dsts) > setCap {
t.Fatal("hour set not capped")
}
}
if n > HourBuckets {
t.Fatal("buckets")
}
// dedupe: same key updates count
e2 := newEng(t, Config{})
for i := 0; i < 5; i++ {
e2.IngestEvent(mk(t0.Add(time.Duration(i)*time.Minute), "10.0.3.5", "203.0.113.1", "tcp", 6667))
}
if f := kinds(rep(e2), "port"); len(f) != 1 || f[0].Count != 5 {
t.Fatalf("dedupe: %+v", f)
}
}
func TestReportMergeSanitize(t *testing.T) {
e := newEng(t, Config{})
e.IngestEvent(mk(t0, "10.0.3.5", "203.0.113.1", "tcp", 6667))
local := e.Report(t0.Unix()-3600, t0.Unix()+3600)
peer := e.Report(t0.Unix()-7200, t0.Unix()+3600)
peer.Sanitize("oracle")
local.Merge(peer, "oracle")
if len(local.Findings) != 2 || local.Findings[1].Host != "oracle" && local.Findings[0].Host != "oracle" {
t.Fatalf("merge: %+v", local.Findings)
}
if _, ok := local.Timeline.Series["oracle/container 10.0.3.5"]; !ok {
t.Fatalf("series: %v", local.Timeline.Series)
}
}
func TestNameMatchExactAndPrefix(t *testing.T) {
e := newEng(t, Config{Workloads: "a=name:web:default;b=name:api*:default;c=name:pay:default"})
e.SetContainers(map[netip.Addr]string{ip("172.18.0.1"): "web-1700000000000", ip("172.18.0.2"): "webshell-1700000000000",
ip("172.18.0.3"): "apigw-17", ip("172.18.0.4"): "pay", ip("172.18.0.5"): "payroll"})
for src, want := range map[string]string{"172.18.0.1": "a", "172.18.0.2": "webshell", "172.18.0.3": "b", "172.18.0.4": "c", "172.18.0.5": "payroll"} {
if n, _ := e.resolve(mk(t0, src, "1.1.1.1", "tcp", 1)); n != want {
t.Errorf("%s: %s want %s", src, n, want)
}
}
}
func TestHostWorkloadRole(t *testing.T) {
e := newEng(t, Config{Workloads: "host=host:mail"})
n, r := e.resolve(Event{Time: t0, Src: ip("10.0.0.2"), Dst: ip("1.1.1.1"), Proto: "tcp", Host: true})
if n != "host" || r != RoleMail {
t.Fatalf("%s/%s", n, r)
}
e.IngestEvent(Event{Time: t0, Src: ip("10.0.0.2"), Dst: ip("203.0.113.5"), Proto: "tcp", DPort: 25, Host: true})
if f := kinds(rep(e), "port"); len(f) != 0 {
t.Fatalf("mail host flagged: %+v", f)
}
}
func TestResolvConfAllowed(t *testing.T) {
p := filepath.Join(t.TempDir(), "resolv.conf")
os.WriteFile(p, []byte("# x\nnameserver 203.0.113.53\nnameserver fe80::1%eth0\nsearch x\n"), 0o644)
e := newEng(t, Config{ResolvConf: []string{p, "/nonexistent"}})
for i := 0; i < 3; i++ {
e.IngestEvent(mk(t0.Add(time.Duration(i)*time.Second), "10.0.3.5", "203.0.113.53", "udp", 53))
}
if f := kinds(rep(e), "dns_bypass"); len(f) != 0 {
t.Fatalf("resolv.conf nameserver flagged: %+v", f)
}
e.IngestEvent(mk(t0, "10.0.3.5", "203.0.113.54", "udp", 53))
if f := kinds(rep(e), "dns_bypass"); len(f) != 1 {
t.Fatalf("other resolver not flagged: %+v", f)
}
}
func TestAllowedPollerNoBeacon(t *testing.T) {
e := newEng(t, Config{Allow: []netip.Prefix{netip.MustParsePrefix("203.0.113.0/24")}})
feedBeacon(e, "10.0.3.5", "203.0.113.7", 443, t0, 60, 60*time.Second, 0, rand.New(rand.NewSource(1)))
if f := kinds(rep(e), "beacon"); len(f) != 0 {
t.Fatalf("%+v", f)
}
}
func TestNTPExemption(t *testing.T) {
bad := func(a netip.Addr) (bool, string) { return a == ip("203.0.113.99"), "known attacker" }
e := newEng(t, Config{BadDst: bad})
rnd := rand.New(rand.NewSource(1))
feedBeacon(e, "10.0.3.5", "203.0.113.10", 123, t0, 50, 128*time.Second, 0, rnd) // normal poll: exempt
feedBeacon(e, "10.0.3.5", "203.0.113.11", 123, t0, 50, 60*time.Second, 0, rnd) // fast NTP: not exempt
feedBeacon(e, "10.0.3.5", "203.0.113.99", 123, t0, 50, 128*time.Second, 0, rnd) // bad dst: never exempt
got := map[string]bool{}
for _, f := range kinds(rep(e), "beacon") {
got[f.Dst] = true
}
if got["203.0.113.10"] || !got["203.0.113.11"] || !got["203.0.113.99"] {
t.Fatalf("%v", got)
}
}
func TestBeaconDuringContinuousScan(t *testing.T) {
e := newEng(t, Config{Workloads: "ciberlab=10.0.5.0/24:scanner"})
// a light scan every 4 min (each opens or keeps the burst alive) for 2 h; the C2
// is contacted every 60 s starting 12 min AFTER the first burst opened
var evs []Event
for k := 0; k < 30; k++ {
for i := 0; i < 60; i++ {
evs = append(evs, mk(t0.Add(time.Duration(k)*4*time.Minute+time.Duration(i)*time.Second), "10.0.5.2",
fmt.Sprintf("198.18.%d.%d", k, 1+i), "tcp", 443))
}
}
for i := 0; i < 100; i++ {
evs = append(evs, mk(t0.Add(12*time.Minute+time.Duration(i)*time.Minute+30*time.Second), "10.0.5.2", "203.0.113.77", "tcp", 8443))
}
sort.SliceStable(evs, func(i, j int) bool { return evs[i].Time.Before(evs[j].Time) })
for _, ev := range evs {
e.IngestEvent(ev)
}
var found bool
for _, f := range kinds(rep(e), "beacon") {
found = found || f.Dst == "203.0.113.77"
}
if !found {
t.Fatalf("C2 invisible during the continuous scan: %+v", rep(e).Findings)
}
if e.fanSeen.len() > maxFanSeen {
t.Fatal("fanSeen unbounded")
}
}
+869
View File
@@ -0,0 +1,869 @@
package egress
import (
"container/list"
"fmt"
"hash/fnv"
"math"
"net/netip"
"os"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
)
// Limits and thresholds.
const (
MaxPairs = 50000
MaxDsts = 50000
MaxFindings = 2000
HourBuckets = 720 // 30 days
maxWorkloads = 256
maxClosedBurst = 200
maxFanSeen = 20000 // (workload,dst,port,proto) tuples seen only as fan-out
fanPromoteN = 3 // hits within fanPromoteWin that turn a fan-out flow into a pair
fanPromoteWin = 3600
fanDsts = 50
fanPorts = 100
fanWindow = 600 // seconds
burstQuiet = 300 // a burst closes after 5 min without fan-out
maxWin = 8192
ringSize = 64
beaconMinN = 8
beaconSpan = 1800
beaconMinIv = 10
beaconMaxIv = 6 * 3600
beaconCV = 0.25
beaconMAD = 0.20
setCap = 64
ntpMinIv = 64
)
// Config of the engine.
type Config struct {
// Workloads: "ciberlab=10.0.5.0/24:scanner;mail=name:protocols:mail".
Workloads string
// Resolvers lists the allowed DNS resolvers (comma separated IPs). Rule:
// DNS (53 tcp/udp) or DoT (853) from a non-resolver workload to a public
// address that is not an allowed resolver is "dns_bypass". When the list is
// empty the allowed set is the usual public resolvers (Cloudflare, Google,
// Quad9, OpenDNS), so only DoT and port 53 to unusual public IPs alert.
Resolvers string
// Allow lists destinations that never produce a finding (peers, own servers).
Allow []netip.Prefix
// Containers is the path of the containers.map file (optional); it is
// reloaded when its mtime changes.
Containers string
// Geo enriches a destination (cc, asn, org); BadDst says whether a
// destination is a known attacker or Tor exit (and why).
Geo func(ip string) (cc, asn, org string)
BadDst func(netip.Addr) (bool, string)
Now func() time.Time
// Learn is the per-workload learning time before new_geo (default 24h).
Learn time.Duration
// ResolvConf lists resolv.conf files whose nameservers are allowed resolvers
// (default: /etc/resolv.conf and /logs/host/resolv.conf, both optional).
ResolvConf []string
}
var usualResolvers = []string{"1.1.1.1", "1.0.0.1", "8.8.8.8", "8.8.4.4", "9.9.9.9", "149.112.112.112",
"208.67.222.222", "208.67.220.220", "2606:4700:4700::1111", "2606:4700:4700::1001",
"2001:4860:4860::8888", "2001:4860:4860::8844", "2620:fe::fe"}
type lru[K comparable, V any] struct {
cap int
l *list.List
m map[K]*list.Element
}
type lent[K comparable, V any] struct {
k K
v V
}
func newLRU[K comparable, V any](n int) *lru[K, V] {
return &lru[K, V]{cap: n, l: list.New(), m: map[K]*list.Element{}}
}
func (c *lru[K, V]) get(k K) (v V, ok bool) {
el, ok := c.m[k]
if !ok {
return v, false
}
c.l.MoveToFront(el)
return el.Value.(*lent[K, V]).v, true
}
func (c *lru[K, V]) put(k K, v V) {
if el, ok := c.m[k]; ok {
el.Value.(*lent[K, V]).v = v
c.l.MoveToFront(el)
return
}
c.m[k] = c.l.PushFront(&lent[K, V]{k, v})
if c.l.Len() > c.cap {
el := c.l.Back()
delete(c.m, el.Value.(*lent[K, V]).k)
c.l.Remove(el)
}
}
func (c *lru[K, V]) len() int { return c.l.Len() }
type pairKey struct {
wl string
dst netip.Addr
dport uint16
proto string
}
type pairState struct {
ts [ringSize]uint32
n int
total uint32
fan, nonFan uint32
first, last int64
flagged bool
fkey string
interval, cv float64
}
func (p *pairState) add(t int64, fan bool) {
if p.total == 0 {
p.first = t
}
p.total++
if fan {
p.fan++
} else {
p.nonFan++
}
if p.n > 0 && t-int64(p.ts[p.n-1]) < 2 {
p.last = t
return // retries of the same second are one beat
}
if p.n == ringSize {
copy(p.ts[:], p.ts[1:])
p.n--
}
p.ts[p.n] = uint32(t)
p.n++
p.last = t
}
type dayN struct {
day int32
n uint32
}
type dstStat struct {
ip netip.Addr
cc, asn, og string
days []dayN
wls []string
ports []uint16
}
type hbucket struct {
hour int64
conns, supp uint32
dsts, ports []uint32
}
type burstState struct {
start, lastFan int64
conns, badHits uint32
targets map[netip.Addr]struct{}
nets map[netip.Prefix]uint32
ports map[uint16]uint32
}
type wstate struct {
name, role string
first int64
hours [HourBuckets]hbucket
win map[netip.Addr]int64
wports map[uint16]int64
lastPrune int64
burst *burstState
geo map[string]struct{}
// recent are the normal flows of the fan-out window: when a burst opens
// they are re-read as part of it (the first 49 probes of a scan).
recent []winFlow
}
type winFlow struct {
pk pairKey
t int64
badKey string // bad_dst finding this flow raised, if any
}
// Engine analyses egress events. Safe for concurrent use.
type Engine struct {
mu sync.Mutex
cfg Config
wls []workloadDef
resolvers map[netip.Addr]bool
now func() time.Time
containers map[netip.Addr]string
mapMod time.Time
mapCheck time.Time
ws map[string]*wstate
pairs *lru[pairKey, *pairState]
dsts *lru[netip.Addr, *dstStat]
fanSeen *lru[pairKey, *fanRec]
findings map[string]*Finding
closed []BurstOut
maxT int64
lines, malformed atomic.Uint64
last atomic.Int64
stateFn atomic.Pointer[func() string]
}
// New builds an engine.
func New(c Config) (*Engine, error) {
wls, err := ParseWorkloads(c.Workloads)
if err != nil {
return nil, err
}
e := &Engine{cfg: c, wls: wls, now: c.Now, resolvers: map[netip.Addr]bool{}, containers: map[netip.Addr]string{},
ws: map[string]*wstate{}, pairs: newLRU[pairKey, *pairState](MaxPairs), dsts: newLRU[netip.Addr, *dstStat](MaxDsts),
findings: map[string]*Finding{}, fanSeen: newLRU[pairKey, *fanRec](maxFanSeen)}
if e.now == nil {
e.now = time.Now
}
if e.cfg.Learn <= 0 {
e.cfg.Learn = 24 * time.Hour
}
list := strings.Split(c.Resolvers, ",")
if strings.TrimSpace(c.Resolvers) == "" {
list = usualResolvers
}
for _, s := range list {
if s = strings.TrimSpace(s); s == "" {
continue
}
a, err := netip.ParseAddr(s)
if err != nil {
return nil, fmt.Errorf("resolver %q: %w", s, err)
}
e.resolvers[a.Unmap()] = true
}
rc := c.ResolvConf
if rc == nil {
rc = []string{"/etc/resolv.conf", "/logs/host/resolv.conf"}
}
for _, p := range rc {
for _, a := range readNameservers(p) {
e.resolvers[a] = true
}
}
return e, nil
}
// readNameservers returns the nameserver addresses of a resolv.conf (missing file: none).
func readNameservers(path string) []netip.Addr {
b, err := os.ReadFile(path)
if err != nil {
return nil
}
var out []netip.Addr
for _, ln := range strings.Split(string(b), "\n") {
f := strings.Fields(ln)
if len(f) >= 2 && f[0] == "nameserver" {
if a, err := netip.ParseAddr(f[1]); err == nil {
out = append(out, a.WithZone("").Unmap())
}
}
if len(out) >= 16 {
break
}
}
return out
}
// fanRec accumulates the sightings of a flow that was only ever seen as fan-out.
type fanRec struct{ ts []int64 }
// fanPromote records one fan-out sighting; when the same flow shows up
// fanPromoteN times within the hour it is a real pair (a C2 contacted during a
// continuous scan), returned with its accumulated timestamps.
func (e *Engine) fanPromote(pk pairKey, t int64) *pairState {
r, ok := e.fanSeen.get(pk)
if !ok {
r = &fanRec{}
e.fanSeen.put(pk, r)
}
k := 0
for _, x := range r.ts {
if t-x <= fanPromoteWin {
r.ts[k] = x
k++
}
}
r.ts = r.ts[:k]
if n := len(r.ts); n == 0 || t-r.ts[n-1] >= 2 { // retries of the same second are one beat
r.ts = append(r.ts, t)
}
if len(r.ts) < fanPromoteN {
return nil
}
p := &pairState{}
for _, x := range r.ts[:len(r.ts)-1] {
p.add(x, false)
}
if el, ok := e.fanSeen.m[pk]; ok {
e.fanSeen.l.Remove(el)
delete(e.fanSeen.m, pk)
}
return p
}
// SetContainers replaces the address to container-name map (tests, wiring).
func (e *Engine) SetContainers(m map[netip.Addr]string) {
e.mu.Lock()
e.containers = m
e.mu.Unlock()
}
func (e *Engine) reloadMap() {
if e.cfg.Containers == "" {
return
}
n := e.now()
if n.Sub(e.mapCheck) < 5*time.Second {
return
}
e.mapCheck = n
fi, err := os.Stat(e.cfg.Containers)
if err != nil || fi.ModTime().Equal(e.mapMod) {
return
}
if m, err := LoadContainers(e.cfg.Containers); err == nil {
e.containers, e.mapMod = m, fi.ModTime()
}
}
// Ingest parses and analyses one log line.
func (e *Engine) Ingest(line []byte) {
ev, err := ParseLine(line, e.now())
if err != nil {
if len(line) > 0 {
e.malformed.Add(1)
}
return
}
e.lines.Add(1)
e.last.Store(e.now().Unix())
e.IngestEvent(ev)
}
// IngestEvent analyses one parsed event.
func (e *Engine) IngestEvent(ev Event) {
e.mu.Lock()
defer e.mu.Unlock()
e.ingest(ev)
}
func (e *Engine) allowed(a netip.Addr) bool {
for _, p := range e.cfg.Allow {
if p.Contains(a) {
return true
}
}
return false
}
func fanCounts(role string, ev Event) bool {
switch {
case role == RoleMail && (ev.DPort == 25 || ev.DPort == 465 || ev.DPort == 587):
return false // a mail server legitimately talks to many MX
case role == RoleResolver && ev.DPort == 53:
return false // a recursive resolver talks to many authoritative servers
}
return true
}
func (e *Engine) wstate(name, role string, t int64) *wstate {
if w, ok := e.ws[name]; ok {
return w
}
if len(e.ws) >= maxWorkloads {
name, role = "container other", RoleDefault
if w, ok := e.ws[name]; ok {
return w
}
}
w := &wstate{name: name, role: role, first: t, win: map[netip.Addr]int64{}, wports: map[uint16]int64{}, geo: map[string]struct{}{}}
e.ws[name] = w
return w
}
func h32(a netip.Addr) uint32 {
b := a.As16()
h := fnv.New32a()
h.Write(b[:])
return h.Sum32()
}
func addSet(s []uint32, v uint32) []uint32 {
for _, x := range s {
if x == v {
return s
}
}
if len(s) >= setCap {
return s
}
return append(s, v)
}
func (w *wstate) bucket(t int64) *hbucket {
h := t / 3600
b := &w.hours[h%HourBuckets]
if b.hour != h {
*b = hbucket{hour: h}
}
return b
}
func (e *Engine) ingest(ev Event) {
t := ev.Time.Unix()
if t <= 0 {
return
}
if t > e.maxT {
e.maxT = t
}
e.reloadMap()
name, role := e.resolve(ev)
ws := e.wstate(name, role, t)
role = ws.role
allowed := e.allowed(ev.Dst)
dport := ev.DPort
if ev.Proto == "icmp" {
dport = 0
}
counts := !allowed && fanCounts(role, ev)
if ws.burst != nil && t-ws.burst.lastFan > burstQuiet {
e.closeBurst(ws)
}
if counts && ws.burst == nil {
e.window(ws, ev.Dst, dport, t)
}
inBurst := counts && ws.burst != nil
pk := pairKey{ws.name, ev.Dst, dport, ev.Proto}
p, _ := e.pairs.get(pk)
fan := inBurst && (p == nil || p.nonFan < 3)
if p == nil && fan && !allowed {
if np := e.fanPromote(pk, t); np != nil {
p, fan = np, false
e.pairs.put(pk, p)
}
}
if p == nil && !fan && !allowed {
p = &pairState{}
e.pairs.put(pk, p) // fan-out flows create pairs only when repeated: a scan must not evict real ones
}
if p != nil {
p.add(t, fan)
}
scanner := role == RoleScanner
if fan {
e.burstFlow(ws, ev, dport, t, scanner)
if scanner {
ws.bucket(t).supp++
return
}
}
b := ws.bucket(t)
b.conns++
if counts && ws.burst == nil && len(ws.recent) < maxWin {
ws.recent = append(ws.recent, winFlow{pk: pk, t: t})
}
b.dsts = addSet(b.dsts, h32(ev.Dst))
b.ports = addSet(b.ports, uint32(dport))
ds := e.dstStat(ws.name, ev.Dst, dport, t)
if allowed {
return
}
e.checks(ws, ev, dport, t, ds, p, fan)
if n := len(ws.recent); n > 0 && ws.recent[n-1].t == t && ws.recent[n-1].pk == pk {
if f := e.findings[fmt.Sprintf("bad_dst|%s|%s|%d", ws.name, ev.Dst, dport)]; f != nil {
ws.recent[n-1].badKey = fmt.Sprintf("bad_dst|%s|%s|%d", ws.name, ev.Dst, dport)
}
}
}
// retro re-reads the flows seen before the burst opened as part of it.
func (e *Engine) retro(ws *wstate) {
cnt := map[pairKey]uint32{}
for _, f := range ws.recent {
cnt[f.pk]++
}
moved := map[pairKey]bool{}
for pk, n := range cnt {
// a pair established before the window, or hit 4+ times inside it (a probe is hit once or retried), stays normal
if p, ok := e.pairs.get(pk); ok && n < 4 && p.nonFan >= n && p.nonFan-n < 3 {
p.fan += n
p.nonFan -= n
moved[pk] = true
} else if !ok && n < 4 {
moved[pk] = true // evicted pair: still a probe
}
}
for _, f := range ws.recent {
if !moved[f.pk] {
continue
}
if ws.role != RoleScanner {
continue
}
b := &ws.hours[(f.t/3600)%HourBuckets]
if b.hour == f.t/3600 && b.conns > 0 {
b.conns--
b.supp++
}
if ds, ok := e.dsts.get(f.pk.dst); ok {
for i := range ds.days {
if ds.days[i].day == int32(f.t/86400) && ds.days[i].n > 0 {
ds.days[i].n--
}
}
}
if f.badKey != "" {
if fd := e.findings[f.badKey]; fd != nil {
if fd.Count--; fd.Count <= 0 {
delete(e.findings, f.badKey)
}
ws.burst.badHits++
}
}
}
ws.recent = ws.recent[:0]
}
func (e *Engine) window(ws *wstate, dst netip.Addr, dport uint16, t int64) {
if t-ws.lastPrune >= 10 {
for k, v := range ws.win {
if t-v > fanWindow {
delete(ws.win, k)
}
}
for k, v := range ws.wports {
if t-v > fanWindow {
delete(ws.wports, k)
}
}
ws.lastPrune = t
k := 0
for _, f := range ws.recent {
if t-f.t <= fanWindow {
ws.recent[k] = f
k++
}
}
ws.recent = ws.recent[:k]
}
if _, ok := ws.win[dst]; ok || len(ws.win) < maxWin {
ws.win[dst] = t
}
if dport != 0 {
ws.wports[dport] = t
}
if len(ws.win) >= fanDsts || len(ws.wports) >= fanPorts {
start := t
for _, v := range ws.win {
if v < start {
start = v
}
}
ws.burst = &burstState{start: start, lastFan: t, targets: map[netip.Addr]struct{}{},
nets: map[netip.Prefix]uint32{}, ports: map[uint16]uint32{}}
clear(ws.win)
clear(ws.wports)
e.retro(ws)
}
}
func (e *Engine) burstFlow(ws *wstate, ev Event, dport uint16, t int64, scanner bool) {
bs := ws.burst
bs.lastFan = t
bs.conns++
if len(bs.targets) < 50000 {
bs.targets[ev.Dst] = struct{}{}
}
bits := 24
if ev.Dst.Is6() {
bits = 48
}
np, _ := ev.Dst.Prefix(bits)
if _, ok := bs.nets[np]; ok || len(bs.nets) < 512 {
bs.nets[np]++
}
if dport != 0 {
if _, ok := bs.ports[dport]; ok || len(bs.ports) < 1024 {
bs.ports[dport]++
}
}
if scanner {
if e.cfg.BadDst != nil {
if bad, _ := e.cfg.BadDst(ev.Dst); bad {
bs.badHits++
}
}
return
}
if bs.conns%32 == 1 {
e.addFinding("scan", "high", ws.name, "", 0, "", t, 0, 0, bs.detail(), 1)
} else {
e.addFinding("scan", "high", ws.name, "", 0, "", t, 0, 0, "", 1)
}
}
func (bs *burstState) detail() string {
return fmt.Sprintf("fan-out: %d targets, %d ports, %d connections", len(bs.targets), len(bs.ports), bs.conns)
}
func (e *Engine) closeBurst(ws *wstate) {
bs := ws.burst
ws.burst = nil
ws.recent = ws.recent[:0]
clear(ws.win)
clear(ws.wports)
if ws.role != RoleScanner {
e.addFinding("scan", "high", ws.name, "", 0, "", bs.lastFan, 0, 0, bs.detail(), 0)
return
}
e.closed = append(e.closed, bs.out(ws.name, bs.lastFan))
if len(e.closed) > maxClosedBurst {
e.closed = e.closed[len(e.closed)-maxClosedBurst:]
}
}
func (e *Engine) dstStat(wl string, dst netip.Addr, dport uint16, t int64) *dstStat {
ds, ok := e.dsts.get(dst)
if !ok {
ds = &dstStat{ip: dst}
if e.cfg.Geo != nil && isGlobal(dst) {
ds.cc, ds.asn, ds.og = e.cfg.Geo(dst.String())
}
e.dsts.put(dst, ds)
}
day := int32(t / 86400)
if n := len(ds.days); n > 0 && ds.days[n-1].day == day {
ds.days[n-1].n++
} else if n == 0 || ds.days[n-1].day < day {
ds.days = append(ds.days, dayN{day, 1})
if len(ds.days) > 30 {
ds.days = ds.days[1:]
}
}
has := false
for _, w := range ds.wls {
has = has || w == wl
}
if !has && len(ds.wls) < 8 {
ds.wls = append(ds.wls, wl)
}
hp := false
for _, p := range ds.ports {
hp = hp || p == dport
}
if !hp && len(ds.ports) < 8 {
ds.ports = append(ds.ports, dport)
}
return ds
}
func isGlobal(a netip.Addr) bool {
return a.IsValid() && !a.IsPrivate() && !a.IsLoopback() && !a.IsLinkLocalUnicast() && !a.IsMulticast() &&
!a.IsUnspecified() && !a.IsLinkLocalMulticast() && !isCGNAT(a)
}
var cgnat = netip.MustParsePrefix("100.64.0.0/10")
func isCGNAT(a netip.Addr) bool { return cgnat.Contains(a) }
func (e *Engine) isResolver(a netip.Addr) bool { return e.resolvers[a] }
func (e *Engine) checks(ws *wstate, ev Event, dport uint16, t int64, ds *dstStat, p *pairState, fan bool) {
dst := ev.Dst.String()
if e.cfg.BadDst != nil {
if bad, why := e.cfg.BadDst(ev.Dst); bad {
e.addFinding("bad_dst", "high", ws.name, dst, dport, ev.Proto, t, 0, 0, why, 1)
}
}
if ev.Proto == "tcp" {
if sev, why := suspiciousPort(dport, ws.role); why != "" {
e.addFinding("port", sev, ws.name, dst, dport, ev.Proto, t, 0, 0, why, 1)
}
}
dns := dport == 53 && (ev.Proto == "udp" || ev.Proto == "tcp") || dport == 853 && ev.Proto == "tcp"
if dns && ws.role != RoleResolver && isGlobal(ev.Dst) && !e.isResolver(ev.Dst) {
e.addFinding("dns_bypass", "medium", ws.name, dst, dport, ev.Proto, t, 0, 0, "DNS to a resolver that is not allowed", 1)
}
if p != nil {
e.beacon(ws, ev, dport, dns, p, ds)
}
if ws.role != RoleScanner && !fan && ds.cc != "" && isGlobal(ev.Dst) {
if _, seen := ws.geo[ds.cc]; !seen {
ws.geo[ds.cc] = struct{}{}
if t-ws.first >= int64(e.cfg.Learn/time.Second) {
e.addFinding("new_geo", "low", ws.name, dst, dport, ev.Proto, t, 0, 0, "first contact with country "+ds.cc+" "+ds.asn, 1)
}
} else if len(ws.geo) > 300 {
ws.geo = map[string]struct{}{}
}
}
}
func suspiciousPort(port uint16, role string) (sev, why string) {
switch port {
case 25, 465, 587:
if role != RoleMail {
return "medium", "SMTP from a non-mail workload (spam)"
}
case 6667, 6697:
return "medium", "IRC (classic botnet C2)"
case 3333, 14444, 45700:
return "high", "mining pool (stratum)"
case 4444, 5555, 7777:
return "medium", "probable mining pool (stratum) or reverse shell"
case 9001, 9030:
return "medium", "Tor ORPort"
}
return "", ""
}
func (e *Engine) beacon(ws *wstate, ev Event, dport uint16, dns bool, p *pairState, ds *dstStat) {
if p.flagged {
e.addFinding("beacon", "", ws.name, ev.Dst.String(), dport, ev.Proto, p.last, p.interval, p.cv, "", 1)
return
}
ntp := ev.Proto == "udp" && dport == 123
switch {
case dns && e.isResolver(ev.Dst):
return
case ws.role == RoleResolver && dport == 53:
return
case p.n < beaconMinN || int64(p.ts[p.n-1])-int64(p.ts[0]) < beaconSpan:
return
case p.fan > p.nonFan:
return // mostly a fan-out target (a daily scan target is not a beacon)
case p.total%4 != 0:
return // evaluate every fourth flow: the statistics allocate
}
iv := make([]float64, p.n-1)
var sum float64
for i := range iv {
iv[i] = float64(p.ts[i+1] - p.ts[i])
sum += iv[i]
}
med := median(iv)
if med < beaconMinIv || med > beaconMaxIv {
return
}
if ntp { // NTP is exempt only at a normal poll rate and never towards a bad destination
bad := false
if e.cfg.BadDst != nil {
bad, _ = e.cfg.BadDst(ev.Dst)
}
if !bad && med >= ntpMinIv {
return
}
}
mean := sum / float64(len(iv))
var ss float64
dev := make([]float64, len(iv))
for i, v := range iv {
ss += (v - mean) * (v - mean)
dev[i] = math.Abs(v - med)
}
cv := math.Sqrt(ss/float64(len(iv))) / mean
mad := median(dev) / med
if cv > beaconCV && mad > beaconMAD {
return
}
jit := cv
if mad < cv {
jit = mad
}
sev := "medium"
why := fmt.Sprintf("regular connections every %.0f s (jitter %.0f%%)", med, jit*100)
if e.cfg.BadDst != nil {
if bad, r := e.cfg.BadDst(ev.Dst); bad {
sev, why = "high", why+"; destination: "+r
}
}
p.flagged, p.interval, p.cv = true, med, jit
f := e.addFinding("beacon", sev, ws.name, ev.Dst.String(), dport, ev.Proto, p.last, med, jit, why, 0)
if f != nil {
f.Count, f.First = int(p.total), p.first
}
}
func median(v []float64) float64 {
s := append([]float64(nil), v...)
sort.Float64s(s)
n := len(s)
if n == 0 {
return 0
}
if n%2 == 1 {
return s[n/2]
}
return (s[n/2-1] + s[n/2]) / 2
}
var sevRank = map[string]int{"low": 1, "medium": 2, "high": 3}
func (e *Engine) addFinding(kind, sev, wl, dst string, dport uint16, proto string, t int64, iv, jit float64, detail string, inc int) *Finding {
key := fmt.Sprintf("%s|%s|%s|%d", kind, wl, dst, dport)
if f, ok := e.findings[key]; ok {
f.Count += inc
if t > f.Last {
f.Last = t
}
if sevRank[sev] > sevRank[f.Severity] {
f.Severity = sev
}
if detail != "" {
f.Detail = detail
}
if iv > 0 {
f.IntervalS, f.Jitter = iv, jit
}
return f
}
if sev == "" {
return nil // an update for a finding that was evicted
}
if len(e.findings) >= MaxFindings {
var worst string
var wf *Finding
for k, f := range e.findings {
if wf == nil || sevRank[f.Severity] < sevRank[wf.Severity] || sevRank[f.Severity] == sevRank[wf.Severity] && f.Last < wf.Last {
worst, wf = k, f
}
}
delete(e.findings, worst)
}
h := fnv.New64a()
h.Write([]byte(key))
f := &Finding{ID: fmt.Sprintf("e%016x", h.Sum64()), Kind: kind, Severity: sev, Workload: wl, Dst: dst, DPort: dport, Proto: proto,
Count: inc, IntervalS: iv, Jitter: jit, First: t, Last: t, Detail: detail}
e.findings[key] = f
return f
}
// Counters for the source status.
func (e *Engine) counters() (lines, malformed uint64, last int64) {
return e.lines.Load(), e.malformed.Load(), e.last.Load()
}
+105
View File
@@ -0,0 +1,105 @@
// Package egress analyses the outbound connections of the host and its
// containers (nftables "URUTAU-EGRESS: " log lines) to spot a compromised
// workload: beaconing, C2, mining, spam, unauthorised scanning.
//
// Central principle: traffic shaped like a scan (fan-out) is suppressed only
// for workloads with role=scanner. Traffic that is not scan shaped is judged
// the same for every workload, the scanner included.
package egress
import (
"errors"
"net/netip"
"strconv"
"strings"
"time"
)
const marker = "URUTAU-EGRESS:"
// Event is one new outbound connection.
type Event struct {
Time time.Time
Src, Dst netip.Addr
Proto string // tcp, udp, icmp, or the lowercased PROTO value
SPort, DPort uint16
In, Out string
Host bool // IN= empty: output of the host itself
}
// ErrNotEgress marks a line that is not an egress log line.
var ErrNotEgress = errors.New("not an egress line")
// ParseLine parses a kernel/rsyslog line. now is only used to infer the year
// of the "Nov 14 22:01:02" rsyslog format (and as the time of a line whose
// timestamp is unreadable).
func ParseLine(b []byte, now time.Time) (Event, error) {
line := string(b)
i := strings.Index(line, marker)
if i < 0 {
return Event{}, ErrNotEgress
}
ev := Event{Time: parseTS(line[:i], now)}
var haveSrc, haveDst bool
for _, f := range strings.Fields(line[i+len(marker):]) {
k, v, ok := strings.Cut(f, "=")
if !ok {
continue
}
switch k {
case "IN":
ev.In = v
case "OUT":
ev.Out = v
case "SRC":
a, err := netip.ParseAddr(v)
if err != nil {
return Event{}, errors.New("bad SRC")
}
ev.Src, haveSrc = a.Unmap(), true
case "DST":
a, err := netip.ParseAddr(v)
if err != nil {
return Event{}, errors.New("bad DST")
}
ev.Dst, haveDst = a.Unmap(), true
case "PROTO":
p := strings.ToLower(v)
if strings.HasPrefix(p, "icmp") {
p = "icmp"
}
ev.Proto = p
case "SPT":
n, _ := strconv.ParseUint(v, 10, 16)
ev.SPort = uint16(n)
case "DPT":
n, _ := strconv.ParseUint(v, 10, 16)
ev.DPort = uint16(n)
}
}
if !haveSrc || !haveDst || ev.Proto == "" {
return Event{}, errors.New("incomplete egress line")
}
ev.Host = ev.In == ""
return ev, nil
}
func parseTS(prefix string, now time.Time) time.Time {
f := strings.Fields(prefix)
if len(f) == 0 {
return now
}
if t, err := time.Parse(time.RFC3339Nano, f[0]); err == nil {
return t
}
if len(f) >= 3 {
if t, err := time.ParseInLocation("Jan 2 15:04:05", f[0]+" "+f[1]+" "+f[2], now.Location()); err == nil {
t = t.AddDate(now.Year(), 0, 0)
if t.After(now.Add(48 * time.Hour)) {
t = t.AddDate(-1, 0, 0)
}
return t
}
}
return now
}
+371
View File
@@ -0,0 +1,371 @@
package egress
import (
"net/netip"
"sort"
"strings"
)
// Finding is one alert; repeated observations update it.
type Finding struct {
ID string `json:"id"`
Kind string `json:"kind"`
Severity string `json:"severity"`
Workload string `json:"workload"`
Dst string `json:"dst"`
DPort uint16 `json:"dport"`
Proto string `json:"proto"`
Count int `json:"count"`
IntervalS float64 `json:"interval_s"`
Jitter float64 `json:"jitter"`
First int64 `json:"first"`
Last int64 `json:"last"`
Detail string `json:"detail"`
Host string `json:"host,omitempty"`
}
// WorkloadOut summarises a workload over the window.
type WorkloadOut struct {
Name string `json:"name"`
Role string `json:"role"`
Conns uint64 `json:"conns"`
Dsts int `json:"dsts"`
Ports int `json:"ports"`
Findings int `json:"findings"`
Suppressed uint64 `json:"suppressed_scan_conns"`
Host string `json:"host,omitempty"`
}
// Timeline holds hourly connection counts per workload.
type Timeline struct {
Start int64 `json:"start"`
Step int64 `json:"step"`
Series map[string][]uint32 `json:"series"`
}
// DstOut is a top destination.
type DstOut struct {
IP string `json:"ip"`
CC string `json:"cc"`
ASN string `json:"asn"`
Org string `json:"org"`
Conns uint64 `json:"conns"`
Workloads []string `json:"workloads"`
Ports []uint16 `json:"ports"`
}
// BurstOut summarises a scanner fan-out burst.
type BurstOut struct {
Workload string `json:"workload"`
Start int64 `json:"start"`
End int64 `json:"end"`
Targets int `json:"targets"`
Nets []string `json:"nets"`
Ports []uint16 `json:"ports"`
Conns uint32 `json:"conns"`
BadDstHit uint32 `json:"bad_dst_hits"`
Host string `json:"host,omitempty"`
}
// ScannerOut groups the scanner bursts.
type ScannerOut struct {
Bursts []BurstOut `json:"bursts"`
}
// Report is the egress analysis of a window.
type Report struct {
Workloads []WorkloadOut `json:"workloads"`
Timeline Timeline `json:"timeline"`
TopDst []DstOut `json:"top_dst"`
Findings []Finding `json:"findings"`
Scanner ScannerOut `json:"scanner"`
}
func (bs *burstState) out(wl string, end int64) BurstOut {
o := BurstOut{Workload: wl, Start: bs.start, End: end, Targets: len(bs.targets), Conns: bs.conns, BadDstHit: bs.badHits,
Nets: []string{}, Ports: []uint16{}}
type nc struct {
p netip.Prefix
n uint32
}
var ns []nc
for p, n := range bs.nets {
ns = append(ns, nc{p, n})
}
sort.Slice(ns, func(i, j int) bool {
if ns[i].n != ns[j].n {
return ns[i].n > ns[j].n
}
return ns[i].p.String() < ns[j].p.String()
})
for i := 0; i < len(ns) && i < 10; i++ {
o.Nets = append(o.Nets, ns[i].p.String())
}
type pc struct {
p uint16
n uint32
}
var ps []pc
for p, n := range bs.ports {
ps = append(ps, pc{p, n})
}
sort.Slice(ps, func(i, j int) bool {
if ps[i].n != ps[j].n {
return ps[i].n > ps[j].n
}
return ps[i].p < ps[j].p
})
for i := 0; i < len(ps) && i < 10; i++ {
o.Ports = append(o.Ports, ps[i].p)
}
return o
}
// Report builds the analysis of [from, to] (unix seconds).
func (e *Engine) Report(from, to int64) Report {
e.mu.Lock()
defer e.mu.Unlock()
if to <= from {
to = from + 1
}
startH, endH := from/3600, to/3600
if endH-startH > HourBuckets-1 {
startH = endH - (HourBuckets - 1)
}
nb := int(endH-startH) + 1
r := Report{Workloads: []WorkloadOut{}, TopDst: []DstOut{}, Findings: []Finding{},
Timeline: Timeline{Start: startH * 3600, Step: 3600, Series: map[string][]uint32{}},
Scanner: ScannerOut{Bursts: []BurstOut{}}}
fc := map[string]int{}
for _, f := range e.findings {
if f.Last >= from && f.First <= to {
r.Findings = append(r.Findings, *f)
fc[f.Workload]++
}
}
sort.Slice(r.Findings, func(i, j int) bool {
a, b := r.Findings[i], r.Findings[j]
if sevRank[a.Severity] != sevRank[b.Severity] {
return sevRank[a.Severity] > sevRank[b.Severity]
}
if a.Last != b.Last {
return a.Last > b.Last
}
return a.ID < b.ID
})
names := make([]string, 0, len(e.ws))
for n := range e.ws {
names = append(names, n)
}
sort.Strings(names)
for _, n := range names {
w := e.ws[n]
o := WorkloadOut{Name: n, Role: w.role, Findings: fc[n]}
series := make([]uint32, nb)
ds, ps := map[uint32]struct{}{}, map[uint32]struct{}{}
for h := startH; h <= endH; h++ {
b := &w.hours[h%HourBuckets]
if b.hour != h {
continue
}
series[h-startH] = b.conns
o.Conns += uint64(b.conns)
o.Suppressed += uint64(b.supp)
for _, x := range b.dsts {
ds[x] = struct{}{}
}
for _, x := range b.ports {
ps[x] = struct{}{}
}
}
o.Dsts, o.Ports = len(ds), len(ps)
if o.Conns == 0 && o.Suppressed == 0 && o.Findings == 0 {
continue
}
r.Workloads = append(r.Workloads, o)
r.Timeline.Series[n] = series
}
type scored struct {
ds *dstStat
n uint64
}
var all []scored
d0, d1 := int32(from/86400), int32(to/86400)
for el := e.dsts.l.Front(); el != nil; el = el.Next() {
ds := el.Value.(*lent[netip.Addr, *dstStat]).v
var n uint64
for _, d := range ds.days {
if d.day >= d0 && d.day <= d1 {
n += uint64(d.n)
}
}
if n > 0 {
all = append(all, scored{ds, n})
}
}
sort.Slice(all, func(i, j int) bool {
if all[i].n != all[j].n {
return all[i].n > all[j].n
}
return all[i].ds.ip.Compare(all[j].ds.ip) < 0
})
for i := 0; i < len(all) && i < 50; i++ {
ds := all[i].ds
ports := append([]uint16(nil), ds.ports...)
sort.Slice(ports, func(a, b int) bool { return ports[a] < ports[b] })
r.TopDst = append(r.TopDst, DstOut{IP: ds.ip.String(), CC: ds.cc, ASN: ds.asn, Org: ds.og, Conns: all[i].n,
Workloads: append([]string{}, ds.wls...), Ports: ports})
}
for _, b := range e.closed {
if b.End >= from && b.Start <= to {
r.Scanner.Bursts = append(r.Scanner.Bursts, b)
}
}
for _, n := range names {
if w := e.ws[n]; w.burst != nil && w.role == RoleScanner && w.burst.lastFan >= from && w.burst.start <= to {
r.Scanner.Bursts = append(r.Scanner.Bursts, w.burst.out(n, w.burst.lastFan))
}
}
return r
}
const (
maxPeerWorkloads = 256
maxPeerFindings = MaxFindings
maxStr = 200
)
func clip(s string) string {
if len(s) > maxStr {
return s[:maxStr]
}
return strings.ToValidUTF8(s, "")
}
// Sanitize bounds an untrusted peer report and stamps it with the peer name.
func (r *Report) Sanitize(host string) {
if len(r.Workloads) > maxPeerWorkloads {
r.Workloads = r.Workloads[:maxPeerWorkloads]
}
if len(r.Findings) > maxPeerFindings {
r.Findings = r.Findings[:maxPeerFindings]
}
if len(r.TopDst) > 50 {
r.TopDst = r.TopDst[:50]
}
if len(r.Scanner.Bursts) > maxClosedBurst+maxPeerWorkloads {
r.Scanner.Bursts = r.Scanner.Bursts[:maxClosedBurst+maxPeerWorkloads]
}
for i := range r.Workloads {
w := &r.Workloads[i]
w.Name, w.Role, w.Host = clip(w.Name), clip(w.Role), host
}
for i := range r.Findings {
f := &r.Findings[i]
f.ID, f.Kind, f.Severity = host+":"+clip(f.ID), clip(f.Kind), clip(f.Severity)
f.Workload, f.Dst, f.Proto, f.Detail, f.Host = clip(f.Workload), clip(f.Dst), clip(f.Proto), clip(f.Detail), host
}
for i := range r.TopDst {
d := &r.TopDst[i]
d.IP, d.CC, d.ASN, d.Org = clip(d.IP), clip(d.CC), clip(d.ASN), clip(d.Org)
if len(d.Workloads) > 8 {
d.Workloads = d.Workloads[:8]
}
for j := range d.Workloads {
d.Workloads[j] = clip(d.Workloads[j])
}
if len(d.Ports) > 8 {
d.Ports = d.Ports[:8]
}
}
for i := range r.Scanner.Bursts {
b := &r.Scanner.Bursts[i]
b.Workload, b.Host = clip(b.Workload), host
if len(b.Nets) > 10 {
b.Nets = b.Nets[:10]
}
for j := range b.Nets {
b.Nets[j] = clip(b.Nets[j])
}
if len(b.Ports) > 10 {
b.Ports = b.Ports[:10]
}
}
for k, v := range r.Timeline.Series {
if len(v) > HourBuckets {
r.Timeline.Series[k] = v[:HourBuckets]
}
}
if len(r.Timeline.Series) > maxPeerWorkloads {
r.Timeline.Series = map[string][]uint32{}
}
}
// Merge adds a sanitized peer report to r (the hub view). Series are keyed
// "host/workload" and placed on r's hourly grid.
func (r *Report) Merge(o Report, host string) {
r.Workloads = append(r.Workloads, o.Workloads...)
r.Findings = append(r.Findings, o.Findings...)
r.Scanner.Bursts = append(r.Scanner.Bursts, o.Scanner.Bursts...)
r.TopDst = append(r.TopDst, o.TopDst...)
sort.SliceStable(r.TopDst, func(i, j int) bool { return r.TopDst[i].Conns > r.TopDst[j].Conns })
if len(r.TopDst) > 50 {
r.TopDst = r.TopDst[:50]
}
sort.SliceStable(r.Findings, func(i, j int) bool {
a, b := r.Findings[i], r.Findings[j]
if sevRank[a.Severity] != sevRank[b.Severity] {
return sevRank[a.Severity] > sevRank[b.Severity]
}
return a.Last > b.Last
})
if len(r.Findings) > MaxFindings {
r.Findings = r.Findings[:MaxFindings]
}
if r.Timeline.Step == 0 {
r.Timeline.Step = 3600
}
for k, v := range o.Timeline.Series {
if r.Timeline.Start == 0 {
r.Timeline.Start = o.Timeline.Start
}
n := len(v)
off := int((o.Timeline.Start - r.Timeline.Start) / 3600)
for _, ex := range r.Timeline.Series {
n = len(ex)
break
}
dst := make([]uint32, n)
for i, x := range v {
if j := i + off; j >= 0 && j < n {
dst[j] = x
}
}
r.Timeline.Series[host+"/"+k] = dst
}
}
// Stamp marks the items of a trusted (local) report with its host name, as
// Sanitize does for a peer, so that a hub view can tell them apart.
func (r *Report) Stamp(host string) {
for i := range r.Workloads {
r.Workloads[i].Host = host
}
for i := range r.Findings {
r.Findings[i].Host = host
r.Findings[i].ID = host + ":" + r.Findings[i].ID
}
for i := range r.Scanner.Bursts {
r.Scanner.Bursts[i].Host = host
}
}
// EmptyReport is a well-formed report without data.
func EmptyReport() Report {
return Report{Workloads: []WorkloadOut{}, TopDst: []DstOut{}, Findings: []Finding{}, Scanner: ScannerOut{Bursts: []BurstOut{}},
Timeline: Timeline{Step: 3600, Series: map[string][]uint32{}}}
}
+110
View File
@@ -0,0 +1,110 @@
package egress
import (
"context"
"errors"
"log/slog"
"os"
"sync"
"sync/atomic"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/tail"
)
const maxLine = 16 * 1024
// Source follows the egress log file and feeds the engine. State is in memory
// only: on start the rotated backups and the live file are replayed from the
// beginning, which rebuilds the beacon history deterministically.
type Source struct {
Path string
E *Engine
Log *slog.Logger
backfilling atomic.Bool
fol atomic.Pointer[tail.Follower]
}
// NewSource creates the source of e reading path.
func NewSource(path string, e *Engine, log *slog.Logger) *Source {
if log == nil {
log = slog.Default()
}
s := &Source{Path: path, E: e, Log: log}
f := s.state
e.stateFn.Store(&f)
return s
}
func (s *Source) state() string {
switch f := s.fol.Load(); {
case s.backfilling.Load():
return "backfill"
case f == nil:
return "waiting"
default:
if err := f.Err(); err != nil {
if errors.Is(err, os.ErrNotExist) {
return "waiting"
}
return "error"
}
}
return "following"
}
// Status is the source line for the sources panel.
func (s *Source) Status() store.SourceStatus {
l, m, last := s.E.counters()
st := store.SourceStatus{Name: "egress", Path: s.Path, State: s.state(), Lines: l, Malformed: m, LastEvent: last}
if st.State == "error" {
st.Error = "read error"
}
return st
}
// Start launches the single goroutine of the source; it stops with ctx.
func (s *Source) Start(ctx context.Context, wg *sync.WaitGroup) {
wg.Add(1)
go func() {
defer wg.Done()
defer func() {
if p := recover(); p != nil {
s.Log.Error("egress source stopped by a panic", "panic", p)
}
}()
s.backfilling.Store(true)
for _, b := range tail.Backups(s.Path) {
if ctx.Err() != nil {
break
}
if err := tail.ReadAll(b, maxLine, s.E.Ingest, func() { s.E.malformed.Add(1) }); err != nil {
s.Log.Warn("egress backfill failed", "file", b, "err", err)
}
}
s.backfilling.Store(false)
f := tail.NewFollower(s.Path, tail.Pos{})
f.MaxLine, f.Handle = maxLine, s.E.Ingest
f.Oversize = func() { s.E.malformed.Add(1) }
s.fol.Store(f)
f.Run(ctx)
}()
}
// SourceInfo is the "source" object of the API.
type SourceInfo struct {
State string `json:"state"`
Lines uint64 `json:"lines"`
Malformed uint64 `json:"malformed"`
Last int64 `json:"last"`
}
// Info reports the source state (state "disabled" when no source is attached).
func (e *Engine) Info() SourceInfo {
l, m, last := e.counters()
st := "disabled"
if f := e.stateFn.Load(); f != nil {
st = (*f)()
}
return SourceInfo{State: st, Lines: l, Malformed: m, Last: last}
}
+169
View File
@@ -0,0 +1,169 @@
package egress
import (
"bufio"
"fmt"
"net/netip"
"os"
"regexp"
"strings"
)
// Roles of a workload.
const (
RoleDefault = "default"
RoleScanner = "scanner"
RoleMail = "mail"
RoleResolver = "resolver"
)
func validRole(r string) bool {
return r == RoleDefault || r == RoleScanner || r == RoleMail || r == RoleResolver
}
type matcher struct {
prefix netip.Prefix // valid when name == "" and !host
name string // container name: exact base name, or a prefix when pfx
pfx bool
host bool // the host's own output ("host")
}
type workloadDef struct {
name, role string
m []matcher
}
// ParseWorkloads parses "name=ITEM,ITEM:role;name2=...". An ITEM is a CIDR, an
// IP, "host" (the host's own output, so it can take a role such as mail),
// "name:<container name>" (exact base name, without the -<digits> suffix) or
// "name:<prefix>*" (explicit prefix); the role (scanner, mail, resolver,
// default) follows the last colon.
func ParseWorkloads(s string) ([]workloadDef, error) {
var out []workloadDef
for _, part := range strings.Split(s, ";") {
part = strings.TrimSpace(part)
if part == "" {
continue
}
name, rest, ok := strings.Cut(part, "=")
name, rest = strings.TrimSpace(name), strings.TrimSpace(rest)
if !ok || name == "" || rest == "" {
return nil, fmt.Errorf("workload %q: expected name=items[:role]", part)
}
role := RoleDefault
if i := strings.LastIndex(rest, ":"); i >= 0 && validRole(rest[i+1:]) {
role, rest = rest[i+1:], rest[:i]
}
w := workloadDef{name: name, role: role}
for _, it := range strings.Split(rest, ",") {
it = strings.TrimSpace(it)
switch {
case it == "":
case it == "host":
w.m = append(w.m, matcher{host: true})
case strings.HasPrefix(it, "name:"):
p := strings.TrimPrefix(it, "name:")
pfx := strings.HasSuffix(p, "*")
p = strings.TrimSuffix(p, "*")
if !nameRe.MatchString(p) {
return nil, fmt.Errorf("workload %q: bad container name %q", name, p)
}
w.m = append(w.m, matcher{name: p, pfx: pfx})
default:
pf, err := netip.ParsePrefix(it)
if err != nil {
a, err2 := netip.ParseAddr(it)
if err2 != nil {
return nil, fmt.Errorf("workload %q: bad address %q", name, it)
}
pf = netip.PrefixFrom(a.Unmap(), a.Unmap().BitLen())
}
w.m = append(w.m, matcher{prefix: pf.Masked()})
}
}
if len(w.m) == 0 {
return nil, fmt.Errorf("workload %q: no addresses", name)
}
out = append(out, w)
}
return out, nil
}
var nameRe = regexp.MustCompile(`^[A-Za-z0-9_.-]{1,128}$`)
var tsSuffix = regexp.MustCompile(`-\d{9,}$`)
var digitSuffix = regexp.MustCompile(`-\d+$`)
// ContainerBase strips the "-<timestamp>" suffix of a container name.
func ContainerBase(n string) string { return tsSuffix.ReplaceAllString(n, "") }
const maxMapLines = 10000
// LoadContainers reads a containers.map file ("<ip> <name>" per line; invalid
// lines are skipped, at most 10k lines).
func LoadContainers(path string) (map[netip.Addr]string, error) {
fh, err := os.Open(path)
if err != nil {
return nil, err
}
defer fh.Close()
m := map[netip.Addr]string{}
sc := bufio.NewScanner(fh)
sc.Buffer(make([]byte, 0, 4096), 4096)
for n := 0; sc.Scan() && n < maxMapLines; n++ {
f := strings.Fields(sc.Text())
if len(f) != 2 || !nameRe.MatchString(f[1]) {
continue
}
a, err := netip.ParseAddr(f[0])
if err != nil {
continue
}
m[a.Unmap()] = f[1]
}
return m, sc.Err()
}
// resolve names the workload of an event: host output is "host"; a container
// address matches the configured workloads (CIDR or container name from the
// current map); otherwise it is named after its mapped container (without the
// timestamp suffix) or "container <ip>".
func (e *Engine) resolve(ev Event) (name, role string) {
if ev.Host {
for _, w := range e.wls {
for _, m := range w.m {
if m.host {
return w.name, w.role
}
}
}
return "host", RoleDefault
}
cname := e.containers[ev.Src]
for _, w := range e.wls {
for _, m := range w.m {
if m.host {
continue
}
if m.name != "" {
if cname != "" && m.matchName(cname) {
return w.name, w.role
}
} else if m.prefix.Contains(ev.Src) {
return w.name, w.role
}
}
}
if cname != "" {
return ContainerBase(cname), RoleDefault
}
return "container " + ev.Src.String(), RoleDefault
}
// matchName compares a container name: the exact base name (the full name or
// without a -<digits> suffix), or a prefix when the item ended in "*".
func (m matcher) matchName(cname string) bool {
if m.pfx {
return strings.HasPrefix(cname, m.name)
}
return cname == m.name || digitSuffix.ReplaceAllString(cname, "") == m.name
}
+497
View File
@@ -0,0 +1,497 @@
package enforce
import (
"fmt"
"net/netip"
"os"
"path/filepath"
"strings"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
)
var t0 = time.Date(2026, 11, 14, 22, 0, 0, 0, time.UTC)
func TestDecide(t *testing.T) {
p := Params{Threshold: 5}
cases := []struct {
name string
in Input
act string
why string
}{
{"below", Input{Attacks: 4, Top: ReasonScannerFlood}, ActNone, ""},
{"threshold", Input{Attacks: 5, Top: ReasonWPBrute}, ActBan, ReasonWPBrute},
{"critical single hit", Input{Crit: ReasonEnvProbe, Crits: 1, Attacks: 1}, ActNone, ""},
{"critical two hits", Input{Crit: ReasonEnvProbe, Crits: 2, Attacks: 2}, ActBan, ReasonEnvProbe},
{"ssh", Input{SSHFails: 5}, ActBan, ReasonSSHBrute},
{"ssh below", Input{SSHFails: 4}, ActNone, ""},
{"trusted", Input{Attacks: 9, Exclude: SkipTrusted}, ActSkip, ""},
{"crawler", Input{Crit: ReasonRCE, Crits: 2, Exclude: SkipCrawler}, ActSkip, ""},
{"infra", Input{Crit: ReasonRCE, Crits: 2, Exclude: SkipInfra}, ActSkip, ""},
{"legit doubles", Input{Attacks: 9, Legit: true, Top: ReasonScannerFlood}, ActNone, ""},
{"legit doubles ok", Input{Attacks: 10, Legit: true, Top: ReasonScannerFlood}, ActBan, ReasonScannerFlood},
{"legit never stops crit", Input{Crit: ReasonRCE, Crits: 2, Attacks: 2, Legit: true}, ActBan, ReasonRCE},
{"legit one crit", Input{Crit: ReasonRCE, Crits: 1, Attacks: 1, Legit: true}, ActNone, ""},
{"legit ssh", Input{SSHFails: 9, Legit: true}, ActNone, ""},
{"already", Input{Attacks: 5, Top: ReasonScannerFlood, Banned: true}, ActAlready, ""},
{"active", Input{Attacks: 5, Top: ReasonScannerFlood, Active: true}, ActActive, ""},
}
for _, c := range cases {
d := Decide(c.in, p)
if d.Action != c.act || (c.why != "" && d.Reason != c.why) {
t.Errorf("%s: %+v", c.name, d)
}
}
}
func TestTTLEscalation(t *testing.T) {
want := []time.Duration{time.Hour, 6 * time.Hour, 24 * time.Hour, 7 * 24 * time.Hour, 7 * 24 * time.Hour}
for i, w := range want {
if TTLFor(i) != w {
t.Errorf("offence %d: %v", i, TTLFor(i))
}
}
}
func TestExclusions(t *testing.T) {
x := Exclusions{Trusted: []netip.Prefix{netip.MustParsePrefix("45.0.0.0/8")}, Peers: map[netip.Addr]bool{netip.MustParseAddr("46.1.1.1"): true},
Infra: map[netip.Addr]bool{netip.MustParseAddr("47.1.1.1"): true}}
for ip, want := range map[string]string{
"10.1.2.3": SkipPrivate, "127.0.0.1": SkipPrivate, "169.254.1.1": SkipPrivate, "100.64.1.1": SkipPrivate,
"::1": SkipPrivate, "fe80::1": SkipPrivate, "fc00::1": SkipPrivate, "ff02::1": SkipPrivate, "224.0.0.1": SkipPrivate,
"240.0.0.1": SkipPrivate, "0.0.0.0": SkipPrivate, "::ffff:10.0.0.1": SkipPrivate, "2001:db8::1": SkipPrivate,
"45.9.9.9": SkipTrusted, "47.1.1.1": SkipInfra, "46.1.1.1": SkipPeer, "::ffff:46.1.1.1": SkipPeer,
"8.8.8.8": SkipInfra, "2606:4700::1111": SkipInfra, "104.16.1.1": SkipInfra, "2a06:98c0::1": SkipInfra, "93.184.216.34": "",
} {
if got := x.Excluded(netip.MustParseAddr(ip)); got != want {
t.Errorf("%s: %q want %q", ip, got, want)
}
}
}
func atk(ip string, at time.Time, path string, st int) core.Event {
return core.Event{Time: at, IP: ip, Cat: core.Scanner, Source: "traefik", Method: "GET", Path: path, Status: st, UA: "x"}
}
type rig struct {
e *Engine
now time.Time
log string
}
func newRig(t *testing.T, mode string, mod func(*Config)) *rig {
r := &rig{now: t0, log: filepath.Join(t.TempDir(), "enf", "decisions.log")}
c := Config{Mode: mode, Path: r.log, StatePath: filepath.Join(t.TempDir(), "enforce.json"), Host: "oracle", Threshold: 5, MaxPerMin: 60,
Trusted: []netip.Prefix{netip.MustParsePrefix("45.0.0.0/8")}, Now: func() time.Time { return r.now }}
if mod != nil {
mod(&c)
}
r.e = New(c)
return r
}
func (r *rig) lines(t *testing.T) []string {
b, err := os.ReadFile(r.log)
if err != nil {
return nil
}
return strings.Split(strings.TrimSpace(string(b)), "\n")
}
func (r *rig) hits(ip string, n int, path string, st int) {
for i := 0; i < n; i++ {
r.e.process(atk(ip, r.now.Add(-time.Duration(i)*time.Second), path, st), "")
}
}
func TestEngineThresholdAndLine(t *testing.T) {
r := newRig(t, ModeOn, nil)
r.hits("203.0.114.7", 4, "/x", 404)
if len(r.lines(t)) != 0 {
t.Fatal("banned below threshold")
}
r.hits("203.0.114.7", 1, "/x", 404)
l := r.lines(t)
if len(l) != 1 || !strings.HasPrefix(l[0], "2026-11-14T22:00:00Z urutau decision=ban ip=203.0.114.7 reason=scanner-flood score=") ||
!strings.HasSuffix(l[0], " ttl=3600 host=oracle src=local") {
t.Fatalf("line %q", l)
}
// dedupe: more hits while the TTL holds write nothing
r.hits("203.0.114.7", 10, "/x", 404)
if len(r.lines(t)) != 1 {
t.Fatal("rewrote during TTL")
}
// escalation after the TTL: 6 h, persisted
r.now = r.now.Add(61 * time.Minute)
r.hits("203.0.114.7", 5, "/x", 404)
l = r.lines(t)
if len(l) != 2 || !strings.Contains(l[1], "ttl=21600") {
t.Fatalf("escalation %q", l)
}
r.e.saveState()
e2 := New(r.e.cfg)
if e2.bans[netip.MustParseAddr("203.0.114.7")].Offences != 2 {
t.Fatalf("state %+v", e2.bans)
}
if fi, err := os.Stat(r.log); err != nil || fi.Mode().Perm() != 0o640 {
t.Fatalf("mode %v %v", fi, err)
}
}
func TestEngineCriticalAndFamily(t *testing.T) {
r := newRig(t, ModeOn, nil)
ev := atk("203.0.114.8", r.now, "/.env", 404)
ev.Cat = core.Exploit
r.e.process(ev, intel.FamEnvCreds)
if len(r.lines(t)) != 0 {
t.Fatal("a single critical hit banned")
}
ev.Time = r.now.Add(time.Second)
r.e.process(ev, intel.FamEnvCreds)
ev2 := atk("203.0.114.9", r.now, "/wp-login.php", 404)
r.e.process(ev2, intel.FamWordPress)
l := r.lines(t)
if len(l) != 1 || !strings.Contains(l[0], "reason=env-probe") {
t.Fatalf("%q", l)
}
}
func TestEngineNeverCounts(t *testing.T) {
r := newRig(t, ModeOn, nil)
for _, st := range []int{404, 400, 405, 500, 502} {
ev := atk("203.0.114.10", r.now, "/x", st)
ev.Cat = core.NotFound // a plain 404 is not an attack category
for i := 0; i < 20; i++ {
r.e.process(ev, "")
}
}
// app and proxy errors on attack-category requests do not count either
for i := 0; i < 20; i++ {
ev := atk("203.0.114.11", r.now, "/x", 500)
ev.Proto, ev.Router, ev.OriginStatus = "HTTP/2", "r@docker", 500
r.e.process(ev, "")
ev = atk("203.0.114.11", r.now, "/x", 502)
ev.Proto, ev.Router, ev.Retries = "HTTP/2", "r@docker", 2
r.e.process(ev, "")
fr := atk("203.0.114.11", r.now, "/x", 404)
fr.Framed = true
r.e.process(fr, "")
}
if len(r.lines(t)) != 0 {
t.Fatalf("banned: %q", r.lines(t))
}
}
func TestEngineExclusionsAndCounts(t *testing.T) {
r := newRig(t, ModeOn, func(c *Config) {
c.Crawler = func(ip string, uas []string) bool { return ip == "66.249.66.1" }
c.PeerHosts = []string{"46.1.1.1"}
})
r.hits("45.1.1.1", 6, "/x", 404)
r.hits("10.0.0.5", 6, "/x", 404)
r.hits("46.1.1.1", 6, "/x", 404)
r.hits("66.249.66.1", 6, "/x", 404)
if len(r.lines(t)) != 0 {
t.Fatalf("banned excluded: %q", r.lines(t))
}
rep := r.e.Report(0)
for _, k := range []string{SkipTrusted, SkipPrivate, SkipPeer, SkipCrawler} {
if rep.Counts.Skipped[k] != 1 {
t.Errorf("skip %s: %v", k, rep.Counts.Skipped)
}
}
// the skip is reported once, not once per event
r.hits("45.1.1.1", 30, "/x", 404)
if r.e.Report(0).Counts.Skipped[SkipTrusted] != 1 {
t.Fatal("skip spam")
}
}
func TestEngineLegitVisitor(t *testing.T) {
r := newRig(t, ModeOn, nil)
vis := core.Event{Time: r.now.Add(-time.Hour), IP: "203.0.114.20", Cat: core.OK, Source: "traefik", Status: 200, FetchDest: "document"}
r.e.process(vis, "")
ev := atk("203.0.114.20", r.now, "/.env", 404)
ev.Cat = core.Exploit
r.e.process(ev, intel.FamEnvCreds)
r.hits("203.0.114.20", 7, "/x", 404)
if len(r.lines(t)) != 0 {
t.Fatalf("legit banned: %q", r.lines(t))
}
r.hits("203.0.114.20", 2, "/y", 404)
if len(r.lines(t)) != 1 {
t.Fatalf("legit double threshold: %q", r.lines(t))
}
}
func TestEngineAlreadyBlocked(t *testing.T) {
r := newRig(t, ModeOn, nil)
r.e.process(core.Event{Time: r.now, IP: "203.0.114.30", Cat: core.Ban, Source: "fail2ban", Jail: "sshd"}, "")
r.hits("203.0.114.30", 8, "/x", 404)
if len(r.lines(t)) != 0 || r.e.Report(0).Counts.AlreadyBlocked != 1 {
t.Fatalf("%q %+v", r.lines(t), r.e.Report(0).Counts)
}
rep := r.e.Report(0)
if rep.Coverage.AttackIPs != 1 || rep.Coverage.BlockedByFirewall != 1 {
t.Fatalf("coverage %+v", rep.Coverage)
}
}
func TestEngineSSH(t *testing.T) {
r := newRig(t, ModeOn, nil)
for i := 0; i < 5; i++ {
r.e.process(core.Event{Time: r.now.Add(-time.Duration(i) * time.Minute), IP: "203.0.114.40", Cat: core.SSHFail, Source: "ssh", User: "root"}, "")
}
if l := r.lines(t); len(l) != 1 || !strings.Contains(l[0], "reason=ssh-bruteforce") {
t.Fatalf("%q", l)
}
}
func TestEngineRateCapAndObserve(t *testing.T) {
r := newRig(t, ModeOn, func(c *Config) { c.MaxPerMin = 3 })
for i := 0; i < 6; i++ {
r.hits(fmt.Sprintf("203.0.114.%d", 50+i), 5, "/x", 404)
}
rep := r.e.Report(0)
if len(r.lines(t)) != 3 || rep.Counts.Written != 3 || rep.Counts.DroppedRate != 3 || rep.Counts.Decided != 6 {
t.Fatalf("%q %+v", r.lines(t), rep.Counts)
}
o := newRig(t, ModeObserve, nil)
o.hits("203.0.114.60", 5, "/x", 404)
rep = o.e.Report(0)
if _, err := os.Stat(o.log); err == nil {
t.Fatal("observe wrote the file")
}
if len(rep.Recent) != 1 || rep.Recent[0].Action != "would_ban" || rep.Coverage.WouldBlock != 1 || rep.Counts.Written != 0 {
t.Fatalf("%+v", rep)
}
}
func TestOldEventsDoNotBan(t *testing.T) {
r := newRig(t, ModeOn, nil)
for i := 0; i < 20; i++ {
r.e.process(atk("203.0.114.70", r.now.Add(-3*time.Hour), "/x", 404), "")
}
if len(r.lines(t)) != 0 {
t.Fatal("replayed events banned")
}
if r.e.Report(0).Coverage.AttackIPs != 1 {
t.Fatal("coverage lost old events")
}
}
func TestObserveNeverBlocks(t *testing.T) {
e := New(Config{Mode: ModeOn, Path: filepath.Join(t.TempDir(), "d.log")})
for i := 0; i < 10000; i++ {
e.Observe(atk("203.0.114.1", t0, "/x", 404), "")
}
if e.dropQ.Load() == 0 {
t.Fatal("full queue must drop and count")
}
}
func (r *rig) seen(ip string) { r.hits(ip, 2, "/x", 404) }
func TestAcceptPeer(t *testing.T) {
r := newRig(t, ModeOn, nil)
r.seen("203.0.114.80")
acc, bad := r.e.AcceptPeer("hostinger", []Wire{
{T: t0.Unix(), IP: "203.0.114.80", Reason: ReasonRCE, Score: 90, TTL: 3600},
{T: t0.Unix(), IP: "203.0.114.81", Reason: "evil\nreason", Score: 90, TTL: 3600},
{T: t0.Unix(), IP: "10.0.0.1", Reason: ReasonRCE, TTL: 3600},
{T: t0.Unix(), IP: "45.2.2.2", Reason: ReasonRCE, TTL: 3600},
{T: t0.Unix(), IP: "nope", Reason: ReasonRCE, TTL: 3600},
})
l := r.lines(t)
if acc != 1 || bad != 3 || len(l) != 1 || !strings.HasSuffix(l[0], "src=peer:hostinger") {
t.Fatalf("%d %d %q", acc, bad, l)
}
if len(r.e.LocalSince(0)) != 0 {
t.Fatal("peer decisions must not be re-shared")
}
if r.e.Report(0).Counts.Skipped[SkipTrusted] != 1 {
t.Fatalf("%+v", r.e.Report(0).Counts)
}
}
func TestAcceptPeerUnconfirmedTTLAndInfra(t *testing.T) {
r := newRig(t, ModeOn, nil)
r.seen("203.0.114.90")
r.seen("1.1.1.1")
r.seen("104.16.5.5")
acc, _ := r.e.AcceptPeer("h", []Wire{
{T: t0.Unix(), IP: "203.0.114.99", Reason: ReasonRCE, Score: 90, TTL: 3600}, // never seen here
{T: t0.Unix(), IP: "203.0.114.90", Reason: ReasonRCE, Score: 90, TTL: 7 * 24 * 3600},
{T: t0.Unix(), IP: "1.1.1.1", Reason: ReasonRCE, Score: 90, TTL: 3600},
{T: t0.Unix(), IP: "104.16.5.5", Reason: ReasonRCE, Score: 90, TTL: 3600},
})
l := r.lines(t)
if acc != 1 || len(l) != 1 || !strings.Contains(l[0], "ip=203.0.114.90") || !strings.Contains(l[0], "ttl=21600") {
t.Fatalf("%d %q", acc, l)
}
sk := r.e.Report(0).Counts.Skipped
if sk[SkipUnconfirmed] != 1 || sk[SkipInfra] < 2 {
t.Fatalf("%v", sk)
}
// an attack seen only long ago does not confirm
r2 := newRig(t, ModeOn, nil)
for i := 0; i < 3; i++ {
r2.e.process(atk("203.0.114.91", r2.now.Add(-8*24*time.Hour), "/x", 404), "")
}
if acc, _ := r2.e.AcceptPeer("h", []Wire{{T: t0.Unix(), IP: "203.0.114.91", Reason: ReasonRCE, TTL: 60}}); acc != 0 {
t.Fatal("stale confirmation accepted")
}
}
func TestInfraNeverBannedLocally(t *testing.T) {
r := newRig(t, ModeOn, func(c *Config) {
c.PeerHosts = []string{"hub.example"}
c.InfraHosts = []string{"hub.example"}
c.LocalAddrs = func() []netip.Addr { return []netip.Addr{netip.MustParseAddr("203.0.114.200")} }
c.Resolve = func(string) []netip.Addr { return []netip.Addr{netip.MustParseAddr("203.0.114.201")} }
})
for _, ip := range []string{"104.16.9.9", "8.8.4.4", "2606:4700:4700::1001", "203.0.114.200", "203.0.114.201"} {
r.hits(ip, 9, "/x", 404)
}
if len(r.lines(t)) != 0 {
t.Fatalf("infra banned: %q", r.lines(t))
}
}
func TestPeerResolutionKeepsLastGood(t *testing.T) {
fail := false
r := newRig(t, ModeOn, func(c *Config) {
c.PeerHosts = []string{"peer.example"}
c.Resolve = func(string) []netip.Addr {
if fail {
return nil
}
return []netip.Addr{netip.MustParseAddr("203.0.114.210")}
}
})
fail = true
r.e.refreshPeers()
r.hits("203.0.114.210", 9, "/x", 404)
if len(r.lines(t)) != 0 {
t.Fatal("peer banned after DNS failure")
}
}
func TestCriticalNeedsTwoHits(t *testing.T) {
r := newRig(t, ModeOn, nil)
mk := func(at time.Time) {
ev := atk("203.0.114.220", at, "/.env", 404)
ev.Cat = core.Exploit
r.e.process(ev, intel.FamEnvCreds)
}
mk(r.now)
if len(r.lines(t)) != 0 {
t.Fatal("one hit")
}
// a forged legitimate visit does not cancel a critical ban
r.e.process(core.Event{Time: r.now, IP: "203.0.114.220", Cat: core.OK, Source: "traefik", Status: 200, FetchDest: "document"}, "")
mk(r.now.Add(time.Second))
if len(r.lines(t)) != 1 {
t.Fatalf("legit visit blocked crit ban: %q", r.lines(t))
}
}
func TestWouldAndBansPruned(t *testing.T) {
r := newRig(t, ModeObserve, nil)
r.e.mu.Lock()
for i := 0; i < maxTracked+10; i++ {
a := netip.AddrFrom4([4]byte{50, byte(i >> 16), byte(i >> 8), byte(i)})
r.e.would[a] = r.now.Add(time.Hour).Unix()
r.e.bans[a] = banRec{Until: r.now.Unix(), Last: r.now.Unix(), Offences: 1}
}
r.e.would[netip.MustParseAddr("51.0.0.1")] = r.now.Add(-48 * time.Hour).Unix()
r.e.trimMaps(r.now)
nw, nb := len(r.e.would), len(r.e.bans)
_, old := r.e.would[netip.MustParseAddr("51.0.0.1")]
r.e.mu.Unlock()
if nw > maxTracked || nb > maxTracked || old {
t.Fatalf("not pruned: %d %d %v", nw, nb, old)
}
}
func TestSaveStateThrottled(t *testing.T) {
r := newRig(t, ModeOn, nil)
r.hits("203.0.114.230", 5, "/x", 404)
r.e.maybeSave()
st := r.e.cfg.StatePath
os.Remove(st)
r.hits("203.0.114.231", 5, "/x", 404)
r.e.maybeSave() // same instant: throttled
if _, err := os.Stat(st); err == nil {
t.Fatal("saved within 30s")
}
r.now = r.now.Add(31 * time.Second)
r.e.maybeSave()
if _, err := os.Stat(st); err != nil {
t.Fatal("not saved after 30s")
}
}
func TestRotation(t *testing.T) {
l := &logFile{path: filepath.Join(t.TempDir(), "d.log")}
line := strings.Repeat("x", 1<<20-1) + "\n"
for i := 0; i < 21; i++ {
if err := l.write(line); err != nil {
t.Fatal(err)
}
}
if _, err := os.Stat(l.path + ".1"); err != nil {
t.Fatal("no rotation")
}
if fi, _ := os.Stat(l.path); fi.Size() > MaxLogBytes {
t.Fatal("too big")
}
}
func TestFormatLineInjection(t *testing.T) {
ip := netip.MustParseAddr("8.8.8.8")
for _, evil := range []string{"x\ny", "a b\r\nurutau decision=ban ip=1.1.1.1", "peer:\x00\n", "\n\n", strings.Repeat("a", 500)} {
if _, err := FormatLine(t0, ip, evil, 90, time.Hour, "h", "local"); err == nil {
t.Errorf("reason %q accepted", evil)
}
l, err := FormatLine(t0, ip, ReasonRCE, 90, time.Hour, evil, "peer:"+evil)
if err != nil || strings.Count(l, "\n") != 1 || !strings.HasSuffix(l, "\n") || strings.ContainsAny(strings.TrimSuffix(l, "\n"), "\r\x00") ||
len(strings.Fields(l)) != 9 {
t.Errorf("host/src %q -> %q", evil, l)
}
}
if _, err := FormatLine(t0, netip.Addr{}, ReasonRCE, 1, time.Hour, "h", "local"); err == nil {
t.Error("invalid ip accepted")
}
}
func FuzzFormatLine(f *testing.F) {
f.Add("h", "peer:x", ReasonRCE)
f.Add("a\nb", "\r\n", "x\ny")
f.Fuzz(func(t *testing.T, host, src, reason string) {
l, err := FormatLine(t0, netip.MustParseAddr("2606:4700::1111"), reason, 5, time.Hour, host, src)
if err != nil {
return
}
if strings.Count(l, "\n") != 1 || len(strings.Fields(l)) != 9 {
t.Fatalf("%q", l)
}
})
}
func TestWritable(t *testing.T) {
d := t.TempDir()
if !Writable(filepath.Join(d, "sub", "x.log")) || !Writable(filepath.Join(d, "x.log")) {
t.Fatal("should be writable")
}
if _, err := os.Stat(filepath.Join(d, "x.log")); err == nil {
t.Fatal("Writable must not create the file")
}
if Writable("") {
t.Fatal("empty path")
}
}
+723
View File
@@ -0,0 +1,723 @@
package enforce
import (
"context"
"encoding/json"
"net/netip"
"os"
"path/filepath"
"sort"
"sync"
"sync/atomic"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
)
// Config configures the engine. Mode must be observe or on (off means no engine).
type Config struct {
Mode string
Path string // decision file
StatePath string // enforce.json, empty: no persistence
Host string // name of this instance, written in every line
Threshold int // attack events in Window
MaxPerMin int
Share bool
Trusted []netip.Prefix
PeerHosts []string // host names or addresses of the peers
InfraHosts []string // hub and other infrastructure hosts, never banned
LocalAddrs func() []netip.Addr // default: the addresses of the local interfaces
Resolve func(host string) []netip.Addr // default: literal parse only
Crawler func(ip string, uas []string) bool // FCrDNS verified crawler
Geo func(ip string) (string, uint32, string) // cc, asn, org
Now func() time.Time
}
// Wire is a decision as exchanged between peers.
type Wire struct {
T int64 `json:"t"`
IP string `json:"ip"`
Reason string `json:"reason"`
Score int `json:"score"`
TTL int `json:"ttl"`
}
// MaxWire is the most decisions accepted or returned in one exchange.
const MaxWire = 500
// Recent is one row of the report.
type Recent struct {
T int64 `json:"t"`
IP string `json:"ip"`
Reason string `json:"reason"`
Score int `json:"score"`
TTL int `json:"ttl"`
Action string `json:"action"` // ban, would_ban, skip
SkipReason string `json:"skip_reason"`
Src string `json:"src"`
CC string `json:"cc"`
ASN uint32 `json:"asn"`
Org string `json:"org"`
}
// Counts are the cumulative counters since start.
type Counts struct {
Decided int `json:"decided"`
Written int `json:"written"`
DroppedRate int `json:"dropped_rate"`
AlreadyBlocked int `json:"already_blocked"`
Skipped map[string]int `json:"skipped"`
DroppedQueue int64 `json:"dropped_queue"`
WriteErrors int `json:"write_errors"`
}
// Coverage tells how many attacking addresses were stopped, by whom.
type Coverage struct {
AttackIPs int `json:"attack_ips"`
BlockedByFirewall int `json:"blocked_by_firewall"`
BlockedByUrutau int `json:"blocked_by_urutau"`
WouldBlock int `json:"would_block"`
Unblocked int `json:"unblocked"`
}
// Report is what the API serves (mode and file status are added by the handler).
type Report struct {
Coverage Coverage `json:"coverage"`
Counts Counts `json:"counts"`
Recent []Recent `json:"recent"`
}
type aevt struct {
ts int64
slug string
}
type ipState struct {
ev []aevt
ssh []int64
legit int64
uas []string
lastAttack int64
f2bAt int64
urutauAt int64
wouldAt int64
banned int64 // fail2ban holds it until (unix), 0 none
}
type banRec struct {
Until int64 `json:"until"`
Offences int `json:"offences"`
Last int64 `json:"last"`
}
type item struct {
ev core.Event
fam string
}
const (
maxIPs = 50000
maxEvents = 128
maxRecent = 200
skipQuiet = 10 * time.Minute
banAssume = 24 * time.Hour
peerRefresh = 10 * time.Minute
maxPeerTTL = 6 * time.Hour
peerConfirmAge = 7 * 24 * time.Hour
maxTracked = 50000 // would and bans
saveEvery = 30 * time.Second
)
// Engine is the second firewall.
type Engine struct {
cfg Config
log *logFile
ch chan item
dropQ atomic.Int64
mu sync.Mutex
ips map[netip.Addr]*ipState
bans map[netip.Addr]banRec
would map[netip.Addr]int64
skipSeen map[netip.Addr]int64
excl Exclusions
counts Counts
recent []Recent
shared []Wire
minute int64
inMinute int
dirty bool
lastSave time.Time
hostIPs map[string][]netip.Addr // last good resolution per host
}
// New builds an engine and loads its state.
func New(c Config) *Engine {
if c.Now == nil {
c.Now = time.Now
}
if c.Threshold < 1 {
c.Threshold = 5
}
if c.MaxPerMin < 1 {
c.MaxPerMin = 60
}
if c.Resolve == nil {
c.Resolve = func(h string) []netip.Addr {
if a, err := netip.ParseAddr(h); err == nil {
return []netip.Addr{a.Unmap()}
}
return nil
}
}
e := &Engine{cfg: c, log: &logFile{path: c.Path}, ch: make(chan item, 4096), ips: map[netip.Addr]*ipState{},
bans: map[netip.Addr]banRec{}, would: map[netip.Addr]int64{}, skipSeen: map[netip.Addr]int64{},
counts: Counts{Skipped: map[string]int{}}}
e.hostIPs = map[string][]netip.Addr{}
e.excl = Exclusions{Trusted: c.Trusted, Peers: map[netip.Addr]bool{}, Infra: map[netip.Addr]bool{}}
e.refreshPeers()
e.loadState()
return e
}
// Mode returns the mode of the engine.
func (e *Engine) Mode() string { return e.cfg.Mode }
// Host is the name of this instance.
func (e *Engine) Host() string { return e.cfg.Host }
// Share reports whether decisions are exchanged with peers.
func (e *Engine) Share() bool { return e.cfg.Share }
// Threshold is the attack-event threshold in use.
func (e *Engine) Threshold() int { return e.cfg.Threshold }
// LogPath is the decision file.
func (e *Engine) LogPath() string { return e.cfg.Path }
// Observe is the ingestion hook: cheap, never blocks; a full queue drops the
// event and counts it.
func (e *Engine) Observe(ev core.Event, fam string) {
switch ev.Cat {
case core.Ban, core.SSHFail, core.Scanner, core.Exploit, core.BruteForce:
case core.OK:
if ev.FetchDest != "document" || ev.Status < 200 || ev.Status > 299 {
return
}
default:
return
}
select {
case e.ch <- item{ev, fam}:
default:
e.dropQ.Add(1)
}
}
// Run processes events until ctx is done.
func (e *Engine) Run(ctx context.Context) {
flush := time.NewTicker(5 * time.Second)
peers := time.NewTicker(peerRefresh)
defer flush.Stop()
defer peers.Stop()
defer e.log.close()
for {
select {
case <-ctx.Done():
e.saveState()
return
case it := <-e.ch:
e.process(it.ev, it.fam)
case <-flush.C:
e.maybeSave()
case <-peers.C:
e.refreshPeers()
}
}
}
// resolveKeep resolves h; an empty answer (DNS failure) keeps the last good one.
func (e *Engine) resolveKeep(h string, into map[netip.Addr]bool) {
as := e.cfg.Resolve(h)
e.mu.Lock()
if len(as) == 0 {
as = e.hostIPs[h]
} else {
e.hostIPs[h] = as
}
e.mu.Unlock()
for _, a := range as {
into[a.Unmap()] = true
}
}
func (e *Engine) refreshPeers() {
m := map[netip.Addr]bool{}
for _, h := range e.cfg.PeerHosts {
e.resolveKeep(h, m)
}
infra := map[netip.Addr]bool{}
for _, h := range e.cfg.InfraHosts {
e.resolveKeep(h, infra)
}
la := e.cfg.LocalAddrs
if la == nil {
la = interfaceAddrs
}
for _, a := range la() {
infra[a.Unmap()] = true
}
e.mu.Lock()
e.excl.Peers = m
e.excl.Infra = infra
e.mu.Unlock()
}
func (e *Engine) stateOf(a netip.Addr) *ipState {
st := e.ips[a]
if st == nil {
if len(e.ips) >= maxIPs {
e.evict()
}
st = &ipState{}
e.ips[a] = st
}
return st
}
func (e *Engine) evict() {
cut := e.cfg.Now().Add(-24 * time.Hour).Unix()
for a, st := range e.ips {
if max(st.lastAttack, st.f2bAt, st.legit) < cut {
delete(e.ips, a)
}
}
for a := range e.ips {
if len(e.ips) < maxIPs/2 {
break
}
delete(e.ips, a)
}
if len(e.skipSeen) > 10000 {
e.skipSeen = map[netip.Addr]int64{}
}
}
// trimMaps prunes would (expired or older than 24 h) and bans (older than 30 d)
// and caps both at maxTracked, dropping the least recent first; the lock is held.
func (e *Engine) trimMaps(now time.Time) {
cutW := now.Unix()
for a, u := range e.would {
if u < cutW || u < now.Add(-24*time.Hour).Unix() {
delete(e.would, a)
}
}
if len(e.would) > maxTracked {
type kv struct {
a netip.Addr
t int64
}
l := make([]kv, 0, len(e.would))
for a, u := range e.would {
l = append(l, kv{a, u})
}
sort.Slice(l, func(i, j int) bool { return l[i].t < l[j].t })
for _, x := range l[:len(l)-maxTracked/2] {
delete(e.would, x.a)
}
}
cutB := now.Add(-30 * 24 * time.Hour).Unix()
for a, b := range e.bans {
if b.Last < cutB {
delete(e.bans, a)
}
}
if len(e.bans) > maxTracked {
type kv struct {
a netip.Addr
t int64
}
l := make([]kv, 0, len(e.bans))
for a, b := range e.bans {
l = append(l, kv{a, b.Last})
}
sort.Slice(l, func(i, j int) bool { return l[i].t < l[j].t })
for _, x := range l[:len(l)-maxTracked/2] {
delete(e.bans, x.a)
}
}
}
// process handles one classified event (called by Run, or directly by tests).
func (e *Engine) process(ev core.Event, fam string) {
a, err := netip.ParseAddr(ev.IP)
if err != nil {
return
}
a = a.Unmap().WithZone("")
now := e.cfg.Now()
ts := ev.Time.Unix()
e.mu.Lock()
defer e.mu.Unlock()
switch {
case ev.Cat == core.Ban:
if ts < now.Add(-30*24*time.Hour).Unix() {
return
}
st := e.stateOf(a)
switch {
case ev.Unban:
st.banned = 0
default:
if ev.Jail == "urutau" { // our own decision, enforced by the host jail
st.urutauAt = max(st.urutauAt, ts)
} else {
st.banned = max(st.banned, ev.Time.Add(banAssume).Unix())
st.f2bAt = max(st.f2bAt, ts)
}
}
return
case LegitVisit(ev):
if ts >= now.Add(-LegitWindow).Unix() {
e.stateOf(a).legit = max(e.stateOf(a).legit, ts)
}
return
case ev.Cat == core.SSHFail:
case CountsAsAttack(ev):
default:
return
}
if ts < now.Add(-30*24*time.Hour).Unix() {
return
}
st := e.stateOf(a)
st.lastAttack = max(st.lastAttack, ts)
if ts < now.Add(-Window).Unix() { // a replayed old event: coverage only
return
}
cut := now.Add(-Window).Unix()
slug, crit := attackSlug(ev, fam)
if ev.Cat == core.SSHFail {
st.ssh = prune(append(st.ssh, ts), cut)
} else {
st.ev = append(st.ev, aevt{ts, slug})
k := 0
for _, x := range st.ev {
if x.ts >= cut {
st.ev[k] = x
k++
}
}
st.ev = st.ev[:k]
if len(st.ev) > maxEvents {
st.ev = st.ev[len(st.ev)-maxEvents:]
}
}
if ev.UA != "" && len(st.uas) < 3 {
ua := ev.UA
if len(ua) > 200 {
ua = ua[:200]
}
dup := false
for _, u := range st.uas {
dup = dup || u == ua
}
if !dup {
st.uas = append(st.uas, ua)
}
}
crits := 0
for _, x := range st.ev {
if criticalReasons[x.slug] {
crits++
}
}
in := Input{Now: now, Attacks: len(st.ev), Top: topSlug(st.ev), SSHFails: len(st.ssh), Crits: crits,
Legit: st.legit >= now.Add(-LegitWindow).Unix(), Exclude: e.excl.Excluded(a)}
if crit {
in.Crit = slug
}
e.fill(a, st, &in, now)
d := Decide(in, Params{Threshold: e.cfg.Threshold})
if d.Action == ActBan && e.cfg.Crawler != nil && len(st.uas) > 0 && e.cfg.Crawler(a.String(), st.uas) {
in.Exclude = SkipCrawler
d = Decide(in, Params{Threshold: e.cfg.Threshold})
}
e.apply(a, st, d, "local", now)
}
func (e *Engine) fill(a netip.Addr, st *ipState, in *Input, now time.Time) {
in.Banned = st.banned > now.Unix()
if b, ok := e.bans[a]; ok {
in.Offences = b.Offences
if b.Until > now.Unix() && e.cfg.Mode == ModeOn {
in.Active = true
}
if now.Unix() > b.Until+30*24*3600 {
in.Offences = 0
}
}
if u, ok := e.would[a]; ok && u > now.Unix() && e.cfg.Mode == ModeObserve {
in.Active = true
}
}
func prune(l []int64, cut int64) []int64 {
k := 0
for _, t := range l {
if t >= cut {
l[k] = t
k++
}
}
l = l[:k]
if len(l) > maxEvents {
l = l[len(l)-maxEvents:]
}
return l
}
func topSlug(evs []aevt) string {
cnt := map[string]int{}
best, bn := "", 0
for _, x := range evs {
cnt[x.slug]++
if cnt[x.slug] >= bn {
best, bn = x.slug, cnt[x.slug]
}
}
return best
}
// apply records the outcome of a decision; the lock is held.
func (e *Engine) apply(a netip.Addr, st *ipState, d Decision, src string, now time.Time) {
switch d.Action {
case ActSkip, ActAlready:
if until, ok := e.skipSeen[a]; ok && until > now.Unix() {
return
}
e.skipSeen[a] = now.Add(skipQuiet).Unix()
r := Recent{T: now.Unix(), IP: a.String(), Action: "skip", SkipReason: d.Skip, Src: src}
if d.Action == ActAlready {
e.counts.AlreadyBlocked++
r.SkipReason = "already_blocked"
} else {
e.counts.Skipped[d.Skip]++
}
e.addRecent(a, r)
case ActBan:
e.counts.Decided++
m := now.Unix() / 60
if m != e.minute {
e.minute, e.inMinute = m, 0
}
if e.inMinute >= e.cfg.MaxPerMin {
e.counts.DroppedRate++
return
}
e.inMinute++
r := Recent{T: now.Unix(), IP: a.String(), Reason: d.Reason, Score: d.Score, TTL: int(d.TTL / time.Second), Src: src}
if e.cfg.Mode != ModeOn {
r.Action = "would_ban"
if len(e.would) >= maxTracked {
e.trimMaps(now)
}
e.would[a] = now.Add(d.TTL).Unix()
st.wouldAt = now.Unix()
e.addRecent(a, r)
return
}
line, err := FormatLine(now, a, d.Reason, d.Score, d.TTL, e.cfg.Host, src)
if err == nil {
err = e.log.write(line)
}
if err != nil {
e.counts.WriteErrors++
return
}
r.Action = "ban"
e.counts.Written++
if len(e.bans) >= maxTracked {
e.trimMaps(now)
}
b := e.bans[a]
if now.Unix() > b.Until+30*24*3600 {
b.Offences = 0
}
if src == "local" {
b.Offences++
e.shared = append(e.shared, Wire{T: now.Unix(), IP: a.String(), Reason: d.Reason, Score: d.Score, TTL: r.TTL})
if len(e.shared) > MaxWire {
e.shared = e.shared[len(e.shared)-MaxWire:]
}
}
b.Until, b.Last = now.Add(d.TTL).Unix(), now.Unix()
e.bans[a] = b
st.urutauAt = now.Unix()
e.dirty = true
e.addRecent(a, r)
}
}
func (e *Engine) addRecent(a netip.Addr, r Recent) {
if e.cfg.Geo != nil {
r.CC, r.ASN, r.Org = e.cfg.Geo(a.String())
}
e.recent = append(e.recent, r)
if len(e.recent) > maxRecent*2 {
e.recent = append([]Recent(nil), e.recent[len(e.recent)-maxRecent:]...)
}
}
// LocalSince returns the decisions this instance wrote since the unix time.
func (e *Engine) LocalSince(since int64) []Wire {
e.mu.Lock()
defer e.mu.Unlock()
out := []Wire{}
for _, w := range e.shared {
if w.T >= since {
out = append(out, w)
}
}
return out
}
// AcceptPeer applies decisions received from a peer, after this instance's own
// exclusions. It returns how many were accepted for the policy (written or
// would-ban) and how many were refused as malformed.
func (e *Engine) AcceptPeer(name string, in []Wire) (accepted, invalid int) {
if len(in) > MaxWire {
in = in[:MaxWire]
}
src := "peer:" + token(name, "peer")
now := e.cfg.Now()
e.mu.Lock()
defer e.mu.Unlock()
for _, w := range in {
a, err := netip.ParseAddr(w.IP)
if err != nil || !ValidReason(w.Reason) || !Public(a) {
invalid++
continue
}
a = a.Unmap().WithZone("")
ttl := min(time.Duration(min(max(w.TTL, 60), 7*24*3600))*time.Second, maxPeerTTL)
if w.T > 0 && w.T+int64(ttl/time.Second) < now.Unix() {
continue // already expired
}
st := e.stateOf(a)
in := Input{Now: now, Crit: w.Reason, Crits: CritHits, Exclude: e.excl.Excluded(a)}
if in.Exclude == "" && st.lastAttack < now.Add(-peerConfirmAge).Unix() {
in.Exclude = SkipUnconfirmed // a peer's word alone never bans: this node must have seen the address attack
}
e.fill(a, st, &in, now)
d := Decide(in, Params{})
if d.Action == ActBan {
d.Reason, d.Score, d.TTL = w.Reason, max(0, min(100, w.Score)), ttl
accepted++
}
e.apply(a, st, d, src, now)
}
return accepted, invalid
}
// Report summarizes the activity since the unix time from.
func (e *Engine) Report(from int64) Report {
e.mu.Lock()
defer e.mu.Unlock()
var cv Coverage
for _, st := range e.ips {
if st.lastAttack < from {
continue
}
cv.AttackIPs++
switch {
case st.f2bAt > 0 && st.f2bAt >= from:
cv.BlockedByFirewall++
case st.urutauAt > 0 && st.urutauAt >= from:
cv.BlockedByUrutau++
case st.wouldAt > 0 && st.wouldAt >= from:
cv.WouldBlock++
default:
cv.Unblocked++
}
}
c := e.counts
c.Skipped = map[string]int{SkipTrusted: 0, SkipPrivate: 0, SkipCrawler: 0, SkipLegit: 0, SkipPeer: 0, SkipInfra: 0, SkipUnconfirmed: 0}
for k, v := range e.counts.Skipped {
c.Skipped[k] = v
}
c.DroppedQueue = e.dropQ.Load()
rec := []Recent{}
for i := len(e.recent) - 1; i >= 0 && len(rec) < maxRecent; i-- {
if e.recent[i].T >= from {
rec = append(rec, e.recent[i])
}
}
return Report{Coverage: cv, Counts: c, Recent: rec}
}
type stateFile struct {
V int `json:"v"`
Bans map[string]banRec `json:"bans"`
}
func (e *Engine) loadState() {
if e.cfg.StatePath == "" {
return
}
b, err := os.ReadFile(e.cfg.StatePath)
if err != nil {
return
}
var sf stateFile
if json.Unmarshal(b, &sf) != nil {
return
}
cut := e.cfg.Now().Add(-30 * 24 * time.Hour).Unix()
for k, v := range sf.Bans {
if a, err := netip.ParseAddr(k); err == nil && v.Last >= cut && v.Offences >= 0 && v.Offences < 1000 {
e.bans[a.Unmap()] = v
}
}
}
// maybeSave writes the state at most every saveEvery.
func (e *Engine) maybeSave() {
if e.cfg.Now().Sub(e.lastSave) < saveEvery {
return
}
e.saveState()
}
// saveState writes enforce.json atomically when something changed.
func (e *Engine) saveState() {
if e.cfg.StatePath == "" {
return
}
e.mu.Lock()
if !e.dirty {
e.mu.Unlock()
return
}
e.lastSave = e.cfg.Now()
e.trimMaps(e.lastSave)
sf := stateFile{V: 1, Bans: map[string]banRec{}}
for a, b := range e.bans {
sf.Bans[a.String()] = b
}
e.dirty = false
e.mu.Unlock()
b, _ := json.Marshal(sf)
tmp := e.cfg.StatePath + ".tmp"
if err := os.MkdirAll(filepath.Dir(tmp), 0o700); err == nil {
if err = os.WriteFile(tmp, b, 0o600); err == nil {
if err = os.Rename(tmp, e.cfg.StatePath); err == nil {
return
}
}
}
e.mu.Lock()
e.dirty = true
e.mu.Unlock()
}
+78
View File
@@ -0,0 +1,78 @@
package enforce
import (
"net"
"net/netip"
)
// SkipInfra is the skip reason of the fixed infrastructure allowlist.
const SkipInfra = "infrastructure"
func mustPrefixes(l ...string) []netip.Prefix {
out := make([]netip.Prefix, 0, len(l))
for _, s := range l {
out = append(out, netip.MustParsePrefix(s))
}
return out
}
// cloudflare are the published Cloudflare ranges (https://www.cloudflare.com/ips/).
// They are never banned: behind the CDN the "client" of a request is an edge
// address shared by thousands of innocent visitors.
var cloudflare = mustPrefixes(
"173.245.48.0/20", "103.21.244.0/22", "103.22.200.0/22", "103.31.4.0/22", "141.101.64.0/18",
"108.162.192.0/18", "190.93.240.0/20", "188.114.96.0/20", "197.234.240.0/22", "198.41.128.0/17",
"162.158.0.0/15", "104.16.0.0/13", "104.24.0.0/14", "172.64.0.0/13", "131.0.72.0/22",
"2400:cb00::/32", "2606:4700::/32", "2803:f800::/32", "2405:b500::/32", "2405:8100::/32",
"2a06:98c0::/29", "2c0f:f248::/32")
// publicResolvers are the well known public DNS resolvers.
var publicResolvers = func() map[netip.Addr]bool {
m := map[netip.Addr]bool{}
for _, s := range []string{"1.1.1.1", "1.0.0.1", "8.8.8.8", "8.8.4.4", "9.9.9.9", "149.112.112.112",
"208.67.222.222", "208.67.220.220", "2606:4700:4700::1111", "2606:4700:4700::1001",
"2001:4860:4860::8888", "2001:4860:4860::8844", "2620:fe::fe", "2620:fe::9",
"2620:119:35::35", "2620:119:53::53"} {
m[netip.MustParseAddr(s)] = true
}
return m
}()
// IsCloudflare reports whether a belongs to a Cloudflare range.
func IsCloudflare(a netip.Addr) bool {
a = a.Unmap()
for _, p := range cloudflare {
if p.Contains(a) {
return true
}
}
return false
}
// IsInfrastructure reports whether a is in the fixed allowlist (Cloudflare, public resolvers).
func IsInfrastructure(a netip.Addr) bool {
a = a.Unmap()
return publicResolvers[a] || IsCloudflare(a)
}
// interfaceAddrs lists the addresses of the local interfaces.
func interfaceAddrs() []netip.Addr {
var out []netip.Addr
addrs, err := net.InterfaceAddrs()
if err != nil {
return nil
}
for _, x := range addrs {
var ip net.IP
switch v := x.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
if a, ok := netip.AddrFromSlice(ip); ok {
out = append(out, a.Unmap())
}
}
return out
}
+145
View File
@@ -0,0 +1,145 @@
package enforce
import (
"errors"
"fmt"
"net/netip"
"os"
"path/filepath"
"strings"
"sync"
"time"
)
// MaxLogBytes is the size at which the decision file is rotated (one .1 kept).
const MaxLogBytes = 20 << 20
// token reduces s to [A-Za-z0-9._-] (at most 32 bytes); fallback if nothing is left.
func token(s, fallback string) string {
var b strings.Builder
for i := 0; i < len(s) && b.Len() < 32; i++ {
c := s[i]
if c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '.' || c == '_' || c == '-' {
b.WriteByte(c)
}
}
if b.Len() == 0 {
return fallback
}
return b.String()
}
// FormatLine renders one decision. Nothing the attacker controls enters it:
// the address is re-formatted by netip, the reason must be a fixed slug and the
// host and source names are reduced to a safe alphabet.
func FormatLine(t time.Time, ip netip.Addr, reason string, score int, ttl time.Duration, host, src string) (string, error) {
ip = ip.Unmap().WithZone("")
if !ip.IsValid() {
return "", errors.New("invalid ip")
}
if !ValidReason(reason) {
return "", errors.New("invalid reason")
}
score = max(0, min(100, score))
secs := max(1, int64(ttl/time.Second))
if src != "local" {
src = "peer:" + token(strings.TrimPrefix(src, "peer:"), "peer")
}
return fmt.Sprintf("%s urutau decision=ban ip=%s reason=%s score=%d ttl=%d host=%s src=%s\n",
t.UTC().Format("2006-01-02T15:04:05Z"), ip.String(), reason, score, secs, token(host, "urutau"), src), nil
}
// logFile appends to the decision file, rotating by size.
type logFile struct {
mu sync.Mutex
path string
f *os.File
size int64
}
func (l *logFile) open() error {
if err := os.MkdirAll(filepath.Dir(l.path), 0o750); err != nil {
return err
}
f, err := os.OpenFile(l.path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o640)
if err != nil {
return err
}
fi, err := f.Stat()
if err != nil {
f.Close()
return err
}
l.f, l.size = f, fi.Size()
return nil
}
func (l *logFile) write(line string) error {
l.mu.Lock()
defer l.mu.Unlock()
if l.f == nil {
if err := l.open(); err != nil {
return err
}
}
if l.size+int64(len(line)) > MaxLogBytes {
l.f.Close()
l.f = nil
if err := os.Rename(l.path, l.path+".1"); err != nil {
return err
}
if err := l.open(); err != nil {
return err
}
}
n, err := l.f.WriteString(line)
l.size += int64(n)
if err != nil {
l.f.Close()
l.f = nil
}
return err
}
func (l *logFile) close() {
l.mu.Lock()
defer l.mu.Unlock()
if l.f != nil {
l.f.Close()
l.f = nil
}
}
// Writable reports whether the decision file can be appended to, without
// creating anything: an existing file is opened for writing, otherwise a
// temporary file is created next to where it would live.
func Writable(path string) bool {
if path == "" {
return false
}
if _, err := os.Stat(path); err == nil {
f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND, 0)
if err != nil {
return false
}
f.Close()
return true
}
dir := filepath.Dir(path)
if _, err := os.Stat(dir); err != nil {
// the directory is created on first write: check the nearest parent
for dir != "/" && dir != "." {
dir = filepath.Dir(dir)
if _, err := os.Stat(dir); err == nil {
break
}
}
}
f, err := os.CreateTemp(dir, ".urutau-w-*")
if err != nil {
return false
}
f.Close()
os.Remove(f.Name())
return true
}
+280
View File
@@ -0,0 +1,280 @@
// Package enforce is the optional "second firewall": it decides which source
// addresses deserve a ban and appends one line per decision to a file. The
// process never gains privileges: a host side fail2ban jail reads the file.
package enforce
import (
"net/netip"
"os"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
)
// Modes.
const (
ModeOff = "off"
ModeObserve = "observe"
ModeOn = "on"
)
// Fixed reason slugs. Anything else is refused (also from peers).
const (
ReasonScannerFlood = "scanner-flood"
ReasonExploitFlood = "exploit-flood"
ReasonWebBrute = "web-bruteforce"
ReasonWPBrute = "wp-bruteforce"
ReasonSSHBrute = "ssh-bruteforce"
ReasonRCE = "rce"
ReasonTraversal = "path-traversal"
ReasonEnvProbe = "env-probe"
ReasonVCSProbe = "vcs-probe"
ReasonWebshell = "webshell"
ReasonSQLi = "sqli"
ReasonLog4Shell = "log4shell"
)
var reasons = map[string]bool{
ReasonScannerFlood: true, ReasonExploitFlood: true, ReasonWebBrute: true, ReasonWPBrute: true,
ReasonSSHBrute: true, ReasonRCE: true, ReasonTraversal: true, ReasonEnvProbe: true,
ReasonVCSProbe: true, ReasonWebshell: true, ReasonSQLi: true, ReasonLog4Shell: true,
}
// ValidReason reports whether s is one of the fixed slugs.
func ValidReason(s string) bool { return reasons[s] }
// criticalFam maps the attack families that justify a ban on one hit.
var criticalFam = map[string]string{
intel.FamRCE: ReasonRCE,
intel.FamTraversal: ReasonTraversal,
intel.FamEnvCreds: ReasonEnvProbe,
intel.FamVCS: ReasonVCSProbe,
intel.FamWebshell: ReasonWebshell,
intel.FamSQLi: ReasonSQLi,
intel.FamLog4Shell: ReasonLog4Shell,
}
// Policy constants.
const (
Window = 10 * time.Minute
LegitWindow = 24 * time.Hour
SSHThreshold = 5
// CritHits is how many critical events of one address (in Window) justify a ban.
CritHits = 2
)
// ttls is the advisory duration by number of previous bans.
var ttls = []time.Duration{time.Hour, 6 * time.Hour, 24 * time.Hour, 7 * 24 * time.Hour}
// TTLFor is the advisory TTL of a ban preceded by n earlier bans.
func TTLFor(offences int) time.Duration {
if offences < 0 {
offences = 0
}
if offences >= len(ttls) {
offences = len(ttls) - 1
}
return ttls[offences]
}
// Skip reasons, also the keys of Counts.Skipped.
const (
SkipTrusted = "trusted"
SkipPrivate = "private"
SkipCrawler = "crawler"
SkipLegit = "legit_visitor"
SkipPeer = "peer"
// SkipUnconfirmed: a peer's decision about an address this node never saw attacking.
SkipUnconfirmed = "peer_unconfirmed"
)
// Actions of a Decision.
const (
ActNone = "" // nothing to do
ActBan = "ban" // write (or would write)
ActSkip = "skip" // excluded
ActAlready = "already" // fail2ban already blocks it
ActActive = "active" // an advisory ban is still valid
)
// Input is everything Decide needs about one address.
type Input struct {
Now time.Time
Attacks int // counted attack events in the window
Top string // reason slug of the dominant attack in the window
SSHFails int // failed SSH logins in the window
Crit string // reason of a critical family hit just seen, "" if none
Crits int // critical events of the address in the window (a single hit is not enough)
Legit bool // a document 2xx from a browser within the last 24 h
Exclude string // Excluded() result or "crawler"
Banned bool // fail2ban already blocks it
Active bool // an advisory ban is still valid
Offences int
}
// Params are the thresholds.
type Params struct{ Threshold int }
// Decision is the verdict of Decide.
type Decision struct {
Action string
Reason string
Score int
TTL time.Duration
Skip string
}
// Decide is the pure policy. It returns ActNone while nothing justifies a ban.
func Decide(in Input, p Params) Decision {
th, sshTh := p.Threshold, SSHThreshold
if th < 1 {
th = 5
}
if in.Legit { // a (forgeable) legitimate visit only relaxes the volumetric thresholds
th, sshTh = th*2, sshTh*2
}
var reason string
score := 0
switch {
case in.Crit != "" && in.Crits >= CritHits:
reason, score = in.Crit, 90
case in.SSHFails >= sshTh:
reason, score = ReasonSSHBrute, min(100, 60+(in.SSHFails-sshTh)*5)
case in.Attacks >= th:
reason, score = in.Top, min(100, 55+(in.Attacks-th)*5)
if !ValidReason(reason) {
reason = ReasonScannerFlood
}
default:
return Decision{}
}
switch {
case in.Exclude != "":
return Decision{Action: ActSkip, Skip: in.Exclude}
case in.Banned:
return Decision{Action: ActAlready}
case in.Active:
return Decision{Action: ActActive}
}
return Decision{Action: ActBan, Reason: reason, Score: score, TTL: TTLFor(in.Offences)}
}
// reservedV4/V6 are special purpose ranges not covered by netip helpers.
var reserved = func() []netip.Prefix {
var out []netip.Prefix
for _, s := range []string{"0.0.0.0/8", "100.64.0.0/10", "192.0.0.0/24", "192.0.2.0/24", "198.18.0.0/15",
"198.51.100.0/24", "203.0.113.0/24", "240.0.0.0/4", "2001:db8::/32", "100::/64", "fc00::/7", "fe80::/10", "ff00::/8"} {
out = append(out, netip.MustParsePrefix(s))
}
return out
}()
// demoReservedPublic is a hidden switch ONLY for the documentation screenshots
// (scripts/screenshots.sh): the demo data uses reserved documentation ranges, which
// production policy rightly treats as private. Never set URUTAU_DEMO_RESERVED_PUBLIC
// outside the screenshot run.
var demoReservedPublic = os.Getenv("URUTAU_DEMO_RESERVED_PUBLIC") == "1"
func demoRanges(p netip.Prefix) bool {
switch p.String() {
case "198.18.0.0/15", "203.0.113.0/24", "198.51.100.0/24", "192.0.2.0/24", "2001:db8::/32":
return true
}
return false
}
// Public reports whether a is a routable unicast address worth blocking.
func Public(a netip.Addr) bool {
a = a.Unmap()
if !a.IsValid() || a.Zone() != "" || a.IsUnspecified() || a.IsLoopback() || a.IsPrivate() || a.IsMulticast() ||
a.IsLinkLocalUnicast() || a.IsLinkLocalMulticast() || a.IsInterfaceLocalMulticast() {
return false
}
for _, p := range reserved {
if demoReservedPublic && demoRanges(p) {
continue
}
if p.Contains(a) {
return false
}
}
return true
}
// Exclusions are the addresses that are never banned.
type Exclusions struct {
Trusted []netip.Prefix // --trusted and --ignore
Peers map[netip.Addr]bool // addresses of the peers
Infra map[netip.Addr]bool // hub, local interfaces (resolved at runtime)
}
var criticalReasons = func() map[string]bool {
m := map[string]bool{}
for _, r := range criticalFam {
m[r] = true
}
return m
}()
// Excluded returns the skip reason of a, or "".
func (x Exclusions) Excluded(a netip.Addr) string {
a = a.Unmap()
if !Public(a) {
return SkipPrivate
}
if x.Peers[a] {
return SkipPeer
}
for _, p := range x.Trusted {
if p.Contains(a) {
return SkipTrusted
}
}
if x.Infra[a] || IsInfrastructure(a) {
return SkipInfra
}
return ""
}
// attackSlug is the reason slug of one attack event, and whether it is critical.
func attackSlug(ev core.Event, fam string) (slug string, crit bool) {
if ev.Cat == core.SSHFail {
return ReasonSSHBrute, false
}
if r, ok := criticalFam[fam]; ok {
return r, true
}
switch {
case fam == intel.FamWordPress:
return ReasonWPBrute, false
case ev.Cat == core.BruteForce:
return ReasonWebBrute, false
case ev.Cat == core.Exploit:
return ReasonExploitFlood, false
}
return ReasonScannerFlood, false
}
// CountsAsAttack reports whether an HTTP event is an attack the policy counts:
// an attack category that was not merely framed, and whose answer is not a
// client, application or proxy error.
func CountsAsAttack(ev core.Event) bool {
if ev.Source != "traefik" || ev.Framed {
return false
}
if ev.Cat != core.Scanner && ev.Cat != core.Exploit && ev.Cat != core.BruteForce {
return false
}
if ev.Status >= 400 {
c := core.ErrorClass(ev, false)
return c == core.ClassAttack || c == core.ClassBlocked
}
return true
}
// LegitVisit reports whether ev is a browser loading a page successfully.
func LegitVisit(ev core.Event) bool {
return ev.Source == "traefik" && ev.Cat == core.OK && ev.Status >= 200 && ev.Status < 300 &&
ev.FetchDest == "document" && !ev.E.Tool && !ev.E.Bot && !ev.Prefetch
}
+46
View File
@@ -0,0 +1,46 @@
package fed
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
)
// Get fetches a peer path with the peer token and decodes the JSON answer.
func (h *Hub) Get(ctx context.Context, p Peer, path string, out any) error {
_, err := h.get(ctx, p, path, out)
return err
}
// PostJSON sends v as JSON to a peer path with the peer token.
func (h *Hub) PostJSON(ctx context.Context, p Peer, path string, v any) error {
b, err := json.Marshal(v)
if err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, p.URL+path, bytes.NewReader(b))
if err != nil {
return err
}
tok := h.Token
if p.Token != "" {
tok = p.Token
}
if tok != "" {
req.Header.Set("Authorization", "Bearer "+tok)
}
req.Header.Set("Content-Type", "application/json")
resp, err := h.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
if resp.StatusCode/100 != 2 {
return fmt.Errorf("HTTP %d", resp.StatusCode)
}
return nil
}
+42
View File
@@ -0,0 +1,42 @@
package fed
import (
"context"
"encoding/json"
"fmt"
"sync"
)
// EgressFor asks the online peers (or one) for their egress analysis of the
// window [from, to] (unix seconds). The raw answers are untrusted: the caller
// decodes and sanitizes them.
func (h *Hub) EgressFor(ctx context.Context, from, to int64, only string) map[string]json.RawMessage {
out := map[string]json.RawMessage{}
var mu sync.Mutex
var wg sync.WaitGroup
for _, p := range h.Peers {
if only != "" && only != p.Name {
continue
}
h.mu.RLock()
st := h.state[p.Name]
online := st != nil && st.online
h.mu.RUnlock()
if !online {
continue
}
wg.Add(1)
go func(p Peer) {
defer wg.Done()
var raw json.RawMessage
if _, err := h.get(ctx, p, fmt.Sprintf("/api/v1/peer/egress?from=%d&to=%d", from, to), &raw); err != nil {
return
}
mu.Lock()
out[p.Name] = raw
mu.Unlock()
}(p)
}
wg.Wait()
return out
}
+41 -2
View File
@@ -32,6 +32,34 @@ type liveState struct {
recent []store.LiveEvent // ring of the newest peer events
head int
subs map[chan store.LiveEvent]struct{}
vsubs map[chan store.VisitMsg]struct{} // legitimate visits: relayed, never kept
}
// SubscribeVisits returns the legitimate visits relayed from peers.
func (h *Hub) SubscribeVisits() (<-chan store.VisitMsg, func()) {
ch := make(chan store.VisitMsg, 64)
h.lmu.Lock()
if h.live.vsubs == nil {
h.live.vsubs = map[chan store.VisitMsg]struct{}{}
}
h.live.vsubs[ch] = struct{}{}
h.lmu.Unlock()
return ch, func() {
h.lmu.Lock()
delete(h.live.vsubs, ch)
h.lmu.Unlock()
}
}
func (h *Hub) publishVisit(m store.VisitMsg) {
h.lmu.Lock()
defer h.lmu.Unlock()
for ch := range h.live.vsubs {
select {
case ch <- m:
default:
}
}
}
// Subscribe returns the live events relayed from peers; call stop when done.
@@ -133,7 +161,7 @@ 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)
req, err := http.NewRequestWithContext(rctx, http.MethodGet, p.URL+"/api/v1/peer/stream?visits=1", nil)
if err != nil {
return err
}
@@ -181,7 +209,7 @@ func (h *Hub) consume(ctx context.Context, p Peer) error {
switch {
case bytes.HasPrefix(line, []byte("event:")):
evName = strings.TrimSpace(string(line[6:]))
case bytes.HasPrefix(line, []byte("data:")) && evName == "ev":
case bytes.HasPrefix(line, []byte("data:")) && (evName == "ev" || evName == "visit"):
now := time.Now()
tokens += now.Sub(last).Seconds() * maxLiveRate
if tokens > maxLiveRate {
@@ -192,6 +220,17 @@ func (h *Hub) consume(ctx context.Context, p Peer) error {
continue // over the budget: discard
}
tokens--
if evName == "visit" {
var v store.VisitMsg
if json.Unmarshal(bytes.TrimSpace(line[5:]), &v) == nil && v.Sanitize(now.Unix()) {
v.Host = p.Name
if v.Kind == "visit" && v.Dst == nil {
v.Dst = h.peerLocation(p.Name)
}
h.publishVisit(v)
}
continue
}
var e store.LiveEvent
if json.Unmarshal(bytes.TrimSpace(line[5:]), &e) != nil || !e.Sanitize(now.Unix()) {
continue
+36
View File
@@ -2,6 +2,7 @@ package fed_test
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
@@ -178,3 +179,38 @@ func TestLiveByteFloodDropsConnection(t *testing.T) {
time.Sleep(20 * time.Millisecond)
}
}
func TestVisitRelayHasNoAddressAndNoRecent(t *testing.T) {
var conns atomic.Int32
srv := fakeStream(t, &conns, func(w http.ResponseWriter) {
fmt.Fprint(w, "event: visit\ndata: "+`{"kind":"visit","t":`+fmt.Sprint(time.Now().Unix())+`,"host":"evil","ip":"9.9.9.9","ua":"Mozilla","domain":"a.example","path":"/x","status":200,"device":"mobile","src":{"lat":-8,"lon":-34.9,"cc":"BR","city":"Recife"}}`+"\n\n")
fmt.Fprint(w, "event: visit\ndata: "+`{"kind":"visit_batch","t":`+fmt.Sprint(time.Now().Unix())+`,"n":7}`+"\n\n")
fmt.Fprint(w, "event: visit\ndata: "+`{"kind":"nope"}`+"\n\n")
})
defer srv.Close()
p, _ := fed.ParsePeer("edge=" + srv.URL)
h := fed.NewHub([]fed.Peer{p}, "tok")
ch, stop := h.SubscribeVisits()
defer stop()
ctx, cancel := context.WithCancel(context.Background())
defer func() { cancel(); h.WaitStream() }()
h.Stream(ctx)
var got []store.VisitMsg
for len(got) < 2 {
select {
case m := <-ch:
got = append(got, m)
case <-time.After(5 * time.Second):
t.Fatalf("timeout, got %+v", got)
}
}
for _, m := range got {
b, _ := json.Marshal(m)
if strings.Contains(string(b), "9.9.9.9") || strings.Contains(string(b), `"ip"`) || strings.Contains(string(b), "Mozilla") || m.Host != "edge" {
t.Fatalf("relayed %s", b)
}
}
if got[0].Device != "mobile" || got[1].Kind != "visit_batch" || got[1].N != 7 || len(h.Recent(10)) != 0 {
t.Fatalf("%+v recent=%d", got, len(h.Recent(10)))
}
}
+71
View File
@@ -0,0 +1,71 @@
package server
import (
"net/http"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
// Temporal analytics: GET /api/v1/evolution, /concentration and /survival.
// They accept range|from&to and host, study the event registry within the
// study budget and deadline (cached 30 s) and share the user-side study slots.
func init() {
registerUserRoute("GET /api/v1/evolution", func(s *Server) http.HandlerFunc { return s.analytics("evolution") })
registerUserRoute("GET /api/v1/concentration", func(s *Server) http.HandlerFunc { return s.analytics("concentration") })
registerUserRoute("GET /api/v1/survival", func(s *Server) http.HandlerFunc { return s.analytics("survival") })
}
func (s *Server) analytics(kind string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
if q.Get("range") == "" && q.Get("from") == "" {
if kind == "evolution" {
q.Set("range", "30d")
} else {
q.Set("range", "7d")
}
r.URL.RawQuery = q.Encode()
}
rg, ok := s.rangeOf(w, r)
if !ok {
return
}
host := q.Get("host")
if len(host) > 64 {
badRequest(w, "invalid host")
return
}
if host == "all" {
host = ""
}
if host != "" && host != s.opt.Store.Name() && (s.opt.Hub == nil || !s.opt.Hub.Has(host)) {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "unknown host"})
return
}
dim := q.Get("dim")
if kind == "concentration" {
if dim == "" {
dim = "ip"
}
if !store.ConcentrationDims[dim] {
badRequest(w, "dim must be ip, asn, country, path or domain")
return
}
}
if !s.userSlot(w) {
return
}
defer func() { <-s.user }()
from, to := rg.Bounds(s.opt.Now().Unix())
st := s.opt.Store
switch kind {
case "evolution":
writeJSON(w, 200, st.Evolution(from, to, host))
case "concentration":
writeJSON(w, 200, st.Concentration(from, to, host, dim))
default:
writeJSON(w, 200, st.Survival(from, to, host))
}
}
}
+57
View File
@@ -0,0 +1,57 @@
package server
import (
"path/filepath"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
func TestAnalyticsAPI(t *testing.T) {
st := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour})
l, _ := evlog.Open(evlog.Options{Dir: filepath.Join(t.TempDir(), "events")})
st.SetEventLog(l)
now := time.Now()
for i := 0; i < 5; i++ {
st.Ingest(core.Event{Time: now.Add(-time.Hour - time.Duration(i)*time.Minute), IP: "20.0.0.1", Cat: core.Scanner, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/.env", Status: 404, UA: "zgrab/0.x"})
}
st.Ingest(core.Event{Time: now.Add(-time.Hour), IP: "20.0.0.2", Cat: core.Scanner, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/x", Status: 404})
st.Ingest(core.Event{Time: now.Add(-30 * time.Minute), IP: "20.0.0.1", Cat: core.Ban, Source: "fail2ban", Jail: "sshd"})
h := New(Options{Token: userTok, Version: "t", Store: st})
auth := map[string]string{"Authorization": "Bearer " + userTok}
e := getJSON(t, h, "/api/v1/evolution", auth)
if e["total"].(float64) != 6 || len(e["days"].([]any)) < 30 || len(e["hour_dow"].([]any)) != 7 {
t.Fatalf("evolution: %v", e)
}
for _, k := range []string{"new_families", "gone_families", "delta_pct"} {
if _, ok := e[k]; !ok {
t.Errorf("evolution misses %s", k)
}
}
c := getJSON(t, h, "/api/v1/concentration?dim=ip&range=24h", auth)
items := c["items"].([]any)
if c["total"].(float64) != 6 || len(items) != 2 || items[0].(map[string]any)["key"] != "20.0.0.1" {
t.Fatalf("concentration: %v", c)
}
v := getJSON(t, h, "/api/v1/survival?range=24h", auth)
if v["km"] == nil || v["by_family"] == nil || v["recidivists"] == nil || v["banned"].(float64) != 1 {
t.Fatalf("survival: %v", v)
}
for path, want := range map[string]int{
"/api/v1/concentration?dim=nope": 400,
"/api/v1/survival?range=bogus": 400,
"/api/v1/evolution?host=nowhere": 404,
"/api/v1/concentration?dim=path&host": 200,
} {
if w := do(h, "GET", path, cloneHdr(auth), nil); w.Code != want {
t.Errorf("%s: %d want %d", path, w.Code, want)
}
}
if w := do(h, "GET", "/api/v1/survival", nil, nil); w.Code != 401 && w.Code != 302 && w.Code != 403 {
t.Errorf("anonymous: %d", w.Code)
}
}
+93
View File
@@ -0,0 +1,93 @@
package server
import (
"net/http"
"regexp"
"strconv"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
var campaignIDRe = regexp.MustCompile(`^[A-Za-z0-9_-]{1,64}$`)
func init() {
registerUserRoute("GET /api/v1/campaigns", func(s *Server) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
p, ok := s.periodStudy(w, r)
if !ok {
return
}
writeJSON(w, 200, store.CampaignsOf(p))
}
})
registerUserRoute("GET /api/v1/campaigns/{id}", func(s *Server) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
if !campaignIDRe.MatchString(id) {
badRequest(w, "invalid campaign id")
return
}
p, ok := s.periodStudy(w, r)
if !ok {
return
}
d, found := store.CampaignOf(p, id)
if !found {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "unknown campaign"})
return
}
writeJSON(w, 200, d)
}
})
}
// periodStudy runs the same study as /api/v1/period (same filters, user
// semaphore, peers merged) and answers the errors itself.
func (s *Server) periodStudy(w http.ResponseWriter, r *http.Request) (store.PeriodOut, bool) {
eq, ok := s.eventFilter(w, r, 24*time.Hour)
if !ok {
return store.PeriodOut{}, false
}
if !s.userSlot(w) {
return store.PeriodOut{}, false
}
defer func() { <-s.user }()
pq := store.PeriodQuery{From: eq.From, To: eq.To, IP: eq.IP, Cat: eq.Cat, Fam: eq.Fam}
if v := r.URL.Query().Get("gap"); v != "" {
n, err := strconv.ParseInt(v, 10, 64)
if err != nil || n < 60 || n > 86400 {
badRequest(w, "gap must be 60..86400 seconds")
return store.PeriodOut{}, false
}
pq.Gap = n
}
local, peers, only, ok := s.studyHosts(w, eq.Host)
if !ok {
return store.PeriodOut{}, false
}
var parts []store.PeriodOut
var studies map[string]store.PeerStudy
if peers {
studies = s.opt.Hub.StudiesFor(r.Context(), pq, only)
}
if local || len(studies) == 0 {
lq := pq
switch {
case !local:
lq.Host = only
case s.opt.Hub != nil:
lq.Host = s.opt.Store.Name()
}
parts = append(parts, s.opt.Store.Period(lq))
}
for _, p := range s.opt.Hub.PeerNames() {
if st, ok := studies[p]; ok {
parts = append(parts, st.Period)
}
}
out := store.MergePeriods(parts)
rg, _ := s.opt.Store.ResolveRange(r.URL.Query().Get("range"), r.URL.Query().Get("from"), r.URL.Query().Get("to"))
out.Range = rg.Info(s.opt.Now().Unix())
return out, true
}
+81
View File
@@ -0,0 +1,81 @@
package server
import (
"net/http"
"path/filepath"
"strconv"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
func campaignServer(t *testing.T) http.Handler {
st := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour})
l, _ := evlog.Open(evlog.Options{Dir: filepath.Join(t.TempDir(), "events")})
st.SetEventLog(l)
now := time.Now()
for _, ip := range []string{"20.0.0.1", "20.0.0.2", "20.0.0.3"} {
for _, p := range []string{"/wp-login.php", "/xmlrpc.php"} {
st.Ingest(core.Event{Time: now.Add(-time.Hour), IP: ip, Cat: core.Scanner, Source: "traefik", Method: "GET", Path: p, Status: 404, UA: "zgrab/0.x"})
}
}
return New(Options{Token: userTok, Version: "t", Store: st})
}
func TestCampaignsAndSessionsAPI(t *testing.T) {
h := campaignServer(t)
auth := map[string]string{"Authorization": "Bearer " + userTok}
list := getJSON(t, h, "/api/v1/campaigns?range=24h", auth)
cs := list["campaigns"].([]any)
if len(cs) != 1 || list["ips_n"].(float64) != 3 {
t.Fatalf("campaigns: %v", list)
}
id := cs[0].(map[string]any)["id"].(string)
d := getJSON(t, h, "/api/v1/campaigns/"+id+"?range=24h", auth)
if len(d["members"].([]any)) != 3 {
t.Fatalf("members: %v", d)
}
f := getJSON(t, h, "/api/v1/sessions/funnel?range=24h", auth)
if f["sessions_n"].(float64) < 3 || f["stages"] == nil {
t.Fatalf("funnel: %v", f)
}
for path, want := range map[string]int{
"/api/v1/campaigns/c-zzzz?range=24h": 404,
"/api/v1/campaigns/bad%20id?range=24h": 400,
"/api/v1/campaigns?range=24h&gap=1": 400,
"/api/v1/campaigns?range=24h&host=nowhere": 404,
} {
if w := do(h, "GET", path, cloneHdr(auth), nil); w.Code != want {
t.Errorf("%s: %d want %d", path, w.Code, want)
}
}
if w := do(h, "GET", "/api/v1/campaigns", nil, nil); w.Code != 401 && w.Code != 302 && w.Code != 403 {
t.Errorf("anonymous: %d", w.Code)
}
}
func TestFunnelCountsEverySession(t *testing.T) {
st := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour})
l, _ := evlog.Open(evlog.Options{Dir: filepath.Join(t.TempDir(), "events")})
st.SetEventLog(l)
now := time.Now()
for i := 0; i < 260; i++ {
ip := "30.0." + strconv.Itoa(i/250) + "." + strconv.Itoa(i%250+1)
st.Ingest(core.Event{Time: now.Add(-time.Hour), IP: ip, Cat: core.Scanner, Source: "traefik", Method: "GET", Path: "/.env", Status: 404, UA: "curl/8"})
}
h := New(Options{Token: userTok, Version: "t", Store: st})
f := getJSON(t, h, "/api/v1/sessions/funnel?range=24h", map[string]string{"Authorization": "Bearer " + userTok})
if f["sessions_n"].(float64) != 260 || f["sampled"] != true || len(f["sessions"].([]any)) > 200 {
t.Fatalf("funnel: sessions_n=%v sampled=%v list=%d", f["sessions_n"], f["sampled"], len(f["sessions"].([]any)))
}
sum := 0.0
for _, v := range f["stages"].(map[string]any) {
sum += v.(float64)
}
if sum != 260 || f["reached"].(map[string]any)["recon"].(float64) != 260 {
t.Fatalf("stages %v reached %v", f["stages"], f["reached"])
}
}
+16
View File
@@ -0,0 +1,16 @@
package server
import "net/http"
func init() {
registerUserRoute("GET /api/v1/defense", func(s *Server) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
pq, ok := s.windowQuery(w, r)
if !ok {
return
}
defer func() { <-s.user }()
writeJSON(w, 200, s.opt.Store.Defense(pq))
}
})
}
+61
View File
@@ -0,0 +1,61 @@
package server
import (
"path/filepath"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
func TestDefenseAndTechniquesAPI(t *testing.T) {
st := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour, AdminUsers: []string{"lucas"}})
l, _ := evlog.Open(evlog.Options{Dir: filepath.Join(t.TempDir(), "events")})
st.SetEventLog(l)
now := time.Now()
for i := 0; i < 5; i++ {
st.Ingest(core.Event{Time: now.Add(-time.Duration(50-i) * time.Minute), IP: "8.8.4.4", Cat: core.Scanner, Source: "traefik", Method: "GET", Path: "/.env", Status: 404, UA: "nuclei"})
}
st.Ingest(core.Event{Time: now.Add(-30 * time.Minute), IP: "8.8.4.4", Cat: core.Ban, Source: "fail2ban", Jail: "sshd"})
st.Ingest(core.Event{Time: now.Add(-10 * time.Minute), IP: "8.8.4.4", Cat: core.Scanner, Source: "traefik", Method: "GET", Path: "/.env", Status: 404})
for _, u := range []string{"root", "lucas", "root"} {
st.Ingest(core.Event{Time: now.Add(-20 * time.Minute), IP: "9.9.9.9", Cat: core.SSHFail, Source: "ssh", User: u})
}
h := New(Options{Token: userTok, Version: "t", Store: st})
auth := map[string]string{"Authorization": "Bearer " + userTok}
d := getJSON(t, h, "/api/v1/defense?range=24h", auth)
if d["bans_total"].(float64) != 1 || d["bans_active"].(float64) != 1 {
t.Fatalf("bans %v", d)
}
ssh := d["ssh"].(map[string]any)
if ssh["fails"].(float64) != 3 || ssh["sources"].(float64) != 1 {
t.Fatalf("ssh %v", ssh)
}
us := ssh["users"].([]any)
if us[0].(map[string]any)["user"] != "root" || us[0].(map[string]any)["admin"] != false || us[1].(map[string]any)["admin"] != true {
t.Fatalf("users %v", us)
}
if d["leak"].(map[string]any)["ips"].(float64) != 1 {
t.Fatalf("leak %v", d["leak"])
}
if d["ttb"].(map[string]any)["median_s"].(float64) <= 0 {
t.Fatalf("ttb %v", d["ttb"])
}
if w := do(h, "GET", "/api/v1/defense?range=nope", cloneHdr(auth), nil); w.Code != 400 {
t.Fatalf("bad range: %d", w.Code)
}
if w := do(h, "GET", "/api/v1/defense?range=24h&host=zzz", cloneHdr(auth), nil); w.Code != 404 {
t.Fatalf("unknown host: %d", w.Code)
}
tq := getJSON(t, h, "/api/v1/techniques?range=24h", auth)
if tq["total"].(float64) < 1 || len(tq["tactics"].([]any)) == 0 {
t.Fatalf("techniques %v", tq)
}
if w := do(h, "GET", "/api/v1/techniques?range=24h", nil, nil); w.Code != 401 {
t.Fatalf("anonymous: %d", w.Code)
}
}
+101
View File
@@ -0,0 +1,101 @@
package server
import (
"encoding/json"
"net/http"
"sort"
"sync/atomic"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
)
func init() {
registerUserRoute("GET /api/v1/egress", func(s *Server) http.HandlerFunc { return s.egressAPI })
}
var egressEngine atomic.Pointer[egress.Engine]
// SetEgress attaches the egress engine (nil disables the endpoints). It is
// called by the daemon wiring, before or after the server starts.
func SetEgress(e *egress.Engine) { egressEngine.Store(e) }
type egressOut struct {
Enabled bool `json:"enabled"`
Source egress.SourceInfo `json:"source"`
egress.Report
}
// egressAPI: GET /api/v1/egress?range=24h&host=all|<name>. On a hub the
// local engine and the peers' reports are merged, items carrying "host".
func (s *Server) egressAPI(w http.ResponseWriter, r *http.Request) {
rg, ok := s.rangeOf(w, r)
if !ok {
return
}
host := r.URL.Query().Get("host")
if len(host) > 253 {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "bad host"})
return
}
local, peers, only, ok := s.studyHosts(w, host)
if !ok {
return
}
from, to := rg.Bounds(s.opt.Store.Now().Unix())
eng := egressEngine.Load()
out := egressOut{Source: egress.SourceInfo{State: "disabled"}}
if eng != nil {
out.Source = eng.Info()
out.Enabled = true
}
rep := egress.EmptyReport()
if local && eng != nil {
rep = eng.Report(from, to)
}
if peers && s.opt.Hub != nil {
merged := egress.EmptyReport()
merged.Timeline.Start = rep.Timeline.Start
if local && eng != nil {
rep.Stamp(s.opt.Store.Name())
merged.Merge(rep, s.opt.Store.Name())
}
raws := s.opt.Hub.EgressFor(r.Context(), from, to, only)
names := make([]string, 0, len(raws))
for n := range raws {
names = append(names, n)
}
sort.Strings(names)
for _, n := range names {
var pr egress.Report
if json.Unmarshal(raws[n], &pr) != nil {
continue
}
pr.Sanitize(n)
merged.Merge(pr, n)
out.Enabled = true
}
rep = merged
}
out.Report = rep
writeJSON(w, 200, out)
}
// peerEgress: GET /api/v1/peer/egress, the local report a hub merges; opened
// only by the peer token (and --peer-allow). It must be registered next to
// the other peer routes.
func (s *Server) peerEgress(w http.ResponseWriter, r *http.Request) {
if !s.peerGate(w, r) {
return
}
eng := egressEngine.Load()
if eng == nil {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "egress is not enabled"})
return
}
rg, ok := s.rangeOf(w, r)
if !ok {
return
}
from, to := rg.Bounds(s.opt.Store.Now().Unix())
writeJSON(w, 200, eng.Report(from, to))
}
+99
View File
@@ -0,0 +1,99 @@
package server
import (
"encoding/json"
"net/http"
"net/http/httptest"
"net/netip"
"strconv"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
func TestEgressAPI(t *testing.T) {
st := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour})
h := New(Options{Token: userTok, Version: "t", Store: st})
auth := map[string]string{"Authorization": "Bearer " + userTok}
SetEgress(nil)
d := getJSON(t, h, "/api/v1/egress?range=24h", auth)
if d["enabled"] != false || d["findings"] == nil || d["top_dst"] == nil {
t.Fatalf("disabled: %v", d)
}
e, err := egress.New(egress.Config{Workloads: "ciberlab=10.0.5.0/24:scanner"})
if err != nil {
t.Fatal(err)
}
SetEgress(e)
defer SetEgress(nil)
now := time.Now()
ev := func(at time.Time, src, dst string, port uint16) egress.Event {
return egress.Event{Time: at, Src: netip.MustParseAddr(src), Dst: netip.MustParseAddr(dst), Proto: "tcp", DPort: port, In: "br-1"}
}
e.IngestEvent(ev(now.Add(-time.Hour), "10.0.3.5", "203.0.113.3", 6667))
e.IngestEvent(ev(now.Add(-time.Hour), "10.0.3.5", "203.0.113.4", 443))
for i := 0; i < 80; i++ {
e.IngestEvent(ev(now.Add(-30*time.Minute+time.Duration(i)*time.Second), "10.0.5.2", "198.18.0."+strconv.Itoa(i+1), 80))
}
d = getJSON(t, h, "/api/v1/egress?range=24h", auth)
if d["enabled"] != true || d["source"].(map[string]any)["state"] == nil {
t.Fatalf("enabled: %v", d)
}
var port map[string]any
for _, f := range d["findings"].([]any) {
if m := f.(map[string]any); m["kind"] == "port" {
port = m
}
}
if port == nil || port["severity"] != "medium" || port["dport"].(float64) != 6667 || port["workload"] != "container 10.0.3.5" {
t.Fatalf("findings: %v", d["findings"])
}
if len(d["scanner"].(map[string]any)["bursts"].([]any)) != 1 || len(d["workloads"].([]any)) != 2 {
t.Fatalf("scanner/workloads: %v", d)
}
if tl := d["timeline"].(map[string]any); tl["step"].(float64) != 3600 || len(tl["series"].(map[string]any)) != 2 {
t.Fatalf("timeline: %v", tl)
}
if w := do(h, "GET", "/api/v1/egress?range=bogus", cloneHdr(auth), nil); w.Code != 400 {
t.Fatalf("range: %d", w.Code)
}
if w := do(h, "GET", "/api/v1/egress?host=nope", cloneHdr(auth), nil); w.Code != 404 {
t.Fatalf("host: %d", w.Code)
}
if w := do(h, "GET", "/api/v1/egress?range=24h", nil, nil); w.Code != 401 {
t.Fatalf("auth: %d", w.Code)
}
if w := do(h, "GET", "/api/v1/egress?range=24h", map[string]string{"Authorization": "Bearer peer-secret"}, nil); w.Code == 200 {
t.Fatalf("peer token must not open the user route")
}
// peer endpoint (registered by the daemon next to the other peer routes)
s := &Server{opt: Options{PeerTokens: []string{"peer-secret"}, Token: userTok, Store: st, Now: time.Now}, ses: newSessions(), lim: newLimiter()}
m := http.NewServeMux()
m.HandleFunc("GET /api/v1/peer/egress", s.peerEgress)
call := func(tok string) *httptest.ResponseRecorder {
r := httptest.NewRequest("GET", "/api/v1/peer/egress?range=24h", nil)
r.RemoteAddr = "198.51.100.1:1234"
if tok != "" {
r.Header.Set("Authorization", "Bearer "+tok)
}
w := httptest.NewRecorder()
m.ServeHTTP(w, r)
return w
}
if w := call(""); w.Code != 401 {
t.Fatalf("peer no token: %d", w.Code)
}
if w := call(userTok); w.Code != 401 {
t.Fatalf("user token on peer route: %d", w.Code)
}
w := call("peer-secret")
var rep egress.Report
if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &rep) != nil || len(rep.Findings) == 0 {
t.Fatalf("peer: %d %s", w.Code, w.Body)
}
}
+112
View File
@@ -0,0 +1,112 @@
package server
import (
"encoding/json"
"errors"
"io"
"net/http"
"strconv"
"sync/atomic"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
)
// enforceEngine is the optional second firewall (nil when --enforce is off).
var enforceEngine atomic.Pointer[enforce.Engine]
// SetEnforce installs the engine the enforce endpoints talk to.
func SetEnforce(e *enforce.Engine) { enforceEngine.Store(e) }
// peerRoute is a route opened by the federation token, contributed by its own file.
type peerRoute struct {
pattern string
handler func(*Server) http.HandlerFunc
}
var peerRoutes []peerRoute
const maxDecisionBody = 64 << 10
func init() {
registerUserRoute("GET /api/v1/enforce", func(s *Server) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
rg, ok := s.rangeOf(w, r)
if !ok {
return
}
now := s.opt.Now()
from := now.Add(-rg.Dur).Unix()
if rg.From > 0 {
from = rg.From
}
out := map[string]any{"mode": enforce.ModeOff, "share": "off", "threshold": 0, "log_writable": false,
"coverage": enforce.Coverage{}, "counts": enforce.Counts{Skipped: map[string]int{}}, "recent": []enforce.Recent{}}
if e := enforceEngine.Load(); e != nil {
rep := e.Report(from)
share := "off"
if e.Share() {
share = "on"
}
out["mode"], out["share"], out["threshold"] = e.Mode(), share, e.Threshold()
out["log_writable"] = enforce.Writable(e.LogPath())
out["coverage"], out["counts"], out["recent"] = rep.Coverage, rep.Counts, rep.Recent
}
writeJSON(w, http.StatusOK, out)
}
})
peerRoutes = append(peerRoutes,
peerRoute{"GET /api/v1/peer/decisions", func(s *Server) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
e := enforceEngine.Load()
if !s.peerGate(w, r) {
return
}
if e == nil || !e.Share() || e.Mode() != enforce.ModeOn {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "decision sharing is not enabled"})
return
}
since, _ := strconv.ParseInt(r.URL.Query().Get("since"), 10, 64)
if min := s.opt.Now().Add(-24 * time.Hour).Unix(); since < min {
since = min
}
writeJSON(w, http.StatusOK, map[string]any{"decisions": e.LocalSince(since)})
}
}},
peerRoute{"POST /api/v1/peer/decisions", func(s *Server) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
e := enforceEngine.Load()
if !s.peerGate(w, r) {
return
}
if e == nil || !e.Share() {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "decision sharing is not enabled"})
return
}
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxDecisionBody))
if err != nil {
var mb *http.MaxBytesError
if errors.As(err, &mb) {
writeJSON(w, http.StatusRequestEntityTooLarge, map[string]string{"error": "body too large"})
} else {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "unreadable body"})
}
return
}
var in struct {
Decisions []enforce.Wire `json:"decisions"`
}
if json.Unmarshal(body, &in) != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON"})
return
}
if len(in.Decisions) > enforce.MaxWire {
writeJSON(w, http.StatusRequestEntityTooLarge, map[string]string{"error": "too many decisions"})
return
}
acc, bad := e.AcceptPeer(r.URL.Query().Get("from"), in.Decisions)
writeJSON(w, http.StatusOK, map[string]int{"accepted": acc, "invalid": bad})
}
}},
)
}
+181
View File
@@ -0,0 +1,181 @@
package server
import (
"context"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
func enforceRig(t *testing.T, share bool) (http.Handler, *enforce.Engine, string) {
t.Helper()
log := filepath.Join(t.TempDir(), "decisions.log")
st := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour})
e := enforce.New(enforce.Config{Mode: enforce.ModeOn, Path: log, Host: "oracle", Threshold: 3, Share: share})
st.SetIngestHook(e.Observe)
SetEnforce(e)
t.Cleanup(func() { SetEnforce(nil) })
return New(Options{Token: userTok, PeerTokens: []string{peerTok}, Version: "t", Store: st}), e, log
}
func TestEnforceAPI(t *testing.T) {
h, e, log := enforceRig(t, true)
auth := map[string]string{"Authorization": "Bearer " + userTok}
d := getJSON(t, h, "/api/v1/enforce?range=24h", auth)
if d["mode"] != "on" || d["share"] != "on" || d["threshold"].(float64) != 3 || d["log_writable"] != true {
t.Fatalf("%v", d)
}
for _, k := range []string{"coverage", "counts", "recent"} {
if d[k] == nil {
t.Fatalf("missing %s: %v", k, d)
}
}
if sk := d["counts"].(map[string]any)["skipped"].(map[string]any); len(sk) != 7 {
t.Fatalf("skipped %v", sk)
}
// feed events through the store hook and the engine worker
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go e.Run(ctx)
e.Observe(core.Event{Time: time.Now(), IP: "203.0.114.5", Cat: core.Scanner, Source: "traefik", Method: "GET", Path: "/x", Status: 404, UA: "x"}, "")
for i := 0; i < 200 && e.Report(0).Coverage.AttackIPs == 0; i++ {
time.Sleep(10 * time.Millisecond)
}
e.AcceptPeer("hostinger", []enforce.Wire{{T: time.Now().Unix(), IP: "203.0.114.5", Reason: "rce", Score: 90, TTL: 3600}})
d = getJSON(t, h, "/api/v1/enforce?range=24h", auth)
rec := d["recent"].([]any)
if len(rec) != 1 {
t.Fatalf("recent %v", d)
}
r := rec[0].(map[string]any)
if r["action"] != "ban" || r["src"] != "peer:hostinger" || r["ip"] != "203.0.114.5" {
t.Fatalf("%v", r)
}
if b, _ := os.ReadFile(log); !strings.Contains(string(b), "src=peer:hostinger") {
t.Fatalf("log %q", b)
}
if w := do(h, "GET", "/api/v1/enforce?range=24h", nil, nil); w.Code != 401 {
t.Fatalf("anonymous %d", w.Code)
}
if w := do(h, "GET", "/api/v1/enforce?range=24h", map[string]string{"Authorization": "Bearer " + peerTok}, nil); w.Code != 403 {
t.Fatalf("peer token %d", w.Code)
}
if w := do(h, "GET", "/api/v1/enforce?range=bad", cloneHdr(auth), nil); w.Code != 400 {
t.Fatalf("bad range %d", w.Code)
}
}
func TestEnforceAPIOff(t *testing.T) {
st := store.New(store.Config{Name: "oracle", Version: "t"})
SetEnforce(nil)
h := New(Options{Token: userTok, Store: st})
d := getJSON(t, h, "/api/v1/enforce", map[string]string{"Authorization": "Bearer " + userTok})
if d["mode"] != "off" {
t.Fatalf("%v", d)
}
}
func post(h http.Handler, path, tok, body string) *httptest.ResponseRecorder {
r := httptest.NewRequest("POST", path, strings.NewReader(body))
r.RemoteAddr = "198.51.100.1:1234"
r.Header.Set("Content-Type", "application/json")
if tok != "" {
r.Header.Set("Authorization", "Bearer "+tok)
}
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w
}
func TestPeerDecisionsEndpoints(t *testing.T) {
h, e, log := enforceRig(t, true)
good := `{"decisions":[{"t":` + strconv.FormatInt(time.Now().Unix(), 10) + `,"ip":"203.0.114.9","reason":"sqli","score":80,"ttl":3600},` +
`{"t":1,"ip":"203.0.114.10","reason":"x\ny","score":80,"ttl":3600},{"ip":"10.0.0.1","reason":"rce","ttl":60}]}`
p := "/api/v1/peer/decisions?from=hostinger"
for _, tok := range []string{"", "wrong-token-0123456789-abcdefghijklmnopqrs", userTok} {
if w := post(h, p, tok, good); w.Code != 401 && w.Code != 403 {
t.Fatalf("token %q: %d", tok, w.Code)
}
if w := do(h, "GET", "/api/v1/peer/decisions", map[string]string{"Authorization": "Bearer " + tok}, nil); w.Code != 401 && w.Code != 403 {
t.Fatalf("GET token %q: %d", tok, w.Code)
}
}
if w := post(h, p, peerTok, strings.Repeat(" ", 70<<10)); w.Code != 413 {
t.Fatalf("big body: %d", w.Code)
}
if w := post(h, p, peerTok, "{nope"); w.Code != 400 {
t.Fatalf("bad json: %d", w.Code)
}
var many strings.Builder
many.WriteString(`{"decisions":[`)
for i := 0; i < 501; i++ {
if i > 0 {
many.WriteString(",")
}
many.WriteString(`{"ip":"1.1.1.1"}`)
}
many.WriteString(`]}`)
if w := post(h, p, peerTok, many.String()); w.Code != 413 {
t.Fatalf("501 items: %d", w.Code)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go e.Run(ctx)
e.Observe(core.Event{Time: time.Now(), IP: "203.0.114.9", Cat: core.Scanner, Source: "traefik", Method: "GET", Path: "/x", Status: 404, UA: "x"}, "")
for i := 0; i < 200 && e.Report(0).Coverage.AttackIPs == 0; i++ {
time.Sleep(10 * time.Millisecond)
}
w := post(h, p, peerTok, good)
if w.Code != 200 || !strings.Contains(w.Body.String(), `"accepted":1`) || !strings.Contains(w.Body.String(), `"invalid":2`) {
t.Fatalf("%d %s", w.Code, w.Body)
}
b, _ := os.ReadFile(log)
if strings.Count(string(b), "\n") != 1 || !strings.Contains(string(b), "ip=203.0.114.9 reason=sqli") || !strings.Contains(string(b), "src=peer:hostinger") {
t.Fatalf("log %q", b)
}
// GET returns local decisions only
if len(e.LocalSince(0)) != 0 {
t.Fatal("peer decision leaked into the local list")
}
rr := do(h, "GET", "/api/v1/peer/decisions?since=0", map[string]string{"Authorization": "Bearer " + peerTok}, nil)
if rr.Code != 200 || !strings.Contains(rr.Body.String(), `"decisions":[]`) {
t.Fatalf("%d %s", rr.Code, rr.Body)
}
}
func TestPeerDecisionsShareOff(t *testing.T) {
h, _, _ := enforceRig(t, false)
if w := post(h, "/api/v1/peer/decisions", peerTok, `{"decisions":[]}`); w.Code != 404 {
t.Fatalf("share off: %d", w.Code)
}
}
func TestEnforceFromStoreHook(t *testing.T) {
log := filepath.Join(t.TempDir(), "d.log")
st := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour})
e := enforce.New(enforce.Config{Mode: enforce.ModeOn, Path: log, Host: "oracle", Threshold: 3})
st.SetIngestHook(e.Observe)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go e.Run(ctx)
for i := 0; i < 3; i++ {
st.Ingest(core.Event{Time: time.Now(), IP: "203.0.114.9", Cat: core.Scanner, Source: "traefik", Method: "GET", Path: "/x" + strconv.Itoa(i), Status: 404, UA: "nuclei"})
}
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
if b, _ := os.ReadFile(log); strings.Contains(string(b), "ip=203.0.114.9 ") {
return
}
time.Sleep(10 * time.Millisecond)
}
t.Fatal("no decision written")
}
+211
View File
@@ -0,0 +1,211 @@
package server
import (
"net/http"
"sort"
"strings"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
func init() {
registerUserRoute("GET /api/v1/errors", func(s *Server) http.HandlerFunc { return s.errorsAPI })
}
// svcWindow resolves range, service and host filters shared by the health routes.
func (s *Server) svcWindow(w http.ResponseWriter, r *http.Request) (from, to int64, svc, host string, ok bool) {
rg, ok := s.rangeOf(w, r)
if !ok {
return
}
q := r.URL.Query()
now := s.opt.Store.Now().Unix()
from, to = rg.Bounds(now)
svc = q.Get("svc")
host = q.Get("host")
if host == "all" || host == s.opt.Store.Name() {
host = ""
}
if len(host) > 253 || len(svc) > 128 {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "bad host or svc"})
return 0, 0, "", "", false
}
return from, to, svc, host, true
}
type kv struct {
Key string
N uint32
}
func topKV(m map[string]uint32, n int) []kv {
out := make([]kv, 0, len(m))
for k, v := range m {
out = append(out, kv{k, v})
}
sort.Slice(out, func(a, b int) bool {
if out[a].N != out[b].N {
return out[a].N > out[b].N
}
return out[a].Key < out[b].Key
})
if len(out) > n {
out = out[:n]
}
return out
}
func errCount(c [store.NumCls]uint32) uint32 {
var n uint32
for _, v := range c {
n += v
}
return n
}
func (s *Server) errorsAPI(w http.ResponseWriter, r *http.Request) {
from, to, svc, host, ok := s.svcWindow(w, r)
if !ok {
return
}
views := s.opt.Store.Services(from, to, svc, host)
var tot [store.NumCls]uint32
var req, legit uint32
startH, endH := from/3600, to/3600
if endH-startH > 719 {
startH = endH - 719
}
nb := int(endH-startH) + 1
series := map[string][]uint32{}
for _, n := range store.ClsNames {
series[n] = make([]uint32, nb)
}
type routeOut struct {
Svc string `json:"svc"`
Route string `json:"route"`
Class string `json:"class"`
N uint32 `json:"n"`
}
var routes []routeOut
broken := map[string]*struct {
n uint32
last int64
ref string
path string
}{}
type heat struct {
alias string
total uint32
byH map[int64]uint32
}
var heats []heat
for _, v := range views {
req += v.Tot.Req
legit += v.Tot.Legit
h := heat{alias: v.Alias, byH: map[int64]uint32{}}
for i := range tot {
tot[i] += v.Tot.Cls[i]
}
for _, hr := range v.Hours {
if hr.Hour < startH || hr.Hour > endH {
continue
}
for i, n := range store.ClsNames {
series[n][hr.Hour-startH] += hr.Cls[i]
}
if c := hr.Cls[store.ClsApp]; c > 0 {
h.byH[hr.Hour] = c
h.total += c
}
}
heats = append(heats, h)
for _, e := range topKV(v.ErrRoutes, 50) {
cl, rt, _ := strings.Cut(e.Key, "|")
routes = append(routes, routeOut{v.Alias, rt, cl, e.N})
}
for k, n := range v.Broken {
p, ref, _ := strings.Cut(k, "\x00")
b := broken[k]
if b == nil {
b = &struct {
n uint32
last int64
ref string
path string
}{ref: ref, path: p}
broken[k] = b
}
b.n += n
if t := v.BrokenLast[k]; t > b.last {
b.last = t
}
}
}
sort.Slice(routes, func(a, b int) bool { return routes[a].N > routes[b].N })
if len(routes) > 50 {
routes = routes[:50]
}
type brokenOut struct {
Path string `json:"path"`
Ref string `json:"ref"`
N uint32 `json:"n"`
Last int64 `json:"last"`
}
bl := make([]brokenOut, 0, len(broken))
for _, b := range broken {
bl = append(bl, brokenOut{b.path, b.ref, b.n, b.last})
}
sort.Slice(bl, func(a, b int) bool {
if bl[a].N != bl[b].N {
return bl[a].N > bl[b].N
}
return bl[a].Path < bl[b].Path
})
if len(bl) > 50 {
bl = bl[:50]
}
// heatmap: services with most app errors, last 168 hours of the window
sort.Slice(heats, func(a, b int) bool { return heats[a].total > heats[b].total })
if len(heats) > 64 {
heats = heats[:64]
}
hStart := startH
if endH-hStart > 167 {
hStart = endH - 167
}
hours := make([]int64, 0, int(endH-hStart)+1)
for h := hStart; h <= endH; h++ {
hours = append(hours, h*3600)
}
svcs := make([]string, len(heats))
grid := make([][]uint32, len(heats))
for i, h := range heats {
svcs[i] = h.alias
grid[i] = make([]uint32, len(hours))
for j := range hours {
grid[i][j] = h.byH[hStart+int64(j)]
}
}
client := tot[store.ClsClientBroken] + tot[store.ClsClientAuth] + tot[store.ClsClientOther]
classes := map[string]uint32{
"app": tot[store.ClsApp], "proxy": tot[store.ClsProxy], "blocked": tot[store.ClsBlocked],
"attack": tot[store.ClsAttack], "bot": tot[store.ClsBot], "client": client,
}
for i, n := range store.ClsNames {
if strings.HasPrefix(n, "client_") {
classes[n] = tot[i]
}
}
errs := errCount(tot)
var rate float64
if legit > 0 {
rate = float64(tot[store.ClsApp]+tot[store.ClsProxy]) / float64(legit)
}
writeJSON(w, 200, map[string]any{
"instance": s.opt.Store.Name(), "range": map[string]int64{"from": from, "to": to}, "requests": req, "errors": errs, "legit": legit,
"app_error_rate": rate, "classes": classes,
"timeline": map[string]any{"start": startH * 3600, "step": 3600, "series": series},
"heatmap": map[string]any{"svcs": svcs, "hours": hours, "err": grid},
"broken": bl, "top_routes": routes,
})
}
+132
View File
@@ -0,0 +1,132 @@
package server
import (
"net/http"
"sort"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
type integritySource struct {
Name string `json:"name"`
State string `json:"state"`
Lines uint64 `json:"lines"`
Malformed uint64 `json:"malformed"`
Last int64 `json:"last"`
}
type integrityHost struct {
Name string `json:"name"`
Online bool `json:"online"`
LastEvent int64 `json:"last_event"`
LagS int64 `json:"lag_s"`
Hourly []uint32 `json:"hourly"`
Gaps []store.Gap `json:"gaps"`
Sources []integritySource `json:"sources"`
ParseErrorRate float64 `json:"parse_error_rate"`
}
type integrityPeer struct {
Name string `json:"name"`
Online bool `json:"online"`
Live bool `json:"live"`
LastSync int64 `json:"last_sync"`
}
type integrityGeo struct {
CityBuild int64 `json:"city_build"`
ASNBuild int64 `json:"asn_build"`
State string `json:"state"`
LastUpdate int64 `json:"last_update"`
Error string `json:"error,omitempty"`
}
type integrityOut struct {
Range store.RangeInfo `json:"range"`
FromHour int64 `json:"from_hour"`
Hosts []integrityHost `json:"hosts"`
Peers []integrityPeer `json:"peers"`
EventLog store.LogStats `json:"eventlog"`
Geo integrityGeo `json:"geo"`
}
func init() {
registerUserRoute("GET /api/v1/integrity", func(s *Server) http.HandlerFunc { return s.integrity })
}
// integrity answers "is the data complete?": events ingested per hour and
// host, silences, source and peer states, parse errors, event log and geo base.
func (s *Server) integrity(w http.ResponseWriter, r *http.Request) {
rg, ok := s.rangeOf(w, r)
if !ok {
return
}
host := r.URL.Query().Get("host")
if host == "" {
host = "all"
}
if !s.knownHost(w, host) {
return
}
now := s.opt.Now().Unix()
info := rg.Info(now)
parts, all := s.parts(r.Context(), rg, host)
fromH, toH := info.From/3600, info.To/3600
if toH-fromH > 24*31-1 {
fromH = toH - (24*31 - 1)
}
out := integrityOut{Range: info, FromHour: fromH, Hosts: []integrityHost{}, Peers: []integrityPeer{}}
seen := map[string]bool{}
for _, p := range parts {
name := p.Host
if name == "" && len(p.Hosts) > 0 {
name = p.Hosts[0].Name
}
seen[name] = true
hh := integrityHost{Name: name, Online: true, Sources: []integritySource{}}
hh.Hourly = store.HourlyFromTimeline(p.Timeline, fromH, toH)
hh.Gaps = store.FindGaps(hh.Hourly, fromH)
var lines, bad uint64
for _, src := range p.Sources {
if src.Name == "geo" {
if name == s.opt.Store.Name() {
out.Geo = integrityGeo{State: src.State, LastUpdate: src.LastEvent, Error: src.Error}
if store.GeoBuilds != nil {
out.Geo.CityBuild, out.Geo.ASNBuild = store.GeoBuilds()
}
}
continue
}
hh.Sources = append(hh.Sources, integritySource{Name: src.Name, State: src.State, Lines: src.Lines, Malformed: src.Malformed, Last: src.LastEvent})
lines += src.Lines
bad += src.Malformed
if src.LastEvent > hh.LastEvent {
hh.LastEvent = src.LastEvent
}
}
if lines+bad > 0 {
hh.ParseErrorRate = float64(bad) / float64(lines+bad)
}
if hh.LastEvent > 0 {
hh.LagS = now - hh.LastEvent
if hh.LagS < 0 {
hh.LagS = 0
}
}
out.Hosts = append(out.Hosts, hh)
}
for _, hi := range all {
if hi.Self {
continue
}
out.Peers = append(out.Peers, integrityPeer{Name: hi.Name, Online: hi.Online, Live: hi.Live, LastSync: hi.LastSeen})
if !seen[hi.Name] && (host == "all" || host == hi.Name) {
out.Hosts = append(out.Hosts, integrityHost{Name: hi.Name, Online: hi.Online, LastEvent: hi.LastSeen,
Hourly: make([]uint32, toH-fromH+1), Gaps: []store.Gap{}, Sources: []integritySource{}})
}
}
sort.SliceStable(out.Hosts, func(i, j int) bool { return out.Hosts[i].Name < out.Hosts[j].Name })
sort.SliceStable(out.Peers, func(i, j int) bool { return out.Peers[i].Name < out.Peers[j].Name })
out.EventLog = s.opt.Store.LogStats()
writeJSON(w, 200, out)
}
+330
View File
@@ -0,0 +1,330 @@
package server
import (
"net/http"
"sort"
"strconv"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
type reportFigures struct {
Requests uint64 `json:"requests"`
Attacks uint64 `json:"attacks"`
UniqueIPs int `json:"unique_ips"`
HostileIPs int `json:"hostile_ips"`
Bans int `json:"bans"`
Visitors uint64 `json:"visitors"`
NonHuman uint64 `json:"nonhuman"`
PageViews uint64 `json:"page_views"`
}
type reportTopIP struct {
IP string `json:"ip"`
Score float64 `json:"score"`
Level string `json:"level"`
CC string `json:"cc,omitempty"`
Country string `json:"country,omitempty"`
ASOrg string `json:"as_org,omitempty"`
Events uint32 `json:"events"`
Banned bool `json:"banned"`
}
type reportExposure struct {
T int64 `json:"t"`
IP string `json:"ip"`
Host string `json:"host"`
Domain string `json:"domain"`
Path string `json:"path"`
Status int `json:"status"`
Fam string `json:"fam"`
}
type reportOut struct {
Range store.RangeInfo `json:"range"`
Generated int64 `json:"generated"`
Hosts []string `json:"hosts"`
Summary struct {
reportFigures
Prev reportFigures `json:"prev"`
DeltaPct map[string]float64 `json:"delta_pct"`
HasPrev bool `json:"has_prev"`
} `json:"summary"`
Timeline struct {
Start int64 `json:"start"`
Step int64 `json:"step"`
Values []uint32 `json:"values"`
} `json:"timeline"`
Families []store.Count `json:"families"`
Techniques []store.Count `json:"techniques"`
Countries []store.Count `json:"countries"`
ASNs []store.Count `json:"asns"`
TopIPs []reportTopIP `json:"top_ips"`
Campaigns []intel.Campaign `json:"campaigns"`
Escalations []store.EscalationOut `json:"escalations"`
Exposures struct {
Total int `json:"total"`
ByFamily []store.Count `json:"by_family"`
Items []reportExposure `json:"items"`
} `json:"exposures"`
Defense struct {
MTTBMedianS float64 `json:"mttb_median_s"`
MTTBP90S float64 `json:"mttb_p90_s"`
MTTBPrevMedianS float64 `json:"mttb_prev_median_s"`
MTTBN int `json:"mttb_n"`
BanCoverage float64 `json:"ban_coverage"`
BanCoveragePrev float64 `json:"ban_coverage_prev"`
BlocklistCover float64 `json:"blocklist_coverage"`
ExposureRate float64 `json:"exposure_rate"`
ExploitsRefused float64 `json:"exploits_refused_pct"`
} `json:"defense"`
Truncated bool `json:"truncated,omitempty"`
}
func init() {
registerUserRoute("GET /api/v1/report", func(s *Server) http.HandlerFunc { return s.report })
}
// figuresOf builds the headline numbers; visitors, non-human clients and page
// views come from the traffic study (real browsers, deduplicated per IP and day).
func figuresOf(t store.Totals, tr store.TrafficData) reportFigures {
return reportFigures{Requests: t.Requests, Attacks: t.Malicious, UniqueIPs: t.UniqueIPs, HostileIPs: t.HostileIPs,
Bans: t.ActiveBans, Visitors: tr.Visitors, NonHuman: tr.NonHuman, PageViews: tr.Pages}
}
// trafficOf is what /api/v1/traffic answers for all domains, merged with the peers.
func (s *Server) trafficOf(r *http.Request, rg store.Range, host string) store.TrafficData {
var parts []store.TrafficData
self := s.opt.Store.Name()
if host == "all" || host == self {
parts = append(parts, s.opt.Store.TrafficFor(rg, "all"))
}
if s.opt.Hub != nil && host != self {
only := ""
if host != "all" {
only = host
}
parts = append(parts, s.opt.Hub.TrafficFor(r.Context(), rg, "all", only)...)
}
return store.MergeTraffic(host, parts)
}
func pctChange(v, prev float64) (float64, bool) {
if prev <= 0 {
return 0, false
}
return (v - prev) / prev * 100, true
}
var attackCats = []string{"scanner", "exploit", "bruteforce", "ssh-fail", "ssh-probe"}
// report: GET /api/v1/report, the aggregate behind the executive report.
func (s *Server) report(w http.ResponseWriter, r *http.Request) {
f := r.URL.Query().Get("format")
if f != "" && f != "json" && f != "html" {
badRequest(w, "format must be json or html")
return
}
rc, ok := s.buildReport(w, r)
if !ok {
return
}
if f == "html" {
s.writeReportHTML(w, r, rc)
return
}
writeJSON(w, 200, rc.out)
}
// reportCtx is the computed report plus the window it covers.
type reportCtx struct {
out reportOut
rg store.Range
host string
from, to int64
}
func (s *Server) buildReport(w http.ResponseWriter, r *http.Request) (*reportCtx, bool) {
if r.URL.Query().Get("range") == "" && r.URL.Query().Get("from") == "" {
q := r.URL.Query()
q.Set("range", "7d")
r.URL.RawQuery = q.Encode()
}
rg, ok := s.rangeOf(w, r)
if !ok {
return nil, false
}
host := r.URL.Query().Get("host")
if host == "" {
host = "all"
}
if !s.knownHost(w, host) {
return nil, false
}
now := s.opt.Now().Unix()
info := rg.Info(now)
var out reportOut
out.Range, out.Generated = info, now
// period study (families, techniques, ASNs, campaigns, escalations)
per, ok := s.periodStudy(w, r)
if !ok {
return nil, false
}
// summary of the period and of the previous one
parts, all := s.parts(r.Context(), rg, host)
var sum store.Summary
if len(parts) > 0 {
sum = store.Merge(host, parts)
}
out.Hosts = []string{}
for _, hi := range all {
if host == "all" || hi.Name == host {
out.Hosts = append(out.Hosts, hi.Name)
}
}
sort.Strings(out.Hosts)
out.Summary.reportFigures = figuresOf(sum.Totals, s.trafficOf(r, rg, host))
span := info.To - info.From
if span > 0 {
if prg, err := s.opt.Store.ResolveRange("", strconv.FormatInt(info.From-span, 10), strconv.FormatInt(info.From, 10)); err == nil {
pp, _ := s.parts(r.Context(), prg, host)
if len(pp) > 0 {
ps := store.Merge(host, pp)
out.Summary.Prev = figuresOf(ps.Totals, s.trafficOf(r, prg, host))
out.Summary.HasPrev = ps.Totals.Requests > 0 || ps.Totals.Malicious > 0
}
}
}
out.Summary.DeltaPct = map[string]float64{}
if out.Summary.HasPrev {
cur, prev := out.Summary.reportFigures, out.Summary.Prev
for k, p := range map[string][2]float64{
"requests": {float64(cur.Requests), float64(prev.Requests)}, "attacks": {float64(cur.Attacks), float64(prev.Attacks)},
"unique_ips": {float64(cur.UniqueIPs), float64(prev.UniqueIPs)}, "hostile_ips": {float64(cur.HostileIPs), float64(prev.HostileIPs)},
"bans": {float64(cur.Bans), float64(prev.Bans)}, "visitors": {float64(cur.Visitors), float64(prev.Visitors)},
"nonhuman": {float64(cur.NonHuman), float64(prev.NonHuman)}, "page_views": {float64(cur.PageViews), float64(prev.PageViews)},
} {
if d, ok := pctChange(p[0], p[1]); ok {
out.Summary.DeltaPct[k] = d
}
}
}
// attacks timeline
tl := sum.Timeline
out.Timeline.Start, out.Timeline.Step = tl.Start, tl.Step
out.Timeline.Values = []uint32{}
for _, c := range attackCats {
for i, v := range tl.Series[c] {
for len(out.Timeline.Values) <= i {
out.Timeline.Values = append(out.Timeline.Values, 0)
}
out.Timeline.Values[i] += v
}
}
// tops
out.Families, out.Techniques, out.ASNs = capCounts(per.TopFams, 10), capCounts(per.TopTechs, 10), capCounts(per.TopASNs, 10)
out.Countries = capCounts(sum.Countries, 10)
out.Campaigns = per.Campaigns
if len(out.Campaigns) > 8 {
out.Campaigns = out.Campaigns[:8]
}
if out.Campaigns == nil {
out.Campaigns = []intel.Campaign{}
}
out.Escalations = per.Escalations
if len(out.Escalations) > 8 {
out.Escalations = out.Escalations[:8]
}
if out.Escalations == nil {
out.Escalations = []store.EscalationOut{}
}
out.Truncated = per.Truncated
ips := append([]store.IPSummary(nil), sum.IPs...)
sort.SliceStable(ips, func(i, j int) bool { return ips[i].Score > ips[j].Score })
out.TopIPs = []reportTopIP{}
out.Exposures.ByFamily, out.Exposures.Items = []store.Count{}, []reportExposure{}
fam := map[string]uint32{}
for i, x := range ips {
var ev uint32
for _, n := range x.Counts {
ev += n
}
if i < 10 {
out.TopIPs = append(out.TopIPs, reportTopIP{IP: x.IP, Score: x.Score, Level: string(x.Level), CC: x.CC, Country: x.Country, ASOrg: x.ASOrg, Events: ev, Banned: x.Banned})
}
if i < 30 {
if inf, ok := s.opt.Store.IPInfoOf(x.IP); ok {
for _, e := range inf.Expo {
if e.T < info.From || e.T > info.To {
continue
}
out.Exposures.Total++
if e.Fam != "" {
fam[e.Fam]++
}
if len(out.Exposures.Items) < 10 {
out.Exposures.Items = append(out.Exposures.Items, reportExposure{T: e.T, IP: x.IP, Host: e.Host, Domain: e.Domain, Path: e.Path, Status: e.Status, Fam: e.Fam})
}
}
}
}
}
for k, n := range fam {
out.Exposures.ByFamily = append(out.Exposures.ByFamily, store.Count{Key: k, N: n})
}
sort.Slice(out.Exposures.ByFamily, func(i, j int) bool {
a, b := out.Exposures.ByFamily[i], out.Exposures.ByFamily[j]
return a.N > b.N || (a.N == b.N && a.Key < b.Key)
})
sort.Slice(out.Exposures.Items, func(i, j int) bool { return out.Exposures.Items[i].T > out.Exposures.Items[j].T })
// defence metrics (same study and slot as /metrics)
m, ok := s.reportMetrics(w, r, rg, host)
if !ok {
return nil, false
}
d := &out.Defense
d.MTTBMedianS, d.MTTBP90S, d.MTTBPrevMedianS, d.MTTBN = m.MTTB.MedianS, m.MTTB.P90S, m.MTTB.PrevMed, m.MTTB.N
d.BanCoverage, d.BanCoveragePrev = m.BanCoverage.Value, m.BanCoverage.Prev
d.BlocklistCover, d.ExposureRate, d.ExploitsRefused = m.BlocklistCoverage.Value, m.ExposureRate.Value, m.ExploitsRefused.Value
f, t := rg.Bounds(now)
return &reportCtx{out: out, rg: rg, host: host, from: f, to: t}, true
}
func capCounts(c []store.Count, n int) []store.Count {
if len(c) > n {
c = c[:n]
}
if c == nil {
return []store.Count{}
}
return c
}
func (s *Server) reportMetrics(w http.ResponseWriter, r *http.Request, rg store.Range, host string) (store.MetricsOut, bool) {
local, peers, only, ok := s.studyHosts(w, host)
if !ok {
return store.MetricsOut{}, false
}
if !s.userSlot(w) {
return store.MetricsOut{}, false
}
defer func() { <-s.user }()
var parts []store.MetricsOut
var studies map[string]store.PeerStudy
if peers {
from, to := rg.Bounds(s.opt.Now().Unix())
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)
}
}
return store.MergeMetrics(parts), true
}
+80
View File
@@ -0,0 +1,80 @@
package server
import (
"encoding/json"
"testing"
)
var opsAuth = map[string]string{"Authorization": "Bearer user-token-0123456789-abcdefghijklmnop"}
func TestIntegrityAPI(t *testing.T) {
h, _ := setup(t)
if w := do(h, "GET", "/api/v1/integrity?range=24h", nil, nil); w.Code != 401 && w.Code != 403 {
t.Fatalf("closed without token: %d", w.Code)
}
w := do(h, "GET", "/api/v1/integrity?range=24h", copyHdr(opsAuth), nil)
if w.Code != 200 {
t.Fatalf("%d %s", w.Code, w.Body)
}
var o struct {
Hosts []struct {
Name string `json:"name"`
Online bool `json:"online"`
Hourly []uint32 `json:"hourly"`
} `json:"hosts"`
Peers []any `json:"peers"`
}
if err := json.Unmarshal(w.Body.Bytes(), &o); err != nil {
t.Fatal(err)
}
if len(o.Hosts) != 1 || o.Hosts[0].Name != "oracle" || !o.Hosts[0].Online || len(o.Hosts[0].Hourly) < 24 {
t.Fatalf("%+v", o)
}
var sum uint32
for _, v := range o.Hosts[0].Hourly {
sum += v
}
if sum == 0 {
t.Fatal("the ingested event must show in the hourly series")
}
if w := do(h, "GET", "/api/v1/integrity?host=nope", copyHdr(opsAuth), nil); w.Code != 404 {
t.Fatalf("unknown host: %d", w.Code)
}
}
func TestReportAPI(t *testing.T) {
h, _ := setup(t)
w := do(h, "GET", "/api/v1/report?range=7d&format=json", copyHdr(opsAuth), nil)
if w.Code != 200 {
t.Fatalf("%d %s", w.Code, w.Body)
}
var o struct {
Hosts []string `json:"hosts"`
Summary struct {
Attacks uint64 `json:"attacks"`
} `json:"summary"`
TopIPs []struct {
IP string `json:"ip"`
} `json:"top_ips"`
}
if err := json.Unmarshal(w.Body.Bytes(), &o); err != nil {
t.Fatal(err)
}
if o.Summary.Attacks != 1 || len(o.TopIPs) != 1 || len(o.Hosts) != 1 {
t.Fatalf("%s", w.Body)
}
if w := do(h, "GET", "/api/v1/report?format=pdf", copyHdr(opsAuth), nil); w.Code != 400 {
t.Fatalf("format: %d", w.Code)
}
if w := do(h, "GET", "/api/v1/report?host=nope", copyHdr(opsAuth), nil); w.Code != 404 {
t.Fatalf("host: %d", w.Code)
}
}
func copyHdr(m map[string]string) map[string]string {
c := map[string]string{}
for k, v := range m {
c[k] = v
}
return c
}
+208
View File
@@ -0,0 +1,208 @@
package server
import (
"math"
"net/http"
"sort"
"strings"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
const sloTarget = 0.995
func init() {
registerUserRoute("GET /api/v1/services", func(s *Server) http.HandlerFunc { return s.servicesAPI })
registerUserRoute("GET /api/v1/services/{svc}", func(s *Server) http.HandlerFunc { return s.serviceAPI })
registerUserRoute("GET /api/v1/protocols", func(s *Server) http.HandlerFunc { return s.protocolsAPI })
}
type tri struct {
Total float64 `json:"total"`
Origin float64 `json:"origin"`
Overhead float64 `json:"overhead"`
}
func errRate(h store.SvcHourOut) float64 {
if h.Legit == 0 {
return 0
}
return float64(h.Cls[store.ClsApp]+h.Cls[store.ClsProxy]) / float64(h.Legit)
}
func round(f float64, d int) float64 {
p := math.Pow(10, float64(d))
return math.Round(f*p) / p
}
func serviceItem(v store.SvcView, to int64) map[string]any {
t := v.Tot
rate := errRate(t)
var peak uint32
for _, h := range v.Hours {
if h.Req > peak {
peak = h.Req
}
}
burn := func(hours int64) float64 {
var sum store.SvcHourOut
for _, h := range v.Hours {
if h.Hour > to/3600-hours {
sum.Legit += h.Legit
sum.Cls[store.ClsApp] += h.Cls[store.ClsApp]
sum.Cls[store.ClsProxy] += h.Cls[store.ClsProxy]
}
}
return round(errRate(sum)/(1-sloTarget), 2)
}
apdex := 1.0
if t.ApN > 0 {
apdex = (float64(t.ApSat) + float64(t.ApTol)/2) / float64(t.ApN)
}
var retries float64
if t.Req > 0 {
retries = float64(t.Retries) / float64(t.Req) * 100
}
spark := make([]uint32, 0, 48)
for _, h := range v.Hours {
spark = append(spark, h.Req)
}
if len(spark) > 48 {
spark = spark[len(spark)-48:]
}
mix := map[string]uint32{}
for i, n := range store.ClsNames {
mix[n] = t.Cls[i]
}
mix["ok"] = t.Req - errCount(t.Cls)
q := func(h [13]uint32, p float64) float64 { return round(store.Quantile(h, p), 1) }
return map[string]any{
"svc": v.Key, "alias": v.Alias, "req": t.Req, "rps_peak": round(float64(peak)/3600, 3),
"sli": round(1-rate, 5), "slo": sloTarget, "budget_left": round(math.Max(0, 1-rate/(1-sloTarget)), 4),
"burn_1h": burn(1), "burn_6h": burn(6), "apdex": round(apdex, 3),
"p50": tri{q(t.Dur, .5), q(t.Org, .5), q(t.Ov, .5)},
"p95": tri{q(t.Dur, .95), q(t.Org, .95), q(t.Ov, .95)},
"p99": tri{q(t.Dur, .99), q(t.Org, .99), q(t.Ov, .99)},
"retries_pct": round(retries, 3), "mix": mix, "spark": spark,
}
}
func (s *Server) servicesAPI(w http.ResponseWriter, r *http.Request) {
from, to, _, host, ok := s.svcWindow(w, r)
if !ok {
return
}
views := s.opt.Store.Services(from, to, "", host)
out := make([]map[string]any, 0, len(views))
for _, v := range views {
out = append(out, serviceItem(v, to))
}
writeJSON(w, 200, out)
}
func (s *Server) serviceAPI(w http.ResponseWriter, r *http.Request) {
from, to, _, host, ok := s.svcWindow(w, r)
if !ok {
return
}
views := s.opt.Store.Services(from, to, r.PathValue("svc"), host)
if len(views) == 0 {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "unknown service"})
return
}
v := views[0]
n := len(v.Hours)
req, errs, p95 := make([]uint32, n), make([]uint32, n), make([]float64, n)
hours := make([]int64, n)
for i, h := range v.Hours {
hours[i], req[i] = h.Hour*3600, h.Req
errs[i] = h.Cls[store.ClsApp] + h.Cls[store.ClsProxy]
p95[i] = round(store.Quantile(h.Dur, .95), 1)
}
type routeOut struct {
Route string `json:"route"`
Class string `json:"class"`
N uint32 `json:"n"`
}
var routes []routeOut
for _, e := range topKV(v.ErrRoutes, 50) {
cl, rt, _ := strings.Cut(e.Key, "|")
routes = append(routes, routeOut{rt, cl, e.N})
}
bounds := store.SvcBounds
writeJSON(w, 200, map[string]any{
"summary": serviceItem(v, to),
"timeline": map[string]any{"hours": hours, "req": req, "errors": errs, "p95": p95},
"histograms": map[string]any{"bounds": bounds[:], "total": v.Tot.Dur, "origin": v.Tot.Org, "overhead": v.Tot.Ov},
"top_routes": routes,
})
}
func (s *Server) protocolsAPI(w http.ResponseWriter, r *http.Request) {
from, to, svc, host, ok := s.svcWindow(w, r)
if !ok {
return
}
views := s.opt.Store.Services(from, to, svc, host)
protos, tls, methods := map[string]map[string]uint32{}, map[string]map[string]uint32{}, map[string]map[string]uint32{}
ciphers := map[string]uint32{}
add := func(dst map[string]map[string]uint32, src map[string]uint32) {
for k, n := range src {
a, b, _ := strings.Cut(k, "|")
if dst[a] == nil {
dst[a] = map[string]uint32{}
}
dst[a][b] += n
}
}
for _, v := range views {
add(protos, v.ProtoCls)
add(tls, v.TLSCls)
add(methods, v.Methods)
for k, n := range v.Ciphers {
ciphers[k] += n
}
}
// methods: the standard ones first, anomalous ones flagged
std := map[string]bool{"GET": true, "HEAD": true, "POST": true, "PUT": true, "PATCH": true, "DELETE": true, "OPTIONS": true}
type mOut struct {
Method string `json:"method"`
Odd bool `json:"odd"`
N uint32 `json:"n"`
Classes map[string]uint32 `json:"classes"`
}
var ms []mOut
for m, c := range methods {
var n uint32
for _, v := range c {
n += v
}
ms = append(ms, mOut{m, !std[m], n, c})
}
sort.Slice(ms, func(a, b int) bool { return ms[a].N > ms[b].N })
if len(ms) > 30 {
ms = ms[:30]
}
type cOut struct {
Name string `json:"name"`
N uint32 `json:"n"`
}
var cs []cOut
for _, e := range topKV(ciphers, 50) {
cs = append(cs, cOut{e.Key, e.N})
}
var https, plain uint32
for k, c := range tls {
for _, n := range c {
if k == "none" {
plain += n
} else {
https += n
}
}
}
writeJSON(w, 200, map[string]any{
"protocols": protos, "tls": tls, "ciphers": cs, "methods": ms,
"scheme": map[string]uint32{"https": https, "http": plain},
})
}
+65
View File
@@ -0,0 +1,65 @@
package server
import (
"encoding/json"
"net/http"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
func TestServicesAndErrorsAPI(t *testing.T) {
st := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour})
now := time.Now()
mk := func(status, origin int, path, ref string, cat core.Category) core.Event {
return core.Event{Time: now.Add(-30 * time.Minute), IP: "20.0.0.9", Cat: cat, Source: "traefik", Domain: "a.example", Method: "GET", Path: path, Referer: ref,
UA: "Mozilla/5.0 x", Status: status, OriginStatus: origin, DurationNS: 30e6, OriginNS: 28e6, Router: "r-app@docker", Service: "r-app@docker",
Proto: "HTTP/2.0", Scheme: "https", TLSVer: "1.3", TLSCiph: "TLS_AES_128_GCM_SHA256", E: core.Enrich{Device: "desktop"}}
}
for i := 0; i < 8; i++ {
st.ObserveService(mk(200, 200, "/", "", core.OK))
}
st.ObserveService(mk(500, 500, "/api/a", "", core.OK))
st.ObserveService(mk(404, 404, "/gone", "https://a.example/", core.NotFound))
st.ObserveService(mk(404, 404, "/.env", "", core.Scanner))
h := New(Options{Token: userTok, Version: "t", Store: st})
auth := map[string]string{"Authorization": "Bearer " + userTok}
e := getJSON(t, h, "/api/v1/errors?range=24h", auth)
cl := e["classes"].(map[string]any)
if cl["app"].(float64) != 1 || cl["attack"].(float64) != 1 || cl["client"].(float64) != 1 || e["errors"].(float64) != 3 {
t.Fatalf("errors: %v", e)
}
if len(e["broken"].([]any)) != 1 || len(e["top_routes"].([]any)) != 3 {
t.Fatalf("lists: %v", e)
}
s := getJSONList(t, h, "/api/v1/services?range=24h", auth)
if len(s) != 1 || s[0].(map[string]any)["svc"] != "r-app" {
t.Fatalf("services: %v", s)
}
d := getJSON(t, h, "/api/v1/services/r-app?range=24h", auth)
if d["histograms"] == nil || d["timeline"] == nil {
t.Fatalf("service: %v", d)
}
if w := do(h, "GET", "/api/v1/services/nope?range=24h", cloneHdr(auth), nil); w.Code != 404 {
t.Fatalf("404 expected, got %d", w.Code)
}
p := getJSON(t, h, "/api/v1/protocols?range=24h", auth)
if p["protocols"].(map[string]any)["http2"] == nil || p["scheme"].(map[string]any)["https"].(float64) != 11 {
t.Fatalf("protocols: %v", p)
}
}
func getJSONList(t *testing.T, h http.Handler, path string, hd map[string]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 []any
if err := json.Unmarshal(w.Body.Bytes(), &m); err != nil {
t.Fatal(err)
}
return m
}
+36
View File
@@ -0,0 +1,36 @@
package server
import (
"net/http"
"strconv"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
func init() {
// GET /api/v1/sessions/funnel?range|from&to&host: every session of the
// period counted by stage, plus the 200 sessions the study keeps and the
// escalation chains. With peers the counts fall back to the merged sample.
registerUserRoute("GET /api/v1/sessions/funnel", func(s *Server) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
p, ok := s.periodStudy(w, r)
if !ok {
return
}
var counts *store.StageCounts
if eq, ok := s.eventFilter(w, r, 24*time.Hour); ok {
if local, peers, _, ok := s.studyHosts(w, eq.Host); ok && local && !peers && s.userSlot(w) {
defer func() { <-s.user }()
pq := store.PeriodQuery{From: eq.From, To: eq.To, IP: eq.IP, Cat: eq.Cat, Fam: eq.Fam}
if n, err := strconv.ParseInt(r.URL.Query().Get("gap"), 10, 64); err == nil {
pq.Gap = n
}
c := s.opt.Store.CountStages(pq)
counts = &c
}
}
writeJSON(w, 200, store.FunnelOf(p, counts))
}
})
}
+37
View File
@@ -0,0 +1,37 @@
package server
import (
"net/http"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
func init() {
registerUserRoute("GET /api/v1/techniques", func(s *Server) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
pq, ok := s.windowQuery(w, r)
if !ok {
return
}
defer func() { <-s.user }()
writeJSON(w, 200, s.opt.Store.Techniques(pq))
}
})
}
// windowQuery parses range|from&to&host like /period and takes a user slot;
// on success the caller releases it with <-s.user.
func (s *Server) windowQuery(w http.ResponseWriter, r *http.Request) (store.PeriodQuery, bool) {
eq, ok := s.eventFilter(w, r, 24*time.Hour)
if !ok {
return store.PeriodQuery{}, false
}
if eq.Host != "" && !s.knownHost(w, eq.Host) {
return store.PeriodQuery{}, false
}
if !s.userSlot(w) {
return store.PeriodQuery{}, false
}
return store.PeriodQuery{From: eq.From, To: eq.To, Host: eq.Host}, true
}
+32
View File
@@ -4,6 +4,7 @@ import (
"bufio"
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
@@ -271,3 +272,34 @@ func TestPeerBlocklistOffUsesLocalOnly(t *testing.T) {
}
}
}
func TestPeerStreamVisitsOnlyOnRequestAndNoIP(t *testing.T) {
const ptok = "peer-secret-0123456789-abcdefghijklmnopqr"
for _, q := range []string{"", "?visits=1"} {
st := store.New(store.Config{Name: "edge", Version: "t"})
st.SetEnricher(fakeGeo{})
ts := httptest.NewServer(New(Options{Token: utok, PeerTokens: []string{ptok}, Version: "t", Store: st}))
req, _ := http.NewRequest("GET", ts.URL+"/api/v1/peer/stream"+q, nil)
req.Header.Set("Authorization", "Bearer "+ptok)
resp, err := http.DefaultClient.Do(req)
if err != nil || resp.StatusCode != 200 {
t.Fatal(err, resp)
}
go func() {
time.Sleep(200 * time.Millisecond)
st.Traffic(core.Event{Time: time.Now(), IP: "200.1.1.9", Cat: core.OK, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/", Status: 200, UA: "Mozilla/5.0 x",
E: core.Enrich{Device: "desktop"}})
time.Sleep(300 * time.Millisecond)
resp.Body.Close()
}()
body, _ := io.ReadAll(resp.Body)
got := strings.Contains(string(body), "event: visit")
if got != (q != "") {
t.Fatalf("query %q: visit event present=%v\n%s", q, got, body)
}
if strings.Contains(string(body), "200.1.1.9") || strings.Contains(string(body), `"ip"`) || strings.Contains(string(body), "Mozilla") {
t.Fatalf("address in stream: %s", body)
}
ts.Close()
}
}
+774
View File
@@ -0,0 +1,774 @@
package server
import (
"bytes"
"encoding/base64"
"fmt"
"html/template"
"image"
"image/color"
"image/png"
"net/http"
"regexp"
"sort"
"strings"
"sync"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
// This file renders GET /api/v1/report?format=html: one self-contained A4 document
// (inline CSS, SVG charts, logo as data URI, no JavaScript). Every dynamic string
// goes through html/template; SVG is built here from escaped text and numbers.
// enforceView is the second-firewall data of the report (nil: engine not running).
type enforceView struct {
Mode string
Share bool
Coverage enforce.Coverage
Counts enforce.Counts
Recent []enforce.Recent
}
// egressView is the outbound-traffic data of the report (nil: analysis not running).
type egressView struct {
Source egress.SourceInfo
Report egress.Report
}
// reportInput is everything the renderer needs. To wire another source, fill a
// field here in reportExtras; the renderer skips sections whose pointer is nil.
type reportInput struct {
Out reportOut
Lang string
Traffic store.TrafficData
Classes [store.NumCls]uint32
HasHealth bool
Enforce *enforceView
Egress *egressView
Peers bool // other hosts included: health and egress cover only this server
}
var (
logoOnce sync.Once
logoURI string
)
// logoDataURI returns web/logo.png scaled to 200px as a data URI (computed once).
func logoDataURI() template.URL {
logoOnce.Do(func() {
raw, err := webFS.ReadFile("web/logo.png")
if err != nil {
return
}
src, err := png.Decode(bytes.NewReader(raw))
if err != nil {
return
}
dst := scaleRGBA(src, 200)
var buf bytes.Buffer
if png.Encode(&buf, dst) == nil {
logoURI = "data:image/png;base64," + base64.StdEncoding.EncodeToString(buf.Bytes())
}
})
return template.URL(logoURI)
}
// scaleRGBA shrinks to a square of side n by averaging premultiplied pixels.
func scaleRGBA(src image.Image, n int) *image.NRGBA {
b := src.Bounds()
w, h := b.Dx(), b.Dy()
dst := image.NewNRGBA(image.Rect(0, 0, n, n))
for y := 0; y < n; y++ {
y0, y1 := y*h/n, (y+1)*h/n
if y1 <= y0 {
y1 = y0 + 1
}
for x := 0; x < n; x++ {
x0, x1 := x*w/n, (x+1)*w/n
if x1 <= x0 {
x1 = x0 + 1
}
var r, g, bl, a, c uint64
for yy := y0; yy < y1 && yy < h; yy++ {
for xx := x0; xx < x1 && xx < w; xx++ {
pr, pg, pb, pa := src.At(b.Min.X+xx, b.Min.Y+yy).RGBA()
r, g, bl, a, c = r+uint64(pr), g+uint64(pg), bl+uint64(pb), a+uint64(pa), c+1
}
}
if c == 0 || a == 0 {
continue
}
dst.SetNRGBA(x, y, color.NRGBA{R: uint8(r * 255 / a), G: uint8(g * 255 / a), B: uint8(bl * 255 / a), A: uint8(a / c >> 8)})
}
}
return dst
}
// ---- view model -------------------------------------------------------------
type kpiV struct{ Label, Value, Delta, Cls string }
type rowV struct{ Cells []string }
type tableV struct {
Head []string
Rows []rowV
Num map[int]bool // right-aligned columns
NoWrap map[int]bool
None string
}
type chartV struct {
Title string
SVG template.HTML
Legend []legendV
Empty bool
}
type legendV struct{ Label, Value, Color string }
type recV struct{ Level, Label, Text string }
type secV struct{ ID, Title string }
type viewV struct {
Lang, Title, RunHead, RunFoot, Kicker, CoverTitle, CoverSub string
Logo template.URL
Motif template.HTML
Servers, Period, Generated string
LPeriod, LServers, LGen, LConf, LToc string
CoverNums []kpiV
TOC []secV
KPIs []kpiV
VerdictCls, VerdictTitle string
Verdict []string
Recs []recV
Trunc string
Timeline chartV
Fams, Techs chartV
IPs, Camps, Escs tableV
Expo tableV
Countries, ASNs chartV
HealthLead string
HealthNotes []string
Classes, Status chartV
VisLead string
VisKPIs []kpiV
Pages, Browsers, Devices, Refs chartV
Defense tableV
HasEnf bool
EnfLead string
EnfNotes []string
EnfKPIs []kpiV
EnfRecent tableV
HasEgress bool
XLead string
XNotes []string
XWl, XFind tableV
XChart, XDst chartV
NoEnf, NoEgress, None, PeersNote, MethodP1, MethodP2, MethodP3 string
TThreats, TGeo, THealth, TVis, TDef, TEnf, TEgress, TRecs, TMethod, TSum string
TIPs, TCamps, TEscs, TExpo, TTimeline, TFams, TTechs, TCountries, TASNs string
TEnfRecent, TXFind, TXWl, TXChart, TXDst, TClasses, TStatus string
ShowPeers bool
}
var rptCCRe = regexp.MustCompile(`^[A-Za-z]{2}$`)
type renderer struct {
lang int
code string
}
func newRenderer(lang string) *renderer {
if strings.HasPrefix(strings.ToLower(lang), "en") {
return &renderer{1, "en"}
}
return &renderer{0, "pt-BR"}
}
func (r *renderer) t(key string, args ...any) string {
v, ok := reportText[key]
if !ok {
return key
}
s := v[r.lang]
if len(args) > 0 {
return fmt.Sprintf(s, args...)
}
return s
}
// num formats integers with the thousands separator of the language.
func (r *renderer) num(n float64) string {
neg := n < 0
if neg {
n = -n
}
s := fmt.Sprintf("%.0f", n)
sep := "."
if r.lang == 1 {
sep = ","
}
var out []byte
for i := range s {
if i > 0 && (len(s)-i)%3 == 0 {
out = append(out, sep...)
}
out = append(out, s[i])
}
if neg {
return "-" + string(out)
}
return string(out)
}
func (r *renderer) dec(v float64, d int) string {
s := fmt.Sprintf("%.*f", d, v)
if r.lang == 0 {
s = strings.Replace(s, ".", ",", 1)
}
return s
}
func (r *renderer) pct(v float64) string { return r.dec(v, 1) + "%" }
func (r *renderer) dur(sec float64) string {
s := int64(sec + 0.5)
switch {
case s < 60:
return fmt.Sprintf("%ds", s)
case s < 3600:
return fmt.Sprintf("%dmin", s/60)
case s < 86400:
return fmt.Sprintf("%dh%02d", s/3600, s%3600/60)
}
return fmt.Sprintf("%dd", s/86400)
}
func (r *renderer) date(ts int64) string {
if r.lang == 1 {
return time.Unix(ts, 0).UTC().Format("2006-01-02 15:04 UTC")
}
return time.Unix(ts, 0).UTC().Format("02/01/2006 15:04 UTC")
}
func (r *renderer) day(ts int64) string {
if r.lang == 1 {
return time.Unix(ts, 0).UTC().Format("2006-01-02")
}
return time.Unix(ts, 0).UTC().Format("02/01/2006")
}
func (r *renderer) yn(b bool) string {
if b {
return r.t("yes")
}
return r.t("no")
}
func (r *renderer) tr(prefix, k string) string {
if v, ok := reportText[prefix+k]; ok {
return v[r.lang]
}
return k
}
func ccOf(cc, name string) string {
switch {
case rptCCRe.MatchString(cc) && name != "":
return strings.ToUpper(cc) + " · " + name
case rptCCRe.MatchString(cc):
return strings.ToUpper(cc)
case name != "":
return name
}
return "-"
}
func (r *renderer) counts(c []store.Count, label func(store.Count) string, n int) []chartItem {
var out []chartItem
for i, x := range c {
if i >= n {
break
}
out = append(out, chartItem{label(x), float64(x.N)})
}
return out
}
func (r *renderer) barChart(title string, items []chartItem, color string) chartV {
if len(items) == 0 {
return chartV{Title: title, Empty: true}
}
return chartV{Title: title, SVG: template.HTML(svgBars(items, color, func(v float64) string { return r.num(v) }, title))}
}
func (r *renderer) donutChart(title string, items []chartItem) chartV {
var total float64
for _, it := range items {
total += it.N
}
if total <= 0 {
return chartV{Title: title, Empty: true}
}
c := chartV{Title: title, SVG: template.HTML(svgDonut(items, title))}
for i, it := range items {
c.Legend = append(c.Legend, legendV{it.Label, r.num(it.N) + " · " + r.pct(it.N/total*100), reportPalette[i%len(reportPalette)]})
}
return c
}
func delta(r *renderer, v float64, ok bool, prev float64) string {
if !ok {
return ""
}
a := "▲"
if v < 0 {
a = "▼"
}
if v > -0.5 && v < 0.5 {
a = "="
}
if v < 0 {
v = -v
}
return fmt.Sprintf("%s %s%% · %s", a, r.num(v+0.0001), r.t("k.before", r.num(prev)))
}
// build turns the data into the view model (all the report decisions live here).
func (r *renderer) build(in reportInput, genTS int64) viewV {
o, s := in.Out, in.Out.Summary
v := viewV{Lang: r.code, Logo: logoDataURI()}
v.Title, v.RunHead, v.RunFoot = r.t("doc.title"), r.t("run.head"), r.t("run.foot")
v.Kicker, v.CoverTitle, v.CoverSub = r.t("cover.kicker"), r.t("cover.title"), r.t("cover.sub")
v.LPeriod, v.LServers, v.LGen, v.LConf, v.LToc = r.t("cover.period"), r.t("cover.servers"), r.t("cover.gen"), r.t("cover.conf"), r.t("toc")
v.None, v.NoEnf, v.NoEgress, v.PeersNote = r.t("none"), r.t("noenf"), r.t("noegress"), r.t("peers.note")
v.MethodP1, v.MethodP2, v.MethodP3 = r.t("m.p1"), r.t("m.p2"), r.t("m.p3")
v.TSum, v.TThreats, v.TGeo, v.THealth, v.TVis = r.t("s.sum"), r.t("s.threats"), r.t("s.geo"), r.t("s.health"), r.t("s.visitors")
v.TDef, v.TEnf, v.TEgress, v.TRecs, v.TMethod = r.t("s.defense"), r.t("s.enforce"), r.t("s.egress"), r.t("s.recs"), r.t("s.method")
v.TIPs, v.TCamps, v.TEscs, v.TExpo, v.TTimeline = r.t("t.ips"), r.t("t.camp"), r.t("t.esc"), r.t("t.expo"), r.t("c.timeline")
v.TFams, v.TTechs, v.TCountries, v.TASNs = r.t("c.families"), r.t("c.techs"), r.t("c.countries"), r.t("c.asns")
v.TEnfRecent, v.TXFind, v.TXWl, v.TXChart, v.TXDst = r.t("t.enf"), r.t("t.find"), r.t("t.wl"), r.t("c.egress"), r.t("c.dst")
v.TClasses, v.TStatus = r.t("c.classes"), r.t("c.status")
v.ShowPeers = in.Peers
servers := r.t("cover.all")
if len(o.Hosts) > 0 {
servers = strings.Join(o.Hosts, ", ")
}
v.Servers = servers
v.Period = r.day(o.Range.From) + " – " + r.day(o.Range.To)
v.Generated = r.date(genTS)
cover := 0.0
if s.HostileIPs > 0 {
cover = o.Defense.BanCoverage
}
v.CoverNums = []kpiV{
{Label: r.t("k.attacks"), Value: r.num(float64(s.Attacks))},
{Label: r.t("k.hostile"), Value: r.num(float64(s.HostileIPs))},
{Label: r.t("k.bans"), Value: r.num(float64(s.Bans))},
{Label: r.t("k.coverage"), Value: r.dec(cover, 0) + "%"},
}
// signals for verdict and recommendations
expo := o.Exposures.Total
var xHigh int
if in.Egress != nil {
for _, f := range in.Egress.Report.Findings {
if f.Severity == "high" || f.Severity == "critical" {
xHigh++
}
}
}
level := "good"
switch {
case expo > 0 || xHigh > 0:
level = "bad"
case len(o.Escalations) > 0 || (s.HostileIPs > 0 && cover < 80):
level = "warn"
}
v.VerdictCls = level
v.VerdictTitle = r.t("verdict." + level)
// verdict paragraph, lay language
var vd []string
if s.Attacks == 0 {
vd = append(vd, r.t("v.none"))
} else {
vd = append(vd, r.t("v.intro", servers, r.num(float64(s.Attacks)), r.num(float64(s.UniqueIPs)), r.num(float64(s.HostileIPs)), r.num(float64(s.Bans))))
if dp, ok := s.DeltaPct["attacks"]; s.HasPrev && ok {
switch {
case dp > -5 && dp < 5:
vd = append(vd, r.t("v.flat"))
case dp > 0:
vd = append(vd, r.t("v.up", r.num(dp)))
default:
vd = append(vd, r.t("v.down", r.num(-dp)))
}
} else {
vd = append(vd, r.t("v.noprev"))
}
if len(o.Families) > 0 && len(o.Countries) > 0 {
vd = append(vd, r.t("v.top", o.Families[0].Key, o.Countries[0].Key))
}
if s.HostileIPs > 0 {
vd = append(vd, r.t("v.cover", r.dec(cover, 0)))
}
if o.Defense.MTTBN > 0 {
vd = append(vd, r.t("v.mttb", r.dur(o.Defense.MTTBMedianS)))
}
}
if expo > 0 {
vd = append(vd, r.t("v.expo", r.num(float64(expo))))
} else if s.Attacks > 0 {
vd = append(vd, r.t("v.expo0"))
}
if len(o.Escalations) > 0 {
vd = append(vd, r.t("v.esc", r.num(float64(len(o.Escalations)))))
}
if xHigh > 0 {
vd = append(vd, r.t("v.egress", r.num(float64(xHigh))))
}
v.Verdict = vd
if o.Truncated {
v.Trunc = r.t("trunc")
}
// KPIs
dl := func(k string, cur, prev uint64) string {
d, ok := s.DeltaPct[k]
return delta(r, d, s.HasPrev && ok, float64(prev))
}
kc := func(warn bool) string {
if warn {
return "warn"
}
return ""
}
v.KPIs = []kpiV{
{r.t("k.requests"), r.num(float64(s.Requests)), dl("requests", s.Requests, s.Prev.Requests), ""},
{r.t("k.attacks"), r.num(float64(s.Attacks)), dl("attacks", s.Attacks, s.Prev.Attacks), kc(s.Attacks > 0)},
{r.t("k.hostile"), r.num(float64(s.HostileIPs)), dl("hostile_ips", uint64(s.HostileIPs), uint64(s.Prev.HostileIPs)), kc(s.HostileIPs > 0)},
{r.t("k.bans"), r.num(float64(s.Bans)), dl("bans", uint64(s.Bans), uint64(s.Prev.Bans)), ""},
{r.t("k.visitors"), r.num(float64(s.Visitors)), dl("visitors", s.Visitors, s.Prev.Visitors), ""},
{r.t("k.coverage"), r.dec(cover, 0) + "%", "", kc(s.HostileIPs > 0 && cover < 80)},
}
// threats
vals := o.Timeline.Values
v.Timeline = chartV{Title: v.TTimeline, SVG: template.HTML(svgArea(vals, o.Timeline.Start, o.Timeline.Step, r.num, v.TTimeline))}
if len(vals) == 0 {
v.Timeline = chartV{Title: v.TTimeline, Empty: true}
}
v.Motif = template.HTML(svgMotif(vals))
v.Fams = r.donutChart(v.TFams, r.counts(o.Families, func(c store.Count) string { return c.Key }, 6))
v.Techs = r.barChart(v.TTechs, r.counts(o.Techniques, func(c store.Count) string {
if c.Label != "" {
return c.Key + " " + c.Label
}
return c.Key
}, 8), "#c2410c")
v.IPs = tableV{Head: []string{r.t("col.ip"), r.t("col.level"), r.t("col.score"), r.t("col.country"), r.t("col.net"), r.t("col.events"), r.t("col.banned")}, Num: map[int]bool{2: true, 5: true}, NoWrap: map[int]bool{0: true}}
for _, x := range o.TopIPs {
v.IPs.Rows = append(v.IPs.Rows, rowV{[]string{x.IP, r.tr("lvl.", x.Level), r.dec(x.Score, 1), ccOf(x.CC, x.Country), dash(x.ASOrg), r.num(float64(x.Events)), r.yn(x.Banned)}})
}
v.Camps = tableV{Head: []string{r.t("col.camp"), r.t("col.ips"), r.t("col.active"), r.t("col.techs")}, Num: map[int]bool{1: true}}
for _, c := range o.Campaigns {
v.Camps.Rows = append(v.Camps.Rows, rowV{[]string{c.ID, r.num(float64(c.IPsN)), r.day(c.First.Unix()) + " – " + r.day(c.Last.Unix()), strings.Join(firstN(c.Techs, 4), ", ")}})
}
v.Escs = tableV{Head: []string{r.t("col.ip"), r.t("col.stage"), r.t("col.host")}}
for _, e := range o.Escalations {
v.Escs.Rows = append(v.Escs.Rows, rowV{[]string{e.IP, r.tr("stage.", e.Stage), dash(e.Host)}})
}
v.Expo = tableV{Head: []string{r.t("col.when"), r.t("col.ip"), r.t("col.host"), r.t("col.path"), r.t("col.status"), r.t("col.fam")}, Num: map[int]bool{4: true}, NoWrap: map[int]bool{0: true, 1: true}}
for _, e := range o.Exposures.Items {
host := e.Domain
if host == "" {
host = e.Host
}
v.Expo.Rows = append(v.Expo.Rows, rowV{[]string{r.date(e.T), e.IP, dash(host), clip(e.Path, 56), fmt.Sprint(e.Status), dash(e.Fam)}})
}
// geography
v.Countries = r.barChart(v.TCountries, r.counts(o.Countries, func(c store.Count) string { return c.Key }, 10), "#087f68")
v.ASNs = r.barChart(v.TASNs, r.counts(o.ASNs, func(c store.Count) string {
if c.Label != "" {
return c.Key + " " + c.Label
}
return c.Key
}, 10), "#087f68")
// health: thwarted attacks are not application errors
c := in.Classes
if in.HasHealth {
good := float64(c[store.ClsAttack] + c[store.ClsBlocked] + c[store.ClsBot])
bad := float64(c[store.ClsApp] + c[store.ClsProxy])
v.HealthLead = r.t("h.lead")
if good > 0 {
v.HealthNotes = append(v.HealthNotes, r.t("h.good", r.num(good)))
}
if bad > 0 {
v.HealthNotes = append(v.HealthNotes, r.t("h.app", r.num(bad)))
}
var items []chartItem
for i, n := range store.ClsNames {
items = append(items, chartItem{r.tr("cls.", n), float64(c[i])})
}
sort.SliceStable(items, func(a, b int) bool { return items[a].N > items[b].N })
v.Classes = r.donutChart(v.TClasses, items)
if in.Traffic.P95 > 0 {
v.HealthNotes = append(v.HealthNotes, r.t("h.p95", r.num(in.Traffic.P50), r.num(in.Traffic.P95)))
}
} else {
v.HealthLead = r.t("h.nodata")
v.Classes = chartV{Title: v.TClasses, Empty: true}
}
st := in.Traffic.Status
v.Status = r.donutChart(v.TStatus, []chartItem{{r.t("st.2xx"), float64(st[0])}, {r.t("st.3xx"), float64(st[1])}, {r.t("st.4xx"), float64(st[2])}, {r.t("st.5xx"), float64(st[3])}})
// visitors
tr := in.Traffic
v.VisLead = r.t("vis.lead")
v.VisKPIs = []kpiV{{Label: r.t("k.visitors"), Value: r.num(float64(tr.Visitors))}, {Label: r.t("k.pages"), Value: r.num(float64(tr.Pages))}, {Label: r.t("k.nonhuman"), Value: r.num(float64(tr.NonHuman))}}
lab := func(c store.Count) string { return dash(c.Key) }
v.Pages = r.barChart(r.t("c.pages"), r.counts(tr.TopPages, lab, 8), "#f97316")
v.Browsers = r.donutChart(r.t("c.browsers"), r.counts(tr.Browsers, lab, 6))
v.Devices = r.donutChart(r.t("c.devices"), r.counts(tr.Devices, lab, 5))
v.Refs = r.barChart(r.t("c.refs"), r.counts(tr.Referrers, lab, 6), "#4b6b61")
// defence
d := o.Defense
nodata := d.MTTBN == 0
mt := func(x float64) string {
if nodata {
return "-"
}
return r.dur(x)
}
v.Defense = tableV{Head: []string{r.t("col.metric"), r.t("col.value"), r.t("col.meaning")}, Num: map[int]bool{1: true}, Rows: []rowV{
{[]string{r.t("d.cover"), r.pct(d.BanCoverage), r.t("d.cover.m")}},
{[]string{r.t("d.mttb"), mt(d.MTTBMedianS), r.t("d.mttb.m")}},
{[]string{r.t("d.mttbp90"), mt(d.MTTBP90S), ""}},
{[]string{r.t("d.mttbn"), r.num(float64(d.MTTBN)), ""}},
{[]string{r.t("d.block"), r.pct(d.BlocklistCover), r.t("d.block.m")}},
{[]string{r.t("d.expo"), r.pct(d.ExposureRate), r.t("d.expo.m")}},
{[]string{r.t("d.refused"), r.pct(d.ExploitsRefused), r.t("d.refused.m")}},
}}
// second firewall
if e := in.Enforce; e != nil && e.Mode != enforce.ModeOff {
v.HasEnf = true
v.EnfLead = r.t("e.lead")
v.EnfNotes = append(v.EnfNotes, r.t("e.mode")+": "+r.t("e.mode."+e.Mode))
cv := e.Coverage
if cv.AttackIPs > 0 {
v.EnfNotes = append(v.EnfNotes, r.t("e.cov", r.num(float64(cv.BlockedByFirewall+cv.BlockedByUrutau)), r.num(float64(cv.AttackIPs)), r.num(float64(cv.BlockedByFirewall)), r.num(float64(cv.BlockedByUrutau))))
}
if cv.WouldBlock > 0 {
v.EnfNotes = append(v.EnfNotes, r.t("e.would", r.num(float64(cv.WouldBlock))))
}
if cv.Unblocked > 0 {
v.EnfNotes = append(v.EnfNotes, r.t("e.unb", r.num(float64(cv.Unblocked))))
}
v.EnfKPIs = []kpiV{{Label: r.t("e.decided"), Value: r.num(float64(e.Counts.Decided))}, {Label: r.t("e.written"), Value: r.num(float64(e.Counts.Written))},
{Label: r.t("e.already"), Value: r.num(float64(e.Counts.AlreadyBlocked))}, {Label: r.t("e.werr"), Value: r.num(float64(e.Counts.WriteErrors)), Cls: kc(e.Counts.WriteErrors > 0)}}
v.EnfRecent = tableV{Head: []string{r.t("col.when"), r.t("col.ip"), r.t("col.reason"), r.t("col.action"), r.t("col.country")}, NoWrap: map[int]bool{0: true, 1: true}}
for i, x := range e.Recent {
if i >= 10 {
break
}
v.EnfRecent.Rows = append(v.EnfRecent.Rows, rowV{[]string{r.date(x.T), x.IP, dash(x.Reason), dash(x.Action), ccOf(x.CC, "")}})
}
}
// egress
if x := in.Egress; x != nil && x.Source.State != "disabled" && x.Source.State != "" {
v.HasEgress = true
v.XLead = r.t("x.lead")
rep := x.Report
if len(rep.Findings) == 0 {
v.XNotes = append(v.XNotes, r.t("x.nof"))
} else {
v.XNotes = append(v.XNotes, r.t("x.sev", r.num(float64(len(rep.Findings))), r.num(float64(xHigh))))
}
v.XNotes = append(v.XNotes, r.t("x.src", x.Source.State))
v.XWl = tableV{Head: []string{r.t("col.wl"), r.t("col.role"), r.t("col.conns"), r.t("col.dst")}, Num: map[int]bool{2: true, 3: true}}
var items []chartItem
for i, w := range rep.Workloads {
if i < 12 {
v.XWl.Rows = append(v.XWl.Rows, rowV{[]string{w.Name, dash(w.Role), r.num(float64(w.Conns)), r.num(float64(w.Dsts))}})
}
if i < 8 {
items = append(items, chartItem{w.Name, float64(w.Conns)})
}
}
v.XChart = r.barChart(v.TXChart, items, "#087f68")
var dst []chartItem
for i, d := range rep.TopDst {
if i >= 8 {
break
}
dst = append(dst, chartItem{d.IP + " " + d.CC, float64(d.Conns)})
}
v.XDst = r.barChart(v.TXDst, dst, "#c2410c")
v.XFind = tableV{Head: []string{r.t("col.sev"), r.t("col.kind"), r.t("col.wl"), r.t("col.dst"), r.t("col.detail")}}
for i, f := range rep.Findings {
if i >= 10 {
break
}
v.XFind.Rows = append(v.XFind.Rows, rowV{[]string{r.tr("sev.", f.Severity), dash(f.Kind), f.Workload, fmt.Sprintf("%s:%d/%s", f.Dst, f.DPort, f.Proto), clip(f.Detail, 80)}})
}
}
for _, tb := range []*tableV{&v.IPs, &v.Camps, &v.Escs, &v.Expo, &v.Defense, &v.EnfRecent, &v.XWl, &v.XFind} {
tb.None = v.None
}
v.Expo.None = r.t("v.expo0")
v.Recs = r.recommend(in, cover, xHigh)
v.TOC = []secV{{"sum", v.TSum}, {"threats", v.TThreats}, {"geo", v.TGeo}, {"health", v.THealth}, {"vis", v.TVis}, {"def", v.TDef}}
if v.HasEnf {
v.TOC = append(v.TOC, secV{"enf", v.TEnf})
}
if v.HasEgress {
v.TOC = append(v.TOC, secV{"egress", v.TEgress})
}
v.TOC = append(v.TOC, secV{"method", v.TMethod})
return v
}
func dash(s string) string {
if s == "" {
return "-"
}
return s
}
func firstN(s []string, n int) []string {
if len(s) > n {
return s[:n]
}
return s
}
// recommend turns the figures into actions with plain rules, most urgent first.
func (r *renderer) recommend(in reportInput, cover float64, xHigh int) []recV {
o, s := in.Out, in.Out.Summary
var rs []recV
add := func(l, k string, a ...any) { rs = append(rs, recV{l, r.t("rec." + l), r.t(k, a...)}) }
enfOn := in.Enforce != nil && in.Enforce.Mode == enforce.ModeOn
if o.Exposures.Total > 0 {
add("bad", "r.expo", r.num(float64(o.Exposures.Total)))
}
if xHigh > 0 {
add("bad", "r.egress", r.num(float64(xHigh)))
}
if len(o.Escalations) > 0 {
add("warn", "r.esc", r.num(float64(len(o.Escalations))))
}
switch {
case in.Enforce == nil || in.Enforce.Mode == enforce.ModeOff:
if s.Attacks > 0 && (s.HostileIPs > 0 && cover < 90) {
add("warn", "r.enforce", r.num(float64(maxInt(s.HostileIPs-s.Bans, 1))))
}
case in.Enforce.Mode == enforce.ModeObserve:
add("warn", "r.observe")
case enfOn && in.Enforce.Coverage.Unblocked > 0:
add("warn", "r.unblocked", r.num(float64(in.Enforce.Coverage.Unblocked)))
}
if s.HostileIPs > 0 && cover < 50 {
add("warn", "r.cover", r.dec(cover, 0))
}
if o.Defense.MTTBN > 0 && o.Defense.MTTBMedianS > 600 {
add("warn", "r.mttb", r.dur(o.Defense.MTTBMedianS))
}
if len(o.Campaigns) > 0 {
add("info", "r.camp", r.num(float64(len(o.Campaigns))))
}
if in.HasHealth {
if n := in.Classes[store.ClsApp] + in.Classes[store.ClsProxy]; n > 0 {
add("warn", "r.app", r.num(float64(n)))
}
}
if dp, ok := s.DeltaPct["attacks"]; s.HasPrev && ok && dp >= 50 && s.Attacks >= 20 {
add("info", "r.up", r.num(dp))
}
if in.Egress == nil || in.Egress.Source.State == "disabled" {
add("info", "r.noegress")
}
if len(rs) == 0 {
add("ok", "r.ok")
}
return rs
}
func maxInt(a, b int) int {
if a > b {
return a
}
return b
}
var reportTpl = template.Must(template.New("report").Parse(reportTemplate))
// renderReportHTML renders the document; the error is a template failure.
func renderReportHTML(in reportInput, now int64) ([]byte, error) {
r := newRenderer(in.Lang)
var buf bytes.Buffer
if err := reportTpl.Execute(&buf, r.build(in, now)); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
var fileSafe = regexp.MustCompile(`[^A-Za-z0-9._-]+`)
// reportExtras gathers what the JSON report does not carry: service health
// classes, traffic study, second firewall and outbound analysis.
func (s *Server) reportExtras(r *http.Request, rc *reportCtx) reportInput {
in := reportInput{Out: rc.out, Lang: r.URL.Query().Get("lang")}
self := s.opt.Store.Name()
in.Traffic = s.trafficOf(r, rc.rg, rc.host)
in.Peers = rc.host != self && s.opt.Hub != nil
if rc.host == "all" || rc.host == self {
for _, v := range s.opt.Store.Services(rc.from, rc.to, "", "") {
in.HasHealth = true
for i := range in.Classes {
in.Classes[i] += v.Tot.Cls[i]
}
}
if e := enforceEngine.Load(); e != nil {
rep := e.Report(rc.from)
in.Enforce = &enforceView{Mode: e.Mode(), Share: e.Share(), Coverage: rep.Coverage, Counts: rep.Counts, Recent: rep.Recent}
}
if e := egressEngine.Load(); e != nil {
in.Egress = &egressView{Source: e.Info(), Report: e.Report(rc.from, rc.to)}
}
}
return in
}
func (s *Server) writeReportHTML(w http.ResponseWriter, r *http.Request, rc *reportCtx) {
now := s.opt.Now().Unix()
body, err := renderReportHTML(s.reportExtras(r, rc), now)
if err != nil {
http.Error(w, "report failed", http.StatusInternalServerError)
return
}
name := fileSafe.ReplaceAllString(rc.host, "-")
if rc.host == "all" && len(rc.out.Hosts) == 1 {
name = fileSafe.ReplaceAllString(rc.out.Hosts[0], "-")
}
if name == "" {
name = "all"
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
// the document is self-contained: inline CSS and data: images only, no script
w.Header().Set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; img-src data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'")
disp := "attachment"
if r.URL.Query().Get("inline") == "1" {
disp = "inline"
}
w.Header().Set("Content-Disposition", fmt.Sprintf(`%s; filename="urutau-relatorio-%s-%s.html"`, disp, name, time.Unix(now, 0).UTC().Format("2006-01-02")))
w.Header().Set("Cache-Control", "no-store")
_, _ = w.Write(body)
}
+193
View File
@@ -0,0 +1,193 @@
package server
// reportText holds the strings of the exported HTML report: [pt-BR, en].
// Unknown keys fall back to the key itself so a typo is visible, not blank.
var reportText = map[string][2]string{
"rec.bad": {"Urgente", "Urgent"},
"rec.warn": {"Importante", "Important"},
"rec.info": {"Sugestão", "Suggestion"},
"rec.ok": {"Tudo certo", "All good"},
"doc.title": {"Urutau · Relatório de segurança", "Urutau · Security report"},
"cover.kicker": {"Ciberfauna · Defesa de servidores web", "Ciberfauna · Web server defence"},
"cover.title": {"Relatório de segurança", "Security report"},
"cover.sub": {"O que atacou, o que foi barrado e o que merece a sua atenção neste período.", "What attacked, what was stopped and what deserves your attention in this period."},
"cover.period": {"Período", "Period"},
"cover.servers": {"Servidor(es)", "Server(s)"},
"cover.gen": {"Gerado em", "Generated"},
"cover.all": {"todos os servidores", "all servers"},
"cover.conf": {"Confidencial · uso interno", "Confidential · internal use"},
"run.head": {"URUTAU · RELATÓRIO DE SEGURANÇA", "URUTAU · SECURITY REPORT"},
"run.foot": {"Ciberfauna · Urutau · uso interno", "Ciberfauna · Urutau · internal use"},
"toc": {"Sumário", "Contents"},
"s.sum": {"Sumário executivo", "Executive summary"},
"s.threats": {"Ameaças", "Threats"},
"s.geo": {"Geografia dos ataques", "Where attacks came from"},
"s.health": {"Erros e saúde dos serviços", "Errors and service health"},
"s.visitors": {"Visitantes", "Visitors"},
"s.defense": {"Defesa", "Defence"},
"s.enforce": {"Segundo firewall", "Second firewall"},
"s.egress": {"Tráfego de saída", "Outbound traffic"},
"s.recs": {"Recomendações", "Recommendations"},
"s.method": {"Como ler este relatório", "How to read this report"},
"k.requests": {"Requisições", "Requests"},
"k.attacks": {"Ataques", "Attacks"},
"k.unique": {"IPs únicos", "Unique IPs"},
"k.hostile": {"IPs hostis", "Hostile IPs"},
"k.bans": {"IPs banidos", "Banned IPs"},
"k.visitors": {"Visitantes", "Visitors"},
"k.nonhuman": {"Clientes não humanos", "Non-human clients"},
"k.pages": {"Páginas vistas", "Page views"},
"k.before": {"antes: %s", "before: %s"},
"k.coverage": {"Cobertura de bloqueio", "Block coverage"},
"verdict.good": {"Situação sob controle", "Under control"},
"verdict.warn": {"Requer atenção", "Needs attention"},
"verdict.bad": {"Ação necessária", "Action needed"},
"v.intro": {"No período, %s registrou %s tentativas de ataque vindas de %s endereços diferentes; %s deles foram classificados como hostis e %s estão banidos.", "In this period, %s recorded %s attack attempts from %s different addresses; %s of them were classified as hostile and %s are banned."},
"v.none": {"Não houve tentativas de ataque registradas no período. Isso é normal em servidores pouco expostos, mas confirme que os logs estão chegando.", "No attack attempts were recorded in this period. That is normal for lightly exposed servers, but make sure logs are arriving."},
"v.up": {"Os ataques aumentaram %s%% em relação ao período anterior.", "Attacks rose %s%% compared with the previous period."},
"v.down": {"Os ataques diminuíram %s%% em relação ao período anterior.", "Attacks fell %s%% compared with the previous period."},
"v.flat": {"O volume de ataques está em linha com o período anterior.", "Attack volume is in line with the previous period."},
"v.noprev": {"Não há período anterior para comparar.", "There is no previous period to compare with."},
"v.top": {"O tipo de ataque mais comum foi %s, e a maior parte veio de %s.", "The most common attack type was %s, and most of it came from %s."},
"v.expo0": {"Nenhuma requisição de ataque obteve resposta de sucesso: nada indica que algo tenha sido exposto.", "No attack request got a success answer: nothing suggests anything was exposed."},
"v.expo": {"Atenção: %s requisições de ataque receberam resposta de sucesso e precisam ser revisadas, pois podem ter alcançado algo que deveria estar protegido.", "Attention: %s attack requests received a success answer and must be reviewed, as they may have reached something that should be protected."},
"v.cover": {"%s%% dos endereços hostis já estão bloqueados.", "%s%% of hostile addresses are already blocked."},
"v.esc": {"%s sessão(ões) mostraram escalada, ou seja, o atacante avançou do reconhecimento para a exploração.", "%s session(s) showed escalation: the attacker moved from reconnaissance to exploitation."},
"v.egress": {"O tráfego de saída tem %s alerta(s) de severidade alta, o que pode indicar um servidor comprometido falando com o exterior.", "Outbound traffic has %s high-severity alert(s), which may indicate a compromised server talking to the outside."},
"v.trunc": {"O estudo foi cortado nos limites internos; os números podem estar parciais.", "The study was cut at its internal limits; figures may be partial."},
"v.mttb": {"Em mediana, um atacante levou %s até ser banido.", "On median, an attacker took %s to get banned."},
"c.timeline": {"Ataques ao longo do tempo", "Attacks over time"},
"c.families": {"Famílias de ataque", "Attack families"},
"c.techs": {"Técnicas MITRE ATT&CK", "MITRE ATT&CK techniques"},
"c.countries": {"Países de origem", "Origin countries"},
"c.asns": {"Redes de origem (ASN)", "Origin networks (ASN)"},
"c.classes": {"Como os pedidos com erro se dividem", "How failed requests split"},
"c.status": {"Respostas por classe", "Responses by class"},
"c.pages": {"Páginas mais acessadas", "Most visited pages"},
"c.browsers": {"Navegadores", "Browsers"},
"c.devices": {"Dispositivos", "Devices"},
"c.refs": {"Origens do acesso", "Referrers"},
"c.egress": {"Conexões por carga de trabalho", "Connections per workload"},
"c.dst": {"Destinos mais contatados", "Most contacted destinations"},
"t.ips": {"Endereços mais perigosos", "Most dangerous addresses"},
"t.camp": {"Campanhas coordenadas", "Coordinated campaigns"},
"t.esc": {"Sessões com escalada", "Escalating sessions"},
"t.expo": {"Requisições de ataque com resposta de sucesso", "Attack requests with a success answer"},
"t.enf": {"Decisões recentes do segundo firewall", "Recent second-firewall decisions"},
"t.find": {"Alertas de saída", "Outbound alerts"},
"t.wl": {"Cargas de trabalho", "Workloads"},
"col.ip": {"Endereço", "Address"},
"col.score": {"Pontuação", "Score"},
"col.level": {"Nível", "Level"},
"col.country": {"País", "Country"},
"col.net": {"Rede", "Network"},
"col.events": {"Eventos", "Events"},
"col.banned": {"Banido", "Banned"},
"col.camp": {"Campanha", "Campaign"},
"col.ips": {"IPs", "IPs"},
"col.active": {"Atividade", "Active"},
"col.techs": {"Técnicas", "Techniques"},
"col.stage": {"Estágio", "Stage"},
"col.host": {"Servidor", "Server"},
"col.path": {"Caminho", "Path"},
"col.status": {"Status", "Status"},
"col.fam": {"Família", "Family"},
"col.when": {"Quando", "When"},
"col.metric": {"Indicador", "Metric"},
"col.value": {"Valor", "Value"},
"col.meaning": {"O que significa", "What it means"},
"col.reason": {"Motivo", "Reason"},
"col.action": {"Ação", "Action"},
"col.sev": {"Severidade", "Severity"},
"col.kind": {"Tipo", "Kind"},
"col.wl": {"Carga", "Workload"},
"col.dst": {"Destino", "Destination"},
"col.conns": {"Conexões", "Connections"},
"col.role": {"Papel", "Role"},
"col.detail": {"Detalhe", "Detail"},
"yes": {"sim", "yes"},
"no": {"não", "no"},
"none": {"Nada a registrar neste período.", "Nothing to report in this period."},
"noenf": {"O segundo firewall não está ativo neste servidor.", "The second firewall is not active on this server."},
"noegress": {"A análise de tráfego de saída não está ativa neste servidor.", "Outbound traffic analysis is not active on this server."},
"unit.attacks": {"ataques", "attacks"},
"cls.attack": {"Ataque frustrado (barrado ou sondagem)", "Thwarted attack (blocked or probe)"},
"cls.blocked": {"Bloqueado pela defesa", "Blocked by the defence"},
"cls.bot": {"Robô ou ferramenta", "Bot or tool"},
"cls.app": {"Erro da aplicação (falha sua)", "Application error (your fault)"},
"cls.proxy": {"Falha do proxy ou serviço fora do ar", "Proxy failure or service down"},
"cls.client_broken": {"Link quebrado do lado do visitante", "Broken link on the visitor side"},
"cls.client_auth": {"Login ou permissão negados", "Login or permission denied"},
"cls.client_other": {"Outro erro do cliente", "Other client error"},
"h.lead": {"Nem todo erro é problema. Um ataque que foi barrado devolve erro e é sinal de que a defesa funcionou; já um erro de aplicação é uma falha do seu serviço e pede correção.", "Not every error is a problem. A thwarted attack returns an error and shows the defence working; an application error is a failure of your own service and needs a fix."},
"h.good": {"%s pedidos com erro foram ataques frustrados ou ruído de robôs, e não indicam defeito.", "%s failed requests were thwarted attacks or bot noise and do not indicate a defect."},
"h.app": {"%s pedidos terminaram em erro de aplicação ou de proxy; esses sim indicam falha de serviço.", "%s requests ended in application or proxy errors; those do indicate a service failure."},
"h.p95": {"Tempo de resposta: mediana %s ms, 95%% dos pedidos abaixo de %s ms.", "Response time: median %s ms, 95%% of requests under %s ms."},
"h.nodata": {"Sem dados de saúde de serviços neste período.", "No service health data in this period."},
"st.2xx": {"2xx sucesso", "2xx success"},
"st.3xx": {"3xx redirecionamento", "3xx redirect"},
"st.4xx": {"4xx erro do cliente", "4xx client error"},
"st.5xx": {"5xx erro do servidor", "5xx server error"},
"vis.lead": {"Visitantes são navegadores reais, contados uma vez por IP e dia. Robôs e ferramentas ficam à parte.", "Visitors are real browsers, counted once per IP and day. Bots and tools are kept apart."},
"d.mttb": {"Tempo mediano até o banimento", "Median time to ban"},
"d.mttbp90": {"Tempo até o banimento (percentil 90)", "Time to ban (90th percentile)"},
"d.mttbn": {"Banimentos medidos", "Bans measured"},
"d.cover": {"Cobertura de banimento", "Ban coverage"},
"d.block": {"Cobertura da lista de bloqueio", "Blocklist coverage"},
"d.expo": {"Taxa de exposição", "Exposure rate"},
"d.refused": {"Exploits recusados", "Exploits refused"},
"d.cover.m": {"Parte dos IPs hostis que já estava banida.", "Share of hostile IPs that were already banned."},
"d.mttb.m": {"Quanto menor, melhor: é a janela entre o primeiro ataque e o bloqueio.", "Lower is better: the window between the first attack and the block."},
"d.block.m": {"Parte dos atacantes que já constava em listas públicas de bloqueio.", "Share of attackers already in public blocklists."},
"d.expo.m": {"Parte dos ataques que recebeu resposta de sucesso. Deve ficar perto de zero.", "Share of attacks that got a success answer. Should stay near zero."},
"d.refused.m": {"Parte das tentativas de exploração recusada pelo servidor.", "Share of exploit attempts refused by the server."},
"e.mode": {"Modo", "Mode"},
"e.mode.on": {"ativo (bloqueia)", "active (blocks)"},
"e.mode.observe": {"observação (só registra o que bloquearia)", "observe (only logs what it would block)"},
"e.mode.off": {"desligado", "off"},
"e.lead": {"O segundo firewall é uma camada extra: o Urutau decide quem bloquear e grava a decisão para outro bloqueador aplicar na borda.", "The second firewall is an extra layer: Urutau decides who to block and writes the decision for another blocker to enforce at the edge."},
"e.cov": {"%s de %s endereços atacantes estão bloqueados (%s pelo firewall, %s pelo Urutau).", "%s of %s attacking addresses are blocked (%s by the firewall, %s by Urutau)."},
"e.would": {"%s endereços seriam bloqueados se o modo ativo estivesse ligado.", "%s addresses would be blocked if active mode were on."},
"e.unb": {"%s endereços atacantes continuam sem bloqueio.", "%s attacking addresses are still unblocked."},
"e.decided": {"Decisões", "Decisions"},
"e.written": {"Gravadas", "Written"},
"e.already": {"Já bloqueadas", "Already blocked"},
"e.rate": {"Descartadas por limite", "Dropped by rate limit"},
"e.werr": {"Erros de gravação", "Write errors"},
"x.lead": {"Tráfego de saída é o que os seus servidores iniciam em direção à internet. Um servidor sadio fala com poucos destinos conhecidos; conversas periódicas com destinos estranhos podem indicar invasão.", "Outbound traffic is what your servers start towards the internet. A healthy server talks to a few known destinations; periodic talks to strange destinations may indicate a breach."},
"x.nof": {"Nenhum alerta de saída no período.", "No outbound alerts in this period."},
"x.sev": {"%s alerta(s) de saída, %s de severidade alta.", "%s outbound alert(s), %s of high severity."},
"x.src": {"Fonte dos dados: %s.", "Data source: %s."},
"stage.recon": {"reconhecimento", "reconnaissance"},
"stage.probe": {"sondagem", "probing"},
"stage.exploit": {"exploração", "exploitation"},
"stage.access": {"acesso", "access"},
"lvl.low": {"baixo", "low"},
"lvl.suspicious": {"suspeito", "suspicious"},
"lvl.hostile": {"hostil", "hostile"},
"sev.high": {"alta", "high"},
"sev.medium": {"média", "medium"},
"sev.low": {"baixa", "low"},
"sev.critical": {"crítica", "critical"},
"r.enforce": {"Ative o segundo firewall (URUTAU_ENFORCE=on). %s atacantes passaram sem bloqueio na borda; hoje o Urutau só os enxerga depois do fato.", "Turn on the second firewall (URUTAU_ENFORCE=on). %s attackers passed without an edge block; today Urutau only sees them after the fact."},
"r.observe": {"O segundo firewall está só observando. Revise as decisões e passe para o modo ativo (URUTAU_ENFORCE=on) para bloquear de fato.", "The second firewall is only observing. Review its decisions and switch to active mode (URUTAU_ENFORCE=on) to actually block."},
"r.unblocked": {"Mesmo com o segundo firewall ativo, %s atacantes seguem sem bloqueio. Confira se o arquivo de decisões está sendo lido pelo bloqueador.", "Even with the second firewall active, %s attackers remain unblocked. Check that the blocker is reading the decisions file."},
"r.expo": {"Revise agora as %s requisições de ataque que receberam resposta de sucesso (seção Ameaças) e confirme que nenhum recurso sensível foi alcançado.", "Review now the %s attack requests that received a success answer (Threats section) and confirm no sensitive resource was reached."},
"r.cover": {"A cobertura de banimento é de apenas %s%%. Reduza o limiar de banimento do fail2ban ou ative a lista de bloqueio compartilhada.", "Ban coverage is only %s%%. Lower the fail2ban ban threshold or enable the shared blocklist."},
"r.mttb": {"O tempo mediano até o banimento (%s) é longo. Bans mais rápidos reduzem a janela de ataque.", "The median time to ban (%s) is long. Faster bans shrink the attack window."},
"r.esc": {"Investigue as %s sessão(ões) com escalada: o atacante passou da sondagem para a exploração.", "Investigate the %s escalating session(s): the attacker moved from probing to exploitation."},
"r.camp": {"Há %s campanha(s) coordenada(s). Considere bloquear as redes de origem inteiras em vez de IP a IP.", "There are %s coordinated campaign(s). Consider blocking whole source networks rather than IP by IP."},
"r.app": {"Corrija os erros de aplicação: %s pedidos falharam por defeito do seu serviço (veja a página Erros no painel).", "Fix the application errors: %s requests failed because of a defect in your service (see the Errors page in the dashboard)."},
"r.egress": {"Investigue os %s alerta(s) de saída de severidade alta; confirme se a carga de trabalho deveria falar com esses destinos.", "Investigate the %s high-severity outbound alert(s); confirm whether the workload should talk to those destinations."},
"r.noegress": {"Ative a análise de tráfego de saída para detectar servidor comprometido falando com o exterior.", "Enable outbound traffic analysis to detect a compromised server talking to the outside."},
"r.up": {"Os ataques cresceram %s%%. Acompanhe a evolução nos próximos dias.", "Attacks grew %s%%. Keep watching in the coming days."},
"r.ok": {"Nenhuma ação urgente. Mantenha os logs chegando e revise este relatório periodicamente.", "No urgent action. Keep logs flowing and review this report periodically."},
"m.p1": {"Os números vêm dos logs do proxy e do SSH lidos pelo Urutau. Endereços, caminhos e nomes aparecem como foram registrados e podem ser falsos: são dados de atacantes.", "Figures come from the proxy and SSH logs read by Urutau. Addresses, paths and names appear as recorded and may be forged: they are attacker-supplied data."},
"m.p2": {"Ataque é toda requisição classificada como varredura, exploração, força bruta ou sondagem SSH. IP hostil é o que acumulou pontuação suficiente para ser tratado como ameaça.", "An attack is any request classified as scanning, exploitation, brute force or SSH probing. A hostile IP is one that accumulated enough score to be treated as a threat."},
"m.p3": {"A comparação usa o período imediatamente anterior, de mesma duração. Datas e horas em UTC.", "Comparisons use the immediately preceding period of the same length. Dates and times are UTC."},
"trunc": {"O estudo foi cortado nos limites internos; os números podem estar parciais.", "The study was cut at its internal limits; figures may be partial."},
"other": {"outros", "other"},
"peers.note": {"Saúde e tráfego de saída refletem apenas o servidor que gerou o relatório.", "Health and outbound traffic reflect only the server that generated the report."},
}
+184
View File
@@ -0,0 +1,184 @@
package server
import (
"fmt"
"html"
"math"
"strings"
"time"
)
// Palette of the printed report (light theme, Ciberfauna identity).
var reportPalette = []string{"#f97316", "#087f68", "#f0b35b", "#45d6b0", "#c2410c", "#4b6b61", "#9aa9a2"}
type chartItem struct {
Label string
N float64
}
func clip(s string, n int) string {
r := []rune(s)
if len(r) <= n {
return s
}
return string(r[:n-1]) + "…"
}
// niceMax rounds a maximum up to 1, 2, 5 x 10^k so the axis reads well.
func niceMax(v float64) float64 {
if v <= 0 {
return 1
}
p := math.Pow(10, math.Floor(math.Log10(v)))
for _, m := range []float64{1, 2, 5, 10} {
if v <= m*p {
return m * p
}
}
return 10 * p
}
// svgArea draws a filled time series. All text is escaped; numbers are formatted here.
func svgArea(vals []uint32, start, step int64, fi func(float64) string, title string) string {
const w, h, ml, mr, mt, mb = 680.0, 150.0, 40.0, 8.0, 8.0, 20.0
var sb strings.Builder
fmt.Fprintf(&sb, `<svg class="chart" viewBox="0 0 %g %g" role="img" aria-label="%s" preserveAspectRatio="xMidYMid meet">`, w, h, html.EscapeString(title))
var mx float64
for _, v := range vals {
if float64(v) > mx {
mx = float64(v)
}
}
top := niceMax(mx)
pw, ph := w-ml-mr, h-mt-mb
for i := 0; i <= 4; i++ {
y := mt + ph - ph*float64(i)/4
fmt.Fprintf(&sb, `<line x1="%g" y1="%.1f" x2="%g" y2="%.1f" stroke="#d7e2dd" stroke-width="0.6"/>`, ml, y, w-mr, y)
fmt.Fprintf(&sb, `<text x="%g" y="%.1f" font-size="9" text-anchor="end" fill="#55665f">%s</text>`, ml-4, y+3, fi(top*float64(i)/4))
}
n := len(vals)
if n > 1 {
xs := func(i int) float64 { return ml + pw*float64(i)/float64(n-1) }
ys := func(v uint32) float64 { return mt + ph - ph*float64(v)/top }
var line strings.Builder
for i, v := range vals {
if i == 0 {
fmt.Fprintf(&line, "M%.1f %.1f", xs(i), ys(v))
} else {
fmt.Fprintf(&line, "L%.1f %.1f", xs(i), ys(v))
}
}
fmt.Fprintf(&sb, `<path d="%sL%.1f %.1f L%.1f %.1f Z" fill="#f97316" fill-opacity="0.18"/>`, line.String(), xs(n-1), mt+ph, xs(0), mt+ph)
fmt.Fprintf(&sb, `<path d="%s" fill="none" stroke="#f97316" stroke-width="1.4" stroke-linejoin="round"/>`, line.String())
if step > 0 {
for i := 0; i < 5; i++ {
idx := (n - 1) * i / 4
ts := start + int64(idx)*step
lbl := time.Unix(ts, 0).UTC().Format("02/01")
if step < 86400 && int64(n)*step <= 3*86400 {
lbl = time.Unix(ts, 0).UTC().Format("02/01 15h")
}
anchor := "middle"
if i == 0 {
anchor = "start"
} else if i == 4 {
anchor = "end"
}
fmt.Fprintf(&sb, `<text x="%.1f" y="%g" font-size="9" text-anchor="%s" fill="#55665f">%s</text>`, xs(idx), h-6, anchor, lbl)
}
}
} else if n == 1 {
fmt.Fprintf(&sb, `<circle cx="%g" cy="%.1f" r="2" fill="#f97316"/>`, ml+pw/2, mt+ph-ph*float64(vals[0])/top)
}
sb.WriteString(`</svg>`)
return sb.String()
}
// svgBars draws horizontal bars with the label on the left and the value on the right.
func svgBars(items []chartItem, color string, fi func(float64) string, title string) string {
const w, lw, rw, rh = 300.0, 112.0, 40.0, 19.0
if len(items) == 0 {
return ""
}
var mx float64
for _, it := range items {
if it.N > mx {
mx = it.N
}
}
if mx <= 0 {
mx = 1
}
h := rh*float64(len(items)) + 2
var sb strings.Builder
fmt.Fprintf(&sb, `<svg class="chart" viewBox="0 0 %g %g" role="img" aria-label="%s">`, w, h, html.EscapeString(title))
bw := w - lw - rw
for i, it := range items {
y := rh * float64(i)
l := it.N / mx * bw
if it.N > 0 && l < 1.5 {
l = 1.5
}
fmt.Fprintf(&sb, `<text x="%g" y="%.1f" font-size="10" text-anchor="end" fill="#22352f">%s</text>`, lw-6, y+13, html.EscapeString(clip(it.Label, 20)))
fmt.Fprintf(&sb, `<rect x="%g" y="%.1f" width="%.1f" height="11" rx="2" fill="%s"/>`, lw, y+3.5, l, color)
fmt.Fprintf(&sb, `<text x="%.1f" y="%.1f" font-size="10" fill="#55665f">%s</text>`, lw+l+4, y+13, fi(it.N))
}
sb.WriteString(`</svg>`)
return sb.String()
}
// svgDonut draws a ring; the legend is HTML next to it (see donutLegend).
func svgDonut(items []chartItem, title string) string {
var total float64
for _, it := range items {
total += it.N
}
var sb strings.Builder
fmt.Fprintf(&sb, `<svg class="donut" viewBox="0 0 120 120" role="img" aria-label="%s">`, html.EscapeString(title))
const r = 44.0
circ := 2 * math.Pi * r
sb.WriteString(`<circle cx="60" cy="60" r="44" fill="none" stroke="#eaf2ef" stroke-width="20"/>`)
if total > 0 {
off := 0.0
for i, it := range items {
if it.N <= 0 {
continue
}
l := it.N / total * circ
fmt.Fprintf(&sb, `<circle cx="60" cy="60" r="44" fill="none" stroke="%s" stroke-width="20" stroke-dasharray="%.2f %.2f" stroke-dashoffset="%.2f" transform="rotate(-90 60 60)"/>`,
reportPalette[i%len(reportPalette)], l, circ-l, -off)
off += l
}
}
sb.WriteString(`</svg>`)
return sb.String()
}
// svgMotif is the faint decoration of the cover, built from the attack series.
func svgMotif(vals []uint32) string {
var sb strings.Builder
sb.WriteString(`<svg class="motif" viewBox="0 0 210 120" preserveAspectRatio="none" aria-hidden="true">`)
for i := 1; i <= 7; i++ {
fmt.Fprintf(&sb, `<line x1="0" y1="%d" x2="210" y2="%d" stroke="#45d6b0" stroke-opacity="0.12" stroke-width="0.25"/>`, i*15, i*15)
}
n := len(vals)
if n > 1 {
var mx uint32 = 1
for _, v := range vals {
if v > mx {
mx = v
}
}
step := 1
if n > 120 {
step = n / 120
}
for i := 0; i < n; i += step {
x := 210 * float64(i) / float64(n-1)
hgt := 4 + 38*float64(vals[i])/float64(mx)
fmt.Fprintf(&sb, `<line x1="%.1f" y1="%.1f" x2="%.1f" y2="%.1f" stroke="#f0b35b" stroke-opacity="0.55" stroke-width="0.7" stroke-linecap="round"/>`, x, 60-hgt/2, x, 60+hgt/2)
}
}
sb.WriteString(`</svg>`)
return sb.String()
}
+123
View File
@@ -0,0 +1,123 @@
package server
import (
"os"
"strings"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
func richReportInput(lang string) reportInput {
var in reportInput
in.Lang = lang
o := &in.Out
o.Range = store.RangeInfo{Name: "7d", From: 1763000000, To: 1763604800, Step: 3600}
o.Hosts = []string{"web-01.example.com", "web-02.example.com"}
o.Summary.reportFigures = reportFigures{Requests: 1843210, Attacks: 48211, UniqueIPs: 912, HostileIPs: 143, Bans: 97, Visitors: 5120, NonHuman: 733, PageViews: 18430}
o.Summary.Prev = reportFigures{Requests: 1500000, Attacks: 30100, UniqueIPs: 700, HostileIPs: 110, Bans: 90, Visitors: 4800, PageViews: 17000}
o.Summary.HasPrev = true
o.Summary.DeltaPct = map[string]float64{"requests": 22.9, "attacks": 60.2, "hostile_ips": 30, "bans": 7.7, "visitors": 6.7}
o.Timeline.Start, o.Timeline.Step = o.Range.From, 3600
for i := 0; i < 168; i++ {
o.Timeline.Values = append(o.Timeline.Values, uint32(200+(i*37)%400+(i%24)*10))
}
o.Families = []store.Count{{Key: "scanner", N: 21000}, {Key: "exploit", N: 14000}, {Key: "bruteforce", N: 8000}, {Key: "ssh-fail", N: 4000}, {Key: "ssh-probe", N: 1211}}
o.Techniques = []store.Count{{Key: "T1190", N: 9000, Label: "Exploit Public-Facing Application"}, {Key: "T1110", N: 4000, Label: "Brute Force"}, {Key: "T1595", N: 3000, Label: "Active Scanning"}}
o.Countries = []store.Count{{Key: "NL", N: 9000}, {Key: "US", N: 8000}, {Key: "DE", N: 5000}, {Key: "RU", N: 3000}, {Key: "BR", N: 900}}
o.ASNs = []store.Count{{Key: "AS64496", N: 9000, Label: "Example Hosting <b>Ltd</b>"}, {Key: "AS64497", N: 5000, Label: "Documentation Net"}}
for i := 0; i < 10; i++ {
o.TopIPs = append(o.TopIPs, reportTopIP{IP: "198.51.100." + string(rune('1'+i)), Score: 92.5 - float64(i), Level: "hostile", CC: "NL", Country: "Netherlands", ASOrg: "Example Hosting", Events: uint32(4000 - i*300), Banned: i%2 == 0})
}
o.Campaigns = []intel.Campaign{{ID: "camp-1", IPsN: 12, First: time.Unix(1763100000, 0), Last: time.Unix(1763500000, 0), Techs: []string{"T1190", "T1595"}}}
o.Escalations = []store.EscalationOut{{IP: "203.0.113.7", Host: "web-01.example.com", Stage: "exploit"}}
o.Exposures.Total = 3
for i := 0; i < 3; i++ {
o.Exposures.Items = append(o.Exposures.Items, reportExposure{T: 1763200000 + int64(i)*600, IP: "203.0.113.7", Domain: "app.example.com", Path: "/<script>alert(1)</script>?x=" + strings.Repeat("a", 120), Status: 200, Fam: "exploit"})
}
o.Defense.MTTBN, o.Defense.MTTBMedianS, o.Defense.MTTBP90S, o.Defense.BanCoverage = 40, 95, 700, 67.8
o.Defense.BlocklistCover, o.Defense.ExposureRate, o.Defense.ExploitsRefused = 31, 0.4, 99
in.Traffic = store.TrafficData{Visitors: 5120, Pages: 18430, NonHuman: 733, P50: 42, P95: 380, Status: [4]uint64{1500000, 200000, 140000, 3210},
TopPages: []store.Count{{Key: "/", N: 9000}, {Key: "/docs", N: 3000}}, Browsers: []store.Count{{Key: "Firefox", N: 3000}, {Key: "Chrome", N: 2000}},
Devices: []store.Count{{Key: "Desktop", N: 4000}, {Key: "Mobile", N: 1100}}, Referrers: []store.Count{{Key: "example.org", N: 400}}}
in.HasHealth = true
in.Classes = [store.NumCls]uint32{store.ClsApp: 120, store.ClsProxy: 12, store.ClsBlocked: 30000, store.ClsAttack: 9000, store.ClsBot: 4000, store.ClsClientBroken: 900, store.ClsClientAuth: 300, store.ClsClientOther: 50}
in.Enforce = &enforceView{Mode: enforce.ModeOn, Coverage: enforce.Coverage{AttackIPs: 143, BlockedByFirewall: 80, BlockedByUrutau: 20, Unblocked: 43},
Counts: enforce.Counts{Decided: 400, Written: 380, AlreadyBlocked: 20},
Recent: []enforce.Recent{{T: 1763300000, IP: "198.51.100.4", Reason: "exploit x12", Action: "ban", CC: "NL"}}}
in.Egress = &egressView{Source: egress.SourceInfo{State: "ok"}, Report: egress.Report{
Workloads: []egress.WorkloadOut{{Name: "app-1", Role: "web", Conns: 12000, Dsts: 14}, {Name: "db-1", Role: "db", Conns: 800, Dsts: 2}},
TopDst: []egress.DstOut{{IP: "192.0.2.10", CC: "US", Conns: 5000}},
Findings: []egress.Finding{{Severity: "high", Kind: "beacon", Workload: "app-1", Dst: "192.0.2.99", DPort: 4444, Proto: "tcp", Detail: "<img src=x onerror=1> periodic"}}}}
return in
}
func TestReportHTMLRenders(t *testing.T) {
for _, lang := range []string{"pt-BR", "en"} {
b, err := renderReportHTML(richReportInput(lang), 1763604800)
if err != nil {
t.Fatal(err)
}
s := string(b)
if strings.Contains(s, "<script") || strings.Contains(s, "<img src=x") || strings.Contains(s, "<b>Ltd") {
t.Fatalf("%s: unescaped attacker data", lang)
}
if !strings.Contains(s, "&lt;script&gt;") || !strings.Contains(s, "data:image/png;base64,") {
t.Fatalf("%s: missing escaped payload or logo", lang)
}
if len(b) > 400<<10 {
t.Fatalf("%s: %d bytes", lang, len(b))
}
want := "Segundo firewall"
if lang == "en" {
want = "Second firewall"
}
if !strings.Contains(s, want) {
t.Fatalf("%s: no %q", lang, want)
}
if dir := os.Getenv("URUTAU_REPORT_OUT"); dir != "" {
_ = os.WriteFile(dir+"/rich-"+lang+".html", b, 0o600)
}
}
}
func TestReportHTMLEmpty(t *testing.T) {
for _, lang := range []string{"", "en", "xx"} {
b, err := renderReportHTML(reportInput{Lang: lang}, 1763604800)
if err != nil || len(b) == 0 {
t.Fatal(err)
}
if dir := os.Getenv("URUTAU_REPORT_OUT"); dir != "" && lang == "" {
_ = os.WriteFile(dir+"/empty.html", b, 0o600)
}
}
}
func TestReportHTMLRoute(t *testing.T) {
h, _ := setup(t)
w := do(h, "GET", "/api/v1/report?range=7d&format=html&lang=en", copyHdr(opsAuth), nil)
if w.Code != 200 {
t.Fatalf("%d %s", w.Code, w.Body)
}
if ct := w.Header().Get("Content-Type"); !strings.HasPrefix(ct, "text/html") {
t.Fatal(ct)
}
cd := w.Header().Get("Content-Disposition")
if !strings.HasPrefix(cd, `attachment; filename="urutau-relatorio-oracle-`) || !strings.HasSuffix(cd, `.html"`) {
t.Fatal(cd)
}
body := w.Body.String()
if strings.Contains(body, "<img src=x") {
t.Fatal("path not escaped")
}
if dir := os.Getenv("URUTAU_REPORT_OUT"); dir != "" {
_ = os.WriteFile(dir+"/route.html", w.Body.Bytes(), 0o600)
}
if w := do(h, "GET", "/api/v1/report?format=html&lang=pt-BR", nil, nil); w.Code != 401 && w.Code != 403 {
t.Fatalf("closed without token: %d", w.Code)
}
}
+185
View File
@@ -0,0 +1,185 @@
package server
// reportTemplate is the document skeleton (html/template; see report_html.go).
// The style block is static text: nothing dynamic reaches CSS.
const reportTemplate = `<!doctype html>
<html lang="{{.Lang}}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex">
<title>{{.Title}}</title>
<style>
:root{--ink:#0d1f1a;--muted:#55665f;--line:#d7e2dd;--paper:#fff;--tint:#f2f8f5;--accent:#087f68;--accent2:#45d6b0;--gold:#f0b35b;--orange:#f97316;--orange2:#fb923c;--crit:#b42318;--high:#c2410c;--med:#a16207;--ok:#087f68;
--sans:system-ui,"Inter","Segoe UI",Roboto,sans-serif;--mono:ui-monospace,"JetBrains Mono","IBM Plex Mono",monospace}
*{box-sizing:border-box}
html,body{margin:0;background:#e9eeec;color:var(--ink);font-family:var(--sans);font-size:10pt;line-height:1.5;-webkit-print-color-adjust:exact;print-color-adjust:exact}
body{padding:0}
.doc{max-width:210mm;margin:0 auto;background:var(--paper)}
.body{padding:0 16mm}
@page{size:A4;margin:22mm 16mm 20mm 16mm;
@top-left{content:"{{.RunHead}}";font-family:var(--mono);font-size:7pt;letter-spacing:.14em;color:#55665f;margin-top:8mm}
@top-right{content:"{{.LConf}}";font-family:var(--mono);font-size:7pt;font-weight:700;letter-spacing:.06em;color:#a15c00;margin-top:8mm}
@bottom-left{content:"{{.RunFoot}}";font-family:var(--mono);font-size:7pt;color:#55665f}
@bottom-right{content:counter(page) " / " counter(pages);font-family:var(--mono);font-size:7pt;color:#55665f}}
@page cover{margin:0;@top-left{content:none}@top-right{content:none}@bottom-left{content:none}@bottom-right{content:none}}
.cover{page:cover;break-after:page;position:relative;width:100%;height:297mm;overflow:hidden;color:#e8f5f0;background:radial-gradient(120% 80% at 80% 55%,#0d3a2f 0%,#06201a 45%,#030d0a 100%)}
.cover .glow{position:absolute;left:70mm;top:92mm;width:160mm;height:160mm;border-radius:50%;background:radial-gradient(circle,rgba(249,115,22,.42) 0%,rgba(251,146,60,.16) 38%,rgba(249,115,22,0) 68%)}
.cover .motif{position:absolute;left:72mm;top:112mm;width:calc(100% - 72mm);height:120mm;opacity:.9}
.cover .logo{position:absolute;left:88mm;top:100mm;width:112mm;height:112mm;object-fit:contain;filter:drop-shadow(0 6mm 10mm rgba(0,0,0,.55))}
.cover .topbar{position:absolute;left:18mm;right:18mm;top:14mm;display:flex;justify-content:space-between;align-items:center}
.wordmark{font-weight:800;letter-spacing:.42em;font-size:11pt;color:#fff}
.auth{font-family:var(--mono);font-size:7.5pt;letter-spacing:.12em;color:#9fc7ba;text-transform:uppercase}
.cover .head{position:absolute;left:18mm;right:18mm;top:34mm}
.eyebrow{font-family:var(--mono);font-size:8pt;letter-spacing:.2em;color:var(--orange2);text-transform:uppercase}
.cover h1{font-size:44px;line-height:1.04;font-weight:800;letter-spacing:-.03em;margin:4mm 0;color:#fff;max-width:165mm}
.cover .sub{font-size:11.5pt;color:#b9d8cd;max-width:140mm;margin:0}
.cover .numbers{position:absolute;left:18mm;top:128mm;width:66mm;display:flex;flex-direction:column;gap:6mm}
.cover .numbers div{border-left:2px solid var(--accent2);padding-left:4mm}
.cover .numbers b{display:block;font-size:26pt;font-weight:800;line-height:1;color:#fff;letter-spacing:-.02em}
.cover .numbers span{font-family:var(--mono);font-size:7pt;letter-spacing:.14em;text-transform:uppercase;color:#9fc7ba}
.cover .meta{position:absolute;left:18mm;right:18mm;bottom:14mm;border-top:1px solid rgba(232,245,240,.25);padding-top:4mm;display:grid;grid-template-columns:1fr 1.7fr 1fr;gap:5mm}
.cover .meta span{display:block;font-family:var(--mono);font-size:6.5pt;letter-spacing:.16em;text-transform:uppercase;color:#86b3a5}
.cover .meta b{display:block;font-size:9pt;font-weight:600;color:#fff;overflow-wrap:anywhere}
section{margin:0 0 7mm}
section.pg{break-before:page}
section.keep{break-inside:avoid}
h2{font-size:17pt;font-weight:800;letter-spacing:-.02em;margin:0 0 3mm;padding-top:4mm;break-after:avoid;background:linear-gradient(var(--accent),var(--accent)) 0 0/14mm 3px no-repeat}
h3{font-size:10.5pt;margin:5mm 0 2mm;break-after:avoid}
p{margin:0 0 2.5mm;orphans:3;widows:3}
.lead{font-size:10.5pt;color:#22352f}
.muted{color:var(--muted)}
@media print{html,body{background:#fff}.doc{max-width:none;margin:0}.body{padding:0}}
.toc ol{list-style:none;padding:0;margin:3mm 0 6mm;counter-reset:t;columns:2;column-gap:8mm}
.toc li{border-bottom:1px solid var(--line);padding:1.3mm 0;counter-increment:t;break-inside:avoid}
.toc a{color:var(--ink);text-decoration:none;font-size:10.5pt}
.toc a::before{content:counter(t,decimal-leading-zero);font-family:var(--mono);color:var(--accent);display:inline-block;width:10mm}
.verdict{border:1px solid var(--line);border-left:5px solid var(--ok);background:var(--tint);padding:4mm 5mm;margin:3mm 0 4mm;break-inside:avoid}
.verdict.warn{border-left-color:var(--orange);background:#fff7ed}
.verdict.bad{border-left-color:var(--crit);background:#fef3f2}
.verdict strong{display:block;font-family:var(--mono);font-size:8pt;letter-spacing:.14em;text-transform:uppercase;color:var(--ok);margin-bottom:1.5mm}
.verdict.warn strong{color:var(--high)}.verdict.bad strong{color:var(--crit)}
.verdict p{margin:0 0 1.5mm;font-size:10.5pt}
.kpis{break-inside:avoid;display:grid;grid-template-columns:repeat(3,1fr);gap:3.5mm;margin:3mm 0 4mm}
.kpi{border-top:3px solid var(--accent);background:var(--tint);padding:2.5mm 3.5mm;break-inside:avoid}
.kpi.warn{border-top-color:var(--orange)}
.kpi b{display:block;font-size:19pt;font-weight:800;letter-spacing:-.02em;line-height:1.1}
.kpi span{display:block;font-family:var(--mono);font-size:6.8pt;letter-spacing:.1em;text-transform:uppercase;color:var(--muted)}
.kpi i{display:block;font-style:normal;font-size:7.5pt;color:var(--muted);margin-top:.5mm}
.kpis.k4{grid-template-columns:repeat(4,1fr)}
.recs{list-style:none;padding:0;margin:2mm 0}
.recs li{border-left:3px solid var(--accent);background:var(--tint);padding:2.5mm 4mm;margin:0 0 2.5mm;break-inside:avoid}
.recs li.bad{border-left-color:var(--crit);background:#fef3f2}.recs li.warn{border-left-color:var(--orange);background:#fff7ed}
.recs li b{font-family:var(--mono);font-size:7pt;letter-spacing:.14em;text-transform:uppercase;display:block;color:var(--accent)}
.recs li.bad b{color:var(--crit)}.recs li.warn b{color:var(--high)}
.grid2.wl{grid-template-columns:1.9fr 1fr}
.grid2{display:grid;grid-template-columns:1fr 1fr;gap:5mm}
.box{break-inside:avoid;margin:0 0 4mm;border:1px solid var(--line);border-radius:2mm;padding:2.5mm 3.5mm}
.box h3{margin:0 0 2mm;font-size:9.5pt}
.chart{width:100%;height:auto;display:block}
.donutwrap{display:flex;gap:4mm;align-items:center}
.grid2 .box+.box .donutwrap{flex-direction:column;align-items:flex-start}
.donut{width:25mm;height:25mm;flex:none}
.legend{list-style:none;margin:0;padding:0;font-size:8pt;flex:1;min-width:0}
.legend li{display:flex;flex-wrap:wrap;gap:0 2mm;align-items:baseline;margin:0 0 1.2mm}
.legend .sw{width:2.6mm;height:2.6mm;border-radius:50%;flex:none;position:relative;top:.2mm}
.legend .lb{flex:1 1 28mm;min-width:0;overflow-wrap:break-word}.legend .vl{font-family:var(--mono);color:var(--muted);white-space:nowrap}
.c0{background:#f97316}.c1{background:#087f68}.c2{background:#f0b35b}.c3{background:#45d6b0}.c4{background:#c2410c}.c5{background:#4b6b61}.c6{background:#9aa9a2}
table{width:100%;border-collapse:collapse;margin:1mm 0 3mm;font-size:8.3pt}
thead{display:table-header-group}
th{text-align:left;font-family:var(--mono);font-size:6.8pt;letter-spacing:.08em;text-transform:uppercase;color:var(--muted);border-bottom:1.5px solid var(--ink);padding:1.5mm 2mm}
td{padding:1.5mm 2mm;border-bottom:1px solid var(--line);vertical-align:top;overflow-wrap:anywhere}
tbody tr:nth-child(even) td{background:var(--tint)}
tr{break-inside:avoid}
td.n,th.n{text-align:right;font-variant-numeric:tabular-nums}td.n,td.w{white-space:nowrap}
.tbl{break-inside:avoid-page}
.tbl h3{margin-top:4mm}
.empty{color:var(--muted);font-style:italic;margin:1mm 0 3mm}
.note{border-left:3px solid var(--accent);padding:1.5mm 3.5mm;margin:0 0 2mm;background:var(--tint);break-inside:avoid}
.warn-t{color:var(--high);font-weight:600}
</style>
</head>
<body>
<div class="doc">
<div class="cover">
<div class="glow"></div>
{{.Motif}}
<img class="logo" src="{{.Logo}}" alt="Urutau">
<div class="topbar"><span class="wordmark">URUTAU</span><span class="auth">{{.LConf}}</span></div>
<div class="head"><div class="eyebrow">{{.Kicker}}</div><h1>{{.CoverTitle}}</h1><p class="sub">{{.CoverSub}}</p></div>
<div class="numbers">{{range .CoverNums}}<div><b>{{.Value}}</b><span>{{.Label}}</span></div>{{end}}</div>
<div class="meta"><div><span>{{.LPeriod}}</span><b>{{.Period}}</b></div><div><span>{{.LServers}}</span><b>{{.Servers}}</b></div><div><span>{{.LGen}}</span><b>{{.Generated}}</b></div></div>
</div>
<div class="body">
<section class="toc"><h2>{{.LToc}}</h2><ol>{{range .TOC}}<li><a href="#{{.ID}}">{{.Title}}</a></li>{{end}}</ol>
<h2 id="sum">{{.TSum}}</h2>
<div class="verdict {{.VerdictCls}}"><strong>{{.VerdictTitle}}</strong>{{range .Verdict}}<p>{{.}}</p>{{end}}</div>
{{if .Trunc}}<p class="warn-t">{{.Trunc}}</p>{{end}}
<div class="kpis">{{range .KPIs}}<div class="kpi {{.Cls}}"><span>{{.Label}}</span><b>{{.Value}}</b>{{if .Delta}}<i>{{.Delta}}</i>{{end}}</div>{{end}}</div>
</section>
<section class="pg" id="recs"><h2>{{.TRecs}}</h2>
<ul class="recs">{{range .Recs}}<li class="{{.Level}}"><b>{{.Label}}</b>{{.Text}}</li>{{end}}</ul>
</section>
<section id="threats"><h2>{{.TThreats}}</h2>
<div class="box"><h3>{{.Timeline.Title}}</h3>{{if .Timeline.Empty}}<p class="empty">{{.None}}</p>{{else}}{{.Timeline.SVG}}{{end}}</div>
<div class="grid2">
{{template "donut" .Fams}}
{{template "bars" .Techs}}
</div>
<div class="tbl"><h3>{{.TIPs}}</h3>{{template "table" .IPs}}</div>
<div class="tbl"><h3>{{.TCamps}}</h3>{{template "table" .Camps}}</div>
<div class="tbl"><h3>{{.TEscs}}</h3>{{template "table" .Escs}}</div>
<div class="tbl"><h3>{{.TExpo}}</h3>{{template "table" .Expo}}</div>
</section>
<section class="keep" id="geo"><h2>{{.TGeo}}</h2>
<div class="grid2">{{template "bars" .Countries}}{{template "bars" .ASNs}}</div>
</section>
<section id="health"><h2>{{.THealth}}</h2>
<p class="lead">{{.HealthLead}}</p>
{{range .HealthNotes}}<div class="note">{{.}}</div>{{end}}
<div class="grid2 wl" style="margin-top:3mm">{{template "donut" .Classes}}{{template "donut" .Status}}</div>
{{if .ShowPeers}}<p class="muted">{{.PeersNote}}</p>{{end}}
</section>
<section class="keep" id="vis"><h2>{{.TVis}}</h2>
<p class="lead">{{.VisLead}}</p>
<div class="kpis">{{range .VisKPIs}}<div class="kpi"><span>{{.Label}}</span><b>{{.Value}}</b></div>{{end}}</div>
<div class="grid2">{{template "bars" .Pages}}{{template "bars" .Refs}}{{template "donut" .Browsers}}{{template "donut" .Devices}}</div>
</section>
<section class="keep" id="def"><h2>{{.TDef}}</h2>
{{template "table" .Defense}}
</section>
{{if .HasEnf}}<section class="keep" id="enf"><h2>{{.TEnf}}</h2>
<p class="lead">{{.EnfLead}}</p>
{{range .EnfNotes}}<div class="note">{{.}}</div>{{end}}
<div class="kpis k4">{{range .EnfKPIs}}<div class="kpi {{.Cls}}"><span>{{.Label}}</span><b>{{.Value}}</b></div>{{end}}</div>
<div class="tbl"><h3>{{.TEnfRecent}}</h3>{{template "table" .EnfRecent}}</div>
</section>{{end}}
{{if .HasEgress}}<section class="keep" id="egress"><h2>{{.TEgress}}</h2>
<p class="lead">{{.XLead}}</p>
{{range .XNotes}}<div class="note">{{.}}</div>{{end}}
<div class="grid2" style="margin-top:3mm">{{template "bars" .XChart}}{{template "bars" .XDst}}</div>
<div class="tbl"><h3>{{.TXFind}}</h3>{{template "table" .XFind}}</div>
<div class="tbl"><h3>{{.TXWl}}</h3>{{template "table" .XWl}}</div>
</section>{{end}}
<section class="keep" id="method"><h2>{{.TMethod}}</h2>
<p>{{.MethodP1}}</p><p>{{.MethodP2}}</p><p>{{.MethodP3}}</p>
</section>
</div>
</div>
</body>
</html>
{{define "table"}}{{if .Rows}}{{$n := .Num}}{{$w := .NoWrap}}<table><thead><tr>{{range $i, $h := .Head}}<th{{if index $n $i}} class="n"{{end}}>{{$h}}</th>{{end}}</tr></thead><tbody>{{range .Rows}}<tr>{{range $i, $c := .Cells}}<td{{if index $n $i}} class="n"{{else if index $w $i}} class="w"{{end}}>{{$c}}</td>{{end}}</tr>{{end}}</tbody></table>{{else}}<p class="empty">{{.None}}</p>{{end}}{{end}}
{{define "bars"}}<div class="box"><h3>{{.Title}}</h3>{{if .Empty}}<p class="empty">-</p>{{else}}{{.SVG}}{{end}}</div>{{end}}
{{define "donut"}}<div class="box"><h3>{{.Title}}</h3>{{if .Empty}}<p class="empty">-</p>{{else}}<div class="donutwrap">{{.SVG}}<ul class="legend">{{range $i, $l := .Legend}}<li><span class="sw c{{$i}}"></span><span class="lb">{{$l.Label}}</span><span class="vl">{{$l.Value}}</span></li>{{end}}</ul></div>{{end}}</div>{{end}}
`
+18
View File
@@ -0,0 +1,18 @@
package server
import "net/http"
// userRoute is an authenticated /api/v1 route contributed by its own file
// (api_<name>.go) so that new analysis endpoints never edit server.go.
type userRoute struct {
pattern string
handler func(*Server) http.HandlerFunc
}
var userRoutes []userRoute
// registerUserRoute is called from init() in api_<name>.go files. The route
// is wrapped by Server.api: session or URUTAU_TOKEN only, peer token 403.
func registerUserRoute(pattern string, h func(*Server) http.HandlerFunc) {
userRoutes = append(userRoutes, userRoute{pattern, h})
}
+45 -3
View File
@@ -102,6 +102,7 @@ func New(opt Options) http.Handler {
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/peer/egress", s.peerEgress)
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))
@@ -114,6 +115,14 @@ func New(opt Options) http.Handler {
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))
// Analysis routes added by api_<name>.go files through registerUserRoute
// (init): user auth only, same wrapper as every /api/v1 route.
for _, r := range userRoutes {
m.HandleFunc(r.pattern, s.api(r.handler(s)))
}
for _, r := range peerRoutes { // peer-token routes of api_<name>.go files
m.HandleFunc(r.pattern, r.handler(s))
}
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)))
@@ -191,7 +200,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, /api/v1/peer/stream and /api/v1/peer/period"})
writeJSON(w, http.StatusForbidden, map[string]string{"error": "the peer token only opens /api/v1/peer/export, /api/v1/peer/stream, /api/v1/peer/period and /api/v1/peer/egress"})
return
default:
ip := clientIP(r, s.opt.TrustedProxy)
@@ -633,21 +642,34 @@ func (s *Server) stream(w http.ResponseWriter, r *http.Request) {
defer stopHub()
hubCh = c
}
// ?visits=1 also streams the legitimate visits (no address in them); nil blocks forever
var visCh, hubVisCh <-chan store.VisitMsg
if r.URL.Query().Get("visits") == "1" {
c, stopV := s.opt.Store.SubscribeVisits()
defer stopV()
visCh = c
if s.opt.Hub != nil {
c, stopHV := s.opt.Hub.SubscribeVisits()
defer stopHV()
hubVisCh = 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 {
sendAs := func(name string, e any) 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 {
if _, err := fmt.Fprintf(w, "event: %s\ndata: %s\n\n", name, b); err != nil {
return false
}
fl.Flush()
return true
}
send := func(e store.LiveEvent) bool { return sendAs("ev", e) }
for {
select {
case <-r.Context().Done():
@@ -668,6 +690,14 @@ func (s *Server) stream(w http.ResponseWriter, r *http.Request) {
if !send(e) {
return
}
case e := <-visCh:
if !sendAs("visit", e) {
return
}
case e := <-hubVisCh:
if !sendAs("visit", e) {
return
}
}
}
}
@@ -697,6 +727,12 @@ func (s *Server) peerStream(w http.ResponseWriter, r *http.Request) {
h.Set("X-Accel-Buffering", "no")
ch, stop := s.opt.Store.Subscribe()
defer stop()
var visCh <-chan store.VisitMsg // only with ?visits=1; carries no address
if r.URL.Query().Get("visits") == "1" {
c, stopV := s.opt.Store.SubscribeVisits()
defer stopV()
visCh = c
}
fmt.Fprint(w, "retry: 3000\n: connected\n\n")
fl.Flush()
tick := time.NewTicker(sseHeartbeat)
@@ -705,6 +741,12 @@ func (s *Server) peerStream(w http.ResponseWriter, r *http.Request) {
select {
case <-r.Context().Done():
return
case v := <-visCh:
b, _ := json.Marshal(v)
if _, err := fmt.Fprintf(w, "event: visit\ndata: %s\n\n", b); err != nil {
return
}
fl.Flush()
case <-tick.C:
if !s.opt.NoAuth && s.authKind(r) != "peer" {
return
+400 -60
View File
@@ -28,6 +28,19 @@
* pt-BR "nas últimas 6 horas" / "na última hora" / "nos últimos 7 dias" / "entre 12 nov 10:00 e 14 nov 18:00"
* Urutau.href(pageId, segments?, query?) -> hash that keeps the current slice
* Urutau.toast(msg) short confirmation toast
* Urutau.help(node, key) appends an accessible "?" button to node (keyboard focus, aria-describedby,
* popover with a short text and "what to do"). Urutau.glossary = { has(key), get(key) -> {text, action} }.
* Keys (central dictionary, en + pt-BR, each with a ".do" companion): help.cat.<category>,
* help.metric.<name> (requests, malicious, unique_ips, attacks_per_hour_24h, moving_avg_7d_per_hour, trend,
* active_attackers_24h/_1h, new_attackers, returning_rate, sessions_per_day, exposure_rate, exploits_refused_pct,
* ban_coverage, blocklist_coverage, blocklist_leak, mttb, visitors, pages, bytes, latency, bots) and
* help.term.<term> (session, stage.recon|probe|exploit|access|banned, campaign, family, mitre, net_type, cadence,
* score, level, fcrdns, exposure, blocklist, peer, hub, client_type, status_class, attack_profile).
* Pass the key WITHOUT the "help." prefix: Urutau.help(el, 'metric.mttb'). Metric cards accept {help:'metric.x'},
* panels accept {help:'term.x'}. Category names: t('cat.<c>') is the long name, t('cat.short.<c>') the short one.
* Groups: registerPage({..., group:'monitor|investigate|analyze|operate|reports'}); known ids are placed by the built-in
* order, unknown ids go to the end of their group (default group: analyze).
* Page scripts load from /pages.json ({"pages":[{"name":"geo","css":true}]}): add your name there when you create <name>.js.
* Urutau.registerI18n({ en: {...}, 'pt-BR': {...} }) merge keys (existing keys win)
* Urutau.t(key, vars?) vars: a number (fills {n}) or an object ({name: ...})
* Urutau.api(path, params) -> Promise<json> GET with query params; 401 goes to
@@ -45,6 +58,16 @@
* function handlers, any other attribute as a string. SVG tags work.
* Urutau.css(name) reads a design token, e.g. css('accent') or css('--cat-exploit')
* Urutau.setSliceNote(text) optional extra words appended to the slice sentence
* Urutau.charts: own SVG chart library (no dependencies, CSP-safe, theme tokens, ResizeObserver,
* every chart also renders a visually hidden <table> for screen readers, and an empty
* state when there is nothing to draw). Every function returns a DOM node; append it.
* donut(data[{key,label,value}], {title, colors:['--viz-3',...], centerLabel, format})
* radar(axes[{key,label}], series[{label,values[]}], {max, format, colors, title})
* stackedArea(series[{key,label,values[]}], stepSeconds, {start (unix), colors, title})
* bars(rows[{key,label,value,color?:'--token',parts?:[{label,value,color?}]}], {horizontal=true, stacked, format, colors, title})
* heatmap(matrix[row][col], xLabels[], yLabels[], {format, title}) cells use --seq-1..5
* sparkline(values[]) gauge(value, max, thresholds[{at,tone:'ok|warn|danger|info'}], {label, format})
* colors are CSS token names ("--viz-1"); the default palette is --viz-1..8 in order.
* Urutau.ui = { panel, stat, metric, lead, empty, badge, bars, chart, sparkline } shared primitives
* (the same ones the core pages use; see their definitions below)
*
@@ -357,6 +380,7 @@
var acts = opts.actions ? [].concat(opts.actions) : null;
var head = h('div', 'panel-h', h('h2', null, opts.title), acts ? h('div', 'acts', acts) : null);
var body = h('div', 'panel-b', kids);
if (opts.help) help(head.firstChild, opts.help);
var variant = pick(['list', 'chart', 'map'], opts.variant, '');
var foot = opts.footer ? h('div', 'panel-f', opts.footer) : null;
var node = h('section', 'panel' + (variant ? ' card-' + variant : '') + (opts.cls ? ' ' + opts.cls : ''), head, opts.hint ? h('p', 'hint', opts.hint) : null, body, foot);
@@ -384,11 +408,13 @@
var arrow = o.delta === 0 ? '\u25A0' : up ? '\u25B2' : '\u25BC';
dl = h('p', 'cm-delta' + (big && o.delta !== 0 ? (good ? ' good' : ' bad') : ''), arrow + ' ' + nfFor({ maximumFractionDigits: 0 }, 'd0').format(Math.abs(o.delta)) + '%');
}
var n = h('div', 'card-metric' + (tn === 'neutral' ? '' : ' tone-' + tn), h('p', 'cm-label', label), h('p', 'cm-value num', value), dl, o.sub ? h('p', 'cm-sub', o.sub) : null, sparkline(o.spark));
var lab = h('p', 'cm-label', label);
if (o.help) help(lab, o.help);
var n = h('div', 'card-metric' + (tn === 'neutral' ? '' : ' tone-' + tn), lab, h('p', 'cm-value num', value), dl, o.sub ? h('p', 'cm-sub', o.sub) : null, sparkline(o.spark));
if (o.hint) n.title = o.hint;
return n;
}
function stat(label, value, sub, tone, hint) { return metric(label, value, { sub: sub, tone: tone, hint: hint }); }
function stat(label, value, sub, tone, hint, helpKey) { return metric(label, value, { sub: sub, tone: tone, hint: hint, help: helpKey }); }
function lead(title, body, tone) {
var tn = pick(['ok', 'danger', 'neutral'], tone, 'ok');
return h('section', 'lead tone-' + tn, h('div', null, h('h2', null, title), body ? h('p', null, body) : null), h('span', 'pulse', ''));
@@ -402,7 +428,47 @@
function showSkeleton(box, n, cls) { clear(box); for (var i = 0; i < n; i++) box.appendChild(h('div', cls || 'skeleton')); }
function badge(text, tone) { var tn = pick(KNOWN_TONES, tone, 'neutral'); return h('span', 'badge' + (tn === 'neutral' ? '' : ' tone-' + tn), text); }
function levelBadge(l) { l = pick(KNOWN_LEVELS, l, 'low'); return badge(t('level.' + l), LEVEL_TONE[l]); }
function catPill(c, label) { var k = pick(KNOWN_CATS, c, 'ok'); return h('span', 'cat c-' + k, label || t('cat.' + k)); }
function catShort(c) { var k = pick(KNOWN_CATS, c, 'ok'); return t('cat.short.' + k); }
function catPill(c, label) { var k = pick(KNOWN_CATS, c, 'ok'), n = h('span', 'cat c-' + k, label || catShort(k)); n.title = t('cat.' + k); return n; }
// ---------------------------------------------------------------- help and glossary
// help.cat.<cat>, help.metric.<name>, help.term.<term> (+ ".do" = what to do) live in the central dictionary
var glossary = {
has: function (key) { var k = 'help.' + key; return t(k) !== k; },
get: function (key) { var k = 'help.' + key, tx = t(k); if (tx === k) return null; var dk = k + '.do', d = t(dk); return { text: tx, action: d === dk ? '' : d }; }
};
var helpPop = null, helpBtn = null, helpPinned = false;
function ensureHelpPop() {
if (!helpPop) { helpPop = h('div', 'help-pop'); helpPop.id = 'help-pop'; helpPop.setAttribute('role', 'tooltip'); helpPop.hidden = true; document.body.appendChild(helpPop); }
return helpPop;
}
function hideHelp() { if (helpPop) helpPop.hidden = true; helpBtn = null; helpPinned = false; }
function showHelp(btn, key) {
var g = glossary.get(key), pop = ensureHelpPop();
if (!g) return;
clear(pop);
pop.appendChild(h('p', 'help-t', g.text));
if (g.action) pop.appendChild(h('p', 'help-do', h('strong', null, t('help.do') + ': '), g.action));
pop.hidden = false; helpBtn = btn;
var r = btn.getBoundingClientRect(), w = pop.offsetWidth, ph = pop.offsetHeight;
var left = Math.max(8, Math.min(r.left, window.innerWidth - w - 8)), top = r.bottom + 6;
if (top + ph > window.innerHeight - 8) top = Math.max(8, r.top - ph - 6);
pop.style.left = left + 'px'; pop.style.top = top + 'px';
}
// append an accessible "?" to a node: focusable, aria-describedby, popover with short text + what to do
function help(node, key) {
if (!node || !glossary.has(key)) return null;
var b = el('button', { type: 'button', class: 'help-btn', 'aria-label': t('help.label'), 'aria-describedby': 'help-pop' }, '?');
ensureHelpPop();
b.addEventListener('mouseenter', function () { if (!helpPinned) showHelp(b, key); });
b.addEventListener('focus', function () { if (!helpPinned) showHelp(b, key); });
b.addEventListener('mouseleave', function () { if (!helpPinned) hideHelp(); });
b.addEventListener('blur', function () { if (!helpPinned) hideHelp(); });
b.addEventListener('click', function (e) { e.stopPropagation(); if (helpBtn === b && helpPinned) hideHelp(); else { showHelp(b, key); helpPinned = true; } });
node.appendChild(b);
return b;
}
// ranked list with a proportional bar; rows: [{key, n, label?}]
function bars(rows, opts) {
@@ -628,6 +694,8 @@
});
th.appendChild(b);
} else th.textContent = colLabel(x.k);
var hk = { score: 'term.score', level: 'term.level', cats: 'term.categories', origin: 'term.net_type' }[x.k];
if (hk) help(th, hk);
tr.appendChild(th);
});
thead.appendChild(tr);
@@ -665,7 +733,7 @@
var chips = h('span');
var kinds = Object.keys(x.counts || {}).filter(function (k) { return k !== 'ok' && k !== 'ssh-ok' && KNOWN_CATS.indexOf(k) >= 0; })
.sort(function (a, b) { return x.counts[b] - x.counts[a]; });
kinds.slice(0, 2).forEach(function (k) { chips.appendChild(h('span', 'chip', t('cat.' + k) + ' ' + nf(x.counts[k]))); });
kinds.slice(0, 2).forEach(function (k) { { var cp = h('span', 'chip', catShort(k) + ' ' + nf(x.counts[k])); cp.title = t('cat.' + k); chips.appendChild(cp); } });
if (kinds.length > 2) chips.appendChild(h('span', 'chip', '+' + (kinds.length - 2)));
cell('cats', chips); break;
}
@@ -822,7 +890,7 @@
bar.appendChild(fill);
[[1, 'drawer.cut.susp'], [5, 'drawer.cut.host']].forEach(function (c) { var tk = h('b', 'tick'); tk.style.left = c[0] + '%'; tk.title = t(c[1]); bar.appendChild(tk); });
var verdict = h('section', 'ip-verdict lv-' + pick(KNOWN_LEVELS, level, 'low'),
h('div', 'iv-top', levelBadge(level), h('span', 'iv-score num', nf(score)), h('span', 'iv-max', '/ 1000')), bar,
h('div', 'iv-top', (function () { var w = h('span', 'iv-lv', levelBadge(level)); help(w, 'term.level'); return w; })(), h('span', 'iv-score num', nf(score)), h('span', 'iv-max', '/ 1000'), (function () { var w = h('span', 'iv-h'); help(w, 'term.score'); return w; })()), bar,
h('p', 'note iv-cuts', t('drawer.cuts')),
origin ? h('p', 'iv-origin', origin) : null,
first && last ? h('p', 'note', t('drawer.active', { v: spanText(last - first) }) + ' \u00b7 ' + t('detail.last') + ': ' + ago(last)) : null);
@@ -836,7 +904,7 @@
var days = typeof tm.active_days === 'number' ? nf(tm.active_days) : '\u2014';
var nbans = (d.bans && d.bans.length) || (d.jails || []).length;
box.appendChild(h('div', 'drawer-metrics',
metric(t('drawer.m.events'), nf(evs)), metric(t('drawer.m.days'), days), metric(t('drawer.m.hosts'), nf((d.hosts || []).length)), metric(t('drawer.m.bans'), nf(nbans), { hint: t('drawer.m.bans') })));
metric(t('drawer.m.events'), nf(evs)), metric(t('drawer.m.days'), days), metric(t('drawer.m.hosts'), nf((d.hosts || []).length)), metric(t('drawer.m.bans'), nf(nbans), { hint: t('drawer.m.bans'), help: 'cat.ban' })));
var tstep = (d.timeline && d.timeline.step) || 3600, all = numbersOf(d.timeline), keep = Math.round(7 * 86400 / tstep), vals = all.slice(-keep);
if (vals.length > 1 && Math.max.apply(null, vals) > 0) {
var t0 = ((d.timeline && d.timeline.start) || 0) + (all.length - vals.length) * tstep;
@@ -845,10 +913,11 @@
if (Array.isArray(d.techniques) && d.techniques.length) {
var chips = h('div', 'chip-group');
d.techniques.slice(0, 8).forEach(function (x) { chips.appendChild(h('span', 'chip-mitre', (x.id ? x.id + ' ' : '') + (x.name || '') + (x.n ? ' \u00d7' + nf(x.n) : ''))); });
box.appendChild(h('section', 'drawer-sec', h('h3', null, t('drawer.techniques')), chips));
var th3 = h('h3', null, t('drawer.techniques')); help(th3, 'term.mitre');
box.appendChild(h('section', 'drawer-sec', th3, chips));
}
var kinds = Object.keys(d.counts || {}).filter(function (c) { return KNOWN_CATS.indexOf(c) >= 0 && c !== 'ok' && c !== 'ssh-ok'; });
if (kinds.length) { var cc = h('div', 'chip-group'); kinds.forEach(function (c) { cc.appendChild(h('span', 'chip', (c === 'ban' ? t('drawer.banEvents') : t('cat.' + c)) + ' ' + nf(d.counts[c]))); }); box.appendChild(h('section', 'drawer-sec', h('h3', null, t('drawer.categories')), cc)); }
if (kinds.length) { var cc = h('div', 'chip-group'); kinds.forEach(function (c) { cc.appendChild(h('span', 'chip', (c === 'ban' ? t('drawer.banEvents') : t('cat.' + c)) + ' ' + nf(d.counts[c]))); }); var ch3 = h('h3', null, t('drawer.categories')); help(ch3, 'term.categories'); box.appendChild(h('section', 'drawer-sec', ch3, cc)); }
if (Array.isArray(v.reasons) && v.reasons.length) {
var ul = h('ul'); v.reasons.slice(0, 3).forEach(function (r) { ul.appendChild(h('li', null, reasonText(r))); });
box.appendChild(h('section', 'drawer-sec', h('h3', null, t('drawer.reasons')), ul));
@@ -874,8 +943,203 @@
setTimeout(function () { if (n.parentNode) n.parentNode.removeChild(n); }, 2600);
}
// ---------------------------------------------------------------- charts library (own SVG, no dependencies)
var VIZ = ['--viz-1', '--viz-2', '--viz-3', '--viz-4', '--viz-5', '--viz-6', '--viz-7', '--viz-8'];
function vizColor(i, colors) { return 'var(' + ((colors && colors[i % colors.length]) || VIZ[i % VIZ.length]) + ')'; }
// run fn(width) now and whenever the box is resized
function watch(node, fn) {
if (!window.ResizeObserver) { fn(node.clientWidth || 320); return; }
var last = 0;
new ResizeObserver(function (es) { var w = Math.round(es[0].contentRect.width); if (w > 0 && w !== last) { last = w; fn(w); } }).observe(node);
}
// screen-reader alternative: a real table with the same numbers
function srTable(caption, head, rows) {
return h('table', 'sr-only', h('caption', null, caption || ''), h('thead', null, h('tr', null, head.map(function (x) { return el('th', { scope: 'col' }, x); }))),
h('tbody', null, rows.map(function (r) { return h('tr', null, r.map(function (c) { return h('td', null, String(c)); })); })));
}
function sumOf(a) { var s = 0; a.forEach(function (x) { s += x; }); return s; }
function legendList(items, colors, fmt, onHover) {
var ul = h('ul', 'vz-legend');
items.forEach(function (d, i) {
var li = h('li', null, h('span', 'sw'), h('span', 'vz-l', d.label), h('span', 'vz-v num', fmt(d)));
li.firstChild.style.background = vizColor(i, colors);
if (onHover) { li.addEventListener('mouseenter', function () { onHover(i); }); li.addEventListener('mouseleave', function () { onHover(-1); }); }
ul.appendChild(li);
});
return ul;
}
// donut(data [{key,label,value}], {title, colors:[token], centerLabel, format})
function donut(data, o) {
o = o || {};
data = (data || []).filter(function (x) { return x && x.value > 0; });
var total = sumOf(data.map(function (x) { return x.value; })), fmt = o.format || nf;
if (!total) return empty(t('charts.empty'));
var R = 70, C = 2 * Math.PI * R, acc = 0, segs = [];
var svg = svgEl('svg', { viewBox: '0 0 200 200', 'class': 'vz-donut', role: 'img', 'aria-label': o.title || '' });
var cv = svgEl('text', { x: 100, y: 102, 'text-anchor': 'middle', 'class': 'vz-c-v' }), cl = svgEl('text', { x: 100, y: 124, 'text-anchor': 'middle', 'class': 'vz-c-l' });
function center(i) {
if (i < 0) { cv.textContent = fmt(total); cl.textContent = o.centerLabel || t('charts.total'); return; }
cv.textContent = pct(data[i].value, total); cl.textContent = data[i].label;
}
data.forEach(function (d, i) {
var len = d.value / total * C, vis = Math.max(0.5, len - (data.length > 1 ? 1.5 : 0));
var c = svgEl('circle', { cx: 100, cy: 100, r: R, fill: 'none', 'stroke-width': 26, 'stroke-dasharray': vis + ' ' + (C - vis), 'stroke-dashoffset': -acc, transform: 'rotate(-90 100 100)', 'class': 'vz-seg', tabindex: 0, 'aria-label': d.label + ': ' + fmt(d.value) + ' (' + pct(d.value, total) + ')' });
c.style.stroke = vizColor(i, o.colors);
c.addEventListener('mouseenter', function () { center(i); }); c.addEventListener('focus', function () { center(i); });
c.addEventListener('mouseleave', function () { center(-1); }); c.addEventListener('blur', function () { center(-1); });
segs.push(c); svg.appendChild(c); acc += len;
});
svg.appendChild(cv); svg.appendChild(cl); center(-1);
var legend = legendList(data, o.colors, function (d) { return fmt(d.value) + ' · ' + pct(d.value, total); }, function (i) { center(i); segs.forEach(function (s, k) { s.classList.toggle('dim', i >= 0 && k !== i); }); });
return h('div', 'vz vz-donut-wrap', h('div', 'vz-donut-svg', svg), legend, srTable(o.title, [t('charts.item'), t('charts.value')], data.map(function (d) { return [d.label, fmt(d.value) + ' (' + pct(d.value, total) + ')']; })));
}
// radar(axes [{key,label}], series [{label, values[]}], {max, format, colors})
function radar(axes, series, o) {
o = o || {};
var n = axes.length;
series = (series || []).filter(function (s) { return s && s.values && s.values.length; });
var mx = o.max || Math.max.apply(null, [0].concat.apply([], series.map(function (s) { return s.values; })));
if (n < 3 || !series.length || !(mx > 0)) return empty(t('charts.empty'));
var fmt = o.format || nf, W = 360, H = 290, cx = 180, cy = 145, R = 82;
var svg = svgEl('svg', { viewBox: '0 0 ' + W + ' ' + H, 'class': 'vz-radar', role: 'img', 'aria-label': o.title || '' });
function pt(i, f) { var a = -Math.PI / 2 + i * 2 * Math.PI / n; return [cx + Math.cos(a) * R * f, cy + Math.sin(a) * R * f, Math.cos(a), Math.sin(a)]; }
[.25, .5, .75, 1].forEach(function (f) {
svg.appendChild(svgEl('polygon', { points: axes.map(function (_, i) { var p = pt(i, f); return p[0].toFixed(1) + ',' + p[1].toFixed(1); }).join(' '), 'class': 'vz-ring' }));
});
var rl = svgEl('text', { x: cx + 4, y: cy - R + 12, 'class': 'axis' }); rl.textContent = fmt(mx); svg.appendChild(rl);
axes.forEach(function (a, i) {
var p = pt(i, 1), q = pt(i, 1.14);
svg.appendChild(svgEl('line', { x1: cx, y1: cy, x2: p[0], y2: p[1], 'class': 'gridline' }));
var tx = svgEl('text', { x: q[0], y: q[1] + 4, 'text-anchor': q[2] > .3 ? 'start' : q[2] < -.3 ? 'end' : 'middle', 'class': 'vz-axl' });
tx.textContent = a.label; svg.appendChild(tx);
});
series.forEach(function (s, k) {
var col = vizColor(k, o.colors);
var poly = svgEl('polygon', { points: axes.map(function (_, i) { var p = pt(i, Math.min(1, (s.values[i] || 0) / mx)); return p[0].toFixed(1) + ',' + p[1].toFixed(1); }).join(' '), 'class': 'vz-rs' });
poly.style.stroke = col; poly.style.fill = col; svg.appendChild(poly);
axes.forEach(function (a, i) {
var p = pt(i, Math.min(1, (s.values[i] || 0) / mx)), c = svgEl('circle', { cx: p[0], cy: p[1], r: 3, 'class': 'vz-dot', tabindex: 0, 'aria-label': s.label + ', ' + a.label + ': ' + fmt(s.values[i] || 0) });
c.style.fill = col; var ti = svgEl('title', {}); ti.textContent = s.label + ' · ' + a.label + ': ' + fmt(s.values[i] || 0); c.appendChild(ti); svg.appendChild(c);
});
});
var legend = legendList(series.map(function (s) { return { label: s.label }; }), o.colors, function () { return ''; });
return h('div', 'vz vz-radar-wrap', svg, legend, srTable(o.title, [t('charts.item')].concat(series.map(function (s) { return s.label; })), axes.map(function (a, i) { return [a.label].concat(series.map(function (s) { return fmt(s.values[i] || 0); })); })));
}
// stackedArea(series [{key,label,values[]}], step seconds, {start, colors, title})
function stackedArea(series, step, o) {
o = o || {};
series = (series || []).filter(function (s) { return s && s.values && s.values.length; });
var n = series.length ? series[0].values.length : 0, tot = [], mx = 0, i;
if (n < 2) return empty(t('charts.empty'));
for (i = 0; i < n; i++) { var v = 0; series.forEach(function (s) { v += s.values[i] || 0; }); tot.push(v); if (v > mx) mx = v; }
var wrap = h('div', 'chart-wrap vz-area'), box = h('div', 'vz');
var colors = o.colors;
function draw(Wpx) {
clear(wrap);
var W = Math.max(280, Wpx), H = 220, L = 40, R = 6, Tp = 8, B = 22, top = niceMax(mx), ph = H - Tp - B, dx = (W - L - R) / (n - 1);
var svg = svgEl('svg', { viewBox: '0 0 ' + W + ' ' + H, role: 'img', 'aria-label': o.title || '' }), k;
for (k = 0; k <= 4; k++) {
var y = Tp + ph - ph * k / 4;
svg.appendChild(svgEl('line', { x1: L, x2: W - R, y1: y, y2: y, 'class': 'gridline' }));
var lb = svgEl('text', { x: L - 5, y: y + 3, 'text-anchor': 'end', 'class': 'axis' }); lb.textContent = top >= 10000 ? nfCompact(Math.round(top * k / 4)) : nf(Math.round(top * k / 4)); svg.appendChild(lb);
}
var nt = W < 520 ? 3 : 5, longSpan = step * n > 2 * 86400;
for (k = 0; k < nt; k++) {
var ix = Math.round((n - 1) * k / (nt - 1)), xl = svgEl('text', { x: L + dx * ix, y: H - 6, 'text-anchor': k === 0 ? 'start' : k === nt - 1 ? 'end' : 'middle', 'class': 'axis' });
xl.textContent = tickLabel((o.start || 0) + ix * step, longSpan); svg.appendChild(xl);
}
var base = []; for (i = 0; i < n; i++) base.push(0);
series.forEach(function (s, si) {
var up = [], down = [];
for (i = 0; i < n; i++) { var lo = base[i], hi = lo + (s.values[i] || 0); up.push((L + dx * i).toFixed(1) + ',' + (Tp + ph - hi / top * ph).toFixed(1)); down.unshift((L + dx * i).toFixed(1) + ',' + (Tp + ph - lo / top * ph).toFixed(1)); base[i] = hi; }
var p = svgEl('polygon', { points: up.concat(down).join(' '), 'class': 'vz-area-s' }); p.style.fill = vizColor(si, colors); svg.appendChild(p);
});
var tip = h('div', 'tip'); tip.hidden = true;
var guide = svgEl('line', { y1: Tp, y2: Tp + ph, 'class': 'vz-guide' }); guide.style.display = 'none'; svg.appendChild(guide);
var hit = svgEl('rect', { x: L, y: Tp, width: W - L - R, height: ph, fill: 'transparent' });
function at(ev) {
var r = svg.getBoundingClientRect(), px = (ev.clientX - r.left) * W / r.width, ix = Math.max(0, Math.min(n - 1, Math.round((px - L) / dx)));
clear(tip); tip.appendChild(h('strong', null, new Date(((o.start || 0) + ix * step) * 1000).toLocaleString(lang, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })));
series.forEach(function (s) { tip.appendChild(h('div', null, h('span', null, s.label), h('span', 'num', nf(s.values[ix] || 0)))); });
tip.hidden = false; tip.style.left = Math.max(0, Math.min(L + dx * ix + 12, W - 170)) + 'px'; tip.style.top = '4px';
guide.setAttribute('x1', L + dx * ix); guide.setAttribute('x2', L + dx * ix); guide.style.display = '';
}
hit.addEventListener('mousemove', at); hit.addEventListener('click', at);
hit.addEventListener('mouseleave', function () { tip.hidden = true; guide.style.display = 'none'; });
svg.appendChild(hit); wrap.appendChild(svg); wrap.appendChild(tip);
}
box.appendChild(wrap);
box.appendChild(legendList(series.map(function (s) { return { label: s.label }; }), colors, function (d, j) { return ''; }));
box.appendChild(srTable(o.title, [t('charts.item'), t('charts.value')], series.map(function (s) { return [s.label, nf(sumOf(s.values))]; })));
watch(wrap, draw);
return box;
}
// bars(rows [{key,label,value,color?,parts?:[{label,value,color?}]}], {horizontal (default true), stacked, format, colors})
function barChart(rows, o) {
o = o || {};
rows = (rows || []).filter(function (r) { return r; });
var fmt = o.format || nf, hor = o.horizontal !== false;
function rowTotal(r) { return r.parts ? sumOf(r.parts.map(function (p) { return p.value; })) : r.value; }
var mx = Math.max.apply(null, [0].concat(rows.map(rowTotal)));
if (!mx) return empty(t('charts.empty'));
var box = h('div', 'vz vz-bars' + (hor ? '' : ' vz-cols'));
rows.forEach(function (r, i) {
var tot = rowTotal(r), track = h('div', 'vz-track');
var parts = r.parts && o.stacked !== false ? r.parts : [{ label: r.label, value: r.value, color: r.color }];
parts.forEach(function (p, j) {
var seg = h('i'); seg.style[hor ? 'width' : 'height'] = Math.max(p.value ? 1 : 0, p.value / mx * 100) + '%';
seg.style.background = p.color ? 'var(' + p.color + ')' : vizColor(r.parts ? j : (r.color ? 0 : i), r.color ? [r.color] : o.colors);
seg.title = p.label + ': ' + fmt(p.value); track.appendChild(seg);
});
box.appendChild(h('div', 'vz-row', h('span', 'vz-l', r.label), track, h('span', 'vz-v num', fmt(tot))));
});
box.appendChild(srTable(o.title, [t('charts.item'), t('charts.value')], rows.map(function (r) { return [r.label, fmt(rowTotal(r))]; })));
return box;
}
// heatmap(matrix [row][col] numbers, xLabels, yLabels, {format, title}); cell colour from --seq-1..5
function heatmap(matrix, xl, yl, o) {
o = o || {};
var mx = 0; (matrix || []).forEach(function (r) { r.forEach(function (v) { if (v > mx) mx = v; }); });
if (!mx) return empty(t('charts.empty'));
var fmt = o.format || nf, wrap = h('div', 'vz vz-heat');
function draw(Wpx) {
clear(wrap);
var ny = matrix.length, nx = matrix[0].length, LW = 56, W = Math.max(240, Wpx), cw = (W - LW) / nx, ch = Math.min(26, Math.max(12, cw)), H = ny * ch + 22;
var svg = svgEl('svg', { viewBox: '0 0 ' + W + ' ' + H, role: 'img', 'aria-label': o.title || '' }), step = Math.ceil(26 / cw);
matrix.forEach(function (row, y) {
var yt = svgEl('text', { x: LW - 6, y: y * ch + ch / 2 + 4, 'text-anchor': 'end', 'class': 'axis' }); yt.textContent = yl[y]; svg.appendChild(yt);
row.forEach(function (v, x) {
var lvl = v ? Math.min(5, 1 + Math.floor(v / mx * 4.999)) : 0;
var r = svgEl('rect', { x: LW + x * cw + 1, y: y * ch + 1, width: Math.max(1, cw - 2), height: ch - 2, rx: 2, 'class': 'vz-cell s' + lvl, tabindex: 0, 'aria-label': yl[y] + ' ' + xl[x] + ': ' + fmt(v) });
var ti = svgEl('title', {}); ti.textContent = yl[y] + ' ' + xl[x] + ': ' + fmt(v); r.appendChild(ti); svg.appendChild(r);
});
});
for (var x = 0; x < nx; x += step) { var xt = svgEl('text', { x: LW + x * cw + cw / 2, y: ny * ch + 15, 'text-anchor': 'middle', 'class': 'axis' }); xt.textContent = xl[x]; svg.appendChild(xt); }
wrap.appendChild(svg);
}
var box = h('div', null, wrap, srTable(o.title, [''].concat(xl), matrix.map(function (r, y) { return [yl[y]].concat(r.map(fmt)); })));
watch(wrap, draw);
return box;
}
// gauge(value, max, thresholds [{at, tone: ok|warn|danger|info}], {label, format})
function gauge(value, max, thr, o) {
o = o || {};
max = max > 0 ? max : 1;
var fmt = o.format || nf, v = Math.max(0, Math.min(max, Number(value) || 0));
thr = thr && thr.length ? thr : [{ at: 0, tone: 'ok' }, { at: max * .5, tone: 'warn' }, { at: max * .8, tone: 'danger' }];
var tone = 'ok'; thr.forEach(function (x) { if (v >= x.at) tone = pick(['ok', 'warn', 'danger', 'info'], x.tone, 'ok'); });
var d = 'M20 100 A80 80 0 0 1 180 100';
var svg = svgEl('svg', { viewBox: '0 0 200 120', 'class': 'vz-gauge', role: 'img', 'aria-label': (o.label || '') + ' ' + fmt(v) + ' / ' + fmt(max) });
svg.appendChild(svgEl('path', { d: d, pathLength: 100, 'class': 'vz-g-bg' }));
svg.appendChild(svgEl('path', { d: d, pathLength: 100, 'class': 'vz-g-fg tone-' + tone, 'stroke-dasharray': (v / max * 100) + ' 100' }));
var tv = svgEl('text', { x: 100, y: 92, 'text-anchor': 'middle', 'class': 'vz-c-v' }); tv.textContent = fmt(v); svg.appendChild(tv);
var lo = svgEl('text', { x: 20, y: 116, 'text-anchor': 'middle', 'class': 'axis' }); lo.textContent = '0'; svg.appendChild(lo);
var hi = svgEl('text', { x: 180, y: 116, 'text-anchor': 'middle', 'class': 'axis' }); hi.textContent = fmt(max); svg.appendChild(hi);
return h('div', 'vz vz-gauge-wrap', svg, o.label ? h('div', 'vz-c-l', o.label) : null);
}
var charts = { donut: donut, radar: radar, stackedArea: stackedArea, bars: barChart, heatmap: heatmap, sparkline: sparkline, gauge: gauge };
// ---------------------------------------------------------------- page registry
var ORDER = ['overview', 'threats', 'geo', 'live', 'replay', 'traffic', 'ips', 'sources'];
var pages = {};
var current = null; // { page, el }
function registerPage(p) {
@@ -883,9 +1147,27 @@
pages[p.id] = p;
if (booted) { renderNav(); route(); }
}
// rail groups; ids not listed go to the end of their group (page.group, else Analyze)
var GROUPS = [
['monitor', ['overview', 'live', 'slo']],
['investigate', ['ips', 'sessions', 'campaigns', 'replay', 'search']],
['analyze', ['threats', 'mitre', 'geo', 'evolution', 'concentration', 'survival', 'traffic', 'errors', 'protocol']],
['operate', ['defense', 'sources', 'integrity']],
['reports', ['reports']]
];
function groupOf(p) {
if (p.group) for (var i = 0; i < GROUPS.length; i++) if (GROUPS[i][0] === p.group) return p.group;
for (var j = 0; j < GROUPS.length; j++) if (GROUPS[j][1].indexOf(p.id) >= 0) return GROUPS[j][0];
return 'analyze';
}
function orderedPages() {
var ids = Object.keys(pages);
return ORDER.filter(function (id) { return pages[id]; }).concat(ids.filter(function (id) { return ORDER.indexOf(id) < 0; }).sort()).map(function (id) { return pages[id]; }).filter(function (p) { return p.nav !== false && p.id !== 'ip'; });
var visible = Object.keys(pages).map(function (id) { return pages[id]; }).filter(function (p) { return p.nav !== false && p.id !== 'ip'; }), out = [];
GROUPS.forEach(function (g) {
var mine = visible.filter(function (p) { return groupOf(p) === g[0]; });
g[1].forEach(function (id) { mine.filter(function (p) { return p.id === id; }).forEach(function (p) { out.push(p); }); });
mine.filter(function (p) { return g[1].indexOf(p.id) < 0; }).sort(function (a, b) { return a.id < b.id ? -1 : 1; }).forEach(function (p) { out.push(p); });
});
return out;
}
function sp(n, node) { node.classList.add('span-' + n); return node; }
function grid12() { return h('div', 'grid-12'); }
@@ -937,7 +1219,7 @@
function bucketNote(step) { return step ? t('timeline.bucket', { n: nf(Math.max(1, Math.round(step / 60))) }) : ''; }
function timelinePanel() {
var wrap = h('div', 'chart-wrap'), legend = h('div', 'legend'), note = h('span', 'note bucket-note');
var node = panel({ title: t('timeline.title'), hint: t('timeline.hint'), variant: 'chart', loading: true }, wrap, legend);
var node = panel({ title: t('timeline.title'), hint: t('timeline.hint'), variant: 'chart', loading: true, help: 'metric.attacks_per_hour_24h' }, wrap, legend);
var data = null;
function renderLegend() {
clear(legend);
@@ -945,7 +1227,9 @@
var b = el('button', { type: 'button', 'aria-pressed': state.hidden[c] ? 'false' : 'true' }, h('span', 'sw b-' + c), h('span', null, t('cat.' + c)));
b.addEventListener('click', function () { state.hidden[c] = !state.hidden[c]; renderLegend(); draw(); });
legend.appendChild(b);
b.title = t('cat.' + c);
});
help(legend, 'term.categories');
legend.appendChild(note);
}
function draw() {
@@ -1003,7 +1287,7 @@
clear(box);
keys.forEach(function (k) {
var x = m[k];
box.appendChild(metric(metricLabel(k), metricValue(k, x.value), { delta: typeof x.delta_pct === 'number' ? x.delta_pct : undefined, goodUp: !!GOOD_UP[k], spark: Array.isArray(x.spark) ? x.spark : null, sub: metricSub(k, x) }));
box.appendChild(metric(metricLabel(k), metricValue(k, x.value), { delta: typeof x.delta_pct === 'number' ? x.delta_pct : undefined, goodUp: !!GOOD_UP[k], spark: Array.isArray(x.spark) ? x.spark : null, sub: metricSub(k, x), help: 'metric.' + k }));
});
return true;
}
@@ -1012,12 +1296,12 @@
var T = s.totals, hosts = s.hosts || [], on = hosts.filter(function (x) { return x.online; }).length;
var range = rangeLower();
clear(box);
box.appendChild(stat(t('kpi.requests'), nf(T.requests), hosts.length > 1 ? t('kpi.sub.hosts', { n: on, m: hosts.length }) : t('kpi.sub.range', { range: range })));
box.appendChild(stat(t('kpi.malicious'), nf(T.malicious), t('kpi.sub.malicious'), T.malicious > 0 ? 'warn' : 'neutral'));
box.appendChild(stat(t('kpi.hostile'), nf(T.hostile_ips), t('kpi.sub.share', { p: pct(T.hostile_ips, T.unique_ips), n: nf(T.unique_ips) }), T.hostile_ips > 0 ? 'danger' : 'neutral'));
box.appendChild(stat(t('kpi.suspicious'), nf(T.suspicious_ips), t('kpi.sub.share', { p: pct(T.suspicious_ips, T.unique_ips), n: nf(T.unique_ips) }), T.suspicious_ips > 0 ? 'warn' : 'neutral'));
box.appendChild(stat(t('kpi.bans'), nf(T.active_bans), t('kpi.sub.bans')));
box.appendChild(stat(t('kpi.ips'), nf(T.unique_ips), t('kpi.sub.range', { range: range })));
box.appendChild(stat(t('kpi.requests'), nf(T.requests), hosts.length > 1 ? t('kpi.sub.hosts', { n: on, m: hosts.length }) : t('kpi.sub.range', { range: range }), 'neutral', null, 'metric.requests'));
box.appendChild(stat(t('kpi.malicious'), nf(T.malicious), t('kpi.sub.malicious'), T.malicious > 0 ? 'warn' : 'neutral', null, 'metric.malicious'));
box.appendChild(stat(t('kpi.hostile'), nf(T.hostile_ips), t('kpi.sub.share', { p: pct(T.hostile_ips, T.unique_ips), n: nf(T.unique_ips) }), T.hostile_ips > 0 ? 'danger' : 'neutral', null, 'term.level'));
box.appendChild(stat(t('kpi.suspicious'), nf(T.suspicious_ips), t('kpi.sub.share', { p: pct(T.suspicious_ips, T.unique_ips), n: nf(T.unique_ips) }), T.suspicious_ips > 0 ? 'warn' : 'neutral', null, 'term.level'));
box.appendChild(stat(t('kpi.bans'), nf(T.active_bans), t('kpi.sub.bans'), 'neutral', null, 'cat.ban'));
box.appendChild(stat(t('kpi.ips'), nf(T.unique_ips), t('kpi.sub.range', { range: range }), 'neutral', null, 'metric.unique_ips'));
}
function overviewLead(s) {
var T = s.totals;
@@ -1043,17 +1327,19 @@
}
// ---------------------------------------------------------------- page: overview
var RADAR_CATS = ['notfound', 'scanner', 'bruteforce', 'exploit', 'ssh-fail', 'ssh-probe'];
var pOverview = corePage({
id: 'overview', icon: ICONS.overview, titleKey: 'nav.overview',
build: function (root) {
var v = {}, g = grid12();
v.lead = sp(12, h('div', 'skeleton lead-skel')); v.kpis = h('div', 'kpi-row'); skeletonCards(v.kpis, 6);
v.timeline = timelinePanel();
v.radar = panel({ title: t('ov.radar'), hint: t('ov.radar.hint'), loading: true, help: 'term.attack_profile' });
v.countries = panel({ title: t('ov.countries'), hint: t('ov.countries.hint'), variant: 'list', loading: true, footer: el('a', { href: '#/geo' }, t('ov.all')) });
v.topips = panel({ title: t('ov.topips'), hint: t('ov.topips.hint'), variant: 'list', loading: true, footer: el('a', { href: '#/ips' }, t('ov.all')) });
v.feedList = feedList(30);
v.feed = panel({ title: t('ov.feed'), hint: t('ov.feed.hint'), variant: 'list', footer: el('a', { href: '#/live' }, t('ov.all')) }, v.feedList.node);
g.appendChild(v.lead); g.appendChild(v.kpis); g.appendChild(sp(12, v.timeline.node));
g.appendChild(v.lead); g.appendChild(v.kpis); g.appendChild(sp(8, v.timeline.node)); g.appendChild(sp(4, v.radar));
g.appendChild(sp(4, v.countries)); g.appendChild(sp(4, v.topips)); g.appendChild(sp(4, v.feed));
root.appendChild(g);
v.offResize = onResize(function () { v.timeline.draw(); });
@@ -1061,9 +1347,21 @@
v.feedList.render();
return v;
},
load: function (c) { return getSummary(c).then(function (s) { return getMetrics(c).then(function (m) { return Object.assign({}, s, { metrics: m }); }); }); },
load: function (c) {
return getSummary(c).then(function (s) {
var hosts = (s.hosts || []).filter(function (x) { return x.online !== false; }).slice(0, 4);
var rq = c.from !== null && c.from !== undefined ? { from: c.from, to: c.to } : { range: c.range };
var jobs = hosts.length > 1 ? hosts.map(function (x) { return api('/api/v1/summary', Object.assign({ host: x.name }, rq)).then(function (r) { return { label: x.name, s: r }; }, function () { return null; }); }) : [Promise.resolve({ label: (hosts[0] && hosts[0].name) || t('host.all'), s: s })];
return Promise.all(jobs).then(function (rs) { return getMetrics(c).then(function (m) { return Object.assign({}, s, { metrics: m, radar: rs.filter(Boolean) }); }); });
});
},
render: function (v, s) {
clear(v.lead); v.lead.classList.remove('skeleton', 'lead-skel'); v.lead.appendChild(overviewLead(s));
ready(v.radar); clear(v.radar.body);
v.radar.body.appendChild(charts.radar(RADAR_CATS.map(function (c) { return { key: c, label: catShort(c) }; }), (s.radar || []).map(function (r) {
var vals = RADAR_CATS.map(function (c) { var n = 0; ((r.s.timeline.series || {})[c] || []).forEach(function (x) { n += x; }); return n; }), tot = sumOf(vals) || 1;
return { label: r.label, values: vals.map(function (x) { return Math.round(x / tot * 1000) / 10; }) };
}), { title: t('ov.radar'), format: function (x) { return nf(x) + '%' } }));
kpiRow(s, v.kpis, s.metrics, 'overview');
v.timeline.set(s);
clear(v.countries.body); v.countries.body.appendChild(bars(s.countries, { label: function (r) { return countryLabel(r.key); } }));
@@ -1097,13 +1395,13 @@
v.lead = sp(12, h('div', 'skeleton lead-skel')); v.kpis = h('div', 'kpi-row'); skeletonCards(v.kpis, 6); v.mon = sp(12, h('p', 'note'));
v.timeline = timelinePanel();
v.mapbox = mapBox();
v.map = panel({ title: t('map.attacks'), hint: t('map.attacks.hint'), variant: 'map', loading: true }, v.mapbox);
v.map = panel({ title: t('map.attacks'), hint: t('map.attacks.hint'), variant: 'map', loading: true, help: 'term.categories' }, v.mapbox);
v.tbl = ipTable(false);
v.ips = panel({ title: t('ips.title'), hint: t('ips.hint'), actions: el('a', { class: 'btn', href: '#/ips' }, t('ov.all')) }, v.tbl.node);
v.ips = panel({ title: t('ips.title'), hint: t('ips.hint'), help: 'term.score', actions: el('a', { class: 'btn', href: '#/ips' }, t('ov.all')) }, v.tbl.node);
v.feedList = feedList(100);
v.feed = panel({ title: t('feed.title'), variant: 'list', footer: el('a', { href: '#/live' }, t('ov.all')) }, v.feedList.node);
v.paths = panel({ title: t('top.paths'), variant: 'list', loading: true }); v.domains = panel({ title: t('top.domains'), variant: 'list', loading: true });
v.uas = panel({ title: t('top.uas'), variant: 'list', loading: true }); v.users = panel({ title: t('top.users'), variant: 'list', loading: true });
v.paths = panel({ title: t('top.paths'), variant: 'list', loading: true, help: 'cat.scanner' }); v.domains = panel({ title: t('top.domains'), variant: 'list', loading: true, help: 'metric.requests' });
v.uas = panel({ title: t('top.uas'), variant: 'list', loading: true, help: 'term.family' }); v.users = panel({ title: t('top.users'), variant: 'list', loading: true, help: 'cat.ssh-fail' });
g.appendChild(v.lead); g.appendChild(v.kpis); g.appendChild(v.mon); g.appendChild(sp(12, v.timeline.node)); g.appendChild(sp(8, v.map)); g.appendChild(sp(4, v.feed));
g.appendChild(sp(12, v.ips));
[v.paths, v.domains, v.uas, v.users].forEach(function (x) { g.appendChild(sp(3, x)); });
@@ -1149,24 +1447,31 @@
sel.value = state.domain;
if (sel.value !== state.domain) sel.value = 'all';
}
var CLIENT_COLORS = { desktop: '--viz-1', mobile: '--viz-6', tablet: '--viz-5', bot: '--viz-3', tool: '--viz-7', unknown: '--viz-8', misc: '--viz-2' };
var CLIENT_ORDER = ['desktop', 'mobile', 'tablet', 'bot', 'tool', 'unknown', 'misc'];
var STATUS_TOKENS = ['--ok', '--info', '--warn', '--danger'];
var pTraffic = corePage({
id: 'traffic', icon: ICONS.traffic, titleKey: 'nav.traffic', domain: true,
build: function (root) {
var v = {}, g = grid12();
v.lead = sp(12, h('div', 'skeleton lead-skel')); v.kpis = h('div', 'kpi-row'); skeletonCards(v.kpis, 6);
v.wrap = h('div', 'chart-wrap'); v.note = h('span', 'note bucket-note');
v.legend = h('div', 'legend', h('span', 'li', h('span', 'sw b-treq'), t('traffic.requests')), h('span', 'li', h('span', 'sw b-tpages'), t('traffic.pages')), v.note);
v.timeline = panel({ title: t('traffic.timeline'), hint: t('traffic.timeline.hint'), variant: 'chart', loading: true }, v.wrap, v.legend);
v.wrap = h('div'); v.note = h('span', 'note bucket-note');
v.timeline = panel({ title: t('traffic.timeline'), hint: t('traffic.area.hint'), variant: 'chart', loading: true, help: 'metric.pages' }, v.wrap, h('div', 'legend', v.note));
v.mapbox = mapBox();
v.map = panel({ title: t('map.visitors'), hint: t('map.visitors.hint'), variant: 'map', loading: true }, v.mapbox);
var ids = [['pages', 'traffic.topPages'], ['refs', 'traffic.referrers'], ['cities', 'traffic.cities'], ['browsers', 'traffic.browsers'], ['oses', 'traffic.oses'], ['devices', 'traffic.devices'], ['bots', 'traffic.bots'], ['status', 'traffic.status']];
var ids = [['pages', 'traffic.topPages'], ['refs', 'traffic.referrers'], ['cities', 'traffic.cities'], ['bots', 'traffic.bots']];
ids.forEach(function (p) { v[p[0]] = panel({ title: t(p[1]), variant: 'list', loading: true }); });
v.client = panel({ title: t('traffic.client'), hint: t('traffic.client.hint'), loading: true, help: 'term.client_type' });
v.browsers = panel({ title: t('traffic.browsers'), hint: t('traffic.browsers.hint'), loading: true });
v.oses = panel({ title: t('traffic.oses'), hint: t('traffic.oses.hint'), loading: true });
v.status = panel({ title: t('traffic.status'), hint: t('traffic.status.hint'), loading: true, help: 'term.status_class' });
v.privacy = sp(12, h('p', 'note', t('traffic.privacy')));
g.appendChild(v.lead); g.appendChild(v.kpis); g.appendChild(sp(12, v.timeline)); g.appendChild(sp(12, v.map));
['pages', 'refs', 'cities', 'browsers', 'oses', 'devices'].forEach(function (k) { g.appendChild(sp(4, v[k])); });
g.appendChild(sp(6, v.bots)); g.appendChild(sp(6, v.status)); g.appendChild(v.privacy);
g.appendChild(sp(4, v.client)); g.appendChild(sp(4, v.browsers)); g.appendChild(sp(4, v.oses));
g.appendChild(sp(6, v.status)); g.appendChild(sp(6, v.bots));
['pages', 'refs', 'cities'].forEach(function (k) { g.appendChild(sp(4, v[k])); });
g.appendChild(v.privacy);
root.appendChild(g);
v.offResize = onResize(function () { if (v.data) drawTraffic(v, v.data); });
return v;
},
load: function (c) { return api('/api/v1/traffic', Object.assign({ host: c.host, domain: c.domain }, c.from !== null && c.from !== undefined ? { from: c.from, to: c.to } : { range: c.range })); },
@@ -1179,31 +1484,35 @@
? lead(t('tr.lead.some', { n: nf(d.visitors), p: nf(d.pages) }), t('tr.lead.body', { r: nf(d.requests), b: nf(d.bots), a: nf(Math.round(d.p50_ms)), c: nf(Math.round(d.p95_ms)) }), 'ok')
: lead(t('tr.lead.none'), t('tr.lead.noneBody'), 'neutral'));
clear(v.kpis);
v.kpis.appendChild(stat(t('traffic.requests'), nf(d.requests), t('traffic.sub.requests')));
v.kpis.appendChild(stat(t('traffic.pages'), nf(d.pages), t('traffic.sub.pages', { n: nf(d.requests) })));
v.kpis.appendChild(stat(t('traffic.visitors'), nf(d.visitors), t('traffic.sub.visitors')));
v.kpis.appendChild(stat(t('traffic.bytes'), fmtBytes(d.bytes), t('kpi.sub.range', { range: rangeLower() })));
v.kpis.appendChild(stat(t('traffic.latency'), Math.round(d.p50_ms) + ' / ' + Math.round(d.p95_ms) + ' ms', t('kpi.sub.range', { range: rangeLower() })));
v.kpis.appendChild(stat(t('traffic.bots'), nf(d.bots), t('traffic.sub.bots', { n: nf(d.requests) })));
ready(v.timeline); ready(v.map);
drawTraffic(v, d);
var rg = rangeLower();
v.kpis.appendChild(stat(t('traffic.requests'), nf(d.requests), t('traffic.sub.requests'), 'neutral', null, 'metric.requests'));
v.kpis.appendChild(stat(t('traffic.pages'), nf(d.pages), t('traffic.sub.pages', { n: nf(d.requests) }), 'neutral', null, 'metric.pages'));
v.kpis.appendChild(stat(t('traffic.visitors'), nf(d.visitors), t('traffic.sub.visitors'), 'neutral', null, 'metric.visitors'));
v.kpis.appendChild(stat(t('traffic.bytes'), fmtBytes(d.bytes), t('kpi.sub.range', { range: rg }), 'neutral', null, 'metric.bytes'));
v.kpis.appendChild(stat(t('traffic.latency'), Math.round(d.p50_ms) + ' / ' + Math.round(d.p95_ms), 'ms \u00b7 ' + t('kpi.sub.range', { range: rg }), 'neutral', null, 'metric.latency'));
v.kpis.appendChild(stat(t('traffic.bots'), nf(d.bots), t('traffic.sub.bots', { n: nf(d.requests) }), 'neutral', null, 'metric.bots'));
// time series: page views and the rest of the requests
var tl = d.timeline, pg = tl.pages || [], other = (tl.req || []).map(function (x, i) { return Math.max(0, x - (pg[i] || 0)); });
ready(v.timeline); clear(v.wrap);
v.note.textContent = bucketNote(tl.step);
v.wrap.appendChild(charts.stackedArea([{ key: 'pages', label: t('traffic.pages'), values: pg }, { key: 'other', label: t('traffic.otherReq'), values: other }], tl.step, { start: tl.start, colors: ['--accent', '--viz-8'], title: t('traffic.timeline') }));
ready(v.map);
renderMap(v.mapbox, d.countries, true, t('map.visitors'));
function fill(key, rows, mono) { clear(v[key].body); v[key].body.appendChild(bars(rows, { mono: mono })); }
fill('pages', d.top_pages, true); fill('refs', d.referrers, true); fill('cities', d.cities, false);
fill('browsers', d.browsers, false); fill('oses', d.oses, false);
fill('devices', (d.devices || []).map(function (x) { return { key: t('device.' + pick(['desktop', 'mobile', 'tablet', 'bot', 'tool'], x.key, 'unknown')), n: x.n }; }), false);
fill('bots', d.bot_names, false);
fill('status', ['2xx', '3xx', '4xx', '5xx'].map(function (k, i) { return { key: k, n: d.status[i] }; }).filter(function (x) { return x.n > 0; }), true);
fill('pages', d.top_pages, true); fill('refs', d.referrers, true); fill('cities', d.cities, false); fill('bots', d.bot_names, false);
// client type: devices as reported, plus bots when the devices list has no bot entry
var dev = (d.devices || []).map(function (x) { return { k: pick(CLIENT_ORDER, x.key, 'misc'), n: x.n }; });
dev.sort(function (a, b) { return CLIENT_ORDER.indexOf(a.k) - CLIENT_ORDER.indexOf(b.k); });
function donutOf(box, data, colors, title) { ready(box); clear(box.body); box.body.appendChild(charts.donut(data, { title: title, colors: colors })); }
donutOf(v.client, dev.map(function (x) { return { key: x.k, label: t('device.' + x.k), value: x.n }; }), dev.map(function (x) { return CLIENT_COLORS[x.k]; }), t('traffic.client'));
donutOf(v.browsers, (d.browsers || []).map(function (x) { return { key: x.key, label: x.key, value: x.n }; }), null, t('traffic.browsers'));
donutOf(v.oses, (d.oses || []).map(function (x) { return { key: x.key, label: x.key, value: x.n }; }), null, t('traffic.oses'));
var cls = ['2xx', '3xx', '4xx', '5xx'];
ready(v.status); clear(v.status.body);
v.status.body.appendChild(charts.bars(cls.map(function (k, i) { return { key: k, label: t('traffic.status.' + k), value: (d.status || [])[i] || 0, color: STATUS_TOKENS[i] }; }), { title: t('traffic.status') }));
},
dispose: function (v) { v.offResize(); }
dispose: function () { }
});
function drawTraffic(v, d) {
var tl = d.timeline;
v.note.textContent = bucketNote(tl.step);
chart(v.wrap, { start: tl.start, step: tl.step, stacked: false, aria: t('traffic.timeline'), layers: [
{ cls: 'b-treq', label: t('traffic.requests'), vals: tl.req }, { cls: 'b-tpages', label: t('traffic.pages'), vals: tl.pages }
] });
}
// ---------------------------------------------------------------- page: ips
var pIPs = corePage({
@@ -1213,7 +1522,7 @@
v.lead = sp(12, h('div'));
v.tbl = ipTable(true);
v.tbl.onTotal(function (n) { setSliceNote(pl('slice.ips', n, { n: nf(n) })); });
v.ips = panel({ title: t('ips.title'), hint: t('ips.hint') }, v.tbl.node);
v.ips = panel({ title: t('ips.title'), hint: t('ips.hint'), help: 'term.score' }, v.tbl.node);
g.appendChild(v.lead); g.appendChild(sp(12, v.ips)); root.appendChild(g);
return v;
},
@@ -1242,7 +1551,7 @@
var copy = el('button', { type: 'button', class: 'btn primary' }, t('blocklist.copy'));
var dlTxt = el('a', { class: 'btn', href: '/api/v1/blocklist.txt' }, t('blocklist.download'));
var dlJson = el('a', { class: 'btn', href: '/api/v1/blocklist.json' }, t('blocklist.downloadJson'));
var node = panel({ title: t('blocklist.title'), hint: t('blocklist.help') },
var node = panel({ title: t('blocklist.title'), hint: t('blocklist.help'), help: 'term.blocklist' },
h('div', 'toolbar', h('label', 'check', h('span', null, t('blocklist.minScore')), minScore), fam, copy, dlTxt, dlJson), count, msg);
var timer = 0, alive = true;
function query(extra) {
@@ -1294,11 +1603,11 @@
var v = {}, g = grid12();
v.lead = sp(12, h('div'));
v.hostsBox = h('div', 'hosts');
v.hosts = panel({ title: t('hosts.title'), hint: t('hosts.hint') }, v.hostsBox);
v.hosts = panel({ title: t('hosts.title'), hint: t('hosts.hint'), help: 'term.peer' }, v.hostsBox);
var thead = h('thead', null, h('tr', null, ['col.host', 'col.source', 'col.state', 'col.lines', 'col.malformed', 'col.lastEvent'].map(function (k) { return el('th', { scope: 'col' }, t(k)); })));
v.tbody = h('tbody');
v.srcEmpty = h('div');
v.sources = panel({ title: t('sources.title'), hint: t('sources.hint') }, h('div', 'tbl-wrap', h('table', 'stack tbl-cards', thead, v.tbody)), v.srcEmpty);
v.sources = panel({ title: t('sources.title'), hint: t('sources.hint'), help: 'term.integrity_gap' }, h('div', 'tbl-wrap', h('table', 'stack tbl-cards', thead, v.tbody)), v.srcEmpty);
v.geoBox = h('div');
v.geo = panel({ title: t('src.geo.title'), hint: t('src.geo.hint') }, v.geoBox);
v.bl = blocklistPanel();
@@ -1504,8 +1813,10 @@
function renderNav() {
var list = orderedPages(), nav = $('#nav'), bar = $('#tabbar'), more = $('#more'), cur = navId();
clear(nav); clear(bar); clear(more);
var lastGroup = null;
list.forEach(function (p) {
var label = t(p.titleKey);
var label = t(p.titleKey), gr = groupOf(p);
if (gr !== lastGroup) { nav.appendChild(h('div', 'nav-group', t('nav.group.' + gr))); lastGroup = gr; }
var a = el('a', { class: 'nav-item', href: hrefFor(p.id), title: label }, h('span', 'nav-ico', iconNode(p.icon)), h('span', 'nav-label', label));
if (cur === p.id) a.setAttribute('aria-current', 'page');
nav.appendChild(a);
@@ -1522,7 +1833,10 @@
if (rest.some(function (p) { return p.id === cur; })) mb.setAttribute('aria-current', 'page');
mb.addEventListener('click', function () { setMore(more.hidden); });
bar.appendChild(mb);
var rg = null;
rest.forEach(function (p) {
var g2 = groupOf(p);
if (g2 !== rg) { more.appendChild(h('div', 'nav-group', t('nav.group.' + g2))); rg = g2; }
var a = el('a', { href: hrefFor(p.id) }, h('span', 'nav-ico', iconNode(p.icon)), h('span', null, t(p.titleKey)));
if (cur === p.id) a.setAttribute('aria-current', 'page');
more.appendChild(a);
@@ -1639,7 +1953,7 @@
});
$('#scrim').addEventListener('click', closeDetail);
document.addEventListener('keydown', function (e) {
if (e.key === 'Escape') { closeDetail(); setMore(false); closeRangePicker(true); return; }
if (e.key === 'Escape') { hideHelp(); closeDetail(); setMore(false); closeRangePicker(true); return; }
var box = $('#detail');
if (e.key === 'Tab' && !box.hidden) {
var f = Array.prototype.slice.call(box.querySelectorAll('button, a[href], [tabindex="0"]'));
@@ -1660,6 +1974,7 @@
var more = $('#more');
if (!more.hidden && !more.contains(e.target) && !$('#tabbar').contains(e.target)) setMore(false);
if (rp.open && !$('#range-picker').contains(e.target)) closeRangePicker(false);
if (helpPinned) hideHelp();
});
window.addEventListener('hashchange', route);
window.matchMedia && matchMedia('(prefers-color-scheme: light)').addEventListener && matchMedia('(prefers-color-scheme: light)').addEventListener('change', notifyPage);
@@ -1680,8 +1995,33 @@
rangeParams: rangeParams, rangeLabel: rangeLabel, href: hrefFor, toast: toast,
fmt: { num: nf, pct: pct, ago: ago, bytes: fmtBytes, flag: flag, country: countryName, clock: clock, date: dateTime },
world: world, el: el, css: cssVar, setSliceNote: setSliceNote,
charts: charts, help: help, glossary: glossary,
ui: { panel: panel, stat: stat, metric: metric, lead: lead, empty: empty, badge: badge, bars: bars, chart: chart, sparkline: sparkline }
};
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot); else setTimeout(boot, 0);
// page scripts are listed in /pages.json ({"pages":[{"name":"geo","css":true}, ...]}); only files that exist
// are listed, so nothing 404s. Each name loads /<name>.js (and /<name>.css) in order, then the app boots.
var DEFAULT_PAGES = [{ name: 'geo', css: true }, { name: 'live', css: true }, { name: 'ip', css: true }, { name: 'replay', css: true }];
function loadScript(src) {
return new Promise(function (ok) {
var sc = document.createElement('script');
sc.src = src; sc.async = false;
sc.onload = ok; sc.onerror = function () { console.warn('page script failed: ' + src); ok(); };
document.head.appendChild(sc);
});
}
function loadPages() {
return fetch('/pages.json', { credentials: 'same-origin' }).then(function (r) { return r.ok ? r.json() : null; }, function () { return null; }).then(function (m) {
var list = m && Array.isArray(m.pages) ? m.pages : DEFAULT_PAGES, chain = Promise.resolve();
list.forEach(function (p) {
var name = p && String(p.name || '');
if (!/^[a-z][a-z0-9-]*$/.test(name)) return;
if (p.css) { var l = document.createElement('link'); l.rel = 'stylesheet'; l.href = '/' + name + '.css'; document.head.appendChild(l); }
chain = chain.then(function () { return loadScript('/' + name + '.js'); });
});
return chain;
});
}
function start() { loadPages().then(boot, boot); }
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start); else setTimeout(start, 0);
})();
+38
View File
@@ -0,0 +1,38 @@
/* Urutau - CAMPAIGNS page. Selectors prefixed cp-. */
.cp { display: flex; flex-direction: column; gap: var(--s-3, 12px); min-width: 0; }
.cp-cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 320px), 1fr)); gap: 12px; }
.cp-card { display: flex; flex-direction: column; gap: 8px; min-width: 0; padding: 12px; border: 1px solid var(--line); border-radius: var(--radius, 10px); background: var(--surface-raised); }
.cp-card.cp-wide { background: var(--surface-panel); }
.cp-card header { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 4px 10px; align-items: baseline; }
.cp-id { font-weight: 650; color: var(--accent); text-decoration: none; }
.cp-win { font-size: .75rem; color: var(--ink-muted); }
.cp-stats { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 6px; }
.cp-st { display: flex; flex-direction: column; min-width: 0; }
.cp-st b { font-size: 1.125rem; color: var(--heading, var(--ink)); }
.cp-sk { font-size: .6875rem; text-transform: uppercase; letter-spacing: .06em; color: var(--ink-muted); }
.cp-sig { margin: 0; display: flex; flex-direction: column; gap: 3px; min-width: 0; }
.cp-chips { display: flex; flex-wrap: wrap; gap: 4px; min-width: 0; }
.cp-chip { max-width: 100%; padding: 1px 8px; border: 1px solid var(--line); border-radius: 999px; background: var(--accent-soft); font-size: .75rem; font-family: var(--font-mono, monospace); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.cp-more { font-family: inherit; color: var(--ink-muted); }
.cp-card footer { display: flex; flex-wrap: wrap; gap: 8px; margin-top: auto; }
.cp-card footer .btn { min-height: 34px; }
.cp-ip { color: var(--accent); text-decoration: none; overflow-wrap: anywhere; }
.cp-back { align-self: flex-start; }
.cp-gwrap { overflow: hidden; }
.cp-gantt { width: 100%; height: auto; display: block; }
.cp-gl { stroke: var(--line); stroke-width: 1; }
.cp-gt { fill: var(--ink-muted); font-size: 11px; font-family: var(--font-mono, monospace); }
.cp-bar { fill: var(--accent); }
.cp-b-recon { fill: var(--info); } .cp-b-probe { fill: var(--warn); } .cp-b-exploit { fill: var(--danger); }
.cp-b-access { fill: #c026d3; } .cp-b-banned { fill: var(--ink-faint); }
.cp-badge { display: inline-block; padding: 1px 9px; border-radius: 999px; font-size: .75rem; font-weight: 600; color: #04121c; }
.cp-s-recon { background: var(--info); } .cp-s-probe { background: var(--warn); } .cp-s-exploit { background: var(--danger); }
.cp-s-access { background: #c026d3; } .cp-s-banned { background: var(--ink-faint); }
.cp-matrix { display: grid; grid-template-columns: repeat(calc(var(--n) + 1), minmax(0, 1fr)); gap: 2px; max-width: 640px; }
.cp-mh { font-size: .625rem; font-family: var(--font-mono, monospace); color: var(--ink-muted); overflow: hidden; text-overflow: ellipsis; align-self: center; }
.cp-mc { display: flex; align-items: center; justify-content: center; aspect-ratio: 1; min-height: 20px; border-radius: 3px; font-size: .625rem; color: var(--ink); background: var(--surface-sunken); }
.cp-lv1 { background: color-mix(in srgb, var(--accent) 22%, var(--surface-sunken)); }
.cp-lv2 { background: color-mix(in srgb, var(--accent) 42%, var(--surface-sunken)); }
.cp-lv3 { background: color-mix(in srgb, var(--accent) 65%, var(--surface-sunken)); }
.cp-lv4 { background: var(--accent); color: var(--on-accent); }
@media (max-width: 640px) { .cp-stats { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
+263
View File
@@ -0,0 +1,263 @@
/* Urutau - CAMPAIGNS page: sets of addresses doing the same thing. List (cards, activity
Gantt, similarity matrix) at #/campaigns and detail at #/campaigns/<id>.
Data: /api/v1/campaigns and /api/v1/campaigns/{id}. Hostile data: textContent only. */
(function () {
'use strict';
var NS = 'http://www.w3.org/2000/svg';
var STAGES = ['recon', 'probe', 'exploit', 'access', 'banned'];
var ICON = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="5" r="2.5"/><circle cx="5" cy="18" r="2.5"/><circle cx="19" cy="18" r="2.5"/><path d="M11 7.5L6 15.5M13 7.5l5 8M7.5 18h9"/></svg>';
var ID_OK = /^[A-Za-z0-9_-]{1,64}$/;
function boot() {
var U = window.Urutau;
if (!U || !U.registerPage) return false;
var t = U.t, nf = U.fmt.num;
function h(tag, a) { if (typeof a === 'string') a = { class: a }; return U.el.apply(null, [tag, a].concat([].slice.call(arguments, 2))); }
U.registerI18n({
en: {
'cp.title': 'Campaigns',
'cp.lead.one': '{n} campaign groups {k} IPs',
'cp.lead.other': '{n} campaigns group {k} IPs',
'cp.lead.body': 'Addresses that asked for the same things {range}.',
'cp.lead.empty': 'No campaign in this slice',
'cp.lead.emptyBody': 'No set of at least three addresses behaved alike {range}.',
'cp.detail.lead': 'Campaign {id} groups {k} IPs',
'cp.cards': 'Campaigns',
'cp.ips': 'IPs',
'cp.asns': 'ASNs',
'cp.ccs': 'Countries',
'cp.sessions': 'Sessions',
'cp.window': 'Window',
'cp.techs': 'Techniques',
'cp.sig': 'Signature',
'cp.tool': 'Tool',
'cp.open': 'Open',
'cp.gantt': 'Activity',
'cp.gantt.hint': 'When each campaign was active.',
'cp.matrix': 'Similarity',
'cp.matrix.hint': 'Share of addresses two campaigns have in common.',
'cp.members': 'Members',
'cp.timeline': 'Timeline',
'cp.timeline.hint': 'Sessions of each member.',
'cp.replay': 'Replay campaign',
'cp.back': 'All campaigns',
'cp.c.ip': 'Address',
'cp.c.first': 'First seen',
'cp.c.last': 'Last seen',
'cp.c.stage': 'Stage',
'cp.c.sessions': 'Sessions',
'cp.truncated': 'The study was cut short; the list may be incomplete.',
'cp.err': 'Could not load the campaigns.',
'cp.retry': 'Try again',
'cp.unknown': 'Campaign not found',
'cp.unknownBody': 'It is not in this slice. Widen the period or go back to the list.',
'cp.stage.recon': 'Recon',
'cp.stage.probe': 'Probe',
'cp.stage.exploit': 'Exploit',
'cp.stage.access': 'Access',
'cp.stage.banned': 'Banned',
'cp.more': '+{n} more'
},
'pt-BR': {
'cp.title': 'Campanhas',
'cp.lead.one': '{n} campanha agrupa {k} IPs',
'cp.lead.other': '{n} campanhas agrupam {k} IPs',
'cp.lead.body': 'Endereços que pediram as mesmas coisas {range}.',
'cp.lead.empty': 'Nenhuma campanha neste recorte',
'cp.lead.emptyBody': 'Nenhum conjunto de três ou mais endereços agiu igual {range}.',
'cp.detail.lead': 'A campanha {id} agrupa {k} IPs',
'cp.cards': 'Campanhas',
'cp.ips': 'IPs',
'cp.asns': 'ASNs',
'cp.ccs': 'Países',
'cp.sessions': 'Sessões',
'cp.window': 'Janela',
'cp.techs': 'Técnicas',
'cp.sig': 'Assinatura',
'cp.tool': 'Ferramenta',
'cp.open': 'Abrir',
'cp.gantt': 'Atividade',
'cp.gantt.hint': 'Quando cada campanha esteve ativa.',
'cp.matrix': 'Semelhança',
'cp.matrix.hint': 'Fração de endereços que duas campanhas têm em comum.',
'cp.members': 'Membros',
'cp.timeline': 'Linha do tempo',
'cp.timeline.hint': 'Sessões de cada membro.',
'cp.replay': 'Reproduzir campanha',
'cp.back': 'Todas as campanhas',
'cp.c.ip': 'Endereço',
'cp.c.first': 'Primeira vez',
'cp.c.last': 'Última vez',
'cp.c.stage': 'Estágio',
'cp.c.sessions': 'Sessões',
'cp.truncated': 'O estudo foi interrompido; a lista pode estar incompleta.',
'cp.err': 'Não foi possível carregar as campanhas.',
'cp.retry': 'Tentar de novo',
'cp.unknown': 'Campanha não encontrada',
'cp.unknownBody': 'Ela não está neste recorte. Amplie o período ou volte à lista.',
'cp.stage.recon': 'Reconhecimento',
'cp.stage.probe': 'Sondagem',
'cp.stage.exploit': 'Exploração',
'cp.stage.access': 'Acesso',
'cp.stage.banned': 'Banido',
'cp.more': '+{n} mais'
}
});
function sec(v) { var n = Date.parse(v); return isFinite(n) ? Math.floor(n / 1000) : 0; }
function iso(s) { return new Date(s * 1000).toISOString(); }
function stg(s) { return STAGES.indexOf(s) >= 0 ? s : 'recon'; }
function short(id) { return String(id).slice(0, 12); }
function replayHref(c) {
return '#/replay?campaign=' + encodeURIComponent(c.id) + '&from=' + encodeURIComponent(iso(sec(c.first) - 300)) + '&to=' + encodeURIComponent(iso(sec(c.last) + 300));
}
function ipLink(ip) { return h('a', { class: 'mono cp-ip', href: '#/ip/' + encodeURIComponent(ip), text: ip }); }
function chips(list, max) {
var box = h('span', 'cp-chips');
(list || []).slice(0, max).forEach(function (x) { box.appendChild(h('span', { class: 'cp-chip', text: x })); });
if ((list || []).length > max) box.appendChild(h('span', { class: 'cp-chip cp-more', text: t('cp.more', { n: list.length - max }) }));
return box;
}
function svg(tag, a) { var n = document.createElementNS(NS, tag); Object.keys(a || {}).forEach(function (k) { n.setAttribute(k, String(a[k])); }); return n; }
// rows: [{label, segs: [{a, b, cls}]}], span: [min, max]; one SVG, rows 22 px high
function gantt(rows, a, b, aria) {
var W = 720, L = 130, R = 8, RH = 22, H = rows.length * RH + 22, span = Math.max(1, b - a);
var s = svg('svg', { viewBox: '0 0 ' + W + ' ' + H, role: 'img', 'aria-label': aria, class: 'cp-gantt' });
rows.forEach(function (r, i) {
var y = i * RH;
s.appendChild(svg('line', { x1: L, x2: W - R, y1: y + RH - 1, y2: y + RH - 1, class: 'cp-gl' }));
var lab = svg('text', { x: 0, y: y + 15, class: 'cp-gt' }); lab.textContent = r.label.length > 18 ? r.label.slice(0, 17) + '…' : r.label; s.appendChild(lab);
r.segs.forEach(function (g) {
var x = L + (g.a - a) / span * (W - L - R), w = Math.max(3, (g.b - g.a) / span * (W - L - R));
var rc = svg('rect', { x: x, y: y + 4, width: w, height: RH - 9, rx: 3, class: g.cls || 'cp-bar' });
var ti = svg('title'); ti.textContent = U.fmt.date(g.a) + ' → ' + U.fmt.date(g.b); rc.appendChild(ti);
s.appendChild(rc);
});
});
[0, 1].forEach(function (k) {
var x = svg('text', { x: k ? W - R : L, y: H - 6, 'text-anchor': k ? 'end' : 'start', class: 'cp-gt' }); x.textContent = U.fmt.date(k ? b : a); s.appendChild(x);
});
return h('div', 'cp-gwrap', s);
}
function jaccard(x, y) {
var m = {}, i = 0; x.forEach(function (v) { m[v] = 1; });
y.forEach(function (v) { if (m[v]) i++; });
var u = x.length + y.length - i; return u ? i / u : 0;
}
function matrix(cs) {
var list = cs.slice(0, 10), box = h('div', 'cp-matrix');
box.style.setProperty('--n', String(list.length));
box.appendChild(h('span', 'cp-mc'));
list.forEach(function (c) { box.appendChild(h('span', { class: 'cp-mh', text: short(c.id) })); });
list.forEach(function (a) {
box.appendChild(h('span', { class: 'cp-mh', text: short(a.id) }));
list.forEach(function (b) {
var j = jaccard(a.ips || [], b.ips || []), lv = j >= .8 ? 4 : j >= .5 ? 3 : j >= .25 ? 2 : j > 0 ? 1 : 0;
box.appendChild(h('span', { class: 'cp-mc cp-lv' + lv, title: short(a.id) + ' / ' + short(b.id) + ': ' + Math.round(j * 100) + '%', text: j > 0 ? String(Math.round(j * 100)) : '' }));
});
});
return box;
}
function stat(k, v) { return h('div', 'cp-st', h('span', { class: 'cp-sk', text: k }), h('b', { class: 'num', text: v })); }
var inst = null;
function Page(root, ctx) {
var self = this, seq = 0, alive = true, data = null, key = '';
this.ctx = ctx;
var wrap = h('div', 'cp');
root.appendChild(wrap);
function id() { var s = self.ctx.params && self.ctx.params.segments || []; return s[0] || ''; }
function load() {
var my = ++seq, cid = id(), path = cid ? '/api/v1/campaigns/' + encodeURIComponent(cid) : '/api/v1/campaigns';
if (cid && !ID_OK.test(cid)) { data = { missing: true }; paint(); return; }
U.api(path, Object.assign({ host: self.ctx.host }, U.rangeParams())).then(function (d) {
if (!alive || my !== seq) return; data = d; key = cid; paint();
}).catch(function (e) {
if (!alive || my !== seq) return;
if (e && e.status === 404 && cid) { data = { missing: true }; key = cid; paint(); return; }
if (data) return;
var b = h('button', { type: 'button', class: 'btn', text: t('cp.retry') });
b.addEventListener('click', load);
wrap.textContent = '';
wrap.appendChild(h('div', 'state-error', h('strong', { text: t('cp.err') }), b));
});
}
function paint() {
wrap.textContent = '';
if (!data) return;
if (id()) return detail();
var cs = data.campaigns || [], range = U.rangeLabel({ inline: true });
wrap.appendChild(cs.length ? U.ui.lead(U.pl('cp.lead', cs.length, { n: nf(data.total || cs.length), k: nf(data.ips_n || 0) }), t('cp.lead.body', { range: range }), 'danger')
: U.ui.lead(t('cp.lead.empty'), t('cp.lead.emptyBody', { range: range }), 'neutral'));
if (data.truncated) wrap.appendChild(h('p', { class: 'note', text: t('cp.truncated') }));
if (!cs.length) return;
var grid = h('div', 'cp-cards');
cs.slice(0, 60).forEach(function (c) {
var sg = c.signature || {};
grid.appendChild(h('article', 'cp-card',
h('header', null, h('a', { class: 'cp-id mono', href: '#/campaigns/' + encodeURIComponent(c.id), text: short(c.id) }),
h('span', { class: 'cp-win', text: U.fmt.date(sec(c.first)) + ' → ' + U.fmt.date(sec(c.last)) })),
h('div', 'cp-stats', stat(t('cp.ips'), nf(c.ips_n || 0)), stat(t('cp.asns'), nf((c.asns || []).length)), stat(t('cp.ccs'), nf((c.ccs || []).length)), stat(t('cp.sessions'), nf(c.sessions_n || 0))),
h('p', 'cp-sig', h('span', { class: 'cp-sk', text: t('cp.sig') }), chips(sg.paths, 3)),
sg.tool ? h('p', 'cp-sig', h('span', { class: 'cp-sk', text: t('cp.tool') }), h('span', { class: 'cp-chip', text: sg.tool })) : null,
(c.techs || []).length ? h('p', 'cp-sig', h('span', { class: 'cp-sk', text: t('cp.techs') }), chips(c.techs, 4)) : null,
(c.ccs || []).length ? h('p', 'cp-sig', h('span', { class: 'cp-sk', text: t('cp.ccs') }), chips((c.ccs || []).map(function (x) { return (U.fmt.flag(x) + ' ' + x).trim(); }), 6)) : null,
h('footer', null, h('a', { class: 'btn', href: '#/campaigns/' + encodeURIComponent(c.id), text: t('cp.open') }),
h('a', { class: 'btn', href: replayHref(c), text: t('cp.replay') }))));
});
wrap.appendChild(U.ui.panel({ title: t('cp.cards'), help: 'term.campaign' }, grid));
var top = cs.slice(0, 15), mn = Infinity, mx = 0;
top.forEach(function (c) { mn = Math.min(mn, sec(c.first)); mx = Math.max(mx, sec(c.last)); });
wrap.appendChild(U.ui.panel({ title: t('cp.gantt'), hint: t('cp.gantt.hint') },
gantt(top.map(function (c) { return { label: short(c.id), segs: [{ a: sec(c.first), b: sec(c.last) }] }; }), mn, Math.max(mx, mn + 1), t('cp.gantt'))));
if (cs.length > 1) wrap.appendChild(U.ui.panel({ title: t('cp.matrix'), help: 'term.campaign', hint: t('cp.matrix.hint') }, matrix(cs)));
}
function detail() {
wrap.appendChild(h('a', { class: 'btn cp-back', href: U.href('campaigns'), text: '← ' + t('cp.back') }));
if (data.missing || !data.campaign) { wrap.appendChild(U.ui.empty(t('cp.unknown'), t('cp.unknownBody'))); return; }
var c = data.campaign, sg = c.signature || {};
wrap.appendChild(U.ui.lead(t('cp.detail.lead', { id: short(c.id), k: nf(c.ips_n || 0) }), U.fmt.date(sec(c.first)) + ' → ' + U.fmt.date(sec(c.last)), 'danger'));
var head = h('div', 'cp-card cp-wide',
h('div', 'cp-stats', stat(t('cp.ips'), nf(c.ips_n || 0)), stat(t('cp.asns'), nf((c.asns || []).length)), stat(t('cp.ccs'), nf((c.ccs || []).length)), stat(t('cp.sessions'), nf(c.sessions_n || 0))),
h('p', 'cp-sig', h('span', { class: 'cp-sk', text: t('cp.sig') }), chips(sg.paths, 5)),
sg.tool ? h('p', 'cp-sig', h('span', { class: 'cp-sk', text: t('cp.tool') }), h('span', { class: 'cp-chip', text: sg.tool })) : null,
(c.techs || []).length ? h('p', 'cp-sig', h('span', { class: 'cp-sk', text: t('cp.techs') }), chips(c.techs, 8)) : null,
h('footer', null, h('a', { class: 'btn primary', href: replayHref(c), text: t('cp.replay') })));
wrap.appendChild(head);
var ms = data.members || [], tb = h('tbody');
ms.forEach(function (m) {
function td(l, k) { return h('td', { 'data-label': l }, k); }
tb.appendChild(h('tr', 'row', td(t('cp.c.ip'), ipLink(m.ip)),
td(t('cp.c.first'), h('span', { text: m.first ? U.fmt.date(m.first) : '' })), td(t('cp.c.last'), h('span', { text: m.last ? U.fmt.date(m.last) : '' })),
td(t('cp.c.stage'), m.stage ? h('span', { class: 'cp-badge cp-s-' + stg(m.stage), text: t('cp.stage.' + stg(m.stage)) }) : h('span')),
td(t('cp.c.sessions'), h('span', { class: 'num', text: (m.sessions || []).length ? nf(m.sessions.length) : '\u2013' }))));
});
var th = h('tr'); ['ip', 'first', 'last', 'stage', 'sessions'].forEach(function (k) { th.appendChild(h('th', { text: t('cp.c.' + k) })); });
wrap.appendChild(U.ui.panel({ title: t('cp.members') + ' (' + nf(ms.length) + ')' }, h('table', 'stack', h('thead', null, th), tb)));
var rows = [], mn = Infinity, mx = 0;
ms.slice(0, 40).forEach(function (m) {
var segs = (m.sessions || []).map(function (s) { var a = sec(s.start), b = sec(s.end); mn = Math.min(mn, a); mx = Math.max(mx, b); return { a: a, b: b, cls: 'cp-bar cp-b-' + stg(s.stage) }; });
if (segs.length) rows.push({ label: m.ip, segs: segs });
});
if (rows.length) wrap.appendChild(U.ui.panel({ title: t('cp.timeline'), hint: t('cp.timeline.hint') }, gantt(rows, mn, Math.max(mx, mn + 1), t('cp.timeline'))));
}
this.update = function (c) {
var lang = self.ctx.lang, prev = key; self.ctx = c;
if (lang !== c.lang && data) paint();
if (id() !== prev) data = null;
load();
};
this.refresh = function () { load(); };
this.destroy = function () { alive = false; seq++; root.textContent = ''; };
load();
}
U.registerPage({
id: 'campaigns', group: 'investigate', icon: ICON, titleKey: 'cp.title',
mount: function (el, ctx) { if (inst) inst.destroy(); inst = new Page(el, ctx); },
update: function (ctx) { if (inst) inst.update(ctx); },
refresh: function () { if (inst) inst.refresh(); },
unmount: function () { if (inst) { inst.destroy(); inst = null; } }
});
return true;
}
if (!boot()) document.addEventListener('DOMContentLoaded', boot);
})();
+20
View File
@@ -0,0 +1,20 @@
/* Concentration page */
.an-chart { min-width: 0; }
.an-svg { display: block; width: 100%; height: auto; max-width: 100%; overflow: visible; }
.an-svg .an-grid { stroke: var(--line); stroke-width: 1; }
.an-svg .an-guide { stroke: var(--warn); stroke-width: 1; stroke-dasharray: 4 4; }
.an-svg .an-line { fill: none; stroke: var(--accent); stroke-width: 2.25; stroke-linejoin: round; stroke-linecap: round; }
.an-svg .an-fill { fill: var(--accent); fill-opacity: .14; stroke: none; }
.an-svg .an-dot { fill: var(--accent); stroke: var(--surface-panel); stroke-width: 1.5; }
.an-svg .an-tick { fill: var(--ink-muted); font-size: 11px; }
.an-svg .an-strong { fill: var(--ink); font-weight: 600; }
.an-kpis { display: flex; flex-wrap: wrap; gap: var(--s-5); margin: 0 0 var(--s-3); }
.an-kpi { display: grid; }
.an-kpi-v { font: 600 1.5rem var(--font-display); font-variant-numeric: tabular-nums; color: var(--heading); }
.an-kpi-l { color: var(--ink-muted); font-size: .8125rem; }
.an-scroll { max-height: 420px; overflow: auto; }
.an-table { width: 100%; border-collapse: collapse; font-size: .875rem; }
.an-table th, .an-table td { padding: 5px var(--s-3); border-bottom: 1px solid var(--line); text-align: left; }
.an-table th { color: var(--ink-muted); font-weight: 500; position: sticky; top: 0; background: var(--surface-panel); }
.an-table .num { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
.an-table .an-key { overflow-wrap: anywhere; word-break: break-all; }
+208
View File
@@ -0,0 +1,208 @@
/* Urutau - CONCENTRACAO page: do a few sources generate most of the attacks?
Pareto curve with a dimension selector (IP, ASN, country, path, domain),
Gini coefficient, top 10 share and a donut of the top 5 against the rest.
Data: /api/v1/concentration. Log data is hostile: textContent only. */
(function () {
'use strict';
var U = window.Urutau;
if (!U || !U.registerPage) return;
var el = U.el, t = U.t;
var DIMS = ['ip', 'asn', 'country', 'path', 'domain'];
U.registerI18n({
en: {
'an.co.title': 'Concentration',
'an.co.lead': 'The top 10 {dim} generate {pct} of the attacks',
'an.co.lead.body': 'Gini {gini} across {distinct} distinct values, {n} malicious events {range}.',
'an.co.lead.empty': 'No malicious events to measure',
'an.co.lead.empty.body': 'Nothing was recorded {range}.',
'an.co.dim': 'Group by',
'an.co.dim.ip': 'IP',
'an.co.dim.asn': 'ASN',
'an.co.dim.country': 'country',
'an.co.dim.path': 'path',
'an.co.dim.domain': 'domain',
'an.co.curve': 'Pareto curve',
'an.co.curve.hint': 'Share of all events held by the top N, ranked from the heaviest.',
'an.co.x': 'Rank',
'an.co.y': 'Cumulative share',
'an.co.gini': 'Gini',
'an.co.top10': 'Top 10',
'an.co.donut': 'Top 5 and the rest',
'an.co.donut.hint': 'How the five heaviest compare with everything else.',
'an.co.rest': 'others',
'an.co.list': 'Ranking',
'an.co.list.hint': 'Up to the 200 heaviest, with the cumulative share.',
'an.co.total': 'events',
'an.co.off': 'The event registry is off',
'an.co.off.d': 'This analysis reads the event registry, which is not enabled on this instance.',
'an.co.err': 'Could not load this analysis.',
'an.co.retry': 'Try again'
},
'pt-BR': {
'an.co.title': 'Concentração',
'an.co.lead': 'Os 10 maiores por {dim} geram {pct} dos ataques',
'an.co.lead.body': 'Gini {gini} em {distinct} valores distintos, {n} eventos maliciosos {range}.',
'an.co.lead.empty': 'Sem eventos maliciosos para medir',
'an.co.lead.empty.body': 'Nada foi registrado {range}.',
'an.co.dim': 'Agrupar por',
'an.co.dim.ip': 'IP',
'an.co.dim.asn': 'ASN',
'an.co.dim.country': 'país',
'an.co.dim.path': 'caminho',
'an.co.dim.domain': 'domínio',
'an.co.curve': 'Curva de Pareto',
'an.co.curve.hint': 'Parcela de todos os eventos nas N primeiras posições, do mais pesado ao mais leve.',
'an.co.x': 'Posição',
'an.co.y': 'Parcela acumulada',
'an.co.gini': 'Gini',
'an.co.top10': 'Top 10',
'an.co.donut': 'Top 5 e o resto',
'an.co.donut.hint': 'Como os cinco mais pesados se comparam com todo o resto.',
'an.co.rest': 'outros',
'an.co.list': 'Ranking',
'an.co.list.hint': 'Até os 200 mais pesados, com a parcela acumulada.',
'an.co.total': 'eventos',
'an.co.off': 'O registro de eventos está desligado',
'an.co.off.d': 'Esta análise lê o registro de eventos, que não está ativo nesta instância.',
'an.co.err': 'Não foi possível carregar esta análise.',
'an.co.retry': 'Tentar de novo'
}
});
function tip(p, key) { var h2 = p.querySelector('.panel-h h2'); if (h2 && U.help) U.help(h2, key); return p; }
function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); }
function s(tag, attrs, kids) { var n = el(tag, attrs); (kids || []).forEach(function (k) { n.appendChild(k); }); return n; }
function itemLabel(dim, it) {
if (dim === 'country') return it.key ? U.fmt.flag(it.key) + ' ' + U.fmt.country(it.key) : it.key;
if (dim === 'asn' && it.label) return it.key + ' ' + it.label;
return it.key;
}
// Pareto line: x is the rank, y the cumulative share (0..100)
function pareto(items) {
var W = 640, H = 280, L = 44, R = 12, T = 12, B = 34, w = W - L - R, h = H - T - B, n = items.length;
var svg = s('svg', { viewBox: '0 0 ' + W + ' ' + H, class: 'an-svg', role: 'img', 'aria-label': t('an.co.curve'), preserveAspectRatio: 'xMidYMid meet' });
function X(i) { return L + (n <= 1 ? 0 : i / (n - 1)) * w; }
function Y(v) { return T + (1 - v / 100) * h; }
[0, 25, 50, 75, 100].forEach(function (v) {
svg.appendChild(el('line', { class: 'an-grid', x1: L, x2: W - R, y1: Y(v), y2: Y(v) }));
svg.appendChild(el('text', { class: 'an-tick', x: L - 6, y: Y(v) + 4, 'text-anchor': 'end' }, v + '%'));
});
[0, 0.5, 1].forEach(function (f) {
var i = Math.round(f * (n - 1));
svg.appendChild(el('text', { class: 'an-tick', x: X(i), y: H - 16, 'text-anchor': f === 0 ? 'start' : f === 1 ? 'end' : 'middle' }, String(i + 1)));
});
svg.appendChild(el('text', { class: 'an-tick', x: L + w / 2, y: H - 2, 'text-anchor': 'middle' }, t('an.co.x')));
svg.appendChild(el('line', { class: 'an-guide', x1: L, x2: W - R, y1: Y(80), y2: Y(80) }));
var pts = items.map(function (it, i) { return X(i).toFixed(1) + ',' + Y(it.cum_pct).toFixed(1); });
if (n > 0) {
svg.appendChild(el('polygon', { class: 'an-fill', points: X(0).toFixed(1) + ',' + Y(0) + ' ' + pts.join(' ') + ' ' + X(n - 1).toFixed(1) + ',' + Y(0) }));
svg.appendChild(el('polyline', { class: 'an-line', points: pts.join(' ') }));
items.forEach(function (it, i) {
if (n > 40 && i % Math.ceil(n / 40) && i !== n - 1) return;
svg.appendChild(el('circle', { class: 'an-dot', cx: X(i), cy: Y(it.cum_pct), r: 3 }, el('title', null, '#' + (i + 1) + ' ' + it.key + ': ' + it.cum_pct + '%')));
});
}
return el('div', { class: 'an-chart' }, svg);
}
var inst = null, dimSaved = 'ip';
function create(root, ctx) {
var seq = 0, alive = true, data = null, c = ctx, dim = dimSaved;
var grid = el('div', { class: 'grid-12 an-page' });
var lead = el('div', { class: 'span-12' });
var chips = el('div', { class: 'chip-group', role: 'group', 'aria-label': t('an.co.dim') });
var btns = {};
DIMS.forEach(function (d) {
var b = el('button', { type: 'button', class: 'chip-btn', 'aria-pressed': d === dim ? 'true' : 'false' }, t('an.co.dim.' + d));
b.addEventListener('click', function () {
if (dim === d) return;
dim = dimSaved = d; data = null;
DIMS.forEach(function (x) { btns[x].setAttribute('aria-pressed', x === d ? 'true' : 'false'); });
load();
});
btns[d] = b; chips.appendChild(b);
});
var curve = U.ui.panel({ title: t('an.co.curve'), hint: t('an.co.curve.hint'), variant: 'chart', loading: true, actions: chips });
tip(curve, 'term.pareto');
var donut = U.ui.panel({ title: t('an.co.donut'), hint: t('an.co.donut.hint'), loading: true });
var list = U.ui.panel({ title: t('an.co.list'), hint: t('an.co.list.hint'), loading: true });
var kpis = el('div', { class: 'an-kpis' });
grid.appendChild(lead);
grid.appendChild(curve); curve.classList.add('span-8');
grid.appendChild(donut); donut.classList.add('span-4');
grid.appendChild(list); list.classList.add('span-12');
root.appendChild(grid);
function paint() {
clear(lead); [curve, donut, list].forEach(function (p) { clear(p.body); });
if (!data) return;
if (!data.enabled) { lead.appendChild(U.ui.empty(t('an.co.off'), t('an.co.off.d'))); return; }
var d = data, range = U.rangeLabel({ inline: true }), dname = t('an.co.dim.' + d.dim);
if (!d.total) {
lead.appendChild(U.ui.lead(t('an.co.lead.empty'), t('an.co.lead.empty.body', { range: range }), 'neutral'));
curve.body.appendChild(U.ui.empty(t('charts.empty')));
donut.body.appendChild(U.ui.empty(t('charts.empty')));
list.body.appendChild(U.ui.empty(t('charts.empty')));
return;
}
lead.appendChild(U.ui.lead(t('an.co.lead', { dim: dname, pct: U.fmt.pct(d.top10_pct / 100) }),
t('an.co.lead.body', { gini: d.gini.toFixed(2), distinct: U.fmt.num(d.distinct), n: U.fmt.num(d.total), range: range }), 'neutral'));
kpis = el('div', { class: 'an-kpis' },
el('div', { class: 'an-kpi' }, el('span', { class: 'an-kpi-v' }, d.gini.toFixed(2)), el('span', { class: 'an-kpi-l' }, t('an.co.gini'), ' ', (function () { var w = el('span'); U.help && U.help(w, 'term.gini'); return w; })())),
el('div', { class: 'an-kpi' }, el('span', { class: 'an-kpi-v' }, U.fmt.pct(d.top10_pct / 100)), el('span', { class: 'an-kpi-l' }, t('an.co.top10'))));
curve.body.appendChild(kpis);
curve.body.appendChild(pareto(d.items));
var top5 = d.items.slice(0, 5), used = 0;
var rows = top5.map(function (it) { used += it.n; return { key: it.key, label: itemLabel(d.dim, it), value: it.n }; });
if (d.total > used) rows.push({ key: '_rest', label: t('an.co.rest'), value: d.total - used });
donut.body.appendChild(U.charts.donut(rows, { title: t('an.co.donut'), centerLabel: t('an.co.total'), colors: ['--viz-1', '--viz-2', '--viz-3', '--viz-4', '--viz-5', '--viz-8'] }));
var tbl = el('table', { class: 'an-table' });
tbl.appendChild(el('thead', null, el('tr', null, el('th', null, '#'), el('th', null, t('an.co.dim.' + d.dim)), el('th', { class: 'num' }, t('an.co.total')), el('th', { class: 'num' }, t('an.co.y')))));
var tb = el('tbody');
d.items.forEach(function (it, i) {
var cell = el('td', { class: 'an-key mono' });
if (d.dim === 'ip') {
var a = el('a', { href: '#/ip/' + encodeURIComponent(it.key) }, it.key);
cell.appendChild(a);
} else cell.textContent = itemLabel(d.dim, it);
tb.appendChild(el('tr', null, el('td', { class: 'num' }, String(i + 1)), cell, el('td', { class: 'num' }, U.fmt.num(it.n)), el('td', { class: 'num' }, it.cum_pct.toFixed(1) + '%')));
});
tbl.appendChild(tb);
list.body.appendChild(el('div', { class: 'an-scroll' }, tbl));
}
function load() {
var my = ++seq;
var p = Object.assign({ dim: dim }, U.rangeParams());
if (c.host && c.host !== 'all') p.host = c.host;
U.api('/api/v1/concentration', p).then(function (r) {
if (!alive || my !== seq) return;
data = r; paint();
}, function () {
if (!alive || my !== seq || data) return;
clear(lead);
var b = el('button', { type: 'button', class: 'btn' }, t('an.co.retry'));
b.addEventListener('click', load);
lead.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('an.co.err')), b));
});
}
load();
return {
root: root, lang: ctx.lang,
update: function (cx) { c = cx; load(); },
destroy: function () { alive = false; seq++; clear(root); }
};
}
U.registerPage({
id: 'concentration', group: 'analyze', titleKey: 'an.co.title',
icon: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M4 20V4"/><path d="M4 20h16"/><path d="M4 6c6 0 9 4 16 4"/></svg>',
mount: function (el, ctx) { if (inst) inst.destroy(); inst = create(el, ctx || {}); },
update: function (ctx) {
ctx = ctx || {};
if (inst && ctx.lang !== inst.lang) { var r = inst.root; inst.destroy(); inst = create(r, ctx); } else if (inst) inst.update(ctx);
},
unmount: function () { if (inst) { inst.destroy(); inst = null; } }
});
})();
+25
View File
@@ -0,0 +1,25 @@
/* Defense page */
.df-page { display: grid; gap: var(--grid-gap, 16px); min-width: 0; }
.df-kpis .card-metric { min-width: 0; }
.df-sum { padding: 0 0 8px; }
.df-bl { color: var(--ink-muted); font-size: .875rem; margin: 4px 0 12px; overflow-wrap: anywhere; }
.df-en { margin-top: var(--grid-gap, 16px); }
.df-en .panel { min-width: 0; }
.df-en-title { font-size: 1.125rem; margin: 0 0 4px; }
.df-mode { margin: 0 0 8px; }
.df-en-p { margin: 0 0 8px; overflow-wrap: anywhere; }
.df-en-meta { overflow-wrap: anywhere; }
.df-en-how { margin: 8px 0 0; padding: 8px 12px; border-left: 3px solid var(--info); background: var(--info-soft); border-radius: 4px; overflow-wrap: anywhere; }
.df-en-sum { font-size: 1.0625rem; font-weight: 600; margin: 0 0 4px; overflow-wrap: anywhere; }
.df-skips { list-style: none; margin: 12px 0 0; padding: 0; display: flex; flex-wrap: wrap; gap: 4px 16px; color: var(--ink-muted); font-size: .875rem; }
.df-skips .num { font-weight: 600; color: var(--ink); }
.df-scroll { max-height: 440px; overflow: auto; }
.df-table { width: 100%; border-collapse: collapse; font-size: .875rem; }
.df-table th, .df-table td { padding: 5px var(--s-3, 10px); border-bottom: 1px solid var(--line); text-align: left; overflow-wrap: anywhere; vertical-align: top; }
.df-table th { color: var(--ink-muted); font-weight: 500; position: sticky; top: 0; background: var(--surface-panel); }
.df-table .num { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
.df-act { display: inline-flex; flex-direction: column; align-items: flex-start; gap: 2px; }
.df-skipwhy { color: var(--ink-muted); font-size: .75rem; }
@media (max-width: 900px) { .df-en .span-4, .df-en .span-8 { grid-column: 1 / -1; } }
.df-nowrap { white-space: nowrap; }
@media (max-width: 700px) { .df-table { min-width: 640px; } .df-table td, .df-table th { overflow-wrap: normal; } }
+454
View File
@@ -0,0 +1,454 @@
/* Urutau - DEFENSE page: is fail2ban acting? Bans over time per jail, time to
ban, blocklist coverage, leak and the SSH users tried. Data:
/api/v1/defense. Log data is hostile: dynamic text goes through textContent
only. */
(function () {
'use strict';
var MAX_BUCKETS = 400;
function boot() {
var U = window.Urutau;
if (!U || !U.registerPage) return false;
U.registerI18n({
en: {
'df.title': 'Defense',
'df.lead.some': 'fail2ban applied {n} bans {range}',
'df.lead.sub.ok': '{a} bans are active. Few attackers kept arriving after being banned.',
'df.lead.sub.leak': '{a} bans are active, but {l} attackers kept arriving after a ban or listing.',
'df.lead.none': 'fail2ban did not ban anyone {range}',
'df.lead.none.sub': 'No ban events in this window. If attacks were seen, check that the fail2ban log is being read.',
'df.kpi.active': 'Active bans',
'df.kpi.active.sub': '{n} bans in the window',
'df.kpi.ttb': 'Time to ban',
'df.kpi.ttb.sub': 'median per attack episode; 90% within {p}',
'df.kpi.ttb.none': 'no data',
'df.kpi.cov': 'Blocklist coverage',
'df.kpi.cov.sub': '{n} addresses listed',
'df.kpi.leak': 'Leak',
'df.kpi.leak.sub': '{n} events after the ban',
'df.bans': 'Bans per jail over time',
'df.jails': 'Bans by jail',
'df.jails.center': 'bans',
'df.users': 'SSH users tried',
'df.users.hint': 'Names attackers tried to log in with. Red: a real account of yours.',
'df.users.none': 'No SSH failures in this window.',
'df.ssh.sum': '{f} failures from {s} sources; {o} successful logins after failures.',
'df.cov': 'Blocklist coverage',
'df.cov.hint': 'Share of the attackers of the window that are in the blocklist.',
'df.cov.label': 'of attackers listed',
'df.bl.size': '{n} addresses ({v4} IPv4, {v6} IPv6 /64)',
'df.bl.updated': 'last change {t}',
'df.bl.download': 'Download blocklist',
'df.error': 'Could not load the defense data.',
'df.disabled': 'The event registry is off',
'df.disabled.sub': 'Defense is computed from the event registry; enable it to see this page.',
'df.partial': 'Partial result: the study hit its time or size limit.',
'df.admin': 'your account',
'df.en.title': 'Second firewall',
'df.en.hint': 'Urutau can also block attackers by itself, as a safety net next to fail2ban.',
'df.en.mode': 'Mode',
'df.en.mode.off': 'Off',
'df.en.mode.observe': 'Observing only',
'df.en.mode.on': 'Active',
'df.en.mode.off.sub': 'Urutau does not block anyone. Nothing is written; the coverage below shows what you would gain by turning it on.',
'df.en.mode.observe.sub': 'Urutau decides who it would block and records it, but blocks nobody. Use it to check the decisions before trusting them.',
'df.en.mode.on.sub': 'Urutau blocks the attackers it recognises, on its own, for a limited time.',
'df.en.mode.where': 'The mode is chosen at deploy time with the variable URUTAU_ENFORCE (off, observe or on). It cannot be changed from this page.',
'df.en.how.title': 'How to turn it on',
'df.en.how.body': 'Set URUTAU_ENFORCE=observe on the server and restart Urutau. Watch the decisions for a few days; when they look right, change it to on.',
'df.en.share': 'Sharing with peers',
'df.en.share.on': 'on: bans are shared with other servers',
'df.en.share.off': 'off: bans stay on this server',
'df.en.threshold': 'Blocks from score {n}',
'df.en.nolog.title': 'Blocks are not being saved',
'df.en.nolog.body': 'The mode is active but the block file cannot be written, so nobody is really blocked. Check the permissions of the folder where Urutau writes the blocklist.',
'df.en.lead': '{b} of {a} attacking addresses were blocked {range}',
'df.en.lead.sub': '{fw} by the server firewall, {ur} by Urutau, {wb} would be blocked in observation mode and {un} got through.',
'df.en.lead.none': 'No attacking addresses {range}',
'df.en.lead.none.sub': 'Nothing to block in this window.',
'df.en.cov': 'Who was blocked',
'df.en.cov.hint': 'Each attacking address counted once, by the first line of defense that stopped it.',
'df.en.cov.center': 'addresses',
'df.en.cov.fw': 'Blocked by the server firewall',
'df.en.cov.ur': 'Blocked by Urutau',
'df.en.cov.wb': 'Would be blocked (observation mode)',
'df.en.cov.un': 'Got through without a block',
'df.en.counts': 'What Urutau decided',
'df.en.counts.hint': 'Counts in this window. "Skipped" are attackers it deliberately left alone.',
'df.en.c.decided': 'Decisions',
'df.en.c.written': 'Blocks written',
'df.en.c.dropped': 'Dropped by rate limit',
'df.en.c.already': 'Already blocked',
'df.en.recent': 'Recent decisions',
'df.en.recent.hint': 'The latest decisions, newest first.',
'df.en.recent.none': 'No decisions in this window.',
'df.en.col.time': 'Time',
'df.en.col.ip': 'Address',
'df.en.col.cc': 'Country',
'df.en.col.reason': 'Reason',
'df.en.col.score': 'Score',
'df.en.col.ttl': 'Duration',
'df.en.col.action': 'Action',
'df.en.col.src': 'Origin',
'df.en.act.ban': 'Blocked',
'df.en.act.would_ban': 'Would block',
'df.en.act.skip': 'Not blocked',
'df.en.src.local': 'this server',
'df.en.src.peer': 'peer {n}',
'df.en.skip.trusted': 'Trusted address (your own list)',
'df.en.skip.private': 'Private network (not on the internet)',
'df.en.skip.crawler': 'Verified search engine',
'df.en.skip.legit_visitor': 'Looks like a legitimate visitor',
'df.en.skip.peer': 'Peer server (yours)',
'df.en.reason.scanner-flood': 'Many vulnerability probes in a short time',
'df.en.reason.exploit-flood': 'Repeated exploit attempts',
'df.en.reason.web-bruteforce': 'Password guessing on a website',
'df.en.reason.wp-bruteforce': 'Password guessing on WordPress',
'df.en.reason.ssh-bruteforce': 'Password guessing on SSH',
'df.en.reason.rce': 'Attempt to run commands on the server',
'df.en.reason.path-traversal': 'Attempt to read files outside the site',
'df.en.reason.env-probe': 'Hunting for secret configuration files (.env)',
'df.en.reason.vcs-probe': 'Hunting for source code history (.git)',
'df.en.reason.webshell': 'Looking for or uploading a backdoor (webshell)',
'df.en.reason.sqli': 'Attempt to tamper with the database (SQL injection)',
'df.en.reason.log4shell': 'Log4Shell exploit attempt',
'df.en.error': 'Could not load the second firewall data.'
},
'pt-BR': {
'df.title': 'Defesa',
'df.lead.some': 'O fail2ban aplicou {n} bans {range}',
'df.lead.sub.ok': '{a} bans estão ativos. Poucos atacantes continuaram chegando depois do ban.',
'df.lead.sub.leak': '{a} bans estão ativos, mas {l} atacantes continuaram chegando depois de um ban ou da listagem.',
'df.lead.none': 'O fail2ban não baniu ninguém {range}',
'df.lead.none.sub': 'Nenhum evento de ban nesta janela. Se houve ataques, confira se o log do fail2ban está sendo lido.',
'df.kpi.active': 'Bans ativos',
'df.kpi.active.sub': '{n} bans na janela',
'df.kpi.ttb': 'Tempo até o ban',
'df.kpi.ttb.sub': 'mediana por episódio de ataque; 90% em até {p}',
'df.kpi.ttb.none': 'sem dados',
'df.kpi.cov': 'Cobertura da blocklist',
'df.kpi.cov.sub': '{n} endereços listados',
'df.kpi.leak': 'Vazamento',
'df.kpi.leak.sub': '{n} eventos depois do ban',
'df.bans': 'Bans por jail ao longo do tempo',
'df.jails': 'Bans por jail',
'df.jails.center': 'bans',
'df.users': 'Usuários SSH tentados',
'df.users.hint': 'Nomes com que os atacantes tentaram entrar. Vermelho: uma conta real sua.',
'df.users.none': 'Nenhuma falha de SSH nesta janela.',
'df.ssh.sum': '{f} falhas de {s} origens; {o} logins bem-sucedidos depois de falhas.',
'df.cov': 'Cobertura da blocklist',
'df.cov.hint': 'Parcela dos atacantes da janela que está na blocklist.',
'df.cov.label': 'dos atacantes listados',
'df.bl.size': '{n} endereços ({v4} IPv4, {v6} IPv6 /64)',
'df.bl.updated': 'última alteração {t}',
'df.bl.download': 'Baixar a blocklist',
'df.error': 'Não foi possível carregar os dados de defesa.',
'df.disabled': 'O registro de eventos está desligado',
'df.disabled.sub': 'A defesa é calculada a partir do registro de eventos; ative-o para ver esta página.',
'df.partial': 'Resultado parcial: o estudo atingiu o limite de tempo ou de tamanho.',
'df.admin': 'sua conta',
'df.en.title': 'Segundo firewall',
'df.en.hint': 'O Urutau também pode bloquear atacantes por conta própria, como uma rede de segurança ao lado do fail2ban.',
'df.en.mode': 'Modo',
'df.en.mode.off': 'Desligado',
'df.en.mode.observe': 'Só observando',
'df.en.mode.on': 'Ativo',
'df.en.mode.off.sub': 'O Urutau não bloqueia ninguém e não grava nada. A cobertura abaixo mostra o quanto você ganharia ao ligá-lo.',
'df.en.mode.observe.sub': 'O Urutau decide quem bloquearia e registra, mas não bloqueia ninguém. Use para conferir as decisões antes de confiar nelas.',
'df.en.mode.on.sub': 'O Urutau bloqueia sozinho os atacantes que reconhece, por tempo limitado.',
'df.en.mode.where': 'O modo é escolhido no deploy, pela variável URUTAU_ENFORCE (off, observe ou on). Não dá para mudá-lo por esta página.',
'df.en.how.title': 'Como ligar',
'df.en.how.body': 'Defina URUTAU_ENFORCE=observe no servidor e reinicie o Urutau. Acompanhe as decisões por alguns dias; quando estiverem certas, troque para on.',
'df.en.share': 'Compartilhamento com parceiros',
'df.en.share.on': 'ligado: os bloqueios são compartilhados com outros servidores',
'df.en.share.off': 'desligado: os bloqueios ficam só neste servidor',
'df.en.threshold': 'Bloqueia a partir da pontuação {n}',
'df.en.nolog.title': 'Os bloqueios não estão sendo salvos',
'df.en.nolog.body': 'O modo está ativo, mas o arquivo de bloqueios não pode ser gravado; na prática ninguém está sendo bloqueado. Confira as permissões da pasta onde o Urutau grava a blocklist.',
'df.en.lead': '{b} de {a} endereços atacantes foram bloqueados {range}',
'df.en.lead.sub': '{fw} pelo firewall do servidor, {ur} pelo Urutau, {wb} seriam bloqueados no modo observação e {un} passaram.',
'df.en.lead.none': 'Nenhum endereço atacante {range}',
'df.en.lead.none.sub': 'Nada a bloquear nesta janela.',
'df.en.cov': 'Quem foi bloqueado',
'df.en.cov.hint': 'Cada endereço atacante conta uma vez, pela primeira linha de defesa que o barrou.',
'df.en.cov.center': 'endereços',
'df.en.cov.fw': 'Bloqueado pelo firewall do servidor',
'df.en.cov.ur': 'Bloqueado pelo Urutau',
'df.en.cov.wb': 'Seria bloqueado (modo observação)',
'df.en.cov.un': 'Passou sem bloqueio',
'df.en.counts': 'O que o Urutau decidiu',
'df.en.counts.hint': 'Contagens desta janela. "Ignorados" são atacantes que ele deixou passar de propósito.',
'df.en.c.decided': 'Decisões',
'df.en.c.written': 'Bloqueios gravados',
'df.en.c.dropped': 'Descartados pelo limite de ritmo',
'df.en.c.already': 'Já estavam bloqueados',
'df.en.recent': 'Decisões recentes',
'df.en.recent.hint': 'As últimas decisões, da mais nova para a mais antiga.',
'df.en.recent.none': 'Nenhuma decisão nesta janela.',
'df.en.col.time': 'Hora',
'df.en.col.ip': 'Endereço',
'df.en.col.cc': 'País',
'df.en.col.reason': 'Motivo',
'df.en.col.score': 'Pontuação',
'df.en.col.ttl': 'Duração',
'df.en.col.action': 'Ação',
'df.en.col.src': 'Origem',
'df.en.act.ban': 'Bloqueado',
'df.en.act.would_ban': 'Bloquearia',
'df.en.act.skip': 'Não bloqueado',
'df.en.src.local': 'este servidor',
'df.en.src.peer': 'parceiro {n}',
'df.en.skip.trusted': 'Endereço confiável (sua própria lista)',
'df.en.skip.private': 'Rede privada (fora da internet)',
'df.en.skip.crawler': 'Buscador verificado',
'df.en.skip.legit_visitor': 'Parece um visitante legítimo',
'df.en.skip.peer': 'Servidor parceiro (seu)',
'df.en.reason.scanner-flood': 'Muitas sondagens de vulnerabilidade em pouco tempo',
'df.en.reason.exploit-flood': 'Tentativas repetidas de exploração',
'df.en.reason.web-bruteforce': 'Tentativa de adivinhar senha num site',
'df.en.reason.wp-bruteforce': 'Tentativa de adivinhar senha no WordPress',
'df.en.reason.ssh-bruteforce': 'Tentativa de adivinhar senha no SSH',
'df.en.reason.rce': 'Tentativa de executar comandos no servidor',
'df.en.reason.path-traversal': 'Tentativa de ler arquivos fora do site',
'df.en.reason.env-probe': 'Caça a arquivos de configuração secretos (.env)',
'df.en.reason.vcs-probe': 'Caça ao histórico do código-fonte (.git)',
'df.en.reason.webshell': 'Procura ou envio de porta dos fundos (webshell)',
'df.en.reason.sqli': 'Tentativa de adulterar o banco de dados (injeção de SQL)',
'df.en.reason.log4shell': 'Tentativa de explorar o Log4Shell',
'df.en.error': 'Não foi possível carregar os dados do segundo firewall.'
}
});
var el = U.el, t = U.t, nf = U.fmt.num;
var root = null, seq = 0, alive = false, ctx = null, data = null;
function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); }
function dur(s) {
s = Math.round(s);
if (s < 60) return s + ' s';
if (s < 3600) return Math.round(s / 60) + ' min';
if (s < 86400) return (s / 3600).toFixed(s < 36000 ? 1 : 0).replace(/\.0$/, '') + ' h';
return (s / 86400).toFixed(1).replace(/\.0$/, '') + ' d';
}
function pctTxt(v) { return (v > 0 && v < 10 ? v.toFixed(1) : Math.round(v)) + '%'; }
function series(d) {
var step = d.step || 3600, from = d.from || 0;
var end = Math.max(ctx && ctx.to ? ctx.to : Math.floor(Date.now() / 1000), 0);
(d.bans || []).forEach(function (b) { if (b.t > end) end = b.t; });
var n = Math.min(MAX_BUCKETS, Math.floor((end - from) / step) + 1);
if (n < 2) n = 2;
var start = from;
if (Math.floor((end - from) / step) + 1 > MAX_BUCKETS) start = Math.floor(end / step) * step - (MAX_BUCKETS - 1) * step;
var jails = {}, order = [];
(d.by_jail || []).forEach(function (j) { jails[j.jail] = new Array(n).fill(0); order.push(j.jail); });
(d.bans || []).forEach(function (b) {
var i = Math.round((b.t - start) / step);
if (i < 0 || i >= n) return;
if (!jails[b.jail]) { jails[b.jail] = new Array(n).fill(0); order.push(b.jail); }
jails[b.jail][i] += b.n;
});
return { step: step, start: start, list: order.map(function (j) { return { key: j, label: j, values: jails[j] }; }) };
}
function paint() {
if (!root) return;
clear(root);
if (!data) { root.appendChild(el('div', { class: 'skeleton', style: { height: '8rem' } })); return; }
if (!data.enabled) { root.appendChild(U.ui.empty(t('df.disabled'), t('df.disabled.sub'))); return; }
var d = data, range = U.rangeLabel({ inline: true }), leak = d.leak || { ips: 0, events: 0 };
var bl = d.blocklist || {}, ssh = d.ssh || { users: [] }, ttb = d.ttb || {};
if (d.bans_total > 0) {
var bad = leak.ips > 0 && leak.ips * 4 > d.bans_total;
root.appendChild(U.ui.lead(t('df.lead.some', { n: nf(d.bans_total), range: range }),
leak.ips > 0 ? t('df.lead.sub.leak', { a: nf(d.bans_active), l: nf(leak.ips) }) : t('df.lead.sub.ok', { a: nf(d.bans_active) }), bad ? 'danger' : 'ok'));
} else {
root.appendChild(U.ui.lead(t('df.lead.none', { range: range }), t('df.lead.none.sub'), 'danger'));
}
if (d.truncated) root.appendChild(el('p', { class: 'hint' }, t('df.partial')));
var kp = el('div', { class: 'grid-12 df-kpis' });
function k(node) { node.classList.add('span-3'); kp.appendChild(node); }
k(U.ui.metric(t('df.kpi.active'), nf(d.bans_active), { sub: t('df.kpi.active.sub', { n: nf(d.bans_total) }) }));
k(U.ui.metric(t('df.kpi.ttb'), ttb.n ? dur(ttb.median_s) : t('df.kpi.ttb.none'), ttb.n ? { sub: t('df.kpi.ttb.sub', { p: dur(ttb.p90_s) }) } : {}));
var cov = bl.coverage_pct || 0;
k(U.ui.metric(t('df.kpi.cov'), pctTxt(cov), { sub: t('df.kpi.cov.sub', { n: nf(bl.size || 0) }), tone: cov >= 70 ? 'ok' : cov >= 40 ? 'warn' : 'danger' }));
k(U.ui.metric(t('df.kpi.leak'), nf(leak.ips), { sub: t('df.kpi.leak.sub', { n: nf(leak.events) }), tone: leak.ips ? 'warn' : 'ok' }));
root.appendChild(kp);
var grid = el('div', { class: 'grid-12' });
var sr = series(d);
var ap = U.ui.panel({ title: t('df.bans'), cls: 'span-8' });
if (U.charts && U.charts.stackedArea && sr.list.length) ap.body.appendChild(U.charts.stackedArea(sr.list, sr.step, { start: sr.start, title: t('df.bans') }));
else ap.body.appendChild(U.ui.empty(t('df.lead.none', { range: range })));
grid.appendChild(ap);
var jp = U.ui.panel({ title: t('df.jails'), cls: 'span-4' });
var jd = (d.by_jail || []).filter(function (j) { return j.total > 0; }).map(function (j) { return { key: j.jail, label: j.jail, value: j.total }; });
if (U.charts && U.charts.donut) jp.body.appendChild(U.charts.donut(jd, { title: t('df.jails'), centerLabel: t('df.jails.center'), format: nf }));
grid.appendChild(jp);
var up = U.ui.panel({ title: t('df.users'), hint: t('df.users.hint'), cls: 'span-8' });
var users = ssh.users || [];
if (!users.length) up.body.appendChild(U.ui.empty(t('df.users.none')));
else {
up.body.appendChild(el('p', { class: 'hint df-sum' }, t('df.ssh.sum', { f: nf(ssh.fails), s: nf(ssh.sources), o: nf(ssh.ok_after_fail) })));
var rows = users.slice(0, 15).map(function (u) {
var lit = u.user === 'admin' || u.user === 'root';
return { key: u.user, label: u.admin ? u.user + ' (' + t('df.admin') + ')' : u.user, value: u.n, color: u.admin ? '--danger' : lit ? '--warn' : '--viz-1' };
});
if (U.charts && U.charts.bars) up.body.appendChild(U.charts.bars(rows, { title: t('df.users'), format: nf }));
}
grid.appendChild(up);
var gp = U.ui.panel({ title: t('df.cov'), hint: t('df.cov.hint'), cls: 'span-4' });
if (U.charts && U.charts.gauge) gp.body.appendChild(U.charts.gauge(Math.round(cov), 100, [{ at: 0, tone: 'danger' }, { at: 40, tone: 'warn' }, { at: 70, tone: 'ok' }], { label: t('df.cov.label'), format: function (v) { return v + '%'; } }));
gp.body.appendChild(el('p', { class: 'df-bl' }, t('df.bl.size', { n: nf(bl.size || 0), v4: nf(bl.v4 || 0), v6: nf(bl.v6 || 0) }) + (bl.updated ? ' · ' + t('df.bl.updated', { t: U.fmt.ago(bl.updated) }) : '')));
gp.body.appendChild(el('a', { class: 'btn', href: '/api/v1/blocklist.txt?download=1&range=7d', download: 'urutau-blocklist.txt' }, t('df.bl.download')));
grid.appendChild(gp);
root.appendChild(grid);
}
var enData = null, enSeq = 0, enBox = null;
function ttlTxt(s) { return s > 0 ? dur(s) : '-'; }
function reasonTxt(r) {
if (!r) return '-';
var k = 'df.en.reason.' + r;
if (t(k) !== k) return t(k);
var parts = String(r).split(/[-_:]/);
for (var i = 0; i < parts.length; i++) { var c = 'df.en.reason.' + parts[i]; if (t(c) !== c) return t(c) + ' (' + r + ')'; }
return r;
}
function tbl(cols, rows) {
var tb = el('tbody');
rows.forEach(function (r) { tb.appendChild(el('tr', null, r.map(function (c, i) { return el('td', { class: cols[i].cls || '' }, c); }))); });
return el('div', { class: 'df-scroll' }, el('table', { class: 'df-table' },
el('thead', null, el('tr', null, cols.map(function (c) { return el('th', { class: c.cls || '' }, c.label); }))), tb));
}
function paintEnforce() {
if (!enBox) return;
clear(enBox);
if (!enData) return;
var e = enData, cv = e.coverage || {}, cn = e.counts || {}, sk = cn.skipped || {}, range = U.rangeLabel({ inline: true });
var mode = /^(off|observe|on)$/.test(e.mode) ? e.mode : 'off';
var head = el('div', { class: 'df-en-head' });
var mt = el('h2', { class: 'df-en-title' }, t('df.en.title'));
if (U.help) U.help(mt, 'term.second_firewall');
head.appendChild(mt);
head.appendChild(el('p', { class: 'hint' }, t('df.en.hint')));
enBox.appendChild(head);
var grid = el('div', { class: 'grid-12' });
var mp = U.ui.panel({ title: t('df.en.mode'), cls: 'span-4', help: mode === 'observe' ? 'term.observe_mode' : null });
var tone = mode === 'on' ? 'ok' : mode === 'observe' ? 'info' : 'warn';
mp.body.appendChild(el('p', { class: 'df-mode' }, U.ui.badge(t('df.en.mode.' + mode), tone)));
mp.body.appendChild(el('p', { class: 'df-en-p' }, t('df.en.mode.' + mode + '.sub')));
mp.body.appendChild(el('p', { class: 'hint' }, t('df.en.mode.where')));
var meta = el('p', { class: 'hint df-en-meta' }, t('df.en.threshold', { n: nf(e.threshold || 0) }) + ' · ' + t('df.en.share') + ': ' + (e.share === 'on' ? t('df.en.share.on') : t('df.en.share.off')));
if (U.help) U.help(meta, 'term.ban_ttl');
mp.body.appendChild(meta);
if (mode === 'on' && e.log_writable === false) mp.body.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('df.en.nolog.title')), el('span', null, t('df.en.nolog.body'))));
if (mode === 'off') {
mp.body.appendChild(el('p', { class: 'df-en-how' }, el('strong', null, t('df.en.how.title') + ': '), t('df.en.how.body')));
}
grid.appendChild(mp);
var total = (cv.blocked_by_firewall || 0) + (cv.blocked_by_urutau || 0) + (cv.would_block || 0) + (cv.unblocked || 0);
var cp = U.ui.panel({ title: t('df.en.cov'), hint: t('df.en.cov.hint'), cls: 'span-8' });
var rows = [
{ key: 'fw', label: t('df.en.cov.fw'), value: cv.blocked_by_firewall || 0, color: '--ok' },
{ key: 'ur', label: t('df.en.cov.ur'), value: cv.blocked_by_urutau || 0, color: '--info' },
{ key: 'wb', label: t('df.en.cov.wb'), value: cv.would_block || 0, color: '--warn' },
{ key: 'un', label: t('df.en.cov.un'), value: cv.unblocked || 0, color: '--danger' }
];
var blocked = (cv.blocked_by_firewall || 0) + (cv.blocked_by_urutau || 0);
cp.body.appendChild(el('p', { class: 'df-en-sum' }, total ? t('df.en.lead', { b: nf(blocked), a: nf(cv.attack_ips || total), range: range }) : t('df.en.lead.none', { range: range })));
if (total) {
cp.body.appendChild(el('p', { class: 'hint' }, t('df.en.lead.sub', { fw: nf(rows[0].value), ur: nf(rows[1].value), wb: nf(rows[2].value), un: nf(rows[3].value) })));
if (U.charts && U.charts.donut) {
cp.body.appendChild(U.charts.donut(rows, { title: t('df.en.cov'), centerLabel: t('df.en.cov.center'), format: nf, colors: rows.map(function (r) { return r.color; }) }));
if (U.help) { var lis = cp.body.querySelectorAll('.vz-legend li'); if (lis[2]) U.help(lis[2], 'term.observe_mode'); }
}
} else cp.body.appendChild(U.ui.empty(t('df.en.lead.none', { range: range }), t('df.en.lead.none.sub')));
grid.appendChild(cp);
var np = U.ui.panel({ title: t('df.en.counts'), hint: t('df.en.counts.hint'), cls: 'span-12' });
var kp = el('div', { class: 'grid-12 df-kpis' });
function k(node) { node.classList.add('span-3'); kp.appendChild(node); }
k(U.ui.metric(t('df.en.c.decided'), nf(cn.decided || 0)));
k(U.ui.metric(t('df.en.c.written'), nf(cn.written || 0), { tone: 'ok' }));
k(U.ui.metric(t('df.en.c.dropped'), nf(cn.dropped_rate || 0), { tone: cn.dropped_rate ? 'warn' : 'neutral' }));
k(U.ui.metric(t('df.en.c.already'), nf(cn.already_blocked || 0)));
np.body.appendChild(kp);
var skl = el('ul', { class: 'df-skips' });
['trusted', 'private', 'crawler', 'legit_visitor', 'peer'].forEach(function (key) {
if (!sk[key]) return;
skl.appendChild(el('li', null, el('span', { class: 'num' }, nf(sk[key])), ' ' + t('df.en.skip.' + key)));
});
if (skl.firstChild) np.body.appendChild(skl);
grid.appendChild(np);
var rp = U.ui.panel({ title: t('df.en.recent'), hint: t('df.en.recent.hint'), cls: 'span-12', variant: 'list' });
var rec = e.recent || [];
if (!rec.length) rp.body.appendChild(U.ui.empty(t('df.en.recent.none')));
else {
var cols = [{ label: t('df.en.col.time') }, { label: t('df.en.col.ip'), cls: 'mono' }, { label: t('df.en.col.cc') }, { label: t('df.en.col.reason') },
{ label: t('df.en.col.score'), cls: 'num' }, { label: t('df.en.col.ttl'), cls: 'num' }, { label: t('df.en.col.action') }, { label: t('df.en.col.src') }];
rp.body.appendChild(tbl(cols, rec.map(function (r) {
var act = /^(ban|would_ban|skip)$/.test(r.action) ? r.action : 'skip';
var actNode = el('span', { class: 'df-act' }, U.ui.badge(t('df.en.act.' + act), act === 'ban' ? 'ok' : act === 'would_ban' ? 'warn' : 'neutral'));
if (act === 'skip' && r.skip_reason) {
var sk2 = 'df.en.skip.' + r.skip_reason;
actNode.appendChild(el('small', { class: 'df-skipwhy' }, t(sk2) !== sk2 ? t(sk2) : r.skip_reason));
}
var peer = String(r.src || 'local');
var src = peer.indexOf('peer:') === 0 ? t('df.en.src.peer', { n: peer.slice(5) }) : t('df.en.src.local');
return [el('span', { class: 'df-nowrap' }, U.fmt.clock(r.t)), el('a', { href: U.href('ip', [r.ip]) }, r.ip), (r.cc ? U.fmt.flag(r.cc) + ' ' : '') + (r.cc || '-'),
reasonTxt(r.reason), nf(r.score || 0), ttlTxt(r.ttl || 0), actNode, src];
})));
}
grid.appendChild(rp);
enBox.appendChild(grid);
}
function loadEnforce() {
var my = ++enSeq;
U.api('/api/v1/enforce', Object.assign(U.rangeParams(), ctx && ctx.host && ctx.host !== 'all' ? { host: ctx.host } : {})).then(function (d) {
if (!alive || my !== enSeq) return;
enData = d; paintEnforce();
}).catch(function () {
if (!alive || my !== enSeq || enData || !enBox) return;
clear(enBox);
enBox.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('df.en.error'))));
});
}
function load() {
loadEnforce();
var my = ++seq;
U.api('/api/v1/defense', Object.assign(U.rangeParams(), ctx && ctx.host && ctx.host !== 'all' ? { host: ctx.host } : {})).then(function (d) {
if (!alive || my !== seq) return;
data = d; paint();
}).catch(function () {
if (!alive || my !== seq || data) return;
clear(root);
root.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('df.error'))));
});
}
U.registerPage({
id: 'defense', group: 'operate', titleKey: 'df.title',
icon: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M12 3l8 3v6c0 4.5-3.2 7.8-8 9-4.8-1.2-8-4.5-8-9V6z"/><path d="M9 12l2 2 4-4"/></svg>',
mount: function (node, cx) { root = el('div', { class: 'df-page' }); node.appendChild(root); enBox = el('div', { class: 'df-page df-en' }); node.appendChild(enBox); ctx = cx; alive = true; data = null; enData = null; paint(); load(); },
update: function (cx) { ctx = cx; load(); },
refresh: function () { load(); },
unmount: function () { alive = false; seq++; enSeq++; if (root && root.parentNode) root.parentNode.removeChild(root); if (enBox && enBox.parentNode) enBox.parentNode.removeChild(enBox); root = null; enBox = null; data = null; enData = null; }
});
return true;
}
if (!boot()) {
var tries = 0, iv = setInterval(function () { if (boot() || ++tries > 50) clearInterval(iv); }, 100);
}
})();
+30
View File
@@ -0,0 +1,30 @@
/* Egress page */
.eg-page { display: grid; gap: var(--grid-gap, 16px); min-width: 0; }
.eg-page .panel, .eg-kpis .card-metric { min-width: 0; }
.eg-wl-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 240px), 1fr)); gap: 12px; }
.eg-wl { min-width: 0; }
.eg-wl-head { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 8px; margin-bottom: 8px; }
.eg-wl-head .badge { white-space: normal; }
.eg-wl-name { margin: 0; font-size: 1rem; overflow-wrap: anywhere; }
.eg-wl-stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: 6px; margin: 0; }
.eg-wl-stats div { min-width: 0; }
.eg-wl-stats dd { margin: 0; font-size: 1.125rem; font-weight: 600; }
.eg-wl-stats dt { color: var(--ink-muted); font-size: .75rem; overflow-wrap: anywhere; }
.eg-warn { color: var(--danger); font-weight: 600; }
.eg-findings { list-style: none; margin: 0; padding: 0; display: grid; gap: 10px; }
.eg-f { border: 1px solid var(--line); border-left-width: 4px; border-radius: 6px; padding: 10px 12px; min-width: 0; }
.eg-sev-high { border-left-color: var(--danger); }
.eg-sev-medium { border-left-color: var(--warn); }
.eg-sev-low { border-left-color: var(--info); }
.eg-f-top { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; }
.eg-f p { margin: 6px 0 0; overflow-wrap: anywhere; }
.eg-f-why { color: var(--ink-muted); }
.eg-f-detail { font-size: .8125rem; }
.eg-scroll { max-height: 440px; overflow: auto; }
.eg-table { width: 100%; border-collapse: collapse; font-size: .875rem; }
.eg-table th, .eg-table td { padding: 5px var(--s-3, 10px); border-bottom: 1px solid var(--line); text-align: left; overflow-wrap: anywhere; vertical-align: top; }
.eg-table th { color: var(--ink-muted); font-weight: 500; position: sticky; top: 0; background: var(--surface-panel); }
.eg-table .num { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
.eg-scanwarn { margin-bottom: 10px; }
@media (max-width: 600px) { .eg-kpis .span-4 { grid-column: 1 / -1; } }
@media (max-width: 700px) { .eg-table { min-width: 560px; } }
+355
View File
@@ -0,0 +1,355 @@
/* Urutau - EGRESS page: what the workloads of your servers talk to on the
internet (outbound traffic). Beacons, scans, odd ports, known-bad
destinations, DNS bypass, new countries, and the summarised scans of the
authorised scanner. Data: /api/v1/egress. Log data is hostile: dynamic text
goes through textContent only. */
(function () {
'use strict';
var SEV = { high: 0, medium: 1, low: 2 };
var SEV_TONE = { high: 'danger', medium: 'warn', low: 'info' };
var KINDS = ['beacon', 'scan', 'port', 'bad_dst', 'dns_bypass', 'new_geo'];
var KIND_HELP = { beacon: 'term.beaconing', scan: 'term.fanout', port: 'term.stratum', bad_dst: 'term.c2', dns_bypass: 'term.dot', new_geo: 'term.new_geo' };
function boot() {
var U = window.Urutau;
if (!U || !U.registerPage) return false;
U.registerI18n({
en: {
'eg.title': 'Outbound traffic',
'eg.error': 'Could not load the outbound traffic data.',
'eg.retry': 'Try again',
'eg.disabled': 'Outbound traffic is not being watched',
'eg.disabled.sub': 'This page shows connections that leave your servers. To see them, add an outbound firewall rule on the server that logs new connections, and set the variable URUTAU_EGRESS so Urutau reads that log.',
'eg.lead.none': 'No outbound connections {range}',
'eg.lead.none.sub': 'Nothing left the watched workloads in this window.',
'eg.lead.ok': '{n} outbound connections {range}, nothing suspicious',
'eg.lead.ok.sub': 'No findings in this window. Authorised scans, if any, are summarised below.',
'eg.lead.bad': '{f} findings in {n} outbound connections {range}',
'eg.lead.bad.sub': '{h} high, {m} medium and {l} low severity. Start with the high ones.',
'eg.src': 'Log source: {state} · {lines} lines read · {bad} unreadable',
'eg.src.following': 'being followed',
'eg.src.waiting': 'waiting for the file',
'eg.src.missing': 'file not found',
'eg.src.error': 'error',
'eg.kpi.conns': 'Connections',
'eg.kpi.conns.sub': 'new outbound connections',
'eg.kpi.dsts': 'Destinations',
'eg.kpi.dsts.sub': 'different addresses reached',
'eg.kpi.find': 'Findings',
'eg.kpi.find.sub': '{h} high · {m} medium · {l} low',
'eg.workloads': 'Workloads',
'eg.workloads.hint': 'Each workload is a program or container that makes outbound connections.',
'eg.wl.conns': 'connections',
'eg.wl.dsts': 'destinations',
'eg.wl.ports': 'ports',
'eg.wl.findings': 'findings',
'eg.wl.suppressed': '{n} scan connections summarised',
'eg.role.scanner': 'authorised scans summarised',
'eg.role.app': 'application',
'eg.role.proxy': 'proxy',
'eg.role.database': 'database',
'eg.role.system': 'system',
'eg.timeline': 'Connections over time',
'eg.timeline.hint': 'Stacked by workload.',
'eg.findings': 'Findings',
'eg.findings.hint': 'Sorted by severity. Each one explains what the pattern usually means.',
'eg.findings.none': 'No findings in this window.',
'eg.sev.high': 'High',
'eg.sev.medium': 'Medium',
'eg.sev.low': 'Low',
'eg.kind.beacon': 'Regular conversation',
'eg.kind.scan': 'Mass connection attempts',
'eg.kind.port': 'Unusual port',
'eg.kind.bad_dst': 'Known-bad destination',
'eg.kind.dns_bypass': 'DNS outside the resolver',
'eg.kind.new_geo': 'New country',
'eg.why.beacon': 'The workload talks to the same destination at regular intervals, like a clock. This is the typical pattern of malware checking in with its controller.',
'eg.why.scan': 'The workload tried to connect to many different addresses in a short time. A server that scans the internet usually means it was taken over.',
'eg.why.port': 'Connection to a port used by mining pools or remote-control tools, which normal software on this server does not use.',
'eg.why.bad_dst': 'The destination is on a list of addresses known for malware or attacks. Nothing on your server should talk to it.',
'eg.why.dns_bypass': 'The workload asked for names directly from an outside DNS server instead of your resolver. Malware does this to hide what it looks up.',
'eg.why.new_geo': 'The workload connected to a country it had never reached before in this window. It may be harmless, but is worth a look.',
'eg.f.to': 'To',
'eg.f.count': '{n} connections',
'eg.f.interval': 'every {s} s (variation {j}%)',
'eg.f.first': 'first {t}',
'eg.f.last': 'last {t}',
'eg.f.host': 'server {h}',
'eg.dst': 'Top destinations',
'eg.dst.hint': 'Where the connections went.',
'eg.dst.none': 'No destinations in this window.',
'eg.col.ip': 'Address',
'eg.col.country': 'Country',
'eg.col.asn': 'Network (ASN)',
'eg.col.conns': 'Connections',
'eg.col.who': 'Workloads',
'eg.col.ports': 'Ports',
'eg.scan': 'Authorised scans',
'eg.scan.hint': 'Scans your own scanner runs on purpose. They are summarised here instead of raising findings.',
'eg.scan.none': 'No scan bursts in this window.',
'eg.scan.warn': 'A scan reached {n} known-bad destinations: check that the scanner is not aiming at the wrong targets.',
'eg.scan.targets': '{n} targets',
'eg.scan.nets': 'networks',
'eg.scan.ports': 'ports',
'eg.scan.conns': '{n} connections',
'eg.scan.when': '{a} to {b}',
'eg.col.who1': 'Workload',
'eg.col.when': 'When',
'eg.col.targets': 'Targets',
'eg.col.nets': 'Networks',
'eg.col.badhits': 'Bad destinations hit'
},
'pt-BR': {
'eg.title': 'Tráfego de saída',
'eg.error': 'Não foi possível carregar os dados de tráfego de saída.',
'eg.retry': 'Tentar de novo',
'eg.disabled': 'O tráfego de saída não está sendo monitorado',
'eg.disabled.sub': 'Esta página mostra as conexões que saem dos seus servidores. Para vê-las, crie no servidor uma regra de firewall de saída que registre as conexões novas e defina a variável URUTAU_EGRESS para o Urutau ler esse registro.',
'eg.lead.none': 'Nenhuma conexão de saída {range}',
'eg.lead.none.sub': 'Nada saiu dos workloads monitorados nesta janela.',
'eg.lead.ok': '{n} conexões de saída {range}, nada suspeito',
'eg.lead.ok.sub': 'Nenhum achado nesta janela. As varreduras autorizadas, se houver, aparecem resumidas abaixo.',
'eg.lead.bad': '{f} achados em {n} conexões de saída {range}',
'eg.lead.bad.sub': '{h} de gravidade alta, {m} média e {l} baixa. Comece pelos de gravidade alta.',
'eg.src': 'Origem do registro: {state} · {lines} linhas lidas · {bad} ilegíveis',
'eg.src.following': 'sendo acompanhado',
'eg.src.waiting': 'aguardando o arquivo',
'eg.src.missing': 'arquivo não encontrado',
'eg.src.error': 'erro',
'eg.kpi.conns': 'Conexões',
'eg.kpi.conns.sub': 'novas conexões de saída',
'eg.kpi.dsts': 'Destinos',
'eg.kpi.dsts.sub': 'endereços diferentes alcançados',
'eg.kpi.find': 'Achados',
'eg.kpi.find.sub': '{h} altos · {m} médios · {l} baixos',
'eg.workloads': 'Workloads',
'eg.workloads.hint': 'Cada workload é um programa ou contêiner que faz conexões de saída.',
'eg.wl.conns': 'conexões',
'eg.wl.dsts': 'destinos',
'eg.wl.ports': 'portas',
'eg.wl.findings': 'achados',
'eg.wl.suppressed': '{n} conexões de varredura resumidas',
'eg.role.scanner': 'varreduras autorizadas resumidas',
'eg.role.app': 'aplicação',
'eg.role.proxy': 'proxy',
'eg.role.database': 'banco de dados',
'eg.role.system': 'sistema',
'eg.timeline': 'Conexões ao longo do tempo',
'eg.timeline.hint': 'Empilhadas por workload.',
'eg.findings': 'Achados',
'eg.findings.hint': 'Ordenados por gravidade. Cada um explica o que o padrão costuma significar.',
'eg.findings.none': 'Nenhum achado nesta janela.',
'eg.sev.high': 'Alta',
'eg.sev.medium': 'Média',
'eg.sev.low': 'Baixa',
'eg.kind.beacon': 'Conversa em intervalos regulares',
'eg.kind.scan': 'Tentativas de conexão em massa',
'eg.kind.port': 'Porta incomum',
'eg.kind.bad_dst': 'Destino sabidamente ruim',
'eg.kind.dns_bypass': 'DNS fora do resolvedor',
'eg.kind.new_geo': 'País novo',
'eg.why.beacon': 'O workload fala com o mesmo destino em intervalos regulares, como um relógio. É o padrão típico de um malware avisando seu controlador que está vivo.',
'eg.why.scan': 'O workload tentou conectar a muitos endereços diferentes em pouco tempo. Um servidor que varre a internet costuma ter sido invadido.',
'eg.why.port': 'Conexão a uma porta usada por mineração de criptomoeda ou ferramentas de controle remoto, que os programas normais deste servidor não usam.',
'eg.why.bad_dst': 'O destino está numa lista de endereços conhecidos por malware ou ataques. Nada no seu servidor deveria falar com ele.',
'eg.why.dns_bypass': 'O workload consultou nomes direto num servidor DNS de fora, em vez do seu resolvedor. Malware faz isso para esconder o que procura.',
'eg.why.new_geo': 'O workload conectou a um país que ainda não tinha alcançado nesta janela. Pode ser inofensivo, mas vale olhar.',
'eg.f.to': 'Para',
'eg.f.count': '{n} conexões',
'eg.f.interval': 'a cada {s} s (variação {j}%)',
'eg.f.first': 'primeira {t}',
'eg.f.last': 'última {t}',
'eg.f.host': 'servidor {h}',
'eg.dst': 'Principais destinos',
'eg.dst.hint': 'Para onde foram as conexões.',
'eg.dst.none': 'Nenhum destino nesta janela.',
'eg.col.ip': 'Endereço',
'eg.col.country': 'País',
'eg.col.asn': 'Rede (ASN)',
'eg.col.conns': 'Conexões',
'eg.col.who': 'Workloads',
'eg.col.ports': 'Portas',
'eg.scan': 'Varreduras autorizadas',
'eg.scan.hint': 'Varreduras que o seu próprio scanner faz de propósito. Aparecem resumidas aqui em vez de gerar achados.',
'eg.scan.none': 'Nenhuma rajada de varredura nesta janela.',
'eg.scan.warn': 'Uma varredura atingiu {n} destinos sabidamente ruins: confira se o scanner não está mirando os alvos errados.',
'eg.scan.targets': '{n} alvos',
'eg.scan.nets': 'redes',
'eg.scan.ports': 'portas',
'eg.scan.conns': '{n} conexões',
'eg.scan.when': '{a} a {b}',
'eg.col.who1': 'Workload',
'eg.col.when': 'Quando',
'eg.col.targets': 'Alvos',
'eg.col.nets': 'Redes',
'eg.col.badhits': 'Destinos ruins atingidos'
}
});
var el = U.el, t = U.t, nf = U.fmt.num;
var root = null, seq = 0, alive = false, ctx = null, data = null, failed = false;
function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); }
function tbl(cols, rows) {
var tb = el('tbody');
rows.forEach(function (r) { tb.appendChild(el('tr', null, r.map(function (c, i) { return el('td', { class: cols[i].cls || '' }, c); }))); });
return el('div', { class: 'eg-scroll' }, el('table', { class: 'eg-table' },
el('thead', null, el('tr', null, cols.map(function (c) { return el('th', { class: c.cls || '' }, c.label); }))), tb));
}
function ipLink(ip) { return el('a', { href: U.href('ip', [ip]), class: 'mono' }, ip); }
function when(ts) { return ts ? U.fmt.clock(ts) : '-'; }
function help(node, key) { if (U.help) U.help(node, key); return node; }
function roleLabel(r) { var k = 'eg.role.' + r; return t(k) !== k ? t(k) : (r || '-'); }
function list(a) { return (a || []).join(', ') || '-'; }
function workloadCard(w, multi) {
var scanner = w.role === 'scanner';
var h = el('h3', { class: 'eg-wl-name' }, w.name);
var head = el('div', { class: 'eg-wl-head' }, h);
if (w.role) {
var b = U.ui.badge(roleLabel(w.role), scanner ? 'info' : 'neutral');
head.appendChild(b);
if (scanner) help(head, 'term.authorized_scanner');
}
var stats = el('dl', { class: 'eg-wl-stats' });
[['conns', w.conns], ['dsts', w.dsts], ['ports', w.ports], ['findings', w.findings]].forEach(function (p) {
stats.appendChild(el('div', null, el('dd', { class: 'num' + (p[0] === 'findings' && p[1] ? ' eg-warn' : '') }, nf(p[1] || 0)), el('dt', null, t('eg.wl.' + p[0]))));
});
var card = el('div', { class: 'card-metric eg-wl' }, head, stats);
if (w.suppressed_scan_conns) card.appendChild(el('p', { class: 'cm-sub' }, t('eg.wl.suppressed', { n: nf(w.suppressed_scan_conns) })));
if (multi && w.host) card.appendChild(el('p', { class: 'cm-sub' }, t('eg.f.host', { h: w.host })));
return card;
}
function findingNode(f, multi) {
var kind = KINDS.indexOf(f.kind) >= 0 ? f.kind : null;
var sev = SEV[f.severity] !== undefined ? f.severity : 'low';
var title = el('strong', { class: 'eg-f-title' }, kind ? t('eg.kind.' + kind) : String(f.kind || '-'));
if (kind) help(title, KIND_HELP[kind]);
var top = el('div', { class: 'eg-f-top' }, U.ui.badge(t('eg.sev.' + sev), SEV_TONE[sev]), title);
var bits = [];
bits.push(el('span', { class: 'mono' }, f.workload || '-'));
bits.push(' → ');
if (f.dst) bits.push(ipLink(f.dst));
if (f.dport) bits.push(el('span', { class: 'mono' }, ':' + f.dport + (f.proto ? '/' + f.proto : '')));
var meta = [];
if (f.count) meta.push(t('eg.f.count', { n: nf(f.count) }));
if (f.interval_s) meta.push(t('eg.f.interval', { s: Math.round(f.interval_s * 10) / 10, j: Math.round((f.jitter || 0) * 100) }));
if (f.first) meta.push(t('eg.f.first', { t: when(f.first) }));
if (f.last) meta.push(t('eg.f.last', { t: when(f.last) }));
if (multi && f.host) meta.push(t('eg.f.host', { h: f.host }));
var li = el('li', { class: 'eg-f eg-sev-' + sev }, top, el('p', { class: 'eg-f-line' }, bits));
if (kind) li.appendChild(el('p', { class: 'eg-f-why' }, t('eg.why.' + kind)));
if (f.detail) li.appendChild(el('p', { class: 'eg-f-detail mono' }, f.detail));
if (meta.length) li.appendChild(el('p', { class: 'hint eg-f-meta' }, meta.join(' · ')));
return li;
}
function paint() {
if (!root) return;
clear(root);
if (!data) { root.appendChild(el('div', { class: 'skeleton', style: { height: '8rem' } })); return; }
if (!data.enabled) { root.appendChild(U.ui.empty(t('eg.disabled'), t('eg.disabled.sub'))); return; }
var d = data, range = U.rangeLabel({ inline: true });
var wls = d.workloads || [], fnd = (d.findings || []).slice();
fnd.sort(function (a, b) { var x = SEV[a.severity], y = SEV[b.severity]; x = x === undefined ? 3 : x; y = y === undefined ? 3 : y; return x - y || (b.count || 0) - (a.count || 0); });
var conns = 0, nsev = { high: 0, medium: 0, low: 0 };
wls.forEach(function (w) { conns += w.conns || 0; });
fnd.forEach(function (f) { if (nsev[f.severity] !== undefined) nsev[f.severity]++; });
var hosts = {};
wls.forEach(function (w) { if (w.host) hosts[w.host] = 1; });
fnd.forEach(function (f) { if (f.host) hosts[f.host] = 1; });
var multi = Object.keys(hosts).length > 1;
var dsts = d.top_dst || [];
if (!conns && !fnd.length) root.appendChild(U.ui.lead(t('eg.lead.none', { range: range }), t('eg.lead.none.sub'), 'neutral'));
else if (!fnd.length) root.appendChild(U.ui.lead(t('eg.lead.ok', { n: nf(conns), range: range }), t('eg.lead.ok.sub'), 'ok'));
else root.appendChild(U.ui.lead(t('eg.lead.bad', { f: nf(fnd.length), n: nf(conns), range: range }), t('eg.lead.bad.sub', { h: nsev.high, m: nsev.medium, l: nsev.low }), nsev.high ? 'danger' : 'ok'));
var src = d.source || {};
var sk = 'eg.src.' + src.state;
root.appendChild(el('p', { class: 'hint' }, t('eg.src', { state: t(sk) !== sk ? t(sk) : (src.state || '-'), lines: nf(src.lines || 0), bad: nf(src.malformed || 0) })));
var kp = el('div', { class: 'grid-12 eg-kpis' });
function k(node) { node.classList.add('span-4'); kp.appendChild(node); }
k(U.ui.metric(t('eg.kpi.conns'), nf(conns), { sub: t('eg.kpi.conns.sub') }));
k(U.ui.metric(t('eg.kpi.dsts'), nf(dsts.length), { sub: t('eg.kpi.dsts.sub') }));
k(U.ui.metric(t('eg.kpi.find'), nf(fnd.length), { sub: t('eg.kpi.find.sub', { h: nsev.high, m: nsev.medium, l: nsev.low }), tone: nsev.high ? 'danger' : fnd.length ? 'warn' : 'ok' }));
root.appendChild(kp);
var grid = el('div', { class: 'grid-12' });
if (wls.length) {
var wp = U.ui.panel({ title: t('eg.workloads'), hint: t('eg.workloads.hint'), cls: 'span-12', help: 'term.workload' });
var wg = el('div', { class: 'eg-wl-grid' });
wls.forEach(function (w) { wg.appendChild(workloadCard(w, multi)); });
wp.body.appendChild(wg);
grid.appendChild(wp);
}
var tl = d.timeline || {}, ser = tl.series || {}, names = Object.keys(ser);
var tp = U.ui.panel({ title: t('eg.timeline'), hint: t('eg.timeline.hint'), cls: 'span-12', variant: 'chart' });
if (U.charts && U.charts.stackedArea && names.length) tp.body.appendChild(U.charts.stackedArea(names.map(function (n) { return { key: n, label: n, values: ser[n] }; }), tl.step || 3600, { start: tl.start || 0, title: t('eg.timeline') }));
else tp.body.appendChild(U.ui.empty(t('eg.lead.none', { range: range })));
grid.appendChild(tp);
var fp = U.ui.panel({ title: t('eg.findings'), hint: t('eg.findings.hint'), cls: 'span-12' });
if (!fnd.length) fp.body.appendChild(U.ui.empty(t('eg.findings.none')));
else { var ul = el('ul', { class: 'eg-findings' }); fnd.forEach(function (f) { ul.appendChild(findingNode(f, multi)); }); fp.body.appendChild(ul); }
grid.appendChild(fp);
var dp = U.ui.panel({ title: t('eg.dst'), hint: t('eg.dst.hint'), cls: 'span-12', variant: 'list' });
if (!dsts.length) dp.body.appendChild(U.ui.empty(t('eg.dst.none')));
else dp.body.appendChild(tbl([{ label: t('eg.col.ip') }, { label: t('eg.col.country') }, { label: t('eg.col.asn') }, { label: t('eg.col.conns'), cls: 'num' }, { label: t('eg.col.who') }, { label: t('eg.col.ports') }],
dsts.map(function (x) {
return [ipLink(x.ip), (x.cc ? U.fmt.flag(x.cc) + ' ' + U.fmt.country(x.cc) : '-'), (x.asn || '') + (x.org ? ' ' + x.org : '') || '-', nf(x.conns || 0), list(x.workloads), list(x.ports)];
})));
grid.appendChild(dp);
var bursts = (d.scanner && d.scanner.bursts) || [];
var sp = U.ui.panel({ title: t('eg.scan'), hint: t('eg.scan.hint'), cls: 'span-12', variant: 'list', help: 'term.authorized_scanner' });
if (!bursts.length) sp.body.appendChild(U.ui.empty(t('eg.scan.none')));
else {
var bad = 0;
bursts.forEach(function (b) { bad += b.bad_dst_hits || 0; });
if (bad > 0) sp.body.appendChild(el('div', { class: 'state-error eg-scanwarn' }, el('strong', null, t('eg.scan.warn', { n: nf(bad) }))));
sp.body.appendChild(tbl([{ label: t('eg.col.who1') }, { label: t('eg.col.when') }, { label: t('eg.col.targets'), cls: 'num' }, { label: t('eg.col.nets') }, { label: t('eg.col.ports') }, { label: t('eg.col.conns'), cls: 'num' }, { label: t('eg.col.badhits'), cls: 'num' }],
bursts.map(function (b) {
return [b.workload || '-', t('eg.scan.when', { a: when(b.start), b: when(b.end) }), nf(b.targets || 0), list(b.nets), list(b.ports), nf(b.conns || 0),
el('span', { class: b.bad_dst_hits ? 'eg-warn' : '' }, nf(b.bad_dst_hits || 0))];
})));
}
grid.appendChild(sp);
root.appendChild(grid);
}
function load() {
var my = ++seq;
var p = Object.assign({}, U.rangeParams());
if (ctx && ctx.host && ctx.host !== 'all') p.host = ctx.host;
U.api('/api/v1/egress', p).then(function (d) {
if (!alive || my !== seq) return;
data = d; paint();
}).catch(function () {
if (!alive || my !== seq || data) return;
clear(root);
var b = el('button', { type: 'button', class: 'btn' }, t('eg.retry'));
b.addEventListener('click', load);
root.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('eg.error')), b));
});
}
U.registerPage({
id: 'egress', group: 'investigate', titleKey: 'eg.title',
icon: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><rect x="3" y="5" width="12" height="14" rx="2"/><path d="M11 12h10"/><path d="M17 8l4 4-4 4"/></svg>',
mount: function (node, cx) { root = el('div', { class: 'eg-page' }); node.appendChild(root); ctx = cx; alive = true; data = null; paint(); load(); },
update: function (cx) { ctx = cx; load(); },
refresh: function () { load(); },
unmount: function () { alive = false; seq++; if (root && root.parentNode) root.parentNode.removeChild(root); root = null; data = null; }
});
return true;
}
if (!boot()) {
var tries = 0, iv = setInterval(function () { if (boot() || ++tries > 50) clearInterval(iv); }, 100);
}
})();
+10
View File
@@ -0,0 +1,10 @@
/* Errors page */
.hl-scroll { max-height: 420px; overflow: auto; }
.hl-table { width: 100%; border-collapse: collapse; font-size: .875rem; }
.hl-table th, .hl-table td { padding: 5px var(--s-3); border-bottom: 1px solid var(--line); text-align: left; overflow-wrap: anywhere; }
.hl-table th { color: var(--ink-muted); font-weight: 500; position: sticky; top: 0; background: var(--surface-panel); }
.hl-table .num { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
.hl-page .panel { min-width: 0; }
@media (max-width: 900px) { .hl-page .span-6, { grid-column: 1 / -1; } }
.hl-helps { display: flex; flex-wrap: wrap; gap: 6px 12px; margin-top: var(--s-3, 10px); font-size: .8125rem; color: var(--ink-muted); }
.hl-help { display: inline-flex; align-items: center; gap: 4px; }
+146
View File
@@ -0,0 +1,146 @@
/* Urutau - page ERRORS ("where do the errors come from"): splits every 4xx/5xx into
frustrated attacks, proxy trouble, real application errors, bots and client mistakes.
Data: /api/v1/errors. Log data is hostile: textContent only. */
(function () {
'use strict';
var U = window.Urutau;
if (!U || !U.registerPage) return;
var el = U.el, t = U.t;
var ORDER = ['app', 'proxy', 'blocked', 'attack', 'bot', 'client_broken', 'client_auth', 'client_other'];
var COLOR = { app: '--danger', proxy: '--warn', blocked: '--info', attack: '--cat-exploit', bot: '--viz-6', client_broken: '--viz-2', client_auth: '--viz-4', client_other: '--ink-muted' };
U.registerI18n({
en: {
'hl.er.title': 'Where errors come from',
'hl.er.lead': '{n} errors; {atk} frustrated attacks, {app} real application errors',
'hl.er.lead.body': 'Of {req} requests {range}, {proxy} of the errors are proxy trouble and {bot} come from crawlers. Server error rate (application + proxy over legitimate requests, client cancellations excluded): {rate}. Data from this instance ({inst}) only.',
'hl.er.lead.empty': 'No errors recorded',
'hl.er.lead.empty.body': 'No 4xx or 5xx answers {range}, or the log has no origin fields yet.',
'hl.cls.app': 'Application', 'hl.cls.proxy': 'Proxy / network', 'hl.cls.blocked': 'Blocked by rule', 'hl.cls.attack': 'Attack',
'hl.cls.bot': 'Crawlers', 'hl.cls.client_broken': 'Broken links', 'hl.cls.client_auth': 'Authentication', 'hl.cls.client_other': 'Other client errors',
'hl.er.donut': 'Error classes', 'hl.er.donut.hint': 'Application and proxy errors are yours to fix; attacks and blocks mean the defences worked.',
'hl.er.total': 'errors',
'hl.er.time': 'Errors over time', 'hl.er.time.hint': 'Hourly, stacked by class.',
'hl.er.heat': 'Application errors by service and hour', 'hl.er.heat.hint': 'Only answers the backend itself failed (5xx from the origin).',
'hl.er.broken': 'Broken links', 'hl.er.broken.hint': 'Pages that answered 404 to a visitor who clicked a link. Fix the link or add a redirect.',
'hl.er.routes': 'Routes with the most errors', 'hl.er.routes.hint': 'Method and path (ids folded), by service and class.',
'hl.er.col.path': 'Missing path', 'hl.er.col.ref': 'Came from', 'hl.er.col.n': 'Hits', 'hl.er.col.last': 'Last',
'hl.er.col.svc': 'Service', 'hl.er.col.route': 'Route', 'hl.er.col.class': 'Class',
'hl.er.err': 'Could not load the error breakdown.', 'hl.er.retry': 'Try again',
'hl.er.empty': 'Nothing to show for this range.'
},
'pt-BR': {
'hl.er.title': 'De onde vêm os erros',
'hl.er.lead': '{n} erros; {atk} ataques frustrados, {app} erros reais de aplicação',
'hl.er.lead.body': 'De {req} requisições {range}, {proxy} dos erros são problema de proxy e {bot} vêm de rastreadores. Taxa de erro do servidor (aplicação + proxy sobre as requisições legítimas, sem cancelamentos do cliente): {rate}. Dados só desta instância ({inst}).',
'hl.er.lead.empty': 'Nenhum erro registrado',
'hl.er.lead.empty.body': 'Nenhuma resposta 4xx ou 5xx {range}, ou o log ainda não tem os campos de origem.',
'hl.cls.app': 'Aplicação', 'hl.cls.proxy': 'Proxy / rede', 'hl.cls.blocked': 'Bloqueado por regra', 'hl.cls.attack': 'Ataque',
'hl.cls.bot': 'Rastreadores', 'hl.cls.client_broken': 'Links quebrados', 'hl.cls.client_auth': 'Autenticação', 'hl.cls.client_other': 'Outros erros do cliente',
'hl.er.donut': 'Classes de erro', 'hl.er.donut.hint': 'Erros de aplicação e de proxy são seus para corrigir; ataques e bloqueios mostram que a defesa funcionou.',
'hl.er.total': 'erros',
'hl.er.time': 'Erros no tempo', 'hl.er.time.hint': 'Por hora, empilhados por classe.',
'hl.er.heat': 'Erros de aplicação por serviço e hora', 'hl.er.heat.hint': 'Só respostas em que o próprio backend falhou (5xx da origem).',
'hl.er.broken': 'Links quebrados', 'hl.er.broken.hint': 'Páginas que deram 404 para quem clicou num link. Corrija o link ou crie um redirecionamento.',
'hl.er.routes': 'Rotas com mais erros', 'hl.er.routes.hint': 'Método e caminho (ids agrupados), por serviço e classe.',
'hl.er.col.path': 'Caminho ausente', 'hl.er.col.ref': 'Veio de', 'hl.er.col.n': 'Acessos', 'hl.er.col.last': 'Último',
'hl.er.col.svc': 'Serviço', 'hl.er.col.route': 'Rota', 'hl.er.col.class': 'Classe',
'hl.er.err': 'Não foi possível carregar o detalhamento dos erros.', 'hl.er.retry': 'Tentar de novo',
'hl.er.empty': 'Nada para mostrar neste período.'
}
});
function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); }
function pctOf(a, b) { return b > 0 ? U.fmt.pct(a / b) : '0%'; }
function table(cols, rows) {
var tb = el('tbody');
rows.forEach(function (r) { tb.appendChild(el('tr', null, r.map(function (c, i) { return el('td', { class: cols[i].cls || '' }, c); }))); });
return el('div', { class: 'hl-scroll' }, el('table', { class: 'hl-table' },
el('thead', null, el('tr', null, cols.map(function (c) { return el('th', { class: c.cls || '' }, c.label); }))), tb));
}
function clock(ts) { return U.fmt.clock ? U.fmt.clock(ts) : String(ts); }
var inst = null;
function create(root, ctx) {
var seq = 0, alive = true, data = null, c = ctx;
var grid = el('div', { class: 'grid-12 hl-page' });
var lead = el('div', { class: 'span-12' });
var pd = U.ui.panel({ title: t('hl.er.donut'), hint: t('hl.er.donut.hint'), loading: true, cls: 'span-4' });
var pt = U.ui.panel({ title: t('hl.er.time'), hint: t('hl.er.time.hint'), variant: 'chart', loading: true, cls: 'span-8' });
var ph = U.ui.panel({ title: t('hl.er.heat'), hint: t('hl.er.heat.hint'), variant: 'chart', loading: true, cls: 'span-12' });
var pb = U.ui.panel({ title: t('hl.er.broken'), hint: t('hl.er.broken.hint'), variant: 'list', loading: true, cls: 'span-6' });
var pr = U.ui.panel({ title: t('hl.er.routes'), hint: t('hl.er.routes.hint'), variant: 'list', loading: true, cls: 'span-6' });
[lead, pd, pt, ph, pb, pr].forEach(function (n) { grid.appendChild(n); });
root.appendChild(grid);
function chart(fn, args, host) {
if (U.charts && U.charts[fn]) host.appendChild(U.charts[fn].apply(null, args));
else host.appendChild(U.ui.empty(t('hl.er.empty')));
}
function paint() {
clear(lead); [pd, pt, ph, pb, pr].forEach(function (p) { clear(p.body); });
if (!data) return;
var d = data, cl = d.classes || {}, range = U.rangeLabel({ inline: true });
if (!d.errors) {
lead.appendChild(U.ui.lead(t('hl.er.lead.empty'), t('hl.er.lead.empty.body', { range: range }), 'neutral'));
[pd, pt, ph, pb, pr].forEach(function (p) { p.body.appendChild(U.ui.empty(t('hl.er.empty'))); });
return;
}
lead.appendChild(U.ui.lead(t('hl.er.lead', { n: U.fmt.num(d.errors), atk: pctOf(cl.attack, d.errors), app: pctOf(cl.app, d.errors) }),
t('hl.er.lead.body', { req: U.fmt.num(d.requests), range: range, proxy: pctOf(cl.proxy, d.errors), bot: pctOf(cl.bot, d.errors), rate: U.fmt.pct(d.app_error_rate || 0), inst: d.instance || '' }),
(cl.app || 0) > (cl.attack || 0) ? 'warn' : 'neutral'));
var main = ['app', 'proxy', 'blocked', 'attack', 'bot'].map(function (k) { return { key: k, label: t('hl.cls.' + k), value: cl[k] || 0 }; });
main.push({ key: 'client', label: t('hl.cls.client_other'), value: cl.client || 0 });
chart('donut', [main, { title: t('hl.er.donut'), centerLabel: t('hl.er.total') }], pd.body);
if (U.help && U.glossary) {
var lis = pd.body.querySelectorAll('.vz-legend li');
['app', 'proxy', 'blocked', 'attack', 'bot', 'client'].forEach(function (k, i) {
if (lis[i] && U.glossary.has('term.error_class.' + k)) U.help(lis[i], 'term.error_class.' + k);
});
}
var series = ORDER.map(function (k) { return { key: k, label: t('hl.cls.' + k), values: (d.timeline.series[k] || []) }; });
chart('stackedArea', [series, d.timeline.step, { start: d.timeline.start, title: t('hl.er.time') }], pt.body);
var hm = d.heatmap || {};
if ((hm.svcs || []).length && (hm.hours || []).length) {
var xl = hm.hours.map(function (h) { return new Date(h * 1000).getHours() + 'h'; });
var seen = {}, yl = hm.svcs.map(function (n) {
var b = String(n).split('.')[0].slice(0, 8) || n; seen[b] = (seen[b] || 0) + 1;
return seen[b] > 1 ? b + seen[b] : b;
});
chart('heatmap', [hm.err, xl, yl, { title: t('hl.er.heat') }], ph.body);
} else ph.body.appendChild(U.ui.empty(t('hl.er.empty')));
var br = d.broken || [];
if (U.help && U.glossary && U.glossary.has('term.broken_link')) U.help(pb.querySelector('h2'), 'term.broken_link');
if (br.length) pb.body.appendChild(table([{ label: t('hl.er.col.path'), cls: 'mono' }, { label: t('hl.er.col.ref'), cls: 'mono' }, { label: t('hl.er.col.n'), cls: 'num' }, { label: t('hl.er.col.last') }],
br.map(function (b) { return [b.path, b.ref, U.fmt.num(b.n), b.last ? U.fmt.ago(b.last) : '']; })));
else pb.body.appendChild(U.ui.empty(t('hl.er.empty')));
var tr = d.top_routes || [];
if (tr.length) pr.body.appendChild(table([{ label: t('hl.er.col.svc') }, { label: t('hl.er.col.route'), cls: 'mono' }, { label: t('hl.er.col.class') }, { label: t('hl.er.col.n'), cls: 'num' }],
tr.map(function (r) { return [r.svc, r.route, (/^(app|proxy|blocked|attack|bot)$/.test(r.class) ? t('hl.cls.' + r.class) : t('hl.cls.client_other')), U.fmt.num(r.n)]; })));
else pr.body.appendChild(U.ui.empty(t('hl.er.empty')));
}
function load() {
var my = ++seq;
var p = Object.assign({}, U.rangeParams());
if (c.host && c.host !== 'all') p.host = c.host;
if (c.domain && c.domain !== 'all') p.host = c.domain;
U.api('/api/v1/errors', p).then(function (r) { if (alive && my === seq) { data = r; paint(); } }, function () {
if (!alive || my !== seq || data) return;
clear(lead);
var b = el('button', { type: 'button', class: 'btn' }, t('hl.er.retry'));
b.addEventListener('click', load);
lead.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('hl.er.err')), b));
});
}
load();
return { update: function (cx) { c = cx; load(); }, destroy: function () { alive = false; seq++; clear(root); } };
}
U.registerPage({
id: 'errors', group: 'analyze', titleKey: 'hl.er.title',
icon: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M12 3l9 16H3z"/><path d="M12 10v4"/><path d="M12 17h.01"/></svg>',
mount: function (node, ctx) { if (inst) inst.destroy(); inst = create(node, ctx || {}); },
update: function (ctx) { if (inst) inst.update(ctx); },
unmount: function () { if (inst) { inst.destroy(); inst = null; } }
});
})();
+9
View File
@@ -0,0 +1,9 @@
/* Evolution page (shared helpers .an-* live here: this file loads with the page set) */
.an-page .an-muted { color: var(--ink-muted); margin: 0; }
.an-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 2px; }
.an-list li { display: flex; justify-content: space-between; align-items: baseline; gap: var(--s-3); padding: 4px 0; border-bottom: 1px solid var(--line); min-width: 0; }
.an-list li:last-child { border-bottom: 0; }
.an-list .an-k, .an-list a { overflow-wrap: anywhere; min-width: 0; }
.an-list .an-n { font-variant-numeric: tabular-nums; color: var(--ink-muted); white-space: nowrap; }
.an-list .an-bad { color: var(--danger); }
.an-list .an-good { color: var(--ok); }
+158
View File
@@ -0,0 +1,158 @@
/* Urutau - EVOLUCAO page: are we getting better or worse? Daily stacked area by
attack family, weekday x hour heatmap, families that appeared or vanished and
the change against the previous period. Data: /api/v1/evolution. Log data is
hostile: every string goes through textContent (Urutau.el). */
(function () {
'use strict';
var U = window.Urutau;
if (!U || !U.registerPage) return;
var el = U.el, t = U.t;
U.registerI18n({
en: {
'an.ev.title': 'Evolution',
'an.ev.lead.better': 'Getting better: {pct} fewer attacks',
'an.ev.lead.worse': 'Getting worse: {pct} more attacks',
'an.ev.lead.same': 'Holding steady against the previous period',
'an.ev.lead.none': 'No previous period to compare',
'an.ev.lead.body': '{n} malicious events {range}, against {prev} in the period before.',
'an.ev.area': 'Attacks per day, by family',
'an.ev.area.hint': 'The seven busiest families; the rest are grouped as "other".',
'an.ev.heat': 'When do they come? (UTC)',
'an.ev.heat.hint': 'Malicious events by weekday and hour of the day.',
'an.ev.new': 'Appeared',
'an.ev.new.hint': 'Families seen now that did not exist in the previous period.',
'an.ev.gone': 'Vanished',
'an.ev.gone.hint': 'Families of the previous period that did not come back.',
'an.ev.none': 'None',
'an.ev.nocmp': 'There is no previous period with events to compare against.',
'an.ev.other': 'other',
'an.ev.off': 'The event registry is off',
'an.ev.off.d': 'This analysis reads the event registry, which is not enabled on this instance.',
'an.ev.err': 'Could not load this analysis.',
'an.ev.retry': 'Try again'
},
'pt-BR': {
'an.ev.title': 'Evolução',
'an.ev.lead.better': 'Melhorando: {pct} menos ataques',
'an.ev.lead.worse': 'Piorando: {pct} mais ataques',
'an.ev.lead.same': 'Estável em relação ao período anterior',
'an.ev.lead.none': 'Sem período anterior para comparar',
'an.ev.lead.body': '{n} eventos maliciosos {range}, contra {prev} no período anterior.',
'an.ev.area': 'Ataques por dia, por família',
'an.ev.area.hint': 'As sete famílias mais ativas; as demais ficam em "outras".',
'an.ev.heat': 'Quando eles vêm? (UTC)',
'an.ev.heat.hint': 'Eventos maliciosos por dia da semana e hora do dia.',
'an.ev.new': 'Surgiram',
'an.ev.new.hint': 'Famílias vistas agora que não existiam no período anterior.',
'an.ev.gone': 'Sumiram',
'an.ev.gone.hint': 'Famílias do período anterior que não voltaram.',
'an.ev.none': 'Nenhuma',
'an.ev.nocmp': 'Não há período anterior com eventos para comparar.',
'an.ev.other': 'outras',
'an.ev.off': 'O registro de eventos está desligado',
'an.ev.off.d': 'Esta análise lê o registro de eventos, que não está ativo nesta instância.',
'an.ev.err': 'Não foi possível carregar esta análise.',
'an.ev.retry': 'Tentar de novo'
}
});
function tip(p, key) { var h2 = p.querySelector('.panel-h h2'); if (h2 && U.help) U.help(h2, key); return p; }
function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); }
function params(ctx) {
var p = Object.assign({}, U.rangeParams());
if (ctx && ctx.host && ctx.host !== 'all') p.host = ctx.host;
return p;
}
function famList(rows, tone) {
if (!rows || !rows.length) return el('p', { class: 'an-muted' }, t('an.ev.none'));
var ul = el('ul', { class: 'an-list' });
rows.slice(0, 10).forEach(function (r) {
ul.appendChild(el('li', null, el('span', { class: 'an-k mono' }, r.fam), el('span', { class: 'an-n an-' + tone }, U.fmt.num(r.n))));
});
return ul;
}
var inst = null;
function create(root, ctx) {
var seq = 0, alive = true, data = null, lang = ctx.lang, c = ctx;
var grid = el('div', { class: 'grid-12 an-page' });
var lead = el('div', { class: 'span-12' });
var area = U.ui.panel({ title: t('an.ev.area'), hint: t('an.ev.area.hint'), variant: 'chart', loading: true });
var heat = U.ui.panel({ title: t('an.ev.heat'), hint: t('an.ev.heat.hint'), loading: true });
var nw = U.ui.panel({ title: t('an.ev.new'), hint: t('an.ev.new.hint'), loading: true });
var gone = U.ui.panel({ title: t('an.ev.gone'), hint: t('an.ev.gone.hint'), loading: true });
tip(area, 'metric.attacks_per_hour_24h');
[lead, area, heat, nw, gone].forEach(function (n, i) { grid.appendChild(n); if (i) n.classList.add(i === 1 ? 'span-12' : i === 2 ? 'span-12' : 'span-6'); });
root.appendChild(grid);
function paint() {
clear(lead); [area, heat, nw, gone].forEach(function (p) { clear(p.body); });
if (!data.enabled) { lead.appendChild(U.ui.empty(t('an.ev.off'), t('an.ev.off.d'))); return; }
var d = data, pct = d.delta_pct, title, tone = 'neutral';
if (pct === null || pct === undefined) title = t('an.ev.lead.none');
else if (Math.abs(pct) < 5) title = t('an.ev.lead.same');
else if (pct < 0) { title = t('an.ev.lead.better', { pct: Math.abs(Math.round(pct)) + '%' }); tone = 'ok'; }
else { title = t('an.ev.lead.worse', { pct: Math.round(pct) + '%' }); tone = 'danger'; }
lead.appendChild(U.ui.lead(title, t('an.ev.lead.body', { n: U.fmt.num(d.total), range: U.rangeLabel({ inline: true }), prev: U.fmt.num(d.prev) }), tone));
// area: top 7 families + other
var tot = {};
d.days.forEach(function (x) { Object.keys(x.by_fam || {}).forEach(function (f) { tot[f] = (tot[f] || 0) + x.by_fam[f]; }); });
var top = Object.keys(tot).filter(function (f) { return f !== 'other'; }).sort(function (a, b) { return tot[b] - tot[a]; }).slice(0, 7);
var series = top.map(function (f) { return { key: f, label: f, values: d.days.map(function (x) { return (x.by_fam || {})[f] || 0; }) }; });
var rest = d.days.map(function (x) {
var s = 0; Object.keys(x.by_fam || {}).forEach(function (f) { if (top.indexOf(f) < 0) s += x.by_fam[f]; }); return s;
});
if (rest.some(function (v) { return v > 0; })) series.push({ key: 'other', label: t('an.ev.other'), values: rest });
var start = d.days.length ? Date.parse(d.days[0].d + 'T00:00:00Z') / 1000 : 0;
if (series.length && d.days.length >= 3) area.body.appendChild(U.charts.stackedArea(series, 86400, { start: start, title: t('an.ev.area') }));
else area.body.appendChild(U.ui.empty(t('charts.empty')));
// heatmap, Monday first
var order = [1, 2, 3, 4, 5, 6, 0], fmt = new Intl.DateTimeFormat(c.lang || undefined, { weekday: 'short', timeZone: 'UTC' });
var labels = order.map(function (w) { return fmt.format(new Date(Date.UTC(2023, 0, 1 + w))); });
var hours = []; for (var h = 0; h < 24; h++) hours.push(h % 3 === 0 ? String(h) : '');
heat.body.appendChild(U.charts.heatmap(order.map(function (w) { return d.hour_dow[w] || []; }), hours, labels, { title: t('an.ev.heat') }));
if (pct === null || pct === undefined) {
nw.body.appendChild(el('p', { class: 'an-muted' }, t('an.ev.nocmp')));
gone.body.appendChild(el('p', { class: 'an-muted' }, t('an.ev.nocmp')));
} else {
nw.body.appendChild(famList(d.new_families, 'bad'));
gone.body.appendChild(famList(d.gone_families, 'good'));
}
}
function load() {
var my = ++seq;
U.api('/api/v1/evolution', params(c)).then(function (r) {
if (!alive || my !== seq) return;
data = r; paint();
}, function () {
if (!alive || my !== seq || data) return;
clear(lead);
var b = el('button', { type: 'button', class: 'btn' }, t('an.ev.retry'));
b.addEventListener('click', load);
lead.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('an.ev.err')), b));
});
}
load();
return {
root: root,
lang: lang,
update: function (cx) { c = cx; load(); },
destroy: function () { alive = false; seq++; clear(root); }
};
}
U.registerPage({
id: 'evolution', group: 'analyze', titleKey: 'an.ev.title',
icon: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M3 17l5-5 4 4 8-9"/><path d="M15 7h5v5"/></svg>',
mount: function (el, ctx) { if (inst) inst.destroy(); inst = create(el, ctx || {}); },
update: function (ctx) {
ctx = ctx || {};
if (inst && ctx.lang !== inst.lang) { var r = inst.root; inst.destroy(); inst = create(r, ctx); } else if (inst) inst.update(ctx);
},
unmount: function () { if (inst) { inst.destroy(); inst = null; } }
});
})();
+424 -20
View File
@@ -240,14 +240,14 @@ window.URUTAU_I18N = {
'state.error': 'error',
'state.disabled': 'disabled',
'cat.ok': 'ok',
'cat.notfound': 'not found',
'cat.scanner': 'scanner',
'cat.exploit': 'exploit',
'cat.bruteforce': 'brute force',
'cat.ssh-fail': 'ssh fail',
'cat.ssh-probe': 'ssh probe',
'cat.ssh-ok': 'ssh login',
'cat.ban': 'ban',
'cat.notfound': 'Nonexistent page (404)',
'cat.scanner': 'Vulnerability scan',
'cat.exploit': 'Exploit attempt',
'cat.bruteforce': 'Brute force (login)',
'cat.ssh-fail': 'Failed SSH login',
'cat.ssh-probe': 'SSH probe',
'cat.ssh-ok': 'Successful SSH login',
'cat.ban': 'Banned (fail2ban)',
'feed.unban': 'unban',
'ago.now': 'now',
'ago.s': '{n}s ago',
@@ -269,7 +269,6 @@ window.URUTAU_I18N = {
'traffic.domain': 'Domain',
'traffic.allDomains': 'All domains',
'traffic.timeline': 'Requests and page views',
'traffic.timeline.hint': 'Requests answered per time bucket; the darker bar is the share counted as page views.',
'traffic.requests': 'Requests',
'traffic.pages': 'Page views',
'traffic.visitors': 'Visitors',
@@ -281,7 +280,6 @@ window.URUTAU_I18N = {
'traffic.cities': 'Cities',
'traffic.browsers': 'Browsers',
'traffic.oses': 'Operating systems',
'traffic.devices': 'Devices',
'traffic.status': 'Status codes',
'traffic.privacy': 'Visitors are counted with a daily rotating hash kept in memory only. No visitor IP is stored.',
'traffic.sub.visitors': 'distinct, hash per day',
@@ -299,6 +297,210 @@ window.URUTAU_I18N = {
'device.bot': 'bot',
'device.tool': 'tool',
'device.unknown': 'unknown',
'charts.empty': 'Nothing to chart in this slice.',
'charts.total': 'Total',
'charts.item': 'Item',
'charts.value': 'Value',
'nav.group.monitor': 'Monitor',
'nav.group.investigate': 'Investigate',
'nav.group.analyze': 'Analyze',
'nav.group.operate': 'Operate',
'nav.group.reports': 'Reports',
'traffic.client': 'Client type',
'traffic.client.hint': 'Share of visitors by kind of client, from the user agent.',
'traffic.otherReq': 'Other requests',
'traffic.status.2xx': '2xx success',
'traffic.status.3xx': '3xx redirect',
'traffic.status.4xx': '4xx client error',
'traffic.status.5xx': '5xx server error',
'traffic.browsers.hint': 'Browser family of the visitors.',
'traffic.oses.hint': 'Operating system of the visitors.',
'traffic.status.hint': 'Answers by HTTP status class.',
'traffic.area.hint': 'Requests per time bucket, split into page views and other requests (assets, APIs, bots).',
'device.misc': 'other',
'ov.radar': 'Attack profile',
'ov.radar.hint': 'Share of each attack category among the attacks of each host.',
'help.label': 'Explain',
'help.do': 'What to do',
'cat.short.ok': 'ok',
'cat.short.notfound': '404',
'cat.short.scanner': 'scan',
'cat.short.exploit': 'exploit',
'cat.short.bruteforce': 'brute force',
'cat.short.ssh-fail': 'SSH fail',
'cat.short.ssh-probe': 'SSH probe',
'cat.short.ssh-ok': 'SSH login',
'cat.short.ban': 'ban',
'help.cat.ok': 'A normal request that was answered successfully (2xx/3xx).',
'help.cat.ok.do': 'Nothing to do. These are your regular visitors.',
'help.cat.notfound': 'The visitor asked for an address that does not exist on the site. Almost always a robot guessing paths such as /.env or /wp-admin; it got nothing. Many 404s from one IP means scanning.',
'help.cat.notfound.do': 'Ignore isolated cases. If one IP keeps doing it, check whether it is already banned or listed on the blocklist.',
'help.cat.scanner': 'Automated probing for known weak spots (admin panels, backup files, old plugins). It looks for doors, it does not break them.',
'help.cat.scanner.do': 'Make sure the probed software is not exposed or outdated. Block repeat offenders.',
'help.cat.exploit': 'A request carrying an attack payload (path traversal, injection, known CVE). It tries to break in.',
'help.cat.exploit.do': 'Check whether the answer was refused (4xx/5xx). If it was answered 2xx, treat it as an incident and review the application.',
'help.cat.bruteforce': 'Repeated login attempts guessing passwords on a web form.',
'help.cat.bruteforce.do': 'Enforce strong passwords and rate limits; block the IP.',
'help.cat.ssh-fail': 'A failed SSH login: wrong user, wrong password or wrong key.',
'help.cat.ssh-fail.do': 'Disable password login, keep fail2ban active and review accounts with many failures.',
'help.cat.ssh-probe': 'A connection to the SSH port that never tried to log in (banner grab, protocol or key exchange scan).',
'help.cat.ssh-probe.do': 'Usually harmless alone; look for the same IP also failing logins.',
'help.cat.ssh-ok': 'A successful SSH login.',
'help.cat.ssh-ok.do': 'If the user or the origin is unexpected, check the account at once.',
'help.cat.ban': 'fail2ban banned the address after repeated abuse (or lifted a ban).',
'help.cat.ban.do': 'Nothing to do; the ban is automatic. Check the blocklist if the same IP returns.',
'help.metric.requests': 'All requests answered by the monitored servers in the slice, including assets and bots.',
'help.metric.requests.do': 'Compare with malicious events to see how much of the traffic is hostile.',
'help.metric.malicious': 'Events classified as an attack: scanning, exploits, brute force, SSH failures and probes.',
'help.metric.malicious.do': 'A sudden rise means a campaign; open Threats to see which category.',
'help.metric.unique_ips': 'Different IP addresses seen in the slice.',
'help.metric.unique_ips.do': 'Many new addresses with the same behavior suggest a distributed campaign.',
'help.metric.attacks_per_hour_24h': 'Average number of attack events per hour over the last 24 hours, with the change against the 24 hours before.',
'help.metric.attacks_per_hour_24h.do': 'Above your normal baseline? Check Threats for the dominant category.',
'help.metric.moving_avg_7d_per_hour': 'Attacks per hour averaged over 7 days: your usual background noise.',
'help.metric.moving_avg_7d_per_hour.do': 'Use it as the baseline; only deviations from it deserve attention.',
'help.metric.trend': 'How the attack rate moves compared with the previous period (rising, steady, falling).',
'help.metric.trend.do': 'A rising trend with new attackers is the pattern of a fresh campaign.',
'help.metric.active_attackers_24h': 'Distinct attacking IPs active in the last 24 hours.',
'help.metric.active_attackers_24h.do': 'If it keeps growing, review the blocklist coverage.',
'help.metric.active_attackers_1h': 'Distinct attacking IPs active in the last hour.',
'help.metric.active_attackers_1h.do': 'A spike here is the earliest sign of a new wave.',
'help.metric.new_attackers': 'Attacking IPs seen for the first time in this period.',
'help.metric.new_attackers.do': 'Many new IPs in a short time point to rotating infrastructure.',
'help.metric.returning_rate': 'Share of attackers that had already been seen before.',
'help.metric.returning_rate.do': 'High values mean persistent attackers: banning them pays off.',
'help.metric.sessions_per_day': 'Average attack sessions per day. A session groups one IP’s requests separated by short pauses.',
'help.metric.sessions_per_day.do': 'Compare with active attackers to see whether each one is persistent.',
'help.metric.exposure_rate': 'Share of attacks answered with success (2xx) on a sensitive path. This is the only number that shows real exposure.',
'help.metric.exposure_rate.do': 'Anything above 0% needs a look: open the IP page and the exposure section.',
'help.metric.exploits_refused_pct': 'Share of exploit attempts that the server refused (4xx/5xx).',
'help.metric.exploits_refused_pct.do': 'Close to 100% is healthy. Lower means some payloads got through.',
'help.metric.ban_coverage': 'Share of attacking IPs that fail2ban has banned.',
'help.metric.ban_coverage.do': 'Low coverage means attackers are not being stopped: check jails and thresholds.',
'help.metric.blocklist_coverage': 'Share of hostile IPs that are present on the exported blocklist.',
'help.metric.blocklist_coverage.do': 'Import the blocklist into your firewall to close the gap.',
'help.metric.blocklist_leak': 'Hostile IPs that were on the blocklist and still got through.',
'help.metric.blocklist_leak.do': 'Check that the firewall really applies the list.',
'help.metric.mttb': 'Mean time to ban: how long an attacker acts before fail2ban bans it (median).',
'help.metric.mttb.do': 'High values mean the ban rules are too slow.',
'help.metric.visitors': 'Distinct visitors, counted with a daily rotating hash. No IP is stored.',
'help.metric.visitors.do': 'Compare with page views to estimate engagement.',
'help.metric.pages': 'Page views: successful answers to real page requests, without assets, bots or tools.',
'help.metric.pages.do': 'A big gap to requests is normal: images, scripts and APIs are not pages.',
'help.metric.bytes': 'Total data sent to clients.',
'help.metric.bytes.do': 'A jump without more page views can mean downloads or scraping.',
'help.metric.latency': 'Response time: p50 is the typical request, p95 is the slowest 5%.',
'help.metric.latency.do': 'A high p95 with a normal p50 points to a few slow endpoints.',
'help.metric.bots': 'Requests made by search and AI crawlers.',
'help.metric.bots.do': 'Unwanted crawlers can be limited in robots.txt or at the proxy.',
'help.term.session': 'A burst of requests from one IP separated from the next by a long pause. It turns a flood of log lines into a few readable episodes.',
'help.term.session.do': 'Open an IP to see its sessions in order.',
'help.term.stage.recon': 'Reconnaissance: the attacker maps what exists (404s, probing).',
'help.term.stage.recon.do': 'Low risk by itself.',
'help.term.stage.probe': 'Probing: it tests specific weak points.',
'help.term.stage.probe.do': 'Watch whether it moves on to exploitation.',
'help.term.stage.exploit': 'Exploitation: it sends attack payloads.',
'help.term.stage.exploit.do': 'Check whether they were refused.',
'help.term.stage.access': 'Access: it got a successful answer or logged in.',
'help.term.stage.access.do': 'Treat as an incident and review the system.',
'help.term.stage.banned': 'Banned: fail2ban stopped it.',
'help.term.stage.banned.do': 'Confirm it does not come back from another address.',
'help.term.campaign': 'Several IPs acting alike (same tools, same targets, same time): probably one operator.',
'help.term.campaign.do': 'Block the whole network range, not just one IP.',
'help.term.family': 'A group of similar requests, such as WordPress, version control files or SQL injection.',
'help.term.family.do': 'Use it to see what the attackers are after.',
'help.term.mitre': 'A standard name for an attack technique, from the MITRE ATT&CK catalogue (for example T1110 Brute Force).',
'help.term.mitre.do': 'Use the code to search for mitigations.',
'help.term.net_type': 'The kind of network that owns the address: hosting, residential, mobile, university, VPN.',
'help.term.net_type.do': 'Hosting and VPN origins are rarely real customers.',
'help.term.cadence': 'How regular the time between requests is. Machines are regular; people are not.',
'help.term.cadence.do': 'Very regular cadence confirms automation.',
'help.term.score': 'A number from 0 to 1000 that adds up the evidence against an IP. Suspicious from 10, hostile from 50 (a strong rule can also make it hostile).',
'help.term.score.do': 'Sort by score to decide what to block first.',
'help.term.level': 'The verdict derived from the score: low, suspicious or hostile.',
'help.term.level.do': 'Hostile IPs are the candidates for the blocklist.',
'help.term.fcrdns': 'Forward-confirmed reverse DNS: the IP’s name resolves back to the same IP. Real search engines pass; impostors do not.',
'help.term.fcrdns.do': 'A bot claiming to be Google without FCrDNS is fake.',
'help.term.exposure': 'A sensitive path (such as /.env) that answered successfully to an attacker. Real exposure, not just an attempt.',
'help.term.exposure.do': 'Remove or protect the resource and rotate any secret in it.',
'help.term.blocklist': 'The list of hostile IPs ready to import into a firewall. Only addresses with strong evidence are included.',
'help.term.blocklist.do': 'Export it as text or JSON and load it into your firewall or fail2ban.',
'help.term.peer': 'Another Urutau instance that shares its data with this one.',
'help.term.peer.do': 'If a peer is offline, its numbers are missing from the totals.',
'help.term.hub': 'The instance that gathers the data of its peers into one view.',
'help.term.hub.do': 'Open the hub to see all servers together.',
'help.term.client_type': 'The kind of client behind each request: desktop, mobile, tablet, bot, tool or unknown, from its user agent.',
'help.term.client_type.do': 'A large share of tools or unknown clients is worth checking.',
'help.term.status_class': 'HTTP answers grouped by first digit: 2xx success, 3xx redirect, 4xx client error, 5xx server error.',
'help.term.status_class.do': '5xx means a problem on your side; many 4xx is usually scanning.',
'help.term.attack_profile': 'The share of each attack category among all attacks of a host. Different shapes mean different kinds of pressure.',
'help.term.attack_profile.do': 'A host with a very different shape is being targeted differently.',
'help.term.categories': 'Attack categories: 404 = a page that does not exist (usually a robot guessing paths); scan = automated search for weak spots; brute force = password guessing on a login form; exploit = a request carrying an attack payload; SSH fail = a wrong SSH login; SSH probe = a connection to the SSH port with no login attempt; ban = fail2ban blocked the address.',
'help.term.categories.do': 'Hover or focus the category names in the legend for the detail of each one.',
'help.term.apdex': 'Apdex: a 0 to 1 satisfaction score from response times. Fast answers count fully, tolerable ones count half, slow ones count zero.',
'help.term.apdex.do': 'Below 0.85 means users feel slowness: look at the slowest endpoints.',
'help.term.slo': 'Service level objective: the target you promise, for example 99.9% of requests answered without a server error.',
'help.term.slo.do': 'Compare the real number with the target; the gap is the error budget.',
'help.term.error_budget': 'How many failures the SLO still allows in the period. When it reaches zero, the target is broken.',
'help.term.error_budget.do': 'If the budget burns fast, pause risky changes and fix the cause first.',
'help.term.second_firewall': 'A second line of defense: besides fail2ban, Urutau can itself block addresses it recognises as attackers, for a limited time.',
'help.term.second_firewall.do': 'Start in observe mode and compare its decisions with what you expect before turning it on.',
'help.term.observe_mode': 'Observation mode: Urutau decides who it would block and records it, but blocks nobody. A dry run.',
'help.term.observe_mode.do': 'Watch the decisions for a few days. If they look right, switch URUTAU_ENFORCE to on.',
'help.term.beaconing': 'Beaconing: a program that contacts the same destination at regular intervals, like a heartbeat. Normal software rarely does this so evenly; malware does, to ask for orders.',
'help.term.beaconing.do': 'Find out which workload it is and whether the destination is something you know. If not, isolate the workload.',
'help.term.c2': 'C2 (command and control): the server an attacker uses to give orders to infected machines. A connection to one means your machine may be taking orders.',
'help.term.c2.do': 'Treat it as an incident: isolate the workload, then investigate.',
'help.term.fanout': 'Fan-out or scan: one machine trying to connect to many different addresses in a short time, looking for something to attack.',
'help.term.fanout.do': 'If it is not your own scanner, the workload may have been compromised.',
'help.term.stratum': 'Stratum is the protocol of cryptocurrency mining pools. A server connecting to one is probably mining coins for someone else, on your electricity.',
'help.term.stratum.do': 'Look for unknown processes using lots of CPU and remove them.',
'help.term.dot': 'DoT (DNS over TLS): encrypted name lookups sent straight to an outside server, skipping your resolver. Malware uses it so you cannot see what it looks up.',
'help.term.dot.do': 'Confirm the workload is allowed to do this; block outbound port 853 if not.',
'help.term.workload': 'Workload: a program or container running on a server that makes its own network connections.',
'help.term.workload.do': 'Compare each workload with what it should be doing; a database talking to the internet is suspicious.',
'help.term.authorized_scanner': 'Authorised scanner: a workload you run on purpose to scan networks. Its mass connections are summarised instead of raised as alerts.',
'help.term.authorized_scanner.do': 'Make sure it only aims at targets you own or may test.',
'help.term.ban_ttl': 'Block duration (TTL): how long an address stays blocked before being released. Repeat offenders get longer blocks.',
'help.term.ban_ttl.do': 'Short blocks are safer against mistakes; long ones stop persistent attackers.',
'help.term.new_geo': 'New country: the workload connected to a country it had not reached before in this window.',
'help.term.new_geo.do': 'Check whether the destination is a service you use.',
'help.term.error_class.app': 'Errors caused by your own application (5xx coming from the app).',
'help.term.error_class.app.do': 'These are yours to fix: read the application logs.',
'help.term.error_class.proxy': 'Errors produced by the reverse proxy itself (bad gateway, timeout, no backend).',
'help.term.error_class.proxy.do': 'Check whether the backend is up and the proxy limits are right.',
'help.term.error_class.blocked': 'Requests refused on purpose by a rule (403, firewall or ban).',
'help.term.error_class.blocked.do': 'Usually healthy. Check only if real users are being blocked.',
'help.term.error_class.attack': 'Errors caused by attack traffic (probing for pages that do not exist, exploit attempts).',
'help.term.error_class.attack.do': 'Not a service problem. Do not count it against the SLO.',
'help.term.error_class.bot': 'Errors triggered by crawlers and automated clients that are not attacks.',
'help.term.error_class.bot.do': 'Fix broken links they find or limit them in robots.txt.',
'help.term.error_class.client': 'Errors caused by real visitors (a mistyped address, an expired link).',
'help.term.error_class.client.do': 'If frequent for one page, there may be a broken link.',
'help.term.error_class.unknown': 'Errors that could not be assigned to a cause.',
'help.term.error_class.unknown.do': 'Look at the examples to decide where they belong.',
'help.term.broken_link': 'An address that real visitors request and that answers 404. Usually a link that points to a page that was moved or removed.',
'help.term.broken_link.do': 'Fix the link or add a redirect to the new address.',
'help.term.gini': 'Gini index: how concentrated the attacks are, from 0 (spread evenly) to 1 (a few sources do almost everything).',
'help.term.gini.do': 'A high value means blocking a few addresses removes most of the noise.',
'help.term.pareto': 'Pareto curve: the share of all attacks produced by the top sources (the 80/20 view).',
'help.term.pareto.do': 'See how few IPs explain most of the attacks and block those first.',
'help.term.kaplan_meier': 'Survival curve (Kaplan-Meier): the share of attackers still active after a given time. It shows how long they persist.',
'help.term.kaplan_meier.do': 'A curve that stays high means persistent attackers: tighten the ban rules.',
'help.term.recidivism': 'The share of banned addresses that came back after the ban ended.',
'help.term.recidivism.do': 'High recidivism suggests longer bans or a permanent blocklist.',
'help.term.mitre_tactic': 'A tactic is the goal of an attacker in the MITRE ATT&CK catalogue (reconnaissance, initial access, credential access...). Techniques are the ways to reach it.',
'help.term.mitre_tactic.do': 'Use tactics to see which stage of an attack you are mostly seeing.',
'help.term.ttb': 'Time to ban: how long an attacker acted before being banned.',
'help.term.ttb.do': 'Long times mean the ban rules react too late.',
'help.term.leak': 'A leak is a request from an address that was already banned or blocklisted and still got an answer.',
'help.term.leak.do': 'Check that the firewall applies the blocklist at the right place.',
'help.term.integrity_gap': 'A period where the logs have a hole: no lines were read, so events may be missing.',
'help.term.integrity_gap.do': 'Check the log source and whether the file was rotated or the service stopped.',
'help.term.nonhuman': 'Non-human clients: bots, crawlers, tools and scripts, recognised by their user agent or behavior.',
'help.term.nonhuman.do': 'Not counted as visitors. Limit unwanted ones in robots.txt or at the proxy.',
'help.term.visit': 'A legitimate visit, shown anonymously on the live map: a real visitor, with no IP or identity stored.',
'help.term.visit.do': 'Nothing to do; it only shows where your audience comes from.',
'login.token': 'Access token',
'login.submit': 'Sign in',
'login.err.bad': 'Invalid token.',
@@ -532,14 +734,14 @@ window.URUTAU_I18N = {
'state.error': 'erro',
'state.disabled': 'desativada',
'cat.ok': 'ok',
'cat.notfound': 'não encontrado',
'cat.scanner': 'scanner',
'cat.exploit': 'exploit',
'cat.bruteforce': 'força bruta',
'cat.ssh-fail': 'falha ssh',
'cat.ssh-probe': 'sondagem ssh',
'cat.ssh-ok': 'login ssh',
'cat.ban': 'ban',
'cat.notfound': 'Página inexistente (404)',
'cat.scanner': 'Varredura de vulnerabilidades',
'cat.exploit': 'Tentativa de exploração',
'cat.bruteforce': 'Força bruta (login)',
'cat.ssh-fail': 'Login SSH falho',
'cat.ssh-probe': 'Sondagem SSH',
'cat.ssh-ok': 'Login SSH bem-sucedido',
'cat.ban': 'Banido (fail2ban)',
'feed.unban': 'desbanido',
'ago.now': 'agora',
'ago.s': 'há {n}s',
@@ -561,7 +763,6 @@ window.URUTAU_I18N = {
'traffic.domain': 'Domínio',
'traffic.allDomains': 'Todos os domínios',
'traffic.timeline': 'Requisições e páginas vistas',
'traffic.timeline.hint': 'Requisições atendidas por intervalo; a barra mais escura é a parcela contada como página vista.',
'traffic.requests': 'Requisições',
'traffic.pages': 'Páginas vistas',
'traffic.visitors': 'Visitantes',
@@ -573,7 +774,6 @@ window.URUTAU_I18N = {
'traffic.cities': 'Cidades',
'traffic.browsers': 'Navegadores',
'traffic.oses': 'Sistemas operacionais',
'traffic.devices': 'Dispositivos',
'traffic.status': 'Códigos de status',
'traffic.privacy': 'Visitantes são contados com um hash que muda todo dia e fica só na memória. Nenhum IP de visitante é guardado.',
'traffic.sub.visitors': 'distintos, hash diário',
@@ -591,6 +791,210 @@ window.URUTAU_I18N = {
'device.bot': 'bot',
'device.tool': 'ferramenta',
'device.unknown': 'desconhecido',
'charts.empty': 'Nada a exibir neste recorte.',
'charts.total': 'Total',
'charts.item': 'Item',
'charts.value': 'Valor',
'nav.group.monitor': 'Monitorar',
'nav.group.investigate': 'Investigar',
'nav.group.analyze': 'Analisar',
'nav.group.operate': 'Operar',
'nav.group.reports': 'Relatórios',
'traffic.client': 'Tipo de cliente',
'traffic.client.hint': 'Parcela dos visitantes por tipo de cliente, a partir do user-agent.',
'traffic.otherReq': 'Outras requisições',
'traffic.status.2xx': '2xx sucesso',
'traffic.status.3xx': '3xx redirecionamento',
'traffic.status.4xx': '4xx erro do cliente',
'traffic.status.5xx': '5xx erro do servidor',
'traffic.browsers.hint': 'Família de navegador dos visitantes.',
'traffic.oses.hint': 'Sistema operacional dos visitantes.',
'traffic.status.hint': 'Respostas por classe de status HTTP.',
'traffic.area.hint': 'Requisições por intervalo, divididas em páginas vistas e outras requisições (arquivos, APIs, robôs).',
'device.misc': 'outros',
'ov.radar': 'Perfil de ataque',
'ov.radar.hint': 'Parcela de cada categoria de ataque entre os ataques de cada host.',
'help.label': 'Explicar',
'help.do': 'O que fazer',
'cat.short.ok': 'ok',
'cat.short.notfound': '404',
'cat.short.scanner': 'varredura',
'cat.short.exploit': 'exploração',
'cat.short.bruteforce': 'força bruta',
'cat.short.ssh-fail': 'SSH falho',
'cat.short.ssh-probe': 'sondagem SSH',
'cat.short.ssh-ok': 'login SSH',
'cat.short.ban': 'ban',
'help.cat.ok': 'Um acesso normal que foi atendido com sucesso (2xx/3xx).',
'help.cat.ok.do': 'Nada a fazer. São os seus visitantes comuns.',
'help.cat.notfound': 'O visitante pediu um endereço que não existe no site. Quase sempre é um robô chutando caminhos como /.env ou /wp-admin; ele não obteve nada. Muitos 404 de um mesmo IP = varredura.',
'help.cat.notfound.do': 'Ignore casos isolados. Se um IP insiste, confira se já está banido ou na lista de bloqueio.',
'help.cat.scanner': 'Sondagem automática atrás de pontos fracos conhecidos (painéis, backups, plugins antigos). Procura portas, não as arromba.',
'help.cat.scanner.do': 'Confirme que o software sondado não está exposto nem desatualizado. Bloqueie reincidentes.',
'help.cat.exploit': 'Requisição com carga de ataque (travessia de caminho, injeção, CVE conhecida). Tenta invadir.',
'help.cat.exploit.do': 'Veja se a resposta foi recusada (4xx/5xx). Se foi 2xx, trate como incidente e revise a aplicação.',
'help.cat.bruteforce': 'Tentativas repetidas de login adivinhando senhas em um formulário web.',
'help.cat.bruteforce.do': 'Exija senhas fortes e limite de tentativas; bloqueie o IP.',
'help.cat.ssh-fail': 'Um login SSH que falhou: usuário, senha ou chave errados.',
'help.cat.ssh-fail.do': 'Desative login por senha, mantenha o fail2ban ativo e revise contas com muitas falhas.',
'help.cat.ssh-probe': 'Uma conexão à porta SSH que nunca tentou entrar (leitura de banner, varredura de protocolo ou troca de chaves).',
'help.cat.ssh-probe.do': 'Sozinha costuma ser inofensiva; veja se o mesmo IP também falha logins.',
'help.cat.ssh-ok': 'Um login SSH bem-sucedido.',
'help.cat.ssh-ok.do': 'Se o usuário ou a origem forem inesperados, verifique a conta imediatamente.',
'help.cat.ban': 'O fail2ban baniu o endereço após abusos repetidos (ou retirou o ban).',
'help.cat.ban.do': 'Nada a fazer; o ban é automático. Veja a lista de bloqueio se o mesmo IP voltar.',
'help.metric.requests': 'Todas as requisições atendidas pelos servidores monitorados no recorte, incluindo arquivos estáticos e robôs.',
'help.metric.requests.do': 'Compare com os eventos maliciosos para ver quanto do tráfego é hostil.',
'help.metric.malicious': 'Eventos classificados como ataque: varredura, exploração, força bruta, falhas e sondagens SSH.',
'help.metric.malicious.do': 'Uma alta repentina indica campanha; abra Ameaças para ver a categoria.',
'help.metric.unique_ips': 'Endereços IP diferentes vistos no recorte.',
'help.metric.unique_ips.do': 'Muitos endereços novos com o mesmo comportamento sugerem campanha distribuída.',
'help.metric.attacks_per_hour_24h': 'Média de eventos de ataque por hora nas últimas 24 horas, com a variação frente às 24 horas anteriores.',
'help.metric.attacks_per_hour_24h.do': 'Acima do seu normal? Veja em Ameaças qual categoria domina.',
'help.metric.moving_avg_7d_per_hour': 'Ataques por hora médios em 7 dias: o seu ruído de fundo habitual.',
'help.metric.moving_avg_7d_per_hour.do': 'Use como linha de base; só desvios dela merecem atenção.',
'help.metric.trend': 'Como a taxa de ataques se move frente ao período anterior (subindo, estável, caindo).',
'help.metric.trend.do': 'Tendência de alta com atacantes novos é o padrão de uma campanha recente.',
'help.metric.active_attackers_24h': 'IPs atacantes distintos ativos nas últimas 24 horas.',
'help.metric.active_attackers_24h.do': 'Se continuar crescendo, revise a cobertura da lista de bloqueio.',
'help.metric.active_attackers_1h': 'IPs atacantes distintos ativos na última hora.',
'help.metric.active_attackers_1h.do': 'Um pico aqui é o primeiro sinal de uma nova onda.',
'help.metric.new_attackers': 'IPs atacantes vistos pela primeira vez neste período.',
'help.metric.new_attackers.do': 'Muitos IPs novos em pouco tempo apontam para infraestrutura rotativa.',
'help.metric.returning_rate': 'Parcela dos atacantes que já tinham sido vistos antes.',
'help.metric.returning_rate.do': 'Valores altos indicam atacantes persistentes: banir compensa.',
'help.metric.sessions_per_day': 'Média de sessões de ataque por dia. Uma sessão agrupa as requisições de um IP separadas por pausas curtas.',
'help.metric.sessions_per_day.do': 'Compare com os atacantes ativos para ver se cada um é persistente.',
'help.metric.exposure_rate': 'Parcela dos ataques respondidos com sucesso (2xx) em um caminho sensível. É o único número que mostra exposição real.',
'help.metric.exposure_rate.do': 'Qualquer valor acima de 0% merece análise: abra a página do IP e a seção de exposição.',
'help.metric.exploits_refused_pct': 'Parcela das tentativas de exploração que o servidor recusou (4xx/5xx).',
'help.metric.exploits_refused_pct.do': 'Perto de 100% é saudável. Menos indica que alguma carga passou.',
'help.metric.ban_coverage': 'Parcela dos IPs atacantes que o fail2ban baniu.',
'help.metric.ban_coverage.do': 'Cobertura baixa significa atacantes não contidos: revise as jails e os limites.',
'help.metric.blocklist_coverage': 'Parcela dos IPs hostis que estão na lista de bloqueio exportada.',
'help.metric.blocklist_coverage.do': 'Importe a lista no firewall para fechar a diferença.',
'help.metric.blocklist_leak': 'IPs hostis que estavam na lista de bloqueio e ainda assim passaram.',
'help.metric.blocklist_leak.do': 'Verifique se o firewall realmente aplica a lista.',
'help.metric.mttb': 'Tempo médio até o ban: quanto o atacante age antes de ser banido (mediana).',
'help.metric.mttb.do': 'Valores altos indicam regras de ban lentas demais.',
'help.metric.visitors': 'Visitantes distintos, contados com um hash diário rotativo. Nenhum IP é guardado.',
'help.metric.visitors.do': 'Compare com as páginas vistas para estimar o engajamento.',
'help.metric.pages': 'Páginas vistas: respostas bem-sucedidas a pedidos de página reais, sem arquivos estáticos, robôs ou ferramentas.',
'help.metric.pages.do': 'Uma grande diferença para as requisições é normal: imagens, scripts e APIs não são páginas.',
'help.metric.bytes': 'Total de dados enviados aos clientes.',
'help.metric.bytes.do': 'Um salto sem mais páginas vistas pode indicar downloads ou raspagem.',
'help.metric.latency': 'Tempo de resposta: p50 é o pedido típico, p95 é o dos 5% mais lentos.',
'help.metric.latency.do': 'p95 alto com p50 normal aponta para poucos endpoints lentos.',
'help.metric.bots': 'Requisições feitas por robôs de busca e de IA.',
'help.metric.bots.do': 'Robôs indesejados podem ser limitados no robots.txt ou no proxy.',
'help.term.session': 'Uma rajada de requisições de um IP separada da próxima por uma pausa longa. Transforma milhares de linhas em poucos episódios legíveis.',
'help.term.session.do': 'Abra um IP para ver as sessões em ordem.',
'help.term.stage.recon': 'Reconhecimento: o atacante mapeia o que existe (404, sondagem).',
'help.term.stage.recon.do': 'Risco baixo isoladamente.',
'help.term.stage.probe': 'Sondagem: testa pontos fracos específicos.',
'help.term.stage.probe.do': 'Acompanhe se avança para a exploração.',
'help.term.stage.exploit': 'Exploração: envia cargas de ataque.',
'help.term.stage.exploit.do': 'Verifique se foram recusadas.',
'help.term.stage.access': 'Acesso: obteve resposta de sucesso ou entrou.',
'help.term.stage.access.do': 'Trate como incidente e revise o sistema.',
'help.term.stage.banned': 'Banido: o fail2ban o conteve.',
'help.term.stage.banned.do': 'Confirme que não volta por outro endereço.',
'help.term.campaign': 'Vários IPs agindo de forma parecida (mesmas ferramentas, alvos e horários): provavelmente um único operador.',
'help.term.campaign.do': 'Bloqueie a faixa de rede inteira, não só um IP.',
'help.term.family': 'Um grupo de requisições parecidas, como WordPress, arquivos de controle de versão ou injeção de SQL.',
'help.term.family.do': 'Use para ver o que os atacantes procuram.',
'help.term.mitre': 'Nome padronizado de uma técnica de ataque, do catálogo MITRE ATT&CK (por exemplo T1110 Força bruta).',
'help.term.mitre.do': 'Use o código para buscar mitigações.',
'help.term.net_type': 'O tipo de rede dona do endereço: hospedagem, residencial, móvel, universidade, VPN.',
'help.term.net_type.do': 'Origens de hospedagem e VPN raramente são clientes reais.',
'help.term.cadence': 'Quão regular é o intervalo entre as requisições. Máquinas são regulares; pessoas não.',
'help.term.cadence.do': 'Cadência muito regular confirma automação.',
'help.term.score': 'Número de 0 a 1000 que soma as evidências contra um IP. Suspeito a partir de 10, hostil a partir de 50 (uma regra forte também pode torná-lo hostil).',
'help.term.score.do': 'Ordene por pontuação para decidir o que bloquear primeiro.',
'help.term.level': 'O veredito derivado da pontuação: baixo, suspeito ou hostil.',
'help.term.level.do': 'IPs hostis são os candidatos à lista de bloqueio.',
'help.term.fcrdns': 'DNS reverso confirmado: o nome do IP resolve de volta para o mesmo IP. Buscadores reais passam; impostores não.',
'help.term.fcrdns.do': 'Um robô que diz ser Google sem FCrDNS é falso.',
'help.term.exposure': 'Um caminho sensível (como /.env) que respondeu com sucesso a um atacante. Exposição real, não apenas tentativa.',
'help.term.exposure.do': 'Remova ou proteja o recurso e troque qualquer segredo contido nele.',
'help.term.blocklist': 'A lista de IPs hostis pronta para importar em um firewall. Só entram endereços com evidência forte.',
'help.term.blocklist.do': 'Exporte em texto ou JSON e carregue no firewall ou no fail2ban.',
'help.term.peer': 'Outra instância do Urutau que compartilha seus dados com esta.',
'help.term.peer.do': 'Se um par está offline, os números dele faltam nos totais.',
'help.term.hub': 'A instância que reúne os dados dos pares em uma só visão.',
'help.term.hub.do': 'Abra o hub para ver todos os servidores juntos.',
'help.term.client_type': 'O tipo de cliente por trás de cada requisição: computador, celular, tablet, robô, ferramenta ou desconhecido, pelo user-agent.',
'help.term.client_type.do': 'Uma parcela grande de ferramentas ou desconhecidos merece verificação.',
'help.term.status_class': 'Respostas HTTP agrupadas pelo primeiro dígito: 2xx sucesso, 3xx redirecionamento, 4xx erro do cliente, 5xx erro do servidor.',
'help.term.status_class.do': '5xx indica problema do seu lado; muitos 4xx costumam ser varredura.',
'help.term.attack_profile': 'A parcela de cada categoria de ataque entre todos os ataques de um host. Formas diferentes indicam pressões diferentes.',
'help.term.attack_profile.do': 'Um host com forma muito diferente está sendo alvo de outro tipo de ataque.',
'help.term.categories': 'Categorias de ataque: 404 = página que não existe (em geral um robô chutando caminhos); varredura = busca automática por pontos fracos; força bruta = adivinhar senha em um login; exploração = requisição com carga de ataque; SSH falho = login SSH errado; sondagem SSH = conexão à porta SSH sem tentar entrar; ban = o fail2ban bloqueou o endereço.',
'help.term.categories.do': 'Passe o mouse ou o foco nos nomes da legenda para ver o detalhe de cada uma.',
'help.term.apdex': 'Apdex: nota de satisfação de 0 a 1 a partir dos tempos de resposta. Respostas rápidas valem tudo, toleráveis valem metade, lentas valem zero.',
'help.term.apdex.do': 'Abaixo de 0,85 os usuários sentem lentidão: veja os endpoints mais lentos.',
'help.term.slo': 'Objetivo de nível de serviço: a meta prometida, por exemplo 99,9% das requisições atendidas sem erro do servidor.',
'help.term.slo.do': 'Compare o número real com a meta; a diferença é o orçamento de erro.',
'help.term.error_budget': 'Quantas falhas o SLO ainda permite no período. Quando chega a zero, a meta foi quebrada.',
'help.term.error_budget.do': 'Se o orçamento queima rápido, pause mudanças arriscadas e corrija a causa primeiro.',
'help.term.second_firewall': 'Uma segunda linha de defesa: além do fail2ban, o próprio Urutau pode bloquear endereços que reconhece como atacantes, por tempo limitado.',
'help.term.second_firewall.do': 'Comece no modo observação e compare as decisões com o que você espera antes de ligar.',
'help.term.observe_mode': 'Modo observação: o Urutau decide quem bloquearia e registra, mas não bloqueia ninguém. Um ensaio.',
'help.term.observe_mode.do': 'Acompanhe as decisões por alguns dias. Se estiverem certas, mude URUTAU_ENFORCE para on.',
'help.term.beaconing': 'Beaconing (sinal periódico): um programa que contata o mesmo destino em intervalos regulares, como um batimento. Software normal raramente é tão regular; malware faz isso para pedir ordens.',
'help.term.beaconing.do': 'Descubra qual workload é e se você conhece o destino. Se não conhece, isole o workload.',
'help.term.c2': 'C2 (comando e controle): o servidor que um atacante usa para dar ordens às máquinas infectadas. Uma conexão com ele indica que a sua máquina pode estar recebendo ordens.',
'help.term.c2.do': 'Trate como incidente: isole o workload e investigue.',
'help.term.fanout': 'Fan-out ou varredura: uma máquina tentando conectar a muitos endereços diferentes em pouco tempo, procurando algo para atacar.',
'help.term.fanout.do': 'Se não for o seu scanner, o workload pode ter sido comprometido.',
'help.term.stratum': 'Stratum é o protocolo dos grupos de mineração de criptomoedas. Um servidor conectado a um deles provavelmente está minerando moedas para outra pessoa, gastando a sua energia.',
'help.term.stratum.do': 'Procure processos desconhecidos gastando muita CPU e remova-os.',
'help.term.dot': 'DoT (DNS sobre TLS): consultas de nomes criptografadas, enviadas direto a um servidor de fora, sem passar pelo seu resolvedor. Malware usa para você não ver o que ele consulta.',
'help.term.dot.do': 'Confirme se o workload tem permissão para isso; bloqueie a porta 853 de saída se não tiver.',
'help.term.workload': 'Workload (carga de trabalho): um programa ou contêiner rodando no servidor que faz as próprias conexões de rede.',
'help.term.workload.do': 'Compare cada workload com o que ele deveria fazer; um banco de dados falando com a internet é suspeito.',
'help.term.authorized_scanner': 'Scanner autorizado: um workload que você mantém de propósito para varrer redes. As conexões em massa dele são resumidas, em vez de virar alerta.',
'help.term.authorized_scanner.do': 'Garanta que ele só mire alvos seus ou que você pode testar.',
'help.term.ban_ttl': 'Duração do bloqueio (TTL): por quanto tempo o endereço fica bloqueado antes de ser liberado. Reincidentes recebem bloqueios mais longos.',
'help.term.ban_ttl.do': 'Bloqueios curtos são mais seguros contra enganos; longos barram atacantes persistentes.',
'help.term.new_geo': 'País novo: o workload conectou a um país que ainda não tinha alcançado nesta janela.',
'help.term.new_geo.do': 'Confira se o destino é um serviço que você usa.',
'help.term.error_class.app': 'Erros causados pela sua própria aplicação (5xx vindos do app).',
'help.term.error_class.app.do': 'São seus para corrigir: leia os logs da aplicação.',
'help.term.error_class.proxy': 'Erros produzidos pelo próprio proxy reverso (bad gateway, timeout, sem backend).',
'help.term.error_class.proxy.do': 'Veja se o backend está no ar e se os limites do proxy estão certos.',
'help.term.error_class.blocked': 'Requisições recusadas de propósito por uma regra (403, firewall ou ban).',
'help.term.error_class.blocked.do': 'Em geral é saudável. Verifique só se usuários reais estão sendo bloqueados.',
'help.term.error_class.attack': 'Erros causados por tráfego de ataque (sondagem de páginas inexistentes, tentativas de exploração).',
'help.term.error_class.attack.do': 'Não é problema do serviço. Não conte contra o SLO.',
'help.term.error_class.bot': 'Erros provocados por rastreadores e clientes automáticos que não são ataques.',
'help.term.error_class.bot.do': 'Corrija os links quebrados que eles acham ou limite-os no robots.txt.',
'help.term.error_class.client': 'Erros causados por visitantes reais (endereço digitado errado, link expirado).',
'help.term.error_class.client.do': 'Se forem frequentes em uma página, pode haver um link quebrado.',
'help.term.error_class.unknown': 'Erros que não puderam ser atribuídos a uma causa.',
'help.term.error_class.unknown.do': 'Veja os exemplos para decidir a que causa pertencem.',
'help.term.broken_link': 'Um endereço que visitantes reais pedem e que responde 404. Em geral um link apontando para uma página movida ou removida.',
'help.term.broken_link.do': 'Corrija o link ou crie um redirecionamento para o novo endereço.',
'help.term.gini': 'Índice de Gini: quanto os ataques estão concentrados, de 0 (bem espalhados) a 1 (poucas fontes fazem quase tudo).',
'help.term.gini.do': 'Valor alto significa que bloquear poucos endereços elimina a maior parte do ruído.',
'help.term.pareto': 'Curva de Pareto: a parcela de todos os ataques produzida pelas maiores fontes (visão 80/20).',
'help.term.pareto.do': 'Veja quantos poucos IPs explicam a maioria dos ataques e bloqueie esses primeiro.',
'help.term.kaplan_meier': 'Curva de sobrevivência (Kaplan-Meier): a parcela de atacantes ainda ativos após certo tempo. Mostra quanto tempo persistem.',
'help.term.kaplan_meier.do': 'Curva que se mantém alta indica atacantes persistentes: endureça as regras de ban.',
'help.term.recidivism': 'A parcela dos endereços banidos que voltaram depois do fim do ban.',
'help.term.recidivism.do': 'Reincidência alta sugere bans mais longos ou lista de bloqueio permanente.',
'help.term.mitre_tactic': 'Uma tática é o objetivo do atacante no catálogo MITRE ATT&CK (reconhecimento, acesso inicial, acesso a credenciais...). As técnicas são os jeitos de alcançá-lo.',
'help.term.mitre_tactic.do': 'Use as táticas para ver em qual estágio de ataque você mais está.',
'help.term.ttb': 'Tempo até o ban: quanto tempo o atacante agiu antes de ser banido.',
'help.term.ttb.do': 'Tempos longos indicam regras de ban que reagem tarde.',
'help.term.leak': 'Vazamento é uma requisição de um endereço já banido ou na lista de bloqueio que ainda assim foi atendida.',
'help.term.leak.do': 'Verifique se o firewall aplica a lista de bloqueio no lugar certo.',
'help.term.integrity_gap': 'Um período em que os logs têm um buraco: nenhuma linha foi lida, então podem faltar eventos.',
'help.term.integrity_gap.do': 'Veja a fonte de log e se o arquivo foi rotacionado ou o serviço parou.',
'help.term.nonhuman': 'Clientes não humanos: robôs, rastreadores, ferramentas e scripts, reconhecidos pelo user-agent ou pelo comportamento.',
'help.term.nonhuman.do': 'Não contam como visitantes. Limite os indesejados no robots.txt ou no proxy.',
'help.term.visit': 'Uma visita legítima, mostrada de forma anônima no mapa ao vivo: um visitante real, sem IP nem identidade guardados.',
'help.term.visit.do': 'Nada a fazer; apenas mostra de onde vem o seu público.',
'login.token': 'Token de acesso',
'login.submit': 'Entrar',
'login.err.bad': 'Token inválido.',
-8
View File
@@ -7,10 +7,6 @@
<title>Urutau</title>
<link rel="icon" type="image/png" href="/favicon.png">
<link rel="stylesheet" href="/style.css">
<link rel="stylesheet" href="/geo.css">
<link rel="stylesheet" href="/live.css">
<link rel="stylesheet" href="/ip.css">
<link rel="stylesheet" href="/replay.css">
<script src="/i18n.js"></script>
</head>
<body>
@@ -65,9 +61,5 @@
<script src="/world.js"></script>
<script src="/app.js"></script>
<script src="/geo.js"></script>
<script src="/live.js"></script>
<script src="/ip.js"></script>
<script src="/replay.js"></script>
</body>
</html>
+24
View File
@@ -0,0 +1,24 @@
/* Urutau - INTEGRITY page. Selectors prefixed ig-. */
.ig { display: flex; flex-direction: column; gap: var(--grid-gap, 16px); min-width: 0; }
.ig-box { display: flex; flex-direction: column; gap: var(--grid-gap, 16px); min-width: 0; }
.ig-stats > * { grid-column: span 12; }
@media (min-width: 700px) { .ig-stats > .span-3 { grid-column: span 6; } }
@media (min-width: 1100px) { .ig-stats > .span-3 { grid-column: span 3; } }
@media (min-width: 1100px) {
.ig .grid-12 > .span-6 { grid-column: span 6; }
.ig .grid-12 > .span-8 { grid-column: span 8; }
.ig .grid-12 > .span-4 { grid-column: span 4; }
}
.ig-scroll { overflow-x: auto; max-width: 100%; }
.ig-table { width: 100%; border-collapse: collapse; font-size: .8125rem; }
.ig-table th { text-align: left; font-weight: 600; color: var(--ink-muted); padding: 6px 10px; border-bottom: 1px solid var(--line); white-space: nowrap; }
.ig-table td { padding: 6px 10px; border-bottom: 1px solid var(--line); overflow-wrap: anywhere; }
.ig-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 8px; font-size: .875rem; overflow-wrap: anywhere; }
.ig-muted { color: var(--ink-muted); font-size: .8125rem; }
.ig-kv { display: grid; grid-template-columns: auto 1fr; gap: 6px 14px; margin: 8px 0 0; font-size: .875rem; }
.ig-kv dt { color: var(--ink-muted); }
.ig-kv dd { margin: 0; text-align: right; overflow-wrap: anywhere; }
.ig .vz-heat { width: 100%; max-width: 100%; min-width: 0; overflow: hidden; }
.ig .vz-heat svg { max-width: 100%; height: auto; display: block; }
.ig .panel, .ig .panel-b { min-width: 0; max-width: 100%; }
.ig-heatbox { position: relative; overflow: hidden; max-width: 100%; }
+279
View File
@@ -0,0 +1,279 @@
/* Urutau - INTEGRITY page ("Is the data complete?"): volume ingested per host and
hour (holes show as empty cells), state of every source and peer, share of
malformed lines, event log and geolocation base. Log data is hostile: every
dynamic string goes through textContent (the shell's el/h helpers). */
(function () {
'use strict';
var STATES = { following: 1, waiting: 1, backfill: 1, error: 1, disabled: 1 };
var ICON = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3 4 6v6c0 4.5 3.2 7.8 8 9 4.8-1.2 8-4.5 8-9V6l-8-3z"/><path d="m9 12 2 2 4-4"/></svg>';
function boot() {
var U = window.Urutau;
if (!U || !U.registerPage) return false;
U.registerI18n({
en: {
'ig.title': 'Integrity',
'ig.lead.ok': 'The data is complete',
'ig.lead.okBody': 'No gaps of {n} hours or more, every source answers and few lines were rejected.',
'ig.lead.bad.one': '{n} hole in the data',
'ig.lead.bad.other': '{n} holes in the data',
'ig.lead.badBody': 'Silences of two hours or more in sources that normally report, offline peers or sources in error. Check the panels below.',
'ig.lead.loading': 'Checking the data...',
'ig.stat.hosts': 'Hosts reporting',
'ig.stat.gaps': 'Gaps found',
'ig.stat.parse': 'Invalid lines',
'ig.stat.log': 'Event log',
'ig.stat.logSub': '{days} days, {size}',
'ig.stat.logOff': 'off',
'ig.heat.title': 'Events ingested per hour',
'ig.heat.hint': 'One row per host, one column per hour. Empty cells are hours with no event at all.',
'ig.heat.empty': 'No events in this period.',
'ig.gaps.title': 'Gaps',
'ig.gaps.none': 'No silence of two hours or more.',
'ig.gaps.line': '{host}: {from} to {to} ({h} h)',
'ig.src.title': 'Sources',
'ig.src.host': 'Host',
'ig.src.name': 'Source',
'ig.src.state': 'State',
'ig.src.lines': 'Lines',
'ig.src.bad': 'Invalid',
'ig.src.last': 'Last event',
'ig.src.none': 'No sources reported.',
'ig.state.following': 'following',
'ig.state.waiting': 'waiting',
'ig.state.backfill': 'catching up',
'ig.state.error': 'error',
'ig.state.disabled': 'disabled',
'ig.peers.title': 'Peers',
'ig.peers.none': 'No peers configured.',
'ig.peers.online': 'online',
'ig.peers.offline': 'offline',
'ig.peers.live': 'live',
'ig.peers.sync': 'synced {t}',
'ig.peers.never': 'never synced',
'ig.log.title': 'Event log and geolocation',
'ig.log.off': 'The event log is off: periods, sessions and replay have no data.',
'ig.log.days': 'Days kept',
'ig.log.size': 'Size on disk',
'ig.log.dropped': 'Events dropped',
'ig.geo.state': 'Geolocation base',
'ig.geo.city': 'City base build',
'ig.geo.asn': 'ASN base build',
'ig.geo.unknown': 'unknown',
'ig.lag': 'Delay',
'ig.host.lagLine': '{host}: last event {t}'
},
'pt-BR': {
'ig.title': 'Integridade',
'ig.lead.ok': 'Os dados estão completos',
'ig.lead.okBody': 'Nenhum buraco de {n} horas ou mais, todas as fontes respondem e poucas linhas foram rejeitadas.',
'ig.lead.bad.one': '{n} buraco nos dados',
'ig.lead.bad.other': '{n} buracos nos dados',
'ig.lead.badBody': 'Silêncios de duas horas ou mais em fontes que costumam registrar, peers fora do ar ou fontes com erro. Veja os painéis abaixo.',
'ig.lead.loading': 'Conferindo os dados...',
'ig.stat.hosts': 'Hosts reportando',
'ig.stat.gaps': 'Buracos encontrados',
'ig.stat.parse': 'Linhas inválidas',
'ig.stat.log': 'Registro de eventos',
'ig.stat.logSub': '{days} dias, {size}',
'ig.stat.logOff': 'desligado',
'ig.heat.title': 'Eventos ingeridos por hora',
'ig.heat.hint': 'Uma linha por host, uma coluna por hora. Células vazias são horas sem nenhum evento.',
'ig.heat.empty': 'Nenhum evento neste período.',
'ig.gaps.title': 'Buracos',
'ig.gaps.none': 'Nenhum silêncio de duas horas ou mais.',
'ig.gaps.line': '{host}: de {from} a {to} ({h} h)',
'ig.src.title': 'Fontes',
'ig.src.host': 'Host',
'ig.src.name': 'Fonte',
'ig.src.state': 'Estado',
'ig.src.lines': 'Linhas',
'ig.src.bad': 'Inválidas',
'ig.src.last': 'Último evento',
'ig.src.none': 'Nenhuma fonte informada.',
'ig.state.following': 'acompanhando',
'ig.state.waiting': 'aguardando',
'ig.state.backfill': 'recuperando',
'ig.state.error': 'erro',
'ig.state.disabled': 'desativada',
'ig.peers.title': 'Peers',
'ig.peers.none': 'Nenhum peer configurado.',
'ig.peers.online': 'no ar',
'ig.peers.offline': 'fora do ar',
'ig.peers.live': 'ao vivo',
'ig.peers.sync': 'sincronizado {t}',
'ig.peers.never': 'nunca sincronizou',
'ig.log.title': 'Registro de eventos e geolocalização',
'ig.log.off': 'O registro de eventos está desligado: períodos, sessões e replay ficam sem dados.',
'ig.log.days': 'Dias guardados',
'ig.log.size': 'Tamanho em disco',
'ig.log.dropped': 'Eventos descartados',
'ig.geo.state': 'Base de geolocalização',
'ig.geo.city': 'Build da base de cidades',
'ig.geo.asn': 'Build da base de ASN',
'ig.geo.unknown': 'desconhecida',
'ig.lag': 'Atraso',
'ig.host.lagLine': '{host}: último evento {t}'
}
});
var t = U.t, nf = U.fmt.num;
var h = function (tag, cls) { return U.el.apply(null, [tag, cls ? { class: cls } : null].concat([].slice.call(arguments, 2))); };
function when(ts) { return ts ? U.fmt.date(ts) : '-'; }
var root = null, box = null, ctx0 = null, seq = 0, alive = false, data = null, timer = null;
function params(c) {
var p = U.rangeParams();
if (c && c.host && c.host !== 'all') p.host = c.host;
return p;
}
function load(c) {
var my = ++seq;
U.api('/api/v1/integrity', params(c || ctx0)).then(function (d) {
if (!alive || my !== seq) return;
data = d; paint();
}).catch(function () {
if (!alive || my !== seq || data) return;
while (box.firstChild) box.removeChild(box.firstChild);
box.appendChild(U.ui.empty(t('error.load')));
});
}
function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); }
function hourLabel(hn) {
var d = new Date(hn * 3600000);
return ('0' + d.getDate()).slice(-2) + '/' + ('0' + d.getHours()).slice(-2);
}
function table(headers, rows) {
var tb = h('table', 'ig-table');
var tr = h('tr');
headers.forEach(function (x) { tr.appendChild(h('th', null, x)); });
tb.appendChild(h('thead', null, tr));
var body = h('tbody');
rows.forEach(function (r) {
var row = h('tr');
r.forEach(function (c) { row.appendChild(h('td', null, c)); });
body.appendChild(row);
});
tb.appendChild(body);
return h('div', 'ig-scroll', tb);
}
function paint() {
if (!data) return;
clear(box);
var hosts = data.hosts || [], peers = data.peers || [];
var gaps = 0, lines = 0, bad = 0, errors = 0, onlineN = 0;
hosts.forEach(function (x) {
gaps += (x.gaps || []).length;
if (x.online) onlineN++;
(x.sources || []).forEach(function (s) { lines += s.lines; bad += s.malformed; if (s.state === 'error') errors++; });
});
var offline = peers.filter(function (p) { return !p.online; }).length;
var rate = lines + bad > 0 ? bad / (lines + bad) : 0;
var holes = gaps + offline + errors;
var ok = holes === 0 && rate < 0.01;
var title = ok ? t('ig.lead.ok') : U.pl('ig.lead.bad', holes || 1);
box.appendChild(U.ui.lead(title, ok ? t('ig.lead.okBody', { n: 2 }) : t('ig.lead.badBody'), ok ? 'ok' : 'danger'));
var stats = h('div', 'grid-12 ig-stats');
function sp(node) { node.classList.add('span-3'); stats.appendChild(node); }
sp(U.ui.stat(t('ig.stat.hosts'), nf(onlineN) + ' / ' + nf(hosts.length), null, onlineN === hosts.length ? 'ok' : 'danger'));
sp(U.ui.stat(t('ig.stat.gaps'), nf(gaps), null, gaps ? 'danger' : 'ok', null, 'term.integrity_gap'));
sp(U.ui.stat(t('ig.stat.parse'), (rate * 100).toFixed(rate < 0.1 ? 2 : 1) + '%', nf(bad) + ' / ' + nf(lines + bad), rate >= 0.01 ? 'danger' : 'ok'));
var lg = data.eventlog || {};
sp(U.ui.stat(t('ig.stat.log'), lg.enabled ? nf(lg.days) : t('ig.stat.logOff'), lg.enabled ? t('ig.stat.logSub', { days: nf(lg.days), size: U.fmt.bytes(lg.bytes) }) : null, lg.enabled ? 'ok' : 'neutral'));
box.appendChild(stats);
// heatmap
var hp = U.ui.panel({ title: t('ig.heat.title'), hint: t('ig.heat.hint'), variant: 'chart' });
var n = hosts.length ? (hosts[0].hourly || []).length : 0;
if (!n || !hosts.some(function (x) { return (x.hourly || []).some(function (v) { return v > 0; }); })) {
hp.body.appendChild(U.ui.empty(t('ig.heat.empty')));
} else {
var xl = [];
for (var i = 0; i < n; i++) xl.push(hourLabel(data.from_hour + i));
hp.body.appendChild(h('div', 'ig-heatbox', U.charts.heatmap(hosts.map(function (x) { return x.hourly; }), xl, hosts.map(function (x) { return x.name; }), { title: t('ig.heat.title') }))); }
box.appendChild(hp);
var grid = h('div', 'grid-12');
// gaps
var gp = U.ui.panel({ title: t('ig.gaps.title') });
gp.classList.add('span-6');
var gl = h('ul', 'ig-list');
hosts.forEach(function (x) {
(x.gaps || []).forEach(function (g) {
gl.appendChild(h('li', null, t('ig.gaps.line', { host: x.name, from: when(g.from), to: when(g.to), h: nf(Math.round((g.to - g.from) / 3600)) })));
});
});
gp.body.appendChild(gl.children.length ? gl : U.ui.empty(t('ig.gaps.none')));
grid.appendChild(gp);
// peers
var pp = U.ui.panel({ title: t('ig.peers.title') });
pp.classList.add('span-6');
if (!peers.length) pp.body.appendChild(U.ui.empty(t('ig.peers.none')));
else {
var pl = h('ul', 'ig-list');
peers.forEach(function (p) {
pl.appendChild(h('li', null, h('strong', null, p.name), ' ', U.ui.badge(t(p.online ? 'ig.peers.online' : 'ig.peers.offline'), p.online ? 'ok' : 'danger'),
p.live ? ' ' : null, p.live ? U.ui.badge(t('ig.peers.live'), 'neutral') : null, ' ',
h('span', 'ig-muted', p.last_sync ? t('ig.peers.sync', { t: U.fmt.ago(p.last_sync) }) : t('ig.peers.never'))));
});
pp.body.appendChild(pl);
}
grid.appendChild(pp);
// sources
var sp2 = U.ui.panel({ title: t('ig.src.title') });
sp2.classList.add('span-8');
var rows = [];
hosts.forEach(function (x) {
(x.sources || []).forEach(function (s) {
var tone = s.state === 'error' ? 'danger' : s.state === 'following' ? 'ok' : 'neutral';
rows.push([x.name, s.name, U.ui.badge(STATES[s.state] ? t('ig.state.' + s.state) : String(s.state || ''), tone), nf(s.lines), nf(s.malformed), s.last ? U.fmt.ago(s.last) : '-']);
});
});
sp2.body.appendChild(rows.length ? table([t('ig.src.host'), t('ig.src.name'), t('ig.src.state'), t('ig.src.lines'), t('ig.src.bad'), t('ig.src.last')], rows) : U.ui.empty(t('ig.src.none')));
grid.appendChild(sp2);
// log + geo
var lp = U.ui.panel({ title: t('ig.log.title') });
lp.classList.add('span-4');
if (!lg.enabled) lp.body.appendChild(h('p', 'ig-muted', t('ig.log.off')));
var kv = h('dl', 'ig-kv');
function row(k, v) { kv.appendChild(h('dt', null, k)); kv.appendChild(h('dd', null, v)); }
if (lg.enabled) { row(t('ig.log.days'), nf(lg.days)); row(t('ig.log.size'), U.fmt.bytes(lg.bytes)); row(t('ig.log.dropped'), nf(lg.dropped)); }
var g = data.geo || {};
row(t('ig.geo.state'), g.state ? (STATES[g.state] ? t('ig.state.' + g.state) : String(g.state)) : t('ig.geo.unknown'));
row(t('ig.geo.city'), g.city_build ? U.fmt.date(g.city_build) : t('ig.geo.unknown'));
row(t('ig.geo.asn'), g.asn_build ? U.fmt.date(g.asn_build) : t('ig.geo.unknown'));
lp.body.appendChild(kv);
grid.appendChild(lp);
box.appendChild(grid);
}
U.registerPage({
id: 'integrity', group: 'operate', icon: ICON, titleKey: 'ig.title',
mount: function (el, c) {
ctx0 = c; alive = true; data = null;
root = h('div', 'ig');
box = h('div', 'ig-box');
root.appendChild(box);
box.appendChild(U.ui.lead(t('ig.lead.loading'), null, 'neutral'));
el.appendChild(root);
load(c);
},
update: function (c) { ctx0 = c; load(c); if (data) paint(); },
refresh: function () { load(ctx0); },
unmount: function () { alive = false; seq++; if (root && root.parentNode) root.parentNode.removeChild(root); root = box = data = null; }
});
return true;
}
if (!boot()) {
var tries = 0, iv = setInterval(function () { if (boot() || ++tries > 50) clearInterval(iv); }, 100);
}
})();
+16
View File
@@ -164,3 +164,19 @@ button.lv-row[aria-pressed="false"] .lv-row-l { text-decoration: line-through; }
.lv-bar { gap: 6px; }
.lv-notes { margin-left: 0; width: 100%; }
}
/* legitimate traffic (anonymous visits) */
.lv-vis { gap: 8px; }
.lv-vis-dot { width: 10px; height: 10px; border-radius: 50%; border: 2px solid var(--lv-muted); flex: none; }
.lv-vis[aria-pressed="true"] { border-color: var(--accent); }
.lv-vis[aria-pressed="true"] .lv-vis-dot { background: var(--lv-muted); border-color: var(--lv-muted); }
.lv-devs, .lv-m-visit { display: none; }
.lv-vis-on .lv-devs { display: flex; }
.lv-vis-on .lv-m-visit { display: flex; }
.lv-k-visit { --k: var(--ink-muted, #9db3bd); }
.lv-ev-visit .lv-vtxt { grid-column: span 1; color: var(--lv-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.lv-ev-visit { grid-template-columns: auto auto minmax(0, 1fr); }
.lv-left .lv-ev-visit { grid-template-columns: auto auto minmax(0, 1fr); }
.lv-leg { display: none; align-items: center; gap: 6px; }
.lv-vis-on .lv-leg { display: inline-flex; }
.lv-leg-sw { width: 16px; height: 2px; background: var(--ink-muted, #9db3bd); }
+186 -34
View File
@@ -15,7 +15,7 @@
var CAT_OK = {};
CATS.forEach(function (c) { CAT_OK[c] = 1; });
var MAX_ARCS = 300, MAX_PENDING = 400, RING_MAX = 800, RING_TRIM = 300;
var MAX_VARCS = 150, MAX_VPENDING = 150, MAX_ARCS = 300, MAX_PENDING = 400, RING_MAX = 800, RING_TRIM = 300;
var WORLD_W = 2000, WORLD_H = 789, LAT_TOP = 84, LAT_BOT = -58;
var DEFAULT_DST = { lat: -23.55, lon: -46.63 };
var RAD = Math.PI / 180, TAU = Math.PI * 2;
@@ -138,7 +138,7 @@
this.paused = false; this.hidden = document.hidden;
this.reduced = !!(window.matchMedia && matchMedia('(prefers-reduced-motion: reduce)').matches);
this.T = 0; this.last = 0; this.raf = 0; this.dirty = true;
this.arcs = []; this.free = []; this.pending = []; this.frameKey = {};
this.arcs = []; this.varcs = []; this.vpending = []; this.free = []; this.pending = []; this.frameKey = {};
this.dests = {}; this.destList = []; this.dots = []; this.more = [];
this.frameAvg = 16; this.quality = 1;
this.W = 0; this.H = 0; this.dpr = 1; this.reserve = 0;
@@ -189,7 +189,7 @@
this.listeners.forEach(function (l) { try { l[0].removeEventListener(l[1], l[2], l[3]); } catch (x) { /* ignore */ } });
this.listeners = [];
if (this.ro) { this.ro.disconnect(); this.ro = null; }
this.arcs = []; this.free = []; this.pending = []; this.dots = []; this.flatCache = null; this.pickCbs = [];
this.arcs = []; this.varcs = []; this.vpending = []; this.free = []; this.pending = []; this.dots = []; this.flatCache = null; this.pickCbs = [];
if (this.cv.parentNode) this.cv.parentNode.removeChild(this.cv);
};
@@ -202,6 +202,8 @@
var rgb = parseColor(css(TOKEN[c]), FALLBACK[c]);
cols[c] = { rgb: rgb, c0: rgba(rgb, 0), c1: rgba(rgb, 1), css: rgba(rgb, 1) };
});
var vrgb = parseColor(tok('--ink-muted', '--muted'), '#9db3bd');
cols.visit = { rgb: vrgb, c0: rgba(vrgb, 0), c1: rgba(vrgb, 1), css: rgba(vrgb, 1) };
this.colors = cols;
this.dark = (bg[0] * 299 + bg[1] * 587 + bg[2] * 114) / 1000 < 128;
this.pal = { text: text, bg: bg, accent: parseColor(css('--accent'), '#38bdf8') };
@@ -211,8 +213,8 @@
M.setTheme = function () { this.readTheme(); this.kick(); };
M.setMode = function (m) { this.mode = m === 'globe' ? 'globe' : 'flat'; this.target = this.mode === 'globe' ? 1 : 0; this.cv.classList.toggle('lv-globe', this.mode === 'globe'); this.dirty = true; this.kick(); };
M.pause = function (p) { this.paused = !!p; if (p) this.pending.length = 0; this.last = 0; this.dirty = true; this.kick(); };
M.clear = function () { this.arcs = []; this.pending.length = 0; this.dots = []; this.more = []; this.dirty = true; this.kick(); };
M.pause = function (p) { this.paused = !!p; if (p) { this.pending.length = 0; this.vpending.length = 0; } this.last = 0; this.dirty = true; this.kick(); };
M.clear = function () { this.arcs = []; this.varcs = []; this.vpending.length = 0; this.pending.length = 0; this.dots = []; this.more = []; this.dirty = true; this.kick(); };
M.setDest = function (host, d, est) {
var cur = this.dests[host];
@@ -260,13 +262,21 @@
// ev: an event as sent by the server ({cat, host, src, dst, cc}); returns whether it can be drawn
M.spawnEvent = function (ev, o) {
if (!this.alive || !ev || !CAT_OK[ev.cat]) return false;
var vis = !!(o && o.visit);
if (!this.alive || !ev || (!vis && !CAT_OK[ev.cat])) return false;
var org = this.originOf(ev);
if (!org) return false;
var host = str(ev.host, 64) || 'local';
var d = this.destFor(host, ev.dst && typeof ev.dst === 'object' ? ev.dst : null);
var hl = !!(o && o.highlight) || !!HOSTILE[ev.cat];
var hl = !vis && (!!(o && o.highlight) || !!HOSTILE[ev.cat]);
if (this.paused || this.hidden) return true;
if (vis) {
if (this.reduced) return true;
if (this.vpending.length >= MAX_VPENDING) this.vpending.shift();
this.vpending.push({ o: org, d: d, cat: 'visit', hl: false, v: true });
this.kick();
return true;
}
if (this.reduced) {
this.dots.push({ lat: org.lat, lon: org.lon, v: vec(org.lat, org.lon), cat: ev.cat });
if (this.dots.length > 160) this.dots.shift();
@@ -353,7 +363,7 @@
M.onVisibility = function () {
this.hidden = document.hidden;
if (this.hidden) { if (this.raf) cancelAnimationFrame(this.raf); this.raf = 0; this.pending.length = 0; }
if (this.hidden) { if (this.raf) cancelAnimationFrame(this.raf); this.raf = 0; this.pending.length = 0; this.vpending.length = 0; }
else { this.last = 0; this.dirty = true; this.kick(); }
};
@@ -473,7 +483,7 @@
};
M.drawFlatLayer = function (g, layerAlpha, add) {
var ox = this.ox, oy = this.oy, mw = this.mw, mh = this.mh, T = this.T, arcs = this.arcs, i;
var ox = this.ox, oy = this.oy, mw = this.mw, mh = this.mh, T = this.T, arcs = this.ordered(), i;
g.globalCompositeOperation = 'source-over';
for (i = 0; i < this.dots.length; i++) { // reduced motion: static dots instead of arcs
var dd = this.dots[i];
@@ -485,12 +495,12 @@
for (i = 0; i < arcs.length; i++) {
var a = arcs[i], age = T - a.born;
if (age < 0) continue;
var col = this.colors[a.cat];
var col = a.visit ? this.colors.visit : this.colors[a.cat];
var x0 = ox + a.u0 * mw, y0 = oy + a.v0 * mh, x1 = ox + a.dest.u0 * mw, y1 = oy + a.dest.v0 * mh;
var dx = x1 - x0, dy = y1 - y0, dist = Math.sqrt(dx * dx + dy * dy);
var cx = (x0 + x1) / 2, cy = (y0 + y1) / 2 - Math.min(dist * 0.42, mh * 0.5) - 4;
var head = ease(clamp(age / a.D, 0, 1)), tail = ease(clamp((age - a.hold) / a.D, 0, 1));
var fade = layerAlpha * (1 - 0.75 * tail);
var fade = layerAlpha * (1 - 0.75 * tail) * (a.visit ? 0.8 : 1);
if (tail < 1 && head > tail) {
// exact sub-curve of the quadratic Bezier between parameters tail..head
var ut = 1 - tail, uh = 1 - head;
@@ -503,18 +513,18 @@
g.strokeStyle = gr;
g.beginPath(); g.moveTo(ax, ay); g.quadraticCurveTo(kx, ky, bx, by);
if (a.hostile) { g.globalAlpha = fade * 0.25; g.lineWidth = 5; g.stroke(); }
g.globalAlpha = fade; g.lineWidth = (a.hostile ? 2.2 : 1.3) + (a.n > 1 ? Math.min(2, Math.log(a.n)) : 0);
g.globalAlpha = fade; g.lineWidth = (a.visit ? 0.9 : a.hostile ? 2.2 : 1.3) + (a.n > 1 ? Math.min(2, Math.log(a.n)) : 0);
g.stroke();
if (head < 1) {
g.fillStyle = col.css;
g.beginPath(); g.arc(bx, by, a.hostile ? 2.8 : 2, 0, TAU); g.fill();
}
}
if (age < 0.7) {
if (age < 0.7 && !a.visit) {
g.globalAlpha = layerAlpha * (1 - age / 0.7) * 0.8; g.strokeStyle = col.css; g.lineWidth = 1;
g.beginPath(); g.arc(x0, y0, 2 + age * 9, 0, TAU); g.stroke();
}
this.drawPulse(g, x1, y1, a, age, col, null, 1, layerAlpha);
if (!a.visit) this.drawPulse(g, x1, y1, a, age, col, null, 1, layerAlpha);
}
g.globalCompositeOperation = 'source-over';
for (i = 0; i < this.destList.length; i++) {
@@ -660,7 +670,7 @@
};
M.drawGlobeLayer = function (g, m, add) {
var cx = this.cx, cy = this.cy, R = this.gR, T = this.T, arcs = this.arcs, i, k;
var cx = this.cx, cy = this.cy, R = this.gR, T = this.T, arcs = this.ordered(), i, k;
g.globalCompositeOperation = 'source-over';
for (i = 0; i < this.dots.length; i++) {
var dd = this.dots[i];
@@ -674,9 +684,9 @@
for (i = 0; i < arcs.length; i++) {
var a = arcs[i], age = T - a.born;
if (age < 0) continue;
var col = this.colors[a.cat];
var col = a.visit ? this.colors.visit : this.colors[a.cat];
var head = ease(clamp(age / a.D, 0, 1)), tail = ease(clamp((age - a.hold) / a.D, 0, 1));
var fade = m * (1 - 0.75 * tail);
var fade = m * (1 - 0.75 * tail) * (a.visit ? 0.8 : 1);
var A = a.a, B = a.b, w = a.w, sw = Math.sin(w);
if (tail < 1 && head > tail) {
var lift = 0.05 + 0.22 * w / Math.PI;
@@ -700,16 +710,16 @@
gr.addColorStop(0, col.c0); gr.addColorStop(1, col.c1);
g.strokeStyle = gr;
if (a.hostile) { g.globalAlpha = fade * 0.25; g.lineWidth = 5; g.stroke(); }
g.globalAlpha = fade; g.lineWidth = (a.hostile ? 2.2 : 1.3) + (a.n > 1 ? Math.min(2, Math.log(a.n)) : 0);
g.globalAlpha = fade; g.lineWidth = (a.visit ? 0.9 : a.hostile ? 2.2 : 1.3) + (a.n > 1 ? Math.min(2, Math.log(a.n)) : 0);
g.stroke();
if (head < 1) { g.fillStyle = col.css; g.beginPath(); g.arc(lx, ly, a.hostile ? 2.8 : 2, 0, TAU); g.fill(); }
}
}
if (age >= a.D) {
if (age >= a.D && !a.visit) {
this.rot(B[0], B[1], B[2]);
if (this.rz > 0.02) this.drawPulse(g, cx + this.rx * R, cy - this.ry * R, a, age, col, Math.atan2(-this.ry, this.rx), this.rz, m);
}
if (age < 0.7) {
if (age < 0.7 && !a.visit) {
this.rot(A[0], A[1], A[2]);
if (this.rz > 0.02) {
g.globalAlpha = m * (1 - age / 0.7) * 0.8; g.strokeStyle = col.css; g.lineWidth = 1;
@@ -753,7 +763,7 @@
M.spawn = function (it) {
var a = this.free.pop() || {};
var o = it.o, d = it.d, hostile = !!it.hl;
a.cat = it.cat; a.hostile = hostile; a.n = 1; a.dest = d;
a.cat = it.cat; a.hostile = hostile; a.n = 1; a.dest = d; a.visit = !!it.v;
a.born = this.T;
a.u0 = (o.lon + 180) / 360; a.v0 = (LAT_TOP - clamp(o.lat, LAT_BOT, LAT_TOP)) / (LAT_TOP - LAT_BOT);
a.a = vec(o.lat, o.lon); a.b = d.v;
@@ -761,8 +771,9 @@
a.D = hostile ? 1.35 : 1.0;
a.hold = hostile ? 1.4 : 0.2;
a.pl = hostile ? 1.9 : 1.1;
if (a.visit) { a.D = 0.75; a.hold = 0; a.pl = 0.1; }
a.life = Math.max(a.D + a.pl, a.D + a.hold + a.D);
this.arcs.push(a);
(a.visit ? this.varcs : this.arcs).push(a);
return a;
};
@@ -782,6 +793,19 @@
if (merged) this.addMore(merged);
};
// legitimate visits: their own queue and cap, always drawn under the attacks
M.stepVisits = function () {
var q = this.vpending, n = 0, budget = q.length > 60 ? 30 : 8;
while (q.length && n < budget && this.varcs.length < Math.round(MAX_VARCS * this.quality)) { this.spawn(q.shift()); n++; }
};
M.ordered = function () {
var o = this.order || (this.order = []), i, j = 0;
for (i = 0; i < this.varcs.length; i++) o[j++] = this.varcs[i];
for (i = 0; i < this.arcs.length; i++) o[j++] = this.arcs[i];
o.length = j;
return o;
};
M.addMore = function (n) {
var s = Math.floor(Date.now() / 1000), m = this.more;
if (m.length && m[m.length - 1][0] === s) m[m.length - 1][1] += n; else m.push([s, n]);
@@ -811,7 +835,7 @@
if (this.frameAvg > 26) this.quality = Math.max(0.35, this.quality - 0.02);
else if (this.frameAvg < 20) this.quality = Math.min(1, this.quality + 0.01);
}
this.stepSpawn();
this.stepSpawn(); this.stepVisits();
}
var df = this.target - this.m, morph = false;
if (Math.abs(df) > 0.003) { this.m += df * (this.reduced ? 1 : Math.min(1, dt * 6.5)); morph = true; } else this.m = this.target;
@@ -826,11 +850,14 @@
if (still && !wasDirty && !morph) return; // nothing changed: leave the loop idle
this.dirty = false;
this.draw();
var arcs = this.arcs;
for (var i = arcs.length - 1; i >= 0; i--) {
if (this.T - arcs[i].born > arcs[i].life) {
this.free.push(arcs[i]);
arcs[i] = arcs[arcs.length - 1]; arcs.pop();
var lists = [this.arcs, this.varcs];
for (var li = 0; li < 2; li++) {
var arcs = lists[li];
for (var i = arcs.length - 1; i >= 0; i--) {
if (this.T - arcs[i].born > arcs[i].life) {
this.free.push(arcs[i]);
arcs[i] = arcs[arcs.length - 1]; arcs.pop();
}
}
}
if (!still || morph || this.dirty) this.kick();
@@ -845,6 +872,14 @@
U.registerI18n({
en: {
'live.title': 'Live',
'live.visits': 'Legitimate traffic',
'live.visit': 'visit',
'live.legend.visits': 'visits',
'live.m.vis': 'Visits, 15 min',
'live.m.pages': 'Pages, 15 min',
'live.unit.pages': 'distinct pages',
'live.devices': 'Devices',
'live.vis.empty': 'anonymous',
'live.mode': 'View',
'live.mode.flat': 'Flat map',
'live.mode.globe': 'Globe',
@@ -886,6 +921,14 @@
},
'pt-BR': {
'live.title': 'Ao vivo',
'live.visits': 'Tráfego legítimo',
'live.visit': 'visita',
'live.legend.visits': 'visitas',
'live.m.vis': 'Visitas, 15 min',
'live.m.pages': 'Páginas, 15 min',
'live.unit.pages': 'páginas distintas',
'live.vis.empty': 'anônima',
'live.devices': 'Dispositivos',
'live.mode': 'Visualização',
'live.mode.flat': 'Mapa plano',
'live.mode.globe': 'Globo',
@@ -951,12 +994,15 @@
this.minute = -1; this.listDirty = true; this.hoverList = false;
this.more = []; this.listeners = []; this.timers = []; this.dn = null; this.dnLang = '';
this.lastEv = null;
this.visitsOn = false; this.es = null; this.vring = []; this.vbk = {}; this.pathLast = new Map(); this.devs = {}; this.devChips = {}; this.offDev = {}; this.seen = {}; this.seenN = 0;
try { this.visitsOn = localStorage.getItem('urutau.live.visits') === '1'; } catch (x) { /* storage blocked */ }
this.build();
this.map = mapApi(new AttackMap(U, this.mapBox, { mode: this.pref(), interactive: true }));
this.map.onMore(function (n) { self.addMore(n); });
this.map.onPick(function (d) { self.toggleHost(d.host); });
this.syncMode(this.pref());
this.applyVisits();
this.unsub = U.onEvent ? U.onEvent(function (e) { self.ingest(e); }) : null;
this.listen(document, 'visibilitychange', function () { self.onVisibility(); });
@@ -984,6 +1030,7 @@
P.destroy = function () {
this.alive = false;
if (this.unsub) { try { this.unsub(); } catch (x) { /* ignore */ } this.unsub = null; }
this.closeStream();
this.timers.forEach(clearInterval); this.timers = [];
this.listeners.forEach(function (l) { try { l[0].removeEventListener(l[1], l[2], l[3]); } catch (x) { /* ignore */ } });
this.listeners = [];
@@ -1003,14 +1050,16 @@
// language changed: rebuild the DOM keeping the map, the filters and the paused state
P.rebuild = function () {
var self = this, hosts = Object.keys(this.hostsSeen), paused = this.paused;
this.hostsSeen = {}; this.hostChips = {};
var self = this, hosts = Object.keys(this.hostsSeen), paused = this.paused, devs = Object.keys(this.devs);
this.hostsSeen = {}; this.hostChips = {}; this.devChips = {}; this.devs = {};
var mapEl = this.map._map.cv, was = this.stage.classList.contains('lv-nopanels');
this.build();
this.mapBox.appendChild(mapEl);
this.map._map.container = this.mapBox;
if (this.map._map.ro) { this.map._map.ro.disconnect(); this.map._map.ro.observe(this.mapBox); }
hosts.forEach(function (h) { self.noteHost(h); });
devs.forEach(function (d) { self.noteDevice(d); });
this.applyVisits();
this.stage.classList.toggle('lv-nopanels', was);
this.syncMode(this.map.getMode());
if (paused) this.setPaused(true);
@@ -1083,15 +1132,24 @@
this.bFs.setAttribute('aria-pressed', 'false');
ctl.appendChild(this.bFs);
}
this.bVis = document.createElement('button');
this.bVis.type = 'button'; this.bVis.className = 'lv-btn lv-vis';
this.bVis.appendChild(this.el('span', 'lv-vis-dot'));
this.bVis.appendChild(this.el('span', '', t('live.visits')));
this.bVis.addEventListener('click', function () { self.setVisits(!self.visitsOn); });
ctl.appendChild(this.bVis);
bar.appendChild(ctl);
this.hostBox = el('div', 'lv-hosts'); this.hostBox.setAttribute('role', 'group'); this.hostBox.setAttribute('aria-label', t('live.hosts'));
bar.appendChild(this.hostBox);
this.devBox = el('div', 'lv-hosts lv-devs'); this.devBox.setAttribute('role', 'group'); this.devBox.setAttribute('aria-label', t('live.devices'));
bar.appendChild(this.devBox);
var notes = el('div', 'lv-notes');
this.nPaused = el('span', 'lv-note', t('live.paused')); this.nPaused.hidden = true;
this.nFilter = el('span', 'lv-note', t('live.filtered')); this.nFilter.hidden = true;
this.nMore = el('span', 'lv-note', ''); this.nMore.hidden = true;
this.nEst = el('span', 'lv-note', t('live.est')); this.nEst.hidden = true;
[this.nPaused, this.nFilter, this.nMore, this.nEst].forEach(function (n) { notes.appendChild(n); });
this.nLeg = el('span', 'lv-note lv-leg'); this.nLeg.appendChild(el('span', 'lv-leg-sw')); this.nLeg.appendChild(el('span', '', t('live.legend.visits')));
[this.nPaused, this.nFilter, this.nMore, this.nEst, this.nLeg].forEach(function (n) { notes.appendChild(n); });
bar.appendChild(notes);
stage.appendChild(bar);
@@ -1105,7 +1163,7 @@
var side = el('div', 'lv-side'); this.side = side;
var mets = el('div', 'lv-metrics');
this.mM = {};
['15m', '1h', 'avg', 'ips', 'new', 'last'].forEach(function (k) { self.mM[k] = self.metric(k); mets.appendChild(self.mM[k]); });
['15m', '1h', 'avg', 'ips', 'new', 'last', 'vis', 'pages'].forEach(function (k) { self.mM[k] = self.metric(k); if (k === 'vis' || k === 'pages') self.mM[k].classList.add('lv-m-visit'); mets.appendChild(self.mM[k]); });
this.spark = document.createElement('canvas'); this.spark.className = 'lv-spark'; this.spark.setAttribute('aria-hidden', 'true');
this.spark.width = 150; this.spark.height = 32;
this.mM['15m'].appendChild(this.spark);
@@ -1195,6 +1253,72 @@
this.map.resize();
};
// ---- legitimate traffic (anonymous visits): its own stream, only while the option is on
P.setVisits = function (on) {
this.visitsOn = on;
try { localStorage.setItem('urutau.live.visits', on ? '1' : '0'); } catch (x) { /* storage blocked */ }
this.applyVisits();
this.minute = -1; this.listDirty = true; this.tick(true);
};
P.applyVisits = function () {
var on = this.visitsOn;
this.bVis.setAttribute('aria-pressed', on ? 'true' : 'false');
this.stage.classList.toggle('lv-vis-on', on);
if (on) this.openStream(); else { this.closeStream(); this.vring = []; this.map.clear(); }
this.map._map.resize();
};
P.openStream = function () {
var self = this;
if (this.es || !window.EventSource) return;
var es = new EventSource('/api/v1/events/stream?visits=1');
es.addEventListener('ev', function (m) {
var e;
try { e = JSON.parse(m.data); } catch (x) { return; }
if (!e || typeof e !== 'object') return;
if (e.kind === 'visit') self.visit(e);
else if (e.kind === 'visit_batch') self.visitBatch(e);
else self.ingest(e);
});
this.es = es;
};
P.closeStream = function () { if (this.es) { this.es.close(); this.es = null; } };
P.noteDevice = function (d) {
if (!d || this.devs[d] || Object.keys(this.devs).length >= 8) return;
var self = this;
this.devs[d] = 1;
var b = document.createElement('button');
b.type = 'button'; b.className = 'lv-chip'; b.setAttribute('aria-pressed', this.offDev[d] ? 'false' : 'true');
b.appendChild(this.el('span', 'lv-chip-l', d));
b.addEventListener('click', function () {
self.offDev[d] = !self.offDev[d];
b.setAttribute('aria-pressed', self.offDev[d] ? 'false' : 'true');
self.listDirty = true;
});
this.devBox.appendChild(b); this.devChips[d] = b;
};
P.vcount = function (n, t, dev, path) {
var m = Math.floor(t / 60), b = this.vbk[m] || (this.vbk[m] = { n: 0 });
b.n += n;
if (path && (this.pathLast.size < 5000 || this.pathLast.has(path))) this.pathLast.set(path, m);
};
P.visit = function (e) {
var s = e.src && typeof e.src === 'object' ? e.src : null, tsec = isNum(e.t) ? e.t : Date.now() / 1000;
var dev = str(e.device, 16), path = str(e.path, 90);
var r = { visit: true, t: tsec, host: str(e.host, 64) || 'local', city: str(s && s.city, 48), cc: cc2(s && s.cc) || cc2(e.cc), domain: str(e.domain, 60), path: path, device: dev, ev: e };
this.noteHost(r.host); if (dev) this.noteDevice(dev);
this.vcount(1, tsec, dev, path);
this.vring.push(r);
if (this.vring.length > 200) this.vring.splice(0, 80);
this.listDirty = true;
if (this.paused || this.hidden || this.offHosts[r.host] || (dev && this.offDev[dev])) return;
var h = this.ctx && this.ctx.host;
if (h && h !== 'all' && h !== r.host) return;
this.map.spawn(e, { visit: true });
};
P.visitBatch = function (e) { if (isNum(e.n) && e.n > 0) this.vcount(Math.min(e.n, 1e6), isNum(e.t) ? e.t : Date.now() / 1000, '', ''); };
P.toggleHost = function (h) {
if (!this.hostChips[h]) return;
this.offHosts[h] = !this.offHosts[h];
@@ -1331,6 +1455,11 @@
else if (e.source === 'fail2ban') what = 'fail2ban [' + str(e.jail, 40) + ']';
var key = tsec + '|' + ip + '|' + e.cat + '|' + what;
if (have) { if (have[key]) return null; have[key] = 1; }
else if (this.es) {
if (this.seen[key]) return null;
this.seen[key] = 1;
if (++this.seenN > 3000) { this.seen = {}; this.seenN = 0; }
}
var r = { t: tsec, key: key, cat: e.cat, host: host, ip: ip, what: what, cc: cc2(s && s.cc) || cc2(e.cc), city: str(s && s.city, 48), ev: e };
this.noteHost(host);
this.ring.push(r);
@@ -1467,6 +1596,16 @@
for (var k in this.bk) if (+k < min - 1500) delete this.bk[k];
};
P.visitMetrics = function (min, fmtN) {
var vn = 0, pg = 0, vi, mm = this.mM, self = this;
for (vi = min - 14; vi <= min; vi++) if (this.vbk[vi]) vn += this.vbk[vi].n;
this.pathLast.forEach(function (last) { if (last >= min - 14) pg++; });
mm.vis.val.textContent = fmtN(vn); this.setSub(mm.vis, this.t('live.legend.visits'), '');
mm.pages.val.textContent = fmtN(pg); this.setSub(mm.pages, this.t('live.unit.pages'), '');
this.pathLast.forEach(function (last, p) { if (last < min - 30) self.pathLast.delete(p); });
for (var vk in this.vbk) if (+vk < min - 40) delete this.vbk[vk];
};
P.regionName = function (cc) {
if (this.U.fmt && this.U.fmt.country) { var n = this.U.fmt.country(cc); if (n) return n; }
var lang = this.ctx.lang || undefined;
@@ -1482,6 +1621,7 @@
var fmtN = this.U.fmt && this.U.fmt.num ? this.U.fmt.num : String;
var fl = this.U.fmt && this.U.fmt.flag ? this.U.fmt.flag : function () { return ''; };
if (min !== this.minute) { this.minute = min; this.computeMetrics(min, fmtN); }
if (this.visitsOn) this.visitMetrics(min, fmtN);
// category and server counts, origins: the 15 minute window (partial minute included)
var a = this.agg(min - 14, min, true), vis = this.agg(min - 14, min, false), c;
CATS.forEach(function (k) {
@@ -1541,8 +1681,20 @@
var box = this.recList, ring = this.ring, n = 0, self = this, i, r;
var fl = this.U.fmt && this.U.fmt.flag ? this.U.fmt.flag : function () { return ''; };
while (box.firstChild) box.removeChild(box.firstChild);
for (i = ring.length - 1; i >= 0 && n < 30; i--) {
r = ring[i];
var merged = ring;
if (this.visitsOn && this.vring.length) merged = ring.concat(this.vring).sort(function (a, b) { return a.t - b.t; });
for (i = merged.length - 1; i >= 0 && n < 30; i--) {
r = merged[i];
if (r.visit) {
if (!this.hostOk(r.host) || (r.device && this.offDev[r.device])) continue;
n++;
var vl = this.el('li', 'lv-ev lv-ev-visit');
vl.appendChild(this.el('time', 'lv-ev-t', new Date(r.t * 1000).toLocaleTimeString(this.ctx.lang || undefined, { hour: '2-digit', minute: '2-digit', second: '2-digit' })));
vl.appendChild(this.el('span', 'lv-tag lv-k-visit', this.t('live.visit')));
vl.appendChild(this.el('span', 'lv-vtxt', [r.city || this.t('live.vis.empty'), r.domain, r.path, r.device].filter(Boolean).join(' \u00B7 ')));
box.appendChild(vl);
continue;
}
if (!this.visible(r)) continue;
n++;
var li = this.el('li', 'lv-ev');
+28
View File
@@ -0,0 +1,28 @@
/* MITRE ATT&CK page */
.mt-page { display: grid; gap: var(--grid-gap, 16px); min-width: 0; }
.mt-matrix { display: grid; gap: var(--s-3, 12px); grid-template-columns: repeat(auto-fit, minmax(10.5rem, 1fr)); }
.mt-col { display: flex; flex-direction: column; gap: 6px; min-width: 0; }
.mt-th { display: flex; flex-direction: column; padding: 6px 8px; border-bottom: 2px solid var(--accent); min-width: 0; }
.mt-th strong { font: 700 .875rem/1.25 var(--font-display, inherit); color: var(--heading, var(--ink)); overflow-wrap: anywhere; }
.mt-th-sub { color: var(--ink-muted); font-size: .75rem; }
.mt-cell { display: grid; grid-template-columns: 1fr auto; gap: 0 8px; text-align: left; cursor: pointer; min-width: 0;
color: var(--ink); font: inherit; padding: 7px 9px; border-radius: 6px; border: 1px solid var(--line);
background: color-mix(in srgb, var(--accent) calc(var(--i, .1) * 60%), var(--surface-panel)); }
.mt-cell:hover, .mt-cell:focus-visible { border-color: var(--accent); }
.mt-cell.on { outline: 2px solid var(--accent); outline-offset: 1px; }
.mt-id { font: 600 .75rem/1.2 var(--font-mono, monospace); color: var(--ink-muted); grid-column: 1; }
.mt-n { grid-column: 2; grid-row: 1 / span 2; align-self: center; font-weight: 700; }
.mt-name { grid-column: 1; font-size: .8125rem; line-height: 1.25; overflow-wrap: anywhere; }
.mt-table { width: 100%; border-collapse: collapse; font-size: .875rem; }
.mt-table th, .mt-table td { text-align: left; padding: 6px 8px; border-bottom: 1px solid var(--line); vertical-align: top; overflow-wrap: anywhere; }
.mt-table th.num, .mt-table td.num { text-align: right; }
.mt-tablewrap { min-width: 0; max-width: 100%; }
.mt-link { color: var(--accent); font-family: var(--font-mono, monospace); }
.mt-trend { white-space: nowrap; font-size: .8125rem; }
.mt-up { color: var(--danger); } .mt-down { color: var(--ok); } .mt-flat, .mt-new { color: var(--ink-muted); }
.mt-drill { margin-top: var(--s-4, 16px); padding-top: var(--s-3, 12px); border-top: 1px solid var(--line); }
.mt-drill-h { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.mt-drill-h h3 { margin-right: auto; font-size: 1rem; overflow-wrap: anywhere; }
.mt-drill h4 { margin: 12px 0 6px; font-size: .875rem; color: var(--ink-muted); }
.mt-ips { display: flex; flex-wrap: wrap; gap: 6px; }
.mt-path { font-family: var(--font-mono, monospace); }
Loaded 100 of 134 files, more files were not shown because too many files have changed in this diff. Show more