Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
873219416f | ||
|
|
da333d70f1 | ||
|
|
1ef5a0ce9f | ||
|
|
0dc3268b29 | ||
|
|
50cd2bd3ce | ||
|
|
045ed53e43 | ||
|
|
ec46fb94ff | ||
|
|
432f521ed1 | ||
|
|
f27d8441a9 | ||
|
|
b267b98f18 | ||
|
|
9bdfdb491b | ||
|
|
5d3374ee11 | ||
|
|
c33cca22e3 |
No files matched your search
@@ -25,3 +25,4 @@ __pycache__/
|
||||
|
||||
# Runtime pid files left by local test scripts
|
||||
*.pid
|
||||
pid
|
||||
@@ -6,12 +6,73 @@ Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versio
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [1.1.1] - 2026-11-14
|
||||
## [1.4.7] - 2026-11-15
|
||||
|
||||
### 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.
|
||||
- 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
|
||||
|
||||
### Added
|
||||
|
||||
- Second firewall (optional, `URUTAU_ENFORCE=off|observe|on`): Urutau decides which attacking addresses to block and writes the decisions to a file; the host fail2ban (jail `urutau`) applies them. Urutau gets no privileges. Observe mode shows what would be blocked. Optional decision sharing between hub and peers (`URUTAU_ENFORCE_SHARE`), applied only when the receiving server also saw the address attack. Never blocks trusted addresses, private ranges, CDN (Cloudflare) and public resolver ranges, peers or the server itself. The ban only drops connections the address starts, so replies to the server's own connections keep flowing.
|
||||
- Egress analysis (`URUTAU_EGRESS`): new outbound connections of the host and containers, logged by nftables, are checked for beaconing (regular conversations with one destination), mining, IRC and SMTP ports, contact with addresses that attacked the server or Tor exits, DNS outside the allowed resolvers, unauthorised outbound scans and new countries. Workloads by network or container name (`URUTAU_EGRESS_WORKLOADS`); a `scanner` workload (an authorised surface scanner) has only its scan-shaped traffic summarised, everything else is judged like any other workload, so its beaconing is still detected.
|
||||
- Host kit in `deploy/host` (nftables table, rsyslog, logrotate, container map, fail2ban filter, action and jail, `install.sh`).
|
||||
- New page Outbound traffic and a Second firewall section in Defense.
|
||||
- HTML report (`/api/v1/report?format=html`): cover, executive summary in plain language, rule-based recommendations, threats, geography, errors and health, visitors, defense, second firewall and outbound traffic, printable on A4. The Reports page downloads or prints it.
|
||||
- Screenshot script covers every page.
|
||||
|
||||
## [1.3.0] - 2026-11-14
|
||||
|
||||
@@ -45,6 +106,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
|
||||
|
||||
@@ -6,12 +6,73 @@ Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/);
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [1.1.1] - 2026-11-14
|
||||
## [1.4.7] - 2026-11-15
|
||||
|
||||
### 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.
|
||||
- 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
|
||||
|
||||
### Adicionado
|
||||
|
||||
- Segundo firewall (opcional, `URUTAU_ENFORCE=off|observe|on`): o Urutau decide quais endereços atacantes bloquear e grava as decisões num arquivo; o fail2ban do host (jail `urutau`) as aplica. O Urutau não ganha privilégios. O modo observação mostra o que seria bloqueado. Compartilhamento opcional de decisões entre hub e peers (`URUTAU_ENFORCE_SHARE`), aplicado só quando o servidor que recebe também viu o endereço atacar. Nunca bloqueia endereços confiáveis, redes privadas, faixas de CDN (Cloudflare) e de resolvedores públicos, peers nem o próprio servidor. O banimento só derruba conexões que o endereço inicia, então as respostas às conexões do próprio servidor continuam passando.
|
||||
- Análise do tráfego de saída (`URUTAU_EGRESS`): as conexões novas de saída do host e dos contêineres, registradas pelo nftables, são analisadas em busca de beaconing (conversa regular com um destino), mineração, portas de IRC e SMTP, contato com endereços que atacaram o servidor ou saídas Tor, DNS fora dos resolvedores permitidos, varreduras de saída não autorizadas e países novos. Workloads por rede ou nome de contêiner (`URUTAU_EGRESS_WORKLOADS`); um workload `scanner` (scanner de superfície autorizado) só tem resumido o tráfego em formato de varredura, todo o resto é julgado como o de qualquer workload, então o beaconing dele continua sendo detectado.
|
||||
- Kit de host em `deploy/host` (tabela nftables, rsyslog, logrotate, mapa de contêineres, filtro, ação e jail do fail2ban, `install.sh`).
|
||||
- Página nova Tráfego de saída e seção Segundo firewall em Defesa.
|
||||
- Relatório HTML (`/api/v1/report?format=html`): capa, sumário executivo em linguagem leiga, recomendações por regras, ameaças, geografia, erros e saúde, visitantes, defesa, segundo firewall e tráfego de saída, imprimível em A4. A página Relatórios baixa ou imprime.
|
||||
- O script de capturas cobre todas as páginas.
|
||||
|
||||
## [1.3.0] - 2026-11-14
|
||||
|
||||
@@ -45,6 +106,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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
# 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
|
||||
}
|
||||
|
||||
# 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
|
||||
}
|
||||
@@ -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>
|
||||
@@ -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 =
|
||||
@@ -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]
|
||||
@@ -0,0 +1,69 @@
|
||||
#!/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 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-unban.path /etc/systemd/system/urutau-unban.service /usr/local/sbin/urutau-unban
|
||||
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
|
||||
[ -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"
|
||||
fi
|
||||
@@ -0,0 +1,32 @@
|
||||
#!/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
|
||||
|
||||
# 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
|
||||
@@ -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
|
||||
@@ -0,0 +1,10 @@
|
||||
[Unit]
|
||||
Description=Urutau: refresh the container map every minute
|
||||
|
||||
[Timer]
|
||||
OnBootSec=30s
|
||||
OnUnitActiveSec=60s
|
||||
AccuracySec=5s
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@@ -0,0 +1,63 @@
|
||||
#!/usr/sbin/nft -f
|
||||
# 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).
|
||||
# @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
|
||||
}
|
||||
|
||||
# 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
|
||||
}
|
||||
|
||||
chain output_log {
|
||||
type filter hook output priority filter - 10; policy accept;
|
||||
ct state new oifname "@WAN@" jump egress
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
[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
|
||||
ExecStartPost=-/usr/local/sbin/urutau-containers-map
|
||||
ExecStop=/usr/sbin/nft delete table inet urutau_egress
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -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
|
||||
@@ -0,0 +1,9 @@
|
||||
[Unit]
|
||||
Description=Urutau: check the egress log size every 10 minutes
|
||||
|
||||
[Timer]
|
||||
OnBootSec=5m
|
||||
OnUnitActiveSec=10m
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@@ -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"
|
||||
@@ -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
|
||||
@@ -0,0 +1,6 @@
|
||||
[Unit]
|
||||
Description=Urutau: apply the operator's unban requests
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/usr/local/sbin/urutau-unban
|
||||
@@ -0,0 +1,14 @@
|
||||
/var/log/urutau/egress.log /var/log/urutau/probe.log {
|
||||
daily
|
||||
rotate 7
|
||||
maxsize 200M
|
||||
maxage 7
|
||||
compress
|
||||
delaycompress
|
||||
missingok
|
||||
notifempty
|
||||
create 0640 syslog adm
|
||||
postrotate
|
||||
/usr/lib/rsyslog/rsyslog-rotate
|
||||
endscript
|
||||
}
|
||||
|
After Width: | Height: | Size: 149 KiB |
|
After Width: | Height: | Size: 145 KiB |
|
After Width: | Height: | Size: 211 KiB |
|
After Width: | Height: | Size: 210 KiB |
|
After Width: | Height: | Size: 211 KiB |
|
After Width: | Height: | Size: 215 KiB |
|
After Width: | Height: | Size: 193 KiB |
|
After Width: | Height: | Size: 186 KiB |
|
After Width: | Height: | Size: 437 KiB |
|
After Width: | Height: | Size: 413 KiB |
|
After Width: | Height: | Size: 421 KiB |
|
After Width: | Height: | Size: 190 KiB |
|
After Width: | Height: | Size: 693 KiB |
|
After Width: | Height: | Size: 677 KiB |
|
After Width: | Height: | Size: 690 KiB |
|
After Width: | Height: | Size: 270 KiB |
|
After Width: | Height: | Size: 225 KiB |
|
After Width: | Height: | Size: 209 KiB |
|
After Width: | Height: | Size: 289 KiB |
|
After Width: | Height: | Size: 154 KiB |
|
After Width: | Height: | Size: 151 KiB |
|
After Width: | Height: | Size: 175 KiB |
|
Before Width: | Height: | Size: 154 KiB After Width: | Height: | Size: 171 KiB |
|
After Width: | Height: | Size: 202 KiB |
|
Before Width: | Height: | Size: 175 KiB After Width: | Height: | Size: 196 KiB |
|
Before Width: | Height: | Size: 166 KiB After Width: | Height: | Size: 188 KiB |
|
Before Width: | Height: | Size: 168 KiB After Width: | Height: | Size: 187 KiB |
|
Before Width: | Height: | Size: 164 KiB After Width: | Height: | Size: 184 KiB |
|
After Width: | Height: | Size: 219 KiB |
|
After Width: | Height: | Size: 206 KiB |
|
Before Width: | Height: | Size: 238 KiB After Width: | Height: | Size: 259 KiB |
|
Before Width: | Height: | Size: 236 KiB After Width: | Height: | Size: 255 KiB |
|
Before Width: | Height: | Size: 241 KiB After Width: | Height: | Size: 260 KiB |
|
Before Width: | Height: | Size: 169 KiB After Width: | Height: | Size: 191 KiB |
|
Before Width: | Height: | Size: 170 KiB After Width: | Height: | Size: 190 KiB |
|
Before Width: | Height: | Size: 222 KiB After Width: | Height: | Size: 222 KiB |
|
After Width: | Height: | Size: 416 KiB |
|
Before Width: | Height: | Size: 372 KiB After Width: | Height: | Size: 391 KiB |
|
Before Width: | Height: | Size: 368 KiB After Width: | Height: | Size: 393 KiB |
|
Before Width: | Height: | Size: 310 KiB After Width: | Height: | Size: 296 KiB |
|
Before Width: | Height: | Size: 596 KiB After Width: | Height: | Size: 612 KiB |
|
Before Width: | Height: | Size: 593 KiB After Width: | Height: | Size: 617 KiB |
|
After Width: | Height: | Size: 203 KiB |
|
After Width: | Height: | Size: 196 KiB |
|
Before Width: | Height: | Size: 173 KiB After Width: | Height: | Size: 211 KiB |
|
Before Width: | Height: | Size: 163 KiB After Width: | Height: | Size: 197 KiB |
|
Before Width: | Height: | Size: 167 KiB After Width: | Height: | Size: 203 KiB |
|
Before Width: | Height: | Size: 221 KiB After Width: | Height: | Size: 224 KiB |
|
After Width: | Height: | Size: 210 KiB |
|
After Width: | Height: | Size: 188 KiB |
|
Before Width: | Height: | Size: 207 KiB After Width: | Height: | Size: 232 KiB |
|
Before Width: | Height: | Size: 207 KiB After Width: | Height: | Size: 228 KiB |
|
After Width: | Height: | Size: 162 KiB |
|
After Width: | Height: | Size: 151 KiB |
|
After Width: | Height: | Size: 202 KiB |
|
After Width: | Height: | Size: 194 KiB |
|
After Width: | Height: | Size: 186 KiB |
|
After Width: | Height: | Size: 175 KiB |
|
After Width: | Height: | Size: 390 KiB |
|
After Width: | Height: | Size: 380 KiB |
|
After Width: | Height: | Size: 381 KiB |
|
After Width: | Height: | Size: 312 KiB |
|
Before Width: | Height: | Size: 154 KiB After Width: | Height: | Size: 176 KiB |
|
Before Width: | Height: | Size: 148 KiB After Width: | Height: | Size: 167 KiB |
|
After Width: | Height: | Size: 198 KiB |
|
After Width: | Height: | Size: 190 KiB |
|
Before Width: | Height: | Size: 181 KiB After Width: | Height: | Size: 212 KiB |
|
Before Width: | Height: | Size: 162 KiB After Width: | Height: | Size: 189 KiB |
|
Before Width: | Height: | Size: 244 KiB After Width: | Height: | Size: 248 KiB |
|
Before Width: | Height: | Size: 180 KiB After Width: | Height: | Size: 215 KiB |
|
Before Width: | Height: | Size: 172 KiB After Width: | Height: | Size: 204 KiB |
@@ -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
|
||||
@@ -112,3 +142,7 @@ State and city boundaries on the Geography page are from [Natural Earth](https:/
|
||||
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>
|
||||
@@ -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
|
||||
@@ -109,3 +139,7 @@ Os limites de estados e cidades da página Geografia são do [Natural Earth](htt
|
||||
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>
|
||||
@@ -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,9 +44,24 @@ 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
|
||||
|
||||
// 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 +102,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
|
||||
@@ -127,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", "")}
|
||||
@@ -150,8 +176,20 @@ 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)")
|
||||
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 +248,33 @@ 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")
|
||||
}
|
||||
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{}
|
||||
|
||||
@@ -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())
|
||||
@@ -56,6 +64,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
|
||||
@@ -133,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
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
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"
|
||||
"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
|
||||
}
|
||||
}
|
||||
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
|
||||
}
|
||||
eng, err := egress.New(egress.Config{
|
||||
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 := ""
|
||||
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
|
||||
}
|
||||
|
||||
// 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()...)
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
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, ready func() bool) *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, 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, ""
|
||||
}
|
||||
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{}
|
||||
pushedUn := 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
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
|
||||
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
|
||||
}
|
||||
|
||||
// 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")
|
||||
}
|
||||
@@ -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 ""
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||