From 8546d14cef3571b7f00387279b9f581e87d104e7 Mon Sep 17 00:00:00 2001 From: Lucas Rayan Date: Sun, 15 Nov 2026 22:14:50 -0300 Subject: [PATCH] feat!: Urutau 2.0.0, ultralight probes and a single analysis hub 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 --- .env.example | 27 +- .gitea/workflows/ci.yml | 22 +- .gitea/workflows/release.yml | 75 +- CHANGELOG.md | 30 +- CHANGELOG.pt-BR.md | 30 +- CONTRIBUTING.md | 8 +- CONTRIBUTING.pt-BR.md | 8 +- Dockerfile | 53 +- README.md | 86 +- README.pt-BR.md | 88 +- ROADMAP.md | 6 +- ROADMAP.pt-BR.md | 6 +- SECURITY.md | 20 +- SECURITY.pt-BR.md | 18 +- cmd/urutau/main.go | 14 +- cmd/urutau/probe.go | 232 +++++ deploy/host/install.sh | 45 +- deploy/probe/.env.example | 12 + deploy/probe/docker-compose.yml | 70 ++ docker-compose.yml | 42 +- docs/architecture.md | 90 +- docs/cli.md | 99 ++- docs/configuration.md | 95 ++- docs/docker.md | 110 +-- docs/interface.md | 22 +- docs/migration-2.0.md | 172 ++++ docs/pt-BR/arquitetura.md | 100 ++- docs/pt-BR/cli.md | 99 ++- docs/pt-BR/configuracao.md | 97 ++- docs/pt-BR/docker.md | 108 +-- docs/pt-BR/interface.md | 22 +- docs/pt-BR/migracao-2.0.md | 49 ++ docs/pt-BR/suporte.md | 18 +- docs/support.md | 18 +- internal/app/app_test.go | 136 +-- internal/app/config.go | 252 ++---- internal/app/doctor.go | 4 +- internal/app/egress.go | 70 +- internal/app/enforce.go | 139 +-- internal/app/import.go | 795 ++++++++++++++++++ internal/app/import_test.go | 537 ++++++++++++ internal/app/node.go | 357 ++++++++ internal/app/serve.go | 287 ++++--- internal/app/sources.go | 165 +++- .../app/testdata/hostinger-1.6.expected.json | 11 + .../app/testdata/hostinger-1.6/enforce.json | 1 + .../hostinger-1.6/events/2026-11-12.jsonl | 2 + .../hostinger-1.6/events/2026-11-13.jsonl | 5 + .../hostinger-1.6/events/2026-11-15.jsonl | 10 + .../hostinger-1.6/geo/GeoLite2-City.mmdb | 1 + .../app/testdata/hostinger-1.6/incidents.json | 1 + .../testdata/hostinger-1.6/operator-notes.txt | 1 + .../hostinger-1.6/tor/exit-addresses.txt | 2 + .../testdata/hostinger-1.6/tor/relays.json | 1 + .../testdata/hostinger-1.6/urutau-state.gob | Bin 0 -> 52827 bytes internal/app/tor_lists_test.go | 2 +- internal/app/v2_test.go | 6 +- internal/app/v4_test.go | 53 +- internal/app/version.go | 2 +- internal/egress/egress_test.go | 6 +- internal/egress/engine.go | 29 +- internal/egress/source.go | 22 + internal/egress/workload.go | 8 +- internal/enforce/engine.go | 21 +- internal/enforce/unban.go | 8 +- internal/fed/decisions.go | 46 - internal/fed/egress.go | 42 - internal/fed/export_test.go | 13 - internal/fed/fed.go | 521 ++++-------- internal/fed/fed_test.go | 182 +--- internal/fed/live.go | 229 ++--- internal/fed/live_test.go | 216 ----- internal/fed/study.go | 87 -- internal/fed/v2_test.go | 115 --- internal/fed/v3_test.go | 120 --- internal/hub/cmdqueue.go | 191 +++++ internal/hub/ingest.go | 254 ++++++ internal/hub/integration_test.go | 671 +++++++++++++++ internal/hub/manager.go | 305 +++++++ internal/hub/registry.go | 214 +++++ internal/hub/registry_test.go | 59 ++ internal/probeagent/client.go | 198 +++++ internal/probeagent/cmds.go | 55 ++ internal/probeagent/inode_test.go | 8 + internal/probeagent/norace_test.go | 5 + internal/probeagent/probe.go | 435 ++++++++++ internal/probeagent/probe_test.go | 742 ++++++++++++++++ internal/probeagent/race_test.go | 5 + internal/probeagent/spool.go | 176 ++++ internal/probeagent/spool_test.go | 129 +++ internal/probeagent/state.go | 176 ++++ internal/probeagent/tailer.go | 230 +++++ internal/server/api_egress.go | 20 - internal/server/api_egress_test.go | 29 - internal/server/api_enforce.go | 146 +--- internal/server/api_enforce_test.go | 68 +- internal/server/api_incidents.go | 232 ++++- internal/server/api_incidents_test.go | 11 +- internal/server/api_unban_test.go | 26 +- internal/server/fakehub_test.go | 28 + internal/server/hardening_test.go | 66 +- internal/server/investigate.go | 27 - internal/server/live_test.go | 134 +-- internal/server/probes.go | 164 ++++ internal/server/server.go | 164 +--- internal/server/server_test.go | 64 +- internal/server/v2_test.go | 6 +- internal/server/web/app.js | 89 +- internal/server/web/defense.js | 12 +- internal/server/web/egress.js | 2 +- internal/server/web/i18n.js | 24 +- internal/server/web/incidents.js | 26 +- internal/server/web/integrity.js | 36 +- internal/server/web/live.css | 3 +- internal/server/web/live.js | 54 +- internal/server/web/pages.json | 4 + internal/server/web/probes.css | 44 + internal/server/web/probes.js | 430 ++++++++++ internal/server/web/replay.js | 16 +- internal/server/web/style.css | 9 + internal/store/live.go | 17 +- internal/store/store.go | 2 + internal/tail/hardening_test.go | 121 +++ internal/tail/tail.go | 21 +- internal/wire/wire_test.go | 104 +++ scripts/check-docs-links.py | 42 + scripts/check.sh | 4 +- scripts/screenshots.sh | 59 +- scripts/smoke-image.sh | 20 +- scripts/smoke-probe.sh | 34 + 130 files changed, 9396 insertions(+), 3311 deletions(-) create mode 100644 cmd/urutau/probe.go create mode 100644 deploy/probe/.env.example create mode 100644 deploy/probe/docker-compose.yml create mode 100644 docs/migration-2.0.md create mode 100644 docs/pt-BR/migracao-2.0.md create mode 100644 internal/app/import.go create mode 100644 internal/app/import_test.go create mode 100644 internal/app/node.go create mode 100644 internal/app/testdata/hostinger-1.6.expected.json create mode 100644 internal/app/testdata/hostinger-1.6/enforce.json create mode 100644 internal/app/testdata/hostinger-1.6/events/2026-11-12.jsonl create mode 100644 internal/app/testdata/hostinger-1.6/events/2026-11-13.jsonl create mode 100644 internal/app/testdata/hostinger-1.6/events/2026-11-15.jsonl create mode 100644 internal/app/testdata/hostinger-1.6/geo/GeoLite2-City.mmdb create mode 100644 internal/app/testdata/hostinger-1.6/incidents.json create mode 100644 internal/app/testdata/hostinger-1.6/operator-notes.txt create mode 100644 internal/app/testdata/hostinger-1.6/tor/exit-addresses.txt create mode 100644 internal/app/testdata/hostinger-1.6/tor/relays.json create mode 100644 internal/app/testdata/hostinger-1.6/urutau-state.gob delete mode 100644 internal/fed/decisions.go delete mode 100644 internal/fed/egress.go delete mode 100644 internal/fed/export_test.go delete mode 100644 internal/fed/live_test.go delete mode 100644 internal/fed/study.go delete mode 100644 internal/fed/v2_test.go delete mode 100644 internal/fed/v3_test.go create mode 100644 internal/hub/cmdqueue.go create mode 100644 internal/hub/ingest.go create mode 100644 internal/hub/integration_test.go create mode 100644 internal/hub/manager.go create mode 100644 internal/hub/registry.go create mode 100644 internal/hub/registry_test.go create mode 100644 internal/probeagent/client.go create mode 100644 internal/probeagent/cmds.go create mode 100644 internal/probeagent/inode_test.go create mode 100644 internal/probeagent/norace_test.go create mode 100644 internal/probeagent/probe.go create mode 100644 internal/probeagent/probe_test.go create mode 100644 internal/probeagent/race_test.go create mode 100644 internal/probeagent/spool.go create mode 100644 internal/probeagent/spool_test.go create mode 100644 internal/probeagent/state.go create mode 100644 internal/probeagent/tailer.go create mode 100644 internal/server/fakehub_test.go create mode 100644 internal/server/probes.go create mode 100644 internal/server/web/probes.css create mode 100644 internal/server/web/probes.js create mode 100644 internal/wire/wire_test.go create mode 100755 scripts/check-docs-links.py create mode 100755 scripts/smoke-probe.sh diff --git a/.env.example b/.env.example index a8e50f7..e805745 100644 --- a/.env.example +++ b/.env.example @@ -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_ -# 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 /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= diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 5cf3979..9418aed 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -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 diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml index 7fbf52d..da12cef 100644 --- a/.gitea/workflows/release.yml +++ b/.gitea/workflows/release.yml @@ -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 () and the probe (-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- 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- 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 diff --git a/CHANGELOG.md b/CHANGELOG.md index dd5c2c4..a84a485 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/CHANGELOG.pt-BR.md b/CHANGELOG.pt-BR.md index 74cfc55..0925a90 100644 --- a/CHANGELOG.pt-BR.md +++ b/CHANGELOG.pt-BR.md @@ -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 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 996f0de..7f74054 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -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 diff --git a/CONTRIBUTING.pt-BR.md b/CONTRIBUTING.pt-BR.md index 37d2879..867b1f5 100644 --- a/CONTRIBUTING.pt-BR.md +++ b/CONTRIBUTING.pt-BR.md @@ -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 diff --git a/Dockerfile b/Dockerfile index 98ef0a4..4e6e7ea 100644 --- a/Dockerfile +++ b/Dockerfile @@ -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 diff --git a/README.md b/README.md index fa74dbb..85b9575 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@

Urutau

Lightweight, always-on threat intelligence and privacy-friendly web analytics for self-hosted servers.
Go, single static binary · local-first · authorized use.

-

Terminal · Interface · Architecture · Configuration · Docker · Support · Roadmap · Changelog

+

Terminal · Interface · Architecture · Configuration · Docker · Support · Migrating to 2.0 · Roadmap · Changelog

English · Português

@@ -22,14 +22,14 @@

Urutau overview on a phone Urutau defense page on a phone
The phone layout: a tab bar replaces the side rail and tables become cards.

-**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//...`, `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-`) 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-` (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-` (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/`), 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 | diff --git a/README.pt-BR.md b/README.pt-BR.md index a23d43b..8499990 100644 --- a/README.pt-BR.md +++ b/README.pt-BR.md @@ -2,7 +2,7 @@

Urutau

Threat intelligence leve e sempre ligado e web analytics amigável à privacidade para servidores self-hosted.
Go, binário estático único · local-first · uso autorizado.

-

Terminal · Interface · Arquitetura · Configuração · Docker · Suporte · Roadmap · Changelog

+

Terminal · Interface · Arquitetura · Configuração · Docker · Suporte · Migrar para a 2.0 · Roadmap · Changelog

English · Português

@@ -22,14 +22,14 @@

Visão geral do Urutau no celular Página Defesa do Urutau no celular
O layout de celular: uma barra de abas substitui a lateral e as tabelas viram cartões.

-**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//...`, `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-`) 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-` (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-` (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/`), 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 | diff --git a/ROADMAP.md b/ROADMAP.md index 918f58e..8ebe790 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -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. diff --git a/ROADMAP.pt-BR.md b/ROADMAP.pt-BR.md index 0e63178..25f2b87 100644 --- a/ROADMAP.pt-BR.md +++ b/ROADMAP.pt-BR.md @@ -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. diff --git a/SECURITY.md b/SECURITY.md index f5b2c36..0dcdf89 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -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_` 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 `/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):** `/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. diff --git a/SECURITY.pt-BR.md b/SECURITY.pt-BR.md index f7ec3ef..31de3c1 100644 --- a/SECURITY.pt-BR.md +++ b/SECURITY.pt-BR.md @@ -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_` 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 `/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):** `/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. diff --git a/cmd/urutau/main.go b/cmd/urutau/main.go index 82da619..c185f39 100644 --- a/cmd/urutau/main.go +++ b/cmd/urutau/main.go @@ -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: diff --git a/cmd/urutau/probe.go b/cmd/urutau/probe.go new file mode 100644 index 0000000..e285a8f --- /dev/null +++ b/cmd/urutau/probe.go @@ -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 /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 +} diff --git a/deploy/host/install.sh b/deploy/host/install.sh index 5c923c3..302b45b 100644 --- a/deploy/host/install.sh +++ b/deploy/host/install.sh @@ -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 ) and start deploy/probe/docker-compose.yml" fi diff --git a/deploy/probe/.env.example b/deploy/probe/.env.example new file mode 100644 index 0000000..c1b9798 --- /dev/null +++ b/deploy/probe/.env.example @@ -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 +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 diff --git a/deploy/probe/docker-compose.yml b/deploy/probe/docker-compose.yml new file mode 100644 index 0000000..7c8c93a --- /dev/null +++ b/deploy/probe/docker-compose.yml @@ -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 # 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 diff --git a/docker-compose.yml b/docker-compose.yml index dbb0d5f..1d57069 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -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 # 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] diff --git a/docs/architecture.md b/docs/architecture.md index cb46948..d3e7810 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -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 `/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 `