Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4143bf599e | ||
|
|
65015158dc | ||
|
|
87178dbc94 | ||
|
|
c2bee81bc1 | ||
|
|
551b0ebc40 | ||
|
|
7b90d9e40f | ||
|
|
0db50c05c4 | ||
|
|
19afd221e2 |
No files matched your search
@@ -6,6 +6,38 @@ Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versio
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [2.2.2] - 2026-11-19
|
||||
|
||||
### Fixed
|
||||
|
||||
- Outbound traffic: a redeploy that swapped addresses between containers (LambdaMail's rspamd and clamav traded 172.19.0.2 and .5) was judged with the previous minute's `containers.map`, so findings landed on the wrong workload (rspamd's SURBL and DNS traffic as `clamav`, freshclam as `dns`). The host kit now also runs `urutau-containers-watch`, which rewrites the map on every container start or network attach, and the probe checks the file every 2 seconds instead of 10. Reinstall the host kit (`deploy/host/install.sh`) and update the probes.
|
||||
- Outbound traffic: `new_geo` no longer fires for large CDNs and clouds (Cloudflare, Google, AWS, Azure, Akamai, Fastly, Telegram): their addresses are anycast or global, and the database country (1.1.1.1 in Australia, a Cloudflare edge in Canada) says nothing about where the traffic goes. Test `TestNewGeoSkipsAnycastCDN`.
|
||||
|
||||
## [2.2.1] - 2026-11-16
|
||||
|
||||
### Fixed
|
||||
|
||||
- Traffic on probe-fed hosts kept disappearing after Traefik's copytruncate rotation even with 2.2.0: the head fingerprint covered only 64 bytes, and Traefik's first line of every generation starts with the same keep-alive client address and port, so every generation looked like the same file and the hub dropped every line below the previous high-water mark. The fingerprint now covers up to 1024 bytes (the whole first line, with its nanosecond timestamp), and the hub treats fingerprints of different lengths as different generations. Update the probes too. Tests `TestHeadCoversFirstLine` and `TestSameHeadCopytruncate`.
|
||||
|
||||
## [2.2.0] - 2026-11-16
|
||||
|
||||
### Added
|
||||
|
||||
- IP analysis: an address that never attacked but is an egress destination (for example the IP of an egress incident) now opens a "Destination" view: which hosts and workloads connected to it, ports, connections, ASN/country, findings and linked incidents. New endpoint `GET /api/v1/ip/{ip}/egress`. When nothing exists the page says definitively that the IP was never seen; if it was seen inbound outside the period it shows the last date and a 30-day button.
|
||||
- Global host filter: several probes can be selected at once (`host=oracle,hostinger` in the URL and the API); selecting all of them, or "All hosts", means every probe.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Traffic: the hub dropped Traefik lines after every copytruncate rotation of `access.log` (it compared only inode and offset and ignored the head fingerprint the probe sends), so legitimate traffic on the Oracle host vanished for hours after each rotation. Regression test `TestSameHeadCopytruncate`.
|
||||
- Global host filter: going back to "All hosts" did nothing, because the URL without `host=` kept the previous host.
|
||||
|
||||
## [2.1.2] - 2026-11-16
|
||||
|
||||
### Fixed
|
||||
|
||||
- Egress, false `dns_bypass` right after a hub restart: the files a probe sends (`resolv.conf`, `containers.map`) lived only in the hub's memory, so after a restart the egress lines the probe replayed on reconnect were judged before the probe sent them again (Hostinger `coolify-sentinel` → its upstream resolver 153.92.2.6, hostinger/INC-8). The hub now keeps the last copy of each file in the node's data directory (`probe-resolv.conf`, `probe-containers.map`) and loads it at start. Regression test `TestProbeFilesSurviveRestart`.
|
||||
- Phone layout: the global filter sheet (period and host) opens above the bottom tab bar instead of covering it, tapping the tab bar closes it, and the sticky filter bar no longer sits on top of the "More" menu.
|
||||
|
||||
## [2.1.1] - 2026-11-16
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -6,6 +6,38 @@ Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/);
|
||||
|
||||
## [Não lançado]
|
||||
|
||||
## [2.2.2] - 2026-11-19
|
||||
|
||||
### Corrigido
|
||||
|
||||
- Tráfego de saída: um redeploy que trocou endereços entre contêineres (o rspamd e o clamav do LambdaMail trocaram 172.19.0.2 e .5) era julgado com o `containers.map` do minuto anterior, e os achados caíam no workload errado (SURBL e DNS do rspamd como `clamav`, freshclam como `dns`). O kit do host agora também roda o `urutau-containers-watch`, que regrava o mapa a cada contêiner que sobe ou entra numa rede, e a sonda confere o arquivo a cada 2 segundos em vez de 10. Reinstale o kit do host (`deploy/host/install.sh`) e atualize as sondas.
|
||||
- Tráfego de saída: `new_geo` não dispara mais para grandes CDNs e nuvens (Cloudflare, Google, AWS, Azure, Akamai, Fastly, Telegram): os endereços são anycast ou globais, e o país da base (1.1.1.1 na Austrália, uma borda da Cloudflare no Canadá) nada diz sobre o destino do tráfego. Teste `TestNewGeoSkipsAnycastCDN`.
|
||||
|
||||
## [2.2.1] - 2026-11-16
|
||||
|
||||
### Corrigido
|
||||
|
||||
- O tráfego dos hosts alimentados por sonda continuava sumindo depois da rotação copytruncate do Traefik mesmo na 2.2.0: a impressão digital do início do arquivo cobria só 64 bytes, e a primeira linha de cada geração do Traefik começa com o mesmo endereço e porta de uma conexão keep-alive, então toda geração parecia o mesmo arquivo e o hub descartava as linhas abaixo da marca anterior. A impressão digital agora cobre até 1024 bytes (a primeira linha inteira, com carimbo de tempo em nanossegundos), e o hub trata impressões de tamanhos diferentes como gerações diferentes. Atualize também as sondas. Testes `TestHeadCoversFirstLine` e `TestSameHeadCopytruncate`.
|
||||
|
||||
## [2.2.0] - 2026-11-16
|
||||
|
||||
### Adicionado
|
||||
|
||||
- Análise de IP: um endereço que nunca atacou mas é destino de saída (por exemplo o IP de um incidente de egress) agora abre a vista "Destino de saída": quais hosts e cargas de trabalho se conectaram, portas, conexões, ASN/país, achados e incidentes ligados. Endpoint novo `GET /api/v1/ip/{ip}/egress`. Quando não há nada, a página diz de forma definitiva que o IP nunca foi visto; se foi visto como origem fora do período, mostra a última data e um botão de 30 dias.
|
||||
- Filtro global de host: várias sondas podem ser selecionadas ao mesmo tempo (`host=oracle,hostinger` na URL e na API); marcar todas, ou "Todos os hosts", significa todas as sondas.
|
||||
|
||||
### Corrigido
|
||||
|
||||
- Tráfego: o hub descartava linhas do Traefik depois de cada rotação copytruncate do `access.log` (comparava só inode e offset e ignorava a impressão digital do início que a sonda envia), então o tráfego legítimo do host Oracle sumia por horas após cada rotação. Teste de regressão `TestSameHeadCopytruncate`.
|
||||
- Filtro global de host: voltar para "Todos os hosts" não fazia nada, porque a URL sem `host=` mantinha o host anterior.
|
||||
|
||||
## [2.1.2] - 2026-11-16
|
||||
|
||||
### Corrigido
|
||||
|
||||
- Saída, `dns_bypass` falso logo após reiniciar o hub: os arquivos que a sonda envia (`resolv.conf`, `containers.map`) ficavam só na memória do hub, então depois de um reinício as linhas de saída que a sonda reenviava ao reconectar eram julgadas antes de ela mandar os arquivos de novo (`coolify-sentinel` da Hostinger → o resolvedor upstream 153.92.2.6, hostinger/INC-8). O hub agora guarda a última cópia de cada arquivo no diretório do nó (`probe-resolv.conf`, `probe-containers.map`) e a carrega na inicialização. Teste de regressão `TestProbeFilesSurviveRestart`.
|
||||
- Celular: a folha de filtros globais (período e host) abre acima da barra de navegação inferior em vez de cobri-la, tocar na barra a fecha, e a barra de filtros fixa não fica mais por cima do menu "Mais".
|
||||
|
||||
## [2.1.1] - 2026-11-16
|
||||
|
||||
### Corrigido
|
||||
|
||||
@@ -87,7 +87,7 @@ It never blocks trusted addresses, private ranges, CDN (Cloudflare) and public r
|
||||
|
||||
## Outbound traffic and incidents
|
||||
|
||||
Optional (`URUTAU_EGRESS=auto|on|off`; `auto` turns it on for a probe that sends the outbound log). The host kit logs only new TCP connection attempts through nftables, and a container map names the workloads. Urutau checks them for beaconing (regular conversations with one destination), mining, IRC and SMTP ports, contact with addresses that attacked the server or with Tor relays, DNS outside the allowed resolvers (`URUTAU_EGRESS_RESOLVERS`), unauthorised outbound scans and new countries. Workloads are defined 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. The servers themselves, peers and the host's own provider never raise findings, cloud metadata services polled by the host are `infra`, and regular connections to large CDNs and clouds are low severity.
|
||||
Optional (`URUTAU_EGRESS=auto|on|off`; `auto` turns it on for a probe that sends the outbound log). The host kit logs only new TCP connection attempts through nftables, and a container map names the workloads. Urutau checks them for beaconing (regular conversations with one destination), mining, IRC and SMTP ports, contact with addresses that attacked the server or with Tor relays, DNS outside the allowed resolvers (`URUTAU_EGRESS_RESOLVERS`), unauthorised outbound scans and new countries. Workloads are defined 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. The servers themselves, peers and the host's own provider never raise findings, cloud metadata services polled by the host are `infra`, and regular connections to large CDNs and clouds are low severity, and they never raise a new country (their database country means nothing for anycast).
|
||||
|
||||
Every finding above info severity becomes a ticket `INC-<n>` (list, ticket page, manual tickets, CSV export, `/api/v1/incidents`). A ticket marked `false_positive` or `benign` can suppress findings with exactly its key; a resolved ticket reopens if the finding comes back.
|
||||
|
||||
|
||||
+1
-1
@@ -87,7 +87,7 @@ Nunca bloqueia endereços confiáveis, faixas privadas, faixas de CDN (Cloudflar
|
||||
|
||||
## Tráfego de saída e incidentes
|
||||
|
||||
Opcional (`URUTAU_EGRESS=auto|on|off`; `auto` liga para a sonda que envia o log de saída). O kit de host registra, pelo nftables, só tentativas novas de conexão TCP, e um mapa de contêineres nomeia os workloads. O Urutau checa beaconing (conversas regulares com um destino), mineração, portas de IRC e SMTP, contato com endereços que atacaram o servidor ou com relays Tor, DNS fora dos resolvers permitidos (`URUTAU_EGRESS_RESOLVERS`), varreduras de saída não autorizadas e países novos. Os workloads são definidos por nome de rede ou de contêiner (`URUTAU_EGRESS_WORKLOADS`); um workload `scanner` (um scanner de superfície autorizado) tem só o tráfego em forma de varredura resumido, o resto é julgado como qualquer outro workload. Os próprios servidores, peers e o provedor do host nunca geram achados, serviços de metadados de nuvem consultados pelo host são `infra`, e conexões regulares a grandes CDNs e nuvens têm severidade baixa.
|
||||
Opcional (`URUTAU_EGRESS=auto|on|off`; `auto` liga para a sonda que envia o log de saída). O kit de host registra, pelo nftables, só tentativas novas de conexão TCP, e um mapa de contêineres nomeia os workloads. O Urutau checa beaconing (conversas regulares com um destino), mineração, portas de IRC e SMTP, contato com endereços que atacaram o servidor ou com relays Tor, DNS fora dos resolvers permitidos (`URUTAU_EGRESS_RESOLVERS`), varreduras de saída não autorizadas e países novos. Os workloads são definidos por nome de rede ou de contêiner (`URUTAU_EGRESS_WORKLOADS`); um workload `scanner` (um scanner de superfície autorizado) tem só o tráfego em forma de varredura resumido, o resto é julgado como qualquer outro workload. Os próprios servidores, peers e o provedor do host nunca geram achados, serviços de metadados de nuvem consultados pelo host são `infra`, e conexões regulares a grandes CDNs e nuvens têm severidade baixa e nunca geram país novo (o país da base nada diz sobre anycast).
|
||||
|
||||
Todo achado acima de info vira um chamado `INC-<n>` (lista, página do chamado, chamados manuais, exportação CSV, `/api/v1/incidents`). Um chamado marcado `false_positive` ou `benign` pode suprimir achados com exatamente a sua chave; um chamado resolvido reabre se o achado voltar.
|
||||
|
||||
|
||||
@@ -35,9 +35,10 @@ done
|
||||
[ "$(id -u)" = 0 ] || { echo "run as root" >&2; exit 1; }
|
||||
|
||||
if [ "$remove" = 1 ]; then
|
||||
systemctl disable --now urutau-egress.service urutau-containers-map.timer urutau-logrotate.timer urutau-unban.path 2>/dev/null || true
|
||||
systemctl disable --now urutau-egress.service urutau-containers-watch.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/systemd/system/urutau-containers-watch.service /usr/local/sbin/urutau-containers-watch \
|
||||
/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 \
|
||||
@@ -62,14 +63,16 @@ 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 0755 "$here/urutau-containers-watch" /usr/local/sbin/urutau-containers-watch
|
||||
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/
|
||||
"$here/urutau-containers-map.timer" "$here/urutau-containers-watch.service" "$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 enable urutau-egress.service urutau-containers-map.timer urutau-containers-watch.service 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
|
||||
systemctl restart urutau-containers-watch.service
|
||||
echo "egress logging on $wan: /var/log/urutau/egress.log, map: /var/log/urutau/containers.map"
|
||||
|
||||
if [ "$probe" = 1 ] && [ "$enforce" = 0 ]; then
|
||||
|
||||
Executable
+13
@@ -0,0 +1,13 @@
|
||||
#!/bin/bash
|
||||
# Urutau: rewrites containers.map as soon as Docker attaches a container to a
|
||||
# network, so a redeploy that swaps addresses between containers is not judged
|
||||
# with the old names until the next minute of the timer.
|
||||
set -u
|
||||
docker events --filter type=network --filter event=connect --filter type=container --filter event=start --format '{{.Type}}' |
|
||||
while read -r _; do
|
||||
/usr/local/sbin/urutau-containers-map || true
|
||||
# a stack redeploy fires dozens of events: drain the burst, then refresh once more
|
||||
n=0
|
||||
while read -r -t 1 _; do n=$((n + 1)); done
|
||||
[ "$n" -gt 0 ] && { /usr/local/sbin/urutau-containers-map || true; }
|
||||
done
|
||||
@@ -0,0 +1,12 @@
|
||||
[Unit]
|
||||
Description=Urutau: refresh the container map when containers start
|
||||
After=docker.service
|
||||
Requires=docker.service
|
||||
|
||||
[Service]
|
||||
ExecStart=/usr/local/sbin/urutau-containers-watch
|
||||
Restart=always
|
||||
RestartSec=5s
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -96,7 +96,7 @@ The probe has only these variables (flags in [cli.md](cli.md#urutau-probe)). A p
|
||||
| `URUTAU_FAIL2BAN_LOG` | `/logs/host/fail2ban.log` | fail2ban log |
|
||||
| `URUTAU_PROBE_LOG` | `/logs/host/probe.log` | kernel log of connections to unserved ports, written by the host kit (see [Probes](#probes-port-scans)) |
|
||||
| `URUTAU_EGRESS_LOG` | `/logs/host/egress.log` | kernel log of new outbound connections, written by the host kit |
|
||||
| `URUTAU_EGRESS_CONTAINERS` | `/logs/host/containers.map` | `"<ip> <container>"` map written by the host kit every minute, so workloads keep their name when the address changes on a redeploy; sent whole when it changes |
|
||||
| `URUTAU_EGRESS_CONTAINERS` | `/logs/host/containers.map` | `"<ip> <container>"` map written by the host kit when a container starts (and every minute), so workloads keep their name when the address changes on a redeploy; sent whole when it changes |
|
||||
| `URUTAU_RESOLV` | `/etc/resolv.conf` of the host (mounted) | resolvers of the host, sent whole when it changes |
|
||||
| `URUTAU_ENFORCE_LOG` | `/logs/enforce/decisions.log` | file where the ban decisions of the hub are appended, read by the host jail; empty ignores ban commands and counts them as errors |
|
||||
| `URUTAU_ENFORCE_UNBAN_LOG` | `/logs/enforce/unban.log` | file where unban requests are appended, read by the host; empty ignores them |
|
||||
|
||||
+1
-1
@@ -179,7 +179,7 @@ It is idempotent. `URUTAU_WAN` overrides the detected uplink interface and `URUT
|
||||
|---|---|
|
||||
| egress logging | nftables table `inet urutau_egress` (`/etc/urutau/egress.nft`, only logs, never drops, separate from the Docker and fail2ban tables) and the `urutau-egress.service` unit; rsyslog rule `41-urutau-egress.conf` sends the kernel lines to `/var/log/urutau/egress.log` (`URUTAU-EGRESS:`) and `/var/log/urutau/probe.log` (`URUTAU-PROBE:`); logrotate daily, 7 copies, at most 200 MB (`urutau-logrotate.timer`) |
|
||||
| probes | the `URUTAU-PROBE:` rule logs new inbound connections on the uplink to ports no socket listens on (at most 10 per second per source); the set of open ports is refreshed every minute from `ss`, including ports Docker publishes |
|
||||
| container map | `urutau-containers-map` and its timer (every minute) write `/var/log/urutau/containers.map` (`<ip> <container>`) and `/var/log/urutau/resolv.conf` (the real upstream resolvers) |
|
||||
| container map | `urutau-containers-map`, run by its timer (every minute) and by `urutau-containers-watch` (on every container start or network attach, so a redeploy that swaps addresses is named right within seconds), writes `/var/log/urutau/containers.map` (`<ip> <container>`) and `/var/log/urutau/resolv.conf` (the real upstream resolvers) |
|
||||
| second firewall (`--enforce`) | directory `/var/log/urutau-enforce` (owned by `URUTAU_UID`, group `adm`) with `decisions.log` and `unban.log`; fail2ban filter `urutau`, action `urutau-allports` and jail `urutau` (`polling` backend, `maxretry = 1`, `bantime = 1h`, actions on `INPUT` and `DOCKER-USER`, host `ignoreip` kept); `urutau-unban.path` and `urutau-unban` apply the Unban button |
|
||||
|
||||
The `urutau-allports` action behaves like `iptables-allports` but only drops connections the banned address starts (conntrack original direction), so replies to connections the host opened keep flowing. The egress and probe files land in `/var/log/urutau`, which the probe compose file already mounts at `/logs/host`, so the probe finds them at its defaults (`URUTAU_EGRESS=auto` turns on by itself once the file exists). For the second firewall add the mount and the variables to the compose file, start with `observe` and move to `on` when the decisions look right:
|
||||
|
||||
+1
-1
@@ -81,7 +81,7 @@ A side rail (a tab bar on phones, with a "More" menu that scrolls when it is tal
|
||||
<p align="center"><img src="img/incidents-dark.png" width="900" alt="Page: Incidents"><br><sub>Incidents: tickets for outbound-traffic findings.</sub></p>
|
||||
<p align="center"><img src="img/incident-detail-dark.png" width="900" alt="Page: Incident ticket"><br><sub>Incident ticket: summary, activity timeline and properties.</sub></p>
|
||||
|
||||
**Outbound traffic** (`#/egress`, needs `URUTAU_EGRESS` and the host kit in `deploy/host` on a probe): the new outbound connections of the host and containers, logged by nftables, analysed for beaconing (regular conversations with one destination, with the interval histogram), mining, IRC and SMTP ports, contact with addresses that attacked the server or Tor relays, DNS outside the allowed resolvers, unauthorised outbound scans and new countries. It shows a plain-language verdict, evidence cards, a destination map, activity by hour, compact workloads (by network or container name, `URUTAU_EGRESS_WORKLOADS`; a `scanner` workload has only its scan-shaped traffic summarised) and the timeline of authorised scans. Servers themselves, probes and the host's own provider never raise findings; regular connections to large CDNs and clouds are low severity.
|
||||
**Outbound traffic** (`#/egress`, needs `URUTAU_EGRESS` and the host kit in `deploy/host` on a probe): the new outbound connections of the host and containers, logged by nftables, analysed for beaconing (regular conversations with one destination, with the interval histogram), mining, IRC and SMTP ports, contact with addresses that attacked the server or Tor relays, DNS outside the allowed resolvers, unauthorised outbound scans and new countries. It shows a plain-language verdict, evidence cards, a destination map, activity by hour, compact workloads (by network or container name, `URUTAU_EGRESS_WORKLOADS`; a `scanner` workload has only its scan-shaped traffic summarised) and the timeline of authorised scans. Servers themselves, probes and the host's own provider never raise findings; regular connections to large CDNs and clouds are low severity, and they never raise a new country (anycast).
|
||||
|
||||
<p align="center"><img src="img/egress-dark.png" width="900" alt="Page: Outbound traffic"><br><sub>Outbound traffic: scan bursts, beacons and mining from containers.</sub></p>
|
||||
|
||||
|
||||
@@ -96,7 +96,7 @@ A sonda usa só estas variáveis (flags em [cli.md](cli.md#urutau-probe)). Um ca
|
||||
| `URUTAU_FAIL2BAN_LOG` | `/logs/host/fail2ban.log` | log do fail2ban |
|
||||
| `URUTAU_PROBE_LOG` | `/logs/host/probe.log` | log do kernel de conexões a portas que ninguém serve, gravado pelo kit do host (veja [Sondagens](#sondagens-varreduras-de-portas)) |
|
||||
| `URUTAU_EGRESS_LOG` | `/logs/host/egress.log` | log do kernel de conexões novas de saída, gravado pelo kit do host |
|
||||
| `URUTAU_EGRESS_CONTAINERS` | `/logs/host/containers.map` | mapa `"<ip> <container>"` gravado pelo kit do host a cada minuto, para que as cargas mantenham o nome quando o endereço muda num redeploy; enviado inteiro quando muda |
|
||||
| `URUTAU_EGRESS_CONTAINERS` | `/logs/host/containers.map` | mapa `"<ip> <container>"` gravado pelo kit do host quando um contêiner sobe (e a cada minuto), para que as cargas mantenham o nome quando o endereço muda num redeploy; enviado inteiro quando muda |
|
||||
| `URUTAU_RESOLV` | `/etc/resolv.conf` do host (montado) | resolvedores do host, enviados inteiros quando mudam |
|
||||
| `URUTAU_ENFORCE_LOG` | `/logs/enforce/decisions.log` | arquivo onde as decisões de ban do hub são acrescentadas, lido pela jail do host; vazio ignora comandos de ban e os conta como erro |
|
||||
| `URUTAU_ENFORCE_UNBAN_LOG` | `/logs/enforce/unban.log` | arquivo onde os pedidos de desban são acrescentados, lido pelo host; vazio os ignora |
|
||||
|
||||
@@ -179,7 +179,7 @@ sudo sh deploy/host/install.sh --remove # desfaz tudo (os logs são mantidos)
|
||||
|---|---|
|
||||
| registro de egress | tabela nftables `inet urutau_egress` (`/etc/urutau/egress.nft`, só registra, nunca descarta, separada das tabelas do Docker e do fail2ban) e a unit `urutau-egress.service`; a regra rsyslog `41-urutau-egress.conf` manda as linhas do kernel para `/var/log/urutau/egress.log` (`URUTAU-EGRESS:`) e `/var/log/urutau/probe.log` (`URUTAU-PROBE:`); logrotate diário, 7 cópias, no máximo 200 MB (`urutau-logrotate.timer`) |
|
||||
| sondagens | a regra `URUTAU-PROBE:` registra conexões novas de entrada pela interface externa a portas em que nenhum socket escuta (no máximo 10 por segundo por origem); o conjunto de portas abertas é atualizado a cada minuto a partir do `ss`, incluindo as portas que o Docker publica |
|
||||
| mapa de containers | `urutau-containers-map` e seu timer (a cada minuto) gravam `/var/log/urutau/containers.map` (`<ip> <container>`) e `/var/log/urutau/resolv.conf` (os resolvedores reais de upstream) |
|
||||
| mapa de containers | `urutau-containers-map`, executado pelo timer (a cada minuto) e pelo `urutau-containers-watch` (a cada contêiner que sobe ou entra numa rede, para que um redeploy que troca endereços seja nomeado certo em segundos), grava `/var/log/urutau/containers.map` (`<ip> <container>`) e `/var/log/urutau/resolv.conf` (os resolvedores reais de upstream) |
|
||||
| segundo firewall (`--enforce`) | diretório `/var/log/urutau-enforce` (dono `URUTAU_UID`, grupo `adm`) com `decisions.log` e `unban.log`; filtro `urutau`, ação `urutau-allports` e jail `urutau` do fail2ban (backend `polling`, `maxretry = 1`, `bantime = 1h`, ações em `INPUT` e `DOCKER-USER`, `ignoreip` do host mantido); `urutau-unban.path` e `urutau-unban` aplicam o botão Desbanir |
|
||||
|
||||
A ação `urutau-allports` funciona como `iptables-allports`, mas só descarta conexões que o endereço banido inicia (direção original do conntrack), então as respostas a conexões que o host abriu continuam fluindo. Os arquivos de egress e sondagem caem em `/var/log/urutau`, que o compose já monta em `/logs/host`, então a sonda os encontra nos padrões (`URUTAU_EGRESS=auto` liga sozinho assim que o arquivo existe). Para o segundo firewall, acrescente a montagem e as variáveis ao compose, comece com `observe` e passe para `on` quando as decisões parecerem certas:
|
||||
|
||||
@@ -81,7 +81,7 @@ Uma barra lateral (barra de abas no celular, com um menu "Mais" que rola quando
|
||||
<p align="center"><img src="../img/incidents-dark-pt.png" width="900" alt="Página: Incidentes"><br><sub>Incidentes: chamados para achados do tráfego de saída.</sub></p>
|
||||
<p align="center"><img src="../img/incident-detail-dark-pt.png" width="900" alt="Página: Chamado de incidente"><br><sub>Chamado de incidente: resumo, linha do tempo de atividade e propriedades.</sub></p>
|
||||
|
||||
**Tráfego de saída** (`#/egress`, exige `URUTAU_EGRESS` e o kit de host em `deploy/host` numa sonda): as novas conexões de saída do host e dos contêineres, registradas pelo nftables, analisadas quanto a beaconing (conversas regulares com um destino, com o histograma de intervalos), mineração, portas de IRC e SMTP, contato com endereços que atacaram o servidor ou relays Tor, DNS fora dos resolvers permitidos, varreduras de saída não autorizadas e países novos. Mostra um veredito em linguagem simples, cartões de evidência, mapa de destinos, atividade por hora, workloads compactos (por nome de rede ou contêiner, `URUTAU_EGRESS_WORKLOADS`; um workload `scanner` tem só o tráfego em forma de varredura resumido) e a linha do tempo das varreduras autorizadas. Os próprios servidores, sondas e o provedor do host nunca geram achados; conexões regulares a grandes CDNs e nuvens têm severidade baixa.
|
||||
**Tráfego de saída** (`#/egress`, exige `URUTAU_EGRESS` e o kit de host em `deploy/host` numa sonda): as novas conexões de saída do host e dos contêineres, registradas pelo nftables, analisadas quanto a beaconing (conversas regulares com um destino, com o histograma de intervalos), mineração, portas de IRC e SMTP, contato com endereços que atacaram o servidor ou relays Tor, DNS fora dos resolvers permitidos, varreduras de saída não autorizadas e países novos. Mostra um veredito em linguagem simples, cartões de evidência, mapa de destinos, atividade por hora, workloads compactos (por nome de rede ou contêiner, `URUTAU_EGRESS_WORKLOADS`; um workload `scanner` tem só o tráfego em forma de varredura resumido) e a linha do tempo das varreduras autorizadas. Os próprios servidores, sondas e o provedor do host nunca geram achados; conexões regulares a grandes CDNs e nuvens têm severidade baixa e nunca geram país novo (anycast).
|
||||
|
||||
<p align="center"><img src="../img/egress-dark-pt.png" width="900" alt="Página: Tráfego de saída"><br><sub>Tráfego de saída: rajadas de varredura, beacons e mineração em contêineres.</sub></p>
|
||||
|
||||
|
||||
@@ -124,6 +124,7 @@ func (sh *shared) newNode(name string, primary bool, rec hub.Probe) (*Node, erro
|
||||
sh.wg.Add(1)
|
||||
go func() { defer sh.wg.Done(); n.Enf.Run(sh.ctx) }()
|
||||
}
|
||||
n.loadProbeFiles()
|
||||
if !egressOff(c) {
|
||||
if err := n.buildEgress(rec.Egress); err != nil {
|
||||
return nil, err
|
||||
@@ -189,6 +190,41 @@ func (n *Node) Close() {
|
||||
}
|
||||
}
|
||||
|
||||
// probeFilePath is where the last copy of a file sent by the probe is kept,
|
||||
// so that after a hub restart the egress lines replayed by the probe are
|
||||
// judged with its resolvers and container names before it sends them again.
|
||||
func (n *Node) probeFilePath(name string) string {
|
||||
return filepath.Join(n.Dir, "probe-"+name)
|
||||
}
|
||||
|
||||
func (n *Node) loadProbeFiles() {
|
||||
for _, f := range []struct {
|
||||
name string
|
||||
dst *atomic.Pointer[[]byte]
|
||||
}{{wire.FileContainers, &n.containers}, {wire.FileResolv, &n.resolv}} {
|
||||
b, err := os.ReadFile(n.probeFilePath(f.name))
|
||||
if err != nil || len(b) > wire.MaxFileBytes {
|
||||
continue
|
||||
}
|
||||
f.dst.Store(&b)
|
||||
}
|
||||
}
|
||||
|
||||
func (n *Node) saveProbeFile(name string, data []byte) {
|
||||
p := n.probeFilePath(name)
|
||||
if old, err := os.ReadFile(p); err == nil && string(old) == string(data) {
|
||||
return
|
||||
}
|
||||
tmp := p + ".tmp"
|
||||
if err := os.WriteFile(tmp, data, 0o600); err != nil {
|
||||
n.sh.log.Warn("probe file not saved", "node", n.name, "file", name, "err", err)
|
||||
return
|
||||
}
|
||||
if err := os.Rename(tmp, p); err != nil {
|
||||
n.sh.log.Warn("probe file not saved", "node", n.name, "file", name, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (n *Node) buildEgress(eg hub.Egress) error {
|
||||
eng, err := newEgressEngine(n.sh.c, n.St, eg, n.Primary)
|
||||
if err != nil {
|
||||
@@ -263,6 +299,7 @@ func (n *Node) Apply(b wire.Batch) (int, int) {
|
||||
default:
|
||||
continue
|
||||
}
|
||||
n.saveProbeFile(f.Name, data)
|
||||
if e := n.egr.Load(); e != nil {
|
||||
if f.Name == wire.FileContainers {
|
||||
e.SetContainers(data)
|
||||
|
||||
@@ -82,3 +82,20 @@ func TestProbeSourceMissingIsWaiting(t *testing.T) {
|
||||
}
|
||||
_ = time.Now
|
||||
}
|
||||
|
||||
func TestSameHeadCopytruncate(t *testing.T) {
|
||||
old := store.Offset{Inode: 7, Offset: 900, FP: 111, FPLen: 64}
|
||||
if !sameHead(old, store.Offset{Inode: 7, Offset: 500, FP: 111, FPLen: 64}) {
|
||||
t.Fatal("same generation must be a duplicate")
|
||||
}
|
||||
if sameHead(old, store.Offset{Inode: 7, Offset: 500, FP: 222, FPLen: 64}) {
|
||||
t.Fatal("truncated and regrown file must not be a duplicate")
|
||||
}
|
||||
// production 2026-11-16: the saved head had 64 bytes, the new probe sends longer ones
|
||||
if sameHead(old, store.Offset{Inode: 7, Offset: 500, FP: 333, FPLen: 1024}) {
|
||||
t.Fatal("fingerprints of different lengths must not be taken for the same file")
|
||||
}
|
||||
if !sameHead(store.Offset{Inode: 7, Offset: 900}, store.Offset{Inode: 7, Offset: 500, FP: 1, FPLen: 64}) {
|
||||
t.Fatal("without a saved fingerprint the offset decides")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"io"
|
||||
"log/slog"
|
||||
"testing"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
|
||||
)
|
||||
|
||||
// The files sent by a probe survive a hub restart: without them the egress
|
||||
// lines the probe replays right after reconnecting were judged with the hub's
|
||||
// own resolvers (a dns_bypass false positive on the probe's upstream resolver).
|
||||
func TestProbeFilesSurviveRestart(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
sh := &shared{log: slog.New(slog.NewTextHandler(io.Discard, nil))}
|
||||
n := &Node{name: "hostinger", Dir: dir, sh: sh}
|
||||
n.saveProbeFile(wire.FileResolv, []byte("nameserver 153.92.2.6\n"))
|
||||
n.saveProbeFile(wire.FileContainers, []byte("172.17.0.2 coolify-sentinel\n"))
|
||||
|
||||
n2 := &Node{name: "hostinger", Dir: dir, sh: sh}
|
||||
n2.loadProbeFiles()
|
||||
if b := n2.resolv.Load(); b == nil || string(*b) != "nameserver 153.92.2.6\n" {
|
||||
t.Fatalf("resolv.conf not restored: %v", b)
|
||||
}
|
||||
if b := n2.containers.Load(); b == nil || string(*b) != "172.17.0.2 coolify-sentinel\n" {
|
||||
t.Fatalf("containers.map not restored: %v", b)
|
||||
}
|
||||
}
|
||||
+16
-1
@@ -225,7 +225,7 @@ func (r *Runner) Feed(src string, text []byte, end store.Offset) bool {
|
||||
|
||||
func (r *Runner) feedLocked(src string, text []byte, end store.Offset) bool {
|
||||
name := runnerSource(src)
|
||||
if saved, ok := r.remote[name]; ok && end.Inode == saved.Inode && end.Offset <= saved.Offset {
|
||||
if saved, ok := r.remote[name]; ok && end.Inode == saved.Inode && end.Offset <= saved.Offset && sameHead(saved, end) {
|
||||
return false
|
||||
}
|
||||
if src == wire.SrcEgress {
|
||||
@@ -243,6 +243,21 @@ func (r *Runner) feedLocked(src string, text []byte, end store.Offset) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// sameHead reports whether two positions of one inode belong to the same file
|
||||
// generation. A copytruncate rotation (Traefik's log) keeps the inode and
|
||||
// restarts the offsets at 0: without comparing the head fingerprint every new
|
||||
// line below the old high-water mark would be taken for a duplicate and lost
|
||||
// until the file regrew past it. Fingerprints of different lengths cannot be
|
||||
// compared: they count as different generations (at worst a replay across a
|
||||
// generation start is counted twice, never a whole generation lost). Without a
|
||||
// fingerprint on either side (old state) the offset alone decides.
|
||||
func sameHead(a, b store.Offset) bool {
|
||||
if a.FPLen == 0 || b.FPLen == 0 {
|
||||
return true
|
||||
}
|
||||
return a.FPLen == b.FPLen && a.FP == b.FP
|
||||
}
|
||||
|
||||
// ApplyBatch applies the lines of a batch under the commit mutex.
|
||||
func (r *Runner) ApplyBatch(lines []wire.Line) (accepted, dup int) {
|
||||
r.mu.Lock()
|
||||
|
||||
@@ -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 = "2.1.1"
|
||||
var Version = "2.2.2"
|
||||
@@ -681,3 +681,45 @@ func TestBeaconMetadataAndKnownCDN(t *testing.T) {
|
||||
t.Fatalf("surbl: %+v", f)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEngineDst(t *testing.T) {
|
||||
e := newEng(t, Config{Workloads: "ciberlab=10.0.5.0/24:scanner"})
|
||||
for i := 0; i < 70; i++ { // more destinations than the top-50
|
||||
e.IngestEvent(mk(t0.Add(time.Duration(i)*time.Second), "10.0.3.5", fmt.Sprintf("198.18.0.%d", i+1), "tcp", 80))
|
||||
}
|
||||
e.IngestEvent(mk(t0.Add(time.Hour), "10.0.3.5", "198.18.0.70", "tcp", 443))
|
||||
from, to := t0.Unix()-60, t0.Unix()+7200
|
||||
d, _, ok := e.Dst(from, to, ip("198.18.0.70"))
|
||||
if !ok || d.Conns != 2 || d.IP != "198.18.0.70" || len(d.Workloads) != 1 || len(d.Ports) != 2 || d.Ports[0] != 80 {
|
||||
t.Fatalf("dst: %+v ok=%v", d, ok)
|
||||
}
|
||||
if _, _, ok := e.Dst(from, to, ip("203.0.113.9")); ok {
|
||||
t.Fatal("unknown dst found")
|
||||
}
|
||||
if _, _, ok := e.Dst(from-10*86400, from-9*86400, ip("198.18.0.70")); ok {
|
||||
t.Fatal("dst found outside the window")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewGeoSkipsAnycastCDN(t *testing.T) {
|
||||
geo := func(s string) (string, string, string) {
|
||||
switch s {
|
||||
case "1.1.1.1":
|
||||
return "AU", "AS13335", "Cloudflare"
|
||||
case "149.154.166.110":
|
||||
return "NL", "", ""
|
||||
case "203.0.113.50":
|
||||
return "DE", "AS197540", "netcup"
|
||||
}
|
||||
return "BR", "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.Add(25*time.Hour), "10.0.3.5", "1.1.1.1", "udp", 53)) // Cloudflare anycast
|
||||
e.IngestEvent(mk(t0.Add(25*time.Hour), "10.0.3.5", "149.154.166.110", "tcp", 443)) // Telegram prefix, no ASN
|
||||
e.IngestEvent(mk(t0.Add(26*time.Hour), "10.0.3.5", "203.0.113.50", "tcp", 443))
|
||||
g := kinds(rep(e), "new_geo")
|
||||
if len(g) != 1 || g[0].Dst != "203.0.113.50" {
|
||||
t.Fatalf("new_geo: %+v", g)
|
||||
}
|
||||
}
|
||||
@@ -752,7 +752,9 @@ func (e *Engine) checks(ws *wstate, ev Event, dport uint16, t int64, ds *dstStat
|
||||
if ws.role != RoleScanner && !fan && ds.cc != "" && isGlobal(ev.Dst) {
|
||||
if _, seen := ws.geo[ds.cc]; !seen {
|
||||
ws.geo[ds.cc] = struct{}{}
|
||||
if t-ws.first >= int64(e.cfg.Learn/time.Second) {
|
||||
// Anycast CDNs and big clouds: the database country of 1.1.1.1 or a
|
||||
// Cloudflare edge says nothing about where the traffic goes.
|
||||
if t-ws.first >= int64(e.cfg.Learn/time.Second) && !commonCloudASNs[ds.asn] && !inCommonCDN(ev.Dst) {
|
||||
e.addFinding("new_geo", "low", ws.name, dst, dport, ev.Proto, t, 0, 0, "first contact with country "+ds.cc+" "+ds.asn, 1)
|
||||
}
|
||||
} else if len(ws.geo) > 300 {
|
||||
|
||||
@@ -454,3 +454,46 @@ func EmptyReport() Report {
|
||||
return Report{Workloads: []WorkloadOut{}, TopDst: []DstOut{}, Findings: []Finding{}, ByCountry: []CountryOut{}, Scanner: ScannerOut{Bursts: []BurstOut{}},
|
||||
Timeline: Timeline{Step: 3600, Series: map[string][]uint32{}}}
|
||||
}
|
||||
|
||||
// Dst looks one destination up in the dst table (not limited to the top 50):
|
||||
// its connections in [from, to] and the findings that target it. ok is false
|
||||
// when the window holds neither.
|
||||
func (e *Engine) Dst(from, to int64, ip netip.Addr) (DstOut, []Finding, bool) {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
if to <= from {
|
||||
to = from + 1
|
||||
}
|
||||
fs := []Finding{}
|
||||
for _, f := range e.findings {
|
||||
if f.Last >= from && f.First <= to && f.Dst == ip.String() {
|
||||
c := *f
|
||||
c.Samples = append([]int64(nil), f.Samples...)
|
||||
fs = append(fs, c)
|
||||
}
|
||||
}
|
||||
sort.Slice(fs, func(i, j int) bool {
|
||||
if fs[i].Last != fs[j].Last {
|
||||
return fs[i].Last > fs[j].Last
|
||||
}
|
||||
return fs[i].ID < fs[j].ID
|
||||
})
|
||||
out := DstOut{IP: ip.String(), Workloads: []string{}, Ports: []uint16{}}
|
||||
if el, ok := e.dsts.m[ip]; ok { // read-only: no LRU promotion
|
||||
ds := el.Value.(*lent[netip.Addr, *dstStat]).v
|
||||
d0, d1 := int32(from/86400), int32(to/86400)
|
||||
for _, d := range ds.days {
|
||||
if d.day >= d0 && d.day <= d1 {
|
||||
out.Conns += uint64(d.n)
|
||||
}
|
||||
}
|
||||
out.CC, out.ASN, out.Org = ds.cc, ds.asn, ds.og
|
||||
out.Workloads = append(out.Workloads, ds.wls...)
|
||||
out.Ports = append(out.Ports, ds.ports...)
|
||||
sort.Slice(out.Ports, func(a, b int) bool { return out.Ports[a] < out.Ports[b] })
|
||||
}
|
||||
if out.Conns == 0 && len(fs) == 0 {
|
||||
return DstOut{}, nil, false
|
||||
}
|
||||
return out, fs, true
|
||||
}
|
||||
+17
-1
@@ -867,7 +867,7 @@ func (f *Filter) Match(r *Rec) bool {
|
||||
if r.T < f.From || (f.To != 0 && r.T > f.To) {
|
||||
return false
|
||||
}
|
||||
if f.Host != "" && r.Host != f.Host {
|
||||
if f.Host != "" && !hostMatch(f.Host, r.Host) {
|
||||
return false
|
||||
}
|
||||
if len(f.Cats) > 0 && !f.Cats[r.Cat] {
|
||||
@@ -1164,3 +1164,19 @@ func (l *Log) Counts(from, to int64) map[int64]int64 {
|
||||
|
||||
// StartCursor is a cursor that begins an ascending read at time t.
|
||||
func StartCursor(t int64) string { return encodeCursor(t, 0) }
|
||||
|
||||
// hostMatch reports whether host is the filter or one of its comma list.
|
||||
func hostMatch(filter, host string) bool {
|
||||
if filter == host {
|
||||
return true
|
||||
}
|
||||
if !strings.Contains(filter, ",") {
|
||||
return false
|
||||
}
|
||||
for _, n := range strings.Split(filter, ",") {
|
||||
if strings.TrimSpace(n) == host {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
+18
-1
@@ -7,6 +7,7 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -67,6 +68,22 @@ func NewHub(provider func() []Backend) *Hub {
|
||||
subs: map[chan store.LiveEvent]struct{}{}, vsubs: map[chan store.VisitMsg]struct{}{}, attach: map[string]func(){}}
|
||||
}
|
||||
|
||||
// onlyHas reports whether name is in only: one node name or a comma list.
|
||||
func onlyHas(only, name string) bool {
|
||||
if only == name {
|
||||
return true
|
||||
}
|
||||
if !strings.Contains(only, ",") {
|
||||
return false
|
||||
}
|
||||
for _, n := range strings.Split(only, ",") {
|
||||
if strings.TrimSpace(n) == name {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (h *Hub) backends(only string) []Backend {
|
||||
if h == nil || h.Provider == nil {
|
||||
return nil
|
||||
@@ -74,7 +91,7 @@ func (h *Hub) backends(only string) []Backend {
|
||||
all := h.Provider()
|
||||
out := make([]Backend, 0, len(all))
|
||||
for _, b := range all {
|
||||
if only == "" || only == b.Name() {
|
||||
if only == "" || onlyHas(only, b.Name()) {
|
||||
out = append(out, b)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ import (
|
||||
const (
|
||||
chanSize = 4096
|
||||
batchBytes = 128 << 10 // well under the hub limit; keeps the probe heap small
|
||||
filePollEach = 10 * time.Second
|
||||
filePollEach = 2 * time.Second
|
||||
)
|
||||
|
||||
// item is what the followers and the file watcher hand to the collector.
|
||||
|
||||
@@ -32,17 +32,16 @@ func (s *Server) analytics(kind string) http.HandlerFunc {
|
||||
return
|
||||
}
|
||||
host := q.Get("host")
|
||||
if len(host) > 64 {
|
||||
if !hostListOK(host) {
|
||||
badRequest(w, "invalid host")
|
||||
return
|
||||
}
|
||||
if host == "all" {
|
||||
host = ""
|
||||
}
|
||||
if host != "" && host != s.opt.Store.Name() && (s.opt.Hub == nil || !s.opt.Hub.Has(host)) {
|
||||
sel, ok := s.parseHosts(host)
|
||||
if !ok {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "unknown host"})
|
||||
return
|
||||
}
|
||||
host = sel.csv(s.opt.Store.Name())
|
||||
dim := q.Get("dim")
|
||||
if kind == "concentration" {
|
||||
if dim == "" {
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"sort"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/incidents"
|
||||
)
|
||||
|
||||
func init() {
|
||||
registerUserRoute("GET /api/v1/ip/{ip}/egress", func(s *Server) http.HandlerFunc { return s.ipEgressAPI })
|
||||
}
|
||||
|
||||
type ipEgressHost struct {
|
||||
Host string `json:"host"`
|
||||
Conns uint64 `json:"conns"`
|
||||
CC string `json:"cc"`
|
||||
ASN string `json:"asn"`
|
||||
Org string `json:"org"`
|
||||
Workloads []string `json:"workloads"`
|
||||
Ports []uint16 `json:"ports"`
|
||||
}
|
||||
|
||||
type ipEgressInc struct {
|
||||
ID string `json:"id"`
|
||||
Host string `json:"host"`
|
||||
Title string `json:"title"`
|
||||
Status string `json:"status"`
|
||||
Severity string `json:"severity"`
|
||||
Kind string `json:"kind"`
|
||||
Workload string `json:"workload"`
|
||||
Last int64 `json:"last_seen"`
|
||||
}
|
||||
|
||||
// ipEgressAPI: GET /api/v1/ip/{ip}/egress. What the node(s) did towards this
|
||||
// address (egress connections, findings, incidents) and when it was last seen
|
||||
// as an inbound source.
|
||||
func (s *Server) ipEgressAPI(w http.ResponseWriter, r *http.Request) {
|
||||
ip, err := netip.ParseAddr(r.PathValue("ip"))
|
||||
if err != nil || ip.Zone() != "" {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid ip"})
|
||||
return
|
||||
}
|
||||
ip = ip.Unmap()
|
||||
rg, ok := s.rangeOf(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
host := r.URL.Query().Get("host")
|
||||
if len(host) > 253 {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "bad host"})
|
||||
return
|
||||
}
|
||||
local, peers, only, ok := s.studyHosts(w, host)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
from, to := rg.Bounds(s.opt.Store.Now().Unix())
|
||||
self := s.opt.Store.Name()
|
||||
out := struct {
|
||||
IP string `json:"ip"`
|
||||
Egress []ipEgressHost `json:"egress"`
|
||||
Findings []egress.Finding `json:"findings"`
|
||||
Incidents []ipEgressInc `json:"incidents"`
|
||||
LastSeenInbound int64 `json:"last_seen_inbound"`
|
||||
}{IP: ip.String(), Egress: []ipEgressHost{}, Findings: []egress.Finding{}, Incidents: []ipEgressInc{}}
|
||||
|
||||
add := func(h string, d egress.DstOut, fs []egress.Finding) {
|
||||
if d.Conns > 0 || len(d.Workloads) > 0 {
|
||||
out.Egress = append(out.Egress, ipEgressHost{Host: h, Conns: d.Conns, CC: d.CC, ASN: d.ASN, Org: d.Org,
|
||||
Workloads: append([]string{}, d.Workloads...), Ports: append([]uint16{}, d.Ports...)})
|
||||
}
|
||||
for _, f := range fs {
|
||||
f.Host = h
|
||||
out.Findings = append(out.Findings, f)
|
||||
}
|
||||
}
|
||||
if eng := egressEngine.Load(); local && eng != nil {
|
||||
if d, fs, ok := eng.Dst(from, to, ip); ok {
|
||||
add(self, d, fs)
|
||||
}
|
||||
}
|
||||
if peers && s.opt.Hub != nil {
|
||||
raws := s.opt.Hub.EgressFor(r.Context(), from, to, only)
|
||||
names := make([]string, 0, len(raws))
|
||||
for n := range raws {
|
||||
names = append(names, n)
|
||||
}
|
||||
sort.Strings(names)
|
||||
for _, n := range names {
|
||||
var pr egress.Report
|
||||
if json.Unmarshal(raws[n], &pr) != nil {
|
||||
continue
|
||||
}
|
||||
pr.Sanitize(n)
|
||||
var fs []egress.Finding
|
||||
for _, f := range pr.Findings {
|
||||
if f.Dst == ip.String() {
|
||||
fs = append(fs, f)
|
||||
}
|
||||
}
|
||||
var d egress.DstOut
|
||||
for _, x := range pr.TopDst { // peers only report their top destinations
|
||||
if x.IP == ip.String() {
|
||||
d = x
|
||||
}
|
||||
}
|
||||
add(n, d, fs)
|
||||
}
|
||||
}
|
||||
sort.Slice(out.Findings, func(i, j int) bool { return out.Findings[i].Last > out.Findings[j].Last })
|
||||
if len(out.Findings) > 200 {
|
||||
out.Findings = out.Findings[:200]
|
||||
}
|
||||
|
||||
for _, h := range s.incHosts() {
|
||||
if (host != "" && host != "all" && host != h) || len(out.Incidents) >= 100 {
|
||||
continue
|
||||
}
|
||||
st := s.incStore(h)
|
||||
if st == nil {
|
||||
continue
|
||||
}
|
||||
for _, t := range st.All(incidents.Query{Q: ip.String()}) {
|
||||
if t.Dst != ip.String() {
|
||||
continue
|
||||
}
|
||||
out.Incidents = append(out.Incidents, ipEgressInc{ID: h + "/" + t.ID, Host: h, Title: t.Title, Status: t.Status,
|
||||
Severity: t.Severity, Kind: t.Kind, Workload: t.Workload, Last: t.LastSeen})
|
||||
}
|
||||
}
|
||||
sort.Slice(out.Incidents, func(i, j int) bool { return out.Incidents[i].Last > out.Incidents[j].Last })
|
||||
|
||||
key := ip.String()
|
||||
if d, ok := s.opt.Store.IP(key); ok {
|
||||
out.LastSeenInbound = d.Last
|
||||
}
|
||||
if s.opt.Hub != nil {
|
||||
for _, d := range s.opt.Hub.IPDetail(key) {
|
||||
if d.Last > out.LastSeenInbound {
|
||||
out.LastSeenInbound = d.Last
|
||||
}
|
||||
}
|
||||
}
|
||||
writeJSON(w, 200, out)
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/incidents"
|
||||
"net/netip"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -68,3 +70,42 @@ func TestEgressAPI(t *testing.T) {
|
||||
t.Fatalf("peer token must not open the user route")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIPEgressAPI(t *testing.T) {
|
||||
st := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour})
|
||||
inc, err := incidents.Open(filepath.Join(t.TempDir(), "incidents.json"), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h := New(Options{Token: userTok, Version: "t", Store: st, Incidents: inc})
|
||||
auth := map[string]string{"Authorization": "Bearer " + userTok}
|
||||
e, err := egress.New(egress.Config{Workloads: "ciberlab=10.0.5.0/24:scanner"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
SetEgress(e)
|
||||
defer SetEgress(nil)
|
||||
now := time.Now()
|
||||
e.IngestEvent(egress.Event{Time: now.Add(-time.Hour), Src: netip.MustParseAddr("10.0.5.2"), Dst: netip.MustParseAddr("203.0.113.7"), Proto: "tcp", DPort: 6667, In: "br-1"})
|
||||
inc.Sync([]incidents.Finding{{Host: "oracle", Kind: "beacon", Severity: "high", Workload: "ciberlab", Dst: "203.0.113.7", Proto: "tcp", DPort: 6667, First: now.Add(-time.Hour).Unix(), Last: now.Unix(), Count: 9}})
|
||||
|
||||
d := getJSON(t, h, "/api/v1/ip/203.0.113.7/egress?range=24h", auth)
|
||||
eg := d["egress"].([]any)
|
||||
if len(eg) != 1 || eg[0].(map[string]any)["host"] != "oracle" || eg[0].(map[string]any)["conns"].(float64) != 1 {
|
||||
t.Fatalf("egress: %v", d)
|
||||
}
|
||||
ics := d["incidents"].([]any)
|
||||
if len(ics) != 1 || ics[0].(map[string]any)["id"] != "oracle/INC-1" {
|
||||
t.Fatalf("incidents: %v", d["incidents"])
|
||||
}
|
||||
if d["last_seen_inbound"].(float64) != 0 {
|
||||
t.Fatalf("inbound: %v", d)
|
||||
}
|
||||
d = getJSON(t, h, "/api/v1/ip/203.0.113.99/egress?range=24h", auth)
|
||||
if len(d["egress"].([]any)) != 0 || len(d["incidents"].([]any)) != 0 || len(d["findings"].([]any)) != 0 {
|
||||
t.Fatalf("empty: %v", d)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/ip/nope/egress", cloneHdr(auth), nil); w.Code != 400 {
|
||||
t.Fatalf("bad ip: %d", w.Code)
|
||||
}
|
||||
}
|
||||
@@ -290,13 +290,10 @@ func (s *Server) incidentList(w http.ResponseWriter, r *http.Request) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
hosts := s.incHosts()
|
||||
if q.Host != "" && q.Host != "all" {
|
||||
hosts = []string{q.Host}
|
||||
if s.incStore(q.Host) == nil {
|
||||
writeJSON(w, 200, qPage{Items: []qSummary{}, Counts: map[string]int{}, Hosts: s.incHosts()})
|
||||
return
|
||||
}
|
||||
hosts := s.incSelect(q.Host)
|
||||
if hosts == nil {
|
||||
writeJSON(w, 200, qPage{Items: []qSummary{}, Counts: map[string]int{}, Hosts: s.incHosts()})
|
||||
return
|
||||
}
|
||||
q.Host = ""
|
||||
if len(hosts) == 1 {
|
||||
@@ -480,10 +477,7 @@ func (s *Server) incidentCSV(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Disposition", `attachment; filename="incidents.csv"`)
|
||||
cw := csv.NewWriter(w)
|
||||
cw.Write([]string{"id", "status", "severity", "host", "kind", "workload", "dst", "dport", "proto", "title", "first_seen", "last_seen", "count", "assignee", "tags", "verdict", "suppress", "created_at", "updated_at"})
|
||||
hosts := s.incHosts()
|
||||
if q.Host != "" && q.Host != "all" {
|
||||
hosts = []string{q.Host}
|
||||
}
|
||||
hosts := s.incSelect(q.Host)
|
||||
q.Host = ""
|
||||
var rows []qSummary
|
||||
for _, h := range hosts {
|
||||
@@ -504,3 +498,26 @@ func (s *Server) incidentCSV(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
cw.Flush()
|
||||
}
|
||||
|
||||
// incSelect resolves the host filter of the ticket queries: "" or "all" is
|
||||
// every host with a store, otherwise the listed ones (comma list) that have
|
||||
// one. It returns nil when a selection names none.
|
||||
func (s *Server) incSelect(raw string) []string {
|
||||
if raw == "" || raw == "all" {
|
||||
return s.incHosts()
|
||||
}
|
||||
var out []string
|
||||
seen := map[string]bool{}
|
||||
for _, n := range strings.Split(raw, ",") {
|
||||
n = strings.TrimSpace(n)
|
||||
if n == "all" {
|
||||
return s.incHosts()
|
||||
}
|
||||
if n == "" || seen[n] || s.incStore(n) == nil {
|
||||
continue
|
||||
}
|
||||
seen[n] = true
|
||||
out = append(out, n)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -96,16 +96,12 @@ func figuresOf(t store.Totals, tr store.TrafficData) reportFigures {
|
||||
// trafficOf is what /api/v1/traffic answers for all domains, merged with the peers.
|
||||
func (s *Server) trafficOf(r *http.Request, rg store.Range, host string) store.TrafficData {
|
||||
var parts []store.TrafficData
|
||||
self := s.opt.Store.Name()
|
||||
if host == "all" || host == self {
|
||||
sel, _ := s.parseHosts(host)
|
||||
if sel.local {
|
||||
parts = append(parts, s.opt.Store.TrafficFor(rg, "all"))
|
||||
}
|
||||
if s.opt.Hub != nil && host != self {
|
||||
only := ""
|
||||
if host != "all" {
|
||||
only = host
|
||||
}
|
||||
parts = append(parts, s.opt.Hub.TrafficFor(r.Context(), rg, "all", only)...)
|
||||
if s.opt.Hub != nil && (sel.all || len(sel.peers) > 0) {
|
||||
parts = append(parts, s.opt.Hub.TrafficFor(r.Context(), rg, "all", sel.only())...)
|
||||
}
|
||||
return store.MergeTraffic(host, parts)
|
||||
}
|
||||
|
||||
@@ -118,7 +118,7 @@ func (s *Server) geoAPI(w http.ResponseWriter, r *http.Request) {
|
||||
if host == "" {
|
||||
host = "all"
|
||||
}
|
||||
if host != "all" && host != s.opt.Store.Name() && (s.opt.Hub == nil || !s.opt.Hub.Has(host)) {
|
||||
if _, ok := s.parseHosts(host); !ok {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "unknown host"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// maxHostSel bounds how many names one host selection may carry.
|
||||
const maxHostSel = 16
|
||||
|
||||
// hostSel is a resolved host selection of a request: "all" (or empty), one
|
||||
// host, or a comma list such as host=oracle,hostinger.
|
||||
type hostSel struct {
|
||||
all bool // every host: no filtering
|
||||
local bool // this node is part of the selection
|
||||
peers []string // the other nodes of the selection (sorted), empty with all
|
||||
}
|
||||
|
||||
// csv is the canonical text of the selection ("" for all): the hub's own name
|
||||
// (when present) first, then the peers.
|
||||
func (h hostSel) csv(self string) string {
|
||||
if h.all {
|
||||
return ""
|
||||
}
|
||||
var n []string
|
||||
if h.local {
|
||||
n = append(n, self)
|
||||
}
|
||||
return strings.Join(append(n, h.peers...), ",")
|
||||
}
|
||||
|
||||
// only is the peers' list the fed.Hub understands ("" asks every node).
|
||||
func (h hostSel) only() string {
|
||||
if h.all {
|
||||
return ""
|
||||
}
|
||||
return strings.Join(h.peers, ",")
|
||||
}
|
||||
|
||||
// parseHosts resolves a host query value. ok is false for names this hub does
|
||||
// not serve, for a malformed or oversized list.
|
||||
func (s *Server) parseHosts(raw string) (hostSel, bool) {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" || raw == "all" {
|
||||
return hostSel{all: true, local: true}, true
|
||||
}
|
||||
if len(raw) > 64*maxHostSel {
|
||||
return hostSel{}, false
|
||||
}
|
||||
self := s.opt.Store.Name()
|
||||
seen := map[string]bool{}
|
||||
var sel hostSel
|
||||
for _, n := range strings.Split(raw, ",") {
|
||||
n = strings.TrimSpace(n)
|
||||
switch {
|
||||
case n == "":
|
||||
continue
|
||||
case n == "all":
|
||||
return hostSel{all: true, local: true}, true
|
||||
case len(n) > 64 || len(seen) >= maxHostSel:
|
||||
return hostSel{}, false
|
||||
case seen[n]:
|
||||
continue
|
||||
}
|
||||
seen[n] = true
|
||||
if n == self {
|
||||
sel.local = true
|
||||
} else if s.opt.Hub != nil && s.opt.Hub.Has(n) {
|
||||
sel.peers = append(sel.peers, n)
|
||||
} else {
|
||||
return hostSel{}, false
|
||||
}
|
||||
}
|
||||
if len(seen) == 0 {
|
||||
return hostSel{all: true, local: true}, true
|
||||
}
|
||||
sort.Strings(sel.peers)
|
||||
// naming every node is the same as asking for all of them
|
||||
if sel.local {
|
||||
every := true
|
||||
if s.opt.Hub != nil {
|
||||
for _, p := range s.opt.Hub.PeerNames() {
|
||||
every = every && seen[p]
|
||||
}
|
||||
}
|
||||
if every {
|
||||
return hostSel{all: true, local: true}, true
|
||||
}
|
||||
}
|
||||
return sel, true
|
||||
}
|
||||
|
||||
// hostListOK bounds the text of a host list: names of 64 bytes at most, 16 at most.
|
||||
func hostListOK(raw string) bool {
|
||||
if len(raw) > 64*maxHostSel+maxHostSel {
|
||||
return false
|
||||
}
|
||||
for _, n := range strings.Split(raw, ",") {
|
||||
if len(strings.TrimSpace(n)) > 64 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
"time"
|
||||
)
|
||||
|
||||
// host= accepts "all", one name or a comma list, the same way on every endpoint.
|
||||
func TestHostSelectionList(t *testing.T) {
|
||||
mk := func(ip string) store.PeerExport {
|
||||
e := store.PeerExport{V: 1}
|
||||
e.Summary.IPs = []store.IPSummary{{IP: ip, Score: 10}}
|
||||
return e
|
||||
}
|
||||
hub := fed.NewHub(func() []fed.Backend {
|
||||
return []fed.Backend{fakeBackend{name: "p1", exp: mk("198.51.100.1")}, fakeBackend{name: "p2", exp: mk("198.51.100.2")}, fakeBackend{name: "p3", exp: mk("198.51.100.3")}}
|
||||
})
|
||||
st := store.New(store.Config{Name: "me", Version: "t"})
|
||||
st.Ingest(core.Event{Time: time.Now(), IP: "203.0.113.9", Cat: core.Scanner, Source: "traefik", Status: 404, Path: "/.env"})
|
||||
h := New(Options{Token: utok, Store: st, Hub: hub})
|
||||
total := func(host string) int {
|
||||
code, body := bearerGet(h, "/api/v1/ips?range=24h&min_score=0&host="+host)
|
||||
if code != 200 {
|
||||
t.Fatalf("host=%q: %d %s", host, code, body)
|
||||
}
|
||||
var o struct{ Total int }
|
||||
if err := json.Unmarshal([]byte(body), &o); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return o.Total
|
||||
}
|
||||
for host, want := range map[string]int{"": 4, "all": 4, "p1": 1, "p1,p2": 2, "p1,p2,p3": 3, "me,p3": 2, "me": 1, "me,p1,p2,p3": 4, "p2,p2": 1, "p1,all": 4} {
|
||||
if got := total(host); got != want {
|
||||
t.Errorf("host=%q: %d IPs, want %d", host, got, want)
|
||||
}
|
||||
}
|
||||
for _, ep := range []string{"summary", "traffic", "integrity", "geo", "report"} {
|
||||
if code, _ := bearerGet(h, "/api/v1/"+ep+"?host=p1,p2"); code != 200 {
|
||||
t.Errorf("%s host=p1,p2: %d", ep, code)
|
||||
}
|
||||
if code, _ := bearerGet(h, "/api/v1/"+ep+"?host=p1,nope"); code != 404 {
|
||||
t.Errorf("%s host=p1,nope: %d", ep, code)
|
||||
}
|
||||
}
|
||||
for _, ep := range []string{"period", "metrics", "evolution", "egress"} {
|
||||
if code, _ := bearerGet(h, "/api/v1/"+ep+"?host=me,p1"); code != 200 {
|
||||
t.Errorf("%s host=me,p1: %d", ep, code)
|
||||
}
|
||||
if code, _ := bearerGet(h, "/api/v1/"+ep+"?host=p1,nope"); code != 404 {
|
||||
t.Errorf("%s host=p1,nope: %d", ep, code)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -37,13 +37,13 @@ func (s *Server) eventFilter(w http.ResponseWriter, r *http.Request, defaultSpan
|
||||
}
|
||||
eq.From, eq.To = rg.Bounds(s.opt.Now().Unix())
|
||||
eq.Host = q.Get("host")
|
||||
if eq.Host == "all" {
|
||||
eq.Host = ""
|
||||
}
|
||||
if len(eq.Host) > 64 {
|
||||
if !hostListOK(eq.Host) {
|
||||
badRequest(w, "invalid host")
|
||||
return eq, false
|
||||
}
|
||||
if sel, ok := s.parseHosts(eq.Host); ok { // "all" and a list naming every node become ""
|
||||
eq.Host = sel.csv(s.opt.Store.Name())
|
||||
}
|
||||
if ip := q.Get("ip"); ip != "" {
|
||||
_, err1 := netip.ParseAddr(ip)
|
||||
_, err2 := netip.ParsePrefix(ip)
|
||||
@@ -217,21 +217,19 @@ func (s *Server) sessionsAPI(w http.ResponseWriter, r *http.Request) {
|
||||
}{list[from:to], gap, trunc, s.opt.Store.EventLog() != nil, pageTotal{metaOf(len(list), page, per), len(list)}})
|
||||
}
|
||||
|
||||
// studyHosts resolves the host selection of period and metrics: whether the
|
||||
// local study is wanted and which peers to ask. It answers 404 itself.
|
||||
// studyHosts resolves the host selection of period and metrics (one name, "all"
|
||||
// or a comma list): whether the local study is wanted and which peers to ask
|
||||
// (only: their names, comma separated). It answers 404 itself.
|
||||
func (s *Server) studyHosts(w http.ResponseWriter, host string) (local bool, peers bool, only string, ok bool) {
|
||||
self := s.opt.Store.Name()
|
||||
if host == "" || host == "all" {
|
||||
return true, s.opt.Hub != nil, "", true
|
||||
}
|
||||
if host == self {
|
||||
return true, false, "", true
|
||||
}
|
||||
if s.opt.Hub == nil || !s.opt.Hub.Has(host) {
|
||||
sel, ok := s.parseHosts(host)
|
||||
if !ok {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "unknown host"})
|
||||
return false, false, "", false
|
||||
}
|
||||
return false, true, host, true
|
||||
if sel.all {
|
||||
return true, s.opt.Hub != nil, "", true
|
||||
}
|
||||
return sel.local, len(sel.peers) > 0, sel.only(), true
|
||||
}
|
||||
|
||||
// userSlot admits one more user-side study (503 with Retry-After when four run).
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
|
||||
@@ -139,7 +140,7 @@ func (s *Server) primaryName() string { return s.opt.Store.Name() }
|
||||
|
||||
// enforceFor returns the engine of a host ("" or the primary: the primary's).
|
||||
func (s *Server) enforceFor(host string) *enforce.Engine {
|
||||
if host == "" || host == s.primaryName() || s.opt.Nodes == nil {
|
||||
if host == "" || strings.Contains(host, ",") || host == s.primaryName() || s.opt.Nodes == nil {
|
||||
return enforceEngine.Load()
|
||||
}
|
||||
return s.opt.Nodes.Enforce(host)
|
||||
|
||||
+13
-25
@@ -371,27 +371,23 @@ func (s *Server) logout(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// parts returns the summaries to merge for a host selection.
|
||||
func (s *Server) parts(ctx context.Context, rg store.Range, host string) (parts []store.Summary, all []store.HostInfo) {
|
||||
self := s.opt.Store.Name()
|
||||
local := s.opt.Store.SummaryFor(rg)
|
||||
all = append(all, local.Hosts...)
|
||||
if s.opt.Hub != nil {
|
||||
all = append(all, s.opt.Hub.Hosts()...)
|
||||
}
|
||||
if host == "" || host == "all" || host == self {
|
||||
sel, _ := s.parseHosts(host)
|
||||
if sel.local {
|
||||
parts = append(parts, local)
|
||||
}
|
||||
if s.opt.Hub != nil && host != self {
|
||||
only := ""
|
||||
if host != "" && host != "all" {
|
||||
only = host
|
||||
}
|
||||
parts = append(parts, s.opt.Hub.SummariesFor(ctx, rg, only)...)
|
||||
if s.opt.Hub != nil && (sel.all || len(sel.peers) > 0) {
|
||||
parts = append(parts, s.opt.Hub.SummariesFor(ctx, rg, sel.only())...)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Server) knownHost(w http.ResponseWriter, host string) bool {
|
||||
if host != "all" && host != s.opt.Store.Name() && (s.opt.Hub == nil || !s.opt.Hub.Has(host)) {
|
||||
if _, ok := s.parseHosts(host); !ok {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "unknown host"})
|
||||
return false
|
||||
}
|
||||
@@ -437,16 +433,12 @@ func (s *Server) allIPs(ctx context.Context, rg store.Range, host string) []stor
|
||||
|
||||
func (s *Server) ipsOf(ctx context.Context, rg store.Range, host string, localOnly bool) []store.IPSummary {
|
||||
var lists [][]store.IPSummary
|
||||
self := s.opt.Store.Name()
|
||||
if host == "" || host == "all" || host == self {
|
||||
sel, _ := s.parseHosts(host)
|
||||
if sel.local {
|
||||
lists = append(lists, s.opt.Store.AllIPs(rg, false))
|
||||
}
|
||||
if s.opt.Hub != nil && host != self && !localOnly {
|
||||
only := ""
|
||||
if host != "" && host != "all" {
|
||||
only = host
|
||||
}
|
||||
for _, p := range s.opt.Hub.SummariesFor(ctx, rg, only) {
|
||||
if s.opt.Hub != nil && (sel.all || len(sel.peers) > 0) && !localOnly {
|
||||
for _, p := range s.opt.Hub.SummariesFor(ctx, rg, sel.only()) {
|
||||
lists = append(lists, p.IPs)
|
||||
}
|
||||
}
|
||||
@@ -714,20 +706,16 @@ func (s *Server) traffic(w http.ResponseWriter, r *http.Request) {
|
||||
if host == "" {
|
||||
host = "all"
|
||||
}
|
||||
self := s.opt.Store.Name()
|
||||
if !s.knownHost(w, host) {
|
||||
return
|
||||
}
|
||||
sel, _ := s.parseHosts(host)
|
||||
var parts []store.TrafficData
|
||||
if host == "all" || host == self {
|
||||
if sel.local {
|
||||
parts = append(parts, s.opt.Store.TrafficFor(rg, domain))
|
||||
}
|
||||
if s.opt.Hub != nil && host != self {
|
||||
only := ""
|
||||
if host != "all" {
|
||||
only = host
|
||||
}
|
||||
parts = append(parts, s.opt.Hub.TrafficFor(r.Context(), rg, domain, only)...)
|
||||
if s.opt.Hub != nil && (sel.all || len(sel.peers) > 0) {
|
||||
parts = append(parts, s.opt.Hub.TrafficFor(r.Context(), rg, domain, sel.only())...)
|
||||
}
|
||||
out := store.MergeTraffic(host, parts)
|
||||
out.Domain = domain
|
||||
|
||||
+44
-12
@@ -614,7 +614,7 @@
|
||||
var seen = {}, list = [];
|
||||
var rec = state.summary ? state.summary.recent || [] : [];
|
||||
state.live.concat(rec).forEach(function (e) {
|
||||
if (state.host !== 'all' && e.host !== state.host) return;
|
||||
if (!hostHas(state.host, e.host)) return;
|
||||
var key = e.t + '|' + e.ip + '|' + e.cat + '|' + (e.path || e.user || e.jail || '');
|
||||
if (seen[key]) return;
|
||||
seen[key] = 1;
|
||||
@@ -1021,7 +1021,7 @@
|
||||
// each probe enforces its own bans: the operator picks where to lift it (or every host)
|
||||
var hostSel = el('select', { id: 'unban-host' });
|
||||
var hostRow = el('div', { class: 'unban-host', hidden: true }, el('label', { for: 'unban-host' }, t('pr.unban.host')), hostSel);
|
||||
var wantHost = (opts && opts.host) || (state.host !== 'all' ? state.host : 'all');
|
||||
var wantHost = (opts && opts.host) || (hostList(state.host).length === 1 ? state.host : 'all');
|
||||
getSummary(ctx()).then(function (s) {
|
||||
var hs = (s.hosts || []).map(function (x) { return x.name; });
|
||||
if (hs.length < 2) return;
|
||||
@@ -1832,7 +1832,7 @@
|
||||
var p = [];
|
||||
if (sl.from !== null && sl.from !== undefined) p.push('from=' + encodeURIComponent(new Date(sl.from * 1000).toISOString()), 'to=' + encodeURIComponent(new Date(sl.to * 1000).toISOString()));
|
||||
else p.push('r=' + sl.range);
|
||||
if (sl.host && sl.host !== 'all') p.push('host=' + encodeURIComponent(sl.host));
|
||||
if (sl.host && sl.host !== 'all') p.push('host=' + encodeURIComponent(sl.host).replace(/%2C/gi, ','));
|
||||
return p;
|
||||
}
|
||||
function buildHash(id, segments, extra, sl) {
|
||||
@@ -1841,6 +1841,14 @@
|
||||
return '#/' + [id].concat((segments || []).map(encodeURIComponent)).join('/') + '?' + parts.join('&');
|
||||
}
|
||||
function hrefFor(id, segments, extra) { return buildHash(id, segments || [], extra || {}); }
|
||||
// host selection: 'all' or a comma list of probe names (host=oracle,hostinger in the URL and in the API)
|
||||
function hostList(v) {
|
||||
var seen = {}, out = [];
|
||||
String(v || '').split(',').forEach(function (n) { n = n.trim(); if (n && n !== 'all' && n.length <= 64 && !seen[n]) { seen[n] = 1; out.push(n); } });
|
||||
return out.slice(0, 16);
|
||||
}
|
||||
function hostJoin(list) { return list.length ? list.join(',') : 'all'; }
|
||||
function hostHas(v, name) { return v === 'all' || !v || hostList(v).indexOf(name) >= 0; }
|
||||
// read r/from/to/host from the URL; absent keys keep the current slice
|
||||
function readSlice(q) {
|
||||
var f = q.get('from'), to = q.get('to'), r = q.get('r') || q.get('range'), ok = false;
|
||||
@@ -1849,12 +1857,15 @@
|
||||
if (isFinite(a) && isFinite(b) && b > a && (b - a) / 1000 <= MAX_SPAN) { state.from = Math.floor(a / 1000); state.to = Math.floor(b / 1000); ok = true; }
|
||||
}
|
||||
if (!ok && r && PRESETS.indexOf(r) >= 0) { state.range = r; state.from = state.to = null; lsSet('urutau.range', r); }
|
||||
if (q.has('host')) { state.host = q.get('host') || 'all'; lsSet('urutau.host', state.host); }
|
||||
if (q.has('host')) { state.host = hostJoin(hostList(q.get('host'))); lsSet('urutau.host', state.host); }
|
||||
}
|
||||
// change the slice: the URL changes, the router does the rest
|
||||
function setShell(over) {
|
||||
var sl = { range: state.range, from: state.from, to: state.to, host: state.host };
|
||||
Object.keys(over).forEach(function (k) { sl[k] = over[k]; });
|
||||
// "all" leaves host= out of the URL and readSlice keeps the current host when the key is absent:
|
||||
// apply the host here so going back to every probe works
|
||||
if (over.host !== undefined) { state.host = hostJoin(hostList(over.host)); lsSet('urutau.host', state.host); }
|
||||
var q = Object.assign({}, state.params.query); delete q.p; // a new period or host starts at page 1
|
||||
var id = current ? current.id : 'overview', hash = buildHash(id, state.params.segments, q, sl);
|
||||
if (hash !== location.hash) history.pushState(null, '', hash);
|
||||
@@ -1929,6 +1940,8 @@
|
||||
}
|
||||
// closes whichever filter popover is open (kept under this name: Esc and other pages call it)
|
||||
function closeRangePicker(refocus) { closePop(rp, refocus); closePop(hp, refocus); }
|
||||
// the phone sheet sits above the bottom tab bar: using the tab bar closes it
|
||||
document.addEventListener('click', function (e) { if (e.target.closest && e.target.closest('.tabbar')) closeRangePicker(false); }, true);
|
||||
function openRangePicker() {
|
||||
if (!rp.pop) return;
|
||||
rp.open = false; renderRangePicker();
|
||||
@@ -2070,21 +2083,35 @@
|
||||
box.hidden = true;
|
||||
}
|
||||
function hostOpt(value, name, meta, tone) {
|
||||
var on = state.host === value;
|
||||
var sel = hostList(state.host), on = value === 'all' ? !sel.length : sel.indexOf(value) >= 0;
|
||||
var b = el('button', { type: 'button', class: 'fb-opt', 'data-host': value, 'aria-pressed': on ? 'true' : 'false' },
|
||||
h('span', 'fb-dot ' + tone), h('span', 'fb-opt-t', h('span', 'fb-opt-n', name), h('span', 'fb-opt-m', meta)), h('span', 'fb-tick', svgIcon(IC.check)));
|
||||
b.addEventListener('click', function () { closePop(hp, true); if (state.host !== value) setShell({ host: value }); });
|
||||
b.addEventListener('click', function () {
|
||||
// "all" clears the selection; any other row toggles that probe (several can be on); all of them, or none, is "all"
|
||||
var cur = hostList(state.host), next;
|
||||
if (value === 'all') next = [];
|
||||
else {
|
||||
var i = cur.indexOf(value);
|
||||
next = i >= 0 ? cur.filter(function (n) { return n !== value; }) : cur.concat([value]);
|
||||
var names = (state.hostList || []).map(function (x) { return x.name; });
|
||||
if (names.length && names.every(function (n) { return next.indexOf(n) >= 0; })) next = [];
|
||||
}
|
||||
var nv = hostJoin(next);
|
||||
if (value === 'all') closePop(hp, true);
|
||||
if (nv !== state.host) setShell({ host: nv });
|
||||
});
|
||||
return b;
|
||||
}
|
||||
function renderHostPicker() {
|
||||
if (!hp.btn) return;
|
||||
var hosts = state.hostList || [], on = hosts.filter(function (x) { return x.online; }).length;
|
||||
$('#host-picker').hidden = hosts.length < 2;
|
||||
var cur = hosts.filter(function (x) { return x.name === state.host; })[0];
|
||||
hp.label.textContent = state.host === 'all' ? t('host.all') : state.host;
|
||||
var tone = state.host === 'all' ? (on === hosts.length ? 'on' : on ? 'warn' : 'off') : (cur && cur.online ? 'on' : 'off');
|
||||
var sel = hostList(state.host), picked = hosts.filter(function (x) { return sel.indexOf(x.name) >= 0; });
|
||||
var pOn = picked.filter(function (x) { return x.online; }).length;
|
||||
hp.label.textContent = !sel.length ? t('host.all') : sel.join(', ');
|
||||
var tone = !sel.length ? (on === hosts.length ? 'on' : on ? 'warn' : 'off') : (pOn === picked.length && picked.length ? 'on' : pOn ? 'warn' : 'off');
|
||||
hp.dot.className = 'fb-dot ' + tone;
|
||||
hp.count.textContent = state.host === 'all' ? on + '/' + hosts.length : (cur && cur.online ? t('host.online') : t('host.offline'));
|
||||
hp.count.textContent = !sel.length ? on + '/' + hosts.length : (sel.length > 1 ? pOn + '/' + picked.length : (pOn ? t('host.online') : t('host.offline')));
|
||||
hp.count.className = 'fb-count ' + tone;
|
||||
hp.btn.setAttribute('aria-label', t('host.label') + ': ' + hp.label.textContent + ', ' + t('fb.host.status', { n: on, m: hosts.length }));
|
||||
var want = hosts.map(function (x) { return x.name + (x.online ? '1' : '0') + (x.version || ''); }).join('|') + '|' + state.host + '|' + lang;
|
||||
@@ -2124,7 +2151,7 @@
|
||||
var p = $('#slice-text');
|
||||
if (!p) return;
|
||||
clear(p);
|
||||
var parts = [state.host === 'all' ? t('slice.allHosts') : t('slice.host', { name: state.host })];
|
||||
var parts = [state.host === 'all' ? t('slice.allHosts') : t('slice.host', { name: hostList(state.host).join(', ') })];
|
||||
if (current && pages[current.id] && pages[current.id].domain) parts.push(state.domain === 'all' ? t('slice.allDomains') : t('slice.domain', { name: state.domain }));
|
||||
if (state.note) parts.push(state.note);
|
||||
var live = !isCustom();
|
||||
@@ -2304,7 +2331,12 @@
|
||||
function updateHostSelect(s) {
|
||||
var hosts = s.hosts || [];
|
||||
state.hostList = hosts;
|
||||
if (state.host !== 'all' && !hosts.some(function (x) { return x.name === state.host; })) { state.host = 'all'; lsSet('urutau.host', 'all'); }
|
||||
if (state.host !== 'all' && hosts.length) {
|
||||
var known = hostList(state.host).filter(function (n) { return hosts.some(function (x) { return x.name === n; }); });
|
||||
if (known.length === hosts.length) known = [];
|
||||
var kv = hostJoin(known);
|
||||
if (kv !== state.host) { state.host = kv; lsSet('urutau.host', kv); }
|
||||
}
|
||||
renderHostPicker();
|
||||
}
|
||||
function shellSummary() {
|
||||
|
||||
@@ -29,8 +29,21 @@
|
||||
'ip.loading': 'Loading the analysis.',
|
||||
'ip.invalid': 'This is not a valid IP address.',
|
||||
'ip.error': 'Could not load this IP.',
|
||||
'ip.notfound': 'No activity from this IP in the selected period.',
|
||||
'ip.notfound.hint': 'Pick a longer period above, or the IP was never seen.',
|
||||
'ip.never': 'This IP was never seen by Urutau (neither as a source nor as an egress destination).',
|
||||
'ip.dst.title': 'Egress destination',
|
||||
'ip.dst.lead': 'Our workloads connected to this address; it never attacked us.',
|
||||
'ip.dst.hint': 'Outbound connections from this installation to the IP, not inbound attacks.',
|
||||
'ip.dst.host': 'Host',
|
||||
'ip.dst.workloads': 'Workloads',
|
||||
'ip.dst.ports': 'Ports',
|
||||
'ip.dst.conns': 'Connections',
|
||||
'ip.dst.net': 'Network',
|
||||
'ip.dst.findings': 'Findings',
|
||||
'ip.dst.incidents': 'Linked incidents',
|
||||
'ip.dst.nofind': 'No finding in this period.',
|
||||
'ip.dst.last': 'Last: {when}',
|
||||
'ip.dst.inb.after': 'Last seen as an attacker (inbound) on {when}, outside the selected period.',
|
||||
'ip.dst.inb.btn': 'Show the last 30 days',
|
||||
'ip.retry': 'Try again',
|
||||
'ip.lead.hostile': 'Hostile: {events} {range}',
|
||||
'ip.lead.suspicious': 'Suspicious: {events} {range}',
|
||||
@@ -354,8 +367,21 @@
|
||||
'ip.loading': 'Carregando a análise.',
|
||||
'ip.invalid': 'Este não é um endereço IP válido.',
|
||||
'ip.error': 'Não foi possível carregar este IP.',
|
||||
'ip.notfound': 'Nenhuma atividade deste IP no período selecionado.',
|
||||
'ip.notfound.hint': 'Escolha um período maior acima, ou o IP nunca foi visto.',
|
||||
'ip.never': 'Este IP nunca foi visto pelo Urutau (nem como origem nem como destino de saída).',
|
||||
'ip.dst.title': 'Destino de saída',
|
||||
'ip.dst.lead': 'Nossas cargas de trabalho conectaram a este endereço; ele nunca nos atacou.',
|
||||
'ip.dst.hint': 'Conexões de saída desta instalação para o IP, não ataques de entrada.',
|
||||
'ip.dst.host': 'Host',
|
||||
'ip.dst.workloads': 'Cargas de trabalho',
|
||||
'ip.dst.ports': 'Portas',
|
||||
'ip.dst.conns': 'Conexões',
|
||||
'ip.dst.net': 'Rede',
|
||||
'ip.dst.findings': 'Achados',
|
||||
'ip.dst.incidents': 'Incidentes ligados',
|
||||
'ip.dst.nofind': 'Nenhum achado neste período.',
|
||||
'ip.dst.last': 'Último: {when}',
|
||||
'ip.dst.inb.after': 'Visto pela última vez como atacante (entrada) em {when}, fora do período selecionado.',
|
||||
'ip.dst.inb.btn': 'Mostrar os últimos 30 dias',
|
||||
'ip.retry': 'Tentar de novo',
|
||||
'ip.lead.hostile': 'Hostil: {events} {range}',
|
||||
'ip.lead.suspicious': 'Suspeito: {events} {range}',
|
||||
@@ -1988,7 +2014,7 @@
|
||||
h('div', 'ipx-skel-b'), h('div', 'ipx-skel-b short'), h('div', 'ipx-skel-b'));
|
||||
}
|
||||
function errorNode(s, key, withRetry) {
|
||||
var box = h('div', 'ipx-card state-error ipx-state', h('p', 'ipx-empty-t', t(key)), key === 'ip.notfound' ? h('p', 'ipx-empty-h', t('ip.notfound.hint')) : null);
|
||||
var box = h('div', 'ipx-card state-error ipx-state', h('p', 'ipx-empty-t', t(key)));
|
||||
if (withRetry) {
|
||||
var b = h('button', 'ipx-btn', { type: 'button' }, t('ip.retry'));
|
||||
b.addEventListener('click', function () { load(s); });
|
||||
@@ -2029,6 +2055,72 @@
|
||||
watchScrollFade(s, toc);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- egress destination (no inbound data)
|
||||
function dstBadge(sev) { return h('span', 'ipx-chip', str(sev)); }
|
||||
function egressNode(s, d) {
|
||||
var eg = arr(d.egress).filter(isObj), fs = arr(d.findings).filter(isObj), ics = arr(d.incidents).filter(isObj);
|
||||
var c = card('ip.dst.title', 'ip.dst.hint', 12);
|
||||
c.body.appendChild(h('p', 'ipx-lead', t('ip.dst.lead')));
|
||||
if (eg.length) {
|
||||
var tb = h('tbody');
|
||||
eg.forEach(function (x) {
|
||||
var cc = str(x.cc).toUpperCase(), net = [x.asn ? str(x.asn) : '', clip(x.org, 60)].filter(Boolean).join(' ');
|
||||
tb.appendChild(h('tr', null,
|
||||
h('td', null, str(x.host)),
|
||||
h('td', null, arr(x.workloads).join(', ') || '-'),
|
||||
h('td', 'ipx-mono', arr(x.ports).join(', ') || '-'),
|
||||
h('td', 'ipx-num', N(num(x.conns))),
|
||||
h('td', null, (cc && fmt.flag ? fmt.flag(cc) + ' ' : '') + (cc && fmt.country ? fmt.country(cc) : cc) + (net ? ' · ' + net : ''))));
|
||||
});
|
||||
c.body.appendChild(h('div', 'ipx-tbl-w', h('table', 'ipx-tbl ipx-ctbl', h('thead', null, h('tr', null,
|
||||
h('th', null, t('ip.dst.host')), h('th', null, t('ip.dst.workloads')), h('th', null, t('ip.dst.ports')), h('th', null, t('ip.dst.conns')), h('th', null, t('ip.dst.net')))), tb)));
|
||||
}
|
||||
c.body.appendChild(sub('ip.dst.findings'));
|
||||
if (!fs.length) c.body.appendChild(h('p', 'ipx-muted', t('ip.dst.nofind')));
|
||||
else {
|
||||
var fb = h('tbody');
|
||||
fs.forEach(function (f) {
|
||||
fb.appendChild(h('tr', null, h('td', null, str(f.host)), h('td', null, str(f.kind)), h('td', null, dstBadge(f.severity)), h('td', null, str(f.workload)),
|
||||
h('td', 'ipx-mono', (str(f.proto) + '/' + num(f.dport))), h('td', null, clip(f.detail, 120)), h('td', null, dt(num(f.last)))));
|
||||
});
|
||||
c.body.appendChild(h('div', 'ipx-tbl-w', h('table', 'ipx-tbl ipx-ctbl', fb)));
|
||||
}
|
||||
if (ics.length) {
|
||||
c.body.appendChild(sub('ip.dst.incidents'));
|
||||
var ul = h('ul', 'ipx-list');
|
||||
ics.forEach(function (i) {
|
||||
var id = str(i.id), parts = id.split('/');
|
||||
var href = '#/incidents/' + encodeURIComponent(parts[0]) + '/' + encodeURIComponent(parts.slice(1).join('/'));
|
||||
ul.appendChild(h('li', null, h('a', null, { href: href }, id), ' ', dstBadge(i.severity), ' ', h('span', 'ipx-muted', str(i.status) + ' · ' + clip(i.title, 100))));
|
||||
});
|
||||
c.body.appendChild(ul);
|
||||
}
|
||||
return c.node;
|
||||
}
|
||||
function loadEgress(s, my) {
|
||||
var p = Object.assign({}, rParams(s.ctx));
|
||||
if (s.ctx && s.ctx.host && s.ctx.host !== 'all') p.host = s.ctx.host;
|
||||
U.api('/api/v1/ip/' + encodeURIComponent(s.ip) + '/egress', p).then(function (d) {
|
||||
if (!s.alive || my !== s.seq) return;
|
||||
if (!isObj(d)) throw new Error('bad payload');
|
||||
var has1 = arr(d.egress).length || arr(d.findings).length || arr(d.incidents).length, last = num(d.last_seen_inbound);
|
||||
if (has1) { showState(s, egressNode(s, d)); return; }
|
||||
if (last) {
|
||||
var box = h('div', 'ipx-card ipx-state', h('p', 'ipx-empty-t', t('ip.dst.inb.after', { when: dt(last) })));
|
||||
var b = h('button', 'ipx-btn', { type: 'button' }, t('ip.dst.inb.btn'));
|
||||
b.addEventListener('click', function () { location.hash = '#/ip/' + encodeURIComponent(s.ip) + '?r=30d'; });
|
||||
box.appendChild(b);
|
||||
showState(s, box);
|
||||
return;
|
||||
}
|
||||
showState(s, errorNode(s, 'ip.never', false));
|
||||
}).catch(function (e) {
|
||||
if (!s.alive || my !== s.seq) return;
|
||||
if (e && e.message === 'unauthorized') return;
|
||||
showState(s, errorNode(s, 'ip.error', true));
|
||||
});
|
||||
}
|
||||
|
||||
function load(s) {
|
||||
var my = ++s.seq;
|
||||
s.ip = ipFromCtx(s.ctx);
|
||||
@@ -2048,7 +2140,8 @@
|
||||
if (!s.alive || my !== s.seq) return;
|
||||
if (e && e.message === 'unauthorized') return;
|
||||
s.data = null;
|
||||
showState(s, errorNode(s, e && e.status === 404 ? 'ip.notfound' : 'ip.error', !(e && e.status === 404)));
|
||||
if (e && e.status === 404) { loadEgress(s, my); return; }
|
||||
showState(s, errorNode(s, e && e.status === 404 ? 'ip.never' : 'ip.error', !(e && e.status === 404)));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1317,7 +1317,7 @@
|
||||
this.listDirty = true;
|
||||
if (this.paused || this.hidden || this.offHosts[r.host] || (dev && this.offDev[dev])) return;
|
||||
var h = this.ctx && this.ctx.host;
|
||||
if (h && h !== 'all' && h !== r.host) return;
|
||||
if (h && h !== 'all' && (',' + h + ',').indexOf(',' + r.host + ',') < 0) return;
|
||||
this.map.spawn(e, { visit: true });
|
||||
};
|
||||
P.visitBatch = function (e) { if (isNum(e.n) && e.n > 0) this.vcount(Math.min(e.n, 1e6), isNum(e.t) ? e.t : Date.now() / 1000, '', ''); };
|
||||
@@ -1500,21 +1500,21 @@
|
||||
P.draw = function (r) {
|
||||
if (this.offCats[r.cat] || this.offHosts[r.host]) return;
|
||||
var h = this.ctx && this.ctx.host;
|
||||
if (h && h !== 'all' && h !== r.host) return;
|
||||
if (h && h !== 'all' && (',' + h + ',').indexOf(',' + r.host + ',') < 0) return;
|
||||
this.map.spawn(r.ev);
|
||||
};
|
||||
|
||||
P.visible = function (r) {
|
||||
if (this.offCats[r.cat] || this.offHosts[r.host]) return false;
|
||||
var h = this.ctx && this.ctx.host;
|
||||
return !h || h === 'all' || h === r.host;
|
||||
return !h || h === 'all' || (',' + h + ',').indexOf(',' + r.host + ',') >= 0;
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------------ panels and metrics
|
||||
P.hostOk = function (h) {
|
||||
if (this.offHosts[h]) return false;
|
||||
var c = this.ctx && this.ctx.host;
|
||||
return !c || c === 'all' || c === h;
|
||||
return !c || c === 'all' || (',' + c + ',').indexOf(',' + h + ',') >= 0;
|
||||
};
|
||||
|
||||
// sums the minute buckets from..to (inclusive) over the visible hosts (or all of them)
|
||||
|
||||
@@ -411,14 +411,14 @@ aside#detail li { overflow-wrap: anywhere; margin-bottom: 2px; }
|
||||
.grid.kpis { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: var(--s-3); }
|
||||
.stat { padding: var(--s-3); } .stat .v { font-size: 1.5rem; }
|
||||
.tabbar {
|
||||
display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); position: fixed; left: 0; right: 0; bottom: 0; z-index: 30;
|
||||
display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); position: fixed; left: 0; right: 0; bottom: 0; z-index: 34; /* above the sticky filter bar (.slice, 32) */
|
||||
background: var(--rail); border-top: 1px solid var(--rail-line); padding: 4px 4px max(4px, env(safe-area-inset-bottom));
|
||||
}
|
||||
.tab { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 2px; min-height: 56px; border: 0; background: none; color: var(--rail-ink); text-decoration: none; font-size: .75rem; border-radius: var(--radius-sm); cursor: pointer; padding: 4px 2px; }
|
||||
.tab .nav-ico svg { width: 22px; height: 22px; }
|
||||
.tab span:not(.nav-ico):not(.nav-badge) { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.tab[aria-current="page"], .tab[aria-expanded="true"] { background: var(--rail-active); color: #fff; }
|
||||
.more-sheet { position: fixed; left: 0; right: 0; bottom: 68px; z-index: 31; background: var(--surface-overlay); border-top: 1px solid var(--line-strong); border-radius: 14px 14px 0 0; padding: var(--s-3); box-shadow: var(--shadow); max-height: calc(100dvh - 68px - env(safe-area-inset-top, 0px) - 12px); overflow-y: auto; overscroll-behavior: contain; -webkit-overflow-scrolling: touch; }
|
||||
.more-sheet { position: fixed; left: 0; right: 0; bottom: 68px; z-index: 35; background: var(--surface-overlay); border-top: 1px solid var(--line-strong); border-radius: 14px 14px 0 0; padding: var(--s-3); box-shadow: var(--shadow); max-height: calc(100dvh - 68px - env(safe-area-inset-top, 0px) - 12px); overflow-y: auto; overscroll-behavior: contain; -webkit-overflow-scrolling: touch; }
|
||||
.more-sheet:not([hidden]) { display: block; }
|
||||
.more-sheet a { display: flex; align-items: center; gap: var(--s-3); min-height: 48px; padding: 8px var(--s-3); color: var(--ink); text-decoration: none; border-radius: var(--radius-sm); }
|
||||
.more-sheet a[aria-current="page"] { background: var(--accent-soft); }
|
||||
@@ -788,9 +788,10 @@ html, body { overflow-x: clip; }
|
||||
.slice-ctl:has(#domain:not([hidden])) { flex-wrap: wrap; }
|
||||
.fb-link { min-height: 44px; }
|
||||
.fb-copy span { display: none; }
|
||||
.fb-pop { position: fixed; left: 0; right: 0; bottom: 0; top: auto; width: auto; z-index: 61; border-radius: 16px 16px 0 0; border-bottom: 0; max-height: 88dvh; overflow-y: auto; overscroll-behavior: contain;
|
||||
padding: var(--s-3) var(--s-4) max(var(--s-4), env(safe-area-inset-bottom)); }
|
||||
.fb-pop-host { width: auto; padding: var(--s-3) var(--s-4) max(var(--s-4), env(safe-area-inset-bottom)); gap: var(--s-2); }
|
||||
/* the sheet opens just above the bottom tab bar (65 px + safe area), never over it */
|
||||
.fb-pop { position: fixed; left: 0; right: 0; bottom: calc(65px + env(safe-area-inset-bottom, 0px)); top: auto; width: auto; z-index: 61; border-radius: 16px 16px 0 0; border-bottom: 0; max-height: calc(100dvh - 65px - env(safe-area-inset-bottom, 0px) - var(--topbar-h) - 8px); overflow-y: auto; overscroll-behavior: contain;
|
||||
padding: var(--s-3) var(--s-4) var(--s-4); }
|
||||
.fb-pop-host { width: auto; padding: var(--s-3) var(--s-4) var(--s-4); gap: var(--s-2); }
|
||||
.fb-head { display: flex; align-items: center; justify-content: space-between; gap: var(--s-2); }
|
||||
.fb-head h2 { margin: 0; font: 700 1rem var(--font-display); color: var(--heading); }
|
||||
.fb-x { width: 44px; min-height: 44px; }
|
||||
|
||||
@@ -28,7 +28,10 @@ type Pos struct {
|
||||
FPLen int
|
||||
}
|
||||
|
||||
const fpMax = 64
|
||||
// fpMax covers a whole first line: Traefik's first 64 bytes (client address and
|
||||
// port of a keep-alive connection) repeat across rotations, so a short head
|
||||
// cannot tell two generations of the file apart.
|
||||
const fpMax = 1024
|
||||
|
||||
func fingerprint(b []byte) uint64 {
|
||||
h := uint64(14695981039346656037)
|
||||
|
||||
@@ -155,3 +155,16 @@ func TestStalePosAndBackups(t *testing.T) {
|
||||
t.Fatalf("%v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// Traefik: the first 64 bytes of each rotated generation were identical (same
|
||||
// keep-alive client address and port), so the head must cover the whole line.
|
||||
func TestHeadCoversFirstLine(t *testing.T) {
|
||||
a := []byte(`{"ClientAddr":"195.200.0.252:34352","ClientHost":"195.200.0.252","StartUTC":"2026-11-16T21:06:20.1Z"}` + "\n")
|
||||
b := []byte(`{"ClientAddr":"195.200.0.252:34352","ClientHost":"195.200.0.252","StartUTC":"2026-11-16T22:48:21.7Z"}` + "\n")
|
||||
if fingerprint(a[:64]) != fingerprint(b[:64]) {
|
||||
t.Fatal("fixture: the first 64 bytes should collide")
|
||||
}
|
||||
if fpMax < len(a) || fingerprint(a) == fingerprint(b) {
|
||||
t.Fatal("head fingerprint must tell the two generations apart")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user