feat: 1.4.0 second firewall, egress analysis and HTML report
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 28s
CI / Dependency audit (push) Successful in 16s
CI / Tests (Linux, race detector) (push) Successful in 1m3s
Release / Plan (reuse the published image?) (push) Successful in 4s
Release / ci (push) Skipped
Release / Build image (amd64) (push) Skipped
Release / Build image (arm64) (push) Skipped
Release / Publish tags (push) Successful in 13s
Release / Gitea release (push) Successful in 3s
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 28s
CI / Dependency audit (push) Successful in 16s
CI / Tests (Linux, race detector) (push) Successful in 1m3s
Release / Plan (reuse the published image?) (push) Successful in 4s
Release / ci (push) Skipped
Release / Build image (amd64) (push) Skipped
Release / Build image (arm64) (push) Skipped
Release / Publish tags (push) Successful in 13s
Release / Gitea release (push) Successful in 3s
Optional second firewall (URUTAU_ENFORCE off/observe/on) through the host fail2ban, outbound traffic analysis (beaconing, mining, spam, DNS bypass, unauthorised scans) with authorised scanner workloads, host kit in deploy/host and a printable HTML report. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3adaa007ec
commit
c33cca22e3
59 files changed
+7364
-24
No files matched your search
@@ -25,3 +25,4 @@ __pycache__/
|
||||
|
||||
# Runtime pid files left by local test scripts
|
||||
*.pid
|
||||
pid
|
||||
+15
-4
@@ -6,12 +6,16 @@ Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versio
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [1.1.1] - 2026-11-14
|
||||
## [1.4.0] - 2026-11-15
|
||||
|
||||
### Fixed
|
||||
### Added
|
||||
|
||||
- Live page, globe mode: sea and land colors no longer swap while the globe turns. Each country ring is now clipped at the horizon and closed along the edge of the globe, and long edges follow the map projection.
|
||||
- World map data: countries crossing the 180th meridian (Russia, Fiji) are closed along the map edge, so the Sea of Okhotsk is no longer filled as land on the flat maps.
|
||||
- Second firewall (optional, `URUTAU_ENFORCE=off|observe|on`): Urutau decides which attacking addresses to block and writes the decisions to a file; the host fail2ban (jail `urutau`) applies them. Urutau gets no privileges. Observe mode shows what would be blocked. Optional decision sharing between hub and peers (`URUTAU_ENFORCE_SHARE`), applied only when the receiving server also saw the address attack. Never blocks trusted addresses, private ranges, CDN (Cloudflare) and public resolver ranges, peers or the server itself. The ban only drops connections the address starts, so replies to the server's own connections keep flowing.
|
||||
- Egress analysis (`URUTAU_EGRESS`): new outbound connections of the host and containers, logged by nftables, are checked for beaconing (regular conversations with one destination), mining, IRC and SMTP ports, contact with addresses that attacked the server or Tor exits, DNS outside the allowed resolvers, unauthorised outbound scans and new countries. Workloads by network or container name (`URUTAU_EGRESS_WORKLOADS`); a `scanner` workload (an authorised surface scanner) has only its scan-shaped traffic summarised, everything else is judged like any other workload, so its beaconing is still detected.
|
||||
- Host kit in `deploy/host` (nftables table, rsyslog, logrotate, container map, fail2ban filter, action and jail, `install.sh`).
|
||||
- New page Outbound traffic and a Second firewall section in Defense.
|
||||
- HTML report (`/api/v1/report?format=html`): cover, executive summary in plain language, rule-based recommendations, threats, geography, errors and health, visitors, defense, second firewall and outbound traffic, printable on A4. The Reports page downloads or prints it.
|
||||
- Screenshot script covers every page.
|
||||
|
||||
## [1.3.0] - 2026-11-14
|
||||
|
||||
@@ -45,6 +49,13 @@ Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versio
|
||||
|
||||
- The soft memory limit is 256 MiB (worst case measured: about 54 MiB of heap and a snapshot of about 27 MB). In Docker, `mem_limit: 384m` is recommended.
|
||||
|
||||
## [1.1.1] - 2026-11-14
|
||||
|
||||
### Fixed
|
||||
|
||||
- Live page, globe mode: sea and land colors no longer swap while the globe turns. Each country ring is now clipped at the horizon and closed along the edge of the globe, and long edges follow the map projection.
|
||||
- World map data: countries crossing the 180th meridian (Russia, Fiji) are closed along the map edge, so the Sea of Okhotsk is no longer filled as land on the flat maps.
|
||||
|
||||
## [1.1.0] - 2026-11-14
|
||||
|
||||
### Added
|
||||
|
||||
+15
-4
@@ -6,12 +6,16 @@ Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/);
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [1.1.1] - 2026-11-14
|
||||
## [1.4.0] - 2026-11-15
|
||||
|
||||
### Corrigido
|
||||
### Adicionado
|
||||
|
||||
- Página Ao vivo, modo globo: as cores do mar e da terra não se trocam mais enquanto o globo gira. Cada contorno de país agora é recortado no horizonte e fechado ao longo da borda do globo, e as arestas longas seguem a projeção do mapa.
|
||||
- Dados do mapa-múndi: países que cruzam o meridiano 180 (Rússia, Fiji) são fechados ao longo da borda do mapa, então o Mar de Okhotsk não é mais pintado como terra nos mapas planos.
|
||||
- Segundo firewall (opcional, `URUTAU_ENFORCE=off|observe|on`): o Urutau decide quais endereços atacantes bloquear e grava as decisões num arquivo; o fail2ban do host (jail `urutau`) as aplica. O Urutau não ganha privilégios. O modo observação mostra o que seria bloqueado. Compartilhamento opcional de decisões entre hub e peers (`URUTAU_ENFORCE_SHARE`), aplicado só quando o servidor que recebe também viu o endereço atacar. Nunca bloqueia endereços confiáveis, redes privadas, faixas de CDN (Cloudflare) e de resolvedores públicos, peers nem o próprio servidor. O banimento só derruba conexões que o endereço inicia, então as respostas às conexões do próprio servidor continuam passando.
|
||||
- Análise do tráfego de saída (`URUTAU_EGRESS`): as conexões novas de saída do host e dos contêineres, registradas pelo nftables, são analisadas em busca de beaconing (conversa regular com um destino), mineração, portas de IRC e SMTP, contato com endereços que atacaram o servidor ou saídas Tor, DNS fora dos resolvedores permitidos, varreduras de saída não autorizadas e países novos. Workloads por rede ou nome de contêiner (`URUTAU_EGRESS_WORKLOADS`); um workload `scanner` (scanner de superfície autorizado) só tem resumido o tráfego em formato de varredura, todo o resto é julgado como o de qualquer workload, então o beaconing dele continua sendo detectado.
|
||||
- Kit de host em `deploy/host` (tabela nftables, rsyslog, logrotate, mapa de contêineres, filtro, ação e jail do fail2ban, `install.sh`).
|
||||
- Página nova Tráfego de saída e seção Segundo firewall em Defesa.
|
||||
- Relatório HTML (`/api/v1/report?format=html`): capa, sumário executivo em linguagem leiga, recomendações por regras, ameaças, geografia, erros e saúde, visitantes, defesa, segundo firewall e tráfego de saída, imprimível em A4. A página Relatórios baixa ou imprime.
|
||||
- O script de capturas cobre todas as páginas.
|
||||
|
||||
## [1.3.0] - 2026-11-14
|
||||
|
||||
@@ -45,6 +49,13 @@ Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/);
|
||||
|
||||
- O limite suave de memória é 256 MiB (pior caso medido: cerca de 54 MiB de heap e um snapshot de cerca de 27 MB). No Docker, recomenda-se `mem_limit: 384m`.
|
||||
|
||||
## [1.1.1] - 2026-11-14
|
||||
|
||||
### Corrigido
|
||||
|
||||
- Página Ao vivo, modo globo: as cores do mar e da terra não se trocam mais enquanto o globo gira. Cada contorno de país agora é recortado no horizonte e fechado ao longo da borda do globo, e as arestas longas seguem a projeção do mapa.
|
||||
- Dados do mapa-múndi: países que cruzam o meridiano 180 (Rússia, Fiji) são fechados ao longo da borda do mapa, então o Mar de Okhotsk não é mais pintado como terra nos mapas planos.
|
||||
|
||||
## [1.1.0] - 2026-11-14
|
||||
|
||||
### Adicionado
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
# Urutau: kernel log lines of the egress table go to their own file and stay
|
||||
# out of the general syslog (an authorised scan would flood it).
|
||||
if ($syslogfacility-text == "kern" and $msg contains "URUTAU-EGRESS: ") then {
|
||||
action(type="omfile" file="/var/log/urutau/egress.log" template="RSYSLOG_FileFormat"
|
||||
fileOwner="syslog" fileGroup="adm" fileCreateMode="0640")
|
||||
stop
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
# Urutau "second firewall" action: like iptables-allports, but it only drops
|
||||
# connections the banned address STARTS (conntrack original direction). The
|
||||
# replies to connections this host opened (DNS, ACME, image pulls, apt) keep
|
||||
# flowing even if a decision ever names an address the host depends on.
|
||||
[INCLUDES]
|
||||
before = iptables-allports.conf
|
||||
|
||||
[Definition]
|
||||
actionban = <iptables> -I f2b-<name> 1 -s <ip> -m conntrack --ctdir ORIGINAL -j <blocktype>
|
||||
actionunban = <iptables> -D f2b-<name> -s <ip> -m conntrack --ctdir ORIGINAL -j <blocktype>
|
||||
@@ -0,0 +1,7 @@
|
||||
# Urutau "second firewall": one line per decision written by Urutau in
|
||||
# enforce=on mode, e.g.
|
||||
# 2026-11-14T22:00:00Z urutau decision=ban ip=203.0.113.7 reason=wp-bruteforce score=95 ttl=3600 host=oracle src=local
|
||||
[Definition]
|
||||
datepattern = ^%%Y-%%m-%%dT%%H:%%M:%%SZ
|
||||
failregex = ^\s*urutau decision=ban ip=<HOST> reason=[a-z0-9-]+
|
||||
ignoreregex =
|
||||
@@ -0,0 +1,14 @@
|
||||
# Urutau "second firewall". Urutau never gets privileges: it only writes its
|
||||
# decisions to this file and fail2ban applies them, with its own ignoreip
|
||||
# (the [DEFAULT] of the host still protects trusted addresses).
|
||||
[urutau]
|
||||
enabled = true
|
||||
backend = polling
|
||||
filter = urutau
|
||||
logpath = /var/log/urutau-enforce/decisions.log
|
||||
maxretry = 1
|
||||
findtime = 1h
|
||||
bantime = 1h
|
||||
# ignoreip and ignoreself come from the host [DEFAULT] (never override them here)
|
||||
action = urutau-allports[name=urutau-in, chain=INPUT, protocol=all]
|
||||
urutau-allports[name=urutau-docker, chain=DOCKER-USER, protocol=all]
|
||||
@@ -0,0 +1,63 @@
|
||||
#!/bin/sh
|
||||
# Urutau host kit: egress logging (nftables + rsyslog), the container map and,
|
||||
# optionally, the fail2ban jail of the "second firewall".
|
||||
#
|
||||
# sudo sh install.sh # egress logging + container map
|
||||
# sudo sh install.sh --enforce # also the fail2ban jail for URUTAU_ENFORCE=on
|
||||
# sudo sh install.sh --remove # undo everything
|
||||
#
|
||||
# Idempotent. Urutau itself never gets privileges: it only reads these logs and
|
||||
# writes its ban decisions to /var/log/urutau-enforce/decisions.log.
|
||||
set -eu
|
||||
here=$(cd "$(dirname "$0")" && pwd)
|
||||
uid=${URUTAU_UID:-10001}
|
||||
|
||||
[ "$(id -u)" = 0 ] || { echo "run as root" >&2; exit 1; }
|
||||
|
||||
if [ "${1:-}" = "--remove" ]; then
|
||||
systemctl disable --now urutau-egress.service urutau-containers-map.timer urutau-logrotate.timer 2>/dev/null || true
|
||||
rm -f /etc/systemd/system/urutau-egress.service /etc/systemd/system/urutau-containers-map.service \
|
||||
/etc/systemd/system/urutau-containers-map.timer /usr/local/sbin/urutau-containers-map \
|
||||
/etc/rsyslog.d/41-urutau-egress.conf /etc/logrotate.d/urutau-egress \
|
||||
/etc/fail2ban/jail.d/urutau.local /etc/fail2ban/filter.d/urutau.conf /etc/fail2ban/action.d/urutau-allports.conf \
|
||||
/etc/systemd/system/urutau-logrotate.service /etc/systemd/system/urutau-logrotate.timer
|
||||
rm -rf /etc/urutau
|
||||
systemctl daemon-reload
|
||||
systemctl restart rsyslog
|
||||
fail2ban-client reload >/dev/null 2>&1 || true
|
||||
echo "removed (logs under /var/log/urutau kept)"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
wan=${URUTAU_WAN:-$(ip -o route get 1.1.1.1 | sed -n 's/.* dev \([^ ]*\).*/\1/p')}
|
||||
[ -n "$wan" ] || { echo "cannot detect the uplink interface; set URUTAU_WAN" >&2; exit 1; }
|
||||
case "$wan" in *[!A-Za-z0-9_.-]*) echo "bad interface name: $wan" >&2; exit 1 ;; esac
|
||||
|
||||
install -d -m 0750 -o syslog -g adm /var/log/urutau 2>/dev/null || install -d -m 0750 -g adm /var/log/urutau
|
||||
install -d -m 0755 /etc/urutau
|
||||
sed "s/@WAN@/$wan/g" "$here/urutau-egress.nft" > /etc/urutau/egress.nft
|
||||
nft -c -f /etc/urutau/egress.nft
|
||||
|
||||
install -m 0644 "$here/41-urutau-egress.conf" /etc/rsyslog.d/41-urutau-egress.conf
|
||||
install -m 0644 "$here/urutau.logrotate" /etc/logrotate.d/urutau-egress
|
||||
install -m 0755 "$here/urutau-containers-map" /usr/local/sbin/urutau-containers-map
|
||||
install -m 0644 "$here/urutau-egress.service" "$here/urutau-containers-map.service" \
|
||||
"$here/urutau-containers-map.timer" "$here/urutau-logrotate.service" "$here/urutau-logrotate.timer" /etc/systemd/system/
|
||||
systemctl daemon-reload
|
||||
systemctl restart rsyslog
|
||||
systemctl enable urutau-egress.service urutau-containers-map.timer urutau-logrotate.timer >/dev/null
|
||||
systemctl start urutau-logrotate.timer
|
||||
systemctl restart urutau-egress.service
|
||||
systemctl start urutau-containers-map.service urutau-containers-map.timer
|
||||
echo "egress logging on $wan: /var/log/urutau/egress.log, map: /var/log/urutau/containers.map"
|
||||
|
||||
if [ "${1:-}" = "--enforce" ]; then
|
||||
install -d -m 0750 -o "$uid" -g adm /var/log/urutau-enforce
|
||||
[ -e /var/log/urutau-enforce/decisions.log ] || install -m 0640 -o "$uid" -g adm /dev/null /var/log/urutau-enforce/decisions.log
|
||||
install -m 0644 "$here/fail2ban-filter-urutau.conf" /etc/fail2ban/filter.d/urutau.conf
|
||||
install -m 0644 "$here/fail2ban-action-urutau.conf" /etc/fail2ban/action.d/urutau-allports.conf
|
||||
install -m 0644 "$here/fail2ban-jail-urutau.local" /etc/fail2ban/jail.d/urutau.local
|
||||
fail2ban-client -t >/dev/null
|
||||
fail2ban-client reload
|
||||
echo "fail2ban jail 'urutau' on; mount /var/log/urutau-enforce:/logs/enforce (rw) in the container"
|
||||
fi
|
||||
Executable
+13
@@ -0,0 +1,13 @@
|
||||
#!/bin/sh
|
||||
# Urutau: writes "<ip> <container name>" for every running container, so the
|
||||
# egress analysis can name workloads whose address changes on each redeploy.
|
||||
set -eu
|
||||
out=/var/log/urutau/containers.map
|
||||
tmp=$(mktemp /var/log/urutau/.containers.map.XXXXXX)
|
||||
trap 'rm -f "$tmp"' EXIT
|
||||
docker ps -q | xargs -r docker inspect -f '{{$n := .Name}}{{range .NetworkSettings.Networks}}{{if .IPAddress}}{{.IPAddress}} {{$n}}
|
||||
{{end}}{{if .GlobalIPv6Address}}{{.GlobalIPv6Address}} {{$n}}
|
||||
{{end}}{{end}}' | sed 's# /# #' | grep -E '^[0-9a-fA-F.:]+ [A-Za-z0-9_.-]{1,128}$' > "$tmp" || true
|
||||
chgrp adm "$tmp"; chmod 0640 "$tmp"
|
||||
mv -f "$tmp" "$out"
|
||||
trap - EXIT
|
||||
@@ -0,0 +1,7 @@
|
||||
[Unit]
|
||||
Description=Urutau: map container addresses to names
|
||||
After=docker.service
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/usr/local/sbin/urutau-containers-map
|
||||
@@ -0,0 +1,10 @@
|
||||
[Unit]
|
||||
Description=Urutau: refresh the container map every minute
|
||||
|
||||
[Timer]
|
||||
OnBootSec=30s
|
||||
OnUnitActiveSec=60s
|
||||
AccuracySec=5s
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@@ -0,0 +1,44 @@
|
||||
#!/usr/sbin/nft -f
|
||||
# Urutau: logs NEW outbound connections (host and containers) so the egress
|
||||
# analysis can spot beaconing, mining, spam and unauthorised scans.
|
||||
# Lives in its own table: it never touches the iptables-nft tables of Docker
|
||||
# or fail2ban, and it only logs (policy accept, no drop).
|
||||
# @WAN@ is replaced by the uplink interface by install.sh.
|
||||
#
|
||||
# Volume control without blinding the beacon detector:
|
||||
# - a (source, destination, protocol, port) seen in the last 2 h is ALWAYS
|
||||
# logged (a beacon repeats the same pair, so a ceiling never hides it);
|
||||
# - a NEW pair is logged under a per-source ceiling of 20/s (burst 100): an
|
||||
# authorised scan (thousands of new pairs) is capped, and one noisy
|
||||
# workload never eats the budget of the others.
|
||||
table inet urutau_egress
|
||||
delete table inet urutau_egress
|
||||
|
||||
table inet urutau_egress {
|
||||
set rl4 { type ipv4_addr; flags dynamic; timeout 2m; size 65535; }
|
||||
set rl6 { type ipv6_addr; flags dynamic; timeout 2m; size 65535; }
|
||||
set seen4 { type ipv4_addr . ipv4_addr . inet_proto . inet_service; flags dynamic, timeout; timeout 2h; size 131072; }
|
||||
set seen6 { type ipv6_addr . ipv6_addr . inet_proto . inet_service; flags dynamic, timeout; timeout 2h; size 131072; }
|
||||
|
||||
chain egress {
|
||||
# known pair: always log, refresh its timer
|
||||
meta nfproto ipv4 meta l4proto { tcp, udp } ip saddr . ip daddr . meta l4proto . th dport @seen4 update @seen4 { ip saddr . ip daddr . meta l4proto . th dport } log prefix "URUTAU-EGRESS: " level info return
|
||||
meta nfproto ipv6 meta l4proto { tcp, udp } ip6 saddr . ip6 daddr . meta l4proto . th dport @seen6 update @seen6 { ip6 saddr . ip6 daddr . meta l4proto . th dport } log prefix "URUTAU-EGRESS: " level info return
|
||||
# new pair: per-source ceiling, then remember it
|
||||
meta nfproto ipv4 meta l4proto { tcp, udp } add @rl4 { ip saddr limit rate 20/second burst 100 packets } add @seen4 { ip saddr . ip daddr . meta l4proto . th dport } log prefix "URUTAU-EGRESS: " level info return
|
||||
meta nfproto ipv6 meta l4proto { tcp, udp } add @rl6 { ip6 saddr limit rate 20/second burst 100 packets } add @seen6 { ip6 saddr . ip6 daddr . meta l4proto . th dport } log prefix "URUTAU-EGRESS: " level info return
|
||||
# other protocols (ICMP...) under the same ceiling, not remembered
|
||||
meta nfproto ipv4 meta l4proto != { tcp, udp } add @rl4 { ip saddr limit rate 20/second burst 100 packets } log prefix "URUTAU-EGRESS: " level info
|
||||
meta nfproto ipv6 meta l4proto != { tcp, udp } add @rl6 { ip6 saddr limit rate 20/second burst 100 packets } log prefix "URUTAU-EGRESS: " level info
|
||||
}
|
||||
|
||||
chain forward_log {
|
||||
type filter hook forward priority filter - 10; policy accept;
|
||||
ct state new oifname "@WAN@" iifname != "@WAN@" jump egress
|
||||
}
|
||||
|
||||
chain output_log {
|
||||
type filter hook output priority filter - 10; policy accept;
|
||||
ct state new oifname "@WAN@" jump egress
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
[Unit]
|
||||
Description=Urutau: egress connection log (nftables)
|
||||
After=network-online.target docker.service
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
RemainAfterExit=yes
|
||||
ExecStart=/usr/sbin/nft -f /etc/urutau/egress.nft
|
||||
ExecStop=/usr/sbin/nft delete table inet urutau_egress
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,6 @@
|
||||
[Unit]
|
||||
Description=Urutau: rotate the egress log by size
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/usr/sbin/logrotate -s /var/lib/logrotate/urutau-egress.status /etc/logrotate.d/urutau-egress
|
||||
@@ -0,0 +1,9 @@
|
||||
[Unit]
|
||||
Description=Urutau: check the egress log size every 10 minutes
|
||||
|
||||
[Timer]
|
||||
OnBootSec=5m
|
||||
OnUnitActiveSec=10m
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@@ -0,0 +1,14 @@
|
||||
/var/log/urutau/egress.log {
|
||||
daily
|
||||
rotate 7
|
||||
maxsize 200M
|
||||
maxage 7
|
||||
compress
|
||||
delaycompress
|
||||
missingok
|
||||
notifempty
|
||||
create 0640 syslog adm
|
||||
postrotate
|
||||
/usr/lib/rsyslog/rsyslog-rotate
|
||||
endscript
|
||||
}
|
||||
@@ -46,6 +46,19 @@ type Config struct {
|
||||
TorExits string // file with Tor exit addresses, one per line; empty disables the check
|
||||
EventsMax string // size cap of the event registry ("512MB", "0" disables it)
|
||||
NoAuth bool
|
||||
// Second firewall (see internal/enforce).
|
||||
Enforce string // off (default), observe or on
|
||||
EnforceLog string // decision file read by the host fail2ban
|
||||
EnforceShare string // off (default) or on: exchange decisions with peers
|
||||
EnforceThreshold int // attack events in 10 minutes that justify a ban
|
||||
EnforceMaxPerMin int // decisions per minute; the excess is dropped
|
||||
|
||||
// Egress analysis (see internal/egress).
|
||||
Egress string // auto (default: on when the log exists), on or off
|
||||
EgressLog string // kernel log of new outbound connections
|
||||
EgressWorkloads string // "name=CIDR|name:<prefix>[,...][:role];..."
|
||||
EgressResolvers string // DNS resolvers allowed (empty: the usual public ones)
|
||||
EgressContainers string // "<ip> <container>" map written by the host kit
|
||||
}
|
||||
|
||||
// DefaultEventsMax is the default size cap of the event registry.
|
||||
@@ -86,6 +99,15 @@ func env(key, def string) string {
|
||||
return def
|
||||
}
|
||||
|
||||
func envInt(key string, def int) int {
|
||||
if v, ok := os.LookupEnv(key); ok {
|
||||
if n, err := strconv.Atoi(strings.TrimSpace(v)); err == nil {
|
||||
return n
|
||||
}
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
// csvFlag accumulates comma separated values; the first use replaces the default.
|
||||
type csvFlag struct {
|
||||
val string
|
||||
@@ -152,6 +174,16 @@ func ParseFlags(name string, args []string) (Config, error) {
|
||||
fs.DurationVar(&c.Retention, "retention", store.DefaultRetention, "how long data is kept, at most 720h (URUTAU_RETENTION)")
|
||||
fs.StringVar(&c.TorExits, "tor-exits", env("URUTAU_TOR_EXITS", ""), "file with Tor exit node addresses, one per line, reloaded every 24 h when it changes; empty disables (URUTAU_TOR_EXITS)")
|
||||
fs.StringVar(&c.EventsMax, "events-max", env("URUTAU_EVENTS_MAX", DefaultEventsMax), "size cap of the event registry in <data-dir>/events, 0 disables it (URUTAU_EVENTS_MAX)")
|
||||
fs.StringVar(&c.Enforce, "enforce", env("URUTAU_ENFORCE", "off"), "second firewall: off, observe (decide in memory only) or on (write decisions for the host fail2ban) (URUTAU_ENFORCE)")
|
||||
fs.StringVar(&c.EnforceLog, "enforce-log", env("URUTAU_ENFORCE_LOG", "/logs/enforce/decisions.log"), "decision file appended in --enforce=on (URUTAU_ENFORCE_LOG)")
|
||||
fs.StringVar(&c.EnforceShare, "enforce-share", env("URUTAU_ENFORCE_SHARE", "off"), "on: exchange decisions with peers, each side applies its own exclusions (URUTAU_ENFORCE_SHARE)")
|
||||
fs.IntVar(&c.EnforceThreshold, "enforce-threshold", envInt("URUTAU_ENFORCE_THRESHOLD", 5), "attack events in 10 minutes that justify a ban (URUTAU_ENFORCE_THRESHOLD)")
|
||||
fs.StringVar(&c.Egress, "egress", env("URUTAU_EGRESS", "auto"), "egress analysis: auto (on when --egress-log exists), on or off (URUTAU_EGRESS)")
|
||||
fs.StringVar(&c.EgressLog, "egress-log", env("URUTAU_EGRESS_LOG", "/logs/host/egress.log"), "kernel log of new outbound connections written by the host kit (URUTAU_EGRESS_LOG)")
|
||||
fs.StringVar(&c.EgressWorkloads, "egress-workloads", env("URUTAU_EGRESS_WORKLOADS", ""), "workloads: \"ciberlab=name:<container prefix>:scanner;mail=10.0.7.0/24:mail\" (URUTAU_EGRESS_WORKLOADS)")
|
||||
fs.StringVar(&c.EgressResolvers, "egress-resolvers", env("URUTAU_EGRESS_RESOLVERS", ""), "DNS resolvers allowed, comma separated; empty: the usual public ones (URUTAU_EGRESS_RESOLVERS)")
|
||||
fs.StringVar(&c.EgressContainers, "egress-containers", env("URUTAU_EGRESS_CONTAINERS", "/logs/host/containers.map"), "\"<ip> <container>\" map written by the host kit (URUTAU_EGRESS_CONTAINERS)")
|
||||
fs.IntVar(&c.EnforceMaxPerMin, "enforce-max-per-min", envInt("URUTAU_ENFORCE_MAX_PER_MIN", 60), "most decisions per minute, the excess is dropped and counted (URUTAU_ENFORCE_MAX_PER_MIN)")
|
||||
fs.BoolVar(&c.NoAuth, "insecure-no-auth", false, "disable authentication; only allowed on a loopback bind")
|
||||
if v := os.Getenv("URUTAU_GEO_UPDATE"); v != "" {
|
||||
if d, err := time.ParseDuration(v); err == nil {
|
||||
@@ -210,6 +242,30 @@ func (c Config) Validate(token string) ([]fed.Peer, error) {
|
||||
if v := strings.ToLower(c.PeerBlocklist); v != "" && v != "on" && v != "off" {
|
||||
return nil, fmt.Errorf("--peer-blocklist must be on or off")
|
||||
}
|
||||
if c.Enforce != "" || c.EnforceShare != "" { // a Config built by hand may leave them unset
|
||||
switch strings.ToLower(c.Enforce) {
|
||||
case "", "off", "observe", "on":
|
||||
default:
|
||||
return nil, fmt.Errorf("--enforce must be off, observe or on")
|
||||
}
|
||||
if v := strings.ToLower(c.EnforceShare); v != "" && v != "off" && v != "on" {
|
||||
return nil, fmt.Errorf("--enforce-share must be on or off")
|
||||
}
|
||||
if c.EnforceThreshold < 1 || c.EnforceThreshold > 1000 {
|
||||
return nil, fmt.Errorf("--enforce-threshold must be between 1 and 1000")
|
||||
}
|
||||
if c.EnforceMaxPerMin < 1 || c.EnforceMaxPerMin > 10000 {
|
||||
return nil, fmt.Errorf("--enforce-max-per-min must be between 1 and 10000")
|
||||
}
|
||||
}
|
||||
switch strings.ToLower(c.Egress) {
|
||||
case "", "auto", "on", "off":
|
||||
default:
|
||||
return nil, fmt.Errorf("--egress must be auto, on or off")
|
||||
}
|
||||
if strings.EqualFold(c.Enforce, "on") && c.EnforceLog == "" {
|
||||
return nil, fmt.Errorf("--enforce=on needs --enforce-log")
|
||||
}
|
||||
var peers []fed.Peer
|
||||
seen := map[string]bool{}
|
||||
envSeen := map[string]string{}
|
||||
|
||||
@@ -56,6 +56,7 @@ func Doctor(c Config, w io.Writer, asJSON bool) bool {
|
||||
os.Remove(f.Name())
|
||||
add("data-dir", "ok", fmt.Sprintf("%s writable", filepath.Clean(c.DataDir)))
|
||||
}
|
||||
doctorEnforce(c, add)
|
||||
geoInfo := doctorGeo(c, add)
|
||||
stateInfo := doctorState(c, add)
|
||||
ok := true
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/server"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
// newEgress builds the egress analysis, or returns nil when it is off (or in
|
||||
// auto mode without the host log).
|
||||
func newEgress(c Config, st *store.Store, log *slog.Logger) (*egress.Source, error) {
|
||||
mode := strings.ToLower(c.Egress)
|
||||
if mode == "off" || c.EgressLog == "" {
|
||||
return nil, nil
|
||||
}
|
||||
if mode == "" || mode == "auto" {
|
||||
if _, err := os.Stat(c.EgressLog); err != nil {
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
var allow []netip.Prefix
|
||||
if nets, err := core.ParseCIDRs(c.Trusted); err == nil {
|
||||
for _, n := range nets {
|
||||
if p, err := netip.ParsePrefix(n.String()); err == nil {
|
||||
allow = append(allow, p)
|
||||
}
|
||||
}
|
||||
}
|
||||
allow = append(allow, egressExtraAllow(c)...)
|
||||
eng, err := egress.New(egress.Config{
|
||||
Workloads: c.EgressWorkloads,
|
||||
Resolvers: c.EgressResolvers,
|
||||
Allow: allow,
|
||||
Containers: c.EgressContainers,
|
||||
Geo: func(ip string) (string, string, string) {
|
||||
g := st.GeoOf(ip)
|
||||
asn := ""
|
||||
if g.ASN != 0 {
|
||||
asn = "AS" + strconv.FormatUint(uint64(g.ASN), 10)
|
||||
}
|
||||
return g.CC, asn, g.ASOrg
|
||||
},
|
||||
BadDst: func(a netip.Addr) (bool, string) {
|
||||
if intel.IsTorExit(a) {
|
||||
return true, "tor-exit"
|
||||
}
|
||||
if st.KnownHostile(a.String()) {
|
||||
return true, "attacked-us"
|
||||
}
|
||||
return false, ""
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
server.SetEgress(eng)
|
||||
log.Info("egress analysis on", "log", c.EgressLog)
|
||||
return egress.NewSource(c.EgressLog, eng, log), nil
|
||||
}
|
||||
|
||||
// egressExtraAllow adds to the egress Allow list the addresses of the peers and
|
||||
// the CIDRs of URUTAU_EGRESS_ALLOW (legitimate periodic pollers).
|
||||
func egressExtraAllow(c Config) []netip.Prefix {
|
||||
var out []netip.Prefix
|
||||
for _, ps := range c.Peers {
|
||||
p, err := fed.ParsePeer(ps)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if u, err := url.Parse(p.URL); err == nil && u.Hostname() != "" {
|
||||
for _, a := range resolveHost(u.Hostname()) {
|
||||
out = append(out, netip.PrefixFrom(a, a.BitLen()))
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, s := range strings.Split(os.Getenv("URUTAU_EGRESS_ALLOW"), ",") {
|
||||
if s = strings.TrimSpace(s); s == "" {
|
||||
continue
|
||||
}
|
||||
if p, err := netip.ParsePrefix(s); err == nil {
|
||||
out = append(out, p.Masked())
|
||||
} else if a, err := netip.ParseAddr(s); err == nil {
|
||||
a = a.Unmap()
|
||||
out = append(out, netip.PrefixFrom(a, a.BitLen()))
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
// newEnforce builds the second firewall and hooks it into the store; nil when off.
|
||||
func newEnforce(c Config, st *store.Store, peers []fed.Peer, en enricher) *enforce.Engine {
|
||||
mode := strings.ToLower(c.Enforce)
|
||||
if mode != enforce.ModeObserve && mode != enforce.ModeOn {
|
||||
return nil
|
||||
}
|
||||
trusted, _ := core.ParseCIDRs(c.Ignore + "," + c.Trusted)
|
||||
var hosts []string
|
||||
for _, p := range peers {
|
||||
if u, err := url.Parse(p.URL); err == nil && u.Hostname() != "" {
|
||||
hosts = append(hosts, u.Hostname())
|
||||
}
|
||||
}
|
||||
e := enforce.New(enforce.Config{
|
||||
Mode: mode, Path: c.EnforceLog, StatePath: filepath.Join(c.DataDir, "enforce.json"), Host: c.Name,
|
||||
Threshold: c.EnforceThreshold, MaxPerMin: c.EnforceMaxPerMin, Share: strings.EqualFold(c.EnforceShare, "on"),
|
||||
Trusted: trusted, PeerHosts: hosts, InfraHosts: hosts, Resolve: resolveHost,
|
||||
Crawler: func(ip string, uas []string) bool { v := st.FCrDNS(ip, uas); return v != nil && *v },
|
||||
Geo: func(ip string) (string, uint32, string) {
|
||||
if en.g == nil {
|
||||
return "", 0, ""
|
||||
}
|
||||
g := en.Geo(ip)
|
||||
return g.CC, g.ASN, g.ASOrg
|
||||
},
|
||||
})
|
||||
st.SetIngestHook(e.Observe)
|
||||
return e
|
||||
}
|
||||
|
||||
func resolveHost(h string) []netip.Addr {
|
||||
if a, err := netip.ParseAddr(h); err == nil {
|
||||
return []netip.Addr{a.Unmap()}
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
ips, err := net.DefaultResolver.LookupNetIP(ctx, "ip", h)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
for i := range ips {
|
||||
ips[i] = ips[i].Unmap()
|
||||
}
|
||||
return ips
|
||||
}
|
||||
|
||||
// shareDecisions pulls the decisions of every peer and pushes the local ones, every 30 s.
|
||||
func shareDecisions(ctx context.Context, hub *fed.Hub, e *enforce.Engine, log *slog.Logger) {
|
||||
pulled := map[string]int64{}
|
||||
pushed := map[string]int64{}
|
||||
t := time.NewTicker(30 * time.Second)
|
||||
defer t.Stop()
|
||||
for {
|
||||
for _, p := range hub.Peers {
|
||||
start := time.Now().Unix()
|
||||
var in struct {
|
||||
Decisions []enforce.Wire `json:"decisions"`
|
||||
}
|
||||
if err := hub.Get(ctx, p, fmt.Sprintf("/api/v1/peer/decisions?since=%d", pulled[p.Name]), &in); err == nil {
|
||||
e.AcceptPeer(p.Name, in.Decisions)
|
||||
pulled[p.Name] = start - 5
|
||||
} else if ctx.Err() == nil {
|
||||
log.Debug("enforce: pull failed", "peer", p.Name, "err", err)
|
||||
}
|
||||
if mine := e.LocalSince(pushed[p.Name]); len(mine) > 0 {
|
||||
if err := hub.PostJSON(ctx, p, "/api/v1/peer/decisions?from="+url.QueryEscape(e.Host()), map[string]any{"decisions": mine}); err == nil {
|
||||
pushed[p.Name] = start
|
||||
} else if ctx.Err() == nil {
|
||||
log.Debug("enforce: push failed", "peer", p.Name, "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// doctorEnforce reports the mode of the second firewall and its file.
|
||||
func doctorEnforce(c Config, add func(name, status, detail string)) {
|
||||
mode := strings.ToLower(c.Enforce)
|
||||
if mode == "" || mode == "off" {
|
||||
add("enforce", "off", "disabled (--enforce=off)")
|
||||
return
|
||||
}
|
||||
w := enforce.Writable(c.EnforceLog)
|
||||
detail := fmt.Sprintf("mode=%s share=%s threshold=%d file=%s writable=%v", mode, strings.ToLower(orDefault(c.EnforceShare, "off")), c.EnforceThreshold, c.EnforceLog, w)
|
||||
switch {
|
||||
case mode == "on" && !w:
|
||||
add("enforce", "fail", detail)
|
||||
case !w:
|
||||
add("enforce", "warn", detail)
|
||||
default:
|
||||
add("enforce", "ok", detail)
|
||||
}
|
||||
if mode == "on" {
|
||||
if n, tot := cloudflareClients(c.TraefikLog); n > 0 {
|
||||
add("enforce-cdn", "warn", fmt.Sprintf("%d of the last %d requests in %s come from Cloudflare addresses: Traefik is not "+
|
||||
"restoring the real client IP (set entryPoints.*.forwardedHeaders.trustedIPs to the Cloudflare ranges); "+
|
||||
"Cloudflare is never banned, but the real attackers stay invisible", n, tot, c.TraefikLog))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// cloudflareClients counts, in the tail of the Traefik JSON access log, the
|
||||
// requests whose ClientHost is a Cloudflare address.
|
||||
func cloudflareClients(path string) (cf, total int) {
|
||||
if path == "" {
|
||||
return 0, 0
|
||||
}
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return 0, 0
|
||||
}
|
||||
defer f.Close()
|
||||
const tail = 512 << 10
|
||||
if fi, err := f.Stat(); err == nil && fi.Size() > tail {
|
||||
f.Seek(fi.Size()-tail, io.SeekStart)
|
||||
}
|
||||
sc := bufio.NewScanner(f)
|
||||
sc.Buffer(make([]byte, 0, 64<<10), 1<<20)
|
||||
for sc.Scan() {
|
||||
var l struct {
|
||||
ClientHost string `json:"ClientHost"`
|
||||
}
|
||||
if json.Unmarshal(sc.Bytes(), &l) != nil || l.ClientHost == "" {
|
||||
continue
|
||||
}
|
||||
a, err := netip.ParseAddr(l.ClientHost)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
total++
|
||||
if enforce.IsCloudflare(a) {
|
||||
cf++
|
||||
}
|
||||
}
|
||||
return cf, total
|
||||
}
|
||||
@@ -98,6 +98,18 @@ func Serve(c Config) error {
|
||||
bindHost, _, _ := net.SplitHostPort(c.Bind)
|
||||
h := server.New(server.Options{Token: token, PeerTokens: c.PeerTokens, PeerAllow: allow, TrustedProxy: tproxy, Ignore: ign,
|
||||
AllowHosts: []string{bindHost}, NoAuth: c.NoAuth, LocalBlocklist: strings.EqualFold(c.PeerBlocklist, "off"), Version: Version, Store: st, Hub: hub})
|
||||
egressSrc, err := newEgress(c, st, log)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if egressSrc != nil {
|
||||
extra := runner.Extra
|
||||
runner.Extra = func() []store.SourceStatus { return append(extra(), egressSrc.Status()) }
|
||||
}
|
||||
eng := newEnforce(c, st, peers, en)
|
||||
if eng != nil {
|
||||
server.SetEnforce(eng)
|
||||
}
|
||||
ln, err := net.Listen("tcp", c.Bind)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -110,6 +122,9 @@ func Serve(c Config) error {
|
||||
go func() { defer wg.Done(); elog.Run(ctx) }()
|
||||
}
|
||||
runner.Start(ctx, offsets, &wg)
|
||||
if egressSrc != nil {
|
||||
egressSrc.Start(ctx, &wg)
|
||||
}
|
||||
wg.Add(2)
|
||||
go func() { defer wg.Done(); rd.Run(ctx) }()
|
||||
go func() {
|
||||
@@ -140,6 +155,14 @@ func Serve(c Config) error {
|
||||
wg.Add(1)
|
||||
go func() { defer wg.Done(); hub.Run(ctx) }()
|
||||
}
|
||||
if eng != nil {
|
||||
wg.Add(1)
|
||||
go func() { defer wg.Done(); eng.Run(ctx) }()
|
||||
if hub != nil && eng.Share() {
|
||||
wg.Add(1)
|
||||
go func() { defer wg.Done(); shareDecisions(ctx, hub, eng, log) }()
|
||||
}
|
||||
}
|
||||
log.Info("urutau started", "version", Version, "name", c.Name, "bind", ln.Addr().String(), "peers", len(peers), "auth", !c.NoAuth)
|
||||
errc := make(chan error, 1)
|
||||
go func() { errc <- srv.Serve(ln) }()
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -195,3 +196,64 @@ func TestIPDetailConsistentOnSyntheticLogs(t *testing.T) {
|
||||
t.Skip("synthetic data sets not available")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnforceConfig(t *testing.T) {
|
||||
c, err := ParseFlags("x", []string{"--insecure-no-auth", "--bind", "127.0.0.1:1"})
|
||||
if err != nil || c.Enforce != "off" || c.EnforceLog != "/logs/enforce/decisions.log" || c.EnforceShare != "off" || c.EnforceThreshold != 5 || c.EnforceMaxPerMin != 60 {
|
||||
t.Fatalf("%+v %v", c, err)
|
||||
}
|
||||
for _, bad := range [][]string{{"--enforce=maybe"}, {"--enforce-share=x"}, {"--enforce-threshold=0"}, {"--enforce-max-per-min=0"}} {
|
||||
c, err := ParseFlags("x", append([]string{"--insecure-no-auth", "--bind", "127.0.0.1:1", "--data-dir", t.TempDir()}, bad...))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if _, err := c.Validate(""); err == nil {
|
||||
t.Errorf("%v accepted", bad)
|
||||
}
|
||||
}
|
||||
t.Setenv("URUTAU_ENFORCE", "observe")
|
||||
t.Setenv("URUTAU_ENFORCE_THRESHOLD", "9")
|
||||
c, _ = ParseFlags("x", nil)
|
||||
if c.Enforce != "observe" || c.EnforceThreshold != 9 {
|
||||
t.Fatalf("env %+v", c)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDoctorEnforce(t *testing.T) {
|
||||
var got []Check
|
||||
add := func(n, s, d string) { got = append(got, Check{n, s, d}) }
|
||||
doctorEnforce(Config{Enforce: "on", EnforceLog: t.TempDir() + "/x/d.log", EnforceThreshold: 5}, add)
|
||||
doctorEnforce(Config{Enforce: "on", EnforceLog: "/proc/nope/d.log"}, add)
|
||||
doctorEnforce(Config{Enforce: "off"}, add)
|
||||
if got[0].Status != "ok" || !strings.Contains(got[0].Detail, "mode=on") || got[1].Status != "fail" || got[2].Status != "off" {
|
||||
t.Fatalf("%+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDoctorEnforceCloudflare(t *testing.T) {
|
||||
lg := filepath.Join(t.TempDir(), "access.log")
|
||||
os.WriteFile(lg, []byte(`{"ClientHost":"104.16.1.1"}`+"\n"+`{"ClientHost":"203.0.114.5"}`+"\n"), 0o600)
|
||||
var got []Check
|
||||
add := func(n, s, d string) { got = append(got, Check{n, s, d}) }
|
||||
doctorEnforce(Config{Enforce: "on", EnforceLog: t.TempDir() + "/x/d.log", TraefikLog: lg}, add)
|
||||
if len(got) != 2 || got[1].Name != "enforce-cdn" || got[1].Status != "warn" {
|
||||
t.Fatalf("%+v", got)
|
||||
}
|
||||
got = nil
|
||||
doctorEnforce(Config{Enforce: "observe", EnforceLog: t.TempDir() + "/x/d.log", TraefikLog: lg}, add)
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("%+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEgressExtraAllow(t *testing.T) {
|
||||
t.Setenv("URUTAU_EGRESS_ALLOW", "203.0.113.0/24, 198.51.100.7 ,bad")
|
||||
got := egressExtraAllow(Config{Peers: []string{"p=https://192.0.2.9:8443"}})
|
||||
var s []string
|
||||
for _, p := range got {
|
||||
s = append(s, p.String())
|
||||
}
|
||||
if strings.Join(s, " ") != "192.0.2.9/32 203.0.113.0/24 198.51.100.7/32" {
|
||||
t.Fatalf("%v", s)
|
||||
}
|
||||
}
|
||||
@@ -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.3.0"
|
||||
var Version = "1.4.0"
|
||||
@@ -0,0 +1,514 @@
|
||||
package egress
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"net/netip"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
var t0 = time.Date(2026, 11, 14, 0, 0, 0, 0, time.UTC)
|
||||
|
||||
func ip(s string) netip.Addr { return netip.MustParseAddr(s) }
|
||||
|
||||
func mk(t time.Time, src, dst, proto string, dport uint16) Event {
|
||||
return Event{Time: t, Src: ip(src), Dst: ip(dst), Proto: proto, SPort: 40000, DPort: dport, In: "br-1", Out: "enp0s6"}
|
||||
}
|
||||
|
||||
func newEng(t *testing.T, c Config) *Engine {
|
||||
t.Helper()
|
||||
if c.Now == nil {
|
||||
c.Now = func() time.Time { return t0.Add(30 * 24 * time.Hour) }
|
||||
}
|
||||
e, err := New(c)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
func kinds(r Report, kind string) []Finding {
|
||||
var o []Finding
|
||||
for _, f := range r.Findings {
|
||||
if f.Kind == kind {
|
||||
o = append(o, f)
|
||||
}
|
||||
}
|
||||
return o
|
||||
}
|
||||
|
||||
func rep(e *Engine) Report { return e.Report(t0.Unix()-86400, t0.Add(14*24*time.Hour).Unix()) }
|
||||
|
||||
func TestParse(t *testing.T) {
|
||||
now := time.Date(2026, 11, 14, 23, 0, 0, 0, time.UTC)
|
||||
v4 := `2026-11-14T22:01:02.123456+00:00 oracle kernel: [123.4] URUTAU-EGRESS: IN=br-1a2b OUT=enp0s6 MAC=aa SRC=10.0.3.5 DST=93.184.216.34 LEN=60 TOS=0x00 PREC=0x00 TTL=63 ID=1 DF PROTO=TCP SPT=40000 DPT=443 WINDOW=64240 RES=0x00 SYN URGP=0`
|
||||
ev, err := ParseLine([]byte(v4), now)
|
||||
if err != nil || ev.Proto != "tcp" || ev.DPort != 443 || ev.SPort != 40000 || ev.Dst.String() != "93.184.216.34" || ev.Host || ev.Time.Hour() != 22 || ev.In != "br-1a2b" {
|
||||
t.Fatalf("v4: %+v %v", ev, err)
|
||||
}
|
||||
v6 := `2026-11-14T22:01:02+00:00 oracle kernel: URUTAU-EGRESS: IN=br-1 OUT=enp0s6 SRC=fd00::5 DST=2606:4700:4700::1111 LEN=80 TC=0 HOPLIMIT=63 FLOWLBL=0 PROTO=UDP SPT=5353 DPT=53 LEN=40`
|
||||
ev, err = ParseLine([]byte(v6), now)
|
||||
if err != nil || ev.Proto != "udp" || ev.DPort != 53 || !ev.Dst.Is6() {
|
||||
t.Fatalf("v6: %+v %v", ev, err)
|
||||
}
|
||||
ic := `Nov 14 22:01:02 oracle kernel: [1.0] URUTAU-EGRESS: IN=br-1 OUT=enp0s6 SRC=10.0.3.5 DST=1.1.1.1 LEN=84 PROTO=ICMP TYPE=8 CODE=0 ID=1`
|
||||
ev, err = ParseLine([]byte(ic), now)
|
||||
if err != nil || ev.Proto != "icmp" || ev.DPort != 0 || ev.Time.Year() != 2026 || ev.Time.Month() != 11 {
|
||||
t.Fatalf("icmp: %+v %v", ev, err)
|
||||
}
|
||||
ic6 := `Nov 4 22:01:02 oracle kernel: URUTAU-EGRESS: IN=br-1 OUT=x SRC=fd00::5 DST=fd00::6 PROTO=ICMPv6 TYPE=128 CODE=0`
|
||||
if ev, err = ParseLine([]byte(ic6), now); err != nil || ev.Proto != "icmp" || ev.Time.Day() != 4 {
|
||||
t.Fatalf("icmp6: %+v %v", ev, err)
|
||||
}
|
||||
host := `2026-11-14T22:01:02+00:00 oracle kernel: URUTAU-EGRESS: IN= OUT=enp0s6 SRC=10.0.0.2 DST=8.8.8.8 PROTO=TCP SPT=1 DPT=443 SYN`
|
||||
if ev, err = ParseLine([]byte(host), now); err != nil || !ev.Host || ev.In != "" {
|
||||
t.Fatalf("host: %+v %v", ev, err)
|
||||
}
|
||||
// December line read in January belongs to the previous year
|
||||
dec := `Dec 31 23:59:00 h kernel: URUTAU-EGRESS: IN=a OUT=b SRC=1.2.3.4 DST=5.6.7.8 PROTO=TCP DPT=1`
|
||||
if ev, err = ParseLine([]byte(dec), time.Date(2027, 1, 1, 0, 5, 0, 0, time.UTC)); err != nil || ev.Time.Year() != 2026 {
|
||||
t.Fatalf("year: %+v %v", ev, err)
|
||||
}
|
||||
for _, bad := range []string{"", "garbage", "URUTAU-EGRESS: IN=a OUT=b SRC=nope DST=1.1.1.1 PROTO=TCP", "URUTAU-EGRESS: IN=a SRC=1.1.1.1 DST=2.2.2.2", "\x00\xff URUTAU-EGRESS: ===", "sshd: Accepted publickey"} {
|
||||
if _, err := ParseLine([]byte(bad), now); err == nil {
|
||||
t.Fatalf("expected error for %q", bad)
|
||||
}
|
||||
}
|
||||
e := newEng(t, Config{})
|
||||
e.Ingest([]byte("garbage"))
|
||||
e.Ingest([]byte(v4))
|
||||
if e.malformed.Load() != 1 || e.lines.Load() != 1 {
|
||||
t.Fatalf("counters %d %d", e.malformed.Load(), e.lines.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkloadsAndContainers(t *testing.T) {
|
||||
e := newEng(t, Config{Workloads: "ciberlab=name:jhxint9g9uz91:scanner;mail=10.0.7.0/24,10.0.8.4/32:mail;lab=10.0.5.0/24"})
|
||||
e.SetContainers(map[netip.Addr]string{ip("172.18.0.4"): "jhxint9g9uz91-20260101123456", ip("172.18.0.9"): "runner-q620o15zg7-1700000000000"})
|
||||
cases := []struct {
|
||||
ev Event
|
||||
name, role string
|
||||
}{
|
||||
{mk(t0, "172.18.0.4", "1.1.1.1", "tcp", 1), "ciberlab", RoleScanner},
|
||||
{mk(t0, "172.18.0.9", "1.1.1.1", "tcp", 1), "runner-q620o15zg7", RoleDefault},
|
||||
{mk(t0, "10.0.8.4", "1.1.1.1", "tcp", 1), "mail", RoleMail},
|
||||
{mk(t0, "10.0.5.77", "1.1.1.1", "tcp", 1), "lab", RoleDefault},
|
||||
{mk(t0, "10.0.9.9", "1.1.1.1", "tcp", 1), "container 10.0.9.9", RoleDefault},
|
||||
{Event{Time: t0, Src: ip("10.0.0.2"), Dst: ip("1.1.1.1"), Proto: "tcp", Host: true}, "host", RoleDefault},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if n, r := e.resolve(c.ev); n != c.name || r != c.role {
|
||||
t.Errorf("%v: got %s/%s want %s/%s", c.ev.Src, n, r, c.name, c.role)
|
||||
}
|
||||
}
|
||||
// IP changes: the map in force at Ingest wins
|
||||
e.SetContainers(map[netip.Addr]string{ip("172.18.0.5"): "jhxint9g9uz91-20260102000000"})
|
||||
if n, _ := e.resolve(mk(t0, "172.18.0.5", "1.1.1.1", "tcp", 1)); n != "ciberlab" {
|
||||
t.Errorf("remap: %s", n)
|
||||
}
|
||||
for _, bad := range []string{"x", "a=", "a=notip:scanner", "a=name:bad name"} {
|
||||
if _, err := ParseWorkloads(bad); err == nil {
|
||||
t.Errorf("expected error for %q", bad)
|
||||
}
|
||||
}
|
||||
// containers.map file: invalid lines skipped, reload on mtime change
|
||||
dir := t.TempDir()
|
||||
p := filepath.Join(dir, "containers.map")
|
||||
os.WriteFile(p, []byte("172.18.0.4 jhxint9g9uz91-1700000000\nbad line here\n999.1.1.1 x\nfd00::7 six-node\n1.2.3.4 bad/name\n"), 0o644)
|
||||
m, err := LoadContainers(p)
|
||||
if err != nil || len(m) != 2 || m[ip("fd00::7")] != "six-node" {
|
||||
t.Fatalf("map: %v %v", m, err)
|
||||
}
|
||||
clock := t0
|
||||
e2 := newEng(t, Config{Containers: p, Workloads: "c=name:jhxint9g9uz91:scanner", Now: func() time.Time { return clock }})
|
||||
e2.IngestEvent(mk(t0, "172.18.0.4", "5.5.5.5", "tcp", 443))
|
||||
if _, ok := e2.ws["c"]; !ok {
|
||||
t.Fatalf("map file not applied: %v", e2.ws)
|
||||
}
|
||||
os.WriteFile(p, []byte("172.18.0.4 other-1700000000\n"), 0o644)
|
||||
os.Chtimes(p, clock.Add(time.Hour), clock.Add(time.Hour))
|
||||
clock = clock.Add(time.Minute)
|
||||
e2.IngestEvent(mk(t0.Add(time.Minute), "172.18.0.4", "5.5.5.5", "tcp", 443))
|
||||
if _, ok := e2.ws["other"]; !ok {
|
||||
t.Fatalf("map file not reloaded: %v", e2.ws)
|
||||
}
|
||||
}
|
||||
|
||||
func feedBeacon(e *Engine, src, dst string, dport uint16, start time.Time, n int, step time.Duration, jitter float64, rnd *rand.Rand) {
|
||||
t := start
|
||||
for i := 0; i < n; i++ {
|
||||
pr := "tcp"
|
||||
if dport == 123 {
|
||||
pr = "udp"
|
||||
}
|
||||
e.IngestEvent(mk(t, src, dst, pr, dport))
|
||||
j := 1 + (rnd.Float64()*2-1)*jitter
|
||||
t = t.Add(time.Duration(float64(step) * j))
|
||||
}
|
||||
}
|
||||
|
||||
func TestBeaconPositive(t *testing.T) {
|
||||
bad := func(a netip.Addr) (bool, string) { return a == ip("198.51.100.99"), "known attacker" }
|
||||
e := newEng(t, Config{BadDst: bad})
|
||||
rnd := rand.New(rand.NewSource(1))
|
||||
feedBeacon(e, "10.0.3.5", "203.0.113.7", 443, t0, 50, 60*time.Second, 0.05, rnd)
|
||||
feedBeacon(e, "10.0.3.5", "198.51.100.99", 8443, t0, 50, 60*time.Second, 0.05, rnd)
|
||||
r := rep(e)
|
||||
var got, hi *Finding
|
||||
for i, f := range kinds(r, "beacon") {
|
||||
if f.Dst == "203.0.113.7" {
|
||||
got = &kinds(r, "beacon")[i]
|
||||
}
|
||||
if f.Dst == "198.51.100.99" {
|
||||
hi = &kinds(r, "beacon")[i]
|
||||
}
|
||||
}
|
||||
if got == nil || got.Severity != "medium" || got.IntervalS < 55 || got.IntervalS > 65 || got.Jitter > 0.1 || got.Count < 40 || got.Last <= got.First {
|
||||
t.Fatalf("beacon: %+v", got)
|
||||
}
|
||||
if hi == nil || hi.Severity != "high" {
|
||||
t.Fatalf("attacker beacon: %+v", hi)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBeaconNegatives(t *testing.T) {
|
||||
e := newEng(t, Config{Workloads: "sc=10.0.5.0/24:scanner", Allow: []netip.Prefix{netip.MustParsePrefix("192.0.2.0/24")}})
|
||||
rnd := rand.New(rand.NewSource(2))
|
||||
// random intervals
|
||||
tt := t0
|
||||
for i := 0; i < 60; i++ {
|
||||
e.IngestEvent(mk(tt, "10.0.3.5", "203.0.113.8", "tcp", 443))
|
||||
tt = tt.Add(time.Duration(5+rnd.Intn(600)) * time.Second)
|
||||
}
|
||||
// NTP, allowed dst, allowed resolver
|
||||
feedBeacon(e, "10.0.3.5", "203.0.113.9", 123, t0, 50, 128*time.Second, 0, rnd)
|
||||
feedBeacon(e, "10.0.3.5", "192.0.2.4", 443, t0, 50, 60*time.Second, 0, rnd)
|
||||
for i := 0; i < 50; i++ {
|
||||
ev := mk(t0.Add(time.Duration(i)*time.Minute), "10.0.3.5", "1.1.1.1", "udp", 53)
|
||||
e.IngestEvent(ev)
|
||||
}
|
||||
// daily scan: 8 days, 60 targets each, scanner role; and hourly scan
|
||||
for d := 0; d < 8; d++ {
|
||||
for i := 0; i < 60; i++ {
|
||||
e.IngestEvent(mk(t0.Add(time.Duration(d)*24*time.Hour+time.Duration(i)*time.Second), "10.0.5.2", fmt.Sprintf("203.0.113.%d", 100+i), "tcp", 22))
|
||||
}
|
||||
}
|
||||
for h := 0; h < 12; h++ {
|
||||
for i := 0; i < 60; i++ {
|
||||
e.IngestEvent(mk(t0.Add(10*24*time.Hour+time.Duration(h)*time.Hour+time.Duration(i)*time.Second), "10.0.5.2", fmt.Sprintf("198.18.0.%d", 1+i), "tcp", 22))
|
||||
}
|
||||
}
|
||||
if f := kinds(rep(e), "beacon"); len(f) != 0 {
|
||||
t.Fatalf("unexpected beacons: %+v", f)
|
||||
}
|
||||
if f := kinds(rep(e), "dns_bypass"); len(f) != 0 {
|
||||
t.Fatalf("usual resolver flagged: %+v", f)
|
||||
}
|
||||
}
|
||||
|
||||
func fanOut(e *Engine, src string, start time.Time, n int, port uint16) {
|
||||
fanOutNet(e, src, "198.18", start, n, port)
|
||||
}
|
||||
|
||||
func fanOutNet(e *Engine, src, net string, start time.Time, n int, port uint16) {
|
||||
for i := 0; i < n; i++ {
|
||||
e.IngestEvent(mk(start.Add(time.Duration(i)*time.Second), src, fmt.Sprintf("%s.%d.%d", net, i/200, 1+i%200), "tcp", port))
|
||||
}
|
||||
}
|
||||
|
||||
func TestScannerSuppressedVsDefault(t *testing.T) {
|
||||
bad := func(a netip.Addr) (bool, string) { return a == ip("198.18.0.5"), "attacker" }
|
||||
e := newEng(t, Config{Workloads: "ciberlab=10.0.5.0/24:scanner", BadDst: bad})
|
||||
fanOut(e, "10.0.5.2", t0, 300, 80)
|
||||
fanOutNet(e, "10.0.9.9", "198.19", t0, 300, 80) // default workload
|
||||
r := rep(e)
|
||||
var sc, df WorkloadOut
|
||||
for _, w := range r.Workloads {
|
||||
switch w.Name {
|
||||
case "ciberlab":
|
||||
sc = w
|
||||
case "container 10.0.9.9":
|
||||
df = w
|
||||
}
|
||||
}
|
||||
if sc.Suppressed < 240 || sc.Conns > 60 {
|
||||
t.Fatalf("scanner not suppressed: %+v", sc)
|
||||
}
|
||||
if df.Suppressed != 0 || df.Conns != 300 {
|
||||
t.Fatalf("default must not be suppressed: %+v", df)
|
||||
}
|
||||
scan := kinds(r, "scan")
|
||||
if len(scan) != 1 || scan[0].Workload != "container 10.0.9.9" || scan[0].Severity != "high" {
|
||||
t.Fatalf("scan findings: %+v", scan)
|
||||
}
|
||||
if len(r.Scanner.Bursts) != 1 {
|
||||
t.Fatalf("bursts: %+v", r.Scanner.Bursts)
|
||||
}
|
||||
b := r.Scanner.Bursts[0]
|
||||
if b.Workload != "ciberlab" || b.Targets < 240 || len(b.Nets) == 0 || b.Ports[0] != 80 || b.BadDstHit != 1 {
|
||||
t.Fatalf("burst: %+v", b)
|
||||
}
|
||||
for _, f := range kinds(r, "bad_dst") {
|
||||
if f.Workload == "ciberlab" {
|
||||
t.Fatalf("bad_dst of scanner inside a burst must only be counted: %+v", f)
|
||||
}
|
||||
}
|
||||
for _, d := range r.TopDst {
|
||||
for _, w := range d.Workloads {
|
||||
if w == "ciberlab" {
|
||||
t.Fatalf("scanner burst flow in top_dst: %+v", d)
|
||||
}
|
||||
}
|
||||
}
|
||||
// the burst closes after 5 minutes of quiet and a later flow is normal
|
||||
e.IngestEvent(mk(t0.Add(time.Hour), "10.0.5.2", "203.0.113.50", "tcp", 443))
|
||||
r = rep(e)
|
||||
if len(r.Scanner.Bursts) != 1 || r.Scanner.Bursts[0].End > t0.Add(10*time.Minute).Unix() {
|
||||
t.Fatalf("burst end: %+v", r.Scanner.Bursts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestScannerBeaconStillDetectedDuringBurst(t *testing.T) {
|
||||
e := newEng(t, Config{Workloads: "ciberlab=10.0.5.0/24:scanner"})
|
||||
rnd := rand.New(rand.NewSource(3))
|
||||
// beacon every 60 s for 60 min, scan from minute 10 for 150 s; ordered by time
|
||||
var evs []Event
|
||||
for i := 0; i < 60; i++ {
|
||||
evs = append(evs, mk(t0.Add(time.Duration(i)*time.Minute+time.Duration(rnd.Intn(3))*time.Second), "10.0.5.2", "203.0.113.77", "tcp", 8443))
|
||||
}
|
||||
for i := 0; i < 150; i++ {
|
||||
evs = append(evs, mk(t0.Add(10*time.Minute+10*time.Second+time.Duration(i)*time.Second), "10.0.5.2", fmt.Sprintf("198.18.0.%d", 1+i), "tcp", 443))
|
||||
}
|
||||
sort.SliceStable(evs, func(i, j int) bool { return evs[i].Time.Before(evs[j].Time) })
|
||||
for _, ev := range evs {
|
||||
e.IngestEvent(ev)
|
||||
}
|
||||
r := rep(e)
|
||||
var found bool
|
||||
for _, f := range kinds(r, "beacon") {
|
||||
found = found || f.Dst == "203.0.113.77"
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("beacon of the scanner lost: %+v", r.Findings)
|
||||
}
|
||||
if len(r.Scanner.Bursts) == 0 {
|
||||
t.Fatal("expected a burst")
|
||||
}
|
||||
for _, w := range r.Workloads {
|
||||
if w.Name == "ciberlab" && (w.Conns < 55 || w.Suppressed < 140) {
|
||||
t.Fatalf("beacon flows must stay in normal accounting: %+v", w)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSuspiciousPorts(t *testing.T) {
|
||||
e := newEng(t, Config{Workloads: "mail=10.0.7.0/24:mail"})
|
||||
at := func(i int) time.Time { return t0.Add(time.Duration(i) * time.Minute) }
|
||||
e.IngestEvent(mk(at(0), "10.0.3.5", "203.0.113.1", "tcp", 25))
|
||||
e.IngestEvent(mk(at(1), "10.0.7.5", "203.0.113.2", "tcp", 25)) // mail role: fine
|
||||
e.IngestEvent(mk(at(2), "10.0.3.5", "203.0.113.3", "tcp", 6667))
|
||||
e.IngestEvent(mk(at(3), "10.0.3.5", "203.0.113.4", "tcp", 3333))
|
||||
e.IngestEvent(mk(at(4), "10.0.3.5", "203.0.113.5", "tcp", 9001))
|
||||
e.IngestEvent(mk(at(5), "10.0.3.5", "203.0.113.6", "udp", 3333)) // udp: ignored
|
||||
e.IngestEvent(mk(at(6), "10.0.3.5", "203.0.113.7", "udp", 853))
|
||||
e.IngestEvent(mk(at(7), "10.0.3.5", "93.184.216.34", "udp", 53))
|
||||
e.IngestEvent(mk(at(8), "10.0.3.5", "10.9.9.9", "udp", 53)) // private: not bypass
|
||||
r := rep(e)
|
||||
by := map[string]string{}
|
||||
for _, f := range kinds(r, "port") {
|
||||
by[f.Dst] = f.Severity
|
||||
}
|
||||
if len(by) != 4 || by["203.0.113.1"] != "medium" || by["203.0.113.4"] != "high" || by["203.0.113.2"] != "" {
|
||||
t.Fatalf("ports: %v", by)
|
||||
}
|
||||
if d := kinds(r, "dns_bypass"); len(d) != 1 || d[0].Dst != "93.184.216.34" {
|
||||
t.Fatalf("dns_bypass (DoT is tcp-only, 53 to unusual public): %+v", d)
|
||||
}
|
||||
// custom resolver list: Google no longer allowed
|
||||
e2 := newEng(t, Config{Resolvers: "10.0.0.53"})
|
||||
e2.IngestEvent(mk(t0, "10.0.3.5", "8.8.8.8", "udp", 53))
|
||||
e2.IngestEvent(mk(t0, "10.0.3.5", "10.0.0.53", "udp", 53))
|
||||
if d := kinds(rep(e2), "dns_bypass"); len(d) != 1 || d[0].Dst != "8.8.8.8" {
|
||||
t.Fatalf("custom resolvers: %+v", d)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadDstAndNewGeo(t *testing.T) {
|
||||
geo := func(s string) (string, string, string) {
|
||||
if s == "203.0.113.50" {
|
||||
return "RU", "AS1", "x"
|
||||
}
|
||||
return "BR", "AS2", "y"
|
||||
}
|
||||
bad := func(a netip.Addr) (bool, string) { return a == ip("203.0.113.9"), "Tor exit" }
|
||||
e := newEng(t, Config{Geo: geo, BadDst: bad, Workloads: "sc=10.0.5.0/24:scanner"})
|
||||
e.IngestEvent(mk(t0, "10.0.3.5", "203.0.113.1", "tcp", 443))
|
||||
e.IngestEvent(mk(t0.Add(25*time.Hour), "10.0.3.5", "203.0.113.2", "tcp", 443)) // known country
|
||||
e.IngestEvent(mk(t0.Add(26*time.Hour), "10.0.3.5", "203.0.113.50", "tcp", 443))
|
||||
e.IngestEvent(mk(t0.Add(27*time.Hour), "10.0.3.5", "203.0.113.9", "tcp", 443))
|
||||
e.IngestEvent(mk(t0, "10.0.5.2", "203.0.113.1", "tcp", 443))
|
||||
e.IngestEvent(mk(t0.Add(26*time.Hour), "10.0.5.2", "203.0.113.50", "tcp", 443)) // scanner ignored
|
||||
r := rep(e)
|
||||
g := kinds(r, "new_geo")
|
||||
if len(g) != 1 || g[0].Workload != "container 10.0.3.5" || g[0].Dst != "203.0.113.50" || g[0].Severity != "low" {
|
||||
t.Fatalf("new_geo: %+v", g)
|
||||
}
|
||||
if b := kinds(r, "bad_dst"); len(b) != 1 || b[0].Severity != "high" || b[0].Detail != "Tor exit" {
|
||||
t.Fatalf("bad_dst: %+v", b)
|
||||
}
|
||||
if len(r.TopDst) == 0 || r.TopDst[0].CC == "" {
|
||||
t.Fatalf("top_dst not enriched: %+v", r.TopDst)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMemoryLimits(t *testing.T) {
|
||||
e := newEng(t, Config{})
|
||||
// 60k distinct pairs, 15 s apart (never a fan-out) and spam findings
|
||||
for i := 0; i < 60000; i++ {
|
||||
dst := fmt.Sprintf("%d.%d.%d.%d", 20+i/65536, (i/256)%256, i%256, 1)
|
||||
port := uint16(443)
|
||||
if i < 3000 {
|
||||
port = 25
|
||||
}
|
||||
e.IngestEvent(mk(t0.Add(time.Duration(i)*15*time.Second), "10.0.3.5", dst, "tcp", port))
|
||||
}
|
||||
if e.pairs.len() > MaxPairs || e.dsts.len() > MaxDsts || len(e.findings) > MaxFindings {
|
||||
t.Fatalf("limits: %d %d %d", e.pairs.len(), e.dsts.len(), len(e.findings))
|
||||
}
|
||||
if len(e.findings) != MaxFindings {
|
||||
t.Fatalf("findings should be capped at the limit, got %d", len(e.findings))
|
||||
}
|
||||
w := e.ws["container 10.0.3.5"]
|
||||
n := 0
|
||||
for i := range w.hours {
|
||||
if w.hours[i].hour != 0 {
|
||||
n++
|
||||
}
|
||||
if len(w.hours[i].dsts) > setCap {
|
||||
t.Fatal("hour set not capped")
|
||||
}
|
||||
}
|
||||
if n > HourBuckets {
|
||||
t.Fatal("buckets")
|
||||
}
|
||||
// dedupe: same key updates count
|
||||
e2 := newEng(t, Config{})
|
||||
for i := 0; i < 5; i++ {
|
||||
e2.IngestEvent(mk(t0.Add(time.Duration(i)*time.Minute), "10.0.3.5", "203.0.113.1", "tcp", 6667))
|
||||
}
|
||||
if f := kinds(rep(e2), "port"); len(f) != 1 || f[0].Count != 5 {
|
||||
t.Fatalf("dedupe: %+v", f)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReportMergeSanitize(t *testing.T) {
|
||||
e := newEng(t, Config{})
|
||||
e.IngestEvent(mk(t0, "10.0.3.5", "203.0.113.1", "tcp", 6667))
|
||||
local := e.Report(t0.Unix()-3600, t0.Unix()+3600)
|
||||
peer := e.Report(t0.Unix()-7200, t0.Unix()+3600)
|
||||
peer.Sanitize("oracle")
|
||||
local.Merge(peer, "oracle")
|
||||
if len(local.Findings) != 2 || local.Findings[1].Host != "oracle" && local.Findings[0].Host != "oracle" {
|
||||
t.Fatalf("merge: %+v", local.Findings)
|
||||
}
|
||||
if _, ok := local.Timeline.Series["oracle/container 10.0.3.5"]; !ok {
|
||||
t.Fatalf("series: %v", local.Timeline.Series)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNameMatchExactAndPrefix(t *testing.T) {
|
||||
e := newEng(t, Config{Workloads: "a=name:web:default;b=name:api*:default;c=name:pay:default"})
|
||||
e.SetContainers(map[netip.Addr]string{ip("172.18.0.1"): "web-1700000000000", ip("172.18.0.2"): "webshell-1700000000000",
|
||||
ip("172.18.0.3"): "apigw-17", ip("172.18.0.4"): "pay", ip("172.18.0.5"): "payroll"})
|
||||
for src, want := range map[string]string{"172.18.0.1": "a", "172.18.0.2": "webshell", "172.18.0.3": "b", "172.18.0.4": "c", "172.18.0.5": "payroll"} {
|
||||
if n, _ := e.resolve(mk(t0, src, "1.1.1.1", "tcp", 1)); n != want {
|
||||
t.Errorf("%s: %s want %s", src, n, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHostWorkloadRole(t *testing.T) {
|
||||
e := newEng(t, Config{Workloads: "host=host:mail"})
|
||||
n, r := e.resolve(Event{Time: t0, Src: ip("10.0.0.2"), Dst: ip("1.1.1.1"), Proto: "tcp", Host: true})
|
||||
if n != "host" || r != RoleMail {
|
||||
t.Fatalf("%s/%s", n, r)
|
||||
}
|
||||
e.IngestEvent(Event{Time: t0, Src: ip("10.0.0.2"), Dst: ip("203.0.113.5"), Proto: "tcp", DPort: 25, Host: true})
|
||||
if f := kinds(rep(e), "port"); len(f) != 0 {
|
||||
t.Fatalf("mail host flagged: %+v", f)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvConfAllowed(t *testing.T) {
|
||||
p := filepath.Join(t.TempDir(), "resolv.conf")
|
||||
os.WriteFile(p, []byte("# x\nnameserver 203.0.113.53\nnameserver fe80::1%eth0\nsearch x\n"), 0o644)
|
||||
e := newEng(t, Config{ResolvConf: []string{p, "/nonexistent"}})
|
||||
for i := 0; i < 3; i++ {
|
||||
e.IngestEvent(mk(t0.Add(time.Duration(i)*time.Second), "10.0.3.5", "203.0.113.53", "udp", 53))
|
||||
}
|
||||
if f := kinds(rep(e), "dns_bypass"); len(f) != 0 {
|
||||
t.Fatalf("resolv.conf nameserver flagged: %+v", f)
|
||||
}
|
||||
e.IngestEvent(mk(t0, "10.0.3.5", "203.0.113.54", "udp", 53))
|
||||
if f := kinds(rep(e), "dns_bypass"); len(f) != 1 {
|
||||
t.Fatalf("other resolver not flagged: %+v", f)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAllowedPollerNoBeacon(t *testing.T) {
|
||||
e := newEng(t, Config{Allow: []netip.Prefix{netip.MustParsePrefix("203.0.113.0/24")}})
|
||||
feedBeacon(e, "10.0.3.5", "203.0.113.7", 443, t0, 60, 60*time.Second, 0, rand.New(rand.NewSource(1)))
|
||||
if f := kinds(rep(e), "beacon"); len(f) != 0 {
|
||||
t.Fatalf("%+v", f)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNTPExemption(t *testing.T) {
|
||||
bad := func(a netip.Addr) (bool, string) { return a == ip("203.0.113.99"), "known attacker" }
|
||||
e := newEng(t, Config{BadDst: bad})
|
||||
rnd := rand.New(rand.NewSource(1))
|
||||
feedBeacon(e, "10.0.3.5", "203.0.113.10", 123, t0, 50, 128*time.Second, 0, rnd) // normal poll: exempt
|
||||
feedBeacon(e, "10.0.3.5", "203.0.113.11", 123, t0, 50, 60*time.Second, 0, rnd) // fast NTP: not exempt
|
||||
feedBeacon(e, "10.0.3.5", "203.0.113.99", 123, t0, 50, 128*time.Second, 0, rnd) // bad dst: never exempt
|
||||
got := map[string]bool{}
|
||||
for _, f := range kinds(rep(e), "beacon") {
|
||||
got[f.Dst] = true
|
||||
}
|
||||
if got["203.0.113.10"] || !got["203.0.113.11"] || !got["203.0.113.99"] {
|
||||
t.Fatalf("%v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBeaconDuringContinuousScan(t *testing.T) {
|
||||
e := newEng(t, Config{Workloads: "ciberlab=10.0.5.0/24:scanner"})
|
||||
// a light scan every 4 min (each opens or keeps the burst alive) for 2 h; the C2
|
||||
// is contacted every 60 s starting 12 min AFTER the first burst opened
|
||||
var evs []Event
|
||||
for k := 0; k < 30; k++ {
|
||||
for i := 0; i < 60; i++ {
|
||||
evs = append(evs, mk(t0.Add(time.Duration(k)*4*time.Minute+time.Duration(i)*time.Second), "10.0.5.2",
|
||||
fmt.Sprintf("198.18.%d.%d", k, 1+i), "tcp", 443))
|
||||
}
|
||||
}
|
||||
for i := 0; i < 100; i++ {
|
||||
evs = append(evs, mk(t0.Add(12*time.Minute+time.Duration(i)*time.Minute+30*time.Second), "10.0.5.2", "203.0.113.77", "tcp", 8443))
|
||||
}
|
||||
sort.SliceStable(evs, func(i, j int) bool { return evs[i].Time.Before(evs[j].Time) })
|
||||
for _, ev := range evs {
|
||||
e.IngestEvent(ev)
|
||||
}
|
||||
var found bool
|
||||
for _, f := range kinds(rep(e), "beacon") {
|
||||
found = found || f.Dst == "203.0.113.77"
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("C2 invisible during the continuous scan: %+v", rep(e).Findings)
|
||||
}
|
||||
if e.fanSeen.len() > maxFanSeen {
|
||||
t.Fatal("fanSeen unbounded")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,869 @@
|
||||
package egress
|
||||
|
||||
import (
|
||||
"container/list"
|
||||
"fmt"
|
||||
"hash/fnv"
|
||||
"math"
|
||||
"net/netip"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Limits and thresholds.
|
||||
const (
|
||||
MaxPairs = 50000
|
||||
MaxDsts = 50000
|
||||
MaxFindings = 2000
|
||||
HourBuckets = 720 // 30 days
|
||||
maxWorkloads = 256
|
||||
maxClosedBurst = 200
|
||||
maxFanSeen = 20000 // (workload,dst,port,proto) tuples seen only as fan-out
|
||||
fanPromoteN = 3 // hits within fanPromoteWin that turn a fan-out flow into a pair
|
||||
fanPromoteWin = 3600
|
||||
|
||||
fanDsts = 50
|
||||
fanPorts = 100
|
||||
fanWindow = 600 // seconds
|
||||
burstQuiet = 300 // a burst closes after 5 min without fan-out
|
||||
maxWin = 8192
|
||||
ringSize = 64
|
||||
beaconMinN = 8
|
||||
beaconSpan = 1800
|
||||
beaconMinIv = 10
|
||||
beaconMaxIv = 6 * 3600
|
||||
beaconCV = 0.25
|
||||
beaconMAD = 0.20
|
||||
setCap = 64
|
||||
ntpMinIv = 64
|
||||
)
|
||||
|
||||
// Config of the engine.
|
||||
type Config struct {
|
||||
// Workloads: "ciberlab=10.0.5.0/24:scanner;mail=name:protocols:mail".
|
||||
Workloads string
|
||||
// Resolvers lists the allowed DNS resolvers (comma separated IPs). Rule:
|
||||
// DNS (53 tcp/udp) or DoT (853) from a non-resolver workload to a public
|
||||
// address that is not an allowed resolver is "dns_bypass". When the list is
|
||||
// empty the allowed set is the usual public resolvers (Cloudflare, Google,
|
||||
// Quad9, OpenDNS), so only DoT and port 53 to unusual public IPs alert.
|
||||
Resolvers string
|
||||
// Allow lists destinations that never produce a finding (peers, own servers).
|
||||
Allow []netip.Prefix
|
||||
// Containers is the path of the containers.map file (optional); it is
|
||||
// reloaded when its mtime changes.
|
||||
Containers string
|
||||
// Geo enriches a destination (cc, asn, org); BadDst says whether a
|
||||
// destination is a known attacker or Tor exit (and why).
|
||||
Geo func(ip string) (cc, asn, org string)
|
||||
BadDst func(netip.Addr) (bool, string)
|
||||
Now func() time.Time
|
||||
// Learn is the per-workload learning time before new_geo (default 24h).
|
||||
Learn time.Duration
|
||||
// ResolvConf lists resolv.conf files whose nameservers are allowed resolvers
|
||||
// (default: /etc/resolv.conf and /logs/host/resolv.conf, both optional).
|
||||
ResolvConf []string
|
||||
}
|
||||
|
||||
var usualResolvers = []string{"1.1.1.1", "1.0.0.1", "8.8.8.8", "8.8.4.4", "9.9.9.9", "149.112.112.112",
|
||||
"208.67.222.222", "208.67.220.220", "2606:4700:4700::1111", "2606:4700:4700::1001",
|
||||
"2001:4860:4860::8888", "2001:4860:4860::8844", "2620:fe::fe"}
|
||||
|
||||
type lru[K comparable, V any] struct {
|
||||
cap int
|
||||
l *list.List
|
||||
m map[K]*list.Element
|
||||
}
|
||||
type lent[K comparable, V any] struct {
|
||||
k K
|
||||
v V
|
||||
}
|
||||
|
||||
func newLRU[K comparable, V any](n int) *lru[K, V] {
|
||||
return &lru[K, V]{cap: n, l: list.New(), m: map[K]*list.Element{}}
|
||||
}
|
||||
func (c *lru[K, V]) get(k K) (v V, ok bool) {
|
||||
el, ok := c.m[k]
|
||||
if !ok {
|
||||
return v, false
|
||||
}
|
||||
c.l.MoveToFront(el)
|
||||
return el.Value.(*lent[K, V]).v, true
|
||||
}
|
||||
func (c *lru[K, V]) put(k K, v V) {
|
||||
if el, ok := c.m[k]; ok {
|
||||
el.Value.(*lent[K, V]).v = v
|
||||
c.l.MoveToFront(el)
|
||||
return
|
||||
}
|
||||
c.m[k] = c.l.PushFront(&lent[K, V]{k, v})
|
||||
if c.l.Len() > c.cap {
|
||||
el := c.l.Back()
|
||||
delete(c.m, el.Value.(*lent[K, V]).k)
|
||||
c.l.Remove(el)
|
||||
}
|
||||
}
|
||||
func (c *lru[K, V]) len() int { return c.l.Len() }
|
||||
|
||||
type pairKey struct {
|
||||
wl string
|
||||
dst netip.Addr
|
||||
dport uint16
|
||||
proto string
|
||||
}
|
||||
|
||||
type pairState struct {
|
||||
ts [ringSize]uint32
|
||||
n int
|
||||
total uint32
|
||||
fan, nonFan uint32
|
||||
first, last int64
|
||||
flagged bool
|
||||
fkey string
|
||||
interval, cv float64
|
||||
}
|
||||
|
||||
func (p *pairState) add(t int64, fan bool) {
|
||||
if p.total == 0 {
|
||||
p.first = t
|
||||
}
|
||||
p.total++
|
||||
if fan {
|
||||
p.fan++
|
||||
} else {
|
||||
p.nonFan++
|
||||
}
|
||||
if p.n > 0 && t-int64(p.ts[p.n-1]) < 2 {
|
||||
p.last = t
|
||||
return // retries of the same second are one beat
|
||||
}
|
||||
if p.n == ringSize {
|
||||
copy(p.ts[:], p.ts[1:])
|
||||
p.n--
|
||||
}
|
||||
p.ts[p.n] = uint32(t)
|
||||
p.n++
|
||||
p.last = t
|
||||
}
|
||||
|
||||
type dayN struct {
|
||||
day int32
|
||||
n uint32
|
||||
}
|
||||
|
||||
type dstStat struct {
|
||||
ip netip.Addr
|
||||
cc, asn, og string
|
||||
days []dayN
|
||||
wls []string
|
||||
ports []uint16
|
||||
}
|
||||
|
||||
type hbucket struct {
|
||||
hour int64
|
||||
conns, supp uint32
|
||||
dsts, ports []uint32
|
||||
}
|
||||
|
||||
type burstState struct {
|
||||
start, lastFan int64
|
||||
conns, badHits uint32
|
||||
targets map[netip.Addr]struct{}
|
||||
nets map[netip.Prefix]uint32
|
||||
ports map[uint16]uint32
|
||||
}
|
||||
|
||||
type wstate struct {
|
||||
name, role string
|
||||
first int64
|
||||
hours [HourBuckets]hbucket
|
||||
win map[netip.Addr]int64
|
||||
wports map[uint16]int64
|
||||
lastPrune int64
|
||||
burst *burstState
|
||||
geo map[string]struct{}
|
||||
// recent are the normal flows of the fan-out window: when a burst opens
|
||||
// they are re-read as part of it (the first 49 probes of a scan).
|
||||
recent []winFlow
|
||||
}
|
||||
|
||||
type winFlow struct {
|
||||
pk pairKey
|
||||
t int64
|
||||
badKey string // bad_dst finding this flow raised, if any
|
||||
}
|
||||
|
||||
// Engine analyses egress events. Safe for concurrent use.
|
||||
type Engine struct {
|
||||
mu sync.Mutex
|
||||
cfg Config
|
||||
wls []workloadDef
|
||||
resolvers map[netip.Addr]bool
|
||||
now func() time.Time
|
||||
|
||||
containers map[netip.Addr]string
|
||||
mapMod time.Time
|
||||
mapCheck time.Time
|
||||
|
||||
ws map[string]*wstate
|
||||
pairs *lru[pairKey, *pairState]
|
||||
dsts *lru[netip.Addr, *dstStat]
|
||||
fanSeen *lru[pairKey, *fanRec]
|
||||
findings map[string]*Finding
|
||||
closed []BurstOut
|
||||
maxT int64
|
||||
|
||||
lines, malformed atomic.Uint64
|
||||
last atomic.Int64
|
||||
stateFn atomic.Pointer[func() string]
|
||||
}
|
||||
|
||||
// New builds an engine.
|
||||
func New(c Config) (*Engine, error) {
|
||||
wls, err := ParseWorkloads(c.Workloads)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
e := &Engine{cfg: c, wls: wls, now: c.Now, resolvers: map[netip.Addr]bool{}, containers: map[netip.Addr]string{},
|
||||
ws: map[string]*wstate{}, pairs: newLRU[pairKey, *pairState](MaxPairs), dsts: newLRU[netip.Addr, *dstStat](MaxDsts),
|
||||
findings: map[string]*Finding{}, fanSeen: newLRU[pairKey, *fanRec](maxFanSeen)}
|
||||
if e.now == nil {
|
||||
e.now = time.Now
|
||||
}
|
||||
if e.cfg.Learn <= 0 {
|
||||
e.cfg.Learn = 24 * time.Hour
|
||||
}
|
||||
list := strings.Split(c.Resolvers, ",")
|
||||
if strings.TrimSpace(c.Resolvers) == "" {
|
||||
list = usualResolvers
|
||||
}
|
||||
for _, s := range list {
|
||||
if s = strings.TrimSpace(s); s == "" {
|
||||
continue
|
||||
}
|
||||
a, err := netip.ParseAddr(s)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("resolver %q: %w", s, err)
|
||||
}
|
||||
e.resolvers[a.Unmap()] = true
|
||||
}
|
||||
rc := c.ResolvConf
|
||||
if rc == nil {
|
||||
rc = []string{"/etc/resolv.conf", "/logs/host/resolv.conf"}
|
||||
}
|
||||
for _, p := range rc {
|
||||
for _, a := range readNameservers(p) {
|
||||
e.resolvers[a] = true
|
||||
}
|
||||
}
|
||||
return e, nil
|
||||
}
|
||||
|
||||
// readNameservers returns the nameserver addresses of a resolv.conf (missing file: none).
|
||||
func readNameservers(path string) []netip.Addr {
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var out []netip.Addr
|
||||
for _, ln := range strings.Split(string(b), "\n") {
|
||||
f := strings.Fields(ln)
|
||||
if len(f) >= 2 && f[0] == "nameserver" {
|
||||
if a, err := netip.ParseAddr(f[1]); err == nil {
|
||||
out = append(out, a.WithZone("").Unmap())
|
||||
}
|
||||
}
|
||||
if len(out) >= 16 {
|
||||
break
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// fanRec accumulates the sightings of a flow that was only ever seen as fan-out.
|
||||
type fanRec struct{ ts []int64 }
|
||||
|
||||
// fanPromote records one fan-out sighting; when the same flow shows up
|
||||
// fanPromoteN times within the hour it is a real pair (a C2 contacted during a
|
||||
// continuous scan), returned with its accumulated timestamps.
|
||||
func (e *Engine) fanPromote(pk pairKey, t int64) *pairState {
|
||||
r, ok := e.fanSeen.get(pk)
|
||||
if !ok {
|
||||
r = &fanRec{}
|
||||
e.fanSeen.put(pk, r)
|
||||
}
|
||||
k := 0
|
||||
for _, x := range r.ts {
|
||||
if t-x <= fanPromoteWin {
|
||||
r.ts[k] = x
|
||||
k++
|
||||
}
|
||||
}
|
||||
r.ts = r.ts[:k]
|
||||
if n := len(r.ts); n == 0 || t-r.ts[n-1] >= 2 { // retries of the same second are one beat
|
||||
r.ts = append(r.ts, t)
|
||||
}
|
||||
if len(r.ts) < fanPromoteN {
|
||||
return nil
|
||||
}
|
||||
p := &pairState{}
|
||||
for _, x := range r.ts[:len(r.ts)-1] {
|
||||
p.add(x, false)
|
||||
}
|
||||
if el, ok := e.fanSeen.m[pk]; ok {
|
||||
e.fanSeen.l.Remove(el)
|
||||
delete(e.fanSeen.m, pk)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// SetContainers replaces the address to container-name map (tests, wiring).
|
||||
func (e *Engine) SetContainers(m map[netip.Addr]string) {
|
||||
e.mu.Lock()
|
||||
e.containers = m
|
||||
e.mu.Unlock()
|
||||
}
|
||||
|
||||
func (e *Engine) reloadMap() {
|
||||
if e.cfg.Containers == "" {
|
||||
return
|
||||
}
|
||||
n := e.now()
|
||||
if n.Sub(e.mapCheck) < 5*time.Second {
|
||||
return
|
||||
}
|
||||
e.mapCheck = n
|
||||
fi, err := os.Stat(e.cfg.Containers)
|
||||
if err != nil || fi.ModTime().Equal(e.mapMod) {
|
||||
return
|
||||
}
|
||||
if m, err := LoadContainers(e.cfg.Containers); err == nil {
|
||||
e.containers, e.mapMod = m, fi.ModTime()
|
||||
}
|
||||
}
|
||||
|
||||
// Ingest parses and analyses one log line.
|
||||
func (e *Engine) Ingest(line []byte) {
|
||||
ev, err := ParseLine(line, e.now())
|
||||
if err != nil {
|
||||
if len(line) > 0 {
|
||||
e.malformed.Add(1)
|
||||
}
|
||||
return
|
||||
}
|
||||
e.lines.Add(1)
|
||||
e.last.Store(e.now().Unix())
|
||||
e.IngestEvent(ev)
|
||||
}
|
||||
|
||||
// IngestEvent analyses one parsed event.
|
||||
func (e *Engine) IngestEvent(ev Event) {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
e.ingest(ev)
|
||||
}
|
||||
|
||||
func (e *Engine) allowed(a netip.Addr) bool {
|
||||
for _, p := range e.cfg.Allow {
|
||||
if p.Contains(a) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func fanCounts(role string, ev Event) bool {
|
||||
switch {
|
||||
case role == RoleMail && (ev.DPort == 25 || ev.DPort == 465 || ev.DPort == 587):
|
||||
return false // a mail server legitimately talks to many MX
|
||||
case role == RoleResolver && ev.DPort == 53:
|
||||
return false // a recursive resolver talks to many authoritative servers
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (e *Engine) wstate(name, role string, t int64) *wstate {
|
||||
if w, ok := e.ws[name]; ok {
|
||||
return w
|
||||
}
|
||||
if len(e.ws) >= maxWorkloads {
|
||||
name, role = "container other", RoleDefault
|
||||
if w, ok := e.ws[name]; ok {
|
||||
return w
|
||||
}
|
||||
}
|
||||
w := &wstate{name: name, role: role, first: t, win: map[netip.Addr]int64{}, wports: map[uint16]int64{}, geo: map[string]struct{}{}}
|
||||
e.ws[name] = w
|
||||
return w
|
||||
}
|
||||
|
||||
func h32(a netip.Addr) uint32 {
|
||||
b := a.As16()
|
||||
h := fnv.New32a()
|
||||
h.Write(b[:])
|
||||
return h.Sum32()
|
||||
}
|
||||
|
||||
func addSet(s []uint32, v uint32) []uint32 {
|
||||
for _, x := range s {
|
||||
if x == v {
|
||||
return s
|
||||
}
|
||||
}
|
||||
if len(s) >= setCap {
|
||||
return s
|
||||
}
|
||||
return append(s, v)
|
||||
}
|
||||
|
||||
func (w *wstate) bucket(t int64) *hbucket {
|
||||
h := t / 3600
|
||||
b := &w.hours[h%HourBuckets]
|
||||
if b.hour != h {
|
||||
*b = hbucket{hour: h}
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func (e *Engine) ingest(ev Event) {
|
||||
t := ev.Time.Unix()
|
||||
if t <= 0 {
|
||||
return
|
||||
}
|
||||
if t > e.maxT {
|
||||
e.maxT = t
|
||||
}
|
||||
e.reloadMap()
|
||||
name, role := e.resolve(ev)
|
||||
ws := e.wstate(name, role, t)
|
||||
role = ws.role
|
||||
allowed := e.allowed(ev.Dst)
|
||||
dport := ev.DPort
|
||||
if ev.Proto == "icmp" {
|
||||
dport = 0
|
||||
}
|
||||
counts := !allowed && fanCounts(role, ev)
|
||||
|
||||
if ws.burst != nil && t-ws.burst.lastFan > burstQuiet {
|
||||
e.closeBurst(ws)
|
||||
}
|
||||
if counts && ws.burst == nil {
|
||||
e.window(ws, ev.Dst, dport, t)
|
||||
}
|
||||
inBurst := counts && ws.burst != nil
|
||||
|
||||
pk := pairKey{ws.name, ev.Dst, dport, ev.Proto}
|
||||
p, _ := e.pairs.get(pk)
|
||||
fan := inBurst && (p == nil || p.nonFan < 3)
|
||||
if p == nil && fan && !allowed {
|
||||
if np := e.fanPromote(pk, t); np != nil {
|
||||
p, fan = np, false
|
||||
e.pairs.put(pk, p)
|
||||
}
|
||||
}
|
||||
if p == nil && !fan && !allowed {
|
||||
p = &pairState{}
|
||||
e.pairs.put(pk, p) // fan-out flows create pairs only when repeated: a scan must not evict real ones
|
||||
}
|
||||
if p != nil {
|
||||
p.add(t, fan)
|
||||
}
|
||||
|
||||
scanner := role == RoleScanner
|
||||
if fan {
|
||||
e.burstFlow(ws, ev, dport, t, scanner)
|
||||
if scanner {
|
||||
ws.bucket(t).supp++
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
b := ws.bucket(t)
|
||||
b.conns++
|
||||
if counts && ws.burst == nil && len(ws.recent) < maxWin {
|
||||
ws.recent = append(ws.recent, winFlow{pk: pk, t: t})
|
||||
}
|
||||
b.dsts = addSet(b.dsts, h32(ev.Dst))
|
||||
b.ports = addSet(b.ports, uint32(dport))
|
||||
ds := e.dstStat(ws.name, ev.Dst, dport, t)
|
||||
if allowed {
|
||||
return
|
||||
}
|
||||
e.checks(ws, ev, dport, t, ds, p, fan)
|
||||
if n := len(ws.recent); n > 0 && ws.recent[n-1].t == t && ws.recent[n-1].pk == pk {
|
||||
if f := e.findings[fmt.Sprintf("bad_dst|%s|%s|%d", ws.name, ev.Dst, dport)]; f != nil {
|
||||
ws.recent[n-1].badKey = fmt.Sprintf("bad_dst|%s|%s|%d", ws.name, ev.Dst, dport)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// retro re-reads the flows seen before the burst opened as part of it.
|
||||
func (e *Engine) retro(ws *wstate) {
|
||||
cnt := map[pairKey]uint32{}
|
||||
for _, f := range ws.recent {
|
||||
cnt[f.pk]++
|
||||
}
|
||||
moved := map[pairKey]bool{}
|
||||
for pk, n := range cnt {
|
||||
// a pair established before the window, or hit 4+ times inside it (a probe is hit once or retried), stays normal
|
||||
if p, ok := e.pairs.get(pk); ok && n < 4 && p.nonFan >= n && p.nonFan-n < 3 {
|
||||
p.fan += n
|
||||
p.nonFan -= n
|
||||
moved[pk] = true
|
||||
} else if !ok && n < 4 {
|
||||
moved[pk] = true // evicted pair: still a probe
|
||||
}
|
||||
}
|
||||
for _, f := range ws.recent {
|
||||
if !moved[f.pk] {
|
||||
continue
|
||||
}
|
||||
if ws.role != RoleScanner {
|
||||
continue
|
||||
}
|
||||
b := &ws.hours[(f.t/3600)%HourBuckets]
|
||||
if b.hour == f.t/3600 && b.conns > 0 {
|
||||
b.conns--
|
||||
b.supp++
|
||||
}
|
||||
if ds, ok := e.dsts.get(f.pk.dst); ok {
|
||||
for i := range ds.days {
|
||||
if ds.days[i].day == int32(f.t/86400) && ds.days[i].n > 0 {
|
||||
ds.days[i].n--
|
||||
}
|
||||
}
|
||||
}
|
||||
if f.badKey != "" {
|
||||
if fd := e.findings[f.badKey]; fd != nil {
|
||||
if fd.Count--; fd.Count <= 0 {
|
||||
delete(e.findings, f.badKey)
|
||||
}
|
||||
ws.burst.badHits++
|
||||
}
|
||||
}
|
||||
}
|
||||
ws.recent = ws.recent[:0]
|
||||
}
|
||||
|
||||
func (e *Engine) window(ws *wstate, dst netip.Addr, dport uint16, t int64) {
|
||||
if t-ws.lastPrune >= 10 {
|
||||
for k, v := range ws.win {
|
||||
if t-v > fanWindow {
|
||||
delete(ws.win, k)
|
||||
}
|
||||
}
|
||||
for k, v := range ws.wports {
|
||||
if t-v > fanWindow {
|
||||
delete(ws.wports, k)
|
||||
}
|
||||
}
|
||||
ws.lastPrune = t
|
||||
k := 0
|
||||
for _, f := range ws.recent {
|
||||
if t-f.t <= fanWindow {
|
||||
ws.recent[k] = f
|
||||
k++
|
||||
}
|
||||
}
|
||||
ws.recent = ws.recent[:k]
|
||||
}
|
||||
if _, ok := ws.win[dst]; ok || len(ws.win) < maxWin {
|
||||
ws.win[dst] = t
|
||||
}
|
||||
if dport != 0 {
|
||||
ws.wports[dport] = t
|
||||
}
|
||||
if len(ws.win) >= fanDsts || len(ws.wports) >= fanPorts {
|
||||
start := t
|
||||
for _, v := range ws.win {
|
||||
if v < start {
|
||||
start = v
|
||||
}
|
||||
}
|
||||
ws.burst = &burstState{start: start, lastFan: t, targets: map[netip.Addr]struct{}{},
|
||||
nets: map[netip.Prefix]uint32{}, ports: map[uint16]uint32{}}
|
||||
clear(ws.win)
|
||||
clear(ws.wports)
|
||||
e.retro(ws)
|
||||
}
|
||||
}
|
||||
|
||||
func (e *Engine) burstFlow(ws *wstate, ev Event, dport uint16, t int64, scanner bool) {
|
||||
bs := ws.burst
|
||||
bs.lastFan = t
|
||||
bs.conns++
|
||||
if len(bs.targets) < 50000 {
|
||||
bs.targets[ev.Dst] = struct{}{}
|
||||
}
|
||||
bits := 24
|
||||
if ev.Dst.Is6() {
|
||||
bits = 48
|
||||
}
|
||||
np, _ := ev.Dst.Prefix(bits)
|
||||
if _, ok := bs.nets[np]; ok || len(bs.nets) < 512 {
|
||||
bs.nets[np]++
|
||||
}
|
||||
if dport != 0 {
|
||||
if _, ok := bs.ports[dport]; ok || len(bs.ports) < 1024 {
|
||||
bs.ports[dport]++
|
||||
}
|
||||
}
|
||||
if scanner {
|
||||
if e.cfg.BadDst != nil {
|
||||
if bad, _ := e.cfg.BadDst(ev.Dst); bad {
|
||||
bs.badHits++
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
if bs.conns%32 == 1 {
|
||||
e.addFinding("scan", "high", ws.name, "", 0, "", t, 0, 0, bs.detail(), 1)
|
||||
} else {
|
||||
e.addFinding("scan", "high", ws.name, "", 0, "", t, 0, 0, "", 1)
|
||||
}
|
||||
}
|
||||
|
||||
func (bs *burstState) detail() string {
|
||||
return fmt.Sprintf("fan-out: %d targets, %d ports, %d connections", len(bs.targets), len(bs.ports), bs.conns)
|
||||
}
|
||||
|
||||
func (e *Engine) closeBurst(ws *wstate) {
|
||||
bs := ws.burst
|
||||
ws.burst = nil
|
||||
ws.recent = ws.recent[:0]
|
||||
clear(ws.win)
|
||||
clear(ws.wports)
|
||||
if ws.role != RoleScanner {
|
||||
e.addFinding("scan", "high", ws.name, "", 0, "", bs.lastFan, 0, 0, bs.detail(), 0)
|
||||
return
|
||||
}
|
||||
e.closed = append(e.closed, bs.out(ws.name, bs.lastFan))
|
||||
if len(e.closed) > maxClosedBurst {
|
||||
e.closed = e.closed[len(e.closed)-maxClosedBurst:]
|
||||
}
|
||||
}
|
||||
|
||||
func (e *Engine) dstStat(wl string, dst netip.Addr, dport uint16, t int64) *dstStat {
|
||||
ds, ok := e.dsts.get(dst)
|
||||
if !ok {
|
||||
ds = &dstStat{ip: dst}
|
||||
if e.cfg.Geo != nil && isGlobal(dst) {
|
||||
ds.cc, ds.asn, ds.og = e.cfg.Geo(dst.String())
|
||||
}
|
||||
e.dsts.put(dst, ds)
|
||||
}
|
||||
day := int32(t / 86400)
|
||||
if n := len(ds.days); n > 0 && ds.days[n-1].day == day {
|
||||
ds.days[n-1].n++
|
||||
} else if n == 0 || ds.days[n-1].day < day {
|
||||
ds.days = append(ds.days, dayN{day, 1})
|
||||
if len(ds.days) > 30 {
|
||||
ds.days = ds.days[1:]
|
||||
}
|
||||
}
|
||||
has := false
|
||||
for _, w := range ds.wls {
|
||||
has = has || w == wl
|
||||
}
|
||||
if !has && len(ds.wls) < 8 {
|
||||
ds.wls = append(ds.wls, wl)
|
||||
}
|
||||
hp := false
|
||||
for _, p := range ds.ports {
|
||||
hp = hp || p == dport
|
||||
}
|
||||
if !hp && len(ds.ports) < 8 {
|
||||
ds.ports = append(ds.ports, dport)
|
||||
}
|
||||
return ds
|
||||
}
|
||||
|
||||
func isGlobal(a netip.Addr) bool {
|
||||
return a.IsValid() && !a.IsPrivate() && !a.IsLoopback() && !a.IsLinkLocalUnicast() && !a.IsMulticast() &&
|
||||
!a.IsUnspecified() && !a.IsLinkLocalMulticast() && !isCGNAT(a)
|
||||
}
|
||||
|
||||
var cgnat = netip.MustParsePrefix("100.64.0.0/10")
|
||||
|
||||
func isCGNAT(a netip.Addr) bool { return cgnat.Contains(a) }
|
||||
|
||||
func (e *Engine) isResolver(a netip.Addr) bool { return e.resolvers[a] }
|
||||
|
||||
func (e *Engine) checks(ws *wstate, ev Event, dport uint16, t int64, ds *dstStat, p *pairState, fan bool) {
|
||||
dst := ev.Dst.String()
|
||||
if e.cfg.BadDst != nil {
|
||||
if bad, why := e.cfg.BadDst(ev.Dst); bad {
|
||||
e.addFinding("bad_dst", "high", ws.name, dst, dport, ev.Proto, t, 0, 0, why, 1)
|
||||
}
|
||||
}
|
||||
if ev.Proto == "tcp" {
|
||||
if sev, why := suspiciousPort(dport, ws.role); why != "" {
|
||||
e.addFinding("port", sev, ws.name, dst, dport, ev.Proto, t, 0, 0, why, 1)
|
||||
}
|
||||
}
|
||||
dns := dport == 53 && (ev.Proto == "udp" || ev.Proto == "tcp") || dport == 853 && ev.Proto == "tcp"
|
||||
if dns && ws.role != RoleResolver && isGlobal(ev.Dst) && !e.isResolver(ev.Dst) {
|
||||
e.addFinding("dns_bypass", "medium", ws.name, dst, dport, ev.Proto, t, 0, 0, "DNS to a resolver that is not allowed", 1)
|
||||
}
|
||||
if p != nil {
|
||||
e.beacon(ws, ev, dport, dns, p, ds)
|
||||
}
|
||||
if ws.role != RoleScanner && !fan && ds.cc != "" && isGlobal(ev.Dst) {
|
||||
if _, seen := ws.geo[ds.cc]; !seen {
|
||||
ws.geo[ds.cc] = struct{}{}
|
||||
if t-ws.first >= int64(e.cfg.Learn/time.Second) {
|
||||
e.addFinding("new_geo", "low", ws.name, dst, dport, ev.Proto, t, 0, 0, "first contact with country "+ds.cc+" "+ds.asn, 1)
|
||||
}
|
||||
} else if len(ws.geo) > 300 {
|
||||
ws.geo = map[string]struct{}{}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func suspiciousPort(port uint16, role string) (sev, why string) {
|
||||
switch port {
|
||||
case 25, 465, 587:
|
||||
if role != RoleMail {
|
||||
return "medium", "SMTP from a non-mail workload (spam)"
|
||||
}
|
||||
case 6667, 6697:
|
||||
return "medium", "IRC (classic botnet C2)"
|
||||
case 3333, 14444, 45700:
|
||||
return "high", "mining pool (stratum)"
|
||||
case 4444, 5555, 7777:
|
||||
return "medium", "probable mining pool (stratum) or reverse shell"
|
||||
case 9001, 9030:
|
||||
return "medium", "Tor ORPort"
|
||||
}
|
||||
return "", ""
|
||||
}
|
||||
|
||||
func (e *Engine) beacon(ws *wstate, ev Event, dport uint16, dns bool, p *pairState, ds *dstStat) {
|
||||
if p.flagged {
|
||||
e.addFinding("beacon", "", ws.name, ev.Dst.String(), dport, ev.Proto, p.last, p.interval, p.cv, "", 1)
|
||||
return
|
||||
}
|
||||
ntp := ev.Proto == "udp" && dport == 123
|
||||
switch {
|
||||
case dns && e.isResolver(ev.Dst):
|
||||
return
|
||||
case ws.role == RoleResolver && dport == 53:
|
||||
return
|
||||
case p.n < beaconMinN || int64(p.ts[p.n-1])-int64(p.ts[0]) < beaconSpan:
|
||||
return
|
||||
case p.fan > p.nonFan:
|
||||
return // mostly a fan-out target (a daily scan target is not a beacon)
|
||||
case p.total%4 != 0:
|
||||
return // evaluate every fourth flow: the statistics allocate
|
||||
}
|
||||
iv := make([]float64, p.n-1)
|
||||
var sum float64
|
||||
for i := range iv {
|
||||
iv[i] = float64(p.ts[i+1] - p.ts[i])
|
||||
sum += iv[i]
|
||||
}
|
||||
med := median(iv)
|
||||
if med < beaconMinIv || med > beaconMaxIv {
|
||||
return
|
||||
}
|
||||
if ntp { // NTP is exempt only at a normal poll rate and never towards a bad destination
|
||||
bad := false
|
||||
if e.cfg.BadDst != nil {
|
||||
bad, _ = e.cfg.BadDst(ev.Dst)
|
||||
}
|
||||
if !bad && med >= ntpMinIv {
|
||||
return
|
||||
}
|
||||
}
|
||||
mean := sum / float64(len(iv))
|
||||
var ss float64
|
||||
dev := make([]float64, len(iv))
|
||||
for i, v := range iv {
|
||||
ss += (v - mean) * (v - mean)
|
||||
dev[i] = math.Abs(v - med)
|
||||
}
|
||||
cv := math.Sqrt(ss/float64(len(iv))) / mean
|
||||
mad := median(dev) / med
|
||||
if cv > beaconCV && mad > beaconMAD {
|
||||
return
|
||||
}
|
||||
jit := cv
|
||||
if mad < cv {
|
||||
jit = mad
|
||||
}
|
||||
sev := "medium"
|
||||
why := fmt.Sprintf("regular connections every %.0f s (jitter %.0f%%)", med, jit*100)
|
||||
if e.cfg.BadDst != nil {
|
||||
if bad, r := e.cfg.BadDst(ev.Dst); bad {
|
||||
sev, why = "high", why+"; destination: "+r
|
||||
}
|
||||
}
|
||||
p.flagged, p.interval, p.cv = true, med, jit
|
||||
f := e.addFinding("beacon", sev, ws.name, ev.Dst.String(), dport, ev.Proto, p.last, med, jit, why, 0)
|
||||
if f != nil {
|
||||
f.Count, f.First = int(p.total), p.first
|
||||
}
|
||||
}
|
||||
|
||||
func median(v []float64) float64 {
|
||||
s := append([]float64(nil), v...)
|
||||
sort.Float64s(s)
|
||||
n := len(s)
|
||||
if n == 0 {
|
||||
return 0
|
||||
}
|
||||
if n%2 == 1 {
|
||||
return s[n/2]
|
||||
}
|
||||
return (s[n/2-1] + s[n/2]) / 2
|
||||
}
|
||||
|
||||
var sevRank = map[string]int{"low": 1, "medium": 2, "high": 3}
|
||||
|
||||
func (e *Engine) addFinding(kind, sev, wl, dst string, dport uint16, proto string, t int64, iv, jit float64, detail string, inc int) *Finding {
|
||||
key := fmt.Sprintf("%s|%s|%s|%d", kind, wl, dst, dport)
|
||||
if f, ok := e.findings[key]; ok {
|
||||
f.Count += inc
|
||||
if t > f.Last {
|
||||
f.Last = t
|
||||
}
|
||||
if sevRank[sev] > sevRank[f.Severity] {
|
||||
f.Severity = sev
|
||||
}
|
||||
if detail != "" {
|
||||
f.Detail = detail
|
||||
}
|
||||
if iv > 0 {
|
||||
f.IntervalS, f.Jitter = iv, jit
|
||||
}
|
||||
return f
|
||||
}
|
||||
if sev == "" {
|
||||
return nil // an update for a finding that was evicted
|
||||
}
|
||||
if len(e.findings) >= MaxFindings {
|
||||
var worst string
|
||||
var wf *Finding
|
||||
for k, f := range e.findings {
|
||||
if wf == nil || sevRank[f.Severity] < sevRank[wf.Severity] || sevRank[f.Severity] == sevRank[wf.Severity] && f.Last < wf.Last {
|
||||
worst, wf = k, f
|
||||
}
|
||||
}
|
||||
delete(e.findings, worst)
|
||||
}
|
||||
h := fnv.New64a()
|
||||
h.Write([]byte(key))
|
||||
f := &Finding{ID: fmt.Sprintf("e%016x", h.Sum64()), Kind: kind, Severity: sev, Workload: wl, Dst: dst, DPort: dport, Proto: proto,
|
||||
Count: inc, IntervalS: iv, Jitter: jit, First: t, Last: t, Detail: detail}
|
||||
e.findings[key] = f
|
||||
return f
|
||||
}
|
||||
|
||||
// Counters for the source status.
|
||||
func (e *Engine) counters() (lines, malformed uint64, last int64) {
|
||||
return e.lines.Load(), e.malformed.Load(), e.last.Load()
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
// Package egress analyses the outbound connections of the host and its
|
||||
// containers (nftables "URUTAU-EGRESS: " log lines) to spot a compromised
|
||||
// workload: beaconing, C2, mining, spam, unauthorised scanning.
|
||||
//
|
||||
// Central principle: traffic shaped like a scan (fan-out) is suppressed only
|
||||
// for workloads with role=scanner. Traffic that is not scan shaped is judged
|
||||
// the same for every workload, the scanner included.
|
||||
package egress
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/netip"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const marker = "URUTAU-EGRESS:"
|
||||
|
||||
// Event is one new outbound connection.
|
||||
type Event struct {
|
||||
Time time.Time
|
||||
Src, Dst netip.Addr
|
||||
Proto string // tcp, udp, icmp, or the lowercased PROTO value
|
||||
SPort, DPort uint16
|
||||
In, Out string
|
||||
Host bool // IN= empty: output of the host itself
|
||||
}
|
||||
|
||||
// ErrNotEgress marks a line that is not an egress log line.
|
||||
var ErrNotEgress = errors.New("not an egress line")
|
||||
|
||||
// ParseLine parses a kernel/rsyslog line. now is only used to infer the year
|
||||
// of the "Nov 14 22:01:02" rsyslog format (and as the time of a line whose
|
||||
// timestamp is unreadable).
|
||||
func ParseLine(b []byte, now time.Time) (Event, error) {
|
||||
line := string(b)
|
||||
i := strings.Index(line, marker)
|
||||
if i < 0 {
|
||||
return Event{}, ErrNotEgress
|
||||
}
|
||||
ev := Event{Time: parseTS(line[:i], now)}
|
||||
var haveSrc, haveDst bool
|
||||
for _, f := range strings.Fields(line[i+len(marker):]) {
|
||||
k, v, ok := strings.Cut(f, "=")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
switch k {
|
||||
case "IN":
|
||||
ev.In = v
|
||||
case "OUT":
|
||||
ev.Out = v
|
||||
case "SRC":
|
||||
a, err := netip.ParseAddr(v)
|
||||
if err != nil {
|
||||
return Event{}, errors.New("bad SRC")
|
||||
}
|
||||
ev.Src, haveSrc = a.Unmap(), true
|
||||
case "DST":
|
||||
a, err := netip.ParseAddr(v)
|
||||
if err != nil {
|
||||
return Event{}, errors.New("bad DST")
|
||||
}
|
||||
ev.Dst, haveDst = a.Unmap(), true
|
||||
case "PROTO":
|
||||
p := strings.ToLower(v)
|
||||
if strings.HasPrefix(p, "icmp") {
|
||||
p = "icmp"
|
||||
}
|
||||
ev.Proto = p
|
||||
case "SPT":
|
||||
n, _ := strconv.ParseUint(v, 10, 16)
|
||||
ev.SPort = uint16(n)
|
||||
case "DPT":
|
||||
n, _ := strconv.ParseUint(v, 10, 16)
|
||||
ev.DPort = uint16(n)
|
||||
}
|
||||
}
|
||||
if !haveSrc || !haveDst || ev.Proto == "" {
|
||||
return Event{}, errors.New("incomplete egress line")
|
||||
}
|
||||
ev.Host = ev.In == ""
|
||||
return ev, nil
|
||||
}
|
||||
|
||||
func parseTS(prefix string, now time.Time) time.Time {
|
||||
f := strings.Fields(prefix)
|
||||
if len(f) == 0 {
|
||||
return now
|
||||
}
|
||||
if t, err := time.Parse(time.RFC3339Nano, f[0]); err == nil {
|
||||
return t
|
||||
}
|
||||
if len(f) >= 3 {
|
||||
if t, err := time.ParseInLocation("Jan 2 15:04:05", f[0]+" "+f[1]+" "+f[2], now.Location()); err == nil {
|
||||
t = t.AddDate(now.Year(), 0, 0)
|
||||
if t.After(now.Add(48 * time.Hour)) {
|
||||
t = t.AddDate(-1, 0, 0)
|
||||
}
|
||||
return t
|
||||
}
|
||||
}
|
||||
return now
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
package egress
|
||||
|
||||
import (
|
||||
"net/netip"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Finding is one alert; repeated observations update it.
|
||||
type Finding struct {
|
||||
ID string `json:"id"`
|
||||
Kind string `json:"kind"`
|
||||
Severity string `json:"severity"`
|
||||
Workload string `json:"workload"`
|
||||
Dst string `json:"dst"`
|
||||
DPort uint16 `json:"dport"`
|
||||
Proto string `json:"proto"`
|
||||
Count int `json:"count"`
|
||||
IntervalS float64 `json:"interval_s"`
|
||||
Jitter float64 `json:"jitter"`
|
||||
First int64 `json:"first"`
|
||||
Last int64 `json:"last"`
|
||||
Detail string `json:"detail"`
|
||||
Host string `json:"host,omitempty"`
|
||||
}
|
||||
|
||||
// WorkloadOut summarises a workload over the window.
|
||||
type WorkloadOut struct {
|
||||
Name string `json:"name"`
|
||||
Role string `json:"role"`
|
||||
Conns uint64 `json:"conns"`
|
||||
Dsts int `json:"dsts"`
|
||||
Ports int `json:"ports"`
|
||||
Findings int `json:"findings"`
|
||||
Suppressed uint64 `json:"suppressed_scan_conns"`
|
||||
Host string `json:"host,omitempty"`
|
||||
}
|
||||
|
||||
// Timeline holds hourly connection counts per workload.
|
||||
type Timeline struct {
|
||||
Start int64 `json:"start"`
|
||||
Step int64 `json:"step"`
|
||||
Series map[string][]uint32 `json:"series"`
|
||||
}
|
||||
|
||||
// DstOut is a top destination.
|
||||
type DstOut struct {
|
||||
IP string `json:"ip"`
|
||||
CC string `json:"cc"`
|
||||
ASN string `json:"asn"`
|
||||
Org string `json:"org"`
|
||||
Conns uint64 `json:"conns"`
|
||||
Workloads []string `json:"workloads"`
|
||||
Ports []uint16 `json:"ports"`
|
||||
}
|
||||
|
||||
// BurstOut summarises a scanner fan-out burst.
|
||||
type BurstOut struct {
|
||||
Workload string `json:"workload"`
|
||||
Start int64 `json:"start"`
|
||||
End int64 `json:"end"`
|
||||
Targets int `json:"targets"`
|
||||
Nets []string `json:"nets"`
|
||||
Ports []uint16 `json:"ports"`
|
||||
Conns uint32 `json:"conns"`
|
||||
BadDstHit uint32 `json:"bad_dst_hits"`
|
||||
Host string `json:"host,omitempty"`
|
||||
}
|
||||
|
||||
// ScannerOut groups the scanner bursts.
|
||||
type ScannerOut struct {
|
||||
Bursts []BurstOut `json:"bursts"`
|
||||
}
|
||||
|
||||
// Report is the egress analysis of a window.
|
||||
type Report struct {
|
||||
Workloads []WorkloadOut `json:"workloads"`
|
||||
Timeline Timeline `json:"timeline"`
|
||||
TopDst []DstOut `json:"top_dst"`
|
||||
Findings []Finding `json:"findings"`
|
||||
Scanner ScannerOut `json:"scanner"`
|
||||
}
|
||||
|
||||
func (bs *burstState) out(wl string, end int64) BurstOut {
|
||||
o := BurstOut{Workload: wl, Start: bs.start, End: end, Targets: len(bs.targets), Conns: bs.conns, BadDstHit: bs.badHits,
|
||||
Nets: []string{}, Ports: []uint16{}}
|
||||
type nc struct {
|
||||
p netip.Prefix
|
||||
n uint32
|
||||
}
|
||||
var ns []nc
|
||||
for p, n := range bs.nets {
|
||||
ns = append(ns, nc{p, n})
|
||||
}
|
||||
sort.Slice(ns, func(i, j int) bool {
|
||||
if ns[i].n != ns[j].n {
|
||||
return ns[i].n > ns[j].n
|
||||
}
|
||||
return ns[i].p.String() < ns[j].p.String()
|
||||
})
|
||||
for i := 0; i < len(ns) && i < 10; i++ {
|
||||
o.Nets = append(o.Nets, ns[i].p.String())
|
||||
}
|
||||
type pc struct {
|
||||
p uint16
|
||||
n uint32
|
||||
}
|
||||
var ps []pc
|
||||
for p, n := range bs.ports {
|
||||
ps = append(ps, pc{p, n})
|
||||
}
|
||||
sort.Slice(ps, func(i, j int) bool {
|
||||
if ps[i].n != ps[j].n {
|
||||
return ps[i].n > ps[j].n
|
||||
}
|
||||
return ps[i].p < ps[j].p
|
||||
})
|
||||
for i := 0; i < len(ps) && i < 10; i++ {
|
||||
o.Ports = append(o.Ports, ps[i].p)
|
||||
}
|
||||
return o
|
||||
}
|
||||
|
||||
// Report builds the analysis of [from, to] (unix seconds).
|
||||
func (e *Engine) Report(from, to int64) Report {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
if to <= from {
|
||||
to = from + 1
|
||||
}
|
||||
startH, endH := from/3600, to/3600
|
||||
if endH-startH > HourBuckets-1 {
|
||||
startH = endH - (HourBuckets - 1)
|
||||
}
|
||||
nb := int(endH-startH) + 1
|
||||
r := Report{Workloads: []WorkloadOut{}, TopDst: []DstOut{}, Findings: []Finding{},
|
||||
Timeline: Timeline{Start: startH * 3600, Step: 3600, Series: map[string][]uint32{}},
|
||||
Scanner: ScannerOut{Bursts: []BurstOut{}}}
|
||||
|
||||
fc := map[string]int{}
|
||||
for _, f := range e.findings {
|
||||
if f.Last >= from && f.First <= to {
|
||||
r.Findings = append(r.Findings, *f)
|
||||
fc[f.Workload]++
|
||||
}
|
||||
}
|
||||
sort.Slice(r.Findings, func(i, j int) bool {
|
||||
a, b := r.Findings[i], r.Findings[j]
|
||||
if sevRank[a.Severity] != sevRank[b.Severity] {
|
||||
return sevRank[a.Severity] > sevRank[b.Severity]
|
||||
}
|
||||
if a.Last != b.Last {
|
||||
return a.Last > b.Last
|
||||
}
|
||||
return a.ID < b.ID
|
||||
})
|
||||
|
||||
names := make([]string, 0, len(e.ws))
|
||||
for n := range e.ws {
|
||||
names = append(names, n)
|
||||
}
|
||||
sort.Strings(names)
|
||||
for _, n := range names {
|
||||
w := e.ws[n]
|
||||
o := WorkloadOut{Name: n, Role: w.role, Findings: fc[n]}
|
||||
series := make([]uint32, nb)
|
||||
ds, ps := map[uint32]struct{}{}, map[uint32]struct{}{}
|
||||
for h := startH; h <= endH; h++ {
|
||||
b := &w.hours[h%HourBuckets]
|
||||
if b.hour != h {
|
||||
continue
|
||||
}
|
||||
series[h-startH] = b.conns
|
||||
o.Conns += uint64(b.conns)
|
||||
o.Suppressed += uint64(b.supp)
|
||||
for _, x := range b.dsts {
|
||||
ds[x] = struct{}{}
|
||||
}
|
||||
for _, x := range b.ports {
|
||||
ps[x] = struct{}{}
|
||||
}
|
||||
}
|
||||
o.Dsts, o.Ports = len(ds), len(ps)
|
||||
if o.Conns == 0 && o.Suppressed == 0 && o.Findings == 0 {
|
||||
continue
|
||||
}
|
||||
r.Workloads = append(r.Workloads, o)
|
||||
r.Timeline.Series[n] = series
|
||||
}
|
||||
|
||||
type scored struct {
|
||||
ds *dstStat
|
||||
n uint64
|
||||
}
|
||||
var all []scored
|
||||
d0, d1 := int32(from/86400), int32(to/86400)
|
||||
for el := e.dsts.l.Front(); el != nil; el = el.Next() {
|
||||
ds := el.Value.(*lent[netip.Addr, *dstStat]).v
|
||||
var n uint64
|
||||
for _, d := range ds.days {
|
||||
if d.day >= d0 && d.day <= d1 {
|
||||
n += uint64(d.n)
|
||||
}
|
||||
}
|
||||
if n > 0 {
|
||||
all = append(all, scored{ds, n})
|
||||
}
|
||||
}
|
||||
sort.Slice(all, func(i, j int) bool {
|
||||
if all[i].n != all[j].n {
|
||||
return all[i].n > all[j].n
|
||||
}
|
||||
return all[i].ds.ip.Compare(all[j].ds.ip) < 0
|
||||
})
|
||||
for i := 0; i < len(all) && i < 50; i++ {
|
||||
ds := all[i].ds
|
||||
ports := append([]uint16(nil), ds.ports...)
|
||||
sort.Slice(ports, func(a, b int) bool { return ports[a] < ports[b] })
|
||||
r.TopDst = append(r.TopDst, DstOut{IP: ds.ip.String(), CC: ds.cc, ASN: ds.asn, Org: ds.og, Conns: all[i].n,
|
||||
Workloads: append([]string{}, ds.wls...), Ports: ports})
|
||||
}
|
||||
|
||||
for _, b := range e.closed {
|
||||
if b.End >= from && b.Start <= to {
|
||||
r.Scanner.Bursts = append(r.Scanner.Bursts, b)
|
||||
}
|
||||
}
|
||||
for _, n := range names {
|
||||
if w := e.ws[n]; w.burst != nil && w.role == RoleScanner && w.burst.lastFan >= from && w.burst.start <= to {
|
||||
r.Scanner.Bursts = append(r.Scanner.Bursts, w.burst.out(n, w.burst.lastFan))
|
||||
}
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
const (
|
||||
maxPeerWorkloads = 256
|
||||
maxPeerFindings = MaxFindings
|
||||
maxStr = 200
|
||||
)
|
||||
|
||||
func clip(s string) string {
|
||||
if len(s) > maxStr {
|
||||
return s[:maxStr]
|
||||
}
|
||||
return strings.ToValidUTF8(s, "")
|
||||
}
|
||||
|
||||
// Sanitize bounds an untrusted peer report and stamps it with the peer name.
|
||||
func (r *Report) Sanitize(host string) {
|
||||
if len(r.Workloads) > maxPeerWorkloads {
|
||||
r.Workloads = r.Workloads[:maxPeerWorkloads]
|
||||
}
|
||||
if len(r.Findings) > maxPeerFindings {
|
||||
r.Findings = r.Findings[:maxPeerFindings]
|
||||
}
|
||||
if len(r.TopDst) > 50 {
|
||||
r.TopDst = r.TopDst[:50]
|
||||
}
|
||||
if len(r.Scanner.Bursts) > maxClosedBurst+maxPeerWorkloads {
|
||||
r.Scanner.Bursts = r.Scanner.Bursts[:maxClosedBurst+maxPeerWorkloads]
|
||||
}
|
||||
for i := range r.Workloads {
|
||||
w := &r.Workloads[i]
|
||||
w.Name, w.Role, w.Host = clip(w.Name), clip(w.Role), host
|
||||
}
|
||||
for i := range r.Findings {
|
||||
f := &r.Findings[i]
|
||||
f.ID, f.Kind, f.Severity = host+":"+clip(f.ID), clip(f.Kind), clip(f.Severity)
|
||||
f.Workload, f.Dst, f.Proto, f.Detail, f.Host = clip(f.Workload), clip(f.Dst), clip(f.Proto), clip(f.Detail), host
|
||||
}
|
||||
for i := range r.TopDst {
|
||||
d := &r.TopDst[i]
|
||||
d.IP, d.CC, d.ASN, d.Org = clip(d.IP), clip(d.CC), clip(d.ASN), clip(d.Org)
|
||||
if len(d.Workloads) > 8 {
|
||||
d.Workloads = d.Workloads[:8]
|
||||
}
|
||||
for j := range d.Workloads {
|
||||
d.Workloads[j] = clip(d.Workloads[j])
|
||||
}
|
||||
if len(d.Ports) > 8 {
|
||||
d.Ports = d.Ports[:8]
|
||||
}
|
||||
}
|
||||
for i := range r.Scanner.Bursts {
|
||||
b := &r.Scanner.Bursts[i]
|
||||
b.Workload, b.Host = clip(b.Workload), host
|
||||
if len(b.Nets) > 10 {
|
||||
b.Nets = b.Nets[:10]
|
||||
}
|
||||
for j := range b.Nets {
|
||||
b.Nets[j] = clip(b.Nets[j])
|
||||
}
|
||||
if len(b.Ports) > 10 {
|
||||
b.Ports = b.Ports[:10]
|
||||
}
|
||||
}
|
||||
for k, v := range r.Timeline.Series {
|
||||
if len(v) > HourBuckets {
|
||||
r.Timeline.Series[k] = v[:HourBuckets]
|
||||
}
|
||||
}
|
||||
if len(r.Timeline.Series) > maxPeerWorkloads {
|
||||
r.Timeline.Series = map[string][]uint32{}
|
||||
}
|
||||
}
|
||||
|
||||
// Merge adds a sanitized peer report to r (the hub view). Series are keyed
|
||||
// "host/workload" and placed on r's hourly grid.
|
||||
func (r *Report) Merge(o Report, host string) {
|
||||
r.Workloads = append(r.Workloads, o.Workloads...)
|
||||
r.Findings = append(r.Findings, o.Findings...)
|
||||
r.Scanner.Bursts = append(r.Scanner.Bursts, o.Scanner.Bursts...)
|
||||
r.TopDst = append(r.TopDst, o.TopDst...)
|
||||
sort.SliceStable(r.TopDst, func(i, j int) bool { return r.TopDst[i].Conns > r.TopDst[j].Conns })
|
||||
if len(r.TopDst) > 50 {
|
||||
r.TopDst = r.TopDst[:50]
|
||||
}
|
||||
sort.SliceStable(r.Findings, func(i, j int) bool {
|
||||
a, b := r.Findings[i], r.Findings[j]
|
||||
if sevRank[a.Severity] != sevRank[b.Severity] {
|
||||
return sevRank[a.Severity] > sevRank[b.Severity]
|
||||
}
|
||||
return a.Last > b.Last
|
||||
})
|
||||
if len(r.Findings) > MaxFindings {
|
||||
r.Findings = r.Findings[:MaxFindings]
|
||||
}
|
||||
if r.Timeline.Step == 0 {
|
||||
r.Timeline.Step = 3600
|
||||
}
|
||||
for k, v := range o.Timeline.Series {
|
||||
if r.Timeline.Start == 0 {
|
||||
r.Timeline.Start = o.Timeline.Start
|
||||
}
|
||||
n := len(v)
|
||||
off := int((o.Timeline.Start - r.Timeline.Start) / 3600)
|
||||
for _, ex := range r.Timeline.Series {
|
||||
n = len(ex)
|
||||
break
|
||||
}
|
||||
dst := make([]uint32, n)
|
||||
for i, x := range v {
|
||||
if j := i + off; j >= 0 && j < n {
|
||||
dst[j] = x
|
||||
}
|
||||
}
|
||||
r.Timeline.Series[host+"/"+k] = dst
|
||||
}
|
||||
}
|
||||
|
||||
// Stamp marks the items of a trusted (local) report with its host name, as
|
||||
// Sanitize does for a peer, so that a hub view can tell them apart.
|
||||
func (r *Report) Stamp(host string) {
|
||||
for i := range r.Workloads {
|
||||
r.Workloads[i].Host = host
|
||||
}
|
||||
for i := range r.Findings {
|
||||
r.Findings[i].Host = host
|
||||
r.Findings[i].ID = host + ":" + r.Findings[i].ID
|
||||
}
|
||||
for i := range r.Scanner.Bursts {
|
||||
r.Scanner.Bursts[i].Host = host
|
||||
}
|
||||
}
|
||||
|
||||
// EmptyReport is a well-formed report without data.
|
||||
func EmptyReport() Report {
|
||||
return Report{Workloads: []WorkloadOut{}, TopDst: []DstOut{}, Findings: []Finding{}, Scanner: ScannerOut{Bursts: []BurstOut{}},
|
||||
Timeline: Timeline{Step: 3600, Series: map[string][]uint32{}}}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package egress
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"os"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/tail"
|
||||
)
|
||||
|
||||
const maxLine = 16 * 1024
|
||||
|
||||
// Source follows the egress log file and feeds the engine. State is in memory
|
||||
// only: on start the rotated backups and the live file are replayed from the
|
||||
// beginning, which rebuilds the beacon history deterministically.
|
||||
type Source struct {
|
||||
Path string
|
||||
E *Engine
|
||||
Log *slog.Logger
|
||||
backfilling atomic.Bool
|
||||
fol atomic.Pointer[tail.Follower]
|
||||
}
|
||||
|
||||
// NewSource creates the source of e reading path.
|
||||
func NewSource(path string, e *Engine, log *slog.Logger) *Source {
|
||||
if log == nil {
|
||||
log = slog.Default()
|
||||
}
|
||||
s := &Source{Path: path, E: e, Log: log}
|
||||
f := s.state
|
||||
e.stateFn.Store(&f)
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *Source) state() string {
|
||||
switch f := s.fol.Load(); {
|
||||
case s.backfilling.Load():
|
||||
return "backfill"
|
||||
case f == nil:
|
||||
return "waiting"
|
||||
default:
|
||||
if err := f.Err(); err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return "waiting"
|
||||
}
|
||||
return "error"
|
||||
}
|
||||
}
|
||||
return "following"
|
||||
}
|
||||
|
||||
// Status is the source line for the sources panel.
|
||||
func (s *Source) Status() store.SourceStatus {
|
||||
l, m, last := s.E.counters()
|
||||
st := store.SourceStatus{Name: "egress", Path: s.Path, State: s.state(), Lines: l, Malformed: m, LastEvent: last}
|
||||
if st.State == "error" {
|
||||
st.Error = "read error"
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
// Start launches the single goroutine of the source; it stops with ctx.
|
||||
func (s *Source) Start(ctx context.Context, wg *sync.WaitGroup) {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
defer func() {
|
||||
if p := recover(); p != nil {
|
||||
s.Log.Error("egress source stopped by a panic", "panic", p)
|
||||
}
|
||||
}()
|
||||
s.backfilling.Store(true)
|
||||
for _, b := range tail.Backups(s.Path) {
|
||||
if ctx.Err() != nil {
|
||||
break
|
||||
}
|
||||
if err := tail.ReadAll(b, maxLine, s.E.Ingest, func() { s.E.malformed.Add(1) }); err != nil {
|
||||
s.Log.Warn("egress backfill failed", "file", b, "err", err)
|
||||
}
|
||||
}
|
||||
s.backfilling.Store(false)
|
||||
f := tail.NewFollower(s.Path, tail.Pos{})
|
||||
f.MaxLine, f.Handle = maxLine, s.E.Ingest
|
||||
f.Oversize = func() { s.E.malformed.Add(1) }
|
||||
s.fol.Store(f)
|
||||
f.Run(ctx)
|
||||
}()
|
||||
}
|
||||
|
||||
// SourceInfo is the "source" object of the API.
|
||||
type SourceInfo struct {
|
||||
State string `json:"state"`
|
||||
Lines uint64 `json:"lines"`
|
||||
Malformed uint64 `json:"malformed"`
|
||||
Last int64 `json:"last"`
|
||||
}
|
||||
|
||||
// Info reports the source state (state "disabled" when no source is attached).
|
||||
func (e *Engine) Info() SourceInfo {
|
||||
l, m, last := e.counters()
|
||||
st := "disabled"
|
||||
if f := e.stateFn.Load(); f != nil {
|
||||
st = (*f)()
|
||||
}
|
||||
return SourceInfo{State: st, Lines: l, Malformed: m, Last: last}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
package egress
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"net/netip"
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Roles of a workload.
|
||||
const (
|
||||
RoleDefault = "default"
|
||||
RoleScanner = "scanner"
|
||||
RoleMail = "mail"
|
||||
RoleResolver = "resolver"
|
||||
)
|
||||
|
||||
func validRole(r string) bool {
|
||||
return r == RoleDefault || r == RoleScanner || r == RoleMail || r == RoleResolver
|
||||
}
|
||||
|
||||
type matcher struct {
|
||||
prefix netip.Prefix // valid when name == "" and !host
|
||||
name string // container name: exact base name, or a prefix when pfx
|
||||
pfx bool
|
||||
host bool // the host's own output ("host")
|
||||
}
|
||||
|
||||
type workloadDef struct {
|
||||
name, role string
|
||||
m []matcher
|
||||
}
|
||||
|
||||
// ParseWorkloads parses "name=ITEM,ITEM:role;name2=...". An ITEM is a CIDR, an
|
||||
// IP, "host" (the host's own output, so it can take a role such as mail),
|
||||
// "name:<container name>" (exact base name, without the -<digits> suffix) or
|
||||
// "name:<prefix>*" (explicit prefix); the role (scanner, mail, resolver,
|
||||
// default) follows the last colon.
|
||||
func ParseWorkloads(s string) ([]workloadDef, error) {
|
||||
var out []workloadDef
|
||||
for _, part := range strings.Split(s, ";") {
|
||||
part = strings.TrimSpace(part)
|
||||
if part == "" {
|
||||
continue
|
||||
}
|
||||
name, rest, ok := strings.Cut(part, "=")
|
||||
name, rest = strings.TrimSpace(name), strings.TrimSpace(rest)
|
||||
if !ok || name == "" || rest == "" {
|
||||
return nil, fmt.Errorf("workload %q: expected name=items[:role]", part)
|
||||
}
|
||||
role := RoleDefault
|
||||
if i := strings.LastIndex(rest, ":"); i >= 0 && validRole(rest[i+1:]) {
|
||||
role, rest = rest[i+1:], rest[:i]
|
||||
}
|
||||
w := workloadDef{name: name, role: role}
|
||||
for _, it := range strings.Split(rest, ",") {
|
||||
it = strings.TrimSpace(it)
|
||||
switch {
|
||||
case it == "":
|
||||
case it == "host":
|
||||
w.m = append(w.m, matcher{host: true})
|
||||
case strings.HasPrefix(it, "name:"):
|
||||
p := strings.TrimPrefix(it, "name:")
|
||||
pfx := strings.HasSuffix(p, "*")
|
||||
p = strings.TrimSuffix(p, "*")
|
||||
if !nameRe.MatchString(p) {
|
||||
return nil, fmt.Errorf("workload %q: bad container name %q", name, p)
|
||||
}
|
||||
w.m = append(w.m, matcher{name: p, pfx: pfx})
|
||||
default:
|
||||
pf, err := netip.ParsePrefix(it)
|
||||
if err != nil {
|
||||
a, err2 := netip.ParseAddr(it)
|
||||
if err2 != nil {
|
||||
return nil, fmt.Errorf("workload %q: bad address %q", name, it)
|
||||
}
|
||||
pf = netip.PrefixFrom(a.Unmap(), a.Unmap().BitLen())
|
||||
}
|
||||
w.m = append(w.m, matcher{prefix: pf.Masked()})
|
||||
}
|
||||
}
|
||||
if len(w.m) == 0 {
|
||||
return nil, fmt.Errorf("workload %q: no addresses", name)
|
||||
}
|
||||
out = append(out, w)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
var nameRe = regexp.MustCompile(`^[A-Za-z0-9_.-]{1,128}$`)
|
||||
var tsSuffix = regexp.MustCompile(`-\d{9,}$`)
|
||||
var digitSuffix = regexp.MustCompile(`-\d+$`)
|
||||
|
||||
// ContainerBase strips the "-<timestamp>" suffix of a container name.
|
||||
func ContainerBase(n string) string { return tsSuffix.ReplaceAllString(n, "") }
|
||||
|
||||
const maxMapLines = 10000
|
||||
|
||||
// LoadContainers reads a containers.map file ("<ip> <name>" per line; invalid
|
||||
// lines are skipped, at most 10k lines).
|
||||
func LoadContainers(path string) (map[netip.Addr]string, error) {
|
||||
fh, err := os.Open(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer fh.Close()
|
||||
m := map[netip.Addr]string{}
|
||||
sc := bufio.NewScanner(fh)
|
||||
sc.Buffer(make([]byte, 0, 4096), 4096)
|
||||
for n := 0; sc.Scan() && n < maxMapLines; n++ {
|
||||
f := strings.Fields(sc.Text())
|
||||
if len(f) != 2 || !nameRe.MatchString(f[1]) {
|
||||
continue
|
||||
}
|
||||
a, err := netip.ParseAddr(f[0])
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
m[a.Unmap()] = f[1]
|
||||
}
|
||||
return m, sc.Err()
|
||||
}
|
||||
|
||||
// resolve names the workload of an event: host output is "host"; a container
|
||||
// address matches the configured workloads (CIDR or container name from the
|
||||
// current map); otherwise it is named after its mapped container (without the
|
||||
// timestamp suffix) or "container <ip>".
|
||||
func (e *Engine) resolve(ev Event) (name, role string) {
|
||||
if ev.Host {
|
||||
for _, w := range e.wls {
|
||||
for _, m := range w.m {
|
||||
if m.host {
|
||||
return w.name, w.role
|
||||
}
|
||||
}
|
||||
}
|
||||
return "host", RoleDefault
|
||||
}
|
||||
cname := e.containers[ev.Src]
|
||||
for _, w := range e.wls {
|
||||
for _, m := range w.m {
|
||||
if m.host {
|
||||
continue
|
||||
}
|
||||
if m.name != "" {
|
||||
if cname != "" && m.matchName(cname) {
|
||||
return w.name, w.role
|
||||
}
|
||||
} else if m.prefix.Contains(ev.Src) {
|
||||
return w.name, w.role
|
||||
}
|
||||
}
|
||||
}
|
||||
if cname != "" {
|
||||
return ContainerBase(cname), RoleDefault
|
||||
}
|
||||
return "container " + ev.Src.String(), RoleDefault
|
||||
}
|
||||
|
||||
// matchName compares a container name: the exact base name (the full name or
|
||||
// without a -<digits> suffix), or a prefix when the item ended in "*".
|
||||
func (m matcher) matchName(cname string) bool {
|
||||
if m.pfx {
|
||||
return strings.HasPrefix(cname, m.name)
|
||||
}
|
||||
return cname == m.name || digitSuffix.ReplaceAllString(cname, "") == m.name
|
||||
}
|
||||
@@ -0,0 +1,497 @@
|
||||
package enforce
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/netip"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
|
||||
)
|
||||
|
||||
var t0 = time.Date(2026, 11, 14, 22, 0, 0, 0, time.UTC)
|
||||
|
||||
func TestDecide(t *testing.T) {
|
||||
p := Params{Threshold: 5}
|
||||
cases := []struct {
|
||||
name string
|
||||
in Input
|
||||
act string
|
||||
why string
|
||||
}{
|
||||
{"below", Input{Attacks: 4, Top: ReasonScannerFlood}, ActNone, ""},
|
||||
{"threshold", Input{Attacks: 5, Top: ReasonWPBrute}, ActBan, ReasonWPBrute},
|
||||
{"critical single hit", Input{Crit: ReasonEnvProbe, Crits: 1, Attacks: 1}, ActNone, ""},
|
||||
{"critical two hits", Input{Crit: ReasonEnvProbe, Crits: 2, Attacks: 2}, ActBan, ReasonEnvProbe},
|
||||
{"ssh", Input{SSHFails: 5}, ActBan, ReasonSSHBrute},
|
||||
{"ssh below", Input{SSHFails: 4}, ActNone, ""},
|
||||
{"trusted", Input{Attacks: 9, Exclude: SkipTrusted}, ActSkip, ""},
|
||||
{"crawler", Input{Crit: ReasonRCE, Crits: 2, Exclude: SkipCrawler}, ActSkip, ""},
|
||||
{"infra", Input{Crit: ReasonRCE, Crits: 2, Exclude: SkipInfra}, ActSkip, ""},
|
||||
{"legit doubles", Input{Attacks: 9, Legit: true, Top: ReasonScannerFlood}, ActNone, ""},
|
||||
{"legit doubles ok", Input{Attacks: 10, Legit: true, Top: ReasonScannerFlood}, ActBan, ReasonScannerFlood},
|
||||
{"legit never stops crit", Input{Crit: ReasonRCE, Crits: 2, Attacks: 2, Legit: true}, ActBan, ReasonRCE},
|
||||
{"legit one crit", Input{Crit: ReasonRCE, Crits: 1, Attacks: 1, Legit: true}, ActNone, ""},
|
||||
{"legit ssh", Input{SSHFails: 9, Legit: true}, ActNone, ""},
|
||||
{"already", Input{Attacks: 5, Top: ReasonScannerFlood, Banned: true}, ActAlready, ""},
|
||||
{"active", Input{Attacks: 5, Top: ReasonScannerFlood, Active: true}, ActActive, ""},
|
||||
}
|
||||
for _, c := range cases {
|
||||
d := Decide(c.in, p)
|
||||
if d.Action != c.act || (c.why != "" && d.Reason != c.why) {
|
||||
t.Errorf("%s: %+v", c.name, d)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTTLEscalation(t *testing.T) {
|
||||
want := []time.Duration{time.Hour, 6 * time.Hour, 24 * time.Hour, 7 * 24 * time.Hour, 7 * 24 * time.Hour}
|
||||
for i, w := range want {
|
||||
if TTLFor(i) != w {
|
||||
t.Errorf("offence %d: %v", i, TTLFor(i))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestExclusions(t *testing.T) {
|
||||
x := Exclusions{Trusted: []netip.Prefix{netip.MustParsePrefix("45.0.0.0/8")}, Peers: map[netip.Addr]bool{netip.MustParseAddr("46.1.1.1"): true},
|
||||
Infra: map[netip.Addr]bool{netip.MustParseAddr("47.1.1.1"): true}}
|
||||
for ip, want := range map[string]string{
|
||||
"10.1.2.3": SkipPrivate, "127.0.0.1": SkipPrivate, "169.254.1.1": SkipPrivate, "100.64.1.1": SkipPrivate,
|
||||
"::1": SkipPrivate, "fe80::1": SkipPrivate, "fc00::1": SkipPrivate, "ff02::1": SkipPrivate, "224.0.0.1": SkipPrivate,
|
||||
"240.0.0.1": SkipPrivate, "0.0.0.0": SkipPrivate, "::ffff:10.0.0.1": SkipPrivate, "2001:db8::1": SkipPrivate,
|
||||
"45.9.9.9": SkipTrusted, "47.1.1.1": SkipInfra, "46.1.1.1": SkipPeer, "::ffff:46.1.1.1": SkipPeer,
|
||||
"8.8.8.8": SkipInfra, "2606:4700::1111": SkipInfra, "104.16.1.1": SkipInfra, "2a06:98c0::1": SkipInfra, "93.184.216.34": "",
|
||||
} {
|
||||
if got := x.Excluded(netip.MustParseAddr(ip)); got != want {
|
||||
t.Errorf("%s: %q want %q", ip, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func atk(ip string, at time.Time, path string, st int) core.Event {
|
||||
return core.Event{Time: at, IP: ip, Cat: core.Scanner, Source: "traefik", Method: "GET", Path: path, Status: st, UA: "x"}
|
||||
}
|
||||
|
||||
type rig struct {
|
||||
e *Engine
|
||||
now time.Time
|
||||
log string
|
||||
}
|
||||
|
||||
func newRig(t *testing.T, mode string, mod func(*Config)) *rig {
|
||||
r := &rig{now: t0, log: filepath.Join(t.TempDir(), "enf", "decisions.log")}
|
||||
c := Config{Mode: mode, Path: r.log, StatePath: filepath.Join(t.TempDir(), "enforce.json"), Host: "oracle", Threshold: 5, MaxPerMin: 60,
|
||||
Trusted: []netip.Prefix{netip.MustParsePrefix("45.0.0.0/8")}, Now: func() time.Time { return r.now }}
|
||||
if mod != nil {
|
||||
mod(&c)
|
||||
}
|
||||
r.e = New(c)
|
||||
return r
|
||||
}
|
||||
|
||||
func (r *rig) lines(t *testing.T) []string {
|
||||
b, err := os.ReadFile(r.log)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return strings.Split(strings.TrimSpace(string(b)), "\n")
|
||||
}
|
||||
|
||||
func (r *rig) hits(ip string, n int, path string, st int) {
|
||||
for i := 0; i < n; i++ {
|
||||
r.e.process(atk(ip, r.now.Add(-time.Duration(i)*time.Second), path, st), "")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEngineThresholdAndLine(t *testing.T) {
|
||||
r := newRig(t, ModeOn, nil)
|
||||
r.hits("203.0.114.7", 4, "/x", 404)
|
||||
if len(r.lines(t)) != 0 {
|
||||
t.Fatal("banned below threshold")
|
||||
}
|
||||
r.hits("203.0.114.7", 1, "/x", 404)
|
||||
l := r.lines(t)
|
||||
if len(l) != 1 || !strings.HasPrefix(l[0], "2026-11-14T22:00:00Z urutau decision=ban ip=203.0.114.7 reason=scanner-flood score=") ||
|
||||
!strings.HasSuffix(l[0], " ttl=3600 host=oracle src=local") {
|
||||
t.Fatalf("line %q", l)
|
||||
}
|
||||
// dedupe: more hits while the TTL holds write nothing
|
||||
r.hits("203.0.114.7", 10, "/x", 404)
|
||||
if len(r.lines(t)) != 1 {
|
||||
t.Fatal("rewrote during TTL")
|
||||
}
|
||||
// escalation after the TTL: 6 h, persisted
|
||||
r.now = r.now.Add(61 * time.Minute)
|
||||
r.hits("203.0.114.7", 5, "/x", 404)
|
||||
l = r.lines(t)
|
||||
if len(l) != 2 || !strings.Contains(l[1], "ttl=21600") {
|
||||
t.Fatalf("escalation %q", l)
|
||||
}
|
||||
r.e.saveState()
|
||||
e2 := New(r.e.cfg)
|
||||
if e2.bans[netip.MustParseAddr("203.0.114.7")].Offences != 2 {
|
||||
t.Fatalf("state %+v", e2.bans)
|
||||
}
|
||||
if fi, err := os.Stat(r.log); err != nil || fi.Mode().Perm() != 0o640 {
|
||||
t.Fatalf("mode %v %v", fi, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEngineCriticalAndFamily(t *testing.T) {
|
||||
r := newRig(t, ModeOn, nil)
|
||||
ev := atk("203.0.114.8", r.now, "/.env", 404)
|
||||
ev.Cat = core.Exploit
|
||||
r.e.process(ev, intel.FamEnvCreds)
|
||||
if len(r.lines(t)) != 0 {
|
||||
t.Fatal("a single critical hit banned")
|
||||
}
|
||||
ev.Time = r.now.Add(time.Second)
|
||||
r.e.process(ev, intel.FamEnvCreds)
|
||||
ev2 := atk("203.0.114.9", r.now, "/wp-login.php", 404)
|
||||
r.e.process(ev2, intel.FamWordPress)
|
||||
l := r.lines(t)
|
||||
if len(l) != 1 || !strings.Contains(l[0], "reason=env-probe") {
|
||||
t.Fatalf("%q", l)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEngineNeverCounts(t *testing.T) {
|
||||
r := newRig(t, ModeOn, nil)
|
||||
for _, st := range []int{404, 400, 405, 500, 502} {
|
||||
ev := atk("203.0.114.10", r.now, "/x", st)
|
||||
ev.Cat = core.NotFound // a plain 404 is not an attack category
|
||||
for i := 0; i < 20; i++ {
|
||||
r.e.process(ev, "")
|
||||
}
|
||||
}
|
||||
// app and proxy errors on attack-category requests do not count either
|
||||
for i := 0; i < 20; i++ {
|
||||
ev := atk("203.0.114.11", r.now, "/x", 500)
|
||||
ev.Proto, ev.Router, ev.OriginStatus = "HTTP/2", "r@docker", 500
|
||||
r.e.process(ev, "")
|
||||
ev = atk("203.0.114.11", r.now, "/x", 502)
|
||||
ev.Proto, ev.Router, ev.Retries = "HTTP/2", "r@docker", 2
|
||||
r.e.process(ev, "")
|
||||
fr := atk("203.0.114.11", r.now, "/x", 404)
|
||||
fr.Framed = true
|
||||
r.e.process(fr, "")
|
||||
}
|
||||
if len(r.lines(t)) != 0 {
|
||||
t.Fatalf("banned: %q", r.lines(t))
|
||||
}
|
||||
}
|
||||
|
||||
func TestEngineExclusionsAndCounts(t *testing.T) {
|
||||
r := newRig(t, ModeOn, func(c *Config) {
|
||||
c.Crawler = func(ip string, uas []string) bool { return ip == "66.249.66.1" }
|
||||
c.PeerHosts = []string{"46.1.1.1"}
|
||||
})
|
||||
r.hits("45.1.1.1", 6, "/x", 404)
|
||||
r.hits("10.0.0.5", 6, "/x", 404)
|
||||
r.hits("46.1.1.1", 6, "/x", 404)
|
||||
r.hits("66.249.66.1", 6, "/x", 404)
|
||||
if len(r.lines(t)) != 0 {
|
||||
t.Fatalf("banned excluded: %q", r.lines(t))
|
||||
}
|
||||
rep := r.e.Report(0)
|
||||
for _, k := range []string{SkipTrusted, SkipPrivate, SkipPeer, SkipCrawler} {
|
||||
if rep.Counts.Skipped[k] != 1 {
|
||||
t.Errorf("skip %s: %v", k, rep.Counts.Skipped)
|
||||
}
|
||||
}
|
||||
// the skip is reported once, not once per event
|
||||
r.hits("45.1.1.1", 30, "/x", 404)
|
||||
if r.e.Report(0).Counts.Skipped[SkipTrusted] != 1 {
|
||||
t.Fatal("skip spam")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEngineLegitVisitor(t *testing.T) {
|
||||
r := newRig(t, ModeOn, nil)
|
||||
vis := core.Event{Time: r.now.Add(-time.Hour), IP: "203.0.114.20", Cat: core.OK, Source: "traefik", Status: 200, FetchDest: "document"}
|
||||
r.e.process(vis, "")
|
||||
ev := atk("203.0.114.20", r.now, "/.env", 404)
|
||||
ev.Cat = core.Exploit
|
||||
r.e.process(ev, intel.FamEnvCreds)
|
||||
r.hits("203.0.114.20", 7, "/x", 404)
|
||||
if len(r.lines(t)) != 0 {
|
||||
t.Fatalf("legit banned: %q", r.lines(t))
|
||||
}
|
||||
r.hits("203.0.114.20", 2, "/y", 404)
|
||||
if len(r.lines(t)) != 1 {
|
||||
t.Fatalf("legit double threshold: %q", r.lines(t))
|
||||
}
|
||||
}
|
||||
|
||||
func TestEngineAlreadyBlocked(t *testing.T) {
|
||||
r := newRig(t, ModeOn, nil)
|
||||
r.e.process(core.Event{Time: r.now, IP: "203.0.114.30", Cat: core.Ban, Source: "fail2ban", Jail: "sshd"}, "")
|
||||
r.hits("203.0.114.30", 8, "/x", 404)
|
||||
if len(r.lines(t)) != 0 || r.e.Report(0).Counts.AlreadyBlocked != 1 {
|
||||
t.Fatalf("%q %+v", r.lines(t), r.e.Report(0).Counts)
|
||||
}
|
||||
rep := r.e.Report(0)
|
||||
if rep.Coverage.AttackIPs != 1 || rep.Coverage.BlockedByFirewall != 1 {
|
||||
t.Fatalf("coverage %+v", rep.Coverage)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEngineSSH(t *testing.T) {
|
||||
r := newRig(t, ModeOn, nil)
|
||||
for i := 0; i < 5; i++ {
|
||||
r.e.process(core.Event{Time: r.now.Add(-time.Duration(i) * time.Minute), IP: "203.0.114.40", Cat: core.SSHFail, Source: "ssh", User: "root"}, "")
|
||||
}
|
||||
if l := r.lines(t); len(l) != 1 || !strings.Contains(l[0], "reason=ssh-bruteforce") {
|
||||
t.Fatalf("%q", l)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEngineRateCapAndObserve(t *testing.T) {
|
||||
r := newRig(t, ModeOn, func(c *Config) { c.MaxPerMin = 3 })
|
||||
for i := 0; i < 6; i++ {
|
||||
r.hits(fmt.Sprintf("203.0.114.%d", 50+i), 5, "/x", 404)
|
||||
}
|
||||
rep := r.e.Report(0)
|
||||
if len(r.lines(t)) != 3 || rep.Counts.Written != 3 || rep.Counts.DroppedRate != 3 || rep.Counts.Decided != 6 {
|
||||
t.Fatalf("%q %+v", r.lines(t), rep.Counts)
|
||||
}
|
||||
o := newRig(t, ModeObserve, nil)
|
||||
o.hits("203.0.114.60", 5, "/x", 404)
|
||||
rep = o.e.Report(0)
|
||||
if _, err := os.Stat(o.log); err == nil {
|
||||
t.Fatal("observe wrote the file")
|
||||
}
|
||||
if len(rep.Recent) != 1 || rep.Recent[0].Action != "would_ban" || rep.Coverage.WouldBlock != 1 || rep.Counts.Written != 0 {
|
||||
t.Fatalf("%+v", rep)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOldEventsDoNotBan(t *testing.T) {
|
||||
r := newRig(t, ModeOn, nil)
|
||||
for i := 0; i < 20; i++ {
|
||||
r.e.process(atk("203.0.114.70", r.now.Add(-3*time.Hour), "/x", 404), "")
|
||||
}
|
||||
if len(r.lines(t)) != 0 {
|
||||
t.Fatal("replayed events banned")
|
||||
}
|
||||
if r.e.Report(0).Coverage.AttackIPs != 1 {
|
||||
t.Fatal("coverage lost old events")
|
||||
}
|
||||
}
|
||||
|
||||
func TestObserveNeverBlocks(t *testing.T) {
|
||||
e := New(Config{Mode: ModeOn, Path: filepath.Join(t.TempDir(), "d.log")})
|
||||
for i := 0; i < 10000; i++ {
|
||||
e.Observe(atk("203.0.114.1", t0, "/x", 404), "")
|
||||
}
|
||||
if e.dropQ.Load() == 0 {
|
||||
t.Fatal("full queue must drop and count")
|
||||
}
|
||||
}
|
||||
|
||||
func (r *rig) seen(ip string) { r.hits(ip, 2, "/x", 404) }
|
||||
|
||||
func TestAcceptPeer(t *testing.T) {
|
||||
r := newRig(t, ModeOn, nil)
|
||||
r.seen("203.0.114.80")
|
||||
acc, bad := r.e.AcceptPeer("hostinger", []Wire{
|
||||
{T: t0.Unix(), IP: "203.0.114.80", Reason: ReasonRCE, Score: 90, TTL: 3600},
|
||||
{T: t0.Unix(), IP: "203.0.114.81", Reason: "evil\nreason", Score: 90, TTL: 3600},
|
||||
{T: t0.Unix(), IP: "10.0.0.1", Reason: ReasonRCE, TTL: 3600},
|
||||
{T: t0.Unix(), IP: "45.2.2.2", Reason: ReasonRCE, TTL: 3600},
|
||||
{T: t0.Unix(), IP: "nope", Reason: ReasonRCE, TTL: 3600},
|
||||
})
|
||||
l := r.lines(t)
|
||||
if acc != 1 || bad != 3 || len(l) != 1 || !strings.HasSuffix(l[0], "src=peer:hostinger") {
|
||||
t.Fatalf("%d %d %q", acc, bad, l)
|
||||
}
|
||||
if len(r.e.LocalSince(0)) != 0 {
|
||||
t.Fatal("peer decisions must not be re-shared")
|
||||
}
|
||||
if r.e.Report(0).Counts.Skipped[SkipTrusted] != 1 {
|
||||
t.Fatalf("%+v", r.e.Report(0).Counts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAcceptPeerUnconfirmedTTLAndInfra(t *testing.T) {
|
||||
r := newRig(t, ModeOn, nil)
|
||||
r.seen("203.0.114.90")
|
||||
r.seen("1.1.1.1")
|
||||
r.seen("104.16.5.5")
|
||||
acc, _ := r.e.AcceptPeer("h", []Wire{
|
||||
{T: t0.Unix(), IP: "203.0.114.99", Reason: ReasonRCE, Score: 90, TTL: 3600}, // never seen here
|
||||
{T: t0.Unix(), IP: "203.0.114.90", Reason: ReasonRCE, Score: 90, TTL: 7 * 24 * 3600},
|
||||
{T: t0.Unix(), IP: "1.1.1.1", Reason: ReasonRCE, Score: 90, TTL: 3600},
|
||||
{T: t0.Unix(), IP: "104.16.5.5", Reason: ReasonRCE, Score: 90, TTL: 3600},
|
||||
})
|
||||
l := r.lines(t)
|
||||
if acc != 1 || len(l) != 1 || !strings.Contains(l[0], "ip=203.0.114.90") || !strings.Contains(l[0], "ttl=21600") {
|
||||
t.Fatalf("%d %q", acc, l)
|
||||
}
|
||||
sk := r.e.Report(0).Counts.Skipped
|
||||
if sk[SkipUnconfirmed] != 1 || sk[SkipInfra] < 2 {
|
||||
t.Fatalf("%v", sk)
|
||||
}
|
||||
// an attack seen only long ago does not confirm
|
||||
r2 := newRig(t, ModeOn, nil)
|
||||
for i := 0; i < 3; i++ {
|
||||
r2.e.process(atk("203.0.114.91", r2.now.Add(-8*24*time.Hour), "/x", 404), "")
|
||||
}
|
||||
if acc, _ := r2.e.AcceptPeer("h", []Wire{{T: t0.Unix(), IP: "203.0.114.91", Reason: ReasonRCE, TTL: 60}}); acc != 0 {
|
||||
t.Fatal("stale confirmation accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInfraNeverBannedLocally(t *testing.T) {
|
||||
r := newRig(t, ModeOn, func(c *Config) {
|
||||
c.PeerHosts = []string{"hub.example"}
|
||||
c.InfraHosts = []string{"hub.example"}
|
||||
c.LocalAddrs = func() []netip.Addr { return []netip.Addr{netip.MustParseAddr("203.0.114.200")} }
|
||||
c.Resolve = func(string) []netip.Addr { return []netip.Addr{netip.MustParseAddr("203.0.114.201")} }
|
||||
})
|
||||
for _, ip := range []string{"104.16.9.9", "8.8.4.4", "2606:4700:4700::1001", "203.0.114.200", "203.0.114.201"} {
|
||||
r.hits(ip, 9, "/x", 404)
|
||||
}
|
||||
if len(r.lines(t)) != 0 {
|
||||
t.Fatalf("infra banned: %q", r.lines(t))
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerResolutionKeepsLastGood(t *testing.T) {
|
||||
fail := false
|
||||
r := newRig(t, ModeOn, func(c *Config) {
|
||||
c.PeerHosts = []string{"peer.example"}
|
||||
c.Resolve = func(string) []netip.Addr {
|
||||
if fail {
|
||||
return nil
|
||||
}
|
||||
return []netip.Addr{netip.MustParseAddr("203.0.114.210")}
|
||||
}
|
||||
})
|
||||
fail = true
|
||||
r.e.refreshPeers()
|
||||
r.hits("203.0.114.210", 9, "/x", 404)
|
||||
if len(r.lines(t)) != 0 {
|
||||
t.Fatal("peer banned after DNS failure")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCriticalNeedsTwoHits(t *testing.T) {
|
||||
r := newRig(t, ModeOn, nil)
|
||||
mk := func(at time.Time) {
|
||||
ev := atk("203.0.114.220", at, "/.env", 404)
|
||||
ev.Cat = core.Exploit
|
||||
r.e.process(ev, intel.FamEnvCreds)
|
||||
}
|
||||
mk(r.now)
|
||||
if len(r.lines(t)) != 0 {
|
||||
t.Fatal("one hit")
|
||||
}
|
||||
// a forged legitimate visit does not cancel a critical ban
|
||||
r.e.process(core.Event{Time: r.now, IP: "203.0.114.220", Cat: core.OK, Source: "traefik", Status: 200, FetchDest: "document"}, "")
|
||||
mk(r.now.Add(time.Second))
|
||||
if len(r.lines(t)) != 1 {
|
||||
t.Fatalf("legit visit blocked crit ban: %q", r.lines(t))
|
||||
}
|
||||
}
|
||||
|
||||
func TestWouldAndBansPruned(t *testing.T) {
|
||||
r := newRig(t, ModeObserve, nil)
|
||||
r.e.mu.Lock()
|
||||
for i := 0; i < maxTracked+10; i++ {
|
||||
a := netip.AddrFrom4([4]byte{50, byte(i >> 16), byte(i >> 8), byte(i)})
|
||||
r.e.would[a] = r.now.Add(time.Hour).Unix()
|
||||
r.e.bans[a] = banRec{Until: r.now.Unix(), Last: r.now.Unix(), Offences: 1}
|
||||
}
|
||||
r.e.would[netip.MustParseAddr("51.0.0.1")] = r.now.Add(-48 * time.Hour).Unix()
|
||||
r.e.trimMaps(r.now)
|
||||
nw, nb := len(r.e.would), len(r.e.bans)
|
||||
_, old := r.e.would[netip.MustParseAddr("51.0.0.1")]
|
||||
r.e.mu.Unlock()
|
||||
if nw > maxTracked || nb > maxTracked || old {
|
||||
t.Fatalf("not pruned: %d %d %v", nw, nb, old)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveStateThrottled(t *testing.T) {
|
||||
r := newRig(t, ModeOn, nil)
|
||||
r.hits("203.0.114.230", 5, "/x", 404)
|
||||
r.e.maybeSave()
|
||||
st := r.e.cfg.StatePath
|
||||
os.Remove(st)
|
||||
r.hits("203.0.114.231", 5, "/x", 404)
|
||||
r.e.maybeSave() // same instant: throttled
|
||||
if _, err := os.Stat(st); err == nil {
|
||||
t.Fatal("saved within 30s")
|
||||
}
|
||||
r.now = r.now.Add(31 * time.Second)
|
||||
r.e.maybeSave()
|
||||
if _, err := os.Stat(st); err != nil {
|
||||
t.Fatal("not saved after 30s")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRotation(t *testing.T) {
|
||||
l := &logFile{path: filepath.Join(t.TempDir(), "d.log")}
|
||||
line := strings.Repeat("x", 1<<20-1) + "\n"
|
||||
for i := 0; i < 21; i++ {
|
||||
if err := l.write(line); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := os.Stat(l.path + ".1"); err != nil {
|
||||
t.Fatal("no rotation")
|
||||
}
|
||||
if fi, _ := os.Stat(l.path); fi.Size() > MaxLogBytes {
|
||||
t.Fatal("too big")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatLineInjection(t *testing.T) {
|
||||
ip := netip.MustParseAddr("8.8.8.8")
|
||||
for _, evil := range []string{"x\ny", "a b\r\nurutau decision=ban ip=1.1.1.1", "peer:\x00\n", "\n\n", strings.Repeat("a", 500)} {
|
||||
if _, err := FormatLine(t0, ip, evil, 90, time.Hour, "h", "local"); err == nil {
|
||||
t.Errorf("reason %q accepted", evil)
|
||||
}
|
||||
l, err := FormatLine(t0, ip, ReasonRCE, 90, time.Hour, evil, "peer:"+evil)
|
||||
if err != nil || strings.Count(l, "\n") != 1 || !strings.HasSuffix(l, "\n") || strings.ContainsAny(strings.TrimSuffix(l, "\n"), "\r\x00") ||
|
||||
len(strings.Fields(l)) != 9 {
|
||||
t.Errorf("host/src %q -> %q", evil, l)
|
||||
}
|
||||
}
|
||||
if _, err := FormatLine(t0, netip.Addr{}, ReasonRCE, 1, time.Hour, "h", "local"); err == nil {
|
||||
t.Error("invalid ip accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func FuzzFormatLine(f *testing.F) {
|
||||
f.Add("h", "peer:x", ReasonRCE)
|
||||
f.Add("a\nb", "\r\n", "x\ny")
|
||||
f.Fuzz(func(t *testing.T, host, src, reason string) {
|
||||
l, err := FormatLine(t0, netip.MustParseAddr("2606:4700::1111"), reason, 5, time.Hour, host, src)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if strings.Count(l, "\n") != 1 || len(strings.Fields(l)) != 9 {
|
||||
t.Fatalf("%q", l)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestWritable(t *testing.T) {
|
||||
d := t.TempDir()
|
||||
if !Writable(filepath.Join(d, "sub", "x.log")) || !Writable(filepath.Join(d, "x.log")) {
|
||||
t.Fatal("should be writable")
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(d, "x.log")); err == nil {
|
||||
t.Fatal("Writable must not create the file")
|
||||
}
|
||||
if Writable("") {
|
||||
t.Fatal("empty path")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,723 @@
|
||||
package enforce
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/netip"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
)
|
||||
|
||||
// Config configures the engine. Mode must be observe or on (off means no engine).
|
||||
type Config struct {
|
||||
Mode string
|
||||
Path string // decision file
|
||||
StatePath string // enforce.json, empty: no persistence
|
||||
Host string // name of this instance, written in every line
|
||||
Threshold int // attack events in Window
|
||||
MaxPerMin int
|
||||
Share bool
|
||||
Trusted []netip.Prefix
|
||||
PeerHosts []string // host names or addresses of the peers
|
||||
InfraHosts []string // hub and other infrastructure hosts, never banned
|
||||
LocalAddrs func() []netip.Addr // default: the addresses of the local interfaces
|
||||
Resolve func(host string) []netip.Addr // default: literal parse only
|
||||
Crawler func(ip string, uas []string) bool // FCrDNS verified crawler
|
||||
Geo func(ip string) (string, uint32, string) // cc, asn, org
|
||||
Now func() time.Time
|
||||
}
|
||||
|
||||
// Wire is a decision as exchanged between peers.
|
||||
type Wire struct {
|
||||
T int64 `json:"t"`
|
||||
IP string `json:"ip"`
|
||||
Reason string `json:"reason"`
|
||||
Score int `json:"score"`
|
||||
TTL int `json:"ttl"`
|
||||
}
|
||||
|
||||
// MaxWire is the most decisions accepted or returned in one exchange.
|
||||
const MaxWire = 500
|
||||
|
||||
// Recent is one row of the report.
|
||||
type Recent struct {
|
||||
T int64 `json:"t"`
|
||||
IP string `json:"ip"`
|
||||
Reason string `json:"reason"`
|
||||
Score int `json:"score"`
|
||||
TTL int `json:"ttl"`
|
||||
Action string `json:"action"` // ban, would_ban, skip
|
||||
SkipReason string `json:"skip_reason"`
|
||||
Src string `json:"src"`
|
||||
CC string `json:"cc"`
|
||||
ASN uint32 `json:"asn"`
|
||||
Org string `json:"org"`
|
||||
}
|
||||
|
||||
// Counts are the cumulative counters since start.
|
||||
type Counts struct {
|
||||
Decided int `json:"decided"`
|
||||
Written int `json:"written"`
|
||||
DroppedRate int `json:"dropped_rate"`
|
||||
AlreadyBlocked int `json:"already_blocked"`
|
||||
Skipped map[string]int `json:"skipped"`
|
||||
DroppedQueue int64 `json:"dropped_queue"`
|
||||
WriteErrors int `json:"write_errors"`
|
||||
}
|
||||
|
||||
// Coverage tells how many attacking addresses were stopped, by whom.
|
||||
type Coverage struct {
|
||||
AttackIPs int `json:"attack_ips"`
|
||||
BlockedByFirewall int `json:"blocked_by_firewall"`
|
||||
BlockedByUrutau int `json:"blocked_by_urutau"`
|
||||
WouldBlock int `json:"would_block"`
|
||||
Unblocked int `json:"unblocked"`
|
||||
}
|
||||
|
||||
// Report is what the API serves (mode and file status are added by the handler).
|
||||
type Report struct {
|
||||
Coverage Coverage `json:"coverage"`
|
||||
Counts Counts `json:"counts"`
|
||||
Recent []Recent `json:"recent"`
|
||||
}
|
||||
|
||||
type aevt struct {
|
||||
ts int64
|
||||
slug string
|
||||
}
|
||||
|
||||
type ipState struct {
|
||||
ev []aevt
|
||||
ssh []int64
|
||||
legit int64
|
||||
uas []string
|
||||
lastAttack int64
|
||||
f2bAt int64
|
||||
urutauAt int64
|
||||
wouldAt int64
|
||||
banned int64 // fail2ban holds it until (unix), 0 none
|
||||
}
|
||||
|
||||
type banRec struct {
|
||||
Until int64 `json:"until"`
|
||||
Offences int `json:"offences"`
|
||||
Last int64 `json:"last"`
|
||||
}
|
||||
|
||||
type item struct {
|
||||
ev core.Event
|
||||
fam string
|
||||
}
|
||||
|
||||
const (
|
||||
maxIPs = 50000
|
||||
maxEvents = 128
|
||||
maxRecent = 200
|
||||
skipQuiet = 10 * time.Minute
|
||||
banAssume = 24 * time.Hour
|
||||
peerRefresh = 10 * time.Minute
|
||||
|
||||
maxPeerTTL = 6 * time.Hour
|
||||
peerConfirmAge = 7 * 24 * time.Hour
|
||||
maxTracked = 50000 // would and bans
|
||||
saveEvery = 30 * time.Second
|
||||
)
|
||||
|
||||
// Engine is the second firewall.
|
||||
type Engine struct {
|
||||
cfg Config
|
||||
log *logFile
|
||||
ch chan item
|
||||
dropQ atomic.Int64
|
||||
|
||||
mu sync.Mutex
|
||||
ips map[netip.Addr]*ipState
|
||||
bans map[netip.Addr]banRec
|
||||
would map[netip.Addr]int64
|
||||
skipSeen map[netip.Addr]int64
|
||||
excl Exclusions
|
||||
counts Counts
|
||||
recent []Recent
|
||||
shared []Wire
|
||||
minute int64
|
||||
inMinute int
|
||||
dirty bool
|
||||
lastSave time.Time
|
||||
hostIPs map[string][]netip.Addr // last good resolution per host
|
||||
}
|
||||
|
||||
// New builds an engine and loads its state.
|
||||
func New(c Config) *Engine {
|
||||
if c.Now == nil {
|
||||
c.Now = time.Now
|
||||
}
|
||||
if c.Threshold < 1 {
|
||||
c.Threshold = 5
|
||||
}
|
||||
if c.MaxPerMin < 1 {
|
||||
c.MaxPerMin = 60
|
||||
}
|
||||
if c.Resolve == nil {
|
||||
c.Resolve = func(h string) []netip.Addr {
|
||||
if a, err := netip.ParseAddr(h); err == nil {
|
||||
return []netip.Addr{a.Unmap()}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
e := &Engine{cfg: c, log: &logFile{path: c.Path}, ch: make(chan item, 4096), ips: map[netip.Addr]*ipState{},
|
||||
bans: map[netip.Addr]banRec{}, would: map[netip.Addr]int64{}, skipSeen: map[netip.Addr]int64{},
|
||||
counts: Counts{Skipped: map[string]int{}}}
|
||||
e.hostIPs = map[string][]netip.Addr{}
|
||||
e.excl = Exclusions{Trusted: c.Trusted, Peers: map[netip.Addr]bool{}, Infra: map[netip.Addr]bool{}}
|
||||
e.refreshPeers()
|
||||
e.loadState()
|
||||
return e
|
||||
}
|
||||
|
||||
// Mode returns the mode of the engine.
|
||||
func (e *Engine) Mode() string { return e.cfg.Mode }
|
||||
|
||||
// Host is the name of this instance.
|
||||
func (e *Engine) Host() string { return e.cfg.Host }
|
||||
|
||||
// Share reports whether decisions are exchanged with peers.
|
||||
func (e *Engine) Share() bool { return e.cfg.Share }
|
||||
|
||||
// Threshold is the attack-event threshold in use.
|
||||
func (e *Engine) Threshold() int { return e.cfg.Threshold }
|
||||
|
||||
// LogPath is the decision file.
|
||||
func (e *Engine) LogPath() string { return e.cfg.Path }
|
||||
|
||||
// Observe is the ingestion hook: cheap, never blocks; a full queue drops the
|
||||
// event and counts it.
|
||||
func (e *Engine) Observe(ev core.Event, fam string) {
|
||||
switch ev.Cat {
|
||||
case core.Ban, core.SSHFail, core.Scanner, core.Exploit, core.BruteForce:
|
||||
case core.OK:
|
||||
if ev.FetchDest != "document" || ev.Status < 200 || ev.Status > 299 {
|
||||
return
|
||||
}
|
||||
default:
|
||||
return
|
||||
}
|
||||
select {
|
||||
case e.ch <- item{ev, fam}:
|
||||
default:
|
||||
e.dropQ.Add(1)
|
||||
}
|
||||
}
|
||||
|
||||
// Run processes events until ctx is done.
|
||||
func (e *Engine) Run(ctx context.Context) {
|
||||
flush := time.NewTicker(5 * time.Second)
|
||||
peers := time.NewTicker(peerRefresh)
|
||||
defer flush.Stop()
|
||||
defer peers.Stop()
|
||||
defer e.log.close()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
e.saveState()
|
||||
return
|
||||
case it := <-e.ch:
|
||||
e.process(it.ev, it.fam)
|
||||
case <-flush.C:
|
||||
e.maybeSave()
|
||||
case <-peers.C:
|
||||
e.refreshPeers()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// resolveKeep resolves h; an empty answer (DNS failure) keeps the last good one.
|
||||
func (e *Engine) resolveKeep(h string, into map[netip.Addr]bool) {
|
||||
as := e.cfg.Resolve(h)
|
||||
e.mu.Lock()
|
||||
if len(as) == 0 {
|
||||
as = e.hostIPs[h]
|
||||
} else {
|
||||
e.hostIPs[h] = as
|
||||
}
|
||||
e.mu.Unlock()
|
||||
for _, a := range as {
|
||||
into[a.Unmap()] = true
|
||||
}
|
||||
}
|
||||
|
||||
func (e *Engine) refreshPeers() {
|
||||
m := map[netip.Addr]bool{}
|
||||
for _, h := range e.cfg.PeerHosts {
|
||||
e.resolveKeep(h, m)
|
||||
}
|
||||
infra := map[netip.Addr]bool{}
|
||||
for _, h := range e.cfg.InfraHosts {
|
||||
e.resolveKeep(h, infra)
|
||||
}
|
||||
la := e.cfg.LocalAddrs
|
||||
if la == nil {
|
||||
la = interfaceAddrs
|
||||
}
|
||||
for _, a := range la() {
|
||||
infra[a.Unmap()] = true
|
||||
}
|
||||
e.mu.Lock()
|
||||
e.excl.Peers = m
|
||||
e.excl.Infra = infra
|
||||
e.mu.Unlock()
|
||||
}
|
||||
|
||||
func (e *Engine) stateOf(a netip.Addr) *ipState {
|
||||
st := e.ips[a]
|
||||
if st == nil {
|
||||
if len(e.ips) >= maxIPs {
|
||||
e.evict()
|
||||
}
|
||||
st = &ipState{}
|
||||
e.ips[a] = st
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
func (e *Engine) evict() {
|
||||
cut := e.cfg.Now().Add(-24 * time.Hour).Unix()
|
||||
for a, st := range e.ips {
|
||||
if max(st.lastAttack, st.f2bAt, st.legit) < cut {
|
||||
delete(e.ips, a)
|
||||
}
|
||||
}
|
||||
for a := range e.ips {
|
||||
if len(e.ips) < maxIPs/2 {
|
||||
break
|
||||
}
|
||||
delete(e.ips, a)
|
||||
}
|
||||
if len(e.skipSeen) > 10000 {
|
||||
e.skipSeen = map[netip.Addr]int64{}
|
||||
}
|
||||
}
|
||||
|
||||
// trimMaps prunes would (expired or older than 24 h) and bans (older than 30 d)
|
||||
// and caps both at maxTracked, dropping the least recent first; the lock is held.
|
||||
func (e *Engine) trimMaps(now time.Time) {
|
||||
cutW := now.Unix()
|
||||
for a, u := range e.would {
|
||||
if u < cutW || u < now.Add(-24*time.Hour).Unix() {
|
||||
delete(e.would, a)
|
||||
}
|
||||
}
|
||||
if len(e.would) > maxTracked {
|
||||
type kv struct {
|
||||
a netip.Addr
|
||||
t int64
|
||||
}
|
||||
l := make([]kv, 0, len(e.would))
|
||||
for a, u := range e.would {
|
||||
l = append(l, kv{a, u})
|
||||
}
|
||||
sort.Slice(l, func(i, j int) bool { return l[i].t < l[j].t })
|
||||
for _, x := range l[:len(l)-maxTracked/2] {
|
||||
delete(e.would, x.a)
|
||||
}
|
||||
}
|
||||
cutB := now.Add(-30 * 24 * time.Hour).Unix()
|
||||
for a, b := range e.bans {
|
||||
if b.Last < cutB {
|
||||
delete(e.bans, a)
|
||||
}
|
||||
}
|
||||
if len(e.bans) > maxTracked {
|
||||
type kv struct {
|
||||
a netip.Addr
|
||||
t int64
|
||||
}
|
||||
l := make([]kv, 0, len(e.bans))
|
||||
for a, b := range e.bans {
|
||||
l = append(l, kv{a, b.Last})
|
||||
}
|
||||
sort.Slice(l, func(i, j int) bool { return l[i].t < l[j].t })
|
||||
for _, x := range l[:len(l)-maxTracked/2] {
|
||||
delete(e.bans, x.a)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// process handles one classified event (called by Run, or directly by tests).
|
||||
func (e *Engine) process(ev core.Event, fam string) {
|
||||
a, err := netip.ParseAddr(ev.IP)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
a = a.Unmap().WithZone("")
|
||||
now := e.cfg.Now()
|
||||
ts := ev.Time.Unix()
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
switch {
|
||||
case ev.Cat == core.Ban:
|
||||
if ts < now.Add(-30*24*time.Hour).Unix() {
|
||||
return
|
||||
}
|
||||
st := e.stateOf(a)
|
||||
switch {
|
||||
case ev.Unban:
|
||||
st.banned = 0
|
||||
default:
|
||||
if ev.Jail == "urutau" { // our own decision, enforced by the host jail
|
||||
st.urutauAt = max(st.urutauAt, ts)
|
||||
} else {
|
||||
st.banned = max(st.banned, ev.Time.Add(banAssume).Unix())
|
||||
st.f2bAt = max(st.f2bAt, ts)
|
||||
}
|
||||
}
|
||||
return
|
||||
case LegitVisit(ev):
|
||||
if ts >= now.Add(-LegitWindow).Unix() {
|
||||
e.stateOf(a).legit = max(e.stateOf(a).legit, ts)
|
||||
}
|
||||
return
|
||||
case ev.Cat == core.SSHFail:
|
||||
case CountsAsAttack(ev):
|
||||
default:
|
||||
return
|
||||
}
|
||||
if ts < now.Add(-30*24*time.Hour).Unix() {
|
||||
return
|
||||
}
|
||||
st := e.stateOf(a)
|
||||
st.lastAttack = max(st.lastAttack, ts)
|
||||
if ts < now.Add(-Window).Unix() { // a replayed old event: coverage only
|
||||
return
|
||||
}
|
||||
cut := now.Add(-Window).Unix()
|
||||
slug, crit := attackSlug(ev, fam)
|
||||
if ev.Cat == core.SSHFail {
|
||||
st.ssh = prune(append(st.ssh, ts), cut)
|
||||
} else {
|
||||
st.ev = append(st.ev, aevt{ts, slug})
|
||||
k := 0
|
||||
for _, x := range st.ev {
|
||||
if x.ts >= cut {
|
||||
st.ev[k] = x
|
||||
k++
|
||||
}
|
||||
}
|
||||
st.ev = st.ev[:k]
|
||||
if len(st.ev) > maxEvents {
|
||||
st.ev = st.ev[len(st.ev)-maxEvents:]
|
||||
}
|
||||
}
|
||||
if ev.UA != "" && len(st.uas) < 3 {
|
||||
ua := ev.UA
|
||||
if len(ua) > 200 {
|
||||
ua = ua[:200]
|
||||
}
|
||||
dup := false
|
||||
for _, u := range st.uas {
|
||||
dup = dup || u == ua
|
||||
}
|
||||
if !dup {
|
||||
st.uas = append(st.uas, ua)
|
||||
}
|
||||
}
|
||||
crits := 0
|
||||
for _, x := range st.ev {
|
||||
if criticalReasons[x.slug] {
|
||||
crits++
|
||||
}
|
||||
}
|
||||
in := Input{Now: now, Attacks: len(st.ev), Top: topSlug(st.ev), SSHFails: len(st.ssh), Crits: crits,
|
||||
Legit: st.legit >= now.Add(-LegitWindow).Unix(), Exclude: e.excl.Excluded(a)}
|
||||
if crit {
|
||||
in.Crit = slug
|
||||
}
|
||||
e.fill(a, st, &in, now)
|
||||
d := Decide(in, Params{Threshold: e.cfg.Threshold})
|
||||
if d.Action == ActBan && e.cfg.Crawler != nil && len(st.uas) > 0 && e.cfg.Crawler(a.String(), st.uas) {
|
||||
in.Exclude = SkipCrawler
|
||||
d = Decide(in, Params{Threshold: e.cfg.Threshold})
|
||||
}
|
||||
e.apply(a, st, d, "local", now)
|
||||
}
|
||||
|
||||
func (e *Engine) fill(a netip.Addr, st *ipState, in *Input, now time.Time) {
|
||||
in.Banned = st.banned > now.Unix()
|
||||
if b, ok := e.bans[a]; ok {
|
||||
in.Offences = b.Offences
|
||||
if b.Until > now.Unix() && e.cfg.Mode == ModeOn {
|
||||
in.Active = true
|
||||
}
|
||||
if now.Unix() > b.Until+30*24*3600 {
|
||||
in.Offences = 0
|
||||
}
|
||||
}
|
||||
if u, ok := e.would[a]; ok && u > now.Unix() && e.cfg.Mode == ModeObserve {
|
||||
in.Active = true
|
||||
}
|
||||
}
|
||||
|
||||
func prune(l []int64, cut int64) []int64 {
|
||||
k := 0
|
||||
for _, t := range l {
|
||||
if t >= cut {
|
||||
l[k] = t
|
||||
k++
|
||||
}
|
||||
}
|
||||
l = l[:k]
|
||||
if len(l) > maxEvents {
|
||||
l = l[len(l)-maxEvents:]
|
||||
}
|
||||
return l
|
||||
}
|
||||
|
||||
func topSlug(evs []aevt) string {
|
||||
cnt := map[string]int{}
|
||||
best, bn := "", 0
|
||||
for _, x := range evs {
|
||||
cnt[x.slug]++
|
||||
if cnt[x.slug] >= bn {
|
||||
best, bn = x.slug, cnt[x.slug]
|
||||
}
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
// apply records the outcome of a decision; the lock is held.
|
||||
func (e *Engine) apply(a netip.Addr, st *ipState, d Decision, src string, now time.Time) {
|
||||
switch d.Action {
|
||||
case ActSkip, ActAlready:
|
||||
if until, ok := e.skipSeen[a]; ok && until > now.Unix() {
|
||||
return
|
||||
}
|
||||
e.skipSeen[a] = now.Add(skipQuiet).Unix()
|
||||
r := Recent{T: now.Unix(), IP: a.String(), Action: "skip", SkipReason: d.Skip, Src: src}
|
||||
if d.Action == ActAlready {
|
||||
e.counts.AlreadyBlocked++
|
||||
r.SkipReason = "already_blocked"
|
||||
} else {
|
||||
e.counts.Skipped[d.Skip]++
|
||||
}
|
||||
e.addRecent(a, r)
|
||||
case ActBan:
|
||||
e.counts.Decided++
|
||||
m := now.Unix() / 60
|
||||
if m != e.minute {
|
||||
e.minute, e.inMinute = m, 0
|
||||
}
|
||||
if e.inMinute >= e.cfg.MaxPerMin {
|
||||
e.counts.DroppedRate++
|
||||
return
|
||||
}
|
||||
e.inMinute++
|
||||
r := Recent{T: now.Unix(), IP: a.String(), Reason: d.Reason, Score: d.Score, TTL: int(d.TTL / time.Second), Src: src}
|
||||
if e.cfg.Mode != ModeOn {
|
||||
r.Action = "would_ban"
|
||||
if len(e.would) >= maxTracked {
|
||||
e.trimMaps(now)
|
||||
}
|
||||
e.would[a] = now.Add(d.TTL).Unix()
|
||||
st.wouldAt = now.Unix()
|
||||
e.addRecent(a, r)
|
||||
return
|
||||
}
|
||||
line, err := FormatLine(now, a, d.Reason, d.Score, d.TTL, e.cfg.Host, src)
|
||||
if err == nil {
|
||||
err = e.log.write(line)
|
||||
}
|
||||
if err != nil {
|
||||
e.counts.WriteErrors++
|
||||
return
|
||||
}
|
||||
r.Action = "ban"
|
||||
e.counts.Written++
|
||||
if len(e.bans) >= maxTracked {
|
||||
e.trimMaps(now)
|
||||
}
|
||||
b := e.bans[a]
|
||||
if now.Unix() > b.Until+30*24*3600 {
|
||||
b.Offences = 0
|
||||
}
|
||||
if src == "local" {
|
||||
b.Offences++
|
||||
e.shared = append(e.shared, Wire{T: now.Unix(), IP: a.String(), Reason: d.Reason, Score: d.Score, TTL: r.TTL})
|
||||
if len(e.shared) > MaxWire {
|
||||
e.shared = e.shared[len(e.shared)-MaxWire:]
|
||||
}
|
||||
}
|
||||
b.Until, b.Last = now.Add(d.TTL).Unix(), now.Unix()
|
||||
e.bans[a] = b
|
||||
st.urutauAt = now.Unix()
|
||||
e.dirty = true
|
||||
e.addRecent(a, r)
|
||||
}
|
||||
}
|
||||
|
||||
func (e *Engine) addRecent(a netip.Addr, r Recent) {
|
||||
if e.cfg.Geo != nil {
|
||||
r.CC, r.ASN, r.Org = e.cfg.Geo(a.String())
|
||||
}
|
||||
e.recent = append(e.recent, r)
|
||||
if len(e.recent) > maxRecent*2 {
|
||||
e.recent = append([]Recent(nil), e.recent[len(e.recent)-maxRecent:]...)
|
||||
}
|
||||
}
|
||||
|
||||
// LocalSince returns the decisions this instance wrote since the unix time.
|
||||
func (e *Engine) LocalSince(since int64) []Wire {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
out := []Wire{}
|
||||
for _, w := range e.shared {
|
||||
if w.T >= since {
|
||||
out = append(out, w)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// AcceptPeer applies decisions received from a peer, after this instance's own
|
||||
// exclusions. It returns how many were accepted for the policy (written or
|
||||
// would-ban) and how many were refused as malformed.
|
||||
func (e *Engine) AcceptPeer(name string, in []Wire) (accepted, invalid int) {
|
||||
if len(in) > MaxWire {
|
||||
in = in[:MaxWire]
|
||||
}
|
||||
src := "peer:" + token(name, "peer")
|
||||
now := e.cfg.Now()
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
for _, w := range in {
|
||||
a, err := netip.ParseAddr(w.IP)
|
||||
if err != nil || !ValidReason(w.Reason) || !Public(a) {
|
||||
invalid++
|
||||
continue
|
||||
}
|
||||
a = a.Unmap().WithZone("")
|
||||
ttl := min(time.Duration(min(max(w.TTL, 60), 7*24*3600))*time.Second, maxPeerTTL)
|
||||
if w.T > 0 && w.T+int64(ttl/time.Second) < now.Unix() {
|
||||
continue // already expired
|
||||
}
|
||||
st := e.stateOf(a)
|
||||
in := Input{Now: now, Crit: w.Reason, Crits: CritHits, Exclude: e.excl.Excluded(a)}
|
||||
if in.Exclude == "" && st.lastAttack < now.Add(-peerConfirmAge).Unix() {
|
||||
in.Exclude = SkipUnconfirmed // a peer's word alone never bans: this node must have seen the address attack
|
||||
}
|
||||
e.fill(a, st, &in, now)
|
||||
d := Decide(in, Params{})
|
||||
if d.Action == ActBan {
|
||||
d.Reason, d.Score, d.TTL = w.Reason, max(0, min(100, w.Score)), ttl
|
||||
accepted++
|
||||
}
|
||||
e.apply(a, st, d, src, now)
|
||||
}
|
||||
return accepted, invalid
|
||||
}
|
||||
|
||||
// Report summarizes the activity since the unix time from.
|
||||
func (e *Engine) Report(from int64) Report {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
var cv Coverage
|
||||
for _, st := range e.ips {
|
||||
if st.lastAttack < from {
|
||||
continue
|
||||
}
|
||||
cv.AttackIPs++
|
||||
switch {
|
||||
case st.f2bAt > 0 && st.f2bAt >= from:
|
||||
cv.BlockedByFirewall++
|
||||
case st.urutauAt > 0 && st.urutauAt >= from:
|
||||
cv.BlockedByUrutau++
|
||||
case st.wouldAt > 0 && st.wouldAt >= from:
|
||||
cv.WouldBlock++
|
||||
default:
|
||||
cv.Unblocked++
|
||||
}
|
||||
}
|
||||
c := e.counts
|
||||
c.Skipped = map[string]int{SkipTrusted: 0, SkipPrivate: 0, SkipCrawler: 0, SkipLegit: 0, SkipPeer: 0, SkipInfra: 0, SkipUnconfirmed: 0}
|
||||
for k, v := range e.counts.Skipped {
|
||||
c.Skipped[k] = v
|
||||
}
|
||||
c.DroppedQueue = e.dropQ.Load()
|
||||
rec := []Recent{}
|
||||
for i := len(e.recent) - 1; i >= 0 && len(rec) < maxRecent; i-- {
|
||||
if e.recent[i].T >= from {
|
||||
rec = append(rec, e.recent[i])
|
||||
}
|
||||
}
|
||||
return Report{Coverage: cv, Counts: c, Recent: rec}
|
||||
}
|
||||
|
||||
type stateFile struct {
|
||||
V int `json:"v"`
|
||||
Bans map[string]banRec `json:"bans"`
|
||||
}
|
||||
|
||||
func (e *Engine) loadState() {
|
||||
if e.cfg.StatePath == "" {
|
||||
return
|
||||
}
|
||||
b, err := os.ReadFile(e.cfg.StatePath)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var sf stateFile
|
||||
if json.Unmarshal(b, &sf) != nil {
|
||||
return
|
||||
}
|
||||
cut := e.cfg.Now().Add(-30 * 24 * time.Hour).Unix()
|
||||
for k, v := range sf.Bans {
|
||||
if a, err := netip.ParseAddr(k); err == nil && v.Last >= cut && v.Offences >= 0 && v.Offences < 1000 {
|
||||
e.bans[a.Unmap()] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// maybeSave writes the state at most every saveEvery.
|
||||
func (e *Engine) maybeSave() {
|
||||
if e.cfg.Now().Sub(e.lastSave) < saveEvery {
|
||||
return
|
||||
}
|
||||
e.saveState()
|
||||
}
|
||||
|
||||
// saveState writes enforce.json atomically when something changed.
|
||||
func (e *Engine) saveState() {
|
||||
if e.cfg.StatePath == "" {
|
||||
return
|
||||
}
|
||||
e.mu.Lock()
|
||||
if !e.dirty {
|
||||
e.mu.Unlock()
|
||||
return
|
||||
}
|
||||
e.lastSave = e.cfg.Now()
|
||||
e.trimMaps(e.lastSave)
|
||||
sf := stateFile{V: 1, Bans: map[string]banRec{}}
|
||||
for a, b := range e.bans {
|
||||
sf.Bans[a.String()] = b
|
||||
}
|
||||
e.dirty = false
|
||||
e.mu.Unlock()
|
||||
b, _ := json.Marshal(sf)
|
||||
tmp := e.cfg.StatePath + ".tmp"
|
||||
if err := os.MkdirAll(filepath.Dir(tmp), 0o700); err == nil {
|
||||
if err = os.WriteFile(tmp, b, 0o600); err == nil {
|
||||
if err = os.Rename(tmp, e.cfg.StatePath); err == nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
e.mu.Lock()
|
||||
e.dirty = true
|
||||
e.mu.Unlock()
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package enforce
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/netip"
|
||||
)
|
||||
|
||||
// SkipInfra is the skip reason of the fixed infrastructure allowlist.
|
||||
const SkipInfra = "infrastructure"
|
||||
|
||||
func mustPrefixes(l ...string) []netip.Prefix {
|
||||
out := make([]netip.Prefix, 0, len(l))
|
||||
for _, s := range l {
|
||||
out = append(out, netip.MustParsePrefix(s))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// cloudflare are the published Cloudflare ranges (https://www.cloudflare.com/ips/).
|
||||
// They are never banned: behind the CDN the "client" of a request is an edge
|
||||
// address shared by thousands of innocent visitors.
|
||||
var cloudflare = mustPrefixes(
|
||||
"173.245.48.0/20", "103.21.244.0/22", "103.22.200.0/22", "103.31.4.0/22", "141.101.64.0/18",
|
||||
"108.162.192.0/18", "190.93.240.0/20", "188.114.96.0/20", "197.234.240.0/22", "198.41.128.0/17",
|
||||
"162.158.0.0/15", "104.16.0.0/13", "104.24.0.0/14", "172.64.0.0/13", "131.0.72.0/22",
|
||||
"2400:cb00::/32", "2606:4700::/32", "2803:f800::/32", "2405:b500::/32", "2405:8100::/32",
|
||||
"2a06:98c0::/29", "2c0f:f248::/32")
|
||||
|
||||
// publicResolvers are the well known public DNS resolvers.
|
||||
var publicResolvers = func() map[netip.Addr]bool {
|
||||
m := map[netip.Addr]bool{}
|
||||
for _, s := range []string{"1.1.1.1", "1.0.0.1", "8.8.8.8", "8.8.4.4", "9.9.9.9", "149.112.112.112",
|
||||
"208.67.222.222", "208.67.220.220", "2606:4700:4700::1111", "2606:4700:4700::1001",
|
||||
"2001:4860:4860::8888", "2001:4860:4860::8844", "2620:fe::fe", "2620:fe::9",
|
||||
"2620:119:35::35", "2620:119:53::53"} {
|
||||
m[netip.MustParseAddr(s)] = true
|
||||
}
|
||||
return m
|
||||
}()
|
||||
|
||||
// IsCloudflare reports whether a belongs to a Cloudflare range.
|
||||
func IsCloudflare(a netip.Addr) bool {
|
||||
a = a.Unmap()
|
||||
for _, p := range cloudflare {
|
||||
if p.Contains(a) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IsInfrastructure reports whether a is in the fixed allowlist (Cloudflare, public resolvers).
|
||||
func IsInfrastructure(a netip.Addr) bool {
|
||||
a = a.Unmap()
|
||||
return publicResolvers[a] || IsCloudflare(a)
|
||||
}
|
||||
|
||||
// interfaceAddrs lists the addresses of the local interfaces.
|
||||
func interfaceAddrs() []netip.Addr {
|
||||
var out []netip.Addr
|
||||
addrs, err := net.InterfaceAddrs()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
for _, x := range addrs {
|
||||
var ip net.IP
|
||||
switch v := x.(type) {
|
||||
case *net.IPNet:
|
||||
ip = v.IP
|
||||
case *net.IPAddr:
|
||||
ip = v.IP
|
||||
}
|
||||
if a, ok := netip.AddrFromSlice(ip); ok {
|
||||
out = append(out, a.Unmap())
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package enforce
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/netip"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// MaxLogBytes is the size at which the decision file is rotated (one .1 kept).
|
||||
const MaxLogBytes = 20 << 20
|
||||
|
||||
// token reduces s to [A-Za-z0-9._-] (at most 32 bytes); fallback if nothing is left.
|
||||
func token(s, fallback string) string {
|
||||
var b strings.Builder
|
||||
for i := 0; i < len(s) && b.Len() < 32; i++ {
|
||||
c := s[i]
|
||||
if c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '.' || c == '_' || c == '-' {
|
||||
b.WriteByte(c)
|
||||
}
|
||||
}
|
||||
if b.Len() == 0 {
|
||||
return fallback
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// FormatLine renders one decision. Nothing the attacker controls enters it:
|
||||
// the address is re-formatted by netip, the reason must be a fixed slug and the
|
||||
// host and source names are reduced to a safe alphabet.
|
||||
func FormatLine(t time.Time, ip netip.Addr, reason string, score int, ttl time.Duration, host, src string) (string, error) {
|
||||
ip = ip.Unmap().WithZone("")
|
||||
if !ip.IsValid() {
|
||||
return "", errors.New("invalid ip")
|
||||
}
|
||||
if !ValidReason(reason) {
|
||||
return "", errors.New("invalid reason")
|
||||
}
|
||||
score = max(0, min(100, score))
|
||||
secs := max(1, int64(ttl/time.Second))
|
||||
if src != "local" {
|
||||
src = "peer:" + token(strings.TrimPrefix(src, "peer:"), "peer")
|
||||
}
|
||||
return fmt.Sprintf("%s urutau decision=ban ip=%s reason=%s score=%d ttl=%d host=%s src=%s\n",
|
||||
t.UTC().Format("2006-01-02T15:04:05Z"), ip.String(), reason, score, secs, token(host, "urutau"), src), nil
|
||||
}
|
||||
|
||||
// logFile appends to the decision file, rotating by size.
|
||||
type logFile struct {
|
||||
mu sync.Mutex
|
||||
path string
|
||||
f *os.File
|
||||
size int64
|
||||
}
|
||||
|
||||
func (l *logFile) open() error {
|
||||
if err := os.MkdirAll(filepath.Dir(l.path), 0o750); err != nil {
|
||||
return err
|
||||
}
|
||||
f, err := os.OpenFile(l.path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o640)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fi, err := f.Stat()
|
||||
if err != nil {
|
||||
f.Close()
|
||||
return err
|
||||
}
|
||||
l.f, l.size = f, fi.Size()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (l *logFile) write(line string) error {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
if l.f == nil {
|
||||
if err := l.open(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if l.size+int64(len(line)) > MaxLogBytes {
|
||||
l.f.Close()
|
||||
l.f = nil
|
||||
if err := os.Rename(l.path, l.path+".1"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := l.open(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
n, err := l.f.WriteString(line)
|
||||
l.size += int64(n)
|
||||
if err != nil {
|
||||
l.f.Close()
|
||||
l.f = nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (l *logFile) close() {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
if l.f != nil {
|
||||
l.f.Close()
|
||||
l.f = nil
|
||||
}
|
||||
}
|
||||
|
||||
// Writable reports whether the decision file can be appended to, without
|
||||
// creating anything: an existing file is opened for writing, otherwise a
|
||||
// temporary file is created next to where it would live.
|
||||
func Writable(path string) bool {
|
||||
if path == "" {
|
||||
return false
|
||||
}
|
||||
if _, err := os.Stat(path); err == nil {
|
||||
f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND, 0)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
f.Close()
|
||||
return true
|
||||
}
|
||||
dir := filepath.Dir(path)
|
||||
if _, err := os.Stat(dir); err != nil {
|
||||
// the directory is created on first write: check the nearest parent
|
||||
for dir != "/" && dir != "." {
|
||||
dir = filepath.Dir(dir)
|
||||
if _, err := os.Stat(dir); err == nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
f, err := os.CreateTemp(dir, ".urutau-w-*")
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
f.Close()
|
||||
os.Remove(f.Name())
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
// Package enforce is the optional "second firewall": it decides which source
|
||||
// addresses deserve a ban and appends one line per decision to a file. The
|
||||
// process never gains privileges: a host side fail2ban jail reads the file.
|
||||
package enforce
|
||||
|
||||
import (
|
||||
"net/netip"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
|
||||
)
|
||||
|
||||
// Modes.
|
||||
const (
|
||||
ModeOff = "off"
|
||||
ModeObserve = "observe"
|
||||
ModeOn = "on"
|
||||
)
|
||||
|
||||
// Fixed reason slugs. Anything else is refused (also from peers).
|
||||
const (
|
||||
ReasonScannerFlood = "scanner-flood"
|
||||
ReasonExploitFlood = "exploit-flood"
|
||||
ReasonWebBrute = "web-bruteforce"
|
||||
ReasonWPBrute = "wp-bruteforce"
|
||||
ReasonSSHBrute = "ssh-bruteforce"
|
||||
ReasonRCE = "rce"
|
||||
ReasonTraversal = "path-traversal"
|
||||
ReasonEnvProbe = "env-probe"
|
||||
ReasonVCSProbe = "vcs-probe"
|
||||
ReasonWebshell = "webshell"
|
||||
ReasonSQLi = "sqli"
|
||||
ReasonLog4Shell = "log4shell"
|
||||
)
|
||||
|
||||
var reasons = map[string]bool{
|
||||
ReasonScannerFlood: true, ReasonExploitFlood: true, ReasonWebBrute: true, ReasonWPBrute: true,
|
||||
ReasonSSHBrute: true, ReasonRCE: true, ReasonTraversal: true, ReasonEnvProbe: true,
|
||||
ReasonVCSProbe: true, ReasonWebshell: true, ReasonSQLi: true, ReasonLog4Shell: true,
|
||||
}
|
||||
|
||||
// ValidReason reports whether s is one of the fixed slugs.
|
||||
func ValidReason(s string) bool { return reasons[s] }
|
||||
|
||||
// criticalFam maps the attack families that justify a ban on one hit.
|
||||
var criticalFam = map[string]string{
|
||||
intel.FamRCE: ReasonRCE,
|
||||
intel.FamTraversal: ReasonTraversal,
|
||||
intel.FamEnvCreds: ReasonEnvProbe,
|
||||
intel.FamVCS: ReasonVCSProbe,
|
||||
intel.FamWebshell: ReasonWebshell,
|
||||
intel.FamSQLi: ReasonSQLi,
|
||||
intel.FamLog4Shell: ReasonLog4Shell,
|
||||
}
|
||||
|
||||
// Policy constants.
|
||||
const (
|
||||
Window = 10 * time.Minute
|
||||
LegitWindow = 24 * time.Hour
|
||||
SSHThreshold = 5
|
||||
// CritHits is how many critical events of one address (in Window) justify a ban.
|
||||
CritHits = 2
|
||||
)
|
||||
|
||||
// ttls is the advisory duration by number of previous bans.
|
||||
var ttls = []time.Duration{time.Hour, 6 * time.Hour, 24 * time.Hour, 7 * 24 * time.Hour}
|
||||
|
||||
// TTLFor is the advisory TTL of a ban preceded by n earlier bans.
|
||||
func TTLFor(offences int) time.Duration {
|
||||
if offences < 0 {
|
||||
offences = 0
|
||||
}
|
||||
if offences >= len(ttls) {
|
||||
offences = len(ttls) - 1
|
||||
}
|
||||
return ttls[offences]
|
||||
}
|
||||
|
||||
// Skip reasons, also the keys of Counts.Skipped.
|
||||
const (
|
||||
SkipTrusted = "trusted"
|
||||
SkipPrivate = "private"
|
||||
SkipCrawler = "crawler"
|
||||
SkipLegit = "legit_visitor"
|
||||
SkipPeer = "peer"
|
||||
// SkipUnconfirmed: a peer's decision about an address this node never saw attacking.
|
||||
SkipUnconfirmed = "peer_unconfirmed"
|
||||
)
|
||||
|
||||
// Actions of a Decision.
|
||||
const (
|
||||
ActNone = "" // nothing to do
|
||||
ActBan = "ban" // write (or would write)
|
||||
ActSkip = "skip" // excluded
|
||||
ActAlready = "already" // fail2ban already blocks it
|
||||
ActActive = "active" // an advisory ban is still valid
|
||||
)
|
||||
|
||||
// Input is everything Decide needs about one address.
|
||||
type Input struct {
|
||||
Now time.Time
|
||||
Attacks int // counted attack events in the window
|
||||
Top string // reason slug of the dominant attack in the window
|
||||
SSHFails int // failed SSH logins in the window
|
||||
Crit string // reason of a critical family hit just seen, "" if none
|
||||
Crits int // critical events of the address in the window (a single hit is not enough)
|
||||
Legit bool // a document 2xx from a browser within the last 24 h
|
||||
Exclude string // Excluded() result or "crawler"
|
||||
Banned bool // fail2ban already blocks it
|
||||
Active bool // an advisory ban is still valid
|
||||
Offences int
|
||||
}
|
||||
|
||||
// Params are the thresholds.
|
||||
type Params struct{ Threshold int }
|
||||
|
||||
// Decision is the verdict of Decide.
|
||||
type Decision struct {
|
||||
Action string
|
||||
Reason string
|
||||
Score int
|
||||
TTL time.Duration
|
||||
Skip string
|
||||
}
|
||||
|
||||
// Decide is the pure policy. It returns ActNone while nothing justifies a ban.
|
||||
func Decide(in Input, p Params) Decision {
|
||||
th, sshTh := p.Threshold, SSHThreshold
|
||||
if th < 1 {
|
||||
th = 5
|
||||
}
|
||||
if in.Legit { // a (forgeable) legitimate visit only relaxes the volumetric thresholds
|
||||
th, sshTh = th*2, sshTh*2
|
||||
}
|
||||
var reason string
|
||||
score := 0
|
||||
switch {
|
||||
case in.Crit != "" && in.Crits >= CritHits:
|
||||
reason, score = in.Crit, 90
|
||||
case in.SSHFails >= sshTh:
|
||||
reason, score = ReasonSSHBrute, min(100, 60+(in.SSHFails-sshTh)*5)
|
||||
case in.Attacks >= th:
|
||||
reason, score = in.Top, min(100, 55+(in.Attacks-th)*5)
|
||||
if !ValidReason(reason) {
|
||||
reason = ReasonScannerFlood
|
||||
}
|
||||
default:
|
||||
return Decision{}
|
||||
}
|
||||
switch {
|
||||
case in.Exclude != "":
|
||||
return Decision{Action: ActSkip, Skip: in.Exclude}
|
||||
case in.Banned:
|
||||
return Decision{Action: ActAlready}
|
||||
case in.Active:
|
||||
return Decision{Action: ActActive}
|
||||
}
|
||||
return Decision{Action: ActBan, Reason: reason, Score: score, TTL: TTLFor(in.Offences)}
|
||||
}
|
||||
|
||||
// reservedV4/V6 are special purpose ranges not covered by netip helpers.
|
||||
var reserved = func() []netip.Prefix {
|
||||
var out []netip.Prefix
|
||||
for _, s := range []string{"0.0.0.0/8", "100.64.0.0/10", "192.0.0.0/24", "192.0.2.0/24", "198.18.0.0/15",
|
||||
"198.51.100.0/24", "203.0.113.0/24", "240.0.0.0/4", "2001:db8::/32", "100::/64", "fc00::/7", "fe80::/10", "ff00::/8"} {
|
||||
out = append(out, netip.MustParsePrefix(s))
|
||||
}
|
||||
return out
|
||||
}()
|
||||
|
||||
// demoReservedPublic is a hidden switch ONLY for the documentation screenshots
|
||||
// (scripts/screenshots.sh): the demo data uses reserved documentation ranges, which
|
||||
// production policy rightly treats as private. Never set URUTAU_DEMO_RESERVED_PUBLIC
|
||||
// outside the screenshot run.
|
||||
var demoReservedPublic = os.Getenv("URUTAU_DEMO_RESERVED_PUBLIC") == "1"
|
||||
|
||||
func demoRanges(p netip.Prefix) bool {
|
||||
switch p.String() {
|
||||
case "198.18.0.0/15", "203.0.113.0/24", "198.51.100.0/24", "192.0.2.0/24", "2001:db8::/32":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Public reports whether a is a routable unicast address worth blocking.
|
||||
func Public(a netip.Addr) bool {
|
||||
a = a.Unmap()
|
||||
if !a.IsValid() || a.Zone() != "" || a.IsUnspecified() || a.IsLoopback() || a.IsPrivate() || a.IsMulticast() ||
|
||||
a.IsLinkLocalUnicast() || a.IsLinkLocalMulticast() || a.IsInterfaceLocalMulticast() {
|
||||
return false
|
||||
}
|
||||
for _, p := range reserved {
|
||||
if demoReservedPublic && demoRanges(p) {
|
||||
continue
|
||||
}
|
||||
if p.Contains(a) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Exclusions are the addresses that are never banned.
|
||||
type Exclusions struct {
|
||||
Trusted []netip.Prefix // --trusted and --ignore
|
||||
Peers map[netip.Addr]bool // addresses of the peers
|
||||
Infra map[netip.Addr]bool // hub, local interfaces (resolved at runtime)
|
||||
}
|
||||
|
||||
var criticalReasons = func() map[string]bool {
|
||||
m := map[string]bool{}
|
||||
for _, r := range criticalFam {
|
||||
m[r] = true
|
||||
}
|
||||
return m
|
||||
}()
|
||||
|
||||
// Excluded returns the skip reason of a, or "".
|
||||
func (x Exclusions) Excluded(a netip.Addr) string {
|
||||
a = a.Unmap()
|
||||
if !Public(a) {
|
||||
return SkipPrivate
|
||||
}
|
||||
if x.Peers[a] {
|
||||
return SkipPeer
|
||||
}
|
||||
for _, p := range x.Trusted {
|
||||
if p.Contains(a) {
|
||||
return SkipTrusted
|
||||
}
|
||||
}
|
||||
if x.Infra[a] || IsInfrastructure(a) {
|
||||
return SkipInfra
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// attackSlug is the reason slug of one attack event, and whether it is critical.
|
||||
func attackSlug(ev core.Event, fam string) (slug string, crit bool) {
|
||||
if ev.Cat == core.SSHFail {
|
||||
return ReasonSSHBrute, false
|
||||
}
|
||||
if r, ok := criticalFam[fam]; ok {
|
||||
return r, true
|
||||
}
|
||||
switch {
|
||||
case fam == intel.FamWordPress:
|
||||
return ReasonWPBrute, false
|
||||
case ev.Cat == core.BruteForce:
|
||||
return ReasonWebBrute, false
|
||||
case ev.Cat == core.Exploit:
|
||||
return ReasonExploitFlood, false
|
||||
}
|
||||
return ReasonScannerFlood, false
|
||||
}
|
||||
|
||||
// CountsAsAttack reports whether an HTTP event is an attack the policy counts:
|
||||
// an attack category that was not merely framed, and whose answer is not a
|
||||
// client, application or proxy error.
|
||||
func CountsAsAttack(ev core.Event) bool {
|
||||
if ev.Source != "traefik" || ev.Framed {
|
||||
return false
|
||||
}
|
||||
if ev.Cat != core.Scanner && ev.Cat != core.Exploit && ev.Cat != core.BruteForce {
|
||||
return false
|
||||
}
|
||||
if ev.Status >= 400 {
|
||||
c := core.ErrorClass(ev, false)
|
||||
return c == core.ClassAttack || c == core.ClassBlocked
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// LegitVisit reports whether ev is a browser loading a page successfully.
|
||||
func LegitVisit(ev core.Event) bool {
|
||||
return ev.Source == "traefik" && ev.Cat == core.OK && ev.Status >= 200 && ev.Status < 300 &&
|
||||
ev.FetchDest == "document" && !ev.E.Tool && !ev.E.Bot && !ev.Prefetch
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package fed
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// Get fetches a peer path with the peer token and decodes the JSON answer.
|
||||
func (h *Hub) Get(ctx context.Context, p Peer, path string, out any) error {
|
||||
_, err := h.get(ctx, p, path, out)
|
||||
return err
|
||||
}
|
||||
|
||||
// PostJSON sends v as JSON to a peer path with the peer token.
|
||||
func (h *Hub) PostJSON(ctx context.Context, p Peer, path string, v any) error {
|
||||
b, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, p.URL+path, bytes.NewReader(b))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tok := h.Token
|
||||
if p.Token != "" {
|
||||
tok = p.Token
|
||||
}
|
||||
if tok != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+tok)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := h.client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
|
||||
if resp.StatusCode/100 != 2 {
|
||||
return fmt.Errorf("HTTP %d", resp.StatusCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package fed
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// EgressFor asks the online peers (or one) for their egress analysis of the
|
||||
// window [from, to] (unix seconds). The raw answers are untrusted: the caller
|
||||
// decodes and sanitizes them.
|
||||
func (h *Hub) EgressFor(ctx context.Context, from, to int64, only string) map[string]json.RawMessage {
|
||||
out := map[string]json.RawMessage{}
|
||||
var mu sync.Mutex
|
||||
var wg sync.WaitGroup
|
||||
for _, p := range h.Peers {
|
||||
if only != "" && only != p.Name {
|
||||
continue
|
||||
}
|
||||
h.mu.RLock()
|
||||
st := h.state[p.Name]
|
||||
online := st != nil && st.online
|
||||
h.mu.RUnlock()
|
||||
if !online {
|
||||
continue
|
||||
}
|
||||
wg.Add(1)
|
||||
go func(p Peer) {
|
||||
defer wg.Done()
|
||||
var raw json.RawMessage
|
||||
if _, err := h.get(ctx, p, fmt.Sprintf("/api/v1/peer/egress?from=%d&to=%d", from, to), &raw); err != nil {
|
||||
return
|
||||
}
|
||||
mu.Lock()
|
||||
out[p.Name] = raw
|
||||
mu.Unlock()
|
||||
}(p)
|
||||
}
|
||||
wg.Wait()
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"sort"
|
||||
"sync/atomic"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
|
||||
)
|
||||
|
||||
func init() {
|
||||
registerUserRoute("GET /api/v1/egress", func(s *Server) http.HandlerFunc { return s.egressAPI })
|
||||
}
|
||||
|
||||
var egressEngine atomic.Pointer[egress.Engine]
|
||||
|
||||
// SetEgress attaches the egress engine (nil disables the endpoints). It is
|
||||
// called by the daemon wiring, before or after the server starts.
|
||||
func SetEgress(e *egress.Engine) { egressEngine.Store(e) }
|
||||
|
||||
type egressOut struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Source egress.SourceInfo `json:"source"`
|
||||
egress.Report
|
||||
}
|
||||
|
||||
// egressAPI: GET /api/v1/egress?range=24h&host=all|<name>. On a hub the
|
||||
// local engine and the peers' reports are merged, items carrying "host".
|
||||
func (s *Server) egressAPI(w http.ResponseWriter, r *http.Request) {
|
||||
rg, ok := s.rangeOf(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
host := r.URL.Query().Get("host")
|
||||
if len(host) > 253 {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "bad host"})
|
||||
return
|
||||
}
|
||||
local, peers, only, ok := s.studyHosts(w, host)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
from, to := rg.Bounds(s.opt.Store.Now().Unix())
|
||||
eng := egressEngine.Load()
|
||||
out := egressOut{Source: egress.SourceInfo{State: "disabled"}}
|
||||
if eng != nil {
|
||||
out.Source = eng.Info()
|
||||
out.Enabled = true
|
||||
}
|
||||
rep := egress.EmptyReport()
|
||||
if local && eng != nil {
|
||||
rep = eng.Report(from, to)
|
||||
}
|
||||
if peers && s.opt.Hub != nil {
|
||||
merged := egress.EmptyReport()
|
||||
merged.Timeline.Start = rep.Timeline.Start
|
||||
if local && eng != nil {
|
||||
rep.Stamp(s.opt.Store.Name())
|
||||
merged.Merge(rep, s.opt.Store.Name())
|
||||
}
|
||||
raws := s.opt.Hub.EgressFor(r.Context(), from, to, only)
|
||||
names := make([]string, 0, len(raws))
|
||||
for n := range raws {
|
||||
names = append(names, n)
|
||||
}
|
||||
sort.Strings(names)
|
||||
for _, n := range names {
|
||||
var pr egress.Report
|
||||
if json.Unmarshal(raws[n], &pr) != nil {
|
||||
continue
|
||||
}
|
||||
pr.Sanitize(n)
|
||||
merged.Merge(pr, n)
|
||||
out.Enabled = true
|
||||
}
|
||||
rep = merged
|
||||
}
|
||||
out.Report = rep
|
||||
writeJSON(w, 200, out)
|
||||
}
|
||||
|
||||
// peerEgress: GET /api/v1/peer/egress, the local report a hub merges; opened
|
||||
// only by the peer token (and --peer-allow). It must be registered next to
|
||||
// the other peer routes.
|
||||
func (s *Server) peerEgress(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.peerGate(w, r) {
|
||||
return
|
||||
}
|
||||
eng := egressEngine.Load()
|
||||
if eng == nil {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "egress is not enabled"})
|
||||
return
|
||||
}
|
||||
rg, ok := s.rangeOf(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
from, to := rg.Bounds(s.opt.Store.Now().Unix())
|
||||
writeJSON(w, 200, eng.Report(from, to))
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/netip"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
func TestEgressAPI(t *testing.T) {
|
||||
st := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour})
|
||||
h := New(Options{Token: userTok, Version: "t", Store: st})
|
||||
auth := map[string]string{"Authorization": "Bearer " + userTok}
|
||||
|
||||
SetEgress(nil)
|
||||
d := getJSON(t, h, "/api/v1/egress?range=24h", auth)
|
||||
if d["enabled"] != false || d["findings"] == nil || d["top_dst"] == nil {
|
||||
t.Fatalf("disabled: %v", d)
|
||||
}
|
||||
|
||||
e, err := egress.New(egress.Config{Workloads: "ciberlab=10.0.5.0/24:scanner"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
SetEgress(e)
|
||||
defer SetEgress(nil)
|
||||
now := time.Now()
|
||||
ev := func(at time.Time, src, dst string, port uint16) egress.Event {
|
||||
return egress.Event{Time: at, Src: netip.MustParseAddr(src), Dst: netip.MustParseAddr(dst), Proto: "tcp", DPort: port, In: "br-1"}
|
||||
}
|
||||
e.IngestEvent(ev(now.Add(-time.Hour), "10.0.3.5", "203.0.113.3", 6667))
|
||||
e.IngestEvent(ev(now.Add(-time.Hour), "10.0.3.5", "203.0.113.4", 443))
|
||||
for i := 0; i < 80; i++ {
|
||||
e.IngestEvent(ev(now.Add(-30*time.Minute+time.Duration(i)*time.Second), "10.0.5.2", "198.18.0."+strconv.Itoa(i+1), 80))
|
||||
}
|
||||
d = getJSON(t, h, "/api/v1/egress?range=24h", auth)
|
||||
if d["enabled"] != true || d["source"].(map[string]any)["state"] == nil {
|
||||
t.Fatalf("enabled: %v", d)
|
||||
}
|
||||
var port map[string]any
|
||||
for _, f := range d["findings"].([]any) {
|
||||
if m := f.(map[string]any); m["kind"] == "port" {
|
||||
port = m
|
||||
}
|
||||
}
|
||||
if port == nil || port["severity"] != "medium" || port["dport"].(float64) != 6667 || port["workload"] != "container 10.0.3.5" {
|
||||
t.Fatalf("findings: %v", d["findings"])
|
||||
}
|
||||
if len(d["scanner"].(map[string]any)["bursts"].([]any)) != 1 || len(d["workloads"].([]any)) != 2 {
|
||||
t.Fatalf("scanner/workloads: %v", d)
|
||||
}
|
||||
if tl := d["timeline"].(map[string]any); tl["step"].(float64) != 3600 || len(tl["series"].(map[string]any)) != 2 {
|
||||
t.Fatalf("timeline: %v", tl)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/egress?range=bogus", cloneHdr(auth), nil); w.Code != 400 {
|
||||
t.Fatalf("range: %d", w.Code)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/egress?host=nope", cloneHdr(auth), nil); w.Code != 404 {
|
||||
t.Fatalf("host: %d", w.Code)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/egress?range=24h", nil, nil); w.Code != 401 {
|
||||
t.Fatalf("auth: %d", w.Code)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/egress?range=24h", map[string]string{"Authorization": "Bearer peer-secret"}, nil); w.Code == 200 {
|
||||
t.Fatalf("peer token must not open the user route")
|
||||
}
|
||||
|
||||
// peer endpoint (registered by the daemon next to the other peer routes)
|
||||
s := &Server{opt: Options{PeerTokens: []string{"peer-secret"}, Token: userTok, Store: st, Now: time.Now}, ses: newSessions(), lim: newLimiter()}
|
||||
m := http.NewServeMux()
|
||||
m.HandleFunc("GET /api/v1/peer/egress", s.peerEgress)
|
||||
call := func(tok string) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest("GET", "/api/v1/peer/egress?range=24h", nil)
|
||||
r.RemoteAddr = "198.51.100.1:1234"
|
||||
if tok != "" {
|
||||
r.Header.Set("Authorization", "Bearer "+tok)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
m.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
if w := call(""); w.Code != 401 {
|
||||
t.Fatalf("peer no token: %d", w.Code)
|
||||
}
|
||||
if w := call(userTok); w.Code != 401 {
|
||||
t.Fatalf("user token on peer route: %d", w.Code)
|
||||
}
|
||||
w := call("peer-secret")
|
||||
var rep egress.Report
|
||||
if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &rep) != nil || len(rep.Findings) == 0 {
|
||||
t.Fatalf("peer: %d %s", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
|
||||
)
|
||||
|
||||
// enforceEngine is the optional second firewall (nil when --enforce is off).
|
||||
var enforceEngine atomic.Pointer[enforce.Engine]
|
||||
|
||||
// SetEnforce installs the engine the enforce endpoints talk to.
|
||||
func SetEnforce(e *enforce.Engine) { enforceEngine.Store(e) }
|
||||
|
||||
// peerRoute is a route opened by the federation token, contributed by its own file.
|
||||
type peerRoute struct {
|
||||
pattern string
|
||||
handler func(*Server) http.HandlerFunc
|
||||
}
|
||||
|
||||
var peerRoutes []peerRoute
|
||||
|
||||
const maxDecisionBody = 64 << 10
|
||||
|
||||
func init() {
|
||||
registerUserRoute("GET /api/v1/enforce", func(s *Server) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
rg, ok := s.rangeOf(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
now := s.opt.Now()
|
||||
from := now.Add(-rg.Dur).Unix()
|
||||
if rg.From > 0 {
|
||||
from = rg.From
|
||||
}
|
||||
out := map[string]any{"mode": enforce.ModeOff, "share": "off", "threshold": 0, "log_writable": false,
|
||||
"coverage": enforce.Coverage{}, "counts": enforce.Counts{Skipped: map[string]int{}}, "recent": []enforce.Recent{}}
|
||||
if e := enforceEngine.Load(); e != nil {
|
||||
rep := e.Report(from)
|
||||
share := "off"
|
||||
if e.Share() {
|
||||
share = "on"
|
||||
}
|
||||
out["mode"], out["share"], out["threshold"] = e.Mode(), share, e.Threshold()
|
||||
out["log_writable"] = enforce.Writable(e.LogPath())
|
||||
out["coverage"], out["counts"], out["recent"] = rep.Coverage, rep.Counts, rep.Recent
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
})
|
||||
peerRoutes = append(peerRoutes,
|
||||
peerRoute{"GET /api/v1/peer/decisions", func(s *Server) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
e := enforceEngine.Load()
|
||||
if !s.peerGate(w, r) {
|
||||
return
|
||||
}
|
||||
if e == nil || !e.Share() || e.Mode() != enforce.ModeOn {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "decision sharing is not enabled"})
|
||||
return
|
||||
}
|
||||
since, _ := strconv.ParseInt(r.URL.Query().Get("since"), 10, 64)
|
||||
if min := s.opt.Now().Add(-24 * time.Hour).Unix(); since < min {
|
||||
since = min
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"decisions": e.LocalSince(since)})
|
||||
}
|
||||
}},
|
||||
peerRoute{"POST /api/v1/peer/decisions", func(s *Server) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
e := enforceEngine.Load()
|
||||
if !s.peerGate(w, r) {
|
||||
return
|
||||
}
|
||||
if e == nil || !e.Share() {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "decision sharing is not enabled"})
|
||||
return
|
||||
}
|
||||
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxDecisionBody))
|
||||
if err != nil {
|
||||
var mb *http.MaxBytesError
|
||||
if errors.As(err, &mb) {
|
||||
writeJSON(w, http.StatusRequestEntityTooLarge, map[string]string{"error": "body too large"})
|
||||
} else {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "unreadable body"})
|
||||
}
|
||||
return
|
||||
}
|
||||
var in struct {
|
||||
Decisions []enforce.Wire `json:"decisions"`
|
||||
}
|
||||
if json.Unmarshal(body, &in) != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON"})
|
||||
return
|
||||
}
|
||||
if len(in.Decisions) > enforce.MaxWire {
|
||||
writeJSON(w, http.StatusRequestEntityTooLarge, map[string]string{"error": "too many decisions"})
|
||||
return
|
||||
}
|
||||
acc, bad := e.AcceptPeer(r.URL.Query().Get("from"), in.Decisions)
|
||||
writeJSON(w, http.StatusOK, map[string]int{"accepted": acc, "invalid": bad})
|
||||
}
|
||||
}},
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
func enforceRig(t *testing.T, share bool) (http.Handler, *enforce.Engine, string) {
|
||||
t.Helper()
|
||||
log := filepath.Join(t.TempDir(), "decisions.log")
|
||||
st := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour})
|
||||
e := enforce.New(enforce.Config{Mode: enforce.ModeOn, Path: log, Host: "oracle", Threshold: 3, Share: share})
|
||||
st.SetIngestHook(e.Observe)
|
||||
SetEnforce(e)
|
||||
t.Cleanup(func() { SetEnforce(nil) })
|
||||
return New(Options{Token: userTok, PeerTokens: []string{peerTok}, Version: "t", Store: st}), e, log
|
||||
}
|
||||
|
||||
func TestEnforceAPI(t *testing.T) {
|
||||
h, e, log := enforceRig(t, true)
|
||||
auth := map[string]string{"Authorization": "Bearer " + userTok}
|
||||
d := getJSON(t, h, "/api/v1/enforce?range=24h", auth)
|
||||
if d["mode"] != "on" || d["share"] != "on" || d["threshold"].(float64) != 3 || d["log_writable"] != true {
|
||||
t.Fatalf("%v", d)
|
||||
}
|
||||
for _, k := range []string{"coverage", "counts", "recent"} {
|
||||
if d[k] == nil {
|
||||
t.Fatalf("missing %s: %v", k, d)
|
||||
}
|
||||
}
|
||||
if sk := d["counts"].(map[string]any)["skipped"].(map[string]any); len(sk) != 7 {
|
||||
t.Fatalf("skipped %v", sk)
|
||||
}
|
||||
// feed events through the store hook and the engine worker
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go e.Run(ctx)
|
||||
e.Observe(core.Event{Time: time.Now(), IP: "203.0.114.5", Cat: core.Scanner, Source: "traefik", Method: "GET", Path: "/x", Status: 404, UA: "x"}, "")
|
||||
for i := 0; i < 200 && e.Report(0).Coverage.AttackIPs == 0; i++ {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
e.AcceptPeer("hostinger", []enforce.Wire{{T: time.Now().Unix(), IP: "203.0.114.5", Reason: "rce", Score: 90, TTL: 3600}})
|
||||
d = getJSON(t, h, "/api/v1/enforce?range=24h", auth)
|
||||
rec := d["recent"].([]any)
|
||||
if len(rec) != 1 {
|
||||
t.Fatalf("recent %v", d)
|
||||
}
|
||||
r := rec[0].(map[string]any)
|
||||
if r["action"] != "ban" || r["src"] != "peer:hostinger" || r["ip"] != "203.0.114.5" {
|
||||
t.Fatalf("%v", r)
|
||||
}
|
||||
if b, _ := os.ReadFile(log); !strings.Contains(string(b), "src=peer:hostinger") {
|
||||
t.Fatalf("log %q", b)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/enforce?range=24h", nil, nil); w.Code != 401 {
|
||||
t.Fatalf("anonymous %d", w.Code)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/enforce?range=24h", map[string]string{"Authorization": "Bearer " + peerTok}, nil); w.Code != 403 {
|
||||
t.Fatalf("peer token %d", w.Code)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/enforce?range=bad", cloneHdr(auth), nil); w.Code != 400 {
|
||||
t.Fatalf("bad range %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnforceAPIOff(t *testing.T) {
|
||||
st := store.New(store.Config{Name: "oracle", Version: "t"})
|
||||
SetEnforce(nil)
|
||||
h := New(Options{Token: userTok, Store: st})
|
||||
d := getJSON(t, h, "/api/v1/enforce", map[string]string{"Authorization": "Bearer " + userTok})
|
||||
if d["mode"] != "off" {
|
||||
t.Fatalf("%v", d)
|
||||
}
|
||||
}
|
||||
|
||||
func post(h http.Handler, path, tok, body string) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest("POST", path, strings.NewReader(body))
|
||||
r.RemoteAddr = "198.51.100.1:1234"
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
if tok != "" {
|
||||
r.Header.Set("Authorization", "Bearer "+tok)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
|
||||
func TestPeerDecisionsEndpoints(t *testing.T) {
|
||||
h, e, log := enforceRig(t, true)
|
||||
good := `{"decisions":[{"t":` + strconv.FormatInt(time.Now().Unix(), 10) + `,"ip":"203.0.114.9","reason":"sqli","score":80,"ttl":3600},` +
|
||||
`{"t":1,"ip":"203.0.114.10","reason":"x\ny","score":80,"ttl":3600},{"ip":"10.0.0.1","reason":"rce","ttl":60}]}`
|
||||
p := "/api/v1/peer/decisions?from=hostinger"
|
||||
for _, tok := range []string{"", "wrong-token-0123456789-abcdefghijklmnopqrs", userTok} {
|
||||
if w := post(h, p, tok, good); w.Code != 401 && w.Code != 403 {
|
||||
t.Fatalf("token %q: %d", tok, w.Code)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/peer/decisions", map[string]string{"Authorization": "Bearer " + tok}, nil); w.Code != 401 && w.Code != 403 {
|
||||
t.Fatalf("GET token %q: %d", tok, w.Code)
|
||||
}
|
||||
}
|
||||
if w := post(h, p, peerTok, strings.Repeat(" ", 70<<10)); w.Code != 413 {
|
||||
t.Fatalf("big body: %d", w.Code)
|
||||
}
|
||||
if w := post(h, p, peerTok, "{nope"); w.Code != 400 {
|
||||
t.Fatalf("bad json: %d", w.Code)
|
||||
}
|
||||
var many strings.Builder
|
||||
many.WriteString(`{"decisions":[`)
|
||||
for i := 0; i < 501; i++ {
|
||||
if i > 0 {
|
||||
many.WriteString(",")
|
||||
}
|
||||
many.WriteString(`{"ip":"1.1.1.1"}`)
|
||||
}
|
||||
many.WriteString(`]}`)
|
||||
if w := post(h, p, peerTok, many.String()); w.Code != 413 {
|
||||
t.Fatalf("501 items: %d", w.Code)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go e.Run(ctx)
|
||||
e.Observe(core.Event{Time: time.Now(), IP: "203.0.114.9", Cat: core.Scanner, Source: "traefik", Method: "GET", Path: "/x", Status: 404, UA: "x"}, "")
|
||||
for i := 0; i < 200 && e.Report(0).Coverage.AttackIPs == 0; i++ {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
w := post(h, p, peerTok, good)
|
||||
if w.Code != 200 || !strings.Contains(w.Body.String(), `"accepted":1`) || !strings.Contains(w.Body.String(), `"invalid":2`) {
|
||||
t.Fatalf("%d %s", w.Code, w.Body)
|
||||
}
|
||||
b, _ := os.ReadFile(log)
|
||||
if strings.Count(string(b), "\n") != 1 || !strings.Contains(string(b), "ip=203.0.114.9 reason=sqli") || !strings.Contains(string(b), "src=peer:hostinger") {
|
||||
t.Fatalf("log %q", b)
|
||||
}
|
||||
// GET returns local decisions only
|
||||
if len(e.LocalSince(0)) != 0 {
|
||||
t.Fatal("peer decision leaked into the local list")
|
||||
}
|
||||
rr := do(h, "GET", "/api/v1/peer/decisions?since=0", map[string]string{"Authorization": "Bearer " + peerTok}, nil)
|
||||
if rr.Code != 200 || !strings.Contains(rr.Body.String(), `"decisions":[]`) {
|
||||
t.Fatalf("%d %s", rr.Code, rr.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerDecisionsShareOff(t *testing.T) {
|
||||
h, _, _ := enforceRig(t, false)
|
||||
if w := post(h, "/api/v1/peer/decisions", peerTok, `{"decisions":[]}`); w.Code != 404 {
|
||||
t.Fatalf("share off: %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnforceFromStoreHook(t *testing.T) {
|
||||
log := filepath.Join(t.TempDir(), "d.log")
|
||||
st := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour})
|
||||
e := enforce.New(enforce.Config{Mode: enforce.ModeOn, Path: log, Host: "oracle", Threshold: 3})
|
||||
st.SetIngestHook(e.Observe)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go e.Run(ctx)
|
||||
for i := 0; i < 3; i++ {
|
||||
st.Ingest(core.Event{Time: time.Now(), IP: "203.0.114.9", Cat: core.Scanner, Source: "traefik", Method: "GET", Path: "/x" + strconv.Itoa(i), Status: 404, UA: "nuclei"})
|
||||
}
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if b, _ := os.ReadFile(log); strings.Contains(string(b), "ip=203.0.114.9 ") {
|
||||
return
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
t.Fatal("no decision written")
|
||||
}
|
||||
@@ -121,10 +121,31 @@ var attackCats = []string{"scanner", "exploit", "bruteforce", "ssh-fail", "ssh-p
|
||||
|
||||
// report: GET /api/v1/report, the aggregate behind the executive report.
|
||||
func (s *Server) report(w http.ResponseWriter, r *http.Request) {
|
||||
if f := r.URL.Query().Get("format"); f != "" && f != "json" {
|
||||
badRequest(w, "format must be json")
|
||||
f := r.URL.Query().Get("format")
|
||||
if f != "" && f != "json" && f != "html" {
|
||||
badRequest(w, "format must be json or html")
|
||||
return
|
||||
}
|
||||
rc, ok := s.buildReport(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if f == "html" {
|
||||
s.writeReportHTML(w, r, rc)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, rc.out)
|
||||
}
|
||||
|
||||
// reportCtx is the computed report plus the window it covers.
|
||||
type reportCtx struct {
|
||||
out reportOut
|
||||
rg store.Range
|
||||
host string
|
||||
from, to int64
|
||||
}
|
||||
|
||||
func (s *Server) buildReport(w http.ResponseWriter, r *http.Request) (*reportCtx, bool) {
|
||||
if r.URL.Query().Get("range") == "" && r.URL.Query().Get("from") == "" {
|
||||
q := r.URL.Query()
|
||||
q.Set("range", "7d")
|
||||
@@ -132,14 +153,14 @@ func (s *Server) report(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
rg, ok := s.rangeOf(w, r)
|
||||
if !ok {
|
||||
return
|
||||
return nil, false
|
||||
}
|
||||
host := r.URL.Query().Get("host")
|
||||
if host == "" {
|
||||
host = "all"
|
||||
}
|
||||
if !s.knownHost(w, host) {
|
||||
return
|
||||
return nil, false
|
||||
}
|
||||
now := s.opt.Now().Unix()
|
||||
info := rg.Info(now)
|
||||
@@ -149,7 +170,7 @@ func (s *Server) report(w http.ResponseWriter, r *http.Request) {
|
||||
// period study (families, techniques, ASNs, campaigns, escalations)
|
||||
per, ok := s.periodStudy(w, r)
|
||||
if !ok {
|
||||
return
|
||||
return nil, false
|
||||
}
|
||||
// summary of the period and of the previous one
|
||||
parts, all := s.parts(r.Context(), rg, host)
|
||||
@@ -262,13 +283,14 @@ func (s *Server) report(w http.ResponseWriter, r *http.Request) {
|
||||
// defence metrics (same study and slot as /metrics)
|
||||
m, ok := s.reportMetrics(w, r, rg, host)
|
||||
if !ok {
|
||||
return
|
||||
return nil, false
|
||||
}
|
||||
d := &out.Defense
|
||||
d.MTTBMedianS, d.MTTBP90S, d.MTTBPrevMedianS, d.MTTBN = m.MTTB.MedianS, m.MTTB.P90S, m.MTTB.PrevMed, m.MTTB.N
|
||||
d.BanCoverage, d.BanCoveragePrev = m.BanCoverage.Value, m.BanCoverage.Prev
|
||||
d.BlocklistCover, d.ExposureRate, d.ExploitsRefused = m.BlocklistCoverage.Value, m.ExposureRate.Value, m.ExploitsRefused.Value
|
||||
writeJSON(w, 200, out)
|
||||
f, t := rg.Bounds(now)
|
||||
return &reportCtx{out: out, rg: rg, host: host, from: f, to: t}, true
|
||||
}
|
||||
|
||||
func capCounts(c []store.Count, n int) []store.Count {
|
||||
|
||||
@@ -0,0 +1,774 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/png"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
// This file renders GET /api/v1/report?format=html: one self-contained A4 document
|
||||
// (inline CSS, SVG charts, logo as data URI, no JavaScript). Every dynamic string
|
||||
// goes through html/template; SVG is built here from escaped text and numbers.
|
||||
|
||||
// enforceView is the second-firewall data of the report (nil: engine not running).
|
||||
type enforceView struct {
|
||||
Mode string
|
||||
Share bool
|
||||
Coverage enforce.Coverage
|
||||
Counts enforce.Counts
|
||||
Recent []enforce.Recent
|
||||
}
|
||||
|
||||
// egressView is the outbound-traffic data of the report (nil: analysis not running).
|
||||
type egressView struct {
|
||||
Source egress.SourceInfo
|
||||
Report egress.Report
|
||||
}
|
||||
|
||||
// reportInput is everything the renderer needs. To wire another source, fill a
|
||||
// field here in reportExtras; the renderer skips sections whose pointer is nil.
|
||||
type reportInput struct {
|
||||
Out reportOut
|
||||
Lang string
|
||||
Traffic store.TrafficData
|
||||
Classes [store.NumCls]uint32
|
||||
HasHealth bool
|
||||
Enforce *enforceView
|
||||
Egress *egressView
|
||||
Peers bool // other hosts included: health and egress cover only this server
|
||||
}
|
||||
|
||||
var (
|
||||
logoOnce sync.Once
|
||||
logoURI string
|
||||
)
|
||||
|
||||
// logoDataURI returns web/logo.png scaled to 200px as a data URI (computed once).
|
||||
func logoDataURI() template.URL {
|
||||
logoOnce.Do(func() {
|
||||
raw, err := webFS.ReadFile("web/logo.png")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
src, err := png.Decode(bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
dst := scaleRGBA(src, 200)
|
||||
var buf bytes.Buffer
|
||||
if png.Encode(&buf, dst) == nil {
|
||||
logoURI = "data:image/png;base64," + base64.StdEncoding.EncodeToString(buf.Bytes())
|
||||
}
|
||||
})
|
||||
return template.URL(logoURI)
|
||||
}
|
||||
|
||||
// scaleRGBA shrinks to a square of side n by averaging premultiplied pixels.
|
||||
func scaleRGBA(src image.Image, n int) *image.NRGBA {
|
||||
b := src.Bounds()
|
||||
w, h := b.Dx(), b.Dy()
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, n, n))
|
||||
for y := 0; y < n; y++ {
|
||||
y0, y1 := y*h/n, (y+1)*h/n
|
||||
if y1 <= y0 {
|
||||
y1 = y0 + 1
|
||||
}
|
||||
for x := 0; x < n; x++ {
|
||||
x0, x1 := x*w/n, (x+1)*w/n
|
||||
if x1 <= x0 {
|
||||
x1 = x0 + 1
|
||||
}
|
||||
var r, g, bl, a, c uint64
|
||||
for yy := y0; yy < y1 && yy < h; yy++ {
|
||||
for xx := x0; xx < x1 && xx < w; xx++ {
|
||||
pr, pg, pb, pa := src.At(b.Min.X+xx, b.Min.Y+yy).RGBA()
|
||||
r, g, bl, a, c = r+uint64(pr), g+uint64(pg), bl+uint64(pb), a+uint64(pa), c+1
|
||||
}
|
||||
}
|
||||
if c == 0 || a == 0 {
|
||||
continue
|
||||
}
|
||||
dst.SetNRGBA(x, y, color.NRGBA{R: uint8(r * 255 / a), G: uint8(g * 255 / a), B: uint8(bl * 255 / a), A: uint8(a / c >> 8)})
|
||||
}
|
||||
}
|
||||
return dst
|
||||
}
|
||||
|
||||
// ---- view model -------------------------------------------------------------
|
||||
|
||||
type kpiV struct{ Label, Value, Delta, Cls string }
|
||||
type rowV struct{ Cells []string }
|
||||
type tableV struct {
|
||||
Head []string
|
||||
Rows []rowV
|
||||
Num map[int]bool // right-aligned columns
|
||||
NoWrap map[int]bool
|
||||
None string
|
||||
}
|
||||
type chartV struct {
|
||||
Title string
|
||||
SVG template.HTML
|
||||
Legend []legendV
|
||||
Empty bool
|
||||
}
|
||||
type legendV struct{ Label, Value, Color string }
|
||||
type recV struct{ Level, Label, Text string }
|
||||
type secV struct{ ID, Title string }
|
||||
|
||||
type viewV struct {
|
||||
Lang, Title, RunHead, RunFoot, Kicker, CoverTitle, CoverSub string
|
||||
Logo template.URL
|
||||
Motif template.HTML
|
||||
Servers, Period, Generated string
|
||||
LPeriod, LServers, LGen, LConf, LToc string
|
||||
CoverNums []kpiV
|
||||
TOC []secV
|
||||
KPIs []kpiV
|
||||
VerdictCls, VerdictTitle string
|
||||
Verdict []string
|
||||
Recs []recV
|
||||
Trunc string
|
||||
Timeline chartV
|
||||
Fams, Techs chartV
|
||||
IPs, Camps, Escs tableV
|
||||
Expo tableV
|
||||
Countries, ASNs chartV
|
||||
HealthLead string
|
||||
HealthNotes []string
|
||||
Classes, Status chartV
|
||||
VisLead string
|
||||
VisKPIs []kpiV
|
||||
Pages, Browsers, Devices, Refs chartV
|
||||
Defense tableV
|
||||
HasEnf bool
|
||||
EnfLead string
|
||||
EnfNotes []string
|
||||
EnfKPIs []kpiV
|
||||
EnfRecent tableV
|
||||
HasEgress bool
|
||||
XLead string
|
||||
XNotes []string
|
||||
XWl, XFind tableV
|
||||
XChart, XDst chartV
|
||||
NoEnf, NoEgress, None, PeersNote, MethodP1, MethodP2, MethodP3 string
|
||||
TThreats, TGeo, THealth, TVis, TDef, TEnf, TEgress, TRecs, TMethod, TSum string
|
||||
TIPs, TCamps, TEscs, TExpo, TTimeline, TFams, TTechs, TCountries, TASNs string
|
||||
TEnfRecent, TXFind, TXWl, TXChart, TXDst, TClasses, TStatus string
|
||||
ShowPeers bool
|
||||
}
|
||||
|
||||
var rptCCRe = regexp.MustCompile(`^[A-Za-z]{2}$`)
|
||||
|
||||
type renderer struct {
|
||||
lang int
|
||||
code string
|
||||
}
|
||||
|
||||
func newRenderer(lang string) *renderer {
|
||||
if strings.HasPrefix(strings.ToLower(lang), "en") {
|
||||
return &renderer{1, "en"}
|
||||
}
|
||||
return &renderer{0, "pt-BR"}
|
||||
}
|
||||
|
||||
func (r *renderer) t(key string, args ...any) string {
|
||||
v, ok := reportText[key]
|
||||
if !ok {
|
||||
return key
|
||||
}
|
||||
s := v[r.lang]
|
||||
if len(args) > 0 {
|
||||
return fmt.Sprintf(s, args...)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// num formats integers with the thousands separator of the language.
|
||||
func (r *renderer) num(n float64) string {
|
||||
neg := n < 0
|
||||
if neg {
|
||||
n = -n
|
||||
}
|
||||
s := fmt.Sprintf("%.0f", n)
|
||||
sep := "."
|
||||
if r.lang == 1 {
|
||||
sep = ","
|
||||
}
|
||||
var out []byte
|
||||
for i := range s {
|
||||
if i > 0 && (len(s)-i)%3 == 0 {
|
||||
out = append(out, sep...)
|
||||
}
|
||||
out = append(out, s[i])
|
||||
}
|
||||
if neg {
|
||||
return "-" + string(out)
|
||||
}
|
||||
return string(out)
|
||||
}
|
||||
|
||||
func (r *renderer) dec(v float64, d int) string {
|
||||
s := fmt.Sprintf("%.*f", d, v)
|
||||
if r.lang == 0 {
|
||||
s = strings.Replace(s, ".", ",", 1)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func (r *renderer) pct(v float64) string { return r.dec(v, 1) + "%" }
|
||||
|
||||
func (r *renderer) dur(sec float64) string {
|
||||
s := int64(sec + 0.5)
|
||||
switch {
|
||||
case s < 60:
|
||||
return fmt.Sprintf("%ds", s)
|
||||
case s < 3600:
|
||||
return fmt.Sprintf("%dmin", s/60)
|
||||
case s < 86400:
|
||||
return fmt.Sprintf("%dh%02d", s/3600, s%3600/60)
|
||||
}
|
||||
return fmt.Sprintf("%dd", s/86400)
|
||||
}
|
||||
|
||||
func (r *renderer) date(ts int64) string {
|
||||
if r.lang == 1 {
|
||||
return time.Unix(ts, 0).UTC().Format("2006-01-02 15:04 UTC")
|
||||
}
|
||||
return time.Unix(ts, 0).UTC().Format("02/01/2006 15:04 UTC")
|
||||
}
|
||||
|
||||
func (r *renderer) day(ts int64) string {
|
||||
if r.lang == 1 {
|
||||
return time.Unix(ts, 0).UTC().Format("2006-01-02")
|
||||
}
|
||||
return time.Unix(ts, 0).UTC().Format("02/01/2006")
|
||||
}
|
||||
|
||||
func (r *renderer) yn(b bool) string {
|
||||
if b {
|
||||
return r.t("yes")
|
||||
}
|
||||
return r.t("no")
|
||||
}
|
||||
|
||||
func (r *renderer) tr(prefix, k string) string {
|
||||
if v, ok := reportText[prefix+k]; ok {
|
||||
return v[r.lang]
|
||||
}
|
||||
return k
|
||||
}
|
||||
|
||||
func ccOf(cc, name string) string {
|
||||
switch {
|
||||
case rptCCRe.MatchString(cc) && name != "":
|
||||
return strings.ToUpper(cc) + " · " + name
|
||||
case rptCCRe.MatchString(cc):
|
||||
return strings.ToUpper(cc)
|
||||
case name != "":
|
||||
return name
|
||||
}
|
||||
return "-"
|
||||
}
|
||||
|
||||
func (r *renderer) counts(c []store.Count, label func(store.Count) string, n int) []chartItem {
|
||||
var out []chartItem
|
||||
for i, x := range c {
|
||||
if i >= n {
|
||||
break
|
||||
}
|
||||
out = append(out, chartItem{label(x), float64(x.N)})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (r *renderer) barChart(title string, items []chartItem, color string) chartV {
|
||||
if len(items) == 0 {
|
||||
return chartV{Title: title, Empty: true}
|
||||
}
|
||||
return chartV{Title: title, SVG: template.HTML(svgBars(items, color, func(v float64) string { return r.num(v) }, title))}
|
||||
}
|
||||
|
||||
func (r *renderer) donutChart(title string, items []chartItem) chartV {
|
||||
var total float64
|
||||
for _, it := range items {
|
||||
total += it.N
|
||||
}
|
||||
if total <= 0 {
|
||||
return chartV{Title: title, Empty: true}
|
||||
}
|
||||
c := chartV{Title: title, SVG: template.HTML(svgDonut(items, title))}
|
||||
for i, it := range items {
|
||||
c.Legend = append(c.Legend, legendV{it.Label, r.num(it.N) + " · " + r.pct(it.N/total*100), reportPalette[i%len(reportPalette)]})
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func delta(r *renderer, v float64, ok bool, prev float64) string {
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
a := "▲"
|
||||
if v < 0 {
|
||||
a = "▼"
|
||||
}
|
||||
if v > -0.5 && v < 0.5 {
|
||||
a = "="
|
||||
}
|
||||
if v < 0 {
|
||||
v = -v
|
||||
}
|
||||
return fmt.Sprintf("%s %s%% · %s", a, r.num(v+0.0001), r.t("k.before", r.num(prev)))
|
||||
}
|
||||
|
||||
// build turns the data into the view model (all the report decisions live here).
|
||||
func (r *renderer) build(in reportInput, genTS int64) viewV {
|
||||
o, s := in.Out, in.Out.Summary
|
||||
v := viewV{Lang: r.code, Logo: logoDataURI()}
|
||||
v.Title, v.RunHead, v.RunFoot = r.t("doc.title"), r.t("run.head"), r.t("run.foot")
|
||||
v.Kicker, v.CoverTitle, v.CoverSub = r.t("cover.kicker"), r.t("cover.title"), r.t("cover.sub")
|
||||
v.LPeriod, v.LServers, v.LGen, v.LConf, v.LToc = r.t("cover.period"), r.t("cover.servers"), r.t("cover.gen"), r.t("cover.conf"), r.t("toc")
|
||||
v.None, v.NoEnf, v.NoEgress, v.PeersNote = r.t("none"), r.t("noenf"), r.t("noegress"), r.t("peers.note")
|
||||
v.MethodP1, v.MethodP2, v.MethodP3 = r.t("m.p1"), r.t("m.p2"), r.t("m.p3")
|
||||
v.TSum, v.TThreats, v.TGeo, v.THealth, v.TVis = r.t("s.sum"), r.t("s.threats"), r.t("s.geo"), r.t("s.health"), r.t("s.visitors")
|
||||
v.TDef, v.TEnf, v.TEgress, v.TRecs, v.TMethod = r.t("s.defense"), r.t("s.enforce"), r.t("s.egress"), r.t("s.recs"), r.t("s.method")
|
||||
v.TIPs, v.TCamps, v.TEscs, v.TExpo, v.TTimeline = r.t("t.ips"), r.t("t.camp"), r.t("t.esc"), r.t("t.expo"), r.t("c.timeline")
|
||||
v.TFams, v.TTechs, v.TCountries, v.TASNs = r.t("c.families"), r.t("c.techs"), r.t("c.countries"), r.t("c.asns")
|
||||
v.TEnfRecent, v.TXFind, v.TXWl, v.TXChart, v.TXDst = r.t("t.enf"), r.t("t.find"), r.t("t.wl"), r.t("c.egress"), r.t("c.dst")
|
||||
v.TClasses, v.TStatus = r.t("c.classes"), r.t("c.status")
|
||||
v.ShowPeers = in.Peers
|
||||
|
||||
servers := r.t("cover.all")
|
||||
if len(o.Hosts) > 0 {
|
||||
servers = strings.Join(o.Hosts, ", ")
|
||||
}
|
||||
v.Servers = servers
|
||||
v.Period = r.day(o.Range.From) + " – " + r.day(o.Range.To)
|
||||
v.Generated = r.date(genTS)
|
||||
|
||||
cover := 0.0
|
||||
if s.HostileIPs > 0 {
|
||||
cover = o.Defense.BanCoverage
|
||||
}
|
||||
v.CoverNums = []kpiV{
|
||||
{Label: r.t("k.attacks"), Value: r.num(float64(s.Attacks))},
|
||||
{Label: r.t("k.hostile"), Value: r.num(float64(s.HostileIPs))},
|
||||
{Label: r.t("k.bans"), Value: r.num(float64(s.Bans))},
|
||||
{Label: r.t("k.coverage"), Value: r.dec(cover, 0) + "%"},
|
||||
}
|
||||
|
||||
// signals for verdict and recommendations
|
||||
expo := o.Exposures.Total
|
||||
var xHigh int
|
||||
if in.Egress != nil {
|
||||
for _, f := range in.Egress.Report.Findings {
|
||||
if f.Severity == "high" || f.Severity == "critical" {
|
||||
xHigh++
|
||||
}
|
||||
}
|
||||
}
|
||||
level := "good"
|
||||
switch {
|
||||
case expo > 0 || xHigh > 0:
|
||||
level = "bad"
|
||||
case len(o.Escalations) > 0 || (s.HostileIPs > 0 && cover < 80):
|
||||
level = "warn"
|
||||
}
|
||||
v.VerdictCls = level
|
||||
v.VerdictTitle = r.t("verdict." + level)
|
||||
|
||||
// verdict paragraph, lay language
|
||||
var vd []string
|
||||
if s.Attacks == 0 {
|
||||
vd = append(vd, r.t("v.none"))
|
||||
} else {
|
||||
vd = append(vd, r.t("v.intro", servers, r.num(float64(s.Attacks)), r.num(float64(s.UniqueIPs)), r.num(float64(s.HostileIPs)), r.num(float64(s.Bans))))
|
||||
if dp, ok := s.DeltaPct["attacks"]; s.HasPrev && ok {
|
||||
switch {
|
||||
case dp > -5 && dp < 5:
|
||||
vd = append(vd, r.t("v.flat"))
|
||||
case dp > 0:
|
||||
vd = append(vd, r.t("v.up", r.num(dp)))
|
||||
default:
|
||||
vd = append(vd, r.t("v.down", r.num(-dp)))
|
||||
}
|
||||
} else {
|
||||
vd = append(vd, r.t("v.noprev"))
|
||||
}
|
||||
if len(o.Families) > 0 && len(o.Countries) > 0 {
|
||||
vd = append(vd, r.t("v.top", o.Families[0].Key, o.Countries[0].Key))
|
||||
}
|
||||
if s.HostileIPs > 0 {
|
||||
vd = append(vd, r.t("v.cover", r.dec(cover, 0)))
|
||||
}
|
||||
if o.Defense.MTTBN > 0 {
|
||||
vd = append(vd, r.t("v.mttb", r.dur(o.Defense.MTTBMedianS)))
|
||||
}
|
||||
}
|
||||
if expo > 0 {
|
||||
vd = append(vd, r.t("v.expo", r.num(float64(expo))))
|
||||
} else if s.Attacks > 0 {
|
||||
vd = append(vd, r.t("v.expo0"))
|
||||
}
|
||||
if len(o.Escalations) > 0 {
|
||||
vd = append(vd, r.t("v.esc", r.num(float64(len(o.Escalations)))))
|
||||
}
|
||||
if xHigh > 0 {
|
||||
vd = append(vd, r.t("v.egress", r.num(float64(xHigh))))
|
||||
}
|
||||
v.Verdict = vd
|
||||
if o.Truncated {
|
||||
v.Trunc = r.t("trunc")
|
||||
}
|
||||
|
||||
// KPIs
|
||||
dl := func(k string, cur, prev uint64) string {
|
||||
d, ok := s.DeltaPct[k]
|
||||
return delta(r, d, s.HasPrev && ok, float64(prev))
|
||||
}
|
||||
kc := func(warn bool) string {
|
||||
if warn {
|
||||
return "warn"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
v.KPIs = []kpiV{
|
||||
{r.t("k.requests"), r.num(float64(s.Requests)), dl("requests", s.Requests, s.Prev.Requests), ""},
|
||||
{r.t("k.attacks"), r.num(float64(s.Attacks)), dl("attacks", s.Attacks, s.Prev.Attacks), kc(s.Attacks > 0)},
|
||||
{r.t("k.hostile"), r.num(float64(s.HostileIPs)), dl("hostile_ips", uint64(s.HostileIPs), uint64(s.Prev.HostileIPs)), kc(s.HostileIPs > 0)},
|
||||
{r.t("k.bans"), r.num(float64(s.Bans)), dl("bans", uint64(s.Bans), uint64(s.Prev.Bans)), ""},
|
||||
{r.t("k.visitors"), r.num(float64(s.Visitors)), dl("visitors", s.Visitors, s.Prev.Visitors), ""},
|
||||
{r.t("k.coverage"), r.dec(cover, 0) + "%", "", kc(s.HostileIPs > 0 && cover < 80)},
|
||||
}
|
||||
|
||||
// threats
|
||||
vals := o.Timeline.Values
|
||||
v.Timeline = chartV{Title: v.TTimeline, SVG: template.HTML(svgArea(vals, o.Timeline.Start, o.Timeline.Step, r.num, v.TTimeline))}
|
||||
if len(vals) == 0 {
|
||||
v.Timeline = chartV{Title: v.TTimeline, Empty: true}
|
||||
}
|
||||
v.Motif = template.HTML(svgMotif(vals))
|
||||
v.Fams = r.donutChart(v.TFams, r.counts(o.Families, func(c store.Count) string { return c.Key }, 6))
|
||||
v.Techs = r.barChart(v.TTechs, r.counts(o.Techniques, func(c store.Count) string {
|
||||
if c.Label != "" {
|
||||
return c.Key + " " + c.Label
|
||||
}
|
||||
return c.Key
|
||||
}, 8), "#c2410c")
|
||||
v.IPs = tableV{Head: []string{r.t("col.ip"), r.t("col.level"), r.t("col.score"), r.t("col.country"), r.t("col.net"), r.t("col.events"), r.t("col.banned")}, Num: map[int]bool{2: true, 5: true}, NoWrap: map[int]bool{0: true}}
|
||||
for _, x := range o.TopIPs {
|
||||
v.IPs.Rows = append(v.IPs.Rows, rowV{[]string{x.IP, r.tr("lvl.", x.Level), r.dec(x.Score, 1), ccOf(x.CC, x.Country), dash(x.ASOrg), r.num(float64(x.Events)), r.yn(x.Banned)}})
|
||||
}
|
||||
v.Camps = tableV{Head: []string{r.t("col.camp"), r.t("col.ips"), r.t("col.active"), r.t("col.techs")}, Num: map[int]bool{1: true}}
|
||||
for _, c := range o.Campaigns {
|
||||
v.Camps.Rows = append(v.Camps.Rows, rowV{[]string{c.ID, r.num(float64(c.IPsN)), r.day(c.First.Unix()) + " – " + r.day(c.Last.Unix()), strings.Join(firstN(c.Techs, 4), ", ")}})
|
||||
}
|
||||
v.Escs = tableV{Head: []string{r.t("col.ip"), r.t("col.stage"), r.t("col.host")}}
|
||||
for _, e := range o.Escalations {
|
||||
v.Escs.Rows = append(v.Escs.Rows, rowV{[]string{e.IP, r.tr("stage.", e.Stage), dash(e.Host)}})
|
||||
}
|
||||
v.Expo = tableV{Head: []string{r.t("col.when"), r.t("col.ip"), r.t("col.host"), r.t("col.path"), r.t("col.status"), r.t("col.fam")}, Num: map[int]bool{4: true}, NoWrap: map[int]bool{0: true, 1: true}}
|
||||
for _, e := range o.Exposures.Items {
|
||||
host := e.Domain
|
||||
if host == "" {
|
||||
host = e.Host
|
||||
}
|
||||
v.Expo.Rows = append(v.Expo.Rows, rowV{[]string{r.date(e.T), e.IP, dash(host), clip(e.Path, 56), fmt.Sprint(e.Status), dash(e.Fam)}})
|
||||
}
|
||||
|
||||
// geography
|
||||
v.Countries = r.barChart(v.TCountries, r.counts(o.Countries, func(c store.Count) string { return c.Key }, 10), "#087f68")
|
||||
v.ASNs = r.barChart(v.TASNs, r.counts(o.ASNs, func(c store.Count) string {
|
||||
if c.Label != "" {
|
||||
return c.Key + " " + c.Label
|
||||
}
|
||||
return c.Key
|
||||
}, 10), "#087f68")
|
||||
|
||||
// health: thwarted attacks are not application errors
|
||||
c := in.Classes
|
||||
if in.HasHealth {
|
||||
good := float64(c[store.ClsAttack] + c[store.ClsBlocked] + c[store.ClsBot])
|
||||
bad := float64(c[store.ClsApp] + c[store.ClsProxy])
|
||||
v.HealthLead = r.t("h.lead")
|
||||
if good > 0 {
|
||||
v.HealthNotes = append(v.HealthNotes, r.t("h.good", r.num(good)))
|
||||
}
|
||||
if bad > 0 {
|
||||
v.HealthNotes = append(v.HealthNotes, r.t("h.app", r.num(bad)))
|
||||
}
|
||||
var items []chartItem
|
||||
for i, n := range store.ClsNames {
|
||||
items = append(items, chartItem{r.tr("cls.", n), float64(c[i])})
|
||||
}
|
||||
sort.SliceStable(items, func(a, b int) bool { return items[a].N > items[b].N })
|
||||
v.Classes = r.donutChart(v.TClasses, items)
|
||||
if in.Traffic.P95 > 0 {
|
||||
v.HealthNotes = append(v.HealthNotes, r.t("h.p95", r.num(in.Traffic.P50), r.num(in.Traffic.P95)))
|
||||
}
|
||||
} else {
|
||||
v.HealthLead = r.t("h.nodata")
|
||||
v.Classes = chartV{Title: v.TClasses, Empty: true}
|
||||
}
|
||||
st := in.Traffic.Status
|
||||
v.Status = r.donutChart(v.TStatus, []chartItem{{r.t("st.2xx"), float64(st[0])}, {r.t("st.3xx"), float64(st[1])}, {r.t("st.4xx"), float64(st[2])}, {r.t("st.5xx"), float64(st[3])}})
|
||||
|
||||
// visitors
|
||||
tr := in.Traffic
|
||||
v.VisLead = r.t("vis.lead")
|
||||
v.VisKPIs = []kpiV{{Label: r.t("k.visitors"), Value: r.num(float64(tr.Visitors))}, {Label: r.t("k.pages"), Value: r.num(float64(tr.Pages))}, {Label: r.t("k.nonhuman"), Value: r.num(float64(tr.NonHuman))}}
|
||||
lab := func(c store.Count) string { return dash(c.Key) }
|
||||
v.Pages = r.barChart(r.t("c.pages"), r.counts(tr.TopPages, lab, 8), "#f97316")
|
||||
v.Browsers = r.donutChart(r.t("c.browsers"), r.counts(tr.Browsers, lab, 6))
|
||||
v.Devices = r.donutChart(r.t("c.devices"), r.counts(tr.Devices, lab, 5))
|
||||
v.Refs = r.barChart(r.t("c.refs"), r.counts(tr.Referrers, lab, 6), "#4b6b61")
|
||||
|
||||
// defence
|
||||
d := o.Defense
|
||||
nodata := d.MTTBN == 0
|
||||
mt := func(x float64) string {
|
||||
if nodata {
|
||||
return "-"
|
||||
}
|
||||
return r.dur(x)
|
||||
}
|
||||
v.Defense = tableV{Head: []string{r.t("col.metric"), r.t("col.value"), r.t("col.meaning")}, Num: map[int]bool{1: true}, Rows: []rowV{
|
||||
{[]string{r.t("d.cover"), r.pct(d.BanCoverage), r.t("d.cover.m")}},
|
||||
{[]string{r.t("d.mttb"), mt(d.MTTBMedianS), r.t("d.mttb.m")}},
|
||||
{[]string{r.t("d.mttbp90"), mt(d.MTTBP90S), ""}},
|
||||
{[]string{r.t("d.mttbn"), r.num(float64(d.MTTBN)), ""}},
|
||||
{[]string{r.t("d.block"), r.pct(d.BlocklistCover), r.t("d.block.m")}},
|
||||
{[]string{r.t("d.expo"), r.pct(d.ExposureRate), r.t("d.expo.m")}},
|
||||
{[]string{r.t("d.refused"), r.pct(d.ExploitsRefused), r.t("d.refused.m")}},
|
||||
}}
|
||||
|
||||
// second firewall
|
||||
if e := in.Enforce; e != nil && e.Mode != enforce.ModeOff {
|
||||
v.HasEnf = true
|
||||
v.EnfLead = r.t("e.lead")
|
||||
v.EnfNotes = append(v.EnfNotes, r.t("e.mode")+": "+r.t("e.mode."+e.Mode))
|
||||
cv := e.Coverage
|
||||
if cv.AttackIPs > 0 {
|
||||
v.EnfNotes = append(v.EnfNotes, r.t("e.cov", r.num(float64(cv.BlockedByFirewall+cv.BlockedByUrutau)), r.num(float64(cv.AttackIPs)), r.num(float64(cv.BlockedByFirewall)), r.num(float64(cv.BlockedByUrutau))))
|
||||
}
|
||||
if cv.WouldBlock > 0 {
|
||||
v.EnfNotes = append(v.EnfNotes, r.t("e.would", r.num(float64(cv.WouldBlock))))
|
||||
}
|
||||
if cv.Unblocked > 0 {
|
||||
v.EnfNotes = append(v.EnfNotes, r.t("e.unb", r.num(float64(cv.Unblocked))))
|
||||
}
|
||||
v.EnfKPIs = []kpiV{{Label: r.t("e.decided"), Value: r.num(float64(e.Counts.Decided))}, {Label: r.t("e.written"), Value: r.num(float64(e.Counts.Written))},
|
||||
{Label: r.t("e.already"), Value: r.num(float64(e.Counts.AlreadyBlocked))}, {Label: r.t("e.werr"), Value: r.num(float64(e.Counts.WriteErrors)), Cls: kc(e.Counts.WriteErrors > 0)}}
|
||||
v.EnfRecent = tableV{Head: []string{r.t("col.when"), r.t("col.ip"), r.t("col.reason"), r.t("col.action"), r.t("col.country")}, NoWrap: map[int]bool{0: true, 1: true}}
|
||||
for i, x := range e.Recent {
|
||||
if i >= 10 {
|
||||
break
|
||||
}
|
||||
v.EnfRecent.Rows = append(v.EnfRecent.Rows, rowV{[]string{r.date(x.T), x.IP, dash(x.Reason), dash(x.Action), ccOf(x.CC, "")}})
|
||||
}
|
||||
}
|
||||
|
||||
// egress
|
||||
if x := in.Egress; x != nil && x.Source.State != "disabled" && x.Source.State != "" {
|
||||
v.HasEgress = true
|
||||
v.XLead = r.t("x.lead")
|
||||
rep := x.Report
|
||||
if len(rep.Findings) == 0 {
|
||||
v.XNotes = append(v.XNotes, r.t("x.nof"))
|
||||
} else {
|
||||
v.XNotes = append(v.XNotes, r.t("x.sev", r.num(float64(len(rep.Findings))), r.num(float64(xHigh))))
|
||||
}
|
||||
v.XNotes = append(v.XNotes, r.t("x.src", x.Source.State))
|
||||
v.XWl = tableV{Head: []string{r.t("col.wl"), r.t("col.role"), r.t("col.conns"), r.t("col.dst")}, Num: map[int]bool{2: true, 3: true}}
|
||||
var items []chartItem
|
||||
for i, w := range rep.Workloads {
|
||||
if i < 12 {
|
||||
v.XWl.Rows = append(v.XWl.Rows, rowV{[]string{w.Name, dash(w.Role), r.num(float64(w.Conns)), r.num(float64(w.Dsts))}})
|
||||
}
|
||||
if i < 8 {
|
||||
items = append(items, chartItem{w.Name, float64(w.Conns)})
|
||||
}
|
||||
}
|
||||
v.XChart = r.barChart(v.TXChart, items, "#087f68")
|
||||
var dst []chartItem
|
||||
for i, d := range rep.TopDst {
|
||||
if i >= 8 {
|
||||
break
|
||||
}
|
||||
dst = append(dst, chartItem{d.IP + " " + d.CC, float64(d.Conns)})
|
||||
}
|
||||
v.XDst = r.barChart(v.TXDst, dst, "#c2410c")
|
||||
v.XFind = tableV{Head: []string{r.t("col.sev"), r.t("col.kind"), r.t("col.wl"), r.t("col.dst"), r.t("col.detail")}}
|
||||
for i, f := range rep.Findings {
|
||||
if i >= 10 {
|
||||
break
|
||||
}
|
||||
v.XFind.Rows = append(v.XFind.Rows, rowV{[]string{r.tr("sev.", f.Severity), dash(f.Kind), f.Workload, fmt.Sprintf("%s:%d/%s", f.Dst, f.DPort, f.Proto), clip(f.Detail, 80)}})
|
||||
}
|
||||
}
|
||||
|
||||
for _, tb := range []*tableV{&v.IPs, &v.Camps, &v.Escs, &v.Expo, &v.Defense, &v.EnfRecent, &v.XWl, &v.XFind} {
|
||||
tb.None = v.None
|
||||
}
|
||||
v.Expo.None = r.t("v.expo0")
|
||||
v.Recs = r.recommend(in, cover, xHigh)
|
||||
v.TOC = []secV{{"sum", v.TSum}, {"threats", v.TThreats}, {"geo", v.TGeo}, {"health", v.THealth}, {"vis", v.TVis}, {"def", v.TDef}}
|
||||
if v.HasEnf {
|
||||
v.TOC = append(v.TOC, secV{"enf", v.TEnf})
|
||||
}
|
||||
if v.HasEgress {
|
||||
v.TOC = append(v.TOC, secV{"egress", v.TEgress})
|
||||
}
|
||||
v.TOC = append(v.TOC, secV{"method", v.TMethod})
|
||||
return v
|
||||
}
|
||||
|
||||
func dash(s string) string {
|
||||
if s == "" {
|
||||
return "-"
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func firstN(s []string, n int) []string {
|
||||
if len(s) > n {
|
||||
return s[:n]
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// recommend turns the figures into actions with plain rules, most urgent first.
|
||||
func (r *renderer) recommend(in reportInput, cover float64, xHigh int) []recV {
|
||||
o, s := in.Out, in.Out.Summary
|
||||
var rs []recV
|
||||
add := func(l, k string, a ...any) { rs = append(rs, recV{l, r.t("rec." + l), r.t(k, a...)}) }
|
||||
enfOn := in.Enforce != nil && in.Enforce.Mode == enforce.ModeOn
|
||||
if o.Exposures.Total > 0 {
|
||||
add("bad", "r.expo", r.num(float64(o.Exposures.Total)))
|
||||
}
|
||||
if xHigh > 0 {
|
||||
add("bad", "r.egress", r.num(float64(xHigh)))
|
||||
}
|
||||
if len(o.Escalations) > 0 {
|
||||
add("warn", "r.esc", r.num(float64(len(o.Escalations))))
|
||||
}
|
||||
switch {
|
||||
case in.Enforce == nil || in.Enforce.Mode == enforce.ModeOff:
|
||||
if s.Attacks > 0 && (s.HostileIPs > 0 && cover < 90) {
|
||||
add("warn", "r.enforce", r.num(float64(maxInt(s.HostileIPs-s.Bans, 1))))
|
||||
}
|
||||
case in.Enforce.Mode == enforce.ModeObserve:
|
||||
add("warn", "r.observe")
|
||||
case enfOn && in.Enforce.Coverage.Unblocked > 0:
|
||||
add("warn", "r.unblocked", r.num(float64(in.Enforce.Coverage.Unblocked)))
|
||||
}
|
||||
if s.HostileIPs > 0 && cover < 50 {
|
||||
add("warn", "r.cover", r.dec(cover, 0))
|
||||
}
|
||||
if o.Defense.MTTBN > 0 && o.Defense.MTTBMedianS > 600 {
|
||||
add("warn", "r.mttb", r.dur(o.Defense.MTTBMedianS))
|
||||
}
|
||||
if len(o.Campaigns) > 0 {
|
||||
add("info", "r.camp", r.num(float64(len(o.Campaigns))))
|
||||
}
|
||||
if in.HasHealth {
|
||||
if n := in.Classes[store.ClsApp] + in.Classes[store.ClsProxy]; n > 0 {
|
||||
add("warn", "r.app", r.num(float64(n)))
|
||||
}
|
||||
}
|
||||
if dp, ok := s.DeltaPct["attacks"]; s.HasPrev && ok && dp >= 50 && s.Attacks >= 20 {
|
||||
add("info", "r.up", r.num(dp))
|
||||
}
|
||||
if in.Egress == nil || in.Egress.Source.State == "disabled" {
|
||||
add("info", "r.noegress")
|
||||
}
|
||||
if len(rs) == 0 {
|
||||
add("ok", "r.ok")
|
||||
}
|
||||
return rs
|
||||
}
|
||||
|
||||
func maxInt(a, b int) int {
|
||||
if a > b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
var reportTpl = template.Must(template.New("report").Parse(reportTemplate))
|
||||
|
||||
// renderReportHTML renders the document; the error is a template failure.
|
||||
func renderReportHTML(in reportInput, now int64) ([]byte, error) {
|
||||
r := newRenderer(in.Lang)
|
||||
var buf bytes.Buffer
|
||||
if err := reportTpl.Execute(&buf, r.build(in, now)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
var fileSafe = regexp.MustCompile(`[^A-Za-z0-9._-]+`)
|
||||
|
||||
// reportExtras gathers what the JSON report does not carry: service health
|
||||
// classes, traffic study, second firewall and outbound analysis.
|
||||
func (s *Server) reportExtras(r *http.Request, rc *reportCtx) reportInput {
|
||||
in := reportInput{Out: rc.out, Lang: r.URL.Query().Get("lang")}
|
||||
self := s.opt.Store.Name()
|
||||
in.Traffic = s.trafficOf(r, rc.rg, rc.host)
|
||||
in.Peers = rc.host != self && s.opt.Hub != nil
|
||||
if rc.host == "all" || rc.host == self {
|
||||
for _, v := range s.opt.Store.Services(rc.from, rc.to, "", "") {
|
||||
in.HasHealth = true
|
||||
for i := range in.Classes {
|
||||
in.Classes[i] += v.Tot.Cls[i]
|
||||
}
|
||||
}
|
||||
if e := enforceEngine.Load(); e != nil {
|
||||
rep := e.Report(rc.from)
|
||||
in.Enforce = &enforceView{Mode: e.Mode(), Share: e.Share(), Coverage: rep.Coverage, Counts: rep.Counts, Recent: rep.Recent}
|
||||
}
|
||||
if e := egressEngine.Load(); e != nil {
|
||||
in.Egress = &egressView{Source: e.Info(), Report: e.Report(rc.from, rc.to)}
|
||||
}
|
||||
}
|
||||
return in
|
||||
}
|
||||
|
||||
func (s *Server) writeReportHTML(w http.ResponseWriter, r *http.Request, rc *reportCtx) {
|
||||
now := s.opt.Now().Unix()
|
||||
body, err := renderReportHTML(s.reportExtras(r, rc), now)
|
||||
if err != nil {
|
||||
http.Error(w, "report failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
name := fileSafe.ReplaceAllString(rc.host, "-")
|
||||
if rc.host == "all" && len(rc.out.Hosts) == 1 {
|
||||
name = fileSafe.ReplaceAllString(rc.out.Hosts[0], "-")
|
||||
}
|
||||
if name == "" {
|
||||
name = "all"
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
// the document is self-contained: inline CSS and data: images only, no script
|
||||
w.Header().Set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; img-src data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'")
|
||||
disp := "attachment"
|
||||
if r.URL.Query().Get("inline") == "1" {
|
||||
disp = "inline"
|
||||
}
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf(`%s; filename="urutau-relatorio-%s-%s.html"`, disp, name, time.Unix(now, 0).UTC().Format("2006-01-02")))
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
_, _ = w.Write(body)
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
package server
|
||||
|
||||
// reportText holds the strings of the exported HTML report: [pt-BR, en].
|
||||
// Unknown keys fall back to the key itself so a typo is visible, not blank.
|
||||
var reportText = map[string][2]string{
|
||||
"rec.bad": {"Urgente", "Urgent"},
|
||||
"rec.warn": {"Importante", "Important"},
|
||||
"rec.info": {"Sugestão", "Suggestion"},
|
||||
"rec.ok": {"Tudo certo", "All good"},
|
||||
"doc.title": {"Urutau · Relatório de segurança", "Urutau · Security report"},
|
||||
"cover.kicker": {"Ciberfauna · Defesa de servidores web", "Ciberfauna · Web server defence"},
|
||||
"cover.title": {"Relatório de segurança", "Security report"},
|
||||
"cover.sub": {"O que atacou, o que foi barrado e o que merece a sua atenção neste período.", "What attacked, what was stopped and what deserves your attention in this period."},
|
||||
"cover.period": {"Período", "Period"},
|
||||
"cover.servers": {"Servidor(es)", "Server(s)"},
|
||||
"cover.gen": {"Gerado em", "Generated"},
|
||||
"cover.all": {"todos os servidores", "all servers"},
|
||||
"cover.conf": {"Confidencial · uso interno", "Confidential · internal use"},
|
||||
"run.head": {"URUTAU · RELATÓRIO DE SEGURANÇA", "URUTAU · SECURITY REPORT"},
|
||||
"run.foot": {"Ciberfauna · Urutau · uso interno", "Ciberfauna · Urutau · internal use"},
|
||||
"toc": {"Sumário", "Contents"},
|
||||
"s.sum": {"Sumário executivo", "Executive summary"},
|
||||
"s.threats": {"Ameaças", "Threats"},
|
||||
"s.geo": {"Geografia dos ataques", "Where attacks came from"},
|
||||
"s.health": {"Erros e saúde dos serviços", "Errors and service health"},
|
||||
"s.visitors": {"Visitantes", "Visitors"},
|
||||
"s.defense": {"Defesa", "Defence"},
|
||||
"s.enforce": {"Segundo firewall", "Second firewall"},
|
||||
"s.egress": {"Tráfego de saída", "Outbound traffic"},
|
||||
"s.recs": {"Recomendações", "Recommendations"},
|
||||
"s.method": {"Como ler este relatório", "How to read this report"},
|
||||
|
||||
"k.requests": {"Requisições", "Requests"},
|
||||
"k.attacks": {"Ataques", "Attacks"},
|
||||
"k.unique": {"IPs únicos", "Unique IPs"},
|
||||
"k.hostile": {"IPs hostis", "Hostile IPs"},
|
||||
"k.bans": {"IPs banidos", "Banned IPs"},
|
||||
"k.visitors": {"Visitantes", "Visitors"},
|
||||
"k.nonhuman": {"Clientes não humanos", "Non-human clients"},
|
||||
"k.pages": {"Páginas vistas", "Page views"},
|
||||
"k.before": {"antes: %s", "before: %s"},
|
||||
"k.coverage": {"Cobertura de bloqueio", "Block coverage"},
|
||||
"verdict.good": {"Situação sob controle", "Under control"},
|
||||
"verdict.warn": {"Requer atenção", "Needs attention"},
|
||||
"verdict.bad": {"Ação necessária", "Action needed"},
|
||||
|
||||
"v.intro": {"No período, %s registrou %s tentativas de ataque vindas de %s endereços diferentes; %s deles foram classificados como hostis e %s estão banidos.", "In this period, %s recorded %s attack attempts from %s different addresses; %s of them were classified as hostile and %s are banned."},
|
||||
"v.none": {"Não houve tentativas de ataque registradas no período. Isso é normal em servidores pouco expostos, mas confirme que os logs estão chegando.", "No attack attempts were recorded in this period. That is normal for lightly exposed servers, but make sure logs are arriving."},
|
||||
"v.up": {"Os ataques aumentaram %s%% em relação ao período anterior.", "Attacks rose %s%% compared with the previous period."},
|
||||
"v.down": {"Os ataques diminuíram %s%% em relação ao período anterior.", "Attacks fell %s%% compared with the previous period."},
|
||||
"v.flat": {"O volume de ataques está em linha com o período anterior.", "Attack volume is in line with the previous period."},
|
||||
"v.noprev": {"Não há período anterior para comparar.", "There is no previous period to compare with."},
|
||||
"v.top": {"O tipo de ataque mais comum foi %s, e a maior parte veio de %s.", "The most common attack type was %s, and most of it came from %s."},
|
||||
"v.expo0": {"Nenhuma requisição de ataque obteve resposta de sucesso: nada indica que algo tenha sido exposto.", "No attack request got a success answer: nothing suggests anything was exposed."},
|
||||
"v.expo": {"Atenção: %s requisições de ataque receberam resposta de sucesso e precisam ser revisadas, pois podem ter alcançado algo que deveria estar protegido.", "Attention: %s attack requests received a success answer and must be reviewed, as they may have reached something that should be protected."},
|
||||
"v.cover": {"%s%% dos endereços hostis já estão bloqueados.", "%s%% of hostile addresses are already blocked."},
|
||||
"v.esc": {"%s sessão(ões) mostraram escalada, ou seja, o atacante avançou do reconhecimento para a exploração.", "%s session(s) showed escalation: the attacker moved from reconnaissance to exploitation."},
|
||||
"v.egress": {"O tráfego de saída tem %s alerta(s) de severidade alta, o que pode indicar um servidor comprometido falando com o exterior.", "Outbound traffic has %s high-severity alert(s), which may indicate a compromised server talking to the outside."},
|
||||
"v.trunc": {"O estudo foi cortado nos limites internos; os números podem estar parciais.", "The study was cut at its internal limits; figures may be partial."},
|
||||
"v.mttb": {"Em mediana, um atacante levou %s até ser banido.", "On median, an attacker took %s to get banned."},
|
||||
"c.timeline": {"Ataques ao longo do tempo", "Attacks over time"},
|
||||
"c.families": {"Famílias de ataque", "Attack families"},
|
||||
"c.techs": {"Técnicas MITRE ATT&CK", "MITRE ATT&CK techniques"},
|
||||
"c.countries": {"Países de origem", "Origin countries"},
|
||||
"c.asns": {"Redes de origem (ASN)", "Origin networks (ASN)"},
|
||||
"c.classes": {"Como os pedidos com erro se dividem", "How failed requests split"},
|
||||
"c.status": {"Respostas por classe", "Responses by class"},
|
||||
"c.pages": {"Páginas mais acessadas", "Most visited pages"},
|
||||
"c.browsers": {"Navegadores", "Browsers"},
|
||||
"c.devices": {"Dispositivos", "Devices"},
|
||||
"c.refs": {"Origens do acesso", "Referrers"},
|
||||
"c.egress": {"Conexões por carga de trabalho", "Connections per workload"},
|
||||
"c.dst": {"Destinos mais contatados", "Most contacted destinations"},
|
||||
"t.ips": {"Endereços mais perigosos", "Most dangerous addresses"},
|
||||
"t.camp": {"Campanhas coordenadas", "Coordinated campaigns"},
|
||||
"t.esc": {"Sessões com escalada", "Escalating sessions"},
|
||||
"t.expo": {"Requisições de ataque com resposta de sucesso", "Attack requests with a success answer"},
|
||||
"t.enf": {"Decisões recentes do segundo firewall", "Recent second-firewall decisions"},
|
||||
"t.find": {"Alertas de saída", "Outbound alerts"},
|
||||
"t.wl": {"Cargas de trabalho", "Workloads"},
|
||||
"col.ip": {"Endereço", "Address"},
|
||||
"col.score": {"Pontuação", "Score"},
|
||||
"col.level": {"Nível", "Level"},
|
||||
"col.country": {"País", "Country"},
|
||||
"col.net": {"Rede", "Network"},
|
||||
"col.events": {"Eventos", "Events"},
|
||||
"col.banned": {"Banido", "Banned"},
|
||||
"col.camp": {"Campanha", "Campaign"},
|
||||
"col.ips": {"IPs", "IPs"},
|
||||
"col.active": {"Atividade", "Active"},
|
||||
"col.techs": {"Técnicas", "Techniques"},
|
||||
"col.stage": {"Estágio", "Stage"},
|
||||
"col.host": {"Servidor", "Server"},
|
||||
"col.path": {"Caminho", "Path"},
|
||||
"col.status": {"Status", "Status"},
|
||||
"col.fam": {"Família", "Family"},
|
||||
"col.when": {"Quando", "When"},
|
||||
"col.metric": {"Indicador", "Metric"},
|
||||
"col.value": {"Valor", "Value"},
|
||||
"col.meaning": {"O que significa", "What it means"},
|
||||
"col.reason": {"Motivo", "Reason"},
|
||||
"col.action": {"Ação", "Action"},
|
||||
"col.sev": {"Severidade", "Severity"},
|
||||
"col.kind": {"Tipo", "Kind"},
|
||||
"col.wl": {"Carga", "Workload"},
|
||||
"col.dst": {"Destino", "Destination"},
|
||||
"col.conns": {"Conexões", "Connections"},
|
||||
"col.role": {"Papel", "Role"},
|
||||
"col.detail": {"Detalhe", "Detail"},
|
||||
"yes": {"sim", "yes"},
|
||||
"no": {"não", "no"},
|
||||
"none": {"Nada a registrar neste período.", "Nothing to report in this period."},
|
||||
"noenf": {"O segundo firewall não está ativo neste servidor.", "The second firewall is not active on this server."},
|
||||
"noegress": {"A análise de tráfego de saída não está ativa neste servidor.", "Outbound traffic analysis is not active on this server."},
|
||||
"unit.attacks": {"ataques", "attacks"},
|
||||
"cls.attack": {"Ataque frustrado (barrado ou sondagem)", "Thwarted attack (blocked or probe)"},
|
||||
"cls.blocked": {"Bloqueado pela defesa", "Blocked by the defence"},
|
||||
"cls.bot": {"Robô ou ferramenta", "Bot or tool"},
|
||||
"cls.app": {"Erro da aplicação (falha sua)", "Application error (your fault)"},
|
||||
"cls.proxy": {"Falha do proxy ou serviço fora do ar", "Proxy failure or service down"},
|
||||
"cls.client_broken": {"Link quebrado do lado do visitante", "Broken link on the visitor side"},
|
||||
"cls.client_auth": {"Login ou permissão negados", "Login or permission denied"},
|
||||
"cls.client_other": {"Outro erro do cliente", "Other client error"},
|
||||
"h.lead": {"Nem todo erro é problema. Um ataque que foi barrado devolve erro e é sinal de que a defesa funcionou; já um erro de aplicação é uma falha do seu serviço e pede correção.", "Not every error is a problem. A thwarted attack returns an error and shows the defence working; an application error is a failure of your own service and needs a fix."},
|
||||
"h.good": {"%s pedidos com erro foram ataques frustrados ou ruído de robôs, e não indicam defeito.", "%s failed requests were thwarted attacks or bot noise and do not indicate a defect."},
|
||||
"h.app": {"%s pedidos terminaram em erro de aplicação ou de proxy; esses sim indicam falha de serviço.", "%s requests ended in application or proxy errors; those do indicate a service failure."},
|
||||
"h.p95": {"Tempo de resposta: mediana %s ms, 95%% dos pedidos abaixo de %s ms.", "Response time: median %s ms, 95%% of requests under %s ms."},
|
||||
"h.nodata": {"Sem dados de saúde de serviços neste período.", "No service health data in this period."},
|
||||
"st.2xx": {"2xx sucesso", "2xx success"},
|
||||
"st.3xx": {"3xx redirecionamento", "3xx redirect"},
|
||||
"st.4xx": {"4xx erro do cliente", "4xx client error"},
|
||||
"st.5xx": {"5xx erro do servidor", "5xx server error"},
|
||||
"vis.lead": {"Visitantes são navegadores reais, contados uma vez por IP e dia. Robôs e ferramentas ficam à parte.", "Visitors are real browsers, counted once per IP and day. Bots and tools are kept apart."},
|
||||
"d.mttb": {"Tempo mediano até o banimento", "Median time to ban"},
|
||||
"d.mttbp90": {"Tempo até o banimento (percentil 90)", "Time to ban (90th percentile)"},
|
||||
"d.mttbn": {"Banimentos medidos", "Bans measured"},
|
||||
"d.cover": {"Cobertura de banimento", "Ban coverage"},
|
||||
"d.block": {"Cobertura da lista de bloqueio", "Blocklist coverage"},
|
||||
"d.expo": {"Taxa de exposição", "Exposure rate"},
|
||||
"d.refused": {"Exploits recusados", "Exploits refused"},
|
||||
"d.cover.m": {"Parte dos IPs hostis que já estava banida.", "Share of hostile IPs that were already banned."},
|
||||
"d.mttb.m": {"Quanto menor, melhor: é a janela entre o primeiro ataque e o bloqueio.", "Lower is better: the window between the first attack and the block."},
|
||||
"d.block.m": {"Parte dos atacantes que já constava em listas públicas de bloqueio.", "Share of attackers already in public blocklists."},
|
||||
"d.expo.m": {"Parte dos ataques que recebeu resposta de sucesso. Deve ficar perto de zero.", "Share of attacks that got a success answer. Should stay near zero."},
|
||||
"d.refused.m": {"Parte das tentativas de exploração recusada pelo servidor.", "Share of exploit attempts refused by the server."},
|
||||
"e.mode": {"Modo", "Mode"},
|
||||
"e.mode.on": {"ativo (bloqueia)", "active (blocks)"},
|
||||
"e.mode.observe": {"observação (só registra o que bloquearia)", "observe (only logs what it would block)"},
|
||||
"e.mode.off": {"desligado", "off"},
|
||||
"e.lead": {"O segundo firewall é uma camada extra: o Urutau decide quem bloquear e grava a decisão para outro bloqueador aplicar na borda.", "The second firewall is an extra layer: Urutau decides who to block and writes the decision for another blocker to enforce at the edge."},
|
||||
"e.cov": {"%s de %s endereços atacantes estão bloqueados (%s pelo firewall, %s pelo Urutau).", "%s of %s attacking addresses are blocked (%s by the firewall, %s by Urutau)."},
|
||||
"e.would": {"%s endereços seriam bloqueados se o modo ativo estivesse ligado.", "%s addresses would be blocked if active mode were on."},
|
||||
"e.unb": {"%s endereços atacantes continuam sem bloqueio.", "%s attacking addresses are still unblocked."},
|
||||
"e.decided": {"Decisões", "Decisions"},
|
||||
"e.written": {"Gravadas", "Written"},
|
||||
"e.already": {"Já bloqueadas", "Already blocked"},
|
||||
"e.rate": {"Descartadas por limite", "Dropped by rate limit"},
|
||||
"e.werr": {"Erros de gravação", "Write errors"},
|
||||
"x.lead": {"Tráfego de saída é o que os seus servidores iniciam em direção à internet. Um servidor sadio fala com poucos destinos conhecidos; conversas periódicas com destinos estranhos podem indicar invasão.", "Outbound traffic is what your servers start towards the internet. A healthy server talks to a few known destinations; periodic talks to strange destinations may indicate a breach."},
|
||||
"x.nof": {"Nenhum alerta de saída no período.", "No outbound alerts in this period."},
|
||||
"x.sev": {"%s alerta(s) de saída, %s de severidade alta.", "%s outbound alert(s), %s of high severity."},
|
||||
"x.src": {"Fonte dos dados: %s.", "Data source: %s."},
|
||||
"stage.recon": {"reconhecimento", "reconnaissance"},
|
||||
"stage.probe": {"sondagem", "probing"},
|
||||
"stage.exploit": {"exploração", "exploitation"},
|
||||
"stage.access": {"acesso", "access"},
|
||||
"lvl.low": {"baixo", "low"},
|
||||
"lvl.suspicious": {"suspeito", "suspicious"},
|
||||
"lvl.hostile": {"hostil", "hostile"},
|
||||
"sev.high": {"alta", "high"},
|
||||
"sev.medium": {"média", "medium"},
|
||||
"sev.low": {"baixa", "low"},
|
||||
"sev.critical": {"crítica", "critical"},
|
||||
"r.enforce": {"Ative o segundo firewall (URUTAU_ENFORCE=on). %s atacantes passaram sem bloqueio na borda; hoje o Urutau só os enxerga depois do fato.", "Turn on the second firewall (URUTAU_ENFORCE=on). %s attackers passed without an edge block; today Urutau only sees them after the fact."},
|
||||
"r.observe": {"O segundo firewall está só observando. Revise as decisões e passe para o modo ativo (URUTAU_ENFORCE=on) para bloquear de fato.", "The second firewall is only observing. Review its decisions and switch to active mode (URUTAU_ENFORCE=on) to actually block."},
|
||||
"r.unblocked": {"Mesmo com o segundo firewall ativo, %s atacantes seguem sem bloqueio. Confira se o arquivo de decisões está sendo lido pelo bloqueador.", "Even with the second firewall active, %s attackers remain unblocked. Check that the blocker is reading the decisions file."},
|
||||
"r.expo": {"Revise agora as %s requisições de ataque que receberam resposta de sucesso (seção Ameaças) e confirme que nenhum recurso sensível foi alcançado.", "Review now the %s attack requests that received a success answer (Threats section) and confirm no sensitive resource was reached."},
|
||||
"r.cover": {"A cobertura de banimento é de apenas %s%%. Reduza o limiar de banimento do fail2ban ou ative a lista de bloqueio compartilhada.", "Ban coverage is only %s%%. Lower the fail2ban ban threshold or enable the shared blocklist."},
|
||||
"r.mttb": {"O tempo mediano até o banimento (%s) é longo. Bans mais rápidos reduzem a janela de ataque.", "The median time to ban (%s) is long. Faster bans shrink the attack window."},
|
||||
"r.esc": {"Investigue as %s sessão(ões) com escalada: o atacante passou da sondagem para a exploração.", "Investigate the %s escalating session(s): the attacker moved from probing to exploitation."},
|
||||
"r.camp": {"Há %s campanha(s) coordenada(s). Considere bloquear as redes de origem inteiras em vez de IP a IP.", "There are %s coordinated campaign(s). Consider blocking whole source networks rather than IP by IP."},
|
||||
"r.app": {"Corrija os erros de aplicação: %s pedidos falharam por defeito do seu serviço (veja a página Erros no painel).", "Fix the application errors: %s requests failed because of a defect in your service (see the Errors page in the dashboard)."},
|
||||
"r.egress": {"Investigue os %s alerta(s) de saída de severidade alta; confirme se a carga de trabalho deveria falar com esses destinos.", "Investigate the %s high-severity outbound alert(s); confirm whether the workload should talk to those destinations."},
|
||||
"r.noegress": {"Ative a análise de tráfego de saída para detectar servidor comprometido falando com o exterior.", "Enable outbound traffic analysis to detect a compromised server talking to the outside."},
|
||||
"r.up": {"Os ataques cresceram %s%%. Acompanhe a evolução nos próximos dias.", "Attacks grew %s%%. Keep watching in the coming days."},
|
||||
"r.ok": {"Nenhuma ação urgente. Mantenha os logs chegando e revise este relatório periodicamente.", "No urgent action. Keep logs flowing and review this report periodically."},
|
||||
"m.p1": {"Os números vêm dos logs do proxy e do SSH lidos pelo Urutau. Endereços, caminhos e nomes aparecem como foram registrados e podem ser falsos: são dados de atacantes.", "Figures come from the proxy and SSH logs read by Urutau. Addresses, paths and names appear as recorded and may be forged: they are attacker-supplied data."},
|
||||
"m.p2": {"Ataque é toda requisição classificada como varredura, exploração, força bruta ou sondagem SSH. IP hostil é o que acumulou pontuação suficiente para ser tratado como ameaça.", "An attack is any request classified as scanning, exploitation, brute force or SSH probing. A hostile IP is one that accumulated enough score to be treated as a threat."},
|
||||
"m.p3": {"A comparação usa o período imediatamente anterior, de mesma duração. Datas e horas em UTC.", "Comparisons use the immediately preceding period of the same length. Dates and times are UTC."},
|
||||
"trunc": {"O estudo foi cortado nos limites internos; os números podem estar parciais.", "The study was cut at its internal limits; figures may be partial."},
|
||||
"other": {"outros", "other"},
|
||||
"peers.note": {"Saúde e tráfego de saída refletem apenas o servidor que gerou o relatório.", "Health and outbound traffic reflect only the server that generated the report."},
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"html"
|
||||
"math"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Palette of the printed report (light theme, Ciberfauna identity).
|
||||
var reportPalette = []string{"#f97316", "#087f68", "#f0b35b", "#45d6b0", "#c2410c", "#4b6b61", "#9aa9a2"}
|
||||
|
||||
type chartItem struct {
|
||||
Label string
|
||||
N float64
|
||||
}
|
||||
|
||||
func clip(s string, n int) string {
|
||||
r := []rune(s)
|
||||
if len(r) <= n {
|
||||
return s
|
||||
}
|
||||
return string(r[:n-1]) + "…"
|
||||
}
|
||||
|
||||
// niceMax rounds a maximum up to 1, 2, 5 x 10^k so the axis reads well.
|
||||
func niceMax(v float64) float64 {
|
||||
if v <= 0 {
|
||||
return 1
|
||||
}
|
||||
p := math.Pow(10, math.Floor(math.Log10(v)))
|
||||
for _, m := range []float64{1, 2, 5, 10} {
|
||||
if v <= m*p {
|
||||
return m * p
|
||||
}
|
||||
}
|
||||
return 10 * p
|
||||
}
|
||||
|
||||
// svgArea draws a filled time series. All text is escaped; numbers are formatted here.
|
||||
func svgArea(vals []uint32, start, step int64, fi func(float64) string, title string) string {
|
||||
const w, h, ml, mr, mt, mb = 680.0, 150.0, 40.0, 8.0, 8.0, 20.0
|
||||
var sb strings.Builder
|
||||
fmt.Fprintf(&sb, `<svg class="chart" viewBox="0 0 %g %g" role="img" aria-label="%s" preserveAspectRatio="xMidYMid meet">`, w, h, html.EscapeString(title))
|
||||
var mx float64
|
||||
for _, v := range vals {
|
||||
if float64(v) > mx {
|
||||
mx = float64(v)
|
||||
}
|
||||
}
|
||||
top := niceMax(mx)
|
||||
pw, ph := w-ml-mr, h-mt-mb
|
||||
for i := 0; i <= 4; i++ {
|
||||
y := mt + ph - ph*float64(i)/4
|
||||
fmt.Fprintf(&sb, `<line x1="%g" y1="%.1f" x2="%g" y2="%.1f" stroke="#d7e2dd" stroke-width="0.6"/>`, ml, y, w-mr, y)
|
||||
fmt.Fprintf(&sb, `<text x="%g" y="%.1f" font-size="9" text-anchor="end" fill="#55665f">%s</text>`, ml-4, y+3, fi(top*float64(i)/4))
|
||||
}
|
||||
n := len(vals)
|
||||
if n > 1 {
|
||||
xs := func(i int) float64 { return ml + pw*float64(i)/float64(n-1) }
|
||||
ys := func(v uint32) float64 { return mt + ph - ph*float64(v)/top }
|
||||
var line strings.Builder
|
||||
for i, v := range vals {
|
||||
if i == 0 {
|
||||
fmt.Fprintf(&line, "M%.1f %.1f", xs(i), ys(v))
|
||||
} else {
|
||||
fmt.Fprintf(&line, "L%.1f %.1f", xs(i), ys(v))
|
||||
}
|
||||
}
|
||||
fmt.Fprintf(&sb, `<path d="%sL%.1f %.1f L%.1f %.1f Z" fill="#f97316" fill-opacity="0.18"/>`, line.String(), xs(n-1), mt+ph, xs(0), mt+ph)
|
||||
fmt.Fprintf(&sb, `<path d="%s" fill="none" stroke="#f97316" stroke-width="1.4" stroke-linejoin="round"/>`, line.String())
|
||||
if step > 0 {
|
||||
for i := 0; i < 5; i++ {
|
||||
idx := (n - 1) * i / 4
|
||||
ts := start + int64(idx)*step
|
||||
lbl := time.Unix(ts, 0).UTC().Format("02/01")
|
||||
if step < 86400 && int64(n)*step <= 3*86400 {
|
||||
lbl = time.Unix(ts, 0).UTC().Format("02/01 15h")
|
||||
}
|
||||
anchor := "middle"
|
||||
if i == 0 {
|
||||
anchor = "start"
|
||||
} else if i == 4 {
|
||||
anchor = "end"
|
||||
}
|
||||
fmt.Fprintf(&sb, `<text x="%.1f" y="%g" font-size="9" text-anchor="%s" fill="#55665f">%s</text>`, xs(idx), h-6, anchor, lbl)
|
||||
}
|
||||
}
|
||||
} else if n == 1 {
|
||||
fmt.Fprintf(&sb, `<circle cx="%g" cy="%.1f" r="2" fill="#f97316"/>`, ml+pw/2, mt+ph-ph*float64(vals[0])/top)
|
||||
}
|
||||
sb.WriteString(`</svg>`)
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
// svgBars draws horizontal bars with the label on the left and the value on the right.
|
||||
func svgBars(items []chartItem, color string, fi func(float64) string, title string) string {
|
||||
const w, lw, rw, rh = 300.0, 112.0, 40.0, 19.0
|
||||
if len(items) == 0 {
|
||||
return ""
|
||||
}
|
||||
var mx float64
|
||||
for _, it := range items {
|
||||
if it.N > mx {
|
||||
mx = it.N
|
||||
}
|
||||
}
|
||||
if mx <= 0 {
|
||||
mx = 1
|
||||
}
|
||||
h := rh*float64(len(items)) + 2
|
||||
var sb strings.Builder
|
||||
fmt.Fprintf(&sb, `<svg class="chart" viewBox="0 0 %g %g" role="img" aria-label="%s">`, w, h, html.EscapeString(title))
|
||||
bw := w - lw - rw
|
||||
for i, it := range items {
|
||||
y := rh * float64(i)
|
||||
l := it.N / mx * bw
|
||||
if it.N > 0 && l < 1.5 {
|
||||
l = 1.5
|
||||
}
|
||||
fmt.Fprintf(&sb, `<text x="%g" y="%.1f" font-size="10" text-anchor="end" fill="#22352f">%s</text>`, lw-6, y+13, html.EscapeString(clip(it.Label, 20)))
|
||||
fmt.Fprintf(&sb, `<rect x="%g" y="%.1f" width="%.1f" height="11" rx="2" fill="%s"/>`, lw, y+3.5, l, color)
|
||||
fmt.Fprintf(&sb, `<text x="%.1f" y="%.1f" font-size="10" fill="#55665f">%s</text>`, lw+l+4, y+13, fi(it.N))
|
||||
}
|
||||
sb.WriteString(`</svg>`)
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
// svgDonut draws a ring; the legend is HTML next to it (see donutLegend).
|
||||
func svgDonut(items []chartItem, title string) string {
|
||||
var total float64
|
||||
for _, it := range items {
|
||||
total += it.N
|
||||
}
|
||||
var sb strings.Builder
|
||||
fmt.Fprintf(&sb, `<svg class="donut" viewBox="0 0 120 120" role="img" aria-label="%s">`, html.EscapeString(title))
|
||||
const r = 44.0
|
||||
circ := 2 * math.Pi * r
|
||||
sb.WriteString(`<circle cx="60" cy="60" r="44" fill="none" stroke="#eaf2ef" stroke-width="20"/>`)
|
||||
if total > 0 {
|
||||
off := 0.0
|
||||
for i, it := range items {
|
||||
if it.N <= 0 {
|
||||
continue
|
||||
}
|
||||
l := it.N / total * circ
|
||||
fmt.Fprintf(&sb, `<circle cx="60" cy="60" r="44" fill="none" stroke="%s" stroke-width="20" stroke-dasharray="%.2f %.2f" stroke-dashoffset="%.2f" transform="rotate(-90 60 60)"/>`,
|
||||
reportPalette[i%len(reportPalette)], l, circ-l, -off)
|
||||
off += l
|
||||
}
|
||||
}
|
||||
sb.WriteString(`</svg>`)
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
// svgMotif is the faint decoration of the cover, built from the attack series.
|
||||
func svgMotif(vals []uint32) string {
|
||||
var sb strings.Builder
|
||||
sb.WriteString(`<svg class="motif" viewBox="0 0 210 120" preserveAspectRatio="none" aria-hidden="true">`)
|
||||
for i := 1; i <= 7; i++ {
|
||||
fmt.Fprintf(&sb, `<line x1="0" y1="%d" x2="210" y2="%d" stroke="#45d6b0" stroke-opacity="0.12" stroke-width="0.25"/>`, i*15, i*15)
|
||||
}
|
||||
n := len(vals)
|
||||
if n > 1 {
|
||||
var mx uint32 = 1
|
||||
for _, v := range vals {
|
||||
if v > mx {
|
||||
mx = v
|
||||
}
|
||||
}
|
||||
step := 1
|
||||
if n > 120 {
|
||||
step = n / 120
|
||||
}
|
||||
for i := 0; i < n; i += step {
|
||||
x := 210 * float64(i) / float64(n-1)
|
||||
hgt := 4 + 38*float64(vals[i])/float64(mx)
|
||||
fmt.Fprintf(&sb, `<line x1="%.1f" y1="%.1f" x2="%.1f" y2="%.1f" stroke="#f0b35b" stroke-opacity="0.55" stroke-width="0.7" stroke-linecap="round"/>`, x, 60-hgt/2, x, 60+hgt/2)
|
||||
}
|
||||
}
|
||||
sb.WriteString(`</svg>`)
|
||||
return sb.String()
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
func richReportInput(lang string) reportInput {
|
||||
var in reportInput
|
||||
in.Lang = lang
|
||||
o := &in.Out
|
||||
o.Range = store.RangeInfo{Name: "7d", From: 1763000000, To: 1763604800, Step: 3600}
|
||||
o.Hosts = []string{"web-01.example.com", "web-02.example.com"}
|
||||
o.Summary.reportFigures = reportFigures{Requests: 1843210, Attacks: 48211, UniqueIPs: 912, HostileIPs: 143, Bans: 97, Visitors: 5120, NonHuman: 733, PageViews: 18430}
|
||||
o.Summary.Prev = reportFigures{Requests: 1500000, Attacks: 30100, UniqueIPs: 700, HostileIPs: 110, Bans: 90, Visitors: 4800, PageViews: 17000}
|
||||
o.Summary.HasPrev = true
|
||||
o.Summary.DeltaPct = map[string]float64{"requests": 22.9, "attacks": 60.2, "hostile_ips": 30, "bans": 7.7, "visitors": 6.7}
|
||||
o.Timeline.Start, o.Timeline.Step = o.Range.From, 3600
|
||||
for i := 0; i < 168; i++ {
|
||||
o.Timeline.Values = append(o.Timeline.Values, uint32(200+(i*37)%400+(i%24)*10))
|
||||
}
|
||||
o.Families = []store.Count{{Key: "scanner", N: 21000}, {Key: "exploit", N: 14000}, {Key: "bruteforce", N: 8000}, {Key: "ssh-fail", N: 4000}, {Key: "ssh-probe", N: 1211}}
|
||||
o.Techniques = []store.Count{{Key: "T1190", N: 9000, Label: "Exploit Public-Facing Application"}, {Key: "T1110", N: 4000, Label: "Brute Force"}, {Key: "T1595", N: 3000, Label: "Active Scanning"}}
|
||||
o.Countries = []store.Count{{Key: "NL", N: 9000}, {Key: "US", N: 8000}, {Key: "DE", N: 5000}, {Key: "RU", N: 3000}, {Key: "BR", N: 900}}
|
||||
o.ASNs = []store.Count{{Key: "AS64496", N: 9000, Label: "Example Hosting <b>Ltd</b>"}, {Key: "AS64497", N: 5000, Label: "Documentation Net"}}
|
||||
for i := 0; i < 10; i++ {
|
||||
o.TopIPs = append(o.TopIPs, reportTopIP{IP: "198.51.100." + string(rune('1'+i)), Score: 92.5 - float64(i), Level: "hostile", CC: "NL", Country: "Netherlands", ASOrg: "Example Hosting", Events: uint32(4000 - i*300), Banned: i%2 == 0})
|
||||
}
|
||||
o.Campaigns = []intel.Campaign{{ID: "camp-1", IPsN: 12, First: time.Unix(1763100000, 0), Last: time.Unix(1763500000, 0), Techs: []string{"T1190", "T1595"}}}
|
||||
o.Escalations = []store.EscalationOut{{IP: "203.0.113.7", Host: "web-01.example.com", Stage: "exploit"}}
|
||||
o.Exposures.Total = 3
|
||||
for i := 0; i < 3; i++ {
|
||||
o.Exposures.Items = append(o.Exposures.Items, reportExposure{T: 1763200000 + int64(i)*600, IP: "203.0.113.7", Domain: "app.example.com", Path: "/<script>alert(1)</script>?x=" + strings.Repeat("a", 120), Status: 200, Fam: "exploit"})
|
||||
}
|
||||
o.Defense.MTTBN, o.Defense.MTTBMedianS, o.Defense.MTTBP90S, o.Defense.BanCoverage = 40, 95, 700, 67.8
|
||||
o.Defense.BlocklistCover, o.Defense.ExposureRate, o.Defense.ExploitsRefused = 31, 0.4, 99
|
||||
in.Traffic = store.TrafficData{Visitors: 5120, Pages: 18430, NonHuman: 733, P50: 42, P95: 380, Status: [4]uint64{1500000, 200000, 140000, 3210},
|
||||
TopPages: []store.Count{{Key: "/", N: 9000}, {Key: "/docs", N: 3000}}, Browsers: []store.Count{{Key: "Firefox", N: 3000}, {Key: "Chrome", N: 2000}},
|
||||
Devices: []store.Count{{Key: "Desktop", N: 4000}, {Key: "Mobile", N: 1100}}, Referrers: []store.Count{{Key: "example.org", N: 400}}}
|
||||
in.HasHealth = true
|
||||
in.Classes = [store.NumCls]uint32{store.ClsApp: 120, store.ClsProxy: 12, store.ClsBlocked: 30000, store.ClsAttack: 9000, store.ClsBot: 4000, store.ClsClientBroken: 900, store.ClsClientAuth: 300, store.ClsClientOther: 50}
|
||||
in.Enforce = &enforceView{Mode: enforce.ModeOn, Coverage: enforce.Coverage{AttackIPs: 143, BlockedByFirewall: 80, BlockedByUrutau: 20, Unblocked: 43},
|
||||
Counts: enforce.Counts{Decided: 400, Written: 380, AlreadyBlocked: 20},
|
||||
Recent: []enforce.Recent{{T: 1763300000, IP: "198.51.100.4", Reason: "exploit x12", Action: "ban", CC: "NL"}}}
|
||||
in.Egress = &egressView{Source: egress.SourceInfo{State: "ok"}, Report: egress.Report{
|
||||
Workloads: []egress.WorkloadOut{{Name: "app-1", Role: "web", Conns: 12000, Dsts: 14}, {Name: "db-1", Role: "db", Conns: 800, Dsts: 2}},
|
||||
TopDst: []egress.DstOut{{IP: "192.0.2.10", CC: "US", Conns: 5000}},
|
||||
Findings: []egress.Finding{{Severity: "high", Kind: "beacon", Workload: "app-1", Dst: "192.0.2.99", DPort: 4444, Proto: "tcp", Detail: "<img src=x onerror=1> periodic"}}}}
|
||||
return in
|
||||
}
|
||||
|
||||
func TestReportHTMLRenders(t *testing.T) {
|
||||
for _, lang := range []string{"pt-BR", "en"} {
|
||||
b, err := renderReportHTML(richReportInput(lang), 1763604800)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := string(b)
|
||||
if strings.Contains(s, "<script") || strings.Contains(s, "<img src=x") || strings.Contains(s, "<b>Ltd") {
|
||||
t.Fatalf("%s: unescaped attacker data", lang)
|
||||
}
|
||||
if !strings.Contains(s, "<script>") || !strings.Contains(s, "data:image/png;base64,") {
|
||||
t.Fatalf("%s: missing escaped payload or logo", lang)
|
||||
}
|
||||
if len(b) > 400<<10 {
|
||||
t.Fatalf("%s: %d bytes", lang, len(b))
|
||||
}
|
||||
want := "Segundo firewall"
|
||||
if lang == "en" {
|
||||
want = "Second firewall"
|
||||
}
|
||||
if !strings.Contains(s, want) {
|
||||
t.Fatalf("%s: no %q", lang, want)
|
||||
}
|
||||
if dir := os.Getenv("URUTAU_REPORT_OUT"); dir != "" {
|
||||
_ = os.WriteFile(dir+"/rich-"+lang+".html", b, 0o600)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReportHTMLEmpty(t *testing.T) {
|
||||
for _, lang := range []string{"", "en", "xx"} {
|
||||
b, err := renderReportHTML(reportInput{Lang: lang}, 1763604800)
|
||||
if err != nil || len(b) == 0 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if dir := os.Getenv("URUTAU_REPORT_OUT"); dir != "" && lang == "" {
|
||||
_ = os.WriteFile(dir+"/empty.html", b, 0o600)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReportHTMLRoute(t *testing.T) {
|
||||
h, _ := setup(t)
|
||||
w := do(h, "GET", "/api/v1/report?range=7d&format=html&lang=en", copyHdr(opsAuth), nil)
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("%d %s", w.Code, w.Body)
|
||||
}
|
||||
if ct := w.Header().Get("Content-Type"); !strings.HasPrefix(ct, "text/html") {
|
||||
t.Fatal(ct)
|
||||
}
|
||||
cd := w.Header().Get("Content-Disposition")
|
||||
if !strings.HasPrefix(cd, `attachment; filename="urutau-relatorio-oracle-`) || !strings.HasSuffix(cd, `.html"`) {
|
||||
t.Fatal(cd)
|
||||
}
|
||||
body := w.Body.String()
|
||||
if strings.Contains(body, "<img src=x") {
|
||||
t.Fatal("path not escaped")
|
||||
}
|
||||
if dir := os.Getenv("URUTAU_REPORT_OUT"); dir != "" {
|
||||
_ = os.WriteFile(dir+"/route.html", w.Body.Bytes(), 0o600)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/report?format=html&lang=pt-BR", nil, nil); w.Code != 401 && w.Code != 403 {
|
||||
t.Fatalf("closed without token: %d", w.Code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
package server
|
||||
|
||||
// reportTemplate is the document skeleton (html/template; see report_html.go).
|
||||
// The style block is static text: nothing dynamic reaches CSS.
|
||||
const reportTemplate = `<!doctype html>
|
||||
<html lang="{{.Lang}}">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="robots" content="noindex">
|
||||
<title>{{.Title}}</title>
|
||||
<style>
|
||||
:root{--ink:#0d1f1a;--muted:#55665f;--line:#d7e2dd;--paper:#fff;--tint:#f2f8f5;--accent:#087f68;--accent2:#45d6b0;--gold:#f0b35b;--orange:#f97316;--orange2:#fb923c;--crit:#b42318;--high:#c2410c;--med:#a16207;--ok:#087f68;
|
||||
--sans:system-ui,"Inter","Segoe UI",Roboto,sans-serif;--mono:ui-monospace,"JetBrains Mono","IBM Plex Mono",monospace}
|
||||
*{box-sizing:border-box}
|
||||
html,body{margin:0;background:#e9eeec;color:var(--ink);font-family:var(--sans);font-size:10pt;line-height:1.5;-webkit-print-color-adjust:exact;print-color-adjust:exact}
|
||||
body{padding:0}
|
||||
.doc{max-width:210mm;margin:0 auto;background:var(--paper)}
|
||||
.body{padding:0 16mm}
|
||||
@page{size:A4;margin:22mm 16mm 20mm 16mm;
|
||||
@top-left{content:"{{.RunHead}}";font-family:var(--mono);font-size:7pt;letter-spacing:.14em;color:#55665f;margin-top:8mm}
|
||||
@top-right{content:"{{.LConf}}";font-family:var(--mono);font-size:7pt;font-weight:700;letter-spacing:.06em;color:#a15c00;margin-top:8mm}
|
||||
@bottom-left{content:"{{.RunFoot}}";font-family:var(--mono);font-size:7pt;color:#55665f}
|
||||
@bottom-right{content:counter(page) " / " counter(pages);font-family:var(--mono);font-size:7pt;color:#55665f}}
|
||||
@page cover{margin:0;@top-left{content:none}@top-right{content:none}@bottom-left{content:none}@bottom-right{content:none}}
|
||||
.cover{page:cover;break-after:page;position:relative;width:100%;height:297mm;overflow:hidden;color:#e8f5f0;background:radial-gradient(120% 80% at 80% 55%,#0d3a2f 0%,#06201a 45%,#030d0a 100%)}
|
||||
.cover .glow{position:absolute;left:70mm;top:92mm;width:160mm;height:160mm;border-radius:50%;background:radial-gradient(circle,rgba(249,115,22,.42) 0%,rgba(251,146,60,.16) 38%,rgba(249,115,22,0) 68%)}
|
||||
.cover .motif{position:absolute;left:72mm;top:112mm;width:calc(100% - 72mm);height:120mm;opacity:.9}
|
||||
.cover .logo{position:absolute;left:88mm;top:100mm;width:112mm;height:112mm;object-fit:contain;filter:drop-shadow(0 6mm 10mm rgba(0,0,0,.55))}
|
||||
.cover .topbar{position:absolute;left:18mm;right:18mm;top:14mm;display:flex;justify-content:space-between;align-items:center}
|
||||
.wordmark{font-weight:800;letter-spacing:.42em;font-size:11pt;color:#fff}
|
||||
.auth{font-family:var(--mono);font-size:7.5pt;letter-spacing:.12em;color:#9fc7ba;text-transform:uppercase}
|
||||
.cover .head{position:absolute;left:18mm;right:18mm;top:34mm}
|
||||
.eyebrow{font-family:var(--mono);font-size:8pt;letter-spacing:.2em;color:var(--orange2);text-transform:uppercase}
|
||||
.cover h1{font-size:44px;line-height:1.04;font-weight:800;letter-spacing:-.03em;margin:4mm 0;color:#fff;max-width:165mm}
|
||||
.cover .sub{font-size:11.5pt;color:#b9d8cd;max-width:140mm;margin:0}
|
||||
.cover .numbers{position:absolute;left:18mm;top:128mm;width:66mm;display:flex;flex-direction:column;gap:6mm}
|
||||
.cover .numbers div{border-left:2px solid var(--accent2);padding-left:4mm}
|
||||
.cover .numbers b{display:block;font-size:26pt;font-weight:800;line-height:1;color:#fff;letter-spacing:-.02em}
|
||||
.cover .numbers span{font-family:var(--mono);font-size:7pt;letter-spacing:.14em;text-transform:uppercase;color:#9fc7ba}
|
||||
.cover .meta{position:absolute;left:18mm;right:18mm;bottom:14mm;border-top:1px solid rgba(232,245,240,.25);padding-top:4mm;display:grid;grid-template-columns:1fr 1.7fr 1fr;gap:5mm}
|
||||
.cover .meta span{display:block;font-family:var(--mono);font-size:6.5pt;letter-spacing:.16em;text-transform:uppercase;color:#86b3a5}
|
||||
.cover .meta b{display:block;font-size:9pt;font-weight:600;color:#fff;overflow-wrap:anywhere}
|
||||
section{margin:0 0 7mm}
|
||||
section.pg{break-before:page}
|
||||
section.keep{break-inside:avoid}
|
||||
h2{font-size:17pt;font-weight:800;letter-spacing:-.02em;margin:0 0 3mm;padding-top:4mm;break-after:avoid;background:linear-gradient(var(--accent),var(--accent)) 0 0/14mm 3px no-repeat}
|
||||
h3{font-size:10.5pt;margin:5mm 0 2mm;break-after:avoid}
|
||||
p{margin:0 0 2.5mm;orphans:3;widows:3}
|
||||
.lead{font-size:10.5pt;color:#22352f}
|
||||
.muted{color:var(--muted)}
|
||||
@media print{html,body{background:#fff}.doc{max-width:none;margin:0}.body{padding:0}}
|
||||
.toc ol{list-style:none;padding:0;margin:3mm 0 6mm;counter-reset:t;columns:2;column-gap:8mm}
|
||||
.toc li{border-bottom:1px solid var(--line);padding:1.3mm 0;counter-increment:t;break-inside:avoid}
|
||||
.toc a{color:var(--ink);text-decoration:none;font-size:10.5pt}
|
||||
.toc a::before{content:counter(t,decimal-leading-zero);font-family:var(--mono);color:var(--accent);display:inline-block;width:10mm}
|
||||
.verdict{border:1px solid var(--line);border-left:5px solid var(--ok);background:var(--tint);padding:4mm 5mm;margin:3mm 0 4mm;break-inside:avoid}
|
||||
.verdict.warn{border-left-color:var(--orange);background:#fff7ed}
|
||||
.verdict.bad{border-left-color:var(--crit);background:#fef3f2}
|
||||
.verdict strong{display:block;font-family:var(--mono);font-size:8pt;letter-spacing:.14em;text-transform:uppercase;color:var(--ok);margin-bottom:1.5mm}
|
||||
.verdict.warn strong{color:var(--high)}.verdict.bad strong{color:var(--crit)}
|
||||
.verdict p{margin:0 0 1.5mm;font-size:10.5pt}
|
||||
.kpis{break-inside:avoid;display:grid;grid-template-columns:repeat(3,1fr);gap:3.5mm;margin:3mm 0 4mm}
|
||||
.kpi{border-top:3px solid var(--accent);background:var(--tint);padding:2.5mm 3.5mm;break-inside:avoid}
|
||||
.kpi.warn{border-top-color:var(--orange)}
|
||||
.kpi b{display:block;font-size:19pt;font-weight:800;letter-spacing:-.02em;line-height:1.1}
|
||||
.kpi span{display:block;font-family:var(--mono);font-size:6.8pt;letter-spacing:.1em;text-transform:uppercase;color:var(--muted)}
|
||||
.kpi i{display:block;font-style:normal;font-size:7.5pt;color:var(--muted);margin-top:.5mm}
|
||||
.kpis.k4{grid-template-columns:repeat(4,1fr)}
|
||||
.recs{list-style:none;padding:0;margin:2mm 0}
|
||||
.recs li{border-left:3px solid var(--accent);background:var(--tint);padding:2.5mm 4mm;margin:0 0 2.5mm;break-inside:avoid}
|
||||
.recs li.bad{border-left-color:var(--crit);background:#fef3f2}.recs li.warn{border-left-color:var(--orange);background:#fff7ed}
|
||||
.recs li b{font-family:var(--mono);font-size:7pt;letter-spacing:.14em;text-transform:uppercase;display:block;color:var(--accent)}
|
||||
.recs li.bad b{color:var(--crit)}.recs li.warn b{color:var(--high)}
|
||||
.grid2.wl{grid-template-columns:1.9fr 1fr}
|
||||
.grid2{display:grid;grid-template-columns:1fr 1fr;gap:5mm}
|
||||
.box{break-inside:avoid;margin:0 0 4mm;border:1px solid var(--line);border-radius:2mm;padding:2.5mm 3.5mm}
|
||||
.box h3{margin:0 0 2mm;font-size:9.5pt}
|
||||
.chart{width:100%;height:auto;display:block}
|
||||
.donutwrap{display:flex;gap:4mm;align-items:center}
|
||||
.grid2 .box+.box .donutwrap{flex-direction:column;align-items:flex-start}
|
||||
.donut{width:25mm;height:25mm;flex:none}
|
||||
.legend{list-style:none;margin:0;padding:0;font-size:8pt;flex:1;min-width:0}
|
||||
.legend li{display:flex;flex-wrap:wrap;gap:0 2mm;align-items:baseline;margin:0 0 1.2mm}
|
||||
.legend .sw{width:2.6mm;height:2.6mm;border-radius:50%;flex:none;position:relative;top:.2mm}
|
||||
.legend .lb{flex:1 1 28mm;min-width:0;overflow-wrap:break-word}.legend .vl{font-family:var(--mono);color:var(--muted);white-space:nowrap}
|
||||
.c0{background:#f97316}.c1{background:#087f68}.c2{background:#f0b35b}.c3{background:#45d6b0}.c4{background:#c2410c}.c5{background:#4b6b61}.c6{background:#9aa9a2}
|
||||
table{width:100%;border-collapse:collapse;margin:1mm 0 3mm;font-size:8.3pt}
|
||||
thead{display:table-header-group}
|
||||
th{text-align:left;font-family:var(--mono);font-size:6.8pt;letter-spacing:.08em;text-transform:uppercase;color:var(--muted);border-bottom:1.5px solid var(--ink);padding:1.5mm 2mm}
|
||||
td{padding:1.5mm 2mm;border-bottom:1px solid var(--line);vertical-align:top;overflow-wrap:anywhere}
|
||||
tbody tr:nth-child(even) td{background:var(--tint)}
|
||||
tr{break-inside:avoid}
|
||||
td.n,th.n{text-align:right;font-variant-numeric:tabular-nums}td.n,td.w{white-space:nowrap}
|
||||
.tbl{break-inside:avoid-page}
|
||||
.tbl h3{margin-top:4mm}
|
||||
.empty{color:var(--muted);font-style:italic;margin:1mm 0 3mm}
|
||||
.note{border-left:3px solid var(--accent);padding:1.5mm 3.5mm;margin:0 0 2mm;background:var(--tint);break-inside:avoid}
|
||||
.warn-t{color:var(--high);font-weight:600}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="doc">
|
||||
<div class="cover">
|
||||
<div class="glow"></div>
|
||||
{{.Motif}}
|
||||
<img class="logo" src="{{.Logo}}" alt="Urutau">
|
||||
<div class="topbar"><span class="wordmark">URUTAU</span><span class="auth">{{.LConf}}</span></div>
|
||||
<div class="head"><div class="eyebrow">{{.Kicker}}</div><h1>{{.CoverTitle}}</h1><p class="sub">{{.CoverSub}}</p></div>
|
||||
<div class="numbers">{{range .CoverNums}}<div><b>{{.Value}}</b><span>{{.Label}}</span></div>{{end}}</div>
|
||||
<div class="meta"><div><span>{{.LPeriod}}</span><b>{{.Period}}</b></div><div><span>{{.LServers}}</span><b>{{.Servers}}</b></div><div><span>{{.LGen}}</span><b>{{.Generated}}</b></div></div>
|
||||
</div>
|
||||
<div class="body">
|
||||
|
||||
<section class="toc"><h2>{{.LToc}}</h2><ol>{{range .TOC}}<li><a href="#{{.ID}}">{{.Title}}</a></li>{{end}}</ol>
|
||||
|
||||
<h2 id="sum">{{.TSum}}</h2>
|
||||
<div class="verdict {{.VerdictCls}}"><strong>{{.VerdictTitle}}</strong>{{range .Verdict}}<p>{{.}}</p>{{end}}</div>
|
||||
{{if .Trunc}}<p class="warn-t">{{.Trunc}}</p>{{end}}
|
||||
<div class="kpis">{{range .KPIs}}<div class="kpi {{.Cls}}"><span>{{.Label}}</span><b>{{.Value}}</b>{{if .Delta}}<i>{{.Delta}}</i>{{end}}</div>{{end}}</div>
|
||||
</section>
|
||||
|
||||
<section class="pg" id="recs"><h2>{{.TRecs}}</h2>
|
||||
<ul class="recs">{{range .Recs}}<li class="{{.Level}}"><b>{{.Label}}</b>{{.Text}}</li>{{end}}</ul>
|
||||
</section>
|
||||
|
||||
<section id="threats"><h2>{{.TThreats}}</h2>
|
||||
<div class="box"><h3>{{.Timeline.Title}}</h3>{{if .Timeline.Empty}}<p class="empty">{{.None}}</p>{{else}}{{.Timeline.SVG}}{{end}}</div>
|
||||
<div class="grid2">
|
||||
{{template "donut" .Fams}}
|
||||
{{template "bars" .Techs}}
|
||||
</div>
|
||||
<div class="tbl"><h3>{{.TIPs}}</h3>{{template "table" .IPs}}</div>
|
||||
<div class="tbl"><h3>{{.TCamps}}</h3>{{template "table" .Camps}}</div>
|
||||
<div class="tbl"><h3>{{.TEscs}}</h3>{{template "table" .Escs}}</div>
|
||||
<div class="tbl"><h3>{{.TExpo}}</h3>{{template "table" .Expo}}</div>
|
||||
</section>
|
||||
|
||||
<section class="keep" id="geo"><h2>{{.TGeo}}</h2>
|
||||
<div class="grid2">{{template "bars" .Countries}}{{template "bars" .ASNs}}</div>
|
||||
</section>
|
||||
|
||||
<section id="health"><h2>{{.THealth}}</h2>
|
||||
<p class="lead">{{.HealthLead}}</p>
|
||||
{{range .HealthNotes}}<div class="note">{{.}}</div>{{end}}
|
||||
<div class="grid2 wl" style="margin-top:3mm">{{template "donut" .Classes}}{{template "donut" .Status}}</div>
|
||||
{{if .ShowPeers}}<p class="muted">{{.PeersNote}}</p>{{end}}
|
||||
</section>
|
||||
|
||||
<section class="keep" id="vis"><h2>{{.TVis}}</h2>
|
||||
<p class="lead">{{.VisLead}}</p>
|
||||
<div class="kpis">{{range .VisKPIs}}<div class="kpi"><span>{{.Label}}</span><b>{{.Value}}</b></div>{{end}}</div>
|
||||
<div class="grid2">{{template "bars" .Pages}}{{template "bars" .Refs}}{{template "donut" .Browsers}}{{template "donut" .Devices}}</div>
|
||||
</section>
|
||||
|
||||
<section class="keep" id="def"><h2>{{.TDef}}</h2>
|
||||
{{template "table" .Defense}}
|
||||
</section>
|
||||
|
||||
{{if .HasEnf}}<section class="keep" id="enf"><h2>{{.TEnf}}</h2>
|
||||
<p class="lead">{{.EnfLead}}</p>
|
||||
{{range .EnfNotes}}<div class="note">{{.}}</div>{{end}}
|
||||
<div class="kpis k4">{{range .EnfKPIs}}<div class="kpi {{.Cls}}"><span>{{.Label}}</span><b>{{.Value}}</b></div>{{end}}</div>
|
||||
<div class="tbl"><h3>{{.TEnfRecent}}</h3>{{template "table" .EnfRecent}}</div>
|
||||
</section>{{end}}
|
||||
|
||||
{{if .HasEgress}}<section class="keep" id="egress"><h2>{{.TEgress}}</h2>
|
||||
<p class="lead">{{.XLead}}</p>
|
||||
{{range .XNotes}}<div class="note">{{.}}</div>{{end}}
|
||||
<div class="grid2" style="margin-top:3mm">{{template "bars" .XChart}}{{template "bars" .XDst}}</div>
|
||||
<div class="tbl"><h3>{{.TXFind}}</h3>{{template "table" .XFind}}</div>
|
||||
<div class="tbl"><h3>{{.TXWl}}</h3>{{template "table" .XWl}}</div>
|
||||
</section>{{end}}
|
||||
|
||||
<section class="keep" id="method"><h2>{{.TMethod}}</h2>
|
||||
<p>{{.MethodP1}}</p><p>{{.MethodP2}}</p><p>{{.MethodP3}}</p>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
{{define "table"}}{{if .Rows}}{{$n := .Num}}{{$w := .NoWrap}}<table><thead><tr>{{range $i, $h := .Head}}<th{{if index $n $i}} class="n"{{end}}>{{$h}}</th>{{end}}</tr></thead><tbody>{{range .Rows}}<tr>{{range $i, $c := .Cells}}<td{{if index $n $i}} class="n"{{else if index $w $i}} class="w"{{end}}>{{$c}}</td>{{end}}</tr>{{end}}</tbody></table>{{else}}<p class="empty">{{.None}}</p>{{end}}{{end}}
|
||||
{{define "bars"}}<div class="box"><h3>{{.Title}}</h3>{{if .Empty}}<p class="empty">-</p>{{else}}{{.SVG}}{{end}}</div>{{end}}
|
||||
{{define "donut"}}<div class="box"><h3>{{.Title}}</h3>{{if .Empty}}<p class="empty">-</p>{{else}}<div class="donutwrap">{{.SVG}}<ul class="legend">{{range $i, $l := .Legend}}<li><span class="sw c{{$i}}"></span><span class="lb">{{$l.Label}}</span><span class="vl">{{$l.Value}}</span></li>{{end}}</ul></div>{{end}}</div>{{end}}
|
||||
`
|
||||
@@ -102,6 +102,7 @@ func New(opt Options) http.Handler {
|
||||
m.HandleFunc("GET /api/v1/peer/export", s.peerExport)
|
||||
m.HandleFunc("GET /api/v1/peer/stream", s.peerStream)
|
||||
m.HandleFunc("GET /api/v1/peer/period", s.peerPeriod)
|
||||
m.HandleFunc("GET /api/v1/peer/egress", s.peerEgress)
|
||||
m.HandleFunc("GET /api/v1/geo", s.api(s.geoAPI))
|
||||
m.HandleFunc("GET /api/v1/live/recent", s.api(s.liveRecent))
|
||||
m.HandleFunc("GET /api/v1/summary", s.api(s.summary))
|
||||
@@ -119,6 +120,9 @@ func New(opt Options) http.Handler {
|
||||
for _, r := range userRoutes {
|
||||
m.HandleFunc(r.pattern, s.api(r.handler(s)))
|
||||
}
|
||||
for _, r := range peerRoutes { // peer-token routes of api_<name>.go files
|
||||
m.HandleFunc(r.pattern, r.handler(s))
|
||||
}
|
||||
m.HandleFunc("GET /api/v1/events/stream", s.api(s.stream))
|
||||
m.HandleFunc("GET /api/v1/blocklist.txt", s.api(s.blocklist(false)))
|
||||
m.HandleFunc("GET /api/v1/blocklist.json", s.api(s.blocklist(true)))
|
||||
@@ -196,7 +200,7 @@ func (s *Server) api(h http.HandlerFunc) http.HandlerFunc {
|
||||
switch s.authKind(r) {
|
||||
case "session", "bearer":
|
||||
case "peer":
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "the peer token only opens /api/v1/peer/export, /api/v1/peer/stream and /api/v1/peer/period"})
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "the peer token only opens /api/v1/peer/export, /api/v1/peer/stream, /api/v1/peer/period and /api/v1/peer/egress"})
|
||||
return
|
||||
default:
|
||||
ip := clientIP(r, s.opt.TrustedProxy)
|
||||
|
||||
@@ -3,3 +3,23 @@
|
||||
.df-kpis .card-metric { min-width: 0; }
|
||||
.df-sum { padding: 0 0 8px; }
|
||||
.df-bl { color: var(--ink-muted); font-size: .875rem; margin: 4px 0 12px; overflow-wrap: anywhere; }
|
||||
.df-en { margin-top: var(--grid-gap, 16px); }
|
||||
.df-en .panel { min-width: 0; }
|
||||
.df-en-title { font-size: 1.125rem; margin: 0 0 4px; }
|
||||
.df-mode { margin: 0 0 8px; }
|
||||
.df-en-p { margin: 0 0 8px; overflow-wrap: anywhere; }
|
||||
.df-en-meta { overflow-wrap: anywhere; }
|
||||
.df-en-how { margin: 8px 0 0; padding: 8px 12px; border-left: 3px solid var(--info); background: var(--info-soft); border-radius: 4px; overflow-wrap: anywhere; }
|
||||
.df-en-sum { font-size: 1.0625rem; font-weight: 600; margin: 0 0 4px; overflow-wrap: anywhere; }
|
||||
.df-skips { list-style: none; margin: 12px 0 0; padding: 0; display: flex; flex-wrap: wrap; gap: 4px 16px; color: var(--ink-muted); font-size: .875rem; }
|
||||
.df-skips .num { font-weight: 600; color: var(--ink); }
|
||||
.df-scroll { max-height: 440px; overflow: auto; }
|
||||
.df-table { width: 100%; border-collapse: collapse; font-size: .875rem; }
|
||||
.df-table th, .df-table td { padding: 5px var(--s-3, 10px); border-bottom: 1px solid var(--line); text-align: left; overflow-wrap: anywhere; vertical-align: top; }
|
||||
.df-table th { color: var(--ink-muted); font-weight: 500; position: sticky; top: 0; background: var(--surface-panel); }
|
||||
.df-table .num { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
.df-act { display: inline-flex; flex-direction: column; align-items: flex-start; gap: 2px; }
|
||||
.df-skipwhy { color: var(--ink-muted); font-size: .75rem; }
|
||||
@media (max-width: 900px) { .df-en .span-4, .df-en .span-8 { grid-column: 1 / -1; } }
|
||||
.df-nowrap { white-space: nowrap; }
|
||||
@media (max-width: 700px) { .df-table { min-width: 640px; } .df-table td, .df-table th { overflow-wrap: normal; } }
|
||||
@@ -44,7 +44,76 @@
|
||||
'df.disabled': 'The event registry is off',
|
||||
'df.disabled.sub': 'Defense is computed from the event registry; enable it to see this page.',
|
||||
'df.partial': 'Partial result: the study hit its time or size limit.',
|
||||
'df.admin': 'your account'
|
||||
'df.admin': 'your account',
|
||||
'df.en.title': 'Second firewall',
|
||||
'df.en.hint': 'Urutau can also block attackers by itself, as a safety net next to fail2ban.',
|
||||
'df.en.mode': 'Mode',
|
||||
'df.en.mode.off': 'Off',
|
||||
'df.en.mode.observe': 'Observing only',
|
||||
'df.en.mode.on': 'Active',
|
||||
'df.en.mode.off.sub': 'Urutau does not block anyone. Nothing is written; the coverage below shows what you would gain by turning it on.',
|
||||
'df.en.mode.observe.sub': 'Urutau decides who it would block and records it, but blocks nobody. Use it to check the decisions before trusting them.',
|
||||
'df.en.mode.on.sub': 'Urutau blocks the attackers it recognises, on its own, for a limited time.',
|
||||
'df.en.mode.where': 'The mode is chosen at deploy time with the variable URUTAU_ENFORCE (off, observe or on). It cannot be changed from this page.',
|
||||
'df.en.how.title': 'How to turn it on',
|
||||
'df.en.how.body': 'Set URUTAU_ENFORCE=observe on the server and restart Urutau. Watch the decisions for a few days; when they look right, change it to on.',
|
||||
'df.en.share': 'Sharing with peers',
|
||||
'df.en.share.on': 'on: bans are shared with other servers',
|
||||
'df.en.share.off': 'off: bans stay on this server',
|
||||
'df.en.threshold': 'Blocks from score {n}',
|
||||
'df.en.nolog.title': 'Blocks are not being saved',
|
||||
'df.en.nolog.body': 'The mode is active but the block file cannot be written, so nobody is really blocked. Check the permissions of the folder where Urutau writes the blocklist.',
|
||||
'df.en.lead': '{b} of {a} attacking addresses were blocked {range}',
|
||||
'df.en.lead.sub': '{fw} by the server firewall, {ur} by Urutau, {wb} would be blocked in observation mode and {un} got through.',
|
||||
'df.en.lead.none': 'No attacking addresses {range}',
|
||||
'df.en.lead.none.sub': 'Nothing to block in this window.',
|
||||
'df.en.cov': 'Who was blocked',
|
||||
'df.en.cov.hint': 'Each attacking address counted once, by the first line of defense that stopped it.',
|
||||
'df.en.cov.center': 'addresses',
|
||||
'df.en.cov.fw': 'Blocked by the server firewall',
|
||||
'df.en.cov.ur': 'Blocked by Urutau',
|
||||
'df.en.cov.wb': 'Would be blocked (observation mode)',
|
||||
'df.en.cov.un': 'Got through without a block',
|
||||
'df.en.counts': 'What Urutau decided',
|
||||
'df.en.counts.hint': 'Counts in this window. "Skipped" are attackers it deliberately left alone.',
|
||||
'df.en.c.decided': 'Decisions',
|
||||
'df.en.c.written': 'Blocks written',
|
||||
'df.en.c.dropped': 'Dropped by rate limit',
|
||||
'df.en.c.already': 'Already blocked',
|
||||
'df.en.recent': 'Recent decisions',
|
||||
'df.en.recent.hint': 'The latest decisions, newest first.',
|
||||
'df.en.recent.none': 'No decisions in this window.',
|
||||
'df.en.col.time': 'Time',
|
||||
'df.en.col.ip': 'Address',
|
||||
'df.en.col.cc': 'Country',
|
||||
'df.en.col.reason': 'Reason',
|
||||
'df.en.col.score': 'Score',
|
||||
'df.en.col.ttl': 'Duration',
|
||||
'df.en.col.action': 'Action',
|
||||
'df.en.col.src': 'Origin',
|
||||
'df.en.act.ban': 'Blocked',
|
||||
'df.en.act.would_ban': 'Would block',
|
||||
'df.en.act.skip': 'Not blocked',
|
||||
'df.en.src.local': 'this server',
|
||||
'df.en.src.peer': 'peer {n}',
|
||||
'df.en.skip.trusted': 'Trusted address (your own list)',
|
||||
'df.en.skip.private': 'Private network (not on the internet)',
|
||||
'df.en.skip.crawler': 'Verified search engine',
|
||||
'df.en.skip.legit_visitor': 'Looks like a legitimate visitor',
|
||||
'df.en.skip.peer': 'Peer server (yours)',
|
||||
'df.en.reason.scanner-flood': 'Many vulnerability probes in a short time',
|
||||
'df.en.reason.exploit-flood': 'Repeated exploit attempts',
|
||||
'df.en.reason.web-bruteforce': 'Password guessing on a website',
|
||||
'df.en.reason.wp-bruteforce': 'Password guessing on WordPress',
|
||||
'df.en.reason.ssh-bruteforce': 'Password guessing on SSH',
|
||||
'df.en.reason.rce': 'Attempt to run commands on the server',
|
||||
'df.en.reason.path-traversal': 'Attempt to read files outside the site',
|
||||
'df.en.reason.env-probe': 'Hunting for secret configuration files (.env)',
|
||||
'df.en.reason.vcs-probe': 'Hunting for source code history (.git)',
|
||||
'df.en.reason.webshell': 'Looking for or uploading a backdoor (webshell)',
|
||||
'df.en.reason.sqli': 'Attempt to tamper with the database (SQL injection)',
|
||||
'df.en.reason.log4shell': 'Log4Shell exploit attempt',
|
||||
'df.en.error': 'Could not load the second firewall data.'
|
||||
},
|
||||
'pt-BR': {
|
||||
'df.title': 'Defesa',
|
||||
@@ -79,7 +148,76 @@
|
||||
'df.disabled': 'O registro de eventos está desligado',
|
||||
'df.disabled.sub': 'A defesa é calculada a partir do registro de eventos; ative-o para ver esta página.',
|
||||
'df.partial': 'Resultado parcial: o estudo atingiu o limite de tempo ou de tamanho.',
|
||||
'df.admin': 'sua conta'
|
||||
'df.admin': 'sua conta',
|
||||
'df.en.title': 'Segundo firewall',
|
||||
'df.en.hint': 'O Urutau também pode bloquear atacantes por conta própria, como uma rede de segurança ao lado do fail2ban.',
|
||||
'df.en.mode': 'Modo',
|
||||
'df.en.mode.off': 'Desligado',
|
||||
'df.en.mode.observe': 'Só observando',
|
||||
'df.en.mode.on': 'Ativo',
|
||||
'df.en.mode.off.sub': 'O Urutau não bloqueia ninguém e não grava nada. A cobertura abaixo mostra o quanto você ganharia ao ligá-lo.',
|
||||
'df.en.mode.observe.sub': 'O Urutau decide quem bloquearia e registra, mas não bloqueia ninguém. Use para conferir as decisões antes de confiar nelas.',
|
||||
'df.en.mode.on.sub': 'O Urutau bloqueia sozinho os atacantes que reconhece, por tempo limitado.',
|
||||
'df.en.mode.where': 'O modo é escolhido no deploy, pela variável URUTAU_ENFORCE (off, observe ou on). Não dá para mudá-lo por esta página.',
|
||||
'df.en.how.title': 'Como ligar',
|
||||
'df.en.how.body': 'Defina URUTAU_ENFORCE=observe no servidor e reinicie o Urutau. Acompanhe as decisões por alguns dias; quando estiverem certas, troque para on.',
|
||||
'df.en.share': 'Compartilhamento com parceiros',
|
||||
'df.en.share.on': 'ligado: os bloqueios são compartilhados com outros servidores',
|
||||
'df.en.share.off': 'desligado: os bloqueios ficam só neste servidor',
|
||||
'df.en.threshold': 'Bloqueia a partir da pontuação {n}',
|
||||
'df.en.nolog.title': 'Os bloqueios não estão sendo salvos',
|
||||
'df.en.nolog.body': 'O modo está ativo, mas o arquivo de bloqueios não pode ser gravado; na prática ninguém está sendo bloqueado. Confira as permissões da pasta onde o Urutau grava a blocklist.',
|
||||
'df.en.lead': '{b} de {a} endereços atacantes foram bloqueados {range}',
|
||||
'df.en.lead.sub': '{fw} pelo firewall do servidor, {ur} pelo Urutau, {wb} seriam bloqueados no modo observação e {un} passaram.',
|
||||
'df.en.lead.none': 'Nenhum endereço atacante {range}',
|
||||
'df.en.lead.none.sub': 'Nada a bloquear nesta janela.',
|
||||
'df.en.cov': 'Quem foi bloqueado',
|
||||
'df.en.cov.hint': 'Cada endereço atacante conta uma vez, pela primeira linha de defesa que o barrou.',
|
||||
'df.en.cov.center': 'endereços',
|
||||
'df.en.cov.fw': 'Bloqueado pelo firewall do servidor',
|
||||
'df.en.cov.ur': 'Bloqueado pelo Urutau',
|
||||
'df.en.cov.wb': 'Seria bloqueado (modo observação)',
|
||||
'df.en.cov.un': 'Passou sem bloqueio',
|
||||
'df.en.counts': 'O que o Urutau decidiu',
|
||||
'df.en.counts.hint': 'Contagens desta janela. "Ignorados" são atacantes que ele deixou passar de propósito.',
|
||||
'df.en.c.decided': 'Decisões',
|
||||
'df.en.c.written': 'Bloqueios gravados',
|
||||
'df.en.c.dropped': 'Descartados pelo limite de ritmo',
|
||||
'df.en.c.already': 'Já estavam bloqueados',
|
||||
'df.en.recent': 'Decisões recentes',
|
||||
'df.en.recent.hint': 'As últimas decisões, da mais nova para a mais antiga.',
|
||||
'df.en.recent.none': 'Nenhuma decisão nesta janela.',
|
||||
'df.en.col.time': 'Hora',
|
||||
'df.en.col.ip': 'Endereço',
|
||||
'df.en.col.cc': 'País',
|
||||
'df.en.col.reason': 'Motivo',
|
||||
'df.en.col.score': 'Pontuação',
|
||||
'df.en.col.ttl': 'Duração',
|
||||
'df.en.col.action': 'Ação',
|
||||
'df.en.col.src': 'Origem',
|
||||
'df.en.act.ban': 'Bloqueado',
|
||||
'df.en.act.would_ban': 'Bloquearia',
|
||||
'df.en.act.skip': 'Não bloqueado',
|
||||
'df.en.src.local': 'este servidor',
|
||||
'df.en.src.peer': 'parceiro {n}',
|
||||
'df.en.skip.trusted': 'Endereço confiável (sua própria lista)',
|
||||
'df.en.skip.private': 'Rede privada (fora da internet)',
|
||||
'df.en.skip.crawler': 'Buscador verificado',
|
||||
'df.en.skip.legit_visitor': 'Parece um visitante legítimo',
|
||||
'df.en.skip.peer': 'Servidor parceiro (seu)',
|
||||
'df.en.reason.scanner-flood': 'Muitas sondagens de vulnerabilidade em pouco tempo',
|
||||
'df.en.reason.exploit-flood': 'Tentativas repetidas de exploração',
|
||||
'df.en.reason.web-bruteforce': 'Tentativa de adivinhar senha num site',
|
||||
'df.en.reason.wp-bruteforce': 'Tentativa de adivinhar senha no WordPress',
|
||||
'df.en.reason.ssh-bruteforce': 'Tentativa de adivinhar senha no SSH',
|
||||
'df.en.reason.rce': 'Tentativa de executar comandos no servidor',
|
||||
'df.en.reason.path-traversal': 'Tentativa de ler arquivos fora do site',
|
||||
'df.en.reason.env-probe': 'Caça a arquivos de configuração secretos (.env)',
|
||||
'df.en.reason.vcs-probe': 'Caça ao histórico do código-fonte (.git)',
|
||||
'df.en.reason.webshell': 'Procura ou envio de porta dos fundos (webshell)',
|
||||
'df.en.reason.sqli': 'Tentativa de adulterar o banco de dados (injeção de SQL)',
|
||||
'df.en.reason.log4shell': 'Tentativa de explorar o Log4Shell',
|
||||
'df.en.error': 'Não foi possível carregar os dados do segundo firewall.'
|
||||
}
|
||||
});
|
||||
|
||||
@@ -172,7 +310,122 @@
|
||||
root.appendChild(grid);
|
||||
}
|
||||
|
||||
|
||||
var enData = null, enSeq = 0, enBox = null;
|
||||
function ttlTxt(s) { return s > 0 ? dur(s) : '-'; }
|
||||
function reasonTxt(r) {
|
||||
if (!r) return '-';
|
||||
var k = 'df.en.reason.' + r;
|
||||
if (t(k) !== k) return t(k);
|
||||
var parts = String(r).split(/[-_:]/);
|
||||
for (var i = 0; i < parts.length; i++) { var c = 'df.en.reason.' + parts[i]; if (t(c) !== c) return t(c) + ' (' + r + ')'; }
|
||||
return r;
|
||||
}
|
||||
function tbl(cols, rows) {
|
||||
var tb = el('tbody');
|
||||
rows.forEach(function (r) { tb.appendChild(el('tr', null, r.map(function (c, i) { return el('td', { class: cols[i].cls || '' }, c); }))); });
|
||||
return el('div', { class: 'df-scroll' }, el('table', { class: 'df-table' },
|
||||
el('thead', null, el('tr', null, cols.map(function (c) { return el('th', { class: c.cls || '' }, c.label); }))), tb));
|
||||
}
|
||||
function paintEnforce() {
|
||||
if (!enBox) return;
|
||||
clear(enBox);
|
||||
if (!enData) return;
|
||||
var e = enData, cv = e.coverage || {}, cn = e.counts || {}, sk = cn.skipped || {}, range = U.rangeLabel({ inline: true });
|
||||
var mode = /^(off|observe|on)$/.test(e.mode) ? e.mode : 'off';
|
||||
var head = el('div', { class: 'df-en-head' });
|
||||
var mt = el('h2', { class: 'df-en-title' }, t('df.en.title'));
|
||||
if (U.help) U.help(mt, 'term.second_firewall');
|
||||
head.appendChild(mt);
|
||||
head.appendChild(el('p', { class: 'hint' }, t('df.en.hint')));
|
||||
enBox.appendChild(head);
|
||||
|
||||
var grid = el('div', { class: 'grid-12' });
|
||||
var mp = U.ui.panel({ title: t('df.en.mode'), cls: 'span-4', help: mode === 'observe' ? 'term.observe_mode' : null });
|
||||
var tone = mode === 'on' ? 'ok' : mode === 'observe' ? 'info' : 'warn';
|
||||
mp.body.appendChild(el('p', { class: 'df-mode' }, U.ui.badge(t('df.en.mode.' + mode), tone)));
|
||||
mp.body.appendChild(el('p', { class: 'df-en-p' }, t('df.en.mode.' + mode + '.sub')));
|
||||
mp.body.appendChild(el('p', { class: 'hint' }, t('df.en.mode.where')));
|
||||
var meta = el('p', { class: 'hint df-en-meta' }, t('df.en.threshold', { n: nf(e.threshold || 0) }) + ' · ' + t('df.en.share') + ': ' + (e.share === 'on' ? t('df.en.share.on') : t('df.en.share.off')));
|
||||
if (U.help) U.help(meta, 'term.ban_ttl');
|
||||
mp.body.appendChild(meta);
|
||||
if (mode === 'on' && e.log_writable === false) mp.body.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('df.en.nolog.title')), el('span', null, t('df.en.nolog.body'))));
|
||||
if (mode === 'off') {
|
||||
mp.body.appendChild(el('p', { class: 'df-en-how' }, el('strong', null, t('df.en.how.title') + ': '), t('df.en.how.body')));
|
||||
}
|
||||
grid.appendChild(mp);
|
||||
|
||||
var total = (cv.blocked_by_firewall || 0) + (cv.blocked_by_urutau || 0) + (cv.would_block || 0) + (cv.unblocked || 0);
|
||||
var cp = U.ui.panel({ title: t('df.en.cov'), hint: t('df.en.cov.hint'), cls: 'span-8' });
|
||||
var rows = [
|
||||
{ key: 'fw', label: t('df.en.cov.fw'), value: cv.blocked_by_firewall || 0, color: '--ok' },
|
||||
{ key: 'ur', label: t('df.en.cov.ur'), value: cv.blocked_by_urutau || 0, color: '--info' },
|
||||
{ key: 'wb', label: t('df.en.cov.wb'), value: cv.would_block || 0, color: '--warn' },
|
||||
{ key: 'un', label: t('df.en.cov.un'), value: cv.unblocked || 0, color: '--danger' }
|
||||
];
|
||||
var blocked = (cv.blocked_by_firewall || 0) + (cv.blocked_by_urutau || 0);
|
||||
cp.body.appendChild(el('p', { class: 'df-en-sum' }, total ? t('df.en.lead', { b: nf(blocked), a: nf(cv.attack_ips || total), range: range }) : t('df.en.lead.none', { range: range })));
|
||||
if (total) {
|
||||
cp.body.appendChild(el('p', { class: 'hint' }, t('df.en.lead.sub', { fw: nf(rows[0].value), ur: nf(rows[1].value), wb: nf(rows[2].value), un: nf(rows[3].value) })));
|
||||
if (U.charts && U.charts.donut) {
|
||||
cp.body.appendChild(U.charts.donut(rows, { title: t('df.en.cov'), centerLabel: t('df.en.cov.center'), format: nf, colors: rows.map(function (r) { return r.color; }) }));
|
||||
if (U.help) { var lis = cp.body.querySelectorAll('.vz-legend li'); if (lis[2]) U.help(lis[2], 'term.observe_mode'); }
|
||||
}
|
||||
} else cp.body.appendChild(U.ui.empty(t('df.en.lead.none', { range: range }), t('df.en.lead.none.sub')));
|
||||
grid.appendChild(cp);
|
||||
|
||||
var np = U.ui.panel({ title: t('df.en.counts'), hint: t('df.en.counts.hint'), cls: 'span-12' });
|
||||
var kp = el('div', { class: 'grid-12 df-kpis' });
|
||||
function k(node) { node.classList.add('span-3'); kp.appendChild(node); }
|
||||
k(U.ui.metric(t('df.en.c.decided'), nf(cn.decided || 0)));
|
||||
k(U.ui.metric(t('df.en.c.written'), nf(cn.written || 0), { tone: 'ok' }));
|
||||
k(U.ui.metric(t('df.en.c.dropped'), nf(cn.dropped_rate || 0), { tone: cn.dropped_rate ? 'warn' : 'neutral' }));
|
||||
k(U.ui.metric(t('df.en.c.already'), nf(cn.already_blocked || 0)));
|
||||
np.body.appendChild(kp);
|
||||
var skl = el('ul', { class: 'df-skips' });
|
||||
['trusted', 'private', 'crawler', 'legit_visitor', 'peer'].forEach(function (key) {
|
||||
if (!sk[key]) return;
|
||||
skl.appendChild(el('li', null, el('span', { class: 'num' }, nf(sk[key])), ' ' + t('df.en.skip.' + key)));
|
||||
});
|
||||
if (skl.firstChild) np.body.appendChild(skl);
|
||||
grid.appendChild(np);
|
||||
|
||||
var rp = U.ui.panel({ title: t('df.en.recent'), hint: t('df.en.recent.hint'), cls: 'span-12', variant: 'list' });
|
||||
var rec = e.recent || [];
|
||||
if (!rec.length) rp.body.appendChild(U.ui.empty(t('df.en.recent.none')));
|
||||
else {
|
||||
var cols = [{ label: t('df.en.col.time') }, { label: t('df.en.col.ip'), cls: 'mono' }, { label: t('df.en.col.cc') }, { label: t('df.en.col.reason') },
|
||||
{ label: t('df.en.col.score'), cls: 'num' }, { label: t('df.en.col.ttl'), cls: 'num' }, { label: t('df.en.col.action') }, { label: t('df.en.col.src') }];
|
||||
rp.body.appendChild(tbl(cols, rec.map(function (r) {
|
||||
var act = /^(ban|would_ban|skip)$/.test(r.action) ? r.action : 'skip';
|
||||
var actNode = el('span', { class: 'df-act' }, U.ui.badge(t('df.en.act.' + act), act === 'ban' ? 'ok' : act === 'would_ban' ? 'warn' : 'neutral'));
|
||||
if (act === 'skip' && r.skip_reason) {
|
||||
var sk2 = 'df.en.skip.' + r.skip_reason;
|
||||
actNode.appendChild(el('small', { class: 'df-skipwhy' }, t(sk2) !== sk2 ? t(sk2) : r.skip_reason));
|
||||
}
|
||||
var peer = String(r.src || 'local');
|
||||
var src = peer.indexOf('peer:') === 0 ? t('df.en.src.peer', { n: peer.slice(5) }) : t('df.en.src.local');
|
||||
return [el('span', { class: 'df-nowrap' }, U.fmt.clock(r.t)), el('a', { href: U.href('ip', [r.ip]) }, r.ip), (r.cc ? U.fmt.flag(r.cc) + ' ' : '') + (r.cc || '-'),
|
||||
reasonTxt(r.reason), nf(r.score || 0), ttlTxt(r.ttl || 0), actNode, src];
|
||||
})));
|
||||
}
|
||||
grid.appendChild(rp);
|
||||
enBox.appendChild(grid);
|
||||
}
|
||||
function loadEnforce() {
|
||||
var my = ++enSeq;
|
||||
U.api('/api/v1/enforce', Object.assign(U.rangeParams(), ctx && ctx.host && ctx.host !== 'all' ? { host: ctx.host } : {})).then(function (d) {
|
||||
if (!alive || my !== enSeq) return;
|
||||
enData = d; paintEnforce();
|
||||
}).catch(function () {
|
||||
if (!alive || my !== enSeq || enData || !enBox) return;
|
||||
clear(enBox);
|
||||
enBox.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('df.en.error'))));
|
||||
});
|
||||
}
|
||||
|
||||
function load() {
|
||||
loadEnforce();
|
||||
var my = ++seq;
|
||||
U.api('/api/v1/defense', Object.assign(U.rangeParams(), ctx && ctx.host && ctx.host !== 'all' ? { host: ctx.host } : {})).then(function (d) {
|
||||
if (!alive || my !== seq) return;
|
||||
@@ -187,10 +440,10 @@
|
||||
U.registerPage({
|
||||
id: 'defense', group: 'operate', titleKey: 'df.title',
|
||||
icon: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M12 3l8 3v6c0 4.5-3.2 7.8-8 9-4.8-1.2-8-4.5-8-9V6z"/><path d="M9 12l2 2 4-4"/></svg>',
|
||||
mount: function (node, cx) { root = el('div', { class: 'df-page' }); node.appendChild(root); ctx = cx; alive = true; data = null; paint(); load(); },
|
||||
mount: function (node, cx) { root = el('div', { class: 'df-page' }); node.appendChild(root); enBox = el('div', { class: 'df-page df-en' }); node.appendChild(enBox); ctx = cx; alive = true; data = null; enData = null; paint(); load(); },
|
||||
update: function (cx) { ctx = cx; load(); },
|
||||
refresh: function () { load(); },
|
||||
unmount: function () { alive = false; seq++; if (root && root.parentNode) root.parentNode.removeChild(root); root = null; data = null; }
|
||||
unmount: function () { alive = false; seq++; enSeq++; if (root && root.parentNode) root.parentNode.removeChild(root); if (enBox && enBox.parentNode) enBox.parentNode.removeChild(enBox); root = null; enBox = null; data = null; enData = null; }
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
/* Egress page */
|
||||
.eg-page { display: grid; gap: var(--grid-gap, 16px); min-width: 0; }
|
||||
.eg-page .panel, .eg-kpis .card-metric { min-width: 0; }
|
||||
.eg-wl-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 240px), 1fr)); gap: 12px; }
|
||||
.eg-wl { min-width: 0; }
|
||||
.eg-wl-head { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 8px; margin-bottom: 8px; }
|
||||
.eg-wl-head .badge { white-space: normal; }
|
||||
.eg-wl-name { margin: 0; font-size: 1rem; overflow-wrap: anywhere; }
|
||||
.eg-wl-stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: 6px; margin: 0; }
|
||||
.eg-wl-stats div { min-width: 0; }
|
||||
.eg-wl-stats dd { margin: 0; font-size: 1.125rem; font-weight: 600; }
|
||||
.eg-wl-stats dt { color: var(--ink-muted); font-size: .75rem; overflow-wrap: anywhere; }
|
||||
.eg-warn { color: var(--danger); font-weight: 600; }
|
||||
.eg-findings { list-style: none; margin: 0; padding: 0; display: grid; gap: 10px; }
|
||||
.eg-f { border: 1px solid var(--line); border-left-width: 4px; border-radius: 6px; padding: 10px 12px; min-width: 0; }
|
||||
.eg-sev-high { border-left-color: var(--danger); }
|
||||
.eg-sev-medium { border-left-color: var(--warn); }
|
||||
.eg-sev-low { border-left-color: var(--info); }
|
||||
.eg-f-top { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; }
|
||||
.eg-f p { margin: 6px 0 0; overflow-wrap: anywhere; }
|
||||
.eg-f-why { color: var(--ink-muted); }
|
||||
.eg-f-detail { font-size: .8125rem; }
|
||||
.eg-scroll { max-height: 440px; overflow: auto; }
|
||||
.eg-table { width: 100%; border-collapse: collapse; font-size: .875rem; }
|
||||
.eg-table th, .eg-table td { padding: 5px var(--s-3, 10px); border-bottom: 1px solid var(--line); text-align: left; overflow-wrap: anywhere; vertical-align: top; }
|
||||
.eg-table th { color: var(--ink-muted); font-weight: 500; position: sticky; top: 0; background: var(--surface-panel); }
|
||||
.eg-table .num { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
.eg-scanwarn { margin-bottom: 10px; }
|
||||
@media (max-width: 600px) { .eg-kpis .span-4 { grid-column: 1 / -1; } }
|
||||
@media (max-width: 700px) { .eg-table { min-width: 560px; } }
|
||||
@@ -0,0 +1,355 @@
|
||||
/* Urutau - EGRESS page: what the workloads of your servers talk to on the
|
||||
internet (outbound traffic). Beacons, scans, odd ports, known-bad
|
||||
destinations, DNS bypass, new countries, and the summarised scans of the
|
||||
authorised scanner. Data: /api/v1/egress. Log data is hostile: dynamic text
|
||||
goes through textContent only. */
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
var SEV = { high: 0, medium: 1, low: 2 };
|
||||
var SEV_TONE = { high: 'danger', medium: 'warn', low: 'info' };
|
||||
var KINDS = ['beacon', 'scan', 'port', 'bad_dst', 'dns_bypass', 'new_geo'];
|
||||
var KIND_HELP = { beacon: 'term.beaconing', scan: 'term.fanout', port: 'term.stratum', bad_dst: 'term.c2', dns_bypass: 'term.dot', new_geo: 'term.new_geo' };
|
||||
|
||||
function boot() {
|
||||
var U = window.Urutau;
|
||||
if (!U || !U.registerPage) return false;
|
||||
U.registerI18n({
|
||||
en: {
|
||||
'eg.title': 'Outbound traffic',
|
||||
'eg.error': 'Could not load the outbound traffic data.',
|
||||
'eg.retry': 'Try again',
|
||||
'eg.disabled': 'Outbound traffic is not being watched',
|
||||
'eg.disabled.sub': 'This page shows connections that leave your servers. To see them, add an outbound firewall rule on the server that logs new connections, and set the variable URUTAU_EGRESS so Urutau reads that log.',
|
||||
'eg.lead.none': 'No outbound connections {range}',
|
||||
'eg.lead.none.sub': 'Nothing left the watched workloads in this window.',
|
||||
'eg.lead.ok': '{n} outbound connections {range}, nothing suspicious',
|
||||
'eg.lead.ok.sub': 'No findings in this window. Authorised scans, if any, are summarised below.',
|
||||
'eg.lead.bad': '{f} findings in {n} outbound connections {range}',
|
||||
'eg.lead.bad.sub': '{h} high, {m} medium and {l} low severity. Start with the high ones.',
|
||||
'eg.src': 'Log source: {state} · {lines} lines read · {bad} unreadable',
|
||||
'eg.src.following': 'being followed',
|
||||
'eg.src.waiting': 'waiting for the file',
|
||||
'eg.src.missing': 'file not found',
|
||||
'eg.src.error': 'error',
|
||||
'eg.kpi.conns': 'Connections',
|
||||
'eg.kpi.conns.sub': 'new outbound connections',
|
||||
'eg.kpi.dsts': 'Destinations',
|
||||
'eg.kpi.dsts.sub': 'different addresses reached',
|
||||
'eg.kpi.find': 'Findings',
|
||||
'eg.kpi.find.sub': '{h} high · {m} medium · {l} low',
|
||||
'eg.workloads': 'Workloads',
|
||||
'eg.workloads.hint': 'Each workload is a program or container that makes outbound connections.',
|
||||
'eg.wl.conns': 'connections',
|
||||
'eg.wl.dsts': 'destinations',
|
||||
'eg.wl.ports': 'ports',
|
||||
'eg.wl.findings': 'findings',
|
||||
'eg.wl.suppressed': '{n} scan connections summarised',
|
||||
'eg.role.scanner': 'authorised scans summarised',
|
||||
'eg.role.app': 'application',
|
||||
'eg.role.proxy': 'proxy',
|
||||
'eg.role.database': 'database',
|
||||
'eg.role.system': 'system',
|
||||
'eg.timeline': 'Connections over time',
|
||||
'eg.timeline.hint': 'Stacked by workload.',
|
||||
'eg.findings': 'Findings',
|
||||
'eg.findings.hint': 'Sorted by severity. Each one explains what the pattern usually means.',
|
||||
'eg.findings.none': 'No findings in this window.',
|
||||
'eg.sev.high': 'High',
|
||||
'eg.sev.medium': 'Medium',
|
||||
'eg.sev.low': 'Low',
|
||||
'eg.kind.beacon': 'Regular conversation',
|
||||
'eg.kind.scan': 'Mass connection attempts',
|
||||
'eg.kind.port': 'Unusual port',
|
||||
'eg.kind.bad_dst': 'Known-bad destination',
|
||||
'eg.kind.dns_bypass': 'DNS outside the resolver',
|
||||
'eg.kind.new_geo': 'New country',
|
||||
'eg.why.beacon': 'The workload talks to the same destination at regular intervals, like a clock. This is the typical pattern of malware checking in with its controller.',
|
||||
'eg.why.scan': 'The workload tried to connect to many different addresses in a short time. A server that scans the internet usually means it was taken over.',
|
||||
'eg.why.port': 'Connection to a port used by mining pools or remote-control tools, which normal software on this server does not use.',
|
||||
'eg.why.bad_dst': 'The destination is on a list of addresses known for malware or attacks. Nothing on your server should talk to it.',
|
||||
'eg.why.dns_bypass': 'The workload asked for names directly from an outside DNS server instead of your resolver. Malware does this to hide what it looks up.',
|
||||
'eg.why.new_geo': 'The workload connected to a country it had never reached before in this window. It may be harmless, but is worth a look.',
|
||||
'eg.f.to': 'To',
|
||||
'eg.f.count': '{n} connections',
|
||||
'eg.f.interval': 'every {s} s (variation {j}%)',
|
||||
'eg.f.first': 'first {t}',
|
||||
'eg.f.last': 'last {t}',
|
||||
'eg.f.host': 'server {h}',
|
||||
'eg.dst': 'Top destinations',
|
||||
'eg.dst.hint': 'Where the connections went.',
|
||||
'eg.dst.none': 'No destinations in this window.',
|
||||
'eg.col.ip': 'Address',
|
||||
'eg.col.country': 'Country',
|
||||
'eg.col.asn': 'Network (ASN)',
|
||||
'eg.col.conns': 'Connections',
|
||||
'eg.col.who': 'Workloads',
|
||||
'eg.col.ports': 'Ports',
|
||||
'eg.scan': 'Authorised scans',
|
||||
'eg.scan.hint': 'Scans your own scanner runs on purpose. They are summarised here instead of raising findings.',
|
||||
'eg.scan.none': 'No scan bursts in this window.',
|
||||
'eg.scan.warn': 'A scan reached {n} known-bad destinations: check that the scanner is not aiming at the wrong targets.',
|
||||
'eg.scan.targets': '{n} targets',
|
||||
'eg.scan.nets': 'networks',
|
||||
'eg.scan.ports': 'ports',
|
||||
'eg.scan.conns': '{n} connections',
|
||||
'eg.scan.when': '{a} to {b}',
|
||||
'eg.col.who1': 'Workload',
|
||||
'eg.col.when': 'When',
|
||||
'eg.col.targets': 'Targets',
|
||||
'eg.col.nets': 'Networks',
|
||||
'eg.col.badhits': 'Bad destinations hit'
|
||||
},
|
||||
'pt-BR': {
|
||||
'eg.title': 'Tráfego de saída',
|
||||
'eg.error': 'Não foi possível carregar os dados de tráfego de saída.',
|
||||
'eg.retry': 'Tentar de novo',
|
||||
'eg.disabled': 'O tráfego de saída não está sendo monitorado',
|
||||
'eg.disabled.sub': 'Esta página mostra as conexões que saem dos seus servidores. Para vê-las, crie no servidor uma regra de firewall de saída que registre as conexões novas e defina a variável URUTAU_EGRESS para o Urutau ler esse registro.',
|
||||
'eg.lead.none': 'Nenhuma conexão de saída {range}',
|
||||
'eg.lead.none.sub': 'Nada saiu dos workloads monitorados nesta janela.',
|
||||
'eg.lead.ok': '{n} conexões de saída {range}, nada suspeito',
|
||||
'eg.lead.ok.sub': 'Nenhum achado nesta janela. As varreduras autorizadas, se houver, aparecem resumidas abaixo.',
|
||||
'eg.lead.bad': '{f} achados em {n} conexões de saída {range}',
|
||||
'eg.lead.bad.sub': '{h} de gravidade alta, {m} média e {l} baixa. Comece pelos de gravidade alta.',
|
||||
'eg.src': 'Origem do registro: {state} · {lines} linhas lidas · {bad} ilegíveis',
|
||||
'eg.src.following': 'sendo acompanhado',
|
||||
'eg.src.waiting': 'aguardando o arquivo',
|
||||
'eg.src.missing': 'arquivo não encontrado',
|
||||
'eg.src.error': 'erro',
|
||||
'eg.kpi.conns': 'Conexões',
|
||||
'eg.kpi.conns.sub': 'novas conexões de saída',
|
||||
'eg.kpi.dsts': 'Destinos',
|
||||
'eg.kpi.dsts.sub': 'endereços diferentes alcançados',
|
||||
'eg.kpi.find': 'Achados',
|
||||
'eg.kpi.find.sub': '{h} altos · {m} médios · {l} baixos',
|
||||
'eg.workloads': 'Workloads',
|
||||
'eg.workloads.hint': 'Cada workload é um programa ou contêiner que faz conexões de saída.',
|
||||
'eg.wl.conns': 'conexões',
|
||||
'eg.wl.dsts': 'destinos',
|
||||
'eg.wl.ports': 'portas',
|
||||
'eg.wl.findings': 'achados',
|
||||
'eg.wl.suppressed': '{n} conexões de varredura resumidas',
|
||||
'eg.role.scanner': 'varreduras autorizadas resumidas',
|
||||
'eg.role.app': 'aplicação',
|
||||
'eg.role.proxy': 'proxy',
|
||||
'eg.role.database': 'banco de dados',
|
||||
'eg.role.system': 'sistema',
|
||||
'eg.timeline': 'Conexões ao longo do tempo',
|
||||
'eg.timeline.hint': 'Empilhadas por workload.',
|
||||
'eg.findings': 'Achados',
|
||||
'eg.findings.hint': 'Ordenados por gravidade. Cada um explica o que o padrão costuma significar.',
|
||||
'eg.findings.none': 'Nenhum achado nesta janela.',
|
||||
'eg.sev.high': 'Alta',
|
||||
'eg.sev.medium': 'Média',
|
||||
'eg.sev.low': 'Baixa',
|
||||
'eg.kind.beacon': 'Conversa em intervalos regulares',
|
||||
'eg.kind.scan': 'Tentativas de conexão em massa',
|
||||
'eg.kind.port': 'Porta incomum',
|
||||
'eg.kind.bad_dst': 'Destino sabidamente ruim',
|
||||
'eg.kind.dns_bypass': 'DNS fora do resolvedor',
|
||||
'eg.kind.new_geo': 'País novo',
|
||||
'eg.why.beacon': 'O workload fala com o mesmo destino em intervalos regulares, como um relógio. É o padrão típico de um malware avisando seu controlador que está vivo.',
|
||||
'eg.why.scan': 'O workload tentou conectar a muitos endereços diferentes em pouco tempo. Um servidor que varre a internet costuma ter sido invadido.',
|
||||
'eg.why.port': 'Conexão a uma porta usada por mineração de criptomoeda ou ferramentas de controle remoto, que os programas normais deste servidor não usam.',
|
||||
'eg.why.bad_dst': 'O destino está numa lista de endereços conhecidos por malware ou ataques. Nada no seu servidor deveria falar com ele.',
|
||||
'eg.why.dns_bypass': 'O workload consultou nomes direto num servidor DNS de fora, em vez do seu resolvedor. Malware faz isso para esconder o que procura.',
|
||||
'eg.why.new_geo': 'O workload conectou a um país que ainda não tinha alcançado nesta janela. Pode ser inofensivo, mas vale olhar.',
|
||||
'eg.f.to': 'Para',
|
||||
'eg.f.count': '{n} conexões',
|
||||
'eg.f.interval': 'a cada {s} s (variação {j}%)',
|
||||
'eg.f.first': 'primeira {t}',
|
||||
'eg.f.last': 'última {t}',
|
||||
'eg.f.host': 'servidor {h}',
|
||||
'eg.dst': 'Principais destinos',
|
||||
'eg.dst.hint': 'Para onde foram as conexões.',
|
||||
'eg.dst.none': 'Nenhum destino nesta janela.',
|
||||
'eg.col.ip': 'Endereço',
|
||||
'eg.col.country': 'País',
|
||||
'eg.col.asn': 'Rede (ASN)',
|
||||
'eg.col.conns': 'Conexões',
|
||||
'eg.col.who': 'Workloads',
|
||||
'eg.col.ports': 'Portas',
|
||||
'eg.scan': 'Varreduras autorizadas',
|
||||
'eg.scan.hint': 'Varreduras que o seu próprio scanner faz de propósito. Aparecem resumidas aqui em vez de gerar achados.',
|
||||
'eg.scan.none': 'Nenhuma rajada de varredura nesta janela.',
|
||||
'eg.scan.warn': 'Uma varredura atingiu {n} destinos sabidamente ruins: confira se o scanner não está mirando os alvos errados.',
|
||||
'eg.scan.targets': '{n} alvos',
|
||||
'eg.scan.nets': 'redes',
|
||||
'eg.scan.ports': 'portas',
|
||||
'eg.scan.conns': '{n} conexões',
|
||||
'eg.scan.when': '{a} a {b}',
|
||||
'eg.col.who1': 'Workload',
|
||||
'eg.col.when': 'Quando',
|
||||
'eg.col.targets': 'Alvos',
|
||||
'eg.col.nets': 'Redes',
|
||||
'eg.col.badhits': 'Destinos ruins atingidos'
|
||||
}
|
||||
});
|
||||
|
||||
var el = U.el, t = U.t, nf = U.fmt.num;
|
||||
var root = null, seq = 0, alive = false, ctx = null, data = null, failed = false;
|
||||
|
||||
function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); }
|
||||
function tbl(cols, rows) {
|
||||
var tb = el('tbody');
|
||||
rows.forEach(function (r) { tb.appendChild(el('tr', null, r.map(function (c, i) { return el('td', { class: cols[i].cls || '' }, c); }))); });
|
||||
return el('div', { class: 'eg-scroll' }, el('table', { class: 'eg-table' },
|
||||
el('thead', null, el('tr', null, cols.map(function (c) { return el('th', { class: c.cls || '' }, c.label); }))), tb));
|
||||
}
|
||||
function ipLink(ip) { return el('a', { href: U.href('ip', [ip]), class: 'mono' }, ip); }
|
||||
function when(ts) { return ts ? U.fmt.clock(ts) : '-'; }
|
||||
function help(node, key) { if (U.help) U.help(node, key); return node; }
|
||||
function roleLabel(r) { var k = 'eg.role.' + r; return t(k) !== k ? t(k) : (r || '-'); }
|
||||
function list(a) { return (a || []).join(', ') || '-'; }
|
||||
|
||||
function workloadCard(w, multi) {
|
||||
var scanner = w.role === 'scanner';
|
||||
var h = el('h3', { class: 'eg-wl-name' }, w.name);
|
||||
var head = el('div', { class: 'eg-wl-head' }, h);
|
||||
if (w.role) {
|
||||
var b = U.ui.badge(roleLabel(w.role), scanner ? 'info' : 'neutral');
|
||||
head.appendChild(b);
|
||||
if (scanner) help(head, 'term.authorized_scanner');
|
||||
}
|
||||
var stats = el('dl', { class: 'eg-wl-stats' });
|
||||
[['conns', w.conns], ['dsts', w.dsts], ['ports', w.ports], ['findings', w.findings]].forEach(function (p) {
|
||||
stats.appendChild(el('div', null, el('dd', { class: 'num' + (p[0] === 'findings' && p[1] ? ' eg-warn' : '') }, nf(p[1] || 0)), el('dt', null, t('eg.wl.' + p[0]))));
|
||||
});
|
||||
var card = el('div', { class: 'card-metric eg-wl' }, head, stats);
|
||||
if (w.suppressed_scan_conns) card.appendChild(el('p', { class: 'cm-sub' }, t('eg.wl.suppressed', { n: nf(w.suppressed_scan_conns) })));
|
||||
if (multi && w.host) card.appendChild(el('p', { class: 'cm-sub' }, t('eg.f.host', { h: w.host })));
|
||||
return card;
|
||||
}
|
||||
|
||||
function findingNode(f, multi) {
|
||||
var kind = KINDS.indexOf(f.kind) >= 0 ? f.kind : null;
|
||||
var sev = SEV[f.severity] !== undefined ? f.severity : 'low';
|
||||
var title = el('strong', { class: 'eg-f-title' }, kind ? t('eg.kind.' + kind) : String(f.kind || '-'));
|
||||
if (kind) help(title, KIND_HELP[kind]);
|
||||
var top = el('div', { class: 'eg-f-top' }, U.ui.badge(t('eg.sev.' + sev), SEV_TONE[sev]), title);
|
||||
var bits = [];
|
||||
bits.push(el('span', { class: 'mono' }, f.workload || '-'));
|
||||
bits.push(' → ');
|
||||
if (f.dst) bits.push(ipLink(f.dst));
|
||||
if (f.dport) bits.push(el('span', { class: 'mono' }, ':' + f.dport + (f.proto ? '/' + f.proto : '')));
|
||||
var meta = [];
|
||||
if (f.count) meta.push(t('eg.f.count', { n: nf(f.count) }));
|
||||
if (f.interval_s) meta.push(t('eg.f.interval', { s: Math.round(f.interval_s * 10) / 10, j: Math.round((f.jitter || 0) * 100) }));
|
||||
if (f.first) meta.push(t('eg.f.first', { t: when(f.first) }));
|
||||
if (f.last) meta.push(t('eg.f.last', { t: when(f.last) }));
|
||||
if (multi && f.host) meta.push(t('eg.f.host', { h: f.host }));
|
||||
var li = el('li', { class: 'eg-f eg-sev-' + sev }, top, el('p', { class: 'eg-f-line' }, bits));
|
||||
if (kind) li.appendChild(el('p', { class: 'eg-f-why' }, t('eg.why.' + kind)));
|
||||
if (f.detail) li.appendChild(el('p', { class: 'eg-f-detail mono' }, f.detail));
|
||||
if (meta.length) li.appendChild(el('p', { class: 'hint eg-f-meta' }, meta.join(' · ')));
|
||||
return li;
|
||||
}
|
||||
|
||||
function paint() {
|
||||
if (!root) return;
|
||||
clear(root);
|
||||
if (!data) { root.appendChild(el('div', { class: 'skeleton', style: { height: '8rem' } })); return; }
|
||||
if (!data.enabled) { root.appendChild(U.ui.empty(t('eg.disabled'), t('eg.disabled.sub'))); return; }
|
||||
var d = data, range = U.rangeLabel({ inline: true });
|
||||
var wls = d.workloads || [], fnd = (d.findings || []).slice();
|
||||
fnd.sort(function (a, b) { var x = SEV[a.severity], y = SEV[b.severity]; x = x === undefined ? 3 : x; y = y === undefined ? 3 : y; return x - y || (b.count || 0) - (a.count || 0); });
|
||||
var conns = 0, nsev = { high: 0, medium: 0, low: 0 };
|
||||
wls.forEach(function (w) { conns += w.conns || 0; });
|
||||
fnd.forEach(function (f) { if (nsev[f.severity] !== undefined) nsev[f.severity]++; });
|
||||
var hosts = {};
|
||||
wls.forEach(function (w) { if (w.host) hosts[w.host] = 1; });
|
||||
fnd.forEach(function (f) { if (f.host) hosts[f.host] = 1; });
|
||||
var multi = Object.keys(hosts).length > 1;
|
||||
var dsts = d.top_dst || [];
|
||||
|
||||
if (!conns && !fnd.length) root.appendChild(U.ui.lead(t('eg.lead.none', { range: range }), t('eg.lead.none.sub'), 'neutral'));
|
||||
else if (!fnd.length) root.appendChild(U.ui.lead(t('eg.lead.ok', { n: nf(conns), range: range }), t('eg.lead.ok.sub'), 'ok'));
|
||||
else root.appendChild(U.ui.lead(t('eg.lead.bad', { f: nf(fnd.length), n: nf(conns), range: range }), t('eg.lead.bad.sub', { h: nsev.high, m: nsev.medium, l: nsev.low }), nsev.high ? 'danger' : 'ok'));
|
||||
var src = d.source || {};
|
||||
var sk = 'eg.src.' + src.state;
|
||||
root.appendChild(el('p', { class: 'hint' }, t('eg.src', { state: t(sk) !== sk ? t(sk) : (src.state || '-'), lines: nf(src.lines || 0), bad: nf(src.malformed || 0) })));
|
||||
|
||||
var kp = el('div', { class: 'grid-12 eg-kpis' });
|
||||
function k(node) { node.classList.add('span-4'); kp.appendChild(node); }
|
||||
k(U.ui.metric(t('eg.kpi.conns'), nf(conns), { sub: t('eg.kpi.conns.sub') }));
|
||||
k(U.ui.metric(t('eg.kpi.dsts'), nf(dsts.length), { sub: t('eg.kpi.dsts.sub') }));
|
||||
k(U.ui.metric(t('eg.kpi.find'), nf(fnd.length), { sub: t('eg.kpi.find.sub', { h: nsev.high, m: nsev.medium, l: nsev.low }), tone: nsev.high ? 'danger' : fnd.length ? 'warn' : 'ok' }));
|
||||
root.appendChild(kp);
|
||||
|
||||
var grid = el('div', { class: 'grid-12' });
|
||||
if (wls.length) {
|
||||
var wp = U.ui.panel({ title: t('eg.workloads'), hint: t('eg.workloads.hint'), cls: 'span-12', help: 'term.workload' });
|
||||
var wg = el('div', { class: 'eg-wl-grid' });
|
||||
wls.forEach(function (w) { wg.appendChild(workloadCard(w, multi)); });
|
||||
wp.body.appendChild(wg);
|
||||
grid.appendChild(wp);
|
||||
}
|
||||
|
||||
var tl = d.timeline || {}, ser = tl.series || {}, names = Object.keys(ser);
|
||||
var tp = U.ui.panel({ title: t('eg.timeline'), hint: t('eg.timeline.hint'), cls: 'span-12', variant: 'chart' });
|
||||
if (U.charts && U.charts.stackedArea && names.length) tp.body.appendChild(U.charts.stackedArea(names.map(function (n) { return { key: n, label: n, values: ser[n] }; }), tl.step || 3600, { start: tl.start || 0, title: t('eg.timeline') }));
|
||||
else tp.body.appendChild(U.ui.empty(t('eg.lead.none', { range: range })));
|
||||
grid.appendChild(tp);
|
||||
|
||||
var fp = U.ui.panel({ title: t('eg.findings'), hint: t('eg.findings.hint'), cls: 'span-12' });
|
||||
if (!fnd.length) fp.body.appendChild(U.ui.empty(t('eg.findings.none')));
|
||||
else { var ul = el('ul', { class: 'eg-findings' }); fnd.forEach(function (f) { ul.appendChild(findingNode(f, multi)); }); fp.body.appendChild(ul); }
|
||||
grid.appendChild(fp);
|
||||
|
||||
var dp = U.ui.panel({ title: t('eg.dst'), hint: t('eg.dst.hint'), cls: 'span-12', variant: 'list' });
|
||||
if (!dsts.length) dp.body.appendChild(U.ui.empty(t('eg.dst.none')));
|
||||
else dp.body.appendChild(tbl([{ label: t('eg.col.ip') }, { label: t('eg.col.country') }, { label: t('eg.col.asn') }, { label: t('eg.col.conns'), cls: 'num' }, { label: t('eg.col.who') }, { label: t('eg.col.ports') }],
|
||||
dsts.map(function (x) {
|
||||
return [ipLink(x.ip), (x.cc ? U.fmt.flag(x.cc) + ' ' + U.fmt.country(x.cc) : '-'), (x.asn || '') + (x.org ? ' ' + x.org : '') || '-', nf(x.conns || 0), list(x.workloads), list(x.ports)];
|
||||
})));
|
||||
grid.appendChild(dp);
|
||||
|
||||
var bursts = (d.scanner && d.scanner.bursts) || [];
|
||||
var sp = U.ui.panel({ title: t('eg.scan'), hint: t('eg.scan.hint'), cls: 'span-12', variant: 'list', help: 'term.authorized_scanner' });
|
||||
if (!bursts.length) sp.body.appendChild(U.ui.empty(t('eg.scan.none')));
|
||||
else {
|
||||
var bad = 0;
|
||||
bursts.forEach(function (b) { bad += b.bad_dst_hits || 0; });
|
||||
if (bad > 0) sp.body.appendChild(el('div', { class: 'state-error eg-scanwarn' }, el('strong', null, t('eg.scan.warn', { n: nf(bad) }))));
|
||||
sp.body.appendChild(tbl([{ label: t('eg.col.who1') }, { label: t('eg.col.when') }, { label: t('eg.col.targets'), cls: 'num' }, { label: t('eg.col.nets') }, { label: t('eg.col.ports') }, { label: t('eg.col.conns'), cls: 'num' }, { label: t('eg.col.badhits'), cls: 'num' }],
|
||||
bursts.map(function (b) {
|
||||
return [b.workload || '-', t('eg.scan.when', { a: when(b.start), b: when(b.end) }), nf(b.targets || 0), list(b.nets), list(b.ports), nf(b.conns || 0),
|
||||
el('span', { class: b.bad_dst_hits ? 'eg-warn' : '' }, nf(b.bad_dst_hits || 0))];
|
||||
})));
|
||||
}
|
||||
grid.appendChild(sp);
|
||||
root.appendChild(grid);
|
||||
}
|
||||
|
||||
function load() {
|
||||
var my = ++seq;
|
||||
var p = Object.assign({}, U.rangeParams());
|
||||
if (ctx && ctx.host && ctx.host !== 'all') p.host = ctx.host;
|
||||
U.api('/api/v1/egress', p).then(function (d) {
|
||||
if (!alive || my !== seq) return;
|
||||
data = d; paint();
|
||||
}).catch(function () {
|
||||
if (!alive || my !== seq || data) return;
|
||||
clear(root);
|
||||
var b = el('button', { type: 'button', class: 'btn' }, t('eg.retry'));
|
||||
b.addEventListener('click', load);
|
||||
root.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('eg.error')), b));
|
||||
});
|
||||
}
|
||||
|
||||
U.registerPage({
|
||||
id: 'egress', group: 'investigate', titleKey: 'eg.title',
|
||||
icon: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><rect x="3" y="5" width="12" height="14" rx="2"/><path d="M11 12h10"/><path d="M17 8l4 4-4 4"/></svg>',
|
||||
mount: function (node, cx) { root = el('div', { class: 'eg-page' }); node.appendChild(root); ctx = cx; alive = true; data = null; paint(); load(); },
|
||||
update: function (cx) { ctx = cx; load(); },
|
||||
refresh: function () { load(); },
|
||||
unmount: function () { alive = false; seq++; if (root && root.parentNode) root.parentNode.removeChild(root); root = null; data = null; }
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!boot()) {
|
||||
var tries = 0, iv = setInterval(function () { if (boot() || ++tries > 50) clearInterval(iv); }, 100);
|
||||
}
|
||||
})();
|
||||
@@ -443,6 +443,28 @@ window.URUTAU_I18N = {
|
||||
'help.term.slo.do': 'Compare the real number with the target; the gap is the error budget.',
|
||||
'help.term.error_budget': 'How many failures the SLO still allows in the period. When it reaches zero, the target is broken.',
|
||||
'help.term.error_budget.do': 'If the budget burns fast, pause risky changes and fix the cause first.',
|
||||
'help.term.second_firewall': 'A second line of defense: besides fail2ban, Urutau can itself block addresses it recognises as attackers, for a limited time.',
|
||||
'help.term.second_firewall.do': 'Start in observe mode and compare its decisions with what you expect before turning it on.',
|
||||
'help.term.observe_mode': 'Observation mode: Urutau decides who it would block and records it, but blocks nobody. A dry run.',
|
||||
'help.term.observe_mode.do': 'Watch the decisions for a few days. If they look right, switch URUTAU_ENFORCE to on.',
|
||||
'help.term.beaconing': 'Beaconing: a program that contacts the same destination at regular intervals, like a heartbeat. Normal software rarely does this so evenly; malware does, to ask for orders.',
|
||||
'help.term.beaconing.do': 'Find out which workload it is and whether the destination is something you know. If not, isolate the workload.',
|
||||
'help.term.c2': 'C2 (command and control): the server an attacker uses to give orders to infected machines. A connection to one means your machine may be taking orders.',
|
||||
'help.term.c2.do': 'Treat it as an incident: isolate the workload, then investigate.',
|
||||
'help.term.fanout': 'Fan-out or scan: one machine trying to connect to many different addresses in a short time, looking for something to attack.',
|
||||
'help.term.fanout.do': 'If it is not your own scanner, the workload may have been compromised.',
|
||||
'help.term.stratum': 'Stratum is the protocol of cryptocurrency mining pools. A server connecting to one is probably mining coins for someone else, on your electricity.',
|
||||
'help.term.stratum.do': 'Look for unknown processes using lots of CPU and remove them.',
|
||||
'help.term.dot': 'DoT (DNS over TLS): encrypted name lookups sent straight to an outside server, skipping your resolver. Malware uses it so you cannot see what it looks up.',
|
||||
'help.term.dot.do': 'Confirm the workload is allowed to do this; block outbound port 853 if not.',
|
||||
'help.term.workload': 'Workload: a program or container running on a server that makes its own network connections.',
|
||||
'help.term.workload.do': 'Compare each workload with what it should be doing; a database talking to the internet is suspicious.',
|
||||
'help.term.authorized_scanner': 'Authorised scanner: a workload you run on purpose to scan networks. Its mass connections are summarised instead of raised as alerts.',
|
||||
'help.term.authorized_scanner.do': 'Make sure it only aims at targets you own or may test.',
|
||||
'help.term.ban_ttl': 'Block duration (TTL): how long an address stays blocked before being released. Repeat offenders get longer blocks.',
|
||||
'help.term.ban_ttl.do': 'Short blocks are safer against mistakes; long ones stop persistent attackers.',
|
||||
'help.term.new_geo': 'New country: the workload connected to a country it had not reached before in this window.',
|
||||
'help.term.new_geo.do': 'Check whether the destination is a service you use.',
|
||||
'help.term.error_class.app': 'Errors caused by your own application (5xx coming from the app).',
|
||||
'help.term.error_class.app.do': 'These are yours to fix: read the application logs.',
|
||||
'help.term.error_class.proxy': 'Errors produced by the reverse proxy itself (bad gateway, timeout, no backend).',
|
||||
@@ -915,6 +937,28 @@ window.URUTAU_I18N = {
|
||||
'help.term.slo.do': 'Compare o número real com a meta; a diferença é o orçamento de erro.',
|
||||
'help.term.error_budget': 'Quantas falhas o SLO ainda permite no período. Quando chega a zero, a meta foi quebrada.',
|
||||
'help.term.error_budget.do': 'Se o orçamento queima rápido, pause mudanças arriscadas e corrija a causa primeiro.',
|
||||
'help.term.second_firewall': 'Uma segunda linha de defesa: além do fail2ban, o próprio Urutau pode bloquear endereços que reconhece como atacantes, por tempo limitado.',
|
||||
'help.term.second_firewall.do': 'Comece no modo observação e compare as decisões com o que você espera antes de ligar.',
|
||||
'help.term.observe_mode': 'Modo observação: o Urutau decide quem bloquearia e registra, mas não bloqueia ninguém. Um ensaio.',
|
||||
'help.term.observe_mode.do': 'Acompanhe as decisões por alguns dias. Se estiverem certas, mude URUTAU_ENFORCE para on.',
|
||||
'help.term.beaconing': 'Beaconing (sinal periódico): um programa que contata o mesmo destino em intervalos regulares, como um batimento. Software normal raramente é tão regular; malware faz isso para pedir ordens.',
|
||||
'help.term.beaconing.do': 'Descubra qual workload é e se você conhece o destino. Se não conhece, isole o workload.',
|
||||
'help.term.c2': 'C2 (comando e controle): o servidor que um atacante usa para dar ordens às máquinas infectadas. Uma conexão com ele indica que a sua máquina pode estar recebendo ordens.',
|
||||
'help.term.c2.do': 'Trate como incidente: isole o workload e investigue.',
|
||||
'help.term.fanout': 'Fan-out ou varredura: uma máquina tentando conectar a muitos endereços diferentes em pouco tempo, procurando algo para atacar.',
|
||||
'help.term.fanout.do': 'Se não for o seu scanner, o workload pode ter sido comprometido.',
|
||||
'help.term.stratum': 'Stratum é o protocolo dos grupos de mineração de criptomoedas. Um servidor conectado a um deles provavelmente está minerando moedas para outra pessoa, gastando a sua energia.',
|
||||
'help.term.stratum.do': 'Procure processos desconhecidos gastando muita CPU e remova-os.',
|
||||
'help.term.dot': 'DoT (DNS sobre TLS): consultas de nomes criptografadas, enviadas direto a um servidor de fora, sem passar pelo seu resolvedor. Malware usa para você não ver o que ele consulta.',
|
||||
'help.term.dot.do': 'Confirme se o workload tem permissão para isso; bloqueie a porta 853 de saída se não tiver.',
|
||||
'help.term.workload': 'Workload (carga de trabalho): um programa ou contêiner rodando no servidor que faz as próprias conexões de rede.',
|
||||
'help.term.workload.do': 'Compare cada workload com o que ele deveria fazer; um banco de dados falando com a internet é suspeito.',
|
||||
'help.term.authorized_scanner': 'Scanner autorizado: um workload que você mantém de propósito para varrer redes. As conexões em massa dele são resumidas, em vez de virar alerta.',
|
||||
'help.term.authorized_scanner.do': 'Garanta que ele só mire alvos seus ou que você pode testar.',
|
||||
'help.term.ban_ttl': 'Duração do bloqueio (TTL): por quanto tempo o endereço fica bloqueado antes de ser liberado. Reincidentes recebem bloqueios mais longos.',
|
||||
'help.term.ban_ttl.do': 'Bloqueios curtos são mais seguros contra enganos; longos barram atacantes persistentes.',
|
||||
'help.term.new_geo': 'País novo: o workload conectou a um país que ainda não tinha alcançado nesta janela.',
|
||||
'help.term.new_geo.do': 'Confira se o destino é um serviço que você usa.',
|
||||
'help.term.error_class.app': 'Erros causados pela sua própria aplicação (5xx vindos do app).',
|
||||
'help.term.error_class.app.do': 'São seus para corrigir: leia os logs da aplicação.',
|
||||
'help.term.error_class.proxy': 'Erros produzidos pelo próprio proxy reverso (bad gateway, timeout, sem backend).',
|
||||
|
||||
@@ -67,6 +67,10 @@
|
||||
{
|
||||
"name": "reports",
|
||||
"css": true
|
||||
},
|
||||
{
|
||||
"name": "egress",
|
||||
"css": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -2,7 +2,10 @@
|
||||
@media print it fills A4 pages and the shell chrome disappears. */
|
||||
.rpt { min-width: 0; }
|
||||
.rpt-box { display: flex; flex-direction: column; gap: var(--s-3, 12px); min-width: 0; }
|
||||
.rpt-bar { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
.rpt-bar { display: flex; flex-wrap: wrap; gap: 8px; align-items: flex-end; }
|
||||
.rpt-opt { display: flex; flex-direction: column; gap: 2px; font-size: .75rem; color: var(--ink-muted); }
|
||||
.rpt-sel { min-height: 34px; padding: 4px 8px; border: 1px solid var(--line); border-radius: var(--radius-sm, 7px); background: var(--surface-raised, transparent); color: var(--ink); font: inherit; }
|
||||
.rpt-hint { flex-basis: 100%; margin: 0; font-size: .75rem; color: var(--ink-muted); }
|
||||
.rpt-sheet { background: var(--surface-panel); border: 1px solid var(--line); border-radius: var(--radius, 10px); padding: clamp(14px, 3vw, 32px); display: flex; flex-direction: column; gap: 22px; min-width: 0; color: var(--ink); }
|
||||
.rpt-cover { border-bottom: 2px solid var(--accent); padding-bottom: 14px; }
|
||||
.rpt-kicker { margin: 0; font-size: .75rem; letter-spacing: .08em; text-transform: uppercase; color: var(--ink-muted); }
|
||||
|
||||
@@ -26,6 +26,12 @@
|
||||
'rpt.print': 'Print',
|
||||
'rpt.json': 'Export JSON',
|
||||
'rpt.csv': 'Export CSV',
|
||||
'rpt.dl': 'Download report (HTML)',
|
||||
'rpt.pdf': 'Print / PDF',
|
||||
'rpt.opt.period': 'Report period',
|
||||
'rpt.opt.panel': 'Same as the dashboard',
|
||||
'rpt.opt.lang': 'Report language',
|
||||
'rpt.opt.hint': 'The HTML report is one self-contained file, ready to print on A4. Open it and use Print to save as PDF.',
|
||||
'rpt.cover.kicker': 'Executive report',
|
||||
'rpt.cover.title': 'Security report',
|
||||
'rpt.cover.period': 'Period',
|
||||
@@ -97,6 +103,12 @@
|
||||
'rpt.print': 'Imprimir',
|
||||
'rpt.json': 'Exportar JSON',
|
||||
'rpt.csv': 'Exportar CSV',
|
||||
'rpt.dl': 'Baixar relatório (HTML)',
|
||||
'rpt.pdf': 'Imprimir / PDF',
|
||||
'rpt.opt.period': 'Período do relatório',
|
||||
'rpt.opt.panel': 'Igual ao do painel',
|
||||
'rpt.opt.lang': 'Idioma do relatório',
|
||||
'rpt.opt.hint': 'O relatório HTML é um arquivo único, pronto para imprimir em A4. Abra e use Imprimir para salvar em PDF.',
|
||||
'rpt.cover.kicker': 'Relatório executivo',
|
||||
'rpt.cover.title': 'Relatório de segurança',
|
||||
'rpt.cover.period': 'Período',
|
||||
@@ -231,8 +243,34 @@
|
||||
return rows.map(function (r) { return r.map(csvCell).join(','); }).join('\r\n') + '\r\n';
|
||||
}
|
||||
|
||||
var opt = { range: '', lang: '' };
|
||||
function htmlUrl(inline) {
|
||||
var p = params(ctx0);
|
||||
p.format = 'html';
|
||||
if (opt.range) { delete p.from; delete p.to; p.range = opt.range; }
|
||||
p.lang = opt.lang || (ctx0 && ctx0.lang === 'en' ? 'en' : 'pt-BR');
|
||||
if (inline) p.inline = '1';
|
||||
return '/api/v1/report?' + new URLSearchParams(p).toString();
|
||||
}
|
||||
function select(label, key, choices) {
|
||||
var sel = U.el('select', { class: 'rpt-sel', 'aria-label': label });
|
||||
choices.forEach(function (c) { var o = U.el('option', { value: c[0] }, c[1]); if (opt[key] === c[0]) o.selected = true; sel.appendChild(o); });
|
||||
sel.addEventListener('change', function () { opt[key] = sel.value; });
|
||||
return h('label', 'rpt-opt', h('span', null, label), sel);
|
||||
}
|
||||
function toolbar() {
|
||||
var bar = h('div', 'rpt-bar');
|
||||
var dl = U.el('button', { type: 'button', class: 'btn' }, t('rpt.dl'));
|
||||
dl.addEventListener('click', function () {
|
||||
var a = document.createElement('a');
|
||||
a.href = htmlUrl(false); a.download = '';
|
||||
document.body.appendChild(a); a.click(); document.body.removeChild(a);
|
||||
});
|
||||
var pr = U.el('button', { type: 'button', class: 'btn' }, t('rpt.pdf'));
|
||||
pr.addEventListener('click', function () { window.open(htmlUrl(true), '_blank', 'noopener'); });
|
||||
bar.appendChild(select(t('rpt.opt.period'), 'range', [['', t('rpt.opt.panel')], ['24h', '24h'], ['7d', '7d'], ['30d', '30d'], ['90d', '90d']]));
|
||||
bar.appendChild(select(t('rpt.opt.lang'), 'lang', [['', ctx0 && ctx0.lang === 'en' ? 'English' : 'Português'], ['pt-BR', 'Português'], ['en', 'English']]));
|
||||
bar.appendChild(dl); bar.appendChild(pr);
|
||||
var b1 = U.el('button', { type: 'button', class: 'btn' }, t('rpt.print'));
|
||||
b1.addEventListener('click', function () { window.print(); });
|
||||
var b2 = U.el('button', { type: 'button', class: 'btn' }, t('rpt.json'));
|
||||
@@ -240,6 +278,7 @@
|
||||
var b3 = U.el('button', { type: 'button', class: 'btn' }, t('rpt.csv'));
|
||||
b3.addEventListener('click', function () { if (data) save(stamp('csv'), 'text/csv;charset=utf-8', '' + toCSV(data)); });
|
||||
bar.appendChild(b1); bar.appendChild(b2); bar.appendChild(b3);
|
||||
bar.appendChild(h('p', 'rpt-hint', t('rpt.opt.hint')));
|
||||
return bar;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
package store
|
||||
|
||||
// KnownHostile reports, cheaply, whether this instance has seen the address
|
||||
// attack it: banned by a jail or scored hostile. Used by the egress analysis
|
||||
// to flag outbound connections to an attacker.
|
||||
func (s *Store) KnownHostile(ip string) bool {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
r := s.ips[KeyOf(ip)]
|
||||
return r != nil && (len(r.Jails) > 0 || r.Score >= 50)
|
||||
}
|
||||
@@ -254,6 +254,7 @@ type Store struct {
|
||||
ids atomic.Uint64 // event ids, increasing
|
||||
elog *evlog.Log
|
||||
class Classifier
|
||||
hook IngestHook
|
||||
ipx ipxCache
|
||||
study studyCache
|
||||
sizes map[string]map[int64]uint32 // per domain: typical 404 / SPA body sizes
|
||||
@@ -263,6 +264,13 @@ type Store struct {
|
||||
// event (wired to internal/intel); nil or empty results are fine.
|
||||
type Classifier func(core.Event) (fam string, tech []string, marker string)
|
||||
|
||||
// IngestHook sees every ingested event with its attack family, after the store
|
||||
// lock is released. It must be cheap and must never block.
|
||||
type IngestHook func(ev core.Event, fam string)
|
||||
|
||||
// SetIngestHook installs the hook; call it before events flow.
|
||||
func (s *Store) SetIngestHook(h IngestHook) { s.hook = h }
|
||||
|
||||
// SetClassifier installs the classifier.
|
||||
func (s *Store) SetClassifier(c Classifier) { s.class = c }
|
||||
|
||||
@@ -545,6 +553,9 @@ func (s *Store) Ingest(ev core.Event) {
|
||||
if record {
|
||||
s.logEvent(fe)
|
||||
}
|
||||
if s.hook != nil {
|
||||
s.hook(ev, fam)
|
||||
}
|
||||
if feed && now.Unix()-ts < 300 {
|
||||
s.broadcast(fe)
|
||||
}
|
||||
|
||||
@@ -56,7 +56,7 @@ for (let i = 0; i < 50; i++) { try { if ((await fetch(base + '/api/health')).ok)
|
||||
|
||||
let ip = bad[0];
|
||||
try { const j = await (await fetch(base + '/api/v1/ips?per=1')).json(); if (j.items?.[0]) ip = j.items[0].ip; } catch { /* default */ }
|
||||
const routes = ['overview', 'threats', 'geo', 'live', 'replay', 'traffic', 'ips', 'sources', 'ip/' + ip, 'sessions', 'campaigns', 'search', 'mitre', 'defense', 'evolution', 'concentration', 'survival', 'errors', 'slo', 'protocol', 'integrity', 'reports'];
|
||||
const routes = ['overview', 'threats', 'geo', 'live', 'replay', 'traffic', 'ips', 'sources', 'ip/' + ip, 'sessions', 'campaigns', 'search', 'mitre', 'defense', 'egress', 'evolution', 'concentration', 'survival', 'errors', 'slo', 'protocol', 'integrity', 'reports'];
|
||||
const sizes = [[1440, 900], [1024, 768], [768, 1024], [390, 844]];
|
||||
const failures = [];
|
||||
const browser = await puppeteer.launch({ executablePath: chrome, args: ['--no-sandbox'] });
|
||||
|
||||
Reference in new issue
Block a user