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>
This commit is contained in:
Lucas RayanandClaude Sonnet 5.5 committed 2026-11-23 09:09:16 -03:00
1 parent 4143bf599e
commit aefdcea8d2
40 files changed
+1684 -11

No files matched your search

+4
View File
@@ -6,6 +6,10 @@ Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versio
## [Unreleased]
### 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.
## [2.2.2] - 2026-11-19
### Fixed
+4
View File
@@ -6,6 +6,10 @@ Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/);
## [Não lançado]
### 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.
## [2.2.2] - 2026-11-19
### Corrigido
+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.
+9 -1
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.
@@ -326,6 +333,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 +355,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 |
+12
View File
@@ -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 |
@@ -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
+2 -1
View File
@@ -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) |
+9 -1
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.
@@ -326,6 +333,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 +355,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 |
+12
View File
@@ -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 |
@@ -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
+2 -1
View File
@@ -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) |
+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
+10
View File
@@ -115,6 +115,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
@@ -236,6 +239,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)
}
+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
}
+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
}
+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;
}
+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
}
+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 "