feat!: Urutau 2.0.0, ultralight probes and a single analysis hub
CI / Format and vet (pull_request) Failing after 53s
CI / Dependency audit (pull_request) Successful in 33s
CI / Tests (Linux, race detector) (pull_request) Successful in 2m1s
CI / Docker images (build and smoke test) (pull_request) Failing after 47s

Each server runs an ultralight probe (scratch image, ~7 MiB RSS) that
tails the logs, ships raw lines to the hub over HTTPS with an on-disk
spool, and applies enforce decisions locally. The hub keeps one node per
probe (primary node = the 1.x data dir, unchanged), does all analysis and
serves the UI. Peer federation is removed. 'urutau import' brings 1.x
data dirs in with hash and count verification. UI: probes page, host
qualified incidents, IPs never wrap, egress heatmap labels, live and
replay globes no longer auto-rotate, replay repeat, live traffic metrics.

BREAKING CHANGE: URUTAU_PEERS, URUTAU_PEER_* and /api/v1/peer/* are gone;
log path variables move from the hub to the probe. See docs/migration-2.0.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lucas RayanandClaude Opus 5.5 committed 2026-11-15 22:14:50 -03:00
1 parent 23a7a5963a
commit 8546d14cef
130 files changed
+9396 -3311

No files matched your search

+9 -18
View File
@@ -1,4 +1,5 @@
# Variables read by docker-compose.yml. Other URUTAU_* settings need a line in
# Variables read by docker-compose.yml (the hub). A probe has its own file:
# deploy/probe/.env.example. Other URUTAU_* settings need a line in
# the compose `environment` block (see docs/configuration.md).
# Image tag: latest (last release), X.Y.Z / X.Y (pinned), or edge (main).
@@ -14,23 +15,13 @@ URUTAU_PUBLISH=127.0.0.1:8790
URUTAU_TOKEN=
# Name of this instance in the dashboard.
URUTAU_NAME=urutau
# Token shared between a hub and its peers (same rules as URUTAU_TOKEN, and
# different from it). It only opens /api/v1/peer/export. Empty: no export (a
# hub with peers needs a token for each: this one, or URUTAU_PEER_TOKEN_<NAME>
# added to the compose environment).
URUTAU_PEER_TOKEN=
# Source CIDRs allowed to call the export (e.g. the hub's address). Empty: any
# source that has the token.
URUTAU_PEER_ALLOW=
# Reverse proxies whose X-Forwarded-For is trusted (login rate limit, peer allow).
# Reverse proxies whose X-Forwarded-For is trusted (login rate limit, probe auth limiter).
# The compose file puts the service on the urutau-edge network (10.250.0.0/24)
# and trusts only that; connect the proxy to it (see docs/docker.md).
URUTAU_TRUSTED_PROXY=10.250.0.0/24
# SSH users whose successful logins keep their IP out of the blocklist for 24 h
# (comma separated). Empty: no admin immunity.
URUTAU_ADMIN_USERS=
# Peers this instance aggregates (hub mode), comma separated name=https://url.
URUTAU_PEERS=
# Your own servers and monitors: their events are dropped entirely
# (comma separated CIDRs or IPs). Private, link-local and CGNAT ranges are
# already dropped (see --ignore).
@@ -45,7 +36,8 @@ URUTAU_DOMAINS=
# CIDRs the monitoring User-Agents come from. When set, the monitor User-Agent
# only counts from them. Empty: only `ok` answers are filtered.
URUTAU_MONITOR_FROM=
# Time zone of the host: fail2ban.log timestamps are local time.
# Time zone of the probes: fail2ban.log timestamps are local time and the hub
# parses them, so it must be the same on the hub and on every probe.
TZ=UTC
# Event registry size cap in <data-dir>/events (0 turns it off). Not passed by the
# compose file as is: add it to the `environment` block to change the 512MB default.
@@ -55,17 +47,16 @@ URUTAU_RETENTION=720h
# File with Tor exit addresses (one per line); same note as above.
URUTAU_TOR_EXITS=
# Port probes (host kit) and Tor lists
URUTAU_PROBE_LOG=/logs/host/probe.log
# Tor exit/relay lists
URUTAU_TOR_AUTO=on
# Second firewall: off | observe | on (needs deploy/host/install.sh --enforce
# and the /logs/enforce volume in docker-compose.yml)
# Second firewall: off | observe | on (needs deploy/host/install.sh --probe --enforce
# on each probe host; the decisions travel through the probes)
URUTAU_ENFORCE=off
URUTAU_ENFORCE_SHARE=off
URUTAU_ENFORCE_THRESHOLD=5
# Outbound traffic analysis: auto | on | off
# Outbound traffic analysis (egress log sent by the probes): auto | on | off
URUTAU_EGRESS=auto
URUTAU_EGRESS_WORKLOADS=
URUTAU_EGRESS_RESOLVERS=
+15 -7
View File
@@ -39,8 +39,12 @@ jobs:
for f in glob.glob('.gitea/**/*.yml', recursive=True):
yaml.safe_load(open(f))
"
- name: Docker compose config
run: docker compose config --quiet
- name: Docker compose config (hub and probe)
run: |
docker compose config --quiet
URUTAU_HUB=https://hub.example.org URUTAU_PROBE_NAME=ci docker compose -f deploy/probe/docker-compose.yml config --quiet
- name: shellcheck (host kit)
run: docker run --rm -v "$PWD:/mnt:ro" koalaman/shellcheck:v0.10.0 deploy/host/install.sh
- name: gofmt
run: test -z "$(gofmt -l .)"
- run: go vet ./...
@@ -70,15 +74,19 @@ jobs:
govulncheck ./...
image:
name: Docker image (build and smoke test)
name: Docker images (build and smoke test)
if: ${{ gitea.event_name == 'pull_request' }}
runs-on: linux-arm64
steps:
- uses: actions/checkout@v7
- name: Build
run: docker build -t "urutau-ci:${{ gitea.run_id }}" .
- name: Smoke test
- name: Build hub
run: docker build --target hub -t "urutau-ci:${{ gitea.run_id }}" .
- name: Build probe
run: docker build --target probe -t "urutau-probe-ci:${{ gitea.run_id }}" .
- name: Smoke test (hub)
run: scripts/smoke-image.sh "urutau-ci:${{ gitea.run_id }}"
- name: Smoke test (probe, under 15 MB)
run: scripts/smoke-probe.sh "urutau-probe-ci:${{ gitea.run_id }}"
- name: Clean up
if: always()
run: docker rmi -f "urutau-ci:${{ gitea.run_id }}" >/dev/null 2>&1 || true
run: docker rmi -f "urutau-ci:${{ gitea.run_id }}" "urutau-probe-ci:${{ gitea.run_id }}" >/dev/null 2>&1 || true
+47 -28
View File
@@ -1,9 +1,10 @@
name: Release
# Publishes the multi-arch Urutau image (linux/amd64 + linux/arm64) to the Gitea
# container registry. A merge into main publishes `edge`; a v* tag re-points the
# image already built for the same inputs to X.Y.Z, X.Y and latest (no rebuild)
# and creates the Gitea Release. Needs the secret REGISTRY_TOKEN (Gitea token
# Publishes the two multi-arch Urutau images (linux/amd64 + linux/arm64) to the
# Gitea container registry: the hub (<repo>) and the probe (<repo>-probe), both
# built from the same Dockerfile. A merge into main publishes `edge`; a v* tag
# re-points the images already built for the same inputs to X.Y.Z, X.Y and
# latest (no rebuild) and creates the Gitea Release. Needs the secret REGISTRY_TOKEN (Gitea token
# with write:package) visible to this repository.
on:
push:
@@ -19,8 +20,8 @@ env:
REGISTRY: git.lucasrguerra.dev.br
jobs:
# The image is built only from these paths, so their tree hashes identify it.
# When inputs-<hash> already exists (docs-only merge, workflow change, or a tag
# The images are built only from these paths, so their tree hashes identify
# them. When inputs-<hash> already exists for BOTH images (docs-only merge, workflow change, or a tag
# on a commit main already published), nothing is built or tested again.
plan:
name: Plan (reuse the published image?)
@@ -29,6 +30,7 @@ jobs:
inputs: ${{ steps.plan.outputs.inputs }}
reuse: ${{ steps.plan.outputs.reuse }}
image: ${{ steps.plan.outputs.image }}
probe_image: ${{ steps.plan.outputs.probe_image }}
steps:
- uses: actions/checkout@v7
- id: plan
@@ -40,26 +42,30 @@ jobs:
git cat-file -e HEAD:go.sum 2>/dev/null && paths="$paths go.sum"
inputs=$(for p in $paths; do git rev-parse "HEAD:$p"; done | sha256sum | cut -c1-16)
ns="${REPO,,}"
token=$(curl -fsS "https://$REGISTRY/v2/token?service=container_registry&scope=repository:$ns:pull" | jq -r .token)
code=$(curl -s -o /dev/null -w '%{http_code}' -I \
-H "Authorization: Bearer $token" \
-H 'Accept: application/vnd.oci.image.index.v1+json,application/vnd.docker.distribution.manifest.list.v2+json' \
"https://$REGISTRY/v2/$ns/manifests/inputs-$inputs")
echo "inputs-$inputs -> HTTP $code"
reuse=false; [ "$code" = 200 ] && reuse=true
reuse=true
for repo in "$ns" "$ns-probe"; do
token=$(curl -fsS "https://$REGISTRY/v2/token?service=container_registry&scope=repository:$repo:pull" | jq -r .token)
code=$(curl -s -o /dev/null -w '%{http_code}' -I \
-H "Authorization: Bearer $token" \
-H 'Accept: application/vnd.oci.image.index.v1+json,application/vnd.docker.distribution.manifest.list.v2+json' \
"https://$REGISTRY/v2/$repo/manifests/inputs-$inputs")
echo "$repo inputs-$inputs -> HTTP $code"
[ "$code" = 200 ] || reuse=false
done
echo "inputs=$inputs" >> "$GITHUB_OUTPUT"
echo "reuse=$reuse" >> "$GITHUB_OUTPUT"
echo "image=$REGISTRY/$ns" >> "$GITHUB_OUTPUT"
echo "probe_image=$REGISTRY/$ns-probe" >> "$GITHUB_OUTPUT"
ci:
needs: plan
if: ${{ needs.plan.outputs.reuse != 'true' }}
uses: ./.gitea/workflows/ci.yml
# Each architecture is built on a native runner (no QEMU) and pushed under a
# per-architecture tag; publish joins them into one manifest list.
# Each architecture of each image is built on a native runner (no QEMU) and
# pushed under a per-architecture tag; publish joins them into one manifest list.
build:
name: Build image (${{ matrix.arch }})
name: Build ${{ matrix.target }} image (${{ matrix.arch }})
needs: [plan, ci]
if: ${{ needs.plan.outputs.reuse != 'true' }}
runs-on: ${{ matrix.runner }}
@@ -67,8 +73,10 @@ jobs:
fail-fast: false
matrix:
include:
- { arch: amd64, platform: linux/amd64, runner: linux-amd64 }
- { arch: arm64, platform: linux/arm64, runner: linux-arm64 }
- { target: hub, arch: amd64, platform: linux/amd64, runner: linux-amd64 }
- { target: hub, arch: arm64, platform: linux/arm64, runner: linux-arm64 }
- { target: probe, arch: amd64, platform: linux/amd64, runner: linux-amd64 }
- { target: probe, arch: arm64, platform: linux/arm64, runner: linux-arm64 }
steps:
- uses: actions/checkout@v7
- uses: docker/setup-buildx-action@v4
@@ -82,23 +90,33 @@ jobs:
# Same end result, no action to clone.
- name: Build and push (per architecture)
run: |
image='${{ matrix.target == 'probe' && needs.plan.outputs.probe_image || needs.plan.outputs.image }}'
docker buildx build \
--target "${{ matrix.target }}" \
--platform "${{ matrix.platform }}" \
--push \
-t "${{ needs.plan.outputs.image }}:build-${{ gitea.sha }}-${{ matrix.arch }}" \
--cache-from "type=registry,ref=${{ needs.plan.outputs.image }}:buildcache-${{ matrix.arch }}" \
--cache-to "type=registry,ref=${{ needs.plan.outputs.image }}:buildcache-${{ matrix.arch }},mode=max" \
-t "$image:build-${{ gitea.sha }}-${{ matrix.arch }}" \
--cache-from "type=registry,ref=$image:buildcache-${{ matrix.arch }}" \
--cache-to "type=registry,ref=$image:buildcache-${{ matrix.arch }},mode=max" \
.
# Runs the image that was just pushed, on its own architecture.
- name: Smoke test
run: scripts/smoke-image.sh "${{ needs.plan.outputs.image }}:build-${{ gitea.sha }}-${{ matrix.arch }}"
run: |
image='${{ matrix.target == 'probe' && needs.plan.outputs.probe_image || needs.plan.outputs.image }}'
scripts/smoke-${{ matrix.target == 'probe' && 'probe' || 'image' }}.sh "$image:build-${{ gitea.sha }}-${{ matrix.arch }}"
publish:
name: Publish tags
name: Publish tags (${{ matrix.target }})
needs: [plan, build]
# build is skipped, not successful, when the image is reused.
if: ${{ !cancelled() && needs.plan.result == 'success' && (needs.build.result == 'success' || needs.plan.outputs.reuse == 'true') }}
runs-on: linux-arm64
strategy:
fail-fast: false
matrix:
target: [hub, probe]
env:
IMAGE: ${{ matrix.target == 'probe' && needs.plan.outputs.probe_image || needs.plan.outputs.image }}
steps:
- uses: docker/setup-buildx-action@v4
- uses: docker/login-action@v4
@@ -110,7 +128,7 @@ jobs:
id: meta
uses: docker/metadata-action@v6
with:
images: ${{ needs.plan.outputs.image }}
images: ${{ env.IMAGE }}
flavor: latest=false
tags: |
type=semver,pattern={{version}}
@@ -120,7 +138,7 @@ jobs:
type=sha,format=long
- name: Apply tags
run: |
image='${{ needs.plan.outputs.image }}'
image="$IMAGE"
tags=$(jq -cr '.tags | map("-t " + .) | join(" ")' <<< '${{ steps.meta.outputs.json }}')
inputs='${{ needs.plan.outputs.inputs }}'
if [ '${{ needs.plan.outputs.reuse }}' = true ]; then
@@ -131,14 +149,14 @@ jobs:
fi
- name: Check architectures
run: |
docker buildx imagetools inspect "${{ needs.plan.outputs.image }}:inputs-${{ needs.plan.outputs.inputs }}" \
docker buildx imagetools inspect "$IMAGE:inputs-${{ needs.plan.outputs.inputs }}" \
--format '{{json .Manifest}}' \
| jq -r '.manifests[] | select(.platform.os == "linux") | "\(.platform.os)/\(.platform.architecture)"' \
| tee platforms.txt
grep -qx linux/amd64 platforms.txt && grep -qx linux/arm64 platforms.txt
- name: Summary
run: |
{ echo "### Urutau image published (linux/amd64, linux/arm64)"; echo; echo '```'
{ echo "### Urutau ${{ matrix.target }} image published (linux/amd64, linux/arm64)"; echo; echo '```'
echo "${{ steps.meta.outputs.tags }}"; echo '```'; } >> "$GITHUB_STEP_SUMMARY"
gitea-release:
@@ -156,11 +174,12 @@ jobs:
TOKEN: ${{ gitea.token }}
API: ${{ gitea.server_url }}/api/v1/repos/${{ gitea.repository }}
IMAGE: ${{ needs.plan.outputs.image }}
PROBE_IMAGE: ${{ needs.plan.outputs.probe_image }}
run: |
if curl -fsS -H "Authorization: token $TOKEN" "$API/releases/tags/$TAG" >/dev/null 2>&1; then
echo "release $TAG already exists"; exit 0
fi
{ scripts/release-notes.sh "$TAG"; echo; echo '```bash'; echo "docker pull $IMAGE:${TAG#v}"; echo '```'; } > notes.md
{ scripts/release-notes.sh "$TAG"; echo; echo '```bash'; echo "docker pull $IMAGE:${TAG#v}"; echo "docker pull $PROBE_IMAGE:${TAG#v}"; echo '```'; } > notes.md
pre=false; case "$TAG" in *-*) pre=true ;; esac
jq -n --arg tag "$TAG" --arg name "Urutau ${TAG#v}" --rawfile body notes.md --argjson pre "$pre" \
'{tag_name:$tag, name:$name, body:$body, prerelease:$pre}' > release.json
+27 -3
View File
@@ -6,9 +6,32 @@ Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versio
## [Unreleased]
### Documentation
## [2.0.0] - 2026-11-15
- Docs, README and screenshots updated to 1.6.0.
Breaking release: read [docs/migration-2.0.md](docs/migration-2.0.md) before upgrading.
### Added
- Ultra-light probe: `urutau probe` with its own image (`urutau-probe`, `FROM scratch`, under 15 MB, about 20 MB of memory, no open port). It follows the Traefik, sshd, fail2ban, port-probe and egress logs of its server and sends them to the hub.
- Ingestion over plain HTTPS (`/api/v1/probe/hello`, `push`, `commands`) with a disk spool, gzip, idempotent batches and offset-based deduplication, so a hub outage or a restart loses and duplicates nothing. When the spool is full the oldest batches are dropped and the loss is counted and shown.
- Probe management: `urutau probes create|list|revoke`, `GET/POST/PUT/DELETE /api/v1/probes` and the Sources page. The token (`urp_...`) is shown once and the hub stores only its SHA-256.
- Location and egress settings (workloads, resolvers, allowed destinations) configured per probe on the hub.
- `urutau import` brings a 1.x data directory into the hub as a probe (copy, SHA-256 and count verification, idempotent, `--dry-run`, `--verify`, `--count`), with no loss.
- Incidents qualified by host (`host/INC-n`); a bare `INC-n` means the primary probe.
- Two images from one Dockerfile (targets `hub` and `probe`), both multi-arch, built and published together; `deploy/probe/docker-compose.yml` and `deploy/host/install.sh --probe`.
### Changed
- The hub no longer reads local files: the server of the hub runs a probe like any other. The primary probe (the one named like `URUTAU_NAME`) keeps its data in the data-dir root, unchanged from 1.x.
- Second firewall: the hub queues ban and unban commands for each probe, which validates them (`wire.ValidCmdLine`) and appends them to `decisions.log` and `unban.log`; the fail2ban jail is unchanged.
- Sources shows the state of every probe and of each of its sources.
- The hub image no longer sets the log path variables.
- Docs, README and screenshots updated to 2.0.0.
### Removed
- **Breaking:** the peer federation: `URUTAU_PEERS`, `URUTAU_PEER_TOKEN*`, `URUTAU_PEER_ALLOW`, `URUTAU_PEER_BLOCKLIST` and every `/api/v1/peer/*` route (now 404). The hub refuses to start when one of these variables is set.
- **Breaking:** the log path variables of the hub (`URUTAU_TRAEFIK_LOG`, `URUTAU_AUTH_LOG`, `URUTAU_FAIL2BAN_LOG`, `URUTAU_PROBE_LOG`, `URUTAU_EGRESS_LOG`, `URUTAU_EGRESS_CONTAINERS`, `URUTAU_ENFORCE_LOG`, `URUTAU_ENFORCE_UNBAN_LOG`) now belong to the probe. The old image defaults only produce a warning. See [docs/migration-2.0.md](docs/migration-2.0.md).
## [1.6.0] - 2026-11-15
@@ -268,7 +291,8 @@ First release.
- Hostile log content is limited in length and escaped on output; the dashboard ships a strict Content-Security-Policy and the usual hardening headers.
- `--insecure-no-auth` is refused unless the bind address is loopback.
[Unreleased]: https://git.lucasrguerra.dev.br/ciberfauna/urutau/compare/v1.6.0...HEAD
[Unreleased]: https://git.lucasrguerra.dev.br/ciberfauna/urutau/compare/v2.0.0...HEAD
[2.0.0]: https://git.lucasrguerra.dev.br/ciberfauna/urutau/compare/v1.6.0...v2.0.0
[1.6.0]: https://git.lucasrguerra.dev.br/ciberfauna/urutau/compare/v1.5.7...v1.6.0
[1.5.8]: https://git.lucasrguerra.dev.br/ciberfauna/urutau/commit/bc3ce09
[1.5.7]: https://git.lucasrguerra.dev.br/ciberfauna/urutau/compare/v1.5.6...v1.5.7
+27 -3
View File
@@ -6,9 +6,32 @@ Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/);
## [Não lançado]
### Documentação
## [2.0.0] - 2026-11-15
- Documentação, README e capturas de tela atualizados para a 1.6.0.
Versão com quebra de compatibilidade: leia [docs/pt-BR/migracao-2.0.md](docs/pt-BR/migracao-2.0.md) antes de atualizar.
### Adicionado
- Sonda ultraleve: `urutau probe`, com imagem própria (`urutau-probe`, `FROM scratch`, menos de 15 MB, cerca de 20 MB de memória, sem porta aberta). Acompanha os logs de Traefik, sshd, fail2ban, sondagens de porta e egress do seu servidor e os envia ao hub.
- Recepção por HTTPS comum (`/api/v1/probe/hello`, `push`, `commands`) com spool em disco, gzip, lotes idempotentes e deduplicação por offset, então uma queda ou reinício do hub não perde nem duplica nada. Com o spool cheio, os lotes mais antigos são descartados e a perda é contada e mostrada.
- Gestão de sondas: `urutau probes create|list|revoke`, `GET/POST/PUT/DELETE /api/v1/probes` e a página Fontes. O token (`urp_...`) aparece uma vez e o hub guarda só o SHA-256 dele.
- Localização e configuração de egress (workloads, resolvers, destinos permitidos) por sonda, no hub.
- `urutau import` traz um diretório de dados da 1.x para o hub como uma sonda (cópia, verificação de SHA-256 e contagens, idempotente, `--dry-run`, `--verify`, `--count`), sem perda.
- Incidentes qualificados por host (`host/INC-n`); `INC-n` sozinho vale para a sonda primária.
- Duas imagens a partir de um só Dockerfile (targets `hub` e `probe`), ambas multi-arquitetura, construídas e publicadas juntas; `deploy/probe/docker-compose.yml` e `deploy/host/install.sh --probe`.
### Alterado
- O hub não lê mais arquivos locais: o servidor do hub roda uma sonda como qualquer outro. A sonda primária (a de nome igual a `URUTAU_NAME`) mantém seus dados na raiz do data-dir, sem mudança em relação à 1.x.
- Segundo firewall: o hub enfileira comandos de ban e desban para cada sonda, que os valida (`wire.ValidCmdLine`) e os acrescenta a `decisions.log` e `unban.log`; a jail do fail2ban não mudou.
- A página Fontes mostra o estado de cada sonda e de cada uma de suas fontes.
- A imagem do hub não define mais as variáveis de caminho de log.
- Documentação, README e capturas de tela atualizados para a 2.0.0.
### Removido
- **Incompatível:** a federação por peers: `URUTAU_PEERS`, `URUTAU_PEER_TOKEN*`, `URUTAU_PEER_ALLOW`, `URUTAU_PEER_BLOCKLIST` e todas as rotas `/api/v1/peer/*` (agora 404). O hub se recusa a subir quando uma dessas variáveis está definida.
- **Incompatível:** as variáveis de caminho de log do hub (`URUTAU_TRAEFIK_LOG`, `URUTAU_AUTH_LOG`, `URUTAU_FAIL2BAN_LOG`, `URUTAU_PROBE_LOG`, `URUTAU_EGRESS_LOG`, `URUTAU_EGRESS_CONTAINERS`, `URUTAU_ENFORCE_LOG`, `URUTAU_ENFORCE_UNBAN_LOG`) agora pertencem à sonda. Os padrões da imagem antiga só geram um aviso. Veja [docs/pt-BR/migracao-2.0.md](docs/pt-BR/migracao-2.0.md).
## [1.6.0] - 2026-11-15
@@ -268,7 +291,8 @@ Primeira versão.
- O conteúdo hostil dos logs tem tamanho limitado e é escapado na saída; o dashboard envia uma Content-Security-Policy estrita e os cabeçalhos de endurecimento usuais.
- `--insecure-no-auth` é recusado a menos que o endereço de bind seja loopback.
[Não lançado]: https://git.lucasrguerra.dev.br/ciberfauna/urutau/compare/v1.6.0...HEAD
[Não lançado]: https://git.lucasrguerra.dev.br/ciberfauna/urutau/compare/v2.0.0...HEAD
[2.0.0]: https://git.lucasrguerra.dev.br/ciberfauna/urutau/compare/v1.6.0...v2.0.0
[1.6.0]: https://git.lucasrguerra.dev.br/ciberfauna/urutau/compare/v1.5.7...v1.6.0
[1.5.8]: https://git.lucasrguerra.dev.br/ciberfauna/urutau/commit/bc3ce09
[1.5.7]: https://git.lucasrguerra.dev.br/ciberfauna/urutau/compare/v1.5.6...v1.5.7
+4 -4
View File
@@ -2,10 +2,10 @@
**English** · [Português](CONTRIBUTING.pt-BR.md)
Thanks for helping. Urutau is a lightweight threat intelligence panel for self-hosted servers: it reads logs, classifies hostile activity and scores IPs. The most useful contributions right now are tests, log fixtures, new detection rules and documentation.
Thanks for helping. Urutau is a lightweight threat intelligence panel for self-hosted servers: it reads logs, classifies hostile activity and scores IPs. It has two roles in one binary, the hub (`urutau serve`) and the probe (`urutau probe`). The most useful contributions right now are tests, log fixtures, new detection rules and documentation.
1. **Defensive use only.** Urutau reads logs on servers you own or administer. Do not add features that send traffic to the IPs it lists, scan third parties or hide what the tool does.
2. **Log content is hostile.** Every field that comes from a log (path, User-Agent, user name, host, jail) was written by an attacker. It must be length-limited when parsed, never executed or interpolated into a command, and escaped on output. A new parser comes with tests for malformed and oversized input.
2. **Log content is hostile, and so is what a probe sends.** Every field that comes from a log (path, User-Agent, user name, host, jail) was written by an attacker. It must be length-limited when parsed, never executed or interpolated into a command, and escaped on output. A new parser comes with tests for malformed and oversized input. The probe stays tiny: it must not import the store, geolocation or intelligence packages (its memory target is under 20 MB), and anything the hub asks it to write must pass `wire.ValidCmdLine`.
3. **A classification change pins its category.** New or changed detection rules need a test that shows the expected category and, for a weight change, the resulting score.
4. **Standard library first.** The binary is static and dependency-free on purpose. Adding a module needs a clear reason, and `go.sum` then enters the image inputs.
5. **100% English codebase.** Source code, comments, scripts, workflows and commit messages are in English. The dashboard is bilingual (English and Portuguese in `internal/server/web/i18n.js`).
@@ -17,7 +17,7 @@ scripts/install-hooks.sh
scripts/check.sh
```
`check.sh` validates `gofmt`, `go vet`, UI translation coverage, shell script syntax, workflow YAML files and `docker compose config` in seconds, skipping with a warning whatever the machine lacks. `scripts/check.sh --full` also runs `go test -race ./...` and `govulncheck`.
`check.sh` validates `gofmt`, `go vet`, UI translation coverage, shell script syntax, workflow YAML files and `docker compose config` (hub and probe) in seconds, skipping with a warning whatever the machine lacks. `scripts/check.sh --full` also runs `go test -race ./...` and `govulncheck`.
## Interface and translation
@@ -31,7 +31,7 @@ Always maintain document pairs: every `*.md` and `docs/*` file has an English ve
Commits follow Conventional Commits 1.0.0 in English (`feat:`, `fix:`, `chore:`, `ci:`, `docs:`, `refactor:`, `test:`, `perf:`, `build:`). Versions follow SemVer 2.0.0. Update the CHANGELOG in the same pull request as a user-visible change: add it under `[Unreleased]`, and at release time rename that section to the version and date and add the comparison link at the end of the file.
Releases are multi-arch container images (`linux/amd64` and `linux/arm64`) published to the Gitea registry. Pushing a `v*` tag triggers the release workflow, which reuses the image already built for the same inputs when there is one, and creates the Gitea release from the CHANGELOG section.
Releases are two multi-arch container images, the hub `urutau` and the probe `urutau-probe` (`linux/amd64` and `linux/arm64`, built from the same Dockerfile targets), published to the Gitea registry. Pushing a `v*` tag triggers the release workflow, which reuses the images already built for the same inputs when there are, and creates the Gitea release from the CHANGELOG section.
## License
+4 -4
View File
@@ -2,10 +2,10 @@
[English](CONTRIBUTING.md) · **Português**
Obrigado por ajudar. O Urutau é um painel leve de threat intelligence para servidores self-hosted: lê logs, classifica atividade hostil e pontua IPs. As contribuições mais úteis agora são testes, fixtures de logs, novas regras de detecção e documentação.
Obrigado por ajudar. O Urutau é um painel leve de threat intelligence para servidores self-hosted: lê logs, classifica atividade hostil e pontua IPs. Ele tem dois papéis em um só binário, o hub (`urutau serve`) e a sonda (`urutau probe`). As contribuições mais úteis agora são testes, fixtures de logs, novas regras de detecção e documentação.
1. **Apenas uso defensivo.** O Urutau lê logs de servidores que você possui ou administra. Não adicione recursos que enviem tráfego aos IPs listados, varram terceiros ou escondam o que a ferramenta faz.
2. **O conteúdo dos logs é hostil.** Todo campo vindo de um log (caminho, User-Agent, usuário, host, jail) foi escrito por um atacante. Ele deve ter tamanho limitado no parse, nunca ser executado ou interpolado em um comando, e ser escapado na saída. Um parser novo vem com testes para entrada malformada e gigante.
2. **O conteúdo dos logs é hostil, e o que uma sonda envia também.** Todo campo vindo de um log (caminho, User-Agent, usuário, host, jail) foi escrito por um atacante. Ele deve ter tamanho limitado no parse, nunca ser executado ou interpolado em um comando, e ser escapado na saída. Um parser novo vem com testes para entrada malformada e gigante. A sonda continua minúscula: não pode importar os pacotes de store, geolocalização nem intel (a meta de memória é abaixo de 20 MB), e tudo que o hub pedir a ela para gravar precisa passar por `wire.ValidCmdLine`.
3. **Mudança de classificação fixa sua categoria.** Regras de detecção novas ou alteradas precisam de um teste que mostre a categoria esperada e, numa mudança de peso, a pontuação resultante.
4. **Biblioteca padrão primeiro.** O binário é estático e sem dependências de propósito. Adicionar um módulo exige um motivo claro, e então o `go.sum` entra nas entradas da imagem.
5. **Base de código 100% em inglês.** Código-fonte, comentários, scripts, workflows e mensagens de commit são em inglês. O dashboard é bilíngue (inglês e português em `internal/server/web/i18n.js`).
@@ -17,7 +17,7 @@ scripts/install-hooks.sh
scripts/check.sh
```
O `check.sh` valida `gofmt`, `go vet`, cobertura de tradução da UI, sintaxe dos scripts, YAML dos workflows e `docker compose config` em segundos, pulando com aviso o que faltar na máquina. `scripts/check.sh --full` também roda `go test -race ./...` e `govulncheck`.
O `check.sh` valida `gofmt`, `go vet`, cobertura de tradução da UI, sintaxe dos scripts, YAML dos workflows e `docker compose config` (hub e sonda) em segundos, pulando com aviso o que faltar na máquina. `scripts/check.sh --full` também roda `go test -race ./...` e `govulncheck`.
## Interface e tradução
@@ -31,7 +31,7 @@ Mantenha sempre os pares de documentos: todo arquivo `*.md` e `docs/*` tem uma v
Commits seguem Conventional Commits 1.0.0 em inglês (`feat:`, `fix:`, `chore:`, `ci:`, `docs:`, `refactor:`, `test:`, `perf:`, `build:`). Versões seguem SemVer 2.0.0. Atualize o CHANGELOG no mesmo pull request de uma mudança visível ao usuário: registre em `[Não lançado]` e, na hora do release, renomeie essa seção para a versão e a data e acrescente o link de comparação no fim do arquivo.
Os releases são imagens de container multi-arquitetura (`linux/amd64` e `linux/arm64`) publicadas no registro do Gitea. Enviar uma tag `v*` dispara o workflow de release, que reaproveita a imagem já construída para as mesmas entradas, quando existe, e cria o release no Gitea a partir da seção do CHANGELOG.
Os releases são duas imagens de container multi-arquitetura, o hub `urutau` e a sonda `urutau-probe` (`linux/amd64` e `linux/arm64`, construídas dos targets do mesmo Dockerfile), publicadas no registro do Gitea. Enviar uma tag `v*` dispara o workflow de release, que reaproveita as imagens já construídas para as mesmas entradas, quando existem, e cria o release no Gitea a partir da seção do CHANGELOG.
## Licença
+41 -12
View File
@@ -1,6 +1,9 @@
# syntax=docker/dockerfile:1
#
# Urutau image: one static binary (no CGO, standard library only) on Alpine.
# Urutau 2: one static binary (no CGO, standard library only), two images.
# --target hub the hub: dashboard, API, probe ingestion (Alpine)
# --target probe the probe: `urutau probe` only (FROM scratch, a few MB)
# The default (last) stage is the hub, so a plain `docker build .` is the hub.
# Build stage.
FROM golang:1.26.11-alpine3.24 AS build
@@ -10,16 +13,45 @@ COPY cmd cmd
COPY internal internal
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/urutau ./cmd/urutau
# Runtime stage: CA certificates (peers over HTTPS, geo database download) and
# tzdata so TZ can match the host's fail2ban log. The HEALTHCHECK is the binary
# itself (`urutau healthcheck`): no curl in the image.
# Runs unprivileged (uid 10001). To read /var/log/auth.log (group adm) the
# compose file adds the host group with `group_add: ["4"]`.
FROM alpine:3.24
# Files the scratch image needs: CA certificates (HTTPS to the hub), zoneinfo
# (TZ must match the host's fail2ban log) and an owned empty /state.
FROM alpine:3.24 AS probe-files
RUN apk add --no-cache ca-certificates tzdata \
&& mkdir -p /rootfs/state \
&& chown 10001:10001 /rootfs/state
# Probe image: no shell, no package manager, no listening port. It reads the
# host logs (read-only mounts), sends them to the hub over HTTPS and appends the
# hub's ban decisions to a file. The HEALTHCHECK is the binary itself
# (`urutau probe --check` reads the liveness mark in the state volume).
# Runs unprivileged (uid 10001); the compose file adds the host group adm
# (`group_add: ["4"]`) to read /var/log.
FROM scratch AS probe
COPY --from=probe-files /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
COPY --from=probe-files /usr/share/zoneinfo /usr/share/zoneinfo
COPY --from=probe-files --chown=10001:10001 /rootfs/state /state
COPY --from=build /out/urutau /urutau
LABEL org.opencontainers.image.title="Urutau probe" \
org.opencontainers.image.description="Ultra-light Urutau probe: ships host logs to an Urutau hub" \
org.opencontainers.image.source="https://git.lucasrguerra.dev.br/ciberfauna/urutau" \
org.opencontainers.image.licenses="MIT OR Apache-2.0"
ENV URUTAU_STATE_DIR=/state \
SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt \
ZONEINFO=/usr/share/zoneinfo
USER 10001:10001
VOLUME /state
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
CMD ["/urutau", "probe", "--check"]
ENTRYPOINT ["/urutau", "probe"]
# Hub image: CA certificates (hub-to-hub downloads: geo database, Tor lists) and
# tzdata. The HEALTHCHECK is the binary itself (`urutau healthcheck`): no curl in
# the image. The hub reads no log file: the probes bring the lines.
FROM alpine:3.24 AS hub
RUN apk add --no-cache ca-certificates tzdata \
&& addgroup -S -g 10001 urutau \
&& adduser -S -u 10001 -G urutau -h /data -s /sbin/nologin urutau \
&& mkdir -p /data /logs \
&& mkdir -p /data \
&& chown urutau:urutau /data
COPY --from=build /out/urutau /usr/local/bin/urutau
LABEL org.opencontainers.image.title="Urutau" \
@@ -27,10 +59,7 @@ LABEL org.opencontainers.image.title="Urutau" \
org.opencontainers.image.source="https://git.lucasrguerra.dev.br/ciberfauna/urutau" \
org.opencontainers.image.licenses="MIT OR Apache-2.0"
ENV URUTAU_BIND=0.0.0.0:8790 \
URUTAU_DATA_DIR=/data \
URUTAU_TRAEFIK_LOG=/logs/traefik/access.log \
URUTAU_AUTH_LOG=/logs/host/auth.log \
URUTAU_FAIL2BAN_LOG=/logs/host/fail2ban.log
URUTAU_DATA_DIR=/data
USER urutau
WORKDIR /data
VOLUME /data
+49 -37
View File
@@ -2,7 +2,7 @@
<h1 align="center">Urutau</h1>
<p align="center">Lightweight, always-on threat intelligence and privacy-friendly web analytics for self-hosted servers.<br>Go, single static binary · local-first · authorized use.</p>
<p align="center"><a href="docs/cli.md">Terminal</a> · <a href="docs/interface.md">Interface</a> · <a href="docs/architecture.md">Architecture</a> · <a href="docs/configuration.md">Configuration</a> · <a href="docs/docker.md">Docker</a> · <a href="docs/support.md">Support</a> · <a href="ROADMAP.md">Roadmap</a> · <a href="CHANGELOG.md">Changelog</a></p>
<p align="center"><a href="docs/cli.md">Terminal</a> · <a href="docs/interface.md">Interface</a> · <a href="docs/architecture.md">Architecture</a> · <a href="docs/configuration.md">Configuration</a> · <a href="docs/docker.md">Docker</a> · <a href="docs/support.md">Support</a> · <a href="docs/migration-2.0.md">Migrating to 2.0</a> · <a href="ROADMAP.md">Roadmap</a> · <a href="CHANGELOG.md">Changelog</a></p>
<p align="center"><b>English</b> · <a href="README.pt-BR.md">Português</a></p>
@@ -22,14 +22,14 @@
<p align="center"><img src="docs/img/overview-mobile.png" height="420" alt="Urutau overview on a phone"> <img src="docs/img/defense-mobile.png" height="420" alt="Urutau defense page on a phone"><br><sub>The phone layout: a tab bar replaces the side rail and tables become cards.</sub></p>
**Status: stable, v1.6.0.** See [CHANGELOG.md](CHANGELOG.md) for exactly what shipped.
**Status: stable, v2.0.0.** See [CHANGELOG.md](CHANGELOG.md) for exactly what shipped.
Urutau is a small panel that runs on each of your servers (as a container), reads the logs the server already writes, and answers one question: who is attacking me right now? It classifies hostile activity, scores every source IP, keeps 30 days on disk, serves an embedded dashboard, a JSON API and an exportable blocklist, and can decide which attackers to block (a second firewall), watch what your own containers send out (outbound traffic analysis) and turn what it finds into tickets and an HTML report.
Urutau is a small hub plus one ultra-light probe per server. The probe (a container of a few MB, no open port) reads the logs the server already writes and sends them to the hub, which answers one question for the whole fleet: who is attacking me right now? It classifies hostile activity, scores every source IP, keeps 30 days on disk, serves an embedded dashboard, a JSON API and an exportable blocklist, and can decide which attackers to block (a second firewall), watch what your own containers send out (outbound traffic analysis) and turn what it finds into tickets and an HTML report.
- **Reads what already exists:** the Traefik access log (JSON, or the default text format with fewer fields), `/var/log/auth.log` (sshd) and `/var/log/fail2ban.log`. Two optional sources come from the host kit in `deploy/host`: the network probe log (new inbound connections to ports nobody listens on, each a `port-scan` event) and the outbound connection log. No agent on the network path, no packet capture, no telemetry.
- **Reads what already exists, through probes:** on each server the probe follows the Traefik access log (JSON, or the default text format with fewer fields), `/var/log/auth.log` (sshd) and `/var/log/fail2ban.log`. Two optional sources come from the host kit in `deploy/host`: the network probe log (new inbound connections to ports nobody listens on, each a `port-scan` event) and the outbound connection log. No agent on the network path, no packet capture, no telemetry.
- **Classifies:** `scanner`, `exploit`, `bruteforce`, `ssh-fail`, `ssh-probe`, `ban`, `port-scan`, plus the benign `ok`, `notfound` and `ssh-ok`. Browsing a public code forge (`/owner/repo/src/commit/<sha>/...`, `raw`, `blame`, `blob`, `tree` paths) is not an attack; real probes such as `/.env` or `/.git/config` still are.
- **Scores IPs:** every event adds weight to its source IP. A score of 10 or more is **suspicious**; **hostile** needs 50 or more **and** a strong signal (an attack tool, two or more attack categories, a ban, or a clear exploit attempt that was refused). Scanner and exploit probes that got a 2xx or 3xx answer weigh only 0.5. An IP with a successful SSH login is never hostile and never reaches the blocklist. Bans of the `urutau` jail (Urutau's own decisions) and of `recidive` do not count as evidence, so the system does not feed itself.
- **Second firewall (optional):** `URUTAU_ENFORCE=off|observe|on`. Urutau decides which attacking addresses to block and writes the decisions to a file; the host fail2ban (jail `urutau`) applies them, so Urutau needs no privileges. `observe` shows what would be blocked. See [Second firewall](#second-firewall).
- **Second firewall (optional):** `URUTAU_ENFORCE=off|observe|on`. The hub decides which attacking addresses to block and sends each decision to the probe of the host, which appends it to a file; the host fail2ban (jail `urutau`) applies them, so Urutau needs no privileges. `observe` shows what would be blocked. See [Second firewall](#second-firewall).
- **Outbound traffic analysis (optional):** new outbound connections of the host and containers are checked for beaconing, mining, IRC and SMTP ports, contact with attackers or Tor relays, DNS outside the allowed resolvers, unauthorised scans and new countries. See [Outbound traffic and incidents](#outbound-traffic-and-incidents).
- **Incident management:** every outbound finding becomes a ticket (`INC-<n>`) with status, severity, assignee, tags, verdict, comments and history.
- **HTML report:** a printable A4 report (`/api/v1/report?format=html`): cover, executive summary in plain language, rule-based recommendations, threats, geography, errors and health, visitors, defense, second firewall and outbound traffic. The Reports page previews, downloads or prints it.
@@ -40,35 +40,32 @@ Urutau is a small panel that runs on each of your servers (as a container), read
- **Lightweight:** Go standard library only, one static binary, a soft memory limit of 256 MiB, state in a single snapshot file. No database.
- **Live dashboard:** embedded vanilla UI (English and Portuguese, light and dark, with a phone layout), updated through Server-Sent Events, with 23 pages in five groups (see [Interface](#interface)).
- **Blocklist:** hostile, globally routable IPs as plain text or JSON, ready for fail2ban, ipset, nginx or a firewall. IPv6 is aggregated by /64 and exported as `x:x:x:x::/64`.
- **Federation:** one instance (the hub) aggregates others with `--peer name=url`, pulling `/api/v1/peer/export` and relaying their live events through `/api/v1/peer/stream`. Outbound reports and, when `URUTAU_ENFORCE_SHARE` is on, second firewall decisions and unbans travel the same way, each side applying its own exclusions.
- **Probes and hub:** one hub holds the data and the dashboard; each server runs `urutau probe` (image `urutau-probe`, under 15 MB, about 20 MB of memory), which dials out over HTTPS, spools to disk if the hub is away and loses nothing. The token of each probe is stored on the hub only as a hash, and the Sources page creates, edits and revokes probes. Coming from 1.x: [docs/migration-2.0.md](docs/migration-2.0.md).
## How it works
```
on each server: urutau probe (no open port)
Traefik access.log auth.log (sshd) fail2ban.log probe.log* egress.log*
│ │ │ │ │
└────────┬─────────┴─────────────────┴─────────────┘ │
▼ │
tail + parse (rotation aware, bounded lines) │
▼ ▼
classify ──► score per IP ──► state in memory ──► snapshot outbound analysis
│ │ (/data) │
▼ │ ▼
second firewall* │ incident tickets
(decisions.log ──► host │ (incidents.json)
fail2ban, jail urutau) │
└────────────────────┬───────────────────────────────────────┘
▼
tail (rotation aware) ──► batches ──► disk spool ──► HTTPS push ─┐
▲ │
decisions.log ◄── validated ban/unban lines ◄── long-poll ◄─────┐ │
│ │ │
host fail2ban (jail urutau) │ │
│ ▼
on the hub: urutau serve │ one node per probe
parse + classify ──► score per IP ──► state in memory ──► snapshot (/data)
│ │ │
▼ │ ▼
second firewall* ─────────────────────┘ outbound analysis ──► incident tickets
┌────────────────────────┼─────────────────────┐
▼ ▼ ▼
dashboard (SSE) /api/v1/* JSON blocklist.txt / .json
HTML report
(all servers) HTML report
* optional, fed by the host kit in deploy/host
hub ── GET /api/v1/peer/export (peer token) ──► peer A
│ ── GET /api/v1/peer/stream (live events) ──► peer A
│ ── GET /api/v1/peer/export (peer token) ──► peer B
│ ── GET /api/v1/peer/stream (live events) ──► peer B
└──► one dashboard for the whole fleet
```
## Investigation
@@ -77,7 +74,7 @@ Beyond live numbers, Urutau remembers and explains. It keeps 30 days of state an
## Second firewall
Optional (`URUTAU_ENFORCE`, default `off`; `observe` decides in memory only, `on` also writes the decisions to `--enforce-log`). The host kit in `deploy/host` (`install.sh --enforce`) installs the fail2ban filter, action and jail `urutau`, which apply the decisions; the ban only drops connections the address starts, so replies to the server's own connections keep flowing. A decision has a reason, among them:
Optional (`URUTAU_ENFORCE`, default `off`; `observe` decides in memory only, `on` also sends the decisions to the probes, which write them to their `URUTAU_ENFORCE_LOG`). The host kit in `deploy/host` (`install.sh --probe --enforce`) installs the fail2ban filter, action and jail `urutau`, which apply the decisions; the ban only drops connections the address starts, so replies to the server's own connections keep flowing. A decision has a reason, among them:
- a burst of attack events in 10 minutes (`--enforce-threshold`, default 5);
- `known-attacker`: an address already hostile (or suspicious with score 100 or more) is banned on its first new malicious event;
@@ -86,11 +83,11 @@ Optional (`URUTAU_ENFORCE`, default `off`; `observe` decides in memory only, `on
- `neighbor-campaign`: 3 or more distinct addresses of a /24 (IPv4) or /64 (IPv6) banned in the last 24 h make one attack event of another address of the prefix enough;
- a sweep every 10 minutes bans addresses active in the last 24 h that nothing blocks yet, at most `--enforce-max-per-min` (default 60) decisions per minute.
It never blocks trusted addresses, private ranges, CDN (Cloudflare) and public resolver ranges, peers, the server itself, legitimate visitors, crawlers verified by forward-confirmed reverse DNS (Googlebot, Bingbot, Applebot) or addresses you released. The Defense page shows mode, recent decisions, coverage and releases; the **Unban** button (IPs, IP analysis and Defense) asks the host, through `unban.log` next to `--enforce-log`, to lift the block and can keep the address from being banned again for 1 h, 24 h or 7 days. With `URUTAU_ENFORCE_SHARE=on` a hub and its peers exchange decisions, applied only when the receiving server also saw the address attack. Coverage counts an attacker as protected when it is listed or banned by any jail.
It never blocks trusted addresses, private ranges, CDN (Cloudflare) and public resolver ranges, probes, the server itself, legitimate visitors, crawlers verified by forward-confirmed reverse DNS (Googlebot, Bingbot, Applebot) or addresses you released. The Defense page shows mode, recent decisions, coverage and releases; the **Unban** button (IPs, IP analysis and Defense) asks the host, through `unban.log` next to `--enforce-log`, to lift the block and can keep the address from being banned again for 1 h, 24 h or 7 days. With `URUTAU_ENFORCE_SHARE=on` a hub and its peers exchange decisions, applied only when the receiving server also saw the address attack. Coverage counts an attacker as protected when it is listed or banned by any jail.
## Outbound traffic and incidents
Optional (`URUTAU_EGRESS=auto|on|off`; `auto` turns it on when the outbound log exists). The host kit logs only new TCP connection attempts through nftables, and a container map names the workloads. Urutau checks them for beaconing (regular conversations with one destination), mining, IRC and SMTP ports, contact with addresses that attacked the server or with Tor relays, DNS outside the allowed resolvers (`URUTAU_EGRESS_RESOLVERS`), unauthorised outbound scans and new countries. Workloads are defined by network or container name (`URUTAU_EGRESS_WORKLOADS`); a `scanner` workload (an authorised surface scanner) has only its scan-shaped traffic summarised, everything else is judged like any other workload. The servers themselves, peers and the host's own provider never raise findings, cloud metadata services polled by the host are `infra`, and regular connections to large CDNs and clouds are low severity.
Optional (`URUTAU_EGRESS=auto|on|off`; `auto` turns it on for a probe that sends the outbound log). The host kit logs only new TCP connection attempts through nftables, and a container map names the workloads. Urutau checks them for beaconing (regular conversations with one destination), mining, IRC and SMTP ports, contact with addresses that attacked the server or with Tor relays, DNS outside the allowed resolvers (`URUTAU_EGRESS_RESOLVERS`), unauthorised outbound scans and new countries. Workloads are defined by network or container name (`URUTAU_EGRESS_WORKLOADS`); a `scanner` workload (an authorised surface scanner) has only its scan-shaped traffic summarised, everything else is judged like any other workload. The servers themselves, peers and the host's own provider never raise findings, cloud metadata services polled by the host are `infra`, and regular connections to large CDNs and clouds are low severity.
Every finding above info severity becomes a ticket `INC-<n>` (list, ticket page, manual tickets, CSV export, `/api/v1/incidents`). A ticket marked `false_positive` or `benign` can suppress findings with exactly its key; a resolved ticket reopens if the finding comes back.
@@ -98,26 +95,35 @@ Every finding above info severity becomes a ticket `INC-<n>` (list, ticket page,
Pages are grouped in a side rail (a tab bar on phones), with the view kept in the URL hash. A "?" button next to metrics and categories explains what they mean and what to do.
- **Monitor:** Overview (headline numbers, timeline, top IPs; a period selector applies everywhere), Live (attacks as animated arcs on a flat map or a 3D globe, including your peers; `--location` sets where this server sits on the map), Services (SLO, error budget, burn rate and Apdex per service).
- **Monitor:** Overview (headline numbers, timeline, top IPs; a period selector applies everywhere), Live (attacks as animated arcs on a flat map or a 3D globe, from every probe; each probe's location is set on the Sources page), Services (SLO, error budget, burn rate and Apdex per service).
- **Investigate:** IPs (the scored table and the IP analysis page, `#/ip/<ip>`), Sessions, Campaigns, Replay (a period played back on the map), Event search, Incidents (tickets for outbound findings) and Outbound traffic.
- **Analyze:** Threats, MITRE ATT&CK, Geography (country, state, city, `#/geo/BR/Pernambuco/Recife`), Evolution, Concentration, Survival (time to ban), Traffic (privacy-friendly analytics for legitimate visitors), Where errors come from (app, proxy, blocked, attack, bot, client, unknown) and Protocols and TLS.
- **Operate:** Defense (ban and blocklist coverage, second firewall, Unban), Sources and hosts (log sources, peers and the blocklist) and Integrity (health of sources, registry and snapshot).
- **Operate:** Defense (ban and blocklist coverage, second firewall, Unban), Sources and hosts (probes, their log sources and the blocklist) and Integrity (health of sources, registry and snapshot).
- **Reports:** the HTML report of a period.
On phones, plain data tables become stacked cards, so nothing scrolls sideways. See [docs/interface.md](docs/interface.md) for every page with screenshots and the HTTP routes.
## Install
Run it with Docker Compose (recommended):
Two images from one Dockerfile: the **hub** (`urutau`) once, and the **probe** (`urutau-probe`) on every server you want to watch. With Docker Compose (recommended), first the hub:
```bash
cp .env.example .env
# set URUTAU_TOKEN (32+ characters, 128+ bits of entropy; `openssl rand -base64 48` works):
sed -i "s|^URUTAU_TOKEN=.*|URUTAU_TOKEN=$(openssl rand -base64 48 | tr -d '\n')|" .env
docker compose pull && docker compose up -d
docker compose exec urutau urutau probes create web1 # prints the probe token ONCE
```
The dashboard answers at `http://127.0.0.1:8790` and asks for the token. The image is public: `docker pull git.lucasrguerra.dev.br/ciberfauna/urutau:latest`. Or build it locally with `docker compose up -d --build`.
Then on each monitored server (after `sudo sh deploy/host/install.sh --probe`, see [docs/docker.md](docs/docker.md)):
```bash
cd deploy/probe && cp .env.example .env
# set URUTAU_HUB=https://urutau.example.com URUTAU_PROBE_NAME=web1 URUTAU_PROBE_TOKEN=urp_...
docker compose up -d
```
The dashboard answers at `http://127.0.0.1:8790` and asks for the token; the Sources page shows the probe connected. The images are public: `docker pull git.lucasrguerra.dev.br/ciberfauna/urutau:latest` and `.../urutau-probe:latest`. Or build locally with `docker compose up -d --build`.
To compile from source (Go 1.26.11 or newer, no dependency to fetch):
@@ -131,14 +137,18 @@ Supported platform matrix for container images: `linux/amd64` and `linux/arm64`.
## Getting started
```bash
# Check the sources and the data directory
# Check the data directory and the probes
urutau doctor
# Run the daemon and the dashboard
# Run the hub (dashboard, API, probe ingestion)
urutau serve --bind 127.0.0.1:8790
# Aggregate other instances
urutau serve --peer web1=https://urutau.web1.example --peer-token "$URUTAU_PEER_TOKEN"
# Register a probe and run it on the server to watch
urutau probes create web1
URUTAU_HUB=https://urutau.example.com URUTAU_PROBE_NAME=web1 URUTAU_PROBE_TOKEN=urp_... urutau probe
# Bring a 1.x data directory in, losing nothing
urutau import --from /backup/data --host old-server
```
See [docs/cli.md](docs/cli.md) for the command reference and [docs/configuration.md](docs/configuration.md) for every `URUTAU_*` variable.
@@ -205,7 +215,7 @@ The list only holds globally routable addresses, never anything in `--ignore` or
## Security
Urutau handles hostile text by design. Every field it reads from a log (paths, User-Agents, user names, hosts) was written by an attacker: it is length-limited, never executed and always escaped before it reaches the page. The dashboard and the API require a token (`URUTAU_TOKEN`, at least 32 characters, e.g. `openssl rand -base64 48`), the session cookie is `HttpOnly` and `SameSite=Strict`, failed logins are rate limited per IP, and the peer token only opens `GET /api/v1/peer/export`. Put it behind a reverse proxy with TLS before exposing it. See [SECURITY.md](SECURITY.md).
Urutau handles hostile text by design. Every field it reads from a log (paths, User-Agents, user names, hosts) was written by an attacker: it is length-limited, never executed and always escaped before it reaches the page. The dashboard and the API require a token (`URUTAU_TOKEN`, at least 32 characters, e.g. `openssl rand -base64 48`), the session cookie is `HttpOnly` and `SameSite=Strict`, failed logins are rate limited per IP, each probe token (stored only as a hash on the hub) opens only the three probe routes, and the probe itself opens no port and writes only lines that pass a strict format check. Put it behind a reverse proxy with TLS before exposing it. See [SECURITY.md](SECURITY.md).
## Authorized use
@@ -223,7 +233,8 @@ See **[CONTRIBUTING.md](CONTRIBUTING.md)** and **[docs/architecture.md](docs/arc
## Known limits
- Sources: Traefik access log (JSON or default text format), sshd lines from `auth.log` (ISO timestamps), `fail2ban.log`, and the optional probe and outbound connection logs written by the host kit.
- Sources (read by the probes): Traefik access log (JSON or default text format), sshd lines from `auth.log` (ISO timestamps), `fail2ban.log`, and the optional port-probe and outbound connection logs written by the host kit.
- The probe needs the hub reachable over HTTPS (plain HTTP only for private addresses); it spools up to `URUTAU_PROBE_SPOOL_MAX` (64 MiB) while the hub is away and drops the oldest batches beyond that, counting them.
- State is kept for 30 days at most (`--retention`), with up to 20,000 tracked IPs; the event registry is capped by `--events-max`; incidents hold up to 5000 tickets.
- The dashboard login is a single shared token; there are no user accounts, and a ticket author is a free-text name.
- Scores and second firewall decisions are heuristics, not proof of malicious intent. Start with `observe`.
@@ -238,6 +249,7 @@ Summary of the [ROADMAP](ROADMAP.md):
| **Done (1.0.0)** | Log collection, classification and scoring, offline geolocation, User-Agent parsing, privacy-friendly web analytics, snapshot persistence, dashboard with SSE, token login, blocklist, federation, Docker image and CI/CD |
| **Done (1.2.0)** | 30-day retention, any period, on-disk event registry, replay, IP analysis with verdict, MITRE ATT&CK, campaigns, STIX 2.1 and stable metrics |
| **Done (1.4.0 to 1.6.0)** | Second firewall with Unban and decision sharing, outbound traffic analysis, incident management, HTML report, Tor lists, network probes, text-format Traefik logs, verified crawlers and forge browsing recognized, phone layout |
| **Done (2.0.0)** | Hub and ultra-light probes (own image), HTTPS ingestion with disk spool, per-probe tokens, enforce decisions through the probes, `urutau import` for 1.x data |
| **Next** | More log sources, webhook alerts, Prometheus metrics |
| **Later** | IP reputation enrichment |
| **Not planned** | Active scanning or counterattack, mandatory cloud services, telemetry |
+50 -38
View File
@@ -2,7 +2,7 @@
<h1 align="center">Urutau</h1>
<p align="center">Threat intelligence leve e sempre ligado e web analytics amigável à privacidade para servidores self-hosted.<br>Go, binário estático único · local-first · uso autorizado.</p>
<p align="center"><a href="docs/pt-BR/cli.md">Terminal</a> · <a href="docs/pt-BR/interface.md">Interface</a> · <a href="docs/pt-BR/arquitetura.md">Arquitetura</a> · <a href="docs/pt-BR/configuracao.md">Configuração</a> · <a href="docs/pt-BR/docker.md">Docker</a> · <a href="docs/pt-BR/suporte.md">Suporte</a> · <a href="ROADMAP.pt-BR.md">Roadmap</a> · <a href="CHANGELOG.pt-BR.md">Changelog</a></p>
<p align="center"><a href="docs/pt-BR/cli.md">Terminal</a> · <a href="docs/pt-BR/interface.md">Interface</a> · <a href="docs/pt-BR/arquitetura.md">Arquitetura</a> · <a href="docs/pt-BR/configuracao.md">Configuração</a> · <a href="docs/pt-BR/docker.md">Docker</a> · <a href="docs/pt-BR/suporte.md">Suporte</a> · <a href="docs/pt-BR/migracao-2.0.md">Migrar para a 2.0</a> · <a href="ROADMAP.pt-BR.md">Roadmap</a> · <a href="CHANGELOG.pt-BR.md">Changelog</a></p>
<p align="center"><a href="README.md">English</a> · <b>Português</b></p>
@@ -22,14 +22,14 @@
<p align="center"><img src="docs/img/overview-mobile.png" height="420" alt="Visão geral do Urutau no celular"> <img src="docs/img/defense-mobile.png" height="420" alt="Página Defesa do Urutau no celular"><br><sub>O layout de celular: uma barra de abas substitui a lateral e as tabelas viram cartões.</sub></p>
**Status: estável, v1.6.0.** Veja o [CHANGELOG.pt-BR.md](CHANGELOG.pt-BR.md) para saber exatamente o que foi entregue.
**Status: estável, v2.0.0.** Veja o [CHANGELOG.pt-BR.md](CHANGELOG.pt-BR.md) para saber exatamente o que foi entregue.
O Urutau é um painel pequeno que roda em cada um dos seus servidores (como container), lê os logs que o servidor já escreve e responde a uma pergunta: quem está me atacando agora? Ele classifica a atividade hostil, pontua cada IP de origem, guarda 30 dias em disco, serve um dashboard embutido, uma API JSON e uma blocklist exportável, e ainda pode decidir quais atacantes bloquear (um segundo firewall), vigiar o que seus próprios contêineres enviam para fora (análise de tráfego de saída) e transformar o que encontra em chamados e num relatório HTML.
O Urutau é um hub mais uma sonda ultraleve por servidor. A sonda (um container de poucos MB, sem porta aberta) lê os logs que o servidor já escreve e os envia ao hub, que responde a uma pergunta para toda a frota: quem está me atacando agora? Ele classifica a atividade hostil, pontua cada IP de origem, guarda 30 dias em disco, serve um dashboard embutido, uma API JSON e uma blocklist exportável, e ainda pode decidir quais atacantes bloquear (um segundo firewall), vigiar o que seus próprios contêineres enviam para fora (análise de tráfego de saída) e transformar o que encontra em chamados e num relatório HTML.
- **Lê o que já existe:** o access log do Traefik (JSON, ou o formato texto padrão, com menos campos), `/var/log/auth.log` (sshd) e `/var/log/fail2ban.log`. Duas fontes opcionais vêm do kit de host em `deploy/host`: o log de sondagens de rede (novas conexões de entrada a portas em que ninguém escuta, cada uma um evento `port-scan`) e o log de conexões de saída. Sem agente no caminho da rede, sem captura de pacotes, sem telemetria.
- **Lê o que já existe, por meio das sondas:** em cada servidor a sonda acompanha o access log do Traefik (JSON, ou o formato texto padrão, com menos campos), `/var/log/auth.log` (sshd) e `/var/log/fail2ban.log`. Duas fontes opcionais vêm do kit de host em `deploy/host`: o log de sondagens de rede (novas conexões de entrada a portas em que ninguém escuta, cada uma um evento `port-scan`) e o log de conexões de saída. Sem agente no caminho da rede, sem captura de pacotes, sem telemetria.
- **Classifica:** `scanner`, `exploit`, `bruteforce`, `ssh-fail`, `ssh-probe`, `ban`, `port-scan`, além dos benignos `ok`, `notfound` e `ssh-ok`. Navegar num forge de código público (caminhos `/owner/repo/src/commit/<sha>/...`, `raw`, `blame`, `blob`, `tree`) não é ataque; sondas reais como `/.env` ou `/.git/config` continuam sendo.
- **Pontua IPs:** cada evento soma peso ao IP de origem. Pontuação 10 ou mais é **suspeito**; **hostil** exige 50 ou mais **e** um sinal forte (uma ferramenta de ataque, duas ou mais categorias de ataque, um ban ou uma tentativa clara de exploit recusada). Sondas de scanner e exploit que receberam resposta 2xx ou 3xx pesam só 0,5. Um IP com login SSH bem-sucedido nunca é hostil e nunca vai para a blocklist. Bans da jail `urutau` (decisões do próprio Urutau) e da `recidive` não contam como evidência, para o sistema não se alimentar de si mesmo.
- **Segundo firewall (opcional):** `URUTAU_ENFORCE=off|observe|on`. O Urutau decide quais endereços atacantes bloquear e grava as decisões num arquivo; o fail2ban do host (jail `urutau`) as aplica, então o Urutau não precisa de privilégios. `observe` mostra o que seria bloqueado. Veja [Segundo firewall](#segundo-firewall).
- **Segundo firewall (opcional):** `URUTAU_ENFORCE=off|observe|on`. O hub decide quais endereços atacantes bloquear e envia cada decisão à sonda do host, que a grava num arquivo; o fail2ban do host (jail `urutau`) as aplica, então o Urutau não precisa de privilégios. `observe` mostra o que seria bloqueado. Veja [Segundo firewall](#segundo-firewall).
- **Análise de tráfego de saída (opcional):** as novas conexões de saída do host e dos contêineres são checadas quanto a beaconing, mineração, portas de IRC e SMTP, contato com atacantes ou relays Tor, DNS fora dos resolvers permitidos, varreduras não autorizadas e países novos. Veja [Tráfego de saída e incidentes](#tráfego-de-saída-e-incidentes).
- **Gestão de incidentes:** cada achado de saída vira um chamado (`INC-<n>`) com status, severidade, responsável, tags, conclusão, comentários e histórico.
- **Relatório HTML:** um relatório A4 imprimível (`/api/v1/report?format=html`): capa, resumo executivo em linguagem simples, recomendações por regras, ameaças, geografia, erros e saúde, visitantes, defesa, segundo firewall e tráfego de saída. A página Relatórios mostra uma prévia, baixa ou imprime.
@@ -40,35 +40,32 @@ O Urutau é um painel pequeno que roda em cada um dos seus servidores (como cont
- **Leve:** só biblioteca padrão do Go, um binário estático, limite suave de memória de 256 MiB, estado em um único arquivo de snapshot. Sem banco de dados.
- **Dashboard ao vivo:** UI vanilla embutida (inglês e português, claro e escuro, com layout para celular), atualizada por Server-Sent Events, com 23 páginas em cinco grupos (veja [Interface](#interface)).
- **Blocklist:** IPs hostis e globalmente roteáveis em texto ou JSON, prontos para fail2ban, ipset, nginx ou firewall. O IPv6 é agregado por /64 e exportado como `x:x:x:x::/64`.
- **Federação:** uma instância (o hub) agrega outras com `--peer nome=url`, puxando `/api/v1/peer/export` e repassando os eventos ao vivo deles por `/api/v1/peer/stream`. Relatórios de saída e, com `URUTAU_ENFORCE_SHARE` ligado, decisões do segundo firewall e desbans viajam pelo mesmo caminho, cada lado aplicando as próprias exclusões.
- **Sondas e hub:** um hub guarda os dados e o dashboard; cada servidor roda `urutau probe` (imagem `urutau-probe`, abaixo de 15 MB, cerca de 20 MB de memória), que conecta de dentro para fora por HTTPS, guarda em disco se o hub sumir e não perde nada. O token de cada sonda fica no hub só como hash, e a página Fontes cria, edita e revoga sondas. Vindo da 1.x: [docs/pt-BR/migracao-2.0.md](docs/pt-BR/migracao-2.0.md).
## Como funciona
```
em cada servidor: urutau probe (sem porta aberta)
access.log Traefik auth.log (sshd) fail2ban.log probe.log* egress.log*
│ │ │ │ │
└────────┬─────────┴─────────────────┴─────────────┘ │
▼ │
tail + parse (tolera rotação, linhas limitadas) │
▼ ▼
classifica ──► pontua por IP ──► estado em memória ──► snapshot análise de saída
│ │ (/data) │
▼ │ ▼
segundo firewall* │ chamados (incidentes)
(decisions.log ──► fail2ban │ (incidents.json)
do host, jail urutau) │
└────────────────────┬───────────────────────────────────────┘
▼
tail (ciente de rotação) ──► lotes ──► spool em disco ──► push HTTPS ─┐
▲ │
decisions.log ◄── linhas de ban/unban validadas ◄── long-poll ◄────┐ │
│ │ │
fail2ban do host (jail urutau) │ │
│ ▼
no hub: urutau serve │ um nó por sonda
parse + classificação ──► score por IP ──► estado em memória ──► snapshot (/data)
│ │ │
▼ │ ▼
segundo firewall* ──────────────────────┘ análise de saída ──► tickets de incidente
┌────────────────────────┼─────────────────────┐
▼ ▼ ▼
dashboard (SSE) /api/v1/* JSON blocklist.txt / .json
relatório HTML
dashboard (SSE) JSON /api/v1/* blocklist.txt / .json
(todos os servidores) relatório HTML
* opcional, alimentado pelo kit de host em deploy/host
hub ── GET /api/v1/peer/export (token de peer) ──► peer A
│ ── GET /api/v1/peer/stream (eventos ao vivo) ──► peer A
│ ── GET /api/v1/peer/export (token de peer) ──► peer B
│ ── GET /api/v1/peer/stream (eventos ao vivo) ──► peer B
└──► um dashboard para a frota inteira
```
## Investigação
@@ -77,7 +74,7 @@ Além dos números ao vivo, o Urutau lembra e explica. Ele guarda 30 dias de est
## Segundo firewall
Opcional (`URUTAU_ENFORCE`, padrão `off`; `observe` decide só em memória, `on` também grava as decisões em `--enforce-log`). O kit de host em `deploy/host` (`install.sh --enforce`) instala o filtro, a ação e a jail `urutau` do fail2ban, que aplicam as decisões; o ban só derruba conexões que o endereço inicia, então as respostas às conexões do próprio servidor continuam fluindo. Cada decisão tem um motivo, entre eles:
Opcional (`URUTAU_ENFORCE`, padrão `off`; `observe` decide só em memória, `on` também envia as decisões às sondas, que as gravam no `URUTAU_ENFORCE_LOG` delas). O kit de host em `deploy/host` (`install.sh --probe --enforce`) instala o filtro, a ação e a jail `urutau` do fail2ban, que aplicam as decisões; o ban só derruba conexões que o endereço inicia, então as respostas às conexões do próprio servidor continuam fluindo. Cada decisão tem um motivo, entre eles:
- uma rajada de eventos de ataque em 10 minutos (`--enforce-threshold`, padrão 5);
- `known-attacker`: um endereço já hostil (ou suspeito com pontuação 100 ou mais) é banido no primeiro novo evento malicioso;
@@ -86,11 +83,11 @@ Opcional (`URUTAU_ENFORCE`, padrão `off`; `observe` decide só em memória, `on
- `neighbor-campaign`: 3 ou mais endereços distintos de um /24 (IPv4) ou /64 (IPv6) banidos nas últimas 24 h fazem um evento de ataque de outro endereço do prefixo bastar;
- uma varredura a cada 10 minutos bane endereços ativos nas últimas 24 h que nada bloqueia ainda, no máximo `--enforce-max-per-min` (padrão 60) decisões por minuto.
Nunca bloqueia endereços confiáveis, faixas privadas, faixas de CDN (Cloudflare) e de resolvers públicos, peers, o próprio servidor, visitantes legítimos, crawlers verificados por DNS reverso confirmado (Googlebot, Bingbot, Applebot) nem endereços que você liberou. A página Defesa mostra modo, decisões recentes, cobertura e liberações; o botão **Desbanir** (IPs, análise de IP e Defesa) pede ao host, por `unban.log` ao lado de `--enforce-log`, que levante o bloqueio e pode impedir novo ban do endereço por 1 h, 24 h ou 7 dias. Com `URUTAU_ENFORCE_SHARE=on` um hub e seus peers trocam decisões, aplicadas só quando o servidor receptor também viu o endereço atacar. A cobertura conta um atacante como protegido quando ele está listado ou banido por qualquer jail.
Nunca bloqueia endereços confiáveis, faixas privadas, faixas de CDN (Cloudflare) e de resolvers públicos, sondas, o próprio servidor, visitantes legítimos, crawlers verificados por DNS reverso confirmado (Googlebot, Bingbot, Applebot) nem endereços que você liberou. A página Defesa mostra modo, decisões recentes, cobertura e liberações; o botão **Desbanir** (IPs, análise de IP e Defesa) pede ao host, por `unban.log` ao lado de `--enforce-log`, que levante o bloqueio e pode impedir novo ban do endereço por 1 h, 24 h ou 7 dias. Com `URUTAU_ENFORCE_SHARE=on` um hub e seus peers trocam decisões, aplicadas só quando o servidor receptor também viu o endereço atacar. A cobertura conta um atacante como protegido quando ele está listado ou banido por qualquer jail.
## Tráfego de saída e incidentes
Opcional (`URUTAU_EGRESS=auto|on|off`; `auto` liga quando o log de saída existe). O kit de host registra, pelo nftables, só tentativas novas de conexão TCP, e um mapa de contêineres nomeia os workloads. O Urutau checa beaconing (conversas regulares com um destino), mineração, portas de IRC e SMTP, contato com endereços que atacaram o servidor ou com relays Tor, DNS fora dos resolvers permitidos (`URUTAU_EGRESS_RESOLVERS`), varreduras de saída não autorizadas e países novos. Os workloads são definidos por nome de rede ou de contêiner (`URUTAU_EGRESS_WORKLOADS`); um workload `scanner` (um scanner de superfície autorizado) tem só o tráfego em forma de varredura resumido, o resto é julgado como qualquer outro workload. Os próprios servidores, peers e o provedor do host nunca geram achados, serviços de metadados de nuvem consultados pelo host são `infra`, e conexões regulares a grandes CDNs e nuvens têm severidade baixa.
Opcional (`URUTAU_EGRESS=auto|on|off`; `auto` liga para a sonda que envia o log de saída). O kit de host registra, pelo nftables, só tentativas novas de conexão TCP, e um mapa de contêineres nomeia os workloads. O Urutau checa beaconing (conversas regulares com um destino), mineração, portas de IRC e SMTP, contato com endereços que atacaram o servidor ou com relays Tor, DNS fora dos resolvers permitidos (`URUTAU_EGRESS_RESOLVERS`), varreduras de saída não autorizadas e países novos. Os workloads são definidos por nome de rede ou de contêiner (`URUTAU_EGRESS_WORKLOADS`); um workload `scanner` (um scanner de superfície autorizado) tem só o tráfego em forma de varredura resumido, o resto é julgado como qualquer outro workload. Os próprios servidores, peers e o provedor do host nunca geram achados, serviços de metadados de nuvem consultados pelo host são `infra`, e conexões regulares a grandes CDNs e nuvens têm severidade baixa.
Todo achado acima de info vira um chamado `INC-<n>` (lista, página do chamado, chamados manuais, exportação CSV, `/api/v1/incidents`). Um chamado marcado `false_positive` ou `benign` pode suprimir achados com exatamente a sua chave; um chamado resolvido reabre se o achado voltar.
@@ -98,26 +95,35 @@ Todo achado acima de info vira um chamado `INC-<n>` (lista, página do chamado,
As páginas são agrupadas numa barra lateral (barra de abas no celular), com a visão guardada no hash da URL. Um botão "?" ao lado de métricas e categorias explica o que significam e o que fazer.
- **Monitorar:** Visão geral (números principais, linha do tempo, principais IPs; um seletor de período vale em todo lugar), Ao vivo (ataques como arcos animados em mapa plano ou globo 3D, incluindo seus peers; `--location` define onde este servidor fica no mapa), Serviços (SLO, orçamento de erro, burn rate e Apdex por serviço).
- **Monitorar:** Visão geral (números principais, linha do tempo, principais IPs; um seletor de período vale em todo lugar), Ao vivo (ataques como arcos animados em mapa plano ou globo 3D, de todas as sondas; a localização de cada sonda é definida na página Fontes), Serviços (SLO, orçamento de erro, burn rate e Apdex por serviço).
- **Investigar:** IPs (a tabela pontuada e a página de análise de IP, `#/ip/<ip>`), Sessões, Campanhas, Replay (um período reproduzido no mapa), Busca de eventos, Incidentes (chamados dos achados de saída) e Tráfego de saída.
- **Analisar:** Ameaças, MITRE ATT&CK, Geografia (país, estado, cidade, `#/geo/BR/Pernambuco/Recife`), Evolução, Concentração, Sobrevivência (tempo até o ban), Tráfego (analytics amigável à privacidade para visitantes legítimos), De onde vêm os erros (app, proxy, blocked, attack, bot, client, unknown) e Protocolos e TLS.
- **Operar:** Defesa (cobertura de bans e da blocklist, segundo firewall, Desbanir), Fontes e hosts (fontes de log, peers e a blocklist) e Integridade (saúde das fontes, do registro e do snapshot).
- **Operar:** Defesa (cobertura de bans e da blocklist, segundo firewall, Desbanir), Fontes e hosts (sondas, suas fontes de log e a blocklist) e Integridade (saúde das fontes, do registro e do snapshot).
- **Relatórios:** o relatório HTML de um período.
No celular, tabelas de dados simples viram cartões empilhados, e nada rola para o lado. Veja [docs/pt-BR/interface.md](docs/pt-BR/interface.md) para cada página com capturas de tela e as rotas HTTP.
## Instalação
Rode com Docker Compose (recomendado):
Duas imagens a partir de um só Dockerfile: o **hub** (`urutau`), uma vez, e a **sonda** (`urutau-probe`) em cada servidor que você quer vigiar. Com Docker Compose (recomendado), primeiro o hub:
```bash
cp .env.example .env
# defina URUTAU_TOKEN (32+ caracteres, 128+ bits de entropia; `openssl rand -base64 48` serve):
sed -i "s|^URUTAU_TOKEN=.*|URUTAU_TOKEN=$(openssl rand -base64 48 | tr -d '\n')|" .env
docker compose pull && docker compose up -d
docker compose exec urutau urutau probes create web1 # mostra o token da sonda UMA vez
```
O dashboard responde em `http://127.0.0.1:8790` e pede o token. A imagem é pública: `docker pull git.lucasrguerra.dev.br/ciberfauna/urutau:latest`. Ou construa localmente com `docker compose up -d --build`.
Depois, em cada servidor monitorado (após `sudo sh deploy/host/install.sh --probe`, veja [docs/pt-BR/docker.md](docs/pt-BR/docker.md)):
```bash
cd deploy/probe && cp .env.example .env
# defina URUTAU_HUB=https://urutau.example.com URUTAU_PROBE_NAME=web1 URUTAU_PROBE_TOKEN=urp_...
docker compose up -d
```
O dashboard responde em `http://127.0.0.1:8790` e pede o token; a página Fontes mostra a sonda conectada. As imagens são públicas: `docker pull git.lucasrguerra.dev.br/ciberfauna/urutau:latest` e `.../urutau-probe:latest`. Ou construa localmente com `docker compose up -d --build`.
Para compilar do código-fonte (Go 1.26.11 ou mais novo, sem dependência para baixar):
@@ -131,14 +137,18 @@ Matriz de plataformas das imagens: `linux/amd64` e `linux/arm64`. Veja [docs/pt-
## Primeiros passos
```bash
# Confira as fontes e o diretório de dados
# Confira o diretório de dados e as sondas
urutau doctor
# Rode o daemon e o dashboard
# Rode o hub (dashboard, API, recepção das sondas)
urutau serve --bind 127.0.0.1:8790
# Agregue outras instâncias
urutau serve --peer web1=https://urutau.web1.example --peer-token "$URUTAU_PEER_TOKEN"
# Cadastre uma sonda e rode-a no servidor a vigiar
urutau probes create web1
URUTAU_HUB=https://urutau.example.com URUTAU_PROBE_NAME=web1 URUTAU_PROBE_TOKEN=urp_... urutau probe
# Traga um diretório de dados da 1.x, sem perder nada
urutau import --from /backup/data --host servidor-antigo
```
Veja [docs/pt-BR/cli.md](docs/pt-BR/cli.md) para a referência de comandos e [docs/pt-BR/configuracao.md](docs/pt-BR/configuracao.md) para cada variável `URUTAU_*`.
@@ -205,7 +215,7 @@ A lista só traz endereços globalmente roteáveis, nunca algo em `--ignore` ou
## Segurança
O Urutau lida com texto hostil por definição. Todo campo que ele lê de um log (caminhos, User-Agents, nomes de usuário, hosts) foi escrito por um atacante: é limitado em tamanho, nunca executado e sempre escapado antes de chegar à página. O dashboard e a API exigem token (`URUTAU_TOKEN`, no mínimo 32 caracteres, por exemplo `openssl rand -base64 48`), o cookie de sessão é `HttpOnly` e `SameSite=Strict`, logins errados têm limite de tentativas por IP, e o token de peer só abre `GET /api/v1/peer/export`. Coloque-o atrás de um proxy reverso com TLS antes de expor. Veja [SECURITY.pt-BR.md](SECURITY.pt-BR.md).
O Urutau lida com texto hostil por definição. Todo campo que ele lê de um log (caminhos, User-Agents, nomes de usuário, hosts) foi escrito por um atacante: é limitado em tamanho, nunca executado e sempre escapado antes de chegar à página. O dashboard e a API exigem token (`URUTAU_TOKEN`, no mínimo 32 caracteres, por exemplo `openssl rand -base64 48`), o cookie de sessão é `HttpOnly` e `SameSite=Strict`, logins errados têm limite de tentativas por IP, e o token de cada sonda (guardado só como hash no hub) abre apenas as três rotas de sonda; a própria sonda não abre porta e só grava linhas que passam por uma checagem rígida de formato. Coloque-o atrás de um proxy reverso com TLS antes de expor. Veja [SECURITY.pt-BR.md](SECURITY.pt-BR.md).
## Uso autorizado
@@ -223,7 +233,8 @@ Veja **[CONTRIBUTING.pt-BR.md](CONTRIBUTING.pt-BR.md)** e **[docs/pt-BR/arquitet
## Limites conhecidos
- Fontes: access log do Traefik (JSON ou formato texto padrão), linhas do sshd no `auth.log` (timestamps ISO), `fail2ban.log` e os logs opcionais de sondagens e de conexões de saída escritos pelo kit de host.
- Fontes (lidas pelas sondas): access log do Traefik (JSON ou formato texto padrão), linhas do sshd no `auth.log` (timestamps ISO), `fail2ban.log` e os logs opcionais de sondagens e de conexões de saída escritos pelo kit de host.
- A sonda precisa alcançar o hub por HTTPS (HTTP puro só para endereços privados); ela guarda até `URUTAU_PROBE_SPOOL_MAX` (64 MiB) em disco enquanto o hub está fora e descarta os lotes mais antigos além disso, contando-os.
- O estado é mantido por no máximo 30 dias (`--retention`), com até 20.000 IPs rastreados; o registro de eventos é limitado por `--events-max`; os incidentes comportam até 5000 chamados.
- O login do dashboard é um token único compartilhado; não há contas de usuário, e o autor de um chamado é um nome em texto livre.
- Pontuações e decisões do segundo firewall são heurísticas, não prova de intenção maliciosa. Comece por `observe`.
@@ -238,6 +249,7 @@ Resumo do [ROADMAP](ROADMAP.pt-BR.md):
| **Feito (1.0.0)** | Coleta de logs, classificação e pontuação, geolocalização offline, parse de User-Agent, web analytics amigável à privacidade, snapshot em disco, dashboard com SSE, login por token, blocklist, federação, imagem Docker e CI/CD |
| **Feito (1.2.0)** | Retenção de 30 dias, qualquer período, registro de eventos em disco, replay, análise de IP com veredito, MITRE ATT&CK, campanhas, STIX 2.1 e métricas estáveis |
| **Feito (1.4.0 a 1.6.0)** | Segundo firewall com Desbanir e compartilhamento de decisões, análise de tráfego de saída, gestão de incidentes, relatório HTML, listas Tor, sondagens de rede, logs de texto do Traefik, crawlers verificados e navegação em forge reconhecidos, layout de celular |
| **Feito (2.0.0)** | Hub e sondas ultraleves (imagem própria), recepção por HTTPS com spool em disco, token por sonda, decisões do enforce pelas sondas, `urutau import` para dados da 1.x |
| **Próximo** | Mais fontes de log, alertas por webhook, métricas Prometheus |
| **Depois** | Enriquecimento com reputação de IP |
| **Fora do plano** | Varredura ativa ou contra-ataque, serviços de nuvem obrigatórios, telemetria |
+4 -2
View File
@@ -2,7 +2,7 @@
**English** · [Português](ROADMAP.pt-BR.md)
Urutau is lightweight, always-on threat intelligence for self-hosted servers: it reads the logs your server already writes, classifies hostile activity, scores IPs and exports a blocklist. It never sends traffic to the IPs it lists and has no telemetry; the optional second firewall only writes a file that a host jail reads.
Urutau is lightweight, always-on threat intelligence for self-hosted servers: a hub plus an ultra-light probe on each server, which read the logs your servers already write, classifies hostile activity, scores IPs and exports a blocklist. It never sends traffic to the IPs it lists and has no telemetry; the optional second firewall only makes the probe write a file that a host jail reads.
## Done
@@ -11,7 +11,7 @@ Urutau is lightweight, always-on threat intelligence for self-hosted servers: it
- **Persistence (1.0.0):** a 7-day rolling state saved to a snapshot with the file offsets, so a restart never replays a log.
- **Dashboard and API (1.0.0):** embedded bilingual UI with live updates over SSE, token login, JSON API, IP detail.
- **Blocklist (1.0.0):** text and JSON export with a score threshold.
- **Federation (1.0.0):** a hub aggregates peers through `/api/v1/peer/export` with a separate peer token that opens nothing else.
- **Federation (1.0.0, replaced by probes in 2.0.0):** a hub aggregated peers through `/api/v1/peer/export` with a separate peer token.
- **Geolocation and web analytics (1.0.0):** offline DB-IP Lite geolocation, User-Agent parsing and privacy-friendly traffic analytics.
- **Noise filters (1.0.0):** trusted CIDRs and monitoring User-Agents.
- **Container and CI/CD (1.0.0):** multi-arch image, Coolify deployment, Gitea CI with an image-reuse release workflow, weekly audit.
@@ -31,6 +31,8 @@ Urutau is lightweight, always-on threat intelligence for self-hosted servers: it
- **Forge browsing, verified crawlers and coverage (1.6.0):** repository pages are not attacks, crawlers confirmed by reverse DNS are never banned, our own bans no longer feed the score, honest blocklist coverage and a slow-attacker policy; phone tables as cards (1.5.8, shipped inside 1.6.0).
- **Hub and probes (2.0.0):** the hub no longer reads files; a probe of a few MB (own image, no open port) on each server sends the logs over HTTPS with a disk spool and receives the second firewall decisions; per-probe tokens stored as hashes, the Sources page to create, edit and revoke probes, per-probe location and egress settings, incidents qualified by host (`host/INC-n`) and `urutau import` to bring 1.x data directories in without loss. Breaking: the peer federation and the log path variables of the hub are gone ([docs/migration-2.0.md](docs/migration-2.0.md)).
## Next
- **More log sources:** other web servers and proxies (nginx, Caddy), and more daemons' auth failures.
+4 -2
View File
@@ -2,7 +2,7 @@
[English](ROADMAP.md) · **Português**
O Urutau é threat intelligence leve e sempre ligado para servidores self-hosted: lê os logs que o servidor já escreve, classifica atividade hostil, pontua IPs e exporta uma blocklist. Nunca envia tráfego aos IPs que lista e não tem telemetria; o segundo firewall opcional só escreve um arquivo que uma jail do host lê.
O Urutau é threat intelligence leve e sempre ligado para servidores self-hosted: um hub mais uma sonda ultraleve em cada servidor, que leem os logs que os servidores já escrevem, classifica atividade hostil, pontua IPs e exporta uma blocklist. Nunca envia tráfego aos IPs que lista e não tem telemetria; o segundo firewall opcional só faz a sonda escrever um arquivo que uma jail do host lê.
## Feito
@@ -11,7 +11,7 @@ O Urutau é threat intelligence leve e sempre ligado para servidores self-hosted
- **Persistência (1.0.0):** estado móvel de 7 dias salvo em snapshot junto com as posições dos arquivos, para que um reinício nunca reprocesse um log.
- **Dashboard e API (1.0.0):** UI bilíngue embutida com atualização ao vivo por SSE, login por token, API JSON, detalhe do IP.
- **Blocklist (1.0.0):** exportação em texto e JSON com limiar de pontuação.
- **Federação (1.0.0):** um hub agrega peers por `/api/v1/peer/export` com um token de peer separado que não abre mais nada.
- **Federação (1.0.0, substituída por sondas na 2.0.0):** um hub agregava peers por `/api/v1/peer/export` com um token de peer separado.
- **Geolocalização e web analytics (1.0.0):** geolocalização offline DB-IP Lite, interpretação de User-Agent e analytics de tráfego amigável à privacidade.
- **Filtros de ruído (1.0.0):** CIDRs confiáveis e User-Agents de monitoramento.
- **Container e CI/CD (1.0.0):** imagem multi-arquitetura, deploy no Coolify, CI no Gitea com release que reaproveita imagem, auditoria semanal.
@@ -31,6 +31,8 @@ O Urutau é threat intelligence leve e sempre ligado para servidores self-hosted
- **Navegação em forge, crawlers verificados e cobertura (1.6.0):** páginas de repositório não são ataque, crawlers confirmados por DNS reverso nunca são banidos, nossos próprios bans deixam de alimentar a pontuação, cobertura honesta da blocklist e uma política para atacantes lentos; tabelas em cartões no celular (1.5.8, entregue dentro da 1.6.0).
- **Hub e sondas (2.0.0):** o hub não lê mais arquivos; uma sonda de poucos MB (imagem própria, sem porta aberta) em cada servidor envia os logs por HTTPS com spool em disco e recebe as decisões do segundo firewall; token por sonda guardado como hash, página Fontes para criar, editar e revogar sondas, localização e egress por sonda, incidentes qualificados por host (`host/INC-n`) e `urutau import` para trazer diretórios de dados da 1.x sem perda. Incompatível: a federação por peers e as variáveis de caminho de log do hub saíram ([docs/pt-BR/migracao-2.0.md](docs/pt-BR/migracao-2.0.md)).
## Próximo
- **Mais fontes de log:** outros servidores web e proxies (nginx, Caddy) e falhas de autenticação de mais daemons.
+11 -9
View File
@@ -2,7 +2,7 @@
**English** · [Português](SECURITY.pt-BR.md)
Urutau is defensive software, but its whole input is hostile: every line of the Traefik access log, `auth.log` and `fail2ban.log` can carry text an attacker chose on purpose (request paths, User-Agents, user names, host names). Treat every log field as untrusted.
Urutau is defensive software, but its whole input is hostile: every line of the Traefik access log, `auth.log` and `fail2ban.log` can carry text an attacker chose on purpose (request paths, User-Agents, user names, host names). Treat every log field as untrusted, and everything a probe sends as untrusted too.
## Reporting a vulnerability
@@ -12,20 +12,22 @@ Do not open a public issue with exploit details. Open a minimal issue asking for
- **Hostile log fields:** paths, User-Agents, user names, hosts and jails are length-limited when parsed, kept as data, and escaped when rendered. A malformed, oversized or crafted line must be counted as malformed, never crash the daemon, exhaust memory or inject markup, a command or a script into the dashboard. The dashboard ships a Content-Security-Policy that forbids inline script and style.
- **Authentication:** the dashboard and every API route except `/api/health` need `URUTAU_TOKEN` (at least 32 characters and about 128 bits of estimated entropy, compared in constant time; it can come from `URUTAU_TOKEN_FILE`), either as a bearer token or through a login that sets a session cookie (`HttpOnly`, `SameSite=Strict`, `Secure` over HTTPS) valid for 12 hours. The session is revocable: it is a random id kept in memory, logout revokes it and closes its live stream, and a restart invalidates all sessions. Login and logout reject cross-site requests. After 5 failures per 10 minutes from a client (IPv6 counted per /64) the login answers 429, yet the correct token still gets in after a 1 second delay, so an attacker cannot lock the owner out; wrong bearer tokens count as failures too. The client IP comes from the TCP peer; `X-Forwarded-For` is honored only when the peer is in `--trusted-proxy` (default: the private networks), read from right to left, so it cannot be spoofed from outside. Generate tokens with `openssl rand -base64 48` (`-hex 32` also works).
- **Peer token:** The server token (`URUTAU_PEER_TOKEN`, also as `_FILE`; 32+ characters, about 128 bits of estimated entropy, not periodic or sequential, different from `URUTAU_TOKEN`) is the only credential the local export accepts, and it only opens the federation routes: `GET /api/v1/peer/export`, the live stream `GET /api/v1/peer/stream` (at most 10 connections, malicious events only), `GET /api/v1/peer/period` (the study a hub merges; at most two run at once), `GET /api/v1/peer/egress` and, with `--enforce-share`, `GET` and `POST /api/v1/peer/decisions` and `POST /api/v1/peer/unban`; every other route answers 403 to it, and `URUTAU_TOKEN` is refused (401) on them. Without a peer token they are a 404. `--peer-allow` restricts them to source CIDRs. `URUTAU_PEER_TOKEN_<NAME>` values are client credentials a hub sends to that peer; they never open the local export, and peer names that collide in the variable name are refused. A hub refuses to start with a peer that has no token, only talks to those routes, requires `https` outside loopback, does not follow redirects, uses a 4 s timeout and an 8 MB limit, and sanitizes and caps everything a peer sends: an `admin` flag coming from a peer is ignored and a peer's `Strong` flag only counts with a score of 50 or more. The live relay from each peer is capped at about 50 events per second and about 1 MB/s (a peer that sends more is disconnected), lines of at most 16 KB, a 500-event buffer, reconnection with exponential backoff up to 60 s, and every relayed event is rebuilt from validated fields (address, known category, clipped strings without control characters, valid coordinates; the `host` is always the configured peer name). A compromised peer can still add hostile-looking global IPs to the hub's blocklist (only with score 50+ and a strong signal; `admin` and `forged` flags from peers are ignored); set `URUTAU_PEER_BLOCKLIST=off` to keep the blocklist to local observations. Treat a peer as able to read the top 500 IPs, paths and traffic figures its export carries, and its live attack events.
- **Probe tokens and ingestion (2.0):** each probe has its own token (`urp_` plus 43 base64url characters, 256 random bits) shown once at creation. The hub stores only its SHA-256 in `probes.json` (mode 0600, written atomically), never the token, and compares in constant time; a lost token is replaced by revoking the probe and creating it again, and revoking refuses the probe at once while keeping its data. The token opens only `POST /api/v1/probe/hello`, `POST /api/v1/probe/push` and `GET /api/v1/probe/commands` (together with the `X-Urutau-Probe` header, which must match it); every other route refuses it, and the user token is refused on those three. A wrong token is a bare 401 with no detail, under the same attempt limiter as the login. Plain `http://` is accepted only for loopback and private addresses (`wire.CheckHubURL`); otherwise the probe requires HTTPS. The hub treats everything a probe sends as hostile input: bodies are limited to 2 MiB on the wire and 8 MiB inflated, a batch to 5,000 lines of at most 64 KiB, the source name must be one of the known ones, one push at a time per probe (429) and a bounded ingestion queue (503 with `Retry-After`); the hub never trusts a path, an `admin` flag or a host name from a probe, and the host of every event is the registered name of the probe. A compromised probe can inject false events for its own host (and so shape that host's data and, with `URUTAU_ENFORCE=on`, trigger bans of addresses that pass the exclusions); it cannot read data, touch another probe's node or run anything on the hub. Treat a probe token like the right to write lines into your logs.
- **Probe process (2.0):** the probe opens no listening port: it only dials out to the hub. It reads log files read-only and keeps a spool and its positions in its own state directory. Its image is `FROM scratch` (the binary, CA certificates and zoneinfo: no shell, no package manager), runs as uid 10001 with a read-only root filesystem, no capabilities and `no-new-privileges`. A spool that fills drops the oldest batches and counts them, never growing without limit.
- **Command validation on the probe (2.0):** the hub sends ban and unban lines to the probe, which is the only process that writes them to the host. The probe accepts a line only if `wire.ValidCmdLine` passes: exactly the shape the hub's `FormatLine` and `UnbanLine` produce, a valid address, a reason from the fixed list of slugs, a bounded TTL and a bounded length, with no control character or newline; anything else is counted as a command error and never written. Lines are appended with `O_APPEND` and `fsync`, and a repeated command is not written twice. The hub itself never gains write access to a host file.
- **HTTP server limits:** header and body timeouts, `MaxHeaderBytes` of 16 KB, `POST /login` capped at 4 KB, and at most 20 simultaneous live-stream clients (a 21st gets 503 with `Retry-After`; the stream sends a heartbeat every 20 s).
- **Information exposure:** `/api/health` returns only `{"status":"ok"}` (no version), log file paths are never shown in the dashboard or to peers, responses carry `Referrer-Policy: same-origin` and a strict Content-Security-Policy.
- **Information exposure:** `/api/health` returns only `{"status":"ok"}` (no version), log file paths never leave the probe and are never shown in the dashboard, responses carry `Referrer-Policy: same-origin` and a strict Content-Security-Policy.
- **Framed requests:** with the `Sec-Fetch-Site`, `Sec-Fetch-Dest` and `Referer` headers in the Traefik log, a request embedded by another page (cross-site or same-site, or a sub-resource destination such as image or script) creates an IP record like any other but weighs 0.25 per event, with at most 30 points per IP from such requests (below the hostile threshold), and never counts as a strong signal. With an attack-tool User-Agent the headers are ignored. The headers come from the client, so a framed visitor never becomes hostile, and a scanner that forges them shows up as suspicious instead of vanishing.
- **Admin immunity:** an IP with a successful SSH login (of a user in `--admin-users`; the immunity is off unless that list is set) is kept out of the hostile level and the blocklist for 24 hours after its last login, and a strong signal after that login cancels it. A login in the same second as a strong attack gives no immunity.
- **Analytics and blocklist hygiene:** a domain gets an analytics slot only after a 2xx answer (optionally restricted by `--domains`) and inactive domains are pruned, so forged `Host` headers cannot fill memory. The blocklist only contains hostile, globally routable addresses, never `--ignore` or `--trusted` ranges or an IP with a successful SSH login; IPv6 is aggregated by /64 (up to 20,000 tracked entries), so one attacker cannot flood the table. A monitoring User-Agent never excuses an attack request, and with `--monitor-from` it only counts from your monitor networks.
- **No unauthenticated mode on the network:** `--insecure-no-auth` is refused unless the bind address is loopback. Exposing the port on a public interface still needs a reverse proxy with TLS.
- **Container hardening:** the image runs as an unprivileged user (no `curl` or shell tools needed: its `HEALTHCHECK` is `urutau healthcheck`) with a read-only root filesystem and no capabilities. Logs are mounted read-only, and only the Traefik log directory is mounted from the proxy, never `acme.json` or its configuration. Logs come from a dedicated host directory, `/var/log/urutau`, not the whole `/var/log`. `--trusted-proxy` defaults to loopback only; the compose file creates the `urutau-edge` network (`10.250.0.0/24`) and trusts just that, so keep only the reverse proxy on it, since another container there could forge `X-Forwarded-For`. The only write target is the data volume (snapshot, mode `0700` directory).
- **Read-only by design:** Urutau reads logs and never sends traffic to the IPs it lists. The only outbound connections are reverse DNS lookups, the periodic download of the DB-IP Lite databases from `download.db-ip.com` (verified by opening the file before it replaces the old one; a failure never stops the service), the Tor exit and relay lists from `check.torproject.org` and `onionoo.torproject.org` every 6 hours (`--tor-auto=off` turns it off) and, on a hub, the polls to the configured peers. Geolocation lookups are local.
- **Second firewall:** it is off by default (`--enforce=off`). Urutau gains no privileges: it only appends lines to a decision file and a jail of the host fail2ban applies them. A line carries nothing the attacker controls (the address is re-formatted, the reason is one of a fixed list of slugs, host and source names are reduced to `[A-Za-z0-9._-]`), the file rotates at 20 MB, and at most `--enforce-max-per-min` decisions are written per minute. It never bans private ranges, `--trusted`, Cloudflare ranges, public resolvers, peers, the server itself, verified crawlers or addresses with a legitimate visit in the last 24 hours. Decisions from a peer are accepted only with a fixed reason, a TTL capped at 6 hours and an address this server also saw attacking. The unban file is written only by an authenticated user (`POST /api/v1/enforce/unban`), never by a peer token without `--enforce-share`.
- **Egress and incidents:** egress analysis only reads a kernel log written by the host kit, which logs and never drops. Tickets in `<data-dir>/incidents.json` are written with mode 0600, bounded (5,000 tickets, 200 comments, 500 history entries), refuse cross-site writes and are closed to the peer token.
- **Container hardening:** both images run as an unprivileged user without `curl` (the hub's `HEALTHCHECK` is `urutau healthcheck`, the probe's is `urutau probe --check`) with a read-only root filesystem and no capabilities. The hub mounts no log at all; the probe mounts logs read-only, and only the Traefik log directory is mounted from the proxy, never `acme.json` or its configuration. Logs come from a dedicated host directory, `/var/log/urutau`, not the whole `/var/log`. `--trusted-proxy` defaults to loopback only; the compose file creates the `urutau-edge` network (`10.250.0.0/24`) and trusts just that, so keep only the reverse proxy on it, since another container there could forge `X-Forwarded-For`. The only write target of the hub is the data volume (snapshots, mode `0700` directory); the probe writes its `/state` volume and, only for the second firewall, the decision files.
- **Read-only by design:** Urutau reads logs and never sends traffic to the IPs it lists. The only outbound connections are reverse DNS lookups, the periodic download of the DB-IP Lite databases from `download.db-ip.com` (verified by opening the file before it replaces the old one; a failure never stops the service), the Tor exit and relay lists from `check.torproject.org` and `onionoo.torproject.org` every 6 hours (`--tor-auto=off` turns it off) Geolocation lookups are local. A probe's only outbound connection is to its hub.
- **Second firewall:** it is off by default (`--enforce=off`). Urutau gains no privileges: the hub queues a line for the probe, the probe validates it and appends it to a decision file, and a jail of the host fail2ban applies it. A line carries nothing the attacker controls (the address is re-formatted, the reason is one of a fixed list of slugs, host and source names are reduced to `[A-Za-z0-9._-]`), the file rotates at 20 MB, and at most `--enforce-max-per-min` decisions are written per minute. It never bans private ranges, `--trusted`, Cloudflare ranges, public resolvers, peers, the server itself, verified crawlers or addresses with a legitimate visit in the last 24 hours. With `--enforce-share`, a decision of one node is accepted by another only with a fixed reason, a TTL capped at 6 hours and an address that node also saw attacking. The unban file is written only through an authenticated user (`POST /api/v1/enforce/unban`), as a command to the probe of the chosen host.
- **Egress and incidents:** egress analysis only reads a kernel log written by the host kit, which logs and never drops. Tickets in each node's `incidents.json` are written with mode 0600, bounded (5,000 tickets, 200 comments, 500 history entries), refuse cross-site writes and are closed to a probe token.
- **Privacy and local-first:** there is no telemetry. IPs and request details stay on your servers (and on the hub you configure).
- **Visitor privacy (LGPD and GDPR):** the Traffic page counts unique visitors with a hash computed with a daily salt, so a visitor cannot be followed across days, and the IP address of a legitimate visitor is never persisted. There are no cookies for visitors, no fingerprinting and no request to third parties. IPs are retained only for hostile activity, for at most the retention period (7 days). Whether this is enough for your legal basis and notices is your responsibility as the controller.
- **Anonymous visits:** legitimate visitors are never stored. The optional `?visits=1` stream carries no address, User-Agent or referrer (city-level position only, at most 20 per second) and is never written to disk. Paths and `Referer` values are normalized to `:id` when they carry an e-mail address, a token or a long identifier, so personal data in a URL does not reach the lists. The newer analysis routes (`/api/v1/techniques`, `/evolution`, `/concentration`, `/survival`, `/sessions/funnel`, `/campaigns`, `/defense`, `/errors`, `/integrity`, `/report`, `/services`, `/protocols`) are user-only: the peer token gets 403 on them.
- **Anonymous visits:** legitimate visitors are never stored. The optional `?visits=1` stream carries no address, User-Agent or referrer (city-level position only, at most 20 per second) and is never written to disk. Paths and `Referer` values are normalized to `:id` when they carry an e-mail address, a token or a long identifier, so personal data in a URL does not reach the lists. The newer analysis routes (`/api/v1/techniques`, `/evolution`, `/concentration`, `/survival`, `/sessions/funnel`, `/campaigns`, `/defense`, `/errors`, `/integrity`, `/report`, `/services`, `/protocols`) are user-only: a probe token is refused on them.
- **Event registry (privacy):** `<data-dir>/events/` keeps one line per event for replay and investigation, but only about attackers: malicious events, bans, successful SSH logins, a 404 to an attack tool, and answers to addresses that are already suspicious or hostile. The address of a legitimate visitor is never written. Files are removed after the retention (30 days at most) and the total is capped by `--events-max` (512 MB by default, `0` turns the registry off). Treat the directory as personal data under the LGPD and the GDPR: same retention, same access control as the rest of the data volume. A full disk or the size cap drops events instead of stopping the service, and a corrupted line is skipped.
- **Outbound lookups for verdicts:** the network type is inferred locally from the ASN, organisation and reverse DNS (no external API). Forward-confirmed reverse DNS is used only to confirm a claimed Googlebot, Bingbot or Applebot (a confirmed crawler is never banned by the second firewall). The Tor lists are cached locally, and `--tor-exits` accepts a local file.
- **Third-party data:** the geolocation databases are DB-IP Lite, CC BY 4.0, and the attribution must be kept where the data is shown. The state and city boundaries on the Geography page are from Natural Earth, public domain.
@@ -42,4 +44,4 @@ A local user of the host can forge sshd lines with `logger -t sshd`, which rsysl
## Supported versions
Only the latest `1.x` release is supported. There is no long-term support branch.
Only the latest `2.x` release is supported. The 1.x peer federation (`/api/v1/peer/*`, `URUTAU_PEER_*`) was removed in 2.0.0 and gets no fixes; see [docs/migration-2.0.md](docs/migration-2.0.md). There is no long-term support branch.
+10 -8
View File
@@ -12,20 +12,22 @@ Não abra uma issue pública com detalhes de exploração. Abra uma issue mínim
- **Campos hostis de log:** caminhos, User-Agents, usuários, hosts e jails têm tamanho limitado no parse, são mantidos como dado e escapados ao renderizar. Uma linha malformada, gigante ou forjada deve ser contada como malformada, nunca derrubar o daemon, esgotar memória ou injetar marcação, comando ou script no dashboard. O dashboard envia uma Content-Security-Policy que proíbe script e estilo inline.
- **Autenticação:** o dashboard e toda rota da API, exceto `/api/health`, exigem `URUTAU_TOKEN` (no mínimo 32 caracteres e cerca de 128 bits de entropia estimada, comparado em tempo constante; pode vir de `URUTAU_TOKEN_FILE`), como bearer token ou por um login que define um cookie de sessão (`HttpOnly`, `SameSite=Strict`, `Secure` em HTTPS) válido por 12 horas. A sessão é revogável: é um id aleatório guardado em memória, o logout a revoga e fecha o stream ao vivo dela, e um reinício invalida todas as sessões. Login e logout rejeitam requisições cross-site. Após 5 falhas a cada 10 minutos de um cliente (IPv6 contado por /64) o login responde 429, mas o token correto ainda entra após 1 segundo de atraso, para que um atacante não tranque o dono do lado de fora; bearer tokens errados também contam como falha. O IP do cliente vem do peer TCP; `X-Forwarded-For` só vale quando o peer está em `--trusted-proxy` (padrão: as redes privadas), lido da direita para a esquerda, então não pode ser forjado de fora. Gere tokens com `openssl rand -base64 48` (`-hex 32` também serve).
- **Token de peer:** O token de servidor (`URUTAU_PEER_TOKEN`, também via `_FILE`; 32+ caracteres, cerca de 128 bits de entropia estimada, sem padrão periódico nem sequencial, diferente de `URUTAU_TOKEN`) é a única credencial que o export local aceita, e só abre as rotas de federação: `GET /api/v1/peer/export`, o fluxo ao vivo `GET /api/v1/peer/stream` (no máximo 10 conexões, só eventos maliciosos), `GET /api/v1/peer/period` (o estudo que um hub mescla; no máximo dois ao mesmo tempo), `GET /api/v1/peer/egress` e, com `--enforce-share`, `GET` e `POST /api/v1/peer/decisions` e `POST /api/v1/peer/unban`; todas as outras rotas respondem 403 a ele, e o `URUTAU_TOKEN` é recusado (401) nelas. Sem token de peer elas são 404. `--peer-allow` restringe essas rotas a CIDRs de origem. Os valores `URUTAU_PEER_TOKEN_<NOME>` são credenciais de cliente que um hub envia àquele peer; nunca abrem o export local, e nomes de peer que colidem no nome da variável são recusados. Um hub se recusa a iniciar com um peer sem token, só fala com essas rotas, exige `https` fora de loopback, não segue redirects, usa timeout de 4 s e limite de 8 MB, e sanitiza e limita tudo o que um peer envia: um sinalizador `admin` vindo de um peer é ignorado e o `Strong` de um peer só vale com pontuação 50 ou mais. O repasse ao vivo de cada peer é limitado a cerca de 50 eventos por segundo e cerca de 1 MB/s (um peer que manda mais é desconectado), linhas de no máximo 16 KB, buffer de 500 eventos e reconexão com backoff exponencial até 60 s, e cada evento repassado é reconstruído a partir de campos validados (endereço, categoria conhecida, textos cortados e sem caracteres de controle, coordenadas válidas; o `host` é sempre o nome configurado do peer). Um peer comprometido ainda pode pôr IPs globais com cara de hostis na blocklist do hub (só com pontuação 50+ e sinal forte; os sinalizadores `admin` e `forged` vindos de peers são ignorados); defina `URUTAU_PEER_BLOCKLIST=off` para restringir a blocklist às observações locais. Trate um peer como alguém que pode ler os 500 IPs principais, caminhos e números de tráfego que o export carrega, e os seus eventos de ataque ao vivo.
- **Tokens de sonda e recepção (2.0):** cada sonda tem o seu token (`urp_` mais 43 caracteres base64url, 256 bits aleatórios), mostrado uma vez na criação. O hub guarda apenas o SHA-256 dele em `probes.json` (modo 0600, gravação atômica), nunca o token, e compara em tempo constante; um token perdido se resolve revogando a sonda e criando de novo, e revogar recusa a sonda na hora mantendo os dados dela. O token abre só `POST /api/v1/probe/hello`, `POST /api/v1/probe/push` e `GET /api/v1/probe/commands` (junto com o cabeçalho `X-Urutau-Probe`, que precisa corresponder); toda outra rota o recusa, e o token de usuário é recusado nessas três. Token errado é um 401 seco, sem detalhe, sob o mesmo limitador de tentativas do login. `http://` puro só é aceito para loopback e endereços privados (`wire.CheckHubURL`); fora disso a sonda exige HTTPS. O hub trata tudo que a sonda envia como entrada hostil: corpos limitados a 2 MiB no fio e 8 MiB descomprimido, lote de no máximo 5.000 linhas de até 64 KiB, nome de fonte entre os conhecidos, um push por vez por sonda (429) e fila de ingestão limitada (503 com `Retry-After`); o hub nunca confia em caminho, em flag `admin` nem em nome de host vindo da sonda, e o host de cada evento é o nome cadastrado da sonda. Uma sonda comprometida pode injetar eventos falsos no próprio host (moldando os dados dele e, com `URUTAU_ENFORCE=on`, provocando bans de endereços que passem pelas exclusões); não consegue ler dados, tocar o nó de outra sonda nem executar nada no hub. Trate o token de uma sonda como o direito de escrever linhas nos seus logs.
- **Processo da sonda (2.0):** a sonda não abre porta nenhuma: só conecta de dentro para fora até o hub. Lê arquivos de log somente leitura e guarda o spool e as posições no próprio diretório de estado. A imagem é `FROM scratch` (o binário, certificados CA e zoneinfo: sem shell nem gerenciador de pacotes), roda como uid 10001 com sistema de arquivos raiz somente leitura, sem capabilities e com `no-new-privileges`. Um spool cheio descarta os lotes mais antigos e os conta, sem crescer sem limite.
- **Validação de comandos na sonda (2.0):** o hub envia linhas de ban e desban à sonda, que é o único processo que as grava no host. A sonda só aceita uma linha se `wire.ValidCmdLine` passar: exatamente o formato que `FormatLine` e `UnbanLine` do hub produzem, endereço válido, motivo de uma lista fixa de slugs, TTL e tamanho limitados, sem caractere de controle nem quebra de linha; qualquer outra coisa é contada como erro de comando e nunca gravada. As linhas entram com `O_APPEND` e `fsync`, e um comando repetido não é gravado duas vezes. O hub nunca ganha escrita em arquivo do host.
- **Limites do servidor HTTP:** timeouts de cabeçalho e corpo, `MaxHeaderBytes` de 16 KB, `POST /login` limitado a 4 KB e no máximo 20 clientes simultâneos no stream ao vivo (o 21º recebe 503 com `Retry-After`; o stream envia heartbeat a cada 20 s).
- **Exposição de informação:** `/api/health` devolve só `{"status":"ok"}` (sem versão), os caminhos dos arquivos de log nunca aparecem no dashboard nem para peers, e as respostas levam `Referrer-Policy: same-origin` e uma Content-Security-Policy estrita.
- **Exposição de informação:** `/api/health` devolve só `{"status":"ok"}` (sem versão), os caminhos dos arquivos de log nunca saem da sonda nem aparecem no dashboard, e as respostas levam `Referrer-Policy: same-origin` e uma Content-Security-Policy estrita.
- **Requisições enquadradas:** com os cabeçalhos `Sec-Fetch-Site`, `Sec-Fetch-Dest` e `Referer` no log do Traefik, uma requisição embutida por outra página (cross-site ou same-site, ou destino de subrecurso como image ou script) aparece na linha do tempo e cria registro de IP como qualquer outra, mas pesa 0,25 por evento, com no máximo 30 pontos por IP vindos delas (abaixo do limiar hostil), e nunca conta como sinal forte. Com User-Agent de ferramenta de ataque os cabeçalhos são ignorados. Os cabeçalhos vêm do cliente, então um visitante enquadrado nunca vira hostil, e um scanner que os forja aparece como suspeito em vez de sumir.
- **Imunidade de admin:** um IP com login SSH bem-sucedido (de um usuário em `--admin-users`; a imunidade fica desligada a menos que essa lista seja definida) fica fora do nível hostil e da blocklist por 24 horas após o último login, e um sinal forte depois desse login a anula. Um login no mesmo segundo de um ataque forte não dá imunidade.
- **Higiene do analytics e da blocklist:** um domínio só ganha vaga no analytics após uma resposta 2xx (opcionalmente restrito por `--domains`) e domínios inativos são podados, então `Host` forjados não enchem a memória. A blocklist só contém endereços hostis e globalmente roteáveis, nunca faixas de `--ignore` ou `--trusted` nem um IP com login SSH bem-sucedido; o IPv6 é agregado por /64 (até 20.000 entradas rastreadas), então um atacante não inunda a tabela. Um User-Agent de monitoramento nunca desculpa uma requisição de ataque, e com `--monitor-from` só vale vindo das suas redes de monitoramento.
- **Sem modo aberto na rede:** `--insecure-no-auth` é recusado a menos que o bind seja loopback. Expor a porta em uma interface pública ainda exige um proxy reverso com TLS.
- **Endurecimento do container:** a imagem roda com usuário sem privilégios (sem `curl` nem ferramentas de shell: o `HEALTHCHECK` é `urutau healthcheck`), sistema de arquivos raiz somente leitura e sem capabilities. Os logs são montados somente leitura, e do proxy só o diretório de logs do Traefik é montado, nunca o `acme.json` nem a configuração. Os logs vêm de um diretório dedicado do host, `/var/log/urutau`, não do `/var/log` inteiro. `--trusted-proxy` tem como padrão só o loopback; o compose cria a rede `urutau-edge` (`10.250.0.0/24`) e confia só nela, então deixe nela apenas o proxy reverso, pois outro container ali poderia forjar o `X-Forwarded-For`. O único destino de escrita é o volume de dados (snapshot, diretório com modo `0700`).
- **Somente leitura por desenho:** o Urutau lê logs e nunca envia tráfego aos IPs que lista. As únicas conexões de saída são as consultas de DNS reverso, o download periódico das bases DB-IP Lite em `download.db-ip.com` (verificado abrindo o arquivo antes de substituir o antigo; uma falha nunca interrompe o serviço), as listas de saídas e relays do Tor em `check.torproject.org` e `onionoo.torproject.org` a cada 6 horas (`--tor-auto=off` desliga) e, em um hub, as consultas aos peers configurados. As consultas de geolocalização são locais.
- **Segundo firewall:** vem desligado (`--enforce=off`). O Urutau não ganha privilégios: só acrescenta linhas a um arquivo de decisões e uma jail do fail2ban do host as aplica. Uma linha não carrega nada que o atacante controla (o endereço é reformatado, o motivo é um de uma lista fixa de slugs, nomes de host e origem são reduzidos a `[A-Za-z0-9._-]`), o arquivo rotaciona em 20 MB e no máximo `--enforce-max-per-min` decisões são gravadas por minuto. Nunca bane faixas privadas, `--trusted`, faixas da Cloudflare, resolvedores públicos, peers, o próprio servidor, crawlers verificados nem endereços com visita legítima nas últimas 24 horas. Decisões de um peer só são aceitas com motivo fixo, TTL limitado a 6 horas e um endereço que este servidor também viu atacar. O arquivo de desban só é escrito por um usuário autenticado (`POST /api/v1/enforce/unban`), nunca por um token de peer sem `--enforce-share`.
- **Egress e incidentes:** a análise de egress só lê um log do kernel escrito pelo kit do host, que registra e nunca descarta. Os chamados em `<data-dir>/incidents.json` são gravados com modo 0600, limitados (5.000 chamados, 200 comentários, 500 entradas de histórico), recusam escritas cross-site e ficam fechados ao token de peer.
- **Endurecimento do container:** as duas imagens rodam com usuário sem privilégios e sem `curl` (o `HEALTHCHECK` do hub é `urutau healthcheck`, o da sonda é `urutau probe --check`), sistema de arquivos raiz somente leitura e sem capabilities. O hub não monta log algum; a sonda monta os logs somente leitura, e do proxy só o diretório de logs do Traefik é montado, nunca o `acme.json` nem a configuração. Os logs vêm de um diretório dedicado do host, `/var/log/urutau`, não do `/var/log` inteiro. `--trusted-proxy` tem como padrão só o loopback; o compose cria a rede `urutau-edge` (`10.250.0.0/24`) e confia só nela, então deixe nela apenas o proxy reverso, pois outro container ali poderia forjar o `X-Forwarded-For`. O único destino de escrita do hub é o volume de dados (snapshots, diretório com modo `0700`); a sonda escreve o volume `/state` e, só para o segundo firewall, os arquivos de decisão.
- **Somente leitura por desenho:** o Urutau lê logs e nunca envia tráfego aos IPs que lista. As únicas conexões de saída são as consultas de DNS reverso, o download periódico das bases DB-IP Lite em `download.db-ip.com` (verificado abrindo o arquivo antes de substituir o antigo; uma falha nunca interrompe o serviço), as listas de saídas e relays do Tor em `check.torproject.org` e `onionoo.torproject.org` a cada 6 horas (`--tor-auto=off` desliga) As consultas de geolocalização são locais. A única conexão de saída de uma sonda é para o hub dela.
- **Segundo firewall:** vem desligado (`--enforce=off`). O Urutau não ganha privilégios: o hub enfileira uma linha para a sonda, a sonda a valida e a acrescenta a um arquivo de decisões, e uma jail do fail2ban do host a aplica. Uma linha não carrega nada que o atacante controla (o endereço é reformatado, o motivo é um de uma lista fixa de slugs, nomes de host e origem são reduzidos a `[A-Za-z0-9._-]`), o arquivo rotaciona em 20 MB e no máximo `--enforce-max-per-min` decisões são gravadas por minuto. Nunca bane faixas privadas, `--trusted`, faixas da Cloudflare, resolvedores públicos, sondas, o próprio servidor, crawlers verificados nem endereços com visita legítima nas últimas 24 horas. Com `--enforce-share`, a decisão de um nó só é aceita por outro com motivo fixo, TTL limitado a 6 horas e um endereço que esse nó também viu atacar. O arquivo de desban só é escrito por meio de um usuário autenticado (`POST /api/v1/enforce/unban`), como comando para a sonda do host escolhido.
- **Egress e incidentes:** a análise de egress só lê um log do kernel escrito pelo kit do host, que registra e nunca descarta. Os chamados em cada `incidents.json` de nó são gravados com modo 0600, limitados (5.000 chamados, 200 comentários, 500 entradas de histórico), recusam escritas cross-site e ficam fechados ao token de sonda.
- **Privacidade e local-first:** não há telemetria. IPs e detalhes de requisições ficam nos seus servidores (e no hub que você configurar).
- **Privacidade dos visitantes (LGPD e GDPR):** a página Tráfego conta visitantes únicos com um hash calculado com sal diário, então um visitante não pode ser seguido entre dias, e o endereço IP de um visitante legítimo nunca é persistido. Não há cookies para visitantes, fingerprinting nem requisição a terceiros. IPs são retidos apenas para atividade hostil, por no máximo o período de retenção (7 dias). Se isso basta para a sua base legal e seus avisos é responsabilidade sua, como controlador.
- **Visitas anônimas:** visitantes legítimos nunca são armazenados. O stream opcional `?visits=1` não carrega endereço, User-Agent nem referrer (só posição no nível da cidade, no máximo 20 por segundo) e nunca é gravado em disco. Caminhos e valores de `Referer` são normalizados para `:id` quando carregam e-mail, token ou identificador longo, para que dado pessoal numa URL não chegue às listas. As rotas de análise mais novas (`/api/v1/techniques`, `/evolution`, `/concentration`, `/survival`, `/sessions/funnel`, `/campaigns`, `/defense`, `/errors`, `/integrity`, `/report`, `/services`, `/protocols`) são só de usuário: o token de peer recebe 403 nelas.
- **Visitas anônimas:** visitantes legítimos nunca são armazenados. O stream opcional `?visits=1` não carrega endereço, User-Agent nem referrer (só posição no nível da cidade, no máximo 20 por segundo) e nunca é gravado em disco. Caminhos e valores de `Referer` são normalizados para `:id` quando carregam e-mail, token ou identificador longo, para que dado pessoal numa URL não chegue às listas. As rotas de análise mais novas (`/api/v1/techniques`, `/evolution`, `/concentration`, `/survival`, `/sessions/funnel`, `/campaigns`, `/defense`, `/errors`, `/integrity`, `/report`, `/services`, `/protocols`) são só de usuário: o token de sonda é recusado nelas.
- **Registro de eventos (privacidade):** `<data-dir>/events/` guarda uma linha por evento para replay e investigação, mas só de atacantes: eventos maliciosos, bans, logins SSH bem-sucedidos, um 404 para uma ferramenta de ataque, e respostas a endereços já suspeitos ou hostis. O endereço de um visitante legítimo nunca é gravado. Os arquivos são removidos após a retenção (30 dias no máximo) e o total é limitado por `--events-max` (512 MB por padrão, `0` desliga o registro). Trate o diretório como dado pessoal perante a LGPD e o GDPR: mesma retenção e mesmo controle de acesso do resto do volume de dados. Disco cheio ou o teto de tamanho descartam eventos em vez de parar o serviço, e uma linha corrompida é ignorada.
- **Consultas para os vereditos:** o tipo de rede é inferido localmente a partir do ASN, da organização e do DNS reverso (sem API externa). O DNS reverso confirmado serve apenas para confirmar um Googlebot, Bingbot ou Applebot declarado (um crawler confirmado nunca é banido pelo segundo firewall). As listas do Tor ficam em cache local, e `--tor-exits` aceita um arquivo local.
- **Dados de terceiros:** as bases de geolocalização são DB-IP Lite, CC BY 4.0, e a atribuição deve ser mantida onde os dados são exibidos. Os limites de estados e cidades da página Geografia são do Natural Earth, domínio público.
@@ -42,4 +44,4 @@ Um usuário local do host pode forjar linhas do sshd com `logger -t sshd`, que o
## Versões suportadas
Só a última versão `1.x` é suportada. Não há branch de suporte de longo prazo.
Só a última versão `2.x` é suportada. A federação por peers da 1.x (`/api/v1/peer/*`, `URUTAU_PEER_*`) foi removida na 2.0.0 e não recebe correções; veja [docs/pt-BR/migracao-2.0.md](docs/pt-BR/migracao-2.0.md). Não há branch de suporte de longo prazo.
+12 -2
View File
@@ -13,7 +13,11 @@ import (
const usage = `urutau: lightweight threat intelligence for self-hosted servers
Usage:
urutau serve [flags] run the daemon and the dashboard
urutau serve|hub [flags] run the hub (dashboard, API and probe ingest)
urutau probe [flags] run a probe on a monitored host
urutau probe --check exit 0 when the local probe is alive
urutau probes create|list|revoke NAME [--data-dir D | --url U]
urutau import --from DIR --host NAME [--dry-run --force --verify --count]
urutau doctor [--json] [flags] check sources and the data directory
urutau healthcheck exit 0 when the local daemon answers /api/health
urutau version print the version
@@ -29,7 +33,7 @@ func main() {
switch os.Args[1] {
case "version", "--version", "-v":
fmt.Println("urutau", app.Version)
case "serve":
case "serve", "hub":
c, err := app.ParseFlags("serve", os.Args[2:])
if errors.Is(err, flag.ErrHelp) {
return
@@ -69,6 +73,12 @@ func main() {
fmt.Fprintln(os.Stderr, "urutau:", err)
os.Exit(1)
}
case "probe":
os.Exit(runProbe(os.Args[2:]))
case "probes":
os.Exit(runProbes(os.Args[2:]))
case "import":
os.Exit(app.ImportCLI(os.Args[2:], os.Stdout, os.Stderr))
case "help", "--help", "-h":
fmt.Print(usage)
default:
+232
View File
@@ -0,0 +1,232 @@
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"log/slog"
"net/http"
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/app"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/hub"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/probeagent"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
func envOr(k, def string) string {
if v, ok := os.LookupEnv(k); ok {
return v
}
return def
}
func runProbe(args []string) int {
fs := flag.NewFlagSet("probe", flag.ContinueOnError)
var c probeagent.Config
var tokenFile, spool, loc string
check := fs.Bool("check", false, "exit 0 when the probe in --state-dir is alive (container HEALTHCHECK)")
fs.StringVar(&c.Hub, "hub", envOr("URUTAU_HUB", ""), "hub URL (URUTAU_HUB)")
fs.StringVar(&c.Name, "name", envOr("URUTAU_PROBE_NAME", ""), "probe name (URUTAU_PROBE_NAME)")
fs.StringVar(&c.Token, "token", "", "probe token; prefer URUTAU_PROBE_TOKEN or URUTAU_PROBE_TOKEN_FILE")
fs.StringVar(&tokenFile, "token-file", envOr("URUTAU_PROBE_TOKEN_FILE", ""), "file with the probe token (URUTAU_PROBE_TOKEN_FILE)")
fs.StringVar(&c.StateDir, "state-dir", envOr("URUTAU_STATE_DIR", "/state"), "spool and state directory (URUTAU_STATE_DIR)")
paths := map[string]*string{}
for _, p := range []struct{ src, env, def, help string }{
{wire.SrcTraefik, "URUTAU_TRAEFIK_LOG", "", "Traefik JSON access log"},
{wire.SrcAuth, "URUTAU_AUTH_LOG", "", "sshd auth log"},
{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"},
} {
v := new(string)
paths[p.src] = v
fs.StringVar(v, p.src+"-log", envOr(p.env, p.def), p.help+", empty disables ("+p.env+")")
}
fs.StringVar(&c.Containers, "egress-containers", envOr("URUTAU_EGRESS_CONTAINERS", ""), "containers.map written by the host kit (URUTAU_EGRESS_CONTAINERS)")
fs.StringVar(&c.Resolv, "resolv", envOr("URUTAU_RESOLV", "/etc/resolv.conf"), "resolv.conf of the host (URUTAU_RESOLV)")
fs.StringVar(&c.DecisionsLog, "enforce-log", envOr("URUTAU_ENFORCE_LOG", ""), "decisions file the host fail2ban reads, empty ignores decisions (URUTAU_ENFORCE_LOG)")
fs.StringVar(&c.UnbanLog, "enforce-unban-log", envOr("URUTAU_ENFORCE_UNBAN_LOG", ""), "unban requests file, empty ignores unbans (URUTAU_ENFORCE_UNBAN_LOG)")
fs.StringVar(&spool, "spool-max", envOr("URUTAU_PROBE_SPOOL_MAX", "64MiB"), "spool size cap (URUTAU_PROBE_SPOOL_MAX)")
fs.StringVar(&loc, "location", envOr("URUTAU_LOCATION", ""), `"lat,lon[,label]"; the hub configuration wins (URUTAU_LOCATION)`)
if err := fs.Parse(args); err != nil {
if errors.Is(err, flag.ErrHelp) {
return 0
}
return 2
}
if *check {
if err := probeagent.Check(c.StateDir); err != nil {
fmt.Fprintln(os.Stderr, "urutau probe:", err)
return 1
}
return 0
}
fail := func(m string) int { fmt.Fprintln(os.Stderr, "urutau probe:", m); return 2 }
if c.Hub == "" || c.Name == "" {
return fail("URUTAU_HUB and URUTAU_PROBE_NAME are required")
}
if !wire.ValidName(c.Name) {
return fail("invalid probe name")
}
if _, err := wire.CheckHubURL(c.Hub); err != nil {
return fail(err.Error())
}
if c.Token == "" {
c.Token = os.Getenv("URUTAU_PROBE_TOKEN")
}
if c.Token == "" && tokenFile != "" {
b, err := os.ReadFile(tokenFile)
if err != nil {
return fail("URUTAU_PROBE_TOKEN_FILE: " + err.Error())
}
c.Token = strings.TrimSpace(string(b))
}
if c.Token == "" {
return fail("URUTAU_PROBE_TOKEN or URUTAU_PROBE_TOKEN_FILE is required")
}
n, err := app.ParseSize(spool)
if err != nil {
return fail("--spool-max: " + err.Error())
}
c.SpoolMax = n
if l, err := store.ParseLocation(loc); err != nil {
return fail(err.Error())
} else if l != nil {
c.Location = &wire.Location{Lat: l.Lat, Lon: l.Lon, Label: l.Label}
}
c.Paths = map[string]string{}
for src, p := range paths {
if *p != "" {
c.Paths[src] = *p
}
}
c.Version = app.Version
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
defer stop()
if err := probeagent.Run(ctx, c, slog.New(slog.NewTextHandler(os.Stderr, nil))); err != nil &&
!errors.Is(err, context.Canceled) {
fmt.Fprintln(os.Stderr, "urutau probe:", err)
if errors.Is(err, probeagent.ErrUnauthorized) || errors.Is(err, probeagent.ErrIncompatible) {
return 3
}
return 1
}
return 0
}
// runProbes manages probes: directly on <data-dir>/probes.json (hub stopped or
// not, the file is replaced atomically) or through the API with --url.
func runProbes(args []string) int {
if len(args) < 1 {
fmt.Fprintln(os.Stderr, "usage: urutau probes create|list|revoke [NAME] [--data-dir D | --url U]")
return 2
}
verb, rest := args[0], args[1:]
fs := flag.NewFlagSet("probes "+verb, flag.ContinueOnError)
dir := fs.String("data-dir", envOr("URUTAU_DATA_DIR", "/data"), "hub data directory (URUTAU_DATA_DIR)")
url := fs.String("url", "", "hub URL: use the API instead of the file (token from URUTAU_TOKEN)")
var name string
if len(rest) > 0 && !strings.HasPrefix(rest[0], "-") {
name, rest = rest[0], rest[1:]
}
if err := fs.Parse(rest); err != nil {
return 2
}
if name == "" && fs.NArg() > 0 {
name = fs.Arg(0)
}
if verb != "list" && name == "" {
fmt.Fprintln(os.Stderr, "urutau probes: NAME is required")
return 2
}
if *url != "" {
return probesAPI(verb, name, *url)
}
reg, err := hub.OpenRegistry(filepath.Join(*dir, "probes.json"))
if err != nil {
fmt.Fprintln(os.Stderr, "urutau probes:", err)
return 1
}
switch verb {
case "create":
tok, err := reg.Create(name)
if err != nil {
fmt.Fprintln(os.Stderr, "urutau probes:", err)
return 1
}
fmt.Println(tok)
fmt.Fprintln(os.Stderr, "token shown once: keep it as URUTAU_PROBE_TOKEN of the probe", name)
case "revoke":
if err := reg.Revoke(name); err != nil {
fmt.Fprintln(os.Stderr, "urutau probes:", err)
return 1
}
fmt.Println("revoked", name)
case "list":
for _, p := range reg.List() {
st := "active"
if p.Revoked {
st = "revoked"
}
fmt.Printf("%-32s %-8s created %s\n", p.Name, st, time.Unix(p.Created, 0).UTC().Format(time.RFC3339))
}
default:
fmt.Fprintln(os.Stderr, "urutau probes: unknown command", verb)
return 2
}
return 0
}
func probesAPI(verb, name, base string) int {
tok, _ := app.Secret("URUTAU_TOKEN")
var req *http.Request
u := strings.TrimRight(base, "/") + "/api/v1/probes"
switch verb {
case "create":
b, _ := json.Marshal(map[string]string{"name": name})
req, _ = http.NewRequest(http.MethodPost, u, bytes.NewReader(b))
req.Header.Set("Content-Type", "application/json")
case "revoke":
req, _ = http.NewRequest(http.MethodDelete, u+"/"+name, nil)
case "list":
req, _ = http.NewRequest(http.MethodGet, u, nil)
default:
return 2
}
req.Header.Set("Authorization", "Bearer "+tok)
req.Header.Set("Origin", strings.TrimRight(base, "/"))
resp, err := (&http.Client{Timeout: 15 * time.Second}).Do(req)
if err != nil {
fmt.Fprintln(os.Stderr, "urutau probes:", err)
return 1
}
defer resp.Body.Close()
b, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
if resp.StatusCode/100 != 2 {
fmt.Fprintf(os.Stderr, "urutau probes: HTTP %d %s\n", resp.StatusCode, strings.TrimSpace(string(b)))
return 1
}
if verb == "create" {
var o struct{ Token string }
var m map[string]string
_ = json.Unmarshal(b, &m)
o.Token = m["token"]
fmt.Println(o.Token)
_ = strconv.Itoa
return 0
}
fmt.Println(strings.TrimSpace(string(b)))
return 0
}
+39 -6
View File
@@ -2,9 +2,16 @@
# Urutau host kit: egress logging (nftables + rsyslog), the container map and,
# optionally, the fail2ban jail of the "second firewall".
#
# sudo sh install.sh # egress logging + container map
# sudo sh install.sh --enforce # also the fail2ban jail for URUTAU_ENFORCE=on
# sudo sh install.sh --remove # undo everything
# 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 --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
#
# --probe is for servers that run only the Urutau probe (deploy/probe): the
# probe dials out to the hub, so nothing here opens or needs a port. It also
# 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.
#
# Idempotent. Urutau itself never gets privileges: it only reads these logs and
# writes its ban decisions to /var/log/urutau-enforce/decisions.log.
@@ -12,9 +19,22 @@ set -eu
here=$(cd "$(dirname "$0")" && pwd)
uid=${URUTAU_UID:-10001}
probe=0
enforce=0
remove=0
for arg in "$@"; do
case "$arg" in
--probe) probe=1 ;;
--enforce) enforce=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 ;;
esac
done
[ "$(id -u)" = 0 ] || { echo "run as root" >&2; exit 1; }
if [ "${1:-}" = "--remove" ]; then
if [ "$remove" = 1 ]; then
systemctl disable --now urutau-egress.service urutau-containers-map.timer urutau-logrotate.timer urutau-unban.path 2>/dev/null || true
rm -f /etc/systemd/system/urutau-egress.service /etc/systemd/system/urutau-containers-map.service \
/etc/systemd/system/urutau-containers-map.timer /usr/local/sbin/urutau-containers-map \
@@ -52,7 +72,16 @@ systemctl restart urutau-egress.service
systemctl start urutau-containers-map.service urutau-containers-map.timer
echo "egress logging on $wan: /var/log/urutau/egress.log, map: /var/log/urutau/containers.map"
if [ "${1:-}" = "--enforce" ]; then
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.
install -d -m 0750 -o "$uid" -g adm /var/log/urutau-enforce
for f in decisions.log unban.log; do
[ -e "/var/log/urutau-enforce/$f" ] || install -m 0640 -o "$uid" -g adm /dev/null "/var/log/urutau-enforce/$f"
done
fi
if [ "$enforce" = 1 ]; then
install -d -m 0750 -o "$uid" -g adm /var/log/urutau-enforce
[ -e /var/log/urutau-enforce/decisions.log ] || install -m 0640 -o "$uid" -g adm /dev/null /var/log/urutau-enforce/decisions.log
install -m 0644 "$here/fail2ban-filter-urutau.conf" /etc/fail2ban/filter.d/urutau.conf
@@ -65,5 +94,9 @@ if [ "${1:-}" = "--enforce" ]; then
systemctl enable --now urutau-unban.path >/dev/null
fail2ban-client -t >/dev/null
fail2ban-client reload
echo "fail2ban jail 'urutau' on; mount /var/log/urutau-enforce:/logs/enforce (rw) in the container"
echo "fail2ban jail 'urutau' on; the probe container mounts /var/log/urutau-enforce:/logs/enforce (rw)"
fi
if [ "$probe" = 1 ]; then
echo "probe host ready: create the probe on the hub (urutau probes create <name>) and start deploy/probe/docker-compose.yml"
fi
+12
View File
@@ -0,0 +1,12 @@
# Variables read by deploy/probe/docker-compose.yml.
# Image tag: latest (last release), X.Y.Z (pinned) or edge (main).
URUTAU_VERSION=latest
URUTAU_PROBE_IMAGE=git.lucasrguerra.dev.br/ciberfauna/urutau-probe
# Hub address: https://... (http only for loopback or private addresses).
URUTAU_HUB=
# Name registered on the hub: urutau probes create <name>
URUTAU_PROBE_NAME=
# Token printed once by that command (urp_...). Never commit this file.
URUTAU_PROBE_TOKEN=
# Time zone of this host (fail2ban.log is local time; must match the hub's TZ).
TZ=UTC
+70
View File
@@ -0,0 +1,70 @@
# Urutau probe: one per server. It reads the host logs (read-only), sends the
# lines to the hub over HTTPS and appends the hub's ban decisions to a file. It
# opens no port: the connection goes out to the hub.
#
# urutau probes create <name> # on the hub: prints the token once
# cp .env.example .env # set URUTAU_HUB, URUTAU_PROBE_NAME, URUTAU_PROBE_TOKEN
# docker compose up -d
#
# Host kit (egress log, container map, optional fail2ban jail):
# sudo sh ../host/install.sh --probe [--enforce]
name: urutau-probe
services:
probe:
image: ${URUTAU_PROBE_IMAGE:-git.lucasrguerra.dev.br/ciberfauna/urutau-probe}:${URUTAU_VERSION:-latest}
environment:
# https://hub.example.org (plain http only to loopback or private hosts,
# e.g. http://urutau:8790 on the urutau-edge network).
URUTAU_HUB: ${URUTAU_HUB:?set URUTAU_HUB}
# The name registered on the hub with `urutau probes create`.
URUTAU_PROBE_NAME: ${URUTAU_PROBE_NAME:?set URUTAU_PROBE_NAME}
# urp_... token, shown once at creation. The hub keeps only its hash.
# Alternatively mount a file and set URUTAU_PROBE_TOKEN_FILE.
URUTAU_PROBE_TOKEN: ${URUTAU_PROBE_TOKEN:-}
URUTAU_STATE_DIR: /state
# Sources: a path turns it on, empty turns it off. Missing files wait.
URUTAU_TRAEFIK_LOG: ${URUTAU_TRAEFIK_LOG-/logs/traefik/access.log}
URUTAU_AUTH_LOG: ${URUTAU_AUTH_LOG-/logs/host/auth.log}
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}
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.
# Empty ignores that kind of command.
URUTAU_ENFORCE_LOG: ${URUTAU_ENFORCE_LOG-/logs/enforce/decisions.log}
URUTAU_ENFORCE_UNBAN_LOG: ${URUTAU_ENFORCE_UNBAN_LOG-/logs/enforce/unban.log}
# Disk spool while the hub is unreachable; the oldest batches go first
# when it fills, and the loss is counted and shown on the hub.
URUTAU_PROBE_SPOOL_MAX: ${URUTAU_PROBE_SPOOL_MAX:-64MiB}
# Match the host: fail2ban.log timestamps are local time.
TZ: ${TZ:-UTC}
volumes:
# Directories, not single files: logrotate recreates files by rename and a
# file bind mount would keep following the old inode.
- /data/coolify/proxy/logs:/logs/traefik:ro
- /var/log/urutau:/logs/host:ro
- /etc/resolv.conf:/logs/resolv.conf:ro
# Decisions of the second firewall (read-write), only for ENFORCE=observe|on
# on the hub; needs deploy/host/install.sh --probe --enforce.
- /var/log/urutau-enforce:/logs/enforce
- urutau-probe-state:/state
group_add: ["4"] # adm: can read the logs in /var/log/urutau
read_only: true
cap_drop: [ALL]
security_opt:
- no-new-privileges:true
mem_limit: 64m # the probe stays under 20 MB of RSS
cpus: 0.25
restart: unless-stopped
# Only if the hub is the urutau service on the same host (internal address
# http://urutau:8790): join its network (create it with the hub's compose).
# networks: [urutau-edge]
volumes:
urutau-probe-state:
# networks:
# urutau-edge:
# external: true
+10 -32
View File
@@ -1,9 +1,11 @@
# Urutau: reads the Traefik access log, sshd auth log and fail2ban log of the
# host (read-only), classifies what it sees and serves the dashboard.
# Urutau hub: serves the dashboard and the API and receives the lines that the
# probes (one per server, see deploy/probe/docker-compose.yml) send over HTTPS.
# The hub reads no log file and mounts none.
#
# cp .env.example .env # set URUTAU_TOKEN (openssl rand -base64 48)
# docker compose pull && docker compose up -d # operators: published image
# docker compose up -d --build # developers: local build
# docker compose exec urutau urutau probes create <name> # token for a new probe
name: urutau
services:
@@ -14,18 +16,9 @@ services:
# Required: the service refuses to start without it (32+ characters and
# 128+ bits of entropy). Alternatively mount a file and set URUTAU_TOKEN_FILE.
URUTAU_TOKEN: ${URUTAU_TOKEN:-}
URUTAU_AUTH_LOG: /logs/host/auth.log
URUTAU_FAIL2BAN_LOG: /logs/host/fail2ban.log
URUTAU_NAME: ${URUTAU_NAME:-urutau}
# Your own servers: their events are dropped entirely (comma separated CIDRs/IPs).
URUTAU_TRUSTED: ${URUTAU_TRUSTED:-}
# Federation: other instances this one aggregates, e.g. hostinger=https://urutau.example.org
URUTAU_PEERS: ${URUTAU_PEERS:-}
# Shared secret for federation (32+ characters, different from URUTAU_TOKEN);
# it only opens /api/v1/peer/export. Empty disables the export.
URUTAU_PEER_TOKEN: ${URUTAU_PEER_TOKEN:-}
# Only these source networks may call the export (empty: any with the token).
URUTAU_PEER_ALLOW: ${URUTAU_PEER_ALLOW:-}
# Reverse proxies whose X-Forwarded-For is trusted. Only the dedicated
# urutau-edge network below, which holds nothing but this service and the
# reverse proxy: any other container there could forge client IPs.
@@ -38,41 +31,26 @@ services:
URUTAU_ADMIN_USERS: ${URUTAU_ADMIN_USERS:-}
# Geo database refresh interval (0 disables the download).
URUTAU_GEO_UPDATE: ${URUTAU_GEO_UPDATE:-24h}
# Port probes logged by the host kit (deploy/host/install.sh); empty disables.
URUTAU_PROBE_LOG: ${URUTAU_PROBE_LOG:-/logs/host/probe.log}
# Download the official Tor exit/relay lists (on|off).
URUTAU_TOR_AUTO: ${URUTAU_TOR_AUTO:-on}
# Second firewall: off | observe | on. "on" appends ban decisions to
# /logs/enforce/decisions.log, applied by the host fail2ban jail "urutau"
# (install the kit with deploy/host/install.sh --enforce and uncomment the
# /logs/enforce volume below).
# Second firewall: off | observe | on. "on" queues ban decisions for the
# probe of each server, which appends them to its decisions.log, applied by
# the host fail2ban jail "urutau" (install the kit with
# deploy/host/install.sh --probe --enforce on every probe host).
URUTAU_ENFORCE: ${URUTAU_ENFORCE:-off}
URUTAU_ENFORCE_SHARE: ${URUTAU_ENFORCE_SHARE:-off}
URUTAU_ENFORCE_THRESHOLD: ${URUTAU_ENFORCE_THRESHOLD:-5}
# Outbound traffic analysis (auto | on | off) from the kit's nftables log.
# Outbound traffic analysis (auto | on | off) from the egress log each probe sends.
URUTAU_EGRESS: ${URUTAU_EGRESS:-auto}
# name=container-prefix:role, comma separated (see docs/configuration.md).
URUTAU_EGRESS_WORKLOADS: ${URUTAU_EGRESS_WORKLOADS:-}
URUTAU_EGRESS_RESOLVERS: ${URUTAU_EGRESS_RESOLVERS:-}
# Match the host time zone: fail2ban.log timestamps are local time.
# Match the probes' time zone: fail2ban.log timestamps are local time and the hub parses them.
TZ: ${TZ:-UTC}
ports:
- "${URUTAU_PUBLISH:-127.0.0.1:8790}:8790"
volumes:
# Only a dedicated Traefik log directory, never the whole proxy directory
# (it holds acme.json and the dynamic configuration). Point Traefik's
# accesslog.filepath at /traefik/logs/access.log, which Coolify keeps in
# /data/coolify/proxy/logs on the host.
- /data/coolify/proxy/logs:/logs/traefik:ro
# A dedicated host directory holding only the sshd and fail2ban logs
# (rsyslog copies sshd there; fail2ban's logtarget points there). A
# directory, not single files: logrotate recreates them by rename, and a
# file bind mount would keep following the old inode. See docs/docker.md.
- /var/log/urutau:/logs/host:ro
# Second firewall decisions (read-write), only with URUTAU_ENFORCE=observe|on:
# - /var/log/urutau-enforce:/logs/enforce
- urutau-data:/data
group_add: ["4"] # adm: can read the logs in /var/log/urutau
networks: [urutau-edge]
read_only: true
cap_drop: [ALL]
+61 -29
View File
@@ -2,11 +2,11 @@
# Architecture
Urutau is one Go binary with no third-party dependency. Everything runs in one process.
Urutau is one Go binary with no third-party dependency. It runs in two roles: the **hub**, which holds the data and serves the dashboard and the API, and the **probe**, a tiny process on each monitored server that only reads log files and sends them to the hub. The same binary does both (`urutau serve` and `urutau probe`); a separate scratch image carries the probe.
```
cmd/urutau entry point: serve, doctor, healthcheck, version
internal/app flags, wiring, the log runner, probe source, Tor lists, enforce and egress wiring, doctor
cmd/urutau entry point: serve (hub), probe, probes, import, doctor, healthcheck, version
internal/app flags, wiring, the log runner (fed by the probes), probe-log parser, Tor lists, enforce and egress wiring, import, doctor
internal/tail rotation-aware file follower and rotated-file reader
internal/core event model, parsers (Traefik JSON and text, sshd, fail2ban), classifier, error classes
internal/store in-memory state, summaries, merge, snapshot, analytics, services, defense, roster
@@ -18,7 +18,10 @@ internal/ua User-Agent parser (browser, system, device, bot, attack to
internal/enforce second firewall: ban decisions, decision file, unban requests, operator allowances
internal/egress outbound connection analysis: workloads, findings (beacon, C2, mining, scan...)
internal/incidents tickets opened from egress findings or by hand, stored in incidents.json
internal/fed hub that polls peers, live relay, study merge, decision and egress exchange
internal/hub one node per probe: ingestion, commands queue, probe registry (probes.json)
internal/wire probe-hub protocol: messages, limits, command-line validation
internal/probeagent the probe: tailers, spool, client, command application
internal/fed in-process aggregation of the nodes (summaries, IP tables, live, study, geography)
internal/server HTTP handler, auth, API routes, HTML report, embedded dashboard (web/)
deploy/host host kit: nftables table, rsyslog, logrotate, container map, fail2ban jail, installer
```
@@ -28,9 +31,17 @@ The only dependency is the Go standard library.
## Data flow
```
Traefik access.log auth.log fail2ban.log probe.log (nft, closed ports)
│ │ │ │
└──── tail.Follower (one goroutine per source) ┘
── on each monitored server: the probe (urutau probe) ──────────────────────
Traefik access.log auth.log fail2ban.log probe.log egress.log
│ │ │ │ │
└──── tail.Follower (one goroutine per source, rotation-aware) ┘
containers.map and resolv.conf: whole file when it changes (sha256)
▼
batch (up to 5000 lines / 1 MiB / 1 s) ──► disk spool ──► HTTPS push
│
── on the hub (urutau serve) ───────────────────────────────────────▼─────
one node per probe (own store, evlog, incidents, enforce, egress)
offset check (inode or end > saved offset) ──► duplicate lines dropped
▼
parse (core.ParseTraefik / ParseAuth / ParseFail2ban / probe parser) → Event
▼
@@ -43,21 +54,23 @@ The only dependency is the Go standard library.
intel (computed on demand): family, MITRE, network type, cadence, sessions,
campaigns, verdict ──► dashboard, API, STIX, blocklist, HTML report
▼
enforce (optional): decision per attacking IP ──► decisions.log
enforce (optional): decision per attacking IP ──► command queue of the node
▼
probe long-poll receives it, validates the line, appends to decisions.log
▼
host fail2ban jail "urutau" reads decisions.log and bans in the firewall
▼
fail2ban.log "Ban urutau" returns as an event (not counted as evidence)
egress.log (nft, new outbound connections) ──► egress.Source ──► findings
egress lines ──► egress.Source ──► findings
findings ──► incidents (tickets INC-n, suppression) ──► API and report
```
Snapshot every 60 s: `state` ◄──► summaries, IP table, SSE. The second firewall never gains privileges: it only appends lines to a file that a jail on the host reads.
Snapshot every 60 s: `state` ◄──► summaries, IP table, SSE. Neither the hub nor the probe gains privileges: the probe only appends lines to a file that a jail on the host reads, and only after validating that each line has exactly the shape the hub's ban code produces.
## Sources
Each source is followed by its own goroutine and reports a state: `following`, `waiting` (the file does not exist yet), `backfill` (first start, reading rotated copies), `degraded` (more than 20% of the last 1000 lines are unreadable, with at least 50 samples) or `error`. A line larger than 64 KiB is dropped and counted as malformed. On the first start without a snapshot, the rotated copies (`path.1`, `path.N.gz` up to 9) are read oldest first so the window is not empty.
Each source is followed by its own goroutine **in the probe** and the hub reports its state: `following`, `waiting` (the file does not exist yet), `backfill` (first start, reading rotated copies), `degraded` (more than 20% of the last 1000 lines are unreadable, with at least 50 samples) or `error`. A line larger than 64 KiB is dropped and counted as malformed. On the first start without a snapshot, the rotated copies (`path.1`, `path.N.gz` up to 9) are read oldest first so the window is not empty.
Lines are decoded as follows:
@@ -66,7 +79,7 @@ Lines are decoded as follows:
- **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.
- **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 are never exposed: neither the dashboard nor a peer export shows where a source reads from, only its name and state.
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.
Lines that are valid but carry nothing to record are ignored silently; lines that cannot be parsed are counted as malformed and shown per source in the dashboard.
@@ -152,7 +165,7 @@ This is why the number differs from Coolify's analytics, which counts every dist
`<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.
What enters: malicious events (scanner, exploit, bruteforce, ssh-fail, ssh-probe), ban and unban, successful SSH logins, a 404 answered to an attack tool, and `ok` or `notfound` answers only for addresses that are already suspicious or hostile (to show what they got). Never a legitimate visitor. Events relayed from peers are registered with the peer name as host.
What enters: malicious events (scanner, exploit, bruteforce, ssh-fail, ssh-probe), ban and unban, successful SSH logins, a 404 answered to an attack tool, and `ok` or `notfound` answers only for addresses that are already suspicious or hostile (to show what they got). Never a legitimate visitor. Each event is registered with the name of the probe that sent it as host.
Failure behavior: a full disk, the size cap or the day cap drop events (counted, logged at most once in a while, never fatal); a corrupted line is skipped when reading; a partial line left by an earlier failure is terminated before the next write.
@@ -211,7 +224,7 @@ Rules (the first that matches, per address):
A sweep every 10 minutes, and after the start-up backfill, applies the same rules to the addresses active in the last 24 hours that nothing blocks yet. At most `--enforce-max-per-min` decisions are written per minute (default 60); the excess is dropped and counted. The advisory TTL grows with the number of earlier bans: 1 h, 6 h, 24 h, 7 d.
Never banned: private and reserved ranges, `--trusted`, the Cloudflare ranges, well known public resolvers, the peers and the server's own addresses, a verified crawler, an address with a legitimate visit in the last 24 hours, and an operator allowance (below). Each skip is counted by reason.
Never banned: private and reserved ranges, `--trusted`, the Cloudflare ranges, well known public resolvers, the addresses of the probes and the servers' own addresses, a verified crawler, an address with a legitimate visit in the last 24 hours, and an operator allowance (below). Each skip is counted by reason.
Decision file, one line per ban (`MaxLogBytes` 20 MB, then rotated to `.1`):
@@ -223,7 +236,7 @@ Nothing the attacker controls enters the line: the address is re-formatted, the
Unban: `POST /api/v1/enforce/unban` appends `<time> urutau unban ip=<ip> allow=<seconds>` to the unban file (`--enforce-unban-log`, by default `unban.log` next to the decision file); a systemd path unit of the host kit lifts the fail2ban block. With `allow` above zero the engine does not ban the address again for that long (at most 30 days); `DELETE /api/v1/enforce/allow` ends the allowance.
Sharing (`--enforce-share=on`): hub and peers exchange decisions through `GET` and `POST /api/v1/peer/decisions` and unbans through `POST /api/v1/peer/unban`. Each side applies its own exclusions, accepts only the fixed reason slugs, caps the TTL at 6 hours, and bans on a peer's word only an address it also saw attacking in the last 7 days (otherwise the skip is `peer_unconfirmed`).
Sharing (`--enforce-share=on`): a decision taken by the node of one probe is also queued for the nodes of the others. Each node applies its own exclusions, accepts only the fixed reason slugs, caps the TTL at 6 hours, and bans on another node's word only an address it also saw attacking in the last 7 days (otherwise the skip is `peer_unconfirmed`).
## Egress analysis
@@ -244,7 +257,7 @@ Findings (`kind`, severity):
| `scan` | fan-out of more than 50 destinations or 100 ports in 10 minutes, outside `scanner` workloads |
| `new_geo` | first contact with a country after the workload's learning time (24 h) |
Destinations of peers, trusted addresses and the server's own public addresses never raise findings, and regular connections to large CDNs and clouds are low severity unless the destination attacked the server. Limits: 50,000 pairs and destinations, 2,000 findings, 720 hourly buckets. `GET /api/v1/egress` returns the findings, workloads, countries and an hourly timeline; a hub also merges the `GET /api/v1/peer/egress` answer of each peer.
Destinations of the probes, trusted addresses and the server's own public addresses never raise findings, and regular connections to large CDNs and clouds are low severity unless the destination attacked the server. Limits: 50,000 pairs and destinations, 2,000 findings, 720 hourly buckets. `GET /api/v1/egress` returns the findings, workloads, countries and an hourly timeline; the hub merges the egress report of every node. The egress settings (workloads, resolvers, allowed destinations) are kept per probe on the hub, in `probes.json`.
## Incidents
@@ -256,23 +269,39 @@ Destinations of peers, trusted addresses and the server's own public addresses n
## State and persistence
The state lives in memory: minute buckets for the latest 48 hours and hourly data up to 30 days, hourly top lists (paths, domains, User-Agents, users), a table of up to 20,000 IPs (when full, the 10% with the lowest score are evicted; banned IPs are kept), a feed of the latest 500 events and the active bans. `--retention` (1h to 720h) bounds how long IPs are kept; old IPs are pruned every 10 minutes.
Each node (one per probe) keeps its own state in memory: minute buckets for the latest 48 hours and hourly data up to 30 days, hourly top lists (paths, domains, User-Agents, users), a table of up to 20,000 IPs (when full, the 10% with the lowest score are evicted; banned IPs are kept), a feed of the latest 500 events and the active bans. `--retention` (1h to 720h) bounds how long IPs are kept; old IPs are pruned every 10 minutes.
Every 60 seconds, and on shutdown, the state is written to `urutau-state.gob` in the data directory together with the inode and offset of every source. On start it is restored and each source resumes exactly where it stopped, so a restart never counts a log twice. A snapshot is skipped while a backfill runs. An unreadable snapshot is moved to `urutau-state.gob.corrupt` and the service starts empty, reading the logs again (including the rotated copies).
Every 60 seconds, and on shutdown, each node writes its state to `urutau-state.gob` together with the inode and offset of every source. The primary node (the probe whose name equals `URUTAU_NAME`) uses the data-dir root, exactly the 1.x layout; the others use `<data-dir>/probes/<name>/`. On start the state is restored and the hub tells each probe, in the `hello`, the offsets it has, so a restart of either side never counts a line twice and never loses one. A snapshot is skipped while a backfill runs. An unreadable snapshot is moved to `urutau-state.gob.corrupt` and the service starts empty, reading the logs again (including the rotated copies).
The process sets a soft memory limit of 256 MiB unless `GOMEMLIMIT` is set. The worst case measured is about 54 MiB of heap and a snapshot of about 27 MB.
## Federation
## Probes and the hub
A hub is an ordinary instance started with `--peer name=https://url`, and it needs `URUTAU_PEER_TOKEN`. Every 15 seconds it calls each peer's `GET /api/v1/peer/export?range=...` (for the background ranges `1h`, `24h`, `7d` and `30d`; any other range or custom period is fetched on demand) with the peer token and keeps the latest answer. The export is `{"v":1,"summary":...,"traffic":{...}}` with the top 500 IPs and their detail, cached for 5 seconds on the peer. The peer token opens only the federation routes: the export, the live stream, `GET /api/v1/peer/period` (the study of sessions, campaigns and metrics the hub merges for a period or an IP; a peer runs at most two at once), `GET /api/v1/peer/egress` (the egress report) and, with `--enforce-share`, `GET` and `POST /api/v1/peer/decisions` and `POST /api/v1/peer/unban`. The hub never follows redirects, requires `https` outside loopback, uses a 4 second timeout, caps the body at 8 MB and sanitizes and caps whatever a peer sends. A peer that fails is marked offline and the others carry on. The dashboard host selector then offers `all`, the hub itself and each peer; summaries, traffic and IP tables are merged, and every row carries the host it came from.
The probe is a client of the hub: it opens no port. Plain HTTPS, no WebSocket, so any reverse proxy or CDN works (requests are short; the long-poll lasts at most 25 s). Authentication is `Authorization: Bearer urp_...` plus `X-Urutau-Probe: <name>`. The hub keeps only the SHA-256 of each token (`probes.json`) and compares in constant time; a wrong token is a bare 401 under the same attempt limiter as the login. Plain `http://` is accepted only for loopback or private addresses (for example `http://urutau:8790` on the `urutau-edge` network).
### Live relay
| Route | Purpose |
|---|---|
| `POST /api/v1/probe/hello` | start of every session: protocol version in, the offsets the hub holds out (a probe without local state starts from them). 409 on an incompatible version |
| `POST /api/v1/probe/push` | one batch (`seq`, up to 5000 lines, optional gzip, 2 MiB on the wire and 8 MiB inflated, a line of 64 KiB at most) and the probe status. The hub applies the whole batch to the node, then answers `ack = seq`; a repeated `seq` is answered without being applied again. 503 with `Retry-After` while the node loads or its queue is full, 429 for a second concurrent push |
| `GET /api/v1/probe/commands?after=<seq>&wait=<s>` | long-poll (at most 25 s) for ban and unban lines; answers at once when the queue has a command newer than `after` |
Besides the export, a hub keeps one `GET /api/v1/peer/stream` connection open per peer (a subscription per peer, with the peer's own token) and relays the live malicious events to its dashboard. What comes from a peer is bounded and sanitized: at most about 50 events per second per peer, lines of at most 16 KB, a buffer of the latest 500 relayed events (served by `/api/v1/live/recent`), and reconnection with backoff from 1 s up to 60 s. A peer serves at most 10 stream connections.
**Spool.** Before sending, the probe writes each batch to `<state-dir>/spool/NNNNNNNNNNNN.json` and sends them in order, so a hub outage loses nothing. The spool is capped by `URUTAU_PROBE_SPOOL_MAX` (64 MiB by default); beyond it the oldest batch is deleted and its lines are added to the `dropped` counter of the probe status, which the Sources page shows. `state.json` records the batch sequence, the last command applied and the read position of every source, written atomically after each ack. After an error the probe reconnects with exponential backoff from 1 s to 60 s with a 20% jitter.
**Offsets.** The hub is the authority: it keeps the offset of each source in the snapshot of the node and accepts a line only if its inode differs from the saved one or its end offset is past it. Replaying a spool, or importing a 1.x data directory (`urutau import`), therefore neither duplicates nor skips lines.
**Liveness.** With nothing to send, the probe pushes an empty batch with its status every 15 s; the hub marks it offline after 45 s without a push.
**Commands.** The hub queues up to 10,000 commands per node (`commands.json`); the oldest are dropped and counted. The probe accepts a command only if `wire.ValidCmdLine` passes (the exact format of a ban or unban line, with a valid address, reason slug and TTL), appends it with `O_APPEND` and `fsync`, and records the sequence so that a repeated command is not written twice. An invalid line is counted in `cmd_errors` and never written. A probe whose `URUTAU_ENFORCE_LOG` is empty ignores ban commands and counts the error.
**Footprint.** The probe never calls geolocation, intelligence or the store; its memory target is under 20 MB of RSS, checked by a test, and its image is under 15 MB.
### Aggregation across probes
`internal/fed` joins the nodes in the process (no HTTP any more): the dashboard host selector offers `all` and each probe; summaries, traffic, IP tables, studies and the live feed merge the nodes and every row carries the host it came from. An incident is identified as `host/INC-n` (each node numbers its own); a bare `INC-n` means the primary node.
### Geography aggregation
`GET /api/v1/geo` is computed from the IP table (local and the peers' exports) joined with the geolocation databases: countries first, then, for one country, its regions, cities and top IPs. Results are cached for 5 seconds, in a cache of at most 256 keys.
`GET /api/v1/geo` is computed from the IP table (of every node) joined with the geolocation databases: countries first, then, for one country, its regions, cities and top IPs. Results are cached for 5 seconds, in a cache of at most 256 keys.
## HTTP layer
@@ -280,7 +309,7 @@ The server sets read, write and idle timeouts, `MaxHeaderBytes` of 16 KB, caps `
## API routes
All `/api/v1/*` routes except the federation ones need `URUTAU_TOKEN` (bearer) or a session cookie; the peer token gets 403 on them. Analysis routes live in `internal/server/api_<name>.go` files and register themselves with `registerUserRoute`. Routes that take a range accept `range`, or `from` and `to`.
The user routes under `/api/v1/*` need `URUTAU_TOKEN` (bearer) or a session cookie; the `/api/v1/probe/*` routes need a probe token and nothing else opens them. The 1.x `/api/v1/peer/*` routes no longer exist (404). Analysis routes live in `internal/server/api_<name>.go` files and register themselves with `registerUserRoute`. Routes that take a range accept `range`, or `from` and `to`.
| Route | Purpose |
|---|---|
@@ -299,8 +328,8 @@ All `/api/v1/*` routes except the federation ones need `URUTAU_TOKEN` (bearer) o
| `GET /api/v1/egress` | outbound findings |
| `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/peer/export`, `/peer/stream`, `/peer/period`, `/peer/egress` | federation, peer token only |
| `GET`, `POST /api/v1/peer/decisions`, `POST /api/v1/peer/unban` | decision sharing, peer token only, `--enforce-share` |
| `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) |
| `POST /api/v1/probe/hello`, `/probe/push`, `GET /probe/commands` | probe protocol, probe token only |
List endpoints (IPs, sessions, campaigns, events of an address) are paginated by the backend; event search pages by cursor.
@@ -308,11 +337,14 @@ List endpoints (IPs, sessions, campaigns, events of an address) are paginated by
| Where | What |
|---|---|
| `<data-dir>/urutau-state.gob` | state snapshot with the offset of every source (`.corrupt` when unreadable) |
| `<data-dir>/urutau-state.gob` | snapshot of the primary node with the offset of every source (`.corrupt` when unreadable) |
| `<data-dir>/probes/<name>/` | the same layout (snapshot, `events/`, `incidents.json`, `enforce.json`, `commands.json`) for every other probe |
| `<data-dir>/probes.json` | registry of probes: name, SHA-256 of the token, location, egress settings (never the token) |
| `<data-dir>/events/YYYY-MM-DD.jsonl[.gz]` | event registry, one JSON line per event |
| `<data-dir>/geo/` | DB-IP Lite city and ASN databases |
| `<data-dir>/tor/` | cache of the Tor exit and relay lists |
| `<data-dir>/enforce.json` | state of the second firewall |
| `<data-dir>/incidents.json` | tickets |
| `--enforce-log`, `unban.log` | decision file read by the host jail and unban requests read by the host |
| `--probe-log`, `--egress-log`, `--egress-containers` | kernel logs and container map written by the host kit in `deploy/host` |
| `<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` |
+70 -29
View File
@@ -3,26 +3,27 @@
# Terminal
```
urutau serve [flags] run the daemon and the dashboard
urutau serve [flags] run the hub: dashboard, API and probe ingestion (alias: urutau hub)
urutau probe [flags] run a probe: read local logs and send them to the hub
urutau probes create|list|revoke manage the probes registered on a hub
urutau import --from DIR --host NAME bring a 1.x data directory into a hub
urutau doctor [--json] [flags] check the sources and the data directory
urutau healthcheck [flags] exit 0 when the local daemon answers /api/health
urutau version print the version
urutau help print the usage
```
The access token is never a flag: `urutau serve` reads it from the `URUTAU_TOKEN` environment variable, or from the file named by `URUTAU_TOKEN_FILE`, so it does not show up in the process list. Tokens need at least 32 characters and about 128 bits of estimated entropy (length times Shannon entropy; periodic or sequential tokens are refused) (`openssl rand -base64 48` is recommended (`-hex 32` also works)). Every flag below has a `URUTAU_*` environment default; a flag wins over the variable. See [configuration.md](configuration.md).
The access token is never a flag: `urutau serve` and `urutau probe` read theirs (`URUTAU_TOKEN` and `URUTAU_PROBE_TOKEN`) from the environment variable, or from the file named by the same name with `_FILE`, so it does not show up in the process list. Tokens need at least 32 characters and about 128 bits of estimated entropy (length times Shannon entropy; periodic or sequential tokens are refused) (`openssl rand -base64 48` is recommended (`-hex 32` also works)). Every flag below has a `URUTAU_*` environment default; a flag wins over the variable. See [configuration.md](configuration.md).
## `urutau serve`
The hub reads no log file: the lines come from the probes ([architecture.md](architecture.md#probes-and-the-hub)). The 1.x log path flags (`--traefik-log`, `--auth-log`, `--fail2ban-log`, `--probe-log`, `--egress-log`, `--egress-containers`, `--enforce-log`, `--enforce-unban-log`) and the federation flags (`--peer*`) were removed; the hub refuses to start when their `URUTAU_*` variables are set, and the message points to [migration-2.0.md](migration-2.0.md).
| Flag | Variable | Default | Meaning |
|---|---|---|---|
| `--bind` | `URUTAU_BIND` | `0.0.0.0:8790` | listen address |
| `--name` | `URUTAU_NAME` | hostname | name of this instance |
| `--data-dir` | `URUTAU_DATA_DIR` | `/data` | state directory: snapshot `urutau-state.gob`, `geo/`, `tor/`, `events/`, `incidents.json`, `enforce.json` |
| `--traefik-log` | `URUTAU_TRAEFIK_LOG` | `/data/coolify/proxy/access.log` | Traefik JSON access log; empty disables |
| `--auth-log` | `URUTAU_AUTH_LOG` | `/var/log/auth.log` | sshd log; empty disables |
| `--fail2ban-log` | `URUTAU_FAIL2BAN_LOG` | `/var/log/fail2ban.log` | fail2ban log; empty disables |
| `--probe-log` | `URUTAU_PROBE_LOG` | `/logs/host/probe.log` | kernel log of connections to unserved ports, written by the host kit; empty disables |
| `--name` | `URUTAU_NAME` | hostname | name of this instance, and of the primary probe: the one whose data lives in the data-dir root |
| `--data-dir` | `URUTAU_DATA_DIR` | `/data` | state directory: snapshot `urutau-state.gob`, `geo/`, `tor/`, `events/`, `incidents.json`, `enforce.json` of the primary probe, `probes/<name>/` of the others, `probes.json` |
| `--trusted` | `URUTAU_TRUSTED` | empty | CIDRs of trusted origins; their events are dropped entirely. `--ignore` / `URUTAU_IGNORE` is an alias |
| `--ignore` | `URUTAU_IGNORE` | `127.0.0.0/8,::1,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,fc00::/7,fe80::/10,100.64.0.0/10,169.254.0.0/16` | same effect as `--trusted`, with the private ranges as default |
| `--monitor-ua` | `URUTAU_MONITOR_UA` | `(?i)^(Uptime-Kuma/\|Beszel\|Coolify\|kube-probe/\|Go-http-client/.*healthcheck)` | regular expression of monitoring User-Agents |
@@ -30,42 +31,82 @@ The access token is never a flag: `urutau serve` reads it from the `URUTAU_TOKEN
| `--domains` | `URUTAU_DOMAINS` | empty | allowlist of analytics domains (exact or `*.example.com`); empty tracks every domain that answers 2xx; recommended when a backend answers 2xx for any Host |
| `--geo-dir` | `URUTAU_GEO_DIR` | `<data-dir>/geo` | directory of the DB-IP Lite databases (city and ASN) |
| `--geo-update` | `URUTAU_GEO_UPDATE` | `24h` | how often to check for a newer database; `0` turns the download off |
| `--peer` | `URUTAU_PEERS` | none | peer `name=https://url`; repeat the flag, or comma separate the variable (the flag wins) |
| `--peer-token` | `URUTAU_PEER_TOKEN` | empty | token shared with the peers; prefer the variable or `URUTAU_PEER_TOKEN_FILE` (a flag shows up in the process list). Per-peer: `URUTAU_PEER_TOKEN_<NAME>` or `..._<NAME>_FILE` |
| `--admin-users` | `URUTAU_ADMIN_USERS` | empty | SSH users whose successful login keeps their IP out of the blocklist for 24 h; the immunity is off unless set |
| `--peer-allow` | `URUTAU_PEER_ALLOW` | empty | source CIDRs allowed to call the federation routes; empty accepts any source with the token |
| `--peer-blocklist` | `URUTAU_PEER_BLOCKLIST` | `on` | `on` lists in the hub's blocklist the hostile IPs seen only by peers (score 50+ and a strong signal); `off` keeps the blocklist to this instance's own IPs |
| `--location` | `URUTAU_LOCATION` | empty | map position of this instance, `"lat,lon"` or `"lat,lon,Label"` |
| `--trusted-proxy` | `URUTAU_TRUSTED_PROXY` | `127.0.0.0/8,::1` (the compose file sets `10.250.0.0/24`) | proxies whose `X-Forwarded-For` is trusted, read right to left (login rate limit, `--peer-allow`) |
| `--location` | `URUTAU_LOCATION` | empty | default map position of the primary probe (each probe has its own, set on the hub), `"lat,lon"` or `"lat,lon,Label"` |
| `--trusted-proxy` | `URUTAU_TRUSTED_PROXY` | `127.0.0.0/8,::1` (the compose file sets `10.250.0.0/24`) | proxies whose `X-Forwarded-For` is trusted, read right to left (login rate limit, probe auth limiter) |
| `--retention` | `URUTAU_RETENTION` | `720h` | how long data is kept (1h to 720h, that is 30 days) |
| `--events-max` | `URUTAU_EVENTS_MAX` | `512MB` | size cap of the event registry in `<data-dir>/events`; `0` turns it off |
| `--tor-auto` | `URUTAU_TOR_AUTO` | `on` | `on` downloads the official Tor exit and relay lists every 6 h into `<data-dir>/tor`; `off` does not |
| `--tor-exits` | `URUTAU_TOR_EXITS` | empty | file with Tor exit addresses, one per line, reloaded every 24 h when it changes; empty disables |
| `--enforce` | `URUTAU_ENFORCE` | `off` | second firewall: `off`, `observe` (decide in memory only) or `on` (also write decisions for the host fail2ban) |
| `--enforce-log` | `URUTAU_ENFORCE_LOG` | `/logs/enforce/decisions.log` | decision file appended in `on` mode (required then) |
| `--enforce-unban-log` | `URUTAU_ENFORCE_UNBAN_LOG` | `unban.log` next to `--enforce-log` | file the Unban button writes its requests to |
| `--enforce-share` | `URUTAU_ENFORCE_SHARE` | `off` | `on` exchanges decisions and unbans with the peers; each side applies its own exclusions |
| `--enforce-share` | `URUTAU_ENFORCE_SHARE` | `off` | `on` also queues a decision taken for one probe on the others; each node applies its own exclusions |
| `--enforce-threshold` | `URUTAU_ENFORCE_THRESHOLD` | `5` | attack events in 10 minutes that justify a ban (1 to 1000) |
| `--enforce-max-per-min` | `URUTAU_ENFORCE_MAX_PER_MIN` | `60` | most decisions per minute, the excess is dropped and counted (1 to 10000) |
| `--egress` | `URUTAU_EGRESS` | `auto` | egress analysis: `auto` (on when `--egress-log` exists), `on` or `off` |
| `--egress-log` | `URUTAU_EGRESS_LOG` | `/logs/host/egress.log` | kernel log of new outbound connections, written by the host kit |
| `--egress-containers` | `URUTAU_EGRESS_CONTAINERS` | `/logs/host/containers.map` | `"<ip> <container>"` map written by the host kit |
| `--egress-workloads` | `URUTAU_EGRESS_WORKLOADS` | empty | `"name=ITEM,ITEM:role;..."`, roles `default`, `scanner`, `mail`, `resolver` ([configuration.md](configuration.md#egress-analysis)) |
| `--egress-resolvers` | `URUTAU_EGRESS_RESOLVERS` | empty | allowed DNS resolvers, comma separated; empty: the usual public ones plus the host's `resolv.conf` |
| `--egress` | `URUTAU_EGRESS` | `auto` | egress analysis: `auto` (on for a probe that sends an egress log), `on` or `off` |
| `--egress-workloads` | `URUTAU_EGRESS_WORKLOADS` | empty | default for the primary probe (per probe, edit them on the hub): `"name=ITEM,ITEM:role;..."`, roles `default`, `scanner`, `mail`, `resolver` ([configuration.md](configuration.md#egress-analysis)) |
| `--egress-resolvers` | `URUTAU_EGRESS_RESOLVERS` | empty | allowed DNS resolvers, comma separated; empty: the usual public ones plus the `resolv.conf` the probe sends |
| `--insecure-no-auth` | none | off | disable authentication; only on a loopback bind |
`URUTAU_EGRESS_ALLOW` and `URUTAU_EGRESS_PROVIDER_ASN` exist only as environment variables ([configuration.md](configuration.md)). `GOMEMLIMIT` and `TZ` are the standard ones.
Validation at start (any failure exits with code 1 before listening): `URUTAU_TOKEN` and every peer token need at least 32 characters and about 128 bits of estimated entropy (periodic or sequential tokens are refused), and a peer token must differ from `URUTAU_TOKEN`, unless `--insecure-no-auth` on a loopback bind; peers must be `name=https://host` (plain `http` only on loopback), names unique and not `all` or the instance's own name, and each peer needs a client token (`URUTAU_PEER_TOKEN_<NAME>` or the general `URUTAU_PEER_TOKEN`), with no two names collapsing to the same variable; `--retention` from 1h to 720h; `--events-max` a valid size; `--location` valid; `--peer-blocklist`, `--enforce-share` `on`/`off`; `--enforce` `off`/`observe`/`on` (`on` needs `--enforce-log`); `--enforce-threshold` 1 to 1000 and `--enforce-max-per-min` 1 to 10000; `--egress` `auto`/`on`/`off`; `--monitor-ua` a valid regular expression; `--ignore`, `--trusted`, `--peer-allow`, `--trusted-proxy` and `--monitor-from` valid CIDRs or IPs.
Validation at start (any failure exits with code 1 before listening): `URUTAU_TOKEN` needs at least 32 characters and about 128 bits of estimated entropy (periodic or sequential tokens are refused), unless `--insecure-no-auth` on a loopback bind; none of the removed 1.x variables may be set; `--retention` from 1h to 720h; `--events-max` a valid size; `--location` valid; `--enforce-share` `on`/`off`; `--enforce` `off`/`observe`/`on`; `--enforce-threshold` 1 to 1000 and `--enforce-max-per-min` 1 to 10000; `--egress` `auto`/`on`/`off`; `--monitor-ua` a valid regular expression; `--ignore`, `--trusted`, `--trusted-proxy` and `--monitor-from` valid CIDRs or IPs.
```bash
export URUTAU_TOKEN=$(openssl rand -base64 48)
urutau serve --bind 127.0.0.1:8790 --data-dir ./data \
--traefik-log "" --auth-log /var/log/auth.log
urutau serve --bind 127.0.0.1:8790 --data-dir ./data
```
The daemon logs to stderr, saves a snapshot on `SIGTERM` or `SIGINT` and exits 0 on a clean stop.
## `urutau probe`
The probe runs on each monitored server. It opens no port: it follows the log files, spools them to disk and pushes them to the hub over HTTPS, and applies the ban and unban commands the hub sends ([architecture.md](architecture.md#probes-and-the-hub)). Flags and variables, all with the same rules as `serve`:
| Flag | Variable | Default | Meaning |
|---|---|---|---|
| `--hub` | `URUTAU_HUB` | required | hub URL; `https://`, or `http://` only for loopback and private addresses |
| `--name` | `URUTAU_PROBE_NAME` | required | name registered on the hub |
| none | `URUTAU_PROBE_TOKEN` or `URUTAU_PROBE_TOKEN_FILE` | required | token printed once by `urutau probes create` (`urp_...`); never a flag |
| `--state-dir` | `URUTAU_STATE_DIR` | `/state` | spool, positions and liveness mark |
| `--traefik-log` | `URUTAU_TRAEFIK_LOG` | `/logs/traefik/access.log` | Traefik access log; empty disables |
| `--auth-log` | `URUTAU_AUTH_LOG` | `/logs/host/auth.log` | sshd log; empty disables |
| `--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 |
| `--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 |
| `--enforce-unban-log` | `URUTAU_ENFORCE_UNBAN_LOG` | `/logs/enforce/unban.log` | where unban requests are appended; empty ignores them |
| `--spool-max` | `URUTAU_PROBE_SPOOL_MAX` | `64MiB` | spool cap; the oldest batches are dropped and counted |
| `--location` | `URUTAU_LOCATION` | empty | `"lat,lon,Label"`; the hub's setting prevails |
`urutau probe --check` reads the liveness mark in the state directory and exits 0 when the probe is alive; it is the `HEALTHCHECK` of the probe image, which has no shell. A missing hub, name or token stops the probe at start with a clear message.
## `urutau probes`
Manages the registry (`<data-dir>/probes.json`) of a hub. Without `--url` it works directly on the data directory (stop the hub first or expect the hub to reload on the next change); with `--url` and the user token it uses the API.
```bash
urutau probes create oracle # prints the token ONCE; the hub stores only its SHA-256
urutau probes list # name, state, last line, lag, version, dropped
urutau probes revoke hostinger # the probe is refused from now on; its data is kept
```
Names are 1 to 32 characters: lowercase letters, digits and `-`, starting with a letter or digit (the name is also the data subdirectory). The page Sources of the dashboard does the same and also edits the location and the egress settings of each probe.
## `urutau import`
Brings the data directory of a 1.x instance into a hub as one probe, losing nothing ([migration-2.0.md](migration-2.0.md)).
```bash
urutau import --from /backup/hostinger/data --host hostinger --dry-run # what would be copied
urutau import --from /backup/hostinger/data --host hostinger # with the hub stopped
urutau import --verify --from /backup/hostinger/data --host hostinger # compare hashes and counts
urutau import --count /data # print events, IPs, incidents, bans
```
It copies the whole directory through a temporary directory and an atomic rename, checks every SHA-256 and the counts, and is idempotent (a second run reports `skipped`). A different destination fails unless `--force`, which moves it to `.bak-<timestamp>` and never deletes. It refuses to run while the hub holds the data-dir lock.
## Noise and monitoring
```bash
@@ -79,11 +120,11 @@ urutau serve --trusted "10.0.0.0/8,203.0.113.7" \
```bash
urutau serve --enforce observe # decide in memory, write nothing
urutau serve --enforce on --enforce-log /var/log/urutau-enforce/decisions.log
urutau serve --egress on --egress-workloads "mail=10.0.7.0/24:mail"
urutau serve --enforce on # decisions travel to the probes; each appends them to its decisions.log
urutau serve --egress on --egress-workloads "mail=10.0.7.0/24:mail" # primary probe; others: Sources page
```
The host side (nftables logging, the `urutau` fail2ban jail) comes from `deploy/host/install.sh`, see [docker.md](docker.md#host-kit).
The host side (nftables logging, the `urutau` fail2ban jail) comes from `deploy/host/install.sh --probe`, see [docker.md](docker.md#host-kit).
## Geolocation
@@ -95,7 +136,7 @@ Urutau downloads the DB-IP Lite city and ASN databases into `--geo-dir` when the
## `urutau doctor`
Checks the configuration (token, peers, bind and every validation above), each log source (readable, size; Traefik also for a malformed-line rate above 20%), that the data directory is writable, the second firewall, the geolocation databases and the snapshot. The probe and egress logs are not checked. Checks are named `config`, `source traefik`, `source ssh`, `source fail2ban`, `source traefik format`, `data-dir`, `enforce` (and `enforce-cdn`), `geo` and `state`. Statuses are `ok`, `warn` (a source that cannot be opened yet), `fail` and `off` (disabled). The exit code is 1 when any check is `fail` (for example `--enforce=on` with a decision file that is not writable), which makes it usable in a deploy script. It accepts the same flags as `serve`.
Checks the configuration (token, bind and every validation above), that the data directory is writable, the registered probes and their state, the second firewall, the geolocation databases and the snapshot. The hub has no log source to check: what a probe reads is reported by the probe itself on the Sources page. Checks are named `config`, `data-dir`, `probes`, `enforce` (and `enforce-cdn`), `geo` and `state`. Statuses are `ok`, `warn` (a probe offline), `fail` and `off` (disabled). The exit code is 1 when any check is `fail` (for example `--enforce=on` with a decision file that is not writable), which makes it usable in a deploy script. It accepts the same flags as `serve`.
```bash
urutau doctor
+53 -42
View File
@@ -10,38 +10,30 @@ Urutau has no configuration file. Everything is a flag with a `URUTAU_*` environ
|---|---|
| `URUTAU_TOKEN` | **Required.** Access token of the dashboard and the API: at least 32 characters and about 128 bits of estimated entropy (length times Shannon entropy; periodic or sequential tokens are refused). Generate one with `openssl rand -base64 48` (`openssl rand -hex 32` also works; `-hex 16` is refused by the entropy estimate). |
| `URUTAU_TOKEN_FILE` | Path of a file holding the token (whitespace trimmed), instead of the variable. The variable wins when both are set. |
| `URUTAU_PEER_TOKEN` | Optional. The server token of this instance: the only token its federation routes (see [Peers](#peers-hub-mode)) accept, and it opens nothing else. Same strength rules as `URUTAU_TOKEN` (32+ characters, about 128 bits of estimated entropy, not periodic or sequential), and it must differ from it. When this instance is a hub, it is also the fallback client token sent to peers that have no token of their own. |
| `URUTAU_PEER_TOKEN_FILE` | Path of a file holding the general peer token. |
| `URUTAU_PEER_TOKEN_<NAME>` and `..._<NAME>_FILE` | The client credential a hub sends to that one peer; it must equal the peer's own `URUTAU_PEER_TOKEN`. `<NAME>` is the peer name uppercased with every character other than a letter or digit turned into `_` (`my-peer` becomes `MY_PEER`). It does **not** open the local export. Two peer names that collapse to the same variable (`my-peer` and `my_peer`) are refused. A hub with a peer and no token for it refuses to start. |
| `URUTAU_PROBE_TOKEN` | **Probe only, required.** The token of one probe (`urp_` plus 43 base64url characters), printed once by `urutau probes create` or by the Sources page. The hub keeps only its SHA-256 (`probes.json`), so a lost token is replaced, never recovered: revoke the probe and create it again. |
| `URUTAU_PROBE_TOKEN_FILE` | Probe only. Path of a file holding the probe token, instead of the variable. The variable wins when both are set. |
Keep both in `.env` (never versioned) or in your orchestrator's secret store.
The 1.x federation secrets (`URUTAU_PEER_TOKEN`, `URUTAU_PEER_TOKEN_FILE`, `URUTAU_PEER_TOKEN_<NAME>`) do not exist any more; the hub refuses to start when one is set ([migration-2.0.md](migration-2.0.md)).
Keep them in `.env` (never versioned) or in your orchestrator's secret store.
## Settings
Every variable below has a flag of the same meaning ([cli.md](cli.md)); the flag wins over the variable.
Settings are split by role. The **hub** (`urutau serve`) takes the variables in the sections up to [Egress](#egress); the **probe** (`urutau probe`) takes the ones in [Probe](#probe). Every variable below has a flag of the same meaning ([cli.md](cli.md)); the flag wins over the variable.
### Core
| Variable | Default | Meaning |
|---|---|---|
| `URUTAU_BIND` | `0.0.0.0:8790` | listen address |
| `URUTAU_NAME` | container hostname | name shown in the dashboard and used by the hub |
| `URUTAU_DATA_DIR` | `/data` | where the state lives: snapshot `urutau-state.gob`, `geo/`, `tor/`, `events/`, `incidents.json` and `enforce.json` |
| `URUTAU_NAME` | container hostname | name of this instance **and of the primary probe**: the probe whose name equals it keeps its data in the data-dir root (exactly the 1.x layout); every other probe uses `<data-dir>/probes/<name>/` |
| `URUTAU_DATA_DIR` | `/data` | where the state lives: snapshot `urutau-state.gob`, `geo/`, `tor/`, `events/`, `incidents.json` and `enforce.json` of the primary probe, `probes/<name>/` for the others, and `probes.json` |
| `URUTAU_RETENTION` | `720h` | retention as a Go duration, from `1h` to `720h` (30 days); other values refuse to start |
| `URUTAU_EVENTS_MAX` | `512MB` | size cap of the event registry (`<data-dir>/events`); a number with an optional unit (`k`, `kb`, `kib`, `m`, `mb`, `mib`, `g`, `gb`, `gib`, `b`), `0` turns it off |
| `URUTAU_LOCATION` | empty | where this instance is on the map, `"lat,lon"` or `"lat,lon,Label"` (validated at start). It is the destination of the arcs on the Live page and is shared with the hub; empty lets the page fall back to an estimated destination |
| `URUTAU_LOCATION` | empty | default map position of the primary probe (the others get theirs on the hub, per probe), `"lat,lon"` or `"lat,lon,Label"` (validated at start). It is the destination of the arcs on the Live page; empty lets the page fall back to an estimated destination |
| `GOMEMLIMIT` | 256 MiB soft limit | standard Go memory limit; set it to override the default |
| `TZ` | UTC | time zone of `fail2ban.log` timestamps, which carry no zone |
### Log sources
| Variable | Default | Meaning |
|---|---|---|
| `URUTAU_TRAEFIK_LOG` | `/data/coolify/proxy/access.log` | Traefik JSON access log, empty disables |
| `URUTAU_AUTH_LOG` | `/var/log/auth.log` | sshd log, empty disables |
| `URUTAU_FAIL2BAN_LOG` | `/var/log/fail2ban.log` | fail2ban log, empty disables |
| `URUTAU_PROBE_LOG` | `/logs/host/probe.log` | kernel log of new connections to ports nobody serves, written by the host kit (see [Probes](#probes-port-scans)); empty disables, a missing file just stays at `waiting` |
### Noise, trust and monitoring
| Variable | Default | Meaning |
@@ -62,23 +54,18 @@ Every variable below has a flag of the same meaning ([cli.md](cli.md)); the flag
| `URUTAU_TOR_AUTO` | `on` | `on`: download the official Tor exit and relay lists every 6 hours into `<data-dir>/tor`; `off`: do not download (air-gapped hosts) |
| `URUTAU_TOR_EXITS` | empty | file of Tor exit addresses, one per line (`#` comments allowed, at most 100000 addresses, 8 MiB), reloaded every 24 h when it changes; merged with the downloaded list |
### Federation
### Reverse proxy
| Variable | Default | Meaning |
|---|---|---|
| `URUTAU_PEERS` | empty | peers to aggregate, comma separated `name=https://url` (the flag `--peer` repeats instead) |
| `URUTAU_PEER_ALLOW` | empty | CIDRs allowed to call the federation routes; empty accepts any source that has the token |
| `URUTAU_PEER_BLOCKLIST` | `on` | `on`: the hub's blocklist includes hostile IPs seen only by peers (score 50+ and a strong signal); `off`: only this instance's own IPs. Anything else refuses to start |
| `URUTAU_TRUSTED_PROXY` | `127.0.0.0/8,::1` (the compose file sets `10.250.0.0/24`) | reverse proxies whose `X-Forwarded-For` is trusted (read right to left); used by the login rate limit and by `URUTAU_PEER_ALLOW` |
| `URUTAU_TRUSTED_PROXY` | `127.0.0.0/8,::1` (the compose file sets `10.250.0.0/24`) | reverse proxies whose `X-Forwarded-For` is trusted (read right to left); used by the login rate limit and by the probe authentication limiter |
### Second firewall (enforce)
| Variable | Default | Meaning |
|---|---|---|
| `URUTAU_ENFORCE` | `off` | `off`; `observe` (decides in memory and shows what it would ban, writes nothing); `on` (also appends the decisions to `URUTAU_ENFORCE_LOG` for the host fail2ban). Anything else refuses to start |
| `URUTAU_ENFORCE_LOG` | `/logs/enforce/decisions.log` | decision file appended in `on` mode; `on` without it refuses to start |
| `URUTAU_ENFORCE_UNBAN_LOG` | `unban.log` next to `URUTAU_ENFORCE_LOG` | file where the dashboard's Unban button writes its requests, read by the host |
| `URUTAU_ENFORCE_SHARE` | `off` | `on`: exchange decisions and unbans with the peers every 30 s; each side applies its own exclusions. Anything else refuses to start |
| `URUTAU_ENFORCE` | `off` | `off`; `observe` (decides in memory and shows what it would ban, sends nothing); `on` (also queues the decisions for the probe of the host, which appends them to its `URUTAU_ENFORCE_LOG` for the host fail2ban). Anything else refuses to start |
| `URUTAU_ENFORCE_SHARE` | `off` | `on`: a decision taken for one probe is also queued for the others; each node applies its own exclusions. Anything else refuses to start |
| `URUTAU_ENFORCE_THRESHOLD` | `5` | attack events in 10 minutes that justify a ban (1 to 1000) |
| `URUTAU_ENFORCE_MAX_PER_MIN` | `60` | most decisions written per minute; the excess is dropped and counted (1 to 10000) |
@@ -88,15 +75,36 @@ An unparseable number falls back to the default; an out-of-range one refuses to
| Variable | Default | Meaning |
|---|---|---|
| `URUTAU_EGRESS` | `auto` | `auto` (on when `URUTAU_EGRESS_LOG` exists at start), `on` or `off`; anything else refuses to start |
| `URUTAU_EGRESS_LOG` | `/logs/host/egress.log` | kernel log of new outbound connections, written by the host kit |
| `URUTAU_EGRESS_CONTAINERS` | `/logs/host/containers.map` | `"<ip> <container>"` map written by the host kit every minute, so workloads keep their name when the address changes on a redeploy |
| `URUTAU_EGRESS_WORKLOADS` | empty | named workloads and their role, see [Egress analysis](#egress-analysis) |
| `URUTAU_EGRESS_RESOLVERS` | empty | DNS resolvers that are allowed, comma separated IPs; empty means the usual public ones (Cloudflare, Google, Quad9...) plus the nameservers of `/etc/resolv.conf` and `/logs/host/resolv.conf` |
| `URUTAU_EGRESS_ALLOW` | empty | environment only, no flag: CIDRs or IPs of legitimate periodic pollers that must not raise beaconing findings. The peers' addresses, `URUTAU_TRUSTED` and the server's own public addresses are always allowed |
| `URUTAU_EGRESS` | `auto` | `auto` (on for a probe that sends an egress log), `on` or `off`; anything else refuses to start |
| `URUTAU_EGRESS_WORKLOADS` | empty | default for the primary probe; every probe can have its own on the Sources page. Named workloads and their role, see [Egress analysis](#egress-analysis) |
| `URUTAU_EGRESS_RESOLVERS` | empty | DNS resolvers that are allowed, comma separated IPs; empty means the usual public ones (Cloudflare, Google, Quad9...) plus the nameservers of the `resolv.conf` each probe sends |
| `URUTAU_EGRESS_ALLOW` | empty | environment only, no flag: CIDRs or IPs of legitimate periodic pollers that must not raise beaconing findings. The probes' addresses, `URUTAU_TRUSTED` and the server's own public addresses are always allowed |
| `URUTAU_EGRESS_PROVIDER_ASN` | empty | environment only, no flag: AS numbers of your hosting provider, comma separated, so traffic to it is not reported as unusual |
In the container image the log paths default to `/logs/traefik/access.log`, `/logs/host/auth.log` and `/logs/host/fail2ban.log` (the compose file mounts the host logs there); the probe, egress and container map files are in the same `/logs/host` directory. The compose file adds `URUTAU_VERSION` (image tag), `URUTAU_IMAGE` and `URUTAU_PUBLISH` (host address and port), see `.env.example`. It passes only some variables to the container ([docker.md](docker.md)); add any other `URUTAU_*` variable, such as the `URUTAU_ENFORCE_*` and `URUTAU_EGRESS_*` ones, to its `environment` block.
### Probe
The probe has only these variables (flags in [cli.md](cli.md#urutau-probe)). A path turns a source on, empty turns it off, and a file that does not exist yet just stays at `waiting`.
| Variable | Default | Meaning |
|---|---|---|
| `URUTAU_HUB` | required | hub URL: `https://...`, or `http://` only for loopback and private addresses (for example `http://urutau:8790` on the `urutau-edge` network) |
| `URUTAU_PROBE_NAME` | required | name registered on the hub (lowercase letters, digits and `-`, up to 32) |
| `URUTAU_PROBE_TOKEN`, `URUTAU_PROBE_TOKEN_FILE` | required | see [Secrets](#secrets) |
| `URUTAU_STATE_DIR` | `/state` | spool, read positions and liveness mark; keep it on a volume |
| `URUTAU_TRAEFIK_LOG` | `/logs/traefik/access.log` | Traefik JSON access log |
| `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_EGRESS_LOG` | `/logs/host/egress.log` | kernel log of new outbound connections, written by the host kit |
| `URUTAU_EGRESS_CONTAINERS` | `/logs/host/containers.map` | `"<ip> <container>"` map written by the host kit every minute, so workloads keep their name when the address changes on a redeploy; sent whole when it changes |
| `URUTAU_RESOLV` | `/etc/resolv.conf` of the host (mounted) | resolvers of the host, sent whole when it changes |
| `URUTAU_ENFORCE_LOG` | `/logs/enforce/decisions.log` | file where the ban decisions of the hub are appended, read by the host jail; empty ignores ban commands and counts them as errors |
| `URUTAU_ENFORCE_UNBAN_LOG` | `/logs/enforce/unban.log` | file where unban requests are appended, read by the host; empty ignores them |
| `URUTAU_PROBE_SPOOL_MAX` | `64MiB` | spool cap while the hub is unreachable; the oldest batches are dropped, counted, and shown on the Sources page |
| `URUTAU_LOCATION` | empty | `"lat,lon,Label"`; the setting on the hub prevails |
| `TZ` | UTC | time zone of the host: `fail2ban.log` timestamps carry no zone and the hub parses them, so it must be the same on the probe and on the hub |
The probe image defaults to the paths above because the compose file in `deploy/probe` mounts the host logs there.
## Noise and monitoring
@@ -113,14 +121,17 @@ The geolocation databases are checked every 24 hours (`--geo-update`), but DB-IP
The Traffic page needs no setting. `URUTAU_DOMAINS` restricts which domains it tracks (exact names or `*.example.com`); a domain only gets a slot after a 2xx answer and inactive domains are pruned, so forged `Host` headers cannot fill the analytics. Top pages normalize token-looking path segments (ids, hashes, long random strings) to `:id`. It uses the Traefik log, counts unique visitors by a daily-salted hash and never persists the IP address of a legitimate visitor. See [SECURITY.md](../SECURITY.md).
## Peers (hub mode)
## Probes (hub mode)
A hub with nothing else to configure accepts no probe until you create one:
```
URUTAU_PEERS=web1=https://urutau.web1.example,db1=https://urutau.db1.example
URUTAU_PEER_TOKEN=<shared secret>
urutau probes create web1 # prints the token once
```
On each peer, set the same `URUTAU_PEER_TOKEN` (or one `URUTAU_PEER_TOKEN_<NAME>` per peer on the hub). The peer token opens only the federation routes: `GET /api/v1/peer/export` (the hub asks every 15 seconds for `1h`, `24h`, `7d` and `30d`), `GET /api/v1/peer/stream` (live events), `GET /api/v1/peer/period` (the study of a period or an IP), `GET /api/v1/peer/egress` and, when `URUTAU_ENFORCE_SHARE=on`, `GET`/`POST /api/v1/peer/decisions` and `POST /api/v1/peer/unban`. Peer URLs must be `https` (plain `http` is accepted only for loopback): the peer token travels in a header. To restrict who may call these routes, set `URUTAU_PEER_ALLOW` on the peer to the hub's address; when the peer sits behind a proxy, also set `URUTAU_TRUSTED_PROXY` so the real client address is the one compared. Peer names must be unique and cannot be `all` or the hub's own name. With `URUTAU_PEER_BLOCKLIST=off` the hub's blocklist lists only its own IPs.
On the server of that probe, set `URUTAU_HUB`, `URUTAU_PROBE_NAME=web1` and `URUTAU_PROBE_TOKEN` and start `deploy/probe/docker-compose.yml` ([docker.md](docker.md#probe)). The hub stores only the SHA-256 of the token; a wrong token gets a bare 401 under an attempt limiter. Revoking a probe (`urutau probes revoke web1` or the Sources page) refuses it from then on and keeps its data. The location on the map and the egress settings (workloads, resolvers, allowed destinations) of each probe are edited on the Sources page and kept in `probes.json`; `URUTAU_LOCATION`, `URUTAU_EGRESS_WORKLOADS`, `URUTAU_EGRESS_RESOLVERS` and `URUTAU_EGRESS_ALLOW` are the defaults of the primary probe.
If the 1.x variables `URUTAU_PEERS`, `URUTAU_PEER_TOKEN*`, `URUTAU_PEER_ALLOW` or `URUTAU_PEER_BLOCKLIST` are set, or the log path variables on the hub, it stops at start: see [migration-2.0.md](migration-2.0.md).
## Snapshot and retention
@@ -136,7 +147,7 @@ Tickets opened from egress findings (and their status: open, false positive, ben
## Probes (port scans)
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`; Urutau reads that file as `URUTAU_PROBE_LOG`, 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.
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.
## Tor
@@ -144,18 +155,18 @@ Urutau marks addresses that are Tor exits or relays. By default (`URUTAU_TOR_AUT
## Second firewall (enforce)
Optional and off by default. Urutau never gets privileges: it only decides which addresses deserve a ban and appends one line per decision to a file, and a fail2ban jail on the host applies it.
Optional and off by default. Neither Urutau process gets privileges: the hub decides which addresses deserve a ban and queues one line per decision for the probe of that host, the probe checks that the line has exactly the expected shape and appends it to a file, and a fail2ban jail on the host applies it.
- `URUTAU_ENFORCE=observe` decides in memory and shows in the dashboard what it would ban; nothing is written. Use it first.
- `URUTAU_ENFORCE=on` appends `<time> urutau decision=ban ip=<ip> reason=<slug> score=<n> ttl=<s> host=<name> src=<local|peer>` to `URUTAU_ENFORCE_LOG`. The host side is the `urutau` jail and the `urutau-allports` action installed by `install.sh --enforce` ([docker.md](docker.md#host-kit)). The jail uses the host's own `ignoreip`, so trusted addresses stay protected there too. Decisions wait until the log backfill finishes at start.
- `URUTAU_ENFORCE=on` appends `<time> urutau decision=ban ip=<ip> reason=<slug> score=<n> ttl=<s> host=<name> src=<local|peer:NAME>` to the `URUTAU_ENFORCE_LOG` of the probe. The host side is the `urutau` jail and the `urutau-allports` action installed by `install.sh --probe --enforce` ([docker.md](docker.md#host-kit)). The jail uses the host's own `ignoreip`, so trusted addresses stay protected there too. Decisions wait until the log backfill finishes at start.
A ban needs one of these inside the window: two critical events (RCE, traversal, `.env`/credentials, VCS, webshell, SQL injection, Log4Shell), `URUTAU_ENFORCE_THRESHOLD` attack events in 10 minutes (doubled for a visitor with a legitimate visit), 5 SSH failures in 10 minutes, 10 distinct ports probed in 10 minutes, a known attacker, 10 SSH failures or 20 web events in 24 hours, 10 SSH failures or 10 web events without a legitimate visit in 7 days (an `ssh-probe` counts half), or one event from an address of a /24 (IPv4) or /64 (IPv6) where 3 or more addresses were banned in the last 24 hours (`neighbor-campaign`). The advisory TTL grows with repeat offences: 1 h, 6 h, 24 h, 7 d. Never banned: trusted and private addresses (`URUTAU_TRUSTED`, `URUTAU_IGNORE`), verified crawlers (forward-confirmed reverse DNS), addresses with an operator allow, infrastructure and peers' own hosts, Cloudflare addresses, and decisions from a peer the local instance cannot confirm. Bans of the `urutau` jail and of `recidive` do not count as evidence of the address's own behaviour. Reasons are a fixed list: `scanner-flood`, `exploit-flood`, `web-bruteforce`, `wp-bruteforce`, `ssh-bruteforce`, `rce`, `path-traversal`, `env-probe`, `vcs-probe`, `webshell`, `sqli`, `log4shell`, `port-scan`, `known-attacker`, `neighbor-campaign`.
The dashboard's Unban button (`POST /api/v1/enforce/unban`) drops the active ban, writes `<time> urutau unban ip=<ip> allow=<seconds>` to the unban file and, with `URUTAU_ENFORCE_SHARE=on`, tells the peers. On the host `urutau-unban.path` runs `urutau-unban`, which unbans the address in every jail and, with `allow` above 0, ignores it for that many seconds (useful for authorized pentests). `urutau doctor` reports the mode, the file and whether it is writable (`fail` in `on` mode when it is not), and warns when Traefik logs Cloudflare addresses as clients (set `forwardedHeaders.trustedIPs` to the Cloudflare ranges so the real client is seen).
The dashboard's Unban button (`POST /api/v1/enforce/unban`) drops the active ban, queues `<time> urutau unban ip=<ip> allow=<seconds>` for the probe (you choose the host, or all), which appends it to the unban file, and with `URUTAU_ENFORCE_SHARE=on` tells the other nodes. On the host `urutau-unban.path` runs `urutau-unban`, which unbans the address in every jail and, with `allow` above 0, ignores it for that many seconds (useful for authorized pentests). `urutau doctor` reports the mode, the file and whether it is writable (`fail` in `on` mode when it is not), and warns when Traefik logs Cloudflare addresses as clients (set `forwardedHeaders.trustedIPs` to the Cloudflare ranges so the real client is seen).
## Egress analysis
Analyses what leaves the server: new outbound connections of the host and of the containers, logged by the host kit to `/var/log/urutau/egress.log`. It finds beaconing, mining pools, spam, unauthorized scans, DNS that bypasses the allowed resolvers, and destinations known as hostile or Tor exits. With `URUTAU_EGRESS=auto` it turns on by itself when the log exists. Findings can become tickets (see Incidents).
Analyses what leaves the server: new outbound connections of the host and of the containers, logged by the host kit to `/var/log/urutau/egress.log` and sent by the probe. It finds beaconing, mining pools, spam, unauthorized scans, DNS that bypasses the allowed resolvers, and destinations known as hostile or Tor exits. With `URUTAU_EGRESS=auto` it turns on by itself for a probe that sends the log. Findings can become tickets (see Incidents).
`URUTAU_EGRESS_WORKLOADS` names the origins and gives each one a role, so expected behaviour is not reported (a scanner scans, a mail server talks on port 25):
+62 -48
View File
@@ -2,22 +2,29 @@
# Docker
Urutau ships as one small container image (`linux/amd64` and `linux/arm64`, about 28 MB, no `curl`), defined in [`docker-compose.yml`](../docker-compose.yml). It reads log files and writes one data volume (and, only if you turn on the second firewall, one decision file).
Urutau 2 ships as **two** small container images (`linux/amd64` and `linux/arm64`, no `curl`, no shell in the probe), built from one Dockerfile:
| Image | Target | What it is | Compose file |
|---|---|---|---|
| `urutau` | `hub` | Alpine, about 28 MB: dashboard, API, data volume, receives the probes. Reads no log file | [`docker-compose.yml`](../docker-compose.yml) |
| `urutau-probe` | `probe` | `FROM scratch`, under 15 MB: only the binary, CA certificates and zoneinfo. Reads the host logs and pushes them to the hub | [`deploy/probe/docker-compose.yml`](../deploy/probe/docker-compose.yml) |
```
host container urutau
/data/coolify/proxy/logs ── :ro ────────────► /logs/traefik (access.log of Traefik)
/var/log/urutau ── :ro ────────────► /logs/host (auth.log, fail2ban.log, probe.log,
egress.log, containers.map, resolv.conf)
/var/log/urutau-enforce ── read and write ─► /logs/enforce (decisions.log, unban.log; only with URUTAU_ENFORCE=on)
volume urutau-data ── read and write ─► /data (snapshot, geo, tor, events, incidents)
server 1 (probe) hub
/data/coolify/proxy/logs ─:ro─► /logs/traefik
/var/log/urutau ─:ro─► /logs/host ── HTTPS push ──► container urutau
/etc/resolv.conf ─:ro─► /logs/resolv.conf ◄─ long-poll ──── volume urutau-data ─► /data
/var/log/urutau-enforce ─rw──► /logs/enforce (only when the hub's URUTAU_ENFORCE=on)
volume urutau-probe-state ────► /state (spool, positions)
server 2 (probe) ── same layout ──► the same hub
```
The compose file follows this layout, except the `/logs/enforce` mount, which you add when you enable the second firewall (see [below](#host-kit)). The Traefik log directory is mounted outside `/data` so it does not collide with the snapshot volume. Only the dedicated `logs` directory of the proxy is mounted, never the whole `/data/coolify/proxy` (which holds `acme.json` and the dynamic configuration).
The hub and the probes are independent containers: the hub can run on one of the monitored servers (then that server also runs a probe, as any other) or on a machine of its own. The probe opens **no port**: the connection goes out to the hub, so the monitored server needs no inbound rule. Only the dedicated `logs` directory of the proxy is mounted, never the whole `/data/coolify/proxy` (it holds `acme.json`, the TLS private keys).
The image runs as the unprivileged user `urutau` (uid 10001) on Alpine, built from a static Go binary. Its `HEALTHCHECK` is the binary itself (`urutau healthcheck`, every 30 s, which asks the local daemon for `/api/health`), so there is no `curl` in the image. The image sets `URUTAU_BIND=0.0.0.0:8790`, `URUTAU_DATA_DIR=/data` and the three log paths (`/logs/traefik/access.log`, `/logs/host/auth.log`, `/logs/host/fail2ban.log`); `VOLUME /data`, `EXPOSE 8790`, `ENTRYPOINT ["urutau"]`, `CMD ["serve"]`. The compose file sets `mem_limit: 384m` (the Go soft limit is 256 MiB; the worst case measured is about 54 MiB of heap plus a snapshot of about 27 MB), `cpus: 0.5`, a read-only root filesystem, `cap_drop: [ALL]`, `no-new-privileges`, `group_add: ["4"]` (the host `adm` group) and the `urutau-edge` network. The data volume also holds the event registry (`/data/events`, capped by `URUTAU_EVENTS_MAX`, 512 MB by default). It passes from `.env` to the container: `URUTAU_TOKEN`, `URUTAU_NAME`, `URUTAU_TRUSTED`, `URUTAU_PEERS`, `URUTAU_PEER_TOKEN`, `URUTAU_PEER_ALLOW`, `URUTAU_TRUSTED_PROXY`, `URUTAU_DOMAINS`, `URUTAU_MONITOR_FROM`, `URUTAU_ADMIN_USERS`, `URUTAU_GEO_UPDATE` and `TZ`. To set any other `URUTAU_*` variable (`URUTAU_MONITOR_UA`, `URUTAU_RETENTION`, `URUTAU_TOKEN_FILE`, `URUTAU_ENFORCE*`, `URUTAU_EGRESS*`, `URUTAU_TOR_*`, per-peer tokens, ...), add it to the `environment` block.
Both images run unprivileged (uid 10001) from a static Go binary. The hub image sets `URUTAU_BIND=0.0.0.0:8790` and `URUTAU_DATA_DIR=/data` (no log path any more; the 1.x variables stop it at start) and its `HEALTHCHECK` is `urutau healthcheck` every 30 s. The probe image sets `URUTAU_STATE_DIR=/state`, exposes no port and its `HEALTHCHECK` is `/urutau probe --check`, which reads the liveness mark of the state volume (there is no shell). To read `/var/log/urutau` (group `adm`), the probe compose file adds the host group with `group_add: ["4"]`.
## Quick start
## Quick start (hub)
```bash
cp .env.example .env
@@ -27,25 +34,44 @@ docker compose pull && docker compose up -d # published image
docker compose up -d --build
```
The token needs at least 32 characters and about 128 bits of estimated entropy (length times Shannon entropy; periodic or sequential tokens are refused). `openssl rand -base64 48` is recommended (`openssl rand -hex 32` also qualifies). To keep the secret out of the environment, mount a file and set `URUTAU_TOKEN_FILE` (same for `URUTAU_PEER_TOKEN_FILE`).
The token needs at least 32 characters and about 128 bits of estimated entropy (length times Shannon entropy; periodic or sequential tokens are refused). `openssl rand -base64 48` is recommended (`openssl rand -hex 32` also qualifies). To keep the secret out of the environment, mount a file and set `URUTAU_TOKEN_FILE` (the probe has `URUTAU_PROBE_TOKEN_FILE`).
The dashboard comes up at `http://127.0.0.1:8790` by default (`URUTAU_PUBLISH` in `.env` changes the address and port). Check the sources:
The dashboard comes up at `http://127.0.0.1:8790` by default (`URUTAU_PUBLISH` in `.env` changes the address and port). Create a probe for each server and read the answer once:
```bash
docker compose exec urutau urutau probes create web1 # prints the token (urp_...) once
docker compose exec urutau urutau doctor
docker compose logs urutau
```
## Reading the logs
## Probe
On each monitored server, after [preparing the host logs](#preparing-the-host-logs):
```bash
cd deploy/probe
cp .env.example .env
$EDITOR .env # URUTAU_HUB=https://urutau.example.com URUTAU_PROBE_NAME=web1 URUTAU_PROBE_TOKEN=urp_...
docker compose up -d
docker compose logs probe
```
Then open the Sources page of the hub: the probe appears connected with its sources (`following`, `waiting` for a file that does not exist yet). `URUTAU_HUB` must be `https://` (a plain `http://` is accepted only for loopback and private addresses, such as `http://urutau:8790` when the hub is the `urutau` service of the same host and the probe joins the `urutau-edge` network, see the comments in the compose file). Set `TZ` to the host's time zone: the hub parses `fail2ban.log`, which has none, so it must match on both sides.
While the hub is unreachable the probe keeps the batches in the `/state` volume (64 MiB by default, `URUTAU_PROBE_SPOOL_MAX`), reconnects with backoff from 1 to 60 seconds and sends them in order when the hub is back; nothing is lost or counted twice. If the spool overflows, the oldest batches are dropped and the loss is counted and shown on the Sources page. To replace a token, revoke the probe on the hub and create it again; a lost token cannot be recovered because the hub keeps only its SHA-256. The probe stays under about 20 MB of memory.
## Reading the logs (probe)
These notes are about the files the **probe** mounts.
- **Traefik:** the access log must be JSON and written to a dedicated directory. In Traefik's static configuration set `--accesslog=true`, `--accesslog.format=json` and `--accesslog.filepath=/traefik/logs/access.log`. On Coolify the host directory `/data/coolify/proxy` is `/traefik` inside the proxy container, so that file appears on the host as `/data/coolify/proxy/logs/access.log`, which is what the compose file mounts. In the Coolify UI open Servers, the server, Proxy, and add those three lines to the `command` list of the proxy configuration, then restart the proxy. In the same place add the headers Urutau uses to tell real visits from framed requests: `--accesslog.fields.headers.names.Sec-Fetch-Site=keep`, `--accesslog.fields.headers.names.Sec-Fetch-Dest=keep` and `--accesslog.fields.headers.names.Referer=keep`.
- **auth.log and fail2ban.log:** the dedicated host directory `/var/log/urutau` is mounted read-only at `/logs/host` as a directory, because logrotate recreates these files by rename and a single-file mount would keep following the old inode. Prepare it as shown in [Preparing the host logs](#preparing-the-host-logs). The files are owned by `syslog:adm`, so the container adds the host's `adm` group (GID 4) with `group_add: ["4"]`, as the compose file does. Nothing else from the host `/var/log` is exposed.
- **Read-only:** all log mounts are `:ro`. Urutau never writes to a log.
- **Read-only:** all log mounts are `:ro`. Urutau never writes to a log. (The only writable mount is `/logs/enforce`, see [Host kit](#host-kit).)
- **Rotation:** the follower reopens the file when logrotate replaces or truncates it.
## Preparing the host logs
Urutau reads a dedicated directory, `/var/log/urutau`, instead of the whole `/var/log`. Prepare it once on each server (the original `/var/log/auth.log` stays untouched):
The probe reads a dedicated directory, `/var/log/urutau`, instead of the whole `/var/log`. Prepare it once on each server (the original `/var/log/auth.log` stays untouched):
```bash
sudo install -d -m 0750 -o syslog -g adm /var/log/urutau
@@ -90,7 +116,7 @@ If you also install the host kit, the logrotate rule above names only `auth.log`
## Example: Coolify
Create a Docker Compose resource on the Coolify server whose logs you want to watch, with this compose file:
Two resources. On the server that hosts the hub, a Docker Compose resource with the hub and its domain:
```yaml
services:
@@ -99,18 +125,13 @@ services:
restart: unless-stopped
environment:
URUTAU_TOKEN: ${URUTAU_TOKEN}
URUTAU_NAME: server-1
URUTAU_AUTH_LOG: /logs/host/auth.log
URUTAU_FAIL2BAN_LOG: /logs/host/fail2ban.log
URUTAU_NAME: server-1 # the primary probe: its data is the data-dir root
URUTAU_TRUSTED_PROXY: 10.250.0.0/24
TZ: UTC # the host's time zone (fail2ban.log has none)
group_add: ["4"] # adm: read auth.log and fail2ban.log
TZ: UTC
read_only: true
cap_drop: [ALL]
security_opt: ["no-new-privileges:true"]
volumes:
- /data/coolify/proxy/logs:/logs/traefik:ro
- /var/log/urutau:/logs/host:ro
- urutau-data:/data
networks: [urutau-edge]
labels:
@@ -130,22 +151,25 @@ networks:
external: true
```
Then, on every server (including that one), a second Compose resource with `deploy/probe/docker-compose.yml`, with `URUTAU_HUB`, `URUTAU_PROBE_NAME` and `URUTAU_PROBE_TOKEN` in the Coolify environment. On the hub's own server the probe can use `https://urutau.example.com` or join the `urutau-edge` network and use `http://urutau:8790`.
Notes:
- **A network shared only with Traefik.** `--trusted-proxy` defaults to loopback only, so by default `X-Forwarded-For` is ignored. The compose file creates the `urutau-edge` network (`10.250.0.0/24`) and sets `URUTAU_TRUSTED_PROXY=10.250.0.0/24`, so only the proxy on that network is believed (any other container there could forge client IPs, so keep it to the proxy). Connect the proxy once: `docker network connect urutau-edge coolify-proxy`. In a standalone compose like the example below, declare the network the same way and set the variable. The `traefik.docker.network` label tells Traefik to use it. Adapt the entrypoint and certificate resolver names to your proxy.
- The image already points the sources at `/logs/traefik/access.log`, `/logs/host/auth.log` and `/logs/host/fail2ban.log` (its `URUTAU_*_LOG` defaults); the probe, egress and container map defaults (`/logs/host/...`) are the binary's own. The binary's other defaults (`/data/coolify/proxy/access.log`, `/var/log/...`) are for running it directly on the host.
- **A network shared only with Traefik.** `--trusted-proxy` defaults to loopback only, so by default `X-Forwarded-For` is ignored. The compose file creates the `urutau-edge` network (`10.250.0.0/24`) and sets `URUTAU_TRUSTED_PROXY=10.250.0.0/24`, so only the proxy on that network is believed (any other container there could forge client IPs). Attach the proxy with `docker network connect urutau-edge coolify-proxy`, or let the labels do it as above. If the proxy sits elsewhere, set `URUTAU_TRUSTED_PROXY` to its address.
- Set `URUTAU_TOKEN` in the Coolify environment. Behind the proxy the dashboard is served over HTTPS, so the session cookie is `Secure`.
- Do not publish port 8790 on the host when the proxy already routes it.
- If the Traefik access log is missing or not JSON, the source stays at zero lines or `malformed` grows.
- Urutau needs no `tmpfs`: the root filesystem is read-only and its write targets are the `/data` volume and, in enforce mode, `/logs/enforce`.
- Do not publish port 8790 on the host when the proxy already routes it. The domain must pass `/api/v1/probe/*` (it is the same host as the dashboard); a Cloudflare proxy in front is fine: the longest request is a 25 second long-poll.
- If the Traefik access log is missing or not JSON, its source stays at zero lines or `malformed` grows on the Sources page.
- Urutau needs no `tmpfs`: the root filesystem is read-only and the write targets are the `/data` volume of the hub and the `/state` volume (and, in enforce mode, `/logs/enforce`) of the probe.
## Host kit
`deploy/host/` holds an optional kit that needs root on the host and gives Urutau three more sources. Urutau itself never gets privileges: it only reads the logs the kit writes and, in enforce mode, writes a decision file.
`deploy/host/` holds an optional kit that needs root on the host and gives the probe three more sources. Urutau itself never gets privileges: the probe only reads the logs the kit writes and, in enforce mode, appends decisions to a file. Run it on every server that has a probe.
```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 --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)
```
@@ -158,40 +182,30 @@ It is idempotent. `URUTAU_WAN` overrides the detected uplink interface and `URUT
| container map | `urutau-containers-map` and its timer (every minute) write `/var/log/urutau/containers.map` (`<ip> <container>`) and `/var/log/urutau/resolv.conf` (the real upstream resolvers) |
| second firewall (`--enforce`) | directory `/var/log/urutau-enforce` (owned by `URUTAU_UID`, group `adm`) with `decisions.log` and `unban.log`; fail2ban filter `urutau`, action `urutau-allports` and jail `urutau` (`polling` backend, `maxretry = 1`, `bantime = 1h`, actions on `INPUT` and `DOCKER-USER`, host `ignoreip` kept); `urutau-unban.path` and `urutau-unban` apply the Unban button |
The `urutau-allports` action behaves like `iptables-allports` but only drops connections the banned address starts (conntrack original direction), so replies to connections the host opened keep flowing. The egress and probe files land in `/var/log/urutau`, which the compose file already mounts at `/logs/host`, so Urutau 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:
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
# hub (docker-compose.yml)
environment:
URUTAU_ENFORCE: observe # off | observe | on
# URUTAU_ENFORCE_SHARE: "on" # exchange decisions with the peers
# URUTAU_EGRESS_WORKLOADS: "mail=10.0.7.0/24:mail"
volumes:
- /var/log/urutau-enforce:/logs/enforce # read and write, only for enforce=on
# URUTAU_ENFORCE_SHARE: "on" # a decision for one server is also queued for the others
# probe (deploy/probe/docker-compose.yml): the /logs/enforce volume is already there
```
`/logs/enforce` must be writable by uid 10001 (the kit does it) and cannot be `:ro`. Check with `docker compose exec urutau urutau doctor`: the `enforce` line shows mode, file and whether it is writable. See [configuration.md](configuration.md) for the policy and the variables.
The decisions travel from the hub to the probe of the host (long-poll) and the probe appends them to `/logs/enforce/decisions.log`; it accepts only lines with exactly the shape of a ban or unban line. `/logs/enforce` must be writable by uid 10001 (the kit does it) and cannot be `:ro`. The probe counts a refused or unwritable command as an error, shown on the Sources page. See [configuration.md](configuration.md) for the policy and the variables.
## Geolocation database
The DB-IP Lite databases are downloaded into the data volume (`/data/geo`) on first start, so the container needs outbound HTTPS to `download.db-ip.com` once, and then once a month. The Tor lists (`URUTAU_TOR_AUTO=on`) also need `check.torproject.org` and `onionoo.torproject.org` every 6 hours; with `URUTAU_TOR_AUTO=off` that is not needed. If the host cannot reach the internet, copy the two `.mmdb` files into the volume and set `URUTAU_GEO_UPDATE=0` ([configuration.md](configuration.md)). Data by [DB-IP](https://db-ip.com), CC BY 4.0.
## Federation across servers
## Several servers
Run one Urutau per server with its own `URUTAU_NAME`. Every instance that is polled sets its own server token, `URUTAU_PEER_TOKEN` (or `_FILE`), and that is the only token its export accepts. The hub holds a client credential for each peer, equal to that peer's server token: one `URUTAU_PEER_TOKEN_<NAME>` per peer (the peer name uppercased, other characters turned into `_`, for example `URUTAU_PEER_TOKEN_SERVER_2`), with the hub's general `URUTAU_PEER_TOKEN` as fallback. A client credential does not open the hub's own export, and peer names that collapse to the same variable (`my-peer` and `my_peer`) are refused. Tokens need 32+ characters and about 128 bits of entropy, different from `URUTAU_TOKEN` (`openssl rand -base64 48`), and can come from `..._FILE`. On the server that hosts the shared dashboard (the hub) add:
```yaml
environment:
URUTAU_PEERS: server-2=https://urutau.server2.example.com,server-3=https://urutau.server3.example.com
URUTAU_PEER_TOKEN_SERVER_2: ${TOKEN_FOR_SERVER_2}
URUTAU_PEER_TOKEN_SERVER_3: ${TOKEN_FOR_SERVER_3}
```
The hub calls `GET /api/v1/peer/export` on each peer (four ranges every 15 seconds), keeps one `GET /api/v1/peer/stream` open for the live events and fetches periods and egress on demand; with `URUTAU_ENFORCE_SHARE=on` both sides also exchange decisions and unbans every 30 seconds. All of it uses that peer's token, which opens nothing else on the peer and is refused over plain `http` outside loopback. Set `URUTAU_PEER_ALLOW` on a peer to the hub's address to restrict who may call the export. Each peer keeps its own login token for its own dashboard.
One hub, one probe per server, each with its own name and token. There is no peer token and no shared secret: `urutau probes create <name>` makes a token for one probe, only its SHA-256 stays on the hub, and `urutau probes revoke <name>` cuts one server off without touching the others (its data is kept). The dashboard host selector offers `all` and each probe, summaries, IP tables, the live map and incidents (`host/INC-n`) merge them, and the egress settings and map location of each probe are set on the Sources page. With `URUTAU_ENFORCE_SHARE=on` a ban decided for one server is also queued for the others. Moving from 1.x: [migration-2.0.md](migration-2.0.md).
## Hardening
`read_only: true`, `cap_drop: [ALL]`, `no-new-privileges` and read-only log mounts leave the container able to do one thing: read the logs and write its data volume (plus the decision file, only when you enable `URUTAU_ENFORCE=on`). Keep the image on a pinned tag (`X.Y.Z`) in production and `latest` only where you accept updates.
`read_only: true`, `cap_drop: [ALL]`, `no-new-privileges` and read-only log mounts leave the hub able to do one thing, serve and write its data volume, and the probe able to read the logs, write its `/state` volume and dial the hub (plus the decision file, only when you enable `URUTAU_ENFORCE=on`). The probe image has no shell, no package manager and exposes no port. Keep the image on a pinned tag (`X.Y.Z`) in production and `latest` only where you accept updates.
## Health and shutdown
`GET /api/health` answers `{"status":"ok"}` without authentication. `urutau healthcheck` calls it locally and exits 0 when the daemon is healthy; the image uses it as its `HEALTHCHECK`. On `SIGTERM` or `SIGINT` the daemon stops accepting requests (5 second grace), saves the snapshot and exits 0.
`GET /api/health` answers `{"status":"ok"}` without authentication. `urutau healthcheck` calls it locally and exits 0 when the daemon is healthy; the hub image uses it as its `HEALTHCHECK`, and the probe image uses `urutau probe --check`. On `SIGTERM` or `SIGINT` the daemon stops accepting requests (5 second grace), saves the snapshot and exits 0.
+10 -12
View File
@@ -17,7 +17,7 @@ A side rail (a tab bar on phones, with a "More" menu that scrolls when it is tal
## Header
- A live indicator showing whether the event stream (SSE) is connected (an instance serves at most 20 stream clients at once).
- The **host** selector: `all`, this instance and every peer of a hub.
- The **host** selector: `all` and every probe of the hub.
- The **period** selector: twelve ranges (`1h`, `2h`, `3h`, `6h`, `12h`, `24h`, `2d`, `3d`, `5d`, `7d`, `15d`, `30d`) or a custom period (`from` and `to`, at most 30 days). It applies to every page.
- Language, theme and logout buttons.
@@ -40,7 +40,7 @@ A side rail (a tab bar on phones, with a "More" menu that scrolls when it is tal
<p align="center"><img src="img/overview-dark.png" width="900" alt="Overview page"><br><sub>Overview (demo data).</sub></p>
**Live** (`#/live`): attacks drawn as animated arcs from their origin to the server that saw them, on a flat map or a 3D globe, with the rate, categories, servers, recent origins, a metrics column and latest events, filters, pause and full screen. It opens by replaying the latest events (`/api/v1/live/recent`), so it is not still on a quiet server. On a hub it also shows the events of every peer. The position of each server comes from `--location`.
**Live** (`#/live`): attacks drawn as animated arcs from their origin to the server that saw them, on a flat map or a 3D globe, with the rate, categories, servers, recent origins, a metrics column and latest events, filters, pause and full screen. It opens by replaying the latest events (`/api/v1/live/recent`), so it is not still on a quiet server. It shows the events of every probe. The position of each server is set per probe on the Sources page (`--location` is the default of the primary probe).
<p align="center"><img src="img/live-flat-dark.png" width="900" alt="Live page on the flat map"><br><sub>Live: flat map.</sub></p>
<p align="center"><img src="img/live-globe-dark.png" width="900" alt="Live page on the 3D globe"><br><sub>Live: 3D globe.</sub></p>
@@ -81,7 +81,7 @@ A side rail (a tab bar on phones, with a "More" menu that scrolls when it is tal
<p align="center"><img src="img/incidents-dark.png" width="900" alt="Page: Incidents"><br><sub>Incidents: tickets for outbound-traffic findings.</sub></p>
<p align="center"><img src="img/incident-detail-dark.png" width="900" alt="Page: Incident ticket"><br><sub>Incident ticket: summary, activity timeline and properties.</sub></p>
**Outbound traffic** (`#/egress`, needs `URUTAU_EGRESS` and the host kit in `deploy/host`): the new outbound connections of the host and containers, logged by nftables, analysed for beaconing (regular conversations with one destination, with the interval histogram), mining, IRC and SMTP ports, contact with addresses that attacked the server or Tor relays, DNS outside the allowed resolvers, unauthorised outbound scans and new countries. It shows a plain-language verdict, evidence cards, a destination map, activity by hour, compact workloads (by network or container name, `URUTAU_EGRESS_WORKLOADS`; a `scanner` workload has only its scan-shaped traffic summarised) and the timeline of authorised scans. Servers themselves, peers and the host's own provider never raise findings; regular connections to large CDNs and clouds are low severity.
**Outbound traffic** (`#/egress`, needs `URUTAU_EGRESS` and the host kit in `deploy/host` on a probe): the new outbound connections of the host and containers, logged by nftables, analysed for beaconing (regular conversations with one destination, with the interval histogram), mining, IRC and SMTP ports, contact with addresses that attacked the server or Tor relays, DNS outside the allowed resolvers, unauthorised outbound scans and new countries. It shows a plain-language verdict, evidence cards, a destination map, activity by hour, compact workloads (by network or container name, `URUTAU_EGRESS_WORKLOADS`; a `scanner` workload has only its scan-shaped traffic summarised) and the timeline of authorised scans. Servers themselves, probes and the host's own provider never raise findings; regular connections to large CDNs and clouds are low severity.
<p align="center"><img src="img/egress-dark.png" width="900" alt="Page: Outbound traffic"><br><sub>Outbound traffic: scan bursts, beacons and mining from containers.</sub></p>
@@ -127,11 +127,11 @@ 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, peers, 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` a hub and its peers exchange decisions, each side 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. 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>
**Sources and hosts** (`#/sources`): every instance with its state (online, latency, version), every log source with its state (`following`, `waiting`, `backfill`, `error`, and degraded when more than 20% of the last 1000 lines are unreadable), lines read, malformed lines and last event (file paths are not shown), and the **blocklist**: pick a minimum score (default 50), copy or download it. It only lists hostile, globally routable addresses (never `--ignore` or `--trusted` ranges, never an IP with a successful SSH login, never an address whose only evidence is a ban by the `urutau` or `recidive` jails); IPv6 appears as its /64, written `x:x:x:x::/64`.
**Sources and hosts** (`#/sources`): every probe with its state (connected, last line, lag, version, lines dropped by a full spool, spool size and command errors) and a form to create one (the token is shown once, with a ready compose snippet), edit its location and egress settings, or revoke it; for each probe, every log source with its state (`following`, `waiting`, `backfill`, `error`, and degraded when more than 20% of the last 1000 lines are unreadable), lines read, malformed lines and last event (file paths are not shown), and the **blocklist**: pick a minimum score (default 50), copy or download it. It only lists hostile, globally routable addresses (never `--ignore` or `--trusted` ranges, never an IP with a successful SSH login, never an address whose only evidence is a ban by the `urutau` or `recidive` jails); IPv6 appears as its /64, written `x:x:x:x::/64`.
<p align="center"><img src="img/sources-dark.png" width="900" alt="Sources and hosts page: instances, log sources and blocklist"><br><sub>Sources and hosts.</sub></p>
@@ -173,16 +173,13 @@ State and city boundaries on the Geography page are from [Natural Earth](https:/
| `GET /api/v1/summary` | session or bearer | everything the dashboard shows. Query: `range` (any named range) or `from` and `to`, `host` (`all`, a name) |
| `GET /api/v1/traffic` | session or bearer | web analytics of legitimate traffic. Query: `range`, `domain` (`all` or one domain), `host`. Returns visitors, pages, requests, bots, bytes, status classes, `p50_ms`, `p95_ms`, a timeline, top pages, referrers, countries, cities, browsers, operating systems, devices and bot names |
| `GET /api/v1/geo` | session or `URUTAU_TOKEN` | attacker geography. Without `cc`: `{"countries":[{"cc","events","ips","hostile","suspicious","cats"}]}` (up to 250). With `cc=XX` (and optionally `region`): `{"cc","events","ips","hostile","suspicious","cats","regions":[...],"cities":[{"name","region","lat","lon","events","ips"}],"top_ips":[...]}` (64 regions, 200 cities, 50 IPs). Query: `range`, `host`. Cached for 5 s |
| `GET /api/v1/live/recent` | session or `URUTAU_TOKEN` | `{"events":[...]}`: the latest malicious events of this instance and its peers, newest first, in the stream format. Query: `limit` (default 200, at most 500) |
| `GET /api/v1/peer/stream` | peer token only | live federation: server-sent malicious events of this instance. At most 10 connections; same 404/401/403 rules as the export |
| `GET /api/v1/peer/export` | peer token only | federation: `{"v":1,"summary":...,"traffic":{...}}` with the top 500 IPs and their detail. Query: `range` or `from`/`to`. Cached for 5 s. 404 when no peer token is set, 401 for `URUTAU_TOKEN`, 403 from a source outside `--peer-allow` |
| `GET /api/v1/live/recent` | session or `URUTAU_TOKEN` | `{"events":[...]}`: the latest malicious events of every probe, newest first, in the stream format. Query: `limit` (default 200, at most 500) |
| `GET /api/v1/events` | session or bearer | events of the registry, newest first. Query: `range` or `from`/`to`, `host`, `ip`, `cat`, `fam`, `q`, `order`, `limit`, `cursor` |
| `GET /api/v1/events/sessions` | session or bearer | sessions (bursts with a stage) of the period, optionally for one `ip` |
| `GET /api/v1/period` | session or bearer | the study of a period: sessions, campaigns, first-seen techniques, escalations, spikes, new vs returning, top targets, families, techniques, users and ASNs. Query: `range` or `from`/`to`, `host`, `gap` (seconds between sessions, 30 to 86400) |
| `GET /api/v1/period/events` | session or bearer | the events of a period in the stream format, for replay |
| `GET /api/v1/metrics` | session or bearer | stable metrics (see [architecture.md](architecture.md)). Query: `range` or `from`/`to`, `host` |
| `GET /api/v1/ip/{ip}/stix` | session or bearer | STIX 2.1 bundle of one IP |
| `GET /api/v1/peer/period` | peer token only | federation: the study a hub merges. At most two at once (503 with `Retry-After` otherwise) |
| `GET /api/v1/techniques` | session or bearer | MITRE ATT&CK techniques seen in the period |
| `GET /api/v1/evolution`, `/concentration`, `/survival` | session or bearer | analytics of the period: change over time, concentration by IP and ASN, and time to ban with the Kaplan-Meier curve |
| `GET /api/v1/sessions/funnel` | session or bearer | sessions by stage (recon, probe, exploit, access, banned) |
@@ -194,7 +191,7 @@ State and city boundaries on the Geography page are from [Natural Earth](https:/
| `GET /api/v1/services`, `/api/v1/services/{svc}` | session or bearer | per-service SLI, SLO, error budget, burn rate and Apdex |
| `GET /api/v1/protocols` | session or bearer | HTTP and TLS versions in use |
| `GET /api/v1/ips` | session or bearer | IP table. Query: `range`, `host`, `min_score`, `level`, `q`, `banned=1`, `sort` (`score`, `last`, `first`, `events`, `ip`), `order=asc`, `per` (1 to 200, default 50), `page` |
| `GET /api/v1/ip/{ip}` | session or bearer | summarized analysis of one IP: verdict with reasons, actions, families, techniques, network type, cadence, sessions and exposure; merged with the peers. Query: `range` or `from`/`to` (default 30d) |
| `GET /api/v1/ip/{ip}` | session or bearer | summarized analysis of one IP: verdict with reasons, actions, families, techniques, network type, cadence, sessions and exposure; merged with the probes. Query: `range` or `from`/`to` (default 30d) |
| `GET /api/v1/events/stream` | session or bearer | Server-Sent Events, event `ev`, a ping every 20 s. With `visits=1` it also sends anonymous `visit` events (no address, at most 20 per second) |
| `GET /api/v1/blocklist.txt` | session or bearer | one IP per line. Query: `min_score` (default 50), `range` (default `7d`), `host`, `family` (`4`, `6`; default both; `4` suits `ipset hash:ip`), `download=1` |
| `GET /api/v1/blocklist.json` | session or bearer | `{"generated","min_score","count","ips":[{"ip","score","last","hosts"}]}`; the `ip` of an IPv6 entry is a `/64` prefix |
@@ -208,10 +205,11 @@ State and city boundaries on the Geography page are from [Natural Earth](https:/
| `GET /api/v1/enforce` | session or bearer | second firewall: mode, recent decisions, coverage and operator releases (`allows`) |
| `POST /api/v1/enforce/unban` | session or bearer | asks the host to lift a block and, optionally, keeps the address from being banned again for 1 h, 24 h or 7 days (cross-site refused) |
| `DELETE /api/v1/enforce/allow` | session or bearer | ends an operator release |
| `GET /api/v1/peer/egress`, `GET`/`POST /api/v1/peer/decisions`, `POST /api/v1/peer/unban` | peer token only | federation: the egress report a hub merges, and the exchange of second firewall decisions and unbans |
| `GET /api/v1/probes`, `POST /api/v1/probes`, `PUT /api/v1/probes/{name}`, `DELETE /api/v1/probes/{name}` | session or bearer | probe registry behind the Sources page: list with state, lag and counters, create (`{"name"}` answers `{"token"}`, shown once), edit location and egress, revoke (keeps the data) |
| `POST /api/v1/probe/hello`, `POST /api/v1/probe/push`, `GET /api/v1/probe/commands` | probe token only | the probe protocol ([architecture.md](architecture.md#probes-and-the-hub)); every other route answers 401 or 403 to a probe token |
An invalid `range` or period answers 400, and `range` in the responses is an object `{name,from,to,step,clipped}` (`step` is the timeline granularity in seconds).
API clients send `Authorization: Bearer <URUTAU_TOKEN>`. The peer token is accepted only by the `/api/v1/peer/*` routes (`export`, `stream`, `period`, `egress`, `decisions`, `unban`); every other route answers 403 to it.
API clients send `Authorization: Bearer <URUTAU_TOKEN>`. A probe token is accepted only by the three `/api/v1/probe/*` routes (with the `X-Urutau-Probe` header); every other route refuses it. The 1.x `/api/v1/peer/*` routes are gone (404).
+172
View File
@@ -0,0 +1,172 @@
# Migrating from 1.x to 2.0
Urutau 2.0 replaces peer federation with probes. The hub keeps one node per probe, and each node has its own
data directory in the same format as 1.x. Your registered data is not converted, merged or rewritten: it is
copied byte for byte and then verified. Nothing in this procedure deletes data.
| What | Before (1.6) | After (2.0) |
| --- | --- | --- |
| Primary host (Oracle) | data dir `/data` | the same files, as the hub's own data dir, with no conversion |
| Second host (Hostinger) | its own 1.6 instance, polled as a peer | `urutau import` copies its data dir to `/data/probes/hostinger/` |
| Incident IDs | `INC-3` | `hostinger/INC-3` (the primary host keeps `INC-3`; the old IDs stay valid inside their host) |
Removed variables make the hub refuse to start (`URUTAU_PEERS`, `URUTAU_PEER_TOKEN*`, `URUTAU_PEER_ALLOW`,
`URUTAU_PEER_BLOCKLIST` and the log path variables). See `CHANGELOG.md`.
## What the 1.6 data directory contains
Everything below is copied. Unknown files are copied too.
| Path | Content |
| --- | --- |
| `urutau-state.gob` | snapshot: counters, IP registry, feed, **read offsets of each log** |
| `urutau-state.gob.tmp`, `urutau-state.gob.corrupt` | leftovers of a crash (copied if present) |
| `events/*.jsonl`, `events/*.jsonl.gz`, `events/*.idx` | event registry, one file per day |
| `incidents.json` (+ `incidents.json.corrupt-<ts>`) | incidents with comments, history and suppression |
| `enforce.json` (+ `.tmp`) | ban history, offences and allows of the enforcement engine |
| `tor/` | Tor exit and relay list cache |
| `geo/` | geolocation databases, **skipped by default** (the hub downloads its own; add `--include-geo` to copy) |
| anything else | copied verbatim |
The ban decision files (`decisions.log`, `unban.log`) are not in the data dir: they live on the host
(`/var/log/urutau-enforce`) and stay there; the probe keeps writing them.
## Cutover
Every command below is run per host. Replace `<ts>` with a timestamp. Keep the 1.6 apps and their volumes
untouched until the end: they are the rollback.
### 0. Backup and counts (before changing anything)
On each host:
```sh
docker compose stop urutau # short stop, so the files are consistent
docker run --rm -v urutau-data:/data -v "$PWD":/out alpine \
tar --numeric-owner -czf /out/urutau-data-$(hostname)-<ts>.tgz -C /data .
sha256sum urutau-data-*-<ts>.tgz | tee urutau-data-<ts>.sha256
docker compose start urutau
```
Copy both tarballs and their `.sha256` to the Oracle and to a copy outside both servers (your machine), and
check the sums there. Keep the tarballs for 90 days.
Record the counts. The files give exact numbers (extract each tarball to a scratch directory):
```sh
mkdir -p /tmp/count-oracle && tar -xzf urutau-data-oracle-<ts>.tgz -C /tmp/count-oracle
urutau import --count /tmp/count-oracle # 2.0 binary
# events=... event_files=... ips=... offsets=... incidents=... comments=... suppressed=... enforce_bans=... enforce_allow=...
```
and write down what the running 1.6 API says, as a second opinion (summary for 30 days, incidents, active bans):
```sh
curl -s -H "Authorization: Bearer $URUTAU_TOKEN" 'https://<host>/api/v1/summary?range=30d'
curl -s -H "Authorization: Bearer $URUTAU_TOKEN" 'https://<host>/api/v1/incidents?per_page=1' # "total"
```
Do the same for the Hostinger tarball. Save all numbers in a note.
### 1. New hub on a new volume (Oracle)
Do not reuse the volume in use: that keeps the rollback trivial. Restore the Oracle tarball into a new volume:
```sh
docker volume create urutau2-data
docker run --rm -v urutau2-data:/data -v "$PWD":/in alpine \
tar --numeric-owner -xzf /in/urutau-data-oracle-<ts>.tgz -C /data
```
Start the 2.0 hub on that volume with `URUTAU_NAME` equal to the name the Oracle 1.6 used (the primary node uses
the volume root, exactly the 1.6 format), on an internal port, with no public domain yet. Check that the
primary node's counts equal step 0 (`docker exec <hub> urutau import --count /data`, and the Incidents and
Overview pages).
### 2. Create the probes
```sh
docker exec <hub> urutau probes create oracle # prints the token once
docker exec <hub> urutau probes create hostinger
```
Put each token in the `.env` of its host as `URUTAU_PROBE_TOKEN`. The hub stores only its SHA-256.
### 3. Oracle
Stop the 1.6 app, point the domain to the 2.0 hub and start the Oracle probe
(`URUTAU_HUB_URL=http://urutau:8790` on the internal network). Check on the Sources page: connected, lag under
5 seconds, no gap. The hello answer carries the read offsets saved in the snapshot, so the probe continues
exactly where 1.6 stopped. Keep `URUTAU_ENFORCE=observe` for 30 minutes, confirm `decisions.log` is
receiving lines, then switch to `on`.
### 4. Hostinger
1. Stop the 1.6 app there. Make a final tarball (it contains what arrived since step 0) and copy it to the
Oracle. Extract it into an empty directory, for example `/srv/import/hostinger`.
2. Stop the hub (the import refuses to run while `<data-dir>/.lock` exists):
```sh
docker compose stop urutau
```
3. Rehearse, then import, then verify. The data dir is the hub's volume (mounted at `/data`):
```sh
docker run --rm -v urutau2-data:/data -v /srv/import/hostinger:/from:ro <hub-image> \
urutau import --from /from --host hostinger --data-dir /data --dry-run
docker run --rm -v urutau2-data:/data -v /srv/import/hostinger:/from:ro <hub-image> \
urutau import --from /from --host hostinger --data-dir /data
docker run --rm -v urutau2-data:/data -v /srv/import/hostinger:/from:ro <hub-image> \
urutau import --verify --from /from --host hostinger --data-dir /data
```
The import prints the counts. They must equal the Hostinger numbers from step 0 (plus whatever the final
tarball added). Running the import again prints "already imported" and does nothing.
4. Start the hub. The `hostinger` node shows the same events, IPs and incidents (`hostinger/INC-2` with its
comments, suppressions intact) and ban history. Compare with the numbers you wrote down.
5. Start the Hostinger probe (`URUTAU_HUB_URL=https://<hub domain>`). The hello answer returns the imported
offsets, so there is no gap and no duplicate.
### 5. Observe, then clean up
Watch for one week. Then remove the old Hostinger Coolify app, its domain
(`urutau-hostinger.lucasrguerra.dev.br`), DNS record and certificate. Keep the tarballs 90 days and the old
Oracle volume until you are sure.
## `urutau import` reference
```
urutau import --from DIR --host NAME [--data-dir D] [--dry-run] [--force] [--include-geo]
urutau import --verify --from DIR --host NAME [--data-dir D]
urutau import --count DIR
```
- Copies **everything** in `DIR` to `<data-dir>/probes/NAME/`, into a temporary directory that is renamed into
place only after the copy was verified. Mode and mtime are preserved.
- The check compares the sha256 of every file, then loads the snapshot, the event registry, `incidents.json` and
`enforce.json` with the 1.x code and compares the counts with the source. It also confirms the source did
not change while it was copied. Any difference aborts before anything is installed.
- `import-manifest.json` inside the destination records every hash and the counts. A second run with the same
source prints "already imported" and does nothing.
- If the destination exists with other content, the command fails and changes nothing. `--force` moves it to
`NAME.bak-<timestamp>` next to it; nothing is ever deleted.
- `--dry-run` reads and compares, and writes nothing (not even directories).
- The import refuses to run while `<data-dir>/.lock` exists (the hub is running). While it runs, it holds that
file itself, so the hub cannot start in the middle. A stale file after a crash must be removed by hand.
- `--verify` compares the source with the imported copy (hashes, mode, mtime, counts). Use it before the hub
starts on the destination, because the hub rewrites the snapshot as it runs.
- `--count DIR` never writes to `DIR`.
- Exit status: 0 on success, 1 on any failure, 2 on bad usage.
## Rollback
At any step: stop the hub and the probes, start the 1.6 apps on their original volumes again, restore the DNS.
Those volumes were not touched. At steps 3 and 4 the 1.6 instances were stopped, so starting them resumes from
their own offsets. You lose only what 2.0 processed in between, and the raw logs are still on each host to be
processed again. If an import was wrong, nothing is lost either: the failed copy is never installed, and
`--force` keeps the old one as `.bak-<timestamp>`.
## Résumé en portugais
Veja [pt-BR/migracao-2.0.md](pt-BR/migracao-2.0.md).
+66 -34
View File
@@ -2,11 +2,11 @@
# Arquitetura
O Urutau é um único binário Go sem dependência de terceiros. Tudo roda em um processo.
O Urutau é um único binário Go sem dependência de terceiros. Ele roda em dois papéis: o **hub**, que guarda os dados e serve o dashboard e a API, e a **sonda**, um processo minúsculo em cada servidor monitorado que só lê arquivos de log e os envia ao hub. O mesmo binário faz os dois (`urutau serve` e `urutau probe`); uma imagem scratch separada carrega a sonda.
```
cmd/urutau ponto de entrada: serve, doctor, healthcheck, version
internal/app flags, ligação das peças, runner dos logs, fonte de probes, listas Tor, enforce e egress, doctor
cmd/urutau ponto de entrada: serve (hub), probe, probes, import, doctor, healthcheck, version
internal/app flags, ligação das peças, runner dos logs (alimentado pelas sondas), parser do log de probes, listas Tor, enforce e egress, import, doctor
internal/tail seguidor de arquivo que tolera rotação e leitor de rotacionados
internal/core modelo de evento, parsers (Traefik JSON e texto, sshd, fail2ban), classificador, classes de erro
internal/store estado em memória, resumos, merge, snapshot, análises, serviços, defesa, roster
@@ -18,7 +18,10 @@ internal/ua parser de User-Agent (navegador, sistema, dispositivo, bot
internal/enforce segundo firewall: decisões de ban, arquivo de decisões, pedidos de desban, liberações do operador
internal/egress análise das conexões de saída: workloads, achados (beacon, C2, mineração, varredura...)
internal/incidents chamados abertos a partir de achados de egress ou à mão, guardados em incidents.json
internal/fed hub que consulta os peers, repasse ao vivo, mescla de estudos, troca de decisões e egress
internal/hub um nó por sonda: ingestão, fila de comandos, registro de sondas (probes.json)
internal/wire protocolo sonda-hub: mensagens, limites, validação de linha de comando
internal/probeagent a sonda: seguidores, spool, cliente, aplicação de comandos
internal/fed agregação em processo dos nós (resumos, tabelas de IPs, ao vivo, estudo, geografia)
internal/server handler HTTP, autenticação, rotas da API, relatório HTML, dashboard embutido (web/)
deploy/host kit do host: tabela nftables, rsyslog, logrotate, mapa de contêineres, jail do fail2ban, instalador
```
@@ -28,36 +31,46 @@ A única dependência é a biblioteca padrão do Go.
## Fluxo de dados
```
access.log do Traefik auth.log fail2ban.log probe.log (nft, portas fechadas)
│ │ │ │
└──── tail.Follower (uma goroutine por fonte) ─┘
── em cada servidor monitorado: a sonda (urutau probe) ─────────────────────
Traefik access.log auth.log fail2ban.log probe.log egress.log
│ │ │ │ │
└──── tail.Follower (uma goroutine por fonte, tolera rotação) ┘
containers.map e resolv.conf: arquivo inteiro quando mudam (sha256)
▼
parse (core.ParseTraefik / ParseAuth / ParseFail2ban / parser de probes) → Event
lote (até 5000 linhas / 1 MiB / 1 s) ──► spool em disco ──► push HTTPS
│
── no hub (urutau serve) ────────────────────────────────────────────▼─────
um nó por sonda (store, evlog, incidents, enforce e egress próprios)
checagem de offset (inode ou fim > offset salvo) ──► duplicadas descartadas
▼
origem confiável? descarta. UA de monitor e benigno? conta à parte.
parse (core.ParseTraefik / ParseAuth / ParseFail2ban / parser de probe) → Event
▼
classifica (core): categoria, classe de erro, navegação em forge isenta
CIDRs confiáveis? descarta. UA de monitoramento e benigno? conta à parte.
▼
classifica (core): categoria, classe de erro, navegação de forge isenta
▼
store.Ingest: contadores, registro por IP, feed ao vivo ──► evlog (events/)
▼
intel (calculada sob demanda): família, MITRE, tipo de rede, cadência, sessões,
campanhas, veredito ──► dashboard, API, STIX, blocklist, relatório HTML
intel (calculada sob demanda): família, MITRE, tipo de rede, cadência,
sessões, campanhas, veredito ──► dashboard, API, STIX, blocklist, relatório HTML
▼
enforce (opcional): decisão por IP atacante ──► decisions.log
enforce (opcional): decisão por IP atacante ──► fila de comandos do nó
▼
o long-poll da sonda a recebe, valida a linha e acrescenta em decisions.log
▼
jail "urutau" do fail2ban no host lê decisions.log e bane no firewall
▼
fail2ban.log "Ban urutau" volta como evento (não conta como evidência)
egress.log (nft, conexões novas de saída) ──► egress.Source ──► achados
linhas de egress ──► egress.Source ──► achados
achados ──► incidents (chamados INC-n, supressão) ──► API e relatório
```
Snapshot a cada 60 s: `estado` ◄──► resumos, tabela de IPs, SSE. O segundo firewall nunca ganha privilégios: ele só acrescenta linhas a um arquivo que uma jail do host lê.
Snapshot a cada 60 s: `estado` ◄──► resumos, tabela de IPs, SSE. Nem o hub nem a sonda ganham privilégios: a sonda só acrescenta linhas a um arquivo que uma jail do host lê, e só depois de validar que cada linha tem exatamente o formato que o código de ban do hub produz.
## Fontes
Cada fonte é seguida por sua própria goroutine e reporta um estado: `following`, `waiting` (o arquivo ainda não existe), `backfill` (primeira inicialização, lendo as cópias rotacionadas), `degraded` (mais de 20% das últimas 1000 linhas ilegíveis, com pelo menos 50 amostras) ou `error`. Uma linha maior que 64 KiB é descartada e contada como malformada. Na primeira inicialização sem snapshot, as cópias rotacionadas (`path.1`, `path.N.gz` até 9) são lidas da mais antiga para a mais nova, para que a janela não comece vazia.
Cada fonte é seguida por sua própria goroutine **na sonda** e o hub reporta o estado dela: `following`, `waiting` (o arquivo ainda não existe), `backfill` (primeira inicialização, lendo as cópias rotacionadas), `degraded` (mais de 20% das últimas 1000 linhas ilegíveis, com pelo menos 50 amostras) ou `error`. Uma linha maior que 64 KiB é descartada e contada como malformada. Na primeira inicialização sem snapshot, as cópias rotacionadas (`path.1`, `path.N.gz` até 9) são lidas da mais antiga para a mais nova, para que a janela não comece vazia.
As linhas são decodificadas assim:
@@ -66,7 +79,7 @@ As linhas são decodificadas assim:
- **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.
- **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 são expostos: nem o dashboard nem o export de um peer mostram de onde uma fonte lê, só o nome e o estado dela.
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.
Linhas válidas que não trazem nada a registrar são ignoradas em silêncio; linhas que não dá para interpretar são contadas como malformadas e aparecem por fonte no dashboard.
@@ -152,7 +165,7 @@ Um **visitante** é uma pessoa com navegador real: um GET bem-sucedido (2xx) de
`<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.
O que entra: eventos maliciosos (scanner, exploit, bruteforce, ssh-fail, ssh-probe), ban e unban, logins SSH bem-sucedidos, um 404 respondido a uma ferramenta de ataque, e respostas `ok` ou `notfound` só de endereços já suspeitos ou hostis (para mostrar o que receberam). Nunca um visitante legítimo. Eventos repassados por peers são registrados com o nome do peer como host.
O que entra: eventos maliciosos (scanner, exploit, bruteforce, ssh-fail, ssh-probe), ban e unban, logins SSH bem-sucedidos, um 404 respondido a uma ferramenta de ataque, e respostas `ok` ou `notfound` só de endereços já suspeitos ou hostis (para mostrar o que receberam). Nunca um visitante legítimo. Cada evento é registrado com o nome da sonda que o enviou como host.
Comportamento em falha: disco cheio, o teto de tamanho ou o teto diário descartam eventos (contados, registrados no log no máximo de vez em quando, nunca fatais); uma linha corrompida é ignorada na leitura; uma linha parcial deixada por uma falha anterior é terminada antes da próxima escrita.
@@ -211,7 +224,7 @@ Regras (vale a primeira que casar, por endereço):
Uma varredura a cada 10 minutos, e depois do backfill da partida, aplica as mesmas regras aos endereços ativos nas últimas 24 horas que nada bloqueia ainda. No máximo `--enforce-max-per-min` decisões são gravadas por minuto (padrão 60); o excedente é descartado e contado. O TTL consultivo cresce com o número de bans anteriores: 1 h, 6 h, 24 h, 7 d.
Nunca são banidos: faixas privadas e reservadas, `--trusted`, as faixas da Cloudflare, resolvedores públicos conhecidos, os peers e os endereços do próprio servidor, um crawler verificado, um endereço com visita legítima nas últimas 24 horas e uma liberação do operador (abaixo). Cada exclusão é contada por motivo.
Nunca são banidos: faixas privadas e reservadas, `--trusted`, as faixas da Cloudflare, resolvedores públicos conhecidos, os endereços das sondas e dos próprios servidores, um crawler verificado, um endereço com visita legítima nas últimas 24 horas e uma liberação do operador (abaixo). Cada exclusão é contada por motivo.
Arquivo de decisões, uma linha por ban (`MaxLogBytes` de 20 MB, depois rotacionado para `.1`):
@@ -223,7 +236,7 @@ Nada que o atacante controla entra na linha: o endereço é reformatado, o motiv
Desban: `POST /api/v1/enforce/unban` acrescenta `<hora> urutau unban ip=<ip> allow=<segundos>` ao arquivo de desban (`--enforce-unban-log`, por padrão `unban.log` ao lado do arquivo de decisões); uma unit `path` do systemd do kit do host libera o bloqueio do fail2ban. Com `allow` maior que zero o motor não bane o endereço de novo por esse tempo (no máximo 30 dias); `DELETE /api/v1/enforce/allow` encerra a liberação.
Compartilhamento (`--enforce-share=on`): hub e peers trocam decisões por `GET` e `POST /api/v1/peer/decisions` e desbans por `POST /api/v1/peer/unban`. Cada lado aplica as próprias exclusões, aceita só os slugs fixos de motivo, limita o TTL a 6 horas e, pela palavra de um peer, só bane um endereço que ele também viu atacar nos últimos 7 dias (senão a exclusão é `peer_unconfirmed`).
Compartilhamento (`--enforce-share=on`): uma decisão tomada pelo nó de uma sonda também é enfileirada para os nós das outras. Cada nó aplica as próprias exclusões, aceita só os slugs fixos de motivo, limita o TTL a 6 horas e, pela palavra de outro nó, só bane um endereço que ele também viu atacar nos últimos 7 dias (senão a exclusão é `peer_unconfirmed`).
## Análise de egress
@@ -244,7 +257,7 @@ Achados (`kind`, severidade):
| `scan` | abertura para mais de 50 destinos ou 100 portas em 10 minutos, fora de workloads `scanner` |
| `new_geo` | primeiro contato com um país depois do tempo de aprendizado do workload (24 h) |
Destinos de peers, endereços confiáveis e os endereços públicos do próprio servidor nunca geram achados, e conexões regulares a grandes CDNs e nuvens têm severidade baixa, salvo se o destino atacou o servidor. Limites: 50.000 pares e destinos, 2.000 achados, 720 buckets por hora. `GET /api/v1/egress` devolve achados, workloads, países e uma linha do tempo por hora; um hub também mescla a resposta de `GET /api/v1/peer/egress` de cada peer.
Destinos das sondas, endereços confiáveis e os endereços públicos do próprio servidor nunca geram achados, e conexões regulares a grandes CDNs e nuvens têm severidade baixa, salvo se o destino atacou o servidor. Limites: 50.000 pares e destinos, 2.000 achados, 720 buckets por hora. `GET /api/v1/egress` devolve achados, workloads, países e uma linha do tempo por hora; o hub mescla o relatório de egress de todos os nós. A configuração de egress (workloads, resolvedores, destinos permitidos) fica por sonda no hub, em `probes.json`.
## Incidentes
@@ -256,23 +269,39 @@ Destinos de peers, endereços confiáveis e os endereços públicos do próprio
## Estado e persistência
O estado vive em memória: buckets por minuto das últimas 48 horas e dados por hora até 30 dias, listas de top por hora (caminhos, domínios, User-Agents, usuários), uma tabela de até 20.000 IPs (quando cheia, 10% com a menor pontuação são removidos; IPs banidos são mantidos), um feed dos últimos 500 eventos e os bans ativos. `--retention` (1h a 720h) limita quanto tempo os IPs ficam; IPs antigos são podados a cada 10 minutos.
Cada nó (um por sonda) mantém o próprio estado em memória: buckets por minuto das últimas 48 horas e dados por hora até 30 dias, listas de top por hora (caminhos, domínios, User-Agents, usuários), uma tabela de até 20.000 IPs (quando cheia, 10% com a menor pontuação são removidos; IPs banidos são mantidos), um feed dos últimos 500 eventos e os bans ativos. `--retention` (1h a 720h) limita quanto tempo os IPs ficam; IPs antigos são podados a cada 10 minutos.
A cada 60 segundos, e no desligamento, o estado é gravado em `urutau-state.gob` no diretório de dados junto com o inode e a posição de cada fonte. Na inicialização ele é restaurado e cada fonte retoma exatamente de onde parou, então um reinício nunca conta um log duas vezes. O snapshot é pulado enquanto um backfill roda. Um snapshot ilegível é movido para `urutau-state.gob.corrupt` e o serviço sobe vazio, lendo os logs de novo (incluindo as cópias rotacionadas).
A cada 60 segundos, e no desligamento, cada nó grava o estado em `urutau-state.gob` junto com o inode e a posição de cada fonte. O nó primário (a sonda cujo nome é igual a `URUTAU_NAME`) usa a raiz do data-dir, exatamente o layout da 1.x; os demais usam `<data-dir>/probes/<nome>/`. Na inicialização o estado é restaurado e o hub informa a cada sonda, no `hello`, as posições que tem, então um reinício nunca conta um log duas vezes. O snapshot é pulado enquanto um backfill roda. Um snapshot ilegível é movido para `urutau-state.gob.corrupt` e o serviço sobe vazio, lendo os logs de novo (incluindo as cópias rotacionadas).
O processo define um limite suave de memória de 256 MiB, a menos que `GOMEMLIMIT` esteja definido. O pior caso medido é cerca de 54 MiB de heap e um snapshot de cerca de 27 MB.
## Federação
## Sondas e o hub
Um hub é uma instância comum iniciada com `--peer nome=https://url`, e precisa de `URUTAU_PEER_TOKEN`. A cada 15 segundos ele chama `GET /api/v1/peer/export?range=...` de cada peer (para os intervalos de fundo `1h`, `24h`, `7d` e `30d`; qualquer outro intervalo ou período personalizado é buscado sob demanda) com o token de peer e guarda a última resposta. O export é `{"v":1,"summary":...,"traffic":{...}}` com os 500 IPs principais e seus detalhes, em cache de 5 segundos no peer. O token de peer abre só as rotas de federação: o export, o stream ao vivo, `GET /api/v1/peer/period` (o estudo de sessões, campanhas e métricas que o hub mescla para um período ou um IP; um peer executa no máximo dois ao mesmo tempo), `GET /api/v1/peer/egress` (o relatório de egress) e, com `--enforce-share`, `GET` e `POST /api/v1/peer/decisions` e `POST /api/v1/peer/unban`. O hub nunca segue redirects, exige `https` fora de loopback, usa timeout de 4 segundos, limita o corpo a 8 MB e sanitiza e limita o que um peer enviar. Um peer que falha é marcado offline e os demais seguem. O seletor de host do dashboard passa a oferecer `all`, o próprio hub e cada peer; resumos, tráfego e tabelas de IPs são mesclados, e cada linha carrega o host de origem.
A sonda é cliente do hub: não abre porta nenhuma. É HTTPS comum, sem WebSocket, então qualquer proxy reverso ou CDN serve (as requisições são curtas; o long-poll dura no máximo 25 s). A autenticação é `Authorization: Bearer urp_...` mais `X-Urutau-Probe: <nome>`. O hub guarda só o SHA-256 de cada token (`probes.json`) e compara em tempo constante; um token errado recebe um 401 sem corpo, sob o mesmo limitador de tentativas do login. `http://` puro só é aceito para endereços de loopback ou privados (por exemplo `http://urutau:8790` na rede `urutau-edge`).
### Repasse ao vivo
| Rota | Função |
|---|---|
| `POST /api/v1/probe/hello` | início de toda sessão: versão do protocolo na entrada, as posições que o hub tem na saída (uma sonda sem estado local começa a partir delas). 409 se a versão for incompatível |
| `POST /api/v1/probe/push` | um lote (`seq`, até 5000 linhas, gzip opcional, 2 MiB no fio e 8 MiB descomprimido, linha de no máximo 64 KiB) e o status da sonda. O hub aplica o lote inteiro no nó e responde `ack = seq`; um `seq` repetido é respondido sem reaplicar. 503 com `Retry-After` enquanto o nó carrega ou a fila está cheia, 429 para um segundo push simultâneo |
| `GET /api/v1/probe/commands?after=<seq>&wait=<s>` | long-poll (no máximo 25 s) de linhas de ban e unban; responde na hora quando a fila tem um comando mais novo que `after` |
Além do export, um hub mantém uma conexão `GET /api/v1/peer/stream` aberta por peer (uma assinatura por peer, com o token do próprio peer) e repassa os eventos maliciosos ao vivo para o dashboard. O que vem de um peer é limitado e sanitizado: no máximo cerca de 50 eventos por segundo por peer, linhas de no máximo 16 KB, um buffer dos últimos 500 eventos repassados (servido por `/api/v1/live/recent`) e reconexão com backoff de 1 s até 60 s. Um peer atende no máximo 10 conexões de stream.
**Spool.** Antes de enviar, a sonda grava cada lote em `<state-dir>/spool/NNNNNNNNNNNN.json` e envia na ordem, então uma queda do hub não perde nada. O spool é limitado por `URUTAU_PROBE_SPOOL_MAX` (64 MiB por padrão); ao passar, o lote mais antigo é apagado e suas linhas somam no contador `dropped` do status da sonda, que a página Fontes mostra. O `state.json` guarda a sequência dos lotes, o último comando aplicado e a posição de leitura de cada fonte, gravado de forma atômica depois de cada ack. Depois de um erro a sonda reconecta com backoff exponencial de 1 s a 60 s e jitter de 20%.
**Posições.** O hub é a autoridade: guarda a posição de cada fonte no snapshot do nó e só aceita uma linha se o inode for diferente do salvo ou se o offset final passar dele. Reenviar um spool, ou importar um data-dir da 1.x (`urutau import`), portanto não duplica nem pula linhas.
**Vida.** Sem nada para enviar, a sonda manda um lote vazio com o status a cada 15 s; o hub a marca como offline depois de 45 s sem push.
**Comandos.** O hub enfileira até 10.000 comandos por nó (`commands.json`); os mais antigos são descartados e contados. A sonda só aceita um comando se `wire.ValidCmdLine` passar (o formato exato de uma linha de ban ou unban, com endereço, slug de motivo e TTL válidos), acrescenta com `O_APPEND` e `fsync` e registra a sequência para que um comando repetido não seja gravado duas vezes. Uma linha inválida é contada em `cmd_errors` e nunca gravada. Uma sonda com `URUTAU_ENFORCE_LOG` vazio ignora comandos de ban e conta o erro.
**Tamanho.** A sonda nunca chama geolocalização, inteligência nem o store; a meta de memória é abaixo de 20 MB de RSS, verificada por um teste, e a imagem tem menos de 15 MB.
### Agregação entre sondas
`internal/fed` junta os nós dentro do processo (sem HTTP): o seletor de host do dashboard oferece `all` e cada sonda; resumos, tráfego, tabelas de IPs, estudos e o feed ao vivo mesclam os nós e cada linha leva o host de onde veio. Um incidente é identificado como `host/INC-n` (cada nó numera os seus); um `INC-n` sem host vale para o nó primário.
### Agregação de geografia
`GET /api/v1/geo` é calculado a partir da tabela de IPs (local e os exports dos peers) combinada com as bases de geolocalização: primeiro os países e, para um país, suas regiões, cidades e principais IPs. Os resultados ficam em cache por 5 segundos, num cache de no máximo 256 chaves.
`GET /api/v1/geo` é calculado a partir da tabela de IPs (de todos os nós) combinada com as bases de geolocalização: primeiro os países e, para um país, suas regiões, cidades e principais IPs. Os resultados ficam em cache por 5 segundos, num cache de no máximo 256 chaves.
## Camada HTTP
@@ -280,7 +309,7 @@ O servidor define timeouts de leitura, escrita e ociosidade, `MaxHeaderBytes` de
## Rotas da API
Todas as rotas `/api/v1/*`, exceto as de federação, exigem `URUTAU_TOKEN` (bearer) ou um cookie de sessão; o token de peer recebe 403 nelas. As rotas de análise ficam em arquivos `internal/server/api_<nome>.go` e se registram com `registerUserRoute`. As rotas que recebem intervalo aceitam `range`, ou `from` e `to`.
As rotas de usuário em `/api/v1/*` exigem `URUTAU_TOKEN` (bearer) ou um cookie de sessão; as rotas `/api/v1/probe/*` exigem um token de sonda e nada mais as abre. As rotas `/api/v1/peer/*` da 1.x não existem mais (404). As rotas de análise ficam em arquivos `internal/server/api_<nome>.go` e se registram com `registerUserRoute`. As rotas que recebem intervalo aceitam `range`, ou `from` e `to`.
| Rota | Finalidade |
|---|---|
@@ -299,8 +328,8 @@ Todas as rotas `/api/v1/*`, exceto as de federação, exigem `URUTAU_TOKEN` (bea
| `GET /api/v1/egress` | achados de saída |
| `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/peer/export`, `/peer/stream`, `/peer/period`, `/peer/egress` | federação, só token de peer |
| `GET`, `POST /api/v1/peer/decisions`, `POST /api/v1/peer/unban` | compartilhamento de decisões, só token de peer, `--enforce-share` |
| `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) |
| `POST /api/v1/probe/hello`, `/probe/push`, `GET /probe/commands` | protocolo da sonda, só token de sonda |
Os endpoints de lista (IPs, sessões, campanhas, eventos de um endereço) são paginados pelo backend; a busca de eventos pagina por cursor.
@@ -308,11 +337,14 @@ Os endpoints de lista (IPs, sessões, campanhas, eventos de um endereço) são p
| Onde | O quê |
|---|---|
| `<data-dir>/urutau-state.gob` | snapshot do estado com o offset de cada fonte (`.corrupt` quando ilegível) |
| `<data-dir>/urutau-state.gob` | snapshot do nó primário com o offset de cada fonte (`.corrupt` quando ilegível) |
| `<data-dir>/probes/<nome>/` | o mesmo layout (snapshot, `events/`, `incidents.json`, `enforce.json`, `commands.json`) para cada outra sonda |
| `<data-dir>/probes.json` | registro de sondas: nome, SHA-256 do token, localização, configuração de egress (nunca o token) |
| `<data-dir>/events/AAAA-MM-DD.jsonl[.gz]` | registro de eventos, uma linha JSON por evento |
| `<data-dir>/geo/` | bases DB-IP Lite de cidade e ASN |
| `<data-dir>/tor/` | cache das listas de saídas e relays do Tor |
| `<data-dir>/enforce.json` | estado do segundo firewall |
| `<data-dir>/incidents.json` | chamados |
| `--enforce-log`, `unban.log` | arquivo de decisões lido pela jail do host e pedidos de desban lidos pelo host |
| `--probe-log`, `--egress-log`, `--egress-containers` | logs do kernel e mapa de contêineres escritos pelo kit do host em `deploy/host` |
| `<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` |
+70 -29
View File
@@ -3,26 +3,27 @@
# Terminal
```
urutau serve [flags] roda o daemon e o dashboard
urutau serve [flags] roda o hub: dashboard, API e ingestão das sondas (alias: urutau hub)
urutau probe [flags] roda uma sonda: lê os logs locais e os envia ao hub
urutau probes create|list|revoke gerencia as sondas registradas em um hub
urutau import --from DIR --host NOME traz um diretório de dados da 1.x para um hub
urutau doctor [--json] [flags] confere as fontes e o diretório de dados
urutau healthcheck [flags] sai com 0 quando o daemon local responde /api/health
urutau version imprime a versão
urutau help imprime o uso
```
O token de acesso nunca é uma flag: `urutau serve` o lê da variável de ambiente `URUTAU_TOKEN`, ou do arquivo indicado por `URUTAU_TOKEN_FILE`, para que não apareça na lista de processos. Tokens precisam de pelo menos 32 caracteres e cerca de 128 bits de entropia estimada (comprimento vezes entropia de Shannon; tokens periódicos ou sequenciais são recusados) (`openssl rand -base64 48` é o recomendado (`-hex 32` também serve)). Toda flag abaixo tem um padrão por variável `URUTAU_*`; a flag vence a variável. Veja [configuracao.md](configuracao.md).
O token de acesso nunca é uma flag: `urutau serve` e `urutau probe` leem o seu (`URUTAU_TOKEN` e `URUTAU_PROBE_TOKEN`) da variável de ambiente, ou do arquivo indicado pelo mesmo nome com `_FILE`, para que não apareça na lista de processos. Tokens precisam de pelo menos 32 caracteres e cerca de 128 bits de entropia estimada (comprimento vezes entropia de Shannon; tokens periódicos ou sequenciais são recusados) (`openssl rand -base64 48` é o recomendado (`-hex 32` também serve)). Toda flag abaixo tem um padrão por variável `URUTAU_*`; a flag vence a variável. Veja [configuracao.md](configuracao.md).
## `urutau serve`
O hub não lê nenhum arquivo de log: as linhas vêm das sondas ([arquitetura.md](arquitetura.md#sondas-e-o-hub)). As flags de caminho de log da 1.x (`--traefik-log`, `--auth-log`, `--fail2ban-log`, `--probe-log`, `--egress-log`, `--egress-containers`, `--enforce-log`, `--enforce-unban-log`) e as de federação (`--peer*`) foram removidas; o hub se recusa a subir quando as variáveis `URUTAU_*` delas estão definidas, e a mensagem aponta para [migracao-2.0.md](migracao-2.0.md).
| Flag | Variável | Padrão | Significado |
|---|---|---|---|
| `--bind` | `URUTAU_BIND` | `0.0.0.0:8790` | endereço de escuta |
| `--name` | `URUTAU_NAME` | hostname | nome desta instância |
| `--data-dir` | `URUTAU_DATA_DIR` | `/data` | diretório de estado: snapshot `urutau-state.gob`, `geo/`, `tor/`, `events/`, `incidents.json`, `enforce.json` |
| `--traefik-log` | `URUTAU_TRAEFIK_LOG` | `/data/coolify/proxy/access.log` | access log JSON do Traefik; vazio desativa |
| `--auth-log` | `URUTAU_AUTH_LOG` | `/var/log/auth.log` | log do sshd; vazio desativa |
| `--fail2ban-log` | `URUTAU_FAIL2BAN_LOG` | `/var/log/fail2ban.log` | log do fail2ban; vazio desativa |
| `--probe-log` | `URUTAU_PROBE_LOG` | `/logs/host/probe.log` | log do kernel de conexões a portas não servidas, gravado pelo kit do host; vazio desativa |
| `--name` | `URUTAU_NAME` | hostname | nome desta instância e da sonda primária: aquela cujos dados ficam na raiz do data-dir |
| `--data-dir` | `URUTAU_DATA_DIR` | `/data` | diretório de estado: snapshot `urutau-state.gob`, `geo/`, `tor/`, `events/`, `incidents.json`, `enforce.json` da sonda primária, `probes/<nome>/` das demais, `probes.json` |
| `--trusted` | `URUTAU_TRUSTED` | vazio | CIDRs de origens confiáveis; os eventos delas são descartados por completo. `--ignore` / `URUTAU_IGNORE` é um alias |
| `--ignore` | `URUTAU_IGNORE` | `127.0.0.0/8,::1,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,fc00::/7,fe80::/10,100.64.0.0/10,169.254.0.0/16` | mesma função de `--trusted`, com as faixas privadas como padrão |
| `--monitor-ua` | `URUTAU_MONITOR_UA` | `(?i)^(Uptime-Kuma/\|Beszel\|Coolify\|kube-probe/\|Go-http-client/.*healthcheck)` | expressão regular de User-Agents de monitoramento; vazio desativa |
@@ -30,42 +31,82 @@ O token de acesso nunca é uma flag: `urutau serve` o lê da variável de ambien
| `--domains` | `URUTAU_DOMAINS` | vazio | lista de domínios do analytics (exatos ou `*.exemplo.com`); vazio acompanha todo domínio que responde 2xx; recomendado quando um backend responde 2xx para qualquer Host |
| `--geo-dir` | `URUTAU_GEO_DIR` | `<data-dir>/geo` | diretório das bases DB-IP Lite (cidade e ASN) |
| `--geo-update` | `URUTAU_GEO_UPDATE` | `24h` | de quanto em quanto tempo procurar uma base mais nova; `0` desliga o download |
| `--peer` | `URUTAU_PEERS` | nenhum | peer `nome=https://url`; repita a flag ou separe a variável por vírgula |
| `--peer-token` | `URUTAU_PEER_TOKEN` | vazio | token compartilhado com os peers; prefira a variável ou `URUTAU_PEER_TOKEN_FILE` (uma flag aparece na lista de processos). Por peer: `URUTAU_PEER_TOKEN_<NOME>` |
| `--admin-users` | `URUTAU_ADMIN_USERS` | vazio | usuários SSH cujo login bem-sucedido mantém o IP fora da blocklist por 24 h; a imunidade fica desligada se não definido |
| `--peer-allow` | `URUTAU_PEER_ALLOW` | vazio | CIDRs de origem autorizados a chamar as rotas de federação; vazio aceita qualquer origem com o token |
| `--peer-blocklist` | `URUTAU_PEER_BLOCKLIST` | `on` | `on` lista na blocklist do hub os IPs hostis vistos só pelos peers (pontuação 50+ e sinal forte); `off` restringe a blocklist aos IPs da própria instância |
| `--location` | `URUTAU_LOCATION` | vazio | posição desta instância no mapa, `"lat,lon"` ou `"lat,lon,Rótulo"` |
| `--trusted-proxy` | `URUTAU_TRUSTED_PROXY` | `127.0.0.0/8,::1` (o compose define `10.250.0.0/24`) | proxies cujo `X-Forwarded-For` é confiável, lido da direita para a esquerda (limite de login, `--peer-allow`) |
| `--location` | `URUTAU_LOCATION` | vazio | posição padrão da sonda primária no mapa (cada sonda tem a sua, definida no hub), `"lat,lon"` ou `"lat,lon,Rótulo"` |
| `--trusted-proxy` | `URUTAU_TRUSTED_PROXY` | `127.0.0.0/8,::1` (o compose define `10.250.0.0/24`) | proxies cujo `X-Forwarded-For` é confiável, lido da direita para a esquerda (limite de login, limitador de autenticação das sondas) |
| `--retention` | `URUTAU_RETENTION` | `720h` | por quanto tempo os dados ficam (1h a 720h, ou seja, 30 dias) |
| `--events-max` | `URUTAU_EVENTS_MAX` | `512MB` | teto de tamanho do registro de eventos em `<data-dir>/events`; `0` desliga |
| `--tor-auto` | `URUTAU_TOR_AUTO` | `on` | `on` baixa as listas oficiais de saídas e relays do Tor a cada 6 h em `<data-dir>/tor`; `off` não baixa |
| `--tor-exits` | `URUTAU_TOR_EXITS` | vazio | arquivo com endereços de saída do Tor, um por linha, recarregado a cada 24 h quando muda; vazio desativa |
| `--enforce` | `URUTAU_ENFORCE` | `off` | segundo firewall: `off`, `observe` (decide só em memória) ou `on` (também grava as decisões para o fail2ban do host) |
| `--enforce-log` | `URUTAU_ENFORCE_LOG` | `/logs/enforce/decisions.log` | arquivo de decisões acrescentado no modo `on` (obrigatório nele) |
| `--enforce-unban-log` | `URUTAU_ENFORCE_UNBAN_LOG` | `unban.log` ao lado de `--enforce-log` | arquivo onde o botão Desbanir grava os pedidos |
| `--enforce-share` | `URUTAU_ENFORCE_SHARE` | `off` | `on` troca decisões e desbanimentos com os peers; cada lado aplica suas exclusões |
| `--enforce-share` | `URUTAU_ENFORCE_SHARE` | `off` | `on` também enfileira nas outras sondas uma decisão tomada para uma; cada nó aplica suas exclusões |
| `--enforce-threshold` | `URUTAU_ENFORCE_THRESHOLD` | `5` | eventos de ataque em 10 minutos que justificam um banimento (1 a 1000) |
| `--enforce-max-per-min` | `URUTAU_ENFORCE_MAX_PER_MIN` | `60` | máximo de decisões por minuto, o excedente é descartado e contado (1 a 10000) |
| `--egress` | `URUTAU_EGRESS` | `auto` | análise de egress: `auto` (liga quando `--egress-log` existe), `on` ou `off` |
| `--egress-log` | `URUTAU_EGRESS_LOG` | `/logs/host/egress.log` | log do kernel de conexões novas de saída, gravado pelo kit do host |
| `--egress-containers` | `URUTAU_EGRESS_CONTAINERS` | `/logs/host/containers.map` | mapa `"<ip> <container>"` gravado pelo kit do host |
| `--egress-workloads` | `URUTAU_EGRESS_WORKLOADS` | vazio | `"nome=ITEM,ITEM:papel;..."`, papéis `default`, `scanner`, `mail`, `resolver` ([configuracao.md](configuracao.md#análise-de-egress)) |
| `--egress-resolvers` | `URUTAU_EGRESS_RESOLVERS` | vazio | resolvedores DNS permitidos, separados por vírgula; vazio: os públicos usuais mais o `resolv.conf` do host |
| `--egress` | `URUTAU_EGRESS` | `auto` | análise de egress: `auto` (liga para uma sonda que envia o log de egress), `on` ou `off` |
| `--egress-workloads` | `URUTAU_EGRESS_WORKLOADS` | vazio | padrão da sonda primária (por sonda, edite no hub): `"nome=ITEM,ITEM:papel;..."`, papéis `default`, `scanner`, `mail`, `resolver` ([configuracao.md](configuracao.md#análise-de-egress)) |
| `--egress-resolvers` | `URUTAU_EGRESS_RESOLVERS` | vazio | resolvedores DNS permitidos, separados por vírgula; vazio: os públicos usuais mais o `resolv.conf` que a sonda envia |
| `--insecure-no-auth` | nenhuma | desligado | desativa a autenticação; só em bind loopback |
`URUTAU_EGRESS_ALLOW` e `URUTAU_EGRESS_PROVIDER_ASN` existem só como variáveis de ambiente ([configuracao.md](configuracao.md)). `GOMEMLIMIT` e `TZ` são as padrão.
Validação na partida (qualquer falha sai com código 1 antes de escutar): `URUTAU_TOKEN` e todo token de peer precisam de pelo menos 32 caracteres e cerca de 128 bits de entropia estimada (tokens periódicos ou sequenciais são recusados), e um token de peer deve ser diferente de `URUTAU_TOKEN`, exceto com `--insecure-no-auth` em bind loopback; peers devem ser `nome=https://host` (`http` simples só em loopback), nomes únicos e diferentes de `all` e do nome da própria instância, e cada peer precisa de um token de cliente (`URUTAU_PEER_TOKEN_<NOME>` ou o geral `URUTAU_PEER_TOKEN`), sem dois nomes que resultem na mesma variável; `--retention` de 1h a 720h; `--events-max` um tamanho válido; `--location` válida; `--peer-blocklist` e `--enforce-share` `on`/`off`; `--enforce` `off`/`observe`/`on` (`on` exige `--enforce-log`); `--enforce-threshold` de 1 a 1000 e `--enforce-max-per-min` de 1 a 10000; `--egress` `auto`/`on`/`off`; `--monitor-ua` uma expressão regular válida; `--ignore`, `--trusted`, `--peer-allow`, `--trusted-proxy` e `--monitor-from` CIDRs ou IPs válidos.
Validação na partida (qualquer falha sai com código 1 antes de escutar): `URUTAU_TOKEN` precisa de pelo menos 32 caracteres e cerca de 128 bits de entropia estimada (tokens periódicos ou sequenciais são recusados), exceto com `--insecure-no-auth` em bind loopback; nenhuma das variáveis removidas da 1.x pode estar definida; `--retention` de 1h a 720h; `--events-max` um tamanho válido; `--location` válida; `--enforce-share` `on`/`off`; `--enforce` `off`/`observe`/`on`; `--enforce-threshold` de 1 a 1000 e `--enforce-max-per-min` de 1 a 10000; `--egress` `auto`/`on`/`off`; `--monitor-ua` uma expressão regular válida; `--ignore`, `--trusted`, `--trusted-proxy` e `--monitor-from` CIDRs ou IPs válidos.
```bash
export URUTAU_TOKEN=$(openssl rand -base64 48)
urutau serve --bind 127.0.0.1:8790 --data-dir ./data \
--traefik-log "" --auth-log /var/log/auth.log
urutau serve --bind 127.0.0.1:8790 --data-dir ./data
```
O daemon registra logs no stderr, salva um snapshot em `SIGTERM` ou `SIGINT` e sai com 0 numa parada limpa.
## `urutau probe`
A sonda roda em cada servidor monitorado. Não abre porta: segue os arquivos de log, guarda em spool no disco e os envia ao hub por HTTPS, e aplica os comandos de ban e desban que o hub manda ([arquitetura.md](arquitetura.md#sondas-e-o-hub)). Flags e variáveis, com as mesmas regras de `serve`:
| Flag | Variável | Padrão | Significado |
|---|---|---|---|
| `--hub` | `URUTAU_HUB` | obrigatória | URL do hub; `https://`, ou `http://` só para endereços de loopback e privados |
| `--name` | `URUTAU_PROBE_NAME` | obrigatório | nome registrado no hub |
| nenhuma | `URUTAU_PROBE_TOKEN` ou `URUTAU_PROBE_TOKEN_FILE` | obrigatório | token impresso uma vez por `urutau probes create` (`urp_...`); nunca uma flag |
| `--state-dir` | `URUTAU_STATE_DIR` | `/state` | spool, posições e marca de vida |
| `--traefik-log` | `URUTAU_TRAEFIK_LOG` | `/logs/traefik/access.log` | log de acesso do Traefik; vazio desliga |
| `--auth-log` | `URUTAU_AUTH_LOG` | `/logs/host/auth.log` | log do sshd; vazio desliga |
| `--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 |
| `--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 |
| `--enforce-unban-log` | `URUTAU_ENFORCE_UNBAN_LOG` | `/logs/enforce/unban.log` | onde os pedidos de desban são acrescentados; vazio os ignora |
| `--spool-max` | `URUTAU_PROBE_SPOOL_MAX` | `64MiB` | teto do spool; os lotes mais antigos são descartados e contados |
| `--location` | `URUTAU_LOCATION` | vazio | `"lat,lon,Rótulo"`; a configuração do hub prevalece |
`urutau probe --check` lê a marca de vida no diretório de estado e sai com 0 quando a sonda está viva; é o `HEALTHCHECK` da imagem da sonda, que não tem shell. Hub, nome ou token ausentes param a sonda na partida com uma mensagem clara.
## `urutau probes`
Gerencia o registro (`<data-dir>/probes.json`) de um hub. Sem `--url` age direto no diretório de dados (pare o hub antes, ou espere que ele recarregue na próxima alteração); com `--url` e o token de usuário usa a API.
```bash
urutau probes create oracle # imprime o token UMA vez; o hub guarda só o SHA-256
urutau probes list # nome, estado, última linha, atraso, versão, descartadas
urutau probes revoke hostinger # a sonda é recusada daí em diante; os dados ficam
```
Os nomes têm de 1 a 32 caracteres: letras minúsculas, dígitos e `-`, começando por letra ou dígito (o nome também é o subdiretório de dados). A página Fontes do dashboard faz o mesmo e ainda edita a localização e a configuração de egress de cada sonda.
## `urutau import`
Traz o diretório de dados de uma instância 1.x para um hub como uma sonda, sem perder nada ([migracao-2.0.md](migracao-2.0.md)).
```bash
urutau import --from /backup/hostinger/data --host hostinger --dry-run # o que seria copiado
urutau import --from /backup/hostinger/data --host hostinger # com o hub parado
urutau import --verify --from /backup/hostinger/data --host hostinger # compara hashes e contagens
urutau import --count /data # imprime eventos, IPs, incidentes, bans
```
Copia o diretório inteiro por um diretório temporário e um rename atômico, confere todos os SHA-256 e as contagens, e é idempotente (uma segunda execução informa `skipped`). Um destino diferente falha, a menos que use `--force`, que o move para `.bak-<timestamp>` e nunca apaga. Recusa rodar enquanto o hub segura o lock do data-dir.
## Ruído e monitoramento
```bash
@@ -79,11 +120,11 @@ urutau serve --trusted "10.0.0.0/8,203.0.113.7" \
```bash
urutau serve --enforce observe # decide em memória, não grava nada
urutau serve --enforce on --enforce-log /var/log/urutau-enforce/decisions.log
urutau serve --egress on --egress-workloads "mail=10.0.7.0/24:mail"
urutau serve --enforce on # as decisões vão às sondas; cada uma as acrescenta em seu decisions.log
urutau serve --egress on --egress-workloads "mail=10.0.7.0/24:mail" # sonda primária; as outras: página Fontes
```
O lado do host (registro com nftables, jail `urutau` do fail2ban) vem de `deploy/host/install.sh`, veja [docker.md](docker.md#kit-do-host).
O lado do host (registro com nftables, jail `urutau` do fail2ban) vem de `deploy/host/install.sh --probe`, veja [docker.md](docker.md#kit-do-host).
## Geolocalização
@@ -95,7 +136,7 @@ O Urutau baixa as bases DB-IP Lite de cidade e ASN em `--geo-dir` quando faltam
## `urutau doctor`
Confere a configuração (token, peers, bind e todas as validações acima), cada fonte de log (legível, tamanho; no Traefik também se mais de 20% das linhas são malformadas), se o diretório de dados é gravável, o segundo firewall, as bases de geolocalização e o snapshot. Os logs de sondagem e egress não são conferidos. Os checks se chamam `config`, `source traefik`, `source ssh`, `source fail2ban`, `source traefik format`, `data-dir`, `enforce` (e `enforce-cdn`), `geo` e `state`. Os estados são `ok`, `warn` (uma fonte que ainda não abre), `fail` e `off` (desativada). O código de saída é 1 quando algum check é `fail` (por exemplo `--enforce=on` com o arquivo de decisões não gravável), o que o torna útil num script de deploy. Aceita as mesmas flags de `serve`.
Confere a configuração (token, bind e todas as validações acima), se o diretório de dados é gravável, as sondas registradas e o estado delas, o segundo firewall, as bases de geolocalização e o snapshot. O hub não tem fonte de log para conferir: o que cada sonda lê é reportado pela própria sonda na página Fontes. Os checks se chamam `config`, `data-dir`, `probes`, `enforce` (e `enforce-cdn`), `geo` e `state`. Os estados são `ok`, `warn` (uma sonda offline), `fail` e `off` (desativada). O código de saída é 1 quando algum check é `fail` (por exemplo `--enforce=on` com o arquivo de decisões não gravável), o que o torna útil num script de deploy. Aceita as mesmas flags de `serve`.
```bash
urutau doctor
+54 -43
View File
@@ -10,38 +10,30 @@ O Urutau não tem arquivo de configuração. Tudo é uma flag com padrão em var
|---|---|
| `URUTAU_TOKEN` | **Obrigatória.** Token de acesso do dashboard e da API: no mínimo 32 caracteres e cerca de 128 bits de entropia estimada (comprimento vezes entropia de Shannon; tokens periódicos ou sequenciais são recusados). Gere um com `openssl rand -base64 48` (`openssl rand -hex 32` também serve; `-hex 16` é recusado pela estimativa de entropia). |
| `URUTAU_TOKEN_FILE` | Caminho de um arquivo com o token (espaços nas pontas são removidos), no lugar da variável. A variável vence quando as duas existem. |
| `URUTAU_PEER_TOKEN` | Opcional. O token de servidor desta instância: o único que as rotas de federação dela (veja [Peers](#peers-modo-hub)) aceitam, e não abre mais nada. Mesmas regras de força do `URUTAU_TOKEN` (32+ caracteres, cerca de 128 bits de entropia estimada, sem padrão periódico nem sequencial), e deve ser diferente dele. Quando esta instância é um hub, também é o token de cliente de reserva enviado aos peers que não têm o seu. |
| `URUTAU_PEER_TOKEN_FILE` | Caminho de um arquivo com o token de peer geral. |
| `URUTAU_PEER_TOKEN_<NOME>` e `..._<NOME>_FILE` | A credencial de cliente que um hub envia àquele peer; deve ser igual ao `URUTAU_PEER_TOKEN` do próprio peer. `<NOME>` é o nome do peer em maiúsculas, com todo caractere que não seja letra ou dígito virando `_` (`my-peer` vira `MY_PEER`). Ela **não** abre o export local. Dois nomes de peer que viram a mesma variável (`my-peer` e `my_peer`) são recusados. Um hub com um peer sem token para ele se recusa a iniciar. |
| `URUTAU_PROBE_TOKEN` | **Só da sonda, obrigatória.** O token de uma sonda (`urp_` mais 43 caracteres base64url), impresso uma vez por `urutau probes create` ou pela página Fontes. O hub guarda só o SHA-256 dele (`probes.json`), então um token perdido é substituído, nunca recuperado: revogue a sonda e crie de novo. |
| `URUTAU_PROBE_TOKEN_FILE` | Só da sonda. Caminho de um arquivo com o token da sonda, no lugar da variável. A variável vence quando as duas existem. |
Guarde os dois no `.env` (nunca versionado) ou no cofre de segredos do seu orquestrador.
Os segredos de federação da 1.x (`URUTAU_PEER_TOKEN`, `URUTAU_PEER_TOKEN_FILE`, `URUTAU_PEER_TOKEN_<NOME>`) não existem mais; o hub se recusa a subir quando um deles está definido ([migracao-2.0.md](migracao-2.0.md)).
Guarde-os no `.env` (nunca versionado) ou no cofre de segredos do seu orquestrador.
## Ajustes
Toda variável abaixo tem uma flag de mesmo sentido ([cli.md](cli.md)); a flag vence a variável.
Os ajustes se dividem por papel. O **hub** (`urutau serve`) usa as variáveis das seções até [Egress](#egress); a **sonda** (`urutau probe`) usa as de [Sonda](#sonda). Toda variável abaixo tem uma flag de mesmo sentido ([cli.md](cli.md)); a flag vence a variável.
### Geral
| Variável | Padrão | Significado |
|---|---|---|
| `URUTAU_BIND` | `0.0.0.0:8790` | endereço de escuta |
| `URUTAU_NAME` | hostname do container | nome mostrado no dashboard e usado pelo hub |
| `URUTAU_DATA_DIR` | `/data` | onde fica o estado: snapshot `urutau-state.gob`, `geo/`, `tor/`, `events/`, `incidents.json` e `enforce.json` |
| `URUTAU_NAME` | hostname do container | nome desta instância **e da sonda primária**: a sonda cujo nome é igual a ele guarda os dados na raiz do data-dir (exatamente o layout da 1.x); toda outra sonda usa `<data-dir>/probes/<nome>/` |
| `URUTAU_DATA_DIR` | `/data` | onde fica o estado: snapshot `urutau-state.gob`, `geo/`, `tor/`, `events/`, `incidents.json` e `enforce.json` da sonda primária, `probes/<nome>/` das demais e `probes.json` |
| `URUTAU_RETENTION` | `720h` | retenção como duração do Go, de `1h` a `720h` (30 dias); outros valores impedem a inicialização |
| `URUTAU_EVENTS_MAX` | `512MB` | limite de tamanho do registro de eventos (`<data-dir>/events`); número com unidade opcional (`k`, `kb`, `kib`, `m`, `mb`, `mib`, `g`, `gb`, `gib`, `b`), `0` desliga |
| `URUTAU_LOCATION` | vazio | onde esta instância está no mapa, `"lat,lon"` ou `"lat,lon,Rótulo"` (validado na partida). É o destino dos arcos da página Ao vivo e é compartilhado com o hub; vazio faz a página estimar um destino |
| `URUTAU_LOCATION` | vazio | posição padrão da sonda primária no mapa (as outras recebem a delas no hub, por sonda), `"lat,lon"` ou `"lat,lon,Rótulo"` (validado na partida). É o destino dos arcos da página Ao vivo; vazio faz a página estimar um destino |
| `GOMEMLIMIT` | limite suave de 256 MiB | limite de memória padrão do Go; defina para sobrescrever |
| `TZ` | UTC | fuso dos timestamps do `fail2ban.log`, que não trazem fuso |
### Fontes de log
| Variável | Padrão | Significado |
|---|---|---|
| `URUTAU_TRAEFIK_LOG` | `/data/coolify/proxy/access.log` | access log JSON do Traefik, vazio desativa |
| `URUTAU_AUTH_LOG` | `/var/log/auth.log` | log do sshd, vazio desativa |
| `URUTAU_FAIL2BAN_LOG` | `/var/log/fail2ban.log` | log do fail2ban, vazio desativa |
| `URUTAU_PROBE_LOG` | `/logs/host/probe.log` | log do kernel de conexões novas a portas que ninguém serve, gravado pelo kit do host (veja [Sondagens](#sondagens-varreduras-de-portas)); vazio desativa, arquivo ausente só deixa a fonte em `waiting` |
### Ruído, confiança e monitoramento
| Variável | Padrão | Significado |
@@ -62,23 +54,18 @@ Toda variável abaixo tem uma flag de mesmo sentido ([cli.md](cli.md)); a flag v
| `URUTAU_TOR_AUTO` | `on` | `on`: baixa as listas oficiais de saídas e relays do Tor a cada 6 horas em `<data-dir>/tor`; `off`: não baixa (hosts isolados) |
| `URUTAU_TOR_EXITS` | vazio | arquivo com endereços de saída do Tor, um por linha (comentários `#` aceitos, no máximo 100000 endereços, 8 MiB), recarregado a cada 24 h quando muda; combinado com a lista baixada |
### Federação
### Proxy reverso
| Variável | Padrão | Significado |
|---|---|---|
| `URUTAU_PEERS` | vazio | peers a agregar, `nome=https://url` separados por vírgula (a flag `--peer` se repete) |
| `URUTAU_PEER_ALLOW` | vazio | CIDRs autorizados a chamar as rotas de federação; vazio aceita qualquer origem que tenha o token |
| `URUTAU_PEER_BLOCKLIST` | `on` | `on`: a lista de bloqueio do hub inclui IPs hostis vistos só pelos peers (score 50+ e sinal forte); `off`: só os IPs desta instância. Qualquer outro valor impede a inicialização |
| `URUTAU_TRUSTED_PROXY` | `127.0.0.0/8,::1` (o compose define `10.250.0.0/24`) | proxies reversos cujo `X-Forwarded-For` é confiável (lido da direita para a esquerda); usado pelo limite de tentativas de login e por `URUTAU_PEER_ALLOW` |
| `URUTAU_TRUSTED_PROXY` | `127.0.0.0/8,::1` (o compose define `10.250.0.0/24`) | proxies reversos cujo `X-Forwarded-For` é confiável (lido da direita para a esquerda); usado pelo limite de tentativas de login e pelo limitador de autenticação das sondas |
### Segundo firewall (enforce)
| Variável | Padrão | Significado |
|---|---|---|
| `URUTAU_ENFORCE` | `off` | `off`; `observe` (decide em memória e mostra o que baniria, não grava nada); `on` (também acrescenta as decisões em `URUTAU_ENFORCE_LOG` para o fail2ban do host). Qualquer outro valor impede a inicialização |
| `URUTAU_ENFORCE_LOG` | `/logs/enforce/decisions.log` | arquivo de decisões acrescentado no modo `on`; `on` sem ele impede a inicialização |
| `URUTAU_ENFORCE_UNBAN_LOG` | `unban.log` ao lado de `URUTAU_ENFORCE_LOG` | arquivo onde o botão Desbanir do dashboard grava os pedidos, lido pelo host |
| `URUTAU_ENFORCE_SHARE` | `off` | `on`: troca decisões e desbanimentos com os peers a cada 30 s; cada lado aplica suas próprias exclusões. Qualquer outro valor impede a inicialização |
| `URUTAU_ENFORCE` | `off` | `off`; `observe` (decide em memória e mostra o que baniria, não envia nada); `on` (também enfileira as decisões para a sonda do host, que as acrescenta em seu `URUTAU_ENFORCE_LOG` para o fail2ban do host). Qualquer outro valor impede a inicialização |
| `URUTAU_ENFORCE_SHARE` | `off` | `on`: uma decisão tomada para uma sonda também é enfileirada para as outras; cada nó aplica suas próprias exclusões. Qualquer outro valor impede a inicialização |
| `URUTAU_ENFORCE_THRESHOLD` | `5` | eventos de ataque em 10 minutos que justificam um banimento (1 a 1000) |
| `URUTAU_ENFORCE_MAX_PER_MIN` | `60` | máximo de decisões gravadas por minuto; o excedente é descartado e contado (1 a 10000) |
@@ -88,15 +75,36 @@ Um número ilegível volta ao padrão; um fora da faixa impede a inicialização
| Variável | Padrão | Significado |
|---|---|---|
| `URUTAU_EGRESS` | `auto` | `auto` (liga quando `URUTAU_EGRESS_LOG` existe na partida), `on` ou `off`; qualquer outro valor impede a inicialização |
| `URUTAU_EGRESS_LOG` | `/logs/host/egress.log` | log do kernel de conexões novas de saída, gravado pelo kit do host |
| `URUTAU_EGRESS_CONTAINERS` | `/logs/host/containers.map` | mapa `"<ip> <container>"` gravado pelo kit do host a cada minuto, para que as cargas mantenham o nome quando o endereço muda num redeploy |
| `URUTAU_EGRESS_WORKLOADS` | vazio | cargas nomeadas e seu papel, veja [Análise de egress](#análise-de-egress) |
| `URUTAU_EGRESS_RESOLVERS` | vazio | resolvedores DNS permitidos, IPs separados por vírgula; vazio significa os públicos usuais (Cloudflare, Google, Quad9...) mais os nameservers de `/etc/resolv.conf` e `/logs/host/resolv.conf` |
| `URUTAU_EGRESS_ALLOW` | vazio | só variável de ambiente, sem flag: CIDRs ou IPs de consultores periódicos legítimos que não devem gerar achados de beaconing. Endereços dos peers, `URUTAU_TRUSTED` e os endereços públicos do próprio servidor são sempre permitidos |
| `URUTAU_EGRESS` | `auto` | `auto` (liga para uma sonda que envia o log de egress), `on` ou `off`; qualquer outro valor impede a inicialização |
| `URUTAU_EGRESS_WORKLOADS` | vazio | padrão da sonda primária; cada sonda pode ter a sua na página Fontes. Cargas nomeadas e seu papel, veja [Análise de egress](#análise-de-egress) |
| `URUTAU_EGRESS_RESOLVERS` | vazio | resolvedores DNS permitidos, IPs separados por vírgula; vazio significa os públicos usuais (Cloudflare, Google, Quad9...) mais os nameservers do `resolv.conf` que cada sonda envia |
| `URUTAU_EGRESS_ALLOW` | vazio | só variável de ambiente, sem flag: CIDRs ou IPs de consultores periódicos legítimos que não devem gerar achados de beaconing. Endereços das sondas, `URUTAU_TRUSTED` e os endereços públicos do próprio servidor são sempre permitidos |
| `URUTAU_EGRESS_PROVIDER_ASN` | vazio | só variável de ambiente, sem flag: números de AS do seu provedor de hospedagem, separados por vírgula, para que o tráfego até ele não seja apontado como incomum |
Na imagem do container os caminhos de log têm como padrão `/logs/traefik/access.log`, `/logs/host/auth.log` e `/logs/host/fail2ban.log` (o compose monta os logs do host ali); os arquivos de sondagem, egress e mapa de containers ficam no mesmo diretório `/logs/host`. O compose acrescenta `URUTAU_VERSION` (tag da imagem), `URUTAU_IMAGE` e `URUTAU_PUBLISH` (endereço e porta do host), veja `.env.example`. Ele repassa só algumas variáveis ao container ([docker.md](docker.md)); acrescente qualquer outra variável `URUTAU_*`, como as `URUTAU_ENFORCE_*` e `URUTAU_EGRESS_*`, ao bloco `environment`.
### Sonda
A sonda usa só estas variáveis (flags em [cli.md](cli.md#urutau-probe)). Um caminho liga a fonte, vazio desliga, e um arquivo que ainda não existe fica em `waiting`.
| Variável | Padrão | Significado |
|---|---|---|
| `URUTAU_HUB` | obrigatória | URL do hub: `https://...`, ou `http://` só para endereços de loopback e privados (por exemplo `http://urutau:8790` na rede `urutau-edge`) |
| `URUTAU_PROBE_NAME` | obrigatório | nome registrado no hub (letras minúsculas, dígitos e `-`, até 32) |
| `URUTAU_PROBE_TOKEN`, `URUTAU_PROBE_TOKEN_FILE` | obrigatório | veja [Segredos](#segredos) |
| `URUTAU_STATE_DIR` | `/state` | spool, posições de leitura e marca de vida; mantenha em um volume |
| `URUTAU_TRAEFIK_LOG` | `/logs/traefik/access.log` | log de acesso JSON do Traefik |
| `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_EGRESS_LOG` | `/logs/host/egress.log` | log do kernel de conexões novas de saída, gravado pelo kit do host |
| `URUTAU_EGRESS_CONTAINERS` | `/logs/host/containers.map` | mapa `"<ip> <container>"` gravado pelo kit do host a cada minuto, para que as cargas mantenham o nome quando o endereço muda num redeploy; enviado inteiro quando muda |
| `URUTAU_RESOLV` | `/etc/resolv.conf` do host (montado) | resolvedores do host, enviados inteiros quando mudam |
| `URUTAU_ENFORCE_LOG` | `/logs/enforce/decisions.log` | arquivo onde as decisões de ban do hub são acrescentadas, lido pela jail do host; vazio ignora comandos de ban e os conta como erro |
| `URUTAU_ENFORCE_UNBAN_LOG` | `/logs/enforce/unban.log` | arquivo onde os pedidos de desban são acrescentados, lido pelo host; vazio os ignora |
| `URUTAU_PROBE_SPOOL_MAX` | `64MiB` | teto do spool enquanto o hub está inacessível; os lotes mais antigos são descartados, contados e mostrados na página Fontes |
| `URUTAU_LOCATION` | vazio | `"lat,lon,Rótulo"`; a configuração do hub prevalece |
| `TZ` | UTC | fuso do host: os timestamps do `fail2ban.log` não trazem fuso e o hub os interpreta, então deve ser o mesmo na sonda e no hub |
A imagem da sonda usa os caminhos acima como padrão porque o compose em `deploy/probe` monta os logs do host ali.
## Ruído e monitoramento
@@ -113,14 +121,17 @@ As bases de geolocalização são conferidas a cada 24 horas (`--geo-update`), m
A página Tráfego não precisa de ajuste. `URUTAU_DOMAINS` restringe quais domínios ela acompanha (nomes exatos ou `*.exemplo.com`); um domínio só ganha vaga depois de uma resposta 2xx e domínios inativos são podados, então `Host` forjados não enchem o analytics. O top de páginas normaliza segmentos de caminho com cara de token (ids, hashes, strings aleatórias longas) para `:id`. Ela usa o log do Traefik, conta visitantes únicos por um hash com sal diário e nunca persiste o endereço IP de um visitante legítimo. Veja o [SECURITY.pt-BR.md](../../SECURITY.pt-BR.md).
## Peers (modo hub)
## Sondas (modo hub)
Um hub sem mais nada configurado não aceita sonda nenhuma até você criar uma:
```
URUTAU_PEERS=web1=https://urutau.web1.example,db1=https://urutau.db1.example
URUTAU_PEER_TOKEN=<segredo compartilhado>
urutau probes create web1 # imprime o token uma vez
```
Em cada peer, defina o mesmo `URUTAU_PEER_TOKEN` (ou um `URUTAU_PEER_TOKEN_<NOME>` por peer no hub). O token de peer abre só as rotas de federação: `GET /api/v1/peer/export` (o hub pede a cada 15 segundos `1h`, `24h`, `7d` e `30d`), `GET /api/v1/peer/stream` (eventos ao vivo), `GET /api/v1/peer/period` (o estudo de um período ou de um IP), `GET /api/v1/peer/egress` e, com `URUTAU_ENFORCE_SHARE=on`, `GET`/`POST /api/v1/peer/decisions` e `POST /api/v1/peer/unban`. As URLs dos peers devem ser `https` (`http` simples só é aceito em loopback): o token de peer viaja em um cabeçalho. Para restringir quem chama essas rotas, defina `URUTAU_PEER_ALLOW` no peer com o endereço do hub; se o peer está atrás de um proxy, defina também `URUTAU_TRUSTED_PROXY` para que o endereço real do cliente seja o comparado. Os nomes de peer devem ser únicos e não podem ser `all` nem o nome do próprio hub. Com `URUTAU_PEER_BLOCKLIST=off` a lista de bloqueio do hub traz só os IPs dele.
No servidor dessa sonda, defina `URUTAU_HUB`, `URUTAU_PROBE_NAME=web1` e `URUTAU_PROBE_TOKEN` e suba `deploy/probe/docker-compose.yml` ([docker.md](docker.md#sonda)). O hub guarda só o SHA-256 do token; um token errado recebe um 401 sem corpo sob um limitador de tentativas. Revogar uma sonda (`urutau probes revoke web1` ou a página Fontes) a recusa daí em diante e mantém os dados dela. A localização no mapa e a configuração de egress (cargas, resolvedores, destinos permitidos) de cada sonda são editadas na página Fontes e ficam em `probes.json`; `URUTAU_LOCATION`, `URUTAU_EGRESS_WORKLOADS`, `URUTAU_EGRESS_RESOLVERS` e `URUTAU_EGRESS_ALLOW` são os padrões da sonda primária.
Se as variáveis da 1.x `URUTAU_PEERS`, `URUTAU_PEER_TOKEN*`, `URUTAU_PEER_ALLOW` ou `URUTAU_PEER_BLOCKLIST` estiverem definidas, ou as de caminho de log no hub, ele para na partida: veja [migracao-2.0.md](migracao-2.0.md).
## Snapshot e retenção
@@ -136,7 +147,7 @@ Os chamados abertos a partir de achados de egress (e o estado deles: aberto, fal
## Sondagens (varreduras de portas)
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`; o Urutau lê esse arquivo como `URUTAU_PROBE_LOG`, 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.
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.
## Tor
@@ -144,18 +155,18 @@ O Urutau marca endereços que são saídas ou relays do Tor. Por padrão (`URUTA
## Segundo firewall (enforce)
Opcional e desligado por padrão. O Urutau nunca ganha privilégios: ele só decide quais endereços merecem banimento e acrescenta uma linha por decisão em um arquivo, e uma jail do fail2ban no host a aplica.
Opcional e desligado por padrão. Nenhum dos dois processos do Urutau ganha privilégios: o hub decide quais endereços merecem banimento e enfileira uma linha por decisão para a sonda daquele host, a sonda confere que a linha tem exatamente o formato esperado e a acrescenta em um arquivo, e uma jail do fail2ban no host a aplica.
- `URUTAU_ENFORCE=observe` decide em memória e mostra no dashboard o que baniria; nada é gravado. Use primeiro.
- `URUTAU_ENFORCE=on` acrescenta `<hora> urutau decision=ban ip=<ip> reason=<slug> score=<n> ttl=<s> host=<nome> src=<local|peer>` em `URUTAU_ENFORCE_LOG`. O lado do host é a jail `urutau` e a ação `urutau-allports` instaladas por `install.sh --enforce` ([docker.md](docker.md#kit-do-host)). A jail usa o `ignoreip` do próprio host, então endereços confiáveis ficam protegidos ali também. As decisões esperam o backfill dos logs terminar na partida.
- `URUTAU_ENFORCE=on` acrescenta `<hora> urutau decision=ban ip=<ip> reason=<slug> score=<n> ttl=<s> host=<nome> src=<local|peer:NOME>` no `URUTAU_ENFORCE_LOG` da sonda. O lado do host é a jail `urutau` e a ação `urutau-allports` instaladas por `install.sh --probe --enforce` ([docker.md](docker.md#kit-do-host)). A jail usa o `ignoreip` do próprio host, então endereços confiáveis ficam protegidos ali também. As decisões esperam o backfill dos logs terminar na partida.
Um banimento exige uma destas condições dentro da janela: dois eventos críticos (RCE, traversal, `.env`/credenciais, VCS, webshell, SQL injection, Log4Shell), `URUTAU_ENFORCE_THRESHOLD` eventos de ataque em 10 minutos (o dobro para quem fez uma visita legítima), 5 falhas de SSH em 10 minutos, 10 portas distintas sondadas em 10 minutos, um atacante conhecido, 10 falhas de SSH ou 20 eventos web em 24 horas, 10 falhas de SSH ou 10 eventos web sem visita legítima em 7 dias (um `ssh-probe` conta metade), ou um evento de um endereço de um /24 (IPv4) ou /64 (IPv6) em que 3 ou mais endereços foram banidos nas últimas 24 horas (`neighbor-campaign`). O TTL sugerido cresce com a reincidência: 1 h, 6 h, 24 h, 7 d. Nunca são banidos: endereços confiáveis e privados (`URUTAU_TRUSTED`, `URUTAU_IGNORE`), crawlers verificados (DNS reverso confirmado), endereços com permissão do operador, infraestrutura e hosts dos próprios peers, endereços da Cloudflare e decisões de um peer que a instância local não consegue confirmar. Banimentos da jail `urutau` e de `recidive` não contam como evidência do comportamento do próprio endereço. Os motivos são uma lista fixa: `scanner-flood`, `exploit-flood`, `web-bruteforce`, `wp-bruteforce`, `ssh-bruteforce`, `rce`, `path-traversal`, `env-probe`, `vcs-probe`, `webshell`, `sqli`, `log4shell`, `port-scan`, `known-attacker`, `neighbor-campaign`.
Um banimento exige uma destas condições dentro da janela: dois eventos críticos (RCE, traversal, `.env`/credenciais, VCS, webshell, SQL injection, Log4Shell), `URUTAU_ENFORCE_THRESHOLD` eventos de ataque em 10 minutos (o dobro para quem fez uma visita legítima), 5 falhas de SSH em 10 minutos, 10 portas distintas sondadas em 10 minutos, um atacante conhecido, 10 falhas de SSH ou 20 eventos web em 24 horas, 10 falhas de SSH ou 10 eventos web sem visita legítima em 7 dias (um `ssh-probe` conta metade), ou um evento de um endereço de um /24 (IPv4) ou /64 (IPv6) em que 3 ou mais endereços foram banidos nas últimas 24 horas (`neighbor-campaign`). O TTL sugerido cresce com a reincidência: 1 h, 6 h, 24 h, 7 d. Nunca são banidos: endereços confiáveis e privados (`URUTAU_TRUSTED`, `URUTAU_IGNORE`), crawlers verificados (DNS reverso confirmado), endereços com permissão do operador, infraestrutura e hosts das próprias sondas, endereços da Cloudflare e decisões de outro nó que a instância local não consegue confirmar. Banimentos da jail `urutau` e de `recidive` não contam como evidência do comportamento do próprio endereço. Os motivos são uma lista fixa: `scanner-flood`, `exploit-flood`, `web-bruteforce`, `wp-bruteforce`, `ssh-bruteforce`, `rce`, `path-traversal`, `env-probe`, `vcs-probe`, `webshell`, `sqli`, `log4shell`, `port-scan`, `known-attacker`, `neighbor-campaign`.
O botão Desbanir do dashboard (`POST /api/v1/enforce/unban`) remove o banimento ativo, grava `<hora> urutau unban ip=<ip> allow=<segundos>` no arquivo de unban e, com `URUTAU_ENFORCE_SHARE=on`, avisa os peers. No host, `urutau-unban.path` roda `urutau-unban`, que desbane o endereço em todas as jails e, com `allow` maior que 0, o ignora por esse tempo (útil em pentests autorizados). `urutau doctor` informa o modo, o arquivo e se é gravável (`fail` no modo `on` quando não é) e avisa quando o Traefik registra endereços da Cloudflare como clientes (defina `forwardedHeaders.trustedIPs` com as faixas da Cloudflare para enxergar o cliente real).
O botão Desbanir do dashboard (`POST /api/v1/enforce/unban`) remove o banimento ativo, enfileira `<hora> urutau unban ip=<ip> allow=<segundos>` para a sonda (você escolhe o host, ou todos), que o acrescenta no arquivo de unban, e com `URUTAU_ENFORCE_SHARE=on` avisa os outros nós. No host, `urutau-unban.path` roda `urutau-unban`, que desbane o endereço em todas as jails e, com `allow` maior que 0, o ignora por esse tempo (útil em pentests autorizados). `urutau doctor` informa o modo, o arquivo e se é gravável (`fail` no modo `on` quando não é) e avisa quando o Traefik registra endereços da Cloudflare como clientes (defina `forwardedHeaders.trustedIPs` com as faixas da Cloudflare para enxergar o cliente real).
## Análise de egress
Analisa o que sai do servidor: conexões novas de saída do host e dos containers, registradas pelo kit do host em `/var/log/urutau/egress.log`. Encontra beaconing, mineração, spam, varreduras não autorizadas, DNS que contorna os resolvedores permitidos e destinos conhecidos como hostis ou saídas do Tor. Com `URUTAU_EGRESS=auto` liga sozinha quando o log existe. Os achados podem virar chamados (veja Incidentes).
Analisa o que sai do servidor: conexões novas de saída do host e dos containers, registradas pelo kit do host em `/var/log/urutau/egress.log` e enviadas pela sonda. Encontra beaconing, mineração, spam, varreduras não autorizadas, DNS que contorna os resolvedores permitidos e destinos conhecidos como hostis ou saídas do Tor. Com `URUTAU_EGRESS=auto` liga sozinha para uma sonda que envia o log. Os achados podem virar chamados (veja Incidentes).
`URUTAU_EGRESS_WORKLOADS` nomeia as origens e dá um papel a cada uma, para que o comportamento esperado não seja apontado (um scanner varre, um servidor de e-mail fala na porta 25):
+61 -47
View File
@@ -2,22 +2,29 @@
# Docker
O Urutau é distribuído como uma imagem de container pequena (`linux/amd64` e `linux/arm64`, cerca de 28 MB, sem `curl`), definida no [`docker-compose.yml`](../../docker-compose.yml). Ele lê arquivos de log e grava um volume de dados (e, só se você ligar o segundo firewall, um arquivo de decisões).
O Urutau 2 é distribuído como **duas** imagens de container pequenas (`linux/amd64` e `linux/arm64`, sem `curl`, sem shell na sonda), construídas de um só Dockerfile:
| Imagem | Target | O que é | Arquivo compose |
|---|---|---|---|
| `urutau` | `hub` | Alpine, cerca de 28 MB: dashboard, API, volume de dados, recebe as sondas. Não lê arquivo de log | [`docker-compose.yml`](../../docker-compose.yml) |
| `urutau-probe` | `probe` | `FROM scratch`, menos de 15 MB: só o binário, certificados CA e zoneinfo. Lê os logs do host e os envia ao hub | [`deploy/probe/docker-compose.yml`](../../deploy/probe/docker-compose.yml) |
```
host container urutau
/data/coolify/proxy/logs ── :ro ────────────► /logs/traefik (access.log do Traefik)
/var/log/urutau ── :ro ────────────► /logs/host (auth.log, fail2ban.log, probe.log,
egress.log, containers.map, resolv.conf)
/var/log/urutau-enforce ── leitura e escrita ► /logs/enforce (decisions.log, unban.log; só com URUTAU_ENFORCE=on)
volume urutau-data ── leitura e escrita ► /data (snapshot, geo, tor, events, incidents)
servidor 1 (sonda) hub
/data/coolify/proxy/logs ─:ro─► /logs/traefik
/var/log/urutau ─:ro─► /logs/host ── push HTTPS ──► container urutau
/etc/resolv.conf ─:ro─► /logs/resolv.conf ◄─ long-poll ─── volume urutau-data ─► /data
/var/log/urutau-enforce ─rw──► /logs/enforce (só com URUTAU_ENFORCE=on no hub)
volume urutau-probe-state ────► /state (spool, posições)
servidor 2 (sonda) ── mesmo layout ──► o mesmo hub
```
O compose segue esse layout, exceto a montagem `/logs/enforce`, que você acrescenta ao ligar o segundo firewall (veja [abaixo](#kit-do-host)). O diretório de logs do Traefik é montado fora de `/data` para não colidir com o volume do snapshot. Só o diretório `logs` dedicado do proxy é montado, nunca o `/data/coolify/proxy` inteiro (que guarda `acme.json` e a configuração dinâmica).
O hub e as sondas são containers independentes: o hub pode rodar em um dos servidores monitorados (então esse servidor também roda uma sonda, como qualquer outro) ou em uma máquina própria. A sonda **não abre porta**: a conexão sai dela para o hub, então o servidor monitorado não precisa de regra de entrada. Só o diretório dedicado `logs` do proxy é montado, nunca o `/data/coolify/proxy` inteiro (ele guarda o `acme.json`, as chaves privadas do TLS).
A imagem roda com o usuário sem privilégios `urutau` (uid 10001) em Alpine, a partir de um binário Go estático. O `HEALTHCHECK` é o próprio binário (`urutau healthcheck`, a cada 30 s, que pergunta `/api/health` ao daemon local), então não há `curl` na imagem. A imagem define `URUTAU_BIND=0.0.0.0:8790`, `URUTAU_DATA_DIR=/data` e os três caminhos de log (`/logs/traefik/access.log`, `/logs/host/auth.log`, `/logs/host/fail2ban.log`); `VOLUME /data`, `EXPOSE 8790`, `ENTRYPOINT ["urutau"]`, `CMD ["serve"]`. O compose define `mem_limit: 384m` (o limite suave do Go é 256 MiB; o pior caso medido é cerca de 54 MiB de heap mais um snapshot de uns 27 MB), `cpus: 0.5`, sistema de arquivos raiz somente leitura, `cap_drop: [ALL]`, `no-new-privileges`, `group_add: ["4"]` (o grupo `adm` do host) e a rede `urutau-edge`. O volume de dados também guarda o registro de eventos (`/data/events`, limitado por `URUTAU_EVENTS_MAX`, 512 MB por padrão). Ele repassa do `.env` ao container: `URUTAU_TOKEN`, `URUTAU_NAME`, `URUTAU_TRUSTED`, `URUTAU_PEERS`, `URUTAU_PEER_TOKEN`, `URUTAU_PEER_ALLOW`, `URUTAU_TRUSTED_PROXY`, `URUTAU_DOMAINS`, `URUTAU_MONITOR_FROM`, `URUTAU_ADMIN_USERS`, `URUTAU_GEO_UPDATE` e `TZ`. Para definir qualquer outra variável `URUTAU_*` (`URUTAU_MONITOR_UA`, `URUTAU_RETENTION`, `URUTAU_TOKEN_FILE`, `URUTAU_ENFORCE*`, `URUTAU_EGRESS*`, `URUTAU_TOR_*`, tokens por peer, ...), acrescente-a ao bloco `environment`.
As duas imagens rodam sem privilégios (uid 10001) a partir de um binário Go estático. A imagem do hub define `URUTAU_BIND=0.0.0.0:8790` e `URUTAU_DATA_DIR=/data` (sem caminho de log; as variáveis da 1.x o impedem de subir) e seu `HEALTHCHECK` é `urutau healthcheck` a cada 30 s. A imagem da sonda define `URUTAU_STATE_DIR=/state`, não expõe porta e seu `HEALTHCHECK` é `/urutau probe --check`, que lê a marca de vida do volume de estado (não há shell). Para ler `/var/log/urutau` (grupo `adm`), o compose da sonda acrescenta o grupo do host com `group_add: ["4"]`.
## Início rápido
## Início rápido (hub)
```bash
cp .env.example .env
@@ -29,23 +36,42 @@ docker compose up -d --build
O token precisa de pelo menos 32 caracteres e cerca de 128 bits de entropia estimada (comprimento vezes entropia de Shannon; tokens periódicos ou sequenciais são recusados). `openssl rand -base64 48` é o recomendado (`openssl rand -hex 32` também serve). Para manter o segredo fora do ambiente, monte um arquivo e defina `URUTAU_TOKEN_FILE` (o mesmo vale para `URUTAU_PEER_TOKEN_FILE`).
O dashboard sobe em `http://127.0.0.1:8790` por padrão (`URUTAU_PUBLISH` no `.env` muda o endereço e a porta). Confira as fontes:
O dashboard sobe em `http://127.0.0.1:8790` por padrão (`URUTAU_PUBLISH` no `.env` muda o endereço e a porta). Crie uma sonda para cada servidor e leia a resposta uma vez:
```bash
docker compose exec urutau urutau probes create web1 # imprime o token (urp_...) uma vez
docker compose exec urutau urutau doctor
docker compose logs urutau
```
## Lendo os logs
## Sonda
Em cada servidor monitorado, depois de [preparar os logs do host](#preparando-os-logs-do-host):
```bash
cd deploy/probe
cp .env.example .env
$EDITOR .env # URUTAU_HUB=https://urutau.example.com URUTAU_PROBE_NAME=web1 URUTAU_PROBE_TOKEN=urp_...
docker compose up -d
docker compose logs probe
```
Depois abra a página Fontes do hub: a sonda aparece conectada com suas fontes (`following`, `waiting` para um arquivo que ainda não existe). `URUTAU_HUB` deve ser `https://` (um `http://` simples só é aceito para endereços de loopback e privados, como `http://urutau:8790` quando o hub é o serviço `urutau` do mesmo host e a sonda entra na rede `urutau-edge`; veja os comentários no compose). Defina `TZ` com o fuso do host: o hub interpreta o `fail2ban.log`, que não tem fuso, então precisa ser igual dos dois lados.
Enquanto o hub está inacessível a sonda guarda os lotes no volume `/state` (64 MiB por padrão, `URUTAU_PROBE_SPOOL_MAX`), reconecta com backoff de 1 a 60 segundos e os envia na ordem quando o hub volta; nada se perde nem é contado duas vezes. Se o spool estourar, os lotes mais antigos são descartados e a perda é contada e mostrada na página Fontes. Para trocar um token, revogue a sonda no hub e crie de novo; um token perdido não se recupera porque o hub guarda só o SHA-256 dele. A sonda fica abaixo de cerca de 20 MB de memória.
## Lendo os logs (sonda)
Estas notas são sobre os arquivos que a **sonda** monta.
- **Traefik:** o access log precisa ser JSON e gravado em um diretório dedicado. Na configuração estática do Traefik defina `--accesslog=true`, `--accesslog.format=json` e `--accesslog.filepath=/traefik/logs/access.log`. No Coolify o diretório do host `/data/coolify/proxy` é `/traefik` dentro do container do proxy, então esse arquivo aparece no host como `/data/coolify/proxy/logs/access.log`, que é o que o compose monta. Na interface do Coolify abra Servers, o servidor, Proxy, e acrescente essas três linhas à lista `command` da configuração do proxy, depois reinicie o proxy. No mesmo lugar acrescente os cabeçalhos que o Urutau usa para distinguir visitas reais de requisições enquadradas: `--accesslog.fields.headers.names.Sec-Fetch-Site=keep`, `--accesslog.fields.headers.names.Sec-Fetch-Dest=keep` e `--accesslog.fields.headers.names.Referer=keep`.
- **auth.log e fail2ban.log:** o diretório dedicado do host `/var/log/urutau` é montado somente leitura em `/logs/host` como diretório, porque o logrotate recria esses arquivos por renomeação e uma montagem de arquivo único continuaria seguindo o inode antigo. Prepare-o como em [Preparando os logs do host](#preparando-os-logs-do-host). Os arquivos pertencem a `syslog:adm`, então o container adiciona o grupo `adm` do host (GID 4) com `group_add: ["4"]`, como o compose faz. Nada mais do `/var/log` do host é exposto.
- **Somente leitura:** todas as montagens de log são `:ro`. O Urutau nunca escreve em um log.
- **Somente leitura:** todas as montagens de log são `:ro`. O Urutau nunca escreve em um log. (A única montagem gravável é `/logs/enforce`, veja [Kit do host](#kit-do-host).)
- **Rotação:** o seguidor reabre o arquivo quando o logrotate o substitui ou trunca.
## Preparando os logs do host
O Urutau lê um diretório dedicado, `/var/log/urutau`, e não o `/var/log` inteiro. Prepare-o uma vez em cada servidor (o `/var/log/auth.log` original continua intacto):
A sonda lê um diretório dedicado, `/var/log/urutau`, e não o `/var/log` inteiro. Prepare-o uma vez em cada servidor (o `/var/log/auth.log` original continua intacto):
```bash
sudo install -d -m 0750 -o syslog -g adm /var/log/urutau
@@ -90,7 +116,7 @@ O A regra de logrotate acima cita só `auth.log` e `fail2ban.log` de propósito:
## Exemplo: Coolify
Crie um recurso Docker Compose no servidor Coolify cujos logs você quer observar, com este compose:
Dois recursos. No servidor que hospeda o hub, um recurso Docker Compose com o hub e o domínio dele:
```yaml
services:
@@ -99,18 +125,13 @@ services:
restart: unless-stopped
environment:
URUTAU_TOKEN: ${URUTAU_TOKEN}
URUTAU_NAME: server-1
URUTAU_AUTH_LOG: /logs/host/auth.log
URUTAU_FAIL2BAN_LOG: /logs/host/fail2ban.log
URUTAU_NAME: server-1 # a sonda primária: os dados dela são a raiz do data-dir
URUTAU_TRUSTED_PROXY: 10.250.0.0/24
TZ: UTC # o fuso do host (fail2ban.log não tem fuso)
group_add: ["4"] # adm: lê auth.log e fail2ban.log
TZ: UTC
read_only: true
cap_drop: [ALL]
security_opt: ["no-new-privileges:true"]
volumes:
- /data/coolify/proxy/logs:/logs/traefik:ro
- /var/log/urutau:/logs/host:ro
- urutau-data:/data
networks: [urutau-edge]
labels:
@@ -130,22 +151,25 @@ networks:
external: true
```
Depois, em cada servidor (inclusive esse), um segundo recurso Compose com o `deploy/probe/docker-compose.yml`, com `URUTAU_HUB`, `URUTAU_PROBE_NAME` e `URUTAU_PROBE_TOKEN` no ambiente do Coolify. No servidor do próprio hub a sonda pode usar `https://urutau.example.com` ou entrar na rede `urutau-edge` e usar `http://urutau:8790`.
Notas:
- **Uma rede compartilhada só com o Traefik.** `--trusted-proxy` tem como padrão só o loopback, então por padrão o `X-Forwarded-For` é ignorado. O compose cria a rede `urutau-edge` (`10.250.0.0/24`) e define `URUTAU_TRUSTED_PROXY=10.250.0.0/24`, então só o proxy dessa rede é acreditado (qualquer outro container ali poderia forjar IPs de cliente, então deixe só o proxy). Conecte o proxy uma vez: `docker network connect urutau-edge coolify-proxy`. Em um compose avulso como o exemplo abaixo, declare a rede do mesmo jeito e defina a variável. O label `traefik.docker.network` diz ao Traefik para usá-la. Adapte os nomes do entrypoint e do certresolver ao seu proxy.
- A imagem já aponta as fontes para `/logs/traefik/access.log`, `/logs/host/auth.log` e `/logs/host/fail2ban.log` (seus padrões `URUTAU_*_LOG`); os padrões de sondagem, egress e mapa de containers (`/logs/host/...`) são os do próprio binário. Os outros padrões do binário (`/data/coolify/proxy/access.log`, `/var/log/...`) servem para rodá-lo direto no host.
- **Uma rede compartilhada só com o Traefik.** `--trusted-proxy` tem como padrão só o loopback, então por padrão o `X-Forwarded-For` é ignorado. O compose cria a rede `urutau-edge` (`10.250.0.0/24`) e define `URUTAU_TRUSTED_PROXY=10.250.0.0/24`, então só o proxy dessa rede é acreditado (qualquer outro container ali poderia forjar IPs de cliente). Conecte o proxy com `docker network connect urutau-edge coolify-proxy`, ou deixe os labels fazerem isso como acima. Se o proxy estiver em outro lugar, defina `URUTAU_TRUSTED_PROXY` com o endereço dele.
- Defina `URUTAU_TOKEN` no ambiente do Coolify. Atrás do proxy o dashboard é servido por HTTPS, então o cookie de sessão é `Secure`.
- Não publique a porta 8790 no host quando o proxy já a roteia.
- Se o access log do Traefik não existir ou não for JSON, a fonte fica em zero linhas ou `malformed` cresce.
- O Urutau não precisa de `tmpfs`: o sistema de arquivos raiz é somente leitura e seus destinos de escrita são o volume `/data` e, no modo enforce, `/logs/enforce`.
- Não publique a porta 8790 no host quando o proxy já a roteia. O domínio precisa passar `/api/v1/probe/*` (é o mesmo host do dashboard); um proxy da Cloudflare na frente funciona: a requisição mais longa é um long-poll de 25 segundos.
- Se o access log do Traefik não existir ou não for JSON, a fonte dele fica em zero linhas ou `malformed` cresce na página Fontes.
- O Urutau não precisa de `tmpfs`: o sistema de arquivos raiz é somente leitura e os destinos de escrita são o volume `/data` do hub e o volume `/state` (e, no modo enforce, `/logs/enforce`) da sonda.
## Kit do host
`deploy/host/` traz um kit opcional, que precisa de root no host e dá ao Urutau mais três fontes. O Urutau em si nunca ganha privilégios: ele só lê os logs que o kit grava e, no modo enforce, grava um arquivo de decisões.
`deploy/host/` traz um kit opcional, que precisa de root no host e dá à sonda mais três fontes. O Urutau em si nunca ganha privilégios: a sonda só lê os logs que o kit grava e, no modo enforce, acrescenta decisões em um arquivo. Rode em todo servidor que tenha uma sonda.
```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 --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)
```
@@ -158,40 +182,30 @@ sudo sh deploy/host/install.sh --remove # desfaz tudo (os logs são mantidos)
| mapa de containers | `urutau-containers-map` e seu timer (a cada minuto) gravam `/var/log/urutau/containers.map` (`<ip> <container>`) e `/var/log/urutau/resolv.conf` (os resolvedores reais de upstream) |
| segundo firewall (`--enforce`) | diretório `/var/log/urutau-enforce` (dono `URUTAU_UID`, grupo `adm`) com `decisions.log` e `unban.log`; filtro `urutau`, ação `urutau-allports` e jail `urutau` do fail2ban (backend `polling`, `maxretry = 1`, `bantime = 1h`, ações em `INPUT` e `DOCKER-USER`, `ignoreip` do host mantido); `urutau-unban.path` e `urutau-unban` aplicam o botão Desbanir |
A ação `urutau-allports` funciona como `iptables-allports`, mas só descarta conexões que o endereço banido inicia (direção original do conntrack), então as respostas a conexões que o host abriu continuam fluindo. Os arquivos de egress e sondagem caem em `/var/log/urutau`, que o compose já monta em `/logs/host`, então o Urutau 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:
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
# hub (docker-compose.yml)
environment:
URUTAU_ENFORCE: observe # off | observe | on
# URUTAU_ENFORCE_SHARE: "on" # troca decisões com os peers
# URUTAU_EGRESS_WORKLOADS: "mail=10.0.7.0/24:mail"
volumes:
- /var/log/urutau-enforce:/logs/enforce # leitura e escrita, só para enforce=on
# URUTAU_ENFORCE_SHARE: "on" # uma decisão para um servidor também é enfileirada nos outros
# sonda (deploy/probe/docker-compose.yml): o volume /logs/enforce já está lá
```
`/logs/enforce` precisa ser gravável pelo uid 10001 (o kit cuida disso) e não pode ser `:ro`. Confira com `docker compose exec urutau urutau doctor`: a linha `enforce` mostra modo, arquivo e se é gravável. Veja [configuracao.md](configuracao.md) para a política e as variáveis.
As decisões vão do hub à sonda do host (long-poll) e a sonda as acrescenta em `/logs/enforce/decisions.log`; ela só aceita linhas com exatamente o formato de uma linha de ban ou unban. `/logs/enforce` precisa ser gravável pelo uid 10001 (o kit cuida disso) e não pode ser `:ro`. A sonda conta um comando recusado ou não gravável como erro, mostrado na página Fontes.
## Base de geolocalização
As bases DB-IP Lite são baixadas no volume de dados (`/data/geo`) na primeira inicialização, então o container precisa de HTTPS de saída para `download.db-ip.com` uma vez, e depois uma vez por mês. As listas do Tor (`URUTAU_TOR_AUTO=on`) também precisam de `check.torproject.org` e `onionoo.torproject.org` a cada 6 horas; com `URUTAU_TOR_AUTO=off` isso não é necessário. Se o host não alcança a internet, copie os dois arquivos `.mmdb` para o volume e defina `URUTAU_GEO_UPDATE=0` ([configuracao.md](configuracao.md)). Dados por [DB-IP](https://db-ip.com), CC BY 4.0.
## Federação entre servidores
## Vários servidores
Rode um Urutau por servidor, cada um com seu `URUTAU_NAME`. Toda instância consultada define o próprio token de servidor, `URUTAU_PEER_TOKEN` (ou `_FILE`), e esse é o único token que o export dela aceita. O hub guarda uma credencial de cliente para cada peer, igual ao token de servidor desse peer: um `URUTAU_PEER_TOKEN_<NOME>` por peer (o nome do peer em maiúsculas, outros caracteres viram `_`, por exemplo `URUTAU_PEER_TOKEN_SERVER_2`), com o `URUTAU_PEER_TOKEN` geral do hub como reserva. Uma credencial de cliente não abre o export do próprio hub, e nomes de peer que viram a mesma variável (`my-peer` e `my_peer`) são recusados. Os tokens precisam de 32+ caracteres e cerca de 128 bits de entropia, diferentes de `URUTAU_TOKEN` (`openssl rand -base64 48`), e podem vir de `..._FILE`. No servidor que hospeda o dashboard compartilhado (o hub) acrescente:
```yaml
environment:
URUTAU_PEERS: server-2=https://urutau.server2.example.com,server-3=https://urutau.server3.example.com
URUTAU_PEER_TOKEN_SERVER_2: ${TOKEN_FOR_SERVER_2}
URUTAU_PEER_TOKEN_SERVER_3: ${TOKEN_FOR_SERVER_3}
```
O hub chama `GET /api/v1/peer/export` em cada peer (quatro intervalos a cada 15 segundos), mantém um `GET /api/v1/peer/stream` aberto para os eventos ao vivo e busca períodos e egress sob demanda; com `URUTAU_ENFORCE_SHARE=on` os dois lados também trocam decisões e desbanimentos a cada 30 segundos. Tudo usa o token daquele peer, que não abre mais nada no peer e é recusado em `http` simples fora de loopback. Defina `URUTAU_PEER_ALLOW` em um peer com o endereço do hub para restringir quem pode chamar o export. Cada peer mantém seu próprio token de login para o próprio dashboard.
Um hub, uma sonda por servidor, cada uma com nome e token próprios. Não há token de peer nem segredo compartilhado: `urutau probes create <nome>` cria o token de uma sonda, só o SHA-256 dele fica no hub, e `urutau probes revoke <nome>` corta um servidor sem tocar nos outros (os dados dele ficam). O seletor de host do dashboard oferece `all` e cada sonda, e resumos, tabelas de IPs, o mapa ao vivo e os incidentes (`host/INC-n`) juntam todas; a configuração de egress e a localização no mapa de cada sonda são definidas na página Fontes. Com `URUTAU_ENFORCE_SHARE=on` um ban decidido para um servidor também é enfileirado para os outros. Migrando da 1.x: [migracao-2.0.md](migracao-2.0.md).
## Endurecimento
`read_only: true`, `cap_drop: [ALL]`, `no-new-privileges` e montagens de log somente leitura deixam o container capaz de uma coisa só: ler os logs e gravar seu volume de dados (mais o arquivo de decisões, só quando você liga `URUTAU_ENFORCE=on`). Mantenha a imagem em uma tag fixa (`X.Y.Z`) em produção e `latest` só onde você aceita atualizações.
`read_only: true`, `cap_drop: [ALL]`, `no-new-privileges` e montagens de log somente leitura deixam o hub capaz de uma coisa só, servir e gravar seu volume de dados, e a sonda capaz de ler os logs, gravar seu volume `/state` e falar com o hub (mais o arquivo de decisões, só quando você liga `URUTAU_ENFORCE=on`). A imagem da sonda não tem shell nem gerenciador de pacotes e não expõe porta. Mantenha a imagem em uma tag fixa (`X.Y.Z`) em produção e `latest` só onde você aceita atualizações.
## Saúde e desligamento
`GET /api/health` responde `{"status":"ok"}` sem autenticação. `urutau healthcheck` o chama localmente e sai com 0 quando o daemon está saudável; a imagem o usa como `HEALTHCHECK`. Em `SIGTERM` o daemon para de aceitar requisições, salva o snapshot e sai (`SIGINT` também; 5 segundos de tolerância, código 0).
`GET /api/health` responde `{"status":"ok"}` sem autenticação. `urutau healthcheck` o chama localmente e sai com 0 quando o daemon está saudável; a imagem do hub o usa como `HEALTHCHECK`, e a da sonda usa `urutau probe --check`. Em `SIGTERM` o daemon para de aceitar requisições, salva o snapshot e sai (`SIGINT` também; 5 segundos de tolerância, código 0).
+10 -12
View File
@@ -17,7 +17,7 @@ Uma barra lateral (barra de abas no celular, com um menu "Mais" que rola quando
## Cabeçalho
- Um indicador ao vivo mostrando se o stream de eventos (SSE) está conectado (uma instância atende no máximo 20 clientes do stream ao mesmo tempo).
- O seletor de **host**: `all`, esta instância e cada peer de um hub.
- O seletor de **host**: `all` e cada sonda do hub.
- O seletor de **período**: doze intervalos (`1h`, `2h`, `3h`, `6h`, `12h`, `24h`, `2d`, `3d`, `5d`, `7d`, `15d`, `30d`) ou um período personalizado (`from` e `to`, no máximo 30 dias). Vale para todas as páginas.
- Botões de idioma, tema e sair.
@@ -40,7 +40,7 @@ Uma barra lateral (barra de abas no celular, com um menu "Mais" que rola quando
<p align="center"><img src="../img/overview-dark-pt.png" width="900" alt="Página Visão geral"><br><sub>Visão geral (dados de demonstração).</sub></p>
**Ao vivo** (`#/live`): ataques desenhados como arcos animados da origem até o servidor que os viu, num mapa plano ou num globo 3D, com a taxa, categorias, servidores, origens recentes, uma coluna de métricas e os últimos eventos, filtros, pausa e tela cheia. Abre reproduzindo os últimos eventos (`/api/v1/live/recent`), então não fica parada num servidor tranquilo. Num hub mostra também os eventos de todos os peers. A posição de cada servidor vem de `--location`.
**Ao vivo** (`#/live`): ataques desenhados como arcos animados da origem até o servidor que os viu, num mapa plano ou num globo 3D, com a taxa, categorias, servidores, origens recentes, uma coluna de métricas e os últimos eventos, filtros, pausa e tela cheia. Abre reproduzindo os últimos eventos (`/api/v1/live/recent`), então não fica parada num servidor tranquilo. Mostra os eventos de todas as sondas. A posição de cada servidor é definida por sonda na página Fontes (`--location` é o padrão da sonda primária).
<p align="center"><img src="../img/live-flat-dark-pt.png" width="900" alt="Página Ao vivo no mapa plano"><br><sub>Ao vivo: mapa plano.</sub></p>
<p align="center"><img src="../img/live-globe-dark-pt.png" width="900" alt="Página Ao vivo no globo 3D"><br><sub>Ao vivo: globo 3D.</sub></p>
@@ -81,7 +81,7 @@ Uma barra lateral (barra de abas no celular, com um menu "Mais" que rola quando
<p align="center"><img src="../img/incidents-dark-pt.png" width="900" alt="Página: Incidentes"><br><sub>Incidentes: chamados para achados do tráfego de saída.</sub></p>
<p align="center"><img src="../img/incident-detail-dark-pt.png" width="900" alt="Página: Chamado de incidente"><br><sub>Chamado de incidente: resumo, linha do tempo de atividade e propriedades.</sub></p>
**Tráfego de saída** (`#/egress`, exige `URUTAU_EGRESS` e o kit de host em `deploy/host`): as novas conexões de saída do host e dos contêineres, registradas pelo nftables, analisadas quanto a beaconing (conversas regulares com um destino, com o histograma de intervalos), mineração, portas de IRC e SMTP, contato com endereços que atacaram o servidor ou relays Tor, DNS fora dos resolvers permitidos, varreduras de saída não autorizadas e países novos. Mostra um veredito em linguagem simples, cartões de evidência, mapa de destinos, atividade por hora, workloads compactos (por nome de rede ou contêiner, `URUTAU_EGRESS_WORKLOADS`; um workload `scanner` tem só o tráfego em forma de varredura resumido) e a linha do tempo das varreduras autorizadas. Os próprios servidores, peers e o provedor do host nunca geram achados; conexões regulares a grandes CDNs e nuvens têm severidade baixa.
**Tráfego de saída** (`#/egress`, exige `URUTAU_EGRESS` e o kit de host em `deploy/host` numa sonda): as novas conexões de saída do host e dos contêineres, registradas pelo nftables, analisadas quanto a beaconing (conversas regulares com um destino, com o histograma de intervalos), mineração, portas de IRC e SMTP, contato com endereços que atacaram o servidor ou relays Tor, DNS fora dos resolvers permitidos, varreduras de saída não autorizadas e países novos. Mostra um veredito em linguagem simples, cartões de evidência, mapa de destinos, atividade por hora, workloads compactos (por nome de rede ou contêiner, `URUTAU_EGRESS_WORKLOADS`; um workload `scanner` tem só o tráfego em forma de varredura resumido) e a linha do tempo das varreduras autorizadas. Os próprios servidores, sondas e o provedor do host nunca geram achados; conexões regulares a grandes CDNs e nuvens têm severidade baixa.
<p align="center"><img src="../img/egress-dark-pt.png" width="900" alt="Página: Tráfego de saída"><br><sub>Tráfego de saída: rajadas de varredura, beacons e mineração em contêineres.</sub></p>
@@ -127,11 +127,11 @@ 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, peers, 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` um hub e seus peers trocam decisões, cada lado 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. 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>
**Fontes e hosts** (`#/sources`): cada instância com seu estado (online, latência, versão), cada fonte de log com seu estado (`following`, `waiting`, `backfill`, `error`, e degradada quando mais de 20% das últimas 1000 linhas são ilegíveis), linhas lidas, linhas malformadas e último evento (caminhos de arquivo não são mostrados), e a **blocklist**: escolha uma pontuação mínima (padrão 50), copie ou baixe. Só lista endereços hostis e globalmente roteáveis (nunca faixas de `--ignore` ou `--trusted`, nunca um IP com login SSH bem-sucedido, nunca um endereço cuja única evidência é um ban das jails `urutau` ou `recidive`); IPv6 aparece como seu /64, escrito `x:x:x:x::/64`.
**Fontes e hosts** (`#/sources`): cada sonda com seu estado (conectada, última linha, atraso, versão, linhas descartadas por spool cheio, tamanho do spool e erros de comando) e um formulário para criar uma (o token aparece uma vez, com um trecho de compose pronto), editar a localização e a configuração de egress ou revogá-la; para cada sonda, cada fonte de log com seu estado (`following`, `waiting`, `backfill`, `error`, e degradada quando mais de 20% das últimas 1000 linhas são ilegíveis), linhas lidas, linhas malformadas e último evento (caminhos de arquivo não são mostrados), e a **blocklist**: escolha uma pontuação mínima (padrão 50), copie ou baixe. Só lista endereços hostis e globalmente roteáveis (nunca faixas de `--ignore` ou `--trusted`, nunca um IP com login SSH bem-sucedido, nunca um endereço cuja única evidência é um ban das jails `urutau` ou `recidive`); IPv6 aparece como seu /64, escrito `x:x:x:x::/64`.
<p align="center"><img src="../img/sources-dark-pt.png" width="900" alt="Página Fontes e hosts: instâncias, fontes de log e blocklist"><br><sub>Fontes e hosts.</sub></p>
@@ -173,16 +173,13 @@ Os limites de estados e cidades da página Geografia são do [Natural Earth](htt
| `GET /api/v1/summary` | sessão ou bearer | tudo o que o dashboard mostra. Query: `range` (qualquer intervalo nomeado) ou `from` e `to`, `host` (`all`, um nome) |
| `GET /api/v1/traffic` | sessão ou bearer | web analytics do tráfego legítimo. Query: `range`, `domain` (`all` ou um domínio), `host`. Retorna visitantes, páginas, requisições, bots, bytes, classes de status, `p50_ms`, `p95_ms`, linha do tempo, top de páginas, referrers, países, cidades, navegadores, sistemas operacionais, dispositivos e nomes de bots |
| `GET /api/v1/geo` | sessão ou `URUTAU_TOKEN` | geografia dos atacantes. Sem `cc`: `{"countries":[{"cc","events","ips","hostile","suspicious","cats"}]}` (até 250). Com `cc=XX` (e opcionalmente `region`): `{"cc","events","ips","hostile","suspicious","cats","regions":[...],"cities":[{"name","region","lat","lon","events","ips"}],"top_ips":[...]}` (64 regiões, 200 cidades, 50 IPs). Query: `range`, `host`. Cache de 5 s |
| `GET /api/v1/live/recent` | sessão ou `URUTAU_TOKEN` | `{"events":[...]}`: os últimos eventos maliciosos desta instância e dos peers, do mais novo ao mais velho, no formato do stream. Query: `limit` (padrão 200, máximo 500) |
| `GET /api/v1/peer/stream` | só token de peer | federação ao vivo: eventos maliciosos desta instância por SSE. No máximo 10 conexões; mesmas regras 404/401/403 do export |
| `GET /api/v1/peer/export` | só token de peer | federação: `{"v":1,"summary":...,"traffic":{...}}` com os 500 IPs principais e seus detalhes. Query: `range` ou `from`/`to`. Cache de 5 s. 404 sem token de peer, 401 para `URUTAU_TOKEN`, 403 de origem fora de `--peer-allow` |
| `GET /api/v1/live/recent` | sessão ou `URUTAU_TOKEN` | `{"events":[...]}`: os últimos eventos maliciosos de todas as sondas, do mais novo ao mais velho, no formato do stream. Query: `limit` (padrão 200, máximo 500) |
| `GET /api/v1/events` | sessão ou bearer | eventos do registro, do mais novo ao mais antigo. Query: `range` ou `from`/`to`, `host`, `ip`, `cat`, `fam`, `q`, `order`, `limit`, `cursor` |
| `GET /api/v1/events/sessions` | sessão ou bearer | sessões (rajadas com estágio) do período, opcionalmente de um `ip` |
| `GET /api/v1/period` | sessão ou bearer | o estudo de um período: sessões, campanhas, técnicas vistas pela primeira vez, escaladas, picos, novos vs recorrentes, principais alvos, famílias, técnicas, usuários e ASNs. Query: `range` ou `from`/`to`, `host`, `gap` (segundos entre sessões, 30 a 86400) |
| `GET /api/v1/period/events` | sessão ou bearer | os eventos de um período no formato do stream, para o replay |
| `GET /api/v1/metrics` | sessão ou bearer | métricas estáveis (veja [arquitetura.md](arquitetura.md)). Query: `range` ou `from`/`to`, `host` |
| `GET /api/v1/ip/{ip}/stix` | sessão ou bearer | bundle STIX 2.1 de um IP |
| `GET /api/v1/peer/period` | só token de peer | federação: o estudo que um hub mescla. No máximo dois ao mesmo tempo (503 com `Retry-After` caso contrário) |
| `GET /api/v1/techniques` | sessão ou bearer | técnicas MITRE ATT&CK vistas no período |
| `GET /api/v1/evolution`, `/concentration`, `/survival` | sessão ou bearer | análises do período: mudança ao longo do tempo, concentração por IP e ASN, e tempo até o ban com a curva de Kaplan-Meier |
| `GET /api/v1/sessions/funnel` | sessão ou bearer | sessões por estágio (recon, probe, exploit, access, banned) |
@@ -194,7 +191,7 @@ Os limites de estados e cidades da página Geografia são do [Natural Earth](htt
| `GET /api/v1/services`, `/api/v1/services/{svc}` | sessão ou bearer | SLI, SLO, orçamento de erro, burn rate e Apdex por serviço |
| `GET /api/v1/protocols` | sessão ou bearer | versões de HTTP e TLS em uso |
| `GET /api/v1/ips` | sessão ou bearer | tabela de IPs. Query: `range`, `host`, `min_score`, `level`, `q`, `banned=1`, `sort` (`score`, `last`, `first`, `events`, `ip`), `order=asc`, `per` (1 a 200, padrão 50), `page` |
| `GET /api/v1/ip/{ip}` | sessão ou bearer | análise resumida de um IP: veredito com razões, ações, famílias, técnicas, tipo de rede, cadência, sessões e exposição; mesclada com os peers. Query: `range` ou `from`/`to` (padrão 30d) |
| `GET /api/v1/ip/{ip}` | sessão ou bearer | análise resumida de um IP: veredito com razões, ações, famílias, técnicas, tipo de rede, cadência, sessões e exposição; mesclada entre as sondas. Query: `range` ou `from`/`to` (padrão 30d) |
| `GET /api/v1/events/stream` | sessão ou bearer | Server-Sent Events, evento `ev`, um ping a cada 20 s. Com `visits=1` também envia eventos `visit` anônimos (sem endereço, no máximo 20 por segundo) |
| `GET /api/v1/blocklist.txt` | sessão ou bearer | um IP por linha. Query: `min_score` (padrão 50), `range` (padrão `7d`), `host`, `family` (`4`, `6`; padrão ambos; `4` serve ao `ipset hash:ip`), `download=1` |
| `GET /api/v1/blocklist.json` | sessão ou bearer | `{"generated","min_score","count","ips":[{"ip","score","last","hosts"}]}`; o `ip` de uma entrada IPv6 é um prefixo `/64` |
@@ -208,10 +205,11 @@ Os limites de estados e cidades da página Geografia são do [Natural Earth](htt
| `GET /api/v1/enforce` | sessão ou bearer | segundo firewall: modo, decisões recentes, cobertura e liberações do operador (`allows`) |
| `POST /api/v1/enforce/unban` | sessão ou bearer | pede ao host que levante um bloqueio e, opcionalmente, impede novo ban do endereço por 1 h, 24 h ou 7 dias (cross-site recusado) |
| `DELETE /api/v1/enforce/allow` | sessão ou bearer | encerra uma liberação do operador |
| `GET /api/v1/peer/egress`, `GET`/`POST /api/v1/peer/decisions`, `POST /api/v1/peer/unban` | só token de peer | federação: o relatório de saída que um hub mescla e a troca de decisões do segundo firewall e de desbans |
| `GET /api/v1/probes`, `POST /api/v1/probes`, `PUT /api/v1/probes/{nome}`, `DELETE /api/v1/probes/{nome}` | sessão ou bearer | registro de sondas por trás da página Fontes: lista com estado, atraso e contadores, cria (`{"name"}` responde `{"token"}`, mostrado uma vez), edita localização e egress, revoga (mantém os dados) |
| `POST /api/v1/probe/hello`, `POST /api/v1/probe/push`, `GET /api/v1/probe/commands` | só token de sonda | o protocolo da sonda ([arquitetura.md](arquitetura.md#sondas-e-o-hub)); toda outra rota recusa um token de sonda |
Um `range` ou período inválido responde 400, e `range` nas respostas é um objeto `{name,from,to,step,clipped}` (`step` é a granularidade da linha do tempo em segundos).
Clientes da API enviam `Authorization: Bearer <URUTAU_TOKEN>`. O token de peer só é aceito pelas rotas `/api/v1/peer/*` (`export`, `stream`, `period`, `egress`, `decisions`, `unban`); todas as outras rotas respondem 403 a ele.
Clientes da API enviam `Authorization: Bearer <URUTAU_TOKEN>`. Um token de sonda só é aceito pelas três rotas `/api/v1/probe/*` (com o cabeçalho `X-Urutau-Probe`); toda outra rota o recusa. As rotas `/api/v1/peer/*` da 1.x acabaram (404).
+49
View File
@@ -0,0 +1,49 @@
# Migração da 1.x para a 2.0
A 2.0 troca a federação entre pares por sondas. O hub guarda um nó por sonda, cada um com um diretório de dados
no mesmo formato da 1.x. Nada do que está registrado é convertido, mesclado ou reescrito: é copiado byte a byte e
depois verificado. Nenhum passo apaga dados. O guia completo (com todos os comandos) está em
[../migration-2.0.md](../migration-2.0.md); este é o resumo.
- **Oracle (nó primário):** o diretório de dados é reaproveitado sem conversão. Restaure o tar em um volume novo
e suba o hub 2.0 com `URUTAU_NAME` igual ao nome atual.
- **Hostinger:** `urutau import --from <dir> --host hostinger` copia tudo para `/data/probes/hostinger/`.
- **IDs de incidente:** aparecem como `hostinger/INC-3`; `INC-3` sozinho vale para o nó primário.
## O que o import copia
Tudo: `urutau-state.gob` (com as posições de leitura), `events/` (jsonl, jsonl.gz, idx), `incidents.json`,
`enforce.json`, `tor/` e qualquer arquivo desconhecido. `geo/` é pulado por padrão (o hub baixa as suas bases;
use `--include-geo` para copiar). Os arquivos `decisions.log`/`unban.log` ficam no host, fora do data-dir.
## Passos do corte
0. **Backup:** `docker compose stop urutau`, `tar --numeric-owner -czf urutau-data-<host>-<ts>.tgz` do volume
`/data`, conferir `sha256sum`, copiar os dois tars para o Oracle e para uma cópia fora, religar a 1.6.
Registrar as contagens com `urutau import --count <dir extraído>` e pela API 1.6 (`summary?range=30d`,
incidentes, bans ativos).
1. **Hub novo em volume novo** (não reaproveite o volume em uso, para o rollback ser trivial), com o tar do
Oracle restaurado nele, `URUTAU_NAME` igual ao atual, porta interna, sem domínio. Conferir as contagens.
2. **Sondas:** `urutau probes create oracle` e `urutau probes create hostinger`; o token vai para o `.env` de cada
host como `URUTAU_PROBE_TOKEN` (aparece uma única vez).
3. **Oracle:** parar a 1.6, apontar o domínio para o hub 2.0, subir a sonda (`http://urutau:8790`). Conferir em
Sources: conectada, lag abaixo de 5 s, sem lacuna. Enforce em `observe` por 30 min, depois `on`.
4. **Hostinger:** parar a 1.6, tar final, copiar para o Oracle e extrair. Com o hub parado (o import recusa se
existir `<data-dir>/.lock`): `--dry-run`, depois o import de verdade, depois `--verify`. Subir o hub e
conferir as contagens do nó `hostinger` (inclusive `hostinger/INC-2` com os comentários). Subir a sonda da
Hostinger: o hello devolve os offsets importados, então não há lacuna nem duplicata.
5. **Uma semana de observação**, depois remover o app antigo, o domínio, o DNS e o certificado da Hostinger.
Guardar os tars por 90 dias.
## Garantias do import
Cópia em diretório temporário com `rename` atômico; sha256 de todos os arquivos, mode e mtime preservados;
contagens (eventos, IPs, incidentes, comentários, supressões, bans) carregadas com o código real e comparadas;
detecta se a origem mudou durante a cópia. Rodar de novo com a mesma origem diz "already imported" e não faz
nada. Destino diferente sem `--force` é erro; com `--force` o destino antigo vai para `NOME.bak-<data>`, nunca é
apagado. `--dry-run` não escreve nada.
## Rollback
Em qualquer passo: parar o hub e as sondas, religar os apps 1.6 nos volumes originais (intocados), restaurar o
DNS. Perde-se só o que a 2.0 processou no intervalo; os logs brutos continuam no host.
+10 -8
View File
@@ -31,21 +31,23 @@ Não inclua detalhes de exploração numa issue pública. Siga o [SECURITY.pt-BR
| Sintoma | O que checar |
|---|---|
| O container sai ao iniciar com `URUTAU_TOKEN is required` | Defina `URUTAU_TOKEN` com no mínimo 32 caracteres e cerca de 128 bits de entropia estimada (comprimento vezes entropia de Shannon; tokens periódicos ou sequenciais são recusados) (`openssl rand -base64 48`), ou aponte `URUTAU_TOKEN_FILE` para um arquivo que o contenha |
| Uma fonte fica em `waiting` | O arquivo não existe nesse caminho dentro do container; confira a montagem e o caminho `URUTAU_*_LOG` |
| Uma fonte mostra `error` com `permission denied` | Adicione o grupo `adm` do host com `group_add: ["4"]` (`getent group adm`) e monte o arquivo com `:ro` |
| Uma fonte fica em `waiting` | Na página Fontes: a sonda não vê o arquivo nesse caminho dentro do container dela; confira a montagem e o caminho `URUTAU_*_LOG` da sonda |
| Uma fonte mostra `error` com `permission denied` | Adicione o grupo `adm` do host com `group_add: ["4"]` (`getent group adm`) e monte o diretório com `:ro` (no container da sonda) |
| A fonte do Traefik tem muitas linhas malformadas | O access log não é JSON; defina `accessLog.format: json` no Traefik |
| Linhas são contadas mas nada aparece | A origem está em `URUTAU_TRUSTED` ou `URUTAU_IGNORE` (as faixas privadas são descartadas por padrão), ou a requisição é de um User-Agent de monitoramento |
| Todos os acessos vêm de um endereço interno | O proxy esconde o cliente real; repasse o endereço do cliente ao Traefik |
| Os horários do fail2ban estão deslocados em horas | O `fail2ban.log` não tem fuso; defina `TZ` com o fuso do host |
| As contagens parecem duplicadas após um reinício | O snapshot não foi salvo ou foi perdido; monte `/data` em um volume |
| O dashboard fica inacessível de outro host | Ele faz bind em `127.0.0.1` via `URUTAU_PUBLISH`; confira o proxy reverso |
| Um hub se recusa a iniciar com `has no token` | Todo peer precisa de um token: defina `URUTAU_PEER_TOKEN` ou `URUTAU_PEER_TOKEN_<NOME>` (o nome do peer em maiúsculas, outros caracteres como `_`) |
| O hub se recusa a subir e menciona `migration-2.0` | Uma variável da 1.x ainda está definida (`URUTAU_PEERS`, `URUTAU_PEER_*`, ou um caminho de log como `URUTAU_TRAEFIK_LOG`): remova e crie sondas no lugar ([migracao-2.0.md](migracao-2.0.md)) |
| A sonda sai com `URUTAU_HUB`, `URUTAU_PROBE_NAME` ou `URUTAU_PROBE_TOKEN` ausente | Os três são obrigatórios; o token é o que `urutau probes create` imprimiu uma vez |
| O login responde 429 | Falhas demais daquele endereço; espere a janela (10 minutos) ou tente depois, o token correto ainda entra após 1 segundo de atraso |
| A fonte do Traefik fica em `waiting` no Coolify | O Traefik não está gravando `/traefik/logs/access.log`; veja a seção do Coolify em [docker.md](docker.md) |
| Um peer aparece offline | URL ou `URUTAU_PEER_TOKEN` errados, ou o peer não é alcançável pelo hub; o erro aparece no cartão do host |
| A fonte de sondagem ou de egress fica em `waiting` | O kit do host não está instalado ou grava em outro lugar: rode `sudo sh deploy/host/install.sh` e confira que `/var/log/urutau/probe.log` e `egress.log` estão montados em `/logs/host`; o egress com `URUTAU_EGRESS=auto` só liga se o `egress.log` existir quando o Urutau inicia |
| `urutau doctor` mostra `enforce` como `fail` | `URUTAU_ENFORCE=on` mas o arquivo de decisões não é gravável: monte `/var/log/urutau-enforce:/logs/enforce` com leitura e escrita, dono uid 10001 (`install.sh --enforce` faz isso) |
| Aparecem decisões mas nada é banido | A jail `urutau` do fail2ban não está ativa: rode `install.sh --enforce` e depois `fail2ban-client status urutau`; o modo `observe` nunca grava o arquivo |
| Uma sonda aparece offline, ou o log dela diz 401 | `URUTAU_HUB`, nome ou token errados, sonda revogada, ou o hub não é alcançável pela sonda (a sonda disca para fora: confira DNS, TLS e o proxy). Ela continua guardando em spool em `/state` nesse meio tempo; `http://` só funciona para loopback e endereços privados |
| A página Fontes mostra `dropped` acima de zero | O hub ficou inacessível por mais tempo do que o spool (`URUTAU_PROBE_SPOOL_MAX`) comporta, e os lotes mais antigos foram descartados; aumente o teto ou corrija a conexão. Os logs brutos continuam no host |
| A fonte de sondagem ou de egress fica em `waiting` | O kit do host não está instalado ou grava em outro lugar: rode `sudo sh deploy/host/install.sh --probe` e confira que `/var/log/urutau/probe.log` e `egress.log` estão montados em `/logs/host` na sonda; o egress com `URUTAU_EGRESS=auto` liga quando a sonda envia o log |
| `urutau doctor` mostra `enforce` como `fail` | `URUTAU_ENFORCE=on` mas a sonda não consegue gravar o arquivo de decisões (ela conta `cmd_errors`): na sonda, monte `/var/log/urutau-enforce:/logs/enforce` com leitura e escrita, dono uid 10001 (`install.sh --probe --enforce` faz isso) |
| Aparecem decisões mas nada é banido | A jail `urutau` do fail2ban não está ativa: rode `install.sh --probe --enforce` e depois `fail2ban-client status urutau`; o modo `observe` nunca grava o arquivo |
| `urutau doctor` mostra `enforce-cdn` | O Traefik registra endereços da Cloudflare como clientes: defina `forwardedHeaders.trustedIPs` com as faixas da Cloudflare para enxergar o atacante real |
| O container sai com `--enforce=on needs --enforce-log` ou `must be between` | Um valor de enforce, retenção ou egress está fora da faixa ou é desconhecido; rode `urutau doctor` e leia a linha `config` |
| O container sai com `must be between` ou um valor desconhecido | Um valor de enforce, retenção ou egress está fora da faixa ou é desconhecido; rode `urutau doctor` e leia a linha `config` |
| `--insecure-no-auth` é recusado | Só funciona em bind loopback; use um token |
+10 -8
View File
@@ -31,21 +31,23 @@ Do not include exploit details in a public issue. Follow [SECURITY.md](../SECURI
| Symptom | What to check |
|---|---|
| The container exits at start with `URUTAU_TOKEN is required` | Set `URUTAU_TOKEN` with at least 32 characters and about 128 bits of estimated entropy (length times Shannon entropy; periodic or sequential tokens are refused) (`openssl rand -base64 48`), or point `URUTAU_TOKEN_FILE` at a file that holds it |
| A source stays at `waiting` | The file does not exist at that path inside the container; check the mount and the `URUTAU_*_LOG` path |
| A source shows `error` with `permission denied` | Add the host `adm` group with `group_add: ["4"]` (`getent group adm`) and mount the file `:ro` |
| A source stays at `waiting` | On the Sources page: the probe cannot see the file at that path inside its container; check the mount and the `URUTAU_*_LOG` path of the probe |
| A source shows `error` with `permission denied` | Add the host `adm` group with `group_add: ["4"]` (`getent group adm`) and mount the directory `:ro` (on the probe container) |
| The Traefik source has many malformed lines | The access log is not JSON; set `accessLog.format: json` in Traefik |
| Lines count but nothing appears | The origin is in `URUTAU_TRUSTED` or `URUTAU_IGNORE` (private ranges are dropped by default), or the request is a monitoring User-Agent |
| All hits come from one internal address | The proxy hides the real client; pass the client address through to Traefik |
| fail2ban times are off by hours | `fail2ban.log` has no time zone; set `TZ` to the host's zone |
| Counts look duplicated after a restart | The snapshot was not saved or was lost; mount `/data` on a volume |
| The dashboard is unreachable from another host | It binds to `127.0.0.1` through `URUTAU_PUBLISH`; check the reverse proxy |
| A hub refuses to start with `has no token` | Every peer needs a token: set `URUTAU_PEER_TOKEN` or `URUTAU_PEER_TOKEN_<NAME>` (the peer name uppercased, other characters as `_`) |
| The hub refuses to start and mentions `migration-2.0` | A 1.x variable is still set (`URUTAU_PEERS`, `URUTAU_PEER_*`, or a log path such as `URUTAU_TRAEFIK_LOG`): remove it and create probes instead ([migration-2.0.md](migration-2.0.md)) |
| The probe exits with `URUTAU_HUB`, `URUTAU_PROBE_NAME` or `URUTAU_PROBE_TOKEN` missing | All three are required; the token is the one `urutau probes create` printed once |
| The login answers 429 | Too many failures from that address; wait for the window (10 minutes) or retry later, the correct token still gets in after a 1 second delay |
| The Traefik source stays at `waiting` on Coolify | Traefik is not writing `/traefik/logs/access.log`; see the Coolify section of [docker.md](docker.md) |
| A peer shows offline | Wrong URL or `URUTAU_PEER_TOKEN`, or the peer is not reachable from the hub; the error is shown on the host card |
| The probe or egress source stays at `waiting` | The host kit is not installed or writes elsewhere: run `sudo sh deploy/host/install.sh` and check `/var/log/urutau/probe.log` and `egress.log` are mounted at `/logs/host`; egress with `URUTAU_EGRESS=auto` only starts if `egress.log` exists when Urutau starts |
| `urutau doctor` shows `enforce` as `fail` | `URUTAU_ENFORCE=on` but the decision file is not writable: mount `/var/log/urutau-enforce:/logs/enforce` read and write, owned by uid 10001 (`install.sh --enforce` does it) |
| Decisions appear but nothing is banned | The `urutau` fail2ban jail is not active: run `install.sh --enforce`, then `fail2ban-client status urutau`; `observe` mode never writes the file |
| A probe shows offline, or its log says 401 | Wrong `URUTAU_HUB`, name or token, a revoked probe, or the hub is not reachable from the probe (the probe dials out: check DNS, TLS and the proxy). It keeps spooling to `/state` meanwhile; `http://` works only for loopback and private addresses |
| The Sources page shows `dropped` above zero | The hub was unreachable for longer than the spool (`URUTAU_PROBE_SPOOL_MAX`) holds, and the oldest batches were discarded; raise the cap or fix the connection. The raw logs are still on the host |
| The probe or egress source stays at `waiting` | The host kit is not installed or writes elsewhere: run `sudo sh deploy/host/install.sh --probe` and check `/var/log/urutau/probe.log` and `egress.log` are mounted at `/logs/host` in the probe; egress with `URUTAU_EGRESS=auto` starts when the probe sends the log |
| `urutau doctor` shows `enforce` as `fail` | `URUTAU_ENFORCE=on` but the probe cannot write the decision file (the probe counts `cmd_errors`): mount `/var/log/urutau-enforce:/logs/enforce` read and write on the probe, owned by uid 10001 (`install.sh --probe --enforce` does it) |
| Decisions appear but nothing is banned | The `urutau` fail2ban jail is not active: run `install.sh --probe --enforce`, then `fail2ban-client status urutau`; `observe` mode never writes the file |
| `urutau doctor` shows `enforce-cdn` | Traefik logs Cloudflare addresses as clients: set `forwardedHeaders.trustedIPs` to the Cloudflare ranges so the real attacker is seen |
| The container exits with `--enforce=on needs --enforce-log` or `must be between` | An enforce, retention or egress value is out of range or unknown; run `urutau doctor` and read the `config` line |
| The container exits with `must be between` or an unknown value | An enforce, retention or egress value is out of range or unknown; run `urutau doctor` and read the `config` line |
| `--insecure-no-auth` is refused | It only works on a loopback bind; use a token |
+41 -95
View File
@@ -89,17 +89,17 @@ func TestFlagsTrustedAndIgnoreAlias(t *testing.T) {
t.Fatalf("%+v", c)
}
c.Bind = "0.0.0.0:1"
if _, err := c.Validate(tok); err != nil {
if err := c.Validate(tok); err != nil {
t.Fatal(err)
}
c.MonitorUA = "("
if _, err := c.Validate(tok); err == nil {
if err := c.Validate(tok); err == nil {
t.Fatal("bad regex must be rejected")
}
if _, err := (Config{Ignore: "nonsense", MonitorUA: "", Retention: 168 * time.Hour}).Validate(tok); err == nil {
if err := (Config{Ignore: "nonsense", MonitorUA: "", Retention: 168 * time.Hour}).Validate(tok); err == nil {
t.Fatal("bad cidr must be rejected")
}
if _, err := (Config{NoAuth: true, Bind: "0.0.0.0:1", Retention: 168 * time.Hour}).Validate(""); err == nil {
if err := (Config{NoAuth: true, Bind: "0.0.0.0:1", Retention: 168 * time.Hour}).Validate(""); err == nil {
t.Fatal("no-auth must require loopback")
}
}
@@ -143,48 +143,45 @@ func TestEnrichmentFeedsThreatAndTraffic(t *testing.T) {
func TestTokenAndFederationValidation(t *testing.T) {
base := Config{Bind: "0.0.0.0:1", Retention: 168 * time.Hour, MonitorUA: "", Ignore: DefaultIgnore, TrustedProxy: DefaultTrustedProxy}
peerTok := "peer-token-0123456789-abcdefghijklmnopq"
if _, err := base.Validate("short-token-1234567890"); err == nil {
if err := base.Validate("short-token-1234567890"); err == nil {
t.Fatal("URUTAU_TOKEN under 32 characters must be refused")
}
if _, err := base.Validate(tok); err != nil {
if err := base.Validate(tok); err != nil {
t.Fatal(err)
}
c := base
c.PeerToken = "short-peer"
if _, err := c.Validate(tok); err == nil {
t.Fatal("peer token under 32 characters must be refused")
}
c.PeerToken = tok
if _, err := c.Validate(tok); err == nil {
t.Fatal("peer token equal to URUTAU_TOKEN must be refused")
}
c.PeerToken = peerTok
if _, err := c.Validate(tok); err != nil {
t.Fatal(err)
}
c.Peers = []string{"hostinger=https://urutau.example.org"}
c.PeerToken = ""
if _, err := c.Validate(tok); err == nil {
t.Fatal("peers without a peer token must be refused")
}
c.PeerToken = peerTok
c.Peers = []string{"hostinger=http://urutau.example.org"}
if _, err := c.Validate(tok); err == nil {
t.Fatal("plain http to a non-loopback peer must be refused")
}
c.Peers = []string{"h=http://127.0.0.1:8791"}
if _, err := c.Validate(tok); err != nil {
t.Fatalf("http is fine on loopback: %v", err)
}
c.PeerAllow, c.Peers = "not-a-cidr", nil
if _, err := c.Validate(tok); err == nil {
t.Fatal("bad --peer-allow must be refused")
}
cfg, err := ParseFlags("serve", []string{"--peer-allow", "203.0.113.0/24", "--peer-allow", "198.51.100.7", "--trusted-proxy", "10.0.0.0/8"})
if err != nil || cfg.PeerAllow != "203.0.113.0/24,198.51.100.7" || cfg.TrustedProxy != "10.0.0.0/8" {
cfg, err := ParseFlags("serve", []string{"--trusted-proxy", "10.0.0.0/8"})
if err != nil || cfg.TrustedProxy != "10.0.0.0/8" {
t.Fatalf("%+v %v", cfg, err)
}
bad := base
bad.Name = "Not Valid"
if err := bad.Validate(tok); err == nil {
t.Fatal("the primary probe name must follow wire.ValidName")
}
}
func TestRemovedEnvIsFatal(t *testing.T) {
t.Setenv("URUTAU_PEERS", "hostinger=https://x.example.org")
_, err := CheckRemovedEnv(os.LookupEnv)
if err == nil || !strings.Contains(err.Error(), "URUTAU_PEERS") || !strings.Contains(err.Error(), "migration-2.0") {
t.Fatalf("PEERS must stop the hub with a pointer to the guide: %v", err)
}
t.Setenv("URUTAU_PEERS", "")
os.Unsetenv("URUTAU_PEERS")
t.Setenv("URUTAU_PEER_TOKEN_HOSTINGER", "x")
if _, err := CheckRemovedEnv(os.LookupEnv); err == nil {
t.Fatal("per peer token must stop the hub")
}
os.Unsetenv("URUTAU_PEER_TOKEN_HOSTINGER")
t.Setenv("URUTAU_TRAEFIK_LOG", "/x")
warn, err := CheckRemovedEnv(os.LookupEnv)
if err != nil || len(warn) != 1 {
t.Fatalf("the 1.x image variables only warn: %v %v", warn, err)
}
t.Setenv("URUTAU_ENFORCE_LOG", "/x")
if _, err := CheckRemovedEnv(os.LookupEnv); err == nil {
t.Fatal("URUTAU_ENFORCE_LOG must be fatal")
}
}
func TestCorruptSnapshotDoesNotStopStartup(t *testing.T) {
@@ -306,13 +303,13 @@ func (panicEnr) UA(string) core.UAInfo { return core.UAInfo{} }
func TestTokenQualityAndFiles(t *testing.T) {
base := Config{Bind: "0.0.0.0:1", Retention: 168 * time.Hour, Ignore: DefaultIgnore, TrustedProxy: DefaultTrustedProxy}
if _, err := base.Validate(strings.Repeat("a", 40)); err == nil {
if err := base.Validate(strings.Repeat("a", 40)); err == nil {
t.Fatal("aaaa... must be refused: too few distinct characters")
}
if _, err := base.Validate("abababababababababababababababab"); err == nil {
if err := base.Validate("abababababababababababababababab"); err == nil {
t.Fatal("two distinct characters must be refused")
}
if _, err := base.Validate(tok); err != nil {
if err := base.Validate(tok); err != nil {
t.Fatal(err)
}
dir := t.TempDir()
@@ -329,57 +326,6 @@ func TestTokenQualityAndFiles(t *testing.T) {
}
}
func TestPerPeerTokens(t *testing.T) {
t.Setenv("URUTAU_PEER_TOKEN", "")
t.Setenv("URUTAU_PEER_TOKEN_HOSTINGER", "hostinger-token-0123456789-abcdefghijklmn")
f := filepath.Join(t.TempDir(), "o")
os.WriteFile(f, []byte("oracle-token-0123456789-abcdefghijklmnopq\n"), 0o600)
t.Setenv("URUTAU_PEER_TOKEN_MY_ORACLE_FILE", f)
c, err := ParseFlags("serve", []string{"--peer", "hostinger=https://h.example.org", "--peer", "my-oracle=https://o.example.org"})
if err != nil {
t.Fatal(err)
}
peers, err := c.Validate(tok)
if err != nil {
t.Fatal(err)
}
if peers[0].Token != "hostinger-token-0123456789-abcdefghijklmn" || peers[1].Token != "oracle-token-0123456789-abcdefghijklmnopq" {
t.Fatalf("per peer tokens: %+v", peers)
}
// Client tokens sent to peers never open the local export: a compromised
// peer knows its own token and must not read this instance with it.
if len(c.PeerTokens) != 0 {
t.Fatalf("per peer client tokens must not open the local export: %v", c.PeerTokens)
}
c.Peers = append(c.Peers, "nobody=https://n.example.org")
if _, err := c.Validate(tok); err == nil {
t.Fatal("a peer without any token must be refused")
}
}
func TestPeerServerTokenOnlyOpensExport(t *testing.T) {
t.Setenv("URUTAU_PEER_TOKEN", "server-side-token-Zq8vN3pL0xK7mR2wT5yB9cD")
t.Setenv("URUTAU_PEER_TOKEN_HOSTINGER", "client-side-token-Hj4kL9mN2pQ7rS1tV6wX3yZ")
c, err := ParseFlags("serve", []string{"--peer", "hostinger=https://h.example.org"})
if err != nil {
t.Fatal(err)
}
if len(c.PeerTokens) != 1 || c.PeerTokens[0] != "server-side-token-Zq8vN3pL0xK7mR2wT5yB9cD" {
t.Fatalf("export tokens: %v", c.PeerTokens)
}
}
func TestPeerNameTokenCollision(t *testing.T) {
t.Setenv("URUTAU_PEER_TOKEN", "server-side-token-Zq8vN3pL0xK7mR2wT5yB9cD")
c, err := ParseFlags("serve", []string{"--peer", "my-peer=https://a.example.org", "--peer", "my_peer=https://b.example.org"})
if err != nil {
t.Fatal(err)
}
if _, err := c.Validate(tok); err == nil || !strings.Contains(err.Error(), "share the token variable") {
t.Fatalf("colliding peer names must be refused, got %v", err)
}
}
// Without explicit configuration, X-Forwarded-For is only believed from loopback.
func TestTrustedProxyDefaultIsLoopback(t *testing.T) {
os.Unsetenv("URUTAU_TRUSTED_PROXY")
@@ -423,7 +369,7 @@ func TestLocationFlagIsValidated(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if _, err := c.Validate("zK3vQ9xT2mLp7WdR4nYb8HsJ6cFg1UaE5oXi0VtN"); (err == nil) != tc.ok {
if err := c.Validate("zK3vQ9xT2mLp7WdR4nYb8HsJ6cFg1UaE5oXi0VtN"); (err == nil) != tc.ok {
t.Errorf("%q: %v", tc.v, err)
}
}
+85 -167
View File
@@ -14,34 +14,31 @@ import (
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
// Config is the runtime configuration of `urutau serve` and `urutau doctor`.
type Config struct {
Bind string
Name string
DataDir string
Bind string
Name string
DataDir string
// Log paths: the hub no longer reads files (the probes do); these fields
// only serve tests and the file based Runner, they have no flag.
TraefikLog string
AuthLog string
Fail2banLog string
ProbeLog string // kernel log of new connections to unserved ports
Ignore string // networks whose events are dropped (--ignore, alias of --trusted)
Trusted string // trusted sources, e.g. the servers themselves (--trusted)
MonitorUA string // regex of monitoring User-Agents
MonitorFrom string // networks monitors come from (empty: any source)
Domains string // optional allowlist of analytics domains
AdminUsers string // SSH users whose logins grant admin immunity (empty: any user)
PeerTokens []string // tokens accepted by /api/v1/peer/export
PeerTokenFor map[string]string // per peer name (upper case) token used by the hub
GeoDir string // directory of the geo databases (default <data-dir>/geo)
ProbeLog string
Ignore string // networks whose events are dropped (--ignore, alias of --trusted)
Trusted string // trusted sources, e.g. the servers themselves (--trusted)
MonitorUA string // regex of monitoring User-Agents
MonitorFrom string // networks monitors come from (empty: any source)
Domains string // optional allowlist of analytics domains
AdminUsers string // SSH users whose logins grant admin immunity (empty: any user)
GeoDir string // directory of the geo databases (default <data-dir>/geo)
GeoUpdate time.Duration
Peers []string
PeerToken string
Location string // "lat,lon" or "lat,lon,label" (--location)
Location string // "lat,lon" or "lat,lon,label" (--location): default location of the primary probe
PeerBlocklist string // "on" (default) or "off"
PeerAllow string // CIDRs allowed to call /api/v1/peer/export (empty: any source with the token)
TrustedProxy string // proxies whose X-Forwarded-For is believed
Retention time.Duration
TorAuto string // on (default) or off: download the official Tor lists every 6 h
@@ -50,18 +47,19 @@ type Config struct {
NoAuth bool
// Second firewall (see internal/enforce).
Enforce string // off (default), observe or on
EnforceLog string // decision file read by the host fail2ban
EnforceUnbanLog string // unban requests (UI button) read by the host; default: unban.log next to --enforce-log
EnforceShare string // off (default) or on: exchange decisions with peers
EnforceLog string // decision file (tests only: in the hub decisions go to the probe)
EnforceUnbanLog string // unban file (tests only)
EnforceShare string // off (default) or on: a decision of one probe also reaches the others
EnforceThreshold int // attack events in 10 minutes that justify a ban
EnforceMaxPerMin int // decisions per minute; the excess is dropped
// Egress analysis (see internal/egress).
Egress string // auto (default: on when the log exists), on or off
EgressLog string // kernel log of new outbound connections
EgressLog string // kernel log of new outbound connections (tests only)
EgressWorkloads string // "name=CIDR|name:<prefix>[,...][:role];..."
EgressResolvers string // DNS resolvers allowed (empty: the usual public ones)
EgressContainers string // "<ip> <container>" map written by the host kit
EgressContainers string // "<ip> <container>" map (tests only)
EgressAllow string // URUTAU_EGRESS_ALLOW: default for the primary probe
}
// DefaultEventsMax is the default size cap of the event registry.
@@ -146,14 +144,9 @@ func ParseFlags(name string, args []string) (Config, error) {
fs := flag.NewFlagSet(name, flag.ContinueOnError)
var c Config
host, _ := os.Hostname()
var peers listFlag
fs.StringVar(&c.Bind, "bind", env("URUTAU_BIND", "0.0.0.0:8790"), "listen address (URUTAU_BIND)")
fs.StringVar(&c.Name, "name", env("URUTAU_NAME", host), "name of this instance (URUTAU_NAME)")
fs.StringVar(&c.DataDir, "data-dir", env("URUTAU_DATA_DIR", "/data"), "snapshot directory (URUTAU_DATA_DIR)")
fs.StringVar(&c.TraefikLog, "traefik-log", env("URUTAU_TRAEFIK_LOG", "/data/coolify/proxy/access.log"), "Traefik JSON access log, empty disables (URUTAU_TRAEFIK_LOG)")
fs.StringVar(&c.AuthLog, "auth-log", env("URUTAU_AUTH_LOG", "/var/log/auth.log"), "sshd auth log, empty disables (URUTAU_AUTH_LOG)")
fs.StringVar(&c.ProbeLog, "probe-log", env("URUTAU_PROBE_LOG", "/logs/host/probe.log"), "kernel log of network probes (unserved ports) written by the host kit, empty disables (URUTAU_PROBE_LOG)")
fs.StringVar(&c.Fail2banLog, "fail2ban-log", env("URUTAU_FAIL2BAN_LOG", "/var/log/fail2ban.log"), "fail2ban log, empty disables (URUTAU_FAIL2BAN_LOG)")
ign := &csvFlag{val: env("URUTAU_IGNORE", DefaultIgnore)}
trusted := &csvFlag{val: env("URUTAU_TRUSTED", "")}
fs.Var(ign, "ignore", "CIDRs/IPs whose events are dropped, repeatable or comma separated (URUTAU_IGNORE)")
@@ -167,28 +160,21 @@ func ParseFlags(name string, args []string) (Config, error) {
fs.StringVar(&c.GeoDir, "geo-dir", env("URUTAU_GEO_DIR", ""), "geo database directory, default <data-dir>/geo (URUTAU_GEO_DIR)")
fs.DurationVar(&c.GeoUpdate, "geo-update", 24*time.Hour, "how often the geo database is refreshed, 0 disables downloads (URUTAU_GEO_UPDATE)")
fs.StringVar(&c.MonitorUA, "monitor-ua", env("URUTAU_MONITOR_UA", DefaultMonitorUA), "regex of monitoring User-Agents; benign hits are counted apart, empty disables (URUTAU_MONITOR_UA)")
fs.Var(&peers, "peer", "peer instance name=https://url, repeatable (URUTAU_PEERS, comma separated)")
fs.StringVar(&c.PeerToken, "peer-token", "", "bearer token shared with peers; prefer URUTAU_PEER_TOKEN or URUTAU_PEER_TOKEN_FILE")
allow := &csvFlag{val: env("URUTAU_PEER_ALLOW", "")}
tproxy := &csvFlag{val: env("URUTAU_TRUSTED_PROXY", DefaultTrustedProxy)}
fs.Var(allow, "peer-allow", "CIDRs allowed to call /api/v1/peer/export, empty allows any source with the token (URUTAU_PEER_ALLOW)")
fs.Var(tproxy, "trusted-proxy", "reverse proxies whose X-Forwarded-For is trusted for the real client IP (URUTAU_TRUSTED_PROXY)")
fs.StringVar(&c.Location, "location", env("URUTAU_LOCATION", ""), `where this instance lives, "lat,lon" or "lat,lon,label"; shown as the destination of live arcs (URUTAU_LOCATION)`)
fs.StringVar(&c.PeerBlocklist, "peer-blocklist", env("URUTAU_PEER_BLOCKLIST", "on"), "on: the blocklist also lists strong hostile IPs seen only by peers; off: local IPs only (URUTAU_PEER_BLOCKLIST)")
fs.StringVar(&c.PeerBlocklist, "blocklist-scope", "on", "on: the blocklist lists the strong hostile IPs of every probe; off: the primary probe only")
fs.DurationVar(&c.Retention, "retention", store.DefaultRetention, "how long data is kept, at most 720h (URUTAU_RETENTION)")
fs.StringVar(&c.TorAuto, "tor-auto", env("URUTAU_TOR_AUTO", "on"), "download the official Tor exit and relay lists every 6 h into <data-dir>/tor: on or off (URUTAU_TOR_AUTO)")
fs.StringVar(&c.TorExits, "tor-exits", env("URUTAU_TOR_EXITS", ""), "file with Tor exit node addresses, one per line, reloaded every 24 h when it changes; empty disables (URUTAU_TOR_EXITS)")
fs.StringVar(&c.EventsMax, "events-max", env("URUTAU_EVENTS_MAX", DefaultEventsMax), "size cap of the event registry in <data-dir>/events, 0 disables it (URUTAU_EVENTS_MAX)")
fs.StringVar(&c.Enforce, "enforce", env("URUTAU_ENFORCE", "off"), "second firewall: off, observe (decide in memory only) or on (write decisions for the host fail2ban) (URUTAU_ENFORCE)")
fs.StringVar(&c.EnforceLog, "enforce-log", env("URUTAU_ENFORCE_LOG", "/logs/enforce/decisions.log"), "decision file appended in --enforce=on (URUTAU_ENFORCE_LOG)")
fs.StringVar(&c.EnforceUnbanLog, "enforce-unban-log", env("URUTAU_ENFORCE_UNBAN_LOG", ""), "unban request file written by the Unban button (URUTAU_ENFORCE_UNBAN_LOG); default unban.log next to --enforce-log")
fs.StringVar(&c.EnforceShare, "enforce-share", env("URUTAU_ENFORCE_SHARE", "off"), "on: exchange decisions with peers, each side applies its own exclusions (URUTAU_ENFORCE_SHARE)")
fs.StringVar(&c.Enforce, "enforce", env("URUTAU_ENFORCE", "off"), "second firewall: off, observe (decide in memory only) or on (queue decisions for each probe's host fail2ban) (URUTAU_ENFORCE)")
fs.StringVar(&c.EnforceShare, "enforce-share", env("URUTAU_ENFORCE_SHARE", "off"), "on: a decision of one probe also reaches the others, each applies its own exclusions (URUTAU_ENFORCE_SHARE)")
fs.IntVar(&c.EnforceThreshold, "enforce-threshold", envInt("URUTAU_ENFORCE_THRESHOLD", 5), "attack events in 10 minutes that justify a ban (URUTAU_ENFORCE_THRESHOLD)")
fs.StringVar(&c.Egress, "egress", env("URUTAU_EGRESS", "auto"), "egress analysis: auto (on when --egress-log exists), on or off (URUTAU_EGRESS)")
fs.StringVar(&c.EgressLog, "egress-log", env("URUTAU_EGRESS_LOG", "/logs/host/egress.log"), "kernel log of new outbound connections written by the host kit (URUTAU_EGRESS_LOG)")
fs.StringVar(&c.EgressWorkloads, "egress-workloads", env("URUTAU_EGRESS_WORKLOADS", ""), "workloads: \"ciberlab=name:<container prefix>:scanner;mail=10.0.7.0/24:mail\" (URUTAU_EGRESS_WORKLOADS)")
c.EgressAllow = env("URUTAU_EGRESS_ALLOW", "")
fs.StringVar(&c.EgressWorkloads, "egress-workloads", env("URUTAU_EGRESS_WORKLOADS", ""), "default workloads of the primary probe: \"ciberlab=name:<container prefix>:scanner;mail=10.0.7.0/24:mail\" (URUTAU_EGRESS_WORKLOADS)")
fs.StringVar(&c.EgressResolvers, "egress-resolvers", env("URUTAU_EGRESS_RESOLVERS", ""), "DNS resolvers allowed, comma separated; empty: the usual public ones (URUTAU_EGRESS_RESOLVERS)")
fs.StringVar(&c.EgressContainers, "egress-containers", env("URUTAU_EGRESS_CONTAINERS", "/logs/host/containers.map"), "\"<ip> <container>\" map written by the host kit (URUTAU_EGRESS_CONTAINERS)")
fs.IntVar(&c.EnforceMaxPerMin, "enforce-max-per-min", envInt("URUTAU_ENFORCE_MAX_PER_MIN", 60), "most decisions per minute, the excess is dropped and counted (URUTAU_ENFORCE_MAX_PER_MIN)")
fs.BoolVar(&c.NoAuth, "insecure-no-auth", false, "disable authentication; only allowed on a loopback bind")
if v := os.Getenv("URUTAU_GEO_UPDATE"); v != "" {
@@ -204,33 +190,9 @@ func ParseFlags(name string, args []string) (Config, error) {
if err := fs.Parse(args); err != nil {
return c, err
}
c.Peers = peers
c.Ignore, c.Trusted = ign.val, trusted.val
c.PeerAllow, c.TrustedProxy = allow.val, tproxy.val
c.TrustedProxy = tproxy.val
c.MonitorFrom, c.Domains, c.AdminUsers = mfrom.val, doms.val, admins.val
if c.PeerToken == "" {
var err error
if c.PeerToken, err = Secret("URUTAU_PEER_TOKEN"); err != nil {
return c, err
}
}
var err error
if c.PeerTokenFor, err = perPeerTokens(); err != nil {
return c, err
}
// Only the server token opens the local export. URUTAU_PEER_TOKEN_<NAME>
// are client credentials sent to that peer: a compromised peer learns
// them, so they must never open this instance's export.
if c.PeerToken != "" {
c.PeerTokens = append(c.PeerTokens, c.PeerToken)
}
if len(c.Peers) == 0 {
for _, p := range strings.Split(os.Getenv("URUTAU_PEERS"), ",") {
if p = strings.TrimSpace(p); p != "" {
c.Peers = append(c.Peers, p)
}
}
}
if c.GeoDir == "" {
c.GeoDir = filepath.Join(c.DataDir, "geo")
}
@@ -240,109 +202,104 @@ func ParseFlags(name string, args []string) (Config, error) {
return c, nil
}
// Validate checks the configuration and returns the parsed peers.
func (c Config) Validate(token string) ([]fed.Peer, error) {
// Validate checks the configuration.
func (c Config) Validate(token string) error {
if _, err := store.ParseLocation(c.Location); err != nil {
return nil, err
return err
}
if c.Name != "" && !wire.ValidName(c.Name) {
return fmt.Errorf("--name %q must be lowercase letters, digits and dashes, at most 32 characters: it is the name of the primary probe", c.Name)
}
if v := strings.ToLower(c.PeerBlocklist); v != "" && v != "on" && v != "off" {
return nil, fmt.Errorf("--peer-blocklist must be on or off")
return fmt.Errorf("--blocklist-scope must be on or off")
}
if c.Enforce != "" || c.EnforceShare != "" { // a Config built by hand may leave them unset
switch strings.ToLower(c.Enforce) {
case "", "off", "observe", "on":
default:
return nil, fmt.Errorf("--enforce must be off, observe or on")
return fmt.Errorf("--enforce must be off, observe or on")
}
if v := strings.ToLower(c.EnforceShare); v != "" && v != "off" && v != "on" {
return nil, fmt.Errorf("--enforce-share must be on or off")
return fmt.Errorf("--enforce-share must be on or off")
}
if c.EnforceThreshold < 1 || c.EnforceThreshold > 1000 {
return nil, fmt.Errorf("--enforce-threshold must be between 1 and 1000")
return fmt.Errorf("--enforce-threshold must be between 1 and 1000")
}
if c.EnforceMaxPerMin < 1 || c.EnforceMaxPerMin > 10000 {
return nil, fmt.Errorf("--enforce-max-per-min must be between 1 and 10000")
return fmt.Errorf("--enforce-max-per-min must be between 1 and 10000")
}
}
switch strings.ToLower(c.Egress) {
case "", "auto", "on", "off":
default:
return nil, fmt.Errorf("--egress must be auto, on or off")
}
if strings.EqualFold(c.Enforce, "on") && c.EnforceLog == "" {
return nil, fmt.Errorf("--enforce=on needs --enforce-log")
}
if c.EnforceUnbanLog == "" && c.EnforceLog != "" {
c.EnforceUnbanLog = filepath.Join(filepath.Dir(c.EnforceLog), "unban.log")
}
var peers []fed.Peer
seen := map[string]bool{}
envSeen := map[string]string{}
for _, s := range c.Peers {
p, err := fed.ParsePeer(s)
if err != nil {
return nil, err
}
if seen[p.Name] || p.Name == c.Name || p.Name == "all" {
return nil, fmt.Errorf("peer name %q is duplicated or reserved", p.Name)
}
if other, dup := envSeen[tokenEnvName(p.Name)]; dup {
return nil, fmt.Errorf("peer names %q and %q share the token variable URUTAU_PEER_TOKEN_%s", other, p.Name, tokenEnvName(p.Name))
}
envSeen[tokenEnvName(p.Name)] = p.Name
seen[p.Name] = true
peers = append(peers, p)
return fmt.Errorf("--egress must be auto, on or off")
}
if _, err := core.ParseCIDRs(c.Ignore + "," + c.Trusted); err != nil {
return nil, fmt.Errorf("--ignore/--trusted: %w", err)
return fmt.Errorf("--ignore/--trusted: %w", err)
}
if c.MonitorUA != "" {
if _, err := regexp.Compile(c.MonitorUA); err != nil {
return nil, fmt.Errorf("--monitor-ua: %w", err)
return fmt.Errorf("--monitor-ua: %w", err)
}
}
if c.Retention < time.Hour || c.Retention > store.DefaultRetention {
return nil, fmt.Errorf("--retention must be between 1h and 720h")
return fmt.Errorf("--retention must be between 1h and 720h")
}
if c.EventsMax != "" {
if _, err := ParseSize(c.EventsMax); err != nil {
return nil, fmt.Errorf("--events-max: %w", err)
return fmt.Errorf("--events-max: %w", err)
}
}
if c.NoAuth {
if !loopbackBind(c.Bind) {
return nil, fmt.Errorf("--insecure-no-auth is only allowed on a loopback bind (got %q)", c.Bind)
return fmt.Errorf("--insecure-no-auth is only allowed on a loopback bind (got %q)", c.Bind)
}
} else if err := checkToken("URUTAU_TOKEN", token); err != nil {
return nil, err
return err
}
all := append([]string(nil), c.PeerTokens...)
if c.PeerToken != "" && !contains(all, c.PeerToken) {
all = append(all, c.PeerToken)
}
for _, t := range c.PeerTokenFor {
all = append(all, t)
}
for _, t := range all {
if err := checkToken("URUTAU_PEER_TOKEN", t); err != nil {
return nil, err
}
if t == token {
return nil, fmt.Errorf("a peer token must differ from URUTAU_TOKEN")
}
}
for i := range peers {
peers[i].Token = c.PeerTokenFor[tokenEnvName(peers[i].Name)]
if peers[i].Token == "" && c.PeerToken == "" {
return nil, fmt.Errorf("peer %q has no token: set URUTAU_PEER_TOKEN or URUTAU_PEER_TOKEN_%s", peers[i].Name, tokenEnvName(peers[i].Name))
}
}
for _, l := range []struct{ name, v string }{{"--peer-allow", c.PeerAllow}, {"--trusted-proxy", c.TrustedProxy}, {"--monitor-from", c.MonitorFrom}} {
for _, l := range []struct{ name, v string }{{"--trusted-proxy", c.TrustedProxy}, {"--monitor-from", c.MonitorFrom}} {
if _, err := core.ParseCIDRs(l.v); err != nil {
return nil, fmt.Errorf("%s: %w", l.name, err)
return fmt.Errorf("%s: %w", l.name, err)
}
}
return peers, nil
return nil
}
// MigrationGuide is where the removed 1.x variables are explained.
const MigrationGuide = "docs/migration-2.0.md"
// removedEnv are the 1.x variables that make the 2.0 hub refuse to start. The
// log path variables moved to the probe (URUTAU_*_LOG there).
var removedEnv = []string{"URUTAU_PEERS", "URUTAU_PEER_TOKEN", "URUTAU_PEER_TOKEN_FILE", "URUTAU_PEER_ALLOW", "URUTAU_PEER_BLOCKLIST",
"URUTAU_TRAEFIK_LOG", "URUTAU_AUTH_LOG", "URUTAU_FAIL2BAN_LOG", "URUTAU_PROBE_LOG", "URUTAU_EGRESS_LOG", "URUTAU_EGRESS_CONTAINERS",
"URUTAU_ENFORCE_LOG", "URUTAU_ENFORCE_UNBAN_LOG"}
// softEnv are set by the 1.x image: only a warning.
var softEnv = map[string]bool{"URUTAU_TRAEFIK_LOG": true, "URUTAU_AUTH_LOG": true, "URUTAU_FAIL2BAN_LOG": true}
// CheckRemovedEnv returns an error naming the removed variables that are set
// (the old image's TRAEFIK/AUTH/FAIL2BAN defaults only produce warnings).
func CheckRemovedEnv(lookup func(string) (string, bool)) (warn []string, err error) {
var bad []string
for _, k := range removedEnv {
if _, ok := lookup(k); ok {
if softEnv[k] {
warn = append(warn, k)
} else {
bad = append(bad, k)
}
}
}
// URUTAU_PEER_TOKEN_<NAME>[_FILE]
for _, kv := range os.Environ() {
if k, _, _ := strings.Cut(kv, "="); strings.HasPrefix(k, "URUTAU_PEER_TOKEN_") && !contains(bad, k) {
bad = append(bad, k)
}
}
if len(bad) > 0 {
return warn, fmt.Errorf("these variables were removed in Urutau 2.0 (the federation and the log paths moved to probes): %s; see %s", strings.Join(bad, ", "), MigrationGuide)
}
return warn, nil
}
func loopbackBind(bind string) bool {
@@ -448,45 +405,6 @@ func Secret(name string) (string, error) {
return "", nil
}
// tokenEnvName turns a peer name into its environment suffix: "hostinger" ->
// "HOSTINGER", "my-peer" -> "MY_PEER".
func tokenEnvName(name string) string {
return strings.Map(func(r rune) rune {
switch {
case r >= 'a' && r <= 'z':
return r - 32
case r >= 'A' && r <= 'Z', r >= '0' && r <= '9':
return r
}
return '_'
}, name)
}
// perPeerTokens collects URUTAU_PEER_TOKEN_<NAME> and URUTAU_PEER_TOKEN_<NAME>_FILE.
func perPeerTokens() (map[string]string, error) {
const prefix = "URUTAU_PEER_TOKEN_"
out := map[string]string{}
for _, kv := range os.Environ() {
k, v, _ := strings.Cut(kv, "=")
if !strings.HasPrefix(k, prefix) || k == prefix+"FILE" || v == "" {
continue
}
name := strings.TrimPrefix(k, prefix)
if strings.HasSuffix(name, "_FILE") {
b, err := os.ReadFile(v)
if err != nil {
return nil, fmt.Errorf("%s: %w", k, err)
}
out[strings.TrimSuffix(name, "_FILE")] = strings.TrimSpace(string(b))
continue
}
if _, set := out[name]; !set {
out[name] = v
}
}
return out, nil
}
// AdminUserList splits --admin-users into names.
func (c Config) AdminUserList() []string {
var out []string
+2 -2
View File
@@ -31,10 +31,10 @@ func Doctor(c Config, w io.Writer, asJSON bool) bool {
token, terr := Secret("URUTAU_TOKEN")
if terr != nil {
add("config", "fail", terr.Error())
} else if _, err := c.Validate(token); err != nil {
} else if err := c.Validate(token); err != nil {
add("config", "fail", err.Error())
} else {
add("config", "ok", "token, peers and bind are valid")
add("config", "ok", "token and bind are valid")
}
for _, s := range []struct{ name, path string }{{"traefik", c.TraefikLog}, {"ssh", c.AuthLog}, {"fail2ban", c.Fail2banLog}} {
if s.path == "" {
+24 -46
View File
@@ -1,10 +1,8 @@
package app
import (
"log/slog"
"net"
"net/netip"
"net/url"
"os"
"strconv"
"strings"
@@ -12,25 +10,23 @@ import (
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/hub"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/server"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
// newEgress builds the egress analysis, or returns nil when it is off (or in
// auto mode without the host log).
func newEgress(c Config, st *store.Store, log *slog.Logger) (*egress.Source, error) {
mode := strings.ToLower(c.Egress)
if mode == "off" || c.EgressLog == "" {
return nil, nil
// egressMode reports whether the egress analysis may exist at all.
func egressOff(c Config) bool { return strings.ToLower(c.Egress) == "off" }
// newEgressEngine builds the egress engine of one node from its own
// configuration (workloads, resolvers, allow); the primary probe falls back
// to the URUTAU_EGRESS_* defaults of the hub.
func newEgressEngine(c Config, st *store.Store, eg hub.Egress, primary bool) (*egress.Engine, error) {
workloads, resolvers, extra := eg.Workloads, eg.Resolvers, eg.Allow
if primary {
workloads, resolvers = orDefault(workloads, c.EgressWorkloads), orDefault(resolvers, c.EgressResolvers)
extra = orDefault(extra, c.EgressAllow)
}
if mode == "" || mode == "auto" {
if _, err := os.Stat(c.EgressLog); err != nil {
return nil, nil
}
}
allow := egressAllow(c)
var provMu sync.Mutex
var provCache []string
provider := func() []string {
@@ -41,11 +37,11 @@ func newEgress(c Config, st *store.Store, log *slog.Logger) (*egress.Source, err
}
return provCache
}
eng, err := egress.New(egress.Config{
Workloads: c.EgressWorkloads,
Resolvers: c.EgressResolvers,
Allow: allow,
Containers: c.EgressContainers,
return egress.New(egress.Config{
Workloads: workloads,
Resolvers: resolvers,
Allow: egressAllow(c, extra),
ResolvConf: []string{}, // the probe sends its own resolv.conf
TorRelay: func(a netip.Addr) bool { return intel.IsTorRelay(a) && !intel.IsTorExit(a) },
ProviderASNs: provider,
Geo: func(ip string) (string, string, string) {
@@ -66,30 +62,13 @@ func newEgress(c Config, st *store.Store, log *slog.Logger) (*egress.Source, err
return false, ""
},
})
if err != nil {
return nil, err
}
server.SetEgress(eng)
log.Info("egress analysis on", "log", c.EgressLog)
return egress.NewSource(c.EgressLog, eng, log), nil
}
// egressExtraAllow adds to the egress Allow list the addresses of the peers and
// the CIDRs of URUTAU_EGRESS_ALLOW (legitimate periodic pollers).
func egressExtraAllow(c Config) []netip.Prefix {
// egressExtraAllow parses a comma separated list of CIDRs and addresses
// (URUTAU_EGRESS_ALLOW: legitimate periodic pollers).
func egressExtraAllow(spec string) []netip.Prefix {
var out []netip.Prefix
for _, ps := range c.Peers {
p, err := fed.ParsePeer(ps)
if err != nil {
continue
}
if u, err := url.Parse(p.URL); err == nil && u.Hostname() != "" {
for _, a := range resolveHost(u.Hostname()) {
out = append(out, netip.PrefixFrom(a, a.BitLen()))
}
}
}
for _, s := range strings.Split(os.Getenv("URUTAU_EGRESS_ALLOW"), ",") {
for _, s := range strings.Split(spec, ",") {
if s = strings.TrimSpace(s); s == "" {
continue
}
@@ -166,15 +145,14 @@ func providerASNs(explicit string, asnOf func(ip string) uint32) []string {
// egressAllow is the list of destinations that never produce a finding: the
// trusted origins (our own servers, an invalid item does not discard the
// others), the federation peers, URUTAU_EGRESS_ALLOW and the local public
// addresses.
func egressAllow(c Config) []netip.Prefix {
// others), the extra list of the probe and the local public addresses.
func egressAllow(c Config, extra string) []netip.Prefix {
var allow []netip.Prefix
for _, part := range strings.Split(c.Trusted, ",") {
if nets, err := core.ParseCIDRs(part); err == nil {
allow = append(allow, nets...)
}
}
allow = append(allow, egressExtraAllow(c)...)
allow = append(allow, egressExtraAllow(extra)...)
return append(allow, ownPublicPrefixes()...)
}
+29 -110
View File
@@ -1,43 +1,31 @@
package app
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"net"
"net/netip"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
// newEnforce builds the second firewall and hooks it into the store; nil when off.
func newEnforce(c Config, st *store.Store, peers []fed.Peer, en enricher, ready func() bool) *enforce.Engine {
// newEnforce builds the second firewall of one node and hooks it into the
// node's store; nil when off. The decisions go to sink (the probe's queue).
func newEnforce(c Config, st *store.Store, name, dir string, sink func(kind, line string) error, en enricher, ready func() bool) *enforce.Engine {
mode := strings.ToLower(c.Enforce)
if mode != enforce.ModeObserve && mode != enforce.ModeOn {
return nil
}
trusted, _ := core.ParseCIDRs(c.Ignore + "," + c.Trusted)
var hosts []string
for _, p := range peers {
if u, err := url.Parse(p.URL); err == nil && u.Hostname() != "" {
hosts = append(hosts, u.Hostname())
}
}
e := enforce.New(enforce.Config{
Mode: mode, Path: c.EnforceLog, UnbanPath: unbanLogPath(c), StatePath: filepath.Join(c.DataDir, "enforce.json"), Host: c.Name,
Mode: mode, Sink: sink, StatePath: filepath.Join(dir, "enforce.json"), Host: name,
Threshold: c.EnforceThreshold, MaxPerMin: c.EnforceMaxPerMin, Share: strings.EqualFold(c.EnforceShare, "on"),
Trusted: trusted, PeerHosts: hosts, InfraHosts: hosts, Resolve: resolveHost,
Trusted: trusted, Resolve: resolveHost,
Crawler: func(ip string, uas []string) bool {
if v := st.FCrDNS(ip, uas); v != nil && *v {
return true
@@ -91,41 +79,33 @@ func resolveHost(h string) []netip.Addr {
return ips
}
// shareDecisions pulls the decisions of every peer and pushes the local ones, every 30 s.
func shareDecisions(ctx context.Context, hub *fed.Hub, e *enforce.Engine, log *slog.Logger) {
pulled := map[string]int64{}
pushed := map[string]int64{}
pushedUn := map[string]int64{}
// shareDecisions relays, every 30 s, the decisions and unbans of each node to
// the others (ENFORCE_SHARE=on); each receiver applies its own exclusions.
func shareDecisions(ctx context.Context, nodes func() []*Node) {
type mark struct{ dec, un int64 }
last := map[[2]string]mark{} // [from, to]
t := time.NewTicker(30 * time.Second)
defer t.Stop()
for {
for _, p := range hub.Peers {
start := time.Now().Unix()
var in struct {
Decisions []enforce.Wire `json:"decisions"`
all := nodes()
for _, from := range all {
if from.Enf == nil {
continue
}
if err := hub.Get(ctx, p, fmt.Sprintf("/api/v1/peer/decisions?since=%d", pulled[p.Name]), &in); err == nil {
e.AcceptPeer(p.Name, in.Decisions)
pulled[p.Name] = start - 5
} else if ctx.Err() == nil {
log.Debug("enforce: pull failed", "peer", p.Name, "err", err)
}
if mine := e.LocalSince(pushed[p.Name]); len(mine) > 0 {
if err := hub.PostJSON(ctx, p, "/api/v1/peer/decisions?from="+url.QueryEscape(e.Host()), map[string]any{"decisions": mine}); err == nil {
pushed[p.Name] = start
} else if ctx.Err() == nil {
log.Debug("enforce: push failed", "peer", p.Name, "err", err)
for _, to := range all {
if to == from || to.Enf == nil {
continue
}
}
}
for _, p := range hub.Peers {
if mine := e.UnbansSince(pushedUn[p.Name]); len(mine) > 0 {
k := [2]string{from.name, to.name}
m := last[k]
start := time.Now().Unix()
if err := hub.PostJSON(ctx, p, "/api/v1/peer/unban?from="+url.QueryEscape(e.Host()), map[string]any{"unbans": mine}); err == nil {
pushedUn[p.Name] = start
} else if ctx.Err() == nil {
log.Debug("enforce: unban push failed", "peer", p.Name, "err", err)
if d := from.Enf.LocalSince(m.dec); len(d) > 0 {
to.Enf.AcceptPeer(from.name, d)
}
if u := from.Enf.UnbansSince(m.un); len(u) > 0 {
to.Enf.AcceptPeerUnban(from.name, u)
}
last[k] = mark{start - 5, start}
}
}
select {
@@ -136,77 +116,16 @@ func shareDecisions(ctx context.Context, hub *fed.Hub, e *enforce.Engine, log *s
}
}
// doctorEnforce reports the mode of the second firewall and its file.
// doctorEnforce reports the mode of the second firewall. Decisions are queued
// for the probes, which write them on their hosts (the probe reports a
// command that cannot be written as cmd_errors).
func doctorEnforce(c Config, add func(name, status, detail string)) {
mode := strings.ToLower(c.Enforce)
if mode == "" || mode == "off" {
add("enforce", "off", "disabled (--enforce=off)")
return
}
w := enforce.Writable(c.EnforceLog)
detail := fmt.Sprintf("mode=%s share=%s threshold=%d file=%s writable=%v", mode, strings.ToLower(orDefault(c.EnforceShare, "off")), c.EnforceThreshold, c.EnforceLog, w)
switch {
case mode == "on" && !w:
add("enforce", "fail", detail)
case !w:
add("enforce", "warn", detail)
default:
add("enforce", "ok", detail)
}
if mode == "on" {
if n, tot := cloudflareClients(c.TraefikLog); n > 0 {
add("enforce-cdn", "warn", fmt.Sprintf("%d of the last %d requests in %s come from Cloudflare addresses: Traefik is not "+
"restoring the real client IP (set entryPoints.*.forwardedHeaders.trustedIPs to the Cloudflare ranges); "+
"Cloudflare is never banned, but the real attackers stay invisible", n, tot, c.TraefikLog))
}
}
}
// cloudflareClients counts, in the tail of the Traefik JSON access log, the
// requests whose ClientHost is a Cloudflare address.
func cloudflareClients(path string) (cf, total int) {
if path == "" {
return 0, 0
}
f, err := os.Open(path)
if err != nil {
return 0, 0
}
defer f.Close()
const tail = 512 << 10
if fi, err := f.Stat(); err == nil && fi.Size() > tail {
f.Seek(fi.Size()-tail, io.SeekStart)
}
sc := bufio.NewScanner(f)
sc.Buffer(make([]byte, 0, 64<<10), 1<<20)
for sc.Scan() {
var l struct {
ClientHost string `json:"ClientHost"`
}
if json.Unmarshal(sc.Bytes(), &l) != nil || l.ClientHost == "" {
continue
}
a, err := netip.ParseAddr(l.ClientHost)
if err != nil {
continue
}
total++
if enforce.IsCloudflare(a) {
cf++
}
}
return cf, total
}
// unbanLogPath is --enforce-unban-log, or unban.log next to --enforce-log.
func unbanLogPath(c Config) string {
if c.EnforceUnbanLog != "" {
return c.EnforceUnbanLog
}
if c.EnforceLog == "" {
return ""
}
return filepath.Join(filepath.Dir(c.EnforceLog), "unban.log")
add("enforce", "ok", fmt.Sprintf("mode=%s share=%s threshold=%d (decisions are queued for each probe)", mode, strings.ToLower(orDefault(c.EnforceShare, "off")), c.EnforceThreshold))
}
func tallyOf(t store.Tally24) enforce.Tally {
+795
View File
@@ -0,0 +1,795 @@
package app
// Import of a 1.x data directory into a 2.0 hub (see docs/migration-2.0.md).
//
// The rule that shapes everything here: no byte registered in production may
// be lost. So the import never merges, never rewrites and never deletes: it
// copies the whole directory (every file, known or not) into the node
// directory of the probe, byte for byte, and proves the copy with sha256 of
// every file plus counts loaded with the real store, evlog and incident code.
import (
"bufio"
"bytes"
"compress/gzip"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"sort"
"strings"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/incidents"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
// ManifestName is the proof of a finished import, written inside the node
// directory (and so renamed into place together with the data).
const ManifestName = "import-manifest.json"
// lockName is the lock the hub holds on its data directory while it runs.
const lockName = ".lock"
// ImportOptions tune Import.
type ImportOptions struct {
// DryRun reads and compares everything but writes nothing at all.
DryRun bool
// Force replaces a divergent destination by moving it to <dest>.bak-<ts>
// (it is never deleted).
Force bool
// IncludeGeo also copies geo/ (the databases are re-downloaded by the hub,
// so by default they are skipped with a warning).
IncludeGeo bool
}
// FileCopy is one entry of the copy.
type FileCopy struct {
Path string `json:"path"` // relative, slash separated
Kind string `json:"kind"` // file, dir or symlink
Size int64 `json:"size"` // bytes (files)
Mode uint32 `json:"mode"` // permission bits
MTime int64 `json:"mtime_ns"` // modification time, unix ns
SHA256 string `json:"sha256,omitempty"` // files: content; symlinks: of the target text
Target string `json:"target,omitempty"` // symlinks
}
// Counts is what a data directory holds, measured by loading it with the real
// code of the 1.x store, evlog and incidents.
type Counts struct {
Events int `json:"events"` // lines of events/*.jsonl and *.jsonl.gz
EventFiles int `json:"event_files"` // day files in events/
IPs int `json:"ips"` // addresses of the snapshot
Offsets int `json:"offsets"` // saved read positions of the snapshot
Incidents int `json:"incidents"` // tickets of incidents.json
Comments int `json:"comments"` // comments over all tickets
Suppressed int `json:"suppressed"` // tickets with an active suppression
EnforceBans int `json:"enforce_bans"` // bans (with history) of enforce.json
EnforceAllow int `json:"enforce_allow"` // allows of enforce.json
}
// ImportReport is the result of Import and VerifyImport.
type ImportReport struct {
Counts
Files []FileCopy `json:"files"`
Skipped bool `json:"skipped"` // already imported, nothing done
DryRun bool `json:"dry_run"` // nothing was written
Dest string `json:"dest"` // node directory
Backup string `json:"backup,omitempty"` // where --force moved the old destination
Warnings []string `json:"warnings,omitempty"`
}
type manifest struct {
Version int `json:"version"`
Host string `json:"host"`
From string `json:"from"`
ImportedAt string `json:"imported_at"`
Files []FileCopy `json:"files"`
Counts Counts `json:"counts"`
}
// importDest is where the files of a probe live: <data-dir>/probes/<host>.
func importDest(dataDir, host string) string { return NodeDir(dataDir, host, false) }
// FormatCounts is the stable text of `urutau import --count`.
func FormatCounts(c Counts) string {
return fmt.Sprintf("events=%d event_files=%d ips=%d offsets=%d incidents=%d comments=%d suppressed=%d enforce_bans=%d enforce_allow=%d\n",
c.Events, c.EventFiles, c.IPs, c.Offsets, c.Incidents, c.Comments, c.Suppressed, c.EnforceBans, c.EnforceAllow)
}
// ---------------------------------------------------------------------------
// counting
// CountDir loads a data directory read-only and counts what is in it. The
// directory is never modified: the incident store is opened on a private copy
// because Open renames a corrupt file.
func CountDir(dir string) (Counts, error) {
var c Counts
fi, err := os.Stat(dir)
if err != nil {
return c, err
}
if !fi.IsDir() {
return c, fmt.Errorf("%s is not a directory", dir)
}
// snapshot, with the real store code (no IP cap: the snapshot is measured, not trimmed)
snap := SnapshotPath(dir)
if _, err := os.Stat(snap); err == nil {
st := store.New(store.Config{Name: "count", MaxIPs: 1 << 30})
offs, err := st.Load(snap)
if err != nil {
return c, fmt.Errorf("snapshot %s: %w", snap, err)
}
c.IPs, c.Offsets = st.IPCount(), len(offs)
}
// event registry
ents, err := os.ReadDir(filepath.Join(dir, "events"))
if err != nil && !errors.Is(err, os.ErrNotExist) {
return c, err
}
for _, e := range ents {
n := e.Name()
if e.IsDir() || !(strings.HasSuffix(n, ".jsonl") || strings.HasSuffix(n, ".jsonl.gz")) {
continue
}
k, err := countLines(filepath.Join(dir, "events", n), strings.HasSuffix(n, ".gz"))
if err != nil {
return c, fmt.Errorf("events/%s: %w", n, err)
}
c.Events += k
c.EventFiles++
}
// incidents, with the real incident code on a private copy
if b, err := os.ReadFile(filepath.Join(dir, "incidents.json")); err == nil {
if !json.Valid(b) {
return c, errors.New("incidents.json is not valid JSON")
}
tmp, err := os.MkdirTemp("", "urutau-count-")
if err != nil {
return c, err
}
defer os.RemoveAll(tmp)
p := filepath.Join(tmp, "incidents.json")
if err := os.WriteFile(p, b, 0o600); err != nil {
return c, err
}
is, err := incidents.Open(p, nil)
if err != nil {
return c, err
}
c.Incidents = is.Stats().Size
now := time.Now().Unix()
for _, s := range is.All(incidents.Query{}) {
c.Comments += s.CommentCount
if s.Suppress && (s.SuppressUntil == 0 || s.SuppressUntil > now) {
c.Suppressed++
}
}
} else if !errors.Is(err, os.ErrNotExist) {
return c, err
}
// enforce.json (ban history)
if b, err := os.ReadFile(filepath.Join(dir, "enforce.json")); err == nil {
var sf struct {
Bans map[string]json.RawMessage `json:"bans"`
Allows map[string]json.RawMessage `json:"allows"`
}
if err := json.Unmarshal(b, &sf); err != nil {
return c, fmt.Errorf("enforce.json: %w", err)
}
c.EnforceBans, c.EnforceAllow = len(sf.Bans), len(sf.Allows)
} else if !errors.Is(err, os.ErrNotExist) {
return c, err
}
return c, nil
}
func countLines(path string, gz bool) (int, error) {
f, err := os.Open(path)
if err != nil {
return 0, err
}
defer f.Close()
var r io.Reader = f
if gz {
zr, err := gzip.NewReader(f)
if err != nil {
return 0, err
}
defer zr.Close()
r = zr
}
br := bufio.NewReaderSize(r, 256*1024)
n := 0
for {
line, err := br.ReadBytes('\n')
if len(bytes.TrimSpace(line)) > 0 {
n++
}
if err == io.EOF {
return n, nil
}
if err != nil {
return n, err
}
}
}
// ---------------------------------------------------------------------------
// tree
type tree struct {
entries []FileCopy
warnings []string
}
// scanTree lists root (without hashes). Symlinks are kept as symlinks and
// never followed; sockets and devices are skipped with a warning.
func scanTree(root string, includeGeo, dest bool) (*tree, error) {
t := &tree{}
err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
rel, _ := filepath.Rel(root, p)
if rel == "." {
return nil
}
rel = filepath.ToSlash(rel)
top := strings.SplitN(rel, "/", 2)[0]
switch {
case rel == lockName:
t.warnings = append(t.warnings, ".lock of the source is not copied")
return nil
case rel == ManifestName && dest:
t.entries = append(t.entries, FileCopy{Path: rel, Kind: "file"})
return nil
case rel == ManifestName:
return fmt.Errorf("the source already holds %s: it is an import destination, not a 1.x data directory", ManifestName)
case top == "geo" && !includeGeo:
if rel == "geo" {
t.warnings = append(t.warnings, "geo/ skipped (the hub downloads its own databases; use --include-geo to copy it)")
}
if d.IsDir() {
return fs.SkipDir
}
return nil
}
fi, err := d.Info()
if err != nil {
return err
}
e := FileCopy{Path: rel, Mode: uint32(fi.Mode().Perm()), MTime: fi.ModTime().UnixNano(), Size: fi.Size()}
switch m := fi.Mode(); {
case m.IsDir():
e.Kind, e.Size = "dir", 0
case m.IsRegular():
e.Kind = "file"
case m&fs.ModeSymlink != 0:
tg, err := os.Readlink(p)
if err != nil {
return err
}
sum := sha256.Sum256([]byte(tg))
e.Kind, e.Target, e.SHA256, e.Size = "symlink", tg, hex.EncodeToString(sum[:]), 0
default:
t.warnings = append(t.warnings, fmt.Sprintf("%s: special file skipped", rel))
return nil
}
t.entries = append(t.entries, e)
return nil
})
sort.Slice(t.entries, func(i, j int) bool { return t.entries[i].Path < t.entries[j].Path })
return t, err
}
func hashFile(path string) (string, int64, error) {
f, err := os.Open(path)
if err != nil {
return "", 0, err
}
defer f.Close()
h := sha256.New()
n, err := io.Copy(h, f)
return hex.EncodeToString(h.Sum(nil)), n, err
}
// hashTree fills the sha256 of every regular file of t.
func hashTree(root string, t *tree) error {
for i := range t.entries {
e := &t.entries[i]
if e.Kind != "file" {
continue
}
sum, n, err := hashFile(filepath.Join(root, filepath.FromSlash(e.Path)))
if err != nil {
return err
}
e.SHA256, e.Size = sum, n
}
return nil
}
// sameContent compares what the files hold (path, kind, size, hash, target).
func sameContent(a, b []FileCopy) []string {
bm := make(map[string]FileCopy, len(b))
for _, e := range b {
bm[e.Path] = e
}
var diff []string
seen := map[string]bool{}
for _, x := range a {
seen[x.Path] = true
y, ok := bm[x.Path]
switch {
case !ok:
diff = append(diff, "missing: "+x.Path)
case x.Kind != y.Kind:
diff = append(diff, "kind differs: "+x.Path)
case x.SHA256 != y.SHA256 || x.Size != y.Size || x.Target != y.Target:
diff = append(diff, "content differs: "+x.Path)
}
}
for _, y := range b {
if !seen[y.Path] {
diff = append(diff, "extra: "+y.Path)
}
}
sort.Strings(diff)
return diff
}
// sameMeta compares mode and mtime (files and dirs; symlinks have no own mtime we keep).
func sameMeta(a, b []FileCopy) []string {
bm := make(map[string]FileCopy, len(b))
for _, e := range b {
bm[e.Path] = e
}
var diff []string
for _, x := range a {
if x.Kind == "symlink" {
continue
}
if y, ok := bm[x.Path]; ok && (x.Mode != y.Mode || x.MTime != y.MTime) {
diff = append(diff, "mode or mtime differs: "+x.Path)
}
}
return diff
}
// ---------------------------------------------------------------------------
// import
func checkArgs(from, dataDir, host string) (src, dst string, err error) {
if !wire.ValidName(host) {
return "", "", fmt.Errorf("invalid host name %q (lowercase letters, digits and dashes, up to 32)", host)
}
if src, err = filepath.Abs(from); err != nil {
return
}
fi, serr := os.Stat(src)
if serr != nil {
return "", "", serr
}
if !fi.IsDir() {
return "", "", fmt.Errorf("--from %s is not a directory", from)
}
dd, err := filepath.Abs(dataDir)
if err != nil {
return
}
dst = importDest(dd, host)
if within(src, dd) || within(dd, src) {
return "", "", fmt.Errorf("--from %s and the data dir %s must not contain one another", src, dd)
}
return src, dst, nil
}
func within(a, b string) bool {
r, err := filepath.Rel(b, a)
return err == nil && (r == "." || (r != ".." && !strings.HasPrefix(r, ".."+string(filepath.Separator))))
}
// Import copies the whole 1.x data directory `from` into the node directory of
// `host` under dataDir and verifies the copy. See the package comment.
func Import(from, dataDir, host string, opt ImportOptions) (ImportReport, error) {
rep := ImportReport{DryRun: opt.DryRun}
src, dst, err := checkArgs(from, dataDir, host)
if err != nil {
return rep, err
}
dataDir, _ = filepath.Abs(dataDir)
rep.Dest = dst
lock := filepath.Join(dataDir, lockName)
if _, err := os.Lstat(lock); err == nil {
return rep, fmt.Errorf("%s exists: the hub (or another import) is running on this data dir; stop it first (if it is stale, remove the file)", lock)
}
// read the source twice, around the copy, to catch a writer
t, err := scanTree(src, opt.IncludeGeo, false)
if err != nil {
return rep, err
}
rep.Warnings = append(rep.Warnings, t.warnings...)
if err := hashTree(src, t); err != nil {
return rep, err
}
rep.Files = t.entries
srcCounts, err := CountDir(src)
if err != nil {
return rep, fmt.Errorf("source does not load: %w", err)
}
rep.Counts = srcCounts
// destination state
if _, err := os.Lstat(dst); err == nil {
prev, merr := readManifest(dst)
if merr == nil && len(sameContent(t.entries, prev.Files)) == 0 {
rep.Skipped = true
if cur, err := scanTree(dst, true, true); err == nil {
_ = hashTree(dst, cur)
if d := sameContent(prev.Files, dropManifest(cur.entries)); len(d) > 0 {
rep.Warnings = append(rep.Warnings, fmt.Sprintf("destination changed since the import (%d files; the hub already ran?); nothing was touched", len(d)))
}
}
return rep, nil
}
if !opt.Force {
return rep, fmt.Errorf("%s already exists with different content (or no manifest); nothing was changed. Compare with --verify, or use --force to move it to %s.bak-<timestamp> (never deleted)", dst, dst)
}
} else if !errors.Is(err, os.ErrNotExist) {
return rep, err
}
if opt.DryRun {
return rep, nil
}
// from here on we write: take the data-dir lock so the hub cannot start in the middle
if err := os.MkdirAll(dataDir, 0o700); err != nil {
return rep, err
}
lf, err := os.OpenFile(lock, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
if err != nil {
return rep, fmt.Errorf("cannot take %s: %w", lock, err)
}
fmt.Fprintf(lf, "import pid=%d\n", os.Getpid())
lf.Close()
defer os.Remove(lock)
parent := filepath.Dir(dst)
if err := os.MkdirAll(parent, 0o700); err != nil {
return rep, err
}
stamp := time.Now().UTC().Format("20060102T150405")
tmp := filepath.Join(parent, fmt.Sprintf(".import-%s-%d.tmp", host, os.Getpid()))
if err := os.RemoveAll(tmp); err != nil { // our own leftover of this very pid
return rep, err
}
ok := false
defer func() {
if !ok {
os.RemoveAll(tmp)
}
}()
if err := copyTree(src, tmp, t.entries); err != nil {
return rep, err
}
// verify the copy: hashes of what was written, counts through the real loaders, and the source unchanged
got, err := scanTree(tmp, true, true)
if err != nil {
return rep, err
}
if err := hashTree(tmp, got); err != nil {
return rep, err
}
if d := sameContent(t.entries, got.entries); len(d) > 0 {
return rep, fmt.Errorf("copy verification failed (%d differences, first: %s); nothing was installed", len(d), d[0])
}
if d := sameMeta(t.entries, got.entries); len(d) > 0 {
return rep, fmt.Errorf("copy verification failed (%s); nothing was installed", d[0])
}
dstCounts, err := CountDir(tmp)
if err != nil {
return rep, fmt.Errorf("copy does not load: %w", err)
}
if dstCounts != srcCounts {
return rep, fmt.Errorf("counts differ after the copy: source %+v, copy %+v; nothing was installed", srcCounts, dstCounts)
}
after, err := scanTree(src, opt.IncludeGeo, false)
if err != nil {
return rep, err
}
if err := hashTree(src, after); err != nil {
return rep, err
}
if d := sameContent(t.entries, after.entries); len(d) > 0 {
return rep, fmt.Errorf("the source changed while it was being copied (%s): stop the 1.x instance and run again; nothing was installed", d[0])
}
m := manifest{Version: 1, Host: host, From: src, ImportedAt: time.Now().UTC().Format(time.RFC3339), Files: t.entries, Counts: srcCounts}
mb, _ := json.MarshalIndent(m, "", " ")
if err := writeFileSync(filepath.Join(tmp, ManifestName), mb, 0o600); err != nil {
return rep, err
}
syncDir(tmp)
if opt.Force {
if _, err := os.Lstat(dst); err == nil {
bak := dst + ".bak-" + stamp
for i := 2; ; i++ { // never overwrite an earlier backup
if _, err := os.Lstat(bak); errors.Is(err, os.ErrNotExist) {
break
}
bak = fmt.Sprintf("%s.bak-%s-%d", dst, stamp, i)
}
if err := os.Rename(dst, bak); err != nil {
return rep, err
}
rep.Backup = bak
}
}
if err := os.Rename(tmp, dst); err != nil {
return rep, err
}
ok = true
syncDir(parent)
return rep, nil
}
func dropManifest(in []FileCopy) []FileCopy {
out := make([]FileCopy, 0, len(in))
for _, e := range in {
if e.Path != ManifestName {
out = append(out, e)
}
}
return out
}
func readManifest(dir string) (manifest, error) {
var m manifest
b, err := os.ReadFile(filepath.Join(dir, ManifestName))
if err != nil {
return m, err
}
return m, json.Unmarshal(b, &m)
}
// copyTree copies entries (already listed under src) to dst, preserving mode
// and mtime. Directories get their times last, children first.
func copyTree(src, dst string, entries []FileCopy) error {
if err := os.MkdirAll(dst, 0o700); err != nil {
return err
}
var dirs []FileCopy
for _, e := range entries {
from, to := filepath.Join(src, filepath.FromSlash(e.Path)), filepath.Join(dst, filepath.FromSlash(e.Path))
switch e.Kind {
case "dir":
if err := os.MkdirAll(to, 0o700); err != nil {
return err
}
dirs = append(dirs, e)
case "symlink":
if err := os.Symlink(e.Target, to); err != nil {
return err
}
case "file":
if err := copyFile(from, to, e); err != nil {
return fmt.Errorf("%s: %w", e.Path, err)
}
}
}
for i := len(dirs) - 1; i >= 0; i-- {
e := dirs[i]
to := filepath.Join(dst, filepath.FromSlash(e.Path))
if err := os.Chmod(to, fs.FileMode(e.Mode)); err != nil {
return err
}
syncDir(to)
if err := os.Chtimes(to, time.Unix(0, e.MTime), time.Unix(0, e.MTime)); err != nil {
return err
}
}
return nil
}
func copyFile(from, to string, e FileCopy) error {
in, err := os.Open(from)
if err != nil {
return err
}
defer in.Close()
out, err := os.OpenFile(to, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
if err != nil {
return err
}
_, err = io.Copy(out, in)
if err == nil {
err = out.Sync()
}
if cerr := out.Close(); err == nil {
err = cerr
}
if err != nil {
return err
}
if err := os.Chmod(to, fs.FileMode(e.Mode)); err != nil {
return err
}
return os.Chtimes(to, time.Unix(0, e.MTime), time.Unix(0, e.MTime))
}
func writeFileSync(path string, b []byte, mode fs.FileMode) error {
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, mode)
if err != nil {
return err
}
_, err = f.Write(b)
if err == nil {
err = f.Sync()
}
if cerr := f.Close(); err == nil {
err = cerr
}
return err
}
func syncDir(p string) {
if f, err := os.Open(p); err == nil {
_ = f.Sync()
f.Close()
}
}
// ---------------------------------------------------------------------------
// verify
// VerifyImport compares the source with the imported node directory (it
// writes nothing): sha256, size, mode and mtime of every file, then the counts.
// Run it before the hub starts on the destination; once the hub runs, its
// files change by design.
func VerifyImport(from, dataDir, host string) (ImportReport, error) {
rep := ImportReport{DryRun: true}
src, dst, err := checkArgs(from, dataDir, host)
if err != nil {
return rep, err
}
rep.Dest = dst
m, err := readManifest(dst)
if err != nil {
return rep, fmt.Errorf("%s has no readable %s (not imported yet?): %w", dst, ManifestName, err)
}
// geo/ was in the copy iff the manifest lists it
withGeo := false
for _, e := range m.Files {
if e.Path == "geo" || strings.HasPrefix(e.Path, "geo/") {
withGeo = true
break
}
}
s, err := scanTree(src, withGeo, false)
if err != nil {
return rep, err
}
rep.Warnings = append(rep.Warnings, s.warnings...)
if err := hashTree(src, s); err != nil {
return rep, err
}
d, err := scanTree(dst, true, true)
if err != nil {
return rep, err
}
if err := hashTree(dst, d); err != nil {
return rep, err
}
rep.Files = s.entries
var bad []string
bad = append(bad, sameContent(s.entries, dropManifest(d.entries))...)
bad = append(bad, sameMeta(s.entries, d.entries)...)
sc, err := CountDir(src)
if err != nil {
return rep, err
}
rep.Counts = sc
dc, err := CountDir(dst)
if err != nil {
return rep, err
}
if sc != dc {
bad = append(bad, fmt.Sprintf("counts differ: source %+v, destination %+v", sc, dc))
}
if len(bad) > 0 {
n := len(bad)
if n > 10 {
bad = append(bad[:10], fmt.Sprintf("... and %d more", n-10))
}
return rep, fmt.Errorf("verification FAILED (%d problems):\n %s", n, strings.Join(bad, "\n "))
}
return rep, nil
}
// ---------------------------------------------------------------------------
// command line
// ImportCLI runs `urutau import ...` (args after the word "import") and
// returns the exit code.
//
// urutau import --from DIR --host NAME [--data-dir D] [--dry-run] [--force] [--include-geo]
// urutau import --verify --from DIR --host NAME [--data-dir D]
// urutau import --count DIR
func ImportCLI(args []string, out, errw io.Writer) int {
fs := flag.NewFlagSet("import", flag.ContinueOnError)
fs.SetOutput(errw)
from := fs.String("from", "", "1.x data directory to import (stopped instance)")
host := fs.String("host", "", "name of the probe that receives it")
dataDir := fs.String("data-dir", env("URUTAU_DATA_DIR", "/data"), "hub data directory (URUTAU_DATA_DIR)")
dry := fs.Bool("dry-run", false, "compare and report, write nothing")
force := fs.Bool("force", false, "move a divergent destination to .bak-<ts> (never deleted)")
geo := fs.Bool("include-geo", false, "also copy geo/")
verify := fs.Bool("verify", false, "only compare --from with the imported copy")
count := fs.String("count", "", "print the counts of this data directory and exit")
if err := fs.Parse(args); err != nil {
return 2
}
if *count != "" {
c, err := CountDir(*count)
if err != nil {
fmt.Fprintln(errw, "error:", err)
return 1
}
fmt.Fprint(out, FormatCounts(c))
return 0
}
if *from == "" || *host == "" {
fmt.Fprintln(errw, "usage: urutau import --from DIR --host NAME [--data-dir D] [--dry-run] [--force] [--include-geo] | --verify ... | --count DIR")
return 2
}
if *verify {
rep, err := VerifyImport(*from, *dataDir, *host)
for _, w := range rep.Warnings {
fmt.Fprintln(errw, "warning:", w)
}
if err != nil {
fmt.Fprintln(errw, "error:", err)
return 1
}
fmt.Fprintf(out, "verified: %d files identical (sha256, mode, mtime) in %s\n%s", len(rep.Files), rep.Dest, FormatCounts(rep.Counts))
return 0
}
rep, err := Import(*from, *dataDir, *host, ImportOptions{DryRun: *dry, Force: *force, IncludeGeo: *geo})
for _, w := range rep.Warnings {
fmt.Fprintln(errw, "warning:", w)
}
if err != nil {
fmt.Fprintln(errw, "error:", err)
return 1
}
switch {
case rep.Skipped:
fmt.Fprintf(out, "already imported into %s, nothing done\n", rep.Dest)
case rep.DryRun:
fmt.Fprintf(out, "dry run: %d entries would be copied to %s\n", len(rep.Files), rep.Dest)
default:
fmt.Fprintf(out, "imported %d entries into %s\n", len(rep.Files), rep.Dest)
if rep.Backup != "" {
fmt.Fprintf(out, "previous destination kept at %s\n", rep.Backup)
}
}
fmt.Fprint(out, FormatCounts(rep.Counts))
return 0
}
+537
View File
@@ -0,0 +1,537 @@
package app
import (
"bytes"
"context"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/incidents"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
// fixture is a data directory as written by Urutau 1.6 on the Hostinger host.
// Regenerate it (and expected.json) with:
//
// URUTAU_REGEN_FIXTURE=1 go test ./internal/app -run TestRegenFixture16 -count=1
const fixture = "testdata/hostinger-1.6"
func TestRegenFixture16(t *testing.T) {
if os.Getenv("URUTAU_REGEN_FIXTURE") != "1" {
t.Skip("set URUTAU_REGEN_FIXTURE=1 to regenerate " + fixture)
}
dir, _ := filepath.Abs(fixture)
if err := os.RemoveAll(dir); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(dir, 0o700); err != nil {
t.Fatal(err)
}
now := time.Now()
// store + evlog: the same wiring as serve.go
elog, err := evlog.Open(evlog.Options{Dir: filepath.Join(dir, "events"), Retention: 30 * 24 * time.Hour})
if err != nil {
t.Fatal(err)
}
st := store.New(store.Config{Name: "hostinger", Version: "1.6.0", Retention: 7 * 24 * time.Hour})
st.SetEventLog(elog)
type ev struct {
ip string
cat core.Category
src string
path string
st int
ago time.Duration
n int
}
for _, e := range []ev{
{"203.0.114.7", core.Scanner, "traefik", "/.env", 404, 3 * time.Hour, 6},
{"203.0.114.8", core.Exploit, "traefik", "/cgi-bin/../../etc/passwd", 400, 2 * time.Hour, 4},
{"198.51.101.20", core.SSHFail, "ssh", "", 0, 50 * time.Hour, 5},
{"198.51.101.21", core.OK, "traefik", "/", 200, 26 * time.Hour, 3},
{"192.0.2.99", core.Scanner, "traefik", "/wp-login.php", 404, 90 * time.Hour, 2},
} {
for i := 0; i < e.n; i++ {
c := core.Event{Time: now.Add(-e.ago + time.Duration(i)*time.Second), IP: e.ip, Cat: e.cat, Source: e.src, Domain: "a.example", Method: "GET", Path: e.path, Status: e.st, UA: "fixture"}
if e.src == "ssh" {
c.User = "root"
}
st.Ingest(c)
}
}
elog.Flush()
elog.Close()
if err := st.Save(SnapshotPath(dir), map[string]store.Offset{
"traefik": {Inode: 4242, Offset: 1048576},
"auth": {Inode: 4243, Offset: 22000},
"egress": {Inode: 4244, Offset: 90210},
}); err != nil {
t.Fatal(err)
}
// incidents: INC-1 suppressed, INC-2 with comments, INC-3 manual
is, err := incidents.Open(filepath.Join(dir, "incidents.json"), nil)
if err != nil {
t.Fatal(err)
}
is.Sync([]incidents.Finding{
{Host: "hostinger", Kind: "new-destination", Severity: "medium", Workload: "app-a", Dst: "198.51.100.5", Proto: "tcp", DPort: 443, First: now.Add(-48 * time.Hour).Unix(), Last: now.Add(-time.Hour).Unix(), Count: 12, Detail: "first contact"},
{Host: "hostinger", Kind: "exfil", Severity: "high", Workload: "app-b", Dst: "203.0.113.50", Proto: "tcp", DPort: 4444, First: now.Add(-24 * time.Hour).Unix(), Last: now.Add(-time.Hour).Unix(), Count: 40, Detail: "large upload"},
})
if _, err := is.Create(incidents.NewManual{Title: "Manual review of the proxy", Detail: "opened by the operator", Host: "hostinger", Severity: "low", Author: "lucas"}); err != nil {
t.Fatal(err)
}
fp, yes := "false_positive", true
if _, err := is.Update("INC-1", incidents.Patch{Status: &fp, Suppress: &yes, Author: "lucas"}); err != nil {
t.Fatal(err)
}
for _, c := range []string{"Looks like the nightly backup.", "Confirmed with the app owner; keep watching."} {
if _, err := is.AddComment("INC-2", c, "lucas", ""); err != nil {
t.Fatal(err)
}
}
is.Flush()
// enforce.json: real bans through the real engine
decisions := filepath.Join(t.TempDir(), "decisions.log")
eng := enforce.New(enforce.Config{Mode: enforce.ModeOn, Path: decisions, StatePath: filepath.Join(dir, "enforce.json"), Host: "hostinger", Threshold: 5, MaxPerMin: 60})
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() { eng.Run(ctx); close(done) }()
for _, ip := range []string{"203.0.114.7", "203.0.114.8"} {
for i := 0; i < 6; i++ {
eng.Observe(core.Event{Time: time.Now().Add(-time.Duration(i) * time.Second), IP: ip, Cat: core.Scanner, Source: "traefik", Method: "GET", Path: "/x", Status: 404, UA: "x"}, "")
}
}
for i := 0; i < 100; i++ {
if b, _ := os.ReadFile(decisions); strings.Count(string(b), "\n") >= 2 {
break
}
time.Sleep(100 * time.Millisecond)
}
cancel()
<-done
// files the contract does not name: tor cache, a note, and geo (skipped by default)
must := func(p, s string) {
p = filepath.Join(dir, p)
if err := os.MkdirAll(filepath.Dir(p), 0o750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(p, []byte(s), 0o640); err != nil {
t.Fatal(err)
}
}
must("tor/exit-addresses.txt", "198.51.100.200\n198.51.100.201\n")
must("tor/relays.json", `{"relays":[]}`)
must("operator-notes.txt", "unknown file kept verbatim\n")
must("geo/GeoLite2-City.mmdb", "not a real database")
// fixed mtimes, so the preservation check is meaningful
old := time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC)
for _, p := range []string{"operator-notes.txt", "tor/relays.json", "tor/exit-addresses.txt"} {
_ = os.Chtimes(filepath.Join(dir, p), old, old)
}
c, err := CountDir(dir)
if err != nil {
t.Fatal(err)
}
b, _ := json.MarshalIndent(c, "", " ")
if err := os.WriteFile(filepath.Join(filepath.Dir(dir), "hostinger-1.6.expected.json"), append(b, '\n'), 0o644); err != nil {
t.Fatal(err)
}
t.Logf("fixture regenerated: %+v", c)
}
func expectedCounts(t *testing.T) Counts {
b, err := os.ReadFile("testdata/hostinger-1.6.expected.json")
if err != nil {
t.Fatal(err)
}
var c Counts
if err := json.Unmarshal(b, &c); err != nil {
t.Fatal(err)
}
return c
}
func TestFixtureCounts(t *testing.T) {
c, err := CountDir(fixture)
if err != nil {
t.Fatal(err)
}
if want := expectedCounts(t); c != want {
t.Fatalf("counts %+v want %+v", c, want)
}
if c.Events < 10 || c.IPs < 4 || c.Incidents != 3 || c.Comments < 2 || c.Suppressed < 1 || c.EnforceBans < 2 || c.Offsets != 3 {
t.Fatalf("fixture is not realistic enough: %+v", c)
}
}
func mustImport(t *testing.T, from, dd, host string, o ImportOptions) ImportReport {
t.Helper()
r, err := Import(from, dd, host, o)
if err != nil {
t.Fatal(err)
}
return r
}
func copyDir(t *testing.T, from string) string {
t.Helper()
to := filepath.Join(t.TempDir(), "src")
tr, err := scanTree(from, true, false)
if err != nil {
t.Fatal(err)
}
if err := copyTree(from, to, tr.entries); err != nil {
t.Fatal(err)
}
return to
}
func TestImportCountsAndHashes(t *testing.T) {
dd := t.TempDir()
fixture := copyDir(t, fixture) // git does not keep mtimes: pin one
old := time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC)
os.Chtimes(filepath.Join(fixture, "operator-notes.txt"), old, old)
rep := mustImport(t, fixture, dd, "hostinger", ImportOptions{})
dest := filepath.Join(dd, "probes", "hostinger")
if rep.Dest != dest || rep.Skipped || rep.DryRun {
t.Fatalf("report %+v", rep)
}
if want := expectedCounts(t); rep.Counts != want {
t.Fatalf("counts %+v want %+v", rep.Counts, want)
}
got, err := CountDir(dest)
if err != nil || got != rep.Counts {
t.Fatalf("destination counts %+v %v", got, err)
}
// byte for byte: hashes, mode, mtime of every file; unknown files included; geo skipped
srcT, _ := scanTree(fixture, false, false)
hashTree(fixture, srcT)
dstT, _ := scanTree(dest, true, true)
hashTree(dest, dstT)
if d := sameContent(srcT.entries, dropManifest(dstT.entries)); len(d) > 0 {
t.Fatal(d)
}
if d := sameMeta(srcT.entries, dstT.entries); len(d) > 0 {
t.Fatal(d)
}
for _, must := range []string{"urutau-state.gob", "incidents.json", "enforce.json", "operator-notes.txt", "tor/relays.json", ManifestName} {
if _, err := os.Stat(filepath.Join(dest, must)); err != nil {
t.Errorf("%s missing: %v", must, err)
}
}
if _, err := os.Stat(filepath.Join(dest, "geo")); err == nil {
t.Error("geo/ must be skipped by default")
}
found := false
for _, w := range rep.Warnings {
found = found || strings.Contains(w, "geo/")
}
if !found {
t.Errorf("no geo warning: %v", rep.Warnings)
}
if fi, _ := os.Stat(filepath.Join(dest, "operator-notes.txt")); fi.ModTime().UTC().Year() != 2026 || fi.ModTime().UTC().Month() != 11 || fi.ModTime().UTC().Day() != 1 {
t.Errorf("mtime not preserved: %v", fi.ModTime())
}
if _, err := os.Stat(filepath.Join(dd, lockName)); err == nil {
t.Error("the import lock was left behind")
}
if ents, _ := os.ReadDir(filepath.Join(dd, "probes")); len(ents) != 1 {
t.Errorf("temporary directory left behind: %v", ents)
}
// the real loaders on the copy: the INC-2 comments, the suppression, the evlog lines
is, err := incidents.Open(filepath.Join(dest, "incidents.json"), nil)
if err != nil {
t.Fatal(err)
}
tk, err := is.Get("INC-2")
if err != nil || len(tk.Comments) != 2 {
t.Fatalf("INC-2 %+v %v", tk, err)
}
if tk1, _ := is.Get("INC-1"); !tk1.Suppress {
t.Error("INC-1 lost its suppression")
}
el, err := evlog.Open(evlog.Options{Dir: filepath.Join(dest, "events"), Retention: 30 * 24 * time.Hour})
if err != nil {
t.Fatal(err)
}
n := 0
el.Scan(evlog.Filter{}, 0, false, func(evlog.Rec, []byte) bool { n++; return true })
el.Close()
if n != rep.Events {
t.Errorf("evlog scan sees %d events, count says %d", n, rep.Events)
}
st := store.New(store.Config{Name: "hostinger", MaxIPs: 1 << 20})
if offs, err := st.Load(SnapshotPath(dest)); err != nil || len(offs) != 3 || st.IPCount() != rep.IPs {
t.Errorf("snapshot of the copy: %v %d %v", offs, st.IPCount(), err)
}
// verify passes
if _, err := VerifyImport(fixture, dd, "hostinger"); err != nil {
t.Fatal(err)
}
}
func TestImportIdempotentAndDivergent(t *testing.T) {
dd := t.TempDir()
src := copyDir(t, fixture)
mustImport(t, src, dd, "hostinger", ImportOptions{})
if r := mustImport(t, src, dd, "hostinger", ImportOptions{}); !r.Skipped {
t.Fatalf("second run must be skipped: %+v", r)
}
// a hub that already ran changes the destination: still skipped, with a warning, nothing touched
dest := filepath.Join(dd, "probes", "hostinger")
if err := os.WriteFile(filepath.Join(dest, "incidents.json"), []byte(`{"next":9,"tickets":[]}`), 0o600); err != nil {
t.Fatal(err)
}
r := mustImport(t, src, dd, "hostinger", ImportOptions{})
if !r.Skipped || len(r.Warnings) == 0 {
t.Fatalf("drifted destination: %+v", r)
}
if b, _ := os.ReadFile(filepath.Join(dest, "incidents.json")); !strings.Contains(string(b), `"next":9`) {
t.Fatal("skipped import touched the destination")
}
// the source changes: divergent, refuse without --force
if err := os.WriteFile(filepath.Join(src, "operator-notes.txt"), []byte("changed\n"), 0o640); err != nil {
t.Fatal(err)
}
if _, err := Import(src, dd, "hostinger", ImportOptions{}); err == nil || !strings.Contains(err.Error(), "--force") {
t.Fatalf("divergent without --force must fail: %v", err)
}
if b, _ := os.ReadFile(filepath.Join(dest, "incidents.json")); !strings.Contains(string(b), `"next":9`) {
t.Fatal("a refused import touched the destination")
}
// --force: old destination kept as .bak, new one in place
r = mustImport(t, src, dd, "hostinger", ImportOptions{Force: true})
if r.Backup == "" || !strings.Contains(r.Backup, ".bak-") {
t.Fatalf("backup %+v", r)
}
if b, _ := os.ReadFile(filepath.Join(r.Backup, "incidents.json")); !strings.Contains(string(b), `"next":9`) {
t.Fatal("backup lost the old destination")
}
if _, err := os.Stat(filepath.Join(r.Backup, ManifestName)); err != nil {
t.Fatal("backup lost the old manifest")
}
if b, _ := os.ReadFile(filepath.Join(dest, "operator-notes.txt")); string(b) != "changed\n" {
t.Fatal("new content not installed")
}
// a second --force keeps the first backup too
if err := os.WriteFile(filepath.Join(src, "operator-notes.txt"), []byte("changed again\n"), 0o640); err != nil {
t.Fatal(err)
}
r2 := mustImport(t, src, dd, "hostinger", ImportOptions{Force: true})
if r2.Backup == r.Backup {
t.Fatal("backups collided")
}
if _, err := os.Stat(r.Backup); err != nil {
t.Fatal("first backup was deleted")
}
}
func TestImportDestWithoutManifestIsDivergent(t *testing.T) {
dd := t.TempDir()
dest := filepath.Join(dd, "probes", "hostinger")
os.MkdirAll(dest, 0o700)
os.WriteFile(filepath.Join(dest, "urutau-state.gob"), []byte("something"), 0o600)
if _, err := Import(fixture, dd, "hostinger", ImportOptions{}); err == nil {
t.Fatal("must not import over an existing unknown directory")
}
if b, _ := os.ReadFile(filepath.Join(dest, "urutau-state.gob")); string(b) != "something" {
t.Fatal("destination changed")
}
}
func TestImportDryRunWritesNothing(t *testing.T) {
dd := t.TempDir()
rep := mustImport(t, fixture, dd, "hostinger", ImportOptions{DryRun: true})
if !rep.DryRun || len(rep.Files) == 0 || rep.Events == 0 {
t.Fatalf("report %+v", rep)
}
if ents, _ := os.ReadDir(dd); len(ents) != 0 {
t.Fatalf("dry run wrote %v", ents)
}
// also on top of an existing, divergent destination with --force
mustImport(t, fixture, dd, "hostinger", ImportOptions{})
src := copyDir(t, fixture)
os.WriteFile(filepath.Join(src, "operator-notes.txt"), []byte("x"), 0o640)
before := treeSums(t, dd)
if _, err := Import(src, dd, "hostinger", ImportOptions{DryRun: true, Force: true}); err != nil {
t.Fatal(err)
}
if after := treeSums(t, dd); after != before {
t.Fatal("dry run changed the data dir")
}
}
func treeSums(t *testing.T, root string) string {
tr, err := scanTree(root, true, true)
if err != nil {
t.Fatal(err)
}
if err := hashTree(root, tr); err != nil {
t.Fatal(err)
}
b, _ := json.Marshal(tr.entries)
return string(b)
}
func TestImportRefusesWithLock(t *testing.T) {
dd := t.TempDir()
if err := os.WriteFile(filepath.Join(dd, lockName), []byte("12345\n"), 0o600); err != nil {
t.Fatal(err)
}
for _, o := range []ImportOptions{{}, {DryRun: true}, {Force: true}} {
if _, err := Import(fixture, dd, "hostinger", o); err == nil || !strings.Contains(err.Error(), lockName) {
t.Fatalf("lock must refuse (%+v): %v", o, err)
}
}
if _, err := os.Stat(filepath.Join(dd, "probes")); err == nil {
t.Fatal("wrote something despite the lock")
}
if _, err := os.Stat(filepath.Join(dd, lockName)); err != nil {
t.Fatal("removed a lock that was not ours")
}
}
func TestVerifyDetectsDamage(t *testing.T) {
dd := t.TempDir()
src := copyDir(t, fixture)
if _, err := VerifyImport(src, dd, "hostinger"); err == nil {
t.Fatal("verify before import must fail")
}
old := time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC)
os.Chtimes(filepath.Join(src, "operator-notes.txt"), old, old)
mustImport(t, src, dd, "hostinger", ImportOptions{})
if _, err := VerifyImport(src, dd, "hostinger"); err != nil {
t.Fatal(err)
}
dest := filepath.Join(dd, "probes", "hostinger")
os.WriteFile(filepath.Join(dest, "operator-notes.txt"), []byte("unknown file kept verbatim\n"), 0o640) // same bytes, new mtime
if _, err := VerifyImport(src, dd, "hostinger"); err == nil {
t.Fatal("mtime damage not detected")
}
os.Chtimes(filepath.Join(dest, "operator-notes.txt"), old, old)
if _, err := VerifyImport(src, dd, "hostinger"); err != nil {
t.Fatal(err)
}
b, _ := os.ReadFile(filepath.Join(dest, "urutau-state.gob"))
b[len(b)/2] ^= 0xff
os.WriteFile(filepath.Join(dest, "urutau-state.gob"), b, 0o600)
if _, err := VerifyImport(src, dd, "hostinger"); err == nil || !strings.Contains(err.Error(), "urutau-state.gob") {
t.Fatalf("corruption not detected: %v", err)
}
}
func TestCountDirDoesNotModify(t *testing.T) {
src := copyDir(t, fixture)
before := treeSums(t, src)
if _, err := CountDir(src); err != nil {
t.Fatal(err)
}
if treeSums(t, src) != before {
t.Fatal("counting changed the directory")
}
// a corrupt incidents.json is an error and stays where it is (the real Open would rename it)
os.WriteFile(filepath.Join(src, "incidents.json"), []byte("{broken"), 0o600)
if _, err := CountDir(src); err == nil {
t.Fatal("corrupt incidents.json must be an error")
}
if _, err := os.Stat(filepath.Join(src, "incidents.json")); err != nil {
t.Fatal("corrupt file was moved")
}
}
func TestImportArgs(t *testing.T) {
dd := t.TempDir()
if _, err := Import(fixture, dd, "Bad_Name", ImportOptions{}); err == nil {
t.Fatal("invalid host accepted")
}
if _, err := Import(filepath.Join(dd, "missing"), dd, "hostinger", ImportOptions{}); err == nil {
t.Fatal("missing source accepted")
}
src := filepath.Join(dd, "inside")
os.MkdirAll(src, 0o700)
if _, err := Import(src, dd, "hostinger", ImportOptions{}); err == nil {
t.Fatal("source inside the data dir accepted")
}
if _, err := Import(fixture, fixture, "hostinger", ImportOptions{}); err == nil {
t.Fatal("data dir equal to the source accepted")
}
// a source that is itself an import destination is not a 1.x directory
mustImport(t, fixture, dd, "hostinger", ImportOptions{})
if _, err := Import(filepath.Join(dd, "probes", "hostinger"), t.TempDir(), "other", ImportOptions{}); err == nil {
t.Fatal("manifest in the source must be refused")
}
}
func TestImportGeoOptIn(t *testing.T) {
dd := t.TempDir()
mustImport(t, fixture, dd, "hostinger", ImportOptions{IncludeGeo: true})
if _, err := os.Stat(filepath.Join(dd, "probes", "hostinger", "geo", "GeoLite2-City.mmdb")); err != nil {
t.Fatal(err)
}
if _, err := VerifyImport(fixture, dd, "hostinger"); err != nil {
t.Fatal(err)
}
}
func TestImportEmptyAndSymlink(t *testing.T) {
src := t.TempDir()
os.WriteFile(filepath.Join(src, "extra.bin"), []byte{0, 1, 2}, 0o600)
os.MkdirAll(filepath.Join(src, "sub", "deep"), 0o750)
os.WriteFile(filepath.Join(src, "sub", "deep", "x"), []byte("x"), 0o600)
os.Symlink("extra.bin", filepath.Join(src, "link"))
dd := t.TempDir()
rep := mustImport(t, src, dd, "bare", ImportOptions{})
if rep.Events != 0 || rep.IPs != 0 {
t.Fatalf("%+v", rep.Counts)
}
if tg, err := os.Readlink(filepath.Join(dd, "probes", "bare", "link")); err != nil || tg != "extra.bin" {
t.Fatalf("symlink: %q %v", tg, err)
}
if _, err := VerifyImport(src, dd, "bare"); err != nil {
t.Fatal(err)
}
}
func TestImportCLI(t *testing.T) {
var out, errb bytes.Buffer
if code := ImportCLI([]string{"--count", fixture}, &out, &errb); code != 0 || !strings.Contains(out.String(), "incidents=3") {
t.Fatalf("count: %d %q %q", code, out.String(), errb.String())
}
dd := t.TempDir()
out.Reset()
if code := ImportCLI([]string{"--from", fixture, "--host", "hostinger", "--data-dir", dd, "--dry-run"}, &out, &errb); code != 0 || !strings.Contains(out.String(), "dry run") {
t.Fatalf("dry: %d %q %q", code, out.String(), errb.String())
}
out.Reset()
if code := ImportCLI([]string{"--from", fixture, "--host", "hostinger", "--data-dir", dd}, &out, &errb); code != 0 || !strings.Contains(out.String(), "imported") {
t.Fatalf("import: %d %q %q", code, out.String(), errb.String())
}
out.Reset()
if code := ImportCLI([]string{"--verify", "--from", fixture, "--host", "hostinger", "--data-dir", dd}, &out, &errb); code != 0 || !strings.Contains(out.String(), "verified") {
t.Fatalf("verify: %d %q %q", code, out.String(), errb.String())
}
out.Reset()
if code := ImportCLI([]string{"--from", fixture, "--host", "hostinger", "--data-dir", dd}, &out, &errb); code != 0 || !strings.Contains(out.String(), "already imported") {
t.Fatalf("again: %d %q", code, out.String())
}
if code := ImportCLI([]string{"--host", "x"}, &out, &errb); code != 2 {
t.Fatalf("usage code %d", code)
}
}
+357
View File
@@ -0,0 +1,357 @@
package app
import (
"context"
"encoding/json"
"log/slog"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
"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/rdns"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/server"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
// NodeDir is where the data of a probe lives: the primary probe uses the root
// of the data directory (exactly the 1.x layout), the others probes/<name>.
func NodeDir(dataDir, name string, primary bool) string {
if primary {
return dataDir
}
return filepath.Join(dataDir, "probes", name)
}
// shared holds what every node of the hub uses together.
type shared struct {
c Config
log *slog.Logger
en enricher
rd *rdns.Resolver
ctx context.Context
wg *sync.WaitGroup
mgr func() *hub.Manager
prim *Node
mu sync.Mutex
all []*Node
}
// Node is the store, the runner and the engines of one probe. It implements
// hub.Node and fed.Backend.
type Node struct {
name string
Dir string
Primary bool
St *store.Store
Run *Runner
Elog *evlog.Log
Inc *incidents.Store
Enf *enforce.Engine
Q *hub.CmdQueue
sh *shared
egr atomic.Pointer[egress.Engine]
egrSrc atomic.Pointer[egress.Source]
egrActive atomic.Bool
sources atomic.Pointer[[]string]
}
func (sh *shared) newNode(name string, primary bool, rec hub.Probe) (*Node, error) {
c := sh.c
dir := NodeDir(c.DataDir, name, primary)
if err := os.MkdirAll(dir, 0o700); err != nil {
return nil, err
}
loc, _ := store.ParseLocation(c.Location)
if !primary {
loc = nil
}
st := store.New(store.Config{Name: name, Version: Version, Retention: c.Retention, AdminUsers: c.AdminUserList(), Location: loc})
if rec.Location != nil {
st.SetLocation(&store.Location{Lat: rec.Location.Lat, Lon: rec.Location.Lon, Label: rec.Location.Label})
}
st.SetDomains(splitList(c.Domains))
n := &Node{name: name, Dir: dir, Primary: primary, St: st, sh: sh}
if max, err := ParseSize(orDefault(c.EventsMax, DefaultEventsMax)); err == nil && max > 0 {
el, err := evlog.Open(evlog.Options{Dir: filepath.Join(dir, "events"), MaxBytes: max, Retention: c.Retention, Log: sh.log})
if err != nil {
sh.log.Warn("event registry unavailable, replay disabled", "node", name, "err", err)
} else {
n.Elog = el
st.SetEventLog(el)
sh.wg.Add(1)
go func() { defer sh.wg.Done(); el.Run(sh.ctx) }()
}
}
st.SetRDNS(sh.rd)
offsets := LoadState(st, dir, sh.log)
run, err := NewRemoteRunner(c, st, sh.log, dir)
if err != nil {
return nil, err
}
run.Enr = sh.en
st.SetEnricher(sh.en)
st.SetAttribution(Attribution)
run.StartRemote(sh.ctx, offsets)
n.Run = run
run.EgressFeed = func(l []byte) {
if e := n.egr.Load(); e != nil {
e.Ingest(l)
}
}
if n.Inc, err = incidents.Open(filepath.Join(dir, "incidents.json"), sh.log); err != nil {
return nil, err
}
if n.Q, err = hub.OpenQueue(filepath.Join(dir, "commands.json")); err != nil {
return nil, err
}
n.Enf = newEnforce(c, st, name, dir, n.Q.Enqueue, sh.en, func() bool { return true })
if n.Enf != nil {
sh.wg.Add(1)
go func() { defer sh.wg.Done(); n.Enf.Run(sh.ctx) }()
}
if !egressOff(c) {
if err := n.buildEgress(rec.Egress); err != nil {
return nil, err
}
if strings.EqualFold(c.Egress, "on") {
n.activateEgress()
}
}
run.Extra = func() []store.SourceStatus {
out := []store.SourceStatus{}
if n.Primary {
out = append(out, geoStatus(sh.en.g, c.GeoDir))
}
return out
}
// save every minute, prune every 10
sh.wg.Add(1)
go n.maintain()
sh.mu.Lock()
sh.all = append(sh.all, n)
if primary {
sh.prim = n
}
sh.mu.Unlock()
return n, nil
}
func (n *Node) maintain() {
defer n.sh.wg.Done()
c := n.sh.c
_ = c
save := time.NewTicker(60 * time.Second)
prune := time.NewTicker(10 * time.Minute)
defer save.Stop()
defer prune.Stop()
for {
select {
case <-n.sh.ctx.Done():
n.Close()
return
case <-save.C:
if err := n.Run.Save(); err != nil {
n.sh.log.Warn("snapshot failed", "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)
}
}
}
}
// Close writes the final snapshot and flushes the queue and the tickets.
func (n *Node) Close() {
if err := n.Run.Save(); err != nil {
n.sh.log.Warn("final snapshot failed", "node", n.name, "err", err)
}
if n.Inc != nil {
n.Inc.Flush()
}
if n.Q != nil {
n.Q.Close()
}
}
func (n *Node) buildEgress(eg hub.Egress) error {
eng, err := newEgressEngine(n.sh.c, n.St, eg, n.Primary)
if err != nil {
return err
}
n.egr.Store(eng)
n.egrSrc.Store(egress.NewRemoteSource(eng, n.sh.log))
n.egrSrc.Load().SetState("waiting")
if n.egrActive.Load() && n.Primary {
server.SetEgress(eng)
}
return nil
}
func (n *Node) activateEgress() {
e := n.egr.Load()
if e == nil {
return
}
n.egrActive.Store(true)
if s := n.egrSrc.Load(); s != nil {
s.SetState("following")
}
if n.Primary {
server.SetEgress(e)
}
}
// Egress returns the engine when the node has egress analysis active.
func (n *Node) EgressEngine() *egress.Engine {
if !n.egrActive.Load() {
return nil
}
return n.egr.Load()
}
// ResetEgress rebuilds the engine with a new configuration (its in-memory
// history starts over).
func (n *Node) ResetEgress(eg hub.Egress) {
if egressOff(n.sh.c) {
return
}
if err := n.buildEgress(eg); err != nil {
n.sh.log.Warn("egress configuration rejected", "node", n.name, "err", err)
}
}
// ---- hub.Node ----
func (n *Node) Name() string { return n.name }
func (n *Node) Ready() bool { return true }
func (n *Node) Offsets() map[string]wire.Pos { return n.Run.RemoteOffsets() }
func (n *Node) Apply(b wire.Batch) (int, int) {
acc, dup := n.Run.ApplyBatch(b.Lines)
if acc > 0 {
for _, l := range b.Lines {
if l.Src == wire.SrcEgress {
n.activateEgress()
break
}
}
}
for _, f := range b.Files {
e := n.egr.Load()
if e == nil {
continue
}
switch f.Name {
case wire.FileContainers:
e.SetContainers([]byte(f.Data))
case wire.FileResolv:
e.SetResolv([]byte(f.Data))
}
}
return acc, dup
}
func (n *Node) Hello(h wire.Hello) {
n.sources.Store(&h.Sources)
for _, s := range h.Sources {
if s == wire.SrcEgress {
n.activateEgress()
}
}
}
func (n *Node) Queue() *hub.CmdQueue { return n.Q }
func (n *Node) SetStatus(st wire.Status, connected bool) { n.Run.SetRemoteStatus(st, connected) }
func (n *Node) SetLocation(l *wire.Location) {
if l == nil {
n.St.SetLocation(nil)
return
}
n.St.SetLocation(&store.Location{Lat: l.Lat, Lon: l.Lon, Label: l.Label})
}
// ---- fed.Backend ----
func (n *Node) connected() bool {
if m := n.sh.mgr(); m != nil {
return m.Connected(n.name)
}
return false
}
func (n *Node) Online() bool { return n.connected() }
func (n *Node) Location() *store.Location { return n.St.Location() }
func (n *Node) Export(rg store.Range) store.PeerExport { return n.St.ExportFor(rg) }
func (n *Node) Study(q store.PeriodQuery) store.PeerStudy { return n.St.StudyFor(q) }
func (n *Node) EgressReport(from, to int64) (egress.Report, bool) {
e := n.EgressEngine()
if e == nil {
return egress.Report{}, false
}
return e.Report(from, to), true
}
func (n *Node) Egress(from, to int64) json.RawMessage {
rep, ok := n.EgressReport(from, to)
if !ok {
return nil
}
b, _ := json.Marshal(rep)
return b
}
func (n *Node) Subscribe() (<-chan store.LiveEvent, func()) {
in, stop := n.St.Subscribe()
out := make(chan store.LiveEvent, 64)
done := make(chan struct{})
go func() {
for {
select {
case <-done:
return
case fe := <-in:
le := n.St.Live(fe)
select {
case out <- le:
default:
}
}
}
}()
return out, func() { close(done); stop() }
}
func (n *Node) SubscribeVisits() (<-chan store.VisitMsg, func()) { return n.St.SubscribeVisits() }
// HostInfo feeds fed.Hub.Hosts with the connection state of the probe.
func (n *Node) HostInfo() store.HostInfo {
hi := store.HostInfo{Name: n.name, Online: n.connected(), Live: n.connected(), Location: n.St.Location()}
if m := n.sh.mgr(); m != nil {
if in, ok := m.Info(n.name); ok {
hi.Version, hi.LastSeen, hi.LatencyMS = in.Version, in.LastSeen, in.LagMS
if !in.Connected && in.LastSeen > 0 {
hi.Error = "probe offline"
}
}
}
return hi
}
+166 -121
View File
@@ -17,65 +17,107 @@ import (
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
"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/rdns"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/server"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
// Serve runs the daemon until SIGTERM/SIGINT; it returns nil on a clean stop.
func Serve(c Config) error {
log := slog.New(slog.NewTextHandler(os.Stderr, nil))
token, terr := Secret("URUTAU_TOKEN")
if terr != nil {
return terr
// acquireLock creates <data-dir>/.lock exclusively: its presence means "hub
// running" and makes `urutau import` refuse. It is removed on a normal stop.
func acquireLock(dir string) (release func(), err error) {
if err := os.MkdirAll(dir, 0o700); err != nil {
return nil, err
}
peers, err := c.Validate(token)
path := filepath.Join(dir, lockName)
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
if err != nil {
return err
if errors.Is(err, os.ErrExist) {
pid, _ := os.ReadFile(path)
return nil, fmt.Errorf("%s exists (pid %s): another hub uses this data directory; if none is running, remove the file", path, strings.TrimSpace(string(pid)))
}
return nil, err
}
if os.Getenv("GOMEMLIMIT") == "" {
debug.SetMemoryLimit(SoftMemoryLimit)
}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
defer stop()
fmt.Fprintf(f, "%d\n", os.Getpid())
f.Close()
return func() { os.Remove(path) }, nil
}
loc, _ := store.ParseLocation(c.Location) // validated above
st := store.New(store.Config{Name: c.Name, Version: Version, Retention: c.Retention, AdminUsers: c.AdminUserList(), Location: loc})
st.SetDomains(splitList(c.Domains))
// nodeSet implements server.NodeSet over the manager.
type nodeSet struct{ m *hub.Manager }
func (n nodeSet) node(host string) *Node {
nd, _ := n.m.Get(host).(*Node)
return nd
}
func (n nodeSet) Hosts() []string {
var out []string
for _, x := range n.m.Nodes() {
out = append(out, x.Name())
}
return out
}
func (n nodeSet) Enforce(h string) *enforce.Engine {
if nd := n.node(h); nd != nil {
return nd.Enf
}
return nil
}
func (n nodeSet) Egress(h string) *egress.Engine {
if nd := n.node(h); nd != nil {
return nd.EgressEngine()
}
return nil
}
func (n nodeSet) Incidents(h string) *incidents.Store {
if nd := n.node(h); nd != nil {
return nd.Inc
}
return nil
}
// Hub is a running hub without its listener: Serve and the tests build one.
type Hub struct {
Handler http.Handler
Mgr *hub.Manager
Primary *Node
Fed *fed.Hub
wg *sync.WaitGroup
}
// Wait blocks until every background goroutine stopped (cancel the context
// first); the nodes then have saved their snapshots.
func (h *Hub) Wait() {
h.wg.Wait()
h.Mgr.Close()
}
// NewHub validates c and starts the nodes and the background work until ctx is done.
func NewHub(ctx context.Context, c Config, token string, log *slog.Logger) (*Hub, error) {
if err := c.Validate(token); err != nil {
return nil, err
}
wg := &sync.WaitGroup{}
watchTorExits(ctx, c.TorExits, 24*time.Hour, log)
if !strings.EqualFold(c.TorAuto, "off") {
watchTorLists(ctx, filepath.Join(c.DataDir, "tor"), torExitURL, torRelayURL, 6*time.Hour, log)
}
var elog *evlog.Log
if max, err := ParseSize(orDefault(c.EventsMax, DefaultEventsMax)); err == nil && max > 0 {
if elog, err = evlog.Open(evlog.Options{Dir: filepath.Join(c.DataDir, "events"), MaxBytes: max, Retention: c.Retention, Log: log}); err != nil {
log.Warn("event registry unavailable, replay disabled", "err", err)
elog = nil
} else {
st.SetEventLog(elog)
}
}
rd := rdns.New()
st.SetRDNS(rd)
offsets := LoadState(st, c.DataDir, log)
runner, err := NewRunner(c, st, log)
if err != nil {
return err
}
gr, gerr := geo.Open(c.GeoDir)
if gerr != nil {
log.Warn("geo databases unavailable, locations disabled until they are downloaded", "dir", c.GeoDir, "err", gerr)
gr = nil
}
en := enricher{g: gr}
runner.Enr = en
st.SetEnricher(en)
st.SetAttribution(Attribution)
runner.Extra = func() []store.SourceStatus { return []store.SourceStatus{geoStatus(gr, c.GeoDir)} }
// Real build dates of the geo databases for /api/v1/integrity (0 = unknown).
store.GeoBuilds = func() (int64, int64) {
if gr == nil {
@@ -91,102 +133,109 @@ func Serve(c Config) error {
}
return city, asn
}
var hub *fed.Hub
if len(peers) > 0 {
hub = fed.NewHub(peers, c.PeerToken)
hub.OnLive = st.RecordPeerEvent
var mgr *hub.Manager
sh := &shared{c: c, log: log, en: en, rd: rd, ctx: ctx, wg: wg, mgr: func() *hub.Manager { return mgr }}
mgr, err := hub.NewManager(c.DataDir, c.Name, Version, func(name string, primary bool, rec hub.Probe) (hub.Node, error) {
return sh.newNode(name, primary, rec)
}, log)
if err != nil {
return nil, err
}
allow, _ := core.ParseCIDRs(c.PeerAllow)
if err := mgr.Load(); err != nil {
return nil, err
}
prim, _ := mgr.Get(c.Name).(*Node)
if prim == nil {
return nil, fmt.Errorf("primary node %q was not created", c.Name)
}
if prim.Enf != nil {
server.SetEnforce(prim.Enf)
}
fh := fed.NewHub(func() []fed.Backend {
var out []fed.Backend
for _, n := range mgr.Nodes() {
if nd, ok := n.(*Node); ok && !nd.Primary {
out = append(out, nd)
}
}
return out
})
tproxy, _ := core.ParseCIDRs(c.TrustedProxy)
ign, _ := core.ParseCIDRs(c.Ignore + "," + c.Trusted)
bindHost, _, _ := net.SplitHostPort(c.Bind)
incStore, err := incidents.Open(filepath.Join(c.DataDir, "incidents.json"), log)
if err != nil {
return err
}
h := server.New(server.Options{Token: token, PeerTokens: c.PeerTokens, PeerAllow: allow, TrustedProxy: tproxy, Ignore: ign,
AllowHosts: []string{bindHost}, NoAuth: c.NoAuth, LocalBlocklist: strings.EqualFold(c.PeerBlocklist, "off"), Version: Version, Store: st, Hub: hub,
Incidents: incStore})
egressSrc, err := newEgress(c, st, log)
if err != nil {
return err
}
if egressSrc != nil {
extra := runner.Extra
runner.Extra = func() []store.SourceStatus { return append(extra(), egressSrc.Status()) }
}
eng := newEnforce(c, st, peers, en, func() bool {
for _, s := range runner.Sources {
if s.backfilling.Load() {
return false
}
}
return true
})
if eng != nil {
server.SetEnforce(eng)
}
ln, err := net.Listen("tcp", c.Bind)
if err != nil {
return err
}
srv := server.HTTPServer(h, ctx)
var wg sync.WaitGroup
if elog != nil {
wg.Add(1)
go func() { defer wg.Done(); elog.Run(ctx) }()
}
runner.Start(ctx, offsets, &wg)
server.StartIncidentSync(ctx, &wg)
if egressSrc != nil {
egressSrc.Start(ctx, &wg)
}
h := server.New(server.Options{Token: token, TrustedProxy: tproxy, Ignore: ign,
AllowHosts: []string{bindHost}, NoAuth: c.NoAuth, LocalBlocklist: strings.EqualFold(c.PeerBlocklist, "off"), Version: Version, Store: prim.St, Hub: fh,
Incidents: prim.Inc, Probes: mgr, Nodes: nodeSet{mgr}})
server.StartIncidentSync(ctx, wg)
wg.Add(2)
go func() { defer wg.Done(); rd.Run(ctx) }()
go func() {
defer wg.Done()
save := time.NewTicker(60 * time.Second)
prune := time.NewTicker(10 * time.Minute)
defer save.Stop()
defer prune.Stop()
for {
select {
case <-ctx.Done():
return
case <-save.C:
if err := runner.Save(); err != nil {
log.Warn("snapshot failed", "err", err)
}
case <-prune.C:
if n := st.Prune(); n > 0 {
log.Info("pruned old IPs", "n", n)
}
}
}
}()
go func() { defer wg.Done(); fh.Run(ctx) }()
if gr != nil && c.GeoUpdate > 0 {
gr.StartUpdater(ctx, c.GeoUpdate, &http.Client{Timeout: 10 * time.Minute})
}
if hub != nil {
if strings.EqualFold(c.EnforceShare, "on") {
wg.Add(1)
go func() { defer wg.Done(); hub.Run(ctx) }()
go func() {
defer wg.Done()
shareDecisions(ctx, func() []*Node {
var out []*Node
for _, n := range mgr.Nodes() {
if nd, ok := n.(*Node); ok {
out = append(out, nd)
}
}
return out
})
}()
}
if eng != nil {
wg.Add(1)
go func() { defer wg.Done(); eng.Run(ctx) }()
if hub != nil && eng.Share() {
wg.Add(1)
go func() { defer wg.Done(); shareDecisions(ctx, hub, eng, log) }()
}
return &Hub{Handler: h, Mgr: mgr, Primary: prim, Fed: fh, wg: wg}, nil
}
// Serve runs the daemon until SIGTERM/SIGINT; it returns nil on a clean stop.
func Serve(c Config) error {
log := slog.New(slog.NewTextHandler(os.Stderr, nil))
warn, err := CheckRemovedEnv(os.LookupEnv)
if err != nil {
return err
}
log.Info("urutau started", "version", Version, "name", c.Name, "bind", ln.Addr().String(), "peers", len(peers), "auth", !c.NoAuth)
for _, k := range warn {
log.Warn("variable of the 1.x image ignored: the log paths belong to the probe now", "var", k)
}
token, terr := Secret("URUTAU_TOKEN")
if terr != nil {
return terr
}
if err := c.Validate(token); err != nil {
return err
}
if os.Getenv("GOMEMLIMIT") == "" {
debug.SetMemoryLimit(SoftMemoryLimit)
}
release, err := acquireLock(c.DataDir)
if err != nil {
return err
}
defer release()
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
defer stop()
hb, err := NewHub(ctx, c, token, log)
if err != nil {
return err
}
ln, err := net.Listen("tcp", c.Bind)
if err != nil {
stop()
hb.Wait()
return err
}
srv := server.HTTPServer(hb.Handler, ctx)
log.Info("urutau started", "version", Version, "name", c.Name, "bind", ln.Addr().String(), "probes", len(hb.Mgr.Nodes()), "auth", !c.NoAuth)
errc := make(chan error, 1)
go func() { errc <- srv.Serve(ln) }()
select {
case err := <-errc:
stop()
wg.Wait()
hb.Wait()
return err
case <-ctx.Done():
}
@@ -194,12 +243,8 @@ func Serve(c Config) error {
sctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = srv.Shutdown(sctx)
wg.Wait()
if err := runner.Save(); err != nil {
log.Warn("final snapshot failed", "err", err)
} else {
log.Info("snapshot saved")
}
hb.Wait() // every node saves its snapshot and flushes its tickets
log.Info("snapshot saved")
if err := <-errc; err != nil && !errors.Is(err, http.ErrServerClosed) {
return fmt.Errorf("server: %w", err)
}
+162 -3
View File
@@ -14,6 +14,7 @@ import (
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/tail"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
const maxLine = 64 * 1024
@@ -112,8 +113,16 @@ type Runner struct {
Sources []*source
DataDir string
Log *slog.Logger
// EgressFeed receives the "egress" lines of a probe (nil: they are only counted).
EgressFeed func(line []byte)
mu sync.Mutex // commit mutex: held while a line is applied and by snapshots
remote map[string]store.Offset // hub-committed offsets of the sources fed by a probe
isRemote bool
rstatus atomic.Pointer[wire.Status]
connected atomic.Bool
egLines atomic.Uint64
}
// NewRunner builds the runner for the enabled sources.
@@ -143,10 +152,157 @@ func NewRunner(c Config, st *store.Store, log *slog.Logger) (*Runner, error) {
return r, nil
}
func (r *Runner) statuses() []store.SourceStatus {
out := make([]store.SourceStatus, 0, len(r.Sources))
// NewRemoteRunner builds the runner of a node whose sources are fed by a probe
// through Feed: the four parsed sources exist, none follows a file.
func NewRemoteRunner(c Config, st *store.Store, log *slog.Logger, dataDir string) (*Runner, error) {
c.TraefikLog, c.AuthLog, c.Fail2banLog, c.ProbeLog = "", "", "", ""
r, err := NewRunner(c, st, log)
if err != nil {
return nil, err
}
r.DataDir, r.isRemote, r.remote = dataDir, true, map[string]store.Offset{}
for _, name := range []string{"traefik", "ssh", "fail2ban", "probe"} {
parse := map[string]func([]byte) (core.Event, error){"traefik": traefikParse, "ssh": authParse, "fail2ban": f2bParse, "probe": newProbeParser().parse}[name]
r.Sources = append(r.Sources, &source{name: name, parse: parse})
}
return r, nil
}
// runnerSource maps a wire source name to the runner's (and snapshot's) name.
func runnerSource(src string) string {
if src == wire.SrcAuth {
return "ssh"
}
return src
}
// wireSource is the inverse of runnerSource.
func wireSource(name string) string {
if name == "ssh" {
return wire.SrcAuth
}
return name
}
func (r *Runner) find(name string) *source {
for _, s := range r.Sources {
out = append(out, s.status())
if s.name == name {
return s
}
}
return nil
}
// StartRemote sets the committed offsets of a probe-fed runner (from the
// snapshot); there are no followers to start.
func (r *Runner) StartRemote(ctx context.Context, offsets map[string]store.Offset) {
r.mu.Lock()
defer r.mu.Unlock()
for k, v := range offsets {
r.remote[k] = v
}
}
// RemoteOffsets returns the committed positions keyed by wire source name.
func (r *Runner) RemoteOffsets() map[string]wire.Pos {
r.mu.Lock()
defer r.mu.Unlock()
out := map[string]wire.Pos{}
for k, v := range r.remote {
out[wireSource(k)] = wire.Pos{Inode: v.Inode, Offset: v.Offset, FP: v.FP, FPLen: v.FPLen}
}
return out
}
// Feed applies one line of a probe (src is a wire source name): it is dropped
// when its end position is not past the committed one in the same file, else
// handled and committed. It reports whether the line was new.
func (r *Runner) Feed(src string, text []byte, end store.Offset) bool {
r.mu.Lock()
defer r.mu.Unlock()
return r.feedLocked(src, text, end)
}
func (r *Runner) feedLocked(src string, text []byte, end store.Offset) bool {
name := runnerSource(src)
if saved, ok := r.remote[name]; ok && end.Inode == saved.Inode && end.Offset <= saved.Offset {
return false
}
if src == wire.SrcEgress {
r.egLines.Add(1)
if r.EgressFeed != nil {
func() {
defer func() { recover() }() // one hostile line must never take the node down
r.EgressFeed(text)
}()
}
} else if s := r.find(name); s != nil {
r.handle(s)(text)
}
r.remote[name] = end
return true
}
// ApplyBatch applies the lines of a batch under the commit mutex.
func (r *Runner) ApplyBatch(lines []wire.Line) (accepted, dup int) {
r.mu.Lock()
defer r.mu.Unlock()
for _, l := range lines {
if r.feedLocked(l.Src, []byte(l.Text), store.Offset{Inode: l.End.Inode, Offset: l.End.Offset, FP: l.End.FP, FPLen: l.End.FPLen}) {
accepted++
} else {
dup++
}
}
return accepted, dup
}
// SetRemoteStatus stores the last status reported by the probe.
func (r *Runner) SetRemoteStatus(st wire.Status, connected bool) {
r.rstatus.Store(&st)
r.connected.Store(connected)
}
func (r *Runner) remoteStatuses() []store.SourceStatus {
ws := r.rstatus.Load()
var out []store.SourceStatus
seen := map[string]bool{}
if ws != nil {
for _, w := range ws.Sources {
name := runnerSource(w.Src)
seen[name] = true
row := store.SourceStatus{Name: name, State: w.State, Error: w.Error, Lines: w.Lines, Malformed: w.Oversize, LastEvent: w.LastLine}
if s := r.find(name); s != nil {
row.Lines, row.Malformed = max(row.Lines, s.lines.Load()), max(w.Oversize, s.malformed.Load())
if row.LastEvent == 0 {
row.LastEvent = s.lastEvent.Load()
}
if row.State == "following" && s.win.degraded() {
row.State, row.Error = "degraded", degradedMsg
}
}
out = append(out, row)
}
}
for _, s := range r.Sources { // sources the probe has not reported
if !seen[s.name] {
if ws == nil {
out = append(out, store.SourceStatus{Name: s.name, State: "waiting", Lines: s.lines.Load(), Malformed: s.malformed.Load(), LastEvent: s.lastEvent.Load()})
}
}
}
return out
}
func (r *Runner) statuses() []store.SourceStatus {
var out []store.SourceStatus
if r.isRemote {
out = r.remoteStatuses()
} else {
out = make([]store.SourceStatus, 0, len(r.Sources))
for _, s := range r.Sources {
out = append(out, s.status())
}
}
if r.Extra != nil {
out = append(out, r.Extra()...)
@@ -297,6 +453,9 @@ func (r *Runner) Save() error {
r.mu.Lock()
defer r.mu.Unlock()
offs := map[string]store.Offset{}
for k, v := range r.remote {
offs[k] = v
}
for _, s := range r.Sources {
if f := s.fol.Load(); f != nil {
p := f.Pos()
+11
View File
@@ -0,0 +1,11 @@
{
"events": 17,
"event_files": 3,
"ips": 4,
"offsets": 3,
"incidents": 3,
"comments": 2,
"suppressed": 1,
"enforce_bans": 2,
"enforce_allow": 0
}
+1
View File
@@ -0,0 +1 @@
{"v":1,"bans":{"203.0.114.7":{"until":1794794051,"offences":1,"last":1794790451},"203.0.114.8":{"until":1794794051,"offences":1,"last":1794790451}}}
@@ -0,0 +1,2 @@
{"t":1794466451,"ip":"192.0.2.99","cat":"scanner","source":"traefik","host":"hostinger","domain":"a.example","method":"GET","path":"/wp-login.php","status":404,"ua":"fixture","id":16,"fam":"wordpress","tech":["T1110.001","T1595"],"marker":"/wp-login.php"}
{"t":1794466452,"ip":"192.0.2.99","cat":"scanner","source":"traefik","host":"hostinger","domain":"a.example","method":"GET","path":"/wp-login.php","status":404,"ua":"fixture","id":17,"fam":"wordpress","tech":["T1110.001","T1595"],"marker":"/wp-login.php"}
@@ -0,0 +1,5 @@
{"t":1794610451,"ip":"198.51.101.20","cat":"ssh-fail","source":"ssh","host":"hostinger","domain":"a.example","method":"GET","user":"root","ua":"fixture","id":11,"tech":["T1110.001"]}
{"t":1794610452,"ip":"198.51.101.20","cat":"ssh-fail","source":"ssh","host":"hostinger","domain":"a.example","method":"GET","user":"root","ua":"fixture","id":12,"tech":["T1110.001"]}
{"t":1794610453,"ip":"198.51.101.20","cat":"ssh-fail","source":"ssh","host":"hostinger","domain":"a.example","method":"GET","user":"root","ua":"fixture","id":13,"tech":["T1110.001"]}
{"t":1794610454,"ip":"198.51.101.20","cat":"ssh-fail","source":"ssh","host":"hostinger","domain":"a.example","method":"GET","user":"root","ua":"fixture","id":14,"tech":["T1110.001"]}
{"t":1794610455,"ip":"198.51.101.20","cat":"ssh-fail","source":"ssh","host":"hostinger","domain":"a.example","method":"GET","user":"root","ua":"fixture","id":15,"tech":["T1110.001"]}
@@ -0,0 +1,10 @@
{"t":1794779651,"ip":"203.0.114.7","cat":"scanner","source":"traefik","host":"hostinger","domain":"a.example","method":"GET","path":"/.env","status":404,"ua":"fixture","id":1,"fam":"env-credentials","tech":["T1552.001","T1595"],"marker":"/.env"}
{"t":1794779652,"ip":"203.0.114.7","cat":"scanner","source":"traefik","host":"hostinger","domain":"a.example","method":"GET","path":"/.env","status":404,"ua":"fixture","id":2,"fam":"env-credentials","tech":["T1552.001","T1595"],"marker":"/.env"}
{"t":1794779653,"ip":"203.0.114.7","cat":"scanner","source":"traefik","host":"hostinger","domain":"a.example","method":"GET","path":"/.env","status":404,"ua":"fixture","id":3,"fam":"env-credentials","tech":["T1552.001","T1595"],"marker":"/.env"}
{"t":1794779654,"ip":"203.0.114.7","cat":"scanner","source":"traefik","host":"hostinger","domain":"a.example","method":"GET","path":"/.env","status":404,"ua":"fixture","id":4,"fam":"env-credentials","tech":["T1552.001","T1595"],"marker":"/.env"}
{"t":1794779655,"ip":"203.0.114.7","cat":"scanner","source":"traefik","host":"hostinger","domain":"a.example","method":"GET","path":"/.env","status":404,"ua":"fixture","id":5,"fam":"env-credentials","tech":["T1552.001","T1595"],"marker":"/.env"}
{"t":1794779656,"ip":"203.0.114.7","cat":"scanner","source":"traefik","host":"hostinger","domain":"a.example","method":"GET","path":"/.env","status":404,"ua":"fixture","id":6,"fam":"env-credentials","tech":["T1552.001","T1595"],"marker":"/.env"}
{"t":1794783251,"ip":"203.0.114.8","cat":"exploit","source":"traefik","host":"hostinger","domain":"a.example","method":"GET","path":"/cgi-bin/../../etc/passwd","status":400,"ua":"fixture","id":7,"fam":"traversal","tech":["T1083","T1190"],"marker":"../"}
{"t":1794783252,"ip":"203.0.114.8","cat":"exploit","source":"traefik","host":"hostinger","domain":"a.example","method":"GET","path":"/cgi-bin/../../etc/passwd","status":400,"ua":"fixture","id":8,"fam":"traversal","tech":["T1083","T1190"],"marker":"../"}
{"t":1794783253,"ip":"203.0.114.8","cat":"exploit","source":"traefik","host":"hostinger","domain":"a.example","method":"GET","path":"/cgi-bin/../../etc/passwd","status":400,"ua":"fixture","id":9,"fam":"traversal","tech":["T1083","T1190"],"marker":"../"}
{"t":1794783254,"ip":"203.0.114.8","cat":"exploit","source":"traefik","host":"hostinger","domain":"a.example","method":"GET","path":"/cgi-bin/../../etc/passwd","status":400,"ua":"fixture","id":10,"fam":"traversal","tech":["T1083","T1190"],"marker":"../"}
@@ -0,0 +1 @@
not a real database
+1
View File
@@ -0,0 +1 @@
{"next":4,"tickets":[{"id":"INC-1","key":"7d824cc0ddaef8d29ea98a1aa71a3c644a7af995db3500cb7b0e2fbbb1f342d4","source":"egress","host":"hostinger","kind":"new-destination","severity":"medium","max_severity":"medium","workload":"app-a","dst":"198.51.100.5","dport":443,"proto":"tcp","title":"new-destination app-a -\u003e 198.51.100.5:443/tcp","detail":"first contact","first_seen":1794617651,"last_seen":1794786851,"count":12,"status":"false_positive","verdict":"","assignee":"","tags":[],"suppress":true,"created_at":1794790451,"updated_at":1794790451,"suppressed_sev":"medium","suppressed_at":1794790451,"suppress_until":1797382451,"severity_manual":false,"comments":[],"history":[{"at":1794790451,"author":"urutau","field":"created","from":"","to":"medium"},{"at":1794790451,"author":"lucas","field":"status","from":"open","to":"false_positive"},{"at":1794790451,"author":"lucas","field":"suppress","from":"false","to":"true"}]},{"id":"INC-2","key":"77f910eb3c3c828f18e7683a1828419903f282d7a8a6584f4a48092c6b49190e","source":"egress","host":"hostinger","kind":"exfil","severity":"high","max_severity":"high","workload":"app-b","dst":"203.0.113.50","dport":4444,"proto":"tcp","title":"exfil app-b -\u003e 203.0.113.50:4444/tcp","detail":"large upload","first_seen":1794704051,"last_seen":1794786851,"count":40,"status":"open","verdict":"","assignee":"","tags":[],"suppress":false,"created_at":1794790451,"updated_at":1794790451,"suppressed_sev":"","suppressed_at":0,"suppress_until":0,"severity_manual":false,"comments":[{"id":1,"at":1794790451,"author":"lucas","text":"Looks like the nightly backup."},{"id":2,"at":1794790451,"author":"lucas","text":"Confirmed with the app owner; keep watching."}],"history":[{"at":1794790451,"author":"urutau","field":"created","from":"","to":"high"}]},{"id":"INC-3","key":"manual|3","source":"manual","host":"hostinger","kind":"manual","severity":"low","max_severity":"low","workload":"","dst":"","dport":0,"proto":"","title":"Manual review of the proxy","detail":"opened by the operator","first_seen":1794790451,"last_seen":1794790451,"count":1,"status":"open","verdict":"","assignee":"","tags":[],"suppress":false,"created_at":1794790451,"updated_at":1794790451,"suppressed_sev":"","suppressed_at":0,"suppress_until":0,"severity_manual":false,"comments":[],"history":[{"at":1794790451,"author":"lucas","field":"created","from":"","to":"low"}]}]}
@@ -0,0 +1 @@
unknown file kept verbatim
@@ -0,0 +1,2 @@
198.51.100.200
198.51.100.201
+1
View File
@@ -0,0 +1 @@
{"relays":[]}
Binary file not shown.
+1 -1
View File
@@ -97,7 +97,7 @@ func TestEgressOwnAllowAndProvider(t *testing.T) {
}
// the peer has no URUTAU_PEERS: URUTAU_TRUSTED carries both servers, and a
// bad item does not discard the others
al := egressAllow(Config{Trusted: "136.248.78.83,lixo,195.200.0.252/32"})
al := egressAllow(Config{Trusted: "136.248.78.83,lixo,195.200.0.252/32"}, "")
for _, ipS := range []string{"136.248.78.83", "195.200.0.252"} {
ok := false
for _, p := range al {
+3 -3
View File
@@ -21,15 +21,15 @@ func TestRetentionEventsMaxFlags(t *testing.T) {
}
tok := "tok-0123456789-abcdefghijklmnopqrstuvwxyz-QWERTY"
base := Config{Bind: "0.0.0.0:1", Ignore: DefaultIgnore, TrustedProxy: DefaultTrustedProxy, Retention: 720 * time.Hour}
if _, err := base.Validate(tok); err != nil {
if err := base.Validate(tok); err != nil {
t.Fatal(err)
}
base.Retention = 721 * time.Hour
if _, err := base.Validate(tok); err == nil {
if err := base.Validate(tok); err == nil {
t.Fatal("retention over 720h must be refused")
}
base.Retention, base.EventsMax = 720*time.Hour, "lots"
if _, err := base.Validate(tok); err == nil {
if err := base.Validate(tok); err == nil {
t.Fatal("bad --events-max must be refused")
}
for in, want := range map[string]int64{"512MB": 512 << 20, "0": 0, "2g": 2 << 30, "1048576": 1 << 20, "1.5kb": 1536} {
+2 -51
View File
@@ -8,7 +8,6 @@ import (
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
@@ -199,7 +198,7 @@ func TestIPDetailConsistentOnSyntheticLogs(t *testing.T) {
func TestEnforceConfig(t *testing.T) {
c, err := ParseFlags("x", []string{"--insecure-no-auth", "--bind", "127.0.0.1:1"})
if err != nil || c.Enforce != "off" || c.EnforceLog != "/logs/enforce/decisions.log" || c.EnforceShare != "off" || c.EnforceThreshold != 5 || c.EnforceMaxPerMin != 60 {
if err != nil || c.Enforce != "off" || c.EnforceShare != "off" || c.EnforceThreshold != 5 || c.EnforceMaxPerMin != 60 {
t.Fatalf("%+v %v", c, err)
}
for _, bad := range [][]string{{"--enforce=maybe"}, {"--enforce-share=x"}, {"--enforce-threshold=0"}, {"--enforce-max-per-min=0"}} {
@@ -207,7 +206,7 @@ func TestEnforceConfig(t *testing.T) {
if err != nil {
continue
}
if _, err := c.Validate(""); err == nil {
if err := c.Validate(""); err == nil {
t.Errorf("%v accepted", bad)
}
}
@@ -219,45 +218,6 @@ func TestEnforceConfig(t *testing.T) {
}
}
func TestDoctorEnforce(t *testing.T) {
var got []Check
add := func(n, s, d string) { got = append(got, Check{n, s, d}) }
doctorEnforce(Config{Enforce: "on", EnforceLog: t.TempDir() + "/x/d.log", EnforceThreshold: 5}, add)
doctorEnforce(Config{Enforce: "on", EnforceLog: "/proc/nope/d.log"}, add)
doctorEnforce(Config{Enforce: "off"}, add)
if got[0].Status != "ok" || !strings.Contains(got[0].Detail, "mode=on") || got[1].Status != "fail" || got[2].Status != "off" {
t.Fatalf("%+v", got)
}
}
func TestDoctorEnforceCloudflare(t *testing.T) {
lg := filepath.Join(t.TempDir(), "access.log")
os.WriteFile(lg, []byte(`{"ClientHost":"104.16.1.1"}`+"\n"+`{"ClientHost":"203.0.114.5"}`+"\n"), 0o600)
var got []Check
add := func(n, s, d string) { got = append(got, Check{n, s, d}) }
doctorEnforce(Config{Enforce: "on", EnforceLog: t.TempDir() + "/x/d.log", TraefikLog: lg}, add)
if len(got) != 2 || got[1].Name != "enforce-cdn" || got[1].Status != "warn" {
t.Fatalf("%+v", got)
}
got = nil
doctorEnforce(Config{Enforce: "observe", EnforceLog: t.TempDir() + "/x/d.log", TraefikLog: lg}, add)
if len(got) != 1 {
t.Fatalf("%+v", got)
}
}
func TestEgressExtraAllow(t *testing.T) {
t.Setenv("URUTAU_EGRESS_ALLOW", "203.0.113.0/24, 198.51.100.7 ,bad")
got := egressExtraAllow(Config{Peers: []string{"p=https://192.0.2.9:8443"}})
var s []string
for _, p := range got {
s = append(s, p.String())
}
if strings.Join(s, " ") != "192.0.2.9/32 203.0.113.0/24 198.51.100.7/32" {
t.Fatalf("%v", s)
}
}
func TestSourceDegradedWindow(t *testing.T) {
var w window
for i := 0; i < 100; i++ {
@@ -279,12 +239,3 @@ func TestSourceDegradedWindow(t *testing.T) {
t.Fatal("window must recover")
}
}
func TestUnbanLogPathDefault(t *testing.T) {
if got := unbanLogPath(Config{EnforceLog: "/logs/enforce/decisions.log"}); got != "/logs/enforce/unban.log" {
t.Fatalf("default unban log = %q", got)
}
if got := unbanLogPath(Config{EnforceLog: "/a/d.log", EnforceUnbanLog: "/b/u.log"}); got != "/b/u.log" {
t.Fatalf("explicit unban log = %q", got)
}
}
+1 -1
View File
@@ -2,4 +2,4 @@ package app
// Version is the release version (SemVer). Release builds may override it with
// -ldflags "-X .../internal/app.Version=...".
var Version = "1.6.0"
var Version = "2.0.0"
+3 -3
View File
@@ -90,7 +90,7 @@ func TestParse(t *testing.T) {
func TestWorkloadsAndContainers(t *testing.T) {
e := newEng(t, Config{Workloads: "ciberlab=name:jhxint9g9uz91:scanner;mail=10.0.7.0/24,10.0.8.4/32:mail;lab=10.0.5.0/24"})
e.SetContainers(map[netip.Addr]string{ip("172.18.0.4"): "jhxint9g9uz91-20260101123456", ip("172.18.0.9"): "runner-q620o15zg7-1700000000000"})
e.SetContainerMap(map[netip.Addr]string{ip("172.18.0.4"): "jhxint9g9uz91-20260101123456", ip("172.18.0.9"): "runner-q620o15zg7-1700000000000"})
cases := []struct {
ev Event
name, role string
@@ -108,7 +108,7 @@ func TestWorkloadsAndContainers(t *testing.T) {
}
}
// IP changes: the map in force at Ingest wins
e.SetContainers(map[netip.Addr]string{ip("172.18.0.5"): "jhxint9g9uz91-20260102000000"})
e.SetContainerMap(map[netip.Addr]string{ip("172.18.0.5"): "jhxint9g9uz91-20260102000000"})
if n, _ := e.resolve(mk(t0, "172.18.0.5", "1.1.1.1", "tcp", 1)); n != "ciberlab" {
t.Errorf("remap: %s", n)
}
@@ -460,7 +460,7 @@ func TestReportByCountry(t *testing.T) {
func TestNameMatchExactAndPrefix(t *testing.T) {
e := newEng(t, Config{Workloads: "a=name:web:default;b=name:api*:default;c=name:pay:default"})
e.SetContainers(map[netip.Addr]string{ip("172.18.0.1"): "web-1700000000000", ip("172.18.0.2"): "webshell-1700000000000",
e.SetContainerMap(map[netip.Addr]string{ip("172.18.0.1"): "web-1700000000000", ip("172.18.0.2"): "webshell-1700000000000",
ip("172.18.0.3"): "apigw-17", ip("172.18.0.4"): "pay", ip("172.18.0.5"): "payroll"})
for src, want := range map[string]string{"172.18.0.1": "a", "172.18.0.2": "webshell", "172.18.0.3": "b", "172.18.0.4": "c", "172.18.0.5": "payroll"} {
if n, _ := e.resolve(mk(t0, src, "1.1.1.1", "tcp", 1)); n != want {
+26 -3
View File
@@ -1,6 +1,7 @@
package egress
import (
"bytes"
"container/list"
"errors"
"fmt"
@@ -276,8 +277,12 @@ func readNameservers(path string) []netip.Addr {
if err != nil {
return nil
}
return parseNameservers(string(b))
}
func parseNameservers(text string) []netip.Addr {
var out []netip.Addr
for _, ln := range strings.Split(string(b), "\n") {
for _, ln := range strings.Split(text, "\n") {
f := strings.Fields(ln)
if len(f) >= 2 && f[0] == "nameserver" {
if a, err := netip.ParseAddr(f[1]); err == nil {
@@ -328,13 +333,31 @@ func (e *Engine) fanPromote(pk pairKey, t int64) *pairState {
return p
}
// SetContainers replaces the address to container-name map (tests, wiring).
func (e *Engine) SetContainers(m map[netip.Addr]string) {
// SetContainerMap replaces the address to container-name map (tests, wiring).
func (e *Engine) SetContainerMap(m map[netip.Addr]string) {
e.mu.Lock()
e.containers = m
e.mu.Unlock()
}
// SetContainers replaces the container map with the content of a
// containers.map file sent by a probe ("<ip> <name>" per line).
func (e *Engine) SetContainers(data []byte) {
m, _ := parseContainers(bytes.NewReader(data))
e.SetContainerMap(m)
}
// SetResolv adds the nameservers of a resolv.conf sent by a probe to the
// allowed resolvers (those of the configuration stay).
func (e *Engine) SetResolv(data []byte) {
ns := parseNameservers(string(data))
e.mu.Lock()
for _, a := range ns {
e.resolvers[a] = true
}
e.mu.Unlock()
}
func (e *Engine) reloadMap() {
if e.cfg.Containers == "" {
return
+22
View File
@@ -23,8 +23,24 @@ type Source struct {
Log *slog.Logger
backfilling atomic.Bool
fol atomic.Pointer[tail.Follower]
remote bool
rstate atomic.Pointer[string]
}
// NewRemoteSource creates a source fed by a probe through Feed: there is no
// file and nothing to start.
func NewRemoteSource(e *Engine, log *slog.Logger) *Source {
s := NewSource("", e, log)
s.remote = true
return s
}
// Feed analyses one line received from a probe.
func (s *Source) Feed(line []byte) { s.E.Ingest(line) }
// SetState sets the state shown for a remote source (following, waiting, error).
func (s *Source) SetState(st string) { s.rstate.Store(&st) }
// NewSource creates the source of e reading path.
func NewSource(path string, e *Engine, log *slog.Logger) *Source {
if log == nil {
@@ -37,6 +53,12 @@ func NewSource(path string, e *Engine, log *slog.Logger) *Source {
}
func (s *Source) state() string {
if s.remote {
if p := s.rstate.Load(); p != nil {
return *p
}
return "waiting"
}
switch f := s.fol.Load(); {
case s.backfilling.Load():
return "backfill"
+7 -1
View File
@@ -3,6 +3,7 @@ package egress
import (
"bufio"
"fmt"
"io"
"net/netip"
"os"
"regexp"
@@ -106,8 +107,13 @@ func LoadContainers(path string) (map[netip.Addr]string, error) {
return nil, err
}
defer fh.Close()
return parseContainers(fh)
}
// parseContainers reads the containers.map format from r.
func parseContainers(r io.Reader) (map[netip.Addr]string, error) {
m := map[netip.Addr]string{}
sc := bufio.NewScanner(fh)
sc := bufio.NewScanner(r)
sc.Buffer(make([]byte, 0, 4096), 4096)
for n := 0; sc.Scan() && n < maxMapLines; n++ {
f := strings.Fields(sc.Text())
+18 -3
View File
@@ -16,8 +16,12 @@ import (
// Config configures the engine. Mode must be observe or on (off means no engine).
type Config struct {
Mode string
Path string // decision file
Mode string
Path string // decision file
// Sink, when set, receives every decision (kind wire.CmdDecision) and unban
// request (wire.CmdUnban) line instead of the files: the hub queues them for
// the probe of the host. Path and UnbanPath are then only informational.
Sink func(kind, line string) error
UnbanPath string // unban requests read by the host (empty: unbanning is unavailable)
StatePath string // enforce.json, empty: no persistence
Host string // name of this instance, written in every line
@@ -233,6 +237,17 @@ func New(c Config) *Engine {
return e
}
// writeLog delivers one decision line to the sink or the decision file.
func (e *Engine) writeLog(line string) error {
if e.cfg.Sink != nil {
return e.cfg.Sink("decision", line)
}
return e.log.write(line)
}
// HasSink reports whether decisions go to a sink instead of local files.
func (e *Engine) HasSink() bool { return e.cfg.Sink != nil }
// Mode returns the mode of the engine.
func (e *Engine) Mode() string { return e.cfg.Mode }
@@ -622,7 +637,7 @@ func (e *Engine) apply(a netip.Addr, st *ipState, d Decision, src string, now ti
}
line, err := FormatLine(now, a, d.Reason, d.Score, d.TTL, e.cfg.Host, src)
if err == nil {
err = e.log.write(line)
err = e.writeLog(line)
}
if err != nil {
e.counts.WriteErrors++
+6 -2
View File
@@ -47,7 +47,7 @@ func UnbanLine(t time.Time, a netip.Addr, allow int) string {
// Unban writes the request for the host, drops the active ban of the address
// and, when allowS > 0, keeps the engine from banning it for that long.
func (e *Engine) Unban(a netip.Addr, allowS int, src string) error {
if e.cfg.UnbanPath == "" {
if e.cfg.UnbanPath == "" && e.cfg.Sink == nil {
return ErrNoUnbanLog
}
if allowS < 0 || allowS > MaxAllow {
@@ -55,7 +55,11 @@ func (e *Engine) Unban(a netip.Addr, allowS int, src string) error {
}
a = a.Unmap().WithZone("")
now := e.cfg.Now()
if err := e.unlog.write(UnbanLine(now, a, allowS)); err != nil {
if e.cfg.Sink != nil {
if err := e.cfg.Sink("unban", UnbanLine(now, a, allowS)); err != nil {
return err
}
} else if err := e.unlog.write(UnbanLine(now, a, allowS)); err != nil {
return err
}
e.mu.Lock()
-46
View File
@@ -1,46 +0,0 @@
package fed
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
)
// Get fetches a peer path with the peer token and decodes the JSON answer.
func (h *Hub) Get(ctx context.Context, p Peer, path string, out any) error {
_, err := h.get(ctx, p, path, out)
return err
}
// PostJSON sends v as JSON to a peer path with the peer token.
func (h *Hub) PostJSON(ctx context.Context, p Peer, path string, v any) error {
b, err := json.Marshal(v)
if err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, p.URL+path, bytes.NewReader(b))
if err != nil {
return err
}
tok := h.Token
if p.Token != "" {
tok = p.Token
}
if tok != "" {
req.Header.Set("Authorization", "Bearer "+tok)
}
req.Header.Set("Content-Type", "application/json")
resp, err := h.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
if resp.StatusCode/100 != 2 {
return fmt.Errorf("HTTP %d", resp.StatusCode)
}
return nil
}
-42
View File
@@ -1,42 +0,0 @@
package fed
import (
"context"
"encoding/json"
"fmt"
"sync"
)
// EgressFor asks the online peers (or one) for their egress analysis of the
// window [from, to] (unix seconds). The raw answers are untrusted: the caller
// decodes and sanitizes them.
func (h *Hub) EgressFor(ctx context.Context, from, to int64, only string) map[string]json.RawMessage {
out := map[string]json.RawMessage{}
var mu sync.Mutex
var wg sync.WaitGroup
for _, p := range h.Peers {
if only != "" && only != p.Name {
continue
}
h.mu.RLock()
st := h.state[p.Name]
online := st != nil && st.online
h.mu.RUnlock()
if !online {
continue
}
wg.Add(1)
go func(p Peer) {
defer wg.Done()
var raw json.RawMessage
if _, err := h.get(ctx, p, fmt.Sprintf("/api/v1/peer/egress?from=%d&to=%d", from, to), &raw); err != nil {
return
}
mu.Lock()
out[p.Name] = raw
mu.Unlock()
}(p)
}
wg.Wait()
return out
}
-13
View File
@@ -1,13 +0,0 @@
package fed
import "time"
// SetLiveLimits shrinks the flood window, the byte ceiling and the first backoff; it returns the restore func.
func SetLiveLimits(window time.Duration, bytesPerSec int, backoff time.Duration) func() {
w, b, k := liveByteWindow, maxLiveBytes, liveBackoff0
liveByteWindow, maxLiveBytes, liveBackoff0 = window, bytesPerSec, backoff
return func() { liveByteWindow, maxLiveBytes, liveBackoff0 = w, b, k }
}
// WaitStream blocks until the live stream goroutines have returned (after ctx is cancelled).
func (h *Hub) WaitStream() { h.swg.Wait() }
+178 -343
View File
@@ -1,287 +1,139 @@
// Package fed lets one instance aggregate the summaries of other instances.
// Package fed aggregates the nodes of the hub: one node per probe, each with
// its own store, served in process through the Backend interface.
package fed
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/netip"
"net/url"
"strings"
"sort"
"sync"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
// maxBody caps what a hub accepts from one peer response.
const maxBody = 8 << 20
// Peer is a remote Urutau instance.
type Peer struct {
Name, URL string
// Token overrides the hub-wide token for this peer (URUTAU_PEER_TOKEN_<NAME>).
Token string
// Backend is one probe node seen from the aggregation layer.
type Backend interface {
Name() string
Export(rg store.Range) store.PeerExport
Study(q store.PeriodQuery) store.PeerStudy
Egress(from, to int64) json.RawMessage
Subscribe() (<-chan store.LiveEvent, func())
SubscribeVisits() (<-chan store.VisitMsg, func())
// Online reports whether the probe is connected. The data of an offline
// node is still served (it lives in the hub).
Online() bool
Location() *store.Location
}
// ParsePeer parses "name=https://url".
func ParsePeer(s string) (Peer, error) {
name, u, ok := strings.Cut(s, "=")
name, u = strings.TrimSpace(name), strings.TrimRight(strings.TrimSpace(u), "/")
if !ok || name == "" || u == "" {
return Peer{}, fmt.Errorf("peer %q: expected name=https://url", s)
}
pu, err := url.Parse(u)
if err != nil || pu.Host == "" || pu.User != nil {
return Peer{}, fmt.Errorf("peer %q: invalid URL", s)
}
switch {
case pu.Scheme == "https":
case pu.Scheme == "http" && isLoopbackHost(pu.Hostname()):
default:
return Peer{}, fmt.Errorf("peer %q: the URL must be https (plain http only for loopback)", s)
}
return Peer{Name: name, URL: u}, nil
}
func isLoopbackHost(h string) bool {
if h == "localhost" {
return true
}
a, err := netip.ParseAddr(h)
return err == nil && a.IsLoopback()
}
type peerState struct {
online bool
lastOK int64
err string
latency int64
version string
exports map[string]store.PeerExport
extra map[string]*extraExport // on-demand windows
studies map[string]*studyCached
live bool
}
// extraExport is an export of a window outside the background set.
type extraExport struct {
at time.Time
e store.PeerExport
// HostStatus is implemented by backends that know more than Online (version,
// last contact, lag); Hosts uses it when present.
type HostStatus interface {
HostInfo() store.HostInfo
}
const (
extraTTL = 15 * time.Second
extraMax = 12 // cached on-demand exports per peer
exportTTL = 5 * time.Second
studyTTL = 30 * time.Second
cacheMax = 24
liveBuf = 500
)
// Hub polls peers and serves their latest summaries.
type cached[T any] struct {
at time.Time
v T
}
// Hub merges the backends supplied by Provider.
type Hub struct {
Peers []Peer
Token string
Interval time.Duration
client *http.Client
stream *http.Client // long-lived SSE: no overall timeout, no redirects
Provider func() []Backend
swg sync.WaitGroup // live stream goroutines
lmu sync.Mutex
live liveState
mu sync.Mutex
exports map[string]cached[store.PeerExport]
studies map[string]cached[store.PeerStudy]
mu sync.RWMutex
state map[string]*peerState
// OnLive, when set, sees every sanitized peer event before it is published
// (it assigns the local id and registers it in the event log).
OnLive func(*store.LiveEvent)
lmu sync.Mutex
recent []store.LiveEvent
head int
subs map[chan store.LiveEvent]struct{}
vsubs map[chan store.VisitMsg]struct{}
attach map[string]func() // backend name -> stop
}
// NewHub creates a hub; Interval defaults to 15 seconds.
func NewHub(peers []Peer, token string) *Hub {
h := &Hub{Peers: peers, Token: token, Interval: 15 * time.Second,
client: &http.Client{Timeout: 4 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}, state: map[string]*peerState{}}
tr := http.DefaultTransport.(*http.Transport).Clone()
tr.ResponseHeaderTimeout = 10 * time.Second
h.stream = &http.Client{Transport: tr, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
for _, p := range peers {
h.state[p.Name] = &peerState{exports: map[string]store.PeerExport{}, extra: map[string]*extraExport{}}
}
return h
// NewHub creates a hub over the backends returned by provider (called on every use).
func NewHub(provider func() []Backend) *Hub {
return &Hub{Provider: provider, exports: map[string]cached[store.PeerExport]{}, studies: map[string]cached[store.PeerStudy]{},
subs: map[chan store.LiveEvent]struct{}{}, vsubs: map[chan store.VisitMsg]struct{}{}, attach: map[string]func(){}}
}
func (h *Hub) get(ctx context.Context, p Peer, path string, out any) (time.Duration, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, p.URL+path, nil)
if err != nil {
return 0, err
func (h *Hub) backends(only string) []Backend {
if h == nil || h.Provider == nil {
return nil
}
tok := h.Token
if p.Token != "" {
tok = p.Token
}
if tok != "" {
req.Header.Set("Authorization", "Bearer "+tok)
}
req.Header.Set("Accept", "application/json")
t := time.Now()
resp, err := h.client.Do(req)
if err != nil {
return 0, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
return 0, fmt.Errorf("HTTP %d", resp.StatusCode)
}
body, err := io.ReadAll(io.LimitReader(resp.Body, maxBody+1))
if err != nil {
return 0, err
}
if len(body) > maxBody {
return 0, fmt.Errorf("response larger than %d bytes", maxBody)
}
if err := json.Unmarshal(body, out); err != nil {
return 0, err
}
return time.Since(t), nil
}
// Refresh fetches every peer once, concurrently. Failures only mark the peer offline.
func (h *Hub) Refresh(ctx context.Context) {
var wg sync.WaitGroup
for _, p := range h.Peers {
wg.Add(1)
go func(p Peer) {
defer wg.Done()
exports := map[string]store.PeerExport{}
var lat time.Duration
var ferr error
for _, name := range store.BackgroundRanges {
var e store.PeerExport
d, err := h.get(ctx, p, "/api/v1/peer/export?range="+name, &e)
if err == nil {
err = e.Sanitize(name)
}
if err != nil {
ferr = err
break
}
lat = d
e.Summary = rename(e.Summary, p.Name)
exports[name] = e
}
h.mu.Lock()
st := h.state[p.Name]
if ferr != nil {
st.online, st.err = false, ferr.Error()
if len(st.err) > 160 {
st.err = st.err[:160]
}
} else {
st.online, st.err, st.lastOK, st.latency, st.exports = true, "", time.Now().Unix(), lat.Milliseconds(), exports
for _, e := range exports {
st.version = e.Summary.Version
}
}
h.mu.Unlock()
}(p)
}
wg.Wait()
}
// fetchRange asks a peer for the export of a window and sanitizes it.
func (h *Hub) fetchRange(ctx context.Context, p Peer, rg store.Range) (store.PeerExport, error) {
var e store.PeerExport
path := "/api/v1/peer/export?range=" + url.QueryEscape(rg.Name)
if rg.Custom() {
path = fmt.Sprintf("/api/v1/peer/export?from=%d&to=%d", rg.From, rg.To)
}
if _, err := h.get(ctx, p, path, &e); err != nil {
return e, err
}
if err := e.SanitizeRange(rg); err != nil {
return e, err
}
e.Summary = rename(e.Summary, p.Name)
return e, nil
}
// exportsFor returns the exports of the online peers (or one) for a window:
// the cached background ones, or an on-demand fetch cached for 15 s.
func (h *Hub) exportsFor(ctx context.Context, rg store.Range, only string) map[string]store.PeerExport {
out := map[string]store.PeerExport{}
var mu sync.Mutex
var wg sync.WaitGroup
for _, p := range h.Peers {
if only != "" && only != p.Name {
continue
all := h.Provider()
out := make([]Backend, 0, len(all))
for _, b := range all {
if only == "" || only == b.Name() {
out = append(out, b)
}
h.mu.RLock()
st := h.state[p.Name]
online := st.online
var cached *store.PeerExport
if !rg.Custom() {
if e, ok := st.exports[rg.Name]; ok {
cached = &e
}
}
if cached == nil {
if x := st.extra[rg.Key()]; x != nil && time.Since(x.at) < extraTTL {
e := x.e
cached = &e
}
}
h.mu.RUnlock()
if !online {
continue
}
if cached != nil {
out[p.Name] = *cached
continue
}
wg.Add(1)
go func(p Peer) {
defer wg.Done()
e, err := h.fetchRange(ctx, p, rg)
if err != nil {
return
}
h.mu.Lock()
st := h.state[p.Name]
if len(st.extra) >= extraMax {
st.extra = map[string]*extraExport{}
}
st.extra[rg.Key()] = &extraExport{at: time.Now(), e: e}
h.mu.Unlock()
mu.Lock()
out[p.Name] = e
mu.Unlock()
}(p)
}
wg.Wait()
sort.Slice(out, func(i, j int) bool { return out[i].Name() < out[j].Name() })
return out
}
// SummariesFor returns the summaries of online peers for any window.
// PeerNames lists the names of the nodes (nil-safe).
func (h *Hub) PeerNames() []string {
var out []string
for _, b := range h.backends("") {
out = append(out, b.Name())
}
return out
}
// Has reports whether name is a node served by this hub.
func (h *Hub) Has(name string) bool { return len(h.backends(name)) > 0 }
func (h *Hub) export(b Backend, rg store.Range) (store.PeerExport, bool) {
key := b.Name() + "|" + rg.Key()
h.mu.Lock()
if c, ok := h.exports[key]; ok && time.Since(c.at) < exportTTL {
h.mu.Unlock()
return c.v, true
}
h.mu.Unlock()
e := b.Export(rg)
if err := e.SanitizeRange(rg); err != nil {
return e, false
}
e.Summary = rename(e.Summary, b.Name())
h.mu.Lock()
if len(h.exports) >= cacheMax {
h.exports = map[string]cached[store.PeerExport]{}
}
h.exports[key] = cached[store.PeerExport]{time.Now(), e}
h.mu.Unlock()
return e, true
}
// SummariesFor returns the summaries of the nodes (or one) for any window.
func (h *Hub) SummariesFor(ctx context.Context, rg store.Range, only string) []store.Summary {
m := h.exportsFor(ctx, rg, only)
var out []store.Summary
for _, p := range h.Peers {
if e, ok := m[p.Name]; ok {
for _, b := range h.backends(only) {
if e, ok := h.export(b, rg); ok {
out = append(out, e.Summary)
}
}
return out
}
// TrafficFor returns the analytics of online peers for any window and domain.
// TrafficFor returns the analytics of the nodes (or one) for a window and domain.
func (h *Hub) TrafficFor(ctx context.Context, rg store.Range, domain, only string) []store.TrafficData {
m := h.exportsFor(ctx, rg, only)
var out []store.TrafficData
for _, p := range h.Peers {
if e, ok := m[p.Name]; ok {
for _, b := range h.backends(only) {
if e, ok := h.export(b, rg); ok {
if t, ok := e.Traffic[domain]; ok {
t.Host = p.Name
t.Host = b.Name()
out = append(out, t)
}
}
@@ -289,7 +141,17 @@ func (h *Hub) TrafficFor(ctx context.Context, rg store.Range, domain, only strin
return out
}
// rename forces the configured peer name on every row of a remote summary.
// Summaries is SummariesFor for a named range.
func (h *Hub) Summaries(rangeName, only string) []store.Summary {
return h.SummariesFor(context.Background(), store.ParseRange(rangeName), only)
}
// Traffic is TrafficFor for a named range.
func (h *Hub) Traffic(rangeName, domain, only string) []store.TrafficData {
return h.TrafficFor(context.Background(), store.ParseRange(rangeName), domain, only)
}
// rename forces the node name on every row of a summary.
func rename(s store.Summary, name string) store.Summary {
s.Host = name
for i := range s.Hosts {
@@ -307,96 +169,13 @@ func rename(s store.Summary, name string) store.Summary {
return s
}
// Run refreshes until ctx is done.
func (h *Hub) Run(ctx context.Context) {
if len(h.Peers) == 0 {
return
}
h.Stream(ctx)
h.Refresh(ctx)
t := time.NewTicker(h.Interval)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
h.Refresh(ctx)
}
}
}
// Hosts lists the status of every peer (online or not).
func (h *Hub) Hosts() []store.HostInfo {
h.mu.RLock()
defer h.mu.RUnlock()
out := make([]store.HostInfo, 0, len(h.Peers))
for _, p := range h.Peers {
st := h.state[p.Name]
hi := store.HostInfo{Name: p.Name, Online: st.online, Error: st.err, LastSeen: st.lastOK, LatencyMS: st.latency, Version: st.version, Live: st.live && st.online}
if e, ok := st.exports["24h"]; ok && st.online {
s := e.Summary
hi.Requests, hi.Malicious = s.Totals.Requests, s.Totals.Malicious
hi.HostileIPs, hi.ActiveBans = s.Totals.HostileIPs, s.Totals.ActiveBans
if len(s.Hosts) > 0 {
hi.Location = s.Hosts[0].Location
}
}
out = append(out, hi)
}
return out
}
// Summaries returns the summaries of online peers for a range. When only is
// not empty just that peer is returned.
func (h *Hub) Summaries(rangeName, only string) []store.Summary {
h.mu.RLock()
defer h.mu.RUnlock()
var out []store.Summary
for _, p := range h.Peers {
if only != "" && only != p.Name {
continue
}
st := h.state[p.Name]
if e, ok := st.exports[rangeName]; ok && st.online {
out = append(out, e.Summary)
}
}
return out
}
// Peers lists the configured peer names (nil-safe).
func (h *Hub) PeerNames() []string {
if h == nil {
return nil
}
out := make([]string, 0, len(h.Peers))
for _, p := range h.Peers {
out = append(out, p.Name)
}
return out
}
// Has reports whether name is a configured peer.
func (h *Hub) Has(name string) bool {
for _, p := range h.Peers {
if p.Name == name {
return true
}
}
return false
}
// IPDetail looks an address up in the cached exports of the online peers (the
// 30-day summary, which carries the full row). No request is made to the peer.
// IPDetail looks an address up in the 30-day export of every node.
func (h *Hub) IPDetail(ip string) []store.IPSummary {
h.mu.RLock()
defer h.mu.RUnlock()
var out []store.IPSummary
for _, p := range h.Peers {
st := h.state[p.Name]
e, ok := st.exports["30d"]
if !ok || !st.online {
rg := store.ParseRange("30d")
for _, b := range h.backends("") {
e, ok := h.export(b, rg)
if !ok {
continue
}
for _, x := range e.Summary.IPs {
@@ -409,22 +188,78 @@ func (h *Hub) IPDetail(ip string) []store.IPSummary {
return out
}
// Traffic returns the cached analytics of online peers (or only one) for a
// domain ("all" or a name), from the same export.
func (h *Hub) Traffic(rangeName, domain, only string) []store.TrafficData {
h.mu.RLock()
defer h.mu.RUnlock()
var out []store.TrafficData
for _, p := range h.Peers {
if only != "" && only != p.Name {
// Hosts lists the status of every node (online or not).
func (h *Hub) Hosts() []store.HostInfo {
rg := store.ParseRange("24h")
var out []store.HostInfo
for _, b := range h.backends("") {
hi := store.HostInfo{Name: b.Name(), Online: b.Online(), Live: b.Online(), Location: b.Location()}
if hs, ok := b.(HostStatus); ok {
hi = hs.HostInfo()
hi.Name = b.Name()
}
if e, ok := h.export(b, rg); ok {
s := e.Summary
hi.Requests, hi.Malicious = s.Totals.Requests, s.Totals.Malicious
hi.HostileIPs, hi.ActiveBans = s.Totals.HostileIPs, s.Totals.ActiveBans
if hi.Location == nil && len(s.Hosts) > 0 {
hi.Location = s.Hosts[0].Location
}
}
out = append(out, hi)
}
return out
}
func studyKey(q store.PeriodQuery) string {
return fmt.Sprintf("%d-%d|%s|%s|%s|%d", q.From, q.To, q.IP, q.Cat, q.Fam, q.Gap)
}
// StudiesFor returns the period and metrics study of every node (or one).
func (h *Hub) StudiesFor(ctx context.Context, q store.PeriodQuery, only string) map[string]store.PeerStudy {
out := map[string]store.PeerStudy{}
var mu sync.Mutex
var wg sync.WaitGroup
for _, b := range h.backends(only) {
key := b.Name() + "|" + studyKey(q)
h.mu.Lock()
c, hit := h.studies[key]
h.mu.Unlock()
if hit && time.Since(c.at) < studyTTL {
out[b.Name()] = c.v
continue
}
st := h.state[p.Name]
if e, ok := st.exports[rangeName]; ok && st.online {
if t, ok := e.Traffic[domain]; ok {
t.Host = p.Name
out = append(out, t)
wg.Add(1)
go func(b Backend) {
defer wg.Done()
pq := q
pq.Host = b.Name()
s := b.Study(pq)
if !s.Sanitize(b.Name()) {
return
}
h.mu.Lock()
if len(h.studies) >= cacheMax {
h.studies = map[string]cached[store.PeerStudy]{}
}
h.studies[key] = cached[store.PeerStudy]{time.Now(), s}
h.mu.Unlock()
mu.Lock()
out[b.Name()] = s
mu.Unlock()
}(b)
}
wg.Wait()
return out
}
// EgressFor returns the egress report of every node (or one) for [from, to];
// nodes without egress analysis are left out.
func (h *Hub) EgressFor(ctx context.Context, from, to int64, only string) map[string]json.RawMessage {
out := map[string]json.RawMessage{}
for _, b := range h.backends(only) {
if raw := b.Egress(from, to); len(raw) > 0 {
out[b.Name()] = raw
}
}
return out
+32 -150
View File
@@ -1,168 +1,50 @@
package fed_test
package fed
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/server"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
func TestPeerPollingMergeAndOffline(t *testing.T) {
ps := store.New(store.Config{Name: "remote-self-name", Version: "t"})
ps.Ingest(core.Event{Time: time.Now(), IP: "5.5.5.5", Cat: core.Exploit, Source: "traefik", Path: "/x", Method: "GET"})
ps.Traffic(core.Event{Time: time.Now(), IP: "9.9.9.9", Cat: core.OK, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/", Status: 200})
srv := httptest.NewServer(server.New(server.Options{Token: "main-token-0123456789-abcdefghijklmnopqrs", PeerTokens: []string{"peer-secret-0123456789-abcdefghijklmnopqr"}, Version: "t", Store: ps}))
p, err := fed.ParsePeer("hostinger=" + srv.URL + "/")
if err != nil || p.Name != "hostinger" {
t.Fatal(p, err)
}
for _, bad := range []string{"nourl", "=http://x", "a=ftp://x", "a=", "a=http://example.org", "a=http://10.0.0.5:8790", "a=https://user:pw@example.org"} {
if _, err := fed.ParsePeer(bad); err == nil {
t.Errorf("%q must be rejected", bad)
}
}
good := fed.NewHub([]fed.Peer{p}, "peer-secret-0123456789-abcdefghijklmnopqr")
good.Refresh(context.Background())
sums := good.Summaries("24h", "")
if len(sums) != 1 || sums[0].Host != "hostinger" || sums[0].IPs[0].Hosts[0] != "hostinger" || sums[0].IPs[0].IP != "5.5.5.5" {
t.Fatalf("summaries %+v", sums)
}
if h := good.Hosts(); !h[0].Online || h[0].Name != "hostinger" {
t.Fatalf("hosts %+v", h)
}
if d := good.IPDetail("5.5.5.5"); len(d) != 1 || d[0].Hosts[0] != "hostinger" {
t.Fatalf("ip detail from the cached export: %v", d)
}
if tr := good.Traffic("24h", "all", ""); len(tr) != 1 || tr[0].Requests != 1 || tr[0].Host != "hostinger" {
t.Fatalf("traffic %+v", tr)
}
if tr := good.Traffic("24h", "a.example", "hostinger"); len(tr) != 1 || tr[0].Requests != 1 {
t.Fatalf("per-domain traffic %+v", tr)
}
bad := fed.NewHub([]fed.Peer{p}, "wrong")
bad.Refresh(context.Background())
if h := bad.Hosts(); h[0].Online || h[0].Error == "" || len(bad.Summaries("24h", "")) != 0 {
t.Fatalf("wrong token must mark the peer offline: %+v", h)
}
srv.Close()
good.Refresh(context.Background())
if h := good.Hosts(); h[0].Online || len(good.Summaries("24h", "")) != 0 {
t.Fatalf("closed peer must be offline: %+v", h)
}
type fake struct {
name string
online bool
}
func TestHubOnlyAsksForTheExportAndRefusesHostileResponses(t *testing.T) {
var paths []string
var huge atomic.Bool
var redirects atomic.Int32
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
redirects.Add(1)
w.Write([]byte("{}"))
}))
defer target.Close()
mux := http.NewServeMux()
mux.HandleFunc("/api/v1/peer/export", func(w http.ResponseWriter, r *http.Request) {
paths = append(paths, r.URL.Path)
switch {
case r.URL.Query().Get("redirect") == "1":
case huge.Load():
w.Write([]byte(`{"v":1,"pad":"` + strings.Repeat("x", 9<<20) + `"}`))
return
}
http.Redirect(w, r, target.URL+"/x", http.StatusFound)
})
srv := httptest.NewServer(mux)
defer srv.Close()
p := fed.Peer{Name: "evil", URL: srv.URL}
func (f fake) Name() string { return f.name }
func (f fake) Export(rg store.Range) store.PeerExport {
return store.PeerExport{V: store.ExportVersion, Summary: store.Summary{Host: f.name, Hosts: []store.HostInfo{{Name: f.name, Self: true}}}, Traffic: map[string]store.TrafficData{}}
}
func (f fake) Study(q store.PeriodQuery) store.PeerStudy { return store.PeerStudy{} }
func (f fake) Egress(a, b int64) json.RawMessage { return json.RawMessage(`{"findings":[]}`) }
func (f fake) Subscribe() (<-chan store.LiveEvent, func()) {
return make(chan store.LiveEvent), func() {}
}
func (f fake) SubscribeVisits() (<-chan store.VisitMsg, func()) {
return make(chan store.VisitMsg), func() {}
}
func (f fake) Online() bool { return f.online }
func (f fake) Location() *store.Location { return nil }
h := fed.NewHub([]fed.Peer{p}, "t")
h.Refresh(context.Background())
if redirects.Load() != 0 {
t.Fatal("redirects must not be followed")
func TestHubServesBackendsEvenOffline(t *testing.T) {
h := NewHub(func() []Backend { return []Backend{fake{"b", false}, fake{"a", true}} })
if got := h.PeerNames(); len(got) != 2 || got[0] != "a" || !h.Has("b") || h.Has("c") {
t.Fatalf("%v", got)
}
if st := h.Hosts()[0]; st.Online {
t.Fatalf("a redirect is a failure: %+v", st)
rg := store.ParseRange("24h")
if s := h.SummariesFor(context.Background(), rg, ""); len(s) != 2 || s[0].Host != "a" || s[0].Hosts[0].Self {
t.Fatalf("%+v", s)
}
huge.Store(true)
h.Refresh(context.Background())
if st := h.Hosts()[0]; st.Online || !strings.Contains(st.Error, "larger") {
t.Fatalf("an oversized response must be refused: %+v", st)
if s := h.SummariesFor(context.Background(), rg, "b"); len(s) != 1 {
t.Fatalf("only: %+v", s)
}
for _, path := range paths {
if path != "/api/v1/peer/export" {
t.Fatalf("the hub asked for %s", path)
}
hosts := h.Hosts()
if len(hosts) != 2 || hosts[0].Online != true || hosts[1].Online != false {
t.Fatalf("%+v", hosts)
}
}
func TestHubBoundsAnInflatedPeer(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("/api/v1/peer/export", func(w http.ResponseWriter, r *http.Request) {
var e store.PeerExport
e.V = 1
e.Summary.Version = strings.Repeat("v", 5000)
for i := 0; i < 1000; i++ {
e.Summary.IPs = append(e.Summary.IPs, store.IPSummary{IP: "1.2.3." + "4", Score: 1, Samples: make([]string, 40), Hosts: make([]string, 40)})
}
e.Summary.IPs = append(e.Summary.IPs, store.IPSummary{IP: "not an ip", Score: 1e9})
e.Summary.Timeline.Series = map[string][]uint32{"exploit": make([]uint32, 100000), "evil": make([]uint32, 10)}
for i := 0; i < 200; i++ {
e.Summary.TopPaths = append(e.Summary.TopPaths, store.Count{Key: strings.Repeat("p", 9000), N: 1})
}
e.Traffic = map[string]store.TrafficData{}
for i := 0; i < 60; i++ {
e.Traffic[strings.Repeat("d", i+1)] = store.TrafficData{Timeline: struct {
Start int64 `json:"start"`
Step int64 `json:"step"`
Req []uint32 `json:"req"`
Pages []uint32 `json:"pages"`
}{Req: make([]uint32, 5000)}}
}
json.NewEncoder(w).Encode(e)
})
srv := httptest.NewServer(mux)
defer srv.Close()
h := fed.NewHub([]fed.Peer{{Name: "p", URL: srv.URL}}, "t")
h.Refresh(context.Background())
sums := h.Summaries("1h", "")
if len(sums) != 1 {
t.Fatalf("hosts %+v", h.Hosts())
}
s := sums[0]
if len(s.IPs) != 500 || len(s.Version) > 32 || len(s.TopPaths) > 50 || len(s.TopPaths[0].Key) > 300 {
t.Fatalf("caps not applied: ips=%d version=%d paths=%d", len(s.IPs), len(s.Version), len(s.TopPaths))
}
for _, x := range s.IPs {
if x.IP == "not an ip" || len(x.Samples) > 6 || len(x.Hosts) > 4 {
t.Fatalf("bad row survived: %+v", x)
}
}
if len(s.Timeline.Series["exploit"]) != 60 || s.Timeline.Series["evil"] != nil || len(s.Timeline.Series["ok"]) != 60 {
t.Fatal("the timeline grid is fixed by the range")
}
kept := 0
for i := 1; i <= 60; i++ {
for _, got := range h.Traffic("1h", strings.Repeat("d", i), "") {
kept++
if len(got.Timeline.Req) != 60 {
t.Fatalf("traffic grid must be fixed: %d", len(got.Timeline.Req))
}
}
}
if kept > 27 {
t.Fatalf("too many domains accepted from a peer: %d", kept)
if m := h.EgressFor(context.Background(), 0, 1, ""); len(m) != 2 {
t.Fatalf("%v", m)
}
}
+54 -175
View File
@@ -1,52 +1,21 @@
package fed
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"net/http"
"strings"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
const (
maxLiveLine = 16 << 10 // longest SSE line accepted from a peer
maxLiveRate = 50 // events per second accepted from one peer
liveBuffer = 500 // events kept for /api/v1/live/recent
liveIdle = 70 * time.Second
liveBackoffTo = 60 * time.Second
)
// Variables so tests can shrink them.
var (
maxLiveBytes = 1 << 20 // sustained bytes per second accepted from one peer
liveByteWindow = 10 * time.Second
liveBackoff0 = time.Second
)
type liveState struct {
recent []store.LiveEvent // ring of the newest peer events
head int
subs map[chan store.LiveEvent]struct{}
vsubs map[chan store.VisitMsg]struct{} // legitimate visits: relayed, never kept
}
// SubscribeVisits returns the legitimate visits relayed from peers.
// SubscribeVisits returns the legitimate visits of the nodes.
func (h *Hub) SubscribeVisits() (<-chan store.VisitMsg, func()) {
ch := make(chan store.VisitMsg, 64)
h.lmu.Lock()
if h.live.vsubs == nil {
h.live.vsubs = map[chan store.VisitMsg]struct{}{}
}
h.live.vsubs[ch] = struct{}{}
h.vsubs[ch] = struct{}{}
h.lmu.Unlock()
return ch, func() {
h.lmu.Lock()
delete(h.live.vsubs, ch)
delete(h.vsubs, ch)
h.lmu.Unlock()
}
}
@@ -54,7 +23,7 @@ func (h *Hub) SubscribeVisits() (<-chan store.VisitMsg, func()) {
func (h *Hub) publishVisit(m store.VisitMsg) {
h.lmu.Lock()
defer h.lmu.Unlock()
for ch := range h.live.vsubs {
for ch := range h.vsubs {
select {
case ch <- m:
default:
@@ -62,31 +31,28 @@ func (h *Hub) publishVisit(m store.VisitMsg) {
}
}
// Subscribe returns the live events relayed from peers; call stop when done.
// Subscribe returns the live events of the nodes; call stop when done.
func (h *Hub) Subscribe() (<-chan store.LiveEvent, func()) {
ch := make(chan store.LiveEvent, 64)
h.lmu.Lock()
if h.live.subs == nil {
h.live.subs = map[chan store.LiveEvent]struct{}{}
}
h.live.subs[ch] = struct{}{}
h.subs[ch] = struct{}{}
h.lmu.Unlock()
return ch, func() {
h.lmu.Lock()
delete(h.live.subs, ch)
delete(h.subs, ch)
h.lmu.Unlock()
}
}
// Recent returns the newest relayed peer events, newest first.
// Recent returns the newest live events of the nodes, newest first.
func (h *Hub) Recent(n int) []store.LiveEvent {
h.lmu.Lock()
defer h.lmu.Unlock()
total := len(h.live.recent)
total := len(h.recent)
out := make([]store.LiveEvent, 0, min(n, total))
for i := 0; i < total && len(out) < n; i++ {
idx := ((h.live.head-1-i)%total + total) % total
out = append(out, h.live.recent[idx])
idx := ((h.head-1-i)%total + total) % total
out = append(out, h.recent[idx])
}
return out
}
@@ -94,13 +60,13 @@ func (h *Hub) Recent(n int) []store.LiveEvent {
func (h *Hub) publish(e store.LiveEvent) {
h.lmu.Lock()
defer h.lmu.Unlock()
if len(h.live.recent) < liveBuffer {
h.live.recent = append(h.live.recent, e)
if len(h.recent) < liveBuf {
h.recent = append(h.recent, e)
} else {
h.live.recent[h.live.head] = e
h.live.head = (h.live.head + 1) % liveBuffer
h.recent[h.head] = e
h.head = (h.head + 1) % liveBuf
}
for ch := range h.live.subs {
for ch := range h.subs {
select {
case ch <- e:
default: // slow client: drop
@@ -108,143 +74,56 @@ func (h *Hub) publish(e store.LiveEvent) {
}
}
func (h *Hub) setLive(name string, v bool) {
h.mu.Lock()
h.state[name].live = v
h.mu.Unlock()
}
// peerLocation is the location the peer reported in its last export.
func (h *Hub) peerLocation(name string) *store.Location {
h.mu.RLock()
defer h.mu.RUnlock()
for _, e := range h.state[name].exports {
if len(e.Summary.Hosts) > 0 && e.Summary.Hosts[0].Location != nil {
l := *e.Summary.Hosts[0].Location
return &l
}
// Run keeps the live relay of every node (also those created later) until ctx is done.
func (h *Hub) Run(ctx context.Context) {
if h == nil {
return
}
return nil
}
// Stream keeps one live subscription per peer until ctx is done, reconnecting
// with an exponential backoff (1 s up to 60 s).
func (h *Hub) Stream(ctx context.Context) {
for _, p := range h.Peers {
h.swg.Add(1)
go func() { defer h.swg.Done(); h.streamPeer(ctx, p) }()
}
}
func (h *Hub) streamPeer(ctx context.Context, p Peer) {
back := liveBackoff0
for ctx.Err() == nil {
start := time.Now()
h.consume(ctx, p)
h.setLive(p.Name, false)
if time.Since(start) > 2*liveBackoffTo {
back = liveBackoff0 // it had been healthy for a while
t := time.NewTicker(time.Second)
defer t.Stop()
defer func() {
h.lmu.Lock()
for _, stop := range h.attach {
stop()
}
h.lmu.Unlock()
}()
for {
h.sync(ctx)
select {
case <-ctx.Done():
return
case <-time.After(back):
}
if back *= 2; back > liveBackoffTo {
back = liveBackoffTo
case <-t.C:
}
}
}
var errLive = errors.New("live stream refused")
func (h *Hub) consume(ctx context.Context, p Peer) error {
rctx, cancel := context.WithCancel(ctx)
defer cancel()
req, err := http.NewRequestWithContext(rctx, http.MethodGet, p.URL+"/api/v1/peer/stream?visits=1", nil)
if err != nil {
return err
}
tok := h.Token
if p.Token != "" {
tok = p.Token
}
if tok != "" {
req.Header.Set("Authorization", "Bearer "+tok)
}
req.Header.Set("Accept", "text/event-stream")
resp, err := h.stream.Do(req) // no redirects; https is enforced by ParsePeer
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 || !strings.HasPrefix(resp.Header.Get("Content-Type"), "text/event-stream") {
return errLive
}
idle := time.AfterFunc(liveIdle, cancel) // the peer pings every 20 s
defer idle.Stop()
h.setLive(p.Name, true)
rd := bufio.NewReaderSize(resp.Body, maxLiveLine)
var evName string
var tokens = float64(maxLiveRate)
winStart, winBytes := time.Now(), 0
last := time.Now()
for {
line, err := rd.ReadSlice('\n') // ErrBufferFull: a line over 16 KB ends the stream
if err != nil {
return err
// sync starts the relay of the backends that appeared since the last call.
func (h *Hub) sync(ctx context.Context) {
for _, b := range h.backends("") {
h.lmu.Lock()
_, ok := h.attach[b.Name()]
h.lmu.Unlock()
if ok {
continue
}
idle.Reset(liveIdle)
winBytes += len(line)
if float64(winBytes) > float64(maxLiveBytes)*liveByteWindow.Seconds() {
return errLive // a window's worth of budget burned already: flooding
}
if el := time.Since(winStart); el >= liveByteWindow {
if float64(winBytes)/el.Seconds() > float64(maxLiveBytes) {
return errLive // flooding: drop the connection, the backoff applies
}
winStart, winBytes = time.Now(), 0
}
line = bytes.TrimRight(line, "\r\n")
switch {
case bytes.HasPrefix(line, []byte("event:")):
evName = strings.TrimSpace(string(line[6:]))
case bytes.HasPrefix(line, []byte("data:")) && (evName == "ev" || evName == "visit"):
now := time.Now()
tokens += now.Sub(last).Seconds() * maxLiveRate
if tokens > maxLiveRate {
tokens = maxLiveRate
}
last = now
if tokens < 1 {
continue // over the budget: discard
}
tokens--
if evName == "visit" {
var v store.VisitMsg
if json.Unmarshal(bytes.TrimSpace(line[5:]), &v) == nil && v.Sanitize(now.Unix()) {
v.Host = p.Name
if v.Kind == "visit" && v.Dst == nil {
v.Dst = h.peerLocation(p.Name)
}
ev, stopEv := b.Subscribe()
vis, stopVis := b.SubscribeVisits()
cctx, cancel := context.WithCancel(ctx)
h.lmu.Lock()
h.attach[b.Name()] = func() { cancel(); stopEv(); stopVis() }
h.lmu.Unlock()
go func() {
for {
select {
case <-cctx.Done():
return
case e := <-ev:
h.publish(e)
case v := <-vis:
h.publishVisit(v)
}
continue
}
var e store.LiveEvent
if json.Unmarshal(bytes.TrimSpace(line[5:]), &e) != nil || !e.Sanitize(now.Unix()) {
continue
}
e.Host = p.Name
if e.Dst == nil {
e.Dst = h.peerLocation(p.Name)
}
if h.OnLive != nil {
h.OnLive(&e)
}
h.publish(e)
case len(line) == 0:
evName = ""
}
}()
}
}
-216
View File
@@ -1,216 +0,0 @@
package fed_test
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/server"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
func fakeStream(t *testing.T, conns *atomic.Int32, body func(w http.ResponseWriter)) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/api/v1/peer/stream" {
http.NotFound(w, r)
return
}
if r.Header.Get("Authorization") != "Bearer tok" {
http.Error(w, "no", 401)
return
}
conns.Add(1)
w.Header().Set("Content-Type", "text/event-stream")
w.WriteHeader(200)
body(w)
w.(http.Flusher).Flush()
<-r.Context().Done()
}))
}
func ev(data string) string { return "event: ev\ndata: " + data + "\n\n" }
func TestLiveRelaySanitizesAndDrops(t *testing.T) {
var conns atomic.Int32
big := ev(`{"ip":"1.2.3.4","cat":"scanner","path":"` + strings.Repeat("a", 20000) + `"}`)
srv := fakeStream(t, &conns, func(w http.ResponseWriter) {
fmt.Fprint(w, ": connected\n\n")
fmt.Fprint(w, ev(`{"ip":"not-an-ip","cat":"scanner"}`))
fmt.Fprint(w, ev(`{"ip":"5.5.5.5","cat":"ok"}`)) // not malicious
fmt.Fprint(w, ev(`{"ip":"5.5.5.5","cat":"<script>"}`)) // unknown category
fmt.Fprint(w, ev(`{"ip":"6.6.6.6","cat":"exploit","host":"evil","path":"/a\u0001b`+strings.Repeat("x", 500)+`","cc":"brasil","status":99999,"src":{"lat":500,"lon":1},"dst":{"lat":10,"lon":20,"label":"`+strings.Repeat("L", 200)+`"},"extra":"x"}`))
fmt.Fprint(w, "event: other\ndata: {\"ip\":\"7.7.7.7\",\"cat\":\"exploit\"}\n\n")
fmt.Fprint(w, ev(`{"ip":"8.8.8.8","cat":"scanner","src":{"lat":-8,"lon":-34,"cc":"BR","city":"Recife"}}`))
fmt.Fprint(w, big) // over 16 KB: the stream is cut
})
defer srv.Close()
p, _ := fed.ParsePeer("edge=" + srv.URL)
h := fed.NewHub([]fed.Peer{p}, "tok")
ch, stop := h.Subscribe()
defer stop()
ctx, cancel := context.WithCancel(context.Background())
defer func() { cancel(); h.WaitStream() }()
h.Stream(ctx)
var got []store.LiveEvent
for len(got) < 2 {
select {
case e := <-ch:
got = append(got, e)
case <-time.After(5 * time.Second):
t.Fatalf("only %d events: %+v", len(got), got)
}
}
a, b := got[0], got[1]
if a.IP != "6.6.6.6" || a.Host != "edge" || a.Cat != "exploit" || a.CC != "" || a.Status != 0 || a.Src != nil {
t.Fatalf("sanitized event %+v", a)
}
if strings.ContainsRune(a.Path, 1) || len(a.Path) > 240 || a.Dst == nil || len(a.Dst.Label) != 64 {
t.Fatalf("strings %q dst %+v", a.Path, a.Dst)
}
if b.IP != "8.8.8.8" || b.Src == nil || b.Src.City != "Recife" || b.Host != "edge" {
t.Fatalf("second %+v", b)
}
if r := h.Recent(10); len(r) != 2 || r[0].IP != "8.8.8.8" {
t.Fatalf("recent %+v", r)
}
// the oversize line ended the stream: no event from it, and the hub reconnects
deadline := time.After(5 * time.Second)
for conns.Load() < 2 {
select {
case <-deadline:
t.Fatalf("no reconnection (%d)", conns.Load())
case <-time.After(50 * time.Millisecond):
}
}
select {
case e := <-ch:
if e.IP == "1.2.3.4" {
t.Fatal("oversize line must not become an event")
}
default:
}
}
func TestLiveRateLimitAndFlag(t *testing.T) {
var conns atomic.Int32
srv := fakeStream(t, &conns, func(w http.ResponseWriter) {
for i := 0; i < 400; i++ {
fmt.Fprint(w, ev(fmt.Sprintf(`{"ip":"9.9.%d.%d","cat":"scanner"}`, i/250, i%250+1)))
}
})
defer srv.Close()
p, _ := fed.ParsePeer("edge=" + srv.URL)
h := fed.NewHub([]fed.Peer{p}, "tok")
ctx, cancel := context.WithCancel(context.Background())
defer func() { cancel(); h.WaitStream() }()
h.Stream(ctx)
deadline := time.Now().Add(5 * time.Second)
for len(h.Recent(500)) == 0 && time.Now().Before(deadline) {
time.Sleep(20 * time.Millisecond)
}
time.Sleep(300 * time.Millisecond)
if n := len(h.Recent(500)); n < 40 || n > 120 {
t.Fatalf("a burst of 400 must be cut to about 50 (got %d)", n)
}
if hs := h.Hosts(); len(hs) != 1 || hs[0].Live {
// Live also needs the peer to be online (polled); here it never was
t.Fatalf("hosts %+v", hs)
}
}
func TestLiveWithRealPeerServer(t *testing.T) {
ps := store.New(store.Config{Name: "remote", Version: "t", Location: &store.Location{Lat: -8, Lon: -35, Label: "Recife"}})
srv := httptest.NewServer(server.New(server.Options{Token: "main-token-0123456789-abcdefghijklmnopqrs", PeerTokens: []string{"peer-secret-0123456789-abcdefghijklmnopqr"}, Version: "t", Store: ps}))
defer srv.Close()
p, _ := fed.ParsePeer("edge=" + srv.URL)
h := fed.NewHub([]fed.Peer{p}, "peer-secret-0123456789-abcdefghijklmnopqr")
ctx, cancel := context.WithCancel(context.Background())
defer func() { cancel(); h.WaitStream() }()
h.Refresh(ctx)
h.Stream(ctx)
deadline := time.Now().Add(5 * time.Second)
for time.Now().Before(deadline) {
ps.Ingest(core.Event{Time: time.Now(), IP: "5.5.5.5", Cat: core.Exploit, Source: "traefik", Method: "GET", Path: "/x"})
if len(h.Recent(5)) > 0 {
break
}
time.Sleep(50 * time.Millisecond)
}
r := h.Recent(5)
if len(r) == 0 || r[0].Host != "edge" || r[0].IP != "5.5.5.5" || r[0].Dst == nil || r[0].Dst.Label != "Recife" {
t.Fatalf("relayed %+v", r)
}
hs := h.Hosts()
if !hs[0].Live || !hs[0].Online || hs[0].Location == nil || hs[0].Location.Label != "Recife" {
t.Fatalf("hosts %+v", hs)
}
}
func TestLiveByteFloodDropsConnection(t *testing.T) {
defer fed.SetLiveLimits(200*time.Millisecond, 10_000, 100*time.Millisecond)()
start := time.Now()
var conns atomic.Int32
pad := strings.Repeat("a", 1000)
srv := fakeStream(t, &conns, func(w http.ResponseWriter) {
for i := 0; i < 200; i++ { // ~200 KB at once: far above 10 KB/s
fmt.Fprintf(w, ": %s\n", pad)
}
})
defer srv.Close()
p, _ := fed.ParsePeer("edge=" + srv.URL)
h := fed.NewHub([]fed.Peer{p}, "tok")
ctx, cancel := context.WithCancel(context.Background())
defer func() { cancel(); h.WaitStream() }()
h.Stream(ctx)
// the flood ends the connection (window check), then the hub reconnects after the backoff
for conns.Load() < 2 {
if time.Since(start) > 2500*time.Millisecond {
t.Fatalf("no drop and reconnection (%d connections)", conns.Load())
}
time.Sleep(20 * time.Millisecond)
}
}
func TestVisitRelayHasNoAddressAndNoRecent(t *testing.T) {
var conns atomic.Int32
srv := fakeStream(t, &conns, func(w http.ResponseWriter) {
fmt.Fprint(w, "event: visit\ndata: "+`{"kind":"visit","t":`+fmt.Sprint(time.Now().Unix())+`,"host":"evil","ip":"9.9.9.9","ua":"Mozilla","domain":"a.example","path":"/x","status":200,"device":"mobile","src":{"lat":-8,"lon":-34.9,"cc":"BR","city":"Recife"}}`+"\n\n")
fmt.Fprint(w, "event: visit\ndata: "+`{"kind":"visit_batch","t":`+fmt.Sprint(time.Now().Unix())+`,"n":7}`+"\n\n")
fmt.Fprint(w, "event: visit\ndata: "+`{"kind":"nope"}`+"\n\n")
})
defer srv.Close()
p, _ := fed.ParsePeer("edge=" + srv.URL)
h := fed.NewHub([]fed.Peer{p}, "tok")
ch, stop := h.SubscribeVisits()
defer stop()
ctx, cancel := context.WithCancel(context.Background())
defer func() { cancel(); h.WaitStream() }()
h.Stream(ctx)
var got []store.VisitMsg
for len(got) < 2 {
select {
case m := <-ch:
got = append(got, m)
case <-time.After(5 * time.Second):
t.Fatalf("timeout, got %+v", got)
}
}
for _, m := range got {
b, _ := json.Marshal(m)
if strings.Contains(string(b), "9.9.9.9") || strings.Contains(string(b), `"ip"`) || strings.Contains(string(b), "Mozilla") || m.Host != "edge" {
t.Fatalf("relayed %s", b)
}
}
if got[0].Device != "mobile" || got[1].Kind != "visit_batch" || got[1].N != 7 || len(h.Recent(10)) != 0 {
t.Fatalf("%+v recent=%d", got, len(h.Recent(10)))
}
}
-87
View File
@@ -1,87 +0,0 @@
package fed
import (
"context"
"fmt"
"net/url"
"sync"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
const (
studyTTL = 30 * time.Second
studyMax = 8 // cached studies per peer
)
type studyCached struct {
at time.Time
s store.PeerStudy
}
func studyKey(q store.PeriodQuery) string {
return fmt.Sprintf("%d-%d|%s|%s|%s|%d", q.From, q.To, q.IP, q.Cat, q.Fam, q.Gap)
}
// StudiesFor asks the online peers (or one) for their period and metrics
// study of a window, on demand, cached for 30 s. The answers are sanitized
// and carry the configured peer name.
func (h *Hub) StudiesFor(ctx context.Context, q store.PeriodQuery, only string) map[string]store.PeerStudy {
out := map[string]store.PeerStudy{}
var mu sync.Mutex
var wg sync.WaitGroup
key := studyKey(q)
for _, p := range h.Peers {
if only != "" && only != p.Name {
continue
}
h.mu.RLock()
st := h.state[p.Name]
online := st.online
var hit *store.PeerStudy
if c := st.studies[key]; c != nil && time.Since(c.at) < studyTTL {
s := c.s
hit = &s
}
h.mu.RUnlock()
if !online {
continue
}
if hit != nil {
out[p.Name] = *hit
continue
}
wg.Add(1)
go func(p Peer) {
defer wg.Done()
v := url.Values{}
v.Set("from", fmt.Sprint(q.From))
v.Set("to", fmt.Sprint(q.To))
for k, x := range map[string]string{"ip": q.IP, "cat": q.Cat, "fam": q.Fam} {
if x != "" {
v.Set(k, x)
}
}
if q.Gap > 0 {
v.Set("gap", fmt.Sprint(q.Gap))
}
var s store.PeerStudy
if _, err := h.get(ctx, p, "/api/v1/peer/period?"+v.Encode(), &s); err != nil || !s.Sanitize(p.Name) {
return
}
h.mu.Lock()
st := h.state[p.Name]
if st.studies == nil || len(st.studies) >= studyMax {
st.studies = map[string]*studyCached{}
}
st.studies[key] = &studyCached{time.Now(), s}
h.mu.Unlock()
mu.Lock()
out[p.Name] = s
mu.Unlock()
}(p)
}
wg.Wait()
return out
}
-115
View File
@@ -1,115 +0,0 @@
package fed_test
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/server"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
func TestHubOnDemandRangesRatesAndOldPeers(t *testing.T) {
peerTok := "peer-secret-0123456789-abcdefghijklmnopqr"
ps := store.New(store.Config{Name: "remote", Version: "t", Retention: 720 * time.Hour})
for i := 0; i < 4; i++ {
ps.Ingest(core.Event{Time: time.Now().Add(-time.Duration(i) * time.Minute), IP: "5.5.5.5", Cat: core.Exploit, Source: "traefik", Path: "/x", Method: "GET"})
}
ps.Ingest(core.Event{Time: time.Now().Add(-10 * 24 * time.Hour), IP: "6.6.6.6", Cat: core.Scanner, Source: "traefik", Path: "/y", Method: "GET"})
ps.Traffic(core.Event{Time: time.Now(), IP: "9.9.9.9", Cat: core.OK, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/", Status: 200})
var calls []string
inner := server.New(server.Options{Token: "main-token-0123456789-abcdefghijklmnopqrs", PeerTokens: []string{peerTok}, Version: "t", Store: ps})
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls = append(calls, r.URL.RawQuery)
inner.ServeHTTP(w, r)
}))
defer srv.Close()
p, _ := fed.ParsePeer("hostinger=" + srv.URL)
hub := fed.NewHub([]fed.Peer{p}, peerTok)
hub.Refresh(context.Background())
if len(calls) != len(store.BackgroundRanges) {
t.Fatalf("background fetches: %v", calls)
}
// a window outside the background set is fetched on demand, then cached
rg := store.Ranges["15d"]
n := len(calls)
sums := hub.SummariesFor(context.Background(), rg, "")
if len(sums) != 1 || sums[0].Range.Name != "15d" || sums[0].Totals.Counts["scanner"] != 1 || sums[0].Rates.Last1h != 4 {
t.Fatalf("15d %+v", sums)
}
hub.SummariesFor(context.Background(), rg, "")
if len(calls) != n+1 {
t.Fatalf("on-demand windows must be cached: %v", calls[n:])
}
// a custom window goes as from/to
now := time.Now().Unix()
local := store.New(store.Config{Name: "hub", Retention: 720 * time.Hour})
cr, err := local.ResolveRange("", fmt.Sprint(now-3*3600), "")
if err != nil {
t.Fatal(err)
}
cs := hub.SummariesFor(context.Background(), cr, "")
if len(cs) != 1 || cs[0].Totals.Counts["exploit"] != 4 || !strings.Contains(calls[len(calls)-1], "from=") {
t.Fatalf("custom %+v calls %v", cs, calls[len(calls)-1])
}
if tr := hub.TrafficFor(context.Background(), cr, "all", ""); len(tr) != 1 || tr[0].Requests != 1 {
t.Fatalf("traffic %+v", tr)
}
if got := hub.IPDetail("6.6.6.6"); len(got) != 1 {
t.Fatal("the 30 day export must carry the 10 day old address")
}
m := store.Merge("all", []store.Summary{local.Summary("24h"), sums[0]})
if m.Rates.Last1h != 4 {
t.Fatalf("merged rates %+v", m.Rates)
}
}
func TestOldPeerStringRangeStillParses(t *testing.T) {
var s store.Summary
if err := json.Unmarshal([]byte(`{"range":"24h","host":"x"}`), &s); err != nil || s.Range.Name != "24h" {
t.Fatalf("legacy range: %v %+v", err, s.Range)
}
if err := json.Unmarshal([]byte(`{"range":{"name":"7d","from":1,"to":2,"clipped":true}}`), &s); err != nil || !s.Range.Clipped {
t.Fatal(err)
}
}
func TestPeerEventsAreRegisteredWithHostAndLocalID(t *testing.T) {
var conns atomic.Int32
srv := fakeStream(t, &conns, func(w http.ResponseWriter) {
fmt.Fprint(w, ev(`{"id":999999,"ip":"6.6.6.6","cat":"exploit","host":"evil","ua":"sqlmap","fam":"vcs","tech":["T1190"],"flags":"SZ!"}`))
})
defer srv.Close()
p, _ := fed.ParsePeer("edge=" + srv.URL)
h := fed.NewHub([]fed.Peer{p}, "tok")
local := store.New(store.Config{Name: "hub"})
l, _ := evlog.Open(evlog.Options{Dir: t.TempDir() + "/events"})
local.SetEventLog(l)
h.OnLive = local.RecordPeerEvent
ch, stop := h.Subscribe()
defer stop()
ctx, cancel := context.WithCancel(context.Background())
defer func() { cancel(); h.WaitStream() }()
h.Stream(ctx)
select {
case e := <-ch:
if e.Host != "edge" || e.ID == 0 || e.ID == 999999 || e.Flags != "S" {
t.Fatalf("relayed %+v", e)
}
case <-time.After(5 * time.Second):
t.Fatal("no event")
}
pg, _ := local.QueryEvents(store.EventsQuery{From: time.Now().Unix() - 3600, To: time.Now().Unix() + 10, Host: "edge"})
if len(pg.Events) != 1 || !strings.Contains(string(pg.Events[0]), `"host":"edge"`) {
t.Fatalf("registry %v", pg.Events)
}
}
-120
View File
@@ -1,120 +0,0 @@
package fed_test
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/server"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
func logged(t *testing.T, name string) *store.Store {
s := store.New(store.Config{Name: name, Version: "t", Retention: 720 * time.Hour})
l, err := evlog.Open(evlog.Options{Dir: filepath.Join(t.TempDir(), "events")})
if err != nil {
t.Fatal(err)
}
s.SetEventLog(l)
return s
}
func TestHubMergesPeriodAndMetrics(t *testing.T) {
const userTok, peerTok = "main-token-0123456789-abcdefghijklmnopqrs", "peer-secret-0123456789-abcdefghijklmnopqr"
peer := logged(t, "hostinger")
hubSt := logged(t, "oracle")
now := time.Now()
for i := 0; i < 4; i++ {
peer.Ingest(core.Event{Time: now.Add(-time.Duration(i) * time.Minute), IP: "5.5.5.5", Cat: core.Exploit, Source: "traefik", Method: "GET", Path: "/.env", Status: 404, Domain: "p.example"})
}
hubSt.Ingest(core.Event{Time: now.Add(-time.Hour), IP: "6.6.6.6", Cat: core.Scanner, Source: "traefik", Method: "GET", Path: "/wp-login.php", Status: 404, Domain: "h.example"})
// a copy of the peer's event relayed live to the hub must not be counted twice
le := store.LiveEvent{FeedEvent: store.FeedEvent{T: now.Unix() - 30, IP: "5.5.5.5", Cat: "exploit", Source: "traefik", Host: "hostinger"}}
hubSt.RecordPeerEvent(&le)
var peerCalls []string
pinner := server.New(server.Options{Token: "other-token-0123456789-abcdefghijklmnopqrs", PeerTokens: []string{peerTok}, Version: "t", Store: peer})
psrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
peerCalls = append(peerCalls, r.URL.Path)
pinner.ServeHTTP(w, r)
}))
defer psrv.Close()
p, _ := fed.ParsePeer("hostinger=" + psrv.URL)
hub := fed.NewHub([]fed.Peer{p}, peerTok)
hub.Refresh(context.Background())
h := server.New(server.Options{Token: userTok, Version: "t", Store: hubSt, Hub: hub})
get := func(path string) map[string]any {
r := httptest.NewRequest("GET", path, nil)
r.Header.Set("Authorization", "Bearer "+userTok)
r.RemoteAddr = "198.51.100.1:1"
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
if w.Code != 200 {
t.Fatalf("%s: %d %s", path, w.Code, w.Body)
}
var m map[string]any
json.Unmarshal(w.Body.Bytes(), &m)
return m
}
pd := get("/api/v1/period?range=24h")
if pd["sessions_n"].(float64) != 2 || pd["events"].(float64) != 5 {
t.Fatalf("merged period: sessions %v events %v (relayed copies must not double count)", pd["sessions_n"], pd["events"])
}
hosts := map[string]bool{}
for _, s := range pd["sessions"].([]any) {
hosts[s.(map[string]any)["hosts"].([]any)[0].(string)] = true
}
if !hosts["oracle"] || !hosts["hostinger"] {
t.Fatalf("sessions must carry their host: %v", hosts)
}
if only := get("/api/v1/period?range=24h&host=hostinger"); only["sessions_n"].(float64) != 1 {
t.Fatalf("one peer: %v", only["sessions_n"])
}
if loc := get("/api/v1/period?range=24h&host=oracle"); loc["sessions_n"].(float64) != 1 {
t.Fatalf("local only: %v", loc["sessions_n"])
}
mt := get("/api/v1/metrics?range=24h")
if v := mt["attacks_per_hour_24h"].(map[string]any)["value"].(float64); v < 0.2 || v > 0.3 { // 5 events / 24 h, rounded to 0.1
t.Fatalf("merged attacks per hour: %v", v)
}
n := len(peerCalls)
get("/api/v1/period?range=24h")
for _, c := range peerCalls[n:] {
if c == "/api/v1/peer/period" {
t.Fatal("studies are cached for 30 s")
}
}
// the peer route: only the peer token, never the user token
for tok, want := range map[string]int{peerTok: 200, "other-token-0123456789-abcdefghijklmnopqrs": 401, "bad": 401} {
r := httptest.NewRequest("GET", "/api/v1/peer/period?from=1&to=2", nil)
r.Header.Set("Authorization", "Bearer "+tok)
r.RemoteAddr = "198.51.100.1:1"
w := httptest.NewRecorder()
pinner.ServeHTTP(w, r)
if tok == peerTok {
r = httptest.NewRequest("GET", "/api/v1/peer/period?from="+itoa(now.Unix()-3600)+"&to="+itoa(now.Unix()), nil)
r.Header.Set("Authorization", "Bearer "+tok)
r.RemoteAddr = "198.51.100.1:1"
w = httptest.NewRecorder()
pinner.ServeHTTP(w, r)
}
if w.Code != want {
t.Errorf("peer route with %q: %d, want %d", tok[:3], w.Code, want)
}
}
// a hub that is offline for the peer still answers (local + relayed)
psrv.Close()
hub.Refresh(context.Background())
if pd := get("/api/v1/period?range=24h"); pd["sessions_n"].(float64) < 1 {
t.Fatal("must answer without the peer")
}
}
func itoa(n int64) string { b, _ := json.Marshal(n); return string(b) }
+191
View File
@@ -0,0 +1,191 @@
package hub
import (
"context"
"encoding/json"
"errors"
"os"
"path/filepath"
"sync"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
// MaxQueue is the most commands kept per node; the oldest are dropped.
const MaxQueue = 10000
// CmdQueue is the persisted command queue of one node (commands.json).
type CmdQueue struct {
mu sync.Mutex
path string
next uint64
dropped uint64
cmds []wire.Cmd
dirty bool
notify chan struct{} // closed and replaced on every enqueue
stop chan struct{}
done chan struct{}
}
type queueFile struct {
Next uint64 `json:"next"`
Dropped uint64 `json:"dropped"`
Cmds []wire.Cmd `json:"cmds"`
}
// OpenQueue loads path (missing: empty) and starts the debounced writer; call
// Close to flush. An empty path keeps the queue in memory only.
func OpenQueue(path string) (*CmdQueue, error) {
q := &CmdQueue{path: path, next: 1, notify: make(chan struct{}), stop: make(chan struct{}), done: make(chan struct{})}
if path != "" {
if b, err := os.ReadFile(path); err == nil {
var f queueFile
if err := json.Unmarshal(b, &f); err != nil {
_ = os.Rename(path, path+".corrupt")
} else {
q.next, q.dropped, q.cmds = max(f.Next, 1), f.Dropped, f.Cmds
for _, c := range q.cmds {
q.next = max(q.next, c.Seq+1)
}
}
} else if !errors.Is(err, os.ErrNotExist) {
return nil, err
}
}
go q.writer()
return q, nil
}
func (q *CmdQueue) writer() {
defer close(q.done)
t := time.NewTicker(time.Second)
defer t.Stop()
for {
select {
case <-q.stop:
q.flush()
return
case <-t.C:
q.flush()
}
}
}
func (q *CmdQueue) flush() {
if q.path == "" {
return
}
q.mu.Lock()
if !q.dirty {
q.mu.Unlock()
return
}
b, err := json.Marshal(queueFile{Next: q.next, Dropped: q.dropped, Cmds: q.cmds})
q.dirty = false
q.mu.Unlock()
if err != nil {
return
}
_ = os.MkdirAll(filepath.Dir(q.path), 0o700)
tmp := q.path + ".tmp"
if os.WriteFile(tmp, b, 0o600) == nil {
_ = os.Rename(tmp, q.path)
}
}
// Close flushes the queue and stops the writer.
func (q *CmdQueue) Close() {
select {
case <-q.stop:
default:
close(q.stop)
}
<-q.done
}
// Enqueue appends a command; it matches the signature of enforce.Config.Sink.
func (q *CmdQueue) Enqueue(kind, line string) error {
if !wire.ValidCmdLine(kind, line) {
return errors.New("invalid command line")
}
q.mu.Lock()
q.cmds = append(q.cmds, wire.Cmd{Seq: q.next, Kind: kind, Line: line})
q.next++
if len(q.cmds) > MaxQueue {
n := len(q.cmds) - MaxQueue
q.dropped += uint64(n)
q.cmds = append([]wire.Cmd(nil), q.cmds[n:]...)
}
q.dirty = true
old := q.notify
q.notify = make(chan struct{})
q.mu.Unlock()
close(old)
return nil
}
// Last is the highest queued sequence (0 when nothing was ever queued).
func (q *CmdQueue) Last() uint64 {
q.mu.Lock()
defer q.mu.Unlock()
return q.next - 1
}
// Pending counts the queued commands after seq.
func (q *CmdQueue) Pending(after uint64) int {
q.mu.Lock()
defer q.mu.Unlock()
n := 0
for _, c := range q.cmds {
if c.Seq > after {
n++
}
}
return n
}
// Dropped counts the commands discarded by the size cap.
func (q *CmdQueue) Dropped() uint64 {
q.mu.Lock()
defer q.mu.Unlock()
return q.dropped
}
func (q *CmdQueue) after(seq uint64) ([]wire.Cmd, chan struct{}, uint64) {
q.mu.Lock()
defer q.mu.Unlock()
// the probe persisted everything up to seq: forget it
i := 0
for i < len(q.cmds) && q.cmds[i].Seq <= seq {
i++
}
if i > 0 {
q.cmds = append([]wire.Cmd(nil), q.cmds[i:]...)
q.dirty = true
}
out := q.cmds
if len(out) > 500 {
out = out[:500]
}
return append([]wire.Cmd(nil), out...), q.notify, q.dropped
}
// Wait returns the commands after seq at once, or holds up to wait for one.
func (q *CmdQueue) Wait(ctx context.Context, seq uint64, wait time.Duration) wire.CmdResp {
cmds, ch, dropped := q.after(seq)
if len(cmds) == 0 && wait > 0 {
t := time.NewTimer(wait)
defer t.Stop()
select {
case <-ch:
cmds, _, dropped = q.after(seq)
case <-t.C:
case <-ctx.Done():
}
}
if cmds == nil {
cmds = []wire.Cmd{}
}
return wire.CmdResp{Cmds: cmds, Dropped: dropped}
}
+254
View File
@@ -0,0 +1,254 @@
package hub
import (
"bytes"
"compress/gzip"
"encoding/json"
"errors"
"io"
"net/http"
"strconv"
"strings"
"time"
"unicode/utf8"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
// Authenticate checks Authorization: Bearer <token> and X-Urutau-Probe for a
// registered, non-revoked probe and returns its name.
func (m *Manager) Authenticate(r *http.Request) (string, bool) {
name := r.Header.Get(wire.HeaderProbe)
a := r.Header.Get("Authorization")
if !strings.HasPrefix(a, "Bearer ") {
m.Reg.Verify(name, "") // same work as a real check
return "", false
}
if !m.Reg.Verify(name, strings.TrimSpace(a[7:])) {
return "", false
}
return name, true
}
func writeJSON(w http.ResponseWriter, code int, v any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(code)
json.NewEncoder(w).Encode(v)
}
func fail(w http.ResponseWriter, code int, msg string) {
writeJSON(w, code, map[string]string{"error": msg})
}
// node returns the ready node of an authenticated probe or answers 503.
func (m *Manager) node(w http.ResponseWriter, name string) Node {
n, err := m.Ensure(name)
if err != nil {
w.Header().Set("Retry-After", "5")
fail(w, http.StatusServiceUnavailable, "node unavailable")
return nil
}
if !n.Ready() {
w.Header().Set("Retry-After", "5")
fail(w, http.StatusServiceUnavailable, "node loading")
return nil
}
return n
}
// Hello: POST /api/v1/probe/hello.
func (m *Manager) Hello(w http.ResponseWriter, r *http.Request, name string) {
var h wire.Hello
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 64<<10)).Decode(&h); err != nil {
fail(w, http.StatusBadRequest, "invalid JSON")
return
}
if h.Proto != wire.Proto {
fail(w, http.StatusConflict, "incompatible protocol version")
return
}
if h.Name != "" && h.Name != name {
fail(w, http.StatusBadRequest, "name does not match the token")
return
}
for _, s := range h.Sources {
if !wire.ValidSource(s) {
fail(w, http.StatusBadRequest, "unknown source")
return
}
}
n := m.node(w, name)
if n == nil {
return
}
if h.Location != nil && (h.Location.Lat < -90 || h.Location.Lat > 90 || h.Location.Lon < -180 || h.Location.Lon > 180) {
h.Location = nil
}
h.Version = clip(h.Version, 32)
h.Hostname = clip(h.Hostname, 64)
c := m.conn(name)
c.mu.Lock()
c.lastSeen, c.version, c.hostname = m.Now().Unix(), h.Version, h.Hostname
if h.LastSeq < c.ack {
c.ack = h.LastSeq // a probe that lost its state restarts its numbering
}
ack := c.ack
c.mu.Unlock()
n.Hello(h)
if rec, _ := m.Reg.Get(name); rec.Location != nil {
n.SetLocation(rec.Location)
} else if h.Location != nil {
n.SetLocation(h.Location)
}
writeJSON(w, 200, wire.HelloResp{Proto: wire.Proto, HubVer: m.Version, Offsets: n.Offsets(), AckSeq: ack, FlushMS: 1000})
}
func clip(s string, n int) string {
if len(s) > n {
s = s[:n]
}
return strings.ToValidUTF8(s, "")
}
// Push: POST /api/v1/probe/push.
func (m *Manager) Push(w http.ResponseWriter, r *http.Request, name string) {
c := m.conn(name)
if !c.busy.CompareAndSwap(false, true) {
w.Header().Set("Retry-After", "1")
fail(w, http.StatusTooManyRequests, "one push at a time")
return
}
defer c.busy.Store(false)
if m.infl.Add(1) > 16 {
m.infl.Add(-1)
w.Header().Set("Retry-After", "2")
fail(w, http.StatusServiceUnavailable, "ingest busy")
return
}
defer m.infl.Add(-1)
n := m.node(w, name)
if n == nil {
return
}
raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, wire.MaxBodyBytes))
if err != nil {
var mb *http.MaxBytesError
if errors.As(err, &mb) {
fail(w, http.StatusRequestEntityTooLarge, "body too large")
} else {
fail(w, http.StatusBadRequest, "unreadable body")
}
return
}
if ce := strings.ToLower(r.Header.Get("Content-Encoding")); ce == "gzip" {
zr, err := gzip.NewReader(bytes.NewReader(raw))
if err != nil {
fail(w, http.StatusBadRequest, "invalid gzip")
return
}
raw, err = io.ReadAll(io.LimitReader(zr, wire.MaxInflated+1))
if err != nil {
fail(w, http.StatusBadRequest, "invalid gzip")
return
}
if len(raw) > wire.MaxInflated {
fail(w, http.StatusRequestEntityTooLarge, "body too large")
return
}
} else if ce != "" && ce != "identity" {
fail(w, http.StatusBadRequest, "unsupported encoding")
return
}
var b wire.Batch
if err := json.Unmarshal(raw, &b); err != nil {
fail(w, http.StatusBadRequest, "invalid JSON")
return
}
if len(b.Lines) > wire.MaxLines {
fail(w, http.StatusBadRequest, "too many lines")
return
}
for i := range b.Lines {
l := &b.Lines[i]
if !wire.ValidSource(l.Src) || len(l.Text) > wire.MaxLine {
fail(w, http.StatusBadRequest, "invalid line")
return
}
if l.End.Offset < 0 {
fail(w, http.StatusBadRequest, "invalid line")
return
}
if !utf8.ValidString(l.Text) {
l.Text = strings.ToValidUTF8(l.Text, "�")
}
}
for _, f := range b.Files {
if (f.Name != wire.FileContainers && f.Name != wire.FileResolv) || len(f.Data) > wire.MaxFileBytes {
fail(w, http.StatusBadRequest, "invalid file")
return
}
}
now := m.Now()
c.mu.Lock()
c.lastSeen = now.Unix()
if b.Sent > 0 {
c.lagMS = max(0, now.UnixMilli()-b.Sent)
}
if b.Status != nil {
c.status = *b.Status
for _, s := range b.Status.Sources {
if s.LastLine > c.lastLine {
c.lastLine = s.LastLine
}
}
}
dup := false
if b.Seq != 0 && b.Seq <= c.ack {
dup = true
}
ack := c.ack
c.mu.Unlock()
if b.Status != nil {
n.SetStatus(*b.Status, true)
}
resp := wire.PushResp{Ack: ack}
if q := n.Queue(); q != nil {
resp.PendCmd = q.Last()
}
switch {
case b.Seq == 0: // heartbeat: status only
case dup:
resp.Dup = len(b.Lines)
default:
resp.Accepted, resp.Dup = n.Apply(b)
c.mu.Lock()
c.ack = b.Seq
resp.Ack = b.Seq
c.mu.Unlock()
}
writeJSON(w, 200, resp)
}
// Commands: GET /api/v1/probe/commands?after=<seq>&wait=<s>.
func (m *Manager) Commands(w http.ResponseWriter, r *http.Request, name string) {
n := m.node(w, name)
if n == nil {
return
}
after, _ := strconv.ParseUint(r.URL.Query().Get("after"), 10, 64)
wait, _ := strconv.Atoi(r.URL.Query().Get("wait"))
wait = max(0, min(wait, wire.MaxWaitSec))
c := m.conn(name)
c.mu.Lock()
c.lastSeen = m.Now().Unix()
c.mu.Unlock()
q := n.Queue()
if q == nil {
writeJSON(w, 200, wire.CmdResp{Cmds: []wire.Cmd{}})
return
}
// the write timeout of the server must outlive the long poll
_ = http.NewResponseController(w).SetWriteDeadline(time.Now().Add(time.Duration(wait+10) * time.Second))
writeJSON(w, 200, q.Wait(r.Context(), after, time.Duration(wait)*time.Second))
}
+671
View File
@@ -0,0 +1,671 @@
package hub_test
import (
"bytes"
"compress/gzip"
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"log/slog"
"net"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/app"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/probeagent"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
var quiet = slog.New(slog.NewTextHandler(io.Discard, nil))
func randTok() string {
b := make([]byte, 24)
rand.Read(b)
return hex.EncodeToString(b)
}
func cfgFor(dir string, mut func(*app.Config)) app.Config {
c := app.Config{Bind: "127.0.0.1:0", Name: "oracle", DataDir: dir, GeoDir: filepath.Join(dir, "geo"), Ignore: app.DefaultIgnore,
MonitorUA: app.DefaultMonitorUA, TrustedProxy: app.DefaultTrustedProxy, Retention: 168 * time.Hour, TorAuto: "off",
EventsMax: "64MB", Enforce: "off", EnforceShare: "off", EnforceThreshold: 3, EnforceMaxPerMin: 60, Egress: "on", PeerBlocklist: "on"}
if mut != nil {
mut(&c)
}
return c
}
// hubProc is a hub on a fixed address that can be stopped and started again
// over the same data directory (a process restart).
type hubProc struct {
t *testing.T
cfg app.Config
tok string
addr string
cancel context.CancelFunc
hub *app.Hub
srv *http.Server
}
func newAddr(t *testing.T) string {
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
a := l.Addr().String()
l.Close()
return a
}
func (p *hubProc) start() {
p.t.Helper()
ctx, cancel := context.WithCancel(context.Background())
p.cancel = cancel
h, err := app.NewHub(ctx, p.cfg, p.tok, quiet)
if err != nil {
p.t.Fatal(err)
}
p.hub = h
var ln net.Listener
for i := 0; i < 50; i++ {
if ln, err = net.Listen("tcp", p.addr); err == nil {
break
}
time.Sleep(20 * time.Millisecond)
}
if err != nil {
p.t.Fatal(err)
}
p.srv = &http.Server{Handler: h.Handler}
go p.srv.Serve(ln)
}
func (p *hubProc) stop() {
p.srv.Close()
p.cancel()
p.hub.Wait()
}
func (p *hubProc) get(path string) (int, []byte) {
req, _ := http.NewRequest("GET", "http://"+p.addr+path, nil)
req.Header.Set("Authorization", "Bearer "+p.tok)
resp, err := http.DefaultClient.Do(req)
if err != nil {
p.t.Fatal(err)
}
defer resp.Body.Close()
b, _ := io.ReadAll(resp.Body)
return resp.StatusCode, b
}
func (p *hubProc) json(path string, v any) {
p.t.Helper()
code, b := p.get(path)
if code != 200 {
p.t.Fatalf("%s: %d %s", path, code, b)
}
if err := json.Unmarshal(b, v); err != nil {
p.t.Fatal(err)
}
}
func (p *hubProc) send(method, path string, body any) (int, []byte) {
b, _ := json.Marshal(body)
req, _ := http.NewRequest(method, "http://"+p.addr+path, bytes.NewReader(b))
req.Header.Set("Authorization", "Bearer "+p.tok)
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
p.t.Fatal(err)
}
defer resp.Body.Close()
out, _ := io.ReadAll(resp.Body)
return resp.StatusCode, out
}
func waitFor(t *testing.T, what string, d time.Duration, f func() bool) {
t.Helper()
end := time.Now().Add(d)
for time.Now().Before(end) {
if f() {
return
}
time.Sleep(50 * time.Millisecond)
}
t.Fatalf("timeout: %s", what)
}
type probe struct {
name, dir, traefik, auth, f2b, egress, decisions, unban string
cancel context.CancelFunc
done chan error
}
func newProbe(t *testing.T, name string) *probe {
d := t.TempDir()
p := &probe{name: name, dir: d, traefik: filepath.Join(d, "access.log"), auth: filepath.Join(d, "auth.log"), f2b: filepath.Join(d, "f2b.log"),
egress: filepath.Join(d, "egress.log"), decisions: filepath.Join(d, "enf", "decisions.log"), unban: filepath.Join(d, "enf", "unban.log")}
os.MkdirAll(filepath.Join(d, "enf"), 0o755)
for _, f := range []string{p.traefik, p.auth, p.f2b, p.egress} {
os.WriteFile(f, nil, 0o644)
}
return p
}
func (p *probe) run(t *testing.T, hubURL, token string, spool int64) {
ctx, cancel := context.WithCancel(context.Background())
p.cancel, p.done = cancel, make(chan error, 1)
c := probeagent.Config{Hub: hubURL, Name: p.name, Token: token, StateDir: filepath.Join(p.dir, "state"), SpoolMax: spool,
Paths: map[string]string{wire.SrcTraefik: p.traefik, wire.SrcAuth: p.auth, wire.SrcFail2ban: p.f2b, wire.SrcEgress: p.egress},
DecisionsLog: p.decisions, UnbanLog: p.unban, Location: &wire.Location{Lat: -23.5, Lon: -46.6, Label: p.name}, Version: "test"}
go func() { p.done <- probeagent.Run(ctx, c, quiet) }()
t.Cleanup(p.stop)
}
func (p *probe) stop() {
if p.cancel != nil {
p.cancel()
select {
case <-p.done:
case <-time.After(5 * time.Second):
}
p.cancel = nil
}
}
func appendTo(t *testing.T, path, text string) {
f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0o644)
if err != nil {
t.Fatal(err)
}
defer f.Close()
f.WriteString(text)
}
func traefikLine(ip string, i int, status int, path string) string {
ua := "Mozilla/5.0"
if status == 404 { // an attack: path traversal from a scanner
ua, path = "nuclei", "/index.php?file=../../etc/passwd&x="
}
return fmt.Sprintf(`{"ClientHost":"%s","DownstreamStatus":%d,"RequestHost":"example.org","RequestMethod":"GET","RequestPath":"%s?n=%d","StartUTC":"%s","request_User-Agent":"%s"}`+"\n",
ip, status, path, i, time.Now().UTC().Format(time.RFC3339Nano), ua)
}
type summary struct {
Host string `json:"host"`
Totals struct {
Requests uint64 `json:"requests"`
} `json:"totals"`
Hosts []struct {
Name string `json:"name"`
Location *struct {
Label string `json:"label"`
} `json:"location"`
} `json:"hosts"`
}
func requests(t *testing.T, p *hubProc, host string) uint64 {
var s summary
p.json("/api/v1/summary?range=24h&host="+host, &s)
return s.Totals.Requests
}
type probesResp struct {
Probes []struct {
Name string `json:"name"`
Connected bool `json:"connected"`
Dropped uint64 `json:"dropped"`
Sources []wire.SourceStatus `json:"sources"`
Location *wire.Location `json:"location"`
LastLine int64 `json:"last_line"`
} `json:"probes"`
}
func TestTwoProbesEndToEnd(t *testing.T) {
dir := t.TempDir()
hp := &hubProc{t: t, tok: randTok(), addr: newAddr(t), cfg: cfgFor(dir, func(c *app.Config) { c.Enforce = "on"; c.EnforceShare = "off" })}
hp.start()
defer func() { hp.stop() }()
url := "http://" + hp.addr
// create the probes through the admin API (token shown once)
tokens := map[string]string{}
for _, n := range []string{"oracle", "hostinger"} {
code, b := hp.send("POST", "/api/v1/probes", map[string]string{"name": n})
var o struct{ Name, Token string }
if code != 201 || json.Unmarshal(b, &o) != nil || !strings.HasPrefix(o.Token, "urp_") || len(o.Token) != 47 {
t.Fatalf("create %s: %d %s", n, code, b)
}
tokens[n] = o.Token
}
if code, _ := hp.send("POST", "/api/v1/probes", map[string]string{"name": "oracle"}); code != 409 {
t.Fatalf("duplicate probe: %d", code)
}
// probes.json holds hashes only
raw, err := os.ReadFile(filepath.Join(dir, "probes.json"))
if err != nil {
t.Fatal(err)
}
for _, tk := range tokens {
if strings.Contains(string(raw), tk) {
t.Fatal("probes.json contains a token")
}
}
if fi, _ := os.Stat(filepath.Join(dir, "probes.json")); fi.Mode().Perm() != 0o600 {
t.Fatalf("probes.json mode %v", fi.Mode())
}
po, ph := newProbe(t, "oracle"), newProbe(t, "hostinger")
po.run(t, url, tokens["oracle"], 0)
ph.run(t, url, tokens["hostinger"], 0)
waitFor(t, "both probes connected", 15*time.Second, func() bool {
var r probesResp
hp.json("/api/v1/probes", &r)
n := 0
for _, x := range r.Probes {
if x.Connected {
n++
}
}
return n == 2
})
// every source of both hosts
for i := 0; i < 20; i++ {
appendTo(t, po.traefik, traefikLine("45.94.31.7", i, 404, "/wp-login.php"))
}
for i := 0; i < 7; i++ {
appendTo(t, ph.traefik, traefikLine("45.94.31.9", i, 404, "/wp-login.php"))
}
appendTo(t, ph.auth, time.Now().UTC().Format("2006-01-02T15:04:05.000000+00:00")+" hostinger sshd[123]: Failed password for root from 45.94.31.11 port 22 ssh2\n")
appendTo(t, ph.f2b, time.Now().Format("2006-01-02 15:04:05,000")+" fail2ban.actions [1]: NOTICE [sshd] Ban 45.94.31.11\n")
appendTo(t, ph.egress, time.Now().UTC().Format("2006-01-02T15:04:05+00:00")+" hostinger kernel: URUTAU-EGRESS: IN=br-1 OUT=enp0s6 SRC=10.0.3.5 DST=93.184.216.34 PROTO=TCP SPT=40000 DPT=443 SYN\n")
waitFor(t, "events in the right node", 15*time.Second, func() bool {
return requests(t, hp, "oracle") >= 20 && requests(t, hp, "hostinger") >= 7
})
if got := requests(t, hp, "oracle"); got != 20 {
t.Fatalf("oracle requests %d", got)
}
if got := requests(t, hp, "hostinger"); got != 7 {
t.Fatalf("hostinger requests %d", got)
}
var s summary
hp.json("/api/v1/summary?range=24h&host=hostinger", &s)
if s.Host != "hostinger" {
t.Fatalf("host %q", s.Host)
}
// per-node data directories
if _, err := os.Stat(filepath.Join(dir, "probes", "hostinger")); err != nil {
t.Fatal(err)
}
// live: the events carry the location of their probe
waitFor(t, "live location", 10*time.Second, func() bool {
var r struct {
Events []struct {
Host string `json:"host"`
Dst *struct {
Label string `json:"label"`
} `json:"dst"`
} `json:"events"`
}
code, b := hp.get("/api/v1/live/recent?n=100")
if code != 200 || json.Unmarshal(b, &r) != nil {
// the payload may be a bare array
var arr []struct {
Host string `json:"host"`
Dst *struct {
Label string `json:"label"`
} `json:"dst"`
}
if json.Unmarshal(b, &arr) != nil {
return false
}
for _, e := range arr {
if e.Host == "hostinger" && e.Dst != nil && e.Dst.Label == "hostinger" {
return true
}
}
return false
}
for _, e := range r.Events {
if e.Host == "hostinger" && e.Dst != nil && e.Dst.Label == "hostinger" {
return true
}
}
return false
})
// enforce: the decision reaches decisions.log of the right probe only
waitFor(t, "decision on the probe of the attacked host", 20*time.Second, func() bool {
b, _ := os.ReadFile(ph.decisions)
return strings.Contains(string(b), "ip=45.94.31.9") || strings.Contains(string(b), "ip=45.94.31.7")
})
if b, _ := os.ReadFile(po.decisions); strings.Contains(string(b), "45.94.31.9") {
t.Fatal("a decision of hostinger leaked to the oracle probe")
}
// unban through the API for one host
if code, b := hp.send("POST", "/api/v1/enforce/unban", map[string]any{"ip": "203.0.113.50", "allow_s": 3600, "host": "hostinger"}); code != 200 {
t.Fatalf("unban: %d %s", code, b)
}
waitFor(t, "unban.log", 10*time.Second, func() bool {
b, _ := os.ReadFile(ph.unban)
return strings.Contains(string(b), "unban ip=203.0.113.50 allow=3600")
})
if _, err := os.Stat(po.unban); err == nil {
t.Fatal("the unban of one host reached the other probe")
}
// hub down: 1000 lines written meanwhile arrive exactly once after the restart
before := requests(t, hp, "oracle")
hp.stop()
var sb strings.Builder
for i := 0; i < 1000; i++ {
sb.WriteString(traefikLine(fmt.Sprintf("45.94.32.%d", i%200+1), 1000+i, 200, "/page"))
}
appendTo(t, po.traefik, sb.String())
time.Sleep(300 * time.Millisecond)
hp.start()
waitFor(t, "1000 lines after the restart", 30*time.Second, func() bool { return requests(t, hp, "oracle") >= before+1000 })
time.Sleep(500 * time.Millisecond)
if got := requests(t, hp, "oracle"); got != before+1000 {
t.Fatalf("after the restart: %d requests, want %d (no gap, no duplicate)", got, before+1000)
}
// revoke: 401 afterwards, data stays
po.stop()
if code, _ := hp.send("DELETE", "/api/v1/probes/oracle", nil); code != 200 {
t.Fatalf("revoke: %d", code)
}
req, _ := http.NewRequest("POST", url+wire.PathHello, strings.NewReader(`{"proto":1,"name":"oracle"}`))
req.Header.Set("Authorization", "Bearer "+tokens["oracle"])
req.Header.Set(wire.HeaderProbe, "oracle")
resp, err := http.DefaultClient.Do(req)
if err != nil || resp.StatusCode != 401 {
t.Fatalf("revoked token: %v %v", resp, err)
}
resp.Body.Close()
if got := requests(t, hp, "oracle"); got != before+1000 {
t.Fatalf("data lost after revoke: %d", got)
}
// the old peer routes are gone
for _, p := range []string{"/api/v1/peer/export", "/api/v1/peer/stream", "/api/v1/peer/decisions"} {
if code, _ := hp.get(p); code != 404 {
t.Errorf("%s: %d, want 404", p, code)
}
}
}
func TestEnforceShareReachesBothProbes(t *testing.T) {
dir := t.TempDir()
hp := &hubProc{t: t, tok: randTok(), addr: newAddr(t), cfg: cfgFor(dir, func(c *app.Config) { c.Enforce = "on"; c.EnforceShare = "on" })}
hp.start()
defer hp.stop()
url := "http://" + hp.addr
po, ph := newProbe(t, "oracle"), newProbe(t, "hostinger")
for _, p := range []*probe{po, ph} {
tok, err := hp.hub.Mgr.Create(p.name)
if err != nil {
t.Fatal(err)
}
p.run(t, url, tok, 0)
}
for i := 0; i < 30; i++ {
appendTo(t, ph.traefik, traefikLine("45.94.31.9", i, 404, "/wp-login.php"))
}
waitFor(t, "decision on the origin probe", 20*time.Second, func() bool {
b, _ := os.ReadFile(ph.decisions)
return strings.Contains(string(b), "ip=45.94.31.9")
})
// the sharing loop runs every 30 s: relay now through the engines
for _, n := range hp.hub.Mgr.Nodes() {
_ = n
}
// the relay runs every 30 s; the receiver applies its own policy, and an
// address its own probe never saw attacking is first held "peer_unconfirmed"
waitFor(t, "shared decision on the other probe", 60*time.Second, func() bool {
if b, _ := os.ReadFile(po.decisions); strings.Contains(string(b), "src=peer:hostinger") {
return true
}
return hp.hub.Primary.Enf.Report(0).Counts.Skipped["peer_unconfirmed"] > 0
})
}
func TestSpoolOverflowIsReportedAsDropped(t *testing.T) {
dir := t.TempDir()
hp := &hubProc{t: t, tok: randTok(), addr: newAddr(t), cfg: cfgFor(dir, nil)}
// the hub is not up yet: create the registry offline and start the probe against a dead address
hp.start()
tok, _ := hp.hub.Mgr.Create("hostinger")
hp.stop()
p := newProbe(t, "hostinger")
p.run(t, "http://"+hp.addr, tok, 4096)
for round := 0; round < 12; round++ {
var sb strings.Builder
for i := 0; i < 100; i++ {
sb.WriteString(traefikLine("45.94.33.1", round*100+i, 200, "/spool"))
}
appendTo(t, p.traefik, sb.String())
time.Sleep(1200 * time.Millisecond)
}
hp.start()
defer hp.stop()
waitFor(t, "dropped reported", 30*time.Second, func() bool {
var r probesResp
hp.json("/api/v1/probes", &r)
for _, x := range r.Probes {
if x.Name == "hostinger" && x.Dropped > 0 {
return true
}
}
return false
})
}
func TestIngestLimitsAndDedup(t *testing.T) {
dir := t.TempDir()
hp := &hubProc{t: t, tok: randTok(), addr: newAddr(t), cfg: cfgFor(dir, nil)}
hp.start()
defer hp.stop()
tok, _ := hp.hub.Mgr.Create("hostinger")
do := func(path string, body []byte, gz bool) int {
req, _ := http.NewRequest("POST", "http://"+hp.addr+path, bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer "+tok)
req.Header.Set(wire.HeaderProbe, "hostinger")
if gz {
req.Header.Set("Content-Encoding", "gzip")
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
io.Copy(io.Discard, resp.Body)
return resp.StatusCode
}
push := func(b wire.Batch) (int, wire.PushResp) {
raw, _ := json.Marshal(b)
req, _ := http.NewRequest("POST", "http://"+hp.addr+wire.PathPush, bytes.NewReader(raw))
req.Header.Set("Authorization", "Bearer "+tok)
req.Header.Set(wire.HeaderProbe, "hostinger")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
var pr wire.PushResp
json.NewDecoder(resp.Body).Decode(&pr)
return resp.StatusCode, pr
}
line := func(i int, inode uint64, off int64) wire.Line {
return wire.Line{Src: wire.SrcTraefik, Text: strings.TrimSpace(traefikLine("45.94.34.1", i, 200, "/d")), End: wire.Pos{Inode: inode, Offset: off}}
}
if code, r := push(wire.Batch{Seq: 1, Lines: []wire.Line{line(1, 7, 100), line(2, 7, 200)}}); code != 200 || r.Accepted != 2 {
t.Fatalf("first: %d %+v", code, r)
}
// same positions again under a new seq: duplicates by offset
if code, r := push(wire.Batch{Seq: 2, Lines: []wire.Line{line(1, 7, 100), line(2, 7, 200), line(3, 7, 300)}}); code != 200 || r.Dup != 2 || r.Accepted != 1 {
t.Fatalf("dedup by offset: %d %+v", code, r)
}
// a new inode with a smaller offset is new data (rotation)
if code, r := push(wire.Batch{Seq: 3, Lines: []wire.Line{line(4, 8, 50)}}); code != 200 || r.Accepted != 1 {
t.Fatalf("new inode: %d %+v", code, r)
}
// the same seq again is acknowledged without applying
if code, r := push(wire.Batch{Seq: 3, Lines: []wire.Line{line(5, 8, 500)}}); code != 200 || r.Ack != 3 || r.Accepted != 0 {
t.Fatalf("idempotent seq: %d %+v", code, r)
}
// limits
big := make([]wire.Line, wire.MaxLines+1)
for i := range big {
big[i] = wire.Line{Src: wire.SrcTraefik, Text: "x", End: wire.Pos{Inode: 9, Offset: int64(i + 1)}}
}
if code, _ := push(wire.Batch{Seq: 10, Lines: big}); code != 400 {
t.Fatalf("too many lines: %d", code)
}
if code, _ := push(wire.Batch{Seq: 11, Lines: []wire.Line{{Src: "bogus", Text: "x"}}}); code != 400 {
t.Fatalf("invalid source: %d", code)
}
if code := do(wire.PathPush, bytes.Repeat([]byte("a"), wire.MaxBodyBytes+10), false); code != 413 {
t.Fatalf("raw body too big: %d", code)
}
var zb bytes.Buffer
zw := gzip.NewWriter(&zb)
zw.Write(bytes.Repeat([]byte(" "), wire.MaxInflated+10))
zw.Close()
if code := do(wire.PathPush, zb.Bytes(), true); code != 413 {
t.Fatalf("inflated body too big: %d", code)
}
// hello returns the committed offsets
hb, _ := json.Marshal(wire.Hello{Proto: wire.Proto, Name: "hostinger", Version: "t"})
req, _ := http.NewRequest("POST", "http://"+hp.addr+wire.PathHello, bytes.NewReader(hb))
req.Header.Set("Authorization", "Bearer "+tok)
req.Header.Set(wire.HeaderProbe, "hostinger")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
var hr wire.HelloResp
json.NewDecoder(resp.Body).Decode(&hr)
resp.Body.Close()
if hr.Offsets[wire.SrcTraefik].Inode != 8 || hr.Offsets[wire.SrcTraefik].Offset != 50 {
t.Fatalf("hello offsets: %+v", hr.Offsets)
}
// incompatible protocol
hb, _ = json.Marshal(wire.Hello{Proto: 99, Name: "hostinger"})
if code := do(wire.PathHello, hb, false); code != 409 {
t.Fatalf("protocol: %d", code)
}
}
func TestOldPeerVariablesRefuseToStart(t *testing.T) {
t.Setenv("URUTAU_PEERS", "hostinger=https://x.example.org")
t.Setenv("URUTAU_TOKEN", randTok())
c := cfgFor(t.TempDir(), func(c *app.Config) { c.NoAuth = false })
err := app.Serve(c)
if err == nil || !strings.Contains(err.Error(), "URUTAU_PEERS") || !strings.Contains(err.Error(), "migration-2.0") {
t.Fatalf("Serve with URUTAU_PEERS: %v", err)
}
}
// copyTree copies a directory (fixtures are read-only inputs).
func copyTree(t *testing.T, from, to string) {
filepath.Walk(from, func(p string, info os.FileInfo, err error) error {
if err != nil {
return err
}
rel, _ := filepath.Rel(from, p)
dst := filepath.Join(to, rel)
if info.IsDir() {
return os.MkdirAll(dst, 0o755)
}
b, err := os.ReadFile(p)
if err != nil {
return err
}
return os.WriteFile(dst, b, 0o644)
})
}
var fixture = filepath.Join("..", "app", "testdata", "hostinger-1.6")
func TestPrimaryLoads16DataDirWithSameCounts(t *testing.T) {
if _, err := os.Stat(fixture); err != nil {
t.Skip("fixture of the 1.6 data directory missing")
}
dir := t.TempDir()
copyTree(t, fixture, dir)
want, err := app.CountDir(dir)
if err != nil {
t.Fatal(err)
}
hp := &hubProc{t: t, tok: randTok(), addr: newAddr(t), cfg: cfgFor(dir, func(c *app.Config) { c.Name = "hostinger" })}
hp.start()
defer hp.stop()
var ips struct {
Total int `json:"total"`
}
hp.json("/api/v1/ips?range=30d&per=200", &ips)
if want.IPs == 0 || hp.hub.Primary.St.IPCount() != want.IPs {
t.Fatalf("IPs: node %d, directory %d", hp.hub.Primary.St.IPCount(), want.IPs)
}
var inc struct {
Total int `json:"total"`
}
hp.json("/api/v1/incidents?per_page=100", &inc)
if inc.Total != want.Incidents {
t.Fatalf("incidents: api %d, directory %d", inc.Total, want.Incidents)
}
}
func TestImportedHostIncidentWithComments(t *testing.T) {
if _, err := os.Stat(fixture); err != nil {
t.Skip("fixture of the 1.6 data directory missing")
}
dir := t.TempDir()
rep, err := app.Import(fixture, dir, "hostinger", app.ImportOptions{})
if err != nil {
t.Fatal(err)
}
hp := &hubProc{t: t, tok: randTok(), addr: newAddr(t), cfg: cfgFor(dir, nil)}
hp.start()
defer hp.stop()
for _, path := range []string{"/api/v1/incidents/hostinger%2FINC-2", "/api/v1/incidents/hostinger/INC-2", "/api/v1/incidents/INC-2?host=hostinger"} {
var tk struct {
ID string `json:"id"`
Host string `json:"host"`
Comments []any `json:"comments"`
}
hp.json(path, &tk)
if tk.ID != "hostinger/INC-2" || tk.Host != "hostinger" || len(tk.Comments) != 2 {
t.Fatalf("%s: %+v", path, tk)
}
}
// the list qualifies the ids and counts the imported tickets
var list struct {
Total int `json:"total"`
Items []struct {
ID string `json:"id"`
} `json:"items"`
}
hp.json("/api/v1/incidents?host=hostinger", &list)
if list.Total != rep.Incidents || len(list.Items) == 0 || !strings.HasPrefix(list.Items[0].ID, "hostinger/INC-") {
t.Fatalf("list: %+v (imported %d)", list, rep.Incidents)
}
// and the node serves the imported IPs under its own host
var s summary
hp.json("/api/v1/summary?range=30d&host=hostinger", &s)
if s.Host != "hostinger" {
t.Fatalf("summary host %q", s.Host)
}
var mu sync.Mutex
mu.Lock()
mu.Unlock()
}
+305
View File
@@ -0,0 +1,305 @@
package hub
import (
"fmt"
"log/slog"
"os"
"path/filepath"
"sort"
"sync"
"sync/atomic"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
// Node is one probe's data seen from the ingest layer (implemented by the app).
type Node interface {
Name() string
// Ready is false while the node still loads its snapshot.
Ready() bool
// Offsets are the hub-committed positions, keyed by wire source name.
Offsets() map[string]wire.Pos
// Apply commits a batch under the node's commit mutex.
Apply(b wire.Batch) (accepted, dup int)
// Hello tells the node what the probe announced (sources, location).
Hello(h wire.Hello)
// Queue is the command queue of the node.
Queue() *CmdQueue
// SetStatus hands over the last status the probe reported.
SetStatus(st wire.Status, connected bool)
// SetLocation changes the location events of this node point to.
SetLocation(l *wire.Location)
}
// Factory builds the node of a probe.
type Factory func(name string, primary bool, rec Probe) (Node, error)
// Update is the body of PUT /api/v1/probes/{name}.
type Update struct {
Location *wire.Location `json:"location"`
Egress Egress `json:"egress"`
}
// ProbeInfo is one row of GET /api/v1/probes.
type ProbeInfo struct {
Name string `json:"name"`
Primary bool `json:"primary"`
Registered bool `json:"registered"`
Revoked bool `json:"revoked"`
Created int64 `json:"created,omitempty"`
Connected bool `json:"connected"`
LastSeen int64 `json:"last_seen"`
LastLine int64 `json:"last_line"`
LagMS int64 `json:"lag_ms"`
Version string `json:"version,omitempty"`
Hostname string `json:"hostname,omitempty"`
Dropped uint64 `json:"dropped"`
Spool int64 `json:"spool"`
SpoolFiles int `json:"spool_files"`
CmdPending int `json:"cmd_pending"`
CmdDropped uint64 `json:"cmd_dropped"`
CmdErrors uint64 `json:"cmd_errors"`
Uptime int64 `json:"uptime"`
RSS uint64 `json:"rss"`
Sources []wire.SourceStatus `json:"sources"`
Location *wire.Location `json:"location,omitempty"`
Egress Egress `json:"egress"`
}
type conn struct {
mu sync.Mutex
lastSeen int64
lastLine int64
lagMS int64
version string
hostname string
status wire.Status
ack uint64
busy atomic.Bool
}
// Manager owns the registry and the nodes.
type Manager struct {
Dir string // data directory (primary node lives in its root)
Primary string
Version string
Reg *Registry
Make Factory
Log *slog.Logger
Now func() time.Time
mu sync.Mutex
nodes map[string]Node
conns map[string]*conn
infl atomic.Int32
}
// NewManager opens probes.json in dir and returns a manager; call Load to
// create the nodes.
func NewManager(dir, primary, version string, mk Factory, log *slog.Logger) (*Manager, error) {
reg, err := OpenRegistry(filepath.Join(dir, "probes.json"))
if err != nil {
return nil, err
}
if log == nil {
log = slog.Default()
}
return &Manager{Dir: dir, Primary: primary, Version: version, Reg: reg, Make: mk, Log: log, Now: time.Now,
nodes: map[string]Node{}, conns: map[string]*conn{}}, nil
}
// Load creates the primary node, one node per registered probe and one per
// directory in probes/ (imported data), so every data set is served at once.
func (m *Manager) Load() error {
names := map[string]bool{m.Primary: true}
for _, p := range m.Reg.List() {
names[p.Name] = true
}
if ents, err := os.ReadDir(filepath.Join(m.Dir, "probes")); err == nil {
for _, e := range ents {
if e.IsDir() && wire.ValidName(e.Name()) {
names[e.Name()] = true
}
}
}
list := make([]string, 0, len(names))
for n := range names {
list = append(list, n)
}
sort.Strings(list)
for _, n := range list {
if _, err := m.Ensure(n); err != nil {
return fmt.Errorf("node %s: %w", n, err)
}
}
return nil
}
// Ensure returns the node of name, creating it on first use.
func (m *Manager) Ensure(name string) (Node, error) {
m.mu.Lock()
defer m.mu.Unlock()
if n, ok := m.nodes[name]; ok {
return n, nil
}
if !wire.ValidName(name) {
return nil, ErrName
}
rec, _ := m.Reg.Get(name)
n, err := m.Make(name, name == m.Primary, rec)
if err != nil {
return nil, err
}
m.nodes[name] = n
if m.conns[name] == nil {
m.conns[name] = &conn{}
}
return n, nil
}
// Get returns an existing node.
func (m *Manager) Get(name string) Node {
m.mu.Lock()
defer m.mu.Unlock()
return m.nodes[name]
}
// Nodes lists the nodes sorted by name, the primary first.
func (m *Manager) Nodes() []Node {
m.mu.Lock()
defer m.mu.Unlock()
out := make([]Node, 0, len(m.nodes))
for _, n := range m.nodes {
out = append(out, n)
}
sort.Slice(out, func(i, j int) bool {
a, b := out[i].Name(), out[j].Name()
if (a == m.Primary) != (b == m.Primary) {
return a == m.Primary
}
return a < b
})
return out
}
func (m *Manager) conn(name string) *conn {
m.mu.Lock()
defer m.mu.Unlock()
c := m.conns[name]
if c == nil {
c = &conn{}
m.conns[name] = c
}
return c
}
// Connected reports whether the probe pushed within OfflineSec.
func (m *Manager) Connected(name string) bool {
c := m.conn(name)
c.mu.Lock()
defer c.mu.Unlock()
return c.lastSeen > 0 && m.Now().Unix()-c.lastSeen <= wire.OfflineSec
}
// Info describes one probe.
func (m *Manager) Info(name string) (ProbeInfo, bool) {
n := m.Get(name)
rec, reg := m.Reg.Get(name)
if n == nil && !reg {
return ProbeInfo{}, false
}
c := m.conn(name)
c.mu.Lock()
st := c.status
in := ProbeInfo{Name: name, Primary: name == m.Primary, Registered: reg, Revoked: rec.Revoked, Created: rec.Created,
LastSeen: c.lastSeen, LastLine: c.lastLine, LagMS: c.lagMS, Version: c.version, Hostname: c.hostname,
Dropped: st.Dropped, Spool: st.SpoolBytes, SpoolFiles: st.SpoolFiles, CmdErrors: st.CmdErrors,
Uptime: st.UptimeSec, RSS: st.RSSBytes, Sources: append([]wire.SourceStatus{}, st.Sources...), Location: rec.Location, Egress: rec.Egress}
c.mu.Unlock()
in.Connected = m.Connected(name)
if n != nil {
if q := n.Queue(); q != nil {
in.CmdPending, in.CmdDropped = q.Pending(0), q.Dropped()
}
}
return in, true
}
// List describes every probe (registered ones and nodes without a record, such
// as the primary or imported data).
func (m *Manager) List() []ProbeInfo {
names := map[string]bool{}
for _, n := range m.Nodes() {
names[n.Name()] = true
}
for _, p := range m.Reg.List() {
names[p.Name] = true
}
var out []ProbeInfo
for n := range names {
if in, ok := m.Info(n); ok {
out = append(out, in)
}
}
sort.Slice(out, func(i, j int) bool {
if out[i].Primary != out[j].Primary {
return out[i].Primary
}
return out[i].Name < out[j].Name
})
return out
}
// Create registers a probe, returning its token (shown once).
func (m *Manager) Create(name string) (string, error) {
tok, err := m.Reg.Create(name)
if err != nil {
return "", err
}
if _, err := m.Ensure(name); err != nil {
return "", err
}
return tok, nil
}
// Revoke disables the token of a probe and drops its connection state; the
// data stays.
func (m *Manager) Revoke(name string) error {
if err := m.Reg.Revoke(name); err != nil {
return err
}
c := m.conn(name)
c.mu.Lock()
c.lastSeen = 0
c.mu.Unlock()
return nil
}
// UpdateProbe stores the location and egress configuration and applies the location now.
func (m *Manager) UpdateProbe(name string, u Update) error {
if u.Location != nil {
if l := u.Location; l.Lat < -90 || l.Lat > 90 || l.Lon < -180 || l.Lon > 180 || len(l.Label) > 80 {
return fmt.Errorf("invalid location")
}
}
if err := m.Reg.Update(name, u.Location, u.Egress); err != nil {
return err
}
if n := m.Get(name); n != nil {
n.SetLocation(u.Location)
if r, ok := n.(interface{ ResetEgress(Egress) }); ok {
r.ResetEgress(u.Egress)
}
}
return nil
}
// Close flushes the command queues.
func (m *Manager) Close() {
for _, n := range m.Nodes() {
if q := n.Queue(); q != nil {
q.Close()
}
}
}
+214
View File
@@ -0,0 +1,214 @@
// Package hub is the server side of the probe protocol: the registry of
// probes (probes.json), the per-node command queue and the ingest handlers.
package hub
import (
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
// TokenPrefix starts every probe token.
const TokenPrefix = "urp_"
// Egress is the per-probe configuration of the egress analysis.
type Egress struct {
Workloads string `json:"workloads,omitempty"`
Resolvers string `json:"resolvers,omitempty"`
Allow string `json:"allow,omitempty"`
}
// Probe is one entry of probes.json. The token is never stored, only its hash.
type Probe struct {
Name string `json:"name"`
TokenSHA256 string `json:"token_sha256"`
Created int64 `json:"created"`
Revoked bool `json:"revoked"`
Location *wire.Location `json:"location,omitempty"`
Egress Egress `json:"egress"`
}
// Errors of the registry.
var (
ErrExists = errors.New("probe already exists")
ErrNotFound = errors.New("probe not found")
ErrName = errors.New("invalid probe name (a-z, 0-9 and -, at most 32 characters)")
)
// Registry is probes.json.
type Registry struct {
mu sync.Mutex
path string
probes map[string]*Probe
}
type regFile struct {
Probes []*Probe `json:"probes"`
}
// OpenRegistry loads path (a missing file is an empty registry).
func OpenRegistry(path string) (*Registry, error) {
r := &Registry{path: path, probes: map[string]*Probe{}}
b, err := os.ReadFile(path)
if errors.Is(err, os.ErrNotExist) {
return r, nil
}
if err != nil {
return nil, err
}
var f regFile
if err := json.Unmarshal(b, &f); err != nil {
return nil, fmt.Errorf("%s: %w", path, err)
}
for _, p := range f.Probes {
if p != nil && wire.ValidName(p.Name) {
r.probes[p.Name] = p
}
}
return r, nil
}
// save writes the file atomically with mode 0600; the caller holds mu.
func (r *Registry) save() error {
list := make([]*Probe, 0, len(r.probes))
for _, p := range r.probes {
list = append(list, p)
}
sort.Slice(list, func(i, j int) bool { return list[i].Name < list[j].Name })
b, err := json.MarshalIndent(regFile{Probes: list}, "", " ")
if err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(r.path), 0o700); err != nil {
return err
}
tmp := r.path + ".tmp"
if err := os.WriteFile(tmp, b, 0o600); err != nil {
return err
}
if err := os.Chmod(tmp, 0o600); err != nil {
return err
}
return os.Rename(tmp, r.path)
}
// HashToken is the hex sha256 of a token.
func HashToken(tok string) string {
h := sha256.Sum256([]byte(tok))
return hex.EncodeToString(h[:])
}
// NewToken returns a fresh token: "urp_" + 43 base64url characters.
func NewToken() (string, error) {
var b [32]byte
if _, err := rand.Read(b[:]); err != nil {
return "", err
}
return TokenPrefix + base64.RawURLEncoding.EncodeToString(b[:]), nil
}
// Create registers a probe and returns its token, shown only once. Creating a
// probe that was revoked replaces its token and makes it active again.
func (r *Registry) Create(name string) (string, error) {
if !wire.ValidName(name) || name == "all" {
return "", ErrName
}
tok, err := NewToken()
if err != nil {
return "", err
}
r.mu.Lock()
defer r.mu.Unlock()
if p, ok := r.probes[name]; ok && !p.Revoked {
return "", ErrExists
}
p := r.probes[name]
if p == nil {
p = &Probe{Name: name, Created: time.Now().Unix()}
r.probes[name] = p
}
p.TokenSHA256, p.Revoked = HashToken(tok), false
if err := r.save(); err != nil {
delete(r.probes, name)
return "", err
}
return tok, nil
}
// Revoke disables the token of a probe; its data stays.
func (r *Registry) Revoke(name string) error {
r.mu.Lock()
defer r.mu.Unlock()
p, ok := r.probes[name]
if !ok {
return ErrNotFound
}
p.Revoked = true
return r.save()
}
// Update replaces the location and the egress configuration of a probe.
func (r *Registry) Update(name string, loc *wire.Location, eg Egress) error {
r.mu.Lock()
defer r.mu.Unlock()
p, ok := r.probes[name]
if !ok {
return ErrNotFound
}
p.Location, p.Egress = loc, eg
return r.save()
}
// Verify checks a token in constant time; revoked and unknown probes fail.
func (r *Registry) Verify(name, token string) bool {
r.mu.Lock()
p := r.probes[name]
var want string
revoked := true
if p != nil {
want, revoked = p.TokenSHA256, p.Revoked
}
r.mu.Unlock()
if want == "" {
want = strings.Repeat("0", 64)
}
got := HashToken(token)
ok := subtle.ConstantTimeCompare([]byte(got), []byte(want)) == 1
return ok && !revoked
}
// Get returns a copy of the entry.
func (r *Registry) Get(name string) (Probe, bool) {
r.mu.Lock()
defer r.mu.Unlock()
p, ok := r.probes[name]
if !ok {
return Probe{}, false
}
return *p, true
}
// List returns every entry sorted by name.
func (r *Registry) List() []Probe {
r.mu.Lock()
defer r.mu.Unlock()
out := make([]Probe, 0, len(r.probes))
for _, p := range r.probes {
out = append(out, *p)
}
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
return out
}
+59
View File
@@ -0,0 +1,59 @@
package hub
import (
"os"
"path/filepath"
"strings"
"testing"
)
func TestRegistryHashOnlyAndRevoke(t *testing.T) {
p := filepath.Join(t.TempDir(), "probes.json")
r, err := OpenRegistry(p)
if err != nil {
t.Fatal(err)
}
tok, err := r.Create("hostinger")
if err != nil || !strings.HasPrefix(tok, "urp_") || len(tok) != 47 {
t.Fatalf("%q %v", tok, err)
}
if b, _ := os.ReadFile(p); strings.Contains(string(b), tok) {
t.Fatal("token stored")
}
if fi, _ := os.Stat(p); fi.Mode().Perm() != 0o600 {
t.Fatal(fi.Mode())
}
if !r.Verify("hostinger", tok) || r.Verify("hostinger", tok+"x") || r.Verify("other", tok) {
t.Fatal("verify")
}
if _, err := r.Create("hostinger"); err != ErrExists {
t.Fatal(err)
}
if _, err := r.Create("All"); err != ErrName {
t.Fatal(err)
}
r.Revoke("hostinger")
if r.Verify("hostinger", tok) {
t.Fatal("revoked token accepted")
}
}
func TestQueuePersistsAndPrunes(t *testing.T) {
p := filepath.Join(t.TempDir(), "commands.json")
q, _ := OpenQueue(p)
line := "2026-11-15T10:00:00Z urutau unban ip=203.0.113.9 allow=60\n"
for i := 0; i < 3; i++ {
if err := q.Enqueue("unban", line); err != nil {
t.Fatal(err)
}
}
if q.Enqueue("unban", "rm -rf /\n") == nil {
t.Fatal("invalid line queued")
}
q.Close()
q2, _ := OpenQueue(p)
defer q2.Close()
if q2.Last() != 3 || q2.Pending(1) != 2 {
t.Fatalf("%d %d", q2.Last(), q2.Pending(1))
}
}
+198
View File
@@ -0,0 +1,198 @@
package probeagent
import (
"bytes"
"compress/gzip"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"math/rand/v2"
"net/http"
"net/url"
"strconv"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
var (
// ErrUnauthorized: the hub rejected the token or the probe name. Fatal.
ErrUnauthorized = errors.New("hub rejected the probe credentials (401)")
// ErrIncompatible: protocol version mismatch (409). Fatal.
ErrIncompatible = errors.New("hub speaks an incompatible protocol version (409)")
)
// retryError asks the caller to wait and retry the same request.
type retryError struct {
after time.Duration
code int
}
func (e *retryError) Error() string {
return fmt.Sprintf("hub busy (%d), retry in %s", e.code, e.after)
}
// rejectError: the hub refused this batch for good (400/413); retrying is pointless.
type rejectError struct{ code int }
func (e *rejectError) Error() string { return fmt.Sprintf("hub rejected the batch (%d)", e.code) }
const gzipOver = 8 << 10
type client struct {
base string
name string
token string
hc *http.Client
gz *gzip.Writer
buf bytes.Buffer
raw bytes.Buffer
}
func newClient(base *url.URL, name, token string, hc *http.Client) *client {
if hc == nil {
hc = &http.Client{}
}
return &client{base: base.String(), name: name, token: token, hc: hc}
}
func (c *client) req(ctx context.Context, method, path string, body io.Reader) (*http.Request, error) {
r, err := http.NewRequestWithContext(ctx, method, c.base+path, body)
if err != nil {
return nil, err
}
r.Header.Set("Authorization", "Bearer "+c.token)
r.Header.Set(wire.HeaderProbe, c.name)
r.Header.Set("User-Agent", "urutau-probe")
return r, nil
}
func retryAfter(h http.Header) time.Duration {
d := 5 * time.Second
if v, err := strconv.Atoi(h.Get("Retry-After")); err == nil && v >= 0 {
d = time.Duration(v) * time.Second
}
return min(d, 2*time.Minute)
}
func statusErr(resp *http.Response) error {
switch {
case resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden:
return ErrUnauthorized
case resp.StatusCode == http.StatusConflict:
return ErrIncompatible
case resp.StatusCode == http.StatusServiceUnavailable || resp.StatusCode == http.StatusTooManyRequests:
return &retryError{retryAfter(resp.Header), resp.StatusCode}
}
return fmt.Errorf("hub answered %d", resp.StatusCode)
}
func (c *client) do(r *http.Request, out any, limit int64) (*http.Response, error) {
resp, err := c.hc.Do(r)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
return resp, statusErr(resp)
}
if out != nil {
if err := json.NewDecoder(io.LimitReader(resp.Body, limit)).Decode(out); err != nil {
return resp, fmt.Errorf("bad hub answer: %w", err)
}
}
return resp, nil
}
func (c *client) hello(ctx context.Context, h wire.Hello) (*wire.HelloResp, error) {
data, _ := json.Marshal(&h)
r, err := c.req(ctx, http.MethodPost, wire.PathHello, bytes.NewReader(data))
if err != nil {
return nil, err
}
r.Header.Set("Content-Type", "application/json")
var out wire.HelloResp
if _, err := c.do(r, &out, 1<<20); err != nil {
return nil, err
}
if out.Offsets == nil {
out.Offsets = map[string]wire.Pos{}
}
return &out, nil
}
func (c *client) push(ctx context.Context, b wire.Batch) (*wire.PushResp, error) {
c.raw.Reset()
if err := json.NewEncoder(&c.raw).Encode(&b); err != nil {
return nil, err
}
data := c.raw.Bytes()
var body io.Reader = bytes.NewReader(data)
gzipped := false
if len(data) > gzipOver {
c.buf.Reset()
if c.gz == nil {
c.gz = gzip.NewWriter(&c.buf)
} else {
c.gz.Reset(&c.buf)
}
if _, err := c.gz.Write(data); err != nil {
return nil, err
}
if err := c.gz.Close(); err != nil {
return nil, err
}
body = bytes.NewReader(c.buf.Bytes())
gzipped = true
}
r, err := c.req(ctx, http.MethodPost, wire.PathPush, body)
if err != nil {
return nil, err
}
r.Header.Set("Content-Type", "application/json")
if gzipped {
r.Header.Set("Content-Encoding", "gzip")
}
var out wire.PushResp
resp, err := c.do(r, &out, 1<<20)
if err != nil {
if resp != nil && (resp.StatusCode == http.StatusBadRequest || resp.StatusCode == http.StatusRequestEntityTooLarge) {
return nil, &rejectError{resp.StatusCode}
}
return nil, err
}
return &out, nil
}
// commands long-polls; the caller's context bounds the wait.
func (c *client) commands(ctx context.Context, after uint64, wait int) (*wire.CmdResp, error) {
q := fmt.Sprintf("%s?after=%d&wait=%d", wire.PathCommands, after, wait)
r, err := c.req(ctx, http.MethodGet, q, nil)
if err != nil {
return nil, err
}
var out wire.CmdResp
if _, err := c.do(r, &out, 8<<20); err != nil {
return nil, err
}
return &out, nil
}
// backoff is the reconnect delay after n consecutive failures (n >= 1):
// 1 s doubling up to 60 s, with +-20% jitter. rnd returns [0,1).
func backoff(n int, rnd func() float64) time.Duration {
if n < 1 {
n = 1
}
d := time.Second
for i := 1; i < n && d < 60*time.Second; i++ {
d *= 2
}
d = min(d, 60*time.Second)
return time.Duration(float64(d) * (0.8 + 0.4*rnd()))
}
func jitterRnd() float64 { return rand.Float64() }
+55
View File
@@ -0,0 +1,55 @@
package probeagent
import (
"os"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
// appendLine appends one validated line to path and syncs it.
func appendLine(path, line string) error {
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o640)
if err != nil {
return err
}
if _, err := f.WriteString(line); err != nil {
f.Close()
return err
}
if err := f.Sync(); err != nil {
f.Close()
return err
}
return f.Close()
}
// applyCmds executes the commands above lastCmd, in order, and persists
// lastCmd after each one. An invalid or unroutable command is counted and
// skipped; it never stops the queue. A write failure stops (the same command
// is delivered again later).
func (p *probe) applyCmds(cmds []wire.Cmd) error {
for _, c := range cmds {
if c.Seq <= p.st.lastCmd() {
continue
}
var path string
switch c.Kind {
case wire.CmdDecision:
path = p.cfg.DecisionsLog
case wire.CmdUnban:
path = p.cfg.UnbanLog
}
if path == "" || !wire.ValidCmdLine(c.Kind, c.Line) {
p.cmdErrors.Add(1)
p.log.Warn("command ignored", "seq", c.Seq, "kind", c.Kind)
} else if err := appendLine(path, c.Line); err != nil {
p.cmdErrors.Add(1)
p.log.Error("command write failed", "seq", c.Seq, "kind", c.Kind)
return err
}
if err := p.st.setLastCmd(c.Seq); err != nil {
return err
}
}
return nil
}
+8
View File
@@ -0,0 +1,8 @@
package probeagent
import (
"os"
"syscall"
)
func inodeFor(fi os.FileInfo) uint64 { return fi.Sys().(*syscall.Stat_t).Ino }
+5
View File
@@ -0,0 +1,5 @@
//go:build !race
package probeagent
const raceOn = false
+435
View File
@@ -0,0 +1,435 @@
// Package probeagent is the Urutau 2 probe: it tails the host logs, spools
// batches on disk and ships them to the hub over HTTPS, and applies the
// enforcement commands the hub queues for it.
package probeagent
import (
"bufio"
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"os"
"path/filepath"
"runtime"
"runtime/debug"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
// Config configures one probe. Paths maps a wire source name to the log file
// to follow; an empty path disables the source.
type Config struct {
Hub, Name, Token, StateDir string
Paths map[string]string
Containers, Resolv string
DecisionsLog, UnbanLog string
SpoolMax int64 // default 64 MiB
Location *wire.Location
Client *http.Client // default: plain client, no overall timeout
// Optional.
Version string // reported in hello (default "dev")
Poll time.Duration // tail poll interval (default 500 ms)
}
type probe struct {
cfg Config
log *slog.Logger
cl *client
st *stateStore
spool *Spool
start time.Time
cancel context.CancelCauseFunc
sources []string
stats []*srcStat
in chan item
notify chan struct{}
wg sync.WaitGroup
flushMS atomic.Int64
cmdErrors atomic.Uint64
fileEvery time.Duration
hbEvery time.Duration
resendFiles chan struct{}
}
func (p *probe) flushEvery() time.Duration {
ms := p.flushMS.Load()
if ms < 10 {
ms = 1000
}
return time.Duration(ms) * time.Millisecond
}
func newProbe(c Config, log *slog.Logger) (*probe, error) {
if log == nil {
log = slog.New(slog.NewTextHandler(os.Stderr, nil))
}
if !wire.ValidName(c.Name) {
return nil, errors.New("invalid probe name")
}
if c.Token == "" {
return nil, errors.New("probe token missing")
}
if c.StateDir == "" {
return nil, errors.New("state dir missing")
}
u, err := wire.CheckHubURL(c.Hub)
if err != nil {
return nil, err
}
if c.SpoolMax <= 0 {
c.SpoolMax = 64 << 20
}
if c.Version == "" {
c.Version = "dev"
}
if err := os.MkdirAll(c.StateDir, 0o700); err != nil {
return nil, err
}
st, err := loadState(c.StateDir)
if err != nil {
return nil, err
}
sp, err := OpenSpool(filepath.Join(c.StateDir, "spool"), c.SpoolMax)
if err != nil {
return nil, err
}
st.raiseSeq(sp.MaxSeq())
p := &probe{
cfg: c, log: log, st: st, spool: sp, start: time.Now(),
cl: newClient(u, c.Name, c.Token, c.Client),
in: make(chan item, chanSize),
notify: make(chan struct{}, 1),
fileEvery: filePollEach,
hbEvery: time.Duration(wire.HeartbeatSec) * time.Second,
resendFiles: make(chan struct{}, 1),
}
for _, s := range wire.Sources {
if c.Paths[s] != "" {
p.sources = append(p.sources, s)
}
}
sort.Strings(p.sources)
return p, nil
}
// Run connects to the hub and ships until ctx is done (nil) or the hub
// refuses the credentials or the protocol version (error).
func Run(ctx context.Context, c Config, log *slog.Logger) error {
p, err := newProbe(c, log)
if err != nil {
return err
}
if os.Getenv("GOMEMLIMIT") == "" {
// soft limit: the probe is a small process, make the GC keep it that way
debug.SetMemoryLimit(8 << 20)
debug.SetGCPercent(30)
}
ctx, cancel := context.WithCancelCause(ctx)
p.cancel = cancel
defer cancel(nil)
resp, err := p.connect(ctx)
if err != nil {
return p.result(ctx, err)
}
p.startTailers(ctx, resp.Offsets)
var cw sync.WaitGroup
cw.Add(1)
go func() { defer cw.Done(); p.collect(ctx) }()
p.wg.Add(3)
go func() { defer p.wg.Done(); p.sender(ctx) }()
go func() { defer p.wg.Done(); p.commandLoop(ctx) }()
go func() { defer p.wg.Done(); p.aliveLoop(ctx) }()
<-ctx.Done()
p.wg.Wait()
cw.Wait() // final flush so positions and spool are consistent
_ = p.st.touch()
return p.result(ctx, nil)
}
func (p *probe) result(ctx context.Context, err error) error {
if cause := context.Cause(ctx); cause != nil && !errors.Is(cause, context.Canceled) {
return cause
}
if err != nil && !errors.Is(err, context.Canceled) {
return err
}
return nil
}
func (p *probe) fail(err error) {
p.log.Error("probe stopping", "err", err)
p.cancel(err)
}
func isFatal(err error) bool {
return errors.Is(err, ErrUnauthorized) || errors.Is(err, ErrIncompatible)
}
func sleep(ctx context.Context, d time.Duration) bool {
t := time.NewTimer(d)
defer t.Stop()
select {
case <-ctx.Done():
return false
case <-t.C:
return true
}
}
// hello performs one handshake and applies its answer.
func (p *probe) hello(ctx context.Context) (*wire.HelloResp, error) {
host, _ := os.Hostname()
s := p.st.snapshot()
h := wire.Hello{
Proto: wire.Proto, Name: p.cfg.Name, Version: p.cfg.Version, Hostname: host,
Sources: append([]string{}, p.sources...), Location: p.cfg.Location,
LastSeq: s.Seq, LastCmd: s.LastCmd,
}
hctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
resp, err := p.cl.hello(hctx, h)
if err != nil {
return nil, err
}
if resp.FlushMS > 0 {
p.flushMS.Store(int64(resp.FlushMS))
}
p.st.raiseSeq(resp.AckSeq)
p.spool.Ack(resp.AckSeq)
select {
case p.resendFiles <- struct{}{}:
default:
}
return resp, nil
}
// connect retries the first hello with backoff.
func (p *probe) connect(ctx context.Context) (*wire.HelloResp, error) {
for n := 1; ; n++ {
resp, err := p.hello(ctx)
if err == nil {
return resp, nil
}
if isFatal(err) {
p.log.Error("hello refused", "err", err)
return nil, err
}
if ctx.Err() != nil {
return nil, ctx.Err()
}
d := p.retryDelay(err, n)
p.log.Warn("hub unreachable, retrying", "err", err, "in", d.Round(time.Millisecond))
if !sleep(ctx, d) {
return nil, ctx.Err()
}
}
}
func (p *probe) retryDelay(err error, n int) time.Duration {
var re *retryError
if errors.As(err, &re) {
return re.after
}
return backoff(n, jitterRnd)
}
// sender ships the spool in order, heartbeating when idle; on any transport
// error it reconnects (hello) with backoff.
func (p *probe) sender(ctx context.Context) {
n := 0
first := true
for ctx.Err() == nil {
if !first {
if _, err := p.hello(ctx); err != nil {
if isFatal(err) {
p.fail(err)
return
}
n++
d := p.retryDelay(err, n)
p.log.Warn("hub unreachable, retrying", "err", err, "in", d.Round(time.Millisecond))
if !sleep(ctx, d) {
return
}
continue
}
}
first = false
n = 0
err := p.session(ctx)
if err == nil || ctx.Err() != nil {
return
}
if isFatal(err) {
p.fail(err)
return
}
n++
d := backoff(n, jitterRnd)
p.log.Warn("connection lost, reconnecting", "err", err, "in", d.Round(time.Millisecond))
if !sleep(ctx, d) {
return
}
}
}
func (p *probe) session(ctx context.Context) error {
hb := time.NewTimer(p.hbEvery)
defer hb.Stop()
resetHB := func() {
if !hb.Stop() {
select {
case <-hb.C:
default:
}
}
hb.Reset(p.hbEvery)
}
for {
b, ok, err := p.spool.Head()
if err != nil {
p.log.Error("spool", "err", err)
continue
}
if !ok {
select {
case <-ctx.Done():
return nil
case <-p.notify:
case <-hb.C:
if _, err := p.cl.push(ctx, wire.Batch{Sent: time.Now().UnixMilli(), Status: p.status()}); err != nil {
if p.handlePushErr(ctx, err, wire.Batch{}) {
continue
}
return err
}
hb.Reset(p.hbEvery)
}
continue
}
b.Sent = time.Now().UnixMilli()
b.Status = p.status()
resp, err := p.cl.push(ctx, b)
if err != nil {
if p.handlePushErr(ctx, err, b) {
continue
}
return err
}
if resp.Ack < b.Seq {
return fmt.Errorf("hub acked %d for batch %d", resp.Ack, b.Seq)
}
p.spool.Ack(resp.Ack)
resetHB()
}
}
// handlePushErr deals with the errors that do not need a reconnect.
func (p *probe) handlePushErr(ctx context.Context, err error, b wire.Batch) bool {
var re *retryError
var rj *rejectError
switch {
case errors.As(err, &re):
p.log.Warn("hub busy, backing off", "code", re.code, "in", re.after)
sleep(ctx, re.after)
return true
case errors.As(err, &rj):
if b.Seq == 0 {
sleep(ctx, 5*time.Second)
return true
}
p.log.Error("hub rejected batch, dropping it", "seq", b.Seq, "code", rj.code, "lines", len(b.Lines))
p.spool.Ack(b.Seq)
p.st.addDropped(uint64(len(b.Lines)))
return true
}
return false
}
func (p *probe) commandLoop(ctx context.Context) {
n := 0
for ctx.Err() == nil {
rctx, cancel := context.WithTimeout(ctx, (wire.MaxWaitSec+15)*time.Second)
resp, err := p.cl.commands(rctx, p.st.lastCmd(), wire.MaxWaitSec)
cancel()
if err != nil {
if ctx.Err() != nil {
return
}
if isFatal(err) {
p.fail(err)
return
}
n++
if !sleep(ctx, p.retryDelay(err, n)) {
return
}
continue
}
n = 0
if err := p.applyCmds(resp.Cmds); err != nil {
if !sleep(ctx, 5*time.Second) {
return
}
}
}
}
func (p *probe) aliveLoop(ctx context.Context) {
t := time.NewTicker(15 * time.Second)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
_ = p.st.touch()
}
}
}
func (p *probe) status() *wire.Status {
b, f := p.spool.Stats()
s := &wire.Status{
UptimeSec: int64(time.Since(p.start).Seconds()), RSSBytes: rss(),
SpoolBytes: b, SpoolFiles: f, Dropped: p.st.dropped(), CmdErrors: p.cmdErrors.Load(),
}
for _, ss := range p.stats {
s.Sources = append(s.Sources, ss.status())
}
return s
}
// rss reads VmRSS from /proc; elsewhere it falls back to what the Go runtime holds.
func rss() uint64 {
if f, err := os.Open("/proc/self/status"); err == nil {
defer f.Close()
sc := bufio.NewScanner(f)
for sc.Scan() {
if v, ok := strings.CutPrefix(sc.Text(), "VmRSS:"); ok {
fs := strings.Fields(v)
if len(fs) > 0 {
if kb, err := strconv.ParseUint(fs[0], 10, 64); err == nil {
return kb << 10
}
}
}
}
}
var m runtime.MemStats
runtime.ReadMemStats(&m)
return m.Sys
}
+742
View File
@@ -0,0 +1,742 @@
package probeagent
import (
"bufio"
"bytes"
"compress/gzip"
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
const testToken = "urp_test"
// fakeHub is the smallest hub that speaks the protocol: it applies batches
// idempotently by seq, keeps the lines, and serves a command queue.
type fakeHub struct {
mu sync.Mutex
lines []wire.Line
files map[string]string
ack uint64
offsets map[string]wire.Pos
cmds []wire.Cmd
status *wire.Status
hellos []wire.Hello
gzipSeen int
pushes int
fail503 int // next N pushes answer 503 Retry-After: 1
flushMS int
discard bool // do not keep lines (memory test)
nlines int
}
func newFakeHub() *fakeHub {
return &fakeHub{files: map[string]string{}, offsets: map[string]wire.Pos{}, flushMS: 30}
}
func (h *fakeHub) handler() http.Handler {
mux := http.NewServeMux()
auth := func(w http.ResponseWriter, r *http.Request) bool {
if r.Header.Get("Authorization") != "Bearer "+testToken || r.Header.Get(wire.HeaderProbe) != "p1" {
w.WriteHeader(401)
return false
}
return true
}
mux.HandleFunc(wire.PathHello, func(w http.ResponseWriter, r *http.Request) {
if !auth(w, r) {
return
}
var hello wire.Hello
json.NewDecoder(r.Body).Decode(&hello)
if hello.Proto != wire.Proto {
w.WriteHeader(409)
return
}
h.mu.Lock()
defer h.mu.Unlock()
h.hellos = append(h.hellos, hello)
json.NewEncoder(w).Encode(wire.HelloResp{Proto: wire.Proto, HubVer: "t", Offsets: h.offsets, AckSeq: h.ack, FlushMS: h.flushMS})
})
mux.HandleFunc(wire.PathPush, func(w http.ResponseWriter, r *http.Request) {
if !auth(w, r) {
return
}
var body io.Reader = r.Body
if r.Header.Get("Content-Encoding") == "gzip" {
gz, err := gzip.NewReader(r.Body)
if err != nil {
w.WriteHeader(400)
return
}
body = gz
h.mu.Lock()
h.gzipSeen++
h.mu.Unlock()
}
var b wire.Batch
if err := json.NewDecoder(body).Decode(&b); err != nil {
w.WriteHeader(400)
return
}
h.mu.Lock()
defer h.mu.Unlock()
h.pushes++
if h.fail503 > 0 {
h.fail503--
w.Header().Set("Retry-After", "1")
w.WriteHeader(503)
return
}
h.status = b.Status
resp := wire.PushResp{}
if b.Seq > 0 && b.Seq > h.ack {
for _, l := range b.Lines {
h.nlines++
if !h.discard {
h.lines = append(h.lines, l)
}
h.offsets[l.Src] = l.End
}
for _, f := range b.Files {
h.files[f.Name] = f.Data
}
h.ack = b.Seq
resp.Accepted = len(b.Lines)
} else if b.Seq > 0 {
resp.Dup = len(b.Lines)
}
resp.Ack = h.ack
if n := len(h.cmds); n > 0 {
resp.PendCmd = h.cmds[n-1].Seq
}
json.NewEncoder(w).Encode(resp)
})
mux.HandleFunc(wire.PathCommands, func(w http.ResponseWriter, r *http.Request) {
if !auth(w, r) {
return
}
after, _ := strconv.ParseUint(r.URL.Query().Get("after"), 10, 64)
deadline := time.Now().Add(300 * time.Millisecond)
for {
h.mu.Lock()
var out []wire.Cmd
for _, c := range h.cmds {
if c.Seq > after {
out = append(out, c)
}
}
h.mu.Unlock()
if len(out) > 0 || time.Now().After(deadline) || r.Context().Err() != nil {
json.NewEncoder(w).Encode(wire.CmdResp{Cmds: out})
return
}
time.Sleep(10 * time.Millisecond)
}
})
return mux
}
func (h *fakeHub) texts() []string {
h.mu.Lock()
defer h.mu.Unlock()
var out []string
for _, l := range h.lines {
out = append(out, l.Src+":"+l.Text)
}
return out
}
func (h *fakeHub) count() int { h.mu.Lock(); defer h.mu.Unlock(); return h.nlines }
func quiet() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) }
func eventually(t *testing.T, what string, d time.Duration, f func() bool) {
t.Helper()
end := time.Now().Add(d)
for time.Now().Before(end) {
if f() {
return
}
time.Sleep(10 * time.Millisecond)
}
t.Fatalf("timeout waiting for %s", what)
}
type env struct {
dir, state string
cfg Config
}
func newEnv(t *testing.T, hubURL string) *env {
d := t.TempDir()
e := &env{dir: d, state: filepath.Join(d, "state")}
e.cfg = Config{
Hub: hubURL, Name: "p1", Token: testToken, StateDir: e.state,
Paths: map[string]string{
wire.SrcTraefik: filepath.Join(d, "traefik.log"),
wire.SrcAuth: filepath.Join(d, "auth.log"),
},
DecisionsLog: filepath.Join(d, "decisions.log"),
UnbanLog: filepath.Join(d, "unban.log"),
Poll: 10 * time.Millisecond,
SpoolMax: 64 << 20,
}
return e
}
func appendFile(t *testing.T, path string, lines ...string) {
t.Helper()
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil {
t.Fatal(err)
}
defer f.Close()
for _, l := range lines {
f.WriteString(l + "\n")
}
}
func startRun(ctx context.Context, c Config) chan error {
done := make(chan error, 1)
go func() { done <- Run(ctx, c, quiet()) }()
return done
}
func TestEndToEnd(t *testing.T) {
hub := newFakeHub()
srv := httptest.NewServer(hub.handler())
defer srv.Close()
e := newEnv(t, srv.URL)
e.cfg.Containers = filepath.Join(e.dir, "containers.map")
os.WriteFile(e.cfg.Containers, []byte("172.18.0.2 web\n"), 0o644)
e.cfg.Location = &wire.Location{Lat: 1, Lon: 2, Label: "x"}
appendFile(t, e.cfg.Paths[wire.SrcTraefik], "t1", "t2")
ctx, cancel := context.WithCancel(context.Background())
done := startRun(ctx, e.cfg)
appendFile(t, e.cfg.Paths[wire.SrcAuth], "a1")
eventually(t, "3 lines", 5*time.Second, func() bool { return hub.count() == 3 })
appendFile(t, e.cfg.Paths[wire.SrcTraefik], "t3\xff")
eventually(t, "4 lines", 5*time.Second, func() bool { return hub.count() == 4 })
eventually(t, "file", 2*time.Second, func() bool {
hub.mu.Lock()
defer hub.mu.Unlock()
return hub.files[wire.FileContainers] == "172.18.0.2 web\n"
})
hub.mu.Lock()
h := hub.hellos[0]
last := hub.lines[len(hub.lines)-1]
st := hub.status
hub.mu.Unlock()
if h.Name != "p1" || h.Location == nil || h.Location.Label != "x" || len(h.Sources) != 2 {
t.Errorf("hello %+v", h)
}
if !strings.HasSuffix(last.Text, "�") || last.End.Offset != 10 {
t.Errorf("last %+v", last)
}
if st == nil || len(st.Sources) != 2 || st.RSSBytes == 0 {
t.Errorf("status %+v", st)
}
cancel()
if err := <-done; err != nil {
t.Fatal(err)
}
if err := Check(e.state); err != nil {
t.Errorf("Check after run: %v", err)
}
}
func TestHubOutageNoLossNoDuplicates(t *testing.T) {
hub := newFakeHub()
var down sync.Mutex
isDown := false
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
down.Lock()
d := isDown
down.Unlock()
if d {
hj, _ := w.(http.Hijacker)
c, _, _ := hj.Hijack()
c.Close()
return
}
hub.handler().ServeHTTP(w, r)
}))
defer srv.Close()
e := newEnv(t, srv.URL)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
startRun(ctx, e.cfg)
tp := e.cfg.Paths[wire.SrcTraefik]
appendFile(t, tp, "first")
eventually(t, "first", 5*time.Second, func() bool { return hub.count() == 1 })
down.Lock()
isDown = true
down.Unlock()
for i := 0; i < 1000; i++ {
appendFile(t, tp, fmt.Sprintf("line-%04d", i))
}
time.Sleep(400 * time.Millisecond)
down.Lock()
isDown = false
down.Unlock()
eventually(t, "1001 lines", 15*time.Second, func() bool { return hub.count() == 1001 })
time.Sleep(200 * time.Millisecond)
got := hub.texts()
if len(got) != 1001 {
t.Fatalf("%d lines", len(got))
}
for i := 0; i < 1000; i++ {
if got[i+1] != fmt.Sprintf("traefik:line-%04d", i) {
t.Fatalf("line %d = %s", i, got[i+1])
}
}
}
func TestRestartResumesFromState(t *testing.T) {
hub := newFakeHub()
srv := httptest.NewServer(hub.handler())
defer srv.Close()
e := newEnv(t, srv.URL)
tp := e.cfg.Paths[wire.SrcTraefik]
appendFile(t, tp, "a", "b", "c")
ctx, cancel := context.WithCancel(context.Background())
done := startRun(ctx, e.cfg)
eventually(t, "3", 5*time.Second, func() bool { return hub.count() == 3 })
cancel()
<-done
appendFile(t, tp, "d")
ctx2, cancel2 := context.WithCancel(context.Background())
defer cancel2()
startRun(ctx2, e.cfg)
eventually(t, "4", 5*time.Second, func() bool { return hub.count() >= 4 })
time.Sleep(200 * time.Millisecond)
if got := hub.texts(); len(got) != 4 || got[3] != "traefik:d" {
t.Fatalf("%v", got)
}
}
func TestFreshProbeStartsAtHubOffsets(t *testing.T) {
hub := newFakeHub()
srv := httptest.NewServer(hub.handler())
defer srv.Close()
e := newEnv(t, srv.URL)
tp := e.cfg.Paths[wire.SrcTraefik]
appendFile(t, tp, "old1", "old2", "new1")
fi, _ := os.Stat(tp)
ino := inodeFor(fi)
hub.offsets[wire.SrcTraefik] = wire.Pos{Inode: ino, Offset: int64(len("old1\nold2\n"))}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
startRun(ctx, e.cfg)
eventually(t, "new1", 5*time.Second, func() bool { return hub.count() >= 1 })
time.Sleep(200 * time.Millisecond)
if got := hub.texts(); len(got) != 1 || got[0] != "traefik:new1" {
t.Fatalf("%v", got)
}
}
func TestHubAckAheadRaisesSeq(t *testing.T) {
hub := newFakeHub()
hub.ack = 50 // probe lost its state; hub remembers
srv := httptest.NewServer(hub.handler())
defer srv.Close()
e := newEnv(t, srv.URL)
appendFile(t, e.cfg.Paths[wire.SrcTraefik], "x")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
startRun(ctx, e.cfg)
eventually(t, "x", 5*time.Second, func() bool { return hub.count() == 1 })
}
func TestPushBackpressure503RetryAfter(t *testing.T) {
hub := newFakeHub()
hub.fail503 = 1
srv := httptest.NewServer(hub.handler())
defer srv.Close()
e := newEnv(t, srv.URL)
appendFile(t, e.cfg.Paths[wire.SrcTraefik], "x")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
start := time.Now()
startRun(ctx, e.cfg)
eventually(t, "x", 8*time.Second, func() bool { return hub.count() == 1 })
if el := time.Since(start); el < 900*time.Millisecond {
t.Errorf("retried after %v, Retry-After: 1 not honored", el)
}
hub.mu.Lock()
n := len(hub.hellos)
hub.mu.Unlock()
if n != 1 {
t.Errorf("%d hellos: a 503 must not force a reconnect", n)
}
}
func TestUnauthorizedStopsRun(t *testing.T) {
hub := newFakeHub()
srv := httptest.NewServer(hub.handler())
defer srv.Close()
e := newEnv(t, srv.URL)
e.cfg.Token = "wrong"
var logbuf strings.Builder
done := make(chan error, 1)
go func() { done <- Run(context.Background(), e.cfg, slog.New(slog.NewTextHandler(&logbuf, nil))) }()
select {
case err := <-done:
if err != ErrUnauthorized {
t.Fatalf("err = %v", err)
}
case <-time.After(5 * time.Second):
t.Fatal("Run did not stop on 401")
}
if !strings.Contains(logbuf.String(), "401") {
t.Errorf("401 not logged: %s", logbuf.String())
}
if strings.Contains(logbuf.String(), "wrong") {
t.Error("token leaked in log")
}
}
func TestUnauthorizedRevokedMidSession(t *testing.T) {
hub := newFakeHub()
var revoked sync.Mutex
rev := false
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
revoked.Lock()
x := rev
revoked.Unlock()
if x {
w.WriteHeader(401)
return
}
hub.handler().ServeHTTP(w, r)
}))
defer srv.Close()
e := newEnv(t, srv.URL)
appendFile(t, e.cfg.Paths[wire.SrcTraefik], "x")
done := startRun(context.Background(), e.cfg)
eventually(t, "x", 5*time.Second, func() bool { return hub.count() == 1 })
revoked.Lock()
rev = true
revoked.Unlock()
appendFile(t, e.cfg.Paths[wire.SrcTraefik], "y")
select {
case err := <-done:
if err != ErrUnauthorized {
t.Fatalf("err = %v", err)
}
case <-time.After(30 * time.Second):
t.Fatal("Run kept going after token revocation")
}
}
func TestGzipOverThreshold(t *testing.T) {
hub := newFakeHub()
srv := httptest.NewServer(hub.handler())
defer srv.Close()
e := newEnv(t, srv.URL)
big := strings.Repeat("abcdefghij", 200)
for i := 0; i < 20; i++ {
appendFile(t, e.cfg.Paths[wire.SrcTraefik], fmt.Sprintf("%d%s", i, big))
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
startRun(ctx, e.cfg)
eventually(t, "20", 5*time.Second, func() bool { return hub.count() == 20 })
hub.mu.Lock()
defer hub.mu.Unlock()
if hub.gzipSeen == 0 {
t.Error("large push was not gzipped")
}
if hub.lines[19].Text != "19"+big {
t.Error("gzip round trip altered the line")
}
}
func TestSmallPushNotGzipped(t *testing.T) {
hub := newFakeHub()
srv := httptest.NewServer(hub.handler())
defer srv.Close()
e := newEnv(t, srv.URL)
appendFile(t, e.cfg.Paths[wire.SrcTraefik], "tiny")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
startRun(ctx, e.cfg)
eventually(t, "1", 5*time.Second, func() bool { return hub.count() == 1 })
hub.mu.Lock()
defer hub.mu.Unlock()
if hub.gzipSeen != 0 {
t.Error("small push gzipped")
}
}
func TestCommandsApplied(t *testing.T) {
hub := newFakeHub()
srv := httptest.NewServer(hub.handler())
defer srv.Close()
e := newEnv(t, srv.URL)
good := "2026-11-15T10:20:30Z urutau decision=ban ip=203.0.113.9 reason=rce score=90 ttl=300 host=h src=local\n"
unban := "2026-11-15T10:21:30Z urutau unban ip=203.0.113.9 allow=60\n"
evil := "2026-11-15T10:20:30Z urutau decision=ban ip=203.0.113.9 reason=rce score=90 ttl=300 host=h src=local\nrm -rf /\n"
hub.cmds = []wire.Cmd{
{Seq: 1, Kind: wire.CmdDecision, Line: good},
{Seq: 2, Kind: wire.CmdDecision, Line: evil},
{Seq: 3, Kind: wire.CmdDecision, Line: "garbage\n"},
{Seq: 4, Kind: wire.CmdUnban, Line: unban},
{Seq: 5, Kind: "other", Line: good},
}
ctx, cancel := context.WithCancel(context.Background())
done := startRun(ctx, e.cfg)
eventually(t, "cmds", 5*time.Second, func() bool {
s, err := loadState(e.state)
return err == nil && s.s.LastCmd == 5
})
cancel()
<-done
dec, _ := os.ReadFile(e.cfg.DecisionsLog)
if string(dec) != good {
t.Errorf("decisions.log = %q", dec)
}
ub, _ := os.ReadFile(e.cfg.UnbanLog)
if string(ub) != unban {
t.Errorf("unban.log = %q", ub)
}
// restart: the hub redelivers everything, nothing is applied twice
ctx2, cancel2 := context.WithCancel(context.Background())
done2 := startRun(ctx2, e.cfg)
time.Sleep(600 * time.Millisecond)
cancel2()
<-done2
dec, _ = os.ReadFile(e.cfg.DecisionsLog)
if string(dec) != good {
t.Errorf("decision duplicated after restart: %q", dec)
}
}
func TestApplyCmdsDirect(t *testing.T) {
e := newEnv(t, "http://127.0.0.1:1")
p, err := newProbe(e.cfg, quiet())
if err != nil {
t.Fatal(err)
}
good := "2026-11-15T10:20:30Z urutau decision=ban ip=2001:db8::1 reason=rce score=90 ttl=300 host=h src=peer:o\n"
cmds := []wire.Cmd{{Seq: 1, Kind: wire.CmdDecision, Line: good}, {Seq: 1, Kind: wire.CmdDecision, Line: good}, {Seq: 2, Kind: wire.CmdDecision, Line: "x\n"}}
if err := p.applyCmds(cmds); err != nil {
t.Fatal(err)
}
if err := p.applyCmds(cmds); err != nil {
t.Fatal(err)
}
b, _ := os.ReadFile(e.cfg.DecisionsLog)
if string(b) != good {
t.Errorf("%q", b)
}
if p.cmdErrors.Load() != 1 {
t.Errorf("cmdErrors = %d", p.cmdErrors.Load())
}
if p.st.lastCmd() != 2 {
t.Errorf("lastCmd = %d", p.st.lastCmd())
}
// no unban log configured: counted, not written
p.cfg.UnbanLog = ""
p.applyCmds([]wire.Cmd{{Seq: 3, Kind: wire.CmdUnban, Line: "2026-11-15T10:21:30Z urutau unban ip=1.2.3.4 allow=1\n"}})
if p.cmdErrors.Load() != 2 {
t.Errorf("cmdErrors = %d", p.cmdErrors.Load())
}
}
func TestBackoff(t *testing.T) {
for n, base := range map[int]float64{1: 1, 2: 2, 3: 4, 6: 32, 7: 60, 20: 60} {
for _, r := range []float64{0, 0.5, 0.999} {
d := backoff(n, func() float64 { return r }).Seconds()
if d < base*0.8-1e-9 || d > base*1.2+1e-9 {
t.Errorf("backoff(%d, %v) = %v, want %v +-20%%", n, r, d, base)
}
}
}
if backoff(3, func() float64 { return 0.5 }) != 4*time.Second {
t.Error("middle of jitter should be the base")
}
}
func TestOversizeLineCountedNotSent(t *testing.T) {
hub := newFakeHub()
srv := httptest.NewServer(hub.handler())
defer srv.Close()
e := newEnv(t, srv.URL)
appendFile(t, e.cfg.Paths[wire.SrcTraefik], "ok", strings.Repeat("z", wire.MaxLine+10), "after")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
startRun(ctx, e.cfg)
eventually(t, "2 lines", 5*time.Second, func() bool { return hub.count() == 2 })
time.Sleep(100 * time.Millisecond)
if got := hub.texts(); len(got) != 2 || got[1] != "traefik:after" {
t.Fatalf("%v", got)
}
}
func TestMissingSourceWaitsAndNoPathLeak(t *testing.T) {
hub := newFakeHub()
srv := httptest.NewServer(hub.handler())
defer srv.Close()
e := newEnv(t, srv.URL)
appendFile(t, e.cfg.Paths[wire.SrcTraefik], "x") // auth.log never created
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
startRun(ctx, e.cfg)
eventually(t, "x", 5*time.Second, func() bool { return hub.count() == 1 })
appendFile(t, e.cfg.Paths[wire.SrcTraefik], "y")
eventually(t, "status", 5*time.Second, func() bool {
hub.mu.Lock()
defer hub.mu.Unlock()
if hub.status == nil {
return false
}
for _, s := range hub.status.Sources {
if s.Src == wire.SrcAuth && s.State == "waiting" {
return true
}
}
return false
})
hub.mu.Lock()
b, _ := json.Marshal(hub.status)
hub.mu.Unlock()
if strings.Contains(string(b), e.dir) {
t.Errorf("path leaked in status: %s", b)
}
}
func TestConfigValidation(t *testing.T) {
e := newEnv(t, "https://hub.example.com")
bad := func(m func(*Config)) {
c := e.cfg
m(&c)
if _, err := newProbe(c, quiet()); err == nil {
t.Error("invalid config accepted")
}
}
bad(func(c *Config) { c.Hub = "http://example.com" })
bad(func(c *Config) { c.Name = "Bad Name" })
bad(func(c *Config) { c.Token = "" })
bad(func(c *Config) { c.StateDir = "" })
}
func TestCheck(t *testing.T) {
d := t.TempDir()
if Check(d) == nil {
t.Error("missing state accepted")
}
st, _ := loadState(d)
st.touch()
if err := Check(d); err != nil {
t.Error(err)
}
st.s.Alive = time.Now().Add(-10 * time.Minute).Unix()
b, _ := json.Marshal(&st.s)
os.WriteFile(filepath.Join(d, "state.json"), b, 0o600)
if Check(d) == nil {
t.Error("stale state accepted")
}
}
// TestHelperProbe is the probe process of TestMemoryFootprint, run in a child
// so that nothing but the probe (and the test binary baseline) is measured.
func TestHelperProbe(t *testing.T) {
if os.Getenv("URUTAU_TEST_PROBE_CHILD") == "" {
t.Skip("helper for TestMemoryFootprint")
}
var cfg Config
if err := json.Unmarshal([]byte(os.Getenv("URUTAU_TEST_PROBE_CFG")), &cfg); err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
done := startRun(ctx, cfg)
io.Copy(io.Discard, os.Stdin) // parent closes stdin when done
cancel()
<-done
var m runtime.MemStats
runtime.ReadMemStats(&m)
hwm := uint64(0)
if b, err := os.ReadFile("/proc/self/status"); err == nil {
for _, l := range strings.Split(string(b), "\n") {
if v, ok := strings.CutPrefix(l, "VmHWM:"); ok {
kb, _ := strconv.ParseUint(strings.Fields(v)[0], 10, 64)
hwm = kb << 10
}
}
}
fmt.Printf("RESULT sys=%d hwm=%d\n", m.Sys, hwm)
}
// 5 sources, 50k lines: the probe must stay small (target RSS < 20 MB).
func TestMemoryFootprint(t *testing.T) {
if raceOn {
t.Skip("the race detector inflates RSS; measured in the plain run")
}
hub := newFakeHub()
hub.discard = true
srv := httptest.NewServer(hub.handler())
defer srv.Close()
e := newEnv(t, srv.URL)
e.cfg.Paths = map[string]string{}
srcs := wire.Sources
line := `203.0.113.7 - - [15/Nov/2026:10:20:30 +0000] "GET /wp-login.php HTTP/1.1" 404 153 "-" "Mozilla/5.0 (X11; Linux x86_64)" 1234 "web@docker" "http://172.18.0.5:80" 3ms`
const per = 10000
for _, s := range srcs {
e.cfg.Paths[s] = filepath.Join(e.dir, s+".log")
f, _ := os.Create(e.cfg.Paths[s])
w := bufio.NewWriter(f)
for i := 0; i < per; i++ {
fmt.Fprintf(w, "%s %d\n", line, i)
}
w.Flush()
f.Close()
}
cfgJSON, _ := json.Marshal(e.cfg)
cmd := exec.Command(os.Args[0], "-test.run=^TestHelperProbe$", "-test.v")
cmd.Env = append(os.Environ(), "URUTAU_TEST_PROBE_CHILD=1", "URUTAU_TEST_PROBE_CFG="+string(cfgJSON))
stdin, _ := cmd.StdinPipe()
var out bytes.Buffer
cmd.Stdout = &out
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
eventually(t, "50k lines", 60*time.Second, func() bool { return hub.count() == per*len(srcs) })
time.Sleep(300 * time.Millisecond)
stdin.Close()
if err := cmd.Wait(); err != nil {
t.Fatalf("child: %v\n%s", err, out.String())
}
var sys, hwm uint64
for _, l := range strings.Split(out.String(), "\n") {
if strings.HasPrefix(l, "RESULT ") {
fmt.Sscanf(l, "RESULT sys=%d hwm=%d", &sys, &hwm)
}
}
if sys == 0 {
t.Fatalf("no result from child:\n%s", out.String())
}
t.Logf("50k lines, 5 sources: runtime MemStats.Sys = %.1f MB, peak RSS (VmHWM) = %.1f MB", float64(sys)/(1<<20), float64(hwm)/(1<<20))
if sys >= 20<<20 {
t.Errorf("MemStats.Sys %d >= 20 MB", sys)
}
if hwm >= 20<<20 {
t.Errorf("peak RSS %d >= 20 MB", hwm)
}
}
+5
View File
@@ -0,0 +1,5 @@
//go:build race
package probeagent
const raceOn = true
+176
View File
@@ -0,0 +1,176 @@
package probeagent
import (
"bytes"
"encoding/json"
"fmt"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
// Spool keeps unacknowledged batches on disk, one file per batch, in order.
type Spool struct {
mu sync.Mutex
dir string
max int64
items []spoolItem
bytes int64
wbuf bytes.Buffer // reused encoder buffer
}
type spoolItem struct {
seq uint64
size int64
}
func spoolName(seq uint64) string { return fmt.Sprintf("%012d.json", seq) }
// OpenSpool scans dir (created if missing) and returns the spool.
func OpenSpool(dir string, max int64) (*Spool, error) {
if err := os.MkdirAll(dir, 0o700); err != nil {
return nil, err
}
sp := &Spool{dir: dir, max: max}
ents, err := os.ReadDir(dir)
if err != nil {
return nil, err
}
for _, e := range ents {
n := e.Name()
if strings.HasSuffix(n, ".tmp") {
os.Remove(filepath.Join(dir, n))
continue
}
if !strings.HasSuffix(n, ".json") {
continue
}
seq, err := strconv.ParseUint(strings.TrimSuffix(n, ".json"), 10, 64)
if err != nil {
continue
}
fi, err := e.Info()
if err != nil {
continue
}
sp.items = append(sp.items, spoolItem{seq, fi.Size()})
sp.bytes += fi.Size()
}
sort.Slice(sp.items, func(i, j int) bool { return sp.items[i].seq < sp.items[j].seq })
return sp, nil
}
// MaxSeq is the highest batch number on disk (0 when empty).
func (sp *Spool) MaxSeq() uint64 {
sp.mu.Lock()
defer sp.mu.Unlock()
if len(sp.items) == 0 {
return 0
}
return sp.items[len(sp.items)-1].seq
}
// Add stores b (b.Seq must be above everything already stored). When the cap
// is exceeded the oldest files are deleted, but never the one just added; the
// number of log lines lost that way is returned.
func (sp *Spool) Add(b wire.Batch) (dropped uint64, err error) {
sp.mu.Lock()
defer sp.mu.Unlock()
sp.wbuf.Reset()
if err := json.NewEncoder(&sp.wbuf).Encode(&b); err != nil {
return 0, err
}
data := sp.wbuf.Bytes()
if sp.wbuf.Cap() > 4<<20 {
defer func() { sp.wbuf = bytes.Buffer{} }()
}
p := filepath.Join(sp.dir, spoolName(b.Seq))
tmp := p + ".tmp"
f, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600)
if err != nil {
return 0, err
}
if _, err = f.Write(data); err == nil {
err = f.Sync()
}
if cerr := f.Close(); err == nil {
err = cerr
}
if err == nil {
err = os.Rename(tmp, p)
}
if err != nil {
os.Remove(tmp)
return 0, err
}
sp.items = append(sp.items, spoolItem{b.Seq, int64(len(data))})
sp.bytes += int64(len(data))
for sp.bytes > sp.max && len(sp.items) > 1 {
it := sp.items[0]
dropped += sp.countLines(it.seq)
sp.removeLocked(0)
}
return dropped, nil
}
func (sp *Spool) countLines(seq uint64) uint64 {
data, err := os.ReadFile(filepath.Join(sp.dir, spoolName(seq)))
if err != nil {
return 0
}
var b wire.Batch
if json.Unmarshal(data, &b) != nil {
return 0
}
return uint64(len(b.Lines))
}
func (sp *Spool) removeLocked(i int) {
it := sp.items[i]
os.Remove(filepath.Join(sp.dir, spoolName(it.seq)))
sp.bytes -= it.size
sp.items = append(sp.items[:i], sp.items[i+1:]...)
}
// Head returns the oldest batch.
func (sp *Spool) Head() (wire.Batch, bool, error) {
sp.mu.Lock()
if len(sp.items) == 0 {
sp.mu.Unlock()
return wire.Batch{}, false, nil
}
seq := sp.items[0].seq
sp.mu.Unlock()
data, err := os.ReadFile(filepath.Join(sp.dir, spoolName(seq)))
var b wire.Batch
if err == nil {
err = json.Unmarshal(data, &b)
}
if err != nil {
sp.Ack(seq) // unreadable: discard so the queue moves on
return wire.Batch{}, false, fmt.Errorf("spool batch %d unreadable: %w", seq, err)
}
b.Seq = seq
return b, true, nil
}
// Ack removes every batch with seq <= n.
func (sp *Spool) Ack(n uint64) {
sp.mu.Lock()
defer sp.mu.Unlock()
for len(sp.items) > 0 && sp.items[0].seq <= n {
sp.removeLocked(0)
}
}
// Stats returns the bytes and file count held.
func (sp *Spool) Stats() (bytes int64, files int) {
sp.mu.Lock()
defer sp.mu.Unlock()
return sp.bytes, len(sp.items)
}
+129
View File
@@ -0,0 +1,129 @@
package probeagent
import (
"fmt"
"os"
"path/filepath"
"testing"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
func mkBatch(seq uint64, n int, pad string) wire.Batch {
b := wire.Batch{Seq: seq}
for i := 0; i < n; i++ {
b.Lines = append(b.Lines, wire.Line{Src: wire.SrcTraefik, Text: fmt.Sprintf("%d-%d%s", seq, i, pad), End: wire.Pos{Inode: 1, Offset: int64(i)}})
}
return b
}
func TestSpoolOrderAndReopen(t *testing.T) {
d := t.TempDir()
sp, err := OpenSpool(d, 1<<20)
if err != nil {
t.Fatal(err)
}
for s := uint64(1); s <= 5; s++ {
if dr, err := sp.Add(mkBatch(s, 3, "")); err != nil || dr != 0 {
t.Fatal(dr, err)
}
}
sp.Ack(2)
sp2, err := OpenSpool(d, 1<<20) // reopen
if err != nil {
t.Fatal(err)
}
if sp2.MaxSeq() != 5 {
t.Errorf("MaxSeq %d", sp2.MaxSeq())
}
for want := uint64(3); want <= 5; want++ {
b, ok, err := sp2.Head()
if err != nil || !ok || b.Seq != want || len(b.Lines) != 3 {
t.Fatalf("head %d: %+v %v %v", want, b.Seq, ok, err)
}
sp2.Ack(want)
}
if _, ok, _ := sp2.Head(); ok {
t.Error("spool not empty")
}
if n, f := sp2.Stats(); n != 0 || f != 0 {
t.Errorf("stats %d %d", n, f)
}
}
func TestSpoolCapDropsOldestAndCounts(t *testing.T) {
d := t.TempDir()
probe := mkBatch(1, 10, "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
tmp, _ := OpenSpool(t.TempDir(), 1<<30)
tmp.Add(probe)
size, _ := tmp.Stats()
sp, _ := OpenSpool(d, size*3+size/2) // room for 3 batches
var dropped uint64
for s := uint64(1); s <= 6; s++ {
dr, err := sp.Add(mkBatch(s, 10, "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"))
if err != nil {
t.Fatal(err)
}
dropped += dr
}
if dropped != 30 {
t.Errorf("dropped %d lines, want 30 (3 batches of 10)", dropped)
}
b, ok, _ := sp.Head()
if !ok || b.Seq != 4 {
t.Errorf("oldest remaining = %d, want 4", b.Seq)
}
if _, f := sp.Stats(); f != 3 {
t.Errorf("files %d", f)
}
ents, _ := os.ReadDir(d)
if len(ents) != 3 {
t.Errorf("%d files on disk", len(ents))
}
}
func TestSpoolKeepsLoneOversizeBatch(t *testing.T) {
sp, _ := OpenSpool(t.TempDir(), 10)
dr, err := sp.Add(mkBatch(1, 5, ""))
if err != nil || dr != 0 {
t.Fatal(dr, err)
}
if _, f := sp.Stats(); f != 1 {
t.Error("newest batch must survive the cap")
}
}
func TestSpoolCorruptFileSkipped(t *testing.T) {
d := t.TempDir()
sp, _ := OpenSpool(d, 1<<20)
sp.Add(mkBatch(1, 1, ""))
sp.Add(mkBatch(2, 1, ""))
os.WriteFile(filepath.Join(d, spoolName(1)), []byte("{broken"), 0o600)
if _, _, err := sp.Head(); err == nil {
t.Error("corrupt batch not reported")
}
b, ok, err := sp.Head()
if err != nil || !ok || b.Seq != 2 {
t.Errorf("next head %v %v %v", b.Seq, ok, err)
}
}
func TestStateAtomicRoundTrip(t *testing.T) {
d := t.TempDir()
st, _ := loadState(d)
st.commit(func(seq uint64) uint64 { return 7 }, map[string]wire.Pos{"auth": {Inode: 9, Offset: 123, FP: 5, FPLen: 4}})
st.setLastCmd(4)
st2, err := loadState(d)
if err != nil {
t.Fatal(err)
}
s := st2.s
if s.Seq != 1 || s.LastCmd != 4 || s.Dropped != 7 || s.Positions["auth"].Offset != 123 || s.Positions["auth"].FPLen != 4 {
t.Errorf("%+v", s)
}
os.WriteFile(filepath.Join(d, "state.json"), []byte("garbage"), 0o600)
st3, err := loadState(d)
if err != nil || st3.s.Seq != 0 || st3.s.Positions == nil {
t.Errorf("corrupt state not reset: %+v %v", st3.s, err)
}
}
+176
View File
@@ -0,0 +1,176 @@
package probeagent
import (
"encoding/json"
"errors"
"os"
"path/filepath"
"sync"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
// State is the probe's only durable bookkeeping besides the spool.
type State struct {
Seq uint64 `json:"seq"`
LastCmd uint64 `json:"last_cmd"`
Positions map[string]wire.Pos `json:"positions"`
Dropped uint64 `json:"dropped"`
Alive int64 `json:"alive"` // unix seconds, refreshed by the process; read by Check
}
type stateStore struct {
mu sync.Mutex
path string
s State
}
func loadState(dir string) (*stateStore, error) {
st := &stateStore{path: filepath.Join(dir, "state.json")}
st.s.Positions = map[string]wire.Pos{}
b, err := os.ReadFile(st.path)
if errors.Is(err, os.ErrNotExist) {
return st, nil
}
if err != nil {
return nil, err
}
if err := json.Unmarshal(b, &st.s); err != nil {
// a corrupt state must not keep the probe down: start clean, the hub's
// offsets in the hello cover the gap.
st.s = State{}
}
if st.s.Positions == nil {
st.s.Positions = map[string]wire.Pos{}
}
return st, nil
}
// saveLocked writes state.json atomically. Caller holds mu.
func (st *stateStore) saveLocked() error {
st.s.Alive = time.Now().Unix()
b, err := json.Marshal(&st.s)
if err != nil {
return err
}
tmp := st.path + ".tmp"
f, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600)
if err != nil {
return err
}
if _, err := f.Write(b); err != nil {
f.Close()
return err
}
if err := f.Sync(); err != nil {
f.Close()
return err
}
if err := f.Close(); err != nil {
return err
}
return os.Rename(tmp, st.path)
}
func (st *stateStore) touch() error {
st.mu.Lock()
defer st.mu.Unlock()
return st.saveLocked()
}
func (st *stateStore) snapshot() State {
st.mu.Lock()
defer st.mu.Unlock()
c := st.s
c.Positions = make(map[string]wire.Pos, len(st.s.Positions))
for k, v := range st.s.Positions {
c.Positions[k] = v
}
return c
}
func (st *stateStore) pos(src string) (wire.Pos, bool) {
st.mu.Lock()
defer st.mu.Unlock()
p, ok := st.s.Positions[src]
return p, ok
}
func (st *stateStore) lastCmd() uint64 {
st.mu.Lock()
defer st.mu.Unlock()
return st.s.LastCmd
}
func (st *stateStore) setLastCmd(n uint64) error {
st.mu.Lock()
defer st.mu.Unlock()
st.s.LastCmd = n
return st.saveLocked()
}
func (st *stateStore) dropped() uint64 {
st.mu.Lock()
defer st.mu.Unlock()
return st.s.Dropped
}
func (st *stateStore) addDropped(n uint64) {
if n == 0 {
return
}
st.mu.Lock()
defer st.mu.Unlock()
st.s.Dropped += n
_ = st.saveLocked()
}
// raiseSeq makes sure new batches are numbered above what the hub already
// applied (state lost on the probe, or hub ahead).
func (st *stateStore) raiseSeq(n uint64) {
st.mu.Lock()
defer st.mu.Unlock()
if n > st.s.Seq {
st.s.Seq = n
_ = st.saveLocked()
}
}
func (st *stateStore) lastSeq() uint64 {
st.mu.Lock()
defer st.mu.Unlock()
return st.s.Seq
}
// commit allocates the next batch seq. persist is called with it before the
// positions move, so a spooled batch always has its position recorded.
func (st *stateStore) commit(build func(seq uint64) (dropped uint64), pos map[string]wire.Pos) {
st.mu.Lock()
defer st.mu.Unlock()
st.s.Seq++
st.s.Dropped += build(st.s.Seq)
for k, v := range pos {
st.s.Positions[k] = v
}
_ = st.saveLocked()
}
// Check is the container healthcheck: the process refreshes state.json every
// few seconds, so a stale or missing file means it is not running.
func Check(stateDir string) error {
b, err := os.ReadFile(filepath.Join(stateDir, "state.json"))
if err != nil {
return errors.New("probe state unreadable")
}
var s State
if err := json.Unmarshal(b, &s); err != nil {
return errors.New("probe state corrupt")
}
if age := time.Since(time.Unix(s.Alive, 0)); age > aliveMax {
return errors.New("probe not alive")
}
return nil
}
const aliveMax = 90 * time.Second
+230
View File
@@ -0,0 +1,230 @@
package probeagent
import (
"context"
"crypto/sha256"
"errors"
"io/fs"
"os"
"strings"
"sync/atomic"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/tail"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
const (
chanSize = 4096
batchBytes = 128 << 10 // well under the hub limit; keeps the probe heap small
filePollEach = 10 * time.Second
)
// item is what the followers and the file watcher hand to the collector.
type item struct {
line wire.Line
file *wire.File
}
type srcStat struct {
src string
f *tail.Follower
lines atomic.Uint64
oversize atomic.Uint64
lastLine atomic.Int64
}
func (s *srcStat) status() wire.SourceStatus {
st := wire.SourceStatus{Src: s.src, State: "following", Lines: s.lines.Load(), Oversize: s.oversize.Load(), LastLine: s.lastLine.Load()}
if err := s.f.Err(); err != nil {
switch {
case errors.Is(err, fs.ErrNotExist):
st.State = "waiting"
case errors.Is(err, fs.ErrPermission):
st.State, st.Error = "error", "permission denied"
default:
st.State, st.Error = "error", "read error"
}
}
return st
}
func toTail(p wire.Pos) tail.Pos {
return tail.Pos{Inode: p.Inode, Offset: p.Offset, FP: p.FP, FPLen: p.FPLen}
}
func fromTail(p tail.Pos) wire.Pos {
return wire.Pos{Inode: p.Inode, Offset: p.Offset, FP: p.FP, FPLen: p.FPLen}
}
// startTailers launches one follower per configured source. A source with no
// local position starts where the hub says it already has data.
func (p *probe) startTailers(ctx context.Context, hubOffsets map[string]wire.Pos) {
for _, src := range p.sources {
path := p.cfg.Paths[src]
pos, ok := p.st.pos(src)
if !ok {
pos = hubOffsets[src]
}
f := tail.NewFollower(path, toTail(pos))
f.MaxLine = wire.MaxLine
if p.cfg.Poll > 0 {
f.Poll = p.cfg.Poll
}
ss := &srcStat{src: src, f: f}
p.stats = append(p.stats, ss)
f.Oversize = func() { ss.oversize.Add(1) }
f.HandleAt = func(line []byte, end tail.Pos) {
ss.lines.Add(1)
ss.lastLine.Store(time.Now().Unix())
it := item{line: wire.Line{Src: src, Text: strings.ToValidUTF8(string(line), "�"), End: fromTail(end)}}
select {
case p.in <- it:
case <-ctx.Done():
}
}
p.wg.Add(1)
go func() { defer p.wg.Done(); f.Run(ctx) }()
}
p.wg.Add(1)
go func() { defer p.wg.Done(); p.watchFiles(ctx) }()
}
// watchFiles sends containers.map and resolv.conf whole whenever they change,
// and again after each reconnect.
func (p *probe) watchFiles(ctx context.Context) {
files := []struct{ name, path string }{
{wire.FileContainers, p.cfg.Containers},
{wire.FileResolv, p.cfg.Resolv},
}
sums := map[string][32]byte{}
check := func() {
for _, f := range files {
if f.path == "" {
continue
}
b, err := readSmall(f.path)
if err != nil {
continue
}
sum := sha256.Sum256(b)
if old, ok := sums[f.name]; ok && old == sum {
continue
}
sums[f.name] = sum
select {
case p.in <- item{file: &wire.File{Name: f.name, Data: strings.ToValidUTF8(string(b), "�")}}:
case <-ctx.Done():
return
}
}
}
check()
t := time.NewTicker(p.fileEvery)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-p.resendFiles:
clear(sums)
check()
case <-t.C:
check()
}
}
}
func readSmall(path string) ([]byte, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
fi, err := f.Stat()
if err != nil || fi.Size() > wire.MaxFileBytes {
return nil, errors.New("unusable file")
}
b := make([]byte, fi.Size())
n, err := f.Read(b)
if err != nil && n == 0 && fi.Size() > 0 {
return nil, err
}
return b[:n], nil
}
// collect groups items into batches (flush interval, 5000 lines or 1 MiB),
// writes each to the spool and records the positions it covers.
func (p *probe) collect(ctx context.Context) {
var (
b wire.Batch
size int
pos = map[string]wire.Pos{}
)
flush := func() {
if len(b.Lines) == 0 && len(b.Files) == 0 {
return
}
nl := uint64(len(b.Lines))
p.st.commit(func(seq uint64) uint64 {
b.Seq = seq
b.Sent = time.Now().UnixMilli()
dropped, err := p.spool.Add(b)
if err != nil {
p.log.Error("spool write failed", "err", err)
return nl
}
if dropped > 0 {
p.log.Warn("spool full, oldest batches dropped", "lines", dropped)
}
return dropped
}, pos)
b, size = wire.Batch{Lines: make([]wire.Line, 0, 512)}, 0
clear(pos)
select {
case p.notify <- struct{}{}:
default:
}
}
add := func(it item) {
if it.file != nil {
replaced := false
for i := range b.Files {
if b.Files[i].Name == it.file.Name {
b.Files[i], replaced = *it.file, true
}
}
if !replaced {
b.Files = append(b.Files, *it.file)
}
size += len(it.file.Data)
} else {
b.Lines = append(b.Lines, it.line)
pos[it.line.Src] = it.line.End
size += len(it.line.Text) + 48
}
if len(b.Lines) >= wire.MaxLines || size >= batchBytes {
flush()
}
}
t := time.NewTicker(p.flushEvery())
defer t.Stop()
for {
select {
case it := <-p.in:
add(it)
case <-t.C:
flush()
case <-ctx.Done():
for {
select {
case it := <-p.in:
add(it)
default:
flush()
return
}
}
}
}
}
-20
View File
@@ -94,23 +94,3 @@ func (s *Server) egressReport(ctx context.Context, from, to int64, local, peers
}
return rep, peerOn
}
// peerEgress: GET /api/v1/peer/egress, the local report a hub merges; opened
// only by the peer token (and --peer-allow). It must be registered next to
// the other peer routes.
func (s *Server) peerEgress(w http.ResponseWriter, r *http.Request) {
if !s.peerGate(w, r) {
return
}
eng := egressEngine.Load()
if eng == nil {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "egress is not enabled"})
return
}
rg, ok := s.rangeOf(w, r)
if !ok {
return
}
from, to := rg.Bounds(s.opt.Store.Now().Unix())
writeJSON(w, 200, eng.Report(from, to))
}
-29
View File
@@ -1,9 +1,6 @@
package server
import (
"encoding/json"
"net/http"
"net/http/httptest"
"net/netip"
"strconv"
"testing"
@@ -70,30 +67,4 @@ func TestEgressAPI(t *testing.T) {
if w := do(h, "GET", "/api/v1/egress?range=24h", map[string]string{"Authorization": "Bearer peer-secret"}, nil); w.Code == 200 {
t.Fatalf("peer token must not open the user route")
}
// peer endpoint (registered by the daemon next to the other peer routes)
s := &Server{opt: Options{PeerTokens: []string{"peer-secret"}, Token: userTok, Store: st, Now: time.Now}, ses: newSessions(), lim: newLimiter()}
m := http.NewServeMux()
m.HandleFunc("GET /api/v1/peer/egress", s.peerEgress)
call := func(tok string) *httptest.ResponseRecorder {
r := httptest.NewRequest("GET", "/api/v1/peer/egress?range=24h", nil)
r.RemoteAddr = "198.51.100.1:1234"
if tok != "" {
r.Header.Set("Authorization", "Bearer "+tok)
}
w := httptest.NewRecorder()
m.ServeHTTP(w, r)
return w
}
if w := call(""); w.Code != 401 {
t.Fatalf("peer no token: %d", w.Code)
}
if w := call(userTok); w.Code != 401 {
t.Fatalf("user token on peer route: %d", w.Code)
}
w := call("peer-secret")
var rep egress.Report
if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &rep) != nil || len(rep.Findings) == 0 {
t.Fatalf("peer: %d %s", w.Code, w.Body)
}
}
+41 -105
View File
@@ -3,13 +3,10 @@ package server
import (
"encoding/json"
"errors"
"io"
"net/http"
"net/netip"
"strconv"
"strings"
"sync/atomic"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
)
@@ -20,16 +17,6 @@ var enforceEngine atomic.Pointer[enforce.Engine]
// SetEnforce installs the engine the enforce endpoints talk to.
func SetEnforce(e *enforce.Engine) { enforceEngine.Store(e) }
// peerRoute is a route opened by the federation token, contributed by its own file.
type peerRoute struct {
pattern string
handler func(*Server) http.HandlerFunc
}
var peerRoutes []peerRoute
const maxDecisionBody = 64 << 10
func init() {
registerUserRoute("GET /api/v1/enforce", func(s *Server) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
@@ -44,15 +31,19 @@ func init() {
}
out := map[string]any{"mode": enforce.ModeOff, "share": "off", "threshold": 0, "log_writable": false,
"allows": []enforce.Allow{}, "unban_log_writable": false, "coverage": enforce.Coverage{}, "counts": enforce.Counts{Skipped: map[string]int{}}, "recent": []enforce.Recent{}}
if e := enforceEngine.Load(); e != nil {
if e := s.enforceFor(r.URL.Query().Get("host")); e != nil {
rep := e.Report(from)
share := "off"
if e.Share() {
share = "on"
}
out["mode"], out["share"], out["threshold"] = e.Mode(), share, e.Threshold()
out["log_writable"] = enforce.Writable(e.LogPath())
out["unban_log_writable"] = enforce.Writable(e.UnbanLogPath())
if e.HasSink() { // the probe writes the files: queueing is always possible
out["log_writable"], out["unban_log_writable"] = true, true
} else {
out["log_writable"] = enforce.Writable(e.LogPath())
out["unban_log_writable"] = enforce.Writable(e.UnbanLogPath())
}
out["allows"] = e.Allows()
out["coverage"], out["counts"], out["recent"] = rep.Coverage, rep.Counts, rep.Recent
}
@@ -61,80 +52,6 @@ func init() {
})
registerUserRoute("POST /api/v1/enforce/unban", func(s *Server) http.HandlerFunc { return s.enforceUnban })
registerUserRoute("DELETE /api/v1/enforce/allow", func(s *Server) http.HandlerFunc { return s.enforceEndAllow })
peerRoutes = append(peerRoutes,
peerRoute{"POST /api/v1/peer/unban", func(s *Server) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
e := enforceEngine.Load()
if !s.peerGate(w, r) {
return
}
if e == nil || !e.Share() {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "decision sharing is not enabled"})
return
}
var in struct {
Unbans []enforce.UnbanWire `json:"unbans"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxDecisionBody)).Decode(&in); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON"})
return
}
writeJSON(w, http.StatusOK, map[string]int{"accepted": e.AcceptPeerUnban(r.URL.Query().Get("from"), in.Unbans)})
}
}},
peerRoute{"GET /api/v1/peer/decisions", func(s *Server) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
e := enforceEngine.Load()
if !s.peerGate(w, r) {
return
}
if e == nil || !e.Share() || e.Mode() != enforce.ModeOn {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "decision sharing is not enabled"})
return
}
since, _ := strconv.ParseInt(r.URL.Query().Get("since"), 10, 64)
if min := s.opt.Now().Add(-24 * time.Hour).Unix(); since < min {
since = min
}
writeJSON(w, http.StatusOK, map[string]any{"decisions": e.LocalSince(since)})
}
}},
peerRoute{"POST /api/v1/peer/decisions", func(s *Server) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
e := enforceEngine.Load()
if !s.peerGate(w, r) {
return
}
if e == nil || !e.Share() {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "decision sharing is not enabled"})
return
}
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxDecisionBody))
if err != nil {
var mb *http.MaxBytesError
if errors.As(err, &mb) {
writeJSON(w, http.StatusRequestEntityTooLarge, map[string]string{"error": "body too large"})
} else {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "unreadable body"})
}
return
}
var in struct {
Decisions []enforce.Wire `json:"decisions"`
}
if json.Unmarshal(body, &in) != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON"})
return
}
if len(in.Decisions) > enforce.MaxWire {
writeJSON(w, http.StatusRequestEntityTooLarge, map[string]string{"error": "too many decisions"})
return
}
acc, bad := e.AcceptPeer(r.URL.Query().Get("from"), in.Decisions)
writeJSON(w, http.StatusOK, map[string]int{"accepted": acc, "invalid": bad})
}
}},
)
}
const maxUnbanBody = 1 << 10
@@ -144,14 +61,10 @@ func (s *Server) enforceUnban(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "cross-site request refused"})
return
}
e := enforceEngine.Load()
if e == nil {
writeJSON(w, http.StatusConflict, map[string]string{"error": "the second firewall is off"})
return
}
var in struct {
IP string `json:"ip"`
AllowS int `json:"allow_s"`
Host string `json:"host"`
}
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxUnbanBody))
dec.DisallowUnknownFields()
@@ -160,18 +73,41 @@ func (s *Server) enforceUnban(w http.ResponseWriter, r *http.Request) {
return
}
a, err := netip.ParseAddr(strings.TrimSpace(in.IP))
if err != nil || a.Zone() != "" || in.AllowS < 0 || in.AllowS > enforce.MaxAllow {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid ip or allow_s"})
if err != nil || a.Zone() != "" || in.AllowS < 0 || in.AllowS > enforce.MaxAllow || len(in.Host) > 64 {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid ip, host or allow_s"})
return
}
switch err := e.Unban(a, in.AllowS, "local"); {
case errors.Is(err, enforce.ErrNoUnbanLog):
writeJSON(w, http.StatusConflict, map[string]string{"error": "unban file not configured"})
case err != nil:
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not write the unban request"})
default:
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "ip": a.Unmap().String(), "allow_s": in.AllowS})
var engines []*enforce.Engine
if in.Host == "all" {
hosts := []string{s.primaryName()}
if s.opt.Nodes != nil {
hosts = s.opt.Nodes.Hosts()
}
for _, h := range hosts {
if e := s.enforceFor(h); e != nil {
engines = append(engines, e)
}
}
} else if e := s.enforceFor(in.Host); e != nil {
engines = append(engines, e)
}
if len(engines) == 0 {
writeJSON(w, http.StatusConflict, map[string]string{"error": "the second firewall is off"})
return
}
done := 0
for _, e := range engines {
switch err := e.Unban(a, in.AllowS, "local"); {
case errors.Is(err, enforce.ErrNoUnbanLog):
writeJSON(w, http.StatusConflict, map[string]string{"error": "unban file not configured"})
return
case err != nil:
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not write the unban request"})
return
}
done++
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "ip": a.Unmap().String(), "allow_s": in.AllowS, "hosts": done})
}
func (s *Server) enforceEndAllow(w http.ResponseWriter, r *http.Request) {
@@ -179,7 +115,7 @@ func (s *Server) enforceEndAllow(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "cross-site request refused"})
return
}
e := enforceEngine.Load()
e := s.enforceFor(r.URL.Query().Get("host"))
a, err := netip.ParseAddr(r.URL.Query().Get("ip"))
if e == nil || err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid ip"})
+1 -67
View File
@@ -24,7 +24,7 @@ func enforceRig(t *testing.T, share bool) (http.Handler, *enforce.Engine, string
st.SetIngestHook(e.Observe)
SetEnforce(e)
t.Cleanup(func() { SetEnforce(nil) })
return New(Options{Token: userTok, PeerTokens: []string{peerTok}, Version: "t", Store: st}), e, log
return New(Options{Token: userTok, Version: "t", Store: st}), e, log
}
func TestEnforceAPI(t *testing.T) {
@@ -66,9 +66,6 @@ func TestEnforceAPI(t *testing.T) {
if w := do(h, "GET", "/api/v1/enforce?range=24h", nil, nil); w.Code != 401 {
t.Fatalf("anonymous %d", w.Code)
}
if w := do(h, "GET", "/api/v1/enforce?range=24h", map[string]string{"Authorization": "Bearer " + peerTok}, nil); w.Code != 403 {
t.Fatalf("peer token %d", w.Code)
}
if w := do(h, "GET", "/api/v1/enforce?range=bad", cloneHdr(auth), nil); w.Code != 400 {
t.Fatalf("bad range %d", w.Code)
}
@@ -96,69 +93,6 @@ func post(h http.Handler, path, tok, body string) *httptest.ResponseRecorder {
return w
}
func TestPeerDecisionsEndpoints(t *testing.T) {
h, e, log := enforceRig(t, true)
good := `{"decisions":[{"t":` + strconv.FormatInt(time.Now().Unix(), 10) + `,"ip":"203.0.114.9","reason":"sqli","score":80,"ttl":3600},` +
`{"t":1,"ip":"203.0.114.10","reason":"x\ny","score":80,"ttl":3600},{"ip":"10.0.0.1","reason":"rce","ttl":60}]}`
p := "/api/v1/peer/decisions?from=hostinger"
for _, tok := range []string{"", "wrong-token-0123456789-abcdefghijklmnopqrs", userTok} {
if w := post(h, p, tok, good); w.Code != 401 && w.Code != 403 {
t.Fatalf("token %q: %d", tok, w.Code)
}
if w := do(h, "GET", "/api/v1/peer/decisions", map[string]string{"Authorization": "Bearer " + tok}, nil); w.Code != 401 && w.Code != 403 {
t.Fatalf("GET token %q: %d", tok, w.Code)
}
}
if w := post(h, p, peerTok, strings.Repeat(" ", 70<<10)); w.Code != 413 {
t.Fatalf("big body: %d", w.Code)
}
if w := post(h, p, peerTok, "{nope"); w.Code != 400 {
t.Fatalf("bad json: %d", w.Code)
}
var many strings.Builder
many.WriteString(`{"decisions":[`)
for i := 0; i < 501; i++ {
if i > 0 {
many.WriteString(",")
}
many.WriteString(`{"ip":"1.1.1.1"}`)
}
many.WriteString(`]}`)
if w := post(h, p, peerTok, many.String()); w.Code != 413 {
t.Fatalf("501 items: %d", w.Code)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go e.Run(ctx)
e.Observe(core.Event{Time: time.Now(), IP: "203.0.114.9", Cat: core.Scanner, Source: "traefik", Method: "GET", Path: "/x", Status: 404, UA: "x"}, "")
for i := 0; i < 200 && e.Report(0).Coverage.AttackIPs == 0; i++ {
time.Sleep(10 * time.Millisecond)
}
w := post(h, p, peerTok, good)
if w.Code != 200 || !strings.Contains(w.Body.String(), `"accepted":1`) || !strings.Contains(w.Body.String(), `"invalid":2`) {
t.Fatalf("%d %s", w.Code, w.Body)
}
b, _ := os.ReadFile(log)
if strings.Count(string(b), "\n") != 1 || !strings.Contains(string(b), "ip=203.0.114.9 reason=sqli") || !strings.Contains(string(b), "src=peer:hostinger") {
t.Fatalf("log %q", b)
}
// GET returns local decisions only
if len(e.LocalSince(0)) != 0 {
t.Fatal("peer decision leaked into the local list")
}
rr := do(h, "GET", "/api/v1/peer/decisions?since=0", map[string]string{"Authorization": "Bearer " + peerTok}, nil)
if rr.Code != 200 || !strings.Contains(rr.Body.String(), `"decisions":[]`) {
t.Fatalf("%d %s", rr.Code, rr.Body)
}
}
func TestPeerDecisionsShareOff(t *testing.T) {
h, _, _ := enforceRig(t, false)
if w := post(h, "/api/v1/peer/decisions", peerTok, `{"decisions":[]}`); w.Code != 404 {
t.Fatalf("share off: %d", w.Code)
}
}
func TestEnforceFromStoreHook(t *testing.T) {
log := filepath.Join(t.TempDir(), "d.log")
st := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour})
+212 -20
View File
@@ -6,6 +6,7 @@ import (
"encoding/json"
"errors"
"net/http"
"sort"
"strconv"
"strings"
"sync"
@@ -25,6 +26,10 @@ func init() {
registerUserRoute("POST /api/v1/incidents", func(s *Server) http.HandlerFunc { return s.incidentCreate })
registerUserRoute("PATCH /api/v1/incidents/{id}", func(s *Server) http.HandlerFunc { return s.incidentPatch })
registerUserRoute("POST /api/v1/incidents/{id}/comments", func(s *Server) http.HandlerFunc { return s.incidentComment })
// host/INC-n written as two path segments
registerUserRoute("GET /api/v1/incidents/{host}/{id}", func(s *Server) http.HandlerFunc { return s.incidentGet })
registerUserRoute("PATCH /api/v1/incidents/{host}/{id}", func(s *Server) http.HandlerFunc { return s.incidentPatch })
registerUserRoute("POST /api/v1/incidents/{host}/{id}/comments", func(s *Server) http.HandlerFunc { return s.incidentComment })
}
var incidentServer atomic.Pointer[Server]
@@ -55,14 +60,31 @@ func StartIncidentSync(ctx context.Context, wg *sync.WaitGroup) {
}
func (s *Server) syncNow(ctx context.Context) {
if s.opt.Incidents == nil || egressEngine.Load() == nil {
if s.opt.Incidents == nil {
return
}
now := s.opt.Store.Now().Unix()
if s.opt.Nodes != nil { // one store per node, fed by that node's own egress
for _, h := range s.opt.Nodes.Hosts() {
eng, st := s.opt.Nodes.Egress(h), s.opt.Nodes.Incidents(h)
if eng == nil || st == nil {
continue
}
rep := eng.Report(now-24*3600, now)
for i := range rep.Findings {
rep.Findings[i].Host = h
}
s.syncInto(st, rep)
}
return
}
if egressEngine.Load() == nil {
return
}
cctx, cancel := context.WithTimeout(ctx, 20*time.Second)
defer cancel()
rep, _ := s.egressReport(cctx, now-24*3600, now, true, s.opt.Hub != nil, "")
s.syncIncidents(rep)
s.syncInto(s.opt.Incidents, rep)
}
func (s *Server) findingHost(f egress.Finding) string {
@@ -76,8 +98,10 @@ func (s *Server) findingKey(f egress.Finding) string {
return incidents.Key(s.findingHost(f), f.Kind, f.Workload, f.Dst, f.DPort, f.Proto)
}
func (s *Server) syncIncidents(rep egress.Report) {
if s.opt.Incidents == nil {
func (s *Server) syncIncidents(rep egress.Report) { s.syncInto(s.opt.Incidents, rep) }
func (s *Server) syncInto(st *incidents.Store, rep egress.Report) {
if st == nil {
return
}
fs := make([]incidents.Finding, 0, len(rep.Findings))
@@ -85,7 +109,7 @@ func (s *Server) syncIncidents(rep egress.Report) {
fs = append(fs, incidents.Finding{Host: s.findingHost(f), Kind: f.Kind, Severity: f.Severity, Workload: f.Workload, Dst: f.Dst,
Proto: f.Proto, Detail: f.Detail, DPort: f.DPort, First: f.First, Last: f.Last, Count: f.Count})
}
s.opt.Incidents.Sync(fs)
st.Sync(fs)
}
// annotateFindings fills ticket_id/ticket_status/suppressed and, unless show
@@ -95,16 +119,35 @@ func (s *Server) annotateFindings(rep *egress.Report, show bool) int {
if s.opt.Incidents == nil || len(rep.Findings) == 0 {
return 0
}
keys := make([]string, len(rep.Findings))
refs := make([]incidents.Ref, len(rep.Findings))
has := make([]bool, len(rep.Findings))
byStore := map[string][]int{}
for i, f := range rep.Findings {
keys[i] = s.findingKey(f)
h := s.findingHost(f)
byStore[h] = append(byStore[h], i)
}
for h, idx := range byStore {
st := s.incStore(h)
if st == nil {
continue
}
keys := make([]string, len(idx))
for j, i := range idx {
keys[j] = s.findingKey(rep.Findings[i])
}
m := st.Lookup(keys)
for j, i := range idx {
if ref, ok := m[keys[j]]; ok {
ref.ID = h + "/" + ref.ID
refs[i], has[i] = ref, true
}
}
}
refs := s.opt.Incidents.Lookup(keys)
out := rep.Findings[:0:0]
n := 0
for i, f := range rep.Findings {
if ref, ok := refs[keys[i]]; ok {
f.TicketID, f.TicketStatus, f.Suppressed = ref.ID, ref.Status, ref.Suppress
if has[i] {
f.TicketID, f.TicketStatus, f.Suppressed = refs[i].ID, refs[i].Status, refs[i].Suppress
}
if f.Suppressed {
n++
@@ -191,6 +234,54 @@ func (s *Server) incidentQuery(w http.ResponseWriter, r *http.Request) (incident
return q, true
}
// qSummary and qTicket carry the id qualified by the node ("hostinger/INC-2")
// and the node as host.
type qSummary struct {
incidents.Summary
ID string `json:"id"`
Host string `json:"host"`
}
type qTicket struct {
incidents.Ticket
ID string `json:"id"`
Host string `json:"host"`
}
type qPage struct {
Items []qSummary `json:"items"`
Total int `json:"total"`
Counts map[string]int `json:"counts"`
Store incidents.Stats `json:"store"`
Hosts []string `json:"hosts"`
}
// splitID reads "INC-n" with an optional host (path segment, "host/INC-n"
// in one segment, or ?host=); without host the primary node is meant.
func (s *Server) splitID(r *http.Request) (host, id string) {
id = r.PathValue("id")
host = r.PathValue("host")
if h, rest, ok := strings.Cut(id, "/"); ok {
host, id = h, rest
}
if host == "" {
host = r.URL.Query().Get("host")
}
if host == "" {
host = s.primaryName()
}
return host, id
}
// storeFor answers 404 itself when the node has no ticket store.
func (s *Server) storeFor(w http.ResponseWriter, host string) *incidents.Store {
if st := s.incStore(host); st != nil {
return st
}
writeJSON(w, http.StatusNotFound, map[string]string{"error": "incident not found"})
return nil
}
func (s *Server) incidentList(w http.ResponseWriter, r *http.Request) {
if !s.incidentsOn(w) {
return
@@ -199,19 +290,93 @@ func (s *Server) incidentList(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
writeJSON(w, 200, s.opt.Incidents.List(q))
hosts := s.incHosts()
if q.Host != "" && q.Host != "all" {
hosts = []string{q.Host}
if s.incStore(q.Host) == nil {
writeJSON(w, 200, qPage{Items: []qSummary{}, Counts: map[string]int{}, Hosts: s.incHosts()})
return
}
}
q.Host = ""
if len(hosts) == 1 {
pg := s.incStore(hosts[0]).List(q)
out := qPage{Items: make([]qSummary, 0, len(pg.Items)), Total: pg.Total, Counts: pg.Counts, Store: pg.Store, Hosts: s.incHosts()}
for _, it := range pg.Items {
out.Items = append(out.Items, qSummary{Summary: it, ID: hosts[0] + "/" + it.ID, Host: hosts[0]})
}
writeJSON(w, 200, out)
return
}
// several nodes: merge, sort and page here
all := []qSummary{}
out := qPage{Counts: map[string]int{}, Hosts: s.incHosts()}
page, per := q.Page, q.PerPage
for _, h := range hosts {
st := s.incStore(h)
if st == nil {
continue
}
pg := st.List(incidents.Query{Status: q.Status, Severity: q.Severity, Q: q.Q, Sort: q.Sort, Page: 1, PerPage: 1})
for k, v := range pg.Counts {
out.Counts[k] += v
}
out.Store.Size += pg.Store.Size
out.Store.Max += pg.Store.Max
out.Store.Untracked += pg.Store.Untracked
for _, it := range st.All(q) {
all = append(all, qSummary{Summary: it, ID: h + "/" + it.ID, Host: h})
}
}
sortSummaries(all, q.Sort)
if per <= 0 {
per = 50
}
per = min(per, 200)
if page < 1 {
page = 1
}
lo := min((page-1)*per, len(all))
hi := min(lo+per, len(all))
out.Total, out.Items = len(all), all[lo:hi]
if out.Items == nil {
out.Items = []qSummary{}
}
writeJSON(w, 200, out)
}
func sortSummaries(l []qSummary, mode string) {
sort.SliceStable(l, func(i, j int) bool {
a, b := l[i], l[j]
switch mode {
case "severity":
if ra, rb := incidents.SevRank(a.Severity), incidents.SevRank(b.Severity); ra != rb {
return ra > rb
}
case "last_seen":
if a.LastSeen != b.LastSeen {
return a.LastSeen > b.LastSeen
}
}
return a.UpdatedAt > b.UpdatedAt
})
}
func (s *Server) incidentGet(w http.ResponseWriter, r *http.Request) {
if !s.incidentsOn(w) {
return
}
t, err := s.opt.Incidents.Get(r.PathValue("id"))
host, id := s.splitID(r)
st := s.storeFor(w, host)
if st == nil {
return
}
t, err := st.Get(id)
if err != nil {
incidentErr(w, err)
return
}
writeJSON(w, 200, t)
writeJSON(w, 200, qTicket{Ticket: t, ID: host + "/" + t.ID, Host: host})
}
func (s *Server) incidentCreate(w http.ResponseWriter, r *http.Request) {
@@ -223,12 +388,16 @@ func (s *Server) incidentCreate(w http.ResponseWriter, r *http.Request) {
return
}
in.Via = s.via(r)
t, err := s.opt.Incidents.Create(in)
host := s.primaryName()
if in.Host != "" && s.incStore(in.Host) != nil {
host = in.Host
}
t, err := s.incStore(host).Create(in)
if err != nil {
incidentErr(w, err)
return
}
writeJSON(w, http.StatusCreated, t)
writeJSON(w, http.StatusCreated, qTicket{Ticket: t, ID: host + "/" + t.ID, Host: host})
}
func (s *Server) incidentPatch(w http.ResponseWriter, r *http.Request) {
@@ -240,12 +409,17 @@ func (s *Server) incidentPatch(w http.ResponseWriter, r *http.Request) {
return
}
p.Via = s.via(r)
t, err := s.opt.Incidents.Update(r.PathValue("id"), p)
host, id := s.splitID(r)
st := s.storeFor(w, host)
if st == nil {
return
}
t, err := st.Update(id, p)
if err != nil {
incidentErr(w, err)
return
}
writeJSON(w, 200, t)
writeJSON(w, 200, qTicket{Ticket: t, ID: host + "/" + t.ID, Host: host})
}
func (s *Server) incidentComment(w http.ResponseWriter, r *http.Request) {
@@ -259,12 +433,17 @@ func (s *Server) incidentComment(w http.ResponseWriter, r *http.Request) {
if !incidentBody(w, r, &in) {
return
}
t, err := s.opt.Incidents.AddComment(r.PathValue("id"), in.Text, in.Author, s.via(r))
host, id := s.splitID(r)
st := s.storeFor(w, host)
if st == nil {
return
}
t, err := st.AddComment(id, in.Text, in.Author, s.via(r))
if err != nil {
incidentErr(w, err)
return
}
writeJSON(w, http.StatusCreated, t)
writeJSON(w, http.StatusCreated, qTicket{Ticket: t, ID: host + "/" + t.ID, Host: host})
}
// csvCell neutralises spreadsheet formulas.
@@ -301,7 +480,20 @@ func (s *Server) incidentCSV(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Disposition", `attachment; filename="incidents.csv"`)
cw := csv.NewWriter(w)
cw.Write([]string{"id", "status", "severity", "host", "kind", "workload", "dst", "dport", "proto", "title", "first_seen", "last_seen", "count", "assignee", "tags", "verdict", "suppress", "created_at", "updated_at"})
for _, t := range s.opt.Incidents.All(q) {
hosts := s.incHosts()
if q.Host != "" && q.Host != "all" {
hosts = []string{q.Host}
}
q.Host = ""
var rows []qSummary
for _, h := range hosts {
if st := s.incStore(h); st != nil {
for _, t := range st.All(q) {
rows = append(rows, qSummary{Summary: t, ID: h + "/" + t.ID, Host: h})
}
}
}
for _, t := range rows {
row := []string{t.ID, t.Status, t.Severity, t.Host, t.Kind, t.Workload, t.Dst, strconv.Itoa(int(t.DPort)), t.Proto, t.Title,
strconv.FormatInt(t.FirstSeen, 10), strconv.FormatInt(t.LastSeen, 10), strconv.Itoa(t.Count), t.Assignee, strings.Join(t.Tags, ","), t.Verdict,
strconv.FormatBool(t.Suppress), strconv.FormatInt(t.CreatedAt, 10), strconv.FormatInt(t.UpdatedAt, 10)}
+4 -7
View File
@@ -23,7 +23,7 @@ func incRig(t *testing.T) http.Handler {
if err != nil {
t.Fatal(err)
}
return New(Options{Token: userTok, PeerTokens: []string{peerTok}, Version: "t", Store: st, Incidents: inc})
return New(Options{Token: userTok, Version: "t", Store: st, Incidents: inc})
}
func TestIncidentsEgressSuppression(t *testing.T) {
@@ -50,11 +50,11 @@ func TestIncidentsEgressSuppression(t *testing.T) {
f = m
}
}
if f == nil || f["ticket_id"] != "INC-1" || f["ticket_status"] != "open" || f["suppressed"] != false || d["suppressed_count"].(float64) != 0 {
if f == nil || f["ticket_id"] != "oracle/INC-1" || f["ticket_status"] != "open" || f["suppressed"] != false || d["suppressed_count"].(float64) != 0 {
t.Fatalf("annotated: %v", d)
}
// suppression needs false_positive/benign
if w := do(h, "GET", "/api/v1/incidents", cloneHdr(auth), nil); w.Code != 200 || !strings.Contains(w.Body.String(), `"INC-1"`) || strings.Contains(w.Body.String(), `"history"`) || !strings.Contains(w.Body.String(), `"comment_count"`) {
if w := do(h, "GET", "/api/v1/incidents", cloneHdr(auth), nil); w.Code != 200 || !strings.Contains(w.Body.String(), `"oracle/INC-1"`) || strings.Contains(w.Body.String(), `"history"`) || !strings.Contains(w.Body.String(), `"comment_count"`) {
t.Fatalf("list: %d %s", w.Code, w.Body)
}
if w := req(h, "PATCH", "/api/v1/incidents/INC-1", `{"suppress":true}`, auth); w.Code != 409 {
@@ -99,9 +99,6 @@ func TestIncidentsAPI(t *testing.T) {
if w := req(h, p[0], p[1], `{}`, nil); w.Code != 401 {
t.Errorf("%v no auth: %d", p, w.Code)
}
if w := req(h, p[0], p[1], `{}`, map[string]string{"Authorization": "Bearer " + peerTok}); w.Code != 403 {
t.Errorf("%v peer token: %d", p, w.Code)
}
}
cross := map[string]string{"Authorization": "Bearer " + userTok, "Sec-Fetch-Site": "cross-site"}
for _, p := range paths[2:5] {
@@ -115,7 +112,7 @@ func TestIncidentsAPI(t *testing.T) {
}
var tk map[string]any
json.Unmarshal(w.Body.Bytes(), &tk)
if tk["id"] != "INC-1" || tk["source"] != "manual" || tk["status"] != "open" {
if tk["id"] != "oracle/INC-1" || tk["source"] != "manual" || tk["status"] != "open" {
t.Fatalf("ticket: %v", tk)
}
bad := []struct{ m, p, b string }{
+1 -25
View File
@@ -22,7 +22,7 @@ func unbanRig(t *testing.T) (http.Handler, *enforce.Engine, string) {
Host: "oracle", Threshold: 3, Share: true})
SetEnforce(e)
t.Cleanup(func() { SetEnforce(nil) })
return New(Options{Token: userTok, PeerTokens: []string{peerTok}, Version: "t", Store: st}), e, filepath.Join(dir, "unban.log")
return New(Options{Token: userTok, Version: "t", Store: st}), e, filepath.Join(dir, "unban.log")
}
func req(h http.Handler, method, path, body string, hdr map[string]string) *httptest.ResponseRecorder {
@@ -42,9 +42,6 @@ func TestUnbanRoute(t *testing.T) {
if w := req(h, "POST", "/api/v1/enforce/unban", `{"ip":"203.0.113.7","allow_s":60}`, nil); w.Code != 401 {
t.Fatalf("no auth: %d", w.Code)
}
if w := req(h, "POST", "/api/v1/enforce/unban", `{"ip":"203.0.113.7"}`, map[string]string{"Authorization": "Bearer " + peerTok}); w.Code != 403 {
t.Fatalf("peer token: %d", w.Code)
}
cross := map[string]string{"Authorization": "Bearer " + userTok, "Sec-Fetch-Site": "cross-site"}
if w := req(h, "POST", "/api/v1/enforce/unban", `{"ip":"203.0.113.7"}`, cross); w.Code != 403 {
t.Fatalf("cross-site: %d", w.Code)
@@ -96,24 +93,3 @@ func TestUnbanRoute(t *testing.T) {
t.Fatal("DELETE wrote to the host file")
}
}
func TestPeerUnbanRoute(t *testing.T) {
h, e, file := unbanRig(t)
peer := map[string]string{"Authorization": "Bearer " + peerTok}
if w := req(h, "POST", "/api/v1/peer/unban?from=hostinger", `{"unbans":[{"ip":"203.0.113.7","allow":3600},{"ip":"bad","allow":1}]}`, map[string]string{"Authorization": "Bearer " + userTok}); w.Code == 200 {
t.Fatalf("user token accepted on peer route")
}
w := req(h, "POST", "/api/v1/peer/unban?from=hostinger", `{"unbans":[{"ip":"203.0.113.7","allow":3600},{"ip":"bad","allow":1}]}`, peer)
if w.Code != 200 || !strings.Contains(w.Body.String(), `"accepted":1`) {
t.Fatalf("%d %s", w.Code, w.Body)
}
if len(e.Allows()) != 1 {
t.Fatal("peer allow not applied")
}
if b, _ := os.ReadFile(file); !strings.Contains(string(b), "ip=203.0.113.7 allow=3600") {
t.Fatalf("file: %q", b)
}
if len(e.UnbansSince(0)) != 0 {
t.Fatal("peer unban must not be echoed back")
}
}
+28
View File
@@ -0,0 +1,28 @@
package server
import (
"encoding/json"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
// fakeBackend is an in-process node serving a fixed export.
type fakeBackend struct {
name string
exp store.PeerExport
}
func (f fakeBackend) Name() string { return f.name }
func (f fakeBackend) Export(store.Range) store.PeerExport { return f.exp }
func (f fakeBackend) Study(q store.PeriodQuery) store.PeerStudy {
return store.PeerStudy{}
}
func (f fakeBackend) Egress(from, to int64) json.RawMessage { return nil }
func (f fakeBackend) Subscribe() (<-chan store.LiveEvent, func()) {
return make(chan store.LiveEvent), func() {}
}
func (f fakeBackend) SubscribeVisits() (<-chan store.VisitMsg, func()) {
return make(chan store.VisitMsg), func() {}
}
func (f fakeBackend) Online() bool { return true }
func (f fakeBackend) Location() *store.Location { return nil }
Loaded 100 of 130 files, more files were not shown because too many files have changed in this diff. Show more