Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1ef5a0ce9f | ||
|
|
0dc3268b29 | ||
|
|
50cd2bd3ce | ||
|
|
045ed53e43 | ||
|
|
ec46fb94ff | ||
|
|
432f521ed1 | ||
|
|
f27d8441a9 | ||
|
|
b267b98f18 | ||
|
|
9bdfdb491b | ||
|
|
5d3374ee11 |
No files matched your search
@@ -6,6 +6,50 @@ Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versio
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [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
|
||||
|
||||
@@ -6,6 +6,50 @@ Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/);
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
@@ -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).
|
||||
@@ -32,6 +33,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
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/var/log/urutau/egress.log {
|
||||
/var/log/urutau/egress.log /var/log/urutau/probe.log {
|
||||
daily
|
||||
rotate 7
|
||||
maxsize 200M
|
||||
|
||||
|
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,6 +44,7 @@ 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
|
||||
@@ -149,6 +151,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,6 +175,7 @@ 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)")
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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()...)
|
||||
}
|
||||
@@ -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
|
||||
@@ -39,6 +39,25 @@ func newEnforce(c Config, st *store.Store, peers []fed.Peer, en enricher) *enfor
|
||||
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}
|
||||
}
|
||||
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, ""
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -46,6 +46,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 {
|
||||
@@ -106,7 +109,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)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -257,3 +257,25 @@ 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")
|
||||
}
|
||||
}
|
||||
@@ -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.4.5"
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/netip"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
@@ -72,6 +74,9 @@ type traefikLine struct {
|
||||
|
||||
// ParseTraefik parses one Traefik JSON access log line.
|
||||
func ParseTraefik(line []byte) (Event, error) {
|
||||
if t := bytes.TrimLeft(line, " \t"); len(t) > 0 && t[0] != '{' {
|
||||
return parseTraefikText(string(t))
|
||||
}
|
||||
var l traefikLine
|
||||
if err := json.Unmarshal(line, &l); err != nil {
|
||||
return Event{}, err
|
||||
@@ -213,3 +218,119 @@ func ParseFail2ban(line string) (Event, error) {
|
||||
Unban: m[3] == "Unban", Restore: m[3] == "Restore Ban",
|
||||
}, nil
|
||||
}
|
||||
|
||||
// textFields splits a Traefik text (extended CLF) access log line into its
|
||||
// fields. Quoted fields may carry backslash escapes, the [time] field is read
|
||||
// up to the closing bracket.
|
||||
func textFields(s string) ([]string, bool) {
|
||||
var out []string
|
||||
i := 0
|
||||
for i < len(s) {
|
||||
switch c := s[i]; {
|
||||
case c == ' ' || c == '\t':
|
||||
i++
|
||||
case c == '"':
|
||||
var b strings.Builder
|
||||
i++
|
||||
closed := false
|
||||
for i < len(s) {
|
||||
if s[i] == '\\' && i+1 < len(s) {
|
||||
b.WriteByte(s[i+1])
|
||||
i += 2
|
||||
continue
|
||||
}
|
||||
if s[i] == '"' {
|
||||
closed = true
|
||||
i++
|
||||
break
|
||||
}
|
||||
b.WriteByte(s[i])
|
||||
i++
|
||||
}
|
||||
if !closed {
|
||||
return nil, false
|
||||
}
|
||||
out = append(out, b.String())
|
||||
case c == '[':
|
||||
j := strings.IndexByte(s[i:], ']')
|
||||
if j < 0 {
|
||||
return nil, false
|
||||
}
|
||||
out = append(out, s[i+1:i+j])
|
||||
i += j + 1
|
||||
default:
|
||||
j := i
|
||||
for j < len(s) && s[j] != ' ' && s[j] != '\t' {
|
||||
j++
|
||||
}
|
||||
out = append(out, s[i:j])
|
||||
i = j
|
||||
}
|
||||
}
|
||||
return out, true
|
||||
}
|
||||
|
||||
func dash(s string) string {
|
||||
if s == "-" {
|
||||
return ""
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// parseTraefikText parses the default Traefik access log format:
|
||||
// host ident user [time] "METHOD path PROTO" status size "referer" "ua" count "router" "backend" Nms
|
||||
// The format carries no Host header, so Domain stays empty.
|
||||
func parseTraefikText(line string) (Event, error) {
|
||||
f, ok := textFields(line)
|
||||
if !ok || len(f) < 9 {
|
||||
return Event{}, errors.New("not a traefik text line")
|
||||
}
|
||||
ip, ok := cleanIP(f[0])
|
||||
if !ok {
|
||||
if _, err := netip.ParseAddr(strings.TrimSpace(f[0])); err != nil {
|
||||
return Event{}, errors.New("bad client address")
|
||||
}
|
||||
return Event{}, ErrIgnored
|
||||
}
|
||||
t, err := time.Parse("02/Jan/2006:15:04:05 -0700", f[3])
|
||||
if err != nil {
|
||||
return Event{}, err
|
||||
}
|
||||
rl := strings.Fields(f[4])
|
||||
if len(rl) < 2 {
|
||||
return Event{}, errors.New("bad request line")
|
||||
}
|
||||
method, path, proto := rl[0], rl[1], ""
|
||||
if len(rl) >= 3 {
|
||||
proto = rl[len(rl)-1]
|
||||
}
|
||||
status, err := strconv.Atoi(f[5])
|
||||
if err != nil || status < 100 || status > 999 {
|
||||
return Event{}, errors.New("bad status")
|
||||
}
|
||||
var size int64
|
||||
if f[6] != "-" {
|
||||
if size, err = strconv.ParseInt(f[6], 10, 64); err != nil {
|
||||
return Event{}, err
|
||||
}
|
||||
}
|
||||
ev := Event{
|
||||
Time: t.UTC(), IP: ip, Source: "traefik", Status: status,
|
||||
Method: clip(method, 12), Path: clip(path, maxPath), Proto: clip(proto, 12),
|
||||
Bytes: size, Referer: clip(dash(f[7]), 300), UA: clip(dash(f[8]), maxUA),
|
||||
}
|
||||
if len(f) > 10 {
|
||||
ev.Router = clip(dash(f[10]), 64)
|
||||
}
|
||||
if len(f) > 11 && dash(f[11]) != "" {
|
||||
ev.OriginStatus = status
|
||||
}
|
||||
if len(f) > 12 {
|
||||
if d, err := time.ParseDuration(strings.TrimSpace(f[12])); err == nil {
|
||||
ev.DurationNS = d.Nanoseconds()
|
||||
}
|
||||
}
|
||||
c := Classify(method, path, status)
|
||||
ev.Cat, ev.Soft, ev.Strong, ev.Weak = c.Cat, c.Soft, c.Strong, c.Weak
|
||||
return ev, nil
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package core
|
||||
|
||||
// PortService is the well-known service of a probed port ("" when unknown).
|
||||
func PortService(proto string, port uint16) string {
|
||||
if proto == "udp" {
|
||||
return udpServices[port]
|
||||
}
|
||||
return tcpServices[port]
|
||||
}
|
||||
|
||||
var tcpServices = map[uint16]string{
|
||||
21: "ftp", 22: "ssh", 23: "telnet", 25: "smtp", 53: "dns", 80: "http", 110: "pop3", 111: "rpcbind", 135: "msrpc",
|
||||
139: "netbios", 143: "imap", 389: "ldap", 443: "https", 445: "smb", 465: "smtps", 587: "submission", 993: "imaps",
|
||||
995: "pop3s", 1433: "mssql", 1521: "oracle", 1723: "pptp", 2049: "nfs", 2375: "docker", 3306: "mysql", 3389: "rdp",
|
||||
5432: "postgres", 5900: "vnc", 5901: "vnc", 6379: "redis", 8080: "http-alt", 8443: "https-alt", 9200: "elasticsearch",
|
||||
11211: "memcached", 27017: "mongodb", 2323: "telnet",
|
||||
}
|
||||
|
||||
var udpServices = map[uint16]string{
|
||||
53: "dns", 69: "tftp", 123: "ntp", 161: "snmp", 389: "cldap", 500: "ike", 1900: "ssdp", 5060: "sip", 11211: "memcached",
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
@@ -173,6 +174,14 @@ func TestBeaconPositive(t *testing.T) {
|
||||
if hi == nil || hi.Severity != "high" {
|
||||
t.Fatalf("attacker beacon: %+v", hi)
|
||||
}
|
||||
if n := len(got.Samples); n < 40 || n > MaxSamples || got.Samples[n-1] != got.Last {
|
||||
t.Fatalf("samples: %d %v", n, got.Samples)
|
||||
}
|
||||
for i := 1; i < len(got.Samples); i++ {
|
||||
if got.Samples[i] <= got.Samples[i-1] {
|
||||
t.Fatalf("samples not increasing: %v", got.Samples)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBeaconNegatives(t *testing.T) {
|
||||
@@ -420,6 +429,34 @@ func TestReportMergeSanitize(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestReportByCountry(t *testing.T) {
|
||||
geo := func(s string) (string, string, string) {
|
||||
if s == "203.0.113.1" || s == "203.0.113.2" {
|
||||
return "DE", "AS1", "x"
|
||||
}
|
||||
return "US", "AS2", "y"
|
||||
}
|
||||
e := newEng(t, Config{Geo: geo})
|
||||
e.IngestEvent(mk(t0, "10.0.3.5", "203.0.113.1", "tcp", 443))
|
||||
e.IngestEvent(mk(t0, "10.0.3.5", "203.0.113.2", "tcp", 443))
|
||||
e.IngestEvent(mk(t0.Add(time.Minute), "10.0.3.5", "203.0.113.2", "tcp", 443))
|
||||
e.IngestEvent(mk(t0, "10.0.3.5", "198.51.100.1", "tcp", 443))
|
||||
r := e.Report(t0.Unix()-3600, t0.Unix()+3600)
|
||||
if len(r.ByCountry) != 2 || r.ByCountry[0].CC != "DE" || r.ByCountry[0].Conns != 3 || r.ByCountry[0].Dsts != 2 || r.ByCountry[1].Conns != 1 {
|
||||
t.Fatalf("by_country: %+v", r.ByCountry)
|
||||
}
|
||||
peer := e.Report(t0.Unix()-3600, t0.Unix()+3600)
|
||||
peer.ByCountry = append(peer.ByCountry, make([]CountryOut, 400)...)
|
||||
peer.Sanitize("p")
|
||||
if len(peer.ByCountry) > maxCountries {
|
||||
t.Fatalf("sanitize: %d", len(peer.ByCountry))
|
||||
}
|
||||
r.Merge(peer, "p")
|
||||
if r.ByCountry[0].CC != "DE" || r.ByCountry[0].Conns != 6 {
|
||||
t.Fatalf("merge: %+v", r.ByCountry[:2])
|
||||
}
|
||||
}
|
||||
|
||||
func TestNameMatchExactAndPrefix(t *testing.T) {
|
||||
e := newEng(t, Config{Workloads: "a=name:web:default;b=name:api*:default;c=name:pay:default"})
|
||||
e.SetContainers(map[netip.Addr]string{ip("172.18.0.1"): "web-1700000000000", ip("172.18.0.2"): "webshell-1700000000000",
|
||||
@@ -512,3 +549,59 @@ func TestBeaconDuringContinuousScan(t *testing.T) {
|
||||
t.Fatal("fanSeen unbounded")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBeaconProviderAndCDN(t *testing.T) {
|
||||
geo := func(s string) (string, string, string) {
|
||||
switch s {
|
||||
case "192.0.2.10":
|
||||
return "US", "AS31898", "Oracle Corporation"
|
||||
case "192.0.2.20":
|
||||
return "US", "AS13335", "Cloudflare"
|
||||
}
|
||||
return "BR", "AS2", "y"
|
||||
}
|
||||
bad := func(a netip.Addr) (bool, string) { return a == ip("192.0.2.30"), "known attacker" }
|
||||
e := newEng(t, Config{Geo: geo, BadDst: bad, ProviderASNs: func() []string { return []string{"AS31898"} }})
|
||||
rnd := rand.New(rand.NewSource(2))
|
||||
for _, src := range []string{"10.0.3.5"} {
|
||||
feedBeacon(e, src, "192.0.2.10", 443, t0, 50, 60*time.Second, 0.05, rnd)
|
||||
feedBeacon(e, src, "192.0.2.20", 443, t0, 50, 60*time.Second, 0.05, rnd)
|
||||
}
|
||||
// the host itself towards the provider network
|
||||
for i := 0; i < 50; i++ {
|
||||
ev := mk(t0.Add(time.Duration(i)*60*time.Second), "10.0.3.5", "192.0.2.10", "tcp", 8443)
|
||||
ev.Host = true
|
||||
e.IngestEvent(ev)
|
||||
ev2 := mk(t0.Add(time.Duration(i)*60*time.Second), "10.0.3.5", "192.0.2.30", "tcp", 8443)
|
||||
ev2.Host = true
|
||||
e.IngestEvent(ev2)
|
||||
}
|
||||
r := rep(e)
|
||||
var inf, cont, cdn, hi bool
|
||||
for _, f := range r.Findings {
|
||||
switch {
|
||||
case f.Kind == "infra" && f.Dst == "192.0.2.10" && f.Workload == "host" && f.Severity == "info" && strings.Contains(f.Detail, "provider service (Oracle Corporation)"):
|
||||
inf = true
|
||||
case f.Kind == "beacon" && f.Dst == "192.0.2.10" && f.Severity == "medium":
|
||||
cont = true // container to the provider ASN: evaluated normally
|
||||
case f.Kind == "beacon" && f.Dst == "192.0.2.20" && f.Severity == "low" && strings.Contains(f.Detail, "API"):
|
||||
cdn = true
|
||||
case f.Kind == "beacon" && f.Dst == "192.0.2.30" && f.Severity == "high":
|
||||
hi = true
|
||||
}
|
||||
}
|
||||
if !inf || !cont || !cdn || !hi {
|
||||
t.Fatalf("infra=%v container=%v cdn=%v bad=%v: %+v", inf, cont, cdn, hi, r.Findings)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTorRelayFinding(t *testing.T) {
|
||||
e := newEng(t, Config{Workloads: "sc=10.0.5.0/24:scanner", TorRelay: func(a netip.Addr) bool { return a == ip("192.0.2.77") }})
|
||||
e.IngestEvent(mk(t0, "10.0.3.5", "192.0.2.77", "tcp", 443))
|
||||
e.IngestEvent(mk(t0, "10.0.5.2", "192.0.2.77", "tcp", 443)) // scanner outside a burst
|
||||
e.IngestEvent(mk(t0, "10.0.3.5", "192.0.2.78", "tcp", 443))
|
||||
f := kinds(rep(e), "tor")
|
||||
if len(f) != 2 || f[0].Severity != "high" || f[0].Dst != "192.0.2.77" {
|
||||
t.Fatalf("tor: %+v", f)
|
||||
}
|
||||
}
|
||||
@@ -61,7 +61,13 @@ type Config struct {
|
||||
// destination is a known attacker or Tor exit (and why).
|
||||
Geo func(ip string) (cc, asn, org string)
|
||||
BadDst func(netip.Addr) (bool, string)
|
||||
Now func() time.Time
|
||||
// TorRelay says whether an address is a Tor relay (a connection to one is
|
||||
// a "tor" finding).
|
||||
TorRelay func(netip.Addr) bool
|
||||
// ProviderASNs ("AS31898") are the hosting provider's own networks: a
|
||||
// beacon from the host itself to them is informational ("infra").
|
||||
ProviderASNs func() []string
|
||||
Now func() time.Time
|
||||
// Learn is the per-workload learning time before new_geo (default 24h).
|
||||
Learn time.Duration
|
||||
// ResolvConf lists resolv.conf files whose nameservers are allowed resolvers
|
||||
@@ -700,6 +706,9 @@ func (e *Engine) checks(ws *wstate, ev Event, dport uint16, t int64, ds *dstStat
|
||||
e.addFinding("bad_dst", "high", ws.name, dst, dport, ev.Proto, t, 0, 0, why, 1)
|
||||
}
|
||||
}
|
||||
if e.cfg.TorRelay != nil && e.cfg.TorRelay(ev.Dst) {
|
||||
e.addFinding("tor", "high", ws.name, dst, dport, ev.Proto, t, 0, 0, "connection to a Tor relay", 1)
|
||||
}
|
||||
if ev.Proto == "tcp" {
|
||||
if sev, why := suspiciousPort(dport, ws.role); why != "" {
|
||||
e.addFinding("port", sev, ws.name, dst, dport, ev.Proto, t, 0, 0, why, 1)
|
||||
@@ -744,7 +753,22 @@ func suspiciousPort(port uint16, role string) (sev, why string) {
|
||||
|
||||
func (e *Engine) beacon(ws *wstate, ev Event, dport uint16, dns bool, p *pairState, ds *dstStat) {
|
||||
if p.flagged {
|
||||
e.addFinding("beacon", "", ws.name, ev.Dst.String(), dport, ev.Proto, p.last, p.interval, p.cv, "", 1)
|
||||
kind := "beacon"
|
||||
if ev.Host && e.cfg.Geo != nil {
|
||||
if _, asn, _ := e.cfg.Geo(ev.Dst.String()); e.providerASN(asn) {
|
||||
if _, ok := e.findings[fmt.Sprintf("infra|%s|%s|%d", ws.name, ev.Dst, dport)]; ok {
|
||||
kind = "infra"
|
||||
}
|
||||
}
|
||||
}
|
||||
if f := e.addFinding(kind, "", ws.name, ev.Dst.String(), dport, ev.Proto, p.last, p.interval, p.cv, "", 1); f != nil {
|
||||
if n := len(f.Samples); n == 0 || f.Samples[n-1] != p.last {
|
||||
if n >= MaxSamples {
|
||||
f.Samples = append(f.Samples[:0], f.Samples[1:]...)
|
||||
}
|
||||
f.Samples = append(f.Samples, p.last)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
ntp := ev.Proto == "udp" && dport == 123
|
||||
@@ -795,20 +819,55 @@ func (e *Engine) beacon(ws *wstate, ev Event, dport uint16, dns bool, p *pairSta
|
||||
if mad < cv {
|
||||
jit = mad
|
||||
}
|
||||
sev := "medium"
|
||||
sev, kind := "medium", "beacon"
|
||||
why := fmt.Sprintf("regular connections every %.0f s (jitter %.0f%%)", med, jit*100)
|
||||
bad := false
|
||||
if e.cfg.BadDst != nil {
|
||||
if bad, r := e.cfg.BadDst(ev.Dst); bad {
|
||||
sev, why = "high", why+"; destination: "+r
|
||||
if b, r := e.cfg.BadDst(ev.Dst); b {
|
||||
bad, sev, why = true, "high", why+"; destination: "+r
|
||||
}
|
||||
}
|
||||
if !bad && e.cfg.Geo != nil {
|
||||
_, asn, org := e.cfg.Geo(ev.Dst.String())
|
||||
switch {
|
||||
case ev.Host && e.providerASN(asn):
|
||||
sev, kind = "info", "infra"
|
||||
why = fmt.Sprintf("%s; provider service (%s)", why, org)
|
||||
case commonCloudASNs[asn]:
|
||||
sev = "low"
|
||||
why += "; large CDN/cloud network: regular connections are common for API calls"
|
||||
}
|
||||
}
|
||||
p.flagged, p.interval, p.cv = true, med, jit
|
||||
f := e.addFinding("beacon", sev, ws.name, ev.Dst.String(), dport, ev.Proto, p.last, med, jit, why, 0)
|
||||
f := e.addFinding(kind, sev, ws.name, ev.Dst.String(), dport, ev.Proto, p.last, med, jit, why, 0)
|
||||
if f != nil {
|
||||
f.Count, f.First = int(p.total), p.first
|
||||
f.Samples = make([]int64, 0, MaxSamples)
|
||||
for i := 0; i < p.n; i++ {
|
||||
f.Samples = append(f.Samples, int64(p.ts[i]))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// commonCloudASNs are large CDNs/clouds whose regular connections usually are
|
||||
// API calls.
|
||||
var commonCloudASNs = map[string]bool{"AS13335": true, "AS15169": true, "AS14618": true, "AS16509": true, "AS8075": true, "AS20940": true, "AS54113": true}
|
||||
|
||||
func (e *Engine) providerASN(asn string) bool {
|
||||
if asn == "" {
|
||||
return false
|
||||
}
|
||||
if e.cfg.ProviderASNs == nil {
|
||||
return false
|
||||
}
|
||||
for _, a := range e.cfg.ProviderASNs() {
|
||||
if strings.EqualFold(a, asn) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func median(v []float64) float64 {
|
||||
s := append([]float64(nil), v...)
|
||||
sort.Float64s(s)
|
||||
@@ -822,7 +881,7 @@ func median(v []float64) float64 {
|
||||
return (s[n/2-1] + s[n/2]) / 2
|
||||
}
|
||||
|
||||
var sevRank = map[string]int{"low": 1, "medium": 2, "high": 3}
|
||||
var sevRank = map[string]int{"info": 0, "low": 1, "medium": 2, "high": 3}
|
||||
|
||||
func (e *Engine) addFinding(kind, sev, wl, dst string, dport uint16, proto string, t int64, iv, jit float64, detail string, inc int) *Finding {
|
||||
key := fmt.Sprintf("%s|%s|%s|%d", kind, wl, dst, dport)
|
||||
|
||||