Compare commits

...
8 Commits
Author SHA1 Message Date
lucasrguerra 19bec553f4 Merge pull request 'Urutau 2.3.0: own traffic recorded, firewall telemetry, fast long-range studies' (#5) from release/2.3.0 into main
CI / Format and vet (push) Successful in 28s
CI / Tests (Linux, race detector) (push) Successful in 1m18s
CI / Dependency audit (push) Successful in 22s
Release / Plan (reuse the published image?) (push) Successful in 7s
Release / ci (push) Skipped
Release / Build hub image (amd64) (push) Skipped
Release / Build probe image (amd64) (push) Skipped
Release / Build hub image (arm64) (push) Skipped
Release / Build probe image (arm64) (push) Skipped
Release / Publish tags (hub) (push) Successful in 17s
Release / Publish tags (probe) (push) Successful in 15s
Release / Gitea release (push) Successful in 4s
2026-11-23 12:19:14 +00:00
Lucas Rayan 5e472bc6c4 docs(changelog): 2.3.0 links in pt-BR
CI / Format and vet (pull_request) Successful in 1m6s
CI / Tests (Linux, race detector) (pull_request) Successful in 1m58s
CI / Dependency audit (pull_request) Successful in 19s
2026-11-23 09:15:29 -03:00
Lucas Rayan 7f9db226db chore(release): 2.3.0 2026-11-23 09:15:18 -03:00
Lucas Rayan f9a6783a1f Merge branch 'perf/long-range-studies' into release/2.3.0
# Conflicts:
#	CHANGELOG.md
2026-11-23 09:13:32 -03:00
Lucas RayanandClaude Sonnet 5.5 4ca9c7bf0c perf: serve long-range studies from a decoded closed-day cache
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 09:13:02 -03:00
Lucas Rayan 554ea1340c Merge branch 'feat/inbound-firewall-telemetry' into release/2.3.0
# Conflicts:
#	CHANGELOG.md
#	CHANGELOG.pt-BR.md
2026-11-23 09:09:54 -03:00
Lucas RayanandClaude Sonnet 5.5 aefdcea8d2 feat(ingress): firewall telemetry of inbound attempts (host kit --ingress)
Observation-only nftables table (prerouting -150, counters and a
rate-limited log, never drops or modifies), a per-minute counters file,
probe sources ingress and ingresscnt, a per-host hourly aggregate in the
hub (exact totals, sampled ports/ASNs/countries, banned share by the
hub's own ban state, no ban feedback loop), GET /api/v1/ingress, a
Defense section, doctor check, docs EN/pt-BR and tests.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 09:09:16 -03:00
Lucas RayanandClaude Sonnet 5.5 3511a7141c feat: record own and trusted web traffic in its own classes instead of dropping it
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 09:03:57 -03:00
60 changed files with 2973 additions and 114 deletions

No files matched your search

+16 -1
View File
@@ -6,6 +6,20 @@ Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versio
## [Unreleased]
## [2.3.0] - 2026-11-23
### Added
- Firewall telemetry (inbound attempts): the application logs cannot see connection attempts to ports where nothing listens, nor packets from addresses that are already banned (the firewall drops them silently), so the panel understated the real scale and SSH attacks seemed to fall only because bans work. New host kit option `install.sh --ingress` adds an observation-only nftables table (`inet urutau_ingress`, prerouting priority -150, before Docker's DNAT; counters and a rate-limited log, it never drops, accepts, marks or rewrites anything) and a timer that writes exact counters to `/var/log/urutau/ingress.counters`, plus a sample of the attempts in `/var/log/urutau/ingress.log`. The probe tails both (`URUTAU_INGRESS_LOG`, `URUTAU_INGRESS_COUNTERS`), the hub aggregates per host in hourly buckets for 30 days, and Defense gets a "Firewall: inbound attempts" section: exact totals and attempts per hour, share to closed ports, share from currently banned sources (estimated from the sample), and top ports, networks and countries labelled as sampled. New endpoint `GET /api/v1/ingress`; `urutau doctor` reports whether the source is present and fresh. The attempts are telemetry only: they never become events or evidence, so there is no ban feedback loop. To upgrade: update the hub and the probes, then on each host run `sudo sh deploy/host/install.sh --ingress` (add `--probe` and `--enforce` as that host already uses). The sources show as `waiting` until then. A cloud provider firewall (for example an Oracle Cloud security list) blocks some ports before the host, so the metric is what reaches the host.
### Changed
- Own and trusted traffic is recorded instead of dropped. Web requests from `URUTAU_TRUSTED` (class `trusted`) and from the `URUTAU_IGNORE` ranges, private networks by default (class `internal`), used to vanish at ingestion, which hid about half of the real requests on a busy host (the other server, a CI runner, the Docker gateway). They are now counted in aggregates only (no event record each, kept in the snapshot) and never score an IP or enter threats, campaigns, sessions, maps, the blocklist, ban evidence, egress logic or visitor analytics. API: `totals.trusted`, `totals.internal`, `totals.requests_all` (`requests` plus both classes), `totals.counts.trusted` and `.internal`, and `own` in `/api/v1/summary` (status classes, timeline `series`, `origins`, `domains`, `paths`). The Traffic page has a new section "Own infrastructure and trusted origins". Probes need no change: the hub classifies. Tests `TestOwnTrafficIsCountedNeverAnalysed` and `TestOwnTrafficThroughFeed`.
### Fixed
- Long-range studies (15 and 30 days) no longer time out: with about 25,000 events a day over 30 days, period, report, campaigns, funnel and metrics took 6 to 19 s and came back `truncated` with partial families, techniques and campaigns. Closed days of the event registry are now decoded once and kept in memory (96 MB cap, invalidated by file size and modification time), the live day is read from the file, sessions are built in parallel and shared by period, funnel and metrics, and path normalisation is memoised. On the synthetic 30-day set (750,000 events, 2 hosts) all three views together went from 7.5 s cold and 5.1 s warm (about 16 s with a 256 MiB memory limit, truncated) to 3.7 s cold and 1.5 s warm under GOMEMLIMIT 256MiB, not truncated, about 200 MB heap. The dashboard shows a note when a study really hits a limit. Top targets with equal counts are now ordered by host too, so results are deterministic. Tests `TestDayCacheEqualsFullScan`, `TestDayCacheInvalidatesOnChange` and `BenchmarkStudy30d`.
## [2.2.2] - 2026-11-19
### Fixed
@@ -343,7 +357,8 @@ First release.
- Hostile log content is limited in length and escaped on output; the dashboard ships a strict Content-Security-Policy and the usual hardening headers.
- `--insecure-no-auth` is refused unless the bind address is loopback.
[Unreleased]: https://git.lucasrguerra.dev.br/ciberfauna/urutau/compare/v2.1.1...HEAD
[Unreleased]: https://git.lucasrguerra.dev.br/ciberfauna/urutau/compare/v2.3.0...HEAD
[2.3.0]: https://git.lucasrguerra.dev.br/ciberfauna/urutau/compare/v2.2.2...v2.3.0
[2.1.1]: https://git.lucasrguerra.dev.br/ciberfauna/urutau/compare/v2.1.0...v2.1.1
[2.1.0]: https://git.lucasrguerra.dev.br/ciberfauna/urutau/compare/v2.0.0...v2.1.0
[2.0.0]: https://git.lucasrguerra.dev.br/ciberfauna/urutau/compare/v1.6.0...v2.0.0
+17 -2
View File
@@ -4,7 +4,21 @@
Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/); versionamento segue SemVer.
## [Não lançado]
## [Unreleased]
## [2.3.0] - 2026-11-23
### Adicionado
- Telemetria do firewall (tentativas de entrada): os logs das aplicações não enxergam tentativas de conexão a portas em que nada escuta, nem pacotes de endereços já banidos (o firewall os descarta em silêncio), então o painel subestimava a escala real e os ataques ao SSH pareciam diminuir só porque os bans funcionam. A nova opção do kit do host `install.sh --ingress` instala uma tabela nftables só de observação (`inet urutau_ingress`, prerouting com prioridade -150, antes do DNAT do Docker; contadores e um log com limite de ritmo, nunca descarta, aceita, marca nem reescreve nada) e um timer que grava contadores exatos em `/var/log/urutau/ingress.counters`, além de uma amostra das tentativas em `/var/log/urutau/ingress.log`. A sonda acompanha os dois (`URUTAU_INGRESS_LOG`, `URUTAU_INGRESS_COUNTERS`), o hub agrega por host em baldes por hora durante 30 dias, e a Defesa ganha a seção "Firewall: tentativas de entrada": totais exatos e tentativas por hora, parcela para portas fechadas, parcela de origens banidas no momento (estimada pela amostra) e portas, redes e países mais frequentes rotulados como amostrados. Novo endpoint `GET /api/v1/ingress`; o `urutau doctor` informa se a fonte está presente e fresca. As tentativas são só telemetria: nunca viram eventos nem evidência, então não há laço de retroalimentação de bans. Para atualizar: atualize o hub e as sondas e, em cada host, rode `sudo sh deploy/host/install.sh --ingress` (some `--probe` e `--enforce` conforme o host já usa). As fontes ficam em `waiting` até lá. O firewall do provedor de nuvem (por exemplo uma lista de segurança da Oracle Cloud) barra algumas portas antes do host, então a métrica é o que chega ao host.
### Alterado
- O tráfego próprio e confiável é registrado em vez de descartado. As requisições web de `URUTAU_TRUSTED` (classe `trusted`) e das faixas de `URUTAU_IGNORE`, redes privadas por padrão (classe `internal`), sumiam na ingestão, o que escondia cerca de metade das requisições reais de um host movimentado (o outro servidor, um runner de CI, o gateway do Docker). Agora são contadas só em agregados (sem registro de evento cada, mantidas no snapshot) e nunca pontuam um IP nem entram em ameaças, campanhas, sessões, mapas, lista de bloqueio, evidência de banimento, lógica de egress ou análise de visitantes. API: `totals.trusted`, `totals.internal`, `totals.requests_all` (`requests` mais as duas classes), `totals.counts.trusted` e `.internal`, e `own` em `/api/v1/summary` (classes de status, `series` da linha do tempo, `origins`, `domains`, `paths`). A página Tráfego ganhou a seção "Infraestrutura própria e origens confiáveis". As sondas não precisam mudar: o hub classifica. Testes `TestOwnTrafficIsCountedNeverAnalysed` e `TestOwnTrafficThroughFeed`.
### Corrigido
- Estudos de longo prazo (15 e 30 dias) não estouram mais o tempo: com cerca de 25.000 eventos por dia em 30 dias, período, relatório, campanhas, funil e métricas levavam de 6 a 19 s e voltavam `truncated` com famílias, técnicas e campanhas parciais. Os dias fechados do registro de eventos agora são decodificados uma vez e mantidos na memória (teto de 96 MB, invalidados pelo tamanho e data de modificação do arquivo), o dia atual é lido do arquivo, as sessões são montadas em paralelo e compartilhadas por período, funil e métricas, e a normalização de caminhos é memorizada. No conjunto sintético de 30 dias (750.000 eventos, 2 hosts), as três visões juntas foram de 7,5 s a frio e 5,1 s a quente (cerca de 16 s com limite de memória de 256 MiB, truncado) para 3,7 s a frio e 1,5 s a quente sob GOMEMLIMIT 256MiB, sem truncar, cerca de 200 MB de heap. O painel mostra um aviso quando um estudo realmente atinge um limite. Os alvos mais atacados com contagem igual agora também são ordenados por host, então o resultado é determinístico. Testes `TestDayCacheEqualsFullScan`, `TestDayCacheInvalidatesOnChange` e `BenchmarkStudy30d`.
## [2.2.2] - 2026-11-19
@@ -343,7 +357,8 @@ Primeira versão.
- O conteúdo hostil dos logs tem tamanho limitado e é escapado na saída; o dashboard envia uma Content-Security-Policy estrita e os cabeçalhos de endurecimento usuais.
- `--insecure-no-auth` é recusado a menos que o endereço de bind seja loopback.
[Não lançado]: https://git.lucasrguerra.dev.br/ciberfauna/urutau/compare/v2.1.1...HEAD
[Não lançado]: https://git.lucasrguerra.dev.br/ciberfauna/urutau/compare/v2.3.0...HEAD
[2.3.0]: https://git.lucasrguerra.dev.br/ciberfauna/urutau/compare/v2.2.2...v2.3.0
[2.1.1]: https://git.lucasrguerra.dev.br/ciberfauna/urutau/compare/v2.1.0...v2.1.1
[2.1.0]: https://git.lucasrguerra.dev.br/ciberfauna/urutau/compare/v2.0.0...v2.1.0
[2.0.0]: https://git.lucasrguerra.dev.br/ciberfauna/urutau/compare/v1.6.0...v2.0.0
+8
View File
@@ -0,0 +1,8 @@
# Urutau: kernel log lines of the inbound observation table (a sample of the new
# connection attempts that reach the host) go to their own file and stay out of
# the general syslog. URUTAU-INO: is a port the host serves, URUTAU-IN: is not.
if ($syslogfacility-text == "kern" and ($msg contains "URUTAU-IN: " or $msg contains "URUTAU-INO: ")) then {
action(type="omfile" file="/var/log/urutau/ingress.log" template="RSYSLOG_FileFormat"
fileOwner="syslog" fileGroup="adm" fileCreateMode="0640")
stop
}
+28 -1
View File
@@ -4,6 +4,7 @@
#
# 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 --ingress # also the inbound observation (firewall telemetry)
# sudo sh install.sh --probe # a probe host: the kit above, no hub on this machine
# sudo sh install.sh --probe --enforce # probe host that also applies the hub's bans
# sudo sh install.sh --remove # undo everything
@@ -13,6 +14,13 @@
# prepares /var/log/urutau-enforce (owned by the probe's uid) so the probe can
# append the hub's decisions; the fail2ban jail still needs --enforce.
#
# --ingress adds an nftables table that only counts, and logs a sample of, the new
# inbound connection attempts reaching the host (it never drops or changes a
# packet), a timer that writes the exact counters to /var/log/urutau/ingress.counters
# and an rsyslog rule for /var/log/urutau/ingress.log. It is separate from
# --enforce on purpose (observing is not blocking); combine them freely, and
# re-run without it to leave it as is, or use --remove to undo.
#
# 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
@@ -21,11 +29,13 @@ uid=${URUTAU_UID:-10001}
probe=0
enforce=0
ingress=0
remove=0
for arg in "$@"; do
case "$arg" in
--probe) probe=1 ;;
--enforce) enforce=1 ;;
--ingress) ingress=1 ;;
--remove) remove=1 ;;
-h | --help) awk 'NR > 1 { if (!/^#/) exit; sub(/^# ?/, ""); print }' "$0"; exit 0 ;;
*) echo "unknown option: $arg (see --help)" >&2; exit 2 ;;
@@ -35,7 +45,9 @@ done
[ "$(id -u)" = 0 ] || { echo "run as root" >&2; exit 1; }
if [ "$remove" = 1 ]; then
systemctl disable --now urutau-egress.service urutau-containers-watch.service urutau-containers-map.timer urutau-logrotate.timer urutau-unban.path 2>/dev/null || true
systemctl disable --now urutau-ingress.service urutau-ingress-tick.timer urutau-egress.service urutau-containers-watch.service urutau-containers-map.timer urutau-logrotate.timer urutau-unban.path 2>/dev/null || true
rm -f /etc/systemd/system/urutau-ingress.service /etc/systemd/system/urutau-ingress-tick.service \
/etc/systemd/system/urutau-ingress-tick.timer /usr/local/sbin/urutau-ingress-tick /etc/rsyslog.d/42-urutau-ingress.conf
rm -f /etc/systemd/system/urutau-egress.service /etc/systemd/system/urutau-containers-map.service \
/etc/systemd/system/urutau-containers-map.timer /usr/local/sbin/urutau-containers-map \
/etc/systemd/system/urutau-containers-watch.service /usr/local/sbin/urutau-containers-watch \
@@ -75,6 +87,21 @@ systemctl start urutau-containers-map.service urutau-containers-map.timer
systemctl restart urutau-containers-watch.service
echo "egress logging on $wan: /var/log/urutau/egress.log, map: /var/log/urutau/containers.map"
if [ "$ingress" = 1 ]; then
sed "s/@WAN@/$wan/g" "$here/urutau-ingress.nft" > /etc/urutau/ingress.nft
nft -c -f /etc/urutau/ingress.nft
install -m 0644 "$here/42-urutau-ingress.conf" /etc/rsyslog.d/42-urutau-ingress.conf
install -m 0755 "$here/urutau-ingress-tick" /usr/local/sbin/urutau-ingress-tick
install -m 0644 "$here/urutau-ingress.service" "$here/urutau-ingress-tick.service" "$here/urutau-ingress-tick.timer" /etc/systemd/system/
[ -e /var/log/urutau/ingress.counters ] || install -m 0640 -o syslog -g adm /dev/null /var/log/urutau/ingress.counters 2>/dev/null || install -m 0640 -g adm /dev/null /var/log/urutau/ingress.counters
systemctl daemon-reload
systemctl restart rsyslog
systemctl enable urutau-ingress.service urutau-ingress-tick.timer >/dev/null
systemctl restart urutau-ingress.service
systemctl start urutau-ingress-tick.timer
echo "inbound observation on $wan: /var/log/urutau/ingress.log (sample), /var/log/urutau/ingress.counters (exact)"
fi
if [ "$probe" = 1 ] && [ "$enforce" = 0 ]; then
# The probe appends the hub's decisions here even when the jail is not
# installed yet, so the files must exist and belong to the probe's uid.
+28
View File
@@ -0,0 +1,28 @@
#!/bin/sh
# Urutau: once a minute, (1) refresh the set of ports this host serves, (2) append
# the exact counters of the inbound observation table to ingress.counters.
#
# One line per run, cumulative since the table was loaded (the hub takes the
# difference between two lines; a drop means the table was reloaded):
# ts=1767225600 total=120 tcp=100 udp=15 icmp=5 open=30
# Read-only with respect to the network: it only reads counters and fills a set.
set -eu
t=inet
tab=urutau_ingress
out=${URUTAU_INGRESS_COUNTERS:-/var/log/urutau/ingress.counters}
nft list table "$t" "$tab" >/dev/null 2>&1 || exit 0
# Ports this host serves, so the chain can tell open from closed.
{
echo "flush set $t $tab open"
ss -Hlnt | awk '{print $4}' | sed -n 's/.*:\([0-9][0-9]*\)$/tcp . \1/p'
ss -Hlnu | awk '{print $4}' | sed -n 's/.*:\([0-9][0-9]*\)$/udp . \1/p'
} | sort -u | awk 'NR==1 {print; next} {e = e (e ? ", " : "") $0} END {if (e) print "add element inet urutau_ingress open { " e " }"}' | nft -f - || true
nft list counters table "$t" "$tab" | awk -v ts="$(date +%s)" '
/^[ \t]*counter / { name = $2 }
/^[ \t]*packets / && name != "" { v[name] = $2; name = "" }
END {
printf "ts=%s total=%d tcp=%d udp=%d icmp=%d open=%d\n", ts, v["in_total"], v["in_tcp"], v["in_udp"], v["in_icmp"], v["in_open"]
}' >> "$out"
+7
View File
@@ -0,0 +1,7 @@
[Unit]
Description=Urutau: inbound counters and served ports
After=urutau-ingress.service
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/urutau-ingress-tick
+10
View File
@@ -0,0 +1,10 @@
[Unit]
Description=Urutau: inbound counters every minute
[Timer]
OnBootSec=60s
OnUnitActiveSec=60s
AccuracySec=1s
[Install]
WantedBy=timers.target
+85
View File
@@ -0,0 +1,85 @@
#!/usr/sbin/nft -f
# Urutau: OBSERVES new inbound connection attempts that reach this host from
# outside (the "firewall" telemetry): TCP SYN without ACK, UDP and ICMP echo
# requests. Nothing else.
#
# It never drops, accepts, marks or rewrites a packet: every statement here is a
# counter, a rate limit that only gates the log statement, or a jump. Policy is
# accept and the chain does not touch established traffic.
#
# The chain hooks at prerouting priority -150: after the conntrack lookup, before
# Docker's DNAT (-100). Packets to DNAT'ed container ports and packets from
# sources that fail2ban or Urutau ban a moment later (and drop in INPUT or
# FORWARD, far past this hook) are all seen here.
#
# EXACT totals come from the named counters (read once a minute by
# urutau-ingress-tick, appended to /var/log/urutau/ingress.counters). The log
# lines are only a SAMPLE for details (ports, origins); the rate limits below
# decide how big the sample is. @WAN@ is replaced by the uplink interface.
#
# Not counted: anything that does not arrive on the uplink (loopback, Docker
# bridges, VPN), anything not addressed to this host, and sources that are
# loopback, private, link-local, CGNAT, multicast or one of this host's own
# addresses.
table inet urutau_ingress
delete table inet urutau_ingress
table inet urutau_ingress {
# Ports this host serves (listening sockets, including the ones Docker
# publishes), refreshed every minute by urutau-ingress-tick.
set open { type inet_proto . inet_service; }
counter in_total { }
counter in_tcp { }
counter in_udp { }
counter in_icmp { }
counter in_open { }
chain observe {
type filter hook prerouting priority -150; policy accept;
iifname != "@WAN@" return
fib daddr type != local return
fib saddr . iif type local return
ip saddr { 0.0.0.0/8, 10.0.0.0/8, 100.64.0.0/10, 127.0.0.0/8, 169.254.0.0/16, 172.16.0.0/12, 192.168.0.0/16, 224.0.0.0/3 } return
ip6 saddr { ::/128, ::1/128, fc00::/7, fe80::/10, ff00::/8 } return
meta l4proto tcp tcp flags & (syn | ack) == syn jump new_tcp
meta l4proto udp ct state new jump new_udp
meta l4proto icmp icmp type echo-request jump new_icmp
meta l4proto icmpv6 icmpv6 type echo-request jump new_icmp
}
chain new_tcp {
counter name in_total
counter name in_tcp
jump classify
}
chain new_udp {
counter name in_total
counter name in_udp
jump classify
}
chain new_icmp {
counter name in_total
counter name in_icmp
limit rate 2/second burst 10 packets log prefix "URUTAU-IN: " level info
}
# open vs closed: the open ones are counted, closed = (tcp + udp) - open,
# computed by urutau-ingress-tick, so the chain needs no negated lookup.
chain classify {
meta l4proto . th dport @open counter name in_open jump sample_open
meta l4proto . th dport @open return
jump sample_closed
}
# the sample: a ceiling that only gates the log statement
chain sample_open {
limit rate 5/second burst 25 packets log prefix "URUTAU-INO: " level info
}
chain sample_closed {
limit rate 10/second burst 50 packets log prefix "URUTAU-IN: " level info
}
}
+14
View File
@@ -0,0 +1,14 @@
[Unit]
Description=Urutau: inbound attempts observation (nftables, counters and log only)
After=network-online.target docker.service
Wants=network-online.target
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/sbin/nft -f /etc/urutau/ingress.nft
ExecStartPost=-/usr/local/sbin/urutau-ingress-tick
ExecStop=/usr/sbin/nft delete table inet urutau_ingress
[Install]
WantedBy=multi-user.target
+1 -1
View File
@@ -1,4 +1,4 @@
/var/log/urutau/egress.log /var/log/urutau/probe.log {
/var/log/urutau/egress.log /var/log/urutau/probe.log /var/log/urutau/ingress.log /var/log/urutau/ingress.counters {
daily
rotate 7
maxsize 200M
+3
View File
@@ -29,6 +29,9 @@ services:
URUTAU_FAIL2BAN_LOG: ${URUTAU_FAIL2BAN_LOG-/logs/host/fail2ban.log}
URUTAU_PROBE_LOG: ${URUTAU_PROBE_LOG-/logs/host/probe.log}
URUTAU_EGRESS_LOG: ${URUTAU_EGRESS_LOG-/logs/host/egress.log}
# Firewall telemetry (host kit --ingress): sampled attempts and exact counters.
URUTAU_INGRESS_LOG: ${URUTAU_INGRESS_LOG-/logs/host/ingress.log}
URUTAU_INGRESS_COUNTERS: ${URUTAU_INGRESS_COUNTERS-/logs/host/ingress.counters}
URUTAU_EGRESS_CONTAINERS: ${URUTAU_EGRESS_CONTAINERS-/logs/host/containers.map}
URUTAU_RESOLV: ${URUTAU_RESOLV-/logs/resolv.conf}
# Where the hub's ban decisions land; applied by the host fail2ban jail.
+14 -2
View File
@@ -77,6 +77,7 @@ Lines are decoded as follows:
- **Traefik:** one JSON object per line; the default text format is read too, with fewer fields (no host or service). Client address, host, method, path, status and User-Agent are read; paths and User-Agents are clipped.
- **sshd:** the lines of `auth.log` with ISO timestamps. Failed passwords and keys, invalid users, closed-before-auth connections and `Accepted` logins; negotiation errors, banner exchange failures and protocol mismatches count as probes.
- **probe:** the `URUTAU-PROBE:` lines that the host kit logs for inbound connections to ports nobody listens on (`--probe-log`). Each becomes a `scanner` event with source `probe` (MITRE T1046), at most one per address, port and protocol per minute.
- **ingress, ingresscnt:** the firewall telemetry of the host kit (`--ingress`), described under "Firewall telemetry". They are not event sources: nothing is parsed into an event.
- **fail2ban:** `Ban`, `Unban` and `Restore Ban` lines. A restored ban (replayed after a fail2ban restart) updates the ban state and is not scored.
The egress log (`--egress-log`) has its own source, described in the egress section. Log file paths never leave the probe, and the hub never shows them: the dashboard shows only the name and state of a source. The hub reads no log file at all.
@@ -161,6 +162,12 @@ This is why the number differs from Coolify's analytics, which counts every dist
`GET /api/v1/events/stream?visits=1` adds anonymous visit events to the live stream. A visit carries no address, User-Agent or referrer; its place is the city, with coordinates rounded to one decimal (about 11 km). At most 20 visit events per second per instance are sent (the excess is summarised once a second as a batch), and visits are only broadcast to subscribers: never written to the event log, a snapshot or `live/recent`.
## Firewall telemetry
`internal/ingress` aggregates what the application logs cannot see: new inbound attempts to the host, including ports where nothing listens and packets from banned addresses that the firewall drops without a log line. The host kit table `urutau_ingress` observes at prerouting priority -150 (before Docker's DNAT) and only counts and logs. The probe tails two files as the wire sources `ingresscnt` (`ingress.counters`: `ts=... total=... tcp=... udp=... icmp=... open=...`, cumulative, one line a minute) and `ingress` (`ingress.log`, the sampled `URUTAU-IN:` and `URUTAU-INO:` kernel lines); it imports nothing of the hub and stays tiny. In the hub each node keeps an `ingress.Agg`: the delta of two counter lines is added to the hourly bucket of its timestamp (a decrease is a table reload and restarts from zero; a delta above 2^40, a timestamp more than an hour ahead or older than 30 days is dropped as malformed), and each sampled line adds to the bucket's logged count, top destination ports, top origin ASNs and countries (hub geo) and to the banned count when the store reports a jail ban on the source at that moment. Every field is length-limited when parsed (log lines over 2 KB and counter lines over 256 bytes are refused, sources must be public unicast, TCP needs SYN without ACK). Buckets are hourly for 30 days, each with top lists capped at 48 ports, 48 networks and 64 countries, saved to `ingress.json` once a minute when changed.
The aggregate is deliberately isolated: it receives the store's ban state and geo as two functions and has no way to emit an event, a score or a decision, so attempts from a banned address are never new evidence (no ban feedback loop with the second firewall, the `port-scan` family included). `GET /api/v1/ingress?range=24h&host=all|<name>[,<name>]` returns `{hosts, enabled, from, to, source{state,last_counters,last_line,lines,counter_lines,malformed}, totals{attempts,tcp,udp,icmp,open,closed,closed_pct,per_hour}, sample{logged,logged_banned,ratio,banned_pct,banned_est}, hourly[{t,total,open,closed,logged}], ports[{proto,port,n,served,pct}], asns[{asn,org,n,pct}], countries[{cc,n,pct}]}`. `totals` is exact; `sample`, `ports`, `asns` and `countries` come from the sample, and `ratio` is `logged / attempts`. `urutau doctor` checks that the last counters line of each host is under 5 minutes old.
## Event registry
`<data-dir>/events/` holds one JSON line per event, in the same format as the live stream, one file per UTC day. The current day is appended to and synced every 2 seconds; older days are gzip compressed. Files older than the retention are deleted, and the total is capped by `--events-max` (512 MB by default, `0` disables the registry). A day holds at most 200,000 lines; beyond that, events are only counted.
@@ -169,6 +176,10 @@ What enters: malicious events (scanner, exploit, bruteforce, ssh-fail, ssh-probe
Failure behavior: a full disk, the size cap or the day cap drop events (counted, logged at most once in a while, never fatal); a corrupted line is skipped when reading; a partial line left by an earlier failure is terminated before the next write.
### How studies read the registry
Period, funnel, metrics, campaigns and the other studies read the registry through `evlog.ScanRecs` and `ScanRefs`. A closed day (any day before the current UTC day) never changes, so it is decoded once into a compact form (strings interned per day, 112 bytes per event) and kept in memory under a cap of 96 MB (`evlog.Options.CacheMem`, negative disables it), least recently used first. A day is read again when the size or modification time of its files changes (a late line, a compression pass). The current day is always read live from the file, so the result matches a full scan exactly; sessions and campaigns that cross midnight are built over the events of the whole window, never per day. A study holds only 16-byte references to the decoded events and rebuilds those of one address when it builds that address' sessions (in parallel). Period, funnel and metrics of the same window share one scan and one set of sessions for the 30 s result lifetime. The byte budget (256 MB) counts only what is read from disk; the event count (1,500,000) and the 10 s deadline remain, and `truncated` is true only when one of them is hit (the dashboard then shows a note). First request after a restart decodes the days (3 in parallel); later ones are served from memory.
## Intelligence
The investigation layer is computed from the IP table and the registry, with no external API:
@@ -315,7 +326,7 @@ The user routes under `/api/v1/*` need `URUTAU_TOKEN` (bearer) or a session cook
|---|---|
| `GET /api/health` | `{"status":"ok"}`, no authentication |
| `GET /login`, `POST /login`, `POST /logout` | session cookie |
| `GET /api/v1/summary`, `/traffic`, `/ips`, `/ip/{ip}`, `/ip/{ip}/stix` | totals, web analytics, IP table, one address, STIX 2.1 bundle |
| `GET /api/v1/summary` (also `own`: web requests of `--trusted` and `--ignore` origins, counted apart; `totals.trusted`, `totals.internal` and `totals.requests_all` = `requests` + both; `totals.counts.trusted` and `.internal`), `/traffic`, `/ips`, `/ip/{ip}`, `/ip/{ip}/stix` | totals, web analytics, IP table, one address, STIX 2.1 bundle |
| `GET /api/v1/period`, `/period/events`, `/events`, `/events/sessions` | study of a period, event registry search (cursor), sessions |
| `GET /api/v1/events/stream` | live stream over SSE (`?visits=1` adds anonymous visits) |
| `GET /api/v1/live/recent`, `/geo` | latest live events, geography |
@@ -326,6 +337,7 @@ The user routes under `/api/v1/*` need `URUTAU_TOKEN` (bearer) or a session cook
| `GET /api/v1/blocklist.txt`, `/blocklist.json` | exportable blocklist (`?family=4\|6`) |
| `GET /api/v1/enforce`, `POST /enforce/unban`, `DELETE /enforce/allow` | second firewall |
| `GET /api/v1/egress` | outbound findings |
| `GET /api/v1/ingress` | firewall telemetry: inbound attempts per host (`range` and `host` as in the other endpoints; the probes of this hub only) |
| `GET /api/v1/incidents`, `/incidents/export.csv`, `/incidents/{id}`, `POST /incidents`, `PATCH /incidents/{id}`, `POST /incidents/{id}/comments` | tickets |
| `GET /api/v1/report` | report as JSON or HTML (`?format=`) |
| `GET /api/v1/probes`, `POST /probes`, `PUT /probes/{name}`, `DELETE /probes/{name}` | probe registry behind the Sources page: list with status, create (the token is shown once), edit location and egress settings, revoke (the data is kept) |
@@ -347,4 +359,4 @@ List endpoints (IPs, sessions, campaigns, events of an address) are paginated by
| `<data-dir>/incidents.json` | tickets |
| `<state-dir>/spool/`, `<state-dir>/state.json` | **on the probe:** pending batches, sequence, read positions, last command |
| `URUTAU_ENFORCE_LOG`, `URUTAU_ENFORCE_UNBAN_LOG` | **on the probe:** decision file read by the host jail and unban requests read by the host |
| `URUTAU_PROBE_LOG`, `URUTAU_EGRESS_LOG`, `URUTAU_EGRESS_CONTAINERS` | **on the probe:** kernel logs and container map written by the host kit in `deploy/host` |
| `URUTAU_PROBE_LOG`, `URUTAU_EGRESS_LOG`, `URUTAU_INGRESS_LOG`, `URUTAU_INGRESS_COUNTERS`, `URUTAU_EGRESS_CONTAINERS` | **on the probe:** kernel logs and container map written by the host kit in `deploy/host` |
+2
View File
@@ -73,6 +73,8 @@ The probe runs on each monitored server. It opens no port: it follows the log fi
| `--fail2ban-log` | `URUTAU_FAIL2BAN_LOG` | `/logs/host/fail2ban.log` | fail2ban log; empty disables |
| `--probe-log` | `URUTAU_PROBE_LOG` | `/logs/host/probe.log` | kernel log of connections to unserved ports |
| `--egress-log` | `URUTAU_EGRESS_LOG` | `/logs/host/egress.log` | kernel log of new outbound connections |
| `--ingress-log` | `URUTAU_INGRESS_LOG` | `/logs/host/ingress.log` | sampled kernel log of new inbound attempts (host kit `--ingress`) |
| `--ingresscnt-log` | `URUTAU_INGRESS_COUNTERS` | `/logs/host/ingress.counters` | exact inbound counters, one line a minute |
| `--egress-containers` | `URUTAU_EGRESS_CONTAINERS` | `/logs/host/containers.map` | `"<ip> <container>"` map, sent whole when it changes |
| `--resolv` | `URUTAU_RESOLV` | `/etc/resolv.conf` (the host's, mounted) | resolver list, sent whole when it changes |
| `--enforce-log` | `URUTAU_ENFORCE_LOG` | `/logs/enforce/decisions.log` | where ban decisions are appended; empty ignores ban commands |
+15 -3
View File
@@ -38,8 +38,8 @@ Settings are split by role. The **hub** (`urutau serve`) takes the variables in
| Variable | Default | Meaning |
|---|---|---|
| `URUTAU_TRUSTED` | empty | trusted CIDRs or IPs, comma separated; their events are dropped entirely. Also feeds the exclusions of the second firewall and the egress allow list |
| `URUTAU_IGNORE` | `127.0.0.0/8,::1,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,fc00::/7,fe80::/10,100.64.0.0/10,169.254.0.0/16` | same effect, kept as the alias that carries the private ranges as default |
| `URUTAU_TRUSTED` | empty | trusted CIDRs or IPs, comma separated; their web requests are counted as own traffic (class `trusted`) and never analysed: no score, threat, visitor or ban. Also feeds the exclusions of the second firewall and the egress allow list |
| `URUTAU_IGNORE` | `127.0.0.0/8,::1,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,fc00::/7,fe80::/10,100.64.0.0/10,169.254.0.0/16` | same effect (class `internal`), kept as the alias that carries the private ranges as default |
| `URUTAU_MONITOR_UA` | `(?i)^(Uptime-Kuma/\|Beszel\|Coolify\|kube-probe/\|Go-http-client/.*healthcheck)` | regular expression of monitoring User-Agents; empty disables; an invalid expression refuses to start |
| `URUTAU_MONITOR_FROM` | empty | CIDRs the monitors really come from; when set, the monitoring User-Agent only counts from them |
| `URUTAU_ADMIN_USERS` | empty | SSH users whose successful login keeps their IP out of the blocklist for 24 h after the last login (a later strong signal cancels it); the immunity is off unless this is set |
@@ -95,6 +95,7 @@ The probe has only these variables (flags in [cli.md](cli.md#urutau-probe)). A p
| `URUTAU_AUTH_LOG` | `/logs/host/auth.log` | sshd log |
| `URUTAU_FAIL2BAN_LOG` | `/logs/host/fail2ban.log` | fail2ban log |
| `URUTAU_PROBE_LOG` | `/logs/host/probe.log` | kernel log of connections to unserved ports, written by the host kit (see [Probes](#probes-port-scans)) |
| `URUTAU_INGRESS_LOG`, `URUTAU_INGRESS_COUNTERS` | `/logs/host/ingress.log`, `/logs/host/ingress.counters` | **on the probe:** sampled inbound attempts and the exact once-a-minute counters, written by `install.sh --ingress` (see [Firewall telemetry](#firewall-telemetry-inbound-attempts)) |
| `URUTAU_EGRESS_LOG` | `/logs/host/egress.log` | kernel log of new outbound connections, written by the host kit |
| `URUTAU_EGRESS_CONTAINERS` | `/logs/host/containers.map` | `"<ip> <container>"` map written by the host kit when a container starts (and every minute), so workloads keep their name when the address changes on a redeploy; sent whole when it changes |
| `URUTAU_RESOLV` | `/etc/resolv.conf` of the host (mounted) | resolvers of the host, sent whole when it changes |
@@ -109,7 +110,7 @@ The probe image defaults to the paths above because the compose file in `deploy/
## Noise and monitoring
- **Traefik headers.** Log `Sec-Fetch-Site`, `Sec-Fetch-Dest` and `Referer` so Urutau can tell a page framing your site from a real visit: `--accesslog.fields.headers.names.Sec-Fetch-Site=keep`, `--accesslog.fields.headers.names.Sec-Fetch-Dest=keep` and `--accesslog.fields.headers.names.Referer=keep`. A request framed by another page (`Sec-Fetch-Site` of `cross-site` or `same-site`, or a sub-resource `Sec-Fetch-Dest` such as `image` or `script`) appears in the timeline and creates an IP record like any other, but weighs 0.25 per event, with at most 30 points per IP coming from such requests (below the hostile threshold), and never counts as a strong signal. With an attack-tool User-Agent the headers are ignored.
- **Trusted origins** (`URUTAU_TRUSTED`): your own network, offices, monitors and other servers. `URUTAU_IGNORE` already drops loopback and the private ranges by default, so internal traffic never scores. Add your public monitor IPs. If your proxy reports the Docker gateway as the client, that address is private and already dropped; fix the proxy to pass the real client address instead.
- **Trusted origins** (`URUTAU_TRUSTED`): your own network, offices, monitors and other servers. `URUTAU_IGNORE` already covers loopback and the private ranges by default, so internal traffic never scores. Nothing is silently dropped: web requests from these origins are counted in aggregates only (not as one event record each) and shown in the Traffic page under "Own infrastructure and trusted origins"; they stay out of `totals.requests`, scores, threats, maps, visitors and the blocklist. SSH, fail2ban and network-probe lines from these origins are still ignored. Add your public monitor IPs. If your proxy reports the Docker gateway as the client, that address is private and counted as `internal` own traffic; fix the proxy to pass the real client address instead.
- **Monitoring User-Agent** (`URUTAU_MONITOR_UA`): a Go regular expression. A request that matches and is benign is counted as "monitoring" instead of traffic. If the request is a `scanner`, `exploit` or `bruteforce` it counts as an attack: a User-Agent is trivial to forge, so it never grants immunity.
- **Where monitors come from** (`URUTAU_MONITOR_FROM`): CIDRs of your monitors. When set, the monitoring User-Agent is honored only from those networks and benign requests (`ok` or `notfound`) are filtered. When empty, only `ok` answers are filtered: a `notfound` carrying a monitor User-Agent still counts, because anyone can send that header.
@@ -149,6 +150,17 @@ Tickets opened from egress findings (and their status: open, false positive, ben
Connections to ports nobody serves are not visible in the application logs. The host kit ([docker.md](docker.md#host-kit)) logs them from the kernel to `/var/log/urutau/probe.log`; the probe sends that file (`URUTAU_PROBE_LOG`) and the hub turns each line into a scanner event and keeps at most one event per address, port and protocol per minute. Without the kit the source stays at `waiting` and nothing else changes.
## Firewall telemetry (inbound attempts)
The application logs only show what reaches Traefik, sshd and fail2ban. Two things never appear there: connection attempts to ports where nothing listens, and packets from addresses that are already banned (the firewall drops them without a log line). The host kit with `--ingress` ([docker.md](docker.md#host-kit)) observes both, and the probe sends two sources: `ingress.counters` (exact, one cumulative line a minute) and `ingress.log` (a rate-limited sample of the attempts). Nothing else needs setting; without the kit the sources stay at `waiting`.
- **Exact totals** (attempts per hour, by protocol, closed versus served ports) are the difference between two counter lines. A counter that goes down means the table was reloaded and counts from zero. A malformed, absurd or out-of-window line is dropped and counted as malformed.
- **Details** (top destination ports, top origin ASNs and countries, the banned share) come from the sample, and the panel says so. The exposure ratio is `logged / total`, shown as "Sampled".
- **Banned sources.** The firewall sees a packet before fail2ban drops it, so the hub classifies each sampled line by its own ban state: an address is "banned" when a jail (fail2ban or the `urutau` jail) holds it in the hub's records at that moment, from the `Ban`, `Unban` and `Restore Ban` lines it has read. This is robust because it needs nothing from the host beyond the sampled line, and its limit is that a ban the hub never read is not counted. The share is of the sample; the estimate for the total applies it to the exact count and is labelled as an estimate.
- **No feedback loop.** These attempts are telemetry only: they never become events, never raise a score and never feed the second firewall, `port-scan` included (the closed-port evidence of the second firewall stays with the `probe.log` source above, one event per address, port and protocol per minute). Attempts from an address that is already banned are therefore never new evidence against it, as with `recidive` and the `urutau` jail.
- **Scope.** Retention is the 30 days of the other aggregates, in hourly buckets with capped top lists (48 ports, 48 networks, 64 countries per hour), kept in `<data-dir>/probes/<name>/ingress.json` (the primary probe in the root of the data directory). It is a few MB per host at most, well inside the hub memory limit. A cloud provider firewall (an Oracle Cloud security list, for example) blocks some ports before the host, so the metric is what reaches the host.
- `urutau doctor` reports, per host, whether the source is present and fresh (last counters line under 5 minutes old).
## Tor
Urutau marks addresses that are Tor exits or relays. By default (`URUTAU_TOR_AUTO=on`) it downloads the official exit list and relay list every 6 hours into `<data-dir>/tor` (`exits.txt`, `relays.json`; an invalid download keeps the previous cache); the container then needs outbound HTTPS to `check.torproject.org` and `onionoo.torproject.org`. On an air-gapped host set `URUTAU_TOR_AUTO=off` and maintain your own `URUTAU_TOR_EXITS` file.
+4
View File
@@ -168,6 +168,7 @@ Notes:
```bash
sudo sh deploy/host/install.sh # probe and egress logging + container map
sudo sh deploy/host/install.sh --enforce # also the fail2ban jail of the second firewall
sudo sh deploy/host/install.sh --ingress # also the inbound observation (firewall telemetry)
sudo sh deploy/host/install.sh --probe # probe host: the kit, plus the enforce directory the probe writes
sudo sh deploy/host/install.sh --probe --enforce
sudo sh deploy/host/install.sh --remove # undo everything (logs are kept)
@@ -179,9 +180,12 @@ It is idempotent. `URUTAU_WAN` overrides the detected uplink interface and `URUT
|---|---|
| egress logging | nftables table `inet urutau_egress` (`/etc/urutau/egress.nft`, only logs, never drops, separate from the Docker and fail2ban tables) and the `urutau-egress.service` unit; rsyslog rule `41-urutau-egress.conf` sends the kernel lines to `/var/log/urutau/egress.log` (`URUTAU-EGRESS:`) and `/var/log/urutau/probe.log` (`URUTAU-PROBE:`); logrotate daily, 7 copies, at most 200 MB (`urutau-logrotate.timer`) |
| probes | the `URUTAU-PROBE:` rule logs new inbound connections on the uplink to ports no socket listens on (at most 10 per second per source); the set of open ports is refreshed every minute from `ss`, including ports Docker publishes |
| inbound observation (`--ingress`) | nftables table `inet urutau_ingress` (`/etc/urutau/ingress.nft`) and `urutau-ingress.service`. It only observes: counters and a rate-limited log, never a drop, accept, mark or rewrite, and a policy of accept. Its chain hooks at prerouting priority -150, before Docker's DNAT, so DNAT'ed container ports and sources that are banned (and dropped later, in `INPUT` or `FORWARD`) are all seen. It sees only new attempts that arrive on the uplink and are addressed to the host: a TCP SYN without ACK, a new UDP flow, an ICMP echo request; never loopback, Docker bridges, private, link-local, CGNAT or multicast sources, or the host's own addresses. Exact totals are named nft counters (total, tcp, udp, icmp, and how many went to a served port); `urutau-ingress-tick`, run by `urutau-ingress-tick.timer` every minute, refreshes the set of served ports (listening sockets plus ports Docker publishes) and appends one cumulative line to `/var/log/urutau/ingress.counters`. The details are a sample: a global log ceiling (10 per second for closed ports, 5 for served ones, 2 for ICMP) written by rsyslog rule `42-urutau-ingress.conf` to `/var/log/urutau/ingress.log` (`URUTAU-IN:` closed port, `URUTAU-INO:` served port). Both files rotate with the rest of the kit |
| container map | `urutau-containers-map`, run by its timer (every minute) and by `urutau-containers-watch` (on every container start or network attach, so a redeploy that swaps addresses is named right within seconds), writes `/var/log/urutau/containers.map` (`<ip> <container>`) and `/var/log/urutau/resolv.conf` (the real upstream resolvers) |
| second firewall (`--enforce`) | directory `/var/log/urutau-enforce` (owned by `URUTAU_UID`, group `adm`) with `decisions.log` and `unban.log`; fail2ban filter `urutau`, action `urutau-allports` and jail `urutau` (`polling` backend, `maxretry = 1`, `bantime = 1h`, actions on `INPUT` and `DOCKER-USER`, host `ignoreip` kept); `urutau-unban.path` and `urutau-unban` apply the Unban button |
`--ingress` is separate from `--enforce` on purpose: observing is not blocking. Combine them freely; running the installer again without `--ingress` leaves it as it is, and `--remove` deletes it. The probe compose file already points `URUTAU_INGRESS_LOG` and `URUTAU_INGRESS_COUNTERS` at `/logs/host/ingress.log` and `/logs/host/ingress.counters`, so after `--ingress` the probe starts sending both with no change (before it, the two sources show as `waiting`). Production command, as root on each host: `sudo sh deploy/host/install.sh --ingress` (add `--probe` on a probe-only host, and `--enforce` where the second firewall runs). A cloud provider firewall (an Oracle Cloud security list, for example) drops some ports before they reach the host, so this measures what reaches the host, not what the internet sent.
The `urutau-allports` action behaves like `iptables-allports` but only drops connections the banned address starts (conntrack original direction), so replies to connections the host opened keep flowing. The egress and probe files land in `/var/log/urutau`, which the probe compose file already mounts at `/logs/host`, so the probe finds them at its defaults (`URUTAU_EGRESS=auto` turns on by itself once the file exists). For the second firewall add the mount and the variables to the compose file, start with `observe` and move to `on` when the decisions look right:
```yaml
+3 -2
View File
@@ -113,7 +113,7 @@ A side rail (a tab bar on phones, with a "More" menu that scrolls when it is tal
<p align="center"><img src="img/survival-dark.png" width="900" alt="Page: Survival"><br><sub>Survival: how long attackers keep coming back.</sub></p>
**Traffic** (`#/traffic`): privacy-friendly web analytics for legitimate traffic, built from the same Traefik log: unique visitors, pages, referrers, countries, browsers, operating systems, devices, response latency (p50 and p95), bytes sent and a world map of visitor countries, per domain. A unique visitor is a person with a real browser (a successful GET of a document by a browser User-Agent, one per IP per day, deduplicated globally); bots, tools and unknown clients are counted apart as "non-human clients". Visitors are counted by a hash with a daily salt; the IP of a legitimate visitor is never stored. See [SECURITY.md](../SECURITY.md).
**Traffic** (`#/traffic`): privacy-friendly web analytics for legitimate traffic, built from the same Traefik log: unique visitors, pages, referrers, countries, browsers, operating systems, devices, response latency (p50 and p95), bytes sent and a world map of visitor countries, per domain. A unique visitor is a person with a real browser (a successful GET of a document by a browser User-Agent, one per IP per day, deduplicated globally); bots, tools and unknown clients are counted apart as "non-human clients". Visitors are counted by a hash with a daily salt; the IP of a legitimate visitor is never stored. See [SECURITY.md](../SECURITY.md). A section at the bottom, "Own infrastructure and trusted origins", shows the web requests of `--trusted` and private (`--ignore`) origins (your servers, probes, CI runners, the Docker gateway) that are kept out of every other number: totals per class, a timeline, status classes, a table by origin (address, class, requests), and top domains and paths. They never score an IP or enter threats, maps, visitors or the blocklist.
<p align="center"><img src="img/traffic-dark.png" width="900" alt="Traffic page: web analytics of legitimate visitors"><br><sub>Traffic: privacy-friendly web analytics.</sub></p>
@@ -127,7 +127,7 @@ A side rail (a tab bar on phones, with a "More" menu that scrolls when it is tal
### Operate
**Defense** (`#/defense`): coverage and leaks of bans and of the blocklist. An attacker counts as protected when it is listed or banned by any jail; the API also splits one-shot from repeat attackers (`one_shot`, `repeat_ips`). It also holds the **second firewall** section (`URUTAU_ENFORCE=off|observe|on`): the mode, recent decisions with their reason (for example `known-attacker`, `port-scan`, `neighbor-campaign`), coverage, and the operator releases. Urutau only decides and writes the decisions to a file; the host fail2ban (jail `urutau`) applies them, and in `observe` mode it shows what would be blocked. It never blocks trusted addresses, private ranges, CDN and public resolver ranges, probes, the server itself or crawlers verified by forward-confirmed reverse DNS (Googlebot, Bingbot, Applebot). An **Unban** button on recent decisions and on the address page asks the host to lift the block (through `unban.log` next to `--enforce-log`) and can keep the second firewall from banning the address again for 1 h, 24 h or 7 days. With `URUTAU_ENFORCE_SHARE` the nodes of the probes exchange decisions, each node applying its own exclusions.
**Defense** (`#/defense`): coverage and leaks of bans and of the blocklist. An attacker counts as protected when it is listed or banned by any jail; the API also splits one-shot from repeat attackers (`one_shot`, `repeat_ips`). It also holds the **second firewall** section (`URUTAU_ENFORCE=off|observe|on`): the mode, recent decisions with their reason (for example `known-attacker`, `port-scan`, `neighbor-campaign`), coverage, and the operator releases. Below it, **Firewall: inbound attempts** shows what reaches the host before any ban drops it (host kit `--ingress`): exact totals and an hourly chart from the kit counters, the share that went to closed ports, the share from sources banned at that moment (estimated from the sample), and the top destination ports, origin networks and countries, all labelled as sampled. A cloud provider firewall blocks some ports before the host, so it is what reaches the host. Urutau only decides and writes the decisions to a file; the host fail2ban (jail `urutau`) applies them, and in `observe` mode it shows what would be blocked. It never blocks trusted addresses, private ranges, CDN and public resolver ranges, probes, the server itself or crawlers verified by forward-confirmed reverse DNS (Googlebot, Bingbot, Applebot). An **Unban** button on recent decisions and on the address page asks the host to lift the block (through `unban.log` next to `--enforce-log`) and can keep the second firewall from banning the address again for 1 h, 24 h or 7 days. With `URUTAU_ENFORCE_SHARE` the nodes of the probes exchange decisions, each node applying its own exclusions.
<p align="center"><img src="img/defense-dark.png" width="900" alt="Page: Defense, with the second firewall"><br><sub>Defense: coverage of the host fail2ban and the second firewall (observe mode).</sub></p>
@@ -185,6 +185,7 @@ State and city boundaries on the Geography page are from [Natural Earth](https:/
| `GET /api/v1/sessions/funnel` | session or bearer | sessions by stage (recon, probe, exploit, access, banned) |
| `GET /api/v1/campaigns`, `/api/v1/campaigns/{id}` | session or bearer | campaigns of the period, and one campaign with its IPs |
| `GET /api/v1/defense` | session or bearer | ban and blocklist coverage and leaks |
| `GET /api/v1/ingress` | session or bearer | firewall telemetry: inbound attempts (`totals` exact, `sample`, `ports`, `asns`, `countries` sampled, `hourly`). Query: `range`, `host` |
| `GET /api/v1/errors` | session or bearer | errors by class (`app`, `proxy`, `blocked`, `attack`, `bot`, `client`, `unknown`) |
| `GET /api/v1/integrity` | session or bearer | health of the data: sources, registry, snapshot |
| `GET /api/v1/report` | session or bearer | summary of a period (`format=html` returns the printable A4 report, with `lang`) (requests, attacks, hostile IPs, bans, visitors, non-human clients, page views, top IPs) |
+14 -2
View File
@@ -77,6 +77,7 @@ As linhas são decodificadas assim:
- **Traefik:** um objeto JSON por linha; o formato de texto padrão também é lido, com menos campos (sem host nem serviço). Lê-se endereço do cliente, host, método, caminho, status e User-Agent; caminhos e User-Agents são cortados.
- **sshd:** as linhas do `auth.log` com timestamps ISO. Senhas e chaves recusadas, usuários inválidos, conexões fechadas antes da autenticação e logins `Accepted`; erros de negociação, falhas de banner e versões de protocolo incompatíveis contam como sondagens.
- **probe:** as linhas `URUTAU-PROBE:` que o kit do host registra para conexões de entrada a portas em que ninguém escuta (`--probe-log`). Cada uma vira um evento `scanner` com fonte `probe` (MITRE T1046), no máximo um por endereço, porta e protocolo por minuto.
- **ingress, ingresscnt:** a telemetria do firewall do kit do host (`--ingress`), descrita em "Telemetria do firewall". Não são fontes de eventos: nada vira evento.
- **fail2ban:** linhas `Ban`, `Unban` e `Restore Ban`. Um ban restaurado (reaplicado após um reinício do fail2ban) atualiza o estado de ban e não é pontuado.
O log de egress (`--egress-log`) tem sua própria fonte, descrita na seção de egress. Os caminhos dos arquivos de log nunca saem da sonda e o hub nunca os mostra: o dashboard exibe só o nome e o estado de uma fonte. O hub não lê nenhum arquivo de log.
@@ -161,6 +162,12 @@ Um **visitante** é uma pessoa com navegador real: um GET bem-sucedido (2xx) de
`GET /api/v1/events/stream?visits=1` acrescenta eventos anônimos de visita ao stream ao vivo. Uma visita não carrega endereço, User-Agent nem referrer; o lugar é a cidade, com coordenadas arredondadas a uma casa decimal (cerca de 11 km). No máximo 20 eventos de visita por segundo por instância são enviados (o excesso é resumido uma vez por segundo em um lote), e visitas só são transmitidas a assinantes: nunca gravadas no registro de eventos, em um snapshot nem em `live/recent`.
## Telemetria do firewall
`internal/ingress` agrega o que os logs das aplicações não enxergam: tentativas novas de entrada no host, inclusive em portas em que nada escuta e pacotes de endereços banidos que o firewall descarta sem linha de log. A tabela `urutau_ingress` do kit do host observa em prerouting com prioridade -150 (antes do DNAT do Docker) e só conta e registra. A sonda acompanha dois arquivos como as fontes de protocolo `ingresscnt` (`ingress.counters`: `ts=... total=... tcp=... udp=... icmp=... open=...`, acumulado, uma linha por minuto) e `ingress` (`ingress.log`, as linhas do kernel amostradas `URUTAU-IN:` e `URUTAU-INO:`); ela não importa nada do hub e continua minúscula. No hub cada nó mantém um `ingress.Agg`: a diferença entre duas linhas de contador é somada ao balde horário do seu horário (uma queda é recarga da tabela e recomeça de zero; uma diferença acima de 2^40, um horário mais de uma hora à frente ou mais velho que 30 dias é descartado como malformado), e cada linha amostrada soma ao total registrado do balde, às portas de destino, aos ASNs e países de origem (geo do hub) mais frequentes e ao total de banidos quando o store informa um ban de jail naquela origem naquele momento. Todo campo é limitado em tamanho ao ser lido (linhas de log acima de 2 KB e de contador acima de 256 bytes são recusadas, as origens precisam ser unicast públicas, o TCP precisa de SYN sem ACK). Os baldes são horários por 30 dias, cada um com listas de topo limitadas a 48 portas, 48 redes e 64 países, gravados em `ingress.json` uma vez por minuto quando mudam.
O agregado é isolado de propósito: recebe o estado de bans e o geo do store como duas funções e não tem como emitir evento, pontuação ou decisão, então tentativas de um endereço banido nunca são evidência nova (sem laço de retroalimentação com o segundo firewall, família `port-scan` inclusive). `GET /api/v1/ingress?range=24h&host=all|<nome>[,<nome>]` devolve `{hosts, enabled, from, to, source{state,last_counters,last_line,lines,counter_lines,malformed}, totals{attempts,tcp,udp,icmp,open,closed,closed_pct,per_hour}, sample{logged,logged_banned,ratio,banned_pct,banned_est}, hourly[{t,total,open,closed,logged}], ports[{proto,port,n,served,pct}], asns[{asn,org,n,pct}], countries[{cc,n,pct}]}`. `totals` é exato; `sample`, `ports`, `asns` e `countries` vêm da amostra, e `ratio` é `registradas / attempts`. O `urutau doctor` confere que a última linha de contadores de cada host tem menos de 5 minutos.
## Registro de eventos
`<data-dir>/events/` guarda uma linha JSON por evento, no mesmo formato do stream ao vivo, um arquivo por dia UTC. O dia corrente recebe appends e é sincronizado a cada 2 segundos; dias anteriores são compactados com gzip. Arquivos mais antigos que a retenção são apagados, e o total é limitado por `--events-max` (512 MB por padrão, `0` desativa o registro). Um dia guarda no máximo 200.000 linhas; acima disso os eventos só são contados.
@@ -169,6 +176,10 @@ O que entra: eventos maliciosos (scanner, exploit, bruteforce, ssh-fail, ssh-pro
Comportamento em falha: disco cheio, o teto de tamanho ou o teto diário descartam eventos (contados, registrados no log no máximo de vez em quando, nunca fatais); uma linha corrompida é ignorada na leitura; uma linha parcial deixada por uma falha anterior é terminada antes da próxima escrita.
### Como os estudos leem o registro
Período, funil, métricas, campanhas e os demais estudos leem o registro por `evlog.ScanRecs` e `ScanRefs`. Um dia fechado (qualquer dia anterior ao dia UTC atual) não muda mais, então é decodificado uma vez em forma compacta (textos internados por dia, 112 bytes por evento) e mantido na memória sob um teto de 96 MB (`evlog.Options.CacheMem`, negativo desliga), o menos usado recentemente sai primeiro. Um dia é lido de novo quando o tamanho ou a data de modificação dos arquivos muda (uma linha tardia, uma compressão). O dia atual é sempre lido ao vivo do arquivo, então o resultado é idêntico ao de uma varredura completa; sessões e campanhas que cruzam a meia-noite são montadas sobre os eventos da janela inteira, nunca por dia. O estudo guarda só referências de 16 bytes aos eventos decodificados e reconstrói os de um endereço ao montar as sessões dele (em paralelo). Período, funil e métricas da mesma janela compartilham uma varredura e um conjunto de sessões durante os 30 s de vida do resultado. O orçamento de bytes (256 MB) conta só o que é lido do disco; o limite de eventos (1.500.000) e o prazo de 10 s continuam, e `truncated` só é verdadeiro quando um deles é atingido (o painel então mostra um aviso). A primeira requisição após reiniciar decodifica os dias (3 em paralelo); as seguintes saem da memória.
## Inteligência
A camada de investigação é calculada a partir da tabela de IPs e do registro, sem API externa:
@@ -315,7 +326,7 @@ As rotas de usuário em `/api/v1/*` exigem `URUTAU_TOKEN` (bearer) ou um cookie
|---|---|
| `GET /api/health` | `{"status":"ok"}`, sem autenticação |
| `GET /login`, `POST /login`, `POST /logout` | cookie de sessão |
| `GET /api/v1/summary`, `/traffic`, `/ips`, `/ip/{ip}`, `/ip/{ip}/stix` | totais, web analytics, tabela de IPs, um endereço, bundle STIX 2.1 |
| `GET /api/v1/summary` (também `own`: requisições web de origens `--trusted` e `--ignore`, contadas à parte; `totals.trusted`, `totals.internal` e `totals.requests_all` = `requests` + ambas; `totals.counts.trusted` e `.internal`), `/traffic`, `/ips`, `/ip/{ip}`, `/ip/{ip}/stix` | totais, web analytics, tabela de IPs, um endereço, bundle STIX 2.1 |
| `GET /api/v1/period`, `/period/events`, `/events`, `/events/sessions` | estudo de um período, busca no registro de eventos (cursor), sessões |
| `GET /api/v1/events/stream` | stream ao vivo por SSE (`?visits=1` inclui visitas anônimas) |
| `GET /api/v1/live/recent`, `/geo` | últimos eventos ao vivo, geografia |
@@ -326,6 +337,7 @@ As rotas de usuário em `/api/v1/*` exigem `URUTAU_TOKEN` (bearer) ou um cookie
| `GET /api/v1/blocklist.txt`, `/blocklist.json` | blocklist exportável (`?family=4\|6`) |
| `GET /api/v1/enforce`, `POST /enforce/unban`, `DELETE /enforce/allow` | segundo firewall |
| `GET /api/v1/egress` | achados de saída |
| `GET /api/v1/ingress` | telemetria do firewall: tentativas de entrada por host (`range` e `host` como nos outros endpoints; só as sondas deste hub) |
| `GET /api/v1/incidents`, `/incidents/export.csv`, `/incidents/{id}`, `POST /incidents`, `PATCH /incidents/{id}`, `POST /incidents/{id}/comments` | chamados |
| `GET /api/v1/report` | relatório em JSON ou HTML (`?format=`) |
| `GET /api/v1/probes`, `POST /probes`, `PUT /probes/{nome}`, `DELETE /probes/{nome}` | registro de sondas por trás da página Fontes: lista com estado, cria (o token aparece uma vez), edita localização e egress, revoga (os dados ficam) |
@@ -347,4 +359,4 @@ Os endpoints de lista (IPs, sessões, campanhas, eventos de um endereço) são p
| `<data-dir>/incidents.json` | chamados |
| `<state-dir>/spool/`, `<state-dir>/state.json` | **na sonda:** lotes pendentes, sequência, posições de leitura, último comando |
| `URUTAU_ENFORCE_LOG`, `URUTAU_ENFORCE_UNBAN_LOG` | **na sonda:** arquivo de decisões lido pela jail do host e pedidos de desban lidos pelo host |
| `URUTAU_PROBE_LOG`, `URUTAU_EGRESS_LOG`, `URUTAU_EGRESS_CONTAINERS` | **na sonda:** logs do kernel e mapa de contêineres escritos pelo kit do host em `deploy/host` |
| `URUTAU_PROBE_LOG`, `URUTAU_EGRESS_LOG`, `URUTAU_INGRESS_LOG`, `URUTAU_INGRESS_COUNTERS`, `URUTAU_EGRESS_CONTAINERS` | **na sonda:** logs do kernel e mapa de contêineres escritos pelo kit do host em `deploy/host` |
+2
View File
@@ -73,6 +73,8 @@ A sonda roda em cada servidor monitorado. Não abre porta: segue os arquivos de
| `--fail2ban-log` | `URUTAU_FAIL2BAN_LOG` | `/logs/host/fail2ban.log` | log do fail2ban; vazio desliga |
| `--probe-log` | `URUTAU_PROBE_LOG` | `/logs/host/probe.log` | log do kernel de conexões a portas sem serviço |
| `--egress-log` | `URUTAU_EGRESS_LOG` | `/logs/host/egress.log` | log do kernel de novas conexões de saída |
| `--ingress-log` | `URUTAU_INGRESS_LOG` | `/logs/host/ingress.log` | log do kernel amostrado de novas tentativas de entrada (kit do host `--ingress`) |
| `--ingresscnt-log` | `URUTAU_INGRESS_COUNTERS` | `/logs/host/ingress.counters` | contadores exatos de entrada, uma linha por minuto |
| `--egress-containers` | `URUTAU_EGRESS_CONTAINERS` | `/logs/host/containers.map` | mapa `"<ip> <contêiner>"`, enviado inteiro quando muda |
| `--resolv` | `URUTAU_RESOLV` | `/etc/resolv.conf` (o do host, montado) | lista de resolvedores, enviada inteira quando muda |
| `--enforce-log` | `URUTAU_ENFORCE_LOG` | `/logs/enforce/decisions.log` | onde as decisões de ban são acrescentadas; vazio ignora comandos de ban |
+15 -3
View File
@@ -38,8 +38,8 @@ Os ajustes se dividem por papel. O **hub** (`urutau serve`) usa as variáveis da
| Variável | Padrão | Significado |
|---|---|---|
| `URUTAU_TRUSTED` | vazio | CIDRs ou IPs confiáveis, separados por vírgula; os eventos deles são descartados por completo. Também alimenta as exclusões do segundo firewall e a lista de permitidos do egress |
| `URUTAU_IGNORE` | `127.0.0.0/8,::1,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,fc00::/7,fe80::/10,100.64.0.0/10,169.254.0.0/16` | mesmo efeito, mantido como o alias que carrega as faixas privadas como padrão |
| `URUTAU_TRUSTED` | vazio | CIDRs ou IPs confiáveis, separados por vírgula; as requisições web deles são contadas como tráfego próprio (classe `trusted`) e nunca analisadas: sem pontuação, ameaça, visitante ou banimento. Também alimenta as exclusões do segundo firewall e a lista de permitidos do egress |
| `URUTAU_IGNORE` | `127.0.0.0/8,::1,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,fc00::/7,fe80::/10,100.64.0.0/10,169.254.0.0/16` | mesmo efeito (classe `internal`), mantido como o alias que carrega as faixas privadas como padrão |
| `URUTAU_MONITOR_UA` | `(?i)^(Uptime-Kuma/\|Beszel\|Coolify\|kube-probe/\|Go-http-client/.*healthcheck)` | expressão regular de User-Agents de monitoramento; vazio desativa; expressão inválida impede a inicialização |
| `URUTAU_MONITOR_FROM` | vazio | CIDRs de onde os monitores realmente vêm; quando definido, o User-Agent de monitoramento só vale vindo deles |
| `URUTAU_ADMIN_USERS` | vazio | usuários SSH cujo login bem-sucedido mantém o IP fora da lista de bloqueio por 24 h após o último login (um sinal forte posterior cancela); a imunidade fica desligada se isto não for definido |
@@ -95,6 +95,7 @@ A sonda usa só estas variáveis (flags em [cli.md](cli.md#urutau-probe)). Um ca
| `URUTAU_AUTH_LOG` | `/logs/host/auth.log` | log do sshd |
| `URUTAU_FAIL2BAN_LOG` | `/logs/host/fail2ban.log` | log do fail2ban |
| `URUTAU_PROBE_LOG` | `/logs/host/probe.log` | log do kernel de conexões a portas que ninguém serve, gravado pelo kit do host (veja [Sondagens](#sondagens-varreduras-de-portas)) |
| `URUTAU_INGRESS_LOG`, `URUTAU_INGRESS_COUNTERS` | `/logs/host/ingress.log`, `/logs/host/ingress.counters` | **na sonda:** tentativas de entrada amostradas e os contadores exatos de cada minuto, gravados por `install.sh --ingress` (veja [Telemetria do firewall](#telemetria-do-firewall-tentativas-de-entrada)) |
| `URUTAU_EGRESS_LOG` | `/logs/host/egress.log` | log do kernel de conexões novas de saída, gravado pelo kit do host |
| `URUTAU_EGRESS_CONTAINERS` | `/logs/host/containers.map` | mapa `"<ip> <container>"` gravado pelo kit do host quando um contêiner sobe (e a cada minuto), para que as cargas mantenham o nome quando o endereço muda num redeploy; enviado inteiro quando muda |
| `URUTAU_RESOLV` | `/etc/resolv.conf` do host (montado) | resolvedores do host, enviados inteiros quando mudam |
@@ -109,7 +110,7 @@ A imagem da sonda usa os caminhos acima como padrão porque o compose em `deploy
## Ruído e monitoramento
- **Cabeçalhos do Traefik.** Registre `Sec-Fetch-Site`, `Sec-Fetch-Dest` e `Referer` para o Urutau distinguir uma página que embute seu site de uma visita real: `--accesslog.fields.headers.names.Sec-Fetch-Site=keep`, `--accesslog.fields.headers.names.Sec-Fetch-Dest=keep` e `--accesslog.fields.headers.names.Referer=keep`. Uma requisição enquadrada por outra página (`Sec-Fetch-Site` `cross-site` ou `same-site`, ou `Sec-Fetch-Dest` de subrecurso como `image` ou `script`) aparece na linha do tempo e cria registro de IP como qualquer outra, mas pesa 0,25 por evento, com no máximo 30 pontos por IP vindos delas (abaixo do limiar hostil), e nunca conta como sinal forte. Com User-Agent de ferramenta de ataque os cabeçalhos são ignorados.
- **Origens confiáveis** (`URUTAU_TRUSTED`): sua própria rede, escritórios, monitores e outros servidores. `URUTAU_IGNORE` já descarta loopback e as faixas privadas por padrão, então o tráfego interno nunca pontua. Acrescente os IPs públicos dos seus monitores. Se o proxy informa o gateway do Docker como cliente, esse endereço é privado e já é descartado; corrija o proxy para repassar o endereço real do cliente.
- **Origens confiáveis** (`URUTAU_TRUSTED`): sua própria rede, escritórios, monitores e outros servidores. `URUTAU_IGNORE` já cobre loopback e as faixas privadas por padrão, então o tráfego interno nunca pontua. Nada é descartado em silêncio: as requisições web dessas origens são contadas só em agregados (não como um registro de evento cada) e aparecem na página Tráfego em "Infraestrutura própria e origens confiáveis"; ficam fora de `totals.requests`, pontuação, ameaças, mapas, visitantes e lista de bloqueio. Linhas de SSH, fail2ban e sondas de rede dessas origens continuam ignoradas. Acrescente os IPs públicos dos seus monitores. Se o proxy informa o gateway do Docker como cliente, esse endereço é privado e contado como tráfego próprio `internal`; corrija o proxy para repassar o endereço real do cliente.
- **User-Agent de monitoramento** (`URUTAU_MONITOR_UA`): uma expressão regular do Go. Uma requisição que casa e é benigna é contada como "monitoring" em vez de tráfego. Se a requisição for `scanner`, `exploit` ou `bruteforce`, conta como ataque: um User-Agent é trivial de forjar, então nunca concede imunidade.
- **De onde vêm os monitores** (`URUTAU_MONITOR_FROM`): CIDRs dos seus monitores. Quando definido, o User-Agent de monitoramento só vale vindo dessas redes e requisições benignas (`ok` ou `notfound`) são filtradas. Quando vazio, só respostas `ok` são filtradas: um `notfound` com User-Agent de monitor ainda conta, porque qualquer um pode enviar esse cabeçalho.
@@ -149,6 +150,17 @@ Os chamados abertos a partir de achados de egress (e o estado deles: aberto, fal
Conexões a portas que ninguém serve não aparecem nos logs das aplicações. O kit do host ([docker.md](docker.md#kit-do-host)) as registra do kernel em `/var/log/urutau/probe.log`; a sonda envia esse arquivo (`URUTAU_PROBE_LOG`) e o hub transforma cada linha em um evento de scanner e guarda no máximo um evento por endereço, porta e protocolo por minuto. Sem o kit a fonte fica em `waiting` e mais nada muda.
## Telemetria do firewall (tentativas de entrada)
Os logs das aplicações só mostram o que chega ao Traefik, ao sshd e ao fail2ban. Duas coisas nunca aparecem neles: tentativas de conexão a portas em que nada escuta e pacotes de endereços já banidos (o firewall os descarta sem linha de log). O kit do host com `--ingress` ([docker.md](docker.md#kit-do-host)) observa as duas, e a sonda envia duas fontes: `ingress.counters` (exata, uma linha acumulada por minuto) e `ingress.log` (uma amostra das tentativas, com limite de ritmo). Nada mais precisa ser configurado; sem o kit as fontes ficam em `waiting`.
- **Totais exatos** (tentativas por hora, por protocolo, portas fechadas contra com serviço) são a diferença entre duas linhas de contador. Um contador que diminui quer dizer que a tabela foi recarregada e conta de zero. Uma linha malformada, absurda ou fora da janela é descartada e contada como malformada.
- **Detalhes** (portas de destino mais visadas, ASNs e países de origem, a parcela de banidos) vêm da amostra, e o painel diz isso. A razão de exposição é `registradas / total`, mostrada como "Amostrado".
- **Origens banidas.** O firewall vê o pacote antes de o fail2ban descartá-lo, então o hub classifica cada linha amostrada pelo próprio estado de bans: um endereço é "banido" quando uma jail (fail2ban ou a jail `urutau`) o mantém nos registros do hub naquele momento, pelas linhas `Ban`, `Unban` e `Restore Ban` que ele leu. É robusto porque não exige nada do host além da linha amostrada, e o limite é que um ban que o hub nunca leu não conta. A parcela é da amostra; a estimativa para o total a aplica à contagem exata e vem rotulada como estimativa.
- **Sem laço de retroalimentação.** Estas tentativas são só telemetria: nunca viram eventos, nunca aumentam pontuação e nunca alimentam o segundo firewall, `port-scan` inclusive (a evidência de portas fechadas do segundo firewall continua com a fonte `probe.log` acima, um evento por endereço, porta e protocolo por minuto). Tentativas de um endereço já banido, portanto, nunca são evidência nova contra ele, como acontece com a `recidive` e a jail `urutau`.
- **Escopo.** A retenção é a mesma de 30 dias dos outros agregados, em baldes por hora com listas de topo limitadas (48 portas, 48 redes, 64 países por hora), em `<data-dir>/probes/<nome>/ingress.json` (a sonda primária na raiz do diretório de dados). Dá no máximo alguns MB por host, bem dentro do limite de memória do hub. O firewall do provedor de nuvem (uma lista de segurança da Oracle Cloud, por exemplo) barra algumas portas antes do host, então a métrica é o que chega ao host.
- `urutau doctor` informa, por host, se a fonte está presente e fresca (última linha de contadores com menos de 5 minutos).
## Tor
O Urutau marca endereços que são saídas ou relays do Tor. Por padrão (`URUTAU_TOR_AUTO=on`) baixa a lista oficial de saídas e a de relays a cada 6 horas em `<data-dir>/tor` (`exits.txt`, `relays.json`; um download inválido mantém o cache anterior); o container então precisa de HTTPS de saída para `check.torproject.org` e `onionoo.torproject.org`. Num host isolado defina `URUTAU_TOR_AUTO=off` e mantenha seu próprio arquivo `URUTAU_TOR_EXITS`.
+4
View File
@@ -168,6 +168,7 @@ Notas:
```bash
sudo sh deploy/host/install.sh # registro de sondagens e egress + mapa de containers
sudo sh deploy/host/install.sh --enforce # também a jail do fail2ban do segundo firewall
sudo sh deploy/host/install.sh --ingress # também a observação de entrada (telemetria do firewall)
sudo sh deploy/host/install.sh --probe # host de sonda: o kit, mais o diretório de enforce que a sonda grava
sudo sh deploy/host/install.sh --probe --enforce
sudo sh deploy/host/install.sh --remove # desfaz tudo (os logs são mantidos)
@@ -179,9 +180,12 @@ sudo sh deploy/host/install.sh --remove # desfaz tudo (os logs são mantidos)
|---|---|
| registro de egress | tabela nftables `inet urutau_egress` (`/etc/urutau/egress.nft`, só registra, nunca descarta, separada das tabelas do Docker e do fail2ban) e a unit `urutau-egress.service`; a regra rsyslog `41-urutau-egress.conf` manda as linhas do kernel para `/var/log/urutau/egress.log` (`URUTAU-EGRESS:`) e `/var/log/urutau/probe.log` (`URUTAU-PROBE:`); logrotate diário, 7 cópias, no máximo 200 MB (`urutau-logrotate.timer`) |
| sondagens | a regra `URUTAU-PROBE:` registra conexões novas de entrada pela interface externa a portas em que nenhum socket escuta (no máximo 10 por segundo por origem); o conjunto de portas abertas é atualizado a cada minuto a partir do `ss`, incluindo as portas que o Docker publica |
| observação de entrada (`--ingress`) | tabela nftables `inet urutau_ingress` (`/etc/urutau/ingress.nft`) e `urutau-ingress.service`. Só observa: contadores e um log com limite de ritmo, nunca um drop, accept, marca ou reescrita, e a política é accept. A cadeia entra em prerouting com prioridade -150, antes do DNAT do Docker, então as portas de containers com DNAT e as origens banidas (e descartadas depois, em `INPUT` ou `FORWARD`) são todas vistas. Ela só vê tentativas novas que chegam pela interface externa e são destinadas ao host: um TCP SYN sem ACK, um fluxo UDP novo, um pedido de eco ICMP; nunca loopback, pontes do Docker, origens privadas, link-local, CGNAT ou multicast, nem os endereços do próprio host. Os totais exatos são contadores nomeados do nft (total, tcp, udp, icmp e quantos foram a uma porta com serviço); o `urutau-ingress-tick`, executado pelo `urutau-ingress-tick.timer` a cada minuto, atualiza o conjunto de portas com serviço (sockets em escuta mais as portas que o Docker publica) e acrescenta uma linha acumulada a `/var/log/urutau/ingress.counters`. Os detalhes são uma amostra: um teto global de log (10 por segundo para portas fechadas, 5 para as com serviço, 2 para ICMP) gravado pela regra rsyslog `42-urutau-ingress.conf` em `/var/log/urutau/ingress.log` (`URUTAU-IN:` porta fechada, `URUTAU-INO:` porta com serviço). Os dois arquivos giram junto com o resto do kit |
| mapa de containers | `urutau-containers-map`, executado pelo timer (a cada minuto) e pelo `urutau-containers-watch` (a cada contêiner que sobe ou entra numa rede, para que um redeploy que troca endereços seja nomeado certo em segundos), grava `/var/log/urutau/containers.map` (`<ip> <container>`) e `/var/log/urutau/resolv.conf` (os resolvedores reais de upstream) |
| segundo firewall (`--enforce`) | diretório `/var/log/urutau-enforce` (dono `URUTAU_UID`, grupo `adm`) com `decisions.log` e `unban.log`; filtro `urutau`, ação `urutau-allports` e jail `urutau` do fail2ban (backend `polling`, `maxretry = 1`, `bantime = 1h`, ações em `INPUT` e `DOCKER-USER`, `ignoreip` do host mantido); `urutau-unban.path` e `urutau-unban` aplicam o botão Desbanir |
`--ingress` é separado de `--enforce` de propósito: observar não é bloquear. Combine como quiser; rodar o instalador de novo sem `--ingress` deixa tudo como está, e `--remove` apaga. O compose da sonda já aponta `URUTAU_INGRESS_LOG` e `URUTAU_INGRESS_COUNTERS` para `/logs/host/ingress.log` e `/logs/host/ingress.counters`, então depois do `--ingress` a sonda passa a enviar os dois sem mudar nada (antes disso, as duas fontes ficam em `waiting`). Comando de produção, como root em cada host: `sudo sh deploy/host/install.sh --ingress` (some `--probe` num host só de sonda e `--enforce` onde o segundo firewall roda). O firewall do provedor de nuvem (uma lista de segurança da Oracle Cloud, por exemplo) descarta algumas portas antes de chegarem ao host, então isto mede o que chega ao host, não o que a internet enviou.
A ação `urutau-allports` funciona como `iptables-allports`, mas só descarta conexões que o endereço banido inicia (direção original do conntrack), então as respostas a conexões que o host abriu continuam fluindo. Os arquivos de egress e sondagem caem em `/var/log/urutau`, que o compose já monta em `/logs/host`, então a sonda os encontra nos padrões (`URUTAU_EGRESS=auto` liga sozinho assim que o arquivo existe). Para o segundo firewall, acrescente a montagem e as variáveis ao compose, comece com `observe` e passe para `on` quando as decisões parecerem certas:
```yaml
+3 -2
View File
@@ -113,7 +113,7 @@ Uma barra lateral (barra de abas no celular, com um menu "Mais" que rola quando
<p align="center"><img src="../img/survival-dark-pt.png" width="900" alt="Página: Sobrevivência"><br><sub>Sobrevivência: por quanto tempo os atacantes continuam voltando.</sub></p>
**Tráfego** (`#/traffic`): web analytics amigável à privacidade do tráfego legítimo, feito a partir do mesmo log do Traefik: visitantes únicos, páginas, referrers, países, navegadores, sistemas operacionais, dispositivos, latência de resposta (p50 e p95), bytes enviados e um mapa-múndi dos países dos visitantes, por domínio. Um visitante único é uma pessoa com navegador real (um GET bem-sucedido de um documento por um User-Agent de navegador, um por IP por dia, deduplicado globalmente); bots, ferramentas e clientes desconhecidos são contados à parte como "clientes não humanos". Visitantes são contados por um hash com sal diário; o IP de um visitante legítimo nunca é guardado. Veja [SECURITY.pt-BR.md](../../SECURITY.pt-BR.md).
**Tráfego** (`#/traffic`): web analytics amigável à privacidade do tráfego legítimo, feito a partir do mesmo log do Traefik: visitantes únicos, páginas, referrers, países, navegadores, sistemas operacionais, dispositivos, latência de resposta (p50 e p95), bytes enviados e um mapa-múndi dos países dos visitantes, por domínio. Um visitante único é uma pessoa com navegador real (um GET bem-sucedido de um documento por um User-Agent de navegador, um por IP por dia, deduplicado globalmente); bots, ferramentas e clientes desconhecidos são contados à parte como "clientes não humanos". Visitantes são contados por um hash com sal diário; o IP de um visitante legítimo nunca é guardado. Veja [SECURITY.pt-BR.md](../../SECURITY.pt-BR.md). Uma seção no fim, "Infraestrutura própria e origens confiáveis", mostra as requisições web de origens `--trusted` e privadas (`--ignore`) (seus servidores, sondas, runners de CI, o gateway do Docker) que ficam fora de todos os outros números: totais por classe, linha do tempo, classes de status, tabela por origem (endereço, classe, requisições) e os domínios e caminhos mais pedidos. Elas nunca pontuam um IP nem entram em ameaças, mapas, visitantes ou na lista de bloqueio.
<p align="center"><img src="../img/traffic-dark-pt.png" width="900" alt="Página Tráfego: web analytics dos visitantes legítimos"><br><sub>Tráfego: web analytics amigável à privacidade.</sub></p>
@@ -127,7 +127,7 @@ Uma barra lateral (barra de abas no celular, com um menu "Mais" que rola quando
### Operar
**Defesa** (`#/defense`): cobertura e vazamentos de bans e da blocklist. Um atacante conta como protegido quando está listado ou banido por qualquer jail; a API também separa atacantes de uma só vez dos reincidentes (`one_shot`, `repeat_ips`). Traz ainda a seção do **segundo firewall** (`URUTAU_ENFORCE=off|observe|on`): o modo, as decisões recentes com o motivo (por exemplo `known-attacker`, `port-scan`, `neighbor-campaign`), a cobertura e as liberações do operador. O Urutau só decide e escreve as decisões num arquivo; o fail2ban do host (jail `urutau`) as aplica, e no modo `observe` ele mostra o que seria bloqueado. Nunca bloqueia endereços confiáveis, faixas privadas, faixas de CDN e de resolvers públicos, sondas, o próprio servidor nem crawlers verificados por DNS reverso confirmado (Googlebot, Bingbot, Applebot). Um botão **Desbanir** nas decisões recentes e na página do endereço pede ao host que levante o bloqueio (por `unban.log` ao lado de `--enforce-log`) e pode impedir o segundo firewall de banir o endereço de novo por 1 h, 24 h ou 7 dias. Com `URUTAU_ENFORCE_SHARE` uma decisão tomada para uma sonda também é enfileirada para as outras, cada nó aplicando as próprias exclusões.
**Defesa** (`#/defense`): cobertura e vazamentos de bans e da blocklist. Um atacante conta como protegido quando está listado ou banido por qualquer jail; a API também separa atacantes de uma só vez dos reincidentes (`one_shot`, `repeat_ips`). Traz ainda a seção do **segundo firewall** (`URUTAU_ENFORCE=off|observe|on`): o modo, as decisões recentes com o motivo (por exemplo `known-attacker`, `port-scan`, `neighbor-campaign`), a cobertura e as liberações do operador. Logo abaixo, **Firewall: tentativas de entrada** mostra o que chega ao host antes de qualquer ban descartá-lo (kit do host `--ingress`): totais exatos e um gráfico por hora a partir dos contadores do kit, a parcela que foi a portas fechadas, a parcela de origens banidas naquele momento (estimada pela amostra) e as portas de destino, redes e países de origem mais frequentes, tudo rotulado como amostrado. O firewall do provedor de nuvem barra algumas portas antes do host, então é o que chega ao host. O Urutau só decide e escreve as decisões num arquivo; o fail2ban do host (jail `urutau`) as aplica, e no modo `observe` ele mostra o que seria bloqueado. Nunca bloqueia endereços confiáveis, faixas privadas, faixas de CDN e de resolvers públicos, sondas, o próprio servidor nem crawlers verificados por DNS reverso confirmado (Googlebot, Bingbot, Applebot). Um botão **Desbanir** nas decisões recentes e na página do endereço pede ao host que levante o bloqueio (por `unban.log` ao lado de `--enforce-log`) e pode impedir o segundo firewall de banir o endereço de novo por 1 h, 24 h ou 7 dias. Com `URUTAU_ENFORCE_SHARE` uma decisão tomada para uma sonda também é enfileirada para as outras, cada nó aplicando as próprias exclusões.
<p align="center"><img src="../img/defense-dark-pt.png" width="900" alt="Página: Defesa, com o segundo firewall"><br><sub>Defesa: cobertura do fail2ban do host e do segundo firewall (modo observe).</sub></p>
@@ -185,6 +185,7 @@ Os limites de estados e cidades da página Geografia são do [Natural Earth](htt
| `GET /api/v1/sessions/funnel` | sessão ou bearer | sessões por estágio (recon, probe, exploit, access, banned) |
| `GET /api/v1/campaigns`, `/api/v1/campaigns/{id}` | sessão ou bearer | campanhas do período, e uma campanha com seus IPs |
| `GET /api/v1/defense` | sessão ou bearer | cobertura e vazamentos de ban e blocklist |
| `GET /api/v1/ingress` | sessão ou bearer | telemetria do firewall: tentativas de entrada (`totals` exato; `sample`, `ports`, `asns`, `countries` amostrados; `hourly`). Query: `range`, `host` |
| `GET /api/v1/errors` | sessão ou bearer | erros por classe (`app`, `proxy`, `blocked`, `attack`, `bot`, `client`, `unknown`) |
| `GET /api/v1/integrity` | sessão ou bearer | saúde dos dados: fontes, registro, snapshot |
| `GET /api/v1/report` | sessão ou bearer | resumo de um período (`format=html` devolve o relatório A4 imprimível, com `lang`; requisições, ataques, IPs hostis, bans, visitantes, clientes não humanos, páginas vistas, principais IPs) |
+99 -2
View File
@@ -62,13 +62,13 @@ func TestMonitoringTrustedAndForged(t *testing.T) {
t.Fatalf("feed %+v", rec)
}
// trusted origins are dropped entirely, even for exploits and with other UAs
// trusted origins are only counted (see TestOwnTrafficIsCountedNeverAnalysed), even for exploits
h(line("136.248.78.83", "GET", "/?x=../../etc/passwd", "curl/8", 200))
h(line("2001:db8:1::5", "GET", "/.env", "curl/8", 404))
h(line("127.0.0.1", "GET", "/.env", "curl/8", 404))
for _, a := range []string{"136.248.78.83", "2001:db8:1::5", "127.0.0.1"} {
if _, ok := st.IP(a); ok {
t.Fatalf("%s must be dropped", a)
t.Fatalf("%s must not become an IP record", a)
}
}
// a non-matching UA from an external IP is a normal request
@@ -374,3 +374,100 @@ func TestLocationFlagIsValidated(t *testing.T) {
}
}
}
func TestOwnTrafficIsCountedNeverAnalysed(t *testing.T) {
r, st := runner(t, nil)
h := r.handle(&source{name: "traefik", parse: traefikParse})
h(line("198.51.100.4", "GET", "/", "Mozilla/5.0 (X11; Linux x86_64) Firefox/120.0", 200)) // external: counted as usual
before := st.Summary("1h")
// trusted (--trusted), including an attack-looking request, and a private address (--ignore default)
h(line("136.248.78.83", "GET", "/.env", "curl/8", 404))
h(line("136.248.78.83", "GET", "/api/x?token=secret", "curl/8", 200))
h(line("2001:db8:1::5", "POST", "/login", "curl/8", 401))
h(line("172.18.0.1", "GET", "/", "Mozilla/5.0 (X11; Linux x86_64) Firefox/120.0", 200))
h(line("127.0.0.1", "GET", "/", "x", 502))
after := st.Summary("2h") // another range: the summary of "1h" is cached for 2 s
if after.Totals.Trusted != 3 || after.Totals.Internal != 2 {
t.Fatalf("own counts: %+v", after.Totals)
}
if after.Totals.Requests != before.Totals.Requests || after.Totals.Malicious != before.Totals.Malicious ||
after.Totals.RequestsAll != before.Totals.Requests+5 {
t.Fatalf("totals: before %+v after %+v", before.Totals, after.Totals)
}
if after.Totals.Counts["trusted"] != 3 || after.Totals.Counts["internal"] != 2 {
t.Fatalf("counts: %v", after.Totals.Counts)
}
if after.Totals.UniqueIPs != before.Totals.UniqueIPs || after.Totals.HostileIPs != 0 || after.Totals.SuspiciousIPs != 0 {
t.Fatalf("own traffic must not create IPs: %+v", after.Totals)
}
for _, a := range []string{"136.248.78.83", "2001:db8:1::5", "172.18.0.1", "127.0.0.1"} {
if _, ok := st.IP(a); ok {
t.Fatalf("%s must not have an IP record", a)
}
}
if len(st.Recent(10)) != len(before.Recent) || len(after.IPs) != len(before.IPs) || len(after.TopPaths) != len(before.TopPaths) {
t.Fatal("own traffic must not reach the feed, the IP table or the attack tops")
}
if tr := after; tr.Totals.Monitoring != 0 {
t.Fatalf("monitoring: %+v", tr.Totals)
}
if v := st.TrafficFor(store.ParseRange("1h"), "all"); v.Requests != 1 || v.Visitors != 0 {
t.Fatalf("web analytics must not count own traffic (one external request, no visitor without an enricher): %+v", v)
}
o := after.Own
if o.Status[0] != 2 || o.Status[2] != 2 || o.Status[3] != 1 {
t.Fatalf("status classes: %v", o.Status)
}
var sum uint32
for _, c := range []string{"trusted", "internal"} {
for _, v := range o.Series[c] {
sum += v
}
}
if sum != 5 {
t.Fatalf("series sum %d", sum)
}
got := map[string]string{}
for _, c := range o.Origins {
got[c.Key] = c.Label
}
if got["136.248.78.83"] != "trusted" || got["172.18.0.1"] != "internal" || got["2001:db8:1::/64"] != "trusted" {
t.Fatalf("origins: %+v", o.Origins)
}
for _, p := range o.Paths {
if strings.Contains(p.Key, "secret") {
t.Fatalf("query strings must not be kept: %+v", o.Paths)
}
}
// a snapshot keeps the own traffic
dir := t.TempDir()
if err := st.Save(SnapshotPath(dir), nil); err != nil {
t.Fatal(err)
}
st2 := store.New(store.Config{Name: "t", Version: "t"})
if _, err := st2.Load(SnapshotPath(dir)); err != nil {
t.Fatal(err)
}
if s2 := st2.Summary("3h"); s2.Totals.Trusted != 3 || s2.Totals.Internal != 2 {
t.Fatalf("after reload: %+v", s2.Totals)
}
}
func TestOwnTrafficThroughFeed(t *testing.T) {
// the probe sends every line; the hub runner (remote mode) classifies it
c := Config{Ignore: DefaultIgnore, Trusted: "10.9.9.9", Retention: 168 * time.Hour, Name: "n"}
st := store.New(store.Config{Name: "n", Version: "t"})
r, err := NewRemoteRunner(c, st, slog.New(slog.NewTextHandler(io.Discard, nil)), t.TempDir())
if err != nil {
t.Fatal(err)
}
if !r.Feed("traefik", line("10.9.9.9", "GET", "/", "x", 200), store.Offset{Inode: 1, Offset: 10}) ||
!r.Feed("traefik", line("203.0.113.9", "GET", "/", "x", 200), store.Offset{Inode: 1, Offset: 20}) ||
!r.Feed("traefik", line("192.168.1.2", "GET", "/", "x", 200), store.Offset{Inode: 1, Offset: 30}) {
t.Fatal("feed refused")
}
s := st.Summary("1h")
if s.Totals.Trusted != 1 || s.Totals.Internal != 1 || s.Totals.Requests != 1 || s.Totals.RequestsAll != 3 {
t.Fatalf("totals: %+v", s.Totals)
}
}
+1
View File
@@ -65,6 +65,7 @@ func Doctor(c Config, w io.Writer, asJSON bool) bool {
add("data-dir", "ok", fmt.Sprintf("%s writable", filepath.Clean(c.DataDir)))
}
doctorEnforce(c, add)
doctorIngress(c, add)
geoInfo := doctorGeo(c, add)
stateInfo := doctorState(c, add)
ok := true
+35
View File
@@ -0,0 +1,35 @@
package app
import (
"log/slog"
"path/filepath"
"strconv"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/ingress"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
// IngressPath is the aggregate of the firewall telemetry inside a node directory.
func IngressPath(dir string) string { return filepath.Join(dir, "ingress.json") }
// newIngress builds the firewall telemetry aggregate of one node. A source
// address is "banned" by the node's own ban state (the jails it has read from
// fail2ban.log, the urutau jail included). The aggregate only reads that state:
// it has no way to write an event, a score or a decision, so attempts from a
// banned address never become evidence.
func newIngress(st *store.Store, dir string, log *slog.Logger) *ingress.Agg {
a := ingress.New()
a.Banned = st.Banned
a.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
}
if err := a.Load(IngressPath(dir)); err != nil {
log.Warn("ingress state ignored", "dir", dir, "err", err)
}
return a
}
+60
View File
@@ -0,0 +1,60 @@
package app
import (
"fmt"
"os"
"path/filepath"
"sort"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/ingress"
)
// ingressFresh is how old the last counters line may be before the firewall
// telemetry of a host counts as stale: the kit writes one every minute.
const ingressFresh = 5 * time.Minute
// doctorIngress reports, per host that ever sent it, whether the firewall
// telemetry (host kit --ingress) is present and fresh. It reads the saved
// aggregate of each node; no host sending it is "off", not a failure.
func doctorIngress(c Config, add func(name, status, detail string)) {
dirs := map[string]string{c.Name: c.DataDir}
if ents, err := os.ReadDir(filepath.Join(c.DataDir, "probes")); err == nil {
for _, e := range ents {
if e.IsDir() {
dirs[e.Name()] = filepath.Join(c.DataDir, "probes", e.Name())
}
}
}
names := make([]string, 0, len(dirs))
for n := range dirs {
names = append(names, n)
}
sort.Strings(names)
any := false
for _, n := range names {
p := IngressPath(dirs[n])
if _, err := os.Stat(p); err != nil {
continue
}
a := ingress.New()
if err := a.Load(p); err != nil {
add("ingress "+n, "warn", err.Error())
any = true
continue
}
in := a.Info()
any = true
switch {
case in.LastCounters == 0:
add("ingress "+n, "warn", "sampled log seen but no counters yet: check ingress.counters and urutau-ingress-tick.timer")
case time.Since(time.Unix(in.LastCounters, 0)) > ingressFresh:
add("ingress "+n, "warn", fmt.Sprintf("stale: last counters %s ago (is urutau-ingress-tick.timer running?)", time.Since(time.Unix(in.LastCounters, 0)).Round(time.Second)))
default:
add("ingress "+n, "ok", fmt.Sprintf("fresh: counters %s ago, %d sampled lines", time.Since(time.Unix(in.LastCounters, 0)).Round(time.Second), in.Lines))
}
}
if !any {
add("ingress", "off", "no firewall telemetry received (host kit: install.sh --ingress)")
}
}
+77
View File
@@ -0,0 +1,77 @@
package app
import (
"fmt"
"io"
"log/slog"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
func ingressNode(t *testing.T) (*Runner, *store.Store) {
t.Helper()
st := store.New(store.Config{Name: "t", Version: "t", Retention: 30 * 24 * time.Hour})
log := slog.New(slog.NewTextHandler(io.Discard, nil))
r, err := NewRemoteRunner(Config{DataDir: t.TempDir()}, st, log, t.TempDir())
if err != nil {
t.Fatal(err)
}
r.StartRemote(nil, nil)
r.IngressFeed = newIngress(st, t.TempDir(), log).Ingest
return r, st
}
func lines(src string, ls ...string) []wire.Line {
var out []wire.Line
for i, l := range ls {
out = append(out, wire.Line{Src: src, Text: l, End: wire.Pos{Inode: 7, Offset: int64(i+1) * 100}})
}
return out
}
// Attempts from a banned address are classified from the node's ban state and
// never become events, scores or evidence: the store learns nothing from them.
func TestIngressNeverFeedsTheStore(t *testing.T) {
r, st := ingressNode(t)
// the node knows 203.0.113.9 is banned by a jail
r.ApplyBatch(lines(wire.SrcFail2ban, "2026-11-20 10:00:00,100 fail2ban.actions [1]: NOTICE [sshd] Ban 203.0.113.9"))
if !st.Banned("203.0.113.9") || st.Banned("198.51.100.1") {
t.Fatal("ban state not read")
}
before := st.IPCount()
now := time.Now().UTC().Format("2006-01-02T15:04:05+00:00")
var in []string
for i := 0; i < 500; i++ {
in = append(in, fmt.Sprintf("%s h kernel: URUTAU-IN: IN=eth0 OUT= SRC=203.0.113.9 DST=10.0.0.5 PROTO=TCP SPT=1 DPT=%d SYN", now, 1000+i%40))
in = append(in, fmt.Sprintf("%s h kernel: URUTAU-IN: IN=eth0 OUT= SRC=198.51.100.%d DST=10.0.0.5 PROTO=TCP SPT=1 DPT=23 SYN", now, 1+i%200))
}
acc, _ := r.ApplyBatch(lines(wire.SrcIngress, in...))
if acc != 1000 {
t.Fatalf("accepted %d", acc)
}
r.ApplyBatch(lines(wire.SrcIngressCnt, "ts=1 total=oops"))
if st.IPCount() != before {
t.Fatalf("ingress created IP records: %d -> %d", before, st.IPCount())
}
if st.KnownHostile("198.51.100.1") {
t.Fatal("an ingress attempt became evidence")
}
// the sources are not events: no runner source exists for them
if r.find("ingress") != nil || r.find("ingresscnt") != nil {
t.Fatal("ingress sources must not be event sources")
}
}
func TestIngressDuplicateLinesAreDropped(t *testing.T) {
r, _ := ingressNode(t)
l := lines(wire.SrcIngress, "x URUTAU-IN: SRC=198.51.100.1 DST=1.1.1.1 PROTO=TCP DPT=23 SYN")
if a, _ := r.ApplyBatch(l); a != 1 {
t.Fatal("first not accepted")
}
if a, d := r.ApplyBatch(l); a != 0 || d != 1 {
t.Fatalf("replay accepted %d dup %d", a, d)
}
}
+11
View File
@@ -16,6 +16,7 @@ import (
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/hub"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/incidents"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/ingress"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/rdns"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/server"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
@@ -57,6 +58,8 @@ type Node struct {
Inc *incidents.Store
Enf *enforce.Engine
Q *hub.CmdQueue
// Ing aggregates the firewall telemetry (ingress.log and ingress.counters).
Ing *ingress.Agg
sh *shared
egr atomic.Pointer[egress.Engine]
@@ -113,6 +116,8 @@ func (sh *shared) newNode(name string, primary bool, rec hub.Probe) (*Node, erro
e.Ingest(l)
}
}
n.Ing = newIngress(st, dir, sh.log)
run.IngressFeed = n.Ing.Ingest
if n.Inc, err = incidents.Open(filepath.Join(dir, "incidents.json"), sh.log); err != nil {
return nil, err
}
@@ -169,6 +174,9 @@ func (n *Node) maintain() {
if err := n.Run.Save(); err != nil {
n.sh.log.Warn("snapshot failed", "node", n.name, "err", err)
}
if err := n.Ing.Save(IngressPath(n.Dir)); err != nil {
n.sh.log.Warn("ingress state not saved", "node", n.name, "err", err)
}
case <-prune.C:
if k := n.St.Prune(); k > 0 {
n.sh.log.Info("pruned old IPs", "node", n.name, "n", k)
@@ -179,6 +187,9 @@ func (n *Node) maintain() {
// Close writes the final snapshot and flushes the queue and the tickets.
func (n *Node) Close() {
if err := n.Ing.Save(IngressPath(n.Dir)); err != nil {
n.sh.log.Warn("final ingress state not saved", "node", n.name, "err", err)
}
if err := n.Run.Save(); err != nil {
n.sh.log.Warn("final snapshot failed", "node", n.name, "err", err)
}
+8
View File
@@ -23,6 +23,7 @@ import (
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/geo"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/hub"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/incidents"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/ingress"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/rdns"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/server"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
@@ -78,6 +79,13 @@ func (n nodeSet) Egress(h string) *egress.Engine {
return nil
}
func (n nodeSet) Ingress(h string) *ingress.Agg {
if nd := n.node(h); nd != nil {
return nd.Ing
}
return nil
}
func (n nodeSet) Incidents(h string) *incidents.Store {
if nd := n.node(h); nd != nil {
return nd.Inc
+26 -1
View File
@@ -105,7 +105,8 @@ func (s *source) status() store.SourceStatus {
// Runner owns the log sources of one instance.
type Runner struct {
St *store.Store
Ignore []netip.Prefix
Ignore []netip.Prefix // --ignore and --trusted: their web requests are counted as own traffic only
Trusted []netip.Prefix // --trusted: the class "trusted"; the rest of Ignore is "internal"
Monitor *regexp.Regexp
MonitorFrom []netip.Prefix // when set, monitors are only believed from these networks
Enr core.Enricher // optional geo and User-Agent resolver
@@ -115,6 +116,9 @@ type Runner struct {
Log *slog.Logger
// EgressFeed receives the "egress" lines of a probe (nil: they are only counted).
EgressFeed func(line []byte)
// IngressFeed receives the "ingress" and "ingresscnt" lines of a probe
// (nil: they are only counted). They never become events.
IngressFeed func(src string, line []byte)
mu sync.Mutex // commit mutex: held while a line is applied and by snapshots
@@ -132,6 +136,9 @@ func NewRunner(c Config, st *store.Store, log *slog.Logger) (*Runner, error) {
return nil, err
}
r := &Runner{St: st, Ignore: ign, DataDir: c.DataDir, Log: log}
if r.Trusted, err = core.ParseCIDRs(c.Trusted); err != nil {
return nil, err
}
if r.MonitorFrom, err = core.ParseCIDRs(c.MonitorFrom); err != nil {
return nil, err
}
@@ -236,6 +243,13 @@ func (r *Runner) feedLocked(src string, text []byte, end store.Offset) bool {
r.EgressFeed(text)
}()
}
} else if src == wire.SrcIngress || src == wire.SrcIngressCnt {
if r.IngressFeed != nil {
func() {
defer func() { recover() }()
r.IngressFeed(src, text)
}()
}
} else if s := r.find(name); s != nil {
r.handle(s)(text)
}
@@ -377,6 +391,17 @@ func (r *Runner) handle(s *source) func([]byte) {
}
s.win.add(false)
if core.Ignored(r.Ignore, ev.IP) {
// own and trusted origins are counted, never analysed
if ev.Source == "traefik" {
if _, err := netip.ParseAddr(ev.IP); err == nil {
class := store.OwnInternal
if core.Ignored(r.Trusted, ev.IP) {
class = store.OwnTrusted
}
s.lastEvent.Store(time.Now().Unix())
r.St.Own(ev, class)
}
}
return
}
if r.monitorTraffic(&ev) {
+1 -1
View File
@@ -2,4 +2,4 @@ package app
// Version is the release version (SemVer). Release builds may override it with
// -ldflags "-X .../internal/app.Version=...".
var Version = "2.2.2"
var Version = "2.3.0"
+371
View File
@@ -0,0 +1,371 @@
package evlog
import (
"bytes"
"encoding/json"
"sync"
)
// Closed days never change, so the studies decode each of them once into a
// compact form (strings interned per day, fields as indexes) and keep it in
// memory under a byte cap. A day is reloaded when the size or modification
// time of its files changes. The current day is always read live.
const (
defaultCacheMem = 96 << 20
loadParallel = 3
crecSize = 112
)
type crec struct {
id uint64
bytes, durMS, t int64
s [15]uint32 // ip cat source host domain method path ua user jail cc fam marker flags proto
status, port int32
tech0, techN uint32
unban bool
}
type cday struct {
day int64
sig [4]int64
recs []crec
strs []string
tech []uint32
mem int64
last uint64
}
type dayLoad struct {
done chan struct{}
d *cday
}
type dayCache struct {
mu sync.Mutex
m map[int64]*cday
fl map[int64]*dayLoad
mem int64
tick uint64
loads int64 // days decoded from disk (for tests and diagnostics)
}
func sigOf(f dayFiles) [4]int64 { return [4]int64{f.gsize, f.gmod, f.jsize, f.jmod} }
type interner struct {
m map[string]uint32
strs []string
mem int64
}
func (in *interner) id(s string) uint32 {
if v, ok := in.m[s]; ok {
return v
}
v := uint32(len(in.strs))
in.m[s] = v
in.strs = append(in.strs, s)
in.mem += int64(len(s)) + 48
return v
}
type dayBuilder struct {
d *cday
in *interner
}
func newBuilder(day int64, sig [4]int64) *dayBuilder {
return &dayBuilder{d: &cday{day: day, sig: sig}, in: &interner{m: map[string]uint32{"": 0}, strs: []string{""}}}
}
func (b *dayBuilder) add(r *Rec) {
in, d := b.in, b.d
c := crec{id: r.ID, t: r.T, bytes: r.Bytes, durMS: r.DurMS, status: int32(r.Status), port: int32(r.Port), unban: r.Unban}
c.s = [15]uint32{in.id(r.IP), in.id(r.Cat), in.id(r.Source), in.id(r.Host), in.id(r.Domain), in.id(r.Method), in.id(r.Path),
in.id(r.UA), in.id(r.User), in.id(r.Jail), in.id(r.CC), in.id(r.Fam), in.id(r.Marker), in.id(r.Flags), in.id(r.Proto)}
if len(r.Tech) > 0 {
c.tech0, c.techN = uint32(len(d.tech)), uint32(len(r.Tech))
for _, t := range r.Tech {
d.tech = append(d.tech, in.id(t))
}
}
d.recs = append(d.recs, c)
}
func (b *dayBuilder) done() *cday {
d := b.d
d.recs = append([]crec(nil), d.recs...) // trim the slack
d.strs = b.in.strs
d.mem = int64(len(d.recs))*crecSize + int64(len(d.tech))*4 + b.in.mem
return d
}
// decodeDay reads a whole day into compact form.
func (l *Log) decodeDay(f dayFiles) *cday {
b := newBuilder(f.day, sigOf(f))
l.readDay(f, func(line []byte) bool {
var r Rec
if json.Unmarshal(line, &r) == nil && r.IP != "" {
b.add(&r)
}
return true
}, nil, nil, nil)
return b.done()
}
// Ref points at one event of a decoded day without copying it.
type Ref struct {
d *cday
i uint32
}
// Rec rebuilds the event.
func (r Ref) Rec() Rec { return r.d.rec(&r.d.recs[r.i]) }
// IP is the address of the event, without rebuilding the rest.
func (r Ref) IP() string { return r.d.strs[r.d.recs[r.i].s[0]] }
// T is the time of the event.
func (r Ref) T() int64 { return r.d.recs[r.i].t }
// ScanRefs visits the matching events as references into the decoded days
// (the live day is decoded into a private one), so a long study keeps 16 bytes
// per event instead of a copy. The references keep their days alive.
func (l *Log) ScanRefs(f Filter, maxBytes int64, fn func(Ref) bool) ScanInfo {
var info ScanInfo
var live *dayBuilder
var liveDay int64 = -1
flush := func(stop bool) bool {
if live == nil {
return stop
}
d := live.done()
live = nil
for i := range d.recs {
if !fn(Ref{d, uint32(i)}) {
return true
}
}
return stop
}
info = l.scanDays(f, maxBytes, func(d *cday, idx []uint32) bool {
for _, i := range idx {
if !fn(Ref{d, i}) {
return false
}
}
return true
}, func(day int64, r *Rec) bool {
if live == nil || liveDay != day {
flush(false)
live, liveDay = newBuilder(day, [4]int64{}), day
}
live.add(r)
return true
})
flush(false)
return info
}
func (d *cday) rec(c *crec) Rec {
s := d.strs
r := Rec{ID: c.id, T: c.t, IP: s[c.s[0]], Cat: s[c.s[1]], Source: s[c.s[2]], Host: s[c.s[3]], Domain: s[c.s[4]],
Method: s[c.s[5]], Path: s[c.s[6]], Status: int(c.status), UA: s[c.s[7]], User: s[c.s[8]], Jail: s[c.s[9]], CC: s[c.s[10]],
Unban: c.unban, Fam: s[c.s[11]], Marker: s[c.s[12]], Bytes: c.bytes, DurMS: c.durMS, Flags: s[c.s[13]], Port: int(c.port), Proto: s[c.s[14]]}
if c.techN > 0 {
r.Tech = make([]string, c.techN)
for i := range r.Tech {
r.Tech[i] = s[d.tech[c.tech0+uint32(i)]]
}
}
return r
}
// day returns the decoded day, from memory when its files did not change.
func (l *Log) day(f dayFiles) *cday {
c := &l.dc
for {
c.mu.Lock()
if d, ok := c.m[f.day]; ok && d.sig == sigOf(f) {
c.tick++
d.last = c.tick
c.mu.Unlock()
return d
}
if fl, ok := c.fl[f.day]; ok {
c.mu.Unlock()
<-fl.done
if fl.d != nil && fl.d.sig == sigOf(f) {
return fl.d
}
continue
}
fl := &dayLoad{done: make(chan struct{})}
if c.fl == nil {
c.fl = map[int64]*dayLoad{}
}
c.fl[f.day] = fl
c.mu.Unlock()
d := l.decodeDay(f)
c.mu.Lock()
c.loads++
delete(c.fl, f.day)
fl.d = d
if cap := l.cacheCap(); cap > 0 && d.mem <= cap {
if c.m == nil {
c.m = map[int64]*cday{}
}
if old, ok := c.m[f.day]; ok {
c.mem -= old.mem
}
c.tick++
d.last = c.tick
c.m[f.day], c.mem = d, c.mem+d.mem
for c.mem > cap { // evict the least recently used other days
var victim *cday
for _, x := range c.m {
if x != d && (victim == nil || x.last < victim.last) {
victim = x
}
}
if victim == nil {
break
}
delete(c.m, victim.day)
c.mem -= victim.mem
}
}
c.mu.Unlock()
close(fl.done)
return d
}
}
func (l *Log) cacheCap() int64 {
switch {
case l.opt.CacheMem < 0:
return 0
case l.opt.CacheMem == 0:
return defaultCacheMem
}
return l.opt.CacheMem
}
// CacheStats reports the decoded days held and their approximate size.
func (l *Log) CacheStats() (days int, mem, loads int64) {
l.dc.mu.Lock()
defer l.dc.mu.Unlock()
return len(l.dc.m), l.dc.mem, l.dc.loads
}
// ScanRecs is Scan for callers that do not need the raw line. Closed days are
// served from the decoded day cache, so a repeated study of a long window does
// not decompress and parse the registry again; the current day is read live.
// The byte budget counts only what is read from disk: a cached day is bounded
// by the cache itself.
func (l *Log) ScanRecs(f Filter, maxBytes int64, newestFirst bool, fn func(Rec) bool) ScanInfo {
if l.cacheCap() <= 0 || newestFirst {
return l.Scan(f, maxBytes, newestFirst, func(r Rec, _ []byte) bool { return fn(r) })
}
return l.scanDays(f, maxBytes, func(d *cday, idx []uint32) bool {
for _, i := range idx {
if !fn(d.rec(&d.recs[i])) {
return false
}
}
return true
}, func(_ int64, r *Rec) bool { return fn(*r) })
}
// scanDays walks the days of the window in order: closed days through the
// cache (day and the indexes of its matching events), the live day line by
// line (live).
func (l *Log) scanDays(f Filter, maxBytes int64, closed func(*cday, []uint32) bool, live func(day int64, r *Rec) bool) ScanInfo {
if maxBytes <= 0 {
maxBytes = 512 << 20
}
f.Prepare()
files := l.daysIn(f.From, f.To)
today := l.opt.Now().Unix() / 86400
var info ScanInfo
var snap map[int64]jsnap
for i := 0; i < len(files); {
if info.Bytes >= maxBytes {
info.Truncated = true
break
}
if files[i].day >= today || l.cacheCap() <= 0 { // live day: read the files
if snap == nil {
snap = l.begin()
}
stop := false
rng := &[2]int64{f.From, f.To}
day := files[i].day
l.readDay(files[i], func(line []byte) bool {
if info.Bytes >= maxBytes {
info.Truncated, stop = true, true
return false
}
info.Lines++
if f.ipText != nil && !bytes.Contains(line, f.ipText) {
return true
}
var r Rec
if json.Unmarshal(line, &r) != nil || r.IP == "" || !f.Match(&r) {
return true
}
info.Matched++
if !live(day, &r) {
stop = true
return false
}
return true
}, &info.Bytes, rng, snap)
if stop {
break
}
i++
continue
}
// a batch of closed days, decoded in parallel
j := i
for j < len(files) && j-i < loadParallel && files[j].day < today {
j++
}
days := make([]*cday, j-i)
var wg sync.WaitGroup
for k := range days {
wg.Add(1)
go func() {
defer wg.Done()
days[k] = l.day(files[i+k])
}()
}
wg.Wait()
for _, d := range days {
var idx []uint32
for x := range d.recs {
c := &d.recs[x]
info.Lines++
if c.t < f.From || (f.To != 0 && c.t > f.To) {
continue
}
if f.Host != "" || len(f.Cats) > 0 || f.Fam != "" || f.IP != "" || f.qLower != "" {
r := d.rec(c)
if !f.Match(&r) {
continue
}
}
idx = append(idx, uint32(x))
}
info.Matched += int64(len(idx))
if !closed(d, idx) {
return info
}
}
i = j
}
return info
}
+6 -2
View File
@@ -94,6 +94,7 @@ type Options struct {
SyncEvery time.Duration // flush+fsync period (default 2 s)
Now func() time.Time
Log *slog.Logger
CacheMem int64 // bytes of decoded closed days kept in memory (default 96 MB, <0 off)
}
type file interface {
@@ -123,6 +124,7 @@ type Log struct {
gidx map[string]*dayIdx // hour index of compressed day files (sidecar .idx)
jidx map[int64]*jIdx // hour runs of plain day files written by this process
needNL map[int64]bool
dc dayCache
}
type blk struct {
@@ -396,6 +398,8 @@ type dayFiles struct {
gsize int64
hasJSONL bool
hasGZ bool
gmod int64 // modification times (ns), part of the cache signature
jmod int64
}
// list returns the day files in the directory, oldest first.
@@ -432,9 +436,9 @@ func (l *Log) list() []dayFiles {
continue
}
if gz {
f.gz, f.gsize, f.hasGZ = filepath.Join(l.opt.Dir, name), info.Size(), true
f.gz, f.gsize, f.hasGZ, f.gmod = filepath.Join(l.opt.Dir, name), info.Size(), true, info.ModTime().UnixNano()
} else {
f.jsonl, f.jsize, f.hasJSONL = filepath.Join(l.opt.Dir, name), info.Size(), true
f.jsonl, f.jsize, f.hasJSONL, f.jmod = filepath.Join(l.opt.Dir, name), info.Size(), true, info.ModTime().UnixNano()
}
}
out := make([]dayFiles, 0, len(by))
+529
View File
@@ -0,0 +1,529 @@
package ingress
import (
"encoding/json"
"errors"
"os"
"sort"
"strconv"
"strings"
"sync"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
// Bounds that keep the memory of one host fixed (30 days of hourly buckets,
// each with capped top lists).
const (
Retention = 30 * 24 * time.Hour
maxPorts = 48
maxASNs = 48
maxCCs = 64
maxOrgLen = 80
maxDelta = 1 << 40 // per-minute counter delta beyond this is a corrupt line
maxFileLen = 64 << 20
)
type asnRec struct {
Org string `json:"o,omitempty"`
N uint32 `json:"n"`
}
// bucket is one hour. The exact totals come from the counters; Logged and the
// top lists come from the sampled log lines.
type bucket struct {
Total uint64 `json:"t"`
TCP uint64 `json:"tcp"`
UDP uint64 `json:"udp"`
ICMP uint64 `json:"icmp"`
Open uint64 `json:"open"`
Logged uint32 `json:"l"`
// of the sample: to a served port, from a source banned at that moment
LoggedOpen uint32 `json:"lo"`
LoggedBanned uint32 `json:"lb"`
Ports map[string]uint32 `json:"ports,omitempty"` // "tcp/22/c": proto, port, c(losed)|o(pen)
ASNs map[string]*asnRec `json:"asns,omitempty"` // "AS16509"
CCs map[string]uint32 `json:"ccs,omitempty"`
}
// Agg aggregates one host. Banned and Geo are injected by the hub wiring, so
// this package knows nothing about the store.
type Agg struct {
// Banned reports whether the address is banned by a jail right now.
Banned func(ip string) bool
// Geo returns the country code, "AS<number>" and the organization.
Geo func(ip string) (cc, asn, org string)
Now func() time.Time
mu sync.Mutex
hours map[int64]*bucket // unix hour
prev *Counters
dirty bool
lines uint64
counts uint64
bad uint64
lastLine int64 // unix seconds of the last accepted sampled line (by arrival)
lastCnt int64 // ts of the last accepted counters line
}
func New() *Agg {
return &Agg{hours: map[int64]*bucket{}, Now: time.Now}
}
func hourOf(ts int64) int64 { return ts - ts%3600 }
func (a *Agg) bucketLocked(h int64) *bucket {
b := a.hours[h]
if b == nil {
b = &bucket{}
a.hours[h] = b
}
return b
}
func (a *Agg) validTime(ts int64) bool {
now := a.Now().Unix()
return ts <= now+3600 && ts >= now-int64(Retention/time.Second)
}
// Ingest applies one line of a probe source (wire.SrcIngress or
// wire.SrcIngressCnt). It never panics on hostile input and never has an
// effect outside this aggregate.
func (a *Agg) Ingest(src string, line []byte) {
defer func() { _ = recover() }()
switch src {
case wire.SrcIngressCnt:
a.ingestCounters(line)
case wire.SrcIngress:
a.ingestHit(line)
}
}
func (a *Agg) ingestCounters(line []byte) {
c, err := ParseCounters(line)
a.mu.Lock()
defer a.mu.Unlock()
if err != nil || !a.validTime(c.TS) {
a.bad++
return
}
a.counts++
a.lastCnt = max(a.lastCnt, c.TS)
p := a.prev
cur := c
a.prev = &cur
a.dirty = true
if p == nil || c.TS <= p.TS {
return // first line (no baseline) or not newer: no delta
}
d := Counters{TS: c.TS, Total: c.Total - p.Total, TCP: c.TCP - p.TCP, UDP: c.UDP - p.UDP, ICMP: c.ICMP - p.ICMP, Open: c.Open - p.Open}
if c.Total < p.Total || c.TCP < p.TCP || c.UDP < p.UDP || c.ICMP < p.ICMP || c.Open < p.Open {
// the table was reloaded (or the host rebooted): the counters restarted
d = Counters{TS: c.TS, Total: c.Total, TCP: c.TCP, UDP: c.UDP, ICMP: c.ICMP, Open: c.Open}
}
if d.Total > maxDelta || d.TCP > maxDelta || d.UDP > maxDelta || d.ICMP > maxDelta || d.Open > maxDelta {
a.bad++
return
}
b := a.bucketLocked(hourOf(c.TS))
b.Total += d.Total
b.TCP += d.TCP
b.UDP += d.UDP
b.ICMP += d.ICMP
b.Open += d.Open
a.pruneLocked()
}
func (a *Agg) ingestHit(line []byte) {
h, err := ParseHit(line, a.Now())
a.mu.Lock()
if err != nil {
if !errors.Is(err, ErrNotIngress) {
a.bad++
}
a.mu.Unlock()
return
}
if !a.validTime(h.Time.Unix()) {
a.bad++
a.mu.Unlock()
return
}
a.mu.Unlock()
ip := h.Src.String()
// the callbacks run outside the lock: the store takes its own
banned := a.Banned != nil && a.Banned(ip)
var cc, asn, org string
if a.Geo != nil {
cc, asn, org = a.Geo(ip)
}
a.mu.Lock()
defer a.mu.Unlock()
a.lines++
a.lastLine = a.Now().Unix()
a.dirty = true
b := a.bucketLocked(hourOf(h.Time.Unix()))
b.Logged++
if h.Open {
b.LoggedOpen++
}
if banned {
b.LoggedBanned++
}
if h.DPort != 0 {
k := h.Proto + "/" + strconv.Itoa(int(h.DPort)) + "/c"
if h.Open {
k = h.Proto + "/" + strconv.Itoa(int(h.DPort)) + "/o"
}
if b.Ports == nil {
b.Ports = map[string]uint32{}
}
if _, ok := b.Ports[k]; ok || len(b.Ports) < maxPorts {
b.Ports[k]++
}
}
if len(asn) > 0 && len(asn) <= 12 {
if b.ASNs == nil {
b.ASNs = map[string]*asnRec{}
}
if r, ok := b.ASNs[asn]; ok {
r.N++
} else if len(b.ASNs) < maxASNs {
if len(org) > maxOrgLen {
org = org[:maxOrgLen]
}
b.ASNs[asn] = &asnRec{Org: toValid(org), N: 1}
}
}
if len(cc) == 2 {
if b.CCs == nil {
b.CCs = map[string]uint32{}
}
if _, ok := b.CCs[cc]; ok || len(b.CCs) < maxCCs {
b.CCs[cc]++
}
}
a.pruneLocked()
}
func toValid(s string) string {
out := make([]rune, 0, len(s))
for _, r := range s {
if r >= 0x20 && r != 0x7f && r != 0xFFFD {
out = append(out, r)
}
}
return string(out)
}
func (a *Agg) pruneLocked() {
cut := hourOf(a.Now().Unix() - int64(Retention/time.Second))
for h := range a.hours {
if h < cut {
delete(a.hours, h)
}
}
}
// ---- report ----
type Source struct {
State string `json:"state"` // waiting|following
LastCounters int64 `json:"last_counters"`
LastLine int64 `json:"last_line"`
Lines uint64 `json:"lines"`
Counters uint64 `json:"counter_lines"`
Malformed uint64 `json:"malformed"`
}
type Totals struct {
Attempts uint64 `json:"attempts"` // exact
TCP uint64 `json:"tcp"`
UDP uint64 `json:"udp"`
ICMP uint64 `json:"icmp"`
Open uint64 `json:"open"` // to a port the host serves (tcp+udp)
Closed uint64 `json:"closed"` // to a port nothing serves (tcp+udp)
ClosedPct float64 `json:"closed_pct"`
PerHour float64 `json:"per_hour"` // exact, over the hours covered by counters
}
type Sample struct {
Logged uint64 `json:"logged"`
LoggedBanned uint64 `json:"logged_banned"`
Ratio float64 `json:"ratio"` // logged / exact attempts: how much of the total the details cover
BannedPct float64 `json:"banned_pct"` // of the sample, from sources banned at that moment
BannedEst uint64 `json:"banned_est"` // BannedPct applied to the exact total (an estimate)
}
type Hour struct {
T int64 `json:"t"`
Total uint64 `json:"total"`
Open uint64 `json:"open"`
Closed uint64 `json:"closed"`
Logged uint32 `json:"logged"`
}
type PortRow struct {
Proto string `json:"proto"`
Port uint16 `json:"port"`
N uint64 `json:"n"` // in the sample
Served bool `json:"served"`
Pct float64 `json:"pct"`
}
type ASNRow struct {
ASN string `json:"asn"`
Org string `json:"org,omitempty"`
N uint64 `json:"n"`
Pct float64 `json:"pct"`
}
type CCRow struct {
CC string `json:"cc"`
N uint64 `json:"n"`
Pct float64 `json:"pct"`
}
// Report is what GET /api/v1/ingress returns for one host and window.
type Report struct {
Enabled bool `json:"enabled"`
From int64 `json:"from"`
To int64 `json:"to"`
Source Source `json:"source"`
Totals Totals `json:"totals"`
Sample Sample `json:"sample"`
Hourly []Hour `json:"hourly"`
Ports []PortRow `json:"ports"`
ASNs []ASNRow `json:"asns"`
CCs []CCRow `json:"countries"`
}
const topN = 15
func pct(n, d uint64) float64 {
if d == 0 {
return 0
}
return float64(int(float64(n)/float64(d)*1000+0.5)) / 10
}
func (a *Agg) Info() Source {
a.mu.Lock()
defer a.mu.Unlock()
return a.infoLocked()
}
func (a *Agg) infoLocked() Source {
s := Source{State: "waiting", LastCounters: a.lastCnt, LastLine: a.lastLine, Lines: a.lines, Counters: a.counts, Malformed: a.bad}
if a.counts > 0 || a.lines > 0 {
s.State = "following"
}
return s
}
// Report builds the report of [from, to) (unix seconds) of one host.
func (a *Agg) Report(from, to int64) Report { return ReportOf([]*Agg{a}, from, to) }
// ReportOf builds one report over several hosts (the "all hosts" view): the
// exact totals add up, the sampled lists are merged before the top is taken.
func ReportOf(aggs []*Agg, from, to int64) Report {
r := Report{From: from, To: to, Source: Source{State: "waiting"}, Hourly: []Hour{}, Ports: []PortRow{}, ASNs: []ASNRow{}, CCs: []CCRow{}}
ports := map[string]uint64{}
asns := map[string]*ASNRow{}
ccs := map[string]uint64{}
hours := map[int64]*Hour{}
var hoursWithCounters int
for _, a := range aggs {
if a == nil {
continue
}
a.mu.Lock()
si := a.infoLocked()
if si.State == "following" {
r.Source.State = "following"
}
r.Source.LastCounters, r.Source.LastLine = max(r.Source.LastCounters, si.LastCounters), max(r.Source.LastLine, si.LastLine)
r.Source.Lines += si.Lines
r.Source.Counters += si.Counters
r.Source.Malformed += si.Malformed
for h, b := range a.hours {
if h+3600 <= from || h >= to {
continue
}
r.Totals.Attempts += b.Total
r.Totals.TCP += b.TCP
r.Totals.UDP += b.UDP
r.Totals.ICMP += b.ICMP
r.Totals.Open += b.Open
r.Sample.Logged += uint64(b.Logged)
r.Sample.LoggedBanned += uint64(b.LoggedBanned)
row := hours[h]
if row == nil {
row = &Hour{T: h}
hours[h] = row
}
row.Total += b.Total
row.Open += b.Open
row.Logged += b.Logged
if b.TCP+b.UDP > b.Open {
row.Closed += b.TCP + b.UDP - b.Open
}
for k, n := range b.Ports {
ports[k] += uint64(n)
}
for k, v := range b.ASNs {
row := asns[k]
if row == nil {
row = &ASNRow{ASN: k, Org: v.Org}
asns[k] = row
}
row.N += uint64(v.N)
}
for k, n := range b.CCs {
ccs[k] += uint64(n)
}
}
a.mu.Unlock()
}
r.Enabled = r.Source.State != "waiting"
for _, h := range hours {
r.Hourly = append(r.Hourly, *h)
if h.Total > 0 {
hoursWithCounters++
}
}
sort.Slice(r.Hourly, func(i, j int) bool { return r.Hourly[i].T < r.Hourly[j].T })
t := &r.Totals
if t.TCP+t.UDP > t.Open {
t.Closed = t.TCP + t.UDP - t.Open
}
t.ClosedPct = pct(t.Closed, t.TCP+t.UDP)
if hoursWithCounters > 0 {
t.PerHour = float64(int(float64(t.Attempts)/float64(hoursWithCounters)*10+0.5)) / 10
}
s := &r.Sample
if t.Attempts > 0 {
s.Ratio = float64(int(float64(s.Logged)/float64(t.Attempts)*10000+0.5)) / 10000
}
s.BannedPct = pct(s.LoggedBanned, s.Logged)
if s.Logged > 0 {
s.BannedEst = uint64(float64(s.LoggedBanned) / float64(s.Logged) * float64(t.Attempts))
}
for k, n := range ports {
var proto, port, class string
if !splitPort(k, &proto, &port, &class) {
continue
}
p, _ := strconv.Atoi(port)
r.Ports = append(r.Ports, PortRow{Proto: proto, Port: uint16(p), N: n, Served: class == "o", Pct: pct(n, s.Logged)})
}
sort.Slice(r.Ports, func(i, j int) bool {
if r.Ports[i].N != r.Ports[j].N {
return r.Ports[i].N > r.Ports[j].N
}
return r.Ports[i].Port < r.Ports[j].Port
})
if len(r.Ports) > topN {
r.Ports = r.Ports[:topN]
}
for _, row := range asns {
row.Pct = pct(row.N, s.Logged)
r.ASNs = append(r.ASNs, *row)
}
sort.Slice(r.ASNs, func(i, j int) bool {
if r.ASNs[i].N != r.ASNs[j].N {
return r.ASNs[i].N > r.ASNs[j].N
}
return r.ASNs[i].ASN < r.ASNs[j].ASN
})
if len(r.ASNs) > topN {
r.ASNs = r.ASNs[:topN]
}
for cc, n := range ccs {
r.CCs = append(r.CCs, CCRow{CC: cc, N: n, Pct: pct(n, s.Logged)})
}
sort.Slice(r.CCs, func(i, j int) bool {
if r.CCs[i].N != r.CCs[j].N {
return r.CCs[i].N > r.CCs[j].N
}
return r.CCs[i].CC < r.CCs[j].CC
})
if len(r.CCs) > topN {
r.CCs = r.CCs[:topN]
}
return r
}
func splitPort(k string, proto, port, class *string) bool {
i, j := strings.Index(k, "/"), strings.LastIndex(k, "/")
if i <= 0 || j <= i || j == len(k)-1 {
return false
}
*proto, *port, *class = k[:i], k[i+1:j], k[j+1:]
return true
}
// ---- persistence ----
type saved struct {
V int `json:"v"`
Prev *Counters `json:"prev,omitempty"`
Hours map[int64]*bucket `json:"hours"`
Lines uint64 `json:"lines"`
Cnts uint64 `json:"cnts"`
Bad uint64 `json:"bad"`
LastL int64 `json:"last_line"`
LastC int64 `json:"last_cnt"`
}
// Save writes the aggregate atomically when it changed since the last save.
func (a *Agg) Save(path string) error {
a.mu.Lock()
if !a.dirty {
a.mu.Unlock()
return nil
}
b, err := json.Marshal(saved{V: 1, Prev: a.prev, Hours: a.hours, Lines: a.lines, Cnts: a.counts, Bad: a.bad, LastL: a.lastLine, LastC: a.lastCnt})
a.dirty = false
a.mu.Unlock()
if err != nil {
return err
}
tmp := path + ".tmp"
if err := os.WriteFile(tmp, b, 0o600); err != nil {
return err
}
return os.Rename(tmp, path)
}
// Load restores a saved aggregate; a missing or damaged file leaves it empty.
func (a *Agg) Load(path string) error {
st, err := os.Stat(path)
if err != nil {
return nil
}
if st.Size() > maxFileLen {
return errors.New("ingress state too large")
}
raw, err := os.ReadFile(path)
if err != nil {
return err
}
var s saved
if err := json.Unmarshal(raw, &s); err != nil || s.V != 1 {
return errors.New("ingress state unreadable")
}
a.mu.Lock()
defer a.mu.Unlock()
a.prev, a.lines, a.counts, a.bad, a.lastLine, a.lastCnt = s.Prev, s.Lines, s.Cnts, s.Bad, s.LastL, s.LastC
for h, b := range s.Hours {
if b == nil || h%3600 != 0 || len(b.Ports) > maxPorts || len(b.ASNs) > maxASNs || len(b.CCs) > maxCCs {
continue
}
a.hours[h] = b
}
a.pruneLocked()
return nil
}
+236
View File
@@ -0,0 +1,236 @@
package ingress
import (
"fmt"
"path/filepath"
"strings"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
var t0 = time.Date(2026, 11, 20, 10, 5, 0, 0, time.UTC)
func hitLine(marker, src, proto string, dpt int, flags string) string {
return fmt.Sprintf("2026-11-20T10:05:00+00:00 host kernel: %s IN=eth0 OUT= MAC=aa SRC=%s DST=10.0.0.5 LEN=60 PROTO=%s SPT=4444 DPT=%d %s", marker, src, proto, dpt, flags)
}
func newAgg() *Agg {
a := New()
a.Now = func() time.Time { return t0 }
return a
}
func TestParseHit(t *testing.T) {
h, err := ParseHit([]byte(hitLine("URUTAU-IN:", "203.0.113.9", "TCP", 3389, "SYN")), t0)
if err != nil || h.Proto != "tcp" || h.DPort != 3389 || h.Open || h.Src.String() != "203.0.113.9" {
t.Fatalf("closed tcp: %+v %v", h, err)
}
h, err = ParseHit([]byte(hitLine("URUTAU-INO:", "203.0.113.9", "TCP", 22, "SYN")), t0)
if err != nil || !h.Open {
t.Fatalf("open tcp: %+v %v", h, err)
}
h, err = ParseHit([]byte(hitLine("URUTAU-IN:", "203.0.113.9", "ICMP", 0, "")), t0)
if err != nil || h.Proto != "icmp" || h.DPort != 0 {
t.Fatalf("icmp: %+v %v", h, err)
}
}
func TestParseHitRejects(t *testing.T) {
bad := map[string]string{
"not ours": "Nov 20 kernel: something else",
"ack": hitLine("URUTAU-IN:", "203.0.113.9", "TCP", 80, "SYN ACK"),
"no syn": hitLine("URUTAU-IN:", "203.0.113.9", "TCP", 80, "ACK"),
"no port": hitLine("URUTAU-IN:", "203.0.113.9", "TCP", 0, "SYN"),
"private src": hitLine("URUTAU-IN:", "192.168.1.5", "TCP", 80, "SYN"),
"loopback src": hitLine("URUTAU-IN:", "127.0.0.1", "TCP", 80, "SYN"),
"link-local": hitLine("URUTAU-IN:", "169.254.1.1", "TCP", 80, "SYN"),
"multicast": hitLine("URUTAU-IN:", "224.0.0.1", "UDP", 80, ""),
"bad src": "kernel: URUTAU-IN: SRC=999.1.1.1 DST=1.2.3.4 PROTO=TCP DPT=1 SYN",
"gre": hitLine("URUTAU-IN:", "203.0.113.9", "GRE", 0, ""),
"no proto": "kernel: URUTAU-IN: SRC=203.0.113.9 DST=1.2.3.4",
"injection": "kernel: URUTAU-IN: SRC=203.0.113.9;rm DST=1.2.3.4 PROTO=TCP DPT=1 SYN",
"oversize line": hitLine("URUTAU-IN:", "203.0.113.9", "TCP", 80, "SYN") + strings.Repeat(" X=1", 1000),
}
for name, l := range bad {
if _, err := ParseHit([]byte(l), t0); err == nil {
t.Errorf("%s: accepted", name)
}
}
}
func TestParseCounters(t *testing.T) {
c, err := ParseCounters([]byte("ts=1767225600 total=120 tcp=100 udp=15 icmp=5 open=30 future=7"))
if err != nil || c.Total != 120 || c.Open != 30 || c.TS != 1767225600 {
t.Fatalf("%+v %v", c, err)
}
for name, l := range map[string]string{
"empty": "",
"missing": "ts=1 total=1 tcp=1 udp=0 icmp=0",
"duplicate": "ts=1 total=1 tcp=1 tcp=1 udp=0 icmp=0 open=0",
"negative": "ts=1 total=-1 tcp=0 udp=0 icmp=0 open=0",
"text": "ts=1 total=abc tcp=0 udp=0 icmp=0 open=0",
"huge": "ts=1 total=99999999999999999999 tcp=0 udp=0 icmp=0 open=0",
"no equals": "ts=1 total=1 tcp=1 udp=0 icmp=0 open=0 junk",
"zero ts": "ts=0 total=1 tcp=1 udp=0 icmp=0 open=0",
"open > l4": "ts=5 total=10 tcp=1 udp=0 icmp=0 open=9",
"parts > total": "ts=5 total=10 tcp=100000 udp=0 icmp=0 open=0",
"oversize": "ts=1 total=1 tcp=1 udp=0 icmp=0 open=0 " + strings.Repeat("x=1 ", 100),
} {
if _, err := ParseCounters([]byte(l)); err == nil {
t.Errorf("%s: accepted", name)
}
}
}
func cnt(ts int64, total, tcp, udp, icmp, open int) []byte {
return []byte(fmt.Sprintf("ts=%d total=%d tcp=%d udp=%d icmp=%d open=%d", ts, total, tcp, udp, icmp, open))
}
func TestExactTotalsFromCounterDeltas(t *testing.T) {
a := newAgg()
base := t0.Unix() - 600
a.Ingest(wire.SrcIngressCnt, cnt(base, 1000, 900, 90, 10, 100)) // baseline: no delta
a.Ingest(wire.SrcIngressCnt, cnt(base+60, 1100, 980, 110, 10, 130))
a.Ingest(wire.SrcIngressCnt, cnt(base+120, 1160, 1030, 120, 10, 140))
a.Ingest(wire.SrcIngressCnt, cnt(base+120, 5000, 1030, 120, 10, 140)) // same ts: ignored
r := a.Report(base-3600, t0.Unix()+3600)
if r.Totals.Attempts != 160 || r.Totals.TCP != 130 || r.Totals.UDP != 30 || r.Totals.ICMP != 0 || r.Totals.Open != 40 {
t.Fatalf("totals %+v", r.Totals)
}
if r.Totals.Closed != 120 || r.Totals.ClosedPct != 75 {
t.Fatalf("closed %+v", r.Totals)
}
if !r.Enabled || r.Source.State != "following" {
t.Fatalf("source %+v", r.Source)
}
}
func TestCounterResetCountsFromZero(t *testing.T) {
a := newAgg()
base := t0.Unix() - 300
a.Ingest(wire.SrcIngressCnt, cnt(base, 1000, 1000, 0, 0, 0))
a.Ingest(wire.SrcIngressCnt, cnt(base+60, 40, 40, 0, 0, 5)) // table reloaded
r := a.Report(base-3600, t0.Unix()+3600)
if r.Totals.Attempts != 40 {
t.Fatalf("reset: %+v", r.Totals)
}
}
func TestCounterAbsurdDeltaAndTimesDropped(t *testing.T) {
a := newAgg()
base := t0.Unix() - 300
a.Ingest(wire.SrcIngressCnt, cnt(base, 1, 1, 0, 0, 0))
a.Ingest(wire.SrcIngressCnt, cnt(base+60, 1<<45, 1<<45, 0, 0, 0))
a.Ingest(wire.SrcIngressCnt, cnt(t0.Unix()+86400*5, 10, 10, 0, 0, 0)) // far future
a.Ingest(wire.SrcIngressCnt, cnt(t0.Unix()-86400*400, 10, 10, 0, 0, 0))
if r := a.Report(0, t0.Unix()+86400*10); r.Totals.Attempts != 0 {
t.Fatalf("absurd: %+v", r.Totals)
}
if a.Info().Malformed < 3 {
t.Fatalf("malformed %d", a.Info().Malformed)
}
}
func TestSampleDetailsRatioAndBannedShare(t *testing.T) {
a := newAgg()
banned := map[string]bool{"203.0.113.9": true}
a.Banned = func(ip string) bool { return banned[ip] }
a.Geo = func(ip string) (string, string, string) { return "RU", "AS64500", "Example Net" }
base := t0.Unix() - 300
a.Ingest(wire.SrcIngressCnt, cnt(base, 0, 0, 0, 0, 0))
a.Ingest(wire.SrcIngressCnt, cnt(base+60, 1000, 1000, 0, 0, 0))
for i := 0; i < 6; i++ {
a.Ingest(wire.SrcIngress, []byte(hitLine("URUTAU-IN:", "203.0.113.9", "TCP", 3389, "SYN")))
}
for i := 0; i < 4; i++ {
a.Ingest(wire.SrcIngress, []byte(hitLine("URUTAU-INO:", "198.51.100.7", "TCP", 22, "SYN")))
}
r := a.Report(base-3600, t0.Unix()+3600)
if r.Sample.Logged != 10 || r.Sample.LoggedBanned != 6 || r.Sample.BannedPct != 60 {
t.Fatalf("sample %+v", r.Sample)
}
if r.Sample.Ratio != 0.01 || r.Sample.BannedEst != 600 {
t.Fatalf("ratio %+v", r.Sample)
}
if len(r.Ports) != 2 || r.Ports[0].Port != 3389 || r.Ports[0].Served || r.Ports[0].N != 6 || !r.Ports[1].Served {
t.Fatalf("ports %+v", r.Ports)
}
if len(r.ASNs) != 1 || r.ASNs[0].ASN != "AS64500" || r.ASNs[0].N != 10 || len(r.CCs) != 1 || r.CCs[0].CC != "RU" {
t.Fatalf("origins %+v %+v", r.ASNs, r.CCs)
}
// the ban state is read at the time of the line: unbanning later changes nothing retroactively
delete(banned, "203.0.113.9")
if r2 := a.Report(base-3600, t0.Unix()+3600); r2.Sample.LoggedBanned != 6 {
t.Fatalf("retroactive: %+v", r2.Sample)
}
}
func TestBucketsAreBounded(t *testing.T) {
a := newAgg()
a.Geo = func(ip string) (string, string, string) { return "", "", "" }
for i := 0; i < maxPorts*3; i++ {
a.Ingest(wire.SrcIngress, []byte(hitLine("URUTAU-IN:", "203.0.113.9", "TCP", 1000+i, "SYN")))
}
a.mu.Lock()
n := len(a.hours[hourOf(t0.Unix())].Ports)
a.mu.Unlock()
if n != maxPorts {
t.Fatalf("ports kept %d, want %d", n, maxPorts)
}
}
func TestHostileLinesNeverPanic(t *testing.T) {
a := newAgg()
for _, l := range []string{"", "\x00\x01", strings.Repeat("A", 100000), "URUTAU-IN:", "URUTAU-INO: SRC= DST= PROTO=", "URUTAU-IN: SRC=::ffff:203.0.113.1 DST=1.1.1.1 PROTO=TCP DPT=99999 SYN"} {
a.Ingest(wire.SrcIngress, []byte(l))
a.Ingest(wire.SrcIngressCnt, []byte(l))
}
a.Ingest("bogus", []byte("x"))
}
func TestSaveLoadAndRetention(t *testing.T) {
a := newAgg()
base := t0.Unix() - 300
a.Ingest(wire.SrcIngressCnt, cnt(base, 0, 0, 0, 0, 0))
a.Ingest(wire.SrcIngressCnt, cnt(base+60, 50, 50, 0, 0, 0))
p := filepath.Join(t.TempDir(), "ingress.json")
if err := a.Save(p); err != nil {
t.Fatal(err)
}
b := newAgg()
if err := b.Load(p); err != nil {
t.Fatal(err)
}
if r := b.Report(0, t0.Unix()+3600); r.Totals.Attempts != 50 {
t.Fatalf("loaded %+v", r.Totals)
}
// a later clock prunes the old hour
b.Now = func() time.Time { return t0.Add(Retention + 2*time.Hour) }
b.Ingest(wire.SrcIngressCnt, cnt(b.Now().Unix(), 1, 1, 0, 0, 0))
if r := b.Report(0, b.Now().Unix()+3600); r.Totals.Attempts != 1 { // only the new hour (the counters restarted)
t.Fatalf("not pruned: %+v", r.Totals)
}
}
func TestReportOfMergesHosts(t *testing.T) {
mk := func(n int) *Agg {
a := newAgg()
base := t0.Unix() - 300
a.Ingest(wire.SrcIngressCnt, cnt(base, 0, 0, 0, 0, 0))
a.Ingest(wire.SrcIngressCnt, cnt(base+60, n, n, 0, 0, 0))
return a
}
r := ReportOf([]*Agg{mk(10), mk(32), nil}, 0, t0.Unix()+3600)
if r.Totals.Attempts != 42 || len(r.Hourly) != 1 {
t.Fatalf("%+v", r)
}
}
func TestWaitingWithoutData(t *testing.T) {
r := newAgg().Report(0, t0.Unix())
if r.Enabled || r.Source.State != "waiting" || r.Hourly == nil || r.Ports == nil {
t.Fatalf("%+v", r)
}
}
+152
View File
@@ -0,0 +1,152 @@
// Package ingress aggregates the firewall telemetry of the host kit: the exact
// once-a-minute counters of the inbound observation table and a rate-limited
// sample of the connection attempts it saw.
//
// It is telemetry only. Nothing in this package emits an event, a score or a
// ban decision: attempts, banned sources included, are never evidence (a ban
// would otherwise feed on its own dropped packets). It deliberately does not
// import the store, the intelligence or the enforce packages.
package ingress
import (
"errors"
"net/netip"
"strconv"
"strings"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
)
// Kernel log prefixes written by deploy/host/urutau-ingress.nft: IN for a port
// the host does not serve, INO for one it does.
const (
markerClosed = "URUTAU-IN:"
markerOpen = "URUTAU-INO:"
)
// Hostile input limits.
const (
maxLogLine = 2048
maxCounterLine = 256
maxCounter = 1 << 50 // packets since the table was loaded; far beyond any real count
)
var (
ErrNotIngress = errors.New("not an ingress line")
ErrTooLong = errors.New("line too long")
ErrBadLine = errors.New("invalid ingress line")
)
// Hit is one sampled inbound attempt.
type Hit struct {
Time time.Time
Src netip.Addr
Proto string // tcp, udp, icmp
DPort uint16 // 0 for icmp
Open bool // the host serves this port
}
// ParseHit parses one line of ingress.log. now is the fallback time of a line
// whose timestamp is unreadable.
func ParseHit(b []byte, now time.Time) (Hit, error) {
if len(b) > maxLogLine {
return Hit{}, ErrTooLong
}
line := string(b)
open := false
marker := markerClosed
switch {
case strings.Contains(line, markerOpen):
open, marker = true, markerOpen
case strings.Contains(line, markerClosed):
default:
return Hit{}, ErrNotIngress
}
k, err := egress.ParseKernel(b, marker, now)
if err != nil {
return Hit{}, ErrBadLine
}
switch k.Proto {
case "tcp":
if !k.SYN || k.ACK || k.DPort == 0 {
return Hit{}, ErrBadLine
}
case "udp":
if k.DPort == 0 {
return Hit{}, ErrBadLine
}
case "icmp":
k.DPort, open = 0, false
default:
return Hit{}, ErrBadLine
}
// Defense in depth: the kit already skips these, a forged line must not
// attribute traffic to a local or reserved address either.
a := k.Src
if !a.IsValid() || !a.IsGlobalUnicast() || a.IsPrivate() || a.IsLoopback() || a.IsLinkLocalUnicast() || a.IsMulticast() {
return Hit{}, ErrBadLine
}
return Hit{Time: k.Time, Src: a, Proto: k.Proto, DPort: k.DPort, Open: open}, nil
}
// Counters is one line of ingress.counters. Values are cumulative since the
// nftables table was loaded.
type Counters struct {
TS int64
Total, TCP, UDP, ICMP, Open uint64
}
// ParseCounters parses "ts=1767225600 total=120 tcp=100 udp=15 icmp=5 open=30".
// Unknown keys are ignored (a newer kit); a missing key, a duplicate or a value
// out of range makes the line invalid.
func ParseCounters(b []byte) (Counters, error) {
if len(b) > maxCounterLine {
return Counters{}, ErrTooLong
}
var c Counters
seen := 0
for _, f := range strings.Fields(string(b)) {
k, v, ok := strings.Cut(f, "=")
if !ok {
return Counters{}, ErrBadLine
}
n, err := strconv.ParseUint(v, 10, 64)
if err != nil || n > maxCounter {
if k == "ts" || k == "total" || k == "tcp" || k == "udp" || k == "icmp" || k == "open" {
return Counters{}, ErrBadLine
}
continue
}
bit := 0
switch k {
case "ts":
c.TS, bit = int64(n), 1
case "total":
c.Total, bit = n, 2
case "tcp":
c.TCP, bit = n, 4
case "udp":
c.UDP, bit = n, 8
case "icmp":
c.ICMP, bit = n, 16
case "open":
c.Open, bit = n, 32
}
if bit == 0 {
continue
}
if seen&bit != 0 {
return Counters{}, ErrBadLine
}
seen |= bit
}
if seen != 63 || c.TS <= 0 {
return Counters{}, ErrBadLine
}
// A line that contradicts itself is not trusted.
if c.TCP+c.UDP+c.ICMP > c.Total+1000 || c.Open > c.TCP+c.UDP {
return Counters{}, ErrBadLine
}
return c, nil
}
+24
View File
@@ -8,6 +8,8 @@ import (
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
)
@@ -58,6 +60,28 @@ var (
// NormPath normalises a path for signatures: query dropped, lowercase, uuids
// and long hex runs become {id}, digit runs become {n}.
func NormPath(p string) string {
if v, ok := normMemo.Load(p); ok {
return v.(string)
}
n := normPath(p)
if normMemoN.Add(1) > normMemoMax { // bounded: paths come from attackers
normMemo.Clear()
normMemoN.Store(1)
}
normMemo.Store(p, n)
return n
}
// Paths repeat heavily in a study and the three regular expressions are the
// costliest step of a signature, so results are memoised.
const normMemoMax = 50000
var (
normMemo sync.Map
normMemoN atomic.Int64
)
func normPath(p string) string {
if i := strings.IndexAny(p, "?#"); i >= 0 {
p = p[:i]
}
+52 -13
View File
@@ -3,8 +3,10 @@ package intel
import (
"crypto/sha256"
"encoding/hex"
"runtime"
"sort"
"strconv"
"sync"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
@@ -158,20 +160,57 @@ func Sessions(events []Ev, gap time.Duration) []Session {
for _, e := range events {
byIP[e.IP] = append(byIP[e.IP], e)
}
var out []Session
for ip, evs := range byIP {
sort.SliceStable(evs, func(i, j int) bool { return evs[i].T.Before(evs[j].T) })
priorFail := false
start := 0
for i := 1; i <= len(evs); i++ {
if i < len(evs) && evs[i].T.Sub(evs[i-1].T) <= gap {
continue
return SessionsByIP(byIP, gap)
}
// SessionsByIP is Sessions for events already grouped by address (the lists
// are sorted in place by time), which spares the second copy of a long study.
func SessionsByIP(byIP map[string][]Ev, gap time.Duration) []Session {
ips := make([]string, 0, len(byIP))
for ip := range byIP {
ips = append(ips, ip)
}
return SessionsLazy(ips, func(ip string) []Ev { return byIP[ip] }, gap)
}
// SessionsLazy builds the sessions of the listed addresses, asking load for the
// events of one address at a time so a long study never holds them all.
func SessionsLazy(ips []string, load func(ip string) []Ev, gap time.Duration) []Session {
if gap <= 0 {
gap = DefaultGap
}
// addresses are independent of each other: build their sessions in parallel
workers := min(runtime.GOMAXPROCS(0), 8, 1+len(ips)/256)
parts := make([][]Session, workers)
var wg sync.WaitGroup
for w := 0; w < workers; w++ {
wg.Add(1)
go func() {
defer wg.Done()
var out []Session
for i := w; i < len(ips); i += workers {
ip := ips[i]
evs := load(ip)
sort.SliceStable(evs, func(i, j int) bool { return evs[i].T.Before(evs[j].T) })
priorFail := false
start := 0
for i := 1; i <= len(evs); i++ {
if i < len(evs) && evs[i].T.Sub(evs[i-1].T) <= gap {
continue
}
s, pf := buildSession(ip, evs[start:i], priorFail)
priorFail = pf
out = append(out, s)
start = i
}
}
s, pf := buildSession(ip, evs[start:i], priorFail)
priorFail = pf
out = append(out, s)
start = i
}
parts[w] = out
}()
}
wg.Wait()
var out []Session
for _, p := range parts {
out = append(out, p...)
}
sort.Slice(out, func(i, j int) bool {
if !out[i].Start.Equal(out[j].Start) {
+2
View File
@@ -48,6 +48,8 @@ func Main(args []string, version string) int {
{wire.SrcFail2ban, "URUTAU_FAIL2BAN_LOG", "", "fail2ban log"},
{wire.SrcProbe, "URUTAU_PROBE_LOG", "", "kernel log of network probes"},
{wire.SrcEgress, "URUTAU_EGRESS_LOG", "", "kernel log of outbound connections"},
{wire.SrcIngress, "URUTAU_INGRESS_LOG", "", "sampled kernel log of inbound attempts"},
{wire.SrcIngressCnt, "URUTAU_INGRESS_COUNTERS", "", "exact inbound counters of the host kit"},
} {
v := new(string)
paths[p.src] = v
+75
View File
@@ -0,0 +1,75 @@
package server
import (
"net/http"
"strings"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/ingress"
)
func init() {
registerUserRoute("GET /api/v1/ingress", func(s *Server) http.HandlerFunc { return s.ingressAPI })
}
type ingressOut struct {
Hosts []string `json:"hosts"`
ingress.Report
}
// ingressAPI: GET /api/v1/ingress?range=24h&host=all|<name>[,<name>]. The
// firewall telemetry of the hosts that send it: exact totals from the host kit
// counters, the details (ports, origins, banned share) from its sampled log.
// Only the probes of this hub are covered (the telemetry is not relayed to
// peers).
func (s *Server) ingressAPI(w http.ResponseWriter, r *http.Request) {
rg, ok := s.rangeOf(w, r)
if !ok {
return
}
host := strings.TrimSpace(r.URL.Query().Get("host"))
if len(host) > 64*maxHostSel {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "bad host"})
return
}
var all []string
if s.opt.Nodes != nil {
all = s.opt.Nodes.Hosts()
}
var names []string
switch host {
case "", "all":
names = all
default:
for _, n := range strings.Split(host, ",") {
n = strings.TrimSpace(n)
if n == "" {
continue
}
if !contains(all, n) {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "unknown host"})
return
}
names = append(names, n)
}
}
aggs := make([]*ingress.Agg, 0, len(names))
for _, n := range names {
if a := s.opt.Nodes.Ingress(n); a != nil {
aggs = append(aggs, a)
}
}
from, to := rg.Bounds(s.opt.Store.Now().Unix())
if names == nil {
names = []string{}
}
writeJSON(w, 200, ingressOut{Hosts: names, Report: ingress.ReportOf(aggs, from, to)})
}
func contains(l []string, s string) bool {
for _, x := range l {
if x == s {
return true
}
}
return false
}
+77
View File
@@ -0,0 +1,77 @@
package server
import (
"fmt"
"net/http"
"net/http/httptest"
"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/incidents"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/ingress"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
type fakeNodes struct{ m map[string]*ingress.Agg }
func (f fakeNodes) Hosts() []string {
return []string{"oracle", "hostinger"}
}
func (f fakeNodes) Enforce(string) *enforce.Engine { return nil }
func (f fakeNodes) Egress(string) *egress.Engine { return nil }
func (f fakeNodes) Incidents(string) *incidents.Store { return nil }
func (f fakeNodes) Ingress(h string) *ingress.Agg { return f.m[h] }
func TestIngressAPI(t *testing.T) {
st := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour})
now := time.Now()
mk := func(n int) *ingress.Agg {
a := ingress.New()
ts := now.Add(-10 * time.Minute).Unix()
a.Ingest(wire.SrcIngressCnt, []byte(fmt.Sprintf("ts=%d total=0 tcp=0 udp=0 icmp=0 open=0", ts)))
a.Ingest(wire.SrcIngressCnt, []byte(fmt.Sprintf("ts=%d total=%d tcp=%d udp=0 icmp=0 open=%d", ts+60, n, n, n/4)))
return a
}
nodes := fakeNodes{m: map[string]*ingress.Agg{"oracle": mk(400), "hostinger": mk(100)}}
h := New(Options{Token: userTok, Version: "t", Store: st, Nodes: nodes})
auth := map[string]string{"Authorization": "Bearer " + userTok}
d := getJSON(t, h, "/api/v1/ingress?range=24h", auth)
tot := d["totals"].(map[string]any)
if tot["attempts"] != float64(500) || tot["open"] != float64(125) || tot["closed"] != float64(375) || tot["closed_pct"] != float64(75) || d["enabled"] != true {
t.Fatalf("all: %v", d)
}
for _, k := range []string{"hosts", "source", "sample", "hourly", "ports", "asns", "countries"} {
if d[k] == nil {
t.Errorf("missing %q", k)
}
}
d = getJSON(t, h, "/api/v1/ingress?range=24h&host=hostinger", auth)
if d["totals"].(map[string]any)["attempts"] != float64(100) {
t.Fatalf("one host: %v", d)
}
for _, path := range []string{"/api/v1/ingress?host=nope", "/api/v1/ingress?range=bogus"} {
rec := httptest.NewRecorder()
req := httptest.NewRequest("GET", path, nil)
req.Header.Set("Authorization", "Bearer "+userTok)
h.ServeHTTP(rec, req)
if rec.Code != http.StatusNotFound && rec.Code != http.StatusBadRequest {
t.Errorf("%s: %d", path, rec.Code)
}
}
// no auth
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("GET", "/api/v1/ingress", nil))
if rec.Code != http.StatusUnauthorized {
t.Errorf("unauthenticated: %d", rec.Code)
}
// standalone (no nodes): empty, not an error
h2 := New(Options{Token: userTok, Version: "t", Store: st})
d = getJSON(t, h2, "/api/v1/ingress", auth)
if d["enabled"] != false || len(d["hosts"].([]any)) != 0 {
t.Fatalf("standalone: %v", d)
}
}
+2
View File
@@ -11,6 +11,7 @@ import (
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/hub"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/incidents"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/ingress"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
@@ -34,6 +35,7 @@ type NodeSet interface {
Hosts() []string
Enforce(host string) *enforce.Engine
Egress(host string) *egress.Engine
Ingress(host string) *ingress.Agg
Incidents(host string) *incidents.Store
}
+40 -4
View File
@@ -301,9 +301,17 @@
if (r.status >= 500) { showError(t('error.load')); throw mkErr('HTTP ' + r.status, r.status); }
if (!r.ok) throw mkErr('HTTP ' + r.status, r.status);
hideError();
return r.json();
return r.json().then(function (j) { if (j && j.truncated === true) noteTruncated(); return j; });
}, function (e) { showError(t('error.load')); throw e; });
}
// A study that hit a real limit (event count, byte budget or time) says so; shown at most once per 20 s.
var truncAt = 0;
function noteTruncated() {
var now = Date.now();
if (now - truncAt < 20000) return;
truncAt = now;
toast(t('study.truncated'), 9000);
}
function qs(extra) {
var o = Object.assign({ host: state.host }, rangeParams());
for (var k in extra) o[k] = extra[k];
@@ -982,12 +990,12 @@
});
}
var toastBox = null;
function toast(msg) {
function toast(msg, ms) {
if (!toastBox) toastBox = $('#toasts');
if (!toastBox) return;
var n = h('div', 'toast', String(msg));
toastBox.appendChild(n);
setTimeout(function () { if (n.parentNode) n.parentNode.removeChild(n); }, 2600);
setTimeout(function () { if (n.parentNode) n.parentNode.removeChild(n); }, ms || 2600);
}
// POST/DELETE with a JSON body (same-origin cookie session); resolves with the parsed answer or rejects with its status.
@@ -1579,6 +1587,31 @@
var CLIENT_COLORS = { desktop: '--viz-1', mobile: '--viz-6', tablet: '--viz-5', bot: '--viz-3', tool: '--viz-7', unknown: '--viz-8', misc: '--viz-2' };
var CLIENT_ORDER = ['desktop', 'mobile', 'tablet', 'bot', 'tool', 'unknown', 'misc'];
var STATUS_TOKENS = ['--ok', '--info', '--warn', '--danger'];
// Own infrastructure and trusted origins: counted apart, never analysed (s.own, s.totals.trusted/internal)
function renderOwnTraffic(box, s) {
var o = s.own || {}, T = s.totals || {}, tr = o.trusted || 0, inn = o.internal || 0, tot = tr + inn;
ready(box); clear(box.body);
if (!tot) { box.body.appendChild(empty(t('own.none'), t('own.noneBody'))); return; }
var kp = h('div', 'kpi-row');
kp.appendChild(stat(t('own.trusted'), nf(tr), t('own.sub.trusted'), 'neutral'));
kp.appendChild(stat(t('own.internal'), nf(inn), t('own.sub.internal'), 'neutral'));
kp.appendChild(stat(t('own.all'), nf(T.requests_all || (T.requests || 0) + tot), t('own.sub.all', { n: nf(T.requests || 0), o: nf(tot) }), 'neutral'));
box.body.appendChild(kp);
var ser = o.series || {};
box.body.appendChild(charts.stackedArea([{ key: 'trusted', label: t('own.trusted'), values: ser.trusted || [] }, { key: 'internal', label: t('own.internal'), values: ser.internal || [] }], o.step, { start: o.start, colors: ['--viz-5', '--viz-8'], title: t('own.title') }));
var cls = ['2xx', '3xx', '4xx', '5xx'];
box.body.appendChild(charts.bars(cls.map(function (k, i) { return { key: k, label: t('traffic.status.' + k), value: (o.status || [])[i] || 0, color: STATUS_TOKENS[i] }; }), { title: t('traffic.status') }));
var rows = o.origins || [], tb = el('table', { class: 'tbl' });
tb.appendChild(h('thead', null, h('tr', null, h('th', null, t('own.col.origin')), h('th', null, t('own.col.class')), h('th', 'num', t('own.col.requests')))));
var body = el('tbody');
rows.forEach(function (r) { body.appendChild(h('tr', null, h('td', 'mono', r.key), h('td', null, t('own.' + pick(['trusted', 'internal'], r.label, 'internal'))), h('td', 'num', nf(r.n)))); });
tb.appendChild(body);
box.body.appendChild(h('h3', null, t('own.origins'))); box.body.appendChild(tb);
var two = h('div', 'grid-12');
var dm = h('div', 'span-6', h('h3', null, t('own.domains')), bars(o.domains || [], { mono: true }));
var ph = h('div', 'span-6', h('h3', null, t('own.paths')), bars(o.paths || [], { mono: true }));
two.appendChild(dm); two.appendChild(ph); box.body.appendChild(two);
}
var pTraffic = corePage({
id: 'traffic', icon: ICONS.traffic, titleKey: 'nav.traffic', domain: true,
build: function (root) {
@@ -1594,19 +1627,22 @@
v.browsers = panel({ title: t('traffic.browsers'), hint: t('traffic.browsers.hint'), loading: true });
v.oses = panel({ title: t('traffic.oses'), hint: t('traffic.oses.hint'), loading: true });
v.status = panel({ title: t('traffic.status'), hint: t('traffic.status.hint'), loading: true, help: 'term.status_class' });
v.own = panel({ title: t('own.title'), hint: t('own.hint'), loading: true });
v.privacy = sp(12, h('p', 'note', t('traffic.privacy')));
g.appendChild(v.lead); g.appendChild(v.kpis); g.appendChild(sp(12, v.timeline)); g.appendChild(sp(12, v.map));
g.appendChild(sp(4, v.client)); g.appendChild(sp(4, v.browsers)); g.appendChild(sp(4, v.oses));
g.appendChild(sp(6, v.status)); g.appendChild(sp(6, v.bots));
['pages', 'refs', 'cities'].forEach(function (k) { g.appendChild(sp(4, v[k])); });
g.appendChild(sp(12, v.own));
g.appendChild(v.privacy);
root.appendChild(g);
return v;
},
load: function (c) { return api('/api/v1/traffic', Object.assign({ host: c.host, domain: c.domain }, c.from !== null && c.from !== undefined ? { from: c.from, to: c.to } : { range: c.range })); },
render: function (v, d) {
render: function (v, d, c) {
v.data = d;
setDomains(d.domains || []);
getSummary(c).then(function (s) { renderOwnTraffic(v.own, s); }, function () { ready(v.own); clear(v.own.body); v.own.body.appendChild(empty(t('own.none'), '')); });
var hasData = d.requests > 0;
clear(v.lead); v.lead.classList.remove('skeleton', 'lead-skel');
v.lead.appendChild(hasData
+2
View File
@@ -23,3 +23,5 @@
@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; } }
/* Firewall: inbound attempts */
.df-en + .df-en { margin-top: var(--grid-gap, 16px); }
+125 -4
View File
@@ -126,7 +126,34 @@
'df.en.reason.port-scan': 'Scanning many network ports on the server',
'df.en.reason.known-attacker': 'Known attacker returning (hostile verdict)',
'df.en.reason.neighbor-campaign': 'Part of a campaign: several neighbours in the same network range were already banned',
'df.en.error': 'Could not load the second firewall data.'
'df.en.error': 'Could not load the second firewall data.',
'df.fw.title': 'Firewall: inbound attempts',
'df.fw.hint': 'New connection attempts that reached this host from the internet, counted by the firewall before any ban drops them. What a provider firewall (for example a cloud security list) blocks earlier never gets here.',
'df.fw.lead': '{n} inbound attempts {range}',
'df.fw.lead.sub': 'The totals are exact (counters of the host kit). Ports and origins come from a sample of {r} of them.',
'df.fw.kpi.total': 'Attempts',
'df.fw.kpi.total.sub': '{n} per hour on average',
'df.fw.kpi.closed': 'To closed ports',
'df.fw.kpi.closed.sub': '{n} to ports nothing serves',
'df.fw.kpi.banned': 'From banned sources',
'df.fw.kpi.banned.sub': 'about {n} attempts; estimated from the sample',
'df.fw.kpi.ratio': 'Sampled',
'df.fw.kpi.ratio.sub': '{n} logged attempts of the total',
'df.fw.hourly': 'Attempts per hour',
'df.fw.hourly.closed': 'Closed ports',
'df.fw.hourly.open': 'Served ports',
'df.fw.ports': 'Top destination ports',
'df.fw.ports.hint': 'Sampled. A red bar is a port this host does not serve.',
'df.fw.asns': 'Top origin networks',
'df.fw.asns.hint': 'Sampled, by the ASN of the source address.',
'df.fw.ccs': 'Top origin countries',
'df.fw.ccs.hint': 'Sampled, by the country of the source address.',
'df.fw.sampled': 'Sampled: these details cover about {r} of the attempts; the totals above are exact.',
'df.fw.banned.note': 'Banned means the source was in a jail (fail2ban or Urutau) when its attempt was logged. Those attempts are dropped by the firewall and never count as new evidence against the address.',
'df.fw.none': 'No inbound telemetry yet',
'df.fw.none.sub': 'Install the host kit with "sudo sh deploy/host/install.sh --ingress" and let the probe send ingress.log and ingress.counters.',
'df.fw.nodata': 'No attempts counted in this window',
'df.fw.error': 'Could not load the firewall data.'
},
'pt-BR': {
'df.title': 'Defesa',
@@ -243,7 +270,34 @@
'df.en.reason.port-scan': 'Varredura de muitas portas de rede do servidor',
'df.en.reason.known-attacker': 'Atacante conhecido voltando (veredito hostil)',
'df.en.reason.neighbor-campaign': 'Parte de uma campanha: vários vizinhos da mesma faixa de rede já foram banidos',
'df.en.error': 'Não foi possível carregar os dados do segundo firewall.'
'df.en.error': 'Não foi possível carregar os dados do segundo firewall.',
'df.fw.title': 'Firewall: tentativas de entrada',
'df.fw.hint': 'Tentativas novas de conexão que chegaram a este host pela internet, contadas pelo firewall antes de qualquer banimento descartá-las. O que um firewall do provedor (por exemplo uma lista de segurança na nuvem) barra antes nunca chega aqui.',
'df.fw.lead': '{n} tentativas de entrada {range}',
'df.fw.lead.sub': 'Os totais são exatos (contadores do kit do host). Portas e origens vêm de uma amostra de {r} delas.',
'df.fw.kpi.total': 'Tentativas',
'df.fw.kpi.total.sub': '{n} por hora em média',
'df.fw.kpi.closed': 'Para portas fechadas',
'df.fw.kpi.closed.sub': '{n} para portas em que nada escuta',
'df.fw.kpi.banned': 'De origens banidas',
'df.fw.kpi.banned.sub': 'cerca de {n} tentativas; estimado pela amostra',
'df.fw.kpi.ratio': 'Amostrado',
'df.fw.kpi.ratio.sub': '{n} tentativas registradas do total',
'df.fw.hourly': 'Tentativas por hora',
'df.fw.hourly.closed': 'Portas fechadas',
'df.fw.hourly.open': 'Portas com serviço',
'df.fw.ports': 'Portas de destino mais visadas',
'df.fw.ports.hint': 'Amostrado. Barra vermelha é uma porta que este host não serve.',
'df.fw.asns': 'Redes de origem mais frequentes',
'df.fw.asns.hint': 'Amostrado, pelo ASN do endereço de origem.',
'df.fw.ccs': 'Países de origem mais frequentes',
'df.fw.ccs.hint': 'Amostrado, pelo país do endereço de origem.',
'df.fw.sampled': 'Amostrado: estes detalhes cobrem cerca de {r} das tentativas; os totais acima são exatos.',
'df.fw.banned.note': 'Banida quer dizer que a origem estava numa jaula (fail2ban ou Urutau) quando a tentativa foi registrada. Essas tentativas são descartadas pelo firewall e nunca contam como nova evidência contra o endereço.',
'df.fw.none': 'Ainda sem telemetria de entrada',
'df.fw.none.sub': 'Instale o kit do host com "sudo sh deploy/host/install.sh --ingress" e deixe a sonda enviar ingress.log e ingress.counters.',
'df.fw.nodata': 'Nenhuma tentativa contada nesta janela',
'df.fw.error': 'Não foi possível carregar os dados do firewall.'
}
});
@@ -465,8 +519,75 @@
});
}
var fwData = null, fwSeq = 0, fwBox = null;
function ratioTxt(r) { var v = (r || 0) * 100; return (v > 0 && v < 10 ? v.toFixed(1) : Math.round(v)) + '%'; }
function paintFirewall() {
if (!fwBox) return;
clear(fwBox);
if (!fwData) return;
var d = fwData, tt = d.totals || {}, sm = d.sample || {}, range = U.rangeLabel({ inline: true });
var head = el('div', { class: 'df-en-head' });
head.appendChild(el('h2', { class: 'df-en-title' }, t('df.fw.title')));
head.appendChild(el('p', { class: 'hint' }, t('df.fw.hint')));
fwBox.appendChild(head);
if (!d.enabled) { fwBox.appendChild(U.ui.empty(t('df.fw.none'), t('df.fw.none.sub'))); return; }
if (!tt.attempts) { fwBox.appendChild(U.ui.empty(t('df.fw.nodata'))); return; }
fwBox.appendChild(U.ui.lead(t('df.fw.lead', { n: nf(tt.attempts), range: range }), t('df.fw.lead.sub', { r: ratioTxt(sm.ratio) }), 'info'));
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.fw.kpi.total'), nf(tt.attempts), { sub: t('df.fw.kpi.total.sub', { n: nf(Math.round(tt.per_hour || 0)) }) }));
k(U.ui.metric(t('df.fw.kpi.closed'), pctTxt(tt.closed_pct || 0), { sub: t('df.fw.kpi.closed.sub', { n: nf(tt.closed || 0) }) }));
k(U.ui.metric(t('df.fw.kpi.banned'), pctTxt(sm.banned_pct || 0), { sub: t('df.fw.kpi.banned.sub', { n: nf(sm.banned_est || 0) }), tone: (sm.banned_pct || 0) >= 50 ? 'warn' : 'neutral' }));
k(U.ui.metric(t('df.fw.kpi.ratio'), ratioTxt(sm.ratio), { sub: t('df.fw.kpi.ratio.sub', { n: nf(sm.logged || 0) }) }));
fwBox.appendChild(kp);
var grid = el('div', { class: 'grid-12' });
var hours = d.hourly || [];
var hp = U.ui.panel({ title: t('df.fw.hourly'), cls: 'span-12' });
if (U.charts && U.charts.stackedArea && hours.length) {
var step = 3600, start = hours[0].t, last = hours[hours.length - 1].t;
var n = Math.min(MAX_BUCKETS, Math.floor((last - start) / step) + 1);
if (n < 2) { n = 2; }
var cl = new Array(n).fill(0), op = new Array(n).fill(0);
hours.forEach(function (h) { var i = Math.round((h.t - start) / step); if (i >= 0 && i < n) { cl[i] += h.closed; op[i] += h.open; } });
hp.body.appendChild(U.charts.stackedArea([{ key: 'closed', label: t('df.fw.hourly.closed'), values: cl }, { key: 'open', label: t('df.fw.hourly.open'), values: op }], step, { start: start, title: t('df.fw.hourly') }));
} else hp.body.appendChild(U.ui.empty(t('df.fw.nodata')));
grid.appendChild(hp);
function barsPanel(title, hint, rows, cls) {
var p = U.ui.panel({ title: title, hint: hint, cls: cls });
if (!rows.length) p.body.appendChild(U.ui.empty(t('df.fw.nodata')));
else if (U.charts && U.charts.bars) p.body.appendChild(U.charts.bars(rows, { title: title, format: nf }));
grid.appendChild(p);
}
barsPanel(t('df.fw.ports'), t('df.fw.ports.hint'), (d.ports || []).slice(0, 10).map(function (p) {
return { key: p.proto + '/' + p.port, label: p.proto + '/' + p.port, value: p.n, color: p.served ? '--viz-1' : '--danger' };
}), 'span-4');
barsPanel(t('df.fw.asns'), t('df.fw.asns.hint'), (d.asns || []).slice(0, 10).map(function (a) {
return { key: a.asn, label: a.asn + (a.org ? ' ' + a.org : ''), value: a.n };
}), 'span-4');
barsPanel(t('df.fw.ccs'), t('df.fw.ccs.hint'), (d.countries || []).slice(0, 10).map(function (c) {
return { key: c.cc, label: (U.fmt.flag ? U.fmt.flag(c.cc) + ' ' : '') + c.cc, value: c.n };
}), 'span-4');
fwBox.appendChild(grid);
fwBox.appendChild(el('p', { class: 'hint' }, t('df.fw.sampled', { r: ratioTxt(sm.ratio) })));
fwBox.appendChild(el('p', { class: 'hint' }, t('df.fw.banned.note')));
}
function loadFirewall() {
var my = ++fwSeq;
U.api('/api/v1/ingress', Object.assign(U.rangeParams(), ctx && ctx.host && ctx.host !== 'all' ? { host: ctx.host } : {})).then(function (d) {
if (!alive || my !== fwSeq) return;
fwData = d; paintFirewall();
}).catch(function () {
if (!alive || my !== fwSeq || fwData || !fwBox) return;
clear(fwBox);
fwBox.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('df.fw.error'))));
});
}
function load() {
loadEnforce();
loadFirewall();
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;
@@ -481,10 +602,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); enBox = el('div', { class: 'df-page df-en' }); node.appendChild(enBox); ctx = cx; alive = true; data = null; enData = 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); fwBox = el('div', { class: 'df-page df-en' }); node.appendChild(fwBox); ctx = cx; alive = true; data = null; enData = null; fwData = null; paint(); load(); },
update: function (cx) { ctx = cx; load(); },
refresh: function () { load(); },
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; }
unmount: function () { alive = false; seq++; enSeq++; fwSeq++; if (root && root.parentNode) root.parentNode.removeChild(root); if (enBox && enBox.parentNode) enBox.parentNode.removeChild(enBox); if (fwBox && fwBox.parentNode) fwBox.parentNode.removeChild(fwBox); root = null; enBox = null; fwBox = null; data = null; enData = null; fwData = null; }
});
return true;
}
+34
View File
@@ -43,6 +43,7 @@ window.URUTAU_I18N = {
'range.widen': 'Choose another period',
'timeline.bucket': '{n}-minute buckets',
'toast.copied': 'Copied',
'study.truncated': 'This period is too large to read in full: the figures cover only part of the events. Pick a shorter range for exact numbers.',
'unban.btn': 'Unban',
'unban.title': 'Unban {ip}',
'unban.explain': 'This lifts the block on this address in the server firewall (fail2ban) right away. Use it when the block was a mistake or when you are testing your own system.',
@@ -321,6 +322,22 @@ window.URUTAU_I18N = {
'traffic.browsers': 'Browsers',
'traffic.oses': 'Operating systems',
'traffic.status': 'Status codes',
'own.title': 'Own infrastructure and trusted origins',
'own.hint': 'Requests from --trusted origins and private networks. They are counted here and nowhere else: they never score an IP, enter threats, maps, visitors or the blocklist.',
'own.none': 'No requests from own or trusted origins',
'own.noneBody': 'Nothing came from --trusted or --ignore addresses in this range.',
'own.trusted': 'Trusted origins',
'own.internal': 'Internal networks',
'own.all': 'All requests',
'own.sub.trusted': 'addresses of --trusted',
'own.sub.internal': 'private and --ignore ranges',
'own.sub.all': '{n} external + {o} own',
'own.origins': 'By origin',
'own.domains': 'By domain',
'own.paths': 'Top paths',
'own.col.origin': 'Origin',
'own.col.class': 'Class',
'own.col.requests': 'Requests',
'traffic.privacy': 'Visitors are counted with a daily rotating hash kept in memory only. No visitor IP is stored.',
'traffic.sub.visitors': 'distinct, hash per day',
'traffic.sub.requests': 'incl. assets and bots',
@@ -579,6 +596,7 @@ window.URUTAU_I18N = {
'range.widen': 'Escolher outro período',
'timeline.bucket': 'caixas de {n} min',
'toast.copied': 'Copiado',
'study.truncated': 'Este período é grande demais para ser lido por inteiro: os números cobrem só parte dos eventos. Escolha um intervalo menor para valores exatos.',
'unban.btn': 'Desbanir',
'unban.title': 'Desbanir {ip}',
'unban.explain': 'Isto libera agora o bloqueio deste endereço no firewall do servidor (fail2ban). Use quando o bloqueio foi um engano ou quando você está testando o seu próprio sistema.',
@@ -857,6 +875,22 @@ window.URUTAU_I18N = {
'traffic.browsers': 'Navegadores',
'traffic.oses': 'Sistemas operacionais',
'traffic.status': 'Códigos de status',
'own.title': 'Infraestrutura própria e origens confiáveis',
'own.hint': 'Requisições de origens --trusted e de redes privadas. Elas são contadas aqui e em mais nenhum lugar: nunca pontuam um IP, nem entram em ameaças, mapas, visitantes ou na lista de bloqueio.',
'own.none': 'Nenhuma requisição de origens próprias ou confiáveis',
'own.noneBody': 'Nada veio de endereços --trusted ou --ignore neste período.',
'own.trusted': 'Origens confiáveis',
'own.internal': 'Redes internas',
'own.all': 'Todas as requisições',
'own.sub.trusted': 'endereços de --trusted',
'own.sub.internal': 'faixas privadas e --ignore',
'own.sub.all': '{n} externas + {o} próprias',
'own.origins': 'Por origem',
'own.domains': 'Por domínio',
'own.paths': 'Caminhos mais pedidos',
'own.col.origin': 'Origem',
'own.col.class': 'Classe',
'own.col.requests': 'Requisições',
'traffic.privacy': 'Visitantes são contados com um hash que muda todo dia e fica só na memória. Nenhum IP de visitante é guardado.',
'traffic.sub.visitors': 'distintos, hash diário',
'traffic.sub.requests': 'inclui recursos e bots',
+1 -1
View File
@@ -225,7 +225,7 @@ func anQuant(v []int64, q float64) int64 {
func (s *Store) anScan(from, to int64, host string, fn func(evlog.Rec) bool) (truncated bool) {
deadline := time.Now().Add(studyDead)
n := 0
info := s.elog.Scan(evlog.Filter{From: from, To: to, Host: host}, studyBudget, false, func(r evlog.Rec, _ []byte) bool {
info := s.elog.ScanRecs(evlog.Filter{From: from, To: to, Host: host}, studyBudget, false, func(r evlog.Rec) bool {
if n++; n%4096 == 0 && time.Now().After(deadline) {
truncated = true
return false
+10
View File
@@ -0,0 +1,10 @@
package store
// Banned reports whether a jail (fail2ban or Urutau's own) currently bans the
// address, according to the ban and unban lines this instance has read.
func (s *Store) Banned(ip string) bool {
s.mu.RLock()
defer s.mu.RUnlock()
r := s.ips[KeyOf(ip)]
return r != nil && len(r.Jails) > 0
}
+3 -25
View File
@@ -1,11 +1,8 @@
package store
import (
"context"
"sort"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
)
@@ -207,28 +204,9 @@ func (s *Store) countStages(q PeriodQuery) StageCounts {
if s.elog == nil {
return out
}
gap := time.Duration(q.Gap) * time.Second
if q.Gap < 60 {
gap = intel.DefaultGap
if q.Gap > 0 {
gap = 60 * time.Second
}
}
deadline := time.Now().Add(studyDead)
ctx, cancel := context.WithDeadline(context.Background(), deadline)
defer cancel()
var evs []intel.Ev
info := s.elog.Scan(evlog.Filter{From: q.From, To: q.To, Host: q.Host, IP: q.IP, Cats: catSet(q.Cat), Fam: q.Fam}, studyBudget, false,
func(r evlog.Rec, _ []byte) bool {
if len(evs) >= maxStudyEvents || len(evs)%4096 == 0 && ctx.Err() != nil {
out.Truncated = true
return false
}
evs = append(evs, toEv(r))
return true
})
out.Truncated = out.Truncated || info.Truncated
for _, ss := range intel.Sessions(evs, gap) {
st := s.sessionStudy(q)
out.Truncated = st.truncated
for _, ss := range st.sessions {
out.Add(ss.Stage, ss.Success)
}
return out
+2 -2
View File
@@ -133,8 +133,8 @@ func (s *Store) defense(q PeriodQuery) DefenseOut {
users := map[string]int{}
sshSrc := map[string]struct{}{}
n, malN := 0, 0
info := s.elog.Scan(evlog.Filter{From: q.From, To: q.To, Host: q.Host}, studyBudget, false,
func(r evlog.Rec, _ []byte) bool {
info := s.elog.ScanRecs(evlog.Filter{From: q.From, To: q.To, Host: q.Host}, studyBudget, false,
func(r evlog.Rec) bool {
if n++; n > maxStudyEvents || n%4096 == 0 && time.Now().After(deadline) {
out.Truncated = true
return false
+1 -1
View File
@@ -128,7 +128,7 @@ func (e *PeerExport) SanitizeRange(rg Range) error {
cats[string(c)] = true
}
for k := range s.Totals.Counts {
if !cats[k] {
if !cats[k] && k != OwnTrusted && k != OwnInternal {
delete(s.Totals.Counts, k)
}
}
+80 -34
View File
@@ -180,6 +180,65 @@ type evLite struct {
ua string
}
// sessStudy is the part of a period study that several views share: the
// events of the window grouped by address and the sessions made from them.
type sessStudy struct {
byIP map[string][]evlog.Ref
sessions []intel.Session
events int
truncated bool
}
// evs rebuilds the events of one address.
func (st *sessStudy) evs(ip string) []intel.Ev {
refs := st.byIP[ip]
out := make([]intel.Ev, len(refs))
for i, r := range refs {
out[i] = toEv(r.Rec())
}
return out
}
func normGap(g int64) time.Duration {
switch {
case g <= 0:
return intel.DefaultGap
case g < 60:
return 60 * time.Second
}
return time.Duration(g) * time.Second
}
// sessionStudy scans the window once and builds its sessions; period, funnel
// and metrics of the same window (and filters) share the result for the cache
// lifetime instead of each decoding and grouping the same events.
func (s *Store) sessionStudy(q PeriodQuery) *sessStudy {
run := func() *sessStudy {
st := &sessStudy{byIP: map[string][]evlog.Ref{}}
deadline := time.Now().Add(studyDead)
info := s.elog.ScanRefs(evlog.Filter{From: q.From, To: q.To, Host: q.Host, IP: q.IP, Cats: catSet(q.Cat), Fam: q.Fam}, studyBudget,
func(ref evlog.Ref) bool {
if st.events >= maxStudyEvents || st.events%4096 == 0 && time.Now().After(deadline) {
st.truncated = true
return false
}
ip := KeyOf(ref.IP())
st.byIP[ip] = append(st.byIP[ip], ref)
st.events++
return true
})
st.truncated = st.truncated || info.Truncated
ips := make([]string, 0, len(st.byIP))
for ip := range st.byIP {
ips = append(ips, ip)
}
st.sessions = intel.SessionsLazy(ips, st.evs, normGap(q.Gap))
return st
}
k := studyKey{"sess", q.From, q.To, q.Host, q.IP, q.Cat, q.Fam, int64(normGap(q.Gap) / time.Second)}
return s.cached(k, func() any { return run() }).(*sessStudy)
}
// Period studies [From, To] from the registry: sessions with stages,
// campaigns, first sightings, escalations, spikes and tops. At most 256 MB of
// registry is read and 10 s spent; the result is cached for 30 s.
@@ -206,38 +265,31 @@ func (s *Store) period(q PeriodQuery) PeriodOut {
return out
}
out.Enabled = true
gap := time.Duration(q.Gap) * time.Second
switch {
case q.Gap <= 0:
gap = intel.DefaultGap
case q.Gap < 60:
gap = 60 * time.Second
}
deadline := time.Now().Add(studyDead)
ctx, cancel := context.WithDeadline(context.Background(), deadline)
defer cancel()
var evs []intel.Ev
st := s.sessionStudy(q)
out.Truncated = st.truncated
byIP := map[string][]evLite{}
fams, techs, users, asns := map[string]uint32{}, map[string]uint32{}, map[string]uint32{}, map[string]uint32{}
tgt := map[[2]string]int{}
firstT := map[string]FirstTech{}
ipSeen := map[string]bool{}
info := s.elog.Scan(evlog.Filter{From: q.From, To: q.To, Host: q.Host, IP: q.IP, Cats: catSet(q.Cat), Fam: q.Fam}, studyBudget, false,
func(r evlog.Rec, _ []byte) bool {
if len(evs) >= maxStudyEvents || len(evs)%4096 == 0 && time.Now().After(deadline) {
out.Truncated = true
n := 0
info := s.elog.ScanRecs(evlog.Filter{From: q.From, To: q.To, Host: q.Host, IP: q.IP, Cats: catSet(q.Cat), Fam: q.Fam}, studyBudget, false,
func(r evlog.Rec) bool {
if n++; n > maxStudyEvents || n%4096 == 0 && time.Now().After(deadline) {
return false
}
e := toEv(r)
evs = append(evs, e)
ip := KeyOf(r.IP)
if r.Source == "traefik" {
byIP[e.IP] = append(byIP[e.IP], evLite{r.T, r.Path, r.UA})
byIP[ip] = append(byIP[ip], evLite{r.T, r.Path, r.UA})
}
bumpMap(fams, r.Fam)
for _, t := range r.Tech {
bumpMap(techs, t)
if f, ok := firstT[t]; !ok || r.T < f.T {
firstT[t] = FirstTech{ID: t, Name: intel.TechniqueName(t), T: r.T, IP: e.IP}
firstT[t] = FirstTech{ID: t, Name: intel.TechniqueName(t), T: r.T, IP: ip}
}
}
if r.Cat == string(core.SSHFail) {
@@ -248,12 +300,12 @@ func (s *Store) period(q PeriodQuery) PeriodOut {
tgt[[2]string{r.Host, r.Domain}]++
}
}
ipSeen[e.IP] = true
ipSeen[ip] = true
return true
})
out.Truncated = out.Truncated || info.Truncated
out.Events = len(evs)
sessions := intel.Sessions(evs, gap)
out.Events = st.events
sessions := append([]intel.Session(nil), st.sessions...)
out.SessionsN = len(sessions)
// signatures and campaigns: events and sessions of an address are both in
@@ -327,16 +379,12 @@ func (s *Store) period(q PeriodQuery) PeriodOut {
sort.SliceStable(order, func(a, b int) bool {
return intel.StageRank(sessions[order[a]].Stage) > intel.StageRank(sessions[order[b]].Stage)
})
evByIP := map[string][]intel.Ev{}
for _, e := range evs {
evByIP[e.IP] = append(evByIP[e.IP], e)
}
for _, i := range order {
ss := sessions[i]
if intel.StageRank(ss.Stage) < intel.StageRank(intel.StageExploit) || len(out.Escalations) >= maxEscalations {
break
}
out.Escalations = append(out.Escalations, EscalationOut{Session: ss.ID, IP: ss.IP, Stage: ss.Stage, Steps: intel.Escalation(ss, evByIP[ss.IP])})
out.Escalations = append(out.Escalations, EscalationOut{Session: ss.ID, IP: ss.IP, Stage: ss.Stage, Steps: intel.Escalation(ss, st.evs(ss.IP))})
}
// sessions list: the heaviest, in time order
if len(sessions) > maxPeriodSessions {
@@ -358,7 +406,10 @@ func (s *Store) period(q PeriodQuery) PeriodOut {
if out.TopTargets[i].N != out.TopTargets[j].N {
return out.TopTargets[i].N > out.TopTargets[j].N
}
return out.TopTargets[i].Domain < out.TopTargets[j].Domain
if out.TopTargets[i].Domain != out.TopTargets[j].Domain {
return out.TopTargets[i].Domain < out.TopTargets[j].Domain
}
return out.TopTargets[i].Host < out.TopTargets[j].Host
})
if len(out.TopTargets) > 20 {
out.TopTargets = out.TopTargets[:20]
@@ -612,15 +663,10 @@ func (s *Store) metrics(rg Range) MetricsOut {
// from the registry: sessions, exposure, refused exploits, ssh login after brute force
out.SessionsPerDay, out.ExposureRate, out.ExploitsRefused, out.SSH.OKAfterFail = mk(0, 0, nil), mk(0, 0, nil), mk(0, 0, nil), mk(0, 0, nil)
if s.elog != nil {
var evs []intel.Ev
var expl, refused int
deadline := time.Now().Add(studyDead)
info := s.elog.Scan(evlog.Filter{From: from, To: to}, studyBudget, false, func(r evlog.Rec, _ []byte) bool {
if len(evs) >= maxStudyEvents || len(evs)%4096 == 0 && time.Now().After(deadline) {
out.Truncated = true
return false
}
evs = append(evs, toEv(r))
st := s.sessionStudy(PeriodQuery{From: from, To: to})
out.Truncated = st.truncated
info := s.elog.ScanRecs(evlog.Filter{From: from, To: to, Cats: map[string]bool{string(core.Exploit): true}}, studyBudget, false, func(r evlog.Rec) bool {
if r.Cat == string(core.Exploit) && r.Status > 0 {
expl++
if r.Status >= 400 {
@@ -630,7 +676,7 @@ func (s *Store) metrics(rg Range) MetricsOut {
return true
})
out.Truncated = out.Truncated || info.Truncated
sess := intel.Sessions(evs, 0)
sess := st.sessions
perDay := map[int64]int{}
succ, okAfter := 0, 0
for _, ss := range sess {
+4
View File
@@ -124,6 +124,9 @@ func Merge(host string, parts []Summary) Summary {
out.Totals.Malicious += p.Totals.Malicious
out.Totals.ActiveBans += p.Totals.ActiveBans
out.Totals.Monitoring += p.Totals.Monitoring
out.Totals.Trusted += p.Totals.Trusted
out.Totals.Internal += p.Totals.Internal
out.Totals.RequestsAll += p.Totals.RequestsAll
for k, v := range p.Totals.Counts {
out.Totals.Counts[k] += v
}
@@ -148,6 +151,7 @@ func Merge(host string, parts []Summary) Summary {
ctry = append(ctry, p.Countries)
recent = append(recent, p.Recent...)
}
out.Own = mergeOwn(parts, out.Timeline)
out.IPs = MergeIPs(ipLists...)
// Peers only ship their top IPs, so the merged list can undercount; never
// report less than the largest single instance, and exact for one part.
+221
View File
@@ -0,0 +1,221 @@
package store
import (
"strings"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
)
// Own traffic: web requests whose client is an own or trusted origin (--trusted
// and the --ignore ranges, private networks by default). They are counted in
// aggregates only, apart from every attack and visitor aggregate: they never
// create an IP record, score, session, campaign, technique, family, ban
// evidence or page view, and they leave no event record. The classes are the
// two names below.
const (
OwnTrusted = "trusted" // an address of --trusted (URUTAU_TRUSTED)
OwnInternal = "internal" // an address of an --ignore range (private networks by default)
)
const (
ownCap = 64 // distinct origins, domains and paths kept per hour and class-agnostic
ownPath = 120
)
// ownHour is the own traffic of one hour. Class index: 0 trusted, 1 internal.
type ownHour struct {
N [2]uint32
S [2][4]uint32 // 2xx 3xx 4xx 5xx
Origins, Domains, Paths map[string]uint32
}
func ownIdx(class string) int {
if class == OwnInternal {
return 1
}
return 0
}
// Own counts one web request of an own or trusted origin (class OwnTrusted or
// OwnInternal). Only the Traefik source is recorded.
func (s *Store) Own(ev core.Event, class string) {
now := s.now()
if ev.Time.Before(now.Add(-s.cfg.Retention)) || ev.IP == "" {
return
}
ts := ev.Time.Unix()
if max := now.Unix() + 300; ts > max {
ts = max
}
ci := ownIdx(class)
m, h := ts/60, ts/3600
i := int(m % slots)
path := ev.Path
if j := strings.IndexAny(path, "?#"); j >= 0 {
path = path[:j]
}
if len(path) > ownPath {
path = path[:ownPath]
}
origin := class[:1] + "|" + KeyOf(ev.IP)
s.mu.Lock()
if s.ownSt[i] != m {
s.ownSt[i], s.ownN[i] = m, [2]uint32{}
}
s.ownN[i][ci]++
hs := &s.hours[int(h%hourSlots)]
if hs.Hour != h {
*hs = hourSlot{Hour: h}
}
if hs.Own == nil {
hs.Own = &ownHour{}
}
o := hs.Own
o.N[ci]++
if k := ev.Status/100 - 2; k >= 0 && k < 4 {
o.S[ci][k]++
}
bumpCap(&o.Origins, origin, ownCap)
bumpCap(&o.Domains, normDomain(ev.Domain), ownCap)
bumpCap(&o.Paths, path, ownCap)
s.mu.Unlock()
}
// OwnTraffic is the own and trusted traffic of a window. It is not part of
// totals.requests: RequestsAll in the totals adds it.
type OwnTraffic struct {
Trusted uint64 `json:"trusted"`
Internal uint64 `json:"internal"`
Status [4]uint64 `json:"status"` // 2xx 3xx 4xx 5xx
Start int64 `json:"start"`
Step int64 `json:"step"`
Series map[string][]uint32 `json:"series"` // "trusted" and "internal"
Origins []Count `json:"origins"` // Key: address (an IPv6 /64 as a prefix), Label: class
Domains []Count `json:"domains"`
Paths []Count `json:"paths"`
}
// ownLocked adds the own traffic of the grid to the totals and, when o is not
// nil, to the breakdown. The caller holds s.mu.
func (s *Store) ownLocked(g grid, to int64, tot *Totals) OwnTraffic {
o := OwnTraffic{Start: g.Start, Step: g.Step, Series: map[string][]uint32{
OwnTrusted: make([]uint32, g.N), OwnInternal: make([]uint32, g.N)}}
if g.minute() {
for m := g.Start / 60; m <= to/60; m++ {
i := int(m % slots)
if s.ownSt[i] != m {
continue
}
if b := int((m*60 - g.Start) / g.Step); b >= 0 && b < g.N {
o.Series[OwnTrusted][b] += s.ownN[i][0]
o.Series[OwnInternal][b] += s.ownN[i][1]
}
}
}
origins, doms, paths := map[string]uint32{}, map[string]uint32{}, map[string]uint32{}
for h := g.Start / 3600; h <= to/3600; h++ {
hs := &s.hours[int(h%hourSlots)]
if hs.Hour != h || hs.Own == nil {
continue
}
oh := hs.Own
o.Trusted += uint64(oh.N[0])
o.Internal += uint64(oh.N[1])
for c := range oh.S {
for k, v := range oh.S[c] {
o.Status[k] += uint64(v)
}
}
if !g.minute() {
if b := int(h - g.Start/3600); b >= 0 && b < g.N {
o.Series[OwnTrusted][b] += oh.N[0]
o.Series[OwnInternal][b] += oh.N[1]
}
}
for _, p := range [...]struct{ from, to map[string]uint32 }{{oh.Origins, origins}, {oh.Domains, doms}, {oh.Paths, paths}} {
for k, v := range p.from {
p.to[k] += v
}
}
}
tot.Trusted, tot.Internal = o.Trusted, o.Internal
tot.RequestsAll = tot.Requests + o.Trusted + o.Internal
if o.Trusted > 0 {
tot.Counts[OwnTrusted] = o.Trusted
}
if o.Internal > 0 {
tot.Counts[OwnInternal] = o.Internal
}
o.Origins = ownOrigins(topN(origins, 40))
o.Domains, o.Paths = topN(doms, 20), topN(paths, 20)
return o
}
// ownOrigins splits the stored "<class>|<address>" keys into key and label.
func ownOrigins(in []Count) []Count {
for i, c := range in {
if len(c.Key) > 2 && c.Key[1] == '|' {
if c.Key[0] == 't' {
in[i].Label = OwnTrusted
} else {
in[i].Label = OwnInternal
}
in[i].Key = c.Key[2:]
}
}
return in
}
// mergeOwn adds the own traffic of several hosts. Series are aligned by
// timestamp like the attack timeline.
func mergeOwn(parts []Summary, grid Timeline) OwnTraffic {
n := 0
for _, c := range grid.Cats {
n = len(grid.Series[c])
break
}
out := OwnTraffic{Start: grid.Start, Step: grid.Step, Series: map[string][]uint32{
OwnTrusted: make([]uint32, n), OwnInternal: make([]uint32, n)}}
var origins, doms, paths [][]Count
for _, p := range parts {
o := p.Own
out.Trusted += o.Trusted
out.Internal += o.Internal
for k, v := range o.Status {
out.Status[k] += v
}
if o.Step == out.Step && o.Step > 0 {
shift := (o.Start - out.Start) / out.Step
for _, c := range []string{OwnTrusted, OwnInternal} {
for i, v := range o.Series[c] {
if j := int64(i) + shift; j >= 0 && j < int64(n) {
out.Series[c][j] += v
}
}
}
}
origins = append(origins, o.Origins)
doms = append(doms, o.Domains)
paths = append(paths, o.Paths)
}
out.Origins = mergeOwnOrigins(40, origins)
out.Domains, out.Paths = mergeCounts(20, doms...), mergeCounts(20, paths...)
return out
}
func mergeOwnOrigins(n int, lists [][]Count) []Count {
m, lab := map[string]uint32{}, map[string]string{}
for _, l := range lists {
for _, c := range l {
k := c.Label + "|" + c.Key
m[k] += c.N
lab[k] = c.Label
}
}
out := topN(m, n)
for i := range out {
out[i].Label = lab[out[i].Key]
out[i].Key = out[i].Key[len(out[i].Label)+1:]
}
return out
}
+4 -1
View File
@@ -28,6 +28,8 @@ type snapshot struct {
Hours [hourSlots]hourSlot
MonSt [slots]int64
MonN [slots]uint32
OwnSt [slots]int64 // own traffic minute buckets (optional: older snapshots lack it)
OwnN [slots][2]uint32
Dom map[string]*domData
GDays [anDays]gDay
Svc map[string]*svcData // service health (optional: older snapshots lack it)
@@ -73,7 +75,7 @@ func (s *Store) Save(path string, offsets map[string]Offset) error {
}
bw := bufio.NewWriterSize(f, 256*1024)
s.mu.RLock()
snap := snapshot{V: snapshotVersion, Saved: s.now().Unix(), Stamps: s.stamps, Counts: s.counts, Hours: s.hours, MonSt: s.monSt, MonN: s.monN, Dom: s.tr.dom, GDays: s.tr.gdays, Svc: s.sv.m,
snap := snapshot{V: snapshotVersion, Saved: s.now().Unix(), Stamps: s.stamps, Counts: s.counts, Hours: s.hours, MonSt: s.monSt, MonN: s.monN, OwnSt: s.ownSt, OwnN: s.ownN, Dom: s.tr.dom, GDays: s.tr.gdays, Svc: s.sv.m,
IPs: s.ips, Recent: s.recent, Rhead: s.rhead, Offsets: offsets, IDSeq: s.ids.Load()}
err = gob.NewEncoder(bw).Encode(&snap)
s.mu.RUnlock()
@@ -124,6 +126,7 @@ func (s *Store) Load(path string) (map[string]Offset, error) {
s.mu.Lock()
s.stamps, s.counts, s.hours = snap.Stamps, snap.Counts, snap.Hours
s.monSt, s.monN = snap.MonSt, snap.MonN
s.ownSt, s.ownN = snap.OwnSt, snap.OwnN
s.tr.dom, s.tr.gdays = snap.Dom, snap.GDays
s.sv.m = snap.Svc
for _, d := range s.tr.dom {
+3
View File
@@ -135,6 +135,7 @@ type hourSlot struct {
Paths, Domains, UAs, Users, Countries map[string]uint32
C [core.NumCats]uint32 // events per category in the hour
Mon uint32 // monitoring requests in the hour
Own *ownHour // own and trusted traffic (see own.go), nil when none
}
// FeedEvent is one entry of the live feed.
@@ -261,6 +262,8 @@ type Store struct {
hours [hourSlots]hourSlot
monSt [slots]int64
monN [slots]uint32
ownSt [slots]int64
ownN [slots][2]uint32
tr trafficState
sv svcState
allow []string
+275
View File
@@ -0,0 +1,275 @@
package store
import (
"compress/gzip"
"encoding/json"
"fmt"
"math/rand"
"os"
"path/filepath"
"reflect"
"runtime"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
)
var synthCats = []string{"scanner", "scanner", "exploit", "notfound", "ssh-fail", "ssh-fail", "bruteforce", "ssh-ok", "ban"}
var synthFams = []string{"", "traversal", "sqli", "wordpress", "vcs", "env-credentials", "webshell", "rce-injection"}
// writeSynthDays writes days of bursty traffic from two hosts into dir: closed
// days gzip compressed, the day of now plain. Some bursts cross midnight.
func writeSynthDays(t testing.TB, dir string, days, perDay int, now time.Time, seed int64) {
rng := rand.New(rand.NewSource(seed))
if err := os.MkdirAll(dir, 0o700); err != nil {
t.Fatal(err)
}
ips := make([]string, 4000)
for i := range ips {
ips[i] = fmt.Sprintf("%d.%d.%d.%d", 20+i%200, rng.Intn(250), rng.Intn(250), 1+rng.Intn(250))
}
paths := make([]string, 600)
for i := range paths {
paths[i] = fmt.Sprintf("/wp-content/plugins/p%d/readme.%d.php", rng.Intn(80), i)
}
uas := make([]string, 40)
for i := range uas {
uas[i] = fmt.Sprintf("Mozilla/5.0 (X11; rv:%d.0) Gecko/20100101 Firefox/%d.0", 60+i, 60+i)
}
uas[3], uas[4] = "sqlmap/1.7", "Nuclei - Open-source project"
today := now.Unix() / 86400
var id uint64
for d := today - int64(days) + 1; d <= today; d++ {
var lines [][]byte
emit := func(tt int64, ip string, burstCat string) {
id++
host := []string{"oracle", "hostinger"}[rng.Intn(2)]
c := burstCat
if c == "" {
c = synthCats[rng.Intn(len(synthCats))]
}
r := evlog.Rec{ID: id, T: tt, IP: ip, Cat: c, Source: "traefik", Host: host, Domain: fmt.Sprintf("site%d.example.org", rng.Intn(6)),
Method: "GET", Path: paths[rng.Intn(len(paths))], Status: []int{200, 301, 403, 404, 500}[rng.Intn(5)], UA: uas[rng.Intn(len(uas))],
CC: "BR", Bytes: int64(rng.Intn(5000)), DurMS: int64(rng.Intn(300))}
if c == "ssh-fail" || c == "ssh-ok" || c == "bruteforce" {
r.Source, r.Path, r.UA, r.Domain, r.Status, r.Method = "ssh", "", "", "", 0, ""
r.User = []string{"root", "admin", "ubuntu", "test"}[rng.Intn(4)]
}
if c == "exploit" || c == "scanner" {
r.Fam = synthFams[rng.Intn(len(synthFams))]
if r.Fam != "" {
r.Tech = []string{"T1190", "T1595"}[:1+rng.Intn(2)]
}
}
b, _ := json.Marshal(r)
lines = append(lines, b)
}
base := d * 86400
for len(lines) < perDay {
ip := ips[int(float64(len(ips))*rng.Float64()*rng.Float64())]
start := base + int64(rng.Intn(86400))
n := 1 + rng.Intn(30)
for k := 0; k < n && start < base+86400 && len(lines) < perDay; k++ {
emit(start, ip, "")
start += int64(1 + rng.Intn(20))
}
}
// bursts that cross midnight into the next day (and from the previous one)
for k := 0; k < 25; k++ {
ip := ips[rng.Intn(60)]
for tt := base + 86400 - 90; tt < base+86400+90; tt += int64(5 + rng.Intn(20)) {
if tt < base+86400 {
emit(tt, ip, "scanner")
}
}
}
// the next day gets the tail of last night's bursts
_ = lines
name := time.Unix(d*86400, 0).UTC().Format("2006-01-02")
var out []byte
for _, l := range lines {
out = append(out, l...)
out = append(out, '\n')
}
if d == today {
os.WriteFile(filepath.Join(dir, name+".jsonl"), out, 0o600)
continue
}
f, _ := os.Create(filepath.Join(dir, name+".jsonl.gz"))
zw := gzip.NewWriter(f)
zw.Write(out)
zw.Close()
f.Close()
}
// tails of midnight bursts: events just after midnight into each following day file
for d := today - int64(days) + 1; d < today; d++ {
appendTail(t, dir, d+1, rng, ips[:60], d+1 == today)
}
}
// appendTail adds events shortly after midnight of day d for the first
// addresses, whose bursts began before midnight.
func appendTail(t testing.TB, dir string, d int64, rng *rand.Rand, ips []string, plain bool) {
name := filepath.Join(dir, time.Unix(d*86400, 0).UTC().Format("2006-01-02"))
var add []byte
for i := 0; i < 25; i++ {
ip := ips[i%len(ips)]
for tt := d * 86400; tt < d*86400+90; tt += int64(5 + rng.Intn(20)) {
b, _ := json.Marshal(evlog.Rec{ID: uint64(1e9) + uint64(tt)*100 + uint64(i), T: tt, IP: ip, Cat: "scanner", Source: "traefik", Host: "oracle",
Domain: "site1.example.org", Method: "GET", Path: "/.env", Status: 404, UA: "sqlmap/1.7"})
add = append(add, b...)
add = append(add, '\n')
}
}
if plain {
f, _ := os.OpenFile(name+".jsonl", os.O_APPEND|os.O_WRONLY, 0o600)
f.Write(add)
f.Close()
return
}
// a second gzip member appended to the day file is valid gzip
f, _ := os.OpenFile(name+".jsonl.gz", os.O_APPEND|os.O_WRONLY, 0o600)
zw := gzip.NewWriter(f)
zw.Write(add)
zw.Close()
f.Close()
}
func synthStore(t testing.TB, days, perDay int, cacheMem int64) (*Store, *evlog.Log, string) {
dir := filepath.Join(t.TempDir(), "events")
writeSynthDays(t, dir, days, perDay, t0, 1)
l, err := evlog.Open(evlog.Options{Dir: dir, Now: func() time.Time { return t0 }, MaxBytes: 4 << 30, CacheMem: cacheMem})
if err != nil {
t.Fatal(err)
}
s := store30("oracle")
s.SetEventLog(l)
return s, l, dir
}
func pq(days int) PeriodQuery {
return PeriodQuery{From: t0.Unix() - int64(days)*86400, To: t0.Unix()}
}
func BenchmarkStudy30d(b *testing.B) {
s, l, _ := synthStore(b, 30, 25000, 0)
q := pq(30)
run := func(name string) {
st := time.Now()
p := s.period(q)
c := s.countStages(q)
m := s.metrics(Range{Name: "custom", From: q.From, To: q.To})
var ms runtime.MemStats
runtime.ReadMemStats(&ms)
b.Logf("%s: %v events=%d trunc=%v/%v/%v sessions=%d heap=%dMB", name, time.Since(st), p.Events, p.Truncated, c.Truncated, m.Truncated, p.SessionsN, ms.HeapAlloc>>20)
}
run("cold")
for i := 0; i < b.N; i++ {
s.study.mu.Lock()
s.study.m = nil // the 30 s result cache expired; the decoded days stay
s.study.mu.Unlock()
run("warm")
}
d, mem, loads := l.CacheStats()
b.Logf("cache days=%d mem=%dMB loads=%d", d, mem>>20, loads)
}
// studyDigest is everything the views show of a window, for equality checks.
func studyDigest(s *Store, q PeriodQuery) map[string]any {
p := s.period(q)
c := s.countStages(q)
m := s.metrics(Range{Name: "custom", From: q.From, To: q.To})
p.Range = RangeInfo{}
m.Generated = 0
return map[string]any{"period": p, "funnel": c, "metrics": m}
}
func TestDayCacheEqualsFullScan(t *testing.T) {
dir := filepath.Join(t.TempDir(), "events")
writeSynthDays(t, dir, 6, 3000, t0, 7)
open := func(mem int64) *Store {
l, err := evlog.Open(evlog.Options{Dir: dir, Now: func() time.Time { return t0 }, CacheMem: mem})
if err != nil {
t.Fatal(err)
}
s := store30("oracle")
s.SetEventLog(l)
return s
}
cached, plain := open(0), open(-1)
for _, days := range []int{1, 3, 6} {
q := pq(days)
a, b := studyDigest(cached, q), studyDigest(plain, q)
for k := range a {
if !reflect.DeepEqual(a[k], b[k]) {
t.Errorf("%dd: %s differs", days, k)
}
}
if p, q := a["period"].(PeriodOut), b["period"].(PeriodOut); !reflect.DeepEqual(p, q) {
v1, v2 := reflect.ValueOf(p), reflect.ValueOf(q)
for i := 0; i < v1.NumField(); i++ {
if !reflect.DeepEqual(v1.Field(i).Interface(), v2.Field(i).Interface()) {
t.Errorf("period field %s differs", v1.Type().Field(i).Name)
}
}
}
if !reflect.DeepEqual(a, b) {
t.Fatalf("%dd: cached study differs from the full scan", days)
}
if a["period"].(PeriodOut).SessionsN == 0 || len(a["period"].(PeriodOut).TopFams) == 0 {
t.Fatalf("%dd: empty study", days)
}
}
// sessions that cross midnight stay whole: the burst of 23:58 to 00:01 is one session per address
p := cached.period(pq(6))
crossing := 0
for _, ss := range p.Sessions {
if ss.Start.Unix()/86400 != ss.End.Unix()/86400 {
crossing++
}
}
if crossing == 0 {
t.Fatal("no session crosses midnight in the fixture")
}
if p.Truncated {
t.Fatal("a small study must not be truncated")
}
}
func TestDayCacheInvalidatesOnChange(t *testing.T) {
dir := filepath.Join(t.TempDir(), "events")
writeSynthDays(t, dir, 3, 500, t0, 3)
l, err := evlog.Open(evlog.Options{Dir: dir, Now: func() time.Time { return t0 }})
if err != nil {
t.Fatal(err)
}
count := func() int {
n := 0
l.ScanRecs(evlog.Filter{From: t0.Unix() - 3*86400, To: t0.Unix()}, 0, false, func(evlog.Rec) bool { n++; return true })
return n
}
n1 := count()
if d, _, loads := l.CacheStats(); d != 2 || loads != 2 {
t.Fatalf("closed days cached: days=%d loads=%d", d, loads)
}
if count() != n1 {
t.Fatal("second scan differs")
}
if _, _, loads := l.CacheStats(); loads != 2 {
t.Fatalf("unchanged days must not reload: %d", loads)
}
// a late line lands in a closed day: its signature changes and it is read again
day := time.Unix(t0.Unix()/86400*86400-86400, 0).UTC().Format("2006-01-02")
f, err := os.OpenFile(filepath.Join(dir, day+".jsonl.gz"), os.O_APPEND|os.O_WRONLY, 0o600)
if err != nil {
t.Fatal(err)
}
zw := gzip.NewWriter(f)
zw.Write([]byte(`{"id":99999999,"t":` + fmt.Sprint(t0.Unix()-86400) + `,"ip":"9.9.9.9","cat":"scanner","source":"traefik","host":"oracle"}` + "\n"))
zw.Close()
f.Close()
if n2 := count(); n2 != n1+1 {
t.Fatalf("changed day not reloaded: %d vs %d", n2, n1+1)
}
}
+7 -1
View File
@@ -32,6 +32,10 @@ type Totals struct {
ActiveBans int `json:"active_bans"`
Monitoring uint64 `json:"monitoring"`
Counts map[string]uint64 `json:"counts"`
// Own and trusted traffic (see own.go) is NOT in Requests; RequestsAll adds it.
Trusted uint64 `json:"trusted"`
Internal uint64 `json:"internal"`
RequestsAll uint64 `json:"requests_all"`
}
// IPSummary describes one IP. Samples, UAs and Domains are only filled in the
@@ -98,6 +102,7 @@ type Summary struct {
Generated int64 `json:"generated"`
Hosts []HostInfo `json:"hosts"`
Totals Totals `json:"totals"`
Own OwnTraffic `json:"own"` // own and trusted origins, apart from every attack number
Timeline Timeline `json:"timeline"`
Rates Rates `json:"rates"`
IPs []IPSummary `json:"ips"`
@@ -428,6 +433,7 @@ func (s *Store) buildSummary(rg Range) Summary {
tot.Monitoring += uint64(hs.Mon)
}
}
own := s.ownLocked(g, to, &tot)
paths, doms, uas, users, ctry := map[string]uint32{}, map[string]uint32{}, map[string]uint32{}, map[string]uint32{}, map[string]uint32{}
firstHour, lastHour := start/3600, to/3600
for i := range s.hours {
@@ -522,7 +528,7 @@ func (s *Store) buildSummary(rg Range) Summary {
Hosts: []HostInfo{{Name: s.cfg.Name, Self: true, Online: true, Version: s.cfg.Version, LastSeen: nowU,
Requests: tot.Requests, Malicious: tot.Malicious, HostileIPs: tot.HostileIPs, ActiveBans: tot.ActiveBans,
Live: true, Location: s.Location()}},
Totals: tot, Timeline: tl, Rates: rates, IPs: ips,
Totals: tot, Own: own, Timeline: tl, Rates: rates, IPs: ips,
TopPaths: topN(paths, topKeep), TopDomains: topN(doms, topKeep), TopUAs: topUAs, TopUsers: topN(users, topKeep), Countries: topN(ctry, 120),
Recent: recent, Sources: srcs, Attribution: s.attrib,
}
+2 -2
View File
@@ -97,8 +97,8 @@ func (s *Store) techniques(q PeriodQuery) TechniquesOut {
deadline := time.Now().Add(studyDead)
acc := map[string]*techAcc{}
n := 0
info := s.elog.Scan(evlog.Filter{From: q.From - span, To: q.To, Host: q.Host}, studyBudget, false,
func(r evlog.Rec, _ []byte) bool {
info := s.elog.ScanRecs(evlog.Filter{From: q.From - span, To: q.To, Host: q.Host}, studyBudget, false,
func(r evlog.Rec) bool {
if n++; n > maxStudyEvents || n%4096 == 0 && time.Now().After(deadline) {
out.Truncated = true
return false
+5 -1
View File
@@ -33,6 +33,10 @@ const (
SrcFail2ban = "fail2ban"
SrcProbe = "probe"
SrcEgress = "egress"
// SrcIngress is the sampled kernel log of new inbound attempts (ingress.log)
// and SrcIngressCnt the exact once-a-minute counters (ingress.counters).
SrcIngress = "ingress"
SrcIngressCnt = "ingresscnt"
)
// File names carried whole.
@@ -41,7 +45,7 @@ const (
FileResolv = "resolv.conf"
)
var Sources = []string{SrcTraefik, SrcAuth, SrcFail2ban, SrcProbe, SrcEgress}
var Sources = []string{SrcTraefik, SrcAuth, SrcFail2ban, SrcProbe, SrcEgress, SrcIngress, SrcIngressCnt}
func ValidSource(s string) bool {
for _, x := range Sources {
+17
View File
@@ -48,6 +48,23 @@ if [ "$ui" = 1 ]; then
fi
step "bash script syntax" bash -c 'for f in scripts/*.sh .githooks/*; do bash -n "$f" || exit 1; done'
step "host kit shell syntax" bash -c 'for f in deploy/host/install.sh deploy/host/urutau-ingress-tick deploy/host/urutau-containers-map deploy/host/urutau-containers-watch deploy/host/urutau-unban; do sh -n "$f" || exit 1; done'
# nftables syntax of the host kit tables, validated in a throwaway network
# namespace (no root needed); skipped when nft or unshare cannot do it.
if command -v nft >/dev/null && unshare -rn true 2>/dev/null; then
step "host kit nftables syntax" bash -c 'for f in deploy/host/urutau-egress.nft deploy/host/urutau-ingress.nft; do
t=$(mktemp); sed "s/@WAN@/eth0/g" "$f" > "$t"
unshare -rn nft -c -f "$t" || { rm -f "$t"; exit 1; }
rm -f "$t"
# the observation table must never decide the fate of a packet
if [ "$f" = deploy/host/urutau-ingress.nft ] && grep -Eq "^[^#]*[[:space:]](drop|accept|reject|queue|dnat|snat|masquerade|redirect|ct mark set|meta mark set)([[:space:]]|$)" "$f"; then
echo "$f: the ingress table must only count and log" >&2; exit 1
fi
done'
else
skip "host kit nftables syntax" "nft or unprivileged namespaces not available"
fi
if python3 -c 'import yaml' 2>/dev/null; then
step "workflows and templates (valid YAML)" python3 -c "