Merge branch 'feat/inbound-firewall-telemetry' into release/2.3.0
# Conflicts: # CHANGELOG.md # CHANGELOG.pt-BR.md
This commit is contained in:
commit
554ea1340c
40 files changed
+1684
-11
No files matched your search
@@ -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` |
|
||||
@@ -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 |
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
@@ -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) |
|
||||
|
||||
@@ -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` |
|
||||
@@ -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 |
|
||||
|
||||
@@ -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`.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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) |
|
||||
|
||||
Reference in new issue
Block a user