Compare commits

..
15 Commits
Author SHA1 Message Date
Lucas RayanandClaude Opus 5.5 3c7caef0c8 fix: 1.5.1 incidents status deep link and creation history wording
Release / Publish tags (push) Successful in 14s
Release / Plan (reuse the published image?) (push) Successful in 4s
Release / ci (push) Successful in 1m21s
Release / Build image (amd64) (push) Successful in 24s
Release / Build image (arm64) (push) Successful in 1m12s
CI / Format and vet (push) Successful in 48s
CI / Tests (Linux, race detector) (push) Successful in 1m7s
CI / Dependency audit (push) Successful in 33s
CI / Docker image (build and smoke test) (push) Skipped
Release / Gitea release (push) Successful in 5s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 09:33:56 -03:00
Lucas RayanandClaude Opus 5.5 e5058968e2 feat: 1.5.0 incident management (tickets from egress findings, triage, comments, suppression with expiry)
Release / Publish tags (push) Successful in 14s
Release / Plan (reuse the published image?) (push) Successful in 5s
Release / ci (push) Successful in 1m14s
Release / Build image (amd64) (push) Successful in 24s
Release / Build image (arm64) (push) Successful in 1m13s
CI / Format and vet (push) Successful in 41s
CI / Tests (Linux, race detector) (push) Successful in 1m1s
CI / Dependency audit (push) Successful in 33s
CI / Docker image (build and smoke test) (push) Skipped
Release / Gitea release (push) Successful in 4s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 09:18:06 -03:00
Lucas RayanandClaude Opus 5.5 3ae72e27d6 fix: 1.4.8 egress false positives (non-SYN replies, IMDS on host, Akamai/Telegram)
Release / Publish tags (push) Successful in 13s
Release / Plan (reuse the published image?) (push) Successful in 5s
Release / ci (push) Successful in 1m20s
Release / Build image (amd64) (push) Successful in 24s
Release / Build image (arm64) (push) Successful in 1m11s
Release / Gitea release (push) Skipped
CI / Format and vet (push) Successful in 51s
CI / Tests (Linux, race detector) (push) Successful in 50s
CI / Dependency audit (push) Successful in 29s
CI / Docker image (build and smoke test) (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 08:51:42 -03:00
Lucas RayanandClaude Opus 5.5 873219416f fix: 1.4.7 default unban log path
Release / Plan (reuse the published image?) (push) Successful in 4s
Release / Gitea release (push) Successful in 5s
Release / Publish tags (push) Successful in 19s
CI / Format and vet (push) Successful in 33s
CI / Tests (Linux, race detector) (push) Successful in 37s
CI / Dependency audit (push) Successful in 37s
Release / ci (push) Successful in 1m10s
Release / Build image (amd64) (push) Successful in 23s
Release / Build image (arm64) (push) Successful in 1m20s
CI / Docker image (build and smoke test) (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 02:01:31 -03:00
Lucas RayanandClaude Opus 5.5 da333d70f1 feat: 1.4.6 unban from the UI, operator allows, day-counter fallback for long windows
Release / Publish tags (push) Successful in 16s
Release / ci (push) Successful in 1m47s
Release / Build image (amd64) (push) Successful in 21s
Release / Build image (arm64) (push) Successful in 23s
CI / Format and vet (push) Successful in 27s
CI / Tests (Linux, race detector) (push) Successful in 1m20s
CI / Dependency audit (push) Successful in 31s
CI / Docker image (build and smoke test) (push) Skipped
Release / Plan (reuse the published image?) (push) Successful in 4s
Release / Gitea release (push) Successful in 5s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 01:53:24 -03:00
Lucas RayanandClaude Opus 5.5 1ef5a0ce9f fix: 1.4.5 second firewall uses history, reputation and a periodic sweep
Release / Publish tags (push) Successful in 15s
Release / Plan (reuse the published image?) (push) Successful in 5s
Release / ci (push) Successful in 1m2s
Release / Build image (amd64) (push) Successful in 21s
Release / Build image (arm64) (push) Successful in 1m10s
CI / Format and vet (push) Successful in 26s
CI / Tests (Linux, race detector) (push) Successful in 20s
CI / Dependency audit (push) Successful in 35s
CI / Docker image (build and smoke test) (push) Skipped
Release / Gitea release (push) Successful in 4s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 01:37:25 -03:00
Lucas RayanandClaude Opus 5.5 0dc3268b29 fix: 1.4.4 read Traefik text logs, degraded source alert, mobile menu
Release / Publish tags (push) Successful in 16s
Release / Plan (reuse the published image?) (push) Successful in 5s
Release / ci (push) Successful in 1m46s
Release / Build image (amd64) (push) Successful in 21s
Release / Build image (arm64) (push) Successful in 23s
CI / Format and vet (push) Successful in 24s
CI / Tests (Linux, race detector) (push) Successful in 1m22s
CI / Dependency audit (push) Successful in 27s
CI / Docker image (build and smoke test) (push) Skipped
Release / Gitea release (push) Successful in 4s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 01:20:03 -03:00
Lucas RayanandClaude Opus 5.5 50cd2bd3ce fix: mobile More menu scrolls when it is taller than the screen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 01:18:10 -03:00
Lucas RayanandClaude Opus 5.5 045ed53e43 feat: 1.4.3 Tor lists and classification, egress provider and peer allowlist
Release / Publish tags (push) Successful in 17s
Release / Plan (reuse the published image?) (push) Successful in 6s
Release / ci (push) Successful in 59s
Release / Build image (amd64) (push) Successful in 24s
Release / Build image (arm64) (push) Successful in 1m29s
CI / Format and vet (push) Successful in 26s
CI / Tests (Linux, race detector) (push) Successful in 33s
CI / Dependency audit (push) Successful in 33s
CI / Docker image (build and smoke test) (push) Skipped
Release / Gitea release (push) Successful in 4s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 00:57:22 -03:00
Lucas RayanandClaude Opus 5.5 ec46fb94ff feat: 1.4.2 services page redesign
Release / Publish tags (push) Successful in 14s
Release / Plan (reuse the published image?) (push) Successful in 5s
Release / ci (push) Successful in 58s
Release / Build image (amd64) (push) Successful in 21s
Release / Build image (arm64) (push) Successful in 1m19s
CI / Format and vet (push) Successful in 37s
CI / Tests (Linux, race detector) (push) Successful in 34s
CI / Dependency audit (push) Successful in 21s
CI / Docker image (build and smoke test) (push) Skipped
Release / Gitea release (push) Successful in 4s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 00:30:50 -03:00
Lucas RayanandClaude Opus 5.5 432f521ed1 feat: 1.4.1 pagination, network probes, survival by blocker, report polish
Release / Publish tags (push) Successful in 18s
Release / Plan (reuse the published image?) (push) Successful in 5s
Release / ci (push) Successful in 1m47s
Release / Build image (amd64) (push) Successful in 21s
Release / Build image (arm64) (push) Successful in 28s
CI / Format and vet (push) Successful in 23s
CI / Tests (Linux, race detector) (push) Successful in 1m24s
CI / Dependency audit (push) Successful in 24s
CI / Docker image (build and smoke test) (push) Skipped
Release / Gitea release (push) Successful in 5s
Backend pagination with one pager for sessions, IPs, campaigns and events;
network probe source (port-scan, T1046, second firewall reason port-scan);
host kit logs inbound probes; urutau call on the report cover.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 00:21:43 -03:00
Lucas RayanandClaude Opus 5.5 f27d8441a9 fix: report preview is always an A4 sheet, scaled to fit
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 00:09:17 -03:00
Lucas RayanandClaude Opus 5.5 b267b98f18 feat: outbound traffic page redesign
Verdict, evidence cards (beacon rhythm and interval histogram), destination
map, workload x hour heatmap, compact workloads, authorised scan timeline.
API: findings[].samples and by_country.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 00:08:15 -03:00
Lucas RayanandClaude Opus 5.5 9bdfdb491b feat: report preview page, sharp report logo, time to ban by blocker
The Reports page now previews the HTML report itself (same document as the
download and the print), with only Download and Print. The report logo is
the repository logo at 800 px. Survival splits fail2ban and the Urutau
second firewall.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 00:06:29 -03:00
Lucas RayanandClaude Opus 5.5 5d3374ee11 docs: screenshots of every page, egress and enforce demo data
Release / Plan (reuse the published image?) (push) Successful in 5s
Release / ci (push) Skipped
Release / Build image (amd64) (push) Skipped
Release / Build image (arm64) (push) Skipped
Release / Publish tags (push) Successful in 14s
Release / Gitea release (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 23:51:34 -03:00
174 changed files with 7788 additions and 1131 deletions

No files matched your search

+80 -1
View File
@@ -4,7 +4,86 @@
Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versions follow SemVer.
## [Unreleased]
## [1.5.1] - 2026-11-15
### Fixed
- Incidents: the list accepts `?status=` in the link (alias of `?s=`), so `#/incidents?status=benign` opens filtered.
- Incidents: the ticket creation entry in the history reads "urutau opened the ticket (severity: …)" instead of "changed created".
## [1.5.0] - 2026-11-15
### Added
- Incident management: every egress finding (severity above info) becomes a ticket `INC-<n>` keyed by `host|kind|workload|dst|dport|proto`, created by a sync on each merged egress report and every 60 s. Tickets have status (`open`, `investigating`, `true_positive`, `false_positive`, `benign`, `resolved`), severity, assignee, tags, verdict, comments and a change history; a resolved ticket reopens when the finding reappears. Stored in `<data-dir>/incidents.json` (atomic write, 0600; a corrupt file is moved to `.corrupt`); limits of 5000 tickets, 200 comments and 500 history entries each. Every write is also logged (id, field, author).
- A ticket in `false_positive` or `benign` can suppress the findings with exactly its key: they leave `/api/v1/egress` (and the egress report) unless `?suppressed=1`. Findings now carry `ticket_id`, `ticket_status` and `suppressed`, and the response has `suppressed_count`.
- API: `GET /api/v1/incidents`, `GET /api/v1/incidents/{id}`, `POST /api/v1/incidents`, `PATCH /api/v1/incidents/{id}`, `POST /api/v1/incidents/{id}/comments` and `GET /api/v1/incidents/export.csv` (not open to the peer token; writes refuse cross-site requests).
## [1.4.8] - 2026-11-15
### Fixed
- Egress analysis, false positives: the nftables kit now logs only TCP connection attempts (SYN without ACK), so replies of banned clients (conntrack recreated mid-flow) no longer show up as `bad_dst` "attacked us". **Re-run `deploy/host/install.sh --enforce` on the host to apply the new nft rules.**
- Hosts with the old kit: the parser drops TCP lines without a pure SYN and counts them as `non_syn_dropped` in the egress source (not as `malformed`).
- Cloud metadata services (169.254.169.254, `fd00:c1::a9fe:a9fe`, `fd00:ec2::254`, link-local) polled by the host itself are `infra` (info), not beacon; a container reaching them stays a finding (SSRF/credential theft).
- Regular connections to Akamai (AS20940/AS16625 and its main ranges) and Telegram (AS62041, 149.154.160.0/20, 91.108.0.0/16) are `low` ("large CDN/cloud network"). Hetzner (e.g. SURBL updates) stays `medium`: there is no name correlation, and no IP is hardcoded.
## [1.4.7] - 2026-11-15
### Fixed
- The unban file now defaults to `unban.log` next to `--enforce-log` (the default was lost, so the Unban button reported the file as not writable).
- Second firewall: the 24 h rules also count from the persistent day counters, so they work when the event registry does not cover the whole day (after a reset or upgrade).
## [1.4.6] - 2026-11-15
### Added
- Unban from the interface: an "Unban" button on recent decisions and on the address page asks the host (through `unban.log` next to `--enforce-log`, flag `--enforce-unban-log`) to lift the fail2ban block, and can keep the second firewall from banning the address again for 1 h, 24 h or 7 days (operator releases, listed and endable in Defense; shared with peers when sharing is on). API: `POST /api/v1/enforce/unban`, `DELETE /api/v1/enforce/allow`, `allows` in `GET /api/v1/enforce`.
## [1.4.5] - 2026-11-15
### Fixed
- Second firewall: it now uses the history. An address whose verdict is hostile (or suspicious with score 100 or more) is banned on its first new malicious event (`known-attacker`); 10 SSH failures or 20 web scan/exploit events in 24 h also ban (slow attackers); a sweep every 10 minutes (and after the start-up backfill) bans the addresses active in the last 24 h that nothing blocks yet, at most `--enforce-max-per-min` per minute, with every exclusion kept. Coverage in `/api/v1/enforce` is computed from the store, so it survives restarts.
## [1.4.4] - 2026-11-15
### Fixed
- Traefik access logs in the default text format are now read too (fewer fields than JSON: no host or service), so a proxy that loses its JSON setting no longer silently drops the web traffic.
- A source with more than 20% unreadable lines in its last 1000 is shown as degraded (red) in Integrity and Sources, logged once an hour, and checked by `urutau doctor`.
- Mobile: the More menu scrolls when it is taller than the screen.
## [1.4.3] - 2026-11-15
### Added
- Tor network: the official exit and relay lists are downloaded every 6 hours (`URUTAU_TOR_AUTO`, cached in the data directory). Requests from Tor exits are marked `tor`; a workload talking to a Tor relay is a high outbound finding.
### Fixed
- Outbound traffic: the servers themselves (trusted addresses, peers, local public addresses) never raise findings; regular connections of the host to its own provider (`URUTAU_EGRESS_PROVIDER_ASN` or the provider of its address) are shown as provider services, outside the verdict; regular connections to large CDNs and clouds are low severity unless the destination attacked the server.
## [1.4.2] - 2026-11-15
### Changed
- Services page redesigned: plain-language verdict, KPIs with sparklines, services from worst to best with availability against the 99.5% SLO, error budget left, burn rate, Apdex and latency, and a service detail with requests and errors, how requests were answered, p95 by hour and failing routes split into service errors, blocked attacks and client mistakes. API: `err_spark` in `/api/v1/services`.
## [1.4.1] - 2026-11-15
### Added
- Network probes source (`URUTAU_PROBE_LOG`, default `/logs/host/probe.log`): the host kit logs new inbound connections to ports nobody listens on; each becomes a `port-scan` event (MITRE T1046), and 10 distinct ports in 10 minutes make the second firewall ban the address (reason `port-scan`).
- Survival: who blocked and how fast, the host fail2ban jails apart from the Urutau second firewall.
- Pagination in the backend for sessions, IPs, campaigns and the events of an address, with one pager for every list; event search pages by cursor.
### Changed
- Outbound traffic page redesigned: plain-language verdict, evidence cards (beacon rhythm and interval histogram), destination map, activity by hour, compact workloads and the timeline of authorised scans. API: `findings[].samples`, `by_country`.
- Reports page: a preview of the HTML report itself, always an A4 sheet scaled to the screen, with only Download and Print; language selector, period and server from the header.
- Report: sharp logo (the repository logo at 800 px) and the cover drawing is now the urutau's call, five descending notes.
## [1.4.0] - 2026-11-15
+80 -1
View File
@@ -4,7 +4,86 @@
Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/); versionamento segue SemVer.
## [Unreleased]
## [1.5.1] - 2026-11-15
### Corrigido
- Incidentes: a lista aceita `?status=` no link (sinônimo de `?s=`), então `#/incidents?status=benign` abre filtrado.
- Incidentes: a criação do chamado no histórico aparece como "urutau abriu o chamado (severidade: …)" em vez de "alterou created".
## [1.5.0] - 2026-11-15
### Adicionado
- Gestão de incidentes: cada achado de egress (severidade acima de info) vira um chamado `INC-<n>` com chave `host|kind|workload|dst|dport|proto`, criado por uma sincronização a cada relatório de egress mesclado e a cada 60 s. O chamado tem status (`open`, `investigating`, `true_positive`, `false_positive`, `benign`, `resolved`), severidade, responsável, etiquetas, conclusão, comentários e histórico de mudanças; um chamado resolvido reabre quando o achado reaparece. Fica em `<data-dir>/incidents.json` (escrita atômica, 0600; arquivo corrompido vai para `.corrupt`); limites de 5000 chamados, 200 comentários e 500 entradas de histórico cada. Toda escrita também vai para o log (id, campo, autor).
- Um chamado em `false_positive` ou `benign` pode suprimir os achados com exatamente a sua chave: eles saem de `/api/v1/egress` (e do relatório de egress), salvo com `?suppressed=1`. Os achados agora trazem `ticket_id`, `ticket_status` e `suppressed`, e a resposta tem `suppressed_count`.
- API: `GET /api/v1/incidents`, `GET /api/v1/incidents/{id}`, `POST /api/v1/incidents`, `PATCH /api/v1/incidents/{id}`, `POST /api/v1/incidents/{id}/comments` e `GET /api/v1/incidents/export.csv` (fechada ao token de peer; escritas recusam requisições cross-site).
## [1.4.8] - 2026-11-15
### Corrigido
- Análise de egress, falsos positivos: o kit nftables agora registra só tentativas de conexão TCP (SYN sem ACK), então respostas a clientes banidos (conntrack recriado no meio do fluxo) não aparecem mais como `bad_dst` "nos atacou". **Rode `deploy/host/install.sh --enforce` de novo no host para aplicar o nft novo.**
- Hosts com o kit antigo: o parser descarta linhas TCP sem SYN puro e as conta como `non_syn_dropped` na fonte de egress (não como `malformed`).
- Serviços de metadados de nuvem (169.254.169.254, `fd00:c1::a9fe:a9fe`, `fd00:ec2::254`, link-local) consultados pelo próprio host são `infra` (info), não beacon; container acessando continua alerta (SSRF/roubo de credencial).
- Conexões regulares para Akamai (AS20940/AS16625 e faixas principais) e Telegram (AS62041, 149.154.160.0/20, 91.108.0.0/16) ficam `low` ("rede grande de CDN/nuvem"). Hetzner (ex.: atualização do SURBL) continua `medium`: não há correlação por nome e nenhum IP foi fixado no código.
## [1.4.7] - 2026-11-15
### Corrigido
- O arquivo de desban agora tem como padrão `unban.log` ao lado de `--enforce-log` (o padrão se perdia, e o botão Desbanir dizia que o arquivo não era gravável).
- Segundo firewall: as regras de 24 h também contam pelos contadores diários persistentes, então funcionam quando o registro de eventos não cobre o dia inteiro (após um reset ou atualização).
## [1.4.6] - 2026-11-15
### Adicionado
- Desbanir pela interface: botão "Desbanir" nas decisões recentes e na página do endereço pede ao host (por `unban.log` ao lado de `--enforce-log`, flag `--enforce-unban-log`) que libere o bloqueio do fail2ban, e pode impedir o segundo firewall de banir de novo por 1 h, 24 h ou 7 dias (liberações do operador, listadas e encerráveis em Defesa; compartilhadas com os parceiros quando o compartilhamento está ligado). API: `POST /api/v1/enforce/unban`, `DELETE /api/v1/enforce/allow`, `allows` em `GET /api/v1/enforce`.
## [1.4.5] - 2026-11-15
### Corrigido
- Segundo firewall: agora usa o histórico. Endereço com veredito hostil (ou suspeito com score 100 ou mais) é banido no primeiro evento malicioso novo (`known-attacker`); 10 falhas SSH ou 20 eventos de varredura/exploração web em 24 h também banem (atacantes lentos); uma varredura a cada 10 minutos (e após o backfill da partida) bane os endereços ativos nas últimas 24 h que nada bloqueia ainda, no máximo `--enforce-max-per-min` por minuto, mantidas todas as exclusões. A cobertura de `/api/v1/enforce` sai do store e sobrevive a reinícios.
## [1.4.4] - 2026-11-15
### Corrigido
- O log de acesso do Traefik no formato texto padrão agora também é lido (menos campos que o JSON: sem host nem serviço), então um proxy que perde a configuração JSON não descarta mais o tráfego web em silêncio.
- Uma fonte com mais de 20% de linhas ilegíveis nas últimas 1000 aparece como degradada (vermelho) em Integridade e Fontes, é registrada no log uma vez por hora e é verificada pelo `urutau doctor`.
- Celular: o menu Mais rola quando é maior que a tela.
## [1.4.3] - 2026-11-15
### Adicionado
- Rede Tor: as listas oficiais de saídas e relays são baixadas a cada 6 horas (`URUTAU_TOR_AUTO`, com cache no diretório de dados). Requisições vindas de saídas Tor são marcadas `tor`; um workload falando com um relay Tor é um achado de saída de gravidade alta.
### Corrigido
- Tráfego de saída: os próprios servidores (endereços confiáveis, peers, endereços públicos locais) nunca geram achados; conexões regulares do host com o próprio provedor (`URUTAU_EGRESS_PROVIDER_ASN` ou o provedor do seu endereço) aparecem como serviços do provedor, fora do veredito; conexões regulares com grandes CDNs e nuvens têm gravidade baixa, salvo se o destino atacou o servidor.
## [1.4.2] - 2026-11-15
### Alterado
- Página Serviços refeita: veredito em linguagem leiga, indicadores com mini gráficos, serviços dos piores para os melhores com disponibilidade contra o SLO de 99,5%, orçamento de erro restante, consumo, Apdex e latência, e detalhe do serviço com requisições e erros, como as requisições foram respondidas, p95 por hora e rotas que falham separadas em erros do serviço, ataques barrados e enganos do cliente. API: `err_spark` em `/api/v1/services`.
## [1.4.1] - 2026-11-15
### Adicionado
- Fonte de sondagens de rede (`URUTAU_PROBE_LOG`, padrão `/logs/host/probe.log`): o kit do host registra conexões novas de entrada para portas em que nada escuta; cada uma vira um evento `port-scan` (MITRE T1046), e 10 portas distintas em 10 minutos fazem o segundo firewall banir o endereço (motivo `port-scan`).
- Sobrevivência: quem bloqueou e com que rapidez, os jails do fail2ban do host separados do segundo firewall do Urutau.
- Paginação no backend para sessões, IPs, campanhas e eventos de um endereço, com um paginador único em todas as listas; a busca de eventos pagina por cursor.
### Alterado
- Página Tráfego de saída refeita: veredito em linguagem leiga, cartões de evidência (ritmo do beacon e histograma dos intervalos), mapa de destinos, atividade por hora, workloads compactos e a linha do tempo das varreduras autorizadas. API: `findings[].samples`, `by_country`.
- Página Relatórios: prévia do próprio relatório HTML, sempre uma folha A4 em escala, só com Baixar e Imprimir; seletor de idioma, período e servidor do topo.
- Relatório: logo nítida (a logo do repositório em 800 px) e o desenho da capa agora é o canto do urutau, cinco notas descendentes.
## [1.4.0] - 2026-11-15
+4
View File
@@ -14,6 +14,10 @@
<p align="center"><img src="docs/img/ip-analysis-dark.png" width="900" alt="Urutau IP analysis page: verdict, score, critical exposure and recommended actions for one attacker"><br><sub>IP analysis: verdict, evidence and recommended actions for one address.</sub></p>
<p align="center"><img src="docs/img/defense-dark.png" width="900" alt="Urutau defense page with the second firewall section"><br><sub>Defense: the second firewall in observe mode, next to the host fail2ban.</sub></p>
<p align="center"><img src="docs/img/egress-dark.png" width="900" alt="Egress"><br><sub>Egress: scan bursts, beacons and mining from containers.</sub></p>
**Status: stable, v1.0.0.** See [CHANGELOG.md](CHANGELOG.md) for exactly what shipped.
Urutau is a small panel that runs on each of your servers (as a container), reads the logs the server already writes, and answers one question: who is attacking me right now? It classifies hostile activity, scores every source IP, keeps a rolling window on disk and serves an embedded dashboard, a JSON API and an exportable blocklist.
+4
View File
@@ -14,6 +14,10 @@
<p align="center"><img src="docs/img/ip-analysis-dark-pt.png" width="900" alt="Página de análise de IP do Urutau: veredito, pontuação, exposição crítica e ações recomendadas para um atacante"><br><sub>Análise de IP: veredito, evidências e ações recomendadas para um endereço.</sub></p>
<p align="center"><img src="docs/img/defense-dark-pt.png" width="900" alt="Página Defesa do Urutau com a seção do segundo firewall"><br><sub>Defesa: o segundo firewall em modo observe, ao lado do fail2ban do host.</sub></p>
<p align="center"><img src="docs/img/egress-dark-pt.png" width="900" alt="Egress"><br><sub>Saída: rajadas de varredura, beacons e mineração em contêineres.</sub></p>
**Status: estável, v1.0.0.** Veja o [CHANGELOG.pt-BR.md](CHANGELOG.pt-BR.md) para saber exatamente o que foi entregue.
O Urutau é um painel pequeno que roda em cada um dos seus servidores (como container), lê os logs que o servidor já escreve e responde a uma pergunta: quem está me atacando agora? Ele classifica a atividade hostil, pontua cada IP de origem, mantém uma janela móvel em disco e serve um dashboard embutido, uma API JSON e uma blocklist exportável.
+7
View File
@@ -5,3 +5,10 @@ if ($syslogfacility-text == "kern" and $msg contains "URUTAU-EGRESS: ") then {
fileOwner="syslog" fileGroup="adm" fileCreateMode="0640")
stop
}
# inbound probes to closed ports (port scans)
if ($syslogfacility-text == "kern" and $msg contains "URUTAU-PROBE: ") then {
action(type="omfile" file="/var/log/urutau/probe.log" template="RSYSLOG_FileFormat"
fileOwner="syslog" fileGroup="adm" fileCreateMode="0640")
stop
}
+8 -2
View File
@@ -15,12 +15,13 @@ 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
systemctl disable --now urutau-egress.service urutau-containers-map.timer urutau-logrotate.timer urutau-unban.path 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
/etc/systemd/system/urutau-logrotate.service /etc/systemd/system/urutau-logrotate.timer \
/etc/systemd/system/urutau-unban.path /etc/systemd/system/urutau-unban.service /usr/local/sbin/urutau-unban
rm -rf /etc/urutau
systemctl daemon-reload
systemctl restart rsyslog
@@ -57,6 +58,11 @@ if [ "${1:-}" = "--enforce" ]; then
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
[ -e /var/log/urutau-enforce/unban.log ] || install -m 0640 -o "$uid" -g adm /dev/null /var/log/urutau-enforce/unban.log
install -m 0755 "$here/urutau-unban" /usr/local/sbin/urutau-unban
install -m 0644 "$here/urutau-unban.path" "$here/urutau-unban.service" /etc/systemd/system/
systemctl daemon-reload
systemctl enable --now urutau-unban.path >/dev/null
fail2ban-client -t >/dev/null
fail2ban-client reload
echo "fail2ban jail 'urutau' on; mount /var/log/urutau-enforce:/logs/enforce (rw) in the container"
+19
View File
@@ -11,3 +11,22 @@ docker ps -q | xargs -r docker inspect -f '{{$n := .Name}}{{range .NetworkSettin
chgrp adm "$tmp"; chmod 0640 "$tmp"
mv -f "$tmp" "$out"
trap - EXIT
# The real upstream resolvers (systemd-resolved hides them behind 127.0.0.53),
# so DNS to the provider resolver is not reported as a bypass.
r=/var/log/urutau/resolv.conf
{
resolvectl dns 2>/dev/null | tr ' ' '\n' | grep -E '^([0-9]{1,3}\.){3}[0-9]{1,3}$|^[0-9a-fA-F]*:[0-9a-fA-F:]+$' || true
awk '/^nameserver/ {print $2}' /run/systemd/resolve/resolv.conf 2>/dev/null || true
} | grep -vE '^127\.' | sort -u | sed 's/^/nameserver /' > "$r.tmp"
chgrp adm "$r.tmp"; chmod 0640 "$r.tmp"; mv -f "$r.tmp" "$r"
# Ports this host serves (listening sockets, including the ones Docker
# publishes): connections to any other port are logged as probes.
if nft list set inet urutau_egress open >/dev/null 2>&1; then
{
echo "flush set inet urutau_egress open"
ss -Hlnt | awk '{print $4}' | sed -n 's/.*:\([0-9][0-9]*\)$/tcp . \1/p'
ss -Hlnu | awk '{print $4}' | sed -n 's/.*:\([0-9][0-9]*\)$/udp . \1/p'
} | sort -u | awk 'NR==1 {print; next} {e = e (e ? ", " : "") $0} END {if (e) print "add element inet urutau_egress open { " e " }"}' | nft -f -
fi
+24 -1
View File
@@ -1,5 +1,6 @@
#!/usr/sbin/nft -f
# Urutau: logs NEW outbound connections (host and containers) so the egress
# Urutau: logs NEW outbound connections (host and containers), and inbound
# probes to closed ports, 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).
@@ -21,6 +22,10 @@ table inet urutau_egress {
set seen6 { type ipv6_addr . ipv6_addr . inet_proto . inet_service; flags dynamic, timeout; timeout 2h; size 131072; }
chain egress {
# only real connection attempts (SYN without ACK): replies of flows whose
# conntrack entry was recreated mid-flow (nf_conntrack_tcp_loose=1, e.g.
# after fail2ban drops only the original direction) are not egress
meta l4proto tcp tcp flags & (syn | ack) != syn return
# 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
@@ -32,6 +37,24 @@ table inet urutau_egress {
meta nfproto ipv6 meta l4proto != { tcp, udp } add @rl6 { ip6 saddr limit rate 20/second burst 100 packets } log prefix "URUTAU-EGRESS: " level info
}
# inbound probes: NEW connections to ports nobody listens on (port scans,
# RDP/SMB/database probing). @open is refreshed every minute by
# urutau-containers-map from `ss` (it also sees ports Docker publishes).
set open { type inet_proto . inet_service; }
set prl4 { type ipv4_addr; flags dynamic; timeout 2m; size 65535; }
set prl6 { type ipv6_addr; flags dynamic; timeout 2m; size 65535; }
chain probe_log {
type filter hook prerouting priority -150; policy accept;
iifname != "@WAN@" return
ct state != new return
meta l4proto != { tcp, udp } return
fib daddr type != local return
meta l4proto . th dport @open return
meta nfproto ipv4 add @prl4 { ip saddr limit rate 10/second burst 50 packets } log prefix "URUTAU-PROBE: " level info
meta nfproto ipv6 add @prl6 { ip6 saddr limit rate 10/second burst 50 packets } log prefix "URUTAU-PROBE: " level info
}
chain forward_log {
type filter hook forward priority filter - 10; policy accept;
ct state new oifname "@WAN@" iifname != "@WAN@" jump egress
+1
View File
@@ -7,6 +7,7 @@ Wants=network-online.target
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/sbin/nft -f /etc/urutau/egress.nft
ExecStartPost=-/usr/local/sbin/urutau-containers-map
ExecStop=/usr/sbin/nft delete table inet urutau_egress
[Install]
+31
View File
@@ -0,0 +1,31 @@
#!/bin/sh
# Urutau: applies the operator's unban requests written by Urutau (UI button)
# to /var/log/urutau-enforce/unban.log. One line per request:
# 2026-11-15T05:00:00Z urutau unban ip=203.0.113.7 allow=86400
# The address is validated strictly; fail2ban unbans it from every jail and,
# with allow>0, ignores it in every jail for that many seconds (pentests).
set -eu
log=/var/log/urutau-enforce/unban.log
state=/var/lib/urutau/unban.offset
[ -f "$log" ] || exit 0
mkdir -p /var/lib/urutau
off=$(cat "$state" 2>/dev/null || echo 0)
size=$(stat -c %s "$log")
[ "$size" -lt "$off" ] && off=0 # rotated or truncated
tail -c +"$((off + 1))" "$log" | head -n 1000 | while IFS= read -r line; do
ip=$(printf '%s\n' "$line" | sed -n 's/^[0-9TZ:-]* urutau unban ip=\([0-9a-fA-F.:]\{2,45\}\) allow=\([0-9]\{1,7\}\)$/\1/p')
allow=$(printf '%s\n' "$line" | sed -n 's/^.* allow=\([0-9]\{1,7\}\)$/\1/p')
[ -n "$ip" ] || continue
# only literal IPv4 / IPv6 addresses (no CIDR, no names)
python3 -c 'import ipaddress,sys; ipaddress.ip_address(sys.argv[1])' "$ip" 2>/dev/null || continue
fail2ban-client unban "$ip" >/dev/null 2>&1 || true
logger -t urutau-unban "unban $ip allow=${allow:-0}"
if [ "${allow:-0}" -gt 0 ]; then
for j in $(fail2ban-client status | sed -n 's/.*Jail list:[[:space:]]*//p' | tr ',' ' '); do
fail2ban-client set "$j" addignoreip "$ip" >/dev/null 2>&1 || true
done
systemd-run --quiet --on-active="${allow}s" --unit="urutau-allow-end-$(printf '%s' "$ip" | tr ':.' '--')" \
/bin/sh -c "for j in \$(fail2ban-client status | sed -n 's/.*Jail list:[[:space:]]*//p' | tr ',' ' '); do fail2ban-client set \$j delignoreip $ip; done" 2>/dev/null || true
fi
done
echo "$size" > "$state"
+8
View File
@@ -0,0 +1,8 @@
[Unit]
Description=Urutau: watch the operator's unban requests
[Path]
PathModified=/var/log/urutau-enforce/unban.log
[Install]
WantedBy=multi-user.target
+6
View File
@@ -0,0 +1,6 @@
[Unit]
Description=Urutau: apply the operator's unban requests
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/urutau-unban
+1 -1
View File
@@ -1,4 +1,4 @@
/var/log/urutau/egress.log {
/var/log/urutau/egress.log /var/log/urutau/probe.log {
daily
rotate 7
maxsize 200M
Binary file not shown.

After

Width:  |  Height:  |  Size: 149 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 145 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 211 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 210 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 211 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 215 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 193 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 186 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 437 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 413 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 421 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 190 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 693 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 677 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 690 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 270 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 225 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 209 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 289 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 154 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 151 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 175 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 154 KiB

After

Width:  |  Height:  |  Size: 171 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 202 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 175 KiB

After

Width:  |  Height:  |  Size: 196 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 166 KiB

After

Width:  |  Height:  |  Size: 188 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 168 KiB

After

Width:  |  Height:  |  Size: 187 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 164 KiB

After

Width:  |  Height:  |  Size: 184 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 219 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 206 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 238 KiB

After

Width:  |  Height:  |  Size: 259 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 236 KiB

After

Width:  |  Height:  |  Size: 255 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 241 KiB

After

Width:  |  Height:  |  Size: 260 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 169 KiB

After

Width:  |  Height:  |  Size: 191 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 170 KiB

After

Width:  |  Height:  |  Size: 190 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 222 KiB

After

Width:  |  Height:  |  Size: 222 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 416 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 372 KiB

After

Width:  |  Height:  |  Size: 391 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 368 KiB

After

Width:  |  Height:  |  Size: 393 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 310 KiB

After

Width:  |  Height:  |  Size: 296 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 596 KiB

After

Width:  |  Height:  |  Size: 612 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 593 KiB

After

Width:  |  Height:  |  Size: 617 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 203 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 196 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 173 KiB

After

Width:  |  Height:  |  Size: 211 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 163 KiB

After

Width:  |  Height:  |  Size: 197 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 167 KiB

After

Width:  |  Height:  |  Size: 203 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 221 KiB

After

Width:  |  Height:  |  Size: 224 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 210 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 188 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 207 KiB

After

Width:  |  Height:  |  Size: 232 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 207 KiB

After

Width:  |  Height:  |  Size: 228 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 162 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 151 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 202 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 194 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 186 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 175 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 390 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 380 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 381 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 312 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 154 KiB

After

Width:  |  Height:  |  Size: 176 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 148 KiB

After

Width:  |  Height:  |  Size: 167 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 198 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 190 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 181 KiB

After

Width:  |  Height:  |  Size: 212 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 162 KiB

After

Width:  |  Height:  |  Size: 189 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 244 KiB

After

Width:  |  Height:  |  Size: 248 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 180 KiB

After

Width:  |  Height:  |  Size: 215 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 172 KiB

After

Width:  |  Height:  |  Size: 204 KiB

+40
View File
@@ -53,6 +53,36 @@ A side rail (a tab bar on phones) holds the pages. Each page opens with a senten
<p align="center"><img src="img/sources-dark.png" width="900" alt="Sources and hosts page: instances, log sources and blocklist"><br><sub>Sources and hosts.</sub></p>
<p align="center"><img src="img/sessions-dark.png" width="900" alt="Page: Sessions"><br><sub>Sessions: the stages of each attacker, with a replay link.</sub></p>
<p align="center"><img src="img/campaigns-dark.png" width="900" alt="Page: Campaigns"><br><sub>Campaigns: coordinated groups of addresses (Gantt and similarity).</sub></p>
<p align="center"><img src="img/campaign-detail-dark.png" width="900" alt="Page: Campaign detail"><br><sub>Campaign detail: members, timeline and shared traits.</sub></p>
<p align="center"><img src="img/search-dark.png" width="900" alt="Page: Search"><br><sub>Search: filter the event registry by IP, path, family and status.</sub></p>
<p align="center"><img src="img/mitre-dark.png" width="900" alt="Page: MITRE ATT&CK"><br><sub>MITRE ATT&CK: techniques observed, by tactic.</sub></p>
<p align="center"><img src="img/defense-dark.png" width="900" alt="Page: Defense, with the second firewall"><br><sub>Defense: coverage of the host fail2ban and the second firewall (observe mode).</sub></p>
<p align="center"><img src="img/egress-dark.png" width="900" alt="Page: Egress traffic"><br><sub>Egress: outbound connections of the host and containers, with scan bursts, beacons and mining.</sub></p>
<p align="center"><img src="img/evolution-dark.png" width="900" alt="Page: Evolution"><br><sub>Evolution: how attacks change over time.</sub></p>
<p align="center"><img src="img/concentration-dark.png" width="900" alt="Page: Concentration"><br><sub>Concentration: how much of the hostility a few sources or networks account for.</sub></p>
<p align="center"><img src="img/survival-dark.png" width="900" alt="Page: Survival"><br><sub>Survival: how long attackers keep coming back.</sub></p>
<p align="center"><img src="img/errors-dark.png" width="900" alt="Page: Errors"><br><sub>Errors: response classes, targets and hosts.</sub></p>
<p align="center"><img src="img/slo-dark.png" width="900" alt="Page: Services"><br><sub>Services: availability and latency of each service.</sub></p>
<p align="center"><img src="img/protocol-dark.png" width="900" alt="Page: Protocols and TLS"><br><sub>Protocols and TLS: HTTP and TLS versions by class.</sub></p>
<p align="center"><img src="img/integrity-dark.png" width="900" alt="Page: Integrity"><br><sub>Integrity: health of the log sources and the registry.</sub></p>
<p align="center"><img src="img/reports-dark.png" width="900" alt="Page: Reports"><br><sub>Reports: the exportable report.</sub></p>
<p align="center"><img src="img/overview-light.png" width="620" alt="Overview in the light theme"> <img src="img/overview-mobile.png" height="420" alt="Overview on a phone"><br><sub>The light theme on a desktop and the phone layout (a tab bar replaces the side rail).</sub></p>
## Page groups
@@ -108,7 +138,17 @@ State and city boundaries on the Geography page are from [Natural Earth](https:/
| `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 |
| `GET /api/v1/incidents` | session or bearer | incident tickets (no comments or history, with `comment_count`). Query: `status` (comma list), `severity`, `host`, `q`, `sort` (`updated`, `severity`, `last_seen`), `page`, `per_page` (max 200). Returns `{items,total,counts}` |
| `GET /api/v1/incidents/{id}` | session or bearer | full ticket with `comments` and `history` |
| `GET /api/v1/incidents/export.csv` | session or bearer | the filtered list as CSV |
| `POST /api/v1/incidents` | session or bearer | opens a manual ticket `{title,detail,severity,host,tags,author}` (body up to 64 KiB, unknown fields refused; cross-site refused) |
| `PATCH /api/v1/incidents/{id}` | session or bearer | partial update `{status,severity,assignee,tags,title,verdict,suppress,author}`; each change is a history entry. `suppress` only in `false_positive` or `benign`, and hides findings with the exact same key in `/api/v1/egress` (add `suppressed=1` to see them) |
| `POST /api/v1/incidents/{id}/comments` | session or bearer | adds a comment `{text,author}` |
An invalid `range` or period answers 400, and `range` in the responses is an object `{name,from,to,step,clipped}` (`step` is the timeline granularity in seconds).
API clients send `Authorization: Bearer <URUTAU_TOKEN>`. The peer token is accepted only by `/api/v1/peer/export`, `/api/v1/peer/stream` and `/api/v1/peer/period`; every other route answers 403 to it.
<p align="center"><img src="img/defense-light.png" width="620" alt="Defense"> <img src="img/defense-mobile.png" height="420" alt="Defense"><br><sub>Defense, egress and campaigns in the light theme and on a phone.</sub></p>
<p align="center"><img src="img/egress-light.png" width="620" alt="Egress"> <img src="img/egress-mobile.png" height="420" alt="Egress"></p>
+40
View File
@@ -50,6 +50,36 @@ Uma barra lateral (barra de abas no celular) reúne as páginas. Cada página ab
<p align="center"><img src="../img/sources-dark-pt.png" width="900" alt="Página Fontes e hosts: instâncias, fontes de log e blocklist"><br><sub>Fontes e hosts.</sub></p>
<p align="center"><img src="../img/sessions-dark-pt.png" width="900" alt="Página: Sessões"><br><sub>Sessões: as etapas de cada atacante, com link para o replay.</sub></p>
<p align="center"><img src="../img/campaigns-dark-pt.png" width="900" alt="Página: Campanhas"><br><sub>Campanhas: grupos coordenados de endereços (Gantt e similaridade).</sub></p>
<p align="center"><img src="../img/campaign-detail-dark-pt.png" width="900" alt="Página: Detalhe da campanha"><br><sub>Detalhe da campanha: membros, linha do tempo e traços em comum.</sub></p>
<p align="center"><img src="../img/search-dark-pt.png" width="900" alt="Página: Busca"><br><sub>Busca: filtre o registro de eventos por IP, caminho, família e status.</sub></p>
<p align="center"><img src="../img/mitre-dark-pt.png" width="900" alt="Página: MITRE ATT&CK"><br><sub>MITRE ATT&CK: técnicas observadas, por tática.</sub></p>
<p align="center"><img src="../img/defense-dark-pt.png" width="900" alt="Página: Defesa, com o segundo firewall"><br><sub>Defesa: cobertura do fail2ban do host e do segundo firewall (modo observe).</sub></p>
<p align="center"><img src="../img/egress-dark-pt.png" width="900" alt="Página: Tráfego de saída"><br><sub>Saída: conexões de saída do host e dos contêineres, com rajadas de varredura, beacons e mineração.</sub></p>
<p align="center"><img src="../img/evolution-dark-pt.png" width="900" alt="Página: Evolução"><br><sub>Evolução: como os ataques mudam ao longo do tempo.</sub></p>
<p align="center"><img src="../img/concentration-dark-pt.png" width="900" alt="Página: Concentração"><br><sub>Concentração: quanto da hostilidade poucas fontes ou redes explicam.</sub></p>
<p align="center"><img src="../img/survival-dark-pt.png" width="900" alt="Página: Sobrevivência"><br><sub>Sobrevivência: por quanto tempo os atacantes continuam voltando.</sub></p>
<p align="center"><img src="../img/errors-dark-pt.png" width="900" alt="Página: Erros"><br><sub>Erros: classes de resposta, alvos e hosts.</sub></p>
<p align="center"><img src="../img/slo-dark-pt.png" width="900" alt="Página: Serviços"><br><sub>Serviços: disponibilidade e latência de cada serviço.</sub></p>
<p align="center"><img src="../img/protocol-dark-pt.png" width="900" alt="Página: Protocolos e TLS"><br><sub>Protocolos e TLS: versões de HTTP e TLS por classe.</sub></p>
<p align="center"><img src="../img/integrity-dark-pt.png" width="900" alt="Página: Integridade"><br><sub>Integridade: saúde das fontes de log e do registro.</sub></p>
<p align="center"><img src="../img/reports-dark-pt.png" width="900" alt="Página: Relatórios"><br><sub>Relatórios: o relatório exportável.</sub></p>
<p align="center"><img src="../img/overview-light.png" width="620" alt="Visão geral no tema claro"> <img src="../img/overview-mobile.png" height="420" alt="Visão geral no celular"><br><sub>O tema claro no desktop e o layout de celular (uma barra de abas substitui a lateral).</sub></p>
## Grupos de páginas
@@ -105,7 +135,17 @@ Os limites de estados e cidades da página Geografia são do [Natural Earth](htt
| `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` |
| `GET /api/v1/incidents` | sessão ou bearer | chamados de incidente (sem comentários e histórico, com `comment_count`). Query: `status` (lista separada por vírgula), `severity`, `host`, `q`, `sort` (`updated`, `severity`, `last_seen`), `page`, `per_page` (máx. 200). Devolve `{items,total,counts}` |
| `GET /api/v1/incidents/{id}` | sessão ou bearer | chamado completo, com `comments` e `history` |
| `GET /api/v1/incidents/export.csv` | sessão ou bearer | a lista filtrada em CSV |
| `POST /api/v1/incidents` | sessão ou bearer | abre um chamado manual `{title,detail,severity,host,tags,author}` (corpo até 64 KiB, campos desconhecidos recusados; cross-site recusado) |
| `PATCH /api/v1/incidents/{id}` | sessão ou bearer | atualização parcial `{status,severity,assignee,tags,title,verdict,suppress,author}`; cada mudança vira uma entrada no histórico. `suppress` só em `false_positive` ou `benign`, e esconde de `/api/v1/egress` os achados com exatamente a mesma chave (use `suppressed=1` para vê-los) |
| `POST /api/v1/incidents/{id}/comments` | sessão ou bearer | adiciona um comentário `{text,author}` |
Um `range` ou período inválido responde 400, e `range` nas respostas é um objeto `{name,from,to,step,clipped}` (`step` é a granularidade da linha do tempo em segundos).
Clientes da API enviam `Authorization: Bearer <URUTAU_TOKEN>`. O token de peer só é aceito por `/api/v1/peer/export`, `/api/v1/peer/stream` e `/api/v1/peer/period`; todas as outras rotas respondem 403 a ele.
<p align="center"><img src="../img/defense-light.png" width="620" alt="Defense"> <img src="../img/defense-mobile.png" height="420" alt="Defense"><br><sub>Defesa, saída e campanhas no tema claro e no celular.</sub></p>
<p align="center"><img src="../img/egress-light.png" width="620" alt="Egress"> <img src="../img/egress-mobile.png" height="420" alt="Egress"></p>
+9
View File
@@ -26,6 +26,7 @@ type Config struct {
TraefikLog string
AuthLog string
Fail2banLog string
ProbeLog string // kernel log of new connections to unserved ports
Ignore string // networks whose events are dropped (--ignore, alias of --trusted)
Trusted string // trusted sources, e.g. the servers themselves (--trusted)
MonitorUA string // regex of monitoring User-Agents
@@ -43,12 +44,14 @@ type Config struct {
PeerAllow string // CIDRs allowed to call /api/v1/peer/export (empty: any source with the token)
TrustedProxy string // proxies whose X-Forwarded-For is believed
Retention time.Duration
TorAuto string // on (default) or off: download the official Tor lists every 6 h
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
EnforceUnbanLog string // unban requests (UI button) read by the host; default: unban.log next to --enforce-log
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
@@ -149,6 +152,7 @@ func ParseFlags(name string, args []string) (Config, error) {
fs.StringVar(&c.DataDir, "data-dir", env("URUTAU_DATA_DIR", "/data"), "snapshot directory (URUTAU_DATA_DIR)")
fs.StringVar(&c.TraefikLog, "traefik-log", env("URUTAU_TRAEFIK_LOG", "/data/coolify/proxy/access.log"), "Traefik JSON access log, empty disables (URUTAU_TRAEFIK_LOG)")
fs.StringVar(&c.AuthLog, "auth-log", env("URUTAU_AUTH_LOG", "/var/log/auth.log"), "sshd auth log, empty disables (URUTAU_AUTH_LOG)")
fs.StringVar(&c.ProbeLog, "probe-log", env("URUTAU_PROBE_LOG", "/logs/host/probe.log"), "kernel log of network probes (unserved ports) written by the host kit, empty disables (URUTAU_PROBE_LOG)")
fs.StringVar(&c.Fail2banLog, "fail2ban-log", env("URUTAU_FAIL2BAN_LOG", "/var/log/fail2ban.log"), "fail2ban log, empty disables (URUTAU_FAIL2BAN_LOG)")
ign := &csvFlag{val: env("URUTAU_IGNORE", DefaultIgnore)}
trusted := &csvFlag{val: env("URUTAU_TRUSTED", "")}
@@ -172,10 +176,12 @@ func ParseFlags(name string, args []string) (Config, error) {
fs.StringVar(&c.Location, "location", env("URUTAU_LOCATION", ""), `where this instance lives, "lat,lon" or "lat,lon,label"; shown as the destination of live arcs (URUTAU_LOCATION)`)
fs.StringVar(&c.PeerBlocklist, "peer-blocklist", env("URUTAU_PEER_BLOCKLIST", "on"), "on: the blocklist also lists strong hostile IPs seen only by peers; off: local IPs only (URUTAU_PEER_BLOCKLIST)")
fs.DurationVar(&c.Retention, "retention", store.DefaultRetention, "how long data is kept, at most 720h (URUTAU_RETENTION)")
fs.StringVar(&c.TorAuto, "tor-auto", env("URUTAU_TOR_AUTO", "on"), "download the official Tor exit and relay lists every 6 h into <data-dir>/tor: on or off (URUTAU_TOR_AUTO)")
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.EnforceUnbanLog, "enforce-unban-log", env("URUTAU_ENFORCE_UNBAN_LOG", ""), "unban request file written by the Unban button (URUTAU_ENFORCE_UNBAN_LOG); default unban.log next to --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)")
@@ -266,6 +272,9 @@ func (c Config) Validate(token string) ([]fed.Peer, error) {
if strings.EqualFold(c.Enforce, "on") && c.EnforceLog == "" {
return nil, fmt.Errorf("--enforce=on needs --enforce-log")
}
if c.EnforceUnbanLog == "" && c.EnforceLog != "" {
c.EnforceUnbanLog = filepath.Join(filepath.Dir(c.EnforceLog), "unban.log")
}
var peers []fed.Peer
seen := map[string]bool{}
envSeen := map[string]string{}
+50
View File
@@ -1,10 +1,13 @@
package app
import (
"bytes"
"errors"
"time"
"encoding/json"
"fmt"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/geo"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
"io"
@@ -46,6 +49,11 @@ func Doctor(c Config, w io.Writer, asJSON bool) bool {
fi, _ := f.Stat()
f.Close()
add("source "+s.name, "ok", fmt.Sprintf("%s readable (%d bytes)", s.path, fi.Size()))
if s.name == "traefik" {
if bad, n := sampleMalformed(s.path); n >= winMin && bad*5 > n {
add("source traefik format", "warn", fmt.Sprintf("degraded: %d of the last %d lines are malformed: %s", bad, n, degradedMsg))
}
}
}
if err := os.MkdirAll(c.DataDir, 0o700); err != nil {
add("data-dir", "fail", err.Error())
@@ -134,3 +142,45 @@ func doctorState(c Config, add func(name, status, detail string)) map[string]any
add("state", "ok", fmt.Sprintf("%d IPs, %d domains, %d requests in 7 days", st.IPCount(), len(tr.Domains), tr.Requests))
return info
}
// sampleMalformed parses up to the last winSize lines of a Traefik log and
// counts the malformed ones.
func sampleMalformed(path string) (bad, n int) {
f, err := os.Open(path)
if err != nil {
return 0, 0
}
defer f.Close()
const tailBytes = 512 << 10
off := int64(0)
if fi, err := f.Stat(); err == nil && fi.Size() > tailBytes {
off = fi.Size() - tailBytes
}
if _, err := f.Seek(off, io.SeekStart); err != nil {
return 0, 0
}
b, err := io.ReadAll(io.LimitReader(f, tailBytes))
if err != nil {
return 0, 0
}
lines := bytes.Split(b, []byte("\n"))
if off > 0 && len(lines) > 0 {
lines = lines[1:] // first line is cut
}
if len(lines) > 0 && len(lines[len(lines)-1]) == 0 {
lines = lines[:len(lines)-1]
}
if len(lines) > winSize {
lines = lines[len(lines)-winSize:]
}
for _, l := range lines {
if len(bytes.TrimSpace(l)) == 0 {
continue
}
n++
if _, err := core.ParseTraefik(l); err != nil && !errors.Is(err, core.ErrIgnored) {
bad++
}
}
return bad, n
}
+93 -11
View File
@@ -2,11 +2,13 @@ package app
import (
"log/slog"
"net"
"net/netip"
"net/url"
"os"
"strconv"
"strings"
"sync"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
@@ -28,20 +30,24 @@ func newEgress(c Config, st *store.Store, log *slog.Logger) (*egress.Source, err
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 := egressAllow(c)
var provMu sync.Mutex
var provCache []string
provider := func() []string {
provMu.Lock()
defer provMu.Unlock()
if provCache == nil {
provCache = providerASNs(os.Getenv("URUTAU_EGRESS_PROVIDER_ASN"), func(ip string) uint32 { return st.GeoOf(ip).ASN })
}
return provCache
}
allow = append(allow, egressExtraAllow(c)...)
eng, err := egress.New(egress.Config{
Workloads: c.EgressWorkloads,
Resolvers: c.EgressResolvers,
Allow: allow,
Containers: c.EgressContainers,
Workloads: c.EgressWorkloads,
Resolvers: c.EgressResolvers,
Allow: allow,
Containers: c.EgressContainers,
TorRelay: func(a netip.Addr) bool { return intel.IsTorRelay(a) && !intel.IsTorExit(a) },
ProviderASNs: provider,
Geo: func(ip string) (string, string, string) {
g := st.GeoOf(ip)
asn := ""
@@ -96,3 +102,79 @@ func egressExtraAllow(c Config) []netip.Prefix {
}
return out
}
// ownPublicPrefixes returns the global unicast addresses of the local
// interfaces: the server's own addresses never produce a finding.
func ownPublicPrefixes() []netip.Prefix {
var out []netip.Prefix
for _, a := range localPublicAddrs() {
out = append(out, netip.PrefixFrom(a, a.BitLen()))
}
return out
}
func localPublicAddrs() []netip.Addr {
addrs, err := net.InterfaceAddrs()
if err != nil {
return nil
}
var out []netip.Addr
for _, ad := range addrs {
ipn, ok := ad.(*net.IPNet)
if !ok {
continue
}
a, ok := netip.AddrFromSlice(ipn.IP)
if !ok {
continue
}
a = a.Unmap()
if a.IsGlobalUnicast() && !a.IsPrivate() && !a.IsLoopback() && !a.IsLinkLocalUnicast() && !(a.Is4() && netip.MustParsePrefix("100.64.0.0/10").Contains(a)) {
out = append(out, a)
}
}
return out
}
// providerASNs lists the hosting provider's ASNs ("AS31898"): the explicit
// list (env, "31898,AS47583") wins, otherwise the ASN of the server's public
// interface addresses. nil (retried later) when none is known yet.
func providerASNs(explicit string, asnOf func(ip string) uint32) []string {
var out []string
seen := map[string]bool{}
add := func(n uint64) {
k := "AS" + strconv.FormatUint(n, 10)
if n != 0 && !seen[k] {
seen[k] = true
out = append(out, k)
}
}
for _, s := range strings.Split(explicit, ",") {
s = strings.TrimPrefix(strings.ToUpper(strings.TrimSpace(s)), "AS")
if n, err := strconv.ParseUint(s, 10, 32); err == nil {
add(n)
}
}
if len(out) > 0 {
return out
}
for _, a := range localPublicAddrs() {
add(uint64(asnOf(a.String())))
}
return out
}
// egressAllow is the list of destinations that never produce a finding: the
// trusted origins (our own servers, an invalid item does not discard the
// others), the federation peers, URUTAU_EGRESS_ALLOW and the local public
// addresses.
func egressAllow(c Config) []netip.Prefix {
var allow []netip.Prefix
for _, part := range strings.Split(c.Trusted, ",") {
if nets, err := core.ParseCIDRs(part); err == nil {
allow = append(allow, nets...)
}
}
allow = append(allow, egressExtraAllow(c)...)
return append(allow, ownPublicPrefixes()...)
}
+43 -2
View File
@@ -22,7 +22,7 @@ import (
)
// 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 {
func newEnforce(c Config, st *store.Store, peers []fed.Peer, en enricher, ready func() bool) *enforce.Engine {
mode := strings.ToLower(c.Enforce)
if mode != enforce.ModeObserve && mode != enforce.ModeOn {
return nil
@@ -35,10 +35,29 @@ func newEnforce(c Config, st *store.Store, peers []fed.Peer, en enricher) *enfor
}
}
e := enforce.New(enforce.Config{
Mode: mode, Path: c.EnforceLog, StatePath: filepath.Join(c.DataDir, "enforce.json"), Host: c.Name,
Mode: mode, Path: c.EnforceLog, UnbanPath: unbanLogPath(c), 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 },
Rep: st.Reputation,
Tally: func(ip string, from int64) (int, int) { t := st.AttackTally(ip, from); return t.SSH, t.Web },
Roster: func(from int64) []enforce.Seen {
rows := st.AttackRoster(from)
out := make([]enforce.Seen, len(rows))
for i, r := range rows {
out[i] = enforce.Seen{IP: r.IP, Score: r.Score, Level: r.Level, Jails: r.Jails, Est: enforce.Tally{SSH: r.Est.SSH, Web: r.Est.Web}}
}
return out
},
Tallies: func(from int64) map[string]enforce.Tally {
m := st.AttackTallies(from)
out := make(map[string]enforce.Tally, len(m))
for k, v := range m {
out[k] = enforce.Tally{SSH: v.SSH, Web: v.Web}
}
return out
},
Ready: ready,
Geo: func(ip string) (string, uint32, string) {
if en.g == nil {
return "", 0, ""
@@ -71,6 +90,7 @@ func resolveHost(h string) []netip.Addr {
func shareDecisions(ctx context.Context, hub *fed.Hub, e *enforce.Engine, log *slog.Logger) {
pulled := map[string]int64{}
pushed := map[string]int64{}
pushedUn := map[string]int64{}
t := time.NewTicker(30 * time.Second)
defer t.Stop()
for {
@@ -93,6 +113,16 @@ func shareDecisions(ctx context.Context, hub *fed.Hub, e *enforce.Engine, log *s
}
}
}
for _, p := range hub.Peers {
if mine := e.UnbansSince(pushedUn[p.Name]); len(mine) > 0 {
start := time.Now().Unix()
if err := hub.PostJSON(ctx, p, "/api/v1/peer/unban?from="+url.QueryEscape(e.Host()), map[string]any{"unbans": mine}); err == nil {
pushedUn[p.Name] = start
} else if ctx.Err() == nil {
log.Debug("enforce: unban push failed", "peer", p.Name, "err", err)
}
}
}
select {
case <-ctx.Done():
return
@@ -162,3 +192,14 @@ func cloudflareClients(path string) (cf, total int) {
}
return cf, total
}
// unbanLogPath is --enforce-unban-log, or unban.log next to --enforce-log.
func unbanLogPath(c Config) string {
if c.EnforceUnbanLog != "" {
return c.EnforceUnbanLog
}
if c.EnforceLog == "" {
return ""
}
return filepath.Join(filepath.Dir(c.EnforceLog), "unban.log")
}
+82
View File
@@ -0,0 +1,82 @@
package app
import (
"fmt"
"sync"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
)
const probeMarker = "URUTAU-PROBE:"
// probeMaxKeys bounds the aggregation map; when it is full the entries older
// than a minute are dropped.
const probeMaxKeys = 100000
type probeKey struct {
ip string
port uint16
proto string
}
// probeParser turns "URUTAU-PROBE:" kernel lines into scanner events, at most
// one per (ip, port, proto) per minute, so a SYN flood does not inflate the store.
type probeParser struct {
mu sync.Mutex
last map[probeKey]int64 // minute of the last event kept
now func() time.Time
}
func newProbeParser() *probeParser {
return &probeParser{last: map[probeKey]int64{}, now: time.Now}
}
func (p *probeParser) parse(b []byte) (core.Event, error) {
k, err := egress.ParseKernel(b, probeMarker, p.now())
if err != nil {
return core.Event{}, err
}
if (k.Proto != "tcp" && k.Proto != "udp") || k.DPort == 0 || !k.Src.IsValid() {
return core.Event{}, fmt.Errorf("not a tcp/udp probe")
}
key := probeKey{k.Src.String(), k.DPort, k.Proto}
min := k.Time.Unix() / 60
p.mu.Lock()
if m, ok := p.last[key]; ok && m >= min {
p.mu.Unlock()
return core.Event{}, core.ErrIgnored
}
if len(p.last) >= probeMaxKeys {
cut := p.now().Unix()/60 - 1
for kk, m := range p.last {
if m < cut {
delete(p.last, kk)
}
}
if len(p.last) >= probeMaxKeys {
p.last = map[probeKey]int64{}
}
}
p.last[key] = min
p.mu.Unlock()
return core.Event{Time: k.Time, IP: k.Src.String(), Cat: core.Scanner, Source: "probe", Method: upper(k.Proto),
Path: k.Proto + "/" + itoa(int(k.DPort)) + serviceSuffix(k.Proto, k.DPort), Proto: k.Proto, Port: k.DPort}, nil
}
func upper(s string) string {
if s == "udp" {
return "UDP"
}
return "TCP"
}
func itoa(n int) string { return fmt.Sprint(n) }
func serviceSuffix(proto string, port uint16) string {
if s := core.PortService(proto, port); s != "" {
return " " + s
}
return ""
}
+84
View File
@@ -0,0 +1,84 @@
package app
import (
"errors"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
const probeV4 = `2026-11-15T03:20:01.123456+00:00 srv kernel: URUTAU-PROBE: IN=eth0 OUT= MAC=aa SRC=203.0.113.9 DST=195.200.0.252 LEN=44 TTL=241 ID=1 PROTO=TCP SPT=51234 DPT=3389 WINDOW=1024 SYN URGP=0`
func TestProbeParse(t *testing.T) {
p := newProbeParser()
ev, err := p.parse([]byte(probeV4))
if err != nil {
t.Fatal(err)
}
if ev.IP != "203.0.113.9" || ev.Cat != core.Scanner || ev.Source != "probe" || ev.Port != 3389 || ev.Proto != "tcp" || ev.Path != "tcp/3389 rdp" {
t.Fatalf("%+v", ev)
}
v6 := `2026-11-15T03:20:01+00:00 srv kernel: URUTAU-PROBE: IN=eth0 OUT= SRC=2001:db8::5 DST=2001:db8::1 LEN=60 PROTO=TCP SPT=1 DPT=445 SYN`
if ev, err = p.parse([]byte(v6)); err != nil || ev.IP != "2001:db8::5" || ev.Port != 445 {
t.Fatalf("%+v %v", ev, err)
}
udp := `2026-11-15T03:20:01+00:00 srv kernel: URUTAU-PROBE: IN=eth0 OUT= SRC=203.0.113.9 DST=195.200.0.252 LEN=60 PROTO=UDP SPT=1 DPT=161 LEN=40`
if ev, err = p.parse([]byte(udp)); err != nil || ev.Proto != "udp" || ev.Path != "udp/161 snmp" {
t.Fatalf("%+v %v", ev, err)
}
for _, bad := range []string{"", "garbage", "kernel: URUTAU-PROBE: nothing", `x URUTAU-PROBE: SRC=bad DST=1.1.1.1 PROTO=TCP DPT=1`,
`x URUTAU-PROBE: SRC=1.1.1.1 DST=2.2.2.2 PROTO=ICMP`} {
if _, err := newProbeParser().parse([]byte(bad)); err == nil {
t.Errorf("accepted %q", bad)
}
}
}
func TestProbePerMinuteAggregation(t *testing.T) {
p := newProbeParser()
if _, err := p.parse([]byte(probeV4)); err != nil {
t.Fatal(err)
}
// same ip/port/proto in the same minute: ignored (not malformed)
if _, err := p.parse([]byte(probeV4)); !errors.Is(err, core.ErrIgnored) {
t.Fatalf("got %v", err)
}
// another port is kept
if _, err := p.parse([]byte(probeV4[:len(probeV4)-0])); err == nil {
t.Fatal("repeat accepted")
}
other := `2026-11-15T03:20:02+00:00 srv kernel: URUTAU-PROBE: IN=eth0 OUT= SRC=203.0.113.9 DST=1.2.3.4 PROTO=TCP SPT=1 DPT=22 SYN`
if _, err := p.parse([]byte(other)); err != nil {
t.Fatal(err)
}
// next minute: kept again
next := `2026-11-15T03:21:01+00:00 srv kernel: URUTAU-PROBE: IN=eth0 OUT= SRC=203.0.113.9 DST=1.2.3.4 PROTO=TCP SPT=1 DPT=3389 SYN`
if _, err := p.parse([]byte(next)); err != nil {
t.Fatal(err)
}
}
func TestProbeFamilyMitre(t *testing.T) {
fam, tech, _ := store.IntelClassifier(core.Event{Source: "probe", Cat: core.Scanner, Path: "tcp/23 telnet"})
if fam != intel.FamPortScan {
t.Fatalf("fam %q", fam)
}
has := false
for _, x := range tech {
has = has || x == "T1046"
}
if !has {
t.Fatalf("tech %v", tech)
}
}
func TestProbeSourceMissingIsWaiting(t *testing.T) {
s := &source{name: "probe", path: t.TempDir() + "/absent.log"}
if st := s.status(); st.State != "waiting" || st.Error != "" {
t.Fatalf("%+v", st)
}
_ = time.Now
}
+19 -2
View File
@@ -20,6 +20,7 @@ import (
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/geo"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/incidents"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/rdns"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/server"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
@@ -46,6 +47,9 @@ func Serve(c Config) error {
st := store.New(store.Config{Name: c.Name, Version: Version, Retention: c.Retention, AdminUsers: c.AdminUserList(), Location: loc})
st.SetDomains(splitList(c.Domains))
watchTorExits(ctx, c.TorExits, 24*time.Hour, log)
if !strings.EqualFold(c.TorAuto, "off") {
watchTorLists(ctx, filepath.Join(c.DataDir, "tor"), torExitURL, torRelayURL, 6*time.Hour, log)
}
var elog *evlog.Log
if max, err := ParseSize(orDefault(c.EventsMax, DefaultEventsMax)); err == nil && max > 0 {
if elog, err = evlog.Open(evlog.Options{Dir: filepath.Join(c.DataDir, "events"), MaxBytes: max, Retention: c.Retention, Log: log}); err != nil {
@@ -96,8 +100,13 @@ func Serve(c Config) error {
tproxy, _ := core.ParseCIDRs(c.TrustedProxy)
ign, _ := core.ParseCIDRs(c.Ignore + "," + c.Trusted)
bindHost, _, _ := net.SplitHostPort(c.Bind)
incStore, err := incidents.Open(filepath.Join(c.DataDir, "incidents.json"), log)
if err != nil {
return err
}
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})
AllowHosts: []string{bindHost}, NoAuth: c.NoAuth, LocalBlocklist: strings.EqualFold(c.PeerBlocklist, "off"), Version: Version, Store: st, Hub: hub,
Incidents: incStore})
egressSrc, err := newEgress(c, st, log)
if err != nil {
return err
@@ -106,7 +115,14 @@ func Serve(c Config) error {
extra := runner.Extra
runner.Extra = func() []store.SourceStatus { return append(extra(), egressSrc.Status()) }
}
eng := newEnforce(c, st, peers, en)
eng := newEnforce(c, st, peers, en, func() bool {
for _, s := range runner.Sources {
if s.backfilling.Load() {
return false
}
}
return true
})
if eng != nil {
server.SetEnforce(eng)
}
@@ -122,6 +138,7 @@ func Serve(c Config) error {
go func() { defer wg.Done(); elog.Run(ctx) }()
}
runner.Start(ctx, offsets, &wg)
server.StartIncidentSync(ctx, &wg)
if egressSrc != nil {
egressSrc.Start(ctx, &wg)
}
+54 -2
View File
@@ -23,6 +23,8 @@ type source struct {
parse func([]byte) (core.Event, error)
lines, malformed atomic.Uint64
win window
lastWarn atomic.Int64
lastEvent atomic.Int64
backfilling atomic.Bool
fol atomic.Pointer[tail.Follower]
@@ -32,6 +34,44 @@ func traefikParse(b []byte) (core.Event, error) { return core.ParseTraefik(b) }
func authParse(b []byte) (core.Event, error) { return core.ParseAuth(string(b)) }
func f2bParse(b []byte) (core.Event, error) { return core.ParseFail2ban(string(b)) }
const (
winSize = 1000
winMin = 50 // fewer samples than this never mark a source degraded
degradedMsg = "formato inesperado (JSON esperado?)"
)
// window remembers whether each of the last winSize lines was malformed.
type window struct {
mu sync.Mutex
ring [winSize]bool
n int // lines recorded so far, capped at winSize
pos int
bad int
}
func (w *window) add(bad bool) {
w.mu.Lock()
defer w.mu.Unlock()
if w.n == winSize && w.ring[w.pos] {
w.bad--
}
w.ring[w.pos] = bad
if bad {
w.bad++
}
w.pos = (w.pos + 1) % winSize
if w.n < winSize {
w.n++
}
}
// degraded reports whether more than 20% of the recent lines were malformed.
func (w *window) degraded() bool {
w.mu.Lock()
defer w.mu.Unlock()
return w.n >= winMin && w.bad*5 > w.n
}
func (s *source) status() store.SourceStatus {
st := store.SourceStatus{Name: s.name, Path: s.path, Lines: s.lines.Load(), Malformed: s.malformed.Load(),
LastEvent: s.lastEvent.Load(), State: "following"}
@@ -55,6 +95,9 @@ func (s *source) status() store.SourceStatus {
}
}
}
if st.State == "following" && s.win.degraded() {
st.State, st.Error = "degraded", degradedMsg
}
return st
}
@@ -91,7 +134,7 @@ func NewRunner(c Config, st *store.Store, log *slog.Logger) (*Runner, error) {
for _, d := range []struct {
name, path string
parse func([]byte) (core.Event, error)
}{{"traefik", c.TraefikLog, traefikParse}, {"ssh", c.AuthLog, authParse}, {"fail2ban", c.Fail2banLog, f2bParse}} {
}{{"traefik", c.TraefikLog, traefikParse}, {"ssh", c.AuthLog, authParse}, {"fail2ban", c.Fail2banLog, f2bParse}, {"probe", c.ProbeLog, newProbeParser().parse}} {
if d.path != "" {
r.Sources = append(r.Sources, &source{name: d.name, path: d.path, parse: d.parse})
}
@@ -148,11 +191,20 @@ func (r *Runner) handle(s *source) func([]byte) {
s.lines.Add(1)
ev, err := s.parse(line)
if err != nil {
if !errors.Is(err, core.ErrIgnored) {
bad := !errors.Is(err, core.ErrIgnored)
if bad {
s.malformed.Add(1)
}
s.win.add(bad)
if bad && s.win.degraded() {
now := time.Now().Unix()
if last := s.lastWarn.Load(); now-last >= 3600 && s.lastWarn.CompareAndSwap(last, now) {
r.Log.Warn("many lines of this source are malformed", "source", s.name, "detail", degradedMsg)
}
}
return
}
s.win.add(false)
if core.Ignored(r.Ignore, ev.IP) {
return
}
+182 -1
View File
@@ -3,12 +3,17 @@ package app
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/netip"
"os"
"path/filepath"
"strings"
"sync"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
@@ -69,7 +74,7 @@ func watchTorExits(ctx context.Context, path string, every time.Duration, log *s
log.Warn("tor exit list unreadable", "err", err)
return
}
intel.SetTorExits(addrs)
torLists.setManual(addrs)
lastMod, lastSize = st.ModTime(), st.Size()
log.Info("tor exit list loaded", "n", len(addrs))
}
@@ -87,3 +92,179 @@ func watchTorExits(ctx context.Context, path string, every time.Duration, log *s
}
}()
}
const (
torExitURL = "https://check.torproject.org/torbulkexitlist"
torRelayURL = "https://onionoo.torproject.org/details?running=true&fields=or_addresses,exit_addresses"
maxTorList = 32 << 20
torFetchTO = 60 * time.Second
torUserAgent = "urutau"
maxTorRelays = 400000
torExitCache = "exits.txt"
torRelayCache = "relays.json"
)
// torLists merges the manual exit file (URUTAU_TOR_EXITS) with the downloaded
// lists into the intel package.
var torLists = &torSource{}
type torSource struct {
mu sync.Mutex
manual, auto, rels []netip.Addr
}
func (t *torSource) apply() {
all := append(append([]netip.Addr(nil), t.manual...), t.auto...)
intel.SetTorExits(all)
intel.SetTorRelays(append(all, t.rels...))
}
func (t *torSource) setManual(a []netip.Addr) {
t.mu.Lock()
defer t.mu.Unlock()
t.manual = a
t.apply()
}
func (t *torSource) setAuto(exits, relays []netip.Addr) {
t.mu.Lock()
defer t.mu.Unlock()
if exits != nil {
t.auto = exits
}
if relays != nil {
t.rels = relays
}
t.apply()
}
func torAddr(s string) (netip.Addr, bool) {
s = strings.TrimSpace(s)
if ap, err := netip.ParseAddrPort(s); err == nil {
s = ap.Addr().String()
}
a, err := netip.ParseAddr(strings.Trim(s, "[]"))
if err != nil || a.Zone() != "" {
return netip.Addr{}, false
}
return a.Unmap(), true
}
// ParseTorExitList parses the plain-text exit list (one address per line,
// junk and # comments ignored, at most maxTorExits addresses, input limited to
// 32 MB).
func ParseTorExitList(r io.Reader) []netip.Addr {
var out []netip.Addr
sc := bufio.NewScanner(io.LimitReader(r, maxTorList))
sc.Buffer(make([]byte, 0, 4096), 4096)
for sc.Scan() && len(out) < maxTorExits {
l := sc.Text()
if i := strings.IndexByte(l, '#'); i >= 0 {
l = l[:i]
}
if a, ok := torAddr(l); ok {
out = append(out, a)
}
}
return out
}
// ParseOnionoo extracts the relay and exit addresses (v4 and v6) of an Onionoo
// "details" document (input limited to 32 MB, at most 400000 addresses).
func ParseOnionoo(r io.Reader) ([]netip.Addr, error) {
var doc struct {
Relays []struct {
OR []string `json:"or_addresses"`
Exit []string `json:"exit_addresses"`
} `json:"relays"`
}
if err := json.NewDecoder(io.LimitReader(r, maxTorList)).Decode(&doc); err != nil {
return nil, err
}
var out []netip.Addr
for _, rl := range doc.Relays {
for _, s := range append(rl.OR, rl.Exit...) {
if a, ok := torAddr(s); ok && len(out) < maxTorRelays {
out = append(out, a)
}
}
}
return out, nil
}
func fetchTor(ctx context.Context, url string) ([]byte, error) {
ctx, cancel := context.WithTimeout(ctx, torFetchTO)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", torUserAgent)
resp, err := (&http.Client{Timeout: torFetchTO}).Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("status %d", resp.StatusCode)
}
b, err := io.ReadAll(io.LimitReader(resp.Body, maxTorList+1))
if err != nil {
return nil, err
}
if len(b) > maxTorList {
return nil, errors.New("list larger than 32 MB")
}
return b, nil
}
// refreshTorLists reads the cache in dir and, when force or the cache is older
// than maxAge, downloads the lists again. A failed download keeps the cache.
func refreshTorLists(ctx context.Context, dir, exitURL, relayURL string, maxAge time.Duration, log *slog.Logger) {
_ = os.MkdirAll(dir, 0o750)
one := func(name, url string, parse func([]byte) ([]netip.Addr, error)) []netip.Addr {
path := filepath.Join(dir, name)
st, statErr := os.Stat(path)
if statErr != nil || time.Since(st.ModTime()) >= maxAge {
if b, err := fetchTor(ctx, url); err != nil {
log.Warn("tor list download failed", "list", name, "err", err)
} else if a, err := parse(b); err != nil || len(a) == 0 {
log.Warn("tor list invalid, kept the cache", "list", name, "err", err)
} else if err := os.WriteFile(path+".tmp", b, 0o640); err == nil && os.Rename(path+".tmp", path) == nil {
return a
}
}
b, err := os.ReadFile(path)
if err != nil || len(b) > maxTorList {
return nil
}
a, _ := parse(b)
return a
}
exits := one(torExitCache, exitURL, func(b []byte) ([]netip.Addr, error) {
return ParseTorExitList(strings.NewReader(string(b))), nil
})
relays := one(torRelayCache, relayURL, func(b []byte) ([]netip.Addr, error) {
return ParseOnionoo(strings.NewReader(string(b)))
})
torLists.setAuto(exits, relays)
log.Info("tor lists", "exits", len(exits), "relays", len(relays))
}
// watchTorLists refreshes the official lists now (in the background, so
// startup is not blocked) and every interval.
func watchTorLists(ctx context.Context, dir, exitURL, relayURL string, every time.Duration, log *slog.Logger) {
go func() {
refreshTorLists(ctx, dir, exitURL, relayURL, every*9/10, log)
t := time.NewTicker(every)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
refreshTorLists(ctx, dir, exitURL, relayURL, every*9/10, log)
}
}
}()
}
+110
View File
@@ -0,0 +1,110 @@
package app
import (
"context"
"log/slog"
"net/http"
"net/http/httptest"
"net/netip"
"os"
"path/filepath"
"strings"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
)
func TestParseTorLists(t *testing.T) {
got := ParseTorExitList(strings.NewReader("1.2.3.4\n# c\nlixo\n2001:db8::1 # x\n999.1.1.1\n::ffff:5.6.7.8\n"))
if len(got) != 3 || got[2].String() != "5.6.7.8" {
t.Fatalf("exits: %v", got)
}
js := `{"relays":[{"or_addresses":["10.1.1.1:9001","[2001:db8::2]:443","junk"],"exit_addresses":["10.1.1.2"]},{"or_addresses":[]}]}`
a, err := ParseOnionoo(strings.NewReader(js))
if err != nil || len(a) != 3 || a[1].String() != "2001:db8::2" {
t.Fatalf("onionoo: %v %v", a, err)
}
if _, err := ParseOnionoo(strings.NewReader("<html>")); err == nil {
t.Fatal("garbage must fail")
}
// the size limit truncates the input: broken JSON, an error
if _, err := ParseOnionoo(strings.NewReader(`{"relays":[{"or_addresses":["1.1.1.1:1"]}` + strings.Repeat(" ", maxTorList+10) + `]}`)); err == nil {
t.Fatal("oversize must fail")
}
}
func TestRefreshTorListsCache(t *testing.T) {
hits := 0
fail := false
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hits++
if fail || r.Header.Get("User-Agent") != "urutau" {
http.Error(w, "x", 500)
return
}
if r.URL.Path == "/exit" {
w.Write([]byte("198.51.100.1\n"))
return
}
w.Write([]byte(`{"relays":[{"or_addresses":["198.51.100.2:9001"]}]}`))
}))
defer srv.Close()
defer torLists.setManual(nil)
defer torLists.setAuto([]netip.Addr{}, []netip.Addr{})
dir := filepath.Join(t.TempDir(), "tor")
log := slog.New(slog.NewTextHandler(os.Stderr, nil))
ctx := context.Background()
refreshTorLists(ctx, dir, srv.URL+"/exit", srv.URL+"/relays", time.Hour, log)
if !intel.IsTorExit(netip.MustParseAddr("198.51.100.1")) || !intel.IsTorRelay(netip.MustParseAddr("198.51.100.2")) || hits != 2 {
t.Fatalf("lists not loaded, hits=%d", hits)
}
refreshTorLists(ctx, dir, srv.URL+"/exit", srv.URL+"/relays", time.Hour, log) // fresh cache: no download
if hits != 2 {
t.Fatalf("cache ignored: %d", hits)
}
torLists.setAuto([]netip.Addr{}, []netip.Addr{})
fail = true
refreshTorLists(ctx, dir, srv.URL+"/exit", srv.URL+"/relays", 0, log) // stale + failing: the cache serves
if !intel.IsTorExit(netip.MustParseAddr("198.51.100.1")) || !intel.IsTorRelay(netip.MustParseAddr("198.51.100.2")) {
t.Fatal("fallback to cache failed")
}
// the manual list coexists
torLists.setManual([]netip.Addr{netip.MustParseAddr("203.0.113.9")})
if !intel.IsTorExit(netip.MustParseAddr("203.0.113.9")) || !intel.IsTorExit(netip.MustParseAddr("198.51.100.1")) {
t.Fatal("manual + auto merge failed")
}
}
func TestNetTypeTorEntry(t *testing.T) {
a := netip.MustParseAddr("198.51.100.5")
intel.SetTorExits([]netip.Addr{a})
defer intel.SetTorExits(nil)
if typ, _ := intel.NetTypeIP(a, 0, "", ""); typ != "tor" {
t.Fatal(typ)
}
}
func TestEgressOwnAllowAndProvider(t *testing.T) {
if got := providerASNs("31898, AS47583,x", nil); len(got) != 2 || got[0] != "AS31898" || got[1] != "AS47583" {
t.Fatalf("%v", got)
}
ps := ownPublicPrefixes()
for _, p := range ps {
if p.Addr().IsPrivate() || p.Addr().IsLoopback() {
t.Fatal(p)
}
}
// the peer has no URUTAU_PEERS: URUTAU_TRUSTED carries both servers, and a
// bad item does not discard the others
al := egressAllow(Config{Trusted: "136.248.78.83,lixo,195.200.0.252/32"})
for _, ipS := range []string{"136.248.78.83", "195.200.0.252"} {
ok := false
for _, p := range al {
ok = ok || p.Contains(netip.MustParseAddr(ipS))
}
if !ok {
t.Fatal("not allowed: ", ipS)
}
}
}
+31
View File
@@ -257,3 +257,34 @@ func TestEgressExtraAllow(t *testing.T) {
t.Fatalf("%v", s)
}
}
func TestSourceDegradedWindow(t *testing.T) {
var w window
for i := 0; i < 100; i++ {
w.add(i%10 == 0)
}
if w.degraded() {
t.Fatal("10% must not degrade")
}
for i := 0; i < 400; i++ {
w.add(true)
}
if !w.degraded() {
t.Fatal("expected degraded")
}
for i := 0; i < winSize; i++ {
w.add(false)
}
if w.degraded() {
t.Fatal("window must recover")
}
}
func TestUnbanLogPathDefault(t *testing.T) {
if got := unbanLogPath(Config{EnforceLog: "/logs/enforce/decisions.log"}); got != "/logs/enforce/unban.log" {
t.Fatalf("default unban log = %q", got)
}
if got := unbanLogPath(Config{EnforceLog: "/a/d.log", EnforceUnbanLog: "/b/u.log"}); got != "/b/u.log" {
t.Fatalf("explicit unban log = %q", got)
}
}
+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.4.0"
var Version = "1.5.1"
+22
View File
@@ -266,3 +266,25 @@ func TestZonesAreRejectedEverywhere(t *testing.T) {
}
_ = strings.ToLower
}
func TestParseTraefikText(t *testing.T) {
ev, err := ParseTraefik([]byte(`10.0.15.1 - - [15/Nov/2026:04:10:51 +0000] "GET /wp-content/uploads/2026/08/IMG.jpg HTTP/2.0" 200 252131 "-" "-" 22219 "https-0-fwl1r20xzp8uf2g48log9q49-wordpress-1870@docker" "http://10.0.5.2:80" 3ms`))
if err != nil {
t.Fatal(err)
}
if ev.IP != "10.0.15.1" || ev.Method != "GET" || ev.Path != "/wp-content/uploads/2026/08/IMG.jpg" || ev.Proto != "HTTP/2.0" ||
ev.Status != 200 || ev.Bytes != 252131 || ev.UA != "" || ev.Referer != "" || ev.OriginStatus != 200 ||
ev.DurationNS != 3e6 || ev.Domain != "" || ev.Router != "https-0-fwl1r20xzp8uf2g48log9q49-wordpress-1870@docker" ||
ev.Time.Format("2006-01-02T15:04:05Z") != "2026-11-15T04:10:51Z" {
t.Fatalf("%+v", ev)
}
ev, err = ParseTraefik([]byte(`203.0.113.9 - - [15/Nov/2026:04:10:52 +0000] "POST /wp-login.php HTTP/1.1" 404 19 "https://x/\"y" "Mozilla \"q\" 5.0" 1 "web@docker" "-" 12ms`))
if err != nil || ev.Method != "POST" || ev.Status != 404 || ev.UA != `Mozilla "q" 5.0` || ev.Referer != `https://x/"y` || ev.OriginStatus != 0 {
t.Fatalf("%+v %v", ev, err)
}
for _, bad := range []string{"garbage", `1.2.3.4 - - [bad] "GET / HTTP/1.1" 200 1 "-" "-" 1`, `1.2.3.4 - - [15/Nov/2026:04:10:52 +0000] "GET / HTTP/1.1" 200 1 "-" "-`, `nope - - [15/Nov/2026:04:10:52 +0000] "GET / HTTP/1.1" 200 1 "-" "-" 1`} {
if _, err := ParseTraefik([]byte(bad)); err == nil {
t.Errorf("accepted %q", bad)
}
}
}
+2
View File
@@ -132,6 +132,8 @@ type Event struct {
User string
Jail string
Status int
// Port is the destination port probed (Source "probe"); Proto holds tcp/udp.
Port uint16
// Unban marks a fail2ban unban (Cat is Ban). Restore marks a ban replayed
// by fail2ban after a restart: it updates the ban state but is not scored.
Unban bool
Loaded 100 of 174 files, more files were not shown because too many files have changed in this diff. Show more