refactor!: rename project from Xexéu to Harpia
Release / Build image (amd64) (push) Successful in 10m49s
Release / Plan (reuse the published image?) (push) Successful in 5s
Release / ci (push) Successful in 20m40s
CI / Format and clippy (push) Successful in 5m43s
CI / Tests (Linux) (push) Successful in 16m5s
CI / Dependency audit (push) Successful in 11s
CI / Docker image (build and smoke test) (push) Skipped
Release / Build image (arm64) (push) Successful in 7m34s
Release / Publish tags (push) Successful in 15s
Release / Gitea release (push) Skipped
Release / CLI (linux-aarch64) (push) Skipped
Release / CLI (linux-x86_64) (push) Skipped

Renames the whole project, after the harpy eagle: crates
(xexeu-core/xexeu-cli -> harpia-core/harpia-cli), binary (xexeu ->
harpia), admin token env var (XEXEU_ADMIN_TOKEN -> HARPIA_ADMIN_TOKEN),
compose env vars (XEXEU_* -> HARPIA_*), container image
(ciberfauna/xexeu -> ciberfauna/harpia) and the Gitea repository
(ciberfauna/xexeu -> ciberfauna/harpia). Logo updated to the new brand
artwork. All docs (EN/PT-BR), CI workflows, scripts, GUI strings and
the openspec change history updated to match.

BREAKING CHANGE: binary, crate, env var and image names all changed;
existing .env files, scripts and deployments referencing the old
xexeu/XEXEU names must be updated.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VAyr8cd6jzwpJM9cS1oGjy
This commit is contained in:
Lucas RayanandClaude Sonnet 5 committed 2026-11-03 13:43:21 -03:00
1 parent 1dc754a561
commit 5ed6cb2c95
93 files changed
+849 -826

No files matched your search

+10 -10
View File
@@ -1,14 +1,14 @@
# Xexéu image tag: latest (last release), X.Y.Z / X.Y (pinned), or edge (main).
XEXEU_VERSION=latest
# Harpia image tag: latest (last release), X.Y.Z / X.Y (pinned), or edge (main).
HARPIA_VERSION=latest
# Host address and port of the dashboard. Keep it on loopback unless an
# authenticating reverse proxy sits in front of it.
XEXEU_PUBLISH=127.0.0.1:8788
HARPIA_PUBLISH=127.0.0.1:8788
# Admin token for the dashboard actions that change the configuration (group
# CRUD). At least 16 characters, e.g. `openssl rand -hex 32`. Empty: a new one
# is generated at each start and printed in `docker compose logs xexeu`.
XEXEU_ADMIN_TOKEN=
# Xexéu container image repository.
XEXEU_IMAGE=git.lucasrguerra.dev.br/ciberfauna/xexeu
# Key that signs webhook bodies (X-Xexeu-Signature) when a [[webhook]] sets
# segredo_env = "XEXEU_WEBHOOK_KEY". Empty: webhooks go unsigned.
XEXEU_WEBHOOK_KEY=
# is generated at each start and printed in `docker compose logs harpia`.
HARPIA_ADMIN_TOKEN=
# Harpia container image repository.
HARPIA_IMAGE=git.lucasrguerra.dev.br/ciberfauna/harpia
# Key that signs webhook bodies (X-Harpia-Signature) when a [[webhook]] sets
# segredo_env = "HARPIA_WEBHOOK_KEY". Empty: webhooks go unsigned.
HARPIA_WEBHOOK_KEY=
+3 -3
View File
@@ -8,10 +8,10 @@ body:
validations: { required: true }
- type: input
id: system
attributes: { label: "Operating system and Xexéu version", placeholder: "Ubuntu 24.04 / xexeu 0.1.0" }
attributes: { label: "Operating system and Harpia version", placeholder: "Ubuntu 24.04 / harpia 0.1.0" }
- type: input
id: input
attributes: { label: "Target or configuration", placeholder: "CIDR / target specification, xexeu.toml configuration snippet, or scan profile" }
attributes: { label: "Target or configuration", placeholder: "CIDR / target specification, harpia.toml configuration snippet, or scan profile" }
- type: textarea
id: log
attributes: { label: "Terminal output (xexeu doctor / scan / serve)", render: shell }
attributes: { label: "Terminal output (harpia doctor / scan / serve)", render: shell }
+5 -5
View File
@@ -22,7 +22,7 @@ jobs:
name: Format and clippy
runs-on: linux-arm64
env:
CARGO_TARGET_DIR: /opt/hostedtoolcache/cargo-target/xexeu-lint
CARGO_TARGET_DIR: /opt/hostedtoolcache/cargo-target/harpia-lint
steps:
- uses: actions/checkout@v7
- uses: dtolnay/rust-toolchain@stable
@@ -51,7 +51,7 @@ jobs:
name: Tests (Linux)
runs-on: linux-arm64
env:
CARGO_TARGET_DIR: /opt/hostedtoolcache/cargo-target/xexeu-test
CARGO_TARGET_DIR: /opt/hostedtoolcache/cargo-target/harpia-test
steps:
- uses: actions/checkout@v7
- uses: dtolnay/rust-toolchain@stable
@@ -75,9 +75,9 @@ jobs:
steps:
- uses: actions/checkout@v7
- name: Build
run: docker build -t "xexeu-ci:${{ gitea.run_id }}" .
run: docker build -t "harpia-ci:${{ gitea.run_id }}" .
- name: Smoke test
run: scripts/smoke-image.sh "xexeu-ci:${{ gitea.run_id }}"
run: scripts/smoke-image.sh "harpia-ci:${{ gitea.run_id }}"
- name: Clean up
if: always()
run: docker rmi -f "xexeu-ci:${{ gitea.run_id }}" >/dev/null 2>&1 || true
run: docker rmi -f "harpia-ci:${{ gitea.run_id }}" >/dev/null 2>&1 || true
+6 -6
View File
@@ -1,6 +1,6 @@
name: Release
# Publishes the multi-arch Xexéu image (linux/amd64 + linux/arm64) to the Gitea
# Publishes the multi-arch Harpia 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
@@ -141,7 +141,7 @@ jobs:
grep -qx linux/amd64 platforms.txt && grep -qx linux/arm64 platforms.txt
- name: Summary
run: |
{ echo "### Xexéu image published (linux/amd64, linux/arm64)"; echo; echo '```'
{ echo "### Harpia image published (linux/amd64, linux/arm64)"; echo; echo '```'
echo "${{ steps.meta.outputs.tags }}"; echo '```'; } >> "$GITHUB_STEP_SUMMARY"
gitea-release:
@@ -165,19 +165,19 @@ jobs:
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 "Xexéu ${TAG#v}" --rawfile body notes.md --argjson pre "$pre" \
jq -n --arg tag "$TAG" --arg name "Harpia ${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
# Standalone CLI for hosts that run Xexéu without Docker, built natively on
# each architecture: xexeu-<tag>-<platform>.tar.gz plus its .sha256.
# Standalone CLI for hosts that run Harpia without Docker, built natively on
# each architecture: harpia-<tag>-<platform>.tar.gz plus its .sha256.
cli:
name: CLI (${{ matrix.platform }})
needs: gitea-release
runs-on: ${{ matrix.runner }}
env:
CARGO_TARGET_DIR: /opt/hostedtoolcache/cargo-target/xexeu-release-cli-${{ matrix.platform }}
CARGO_TARGET_DIR: /opt/hostedtoolcache/cargo-target/harpia-release-cli-${{ matrix.platform }}
strategy:
fail-fast: false
matrix:
+2 -2
View File
@@ -34,7 +34,7 @@ jobs:
name: Fuzz (${{ matrix.target }})
runs-on: linux-arm64
env:
CARGO_TARGET_DIR: /opt/hostedtoolcache/cargo-target/xexeu-fuzz
CARGO_TARGET_DIR: /opt/hostedtoolcache/cargo-target/harpia-fuzz
strategy:
fail-fast: false
max-parallel: 1
@@ -47,7 +47,7 @@ jobs:
run: command -v cargo-fuzz >/dev/null || cargo install cargo-fuzz --locked
- name: Fuzz for 10 minutes
run: |
corpus=/opt/hostedtoolcache/fuzz-corpus/xexeu/${{ matrix.target }}
corpus=/opt/hostedtoolcache/fuzz-corpus/harpia/${{ matrix.target }}
mkdir -p "$corpus"
cargo +nightly fuzz run "${{ matrix.target }}" "$corpus" -- -max_total_time=600
# A crash fails the job; its input is printed here so it can be replayed
+1 -1
View File
@@ -29,7 +29,7 @@ if not conv_re.match(subject):
)
body = "\n".join(lines)
cleaned = re.sub(r"\b(Guará|Sabiá|Acauã|Xexéu|Ciberfauna)\b", "", body)
cleaned = re.sub(r"\b(Guará|Sabiá|Acauã|Harpia|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|"
+16 -11
View File
@@ -6,10 +6,15 @@ Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versio
## [Unreleased]
## [2.0.0] - 2026-11-03
### Changed
- Project renamed from Xexéu to **Harpia**, after the harpy eagle. This is a breaking rename: the crates (`xexeu-core`/`xexeu-cli` → `harpia-core`/`harpia-cli`), the binary (`xexeu` → `harpia`), the admin token environment variable (`XEXEU_ADMIN_TOKEN` → `HARPIA_ADMIN_TOKEN`), the compose env vars (`XEXEU_IMAGE`/`XEXEU_VERSION`/`XEXEU_PUBLISH` → `HARPIA_*`), the container image (`ciberfauna/xexeu` → `ciberfauna/harpia`) and the Gitea repository (`ciberfauna/xexeu` → `ciberfauna/harpia`) all changed name. Existing `.env` files, scripts and config paths referencing the old names must be updated.
## [1.2.0] - 2026-11-03
### Added
- `[[webhook]]` alerts: after each ingested sweep, `xexeu serve` posts the surface changes to each receiver, filtered by event kind and group, as Xexéu JSON or a Slack/Discord message, optionally signed with HMAC-SHA256 (`X-Xexeu-Signature`, key from the environment variable named in `segredo_env`). Delivery runs in the background with retries on network errors, `5xx` and `429`; `config check` validates URL, events, groups and variable name.
- `[[webhook]]` alerts: after each ingested sweep, `harpia serve` posts the surface changes to each receiver, filtered by event kind and group, as Harpia JSON or a Slack/Discord message, optionally signed with HMAC-SHA256 (`X-Harpia-Signature`, key from the environment variable named in `segredo_env`). Delivery runs in the background with retries on network errors, `5xx` and `429`; `config check` validates URL, events, groups and variable name.
- `GET /metrics` in Prometheus format: hosts by status, open ports, findings by CVSS severity and in KEV, CVE database size and last sync, per-group last sweep (time, duration, completeness, events) and webhook deliveries.
### Security
@@ -26,30 +31,30 @@ Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versio
- `Weekly` workflow: `cargo audit` independent of pushes, and ten minutes of fuzzing per target on a corpus kept on the runner.
### Changed
- `xexeu-cli` split from one 1,900-line `main.rs` into modules (`server/` with API, exports and embedded assets; `scanner`, `feeds_cmd`, `config_cmd`, `commands`). No behavior change.
- `harpia-cli` split from one 1,900-line `main.rs` into modules (`server/` with API, exports and embedded assets; `scanner`, `feeds_cmd`, `config_cmd`, `commands`). No behavior change.
## [1.0.0] - 2026-11-03
### Security
- The API routes that change the configuration (`POST`/`PUT`/`DELETE /api/config/groups…`) now require an admin token (`--admin-token`/`XEXEU_ADMIN_TOKEN`, at least 16 characters, compared in constant time) in `Authorization: Bearer` or `X-Xexeu-Token`, and reject a browser `Origin` that does not match `Host`. Without a configured token, `serve` generates a random one at each start and prints a `?token=` link; the dashboard keeps it for the tab and asks for it on a `401`. Reads are unchanged.
- The API routes that change the configuration (`POST`/`PUT`/`DELETE /api/config/groups…`) now require an admin token (`--admin-token`/`HARPIA_ADMIN_TOKEN`, at least 16 characters, compared in constant time) in `Authorization: Bearer` or `X-Harpia-Token`, and reject a browser `Origin` that does not match `Host`. Without a configured token, `serve` generates a random one at each start and prints a `?token=` link; the dashboard keeps it for the tab and asks for it on a `401`. Reads are unchanged.
- `quinn-proto` 0.11.17 → 0.11.19 (RUSTSEC-2026-0338, RUSTSEC-2026-0340, RUSTSEC-2026-0343).
### Added
- `LICENSE-MIT` and `LICENSE-APACHE`: the crates and the image already declared `MIT OR Apache-2.0`, but the license texts were missing.
- Releases attach a standalone CLI for `linux-aarch64` and `linux-x86_64` (`xexeu-<tag>-<platform>.tar.gz` plus `.sha256`), built natively on each architecture.
- Releases attach a standalone CLI for `linux-aarch64` and `linux-x86_64` (`harpia-<tag>-<platform>.tar.gz` plus `.sha256`), built natively on each architecture.
- `scripts/check-ui-i18n.mjs`, run by CI and `scripts/check.sh`: every Portuguese dashboard string needs an English translation. It found 38 untranslated strings and a duplicated key, now fixed.
- Rust workspace scaffolding (`xexeu-core`, `xexeu-cli`), Docker Compose topology, documentation pairs and configuration examples.
- Rust workspace scaffolding (`harpia-core`, `harpia-cli`), Docker Compose topology, documentation pairs and configuration examples.
- `config`, `targets` and `schedule`: TOML parsing, CIDR/range/DNS target expansion, 5-field cron with jitter and overlap/cadence warnings.
- Native scan engines: `nativo-sem-raw` (TCP connect) and `nativo` (raw-socket TCP SYN, `CAP_NET_RAW`), with automatic fallback and the engine actually used recorded in every sweep manifest.
- Service fingerprinting (HTTP, SSH, TLS certificate) and CPE/CVE/KEV correlation (`vuln::matcher`, `vuln::feeds`) with confidence levels and non-intrusive configuration checks.
- `batch`, `storage` (SQLite) and `diff`: atomic Parquet sweep batches, idempotent ingestion, scoped diffs that never produce a false disappearance from a partial sweep.
- `xexeu serve`: Axum API, background batch ingestion, and a continuous `xexeu scanner` loop.
- Periodic, self-refreshing CVE/KEV sync inside `xexeu serve` (`feeds.sincronizar_automaticamente`), independent of image/binary updates.
- `harpia serve`: Axum API, background batch ingestion, and a continuous `harpia scanner` loop.
- Periodic, self-refreshing CVE/KEV sync inside `harpia serve` (`feeds.sincronizar_automaticamente`), independent of image/binary updates.
- Embedded dashboard: CVSS-severity palette, SVG charts, host/findings/groups/changes views, settings (language/theme).
- Target group CRUD from the dashboard (`/api/config/groups`) with scanner hot-reload on config file changes.
- CSV export (`/api/export/*.csv`, `xexeu export`), CSV-injection-safe.
- CSV export (`/api/export/*.csv`, `harpia export`), CSV-injection-safe.
- A4, Paged.js-paginated executive report at `/relatorio`.
- `xexeu doctor` and `xexeu export` (JSON/CSV) CLI commands.
- `harpia doctor` and `harpia export` (JSON/CSV) CLI commands.
- Gitea CI/CD (`ci.yml`, `release.yml`), `scripts/check.sh`, pre-push hook, issue/PR templates.
- Full `docs/` set (architecture, CLI, configuration, Docker, interface, support) in EN/PT-BR with real dashboard screenshots.
@@ -57,11 +62,11 @@ Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versio
- `scripts/verificar.sh` → `scripts/check.sh` (fast by default; `--full` adds the workspace tests and `cargo audit`) and `scripts/instalar-hooks.sh` → `scripts/install-hooks.sh`, the same names as the other Ciberfauna projects.
### Fixed
- The image smoke test started the container without `/config/xexeu.toml`, ran `xexeu doctor` against relative paths, and piped into `grep -q` under `pipefail`, which failed at random through SIGPIPE.
- The image smoke test started the container without `/config/harpia.toml`, ran `harpia doctor` against relative paths, and piped into `grep -q` under `pipefail`, which failed at random through SIGPIPE.
- The CI YAML check failed on runners without PyYAML.
- `.env.example` was never in the repository (`.env*` in `.gitignore` matched it), although the README tells operators to copy it.
- The dashboard sidebar always showed `v0.1.0`; it now shows the running version.
- `Dockerfile` didn't copy `apps/` or `logo.png`, so the image never actually built until this was caught by a real `docker build`.
- Sweep batch files were written with mode `0600` by `scanner` (uid 0); `xexeu` (uid 10001) couldn't read them through the read-only `xexeu-sweeps` mount. Batches are now written `0644`/directories `0755` explicitly.
- Sweep batch files were written with mode `0600` by `scanner` (uid 0); `harpia` (uid 10001) couldn't read them through the read-only `harpia-sweeps` mount. Batches are now written `0644`/directories `0755` explicitly.
- Target group names accepted by the config CRUD API weren't validated as safe path components, so an unsafe name would only fail much later when a sweep for that group tried to write its batch; now rejected immediately with a clear error.
- CSV exports had no protection against CSV/formula injection (a cell starting with `=`, `+`, `-`, `@` or a tab); fields are now prefixed to force spreadsheet applications to treat them as plain text.
+16 -11
View File
@@ -6,10 +6,15 @@ Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/);
## [Não lançado]
## [2.0.0] - 2026-11-03
### Alterado
- Projeto renomeado de Xexéu para **Harpia**, em referência ao gavião-real. É uma renomeação com quebra de compatibilidade: os crates (`xexeu-core`/`xexeu-cli` → `harpia-core`/`harpia-cli`), o binário (`xexeu` → `harpia`), a variável de ambiente do token de administração (`XEXEU_ADMIN_TOKEN` → `HARPIA_ADMIN_TOKEN`), as variáveis do compose (`XEXEU_IMAGE`/`XEXEU_VERSION`/`XEXEU_PUBLISH` → `HARPIA_*`), a imagem do container (`ciberfauna/xexeu` → `ciberfauna/harpia`) e o repositório no Gitea (`ciberfauna/xexeu` → `ciberfauna/harpia`) mudaram de nome. Arquivos `.env`, scripts e caminhos de configuração existentes que referenciem os nomes antigos precisam ser atualizados.
## [1.2.0] - 2026-11-03
### Adicionado
- Alertas `[[webhook]]`: depois de cada varredura ingerida, o `xexeu serve` envia as mudanças de superfície a cada receptor, filtradas por tipo de evento e grupo, como JSON do Xexéu ou mensagem de Slack/Discord, opcionalmente assinadas com HMAC-SHA256 (`X-Xexeu-Signature`, chave da variável de ambiente indicada em `segredo_env`). A entrega roda em segundo plano, com novas tentativas em erros de rede, `5xx` e `429`; o `config check` valida URL, eventos, grupos e nome da variável.
- Alertas `[[webhook]]`: depois de cada varredura ingerida, o `harpia serve` envia as mudanças de superfície a cada receptor, filtradas por tipo de evento e grupo, como JSON do Harpia ou mensagem de Slack/Discord, opcionalmente assinadas com HMAC-SHA256 (`X-Harpia-Signature`, chave da variável de ambiente indicada em `segredo_env`). A entrega roda em segundo plano, com novas tentativas em erros de rede, `5xx` e `429`; o `config check` valida URL, eventos, grupos e nome da variável.
- `GET /metrics` em formato Prometheus: hosts por status, portas abertas, achados por severidade CVSS e no KEV, tamanho e última sincronização da base de CVEs, última varredura por grupo (horário, duração, completude, eventos) e entregas de webhook.
### Segurança
@@ -26,30 +31,30 @@ Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/);
- Workflow `Weekly`: `cargo audit` independente de push e dez minutos de fuzzing por alvo sobre um corpus guardado no runner.
### Alterado
- O `xexeu-cli` saiu de um único `main.rs` de 1.900 linhas para módulos (`server/` com API, exportações e arquivos embutidos; `scanner`, `feeds_cmd`, `config_cmd`, `commands`). Sem mudança de comportamento.
- O `harpia-cli` saiu de um único `main.rs` de 1.900 linhas para módulos (`server/` com API, exportações e arquivos embutidos; `scanner`, `feeds_cmd`, `config_cmd`, `commands`). Sem mudança de comportamento.
## [1.0.0] - 2026-11-03
### Segurança
- As rotas da API que mudam a configuração (`POST`/`PUT`/`DELETE /api/config/groups…`) agora exigem um token de administração (`--admin-token`/`XEXEU_ADMIN_TOKEN`, com pelo menos 16 caracteres, comparado em tempo constante) em `Authorization: Bearer` ou `X-Xexeu-Token`, e recusam um `Origin` de navegador que não bata com o `Host`. Sem token configurado, o `serve` gera um aleatório a cada partida e imprime um link `?token=`; o dashboard o guarda na aba e pede o token ao receber `401`. Leituras não mudaram.
- As rotas da API que mudam a configuração (`POST`/`PUT`/`DELETE /api/config/groups…`) agora exigem um token de administração (`--admin-token`/`HARPIA_ADMIN_TOKEN`, com pelo menos 16 caracteres, comparado em tempo constante) em `Authorization: Bearer` ou `X-Harpia-Token`, e recusam um `Origin` de navegador que não bata com o `Host`. Sem token configurado, o `serve` gera um aleatório a cada partida e imprime um link `?token=`; o dashboard o guarda na aba e pede o token ao receber `401`. Leituras não mudaram.
- `quinn-proto` 0.11.17 → 0.11.19 (RUSTSEC-2026-0338, RUSTSEC-2026-0340, RUSTSEC-2026-0343).
### Adicionado
- `LICENSE-MIT` e `LICENSE-APACHE`: os crates e a imagem já declaravam `MIT OR Apache-2.0`, mas faltavam os textos das licenças.
- As releases anexam um CLI avulso para `linux-aarch64` e `linux-x86_64` (`xexeu-<tag>-<plataforma>.tar.gz` mais `.sha256`), compilado nativamente em cada arquitetura.
- As releases anexam um CLI avulso para `linux-aarch64` e `linux-x86_64` (`harpia-<tag>-<plataforma>.tar.gz` mais `.sha256`), compilado nativamente em cada arquitetura.
- `scripts/check-ui-i18n.mjs`, rodado pelo CI e pelo `scripts/check.sh`: todo texto em português do dashboard precisa de tradução inglesa. Ele achou 38 textos sem tradução e uma chave duplicada, já corrigidos.
- Scaffolding do workspace Rust (`xexeu-core`, `xexeu-cli`), topologia Docker Compose, pares de documentação e exemplos de configuração.
- Scaffolding do workspace Rust (`harpia-core`, `harpia-cli`), topologia Docker Compose, pares de documentação e exemplos de configuração.
- `config`, `targets` e `schedule`: parse de TOML, expansão de alvo CIDR/faixa/DNS, cron de 5 campos com jitter e avisos de sobreposição/cadência.
- Motores de varredura nativos: `nativo-sem-raw` (TCP connect) e `nativo` (SYN cru de socket, `CAP_NET_RAW`), com fallback automático e o motor realmente usado registrado em todo manifesto de varredura.
- Fingerprint de serviço (HTTP, SSH, certificado TLS) e correlação CPE/CVE/KEV (`vuln::matcher`, `vuln::feeds`) com níveis de confiança e checagens de configuração não intrusivas.
- `batch`, `storage` (SQLite) e `diff`: lotes Parquet gravados atomicamente, ingestão idempotente, diffs por escopo que nunca geram um falso desaparecimento a partir de uma varredura parcial.
- `xexeu serve`: API Axum, ingestão de lotes em segundo plano, e um loop contínuo `xexeu scanner`.
- Sync periódico e auto-atualizável de CVE/KEV dentro do `xexeu serve` (`feeds.sincronizar_automaticamente`), independente de atualização de imagem/binário.
- `harpia serve`: API Axum, ingestão de lotes em segundo plano, e um loop contínuo `harpia scanner`.
- Sync periódico e auto-atualizável de CVE/KEV dentro do `harpia serve` (`feeds.sincronizar_automaticamente`), independente de atualização de imagem/binário.
- Dashboard embutido: paleta por severidade CVSS, gráficos SVG, telas de hosts/achados/grupos/mudanças, configurações (idioma/tema).
- CRUD de grupos de alvos pelo dashboard (`/api/config/groups`) com hot-reload do scanner em mudanças no arquivo de config.
- Exportação CSV (`/api/export/*.csv`, `xexeu export`), protegida contra injeção de CSV.
- Exportação CSV (`/api/export/*.csv`, `harpia export`), protegida contra injeção de CSV.
- Relatório executivo A4 paginado com Paged.js em `/relatorio`.
- Comandos de CLI `xexeu doctor` e `xexeu export` (JSON/CSV).
- Comandos de CLI `harpia doctor` e `harpia export` (JSON/CSV).
- CI/CD do Gitea (`ci.yml`, `release.yml`), `scripts/check.sh`, hook de pre-push, templates de issue/PR.
- Conjunto completo de `docs/` (arquitetura, CLI, configuração, Docker, interface, suporte) em EN/PT-BR com screenshots reais do dashboard.
@@ -57,11 +62,11 @@ Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/);
- `scripts/verificar.sh` → `scripts/check.sh` (rápido por padrão; `--full` acrescenta os testes do workspace e o `cargo audit`) e `scripts/instalar-hooks.sh` → `scripts/install-hooks.sh`, os mesmos nomes dos outros projetos da Ciberfauna.
### Corrigido
- O smoke test da imagem subia o contêiner sem `/config/xexeu.toml`, rodava o `xexeu doctor` em caminhos relativos e usava pipe para `grep -q` sob `pipefail`, o que falhava ao acaso por SIGPIPE.
- O smoke test da imagem subia o contêiner sem `/config/harpia.toml`, rodava o `harpia doctor` em caminhos relativos e usava pipe para `grep -q` sob `pipefail`, o que falhava ao acaso por SIGPIPE.
- A checagem de YAML do CI falhava em runners sem PyYAML.
- O `.env.example` nunca esteve no repositório (o `.env*` do `.gitignore` o pegava), embora o README mande os operadores copiá-lo.
- A barra lateral do dashboard mostrava sempre `v0.1.0`; agora mostra a versão em execução.
- O `Dockerfile` não copiava `apps/` nem `logo.png`, então a imagem nunca buildava de verdade até isso ser pego por um `docker build` real.
- Arquivos de lote de varredura eram gravados com modo `0600` pelo `scanner` (uid 0); o `xexeu` (uid 10001) não conseguia lê-los pelo mount `xexeu-sweeps` somente leitura. Lotes agora são gravados com `0644`/diretórios com `0755` explicitamente.
- Arquivos de lote de varredura eram gravados com modo `0600` pelo `scanner` (uid 0); o `harpia` (uid 10001) não conseguia lê-los pelo mount `harpia-sweeps` somente leitura. Lotes agora são gravados com `0644`/diretórios com `0755` explicitamente.
- Nomes de grupo de alvos aceitos pela API de CRUD de config não eram validados como componentes de caminho seguros, então um nome inseguro só falhava bem mais tarde, quando uma varredura daquele grupo tentava gravar o lote; agora é rejeitado imediatamente com um erro claro.
- Exportações CSV não tinham proteção contra injeção de CSV/fórmula (uma célula começando com `=`, `+`, `-`, `@` ou tab); campos agora recebem um prefixo que força aplicativos de planilha a tratá-los como texto puro.
+4 -4
View File
@@ -1,10 +1,10 @@
# Contributing to Xexéu
# Contributing to Harpia
**English** · [Português](CONTRIBUTING.pt-BR.md)
Thanks for helping. Xexéu is a continuous attack surface and vulnerability audit engine built around deterministic evidence and least-privilege operation. The most useful contributions right now are tests, fixtures, documentation, and well-scoped engine components.
Thanks for helping. Harpia is a continuous attack surface and vulnerability audit engine built around deterministic evidence and least-privilege operation. The most useful contributions right now are tests, fixtures, documentation, and well-scoped engine components.
1. **Authorized auditing only.** Xexéu is defensive software for networks you own or are explicitly authorized to audit. Do not introduce scanning techniques, collection mechanisms, or evasion methods that hide scope, bypass authorization checks, or perform destructive testing.
1. **Authorized auditing only.** Harpia is defensive software for networks you own or are explicitly authorized to audit. Do not introduce scanning techniques, collection mechanisms, or evasion methods that hide scope, bypass authorization checks, or perform destructive testing.
2. **Deterministic evidence is part of the feature.** Every vulnerability finding and service detection must record its exact inputs, raw banners, candidate CPEs, and matching rules. A score or finding without a reproducible JSON evidence record is not accepted.
3. **Be transparent about what works.** If a feature is a stub, restricted to Linux `NET_RAW`, or represents a degraded mode (such as `nativo-sem-raw`), document it clearly in the README, CLI help, and test suite.
4. **100% English codebase.** Source code, comments, scripts, workflows, and commit messages are in English. The web dashboard remains bilingual (PT-BR source and English via `i18n-en.js`).
@@ -24,7 +24,7 @@ The interface source text is Portuguese. English translations reside in `apps/gu
## Untrusted input and fuzzing
Everything Xexéu reads from the network, from feeds or from the group form is hostile until parsed: it must come back as an error, never a panic. `crates/xexeu-core/tests/untrusted_input.rs` checks this with property tests on every `cargo test`, and the diff engine's guarantees (no removal from a partial sweep, no closed port that was not scanned, disappearance exactly at the threshold) are properties in `diff.rs`. A new parser gets an entry in both places plus a target in `fuzz/`.
Everything Harpia reads from the network, from feeds or from the group form is hostile until parsed: it must come back as an error, never a panic. `crates/harpia-core/tests/untrusted_input.rs` checks this with property tests on every `cargo test`, and the diff engine's guarantees (no removal from a partial sweep, no closed port that was not scanned, disappearance exactly at the threshold) are properties in `diff.rs`. A new parser gets an entry in both places plus a target in `fuzz/`.
For longer runs (nightly toolchain and `cargo install cargo-fuzz`):
+4 -4
View File
@@ -1,10 +1,10 @@
# Contribuindo com o Xexéu
# Contribuindo com o Harpia
[English](CONTRIBUTING.md) · **Português**
Obrigado por ajudar. O Xexéu é um motor de auditoria contínua de superfície de ataque e vulnerabilidades construído em torno de evidência determinística e privilégio mínimo. As contribuições mais úteis agora são testes, fixtures, documentação e componentes modulares do motor.
Obrigado por ajudar. O Harpia é um motor de auditoria contínua de superfície de ataque e vulnerabilidades construído em torno de evidência determinística e privilégio mínimo. As contribuições mais úteis agora são testes, fixtures, documentação e componentes modulares do motor.
1. **Apenas auditoria autorizada.** O Xexéu é software defensivo para redes próprias ou redes que você possui autorização expressa para auditar. Não adicione métodos de varredura, mecanismos de evasão ou testes destrutivos que ocultem escopo ou burlem checagens de autorização.
1. **Apenas auditoria autorizada.** O Harpia é software defensivo para redes próprias ou redes que você possui autorização expressa para auditar. Não adicione métodos de varredura, mecanismos de evasão ou testes destrutivos que ocultem escopo ou burlem checagens de autorização.
2. **Evidência determinística é parte do recurso.** Toda identificação de serviço e achado de vulnerabilidade deve declarar suas entradas, banners brutos, CPEs candidatos e regras de correspondência. Achados sem registro reproduzível de evidência JSON não são aceitos.
3. **Seja transparente sobre o que funciona.** Se um recurso for um stub, limitado a Linux `NET_RAW` ou representar um modo degradado (como `nativo-sem-raw`), documente isso claramente no README, na ajuda da CLI e nos testes.
4. **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 web permanece bilíngue (código-fonte em PT-BR e EN via `i18n-en.js`).
@@ -24,7 +24,7 @@ O texto original da interface é em português. O inglês reside em `apps/gui/ui
## Entrada não confiável e fuzzing
Tudo o que o Xexéu lê da rede, dos feeds ou do formulário de grupos é hostil até ser interpretado: precisa voltar como erro, nunca como pânico. O `crates/xexeu-core/tests/untrusted_input.rs` verifica isso com testes de propriedade a cada `cargo test`, e as garantias do motor de diff (nenhuma remoção a partir de varredura parcial, nenhuma porta fechada que não foi varrida, desaparecimento exatamente no limite) são propriedades em `diff.rs`. Um parser novo ganha entrada nos dois lugares e um alvo em `fuzz/`.
Tudo o que o Harpia lê da rede, dos feeds ou do formulário de grupos é hostil até ser interpretado: precisa voltar como erro, nunca como pânico. O `crates/harpia-core/tests/untrusted_input.rs` verifica isso com testes de propriedade a cada `cargo test`, e as garantias do motor de diff (nenhuma remoção a partir de varredura parcial, nenhuma porta fechada que não foi varrida, desaparecimento exatamente no limite) são propriedades em `diff.rs`. Um parser novo ganha entrada nos dois lugares e um alvo em `fuzz/`.
Para corridas longas (toolchain nightly e `cargo install cargo-fuzz`):
Generated
+51 -51
View File
@@ -312,9 +312,9 @@ checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
[[package]]
name = "cc"
version = "1.10.0"
version = "1.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "86e055fa6e3e40ad6187ba25b6855eeb635d5271f8e0f0e1e9a5826b8d75bea0"
checksum = "375989decec1a0fa424442bed520fa12ede43a48475ce8c7417d2c69b32b5f6b"
dependencies = [
"find-msvc-tools",
"shlex",
@@ -733,6 +733,49 @@ dependencies = [
"zerocopy",
]
[[package]]
name = "harpia-cli"
version = "2.0.0"
dependencies = [
"axum",
"chrono",
"clap",
"harpia-core",
"libc",
"reqwest",
"serde",
"serde_json",
"tempfile",
"tokio",
]
[[package]]
name = "harpia-core"
version = "2.0.0"
dependencies = [
"arrow-array",
"arrow-schema",
"chrono",
"croner",
"hmac",
"ipnet",
"parquet",
"proptest",
"reqwest",
"rusqlite",
"rustls",
"serde",
"serde_json",
"sha2",
"socket2 0.5.10",
"tempfile",
"thiserror 1.0.69",
"tokio",
"tokio-rustls",
"toml",
"ulid",
]
[[package]]
name = "hashbrown"
version = "0.17.1"
@@ -1087,9 +1130,9 @@ checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
[[package]]
name = "lru-slab"
version = "0.1.2"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f"
[[package]]
name = "matchit"
@@ -1269,9 +1312,9 @@ checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0"
[[package]]
name = "quinn"
version = "0.11.11"
version = "0.11.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8"
checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11"
dependencies = [
"bytes",
"cfg_aliases",
@@ -1311,9 +1354,9 @@ dependencies = [
[[package]]
name = "quinn-udp"
version = "0.5.15"
version = "0.5.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694"
checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016"
dependencies = [
"cfg_aliases",
"libc",
@@ -2394,49 +2437,6 @@ version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
[[package]]
name = "xexeu-cli"
version = "1.2.0"
dependencies = [
"axum",
"chrono",
"clap",
"libc",
"reqwest",
"serde",
"serde_json",
"tempfile",
"tokio",
"xexeu-core",
]
[[package]]
name = "xexeu-core"
version = "1.2.0"
dependencies = [
"arrow-array",
"arrow-schema",
"chrono",
"croner",
"hmac",
"ipnet",
"parquet",
"proptest",
"reqwest",
"rusqlite",
"rustls",
"serde",
"serde_json",
"sha2",
"socket2 0.5.10",
"tempfile",
"thiserror 1.0.69",
"tokio",
"tokio-rustls",
"toml",
"ulid",
]
[[package]]
name = "yoke"
version = "0.8.4"
+4 -4
View File
@@ -1,13 +1,13 @@
[workspace]
resolver = "2"
members = ["crates/xexeu-core", "crates/xexeu-cli"]
members = ["crates/harpia-core", "crates/harpia-cli"]
[workspace.package]
version = "1.2.0"
version = "2.0.0"
edition = "2021"
license = "MIT OR Apache-2.0"
repository = "https://git.lucasrguerra.dev.br/ciberfauna/xexeu"
authors = ["Xexéu contributors"]
repository = "https://git.lucasrguerra.dev.br/ciberfauna/harpia"
authors = ["Harpia contributors"]
rust-version = "1.88"
[profile.release]
+15 -15
View File
@@ -1,8 +1,8 @@
# syntax=docker/dockerfile:1
#
# Xexéu image: one binary covering both Compose roles (`serve` and `scanner`).
# Harpia image: one binary covering both Compose roles (`serve` and `scanner`).
# The default image carries no external scanner; nmap lives in the optional
# variant xexeu-scanner-nmap so the NPSL stays out of the standard binary.
# variant harpia-scanner-nmap so the NPSL stays out of the standard binary.
# Build stage.
FROM rust:1.99-slim-trixie AS build
@@ -14,7 +14,7 @@ COPY Cargo.toml Cargo.lock ./
COPY crates crates
COPY apps apps
COPY logo.png ./
RUN cargo build --release --locked -p xexeu-cli
RUN cargo build --release --locked -p harpia-cli
# Runtime stage: Debian slim, the binary and CA certificates for the optional
# outbound feed sync, release check and HEALTHCHECK. Runs unprivileged by
@@ -23,21 +23,21 @@ FROM debian:trixie-slim
RUN apt-get update \
&& apt-get install -y --no-install-recommends ca-certificates curl libstdc++6 \
&& rm -rf /var/lib/apt/lists/* \
&& groupadd --system --gid 10001 xexeu \
&& useradd --system --uid 10001 --gid 10001 --home-dir /data --shell /usr/sbin/nologin xexeu \
&& mkdir -p /data/xexeu /data/sweeps \
&& chown xexeu:xexeu /data/xexeu
COPY --from=build /src/target/release/xexeu /usr/local/bin/xexeu
LABEL org.opencontainers.image.title="Xexéu" \
&& groupadd --system --gid 10001 harpia \
&& useradd --system --uid 10001 --gid 10001 --home-dir /data --shell /usr/sbin/nologin harpia \
&& mkdir -p /data/harpia /data/sweeps \
&& chown harpia:harpia /data/harpia
COPY --from=build /src/target/release/harpia /usr/local/bin/harpia
LABEL org.opencontainers.image.title="Harpia" \
org.opencontainers.image.description="Continuous attack-surface and vulnerability auditing" \
org.opencontainers.image.source="https://git.lucasrguerra.dev.br/ciberfauna/xexeu" \
org.opencontainers.image.source="https://git.lucasrguerra.dev.br/ciberfauna/harpia" \
org.opencontainers.image.licenses="MIT OR Apache-2.0"
ENV XEXEU_RUNTIME=container
USER xexeu
ENV HARPIA_RUNTIME=container
USER harpia
WORKDIR /data
EXPOSE 8788
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
CMD curl -fsS http://127.0.0.1:8788/api/health >/dev/null || exit 1
ENTRYPOINT ["xexeu"]
CMD ["serve", "--bind", "0.0.0.0:8788", "--config", "/config/xexeu.toml", \
"--sweeps", "/data/sweeps", "--data-dir", "/data/xexeu"]
ENTRYPOINT ["harpia"]
CMD ["serve", "--bind", "0.0.0.0:8788", "--config", "/config/harpia.toml", \
"--sweeps", "/data/sweeps", "--data-dir", "/data/harpia"]
+1 -1
View File
@@ -1,6 +1,6 @@
MIT License
Copyright (c) 2026 Xexéu contributors
Copyright (c) 2026 Harpia 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
+24 -24
View File
@@ -1,18 +1,18 @@
<p align="center"><img src="logo.png" width="300" alt="Xexéu"></p>
<h1 align="center">Xexéu</h1>
<p align="center"><img src="logo.png" width="300" alt="Harpia"></p>
<h1 align="center">Harpia</h1>
<p align="center">Continuous attack surface and vulnerability auditing.<br>Lightweight Rust scanner · local-first · authorized use.</p>
<p align="center"><a href="docs/cli.md">Terminal</a> · <a href="docs/interface.md">Interface</a> · <a href="docs/architecture.md">Architecture</a> · <a href="docs/configuration.md">Configuration</a> · <a href="docs/docker.md">Docker</a> · <a href="docs/support.md">Support</a> · <a href="ROADMAP.md">Roadmap</a> · <a href="CHANGELOG.md">Changelog</a></p>
<p align="center"><b>English</b> · <a href="README.pt-BR.md">Português</a></p>
<p align="center"><img src="docs/img/visao-geral-dark-pt.png" width="900" alt="The Xexéu dashboard overview: KPI cards, a severity-distribution chart, a top-exposed-hosts chart and a prioritized findings list"></p>
<p align="center"><img src="docs/img/visao-geral-dark-pt.png" width="900" alt="The Harpia dashboard overview: KPI cards, a severity-distribution chart, a top-exposed-hosts chart and a prioritized findings list"></p>
---
**Status: v1.0 candidate.** The full pipeline — raw-socket SYN scanning, TCP-connect fallback, service fingerprinting, CVE/KEV correlation, scoped diffs, the dashboard, the executive report, CSV export and CI/release — is implemented and has been validated against a real vulnerable target (DVWA) through the actual hardened Docker Compose stack, not just the host binary. See [CHANGELOG.md](CHANGELOG.md) for exactly what shipped and when.
Xexéu is a lightweight continuous attack surface and vulnerability audit daemon for authorized networks. Instead of one-off scans and unorganized XML dumps, Xexéu runs continuously via Docker Compose, tracking what is exposed, what changed between sweeps, and what vulnerabilities exist.
Harpia is a lightweight continuous attack surface and vulnerability audit daemon for authorized networks. Instead of one-off scans and unorganized XML dumps, Harpia runs continuously via Docker Compose, tracking what is exposed, what changed between sweeps, and what vulnerabilities exist.
- **Continuous, not point-in-time:** the primary output is the live deduplicated state of your network surface plus an append-only event log of differences (new hosts, closed ports, altered services, remediated CVEs).
- **Tiered scan cadences:** critical segments (core servers, DMZs) can be scanned frequently (e.g. every 5 minutes), while secondary segments are audited on broader schedules (e.g. daily cron at 03:00) — editable live from the dashboard's Groups view, no file editing required.
@@ -26,23 +26,23 @@ Xexéu is a lightweight continuous attack surface and vulnerability audit daemon
| Area | State |
|---|---|
| Rust workspace and CLI (`xexeu`) | ✅ `serve`, `scanner`, `scan`, `config check`, `feeds`, `changes`, `export`, `doctor` |
| Rust workspace and CLI (`harpia`) | ✅ `serve`, `scanner`, `scan`, `config check`, `feeds`, `changes`, `export`, `doctor` |
| Native scan engine | ✅ raw-socket SYN (`nativo`, `CAP_NET_RAW`) with automatic fallback to TCP connect (`nativo-sem-raw`) |
| Service fingerprinting | ✅ HTTP, SSH, TLS certificate, passive banner grab |
| CPE/CVE/KEV correlation | ✅ NVD CVE JSON 2.0 + CISA KEV, offline import or live sync (one-shot or periodic background) |
| Scoped diff & event history | ✅ deterministic, debounced, partial sweeps never produce false disappearances |
| Storage | ✅ SQLite (state) + Parquet (immutable sweep batches) |
| Dashboard & executive report | ✅ embedded vanilla UI (severity palette, SVG charts, group CRUD), A4 Paged.js report at `/relatorio` |
| CSV / JSON export | ✅ `/api/export/*.csv`, `xexeu export`, CSV-injection-safe |
| CSV / JSON export | ✅ `/api/export/*.csv`, `harpia export`, CSV-injection-safe |
| Docker Compose topology & hardening | ✅ validated end-to-end against a real target, including the permission boundary between the two containers' users |
| CI/CD (Gitea) | ✅ `ci.yml`, `release.yml`, `scripts/check.sh`, pre-push hook |
| Bilingual documentation | ✅ EN/PT-BR pairs, with real dashboard screenshots |
| `nmap` adapter / `xexeu-scanner-nmap` variant | 🚧 not yet implemented |
| `nmap` adapter / `harpia-scanner-nmap` variant | 🚧 not yet implemented |
| Published releases | ❌ none yet — see [ROADMAP.md](ROADMAP.md) |
## Core principles
Xexéu executes an ongoing loop: **schedule → scan → identify → historize → expose**.
Harpia executes an ongoing loop: **schedule → scan → identify → historize → expose**.
1. **Tiered scheduling:** group-based cron expressions with jitter and a shared rate-limiting budget prevent network saturation.
2. **Dual-engine flexibility:** the native Rust SYN engine by default, an unprivileged TCP-connect fallback always available, and an optional external `nmap` adapter planned for deep service discovery.
@@ -51,9 +51,9 @@ Xexéu executes an ongoing loop: **schedule → scan → identify → historize
## Authorized use
Xexéu is defensive software designed strictly for networks you own or are explicitly authorized to audit. Scanning third-party infrastructure without permission is illegal. Operators are responsible for scope, compliance, and data retention policies.
Harpia is defensive software designed strictly for networks you own or are explicitly authorized to audit. Scanning third-party infrastructure without permission is illegal. Operators are responsible for scope, compliance, and data retention policies.
The configuration requires an explicit `[escopo]` block. Any target resolving outside the authorized CIDR ranges is rejected. The API daemon binds to `127.0.0.1` by default; reads are open, and the routes that change the configuration need an admin token (`XEXEU_ADMIN_TOKEN`, or the one-off link printed at startup). Put it behind an authenticating reverse proxy before exposing it beyond localhost. See [SECURITY.md](SECURITY.md).
The configuration requires an explicit `[escopo]` block. Any target resolving outside the authorized CIDR ranges is rejected. The API daemon binds to `127.0.0.1` by default; reads are open, and the routes that change the configuration need an admin token (`HARPIA_ADMIN_TOKEN`, or the one-off link printed at startup). Put it behind an authenticating reverse proxy before exposing it beyond localhost. See [SECURITY.md](SECURITY.md).
## Install
@@ -61,12 +61,12 @@ Run via Docker Compose (recommended for operators):
```bash
cp .env.example .env
mkdir -p config && cp examples/xexeu.toml config/xexeu.toml
mkdir -p config && cp examples/harpia.toml config/harpia.toml
docker compose pull && docker compose up -d
docker compose logs xexeu | grep token # one-off admin link, unless XEXEU_ADMIN_TOKEN is set
docker compose logs harpia | grep token # one-off admin link, unless HARPIA_ADMIN_TOKEN is set
```
The image is public: `docker pull git.lucasrguerra.dev.br/ciberfauna/xexeu:latest`.
The image is public: `docker pull git.lucasrguerra.dev.br/ciberfauna/harpia:latest`.
Or build and run locally with Docker:
@@ -77,15 +77,15 @@ docker compose up -d --build
To compile from source natively (just Rust 1.88+ — no external library to fetch, SQLite is bundled):
```bash
cargo build --release -p xexeu-cli
./target/release/xexeu --help
cargo build --release -p harpia-cli
./target/release/harpia --help
```
Or download the standalone CLI from the [releases page](https://git.lucasrguerra.dev.br/ciberfauna/xexeu/releases) (`linux-x86_64` and `linux-aarch64`) and check it against its `.sha256`:
Or download the standalone CLI from the [releases page](https://git.lucasrguerra.dev.br/ciberfauna/harpia/releases) (`linux-x86_64` and `linux-aarch64`) and check it against its `.sha256`:
```bash
sha256sum -c xexeu-v1.0.0-linux-x86_64.tar.gz.sha256
tar xzf xexeu-v1.0.0-linux-x86_64.tar.gz
sha256sum -c harpia-v1.0.0-linux-x86_64.tar.gz.sha256
tar xzf harpia-v1.0.0-linux-x86_64.tar.gz
```
Supported platform matrix for container images: `linux/amd64` and `linux/arm64`.
@@ -94,19 +94,19 @@ Supported platform matrix for container images: `linux/amd64` and `linux/arm64`.
```bash
# Validate your configuration and view effective schedules
xexeu config check --config config/xexeu.toml
harpia config check --config config/harpia.toml
# Start the server daemon and web dashboard
xexeu serve --bind 127.0.0.1:8788 --config config/xexeu.toml
harpia serve --bind 127.0.0.1:8788 --config config/harpia.toml
# Run an ad-hoc diagnostic scan for a specific group
xexeu scan --group dmz --once
harpia scan --group dmz --once
# Inspect recent surface changes
xexeu changes --since 24h
harpia changes --since 24h
# Diagnose the environment (capabilities, feeds, storage)
xexeu doctor
harpia doctor
```
See [docs/cli.md](docs/cli.md) for the full command reference.
@@ -136,7 +136,7 @@ Summary of the [ROADMAP](ROADMAP.md):
|---|---|
| **Done (1.2.0)** | Workspace crates, native SYN/connect scan engines, fingerprinting, CVE/KEV correlation, scoped diffs, SQLite+Parquet storage, dashboard, executive report, CSV export, config CRUD with scanner hot-reload behind an admin token, CI/CD with published image and CLI, property tests and weekly fuzzing, webhook alerts, Prometheus metrics |
| **Next** | Distribution backport mapping, email alerts |
| **Later** | `nmap` adapter and the `xexeu-scanner-nmap` variant, OSV correlation, multi-scanner aggregation |
| **Later** | `nmap` adapter and the `harpia-scanner-nmap` variant, OSV correlation, multi-scanner aggregation |
| **Not planned** | Exploitation payloads, NASL engine, mandatory cloud services, desktop Tauri wrapper |
## License
+24 -24
View File
@@ -1,18 +1,18 @@
<p align="center"><img src="logo.png" width="300" alt="Xexéu"></p>
<h1 align="center">Xexéu</h1>
<p align="center"><img src="logo.png" width="300" alt="Harpia"></p>
<h1 align="center">Harpia</h1>
<p align="center">Auditoria contínua de superfície de ataque e vulnerabilidades.<br>Scanner leve em Rust · local-first · uso autorizado.</p>
<p align="center"><a href="docs/pt-BR/cli.md">Terminal</a> · <a href="docs/pt-BR/interface.md">Interface</a> · <a href="docs/pt-BR/arquitetura.md">Arquitetura</a> · <a href="docs/pt-BR/configuracao.md">Configuração</a> · <a href="docs/pt-BR/docker.md">Docker</a> · <a href="docs/pt-BR/suporte.md">Suporte</a> · <a href="ROADMAP.pt-BR.md">Roadmap</a> · <a href="CHANGELOG.pt-BR.md">Changelog</a></p>
<p align="center"><a href="README.md">English</a> · <b>Português</b></p>
<p align="center"><img src="docs/img/visao-geral-dark-pt.png" width="900" alt="Visão geral do dashboard da Xexéu: cartões de KPI, gráfico de distribuição por severidade, gráfico de top hosts mais expostos e lista de achados prioritários"></p>
<p align="center"><img src="docs/img/visao-geral-dark-pt.png" width="900" alt="Visão geral do dashboard da Harpia: cartões de KPI, gráfico de distribuição por severidade, gráfico de top hosts mais expostos e lista de achados prioritários"></p>
---
**Status: candidata a v1.0.** O pipeline completo — varredura SYN de socket cru, fallback TCP connect, fingerprint de serviço, correlação CVE/KEV, diffs por escopo, dashboard, relatório executivo, exportação CSV e CI/release — está implementado e foi validado contra um alvo real vulnerável (DVWA) através da stack Docker Compose hardened de verdade, não só do binário no host. Veja o [CHANGELOG.pt-BR.md](CHANGELOG.pt-BR.md) pra saber exatamente o que entrou e quando.
A Xexéu é um daemon leve e contínuo de auditoria de superfície de ataque e vulnerabilidades pra redes autorizadas. Em vez de varreduras pontuais e dumps XML desorganizados, a Xexéu roda continuamente via Docker Compose, rastreando o que está exposto, o que mudou entre varreduras, e quais vulnerabilidades existem.
A Harpia é um daemon leve e contínuo de auditoria de superfície de ataque e vulnerabilidades pra redes autorizadas. Em vez de varreduras pontuais e dumps XML desorganizados, a Harpia roda continuamente via Docker Compose, rastreando o que está exposto, o que mudou entre varreduras, e quais vulnerabilidades existem.
- **Contínuo, não pontual:** o produto principal é o estado atual deduplicado da sua superfície de rede mais um log de eventos de diferenças (hosts novos, portas fechadas, serviços alterados, CVEs corrigidos).
- **Cadências de varredura em níveis:** segmentos críticos (servidores núcleo, DMZs) podem ser varridos com frequência (ex. a cada 5 minutos), enquanto segmentos secundários são auditados em cronogramas mais amplos (ex. cron diário às 03:00) — editável ao vivo pela tela de Grupos do dashboard, sem precisar editar arquivo nenhum.
@@ -26,23 +26,23 @@ A Xexéu é um daemon leve e contínuo de auditoria de superfície de ataque e v
| Área | Estado |
|---|---|
| Workspace Rust e CLI (`xexeu`) | ✅ `serve`, `scanner`, `scan`, `config check`, `feeds`, `changes`, `export`, `doctor` |
| Workspace Rust e CLI (`harpia`) | ✅ `serve`, `scanner`, `scan`, `config check`, `feeds`, `changes`, `export`, `doctor` |
| Motor de varredura nativo | ✅ SYN de socket cru (`nativo`, `CAP_NET_RAW`) com fallback automático pra TCP connect (`nativo-sem-raw`) |
| Fingerprint de serviço | ✅ HTTP, SSH, certificado TLS, captura passiva de banner |
| Correlação CPE/CVE/KEV | ✅ NVD CVE JSON 2.0 + CISA KEV, importação offline ou sync ao vivo (único ou periódico em segundo plano) |
| Diff por escopo e histórico de eventos | ✅ determinístico, amortecido, varreduras parciais nunca geram falsos desaparecimentos |
| Armazenamento | ✅ SQLite (estado) + Parquet (lotes de varredura imutáveis) |
| Dashboard e relatório executivo | ✅ interface embutida em HTML/JS puro (paleta por severidade, gráficos SVG, CRUD de grupos), relatório A4 com Paged.js em `/relatorio` |
| Exportação CSV / JSON | ✅ `/api/export/*.csv`, `xexeu export`, protegido contra injeção de fórmula em CSV |
| Exportação CSV / JSON | ✅ `/api/export/*.csv`, `harpia export`, protegido contra injeção de fórmula em CSV |
| Topologia Docker Compose e hardening | ✅ validado de ponta a ponta contra um alvo real, incluindo o limite de permissão entre os usuários dos dois containers |
| CI/CD (Gitea) | ✅ `ci.yml`, `release.yml`, `scripts/check.sh`, hook de pre-push |
| Documentação bilíngue | ✅ pares EN/PT-BR, com screenshots reais do dashboard |
| Adaptador `nmap` / variante `xexeu-scanner-nmap` | 🚧 ainda não implementado |
| Adaptador `nmap` / variante `harpia-scanner-nmap` | 🚧 ainda não implementado |
| Releases publicados | ❌ nenhum ainda — veja [ROADMAP.pt-BR.md](ROADMAP.pt-BR.md) |
## Princípios centrais
A Xexéu executa um ciclo contínuo: **agendar → varrer → identificar → historizar → expor**.
A Harpia executa um ciclo contínuo: **agendar → varrer → identificar → historizar → expor**.
1. **Agendamento em níveis:** expressões cron por grupo com jitter e um orçamento de taxa compartilhado evitam saturação de rede.
2. **Flexibilidade de motor duplo:** o motor nativo SYN em Rust por padrão, um fallback TCP connect sem privilégio sempre disponível, e um adaptador externo `nmap` opcional planejado pra descoberta de serviço mais profunda.
@@ -51,9 +51,9 @@ A Xexéu executa um ciclo contínuo: **agendar → varrer → identificar → hi
## Uso autorizado
A Xexéu é software defensivo desenhado estritamente pra redes que você possui ou tem autorização explícita pra auditar. Varrer infraestrutura de terceiros sem permissão é ilegal. Operadores são responsáveis pelo escopo, conformidade e políticas de retenção de dados.
A Harpia é software defensivo desenhado estritamente pra redes que você possui ou tem autorização explícita pra auditar. Varrer infraestrutura de terceiros sem permissão é ilegal. Operadores são responsáveis pelo escopo, conformidade e políticas de retenção de dados.
A configuração exige um bloco `[escopo]` explícito. Qualquer alvo que resolva fora das faixas CIDR autorizadas é rejeitado. O daemon de API vincula em `127.0.0.1` por padrão; leituras são abertas, e as rotas que mudam a configuração exigem um token de administração (`XEXEU_ADMIN_TOKEN`, ou o link avulso impresso na partida). Coloque atrás de um proxy reverso autenticador antes de expor além do localhost. Veja [SECURITY.pt-BR.md](SECURITY.pt-BR.md).
A configuração exige um bloco `[escopo]` explícito. Qualquer alvo que resolva fora das faixas CIDR autorizadas é rejeitado. O daemon de API vincula em `127.0.0.1` por padrão; leituras são abertas, e as rotas que mudam a configuração exigem um token de administração (`HARPIA_ADMIN_TOKEN`, ou o link avulso impresso na partida). Coloque atrás de um proxy reverso autenticador antes de expor além do localhost. Veja [SECURITY.pt-BR.md](SECURITY.pt-BR.md).
## Instalação
@@ -61,12 +61,12 @@ Rode via Docker Compose (recomendado pra operadores):
```bash
cp .env.example .env
mkdir -p config && cp examples/xexeu.toml config/xexeu.toml
mkdir -p config && cp examples/harpia.toml config/harpia.toml
docker compose pull && docker compose up -d
docker compose logs xexeu | grep token # link avulso de admin, se XEXEU_ADMIN_TOKEN não estiver definido
docker compose logs harpia | grep token # link avulso de admin, se HARPIA_ADMIN_TOKEN não estiver definido
```
A imagem é pública: `docker pull git.lucasrguerra.dev.br/ciberfauna/xexeu:latest`.
A imagem é pública: `docker pull git.lucasrguerra.dev.br/ciberfauna/harpia:latest`.
Ou builde e rode localmente com Docker:
@@ -77,15 +77,15 @@ docker compose up -d --build
Pra compilar a partir do código-fonte nativamente (só Rust 1.88+ — sem biblioteca externa pra buscar, o SQLite vem embutido):
```bash
cargo build --release -p xexeu-cli
./target/release/xexeu --help
cargo build --release -p harpia-cli
./target/release/harpia --help
```
Ou baixe o CLI avulso na [página de releases](https://git.lucasrguerra.dev.br/ciberfauna/xexeu/releases) (`linux-x86_64` e `linux-aarch64`) e confira com o `.sha256`:
Ou baixe o CLI avulso na [página de releases](https://git.lucasrguerra.dev.br/ciberfauna/harpia/releases) (`linux-x86_64` e `linux-aarch64`) e confira com o `.sha256`:
```bash
sha256sum -c xexeu-v1.0.0-linux-x86_64.tar.gz.sha256
tar xzf xexeu-v1.0.0-linux-x86_64.tar.gz
sha256sum -c harpia-v1.0.0-linux-x86_64.tar.gz.sha256
tar xzf harpia-v1.0.0-linux-x86_64.tar.gz
```
Matriz de plataforma suportada pras imagens de container: `linux/amd64` e `linux/arm64`.
@@ -94,19 +94,19 @@ Matriz de plataforma suportada pras imagens de container: `linux/amd64` e `linux
```bash
# Valide sua configuração e veja os agendamentos efetivos
xexeu config check --config config/xexeu.toml
harpia config check --config config/harpia.toml
# Inicie o daemon do servidor e o dashboard web
xexeu serve --bind 127.0.0.1:8788 --config config/xexeu.toml
harpia serve --bind 127.0.0.1:8788 --config config/harpia.toml
# Rode uma varredura avulsa de diagnóstico pra um grupo específico
xexeu scan --group dmz --once
harpia scan --group dmz --once
# Inspecione mudanças recentes de superfície
xexeu changes --since 24h
harpia changes --since 24h
# Diagnostique o ambiente (capabilities, feeds, armazenamento)
xexeu doctor
harpia doctor
```
Veja [docs/pt-BR/cli.md](docs/pt-BR/cli.md) pra referência completa de comandos.
@@ -136,7 +136,7 @@ Resumo do [ROADMAP](ROADMAP.pt-BR.md):
|---|---|
| **Feito (1.2.0)** | Crates do workspace, motores de varredura SYN/connect nativos, fingerprint, correlação CVE/KEV, diffs por escopo, armazenamento SQLite+Parquet, dashboard, relatório executivo, exportação CSV, CRUD de config com hot-reload do scanner protegido por token de administração, CI/CD com imagem e CLI publicados, testes de propriedade e fuzzing semanal, alertas por webhook, métricas Prometheus |
| **Próximo** | Mapeamento de backports de distribuição, alertas por e-mail |
| **Depois** | Adaptador `nmap` e a variante `xexeu-scanner-nmap`, correlação OSV, agregação de vários scanners |
| **Depois** | Adaptador `nmap` e a variante `harpia-scanner-nmap`, correlação OSV, agregação de vários scanners |
| **Não planejado** | Payloads de exploração, motor NASL, serviços de nuvem obrigatórios, wrapper desktop Tauri |
## Licença
+5 -5
View File
@@ -2,15 +2,15 @@
**English** · [Português](ROADMAP.pt-BR.md)
Xexéu does continuous attack-surface and vulnerability auditing: it sweeps authorized networks on a schedule, fingerprints exposed services, correlates them with NVD/CISA KEV, and records every change in the surface. Always within an explicitly authorized scope, with no active exploitation.
Harpia does continuous attack-surface and vulnerability auditing: it sweeps authorized networks on a schedule, fingerprints exposed services, correlates them with NVD/CISA KEV, and records every change in the surface. Always within an explicitly authorized scope, with no active exploitation.
## Done
- **Webhook alerts (1.2.0):** surface changes posted after each sweep, filtered by kind and group, as JSON or Slack/Discord messages, HMAC-signed, with retries.
- **Prometheus metrics (1.2.0):** `/metrics` with hosts, ports, findings by severity, feed age, per-group last sweep and webhook deliveries.
- **Robustness (1.1.0):** fuzzing of the parsers that read untrusted input (service banners, NVD/KEV feeds, target expansion), property tests for the diff engine's no-false-disappearance guarantee, `xexeu-cli` split into modules, and a weekly dependency audit.
- **Admin token for configuration changes (1.0.0):** the group CRUD routes require `XEXEU_ADMIN_TOKEN` (or a one-off token printed at startup), compared in constant time, plus a same-origin check.
- **Rust workspace & CLI:** `crates/xexeu-core` and `crates/xexeu-cli`; `serve`, `scanner`, `scan`, `config check`, `feeds sync`/`import`, `changes`, `export`, `doctor` all implemented, not stubs.
- **Robustness (1.1.0):** fuzzing of the parsers that read untrusted input (service banners, NVD/KEV feeds, target expansion), property tests for the diff engine's no-false-disappearance guarantee, `harpia-cli` split into modules, and a weekly dependency audit.
- **Admin token for configuration changes (1.0.0):** the group CRUD routes require `HARPIA_ADMIN_TOKEN` (or a one-off token printed at startup), compared in constant time, plus a same-origin check.
- **Rust workspace & CLI:** `crates/harpia-core` and `crates/harpia-cli`; `serve`, `scanner`, `scan`, `config check`, `feeds sync`/`import`, `changes`, `export`, `doctor` all implemented, not stubs.
- **Target & tiered schedule configuration:** `[escopo]`, `[padrao]`, `[perfis.*]`, `[[grupo]]` parsing; CIDR/range/DNS target expansion with rigid `escopo.autorizado` enforcement; 5-field cron with shortcuts, jitter and an aggressive-cadence warning (< 5 min); groups and their cron are editable live from the dashboard (`/api/config/groups`), with `scanner` hot-reloading on the config file's mtime.
- **Scan engine & scheduler:** multi-group scheduler with a shared packet-rate budget and non-overlapping group runs; native raw-socket SYN engine (`nativo`, requires `CAP_NET_RAW`) with automatic fallback to the unprivileged TCP-connect engine (`nativo-sem-raw`); HTTP/SSH/TLS service fingerprinting; atomic Parquet batch writes (`observations.parquet` + `manifest.json`) with file permissions explicit about the two containers running as different, unrelated Linux users.
- **Non-intrusive vulnerability identification:** local NVD CVE JSON 2.0 + CISA KEV caching, offline import or live sync (one-shot or periodic background, independent of image/binary updates); deterministic CPE → CVE matcher with confidence levels (`alta`/`média`/`baixa`); safe configuration checks (expired/soon-to-expire TLS certificates, unencrypted administrative ports).
@@ -26,7 +26,7 @@ Xexéu does continuous attack-surface and vulnerability auditing: it sweeps auth
## Later
- **`nmap` adapter & `xexeu-scanner-nmap` variant:** optional integration with the external `nmap` binary for richer service fingerprinting on profiles that opt in.
- **`nmap` adapter & `harpia-scanner-nmap` variant:** optional integration with the external `nmap` binary for richer service fingerprinting on profiles that opt in.
- **OSV feed integration:** Open Source Vulnerabilities database correlation for exposed application dependencies.
- **Advanced network topologies:** coordinated multi-scanner worker pools reporting to a centralized aggregator daemon.
+5 -5
View File
@@ -2,15 +2,15 @@
[English](ROADMAP.md) · **Português**
O Xexéu faz auditoria contínua de superfície de ataque e de vulnerabilidades: varre redes autorizadas num agendamento, identifica os serviços expostos, correlaciona com NVD/CISA KEV e registra cada mudança na superfície. Sempre dentro de um escopo explicitamente autorizado, sem exploração ativa.
O Harpia faz auditoria contínua de superfície de ataque e de vulnerabilidades: varre redes autorizadas num agendamento, identifica os serviços expostos, correlaciona com NVD/CISA KEV e registra cada mudança na superfície. Sempre dentro de um escopo explicitamente autorizado, sem exploração ativa.
## Concluído
- **Alertas por webhook (1.2.0):** mudanças de superfície enviadas depois de cada varredura, filtradas por tipo e grupo, como JSON ou mensagem de Slack/Discord, assinadas com HMAC, com novas tentativas.
- **Métricas Prometheus (1.2.0):** `/metrics` com hosts, portas, achados por severidade, idade dos feeds, última varredura por grupo e entregas de webhook.
- **Robustez (1.1.0):** fuzzing dos parsers que leem entrada não confiável (banners de serviço, feeds NVD/KEV, expansão de alvos), testes de propriedade da garantia de nenhum desaparecimento falso do motor de diff, `xexeu-cli` dividido em módulos e auditoria semanal de dependências.
- **Token de administração para mudanças de configuração (1.0.0):** as rotas de CRUD de grupos exigem `XEXEU_ADMIN_TOKEN` (ou um token avulso impresso na partida), comparado em tempo constante, mais checagem de mesma origem.
- **Workspace Rust e CLI:** `crates/xexeu-core` e `crates/xexeu-cli`; `serve`, `scanner`, `scan`, `config check`, `feeds sync`/`import`, `changes`, `export`, `doctor` todos implementados de verdade, não são mais stub.
- **Robustez (1.1.0):** fuzzing dos parsers que leem entrada não confiável (banners de serviço, feeds NVD/KEV, expansão de alvos), testes de propriedade da garantia de nenhum desaparecimento falso do motor de diff, `harpia-cli` dividido em módulos e auditoria semanal de dependências.
- **Token de administração para mudanças de configuração (1.0.0):** as rotas de CRUD de grupos exigem `HARPIA_ADMIN_TOKEN` (ou um token avulso impresso na partida), comparado em tempo constante, mais checagem de mesma origem.
- **Workspace Rust e CLI:** `crates/harpia-core` e `crates/harpia-cli`; `serve`, `scanner`, `scan`, `config check`, `feeds sync`/`import`, `changes`, `export`, `doctor` todos implementados de verdade, não são mais stub.
- **Configuração de alvos e agendamento em níveis:** parse de `[escopo]`, `[padrao]`, `[perfis.*]`, `[[grupo]]`; expansão de alvo CIDR/faixa/DNS com imposição estrita de `escopo.autorizado`; cron de 5 campos com atalhos, jitter e aviso de cadência agressiva (< 5 min); grupos e seu cron são editáveis ao vivo pelo dashboard (`/api/config/groups`), com o `scanner` recarregando sozinho pelo `mtime` do arquivo de config.
- **Motor de varredura e agendador:** agendador multi-grupo com orçamento de taxa de pacotes compartilhado e sem sobreposição de execuções; motor nativo de SYN cru (`nativo`, exige `CAP_NET_RAW`) com fallback automático pro motor TCP connect sem privilégio (`nativo-sem-raw`); fingerprint de serviço HTTP/SSH/TLS; gravação atômica de lotes Parquet (`observations.parquet` + `manifest.json`) com permissões de arquivo explícitas sobre os dois containers rodando como usuários Linux diferentes e sem relação.
- **Identificação não intrusiva de vulnerabilidades:** cache local do NVD CVE JSON 2.0 + CISA KEV, importação offline ou sync ao vivo (único ou periódico em segundo plano, independente de atualização de imagem/binário); correlacionador determinístico CPE → CVE com níveis de confiança (`alta`/`média`/`baixa`); checagens seguras de configuração (certificados TLS expirados ou prestes a expirar, portas administrativas sem criptografia).
@@ -26,7 +26,7 @@ O Xexéu faz auditoria contínua de superfície de ataque e de vulnerabilidades:
## Depois
- **Adaptador `nmap` e variante `xexeu-scanner-nmap`:** integração opcional com o binário externo `nmap` pra fingerprint de serviço mais rico em perfis que optarem por isso.
- **Adaptador `nmap` e variante `harpia-scanner-nmap`:** integração opcional com o binário externo `nmap` pra fingerprint de serviço mais rico em perfis que optarem por isso.
- **Integração com feeds OSV:** correlação contra a base Open Source Vulnerabilities pra dependências de aplicações expostas.
- **Topologias distribuídas:** agrupamentos de múltiplos scanners reportando pra um daemon agregador centralizado.
+6 -6
View File
@@ -2,7 +2,7 @@
**English** · [Português](SECURITY.pt-BR.md)
Xexéu is defensive software, but it operates over active networks and processes untrusted remote responses: service banners, TLS certificates, and raw network packets may be malformed on purpose. Treat every target network response as untrusted.
Harpia is defensive software, but it operates over active networks and processes untrusted remote responses: service banners, TLS certificates, and raw network packets may be malformed on purpose. Treat every target network response as untrusted.
## Reporting a vulnerability
@@ -11,14 +11,14 @@ Do not open a public issue with exploit details. Open a minimal issue asking for
## Scope and threat model
- **Container hardening & privilege separation:**
- The `scanner` service runs with `cap_drop: [ALL]` and only `cap_add: [NET_RAW]`. It has no `NET_ADMIN`, no `SYS_ADMIN`, a read-only root filesystem (`read_only: true`), `no-new-privileges: true`, and writes exclusively to the dedicated `xexeu-sweeps` volume.
- The `xexeu` daemon (API, diff engine, dashboard) runs as an unprivileged user (UID 10001) with zero capabilities (`cap_drop: [ALL]`), a read-only root filesystem, and mounts the `xexeu-sweeps` volume as read-only (`:ro`).
- The `scanner` service runs with `cap_drop: [ALL]` and only `cap_add: [NET_RAW]`. It has no `NET_ADMIN`, no `SYS_ADMIN`, a read-only root filesystem (`read_only: true`), `no-new-privileges: true`, and writes exclusively to the dedicated `harpia-sweeps` volume.
- The `harpia` daemon (API, diff engine, dashboard) runs as an unprivileged user (UID 10001) with zero capabilities (`cap_drop: [ALL]`), a read-only root filesystem, and mounts the `harpia-sweeps` volume as read-only (`:ro`).
- **Strict authorized scope:** Target expansion enforces the `[escopo]` configuration boundary. Any target or DNS resolution resolving outside authorized CIDR blocks is rejected at validation time, preventing accidental or unauthorized scanning.
- **Safe vulnerability identification:** Xexéu does not execute exploit payloads, perform credential brute-forcing, or execute denial-of-service tests. Checks are limited to passive banner matching and standard cryptographic handshakes.
- **Safe vulnerability identification:** Harpia does not execute exploit payloads, perform credential brute-forcing, or execute denial-of-service tests. Checks are limited to passive banner matching and standard cryptographic handshakes.
- **Input and batch parsing:** Malformed packets, banner responses, and Parquet batch files must not panic the engine or cause memory exhaustion.
- **API exposure:** The API daemon listens on `127.0.0.1:8788` by default. Configuration changes require the admin token (`XEXEU_ADMIN_TOKEN`, compared in constant time) and a same-origin request; reads are not authenticated, so exposing it on an external network interface still requires an authenticating reverse proxy.
- **API exposure:** The API daemon listens on `127.0.0.1:8788` by default. Configuration changes require the admin token (`HARPIA_ADMIN_TOKEN`, compared in constant time) and a same-origin request; reads are not authenticated, so exposing it on an external network interface still requires an authenticating reverse proxy.
- **Evidence integrity:** Findings and diff events must be reproducible from the same observations and feeds. Nondeterministic behavior is treated as a correctness and security defect.
- **Privacy & local-first:** There is no telemetry. Vulnerability feeds are cached locally in SQLite/Parquet; air-gapped offline import (`xexeu feeds import`) is fully supported.
- **Privacy & local-first:** There is no telemetry. Vulnerability feeds are cached locally in SQLite/Parquet; air-gapped offline import (`harpia feeds import`) is fully supported.
## Out of scope
+6 -6
View File
@@ -2,7 +2,7 @@
[English](SECURITY.md) · **Português**
O Xexéu é software defensivo, mas opera sobre redes ativas e processa respostas remotas não confiáveis: banners de serviços, certificados TLS e pacotes de rede podem ser intencionalmente malformados. Trate toda resposta de rede como não confiável.
O Harpia é software defensivo, mas opera sobre redes ativas e processa respostas remotas não confiáveis: banners de serviços, certificados TLS e pacotes de rede podem ser intencionalmente malformados. Trate toda resposta de rede como não confiável.
## Relatando uma vulnerabilidade
@@ -11,14 +11,14 @@ Não abra uma issue pública com detalhes de exploração. Abra uma issue mínim
## Escopo e modelo de ameaças
- **Endurecimento de containers e separação de privilégios:**
- O serviço `scanner` executa com `cap_drop: [ALL]` e apenas `cap_add: [NET_RAW]`. Ele não possui `NET_ADMIN`, não possui `SYS_ADMIN`, possui filesystem raiz somente leitura (`read_only: true`), `no-new-privileges: true`, e grava exclusivamente no volume dedicado `xexeu-sweeps`.
- O daemon `xexeu` (API, motor de diffs e dashboard) executa como usuário sem privilégios (UID 10001) com zero capabilities (`cap_drop: [ALL]`), filesystem somente leitura e monta o volume de lotes como somente leitura (`:ro`).
- O serviço `scanner` executa com `cap_drop: [ALL]` e apenas `cap_add: [NET_RAW]`. Ele não possui `NET_ADMIN`, não possui `SYS_ADMIN`, possui filesystem raiz somente leitura (`read_only: true`), `no-new-privileges: true`, e grava exclusivamente no volume dedicado `harpia-sweeps`.
- O daemon `harpia` (API, motor de diffs e dashboard) executa como usuário sem privilégios (UID 10001) com zero capabilities (`cap_drop: [ALL]`), filesystem somente leitura e monta o volume de lotes como somente leitura (`:ro`).
- **Escopo autorizado estrito:** A expansão de alvos impõe a barreira definida em `[escopo]`. Qualquer alvo ou resolução DNS que caia fora das faixas CIDR autorizadas é rejeitado na validação, prevenindo varreduras acidentais ou não autorizadas.
- **Identificação segura de vulnerabilidades:** O Xexéu não executa payloads de exploração, força bruta de credenciais ou testes de negação de serviço. As checagens se limitam a correlação passiva de banners e handshakes criptográficos padronizados.
- **Identificação segura de vulnerabilidades:** O Harpia não executa payloads de exploração, força bruta de credenciais ou testes de negação de serviço. As checagens se limitam a correlação passiva de banners e handshakes criptográficos padronizados.
- **Parsing de entradas e lotes:** Pacotes malformados, respostas anômalas de banner e arquivos de lote Parquet corrompidos não devem causar panic no motor nem exaustão de recursos.
- **Exposição da API:** O daemon escuta em `127.0.0.1:8788` por padrão. Mudanças de configuração exigem o token de administração (`XEXEU_ADMIN_TOKEN`, comparado em tempo constante) e requisição de mesma origem; leituras não são autenticadas, então expô-lo externamente ainda exige um proxy reverso com autenticação.
- **Exposição da API:** O daemon escuta em `127.0.0.1:8788` por padrão. Mudanças de configuração exigem o token de administração (`HARPIA_ADMIN_TOKEN`, comparado em tempo constante) e requisição de mesma origem; leituras não são autenticadas, então expô-lo externamente ainda exige um proxy reverso com autenticação.
- **Integridade da evidência:** Achados e eventos de diff devem ser reproduzíveis a partir das mesmas observações e bases de feeds. Nãodeterminismo é tratado como falha de corretude e segurança.
- **Privacidade e local-first:** Não há telemetria. Os feeds de vulnerabilidades são armazenados localmente em SQLite/Parquet; importação offline para redes isoladas (`xexeu feeds import`) é suportada nativamente.
- **Privacidade e local-first:** Não há telemetria. Os feeds de vulnerabilidades são armazenados localmente em SQLite/Parquet; importação offline para redes isoladas (`harpia feeds import`) é suportada nativamente.
## Fora de escopo
+10 -10
View File
@@ -4,9 +4,9 @@ const SVG_NS = 'http://www.w3.org/2000/svg';
const $ = (selector) => document.querySelector(selector);
const $$ = (selector) => document.querySelectorAll(selector);
// Admin token for the routes that change state. `xexeu serve` prints a link
// Admin token for the routes that change state. `harpia serve` prints a link
// with `?token=`; it is kept for this tab only and dropped from the address bar.
const TOKEN_KEY = 'xexeu.adminToken';
const TOKEN_KEY = 'harpia.adminToken';
{
const params = new URLSearchParams(location.search);
if (params.has('token')) {
@@ -25,7 +25,7 @@ async function adminFetch(url, options = {}) {
});
let res = await send();
if (res.status === 401) {
const token = window.prompt(t('Token de administração (exibido no log do xexeu serve ou definido em XEXEU_ADMIN_TOKEN):'));
const token = window.prompt(t('Token de administração (exibido no log do harpia serve ou definido em HARPIA_ADMIN_TOKEN):'));
if (token && token.trim()) {
sessionStorage.setItem(TOKEN_KEY, token.trim());
res = await send();
@@ -269,7 +269,7 @@ async function fetchData() {
]);
if (!healthRes || !statusRes || !hostsRes) {
throw new Error('Falha ao comunicar com a API do Xexéu');
throw new Error('Falha ao comunicar com a API do Harpia');
}
state.health = await healthRes.json();
@@ -282,7 +282,7 @@ async function fetchData() {
connection.classList.remove('offline');
connectionText.textContent = t('Conectado');
if (state.health && state.health.version) {
versionEl.textContent = `Xexéu v${state.health.version}`;
versionEl.textContent = `Harpia v${state.health.version}`;
$('#versionPill').textContent = `v${state.health.version}`;
}
if (state.status) {
@@ -1359,16 +1359,16 @@ function eventKindLabel(kind) {
// ------------------------------------------------------------------ SETTINGS & THEME
function initSettings() {
const savedLang = localStorage.getItem('xexeu-lang') || 'auto';
const savedLang = localStorage.getItem('harpia-lang') || 'auto';
langSel.value = savedLang;
setLang(resolveLang(savedLang));
const savedTheme = localStorage.getItem('xexeu-theme') || 'auto';
const savedTheme = localStorage.getItem('harpia-theme') || 'auto';
applyTheme(savedTheme);
langSel.addEventListener('change', () => {
const val = langSel.value;
localStorage.setItem('xexeu-lang', val);
localStorage.setItem('harpia-lang', val);
setLang(resolveLang(val));
render();
});
@@ -1376,7 +1376,7 @@ function initSettings() {
themePick.querySelectorAll('button').forEach((btn) => {
btn.addEventListener('click', () => {
const mode = btn.dataset.themePick;
localStorage.setItem('xexeu-theme', mode);
localStorage.setItem('harpia-theme', mode);
applyTheme(mode);
});
});
@@ -1386,7 +1386,7 @@ function initSettings() {
doneSettings.addEventListener('click', () => settingsDlg.close());
// Listen to language change to trigger re-render
document.addEventListener('xexeu:lang', () => {
document.addEventListener('harpia:lang', () => {
render();
});
}
+5 -5
View File
@@ -1,5 +1,5 @@
export const EN = {
'Xexéu': 'Xexéu',
'Harpia': 'Harpia',
'superfície contínua e vulnerabilidades': 'continuous attack surface and vulnerabilities',
'Navegação': 'Navigation',
'Visão geral': 'Overview',
@@ -55,7 +55,7 @@ export const EN = {
// Notice & Footnotes
'Uso autorizado.': 'Authorized use.',
'Auditoria contínua e não-intrusiva estritamente nos escopos autorizados. Nenhum payload destrutivo ou exploit é disparado.': 'Continuous, non-intrusive auditing strictly on authorized scopes. No destructive payload or exploit is fired.',
'Xexéu · auditoria contínua de superfície de ataque': 'Xexéu · continuous attack surface auditing',
'Harpia · auditoria contínua de superfície de ataque': 'Harpia · continuous attack surface auditing',
// Hosts View
'Hosts e Superfície Descoberta': 'Hosts and Discovered Surface',
@@ -185,7 +185,7 @@ export const EN = {
'{n}min atrás': '{n}min ago',
'{n}h atrás': '{n}h ago',
'{n}d atrás': '{n}d ago',
'Falha ao comunicar com a API do Xexéu': 'Could not reach the Xexéu API',
'Falha ao comunicar com a API do Harpia': 'Could not reach the Harpia API',
'Contém vulnerabilidade no CISA KEV!': 'Has a vulnerability in CISA KEV!',
'Clique para abrir na tabela de hosts': 'Click to open it in the hosts table',
'Serviço desconhecido': 'Unknown service',
@@ -199,7 +199,7 @@ export const EN = {
'Erro de rede ao salvar grupo': 'Network error while saving the group',
'Erro ao remover grupo': 'Could not remove the group',
'Erro de rede ao remover grupo': 'Network error while removing the group',
'Xexéu — Auditoria Contínua de Superfície de Ataque': 'Xexéu — Continuous Attack Surface Auditing',
'Harpia — Auditoria Contínua de Superfície de Ataque': 'Harpia — Continuous Attack Surface Auditing',
'superfície de risco': 'risk surface',
'Informações de sincronização incremental NVD e catálogo CISA KEV.': 'Incremental NVD sync and CISA KEV catalog status.',
'Média': 'Medium',
@@ -211,7 +211,7 @@ export const EN = {
'Filtrar por severidade': 'Filter by severity',
'Filtrar por período': 'Filter by period',
'Filtrar por IP ou tipo de evento...': 'Filter by IP or event type...',
'Token de administração (exibido no log do xexeu serve ou definido em XEXEU_ADMIN_TOKEN):': 'Admin token (shown in the xexeu serve log or set in XEXEU_ADMIN_TOKEN):',
'Token de administração (exibido no log do harpia serve ou definido em HARPIA_ADMIN_TOKEN):': 'Admin token (shown in the harpia serve log or set in HARPIA_ADMIN_TOKEN):',
'token de administração ausente ou inválido': 'admin token missing or invalid',
'origem da requisição não confere': 'request origin does not match',
};
+1 -1
View File
@@ -129,6 +129,6 @@ export function setLang(next) {
}
restoreAll(document.body);
}
document.dispatchEvent(new CustomEvent('xexeu:lang', { detail: { lang } }));
document.dispatchEvent(new CustomEvent('harpia:lang', { detail: { lang } }));
}
}
+6 -6
View File
@@ -3,7 +3,7 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Xexéu — Auditoria Contínua de Superfície de Ataque</title>
<title>Harpia — Auditoria Contínua de Superfície de Ataque</title>
<link rel="icon" href="/logo.png">
<link rel="stylesheet" href="/app.css">
</head>
@@ -11,9 +11,9 @@
<div class="app">
<aside class="sidebar">
<div class="brand">
<img class="logo" src="/logo.png" alt="Xexéu Logo">
<img class="logo" src="/logo.png" alt="Harpia Logo">
<div>
<strong>Xexéu</strong>
<strong>Harpia</strong>
<small>superfície contínua e vulnerabilidades</small>
</div>
</div>
@@ -52,7 +52,7 @@
<span id="versionPill" class="pill muted">—</span>
</div>
<div class="status-row">
<span id="version" class="mono">Xexéu</span>
<span id="version" class="mono">Harpia</span>
<span class="mono" id="feedsStatus">—</span>
</div>
</div>
@@ -61,7 +61,7 @@
<main class="main">
<header class="topbar">
<div>
<p class="eyebrow">Xexéu</p>
<p class="eyebrow">Harpia</p>
<h1 id="viewTitle">Visão geral</h1>
<p id="viewSub" class="sub">Auditoria contínua de superfície de ataque e identificação de vulnerabilidades</p>
</div>
@@ -305,7 +305,7 @@
</section>
<footer class="foot">
<span>Xexéu · auditoria contínua de superfície de ataque</span>
<span>Harpia · auditoria contínua de superfície de ataque</span>
<span class="mono">MIT OR Apache-2.0</span>
</footer>
</main>
@@ -1,6 +1,6 @@
[package]
name = "xexeu-cli"
description = "Xexéu: continuous attack-surface auditing daemon, scanner and CLI"
name = "harpia-cli"
description = "Harpia: continuous attack-surface auditing daemon, scanner and CLI"
version.workspace = true
edition.workspace = true
license.workspace = true
@@ -9,11 +9,11 @@ authors.workspace = true
rust-version.workspace = true
[[bin]]
name = "xexeu"
name = "harpia"
path = "src/main.rs"
[dependencies]
xexeu-core = { path = "../xexeu-core" }
harpia-core = { path = "../harpia-core" }
axum = "0.8"
chrono = { version = "0.4", features = ["clock"] }
clap = { version = "4", features = ["derive", "env"] }
@@ -2,10 +2,10 @@
//!
//! Reads stay open, as before: the dashboard is meant to sit on loopback or
//! behind a reverse proxy. Writes decide what the scanner sweeps, so they need
//! the admin token in `Authorization: Bearer <token>` or `X-Xexeu-Token`, and a
//! the admin token in `Authorization: Bearer <token>` or `X-Harpia-Token`, and a
//! browser `Origin`, when sent, must match `Host` (CSRF).
//!
//! The token comes from `--admin-token`/`XEXEU_ADMIN_TOKEN`; without one, a
//! The token comes from `--admin-token`/`HARPIA_ADMIN_TOKEN`; without one, a
//! random token is generated at startup and printed once, the same way
//! `sabia ui` hands out its session token.
@@ -54,9 +54,9 @@ impl AdminToken {
}
}
/// Token sent by the client, from `Authorization: Bearer` or `X-Xexeu-Token`.
/// Token sent by the client, from `Authorization: Bearer` or `X-Harpia-Token`.
fn presented_token(headers: &HeaderMap) -> Option<&str> {
if let Some(value) = headers.get("x-xexeu-token").and_then(|v| v.to_str().ok()) {
if let Some(value) = headers.get("x-harpia-token").and_then(|v| v.to_str().ok()) {
return Some(value.trim());
}
headers
@@ -142,7 +142,7 @@ mod tests {
HeaderValue::from_static("Bearer xyz"),
);
assert_eq!(presented_token(&headers), Some("xyz"));
headers.insert("x-xexeu-token", HeaderValue::from_static("abc"));
headers.insert("x-harpia-token", HeaderValue::from_static("abc"));
assert_eq!(presented_token(&headers), Some("abc"));
headers.clear();
headers.insert(header::AUTHORIZATION, HeaderValue::from_static("Basic xyz"));
@@ -1,4 +1,4 @@
//! `xexeu changes`, `xexeu doctor` and `xexeu export`.
//! `harpia changes`, `harpia doctor` and `harpia export`.
use std::fs;
use std::path::Path;
@@ -6,10 +6,10 @@ use std::process::ExitCode;
use crate::server::export::{current_state_to_dtos, generate_hosts_csv};
use crate::{fail, parse_since};
use xexeu_core::storage::{SqliteStorage, Storage};
use harpia_core::storage::{SqliteStorage, Storage};
pub(crate) fn run_changes(since: &str, data_dir: &Path) -> ExitCode {
let db_path = data_dir.join("xexeu.db");
let db_path = data_dir.join("harpia.db");
if !db_path.exists() {
return fail(&format!(
"banco de dados não encontrado em {}",
@@ -34,7 +34,7 @@ pub(crate) fn run_changes(since: &str, data_dir: &Path) -> ExitCode {
}
pub(crate) fn run_doctor(as_json: bool, config_path: &Path, data_dir: &Path) -> ExitCode {
let report = xexeu_core::doctor::run(config_path, data_dir);
let report = harpia_core::doctor::run(config_path, data_dir);
if as_json {
match serde_json::to_string_pretty(&report) {
@@ -53,7 +53,7 @@ pub(crate) fn run_doctor(as_json: bool, config_path: &Path, data_dir: &Path) ->
}
pub(crate) fn run_export(format: &str, data_dir: &Path, out_file: Option<&Path>) -> ExitCode {
let db_path = data_dir.join("xexeu.db");
let db_path = data_dir.join("harpia.db");
let storage = match SqliteStorage::open(&db_path) {
Ok(s) => s,
Err(err) => {
@@ -1,4 +1,4 @@
//! `xexeu config check`: validation report, effective schedules and overlapping groups.
//! `harpia config check`: validation report, effective schedules and overlapping groups.
use std::collections::HashSet;
use std::net::IpAddr;
@@ -7,8 +7,8 @@ use std::process::ExitCode;
use crate::{fail, validated_config};
use chrono::Utc;
use xexeu_core::config::XexeuConfig;
use xexeu_core::targets::{effective_cadence, expand_group, IpRange};
use harpia_core::config::HarpiaConfig;
use harpia_core::targets::{effective_cadence, expand_group, IpRange};
pub(crate) fn run_config_check(path: &Path) -> ExitCode {
let (config, report) = match validated_config(path) {
@@ -61,7 +61,7 @@ pub(crate) fn run_config_check(path: &Path) -> ExitCode {
ExitCode::SUCCESS
}
fn overlapping_ranges(config: &XexeuConfig) -> Result<Vec<IpRange>, String> {
fn overlapping_ranges(config: &HarpiaConfig) -> Result<Vec<IpRange>, String> {
let expansions = config
.groups
.iter()
@@ -1,11 +1,13 @@
//! `xexeu feeds import` and `xexeu feeds sync`.
//! `harpia feeds import` and `harpia feeds sync`.
use std::fs;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use crate::fail;
use xexeu_core::vuln::{import_kev, import_nvd, sync_feeds, KevCatalog, SyncOptions, VulnDatabase};
use harpia_core::vuln::{
import_kev, import_nvd, sync_feeds, KevCatalog, SyncOptions, VulnDatabase,
};
fn find_matching_file(dir: &Path, keyword: &str, ext: &str) -> Option<PathBuf> {
let entries = fs::read_dir(dir).ok()?;
@@ -14,14 +14,14 @@ use clap::{Parser, Subcommand};
use commands::{run_changes, run_doctor, run_export};
use config_cmd::run_config_check;
use feeds_cmd::{run_feeds_import, run_feeds_sync};
use harpia_core::config::{HarpiaConfig, ValidationReport};
use scanner::{run_scanner, scan_once};
use server::run_serve;
use xexeu_core::config::{ValidationReport, XexeuConfig};
#[derive(Parser)]
#[command(
name = "xexeu",
about = "Xexéu — continuous attack-surface and vulnerability auditing",
name = "harpia",
about = "Harpia — continuous attack-surface and vulnerability auditing",
version
)]
struct Cli {
@@ -35,24 +35,24 @@ enum Command {
Serve {
#[arg(long, default_value = "0.0.0.0:8788")]
bind: String,
#[arg(long, default_value = "config/xexeu.toml")]
#[arg(long, default_value = "config/harpia.toml")]
config: PathBuf,
#[arg(long, default_value = "data/sweeps")]
sweeps: PathBuf,
#[arg(long, default_value = "data/xexeu")]
#[arg(long, default_value = "data/harpia")]
data_dir: PathBuf,
/// Token required by the API routes that change state. Without it, a
/// random token is generated at startup and printed once.
#[arg(long, env = "XEXEU_ADMIN_TOKEN", hide_env_values = true)]
#[arg(long, env = "HARPIA_ADMIN_TOKEN", hide_env_values = true)]
admin_token: Option<String>,
},
/// Run the continuous scheduler and scan engine, writing sweep batches.
Scanner {
#[arg(long, default_value = "config/xexeu.toml")]
#[arg(long, default_value = "config/harpia.toml")]
config: PathBuf,
#[arg(long, default_value = "data/sweeps")]
out: PathBuf,
#[arg(long, default_value = "data/xexeu")]
#[arg(long, default_value = "data/harpia")]
data_dir: PathBuf,
},
/// Run a single sweep for diagnostics.
@@ -61,11 +61,11 @@ enum Command {
group: Option<String>,
#[arg(long)]
once: bool,
#[arg(long, default_value = "config/xexeu.toml")]
#[arg(long, default_value = "config/harpia.toml")]
config: PathBuf,
#[arg(long, default_value = "data/sweeps")]
out: PathBuf,
#[arg(long, default_value = "data/xexeu")]
#[arg(long, default_value = "data/harpia")]
data_dir: PathBuf,
},
/// Inspect the configuration.
@@ -82,14 +82,14 @@ enum Command {
Changes {
#[arg(long, default_value = "24h")]
since: String,
#[arg(long, default_value = "data/xexeu")]
#[arg(long, default_value = "data/harpia")]
data_dir: PathBuf,
},
/// Export the current state.
Export {
#[arg(long, default_value = "json")]
format: String,
#[arg(long, default_value = "data/xexeu")]
#[arg(long, default_value = "data/harpia")]
data_dir: PathBuf,
#[arg(long)]
out: Option<PathBuf>,
@@ -98,9 +98,9 @@ enum Command {
Doctor {
#[arg(long)]
json: bool,
#[arg(long, default_value = "config/xexeu.toml")]
#[arg(long, default_value = "config/harpia.toml")]
config: PathBuf,
#[arg(long, default_value = "data/xexeu")]
#[arg(long, default_value = "data/harpia")]
data_dir: PathBuf,
},
}
@@ -109,7 +109,7 @@ enum Command {
enum ConfigAction {
/// Validate the configuration and print the effective cadence per group.
Check {
#[arg(long, default_value = "config/xexeu.toml")]
#[arg(long, default_value = "config/harpia.toml")]
config: PathBuf,
},
}
@@ -118,9 +118,9 @@ enum ConfigAction {
enum FeedsAction {
/// Download NVD and CISA KEV feeds incrementally.
Sync {
#[arg(long, default_value = "config/xexeu.toml")]
#[arg(long, default_value = "config/harpia.toml")]
config: PathBuf,
#[arg(long, default_value = "data/xexeu")]
#[arg(long, default_value = "data/harpia")]
data_dir: PathBuf,
},
/// Import feed files copied manually for isolated networks.
@@ -130,9 +130,9 @@ enum FeedsAction {
nvd: Option<PathBuf>,
#[arg(long)]
kev: Option<PathBuf>,
#[arg(long, default_value = "config/xexeu.toml")]
#[arg(long, default_value = "config/harpia.toml")]
config: PathBuf,
#[arg(long, default_value = "data/xexeu")]
#[arg(long, default_value = "data/harpia")]
data_dir: PathBuf,
},
}
@@ -204,10 +204,10 @@ fn fail(message: &str) -> ExitCode {
ExitCode::FAILURE
}
fn validated_config(path: &Path) -> Result<(XexeuConfig, ValidationReport), String> {
fn validated_config(path: &Path) -> Result<(HarpiaConfig, ValidationReport), String> {
let raw = fs::read_to_string(path)
.map_err(|error| format!("não foi possível ler {}: {error}", path.display()))?;
XexeuConfig::load_validated(&raw)
HarpiaConfig::load_validated(&raw)
.map_err(|error| format!("configuração inválida em {}: {error}", path.display()))
}
@@ -1,4 +1,4 @@
//! `xexeu scanner` and `xexeu scan`: per-group sweeps written as batches.
//! `harpia scanner` and `harpia scan`: per-group sweeps written as batches.
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
@@ -9,18 +9,18 @@ use std::time::Duration;
use crate::server::shutdown_signal;
use crate::validated_config;
use chrono::Utc;
use xexeu_core::batch::{EngineMode, ServiceObservation, SweepBatch, SweepManifest, SweepStatus};
use xexeu_core::config::XexeuConfig;
use xexeu_core::scan::{
use harpia_core::batch::{EngineMode, ServiceObservation, SweepBatch, SweepManifest, SweepStatus};
use harpia_core::config::HarpiaConfig;
use harpia_core::scan::{
discover_hosts_tcp, fingerprint_service, scan_hosts_syn, scan_hosts_tcp_connect,
DiscoveryConfig, HostPortScanResult, HostState, PortScanConfig, PortState, PortTarget,
SynScanConfig, DEFAULT_DISCOVERY_PORTS,
};
use xexeu_core::schedule::{should_run_now, RunDecision, RunHistory};
use xexeu_core::targets::{expand_group, filter_in_scope, resolve_name, scope_ranges};
use xexeu_core::vuln::checks::{check_tls_certificate_der, evaluate_http_admin_response};
use xexeu_core::vuln::matcher::match_banner;
use xexeu_core::vuln::VulnDatabase;
use harpia_core::schedule::{should_run_now, RunDecision, RunHistory};
use harpia_core::targets::{expand_group, filter_in_scope, resolve_name, scope_ranges};
use harpia_core::vuln::checks::{check_tls_certificate_der, evaluate_http_admin_response};
use harpia_core::vuln::matcher::match_banner;
use harpia_core::vuln::VulnDatabase;
struct ScanSummary {
batch: SweepBatch,
@@ -30,7 +30,7 @@ struct ScanSummary {
}
async fn execute_scan_for_group(
config: &XexeuConfig,
config: &HarpiaConfig,
group_name: &str,
out: &Path,
data_dir: &Path,
@@ -117,7 +117,7 @@ async fn execute_scan_for_group(
let wants_raw = profile.engine == "nativo";
let (port_results, engine_used): (Vec<HostPortScanResult>, EngineMode) = if alive.is_empty() {
(Vec::new(), EngineMode::NativeWithoutRaw)
} else if wants_raw && xexeu_core::caps::has_net_raw() {
} else if wants_raw && harpia_core::caps::has_net_raw() {
let syn_hosts = alive.clone();
let syn_ports = ports.clone();
let syn_config = SynScanConfig::default();
@@ -196,7 +196,7 @@ async fn execute_scan_for_group(
}
}
if xexeu_core::vuln::checks::COMMON_ADMIN_PORTS.contains(&port.port) {
if harpia_core::vuln::checks::COMMON_ADMIN_PORTS.contains(&port.port) {
if let Some(raw) = &fp.raw_banner {
if let Some(f) = evaluate_http_admin_response(port.port, raw) {
findings.push(f);
@@ -297,7 +297,7 @@ pub(crate) async fn run_scanner(
config.groups.len()
);
let tick_interval = std::env::var("XEXEU_SCANNER_TICK_SECS")
let tick_interval = std::env::var("HARPIA_SCANNER_TICK_SECS")
.ok()
.and_then(|val| val.parse().ok())
.map(Duration::from_secs)
@@ -10,11 +10,11 @@ use axum::http::{header, StatusCode};
use axum::response::IntoResponse;
use axum::Json;
use chrono::Utc;
use harpia_core::config::{GroupConfig, HarpiaConfig};
use harpia_core::report::ExecutiveReport;
use harpia_core::schedule::next_runs;
use harpia_core::storage::Storage;
use serde::{Deserialize, Serialize};
use xexeu_core::config::{GroupConfig, XexeuConfig};
use xexeu_core::report::ExecutiveReport;
use xexeu_core::schedule::next_runs;
use xexeu_core::storage::Storage;
#[derive(Serialize)]
pub(crate) struct HealthResponse {
@@ -92,7 +92,7 @@ pub(crate) async fn status_handler(State(state): State<ServerState>) -> Json<Sta
})
}
pub(crate) async fn get_config_handler(State(state): State<ServerState>) -> Json<XexeuConfig> {
pub(crate) async fn get_config_handler(State(state): State<ServerState>) -> Json<HarpiaConfig> {
// Webhook URLs are credentials and reads are not authenticated.
let config = state.config.read().await;
Json(config.redacted())
@@ -112,7 +112,7 @@ pub(crate) async fn create_group_handler(
// `sweep` batches are written to `sweeps/<group>/<sweep_id>/`, so an unsafe
// name here (`/`, `..`) would only fail much later, when a sweep for this
// group actually runs. Reject it now, with a clear error, instead.
if xexeu_core::batch::safe_component(&group_name).is_err() {
if harpia_core::batch::safe_component(&group_name).is_err() {
return Err((
StatusCode::BAD_REQUEST,
format!(
@@ -177,7 +177,7 @@ pub(crate) async fn update_group_handler(
"nome do grupo não pode ser vazio".to_string(),
));
}
if xexeu_core::batch::safe_component(new_name).is_err() {
if harpia_core::batch::safe_component(new_name).is_err() {
return Err((
StatusCode::BAD_REQUEST,
format!(
@@ -277,7 +277,7 @@ pub(crate) struct ChangesQuery {
pub(crate) async fn changes_handler(
State(state): State<ServerState>,
Query(query): Query<ChangesQuery>,
) -> Result<Json<Vec<xexeu_core::diff::Event>>, (StatusCode, String)> {
) -> Result<Json<Vec<harpia_core::diff::Event>>, (StatusCode, String)> {
let since = query.since.as_deref().and_then(parse_since);
let storage = state.storage.lock().await;
let events = storage.events(since).map_err(|error| {
File renamed without changes.
@@ -1,4 +1,4 @@
//! CSV exports, shared with `xexeu export`.
//! CSV exports, shared with `harpia export`.
use super::api::ChangesQuery;
use super::ServerState;
@@ -7,10 +7,10 @@ use axum::extract::{Query, State};
use axum::http::{header, HeaderMap, HeaderValue, StatusCode};
use axum::response::IntoResponse;
use chrono::Utc;
use harpia_core::diff::{CurrentState, EventKind};
use harpia_core::storage::Storage;
use harpia_core::vuln::matcher::{Confidence, Finding};
use serde::Serialize;
use xexeu_core::diff::{CurrentState, EventKind};
use xexeu_core::storage::Storage;
use xexeu_core::vuln::matcher::{Confidence, Finding};
/// Escapes a CSV field per RFC 4180, and neutralizes CSV/formula injection
/// (OWASP's "CSV Injection"): a cell starting with `=`, `+`, `-`, `@` or a tab
@@ -165,7 +165,7 @@ pub(crate) async fn export_hosts_csv_handler(
let csv = generate_hosts_csv(&current_state);
let timestamp = Utc::now().format("%Y%m%d-%H%M%S");
let disposition = format!("attachment; filename=\"xexeu-hosts-{timestamp}.csv\"");
let disposition = format!("attachment; filename=\"harpia-hosts-{timestamp}.csv\"");
let mut headers = HeaderMap::new();
headers.insert(
header::CONTENT_TYPE,
@@ -220,7 +220,7 @@ pub(crate) async fn export_findings_csv_handler(
}
let timestamp = Utc::now().format("%Y%m%d-%H%M%S");
let disposition = format!("attachment; filename=\"xexeu-findings-{timestamp}.csv\"");
let disposition = format!("attachment; filename=\"harpia-findings-{timestamp}.csv\"");
let mut headers = HeaderMap::new();
headers.insert(
header::CONTENT_TYPE,
@@ -283,7 +283,7 @@ pub(crate) async fn export_changes_csv_handler(
}
let timestamp = Utc::now().format("%Y%m%d-%H%M%S");
let disposition = format!("attachment; filename=\"xexeu-changes-{timestamp}.csv\"");
let disposition = format!("attachment; filename=\"harpia-changes-{timestamp}.csv\"");
let mut headers = HeaderMap::new();
headers.insert(
header::CONTENT_TYPE,
@@ -11,12 +11,12 @@ use axum::extract::State;
use axum::http::{header, StatusCode};
use axum::response::IntoResponse;
use chrono::{DateTime, Utc};
use harpia_core::alert;
use harpia_core::batch::SweepManifest;
use harpia_core::config::HarpiaConfig;
use harpia_core::diff::{AssetStatus, Event, PortStatus};
use harpia_core::storage::Storage;
use tokio::sync::{Mutex, RwLock};
use xexeu_core::alert;
use xexeu_core::batch::SweepManifest;
use xexeu_core::config::XexeuConfig;
use xexeu_core::diff::{AssetStatus, Event, PortStatus};
use xexeu_core::storage::Storage;
use super::ServerState;
@@ -47,7 +47,7 @@ impl Metrics {
SweepStat {
finished_at,
duration_secs,
complete: manifest.status == xexeu_core::batch::SweepStatus::Complete,
complete: manifest.status == harpia_core::batch::SweepStatus::Complete,
events,
},
);
@@ -57,7 +57,7 @@ impl Metrics {
/// Posts the sweep's events to every webhook that wants them, in the
/// background: a slow or broken receiver never holds up ingestion.
pub(crate) async fn notify(
config: &RwLock<XexeuConfig>,
config: &RwLock<HarpiaConfig>,
metrics: &Arc<Metrics>,
client: &reqwest::Client,
manifest: &SweepManifest,
@@ -175,9 +175,9 @@ pub(crate) async fn metrics_handler(State(state): State<ServerState>) -> impl In
let mut out = String::new();
metric(
&mut out,
"xexeu_build_info",
"harpia_build_info",
"gauge",
"Running Xexéu version.",
"Running Harpia version.",
&[(
format!("{{version=\"{}\"}}", env!("CARGO_PKG_VERSION")),
1.0,
@@ -185,7 +185,7 @@ pub(crate) async fn metrics_handler(State(state): State<ServerState>) -> impl In
);
metric(
&mut out,
"xexeu_sweeps_ingested_total",
"harpia_sweeps_ingested_total",
"counter",
"Sweep batches ingested since start.",
&[(
@@ -195,7 +195,7 @@ pub(crate) async fn metrics_handler(State(state): State<ServerState>) -> impl In
);
metric(
&mut out,
"xexeu_assets",
"harpia_assets",
"gauge",
"Known hosts by status.",
&[
@@ -205,14 +205,14 @@ pub(crate) async fn metrics_handler(State(state): State<ServerState>) -> impl In
);
metric(
&mut out,
"xexeu_open_ports",
"harpia_open_ports",
"gauge",
"Open ports on known hosts.",
&[(String::new(), open_ports as f64)],
);
metric(
&mut out,
"xexeu_findings",
"harpia_findings",
"gauge",
"Findings on open ports by CVSS severity.",
&findings
@@ -222,7 +222,7 @@ pub(crate) async fn metrics_handler(State(state): State<ServerState>) -> impl In
);
metric(
&mut out,
"xexeu_kev_findings",
"harpia_kev_findings",
"gauge",
"Findings listed in CISA KEV.",
&[(String::new(), kev as f64)],
@@ -234,14 +234,14 @@ pub(crate) async fn metrics_handler(State(state): State<ServerState>) -> impl In
};
metric(
&mut out,
"xexeu_vuln_db_cves",
"harpia_vuln_db_cves",
"gauge",
"CVEs in the local database.",
&[(String::new(), cves as f64)],
);
metric(
&mut out,
"xexeu_vuln_db_kev",
"harpia_vuln_db_kev",
"gauge",
"KEV entries in the local database.",
&[(String::new(), kev_entries as f64)],
@@ -249,7 +249,7 @@ pub(crate) async fn metrics_handler(State(state): State<ServerState>) -> impl In
if let Some(last_sync) = *state.feeds_last_sync.read().await {
metric(
&mut out,
"xexeu_feeds_last_sync_timestamp_seconds",
"harpia_feeds_last_sync_timestamp_seconds",
"gauge",
"Unix time of the last successful feed sync.",
&[(String::new(), last_sync.timestamp() as f64)],
@@ -266,28 +266,28 @@ pub(crate) async fn metrics_handler(State(state): State<ServerState>) -> impl In
if !sweeps.is_empty() {
metric(
&mut out,
"xexeu_last_sweep_timestamp_seconds",
"harpia_last_sweep_timestamp_seconds",
"gauge",
"Unix time the group's last ingested sweep finished.",
&per_group(&|stat| stat.finished_at.timestamp() as f64),
);
metric(
&mut out,
"xexeu_last_sweep_duration_seconds",
"harpia_last_sweep_duration_seconds",
"gauge",
"Duration of the group's last ingested sweep.",
&per_group(&|stat| stat.duration_secs),
);
metric(
&mut out,
"xexeu_last_sweep_complete",
"harpia_last_sweep_complete",
"gauge",
"1 if the group's last sweep covered every target.",
&per_group(&|stat| f64::from(u8::from(stat.complete))),
);
metric(
&mut out,
"xexeu_last_sweep_events",
"harpia_last_sweep_events",
"gauge",
"Surface changes found by the group's last sweep.",
&per_group(&|stat| stat.events as f64),
@@ -297,7 +297,7 @@ pub(crate) async fn metrics_handler(State(state): State<ServerState>) -> impl In
metric(
&mut out,
"xexeu_webhook_deliveries_total",
"harpia_webhook_deliveries_total",
"counter",
"Webhook deliveries by result.",
&[
@@ -1,4 +1,4 @@
//! `xexeu serve`: background batch ingestion, feed sync and the HTTP server.
//! `harpia serve`: background batch ingestion, feed sync and the HTTP server.
mod api;
mod assets;
@@ -23,13 +23,13 @@ use assets::{
use axum::Router;
use chrono::{DateTime, Utc};
use export::{export_changes_csv_handler, export_findings_csv_handler, export_hosts_csv_handler};
use harpia_core::batch::SweepBatch;
use harpia_core::config::HarpiaConfig;
use harpia_core::diff::{diff_batch, DiffOptions};
use harpia_core::storage::{SqliteStorage, Storage};
use harpia_core::vuln::{sync_feeds, SyncOptions, VulnDatabase};
use metrics::{metrics_handler, notify, Metrics};
use tokio::sync::{Mutex, RwLock};
use xexeu_core::batch::SweepBatch;
use xexeu_core::config::XexeuConfig;
use xexeu_core::diff::{diff_batch, DiffOptions};
use xexeu_core::storage::{SqliteStorage, Storage};
use xexeu_core::vuln::{sync_feeds, SyncOptions, VulnDatabase};
fn find_sweep_manifests(sweeps_dir: &Path) -> Vec<PathBuf> {
let mut manifests = Vec::new();
@@ -61,7 +61,7 @@ async fn poll_sweeps(
sweeps_dir: PathBuf,
storage: Arc<Mutex<SqliteStorage>>,
sweeps_ingested: Arc<AtomicUsize>,
config: Arc<RwLock<XexeuConfig>>,
config: Arc<RwLock<HarpiaConfig>>,
metrics: Arc<Metrics>,
) {
let client = reqwest::Client::new();
@@ -132,7 +132,7 @@ async fn poll_sweeps(
#[derive(Clone)]
pub(crate) struct ServerState {
config: Arc<RwLock<XexeuConfig>>,
config: Arc<RwLock<HarpiaConfig>>,
config_path: PathBuf,
storage: Arc<Mutex<SqliteStorage>>,
sweeps_ingested: Arc<AtomicUsize>,
@@ -166,13 +166,13 @@ pub(crate) async fn run_serve(
admin_token: Option<&str>,
) -> Result<(), String> {
let (config, _report) = validated_config(config_path)?;
// An empty XEXEU_ADMIN_TOKEN (compose's default) means "generate one".
// An empty HARPIA_ADMIN_TOKEN (compose's default) means "generate one".
let admin_token = admin_token.map(str::trim).filter(|token| !token.is_empty());
let (admin_token, token_generated) = match admin_token {
Some(token) if token.len() >= auth::MIN_TOKEN_LEN => (auth::AdminToken::new(token), false),
Some(_) => {
return Err(format!(
"XEXEU_ADMIN_TOKEN precisa ter pelo menos {} caracteres",
"HARPIA_ADMIN_TOKEN precisa ter pelo menos {} caracteres",
auth::MIN_TOKEN_LEN
))
}
@@ -187,7 +187,7 @@ pub(crate) async fn run_serve(
fs::create_dir_all(data_dir)
.map_err(|error| format!("falha ao criar {}: {error}", data_dir.display()))?;
let db_path = data_dir.join("xexeu.db");
let db_path = data_dir.join("harpia.db");
let storage = SqliteStorage::open(&db_path).map_err(|error| {
format!(
"falha ao abrir banco de dados em {}: {error}",
@@ -344,10 +344,10 @@ pub(crate) async fn run_serve(
.local_addr()
.map_err(|error| format!("falha ao obter endereço local: {error}"))?;
println!("Xexéu listening on http://{local_addr}");
println!("Harpia listening on http://{local_addr}");
if token_generated {
println!(
"Token de administração gerado nesta execução (defina XEXEU_ADMIN_TOKEN para fixá-lo): \
"Token de administração gerado nesta execução (defina HARPIA_ADMIN_TOKEN para fixá-lo): \
http://{local_addr}/?token={}",
admin_token.as_str()
);
@@ -86,7 +86,7 @@ fn ingested_sweep_triggers_signed_webhook_and_updates_metrics() {
.port();
let workspace = TempDir::new().expect("temporary directory");
let config_path = workspace.path().join("xexeu.toml");
let config_path = workspace.path().join("harpia.toml");
let sweeps_dir = workspace.path().join("sweeps");
let data_dir = workspace.path().join("data");
fs::write(
@@ -109,7 +109,7 @@ alvos = ["127.0.0.1/32"]
[[webhook]]
url = "http://127.0.0.1:{hook_port}/hook/secret-path"
eventos = ["porta_nova"]
segredo_env = "XEXEU_E2E_WEBHOOK_KEY"
segredo_env = "HARPIA_E2E_WEBHOOK_KEY"
[[webhook]]
url = "http://127.0.0.1:{dead_port}/down"
@@ -119,7 +119,7 @@ formato = "slack"
)
.expect("write configuration");
let mut child = Command::new(env!("CARGO_BIN_EXE_xexeu"))
let mut child = Command::new(env!("CARGO_BIN_EXE_harpia"))
.args([
"serve",
"--bind",
@@ -131,11 +131,11 @@ formato = "slack"
"--data-dir",
data_dir.to_str().expect("data dir"),
])
.env("XEXEU_E2E_WEBHOOK_KEY", WEBHOOK_KEY)
.env("HARPIA_E2E_WEBHOOK_KEY", WEBHOOK_KEY)
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()
.expect("spawn xexeu serve");
.expect("spawn harpia serve");
let mut reader = BufReader::new(child.stdout.take().expect("take stdout"));
let _guard = ChildGuard(child);
let mut addr = None;
@@ -159,7 +159,7 @@ formato = "slack"
);
assert!(!body.contains("secret-path"), "{body}");
let scan = Command::new(env!("CARGO_BIN_EXE_xexeu"))
let scan = Command::new(env!("CARGO_BIN_EXE_harpia"))
.args([
"scan",
"--group",
@@ -171,7 +171,7 @@ formato = "slack"
sweeps_dir.to_str().expect("sweeps path"),
])
.output()
.expect("run xexeu scan");
.expect("run harpia scan");
assert!(
scan.status.success(),
"{}",
@@ -189,9 +189,9 @@ formato = "slack"
events.iter().all(|event| event["tipo"] == "porta_nova"),
"only subscribed kinds are sent: {payload}"
);
let expected = xexeu_core::alert::sign(WEBHOOK_KEY.as_bytes(), &body);
let expected = harpia_core::alert::sign(WEBHOOK_KEY.as_bytes(), &body);
assert!(
headers.contains(&format!("x-xexeu-signature: {expected}")),
headers.contains(&format!("x-harpia-signature: {expected}")),
"signature header in: {headers}"
);
@@ -200,7 +200,7 @@ formato = "slack"
let metrics = loop {
let (status, body) = http_get(&addr, "/metrics");
assert_eq!(status, 200);
if body.contains("xexeu_webhook_deliveries_total{resultado=\"falha\"} 1")
if body.contains("harpia_webhook_deliveries_total{resultado=\"falha\"} 1")
|| Instant::now() > deadline
{
break body;
@@ -208,13 +208,13 @@ formato = "slack"
std::thread::sleep(Duration::from_millis(500));
};
for expected in [
"xexeu_sweeps_ingested_total 1",
"xexeu_assets{status=\"ativo\"} 1",
"xexeu_open_ports 1",
"xexeu_last_sweep_complete{grupo=\"local\"} 1",
"xexeu_webhook_deliveries_total{resultado=\"ok\"} 1",
"xexeu_webhook_deliveries_total{resultado=\"falha\"} 1",
"# TYPE xexeu_findings gauge",
"harpia_sweeps_ingested_total 1",
"harpia_assets{status=\"ativo\"} 1",
"harpia_open_ports 1",
"harpia_last_sweep_complete{grupo=\"local\"} 1",
"harpia_webhook_deliveries_total{resultado=\"ok\"} 1",
"harpia_webhook_deliveries_total{resultado=\"falha\"} 1",
"# TYPE harpia_findings gauge",
] {
assert!(
metrics.contains(expected),
@@ -63,7 +63,7 @@ fn http_request_with(
#[test]
fn config_crud_and_export_e2e() {
let workspace = TempDir::new().expect("temporary directory");
let config_path = workspace.path().join("xexeu.toml");
let config_path = workspace.path().join("harpia.toml");
let sweeps_dir = workspace.path().join("sweeps");
let data_dir = workspace.path().join("data");
@@ -88,8 +88,8 @@ alvos = ["127.0.0.1/32"]
)
.expect("write configuration");
// 1. Spawn `xexeu serve --bind 127.0.0.1:0`.
let mut child = Command::new(env!("CARGO_BIN_EXE_xexeu"))
// 1. Spawn `harpia serve --bind 127.0.0.1:0`.
let mut child = Command::new(env!("CARGO_BIN_EXE_harpia"))
.args([
"serve",
"--bind",
@@ -101,11 +101,11 @@ alvos = ["127.0.0.1/32"]
"--data-dir",
data_dir.to_str().expect("data dir"),
])
.env("XEXEU_ADMIN_TOKEN", ADMIN_TOKEN)
.env("HARPIA_ADMIN_TOKEN", ADMIN_TOKEN)
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()
.expect("spawn xexeu serve");
.expect("spawn harpia serve");
let stdout = child.stdout.take().expect("take stdout");
let mut reader = BufReader::new(stdout);
@@ -154,7 +154,7 @@ alvos = ["127.0.0.1/32"]
&cross_site,
);
assert_eq!(code, 403);
let same_site = format!("X-Xexeu-Token: {ADMIN_TOKEN}\r\nOrigin: http://{addr}\r\n");
let same_site = format!("X-Harpia-Token: {ADMIN_TOKEN}\r\nOrigin: http://{addr}\r\n");
let (code, _, _) = http_request_with(
&addr,
"POST",
@@ -240,14 +240,14 @@ alvos = ["127.0.0.1/32"]
let (code, headers, body) = http_request(&addr, "GET", "/api/export/hosts.csv", None);
assert_eq!(code, 200);
assert!(headers.contains("content-type: text/csv; charset=utf-8"));
assert!(headers.contains("content-disposition: attachment; filename=\"xexeu-hosts-"));
assert!(headers.contains("content-disposition: attachment; filename=\"harpia-hosts-"));
assert!(body.starts_with("Endereço IP,Grupo,Status do Host,Protocolo,Porta,Status da Porta,Produto,Versão,CPE,Maior CVSS,Quantidade de Achados"));
// Findings CSV
let (code, headers, body) = http_request(&addr, "GET", "/api/export/findings.csv", None);
assert_eq!(code, 200);
assert!(headers.contains("content-type: text/csv; charset=utf-8"));
assert!(headers.contains("content-disposition: attachment; filename=\"xexeu-findings-"));
assert!(headers.contains("content-disposition: attachment; filename=\"harpia-findings-"));
assert!(body.starts_with("Endereço IP,Porta,CVE / ID,CVSS,No KEV,Confiança,Título,Descrição"));
// Changes CSV
@@ -255,14 +255,14 @@ alvos = ["127.0.0.1/32"]
http_request(&addr, "GET", "/api/export/changes.csv?since=24h", None);
assert_eq!(code, 200);
assert!(headers.contains("content-type: text/csv; charset=utf-8"));
assert!(headers.contains("content-disposition: attachment; filename=\"xexeu-changes-"));
assert!(headers.contains("content-disposition: attachment; filename=\"harpia-changes-"));
assert!(body.starts_with("Data/Hora (UTC),Tipo de Evento,Alvo / Host,Grupo,Detalhe"));
// Executive Report HTML
let (code, headers, body) = http_request(&addr, "GET", "/relatorio", None);
assert_eq!(code, 200);
assert!(headers.contains("content-type: text/html; charset=utf-8"));
assert!(body.contains("Relatório Executivo de Segurança — Xexéu"));
assert!(body.contains("Relatório Executivo de Segurança — Harpia"));
assert!(body.contains("Indicadores-Chave de Exposição (KPIs)"));
assert!(body.contains("Glossário e Metodologia de Avaliação"));
@@ -274,7 +274,7 @@ alvos = ["127.0.0.1/32"]
#[test]
fn scanner_hot_reload_on_config_file_change() {
let workspace = TempDir::new().expect("temporary directory");
let config_path = workspace.path().join("xexeu.toml");
let config_path = workspace.path().join("harpia.toml");
let sweeps_dir = workspace.path().join("sweeps");
let data_dir = workspace.path().join("data");
@@ -297,8 +297,8 @@ alvos = ["127.0.0.1/32"]
)
.expect("write initial configuration");
let mut child = Command::new(env!("CARGO_BIN_EXE_xexeu"))
.env("XEXEU_SCANNER_TICK_SECS", "1")
let mut child = Command::new(env!("CARGO_BIN_EXE_harpia"))
.env("HARPIA_SCANNER_TICK_SECS", "1")
.args([
"scanner",
"--config",
@@ -311,7 +311,7 @@ alvos = ["127.0.0.1/32"]
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()
.expect("spawn xexeu scanner");
.expect("spawn harpia scanner");
let stdout = child.stdout.take().expect("take stdout");
let mut reader = BufReader::new(stdout);
@@ -1,15 +1,15 @@
use chrono::Utc;
use harpia_core::diff::{AssetState, AssetStatus, DiffResult, PortStatus, ServiceState};
use harpia_core::storage::{SqliteStorage, Storage};
use harpia_core::vuln::matcher::{Confidence, Finding, FindingType};
use std::fs;
use std::process::Command;
use tempfile::TempDir;
use xexeu_core::diff::{AssetState, AssetStatus, DiffResult, PortStatus, ServiceState};
use xexeu_core::storage::{SqliteStorage, Storage};
use xexeu_core::vuln::matcher::{Confidence, Finding, FindingType};
#[test]
fn doctor_command_json_and_table_and_invalid_config() {
let workspace = TempDir::new().expect("temporary directory");
let valid_config = workspace.path().join("xexeu.toml");
let valid_config = workspace.path().join("harpia.toml");
let invalid_config = workspace.path().join("invalid.toml");
let data_dir = workspace.path().join("data");
@@ -34,7 +34,7 @@ alvos = ["10.0.0.1"]
fs::write(&invalid_config, "invalid toml content !!").expect("write invalid config");
// 1. Valid doctor in table mode
let output = Command::new(env!("CARGO_BIN_EXE_xexeu"))
let output = Command::new(env!("CARGO_BIN_EXE_harpia"))
.args([
"doctor",
"--config",
@@ -43,7 +43,7 @@ alvos = ["10.0.0.1"]
data_dir.to_str().unwrap(),
])
.output()
.expect("run xexeu doctor");
.expect("run harpia doctor");
assert!(
output.status.success(),
@@ -51,14 +51,14 @@ alvos = ["10.0.0.1"]
String::from_utf8_lossy(&output.stderr)
);
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(stdout.contains("Xexéu v"));
assert!(stdout.contains("Harpia v"));
assert!(stdout.contains("versao"));
assert!(stdout.contains("config"));
assert!(stdout.contains("sqlite"));
assert!(stdout.contains("Resultado: OK"));
// 2. Valid doctor in JSON mode
let output_json = Command::new(env!("CARGO_BIN_EXE_xexeu"))
let output_json = Command::new(env!("CARGO_BIN_EXE_harpia"))
.args([
"doctor",
"--json",
@@ -68,7 +68,7 @@ alvos = ["10.0.0.1"]
data_dir.to_str().unwrap(),
])
.output()
.expect("run xexeu doctor --json");
.expect("run harpia doctor --json");
assert!(output_json.status.success());
let parsed: serde_json::Value =
@@ -84,7 +84,7 @@ alvos = ["10.0.0.1"]
.any(|c| c["name"] == "sqlite" && c["status"] == "ok"));
// 3. Invalid doctor mode exits with error code 1
let output_invalid = Command::new(env!("CARGO_BIN_EXE_xexeu"))
let output_invalid = Command::new(env!("CARGO_BIN_EXE_harpia"))
.args([
"doctor",
"--config",
@@ -93,7 +93,7 @@ alvos = ["10.0.0.1"]
data_dir.to_str().unwrap(),
])
.output()
.expect("run xexeu doctor with invalid config");
.expect("run harpia doctor with invalid config");
assert!(!output_invalid.status.success());
let stdout_invalid = String::from_utf8_lossy(&output_invalid.stdout);
@@ -106,7 +106,7 @@ fn export_command_json_and_csv_with_fixture() {
let data_dir = workspace.path().join("data");
fs::create_dir_all(&data_dir).expect("create data dir");
let db_path = data_dir.join("xexeu.db");
let db_path = data_dir.join("harpia.db");
let mut storage = SqliteStorage::open(&db_path).expect("open sqlite storage");
let now = Utc::now();
@@ -150,7 +150,7 @@ fn export_command_json_and_csv_with_fixture() {
.expect("apply fixture state to database");
// 1. Export JSON to stdout
let output_json = Command::new(env!("CARGO_BIN_EXE_xexeu"))
let output_json = Command::new(env!("CARGO_BIN_EXE_harpia"))
.args([
"export",
"--format",
@@ -159,7 +159,7 @@ fn export_command_json_and_csv_with_fixture() {
data_dir.to_str().unwrap(),
])
.output()
.expect("run xexeu export --format json");
.expect("run harpia export --format json");
assert!(
output_json.status.success(),
@@ -179,7 +179,7 @@ fn export_command_json_and_csv_with_fixture() {
// 2. Export CSV to file with --out
let out_csv_file = workspace.path().join("export.csv");
let output_csv = Command::new(env!("CARGO_BIN_EXE_xexeu"))
let output_csv = Command::new(env!("CARGO_BIN_EXE_harpia"))
.args([
"export",
"--format",
@@ -190,7 +190,7 @@ fn export_command_json_and_csv_with_fixture() {
out_csv_file.to_str().unwrap(),
])
.output()
.expect("run xexeu export --format csv --out ...");
.expect("run harpia export --format csv --out ...");
assert!(output_csv.status.success());
let csv_content = fs::read_to_string(&out_csv_file).expect("read exported csv");
@@ -118,7 +118,7 @@ fn feeds_import_command_and_serve_loads_database() {
let workspace = TempDir::new().expect("temporary directory");
let feeds_dir = workspace.path().join("feeds_in");
let data_dir = workspace.path().join("data");
let config_path = workspace.path().join("xexeu.toml");
let config_path = workspace.path().join("harpia.toml");
let sweeps_dir = workspace.path().join("sweeps");
fs::create_dir_all(&feeds_dir).expect("create feeds dir");
@@ -167,8 +167,8 @@ alvos = ["127.0.0.1/32"]
)
.expect("write config");
// 1. Run `xexeu feeds import <feeds_dir> --data-dir <data_dir>`
let import_output = Command::new(env!("CARGO_BIN_EXE_xexeu"))
// 1. Run `harpia feeds import <feeds_dir> --data-dir <data_dir>`
let import_output = Command::new(env!("CARGO_BIN_EXE_harpia"))
.args([
"feeds",
"import",
@@ -192,8 +192,8 @@ alvos = ["127.0.0.1/32"]
let db_path = data_dir.join("vuln_db.json");
assert!(db_path.exists(), "vuln_db.json must exist");
// 2. Start `xexeu serve` and ensure /api/status displays the imported database
let mut child = Command::new(env!("CARGO_BIN_EXE_xexeu"))
// 2. Start `harpia serve` and ensure /api/status displays the imported database
let mut child = Command::new(env!("CARGO_BIN_EXE_harpia"))
.args([
"serve",
"--bind",
@@ -208,7 +208,7 @@ alvos = ["127.0.0.1/32"]
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()
.expect("spawn xexeu serve");
.expect("spawn harpia serve");
let stdout_pipe = child.stdout.take().expect("take stdout");
let mut reader = BufReader::new(stdout_pipe);
@@ -251,7 +251,7 @@ fn feeds_sync_mock_http_and_periodic_serve_timer() {
let workspace = TempDir::new().expect("temporary directory");
let data_dir = workspace.path().join("data");
let sweeps_dir = workspace.path().join("sweeps");
let config_path = workspace.path().join("xexeu.toml");
let config_path = workspace.path().join("harpia.toml");
fs::write(
&config_path,
@@ -277,8 +277,8 @@ alvos = ["127.0.0.1/32"]
)
.expect("write config");
// 1. Run `xexeu feeds sync` using mock endpoints
let sync_output = Command::new(env!("CARGO_BIN_EXE_xexeu"))
// 1. Run `harpia feeds sync` using mock endpoints
let sync_output = Command::new(env!("CARGO_BIN_EXE_harpia"))
.args([
"feeds",
"sync",
@@ -287,8 +287,8 @@ alvos = ["127.0.0.1/32"]
"--config",
config_path.to_str().expect("config path"),
])
.env("XEXEU_NVD_URL", format!("http://{mock_addr}/cves"))
.env("XEXEU_KEV_URL", format!("http://{mock_addr}/kev"))
.env("HARPIA_NVD_URL", format!("http://{mock_addr}/cves"))
.env("HARPIA_KEV_URL", format!("http://{mock_addr}/kev"))
.output()
.expect("run feeds sync");
@@ -303,8 +303,8 @@ alvos = ["127.0.0.1/32"]
"stdout: {stdout}"
);
// 2. Start `xexeu serve` with auto-sync enabled
let mut child = Command::new(env!("CARGO_BIN_EXE_xexeu"))
// 2. Start `harpia serve` with auto-sync enabled
let mut child = Command::new(env!("CARGO_BIN_EXE_harpia"))
.args([
"serve",
"--bind",
@@ -316,12 +316,12 @@ alvos = ["127.0.0.1/32"]
"--data-dir",
data_dir.to_str().expect("data dir"),
])
.env("XEXEU_NVD_URL", format!("http://{mock_addr}/cves"))
.env("XEXEU_KEV_URL", format!("http://{mock_addr}/kev"))
.env("HARPIA_NVD_URL", format!("http://{mock_addr}/cves"))
.env("HARPIA_KEV_URL", format!("http://{mock_addr}/kev"))
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()
.expect("spawn xexeu serve");
.expect("spawn harpia serve");
let stdout_pipe = child.stdout.take().expect("take stdout");
let mut reader = BufReader::new(stdout_pipe);
@@ -368,7 +368,7 @@ fn feeds_sync_network_failure_does_not_corrupt_existing_database_and_server_stay
let workspace = TempDir::new().expect("temporary directory");
let data_dir = workspace.path().join("data");
let sweeps_dir = workspace.path().join("sweeps");
let config_path = workspace.path().join("xexeu.toml");
let config_path = workspace.path().join("harpia.toml");
fs::create_dir_all(&data_dir).expect("create data dir");
// Pre-populate with initial database
@@ -414,8 +414,8 @@ alvos = ["127.0.0.1/32"]
)
.expect("write config");
// 1. Run `xexeu feeds sync` pointing to an unreachable port (e.g. 127.0.0.1:1)
let sync_output = Command::new(env!("CARGO_BIN_EXE_xexeu"))
// 1. Run `harpia feeds sync` pointing to an unreachable port (e.g. 127.0.0.1:1)
let sync_output = Command::new(env!("CARGO_BIN_EXE_harpia"))
.args([
"feeds",
"sync",
@@ -424,8 +424,8 @@ alvos = ["127.0.0.1/32"]
"--config",
config_path.to_str().expect("config path"),
])
.env("XEXEU_NVD_URL", "http://127.0.0.1:1/nonexistent")
.env("XEXEU_KEV_URL", "http://127.0.0.1:1/nonexistent")
.env("HARPIA_NVD_URL", "http://127.0.0.1:1/nonexistent")
.env("HARPIA_KEV_URL", "http://127.0.0.1:1/nonexistent")
.output()
.expect("run feeds sync");
@@ -442,8 +442,8 @@ alvos = ["127.0.0.1/32"]
"original db must remain intact"
);
// 2. Start `xexeu serve` pointing to unreachable port for auto_sync
let mut child = Command::new(env!("CARGO_BIN_EXE_xexeu"))
// 2. Start `harpia serve` pointing to unreachable port for auto_sync
let mut child = Command::new(env!("CARGO_BIN_EXE_harpia"))
.args([
"serve",
"--bind",
@@ -455,12 +455,12 @@ alvos = ["127.0.0.1/32"]
"--data-dir",
data_dir.to_str().expect("data dir"),
])
.env("XEXEU_NVD_URL", "http://127.0.0.1:1/nonexistent")
.env("XEXEU_KEV_URL", "http://127.0.0.1:1/nonexistent")
.env("HARPIA_NVD_URL", "http://127.0.0.1:1/nonexistent")
.env("HARPIA_KEV_URL", "http://127.0.0.1:1/nonexistent")
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()
.expect("spawn xexeu serve");
.expect("spawn harpia serve");
let stdout_pipe = child.stdout.take().expect("take stdout");
let mut reader = BufReader::new(stdout_pipe);
@@ -4,9 +4,9 @@ use std::net::{TcpListener, TcpStream};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
use harpia_core::batch::SweepBatch;
use harpia_core::vuln::feeds::{Cpe, CpeMatchCriteria, CveRecord, VulnDatabase};
use tempfile::TempDir;
use xexeu_core::batch::SweepBatch;
use xexeu_core::vuln::feeds::{Cpe, CpeMatchCriteria, CveRecord, VulnDatabase};
struct ChildGuard(std::process::Child);
@@ -58,7 +58,7 @@ fn fingerprint_and_vuln_matching_e2e() {
// 2. Setup workspace, config, and fixture vuln_db.json
let workspace = TempDir::new().expect("temporary directory");
let config_path = workspace.path().join("xexeu.toml");
let config_path = workspace.path().join("harpia.toml");
let sweeps_dir = workspace.path().join("sweeps");
let data_dir = workspace.path().join("data");
fs::create_dir_all(&data_dir).expect("create data dir");
@@ -110,7 +110,7 @@ alvos = ["127.0.0.1/32"]
.expect("save fixture vuln_db.json");
// 3. Run scan --once with --data-dir pointing to our fixture database
let scan_output = Command::new(env!("CARGO_BIN_EXE_xexeu"))
let scan_output = Command::new(env!("CARGO_BIN_EXE_harpia"))
.args([
"scan",
"--group",
@@ -124,7 +124,7 @@ alvos = ["127.0.0.1/32"]
data_dir.to_str().expect("data dir"),
])
.output()
.expect("run xexeu scan");
.expect("run harpia scan");
assert!(
scan_output.status.success(),
@@ -163,7 +163,7 @@ alvos = ["127.0.0.1/32"]
assert_eq!(finding.cvss, Some(7.5));
// 5. Run serve and verify /api/hosts
let mut child = Command::new(env!("CARGO_BIN_EXE_xexeu"))
let mut child = Command::new(env!("CARGO_BIN_EXE_harpia"))
.args([
"serve",
"--bind",
@@ -178,7 +178,7 @@ alvos = ["127.0.0.1/32"]
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()
.expect("spawn xexeu serve");
.expect("spawn harpia serve");
let stdout = child.stdout.take().expect("take stdout");
let mut reader = BufReader::new(stdout);
@@ -2,8 +2,8 @@ use std::fs;
use std::net::TcpListener;
use std::process::Command;
use harpia_core::batch::{SweepBatch, SweepStatus};
use tempfile::TempDir;
use xexeu_core::batch::{SweepBatch, SweepStatus};
#[test]
fn scan_once_writes_a_complete_batch_with_the_open_port() {
@@ -18,7 +18,7 @@ fn scan_once_writes_a_complete_batch_with_the_open_port() {
});
let workspace = TempDir::new().expect("temporary directory");
let config = workspace.path().join("xexeu.toml");
let config = workspace.path().join("harpia.toml");
fs::write(
&config,
format!(
@@ -43,7 +43,7 @@ alvos = ["127.0.0.1/32"]
.expect("write configuration");
let sweeps = workspace.path().join("sweeps");
let output = Command::new(env!("CARGO_BIN_EXE_xexeu"))
let output = Command::new(env!("CARGO_BIN_EXE_harpia"))
.args([
"scan",
"--group",
@@ -55,7 +55,7 @@ alvos = ["127.0.0.1/32"]
sweeps.to_str().expect("sweeps path"),
])
.output()
.expect("run xexeu scan");
.expect("run harpia scan");
assert!(
output.status.success(),
@@ -50,7 +50,7 @@ fn serve_ingests_sweeps_and_responds_to_api_and_dashboard() {
// 2. Setup workspace with config, sweeps dir, and data dir.
let workspace = TempDir::new().expect("temporary directory");
let config_path = workspace.path().join("xexeu.toml");
let config_path = workspace.path().join("harpia.toml");
let sweeps_dir = workspace.path().join("sweeps");
let data_dir = workspace.path().join("data");
@@ -77,8 +77,8 @@ alvos = ["127.0.0.1/32"]
)
.expect("write configuration");
// 3. Spawn `xexeu serve --bind 127.0.0.1:0 ...`.
let mut child = Command::new(env!("CARGO_BIN_EXE_xexeu"))
// 3. Spawn `harpia serve --bind 127.0.0.1:0 ...`.
let mut child = Command::new(env!("CARGO_BIN_EXE_harpia"))
.args([
"serve",
"--bind",
@@ -93,7 +93,7 @@ alvos = ["127.0.0.1/32"]
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()
.expect("spawn xexeu serve");
.expect("spawn harpia serve");
let stdout = child.stdout.take().expect("take stdout");
let mut reader = BufReader::new(stdout);
@@ -134,7 +134,7 @@ alvos = ["127.0.0.1/32"]
assert!(body.contains(r#""status":"ok""#), "status body: {body}");
// 6. Run scan --once to produce a sweep batch into sweeps_dir
let scan_output = Command::new(env!("CARGO_BIN_EXE_xexeu"))
let scan_output = Command::new(env!("CARGO_BIN_EXE_harpia"))
.args([
"scan",
"--group",
@@ -146,7 +146,7 @@ alvos = ["127.0.0.1/32"]
sweeps_dir.to_str().expect("sweeps path"),
])
.output()
.expect("run xexeu scan");
.expect("run harpia scan");
assert!(
scan_output.status.success(),
"scan failed: {}",
@@ -192,12 +192,12 @@ alvos = ["127.0.0.1/32"]
// 10. Verify / and /dashboard return HTML, and static assets are served
let (status, body) = http_get(&server_addr, "/");
assert_eq!(status, 200);
assert!(body.contains("Xexéu"), "dashboard html: {body}");
assert!(body.contains("Harpia"), "dashboard html: {body}");
assert!(body.contains("app.css"), "dashboard html links css: {body}");
let (status, body) = http_get(&server_addr, "/dashboard");
assert_eq!(status, 200);
assert!(body.contains("Xexéu"), "dashboard html: {body}");
assert!(body.contains("Harpia"), "dashboard html: {body}");
let (status, body) = http_get(&server_addr, "/app.css");
assert_eq!(status, 200);
@@ -36,17 +36,17 @@ fn http_get(addr: &str, path: &str) -> (u16, String) {
#[test]
fn serve_validates_against_real_dvwa_scan_data() {
let validate_dir = Path::new("/tmp/xexeu-validate");
let validate_dir = Path::new("/tmp/harpia-validate");
if !validate_dir.exists() {
eprintln!("skip: /tmp/xexeu-validate does not exist");
eprintln!("skip: /tmp/harpia-validate does not exist");
return;
}
let config_path = validate_dir.join("xexeu.toml");
let config_path = validate_dir.join("harpia.toml");
let sweeps_dir = validate_dir.join("sweeps");
let data_dir = validate_dir.join("data");
let mut child = Command::new(env!("CARGO_BIN_EXE_xexeu"))
let mut child = Command::new(env!("CARGO_BIN_EXE_harpia"))
.args([
"serve",
"--bind",
@@ -61,7 +61,7 @@ fn serve_validates_against_real_dvwa_scan_data() {
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()
.expect("spawn xexeu serve");
.expect("spawn harpia serve");
let stdout = child.stdout.take().expect("take stdout");
let mut reader = BufReader::new(stdout);
@@ -106,7 +106,7 @@ fn serve_validates_against_real_dvwa_scan_data() {
// Check dashboard and static assets
let (status, body) = http_get(&server_addr, "/");
assert_eq!(status, 200);
assert!(body.contains("Xexéu"));
assert!(body.contains("Harpia"));
let (status, body) = http_get(&server_addr, "/app.css");
assert_eq!(status, 200);
@@ -1,6 +1,6 @@
[package]
name = "xexeu-core"
description = "Xexéu: continuous attack-surface and vulnerability auditing core"
name = "harpia-core"
description = "Harpia: continuous attack-surface and vulnerability auditing core"
version.workspace = true
edition.workspace = true
license.workspace = true
@@ -1,9 +1,9 @@
//! Webhook alerts for surface changes.
//!
//! After a sweep is ingested, each `[[webhook]]` gets one POST with the events
//! it subscribed to. The body is Xexéu's JSON, or a short text for Slack and
//! it subscribed to. The body is Harpia's JSON, or a short text for Slack and
//! Discord. With `segredo_env`, the body is signed with HMAC-SHA256 in
//! `X-Xexeu-Signature: sha256=<hex>`, so the receiver can reject forgeries.
//! `X-Harpia-Signature: sha256=<hex>`, so the receiver can reject forgeries.
//!
//! Delivery never blocks ingestion and never fails it: errors are retried a
//! few times and then reported to the caller to log and count.
@@ -19,7 +19,7 @@ use crate::config::{WebhookConfig, WebhookFormat};
use crate::diff::Event;
/// Signature header, `sha256=<hex>` of the body.
pub const SIGNATURE_HEADER: &str = "X-Xexeu-Signature";
pub const SIGNATURE_HEADER: &str = "X-Harpia-Signature";
/// Attempts per delivery, including the first.
pub const MAX_ATTEMPTS: u32 = 3;
const REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
@@ -68,7 +68,7 @@ fn event_line(event: &Event) -> String {
fn chat_text(group: &str, events: &[&Event]) -> String {
let mut text = format!(
"Xexéu: {} mudança(s) na superfície do grupo {group}",
"Harpia: {} mudança(s) na superfície do grupo {group}",
events.len()
);
for event in events.iter().take(CHAT_LINES) {
@@ -85,7 +85,7 @@ fn chat_text(group: &str, events: &[&Event]) -> String {
pub fn render(format: WebhookFormat, group: &str, sweep_id: Ulid, events: &[&Event]) -> Value {
match format {
WebhookFormat::Json => json!({
"fonte": "xexeu",
"fonte": "harpia",
"versao": env!("CARGO_PKG_VERSION"),
"grupo": group,
"sweep_id": sweep_id,
@@ -136,7 +136,7 @@ pub async fn deliver(
.header(reqwest::header::CONTENT_TYPE, "application/json")
.header(
reqwest::header::USER_AGENT,
concat!("xexeu/", env!("CARGO_PKG_VERSION")),
concat!("harpia/", env!("CARGO_PKG_VERSION")),
)
.body(payload.clone());
if let Some(signature) = &signature {
@@ -231,7 +231,7 @@ mod tests {
assert!(discord["content"]
.as_str()
.unwrap()
.starts_with("Xexéu: 1 mudança(s)"));
.starts_with("Harpia: 1 mudança(s)"));
}
#[test]
@@ -123,7 +123,7 @@ pub struct SweepManifest {
/// Coverage status.
#[serde(rename = "status")]
pub status: SweepStatus,
/// Xexéu version that wrote the batch.
/// Harpia version that wrote the batch.
#[serde(rename = "versao")]
pub version: String,
/// SHA-256 of `observations.parquet`, filled by [`SweepBatch::write`].
@@ -250,10 +250,10 @@ impl SweepBatch {
let group = safe_component(&self.manifest.group)?;
let directory = root.join(group).join(self.manifest.sweep_id.to_string());
fs::create_dir_all(&directory)?;
// `scanner` and `xexeu` run as different, unrelated Linux users (the
// `scanner` and `harpia` run as different, unrelated Linux users (the
// Compose hardening in docker.md has `scanner` as uid 0 restricted to
// NET_RAW, `xexeu` as uid 10001 with zero capabilities) sharing the
// `xexeu-sweeps` volume read-only from `xexeu`'s side. `mkdir`'s
// NET_RAW, `harpia` as uid 10001 with zero capabilities) sharing the
// `harpia-sweeps` volume read-only from `harpia`'s side. `mkdir`'s
// default mode is already group/other-readable under a standard
// umask, but it isn't guaranteed (an operator's umask could be 077),
// so set it explicitly rather than depend on an environment detail.
@@ -272,7 +272,7 @@ impl SweepBatch {
let content_hash = hash_file(temporary.path())?;
// `NamedTempFile` is created with mode 0600 (owner-only) by design —
// persisting it as-is would leave the batch unreadable by `xexeu`'s
// persisting it as-is would leave the batch unreadable by `harpia`'s
// uid once `scanner` (running as uid 0) owns it. Widen to 0644
// *before* the rename, matching the read-only mount's intent: any
// local reader, not just root, can read a sweep batch.
@@ -1,5 +1,5 @@
//! Linux capability detection, used to decide between the `nativo` (raw-socket)
//! and `nativo-sem-raw` (TCP connect) scan engines, and reported by `xexeu doctor`.
//! and `nativo-sem-raw` (TCP connect) scan engines, and reported by `harpia doctor`.
use std::fs;
@@ -9,7 +9,7 @@ const CAP_NET_RAW_BIT: u64 = 13;
/// Returns whether the current process has `CAP_NET_RAW` in its effective
/// capability set, by reading `CapEff` from `/proc/self/status`.
///
/// Only meaningful on Linux (the only platform Xexéu's containers run on). On
/// Only meaningful on Linux (the only platform Harpia's containers run on). On
/// any other OS, or if `/proc` is unavailable or unparsable, this returns
/// `false` — callers should treat that as "not verifiable, assume absent" and
/// fall back to the unprivileged engine rather than fail.
@@ -1,4 +1,4 @@
//! Parses and validates `xexeu.toml`: authorized scope, defaults, profiles and target groups.
//! Parses and validates `harpia.toml`: authorized scope, defaults, profiles and target groups.
use std::collections::{BTreeMap, BTreeSet};
@@ -16,7 +16,7 @@ const REFERENCE_INSTANT: i64 = 1_700_000_000;
/// Root configuration document.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct XexeuConfig {
pub struct HarpiaConfig {
/// Authorized scope shared by every group.
#[serde(rename = "escopo")]
pub scope: ScopeConfig,
@@ -38,7 +38,7 @@ pub struct XexeuConfig {
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum WebhookFormat {
/// Xexéu's own JSON: group, sweep and the full events.
/// Harpia's own JSON: group, sweep and the full events.
#[default]
Json,
/// Slack incoming webhook (`{"text": ...}`); also Mattermost and Rocket.Chat.
@@ -280,14 +280,14 @@ pub struct GroupConfig {
impl GroupConfig {
/// Cron expression that applies to this group.
pub fn effective_cron<'a>(&'a self, config: &'a XexeuConfig) -> &'a str {
pub fn effective_cron<'a>(&'a self, config: &'a HarpiaConfig) -> &'a str {
self.cron
.as_deref()
.unwrap_or(config.defaults.cron.as_str())
}
/// Profile that applies to this group.
pub fn effective_profile<'a>(&'a self, config: &'a XexeuConfig) -> &'a str {
pub fn effective_profile<'a>(&'a self, config: &'a HarpiaConfig) -> &'a str {
self.profile
.as_deref()
.or(config.defaults.profile.as_deref())
@@ -431,7 +431,7 @@ pub struct ConfigWarning {
pub message: String,
}
impl XexeuConfig {
impl HarpiaConfig {
/// Parses the TOML document without validating its semantics.
pub fn from_toml_str(raw: &str) -> Result<Self, ConfigError> {
toml::from_str(raw).map_err(|error| ConfigError::Toml {
@@ -661,7 +661,7 @@ fn default_true() -> bool {
mod tests {
use super::*;
const EXAMPLE: &str = include_str!("../../../examples/xexeu.toml");
const EXAMPLE: &str = include_str!("../../../examples/harpia.toml");
fn with_group(target: &str, extra: &str) -> String {
format!(
@@ -684,7 +684,7 @@ alvos = ["{target}"]
#[test]
fn example_configuration_is_valid() {
let (config, report) = XexeuConfig::load_validated(EXAMPLE).expect("example is valid");
let (config, report) = HarpiaConfig::load_validated(EXAMPLE).expect("example is valid");
assert_eq!(config.groups.len(), 4);
assert_eq!(report.groups.len(), 4);
@@ -730,7 +730,7 @@ nome = "teste"
alvos = ["10.0.0.0/24"]
"#;
assert!(matches!(
XexeuConfig::from_toml_str(raw),
HarpiaConfig::from_toml_str(raw),
Err(ConfigError::Toml { .. })
));
}
@@ -746,7 +746,7 @@ alvos = ["10.0.0.0/24"]
nome = "teste"
alvos = ["10.0.0.0/24"]
"#;
let config = XexeuConfig::from_toml_str(raw).expect("config parses");
let config = HarpiaConfig::from_toml_str(raw).expect("config parses");
assert!(matches!(
config.validate(),
Err(ConfigError::InvalidScope { .. })
@@ -756,7 +756,7 @@ alvos = ["10.0.0.0/24"]
#[test]
fn target_outside_scope_is_rejected() {
let raw = with_group("192.168.0.0/24", "");
let config = XexeuConfig::from_toml_str(&raw).expect("config parses");
let config = HarpiaConfig::from_toml_str(&raw).expect("config parses");
match config.validate() {
Err(ConfigError::TargetOutOfScope { group, target }) => {
@@ -770,7 +770,7 @@ alvos = ["10.0.0.0/24"]
#[test]
fn ipv6_target_wider_than_the_limit_is_rejected() {
let raw = with_group("2001:db8::/64", "");
let config = XexeuConfig::from_toml_str(&raw).expect("config parses");
let config = HarpiaConfig::from_toml_str(&raw).expect("config parses");
assert!(matches!(
config.validate(),
@@ -781,7 +781,7 @@ alvos = ["10.0.0.0/24"]
#[test]
fn invalid_cron_is_rejected() {
let raw = with_group("10.0.0.0/24", "cron = \"todo dia\"");
let config = XexeuConfig::from_toml_str(&raw).expect("config parses");
let config = HarpiaConfig::from_toml_str(&raw).expect("config parses");
assert!(matches!(
config.validate(),
@@ -792,7 +792,7 @@ alvos = ["10.0.0.0/24"]
#[test]
fn aggressive_cadence_only_warns() {
let raw = with_group("10.0.0.0/24", "cron = \"* * * * *\"");
let config = XexeuConfig::from_toml_str(&raw).expect("config parses");
let config = HarpiaConfig::from_toml_str(&raw).expect("config parses");
let report = config.validate().expect("aggressive cadence is allowed");
assert_eq!(report.warnings.len(), 1);
@@ -803,14 +803,14 @@ alvos = ["10.0.0.0/24"]
#[test]
fn five_minutes_is_not_aggressive() {
let raw = with_group("10.0.0.0/24", "cron = \"*/5 * * * *\"");
let (_, report) = XexeuConfig::load_validated(&raw).expect("config is valid");
let (_, report) = HarpiaConfig::load_validated(&raw).expect("config is valid");
assert!(report.warnings.is_empty());
}
#[test]
fn unknown_profile_is_rejected() {
let raw = with_group("10.0.0.0/24", "perfil = \"inexistente\"");
let config = XexeuConfig::from_toml_str(&raw).expect("config parses");
let config = HarpiaConfig::from_toml_str(&raw).expect("config parses");
assert!(matches!(
config.validate(),
@@ -834,7 +834,7 @@ alvos = ["10.0.0.0/24"]
nome = "repetido"
alvos = ["10.0.1.0/24"]
"#;
let config = XexeuConfig::from_toml_str(raw).expect("config parses");
let config = HarpiaConfig::from_toml_str(raw).expect("config parses");
assert!(matches!(
config.validate(),
Err(ConfigError::DuplicateGroup { .. })
@@ -853,7 +853,7 @@ autorizado = ["10.0.0.0/8"]
nome = "vazio"
alvos = []
"#;
let config = XexeuConfig::from_toml_str(raw).expect("config parses");
let config = HarpiaConfig::from_toml_str(raw).expect("config parses");
assert!(matches!(
config.validate(),
Err(ConfigError::EmptyTargets { .. })
@@ -868,14 +868,14 @@ autorizado = ["10.0.0.0/8"]
[perfis.padrao]
"#;
let config = XexeuConfig::from_toml_str(raw).expect("config parses");
let config = HarpiaConfig::from_toml_str(raw).expect("config parses");
assert!(matches!(config.validate(), Err(ConfigError::NoGroups)));
}
#[test]
fn dns_names_are_accepted_without_resolution() {
let raw = with_group("db01.interno.exemplo.org", "");
let (_, report) = XexeuConfig::load_validated(&raw).expect("config is valid");
let (_, report) = HarpiaConfig::load_validated(&raw).expect("config is valid");
assert_eq!(report.groups[0].addresses, 0);
assert_eq!(report.groups[0].names, 1);
@@ -893,7 +893,7 @@ autorizado = ["db01.interno.exemplo.org"]
nome = "teste"
alvos = ["10.0.0.0/24"]
"#;
let config = XexeuConfig::from_toml_str(raw).expect("config parses");
let config = HarpiaConfig::from_toml_str(raw).expect("config parses");
assert!(matches!(
config.validate(),
Err(ConfigError::InvalidScope { .. })
@@ -903,7 +903,7 @@ alvos = ["10.0.0.0/24"]
#[test]
fn group_inherits_defaults_and_overrides_them() {
let raw = with_group("10.0.0.0/24", "");
let (config, _) = XexeuConfig::load_validated(&raw).expect("config is valid");
let (config, _) = HarpiaConfig::load_validated(&raw).expect("config is valid");
let group = &config.groups[0];
assert_eq!(group.effective_cron(&config), "@daily");
@@ -913,7 +913,7 @@ alvos = ["10.0.0.0/24"]
#[test]
fn exclusion_inside_scope_is_valid() {
let raw = with_group("10.0.0.0/24", "excluir = [\"10.0.0.128/25\"]");
let (_, report) = XexeuConfig::load_validated(&raw).expect("config is valid");
let (_, report) = HarpiaConfig::load_validated(&raw).expect("config is valid");
assert_eq!(report.groups[0].addresses, 128);
}
@@ -944,20 +944,20 @@ excluir = ["10.0.1.1"]
cron = "0 2 * * *"
criticidade = "alta"
"#;
let (config, _) = XexeuConfig::load_validated(raw).expect("config parses and validates");
let (config, _) = HarpiaConfig::load_validated(raw).expect("config parses and validates");
let toml_str = config.to_toml_string().expect("serializes to toml");
let (reloaded, _) =
XexeuConfig::load_validated(&toml_str).expect("reloaded config is valid");
HarpiaConfig::load_validated(&toml_str).expect("reloaded config is valid");
assert_eq!(config, reloaded);
let temp_dir = tempfile::tempdir().expect("tempdir");
let file_path = temp_dir.path().join("xexeu.toml");
let file_path = temp_dir.path().join("harpia.toml");
config
.save_to_file(&file_path)
.expect("save_to_file succeeds");
let file_content = std::fs::read_to_string(&file_path).expect("read file");
let (from_disk, _) =
XexeuConfig::load_validated(&file_content).expect("from disk validates");
HarpiaConfig::load_validated(&file_content).expect("from disk validates");
assert_eq!(config, from_disk);
}
@@ -973,7 +973,7 @@ alvos = ["10.0.0.0/28"]
"#;
fn with_webhook(webhook: &str) -> Result<ValidationReport, ConfigError> {
XexeuConfig::from_toml_str(&format!("{WEBHOOK_BASE}\n[[webhook]]\n{webhook}"))?.validate()
HarpiaConfig::from_toml_str(&format!("{WEBHOOK_BASE}\n[[webhook]]\n{webhook}"))?.validate()
}
#[test]
@@ -984,7 +984,7 @@ alvos = ["10.0.0.0/28"]
formato = "discord"
eventos = ["porta_nova", "host_sumiu"]
grupos = ["dmz"]
segredo_env = "XEXEU_WEBHOOK_KEY""#
segredo_env = "HARPIA_WEBHOOK_KEY""#
)
.is_ok());
for bad in [
@@ -1017,7 +1017,7 @@ formato = "teams""#
#[test]
fn redacted_config_hides_webhook_paths_and_credentials() {
let config = XexeuConfig::from_toml_str(&format!(
let config = HarpiaConfig::from_toml_str(&format!(
"{WEBHOOK_BASE}\n[[webhook]]\nurl = \"https://user:pw@hooks.slack.example/services/T0/B0/secret?x=1\"\n"
))
.unwrap();
File renamed without changes.
@@ -1,7 +1,7 @@
//! Environment checks: effective capabilities, configuration validity, SQLite access,
//! vulnerability database status, and feed synchronization age.
use crate::config::XexeuConfig;
use crate::config::HarpiaConfig;
use crate::storage::SqliteStorage;
use crate::vuln::VulnDatabase;
use serde::{Deserialize, Serialize};
@@ -58,7 +58,7 @@ impl DoctorReport {
pub fn render_table(&self) -> String {
let mut out = String::new();
out.push_str(&format!(
"Xexéu v{} - Diagnóstico do Ambiente\n",
"Harpia v{} - Diagnóstico do Ambiente\n",
self.version
));
out.push_str(
@@ -176,7 +176,7 @@ pub fn run(config_path: &Path, data_dir: &Path) -> DoctorReport {
name: "versao".to_string(),
status: CheckStatus::Ok,
critical: false,
detail: format!("xexeu v{version}"),
detail: format!("harpia v{version}"),
});
// 2. Configuration file check
@@ -192,7 +192,7 @@ pub fn run(config_path: &Path, data_dir: &Path) -> DoctorReport {
});
} else {
match fs::read_to_string(config_path) {
Ok(raw) => match XexeuConfig::load_validated(&raw) {
Ok(raw) => match HarpiaConfig::load_validated(&raw) {
Ok((cfg, _report)) => {
checks.push(DoctorCheck {
name: "config".to_string(),
@@ -235,7 +235,7 @@ pub fn run(config_path: &Path, data_dir: &Path) -> DoctorReport {
checks.push(check_net_raw_simulated(status_str.as_deref(), is_root));
// 4. Local SQLite storage check
let db_path = data_dir.join("xexeu.db");
let db_path = data_dir.join("harpia.db");
if let Some(parent) = db_path.parent() {
let _ = fs::create_dir_all(parent);
}
@@ -271,7 +271,7 @@ pub fn run(config_path: &Path, data_dir: &Path) -> DoctorReport {
status: CheckStatus::Ausente,
critical: false,
detail: format!(
"base ausente em {} (execute 'xexeu feeds sync' ou 'import')",
"base ausente em {} (execute 'harpia feeds sync' ou 'import')",
vuln_db_path.display()
),
});
@@ -364,7 +364,7 @@ mod tests {
#[test]
fn test_cap_eff_parsing_and_net_raw_simulation() {
// Bit 13 set: 1 << 13 = 0x2000
let status_with_raw = "Name:\txexeu\nUid:\t0\t0\t0\t0\nCapEff:\t0000000000002000\n";
let status_with_raw = "Name:\tharpia\nUid:\t0\t0\t0\t0\nCapEff:\t0000000000002000\n";
assert_eq!(parse_cap_eff_from_status(status_with_raw), Some(0x2000));
assert_eq!(parse_euid_from_status(status_with_raw), Some(0));
assert!(has_net_raw_from_mask(0x2000));
@@ -376,7 +376,7 @@ mod tests {
// Bit 13 cleared
let status_no_raw =
"Name:\txexeu\nUid:\t1000\t1000\t1000\t1000\nCapEff:\t0000000000000000\n";
"Name:\tharpia\nUid:\t1000\t1000\t1000\t1000\nCapEff:\t0000000000000000\n";
assert_eq!(parse_cap_eff_from_status(status_no_raw), Some(0));
assert_eq!(parse_euid_from_status(status_no_raw), Some(1000));
assert!(!has_net_raw_from_mask(0));
@@ -452,7 +452,7 @@ alvos = ["10.0.0.1"]
#[test]
fn test_doctor_table_rendering() {
let dir = tempdir().expect("tempdir");
let config_path = dir.path().join("xexeu.toml");
let config_path = dir.path().join("harpia.toml");
let data_dir = dir.path().join("data");
fs::write(
@@ -475,7 +475,7 @@ alvos = ["192.168.1.1"]
let report = run(&config_path, &data_dir);
let table = report.render_table();
assert!(table.contains("Xexéu v"));
assert!(table.contains("Harpia v"));
assert!(table.contains("versao"));
assert!(table.contains("config"));
assert!(table.contains("sqlite"));
@@ -1,4 +1,4 @@
//! Xexéu core: configuration, scheduling, scanning, vulnerability correlation,
//! Harpia core: configuration, scheduling, scanning, vulnerability correlation,
//! storage and diffing for continuous attack-surface auditing.
pub mod alert;
@@ -1,11 +1,11 @@
//! Executive security report generation and A4 HTML rendering for Xexéu.
//! Executive security report generation and A4 HTML rendering for Harpia.
use std::net::IpAddr;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use crate::config::XexeuConfig;
use crate::config::HarpiaConfig;
use crate::diff::{AssetState, AssetStatus, CurrentState, PortStatus};
use crate::vuln::matcher::{Confidence, Finding};
use crate::vuln::VulnDatabase;
@@ -149,7 +149,7 @@ struct FindingRef<'a> {
impl ExecutiveReport {
/// Builds an executive report from the current state and vulnerability database.
pub fn build(
config: &XexeuConfig,
config: &HarpiaConfig,
current_state: &CurrentState,
vuln_db: &VulnDatabase,
feeds_last_sync: Option<DateTime<Utc>>,
@@ -233,7 +233,7 @@ impl ExecutiveReport {
.map(|c| format!("{c:.1}"))
.unwrap_or_else(|| "0.0".to_string());
let p1 = format!(
"Este relatório executivo consolida os resultados da auditoria contínua de superfície de ataque executada pelo motor Xexéu. No escopo autorizado composto por {groups_count} grupo(s) de varredura, foram identificados {active_hosts_count} host(s) ativo(s) e {open_ports_count} porta(s) com serviços expostos. A correlação determinística com feeds oficiais de vulnerabilidades (NVD) e catalogação CISA KEV identificou um total de {} achado(s) de segurança.",
"Este relatório executivo consolida os resultados da auditoria contínua de superfície de ataque executada pelo motor Harpia. No escopo autorizado composto por {groups_count} grupo(s) de varredura, foram identificados {active_hosts_count} host(s) ativo(s) e {open_ports_count} porta(s) com serviços expostos. A correlação determinística com feeds oficiais de vulnerabilidades (NVD) e catalogação CISA KEV identificou um total de {} achado(s) de segurança.",
all_findings.len()
);
@@ -481,7 +481,7 @@ impl ExecutiveReport {
GlossaryEntry {
term: "CPE (Common Platform Enumeration)".to_string(),
definition: "Esquema padronizado pelo NIST para descrição e nomenclatura uniforme de sistemas operacionais, pacotes e aplicações (ex: cpe:2.3:a:apache:http_server:2.4.52).".to_string(),
how_to_read: "O motor do Xexéu extrai banners de portas abertas e infere candidatos CPE determinísticos para busca e correlação na base NVD.".to_string(),
how_to_read: "O motor do Harpia extrai banners de portas abertas e infere candidatos CPE determinísticos para busca e correlação na base NVD.".to_string(),
},
GlossaryEntry {
term: "CVE (Common Vulnerabilities and Exposures)".to_string(),
@@ -516,7 +516,7 @@ impl ExecutiveReport {
};
ExecutiveReport {
title: "Relatório Executivo de Segurança — Xexéu".to_string(),
title: "Relatório Executivo de Segurança — Harpia".to_string(),
subtitle: format!(
"Auditoria contínua de superfície de ataque e catálogo de vulnerabilidades · Emitido em {}",
now.format("%d/%m/%Y às %H:%M UTC")
@@ -550,7 +550,7 @@ impl ExecutiveReport {
"<script src=\"/paged.polyfill.js\"></script>\n<script>window.Paged || document.write('<script src=\"https://unpkg.com/pagedjs/dist/paged.polyfill.js\"><\\/script>')</script>\n",
);
html.push_str("<style>\n");
html.push_str(&REPORT_CSS.replace("XEXEU_REPORT_TLP_MARKER", self.tlp.label()));
html.push_str(&REPORT_CSS.replace("HARPIA_REPORT_TLP_MARKER", self.tlp.label()));
html.push_str("</style>\n</head>\n<body>\n");
// 1. Cover Page
@@ -827,7 +827,7 @@ impl ExecutiveReport {
}
}
/// The Xexéu logo, embedded so the report renders identically whether it's
/// The Harpia logo, embedded so the report renders identically whether it's
/// viewed live from `/relatorio` or saved as a standalone offline HTML file
/// (same reasoning as `Sabiá/crates/sabia-core/src/report.rs`, which this
/// mirrors — a `src="/logo.png"` reference would 404 once the file is saved
@@ -920,7 +920,7 @@ body {
margin: 24mm 16mm 22mm 16mm;
background: #ffffff;
@top-left {
content: "Xexéu · Auditoria Contínua de Segurança";
content: "Harpia · Auditoria Contínua de Segurança";
font-family: var(--font-sans);
font-size: 7.5pt;
font-weight: 600;
@@ -929,7 +929,7 @@ body {
padding-bottom: 4mm;
}
@top-right {
content: "XEXEU_REPORT_TLP_MARKER · USO AUTORIZADO";
content: "HARPIA_REPORT_TLP_MARKER · USO AUTORIZADO";
font-family: var(--font-mono);
font-size: 7pt;
font-weight: 700;
@@ -1350,7 +1350,7 @@ h2::after {
#[cfg(test)]
mod tests {
use super::*;
use crate::config::XexeuConfig;
use crate::config::HarpiaConfig;
use crate::diff::{AssetState, AssetStatus, CurrentState, PortStatus, ServiceState};
use crate::vuln::matcher::{Confidence, Finding, FindingType};
use crate::vuln::VulnDatabase;
@@ -1371,7 +1371,7 @@ tcp = "80,443"
nome = "producao"
alvos = ["10.0.0.1/32"]
"#;
let (config, _) = XexeuConfig::load_validated(config_raw).expect("valid config");
let (config, _) = HarpiaConfig::load_validated(config_raw).expect("valid config");
let finding_low = Finding {
tipo: FindingType::Cve,
@@ -1478,7 +1478,7 @@ alvos = ["10.0.0.1/32"]
}
let html = report.render_html();
assert!(html.contains("Relatório Executivo de Segurança — Xexéu"));
assert!(html.contains("Relatório Executivo de Segurança — Harpia"));
assert!(html.contains("CVE-2024-CRIT"));
assert!(html.contains("Execução remota crítica"));
assert!(html.contains("paged.polyfill.js"));
@@ -135,7 +135,7 @@ async fn probe_tls(
let cert = captured_cert.lock().ok().and_then(|c| c.clone());
let req = format!(
"GET / HTTP/1.1\r\nHost: {}\r\nUser-Agent: xexeu-audit/0.1\r\nConnection: close\r\n\r\n",
"GET / HTTP/1.1\r\nHost: {}\r\nUser-Agent: harpia-audit/0.1\r\nConnection: close\r\n\r\n",
host_header
);
if tokio::time::timeout(timeout, tls_stream.write_all(req.as_bytes()))
@@ -167,7 +167,7 @@ async fn probe_http(
};
let req = format!(
"GET / HTTP/1.1\r\nHost: {}\r\nUser-Agent: xexeu-audit/0.1\r\nConnection: close\r\n\r\n",
"GET / HTTP/1.1\r\nHost: {}\r\nUser-Agent: harpia-audit/0.1\r\nConnection: close\r\n\r\n",
host_header
);
if tokio::time::timeout(timeout, stream.write_all(req.as_bytes()))
@@ -9,12 +9,12 @@
//! unprivileged user-space with zero capabilities. It uses standard TCP connect sockets for
//! both discovery and port scanning.
//! - `nmap`: Optional secondary mode leveraging an external `nmap` process inside the
//! specialized `xexeu-scanner-nmap` container variant.
//! specialized `harpia-scanner-nmap` container variant.
//!
//! # Determinism Guarantee
//!
//! In contrast to traditional Nmap runs which often present flapping or non-reproducible
//! outputs under variable load, Xexéu enforces deterministic guarantees:
//! outputs under variable load, Harpia enforces deterministic guarantees:
//! - All host discovery and port scan results are strictly sorted (by IP address ascending,
//! and then by port number ascending) before returning.
//! - **Timeouts and network concurrency limits are the only sources of potential variation
File renamed without changes.
File renamed without changes.
@@ -314,14 +314,14 @@ fn local_source_ipv4(target: Ipv4Addr) -> Option<Ipv4Addr> {
/// port range. Deterministic within a run (every probe in a `scan_hosts_syn`
/// call shares it), which is what keeps response matching simple.
fn ephemeral_source_port() -> u16 {
// Derived from the process id so concurrent `xexeu` processes on the same
// Derived from the process id so concurrent `harpia` processes on the same
// host (unusual, but not forbidden) don't collide on the same source port.
let base = 49152u32;
let span = 65535u32 - base;
(base + (std::process::id() % span)) as u16
}
/// A pseudo-random-enough initial sequence number. Xexéu never completes the
/// A pseudo-random-enough initial sequence number. Harpia never completes the
/// handshake, so RFC 6528-grade unpredictability is not a security property
/// this needs — it only has to not collide suspiciously with other local
/// traffic, which a process-time-derived value achieves well enough.
@@ -6,7 +6,7 @@ use chrono::{DateTime, Duration, Utc};
use croner::Cron;
use thiserror::Error;
use crate::config::{GroupConfig, XexeuConfig};
use crate::config::{GroupConfig, HarpiaConfig};
/// Maximum number of jittered occurrences inspected before falling back to the raw cron slot.
const MAX_JITTER_ATTEMPTS: usize = 16;
@@ -200,7 +200,7 @@ pub fn next_run_at(
/// Upcoming execution for every configured group, in configuration order.
pub fn next_runs(
config: &XexeuConfig,
config: &HarpiaConfig,
now: DateTime<Utc>,
) -> Result<Vec<GroupSchedule>, ScheduleError> {
let jitter = Jitter::parse(&config.defaults.jitter)?;
@@ -224,7 +224,7 @@ pub fn next_runs(
/// A group without history is due immediately.
pub fn should_run_now(
group: &GroupConfig,
config: &XexeuConfig,
config: &HarpiaConfig,
now: DateTime<Utc>,
history: &RunHistory,
) -> Result<RunDecision, ScheduleError> {
@@ -294,7 +294,7 @@ mod tests {
.expect("valid test instant")
}
fn group_config() -> XexeuConfig {
fn group_config() -> HarpiaConfig {
const RAW: &str = r#"
[escopo]
autorizado = ["10.0.0.0/8"]
@@ -308,7 +308,7 @@ cron = "*/5 * * * *"
nome = "nucleo"
alvos = ["10.0.1.0/24"]
"#;
XexeuConfig::from_toml_str(RAW).expect("test config parses")
HarpiaConfig::from_toml_str(RAW).expect("test config parses")
}
#[test]
@@ -427,7 +427,7 @@ nome = "nucleo"
alvos = ["10.0.1.0/24"]
cron = "0 3 * * *"
"#;
let config = XexeuConfig::from_toml_str(RAW).expect("test config parses");
let config = HarpiaConfig::from_toml_str(RAW).expect("test config parses");
let now = at(2026, 5, 1, 12, 0);
let schedules = next_runs(&config, now).expect("schedules compute");
File renamed without changes.
@@ -9,7 +9,7 @@ use chrono::{DateTime, Utc};
use ipnet::IpNet;
use thiserror::Error;
use crate::config::{GroupConfig, XexeuConfig};
use crate::config::{GroupConfig, HarpiaConfig};
use crate::schedule::{self, CronSpec, Jitter, ScheduleError};
/// Largest IPv6 prefix accepted for a target; anything wider must list addresses explicitly.
@@ -535,7 +535,7 @@ pub struct HostCadence {
///
/// The most frequent group wins; ties go to the earliest run and then to the group name.
pub fn effective_cadence(
config: &XexeuConfig,
config: &HarpiaConfig,
address: IpAddr,
now: DateTime<Utc>,
) -> Result<Option<HostCadence>, CadenceError> {
@@ -834,7 +834,7 @@ nome = "nucleo"
alvos = ["10.0.1.0/24"]
cron = "*/5 * * * *"
"#;
let config = XexeuConfig::from_toml_str(RAW).expect("test config parses");
let config = HarpiaConfig::from_toml_str(RAW).expect("test config parses");
let now = chrono::TimeZone::with_ymd_and_hms(&Utc, 2026, 5, 1, 12, 3, 0)
.single()
.expect("valid instant");
File renamed without changes.
@@ -333,7 +333,7 @@ pub async fn probe_unencrypted_admin_service(
};
let req = format!(
"GET / HTTP/1.1\r\nHost: {}\r\nUser-Agent: xexeu-audit/0.1\r\nConnection: close\r\n\r\n",
"GET / HTTP/1.1\r\nHost: {}\r\nUser-Agent: harpia-audit/0.1\r\nConnection: close\r\n\r\n",
addr
);
@@ -507,9 +507,9 @@ pub struct SyncOptions {
impl Default for SyncOptions {
fn default() -> Self {
let nvd_url =
std::env::var("XEXEU_NVD_URL").unwrap_or_else(|_| NVD_CVE_API_URL.to_string());
std::env::var("HARPIA_NVD_URL").unwrap_or_else(|_| NVD_CVE_API_URL.to_string());
let kev_url =
std::env::var("XEXEU_KEV_URL").unwrap_or_else(|_| CISA_KEV_API_URL.to_string());
std::env::var("HARPIA_KEV_URL").unwrap_or_else(|_| CISA_KEV_API_URL.to_string());
Self {
nvd_url,
kev_url,
@@ -523,7 +523,7 @@ impl Default for SyncOptions {
pub async fn sync_nvd(client: &reqwest::Client, url: &str) -> Result<NvdCatalog, FeedError> {
let resp = client
.get(url)
.header("User-Agent", "Xexeu-Vuln-Sync/0.1.0")
.header("User-Agent", "Harpia-Vuln-Sync/0.1.0")
.send()
.await
.map_err(|e| FeedError::Network {
@@ -550,7 +550,7 @@ pub async fn sync_nvd(client: &reqwest::Client, url: &str) -> Result<NvdCatalog,
pub async fn sync_kev(client: &reqwest::Client, url: &str) -> Result<KevCatalog, FeedError> {
let resp = client
.get(url)
.header("User-Agent", "Xexeu-Vuln-Sync/0.1.0")
.header("User-Agent", "Harpia-Vuln-Sync/0.1.0")
.send()
.await
.map_err(|e| FeedError::Network {
File renamed without changes.
File renamed without changes.
@@ -1,4 +1,4 @@
//! Parsers that read data Xexéu does not control (service banners, HTTP
//! Parsers that read data Harpia does not control (service banners, HTTP
//! responses, certificates, NVD/KEV feeds, operator-typed targets and cron
//! expressions) must reject bad input with an error, never panic.
//!
@@ -8,15 +8,15 @@
use std::io::Cursor;
use std::net::IpAddr;
use proptest::prelude::*;
use xexeu_core::scan::fingerprint::extract_server_header;
use xexeu_core::schedule::{CronSpec, Jitter};
use xexeu_core::targets::{
use harpia_core::scan::fingerprint::extract_server_header;
use harpia_core::schedule::{CronSpec, Jitter};
use harpia_core::targets::{
merge_ranges, parse_exclusion, parse_scope_entry, parse_target, IpRange,
};
use xexeu_core::vuln::checks::{evaluate_http_admin_response, parse_x509_der_not_after};
use xexeu_core::vuln::feeds::{parse_kev_reader, parse_nvd_json, Cpe};
use xexeu_core::vuln::matcher::parse_banner_to_cpe;
use harpia_core::vuln::checks::{evaluate_http_admin_response, parse_x509_der_not_after};
use harpia_core::vuln::feeds::{parse_kev_reader, parse_nvd_json, Cpe};
use harpia_core::vuln::matcher::parse_banner_to_cpe;
use proptest::prelude::*;
/// DER TLV with a definite length, short or long form.
fn tlv(tag: u8, body: &[u8]) -> Vec<u8> {
+20 -20
View File
@@ -1,15 +1,15 @@
# Xexéu: o scanner varre os alvos autorizados e grava lotes imutáveis;
# o xexeu ingere os lotes, calcula diffs e serve a API e o dashboard.
# Harpia: o scanner varre os alvos autorizados e grava lotes imutáveis;
# o harpia ingere os lotes, calcula diffs e serve a API e o dashboard.
#
# cp .env.example .env && cp examples/xexeu.toml config/xexeu.toml
# cp .env.example .env && cp examples/harpia.toml config/harpia.toml
# docker compose pull && docker compose up -d # operadores: imagem publicada
# docker compose up -d --build # desenvolvedores: build local
name: xexeu
name: harpia
services:
scanner:
image: ${XEXEU_IMAGE:-git.lucasrguerra.dev.br/ciberfauna/xexeu}:${XEXEU_VERSION:-latest}
command: ["scanner", "--config", "/config/xexeu.toml", "--out", "/data/sweeps"]
image: ${HARPIA_IMAGE:-git.lucasrguerra.dev.br/ciberfauna/harpia}:${HARPIA_VERSION:-latest}
command: ["scanner", "--config", "/config/harpia.toml", "--out", "/data/sweeps"]
network_mode: host
user: "0:0" # root sem nenhuma capability além de NET_RAW
cap_drop: [ALL]
@@ -21,25 +21,25 @@ services:
- no-new-privileges:true
volumes:
- ./config:/config:ro
- xexeu-sweeps:/data/sweeps
- harpia-sweeps:/data/sweeps
restart: unless-stopped
xexeu:
image: ${XEXEU_IMAGE:-git.lucasrguerra.dev.br/ciberfauna/xexeu}:${XEXEU_VERSION:-latest}
harpia:
image: ${HARPIA_IMAGE:-git.lucasrguerra.dev.br/ciberfauna/harpia}:${HARPIA_VERSION:-latest}
build: .
command: ["serve", "--bind", "0.0.0.0:8788", "--config", "/config/xexeu.toml",
"--sweeps", "/data/sweeps", "--data-dir", "/data/xexeu"]
command: ["serve", "--bind", "0.0.0.0:8788", "--config", "/config/harpia.toml",
"--sweeps", "/data/sweeps", "--data-dir", "/data/harpia"]
environment:
# Empty: a token is generated at each start and printed in `docker compose logs xexeu`.
XEXEU_ADMIN_TOKEN: ${XEXEU_ADMIN_TOKEN:-}
# Signing key for a [[webhook]] with segredo_env = "XEXEU_WEBHOOK_KEY".
XEXEU_WEBHOOK_KEY: ${XEXEU_WEBHOOK_KEY:-}
# Empty: a token is generated at each start and printed in `docker compose logs harpia`.
HARPIA_ADMIN_TOKEN: ${HARPIA_ADMIN_TOKEN:-}
# Signing key for a [[webhook]] with segredo_env = "HARPIA_WEBHOOK_KEY".
HARPIA_WEBHOOK_KEY: ${HARPIA_WEBHOOK_KEY:-}
ports:
- "${XEXEU_PUBLISH:-127.0.0.1:8788}:8788"
- "${HARPIA_PUBLISH:-127.0.0.1:8788}:8788"
volumes:
- ./config:/config:ro
- xexeu-sweeps:/data/sweeps:ro
- xexeu-data:/data/xexeu
- harpia-sweeps:/data/sweeps:ro
- harpia-data:/data/harpia
read_only: true
tmpfs:
- /tmp
@@ -49,5 +49,5 @@ services:
restart: unless-stopped
volumes:
xexeu-sweeps:
xexeu-data:
harpia-sweeps:
harpia-data:
+17 -17
View File
@@ -2,11 +2,11 @@
**English** · [Português](pt-BR/arquitetura.md)
Xexéu is a lightweight, continuous attack surface management and
Harpia is a lightweight, continuous attack surface management and
vulnerability audit system. It follows a decoupled two-service architecture
distributed via Docker Compose: a privileged packet emitter (`scanner`) and
an unprivileged analytical server (`xexeu`), sharing one binary and one
`crates/xexeu-core` library.
an unprivileged analytical server (`harpia`), sharing one binary and one
`crates/harpia-core` library.
## Technology stack
@@ -16,25 +16,25 @@ an unprivileged analytical server (`xexeu`), sharing one binary and one
| API layer | Axum + Tokio | Asynchronous HTTP service with minimal overhead. |
| Web dashboard | Vanilla HTML/CSS/JS | Zero-dependency frontend embedded directly into the binary via `include_str!`/`include_bytes!` — no `rust-embed`, no build step. |
| Raw-socket engine | `socket2`, hand-built TCP headers | A single `SOCK_RAW`/`IPPROTO_TCP` socket for both sending SYN probes and receiving replies — see [Scan engine](#scan-engine) below. |
| Storage engine | SQLite (`rusqlite`, bundled) + Parquet | Embedded, zero-ops storage. **Not DuckDB**: an early design draft specified DuckDB for its analytical query strengths, but SQLite was chosen instead for v1.0 — no external `libduckdb.so` to link or ship, one less moving part, and the query patterns `xexeu serve` actually needs (point lookups by asset key, small aggregate counts) don't benefit from a columnar engine. Sweep batches themselves stay in Parquet (immutable, one file per sweep, not touched by this choice). |
| Storage engine | SQLite (`rusqlite`, bundled) + Parquet | Embedded, zero-ops storage. **Not DuckDB**: an early design draft specified DuckDB for its analytical query strengths, but SQLite was chosen instead for v1.0 — no external `libduckdb.so` to link or ship, one less moving part, and the query patterns `harpia serve` actually needs (point lookups by asset key, small aggregate counts) don't benefit from a columnar engine. Sweep batches themselves stay in Parquet (immutable, one file per sweep, not touched by this choice). |
| Deployment | Docker Compose | Strict privilege isolation, container hardening, immutable batches over named volumes. |
## System topology & data flow
```
config/xexeu.toml (rw from xexeu, ro-mounted into scanner)
config/harpia.toml (rw from harpia, ro-mounted into scanner)
│
┌─────────────────────┴──────────────────────┐
▼ ▼
scanner (NET_RAW, host net, uid 0) xexeu (uid 10001, zero capabilities)
scanner (NET_RAW, host net, uid 0) harpia (uid 10001, zero capabilities)
- Multi-group scheduler, hot-reload - Batch ingestion (:ro)
- TCP connect discovery - Scoped diff calculation
- SYN (nativo) / connect - CPE -> CVE/KEV matching
(nativo-sem-raw) port scan - SQLite state + CVE database
- Service banner fingerprinting - Axum API, dashboard, exec. report
│ - config CRUD (writes xexeu.toml)
│ - config CRUD (writes harpia.toml)
▼ ▲
xexeu-sweeps (Parquet batches + manifest.json) ───┘
harpia-sweeps (Parquet batches + manifest.json) ───┘
```
### 1. Privilege separation
@@ -45,11 +45,11 @@ scanner (NET_RAW, host net, uid 0) xexeu (uid 10001, zero capabilities)
[`docker.md`](docker.md#why-scanner-runs-as-uid-0-restricted-to-net_raw)
for why Docker makes that necessary), but drops every other capability
(`cap_drop: [ALL]`), runs with a read-only root filesystem, and only
writes to the `xexeu-sweeps` volume. It never opens a listening port, has
writes to the `harpia-sweeps` volume. It never opens a listening port, has
no API, and never touches the SQLite database.
- **`xexeu`:** runs as an unprivileged user (uid 10001) with zero
capabilities. It mounts `xexeu-sweeps` read-only, is the **exclusive
writer** of the SQLite state (`xexeu-data`), writes `xexeu.toml` back
- **`harpia`:** runs as an unprivileged user (uid 10001) with zero
capabilities. It mounts `harpia-sweeps` read-only, is the **exclusive
writer** of the SQLite state (`harpia-data`), writes `harpia.toml` back
when the dashboard's Groups view mutates a group, correlates findings
against the local vulnerability database, and serves the Axum API,
dashboard and executive report bound to `127.0.0.1:8788` by default.
@@ -74,7 +74,7 @@ either can feed the rest of the pipeline unchanged:
mode. No capability needed; every open port is a real, completed TCP
connection.
`execute_scan_for_group` in `xexeu-cli` picks `nativo` whenever a profile
`execute_scan_for_group` in `harpia-cli` picks `nativo` whenever a profile
asks for it **and** `CAP_NET_RAW` is actually usable, and falls back to
`nativo-sem-raw` with a logged warning otherwise — the engine that actually
ran, not the one requested, is what gets recorded in the sweep manifest, so
@@ -82,18 +82,18 @@ an operator reading `/api/status` or a manifest never has to guess.
### 3. Batch contract & idempotency
Communication between `scanner` and `xexeu` happens entirely through
Communication between `scanner` and `harpia` happens entirely through
filesystem batches, never a network call between the two containers:
- Each scan execution writes to `sweeps/<group>/<sweep_id>/observations.parquet`.
- On successful completion, `scanner` atomically creates `manifest.json`
(sweep id, group, scope, engine mode actually used, status).
- `xexeu` polls the sweeps volume, ingests batches idempotently by
- `harpia` polls the sweeps volume, ingests batches idempotently by
`sweep_id`, and `scanner` prunes batches past the retention window.
### 4. Tiered scheduling & scope boundaries
Target configuration in `xexeu.toml` decouples asset definitions from
Target configuration in `harpia.toml` decouples asset definitions from
execution policy — see [`configuration.md`](configuration.md) for the full
reference:
@@ -109,7 +109,7 @@ reference:
### 5. Scoped diffs & event history
Rather than disconnected point-in-time reports, Xexéu evaluates state
Rather than disconnected point-in-time reports, Harpia evaluates state
differences against the specific scope the completed sweep actually
covered:
+48 -48
View File
@@ -2,58 +2,58 @@
# Terminal (CLI)
`xexeu` is one binary covering both Docker Compose roles (`serve` and
`harpia` is one binary covering both Docker Compose roles (`serve` and
`scanner`) plus every operator command. Every subcommand accepts `-h`/
`--help`.
## `xexeu serve`
## `harpia serve`
Runs the API server, batch ingestion, diff engine and the embedded
dashboard/executive report.
```
Usage: xexeu serve [OPTIONS]
Usage: harpia serve [OPTIONS]
Options:
--bind <BIND> [default: 0.0.0.0:8788]
--config <CONFIG> [default: config/xexeu.toml]
--config <CONFIG> [default: config/harpia.toml]
--sweeps <SWEEPS> [default: data/sweeps]
--data-dir <DATA_DIR> [default: data/xexeu]
--data-dir <DATA_DIR> [default: data/harpia]
--admin-token <ADMIN_TOKEN> Token required by the API routes that change state.
Without it, a random token is generated at startup
and printed once [env: XEXEU_ADMIN_TOKEN]
and printed once [env: HARPIA_ADMIN_TOKEN]
```
This is the `xexeu` Compose service's entrypoint.
This is the `harpia` Compose service's entrypoint.
Reads (`GET`) are open; the routes that change the configuration
(`POST`/`PUT`/`DELETE /api/config/groups…`) need the admin token in
`Authorization: Bearer <token>` or `X-Xexeu-Token`, and a browser `Origin`, when
present, must match `Host`. Without `XEXEU_ADMIN_TOKEN`, `serve` prints a fresh
`Authorization: Bearer <token>` or `X-Harpia-Token`, and a browser `Origin`, when
present, must match `Host`. Without `HARPIA_ADMIN_TOKEN`, `serve` prints a fresh
`http://…/?token=…` link at each start; opening it logs the dashboard in for
that tab.
`GET /metrics` serves Prometheus text: `xexeu_build_info`,
`xexeu_sweeps_ingested_total`, `xexeu_assets{status}`, `xexeu_open_ports`,
`xexeu_findings{severidade}`, `xexeu_kev_findings`, `xexeu_vuln_db_cves`,
`xexeu_feeds_last_sync_timestamp_seconds`, per-group
`xexeu_last_sweep_{timestamp_seconds,duration_seconds,complete,events}` and
`xexeu_webhook_deliveries_total{resultado}`. Like the other reads it needs no
token; an alert on `time() - xexeu_last_sweep_timestamp_seconds` catches a
`GET /metrics` serves Prometheus text: `harpia_build_info`,
`harpia_sweeps_ingested_total`, `harpia_assets{status}`, `harpia_open_ports`,
`harpia_findings{severidade}`, `harpia_kev_findings`, `harpia_vuln_db_cves`,
`harpia_feeds_last_sync_timestamp_seconds`, per-group
`harpia_last_sweep_{timestamp_seconds,duration_seconds,complete,events}` and
`harpia_webhook_deliveries_total{resultado}`. Like the other reads it needs no
token; an alert on `time() - harpia_last_sweep_timestamp_seconds` catches a
scanner that stopped.
## `xexeu scanner`
## `harpia scanner`
Runs the continuous scheduler and scan engine, writing sweep batches —
never exits on its own, same lifecycle as a daemon.
```
Usage: xexeu scanner [OPTIONS]
Usage: harpia scanner [OPTIONS]
Options:
--config <CONFIG> [default: config/xexeu.toml]
--config <CONFIG> [default: config/harpia.toml]
--out <OUT> [default: data/sweeps]
--data-dir <DATA_DIR> [default: data/xexeu]
--data-dir <DATA_DIR> [default: data/harpia]
```
Picks the `nativo` (raw SYN) engine whenever a profile asks for it and
@@ -61,45 +61,45 @@ Picks the `nativo` (raw SYN) engine whenever a profile asks for it and
automatically otherwise — see [`architecture.md`](architecture.md#2-scan-engine).
This is the `scanner` Compose service's entrypoint.
## `xexeu scan --group <name> --once`
## `harpia scan --group <name> --once`
Runs a single sweep for one group, for diagnostics — writes a batch exactly
like `scanner` would, then exits.
```
Usage: xexeu scan [OPTIONS]
Usage: harpia scan [OPTIONS]
Options:
--group <GROUP>
--once
--config <CONFIG> [default: config/xexeu.toml]
--config <CONFIG> [default: config/harpia.toml]
--out <OUT> [default: data/sweeps]
--data-dir <DATA_DIR> [default: data/xexeu]
--data-dir <DATA_DIR> [default: data/harpia]
```
```bash
xexeu scan --group dmz --once --config config/xexeu.toml --out data/sweeps --data-dir data/xexeu
harpia scan --group dmz --once --config config/harpia.toml --out data/sweeps --data-dir data/harpia
```
## `xexeu config check`
## `harpia config check`
Validates `xexeu.toml` and prints, per group, the address count, effective
Validates `harpia.toml` and prints, per group, the address count, effective
cron and any cadence overlap. Run this after every manual edit.
```
Usage: xexeu config check [OPTIONS]
Usage: harpia config check [OPTIONS]
Options:
--config <CONFIG> [default: config/xexeu.toml]
--config <CONFIG> [default: config/harpia.toml]
```
Exits non-zero on an invalid configuration — safe to use in a pre-push hook
or CI step, which is exactly what `scripts/check.sh` does.
## `xexeu feeds sync` / `xexeu feeds import`
## `harpia feeds sync` / `harpia feeds import`
```
Usage: xexeu feeds <COMMAND>
Usage: harpia feeds <COMMAND>
Commands:
sync Download NVD and CISA KEV feeds incrementally
@@ -109,66 +109,66 @@ Commands:
```bash
# Live, one-shot sync (also happens automatically inside `serve` if
# padrao.feeds.sincronizar_automaticamente = true — see configuration.md)
xexeu feeds sync --config config/xexeu.toml --data-dir data/xexeu
harpia feeds sync --config config/harpia.toml --data-dir data/harpia
# Offline, for air-gapped networks
xexeu feeds import ./nvd-dump --data-dir data/xexeu
harpia feeds import ./nvd-dump --data-dir data/harpia
```
## `xexeu changes --since <duration>`
## `harpia changes --since <duration>`
Prints diff events (new/gone host, new/closed port, new/fixed
vulnerability) from the local state — the same data `/api/changes` serves.
```bash
xexeu changes --since 24h --data-dir data/xexeu
harpia changes --since 24h --data-dir data/harpia
```
## `xexeu export --format json|csv`
## `harpia export --format json|csv`
Exports the current deduplicated state (hosts, ports, findings) — shares
its formatting logic with the `/api/export/*.csv` and `/api/hosts`
endpoints, so a terminal export and a dashboard download never drift apart.
```
Usage: xexeu export [OPTIONS]
Usage: harpia export [OPTIONS]
Options:
--format <FORMAT> [default: json]
--data-dir <DATA_DIR> [default: data/xexeu]
--data-dir <DATA_DIR> [default: data/harpia]
--out <OUT>
```
```bash
xexeu export --format csv --data-dir data/xexeu --out hosts.csv
xexeu export --format json --data-dir data/xexeu # prints to stdout
harpia export --format csv --data-dir data/harpia --out hosts.csv
harpia export --format json --data-dir data/harpia # prints to stdout
```
## `xexeu doctor [--json]`
## `harpia doctor [--json]`
Diagnoses the runtime environment — run this first when something looks
wrong, and always before reporting an issue (see
[`support.md`](support.md)).
```
Usage: xexeu doctor [OPTIONS]
Usage: harpia doctor [OPTIONS]
Options:
--json
--config <CONFIG> [default: config/xexeu.toml]
--data-dir <DATA_DIR> [default: data/xexeu]
--config <CONFIG> [default: config/harpia.toml]
--data-dir <DATA_DIR> [default: data/harpia]
```
```
$ xexeu doctor
Xexéu v1.0.0 - Diagnóstico do Ambiente
$ harpia doctor
Harpia v1.0.0 - Diagnóstico do Ambiente
================================================================================
Item Status Detalhe
--------------------------------------------------------------------------------
versao ok xexeu v1.0.0
versao ok harpia v1.0.0
config ok configuração válida (4 grupo(s))
net_raw ok CAP_NET_RAW disponível (motor nativo ativo)
sqlite ok banco SQLite acessível em data/xexeu/xexeu.db
sqlite ok banco SQLite acessível em data/harpia/harpia.db
vuln_db ok 135 CVE(s) carregados (12h atrás)
feeds_sync ok sincronizado há 12h (dentro do intervalo configurado)
--------------------------------------------------------------------------------
+14 -14
View File
@@ -2,8 +2,8 @@
# Configuration
Xexéu is configured by a single TOML file, by default `config/xexeu.toml`
(override with `--config` on every command). `xexeu config check --config
Harpia is configured by a single TOML file, by default `config/harpia.toml`
(override with `--config` on every command). `harpia config check --config
<path>` validates it and prints, per group, the address count, effective
cron and cadence overlaps — run it after every edit, before restarting
`serve`/`scanner`.
@@ -40,7 +40,7 @@ perfil = "padrao"
criticidade = "critica"
```
See [`examples/xexeu.toml`](../examples/xexeu.toml) for a fully commented
See [`examples/harpia.toml`](../examples/harpia.toml) for a fully commented
reference covering a corporate network, a DMZ and a core/critical tier with
two cadences (a light 5-minute check and a full 03:00 sweep).
@@ -68,7 +68,7 @@ two cadences (a light 5-minute check and a full 03:00 sweep).
false "host disappeared" event.
- `[padrao.feeds]`: `sincronizar_automaticamente` (bool, default `false`) and
`intervalo_sincronizacao` (default `"24h"`) control the background CVE/KEV
refresh inside `xexeu serve` — see [Vulnerability feeds](#vulnerability-feeds) below.
refresh inside `harpia serve` — see [Vulnerability feeds](#vulnerability-feeds) below.
### `[perfis.<nome>]` — port and engine profiles
@@ -77,7 +77,7 @@ two cadences (a light 5-minute check and a full 03:00 sweep).
- `udp`: list of UDP ports to probe (string list).
- `motor`: `"nativo"` (tries the raw-socket SYN engine, falls back to
`nativo-sem-raw` automatically if `CAP_NET_RAW` isn't available — see
[`docker.md`](docker.md)) or `"nmap"` (requires the `xexeu-scanner-nmap`
[`docker.md`](docker.md)) or `"nmap"` (requires the `harpia-scanner-nmap`
image variant).
- `vulnerabilidades`: whether CVE/KEV correlation and the safe config checks
(expired TLS cert, unencrypted admin port) run for this profile's findings.
@@ -104,7 +104,7 @@ each host's effective (shortest) cadence.
### `[[webhook]]` — change alerts
After each ingested sweep, `xexeu serve` posts the surface changes it found to
After each ingested sweep, `harpia serve` posts the surface changes it found to
every `[[webhook]]` (one request per sweep, only when there is something to
send):
@@ -114,7 +114,7 @@ url = "https://hooks.slack.com/services/T000/B000/XXXX"
formato = "slack" # json (default) | slack | discord
eventos = ["porta_nova", "host_novo"] # empty or omitted: every kind
grupos = ["dmz"] # empty or omitted: every group
segredo_env = "XEXEU_WEBHOOK_KEY" # optional HMAC-SHA256 signature
segredo_env = "HARPIA_WEBHOOK_KEY" # optional HMAC-SHA256 signature
```
- `formato = "json"` sends `{"fonte", "versao", "grupo", "sweep_id", "eventos"}`
@@ -123,31 +123,31 @@ segredo_env = "XEXEU_WEBHOOK_KEY" # optional HMAC-SHA256 signature
- `eventos`: `host_novo`, `host_voltou`, `host_sumiu`, `porta_nova`,
`porta_fechada`, `servico_alterado`.
- `segredo_env` names an environment variable; its value signs the body as
`X-Xexeu-Signature: sha256=<hex HMAC>`. The key itself never goes in the file.
`X-Harpia-Signature: sha256=<hex HMAC>`. The key itself never goes in the file.
- Delivery runs in the background and never holds up ingestion. Network
errors, `5xx` and `429` are retried twice (after 2 s and 4 s); the outcome is
logged and counted in `/metrics`.
- Chat webhook URLs are credentials: `GET /api/config` and the logs show only
`scheme://host/…`.
- `xexeu serve` reads the webhooks at start (and on dashboard edits); restart it
- `harpia serve` reads the webhooks at start (and on dashboard edits); restart it
after changing them by hand.
## Editing a group from the dashboard
`xexeu serve`'s **Groups** view can create, edit and delete groups without
`harpia serve`'s **Groups** view can create, edit and delete groups without
touching the file by hand (`POST`/`PUT`/`DELETE /api/config/groups`) — every
mutation re-runs the same validation as `config check` and persists back to
the TOML file atomically. `xexeu scanner`, running as a separate process,
the TOML file atomically. `harpia scanner`, running as a separate process,
picks up the change on its next tick by comparing the file's mtime; no
restart needed.
## Vulnerability feeds
`xexeu feeds import <dir> --data-dir <path>` loads a local NVD CVE JSON 2.0
`harpia feeds import <dir> --data-dir <path>` loads a local NVD CVE JSON 2.0
dump and a CISA KEV file with no network access (for air-gapped networks).
`xexeu feeds sync --config <path> --data-dir <path>` fetches both live, once,
`harpia feeds sync --config <path> --data-dir <path>` fetches both live, once,
and merges them into the existing local database. Setting
`padrao.feeds.sincronizar_automaticamente = true` makes `xexeu serve` repeat
`padrao.feeds.sincronizar_automaticamente = true` makes `harpia serve` repeat
that sync on its own, every `intervalo_sincronizacao`, for as long as the
process runs — the CVE database then stays fresh independently of the image
or binary being rebuilt, the same principle Trivy uses for its vulnerability
+17 -17
View File
@@ -2,19 +2,19 @@
# Docker
Xexéu ships as two containers from one image, defined in
Harpia ships as two containers from one image, defined in
[`docker-compose.yml`](../docker-compose.yml):
```
xexeu.toml (ro)
harpia.toml (ro)
│
┌─────────────────────┴──────────────────────┐
▼ ▼
scanner (NET_RAW, host net) xexeu (no capabilities)
scanner (NET_RAW, host net) harpia (no capabilities)
schedules + probes targets ingests batches
writes immutable batches ──batches──► correlates CVEs, computes diffs
(xexeu-sweeps volume) serves the API + dashboard
(xexeu-data volume)
(harpia-sweeps volume) serves the API + dashboard
(harpia-data volume)
```
- **`scanner`** only emits packets at the authorized targets and writes
@@ -22,7 +22,7 @@ scanner (NET_RAW, host net) xexeu (no capabilities)
database, never makes an outbound connection. `network_mode: host` is
required so it sees the network the same way the host does (correct
source addresses, visibility of local-segment hosts for discovery).
- **`xexeu`** never emits traffic at scan targets. It ingests batches
- **`harpia`** never emits traffic at scan targets. It ingests batches
(mounted `:ro`), is SQLite's only writer, serves the API/dashboard, and
makes the only outbound connections the stack has (feed sync, update
check) — both opt-in and both disabled by default.
@@ -31,16 +31,16 @@ scanner (NET_RAW, host net) xexeu (no capabilities)
```bash
cp .env.example .env
cp examples/xexeu.toml config/xexeu.toml # edit the scope/groups first
cp examples/harpia.toml config/harpia.toml # edit the scope/groups first
docker compose pull && docker compose up -d # published image
# or, building locally:
docker compose up -d --build
```
The dashboard comes up at `http://127.0.0.1:8788` by default (`XEXEU_PUBLISH`
The dashboard comes up at `http://127.0.0.1:8788` by default (`HARPIA_PUBLISH`
in `.env` to change the bind address/port). To add, edit or remove groups from
it, set `XEXEU_ADMIN_TOKEN` in `.env` (`openssl rand -hex 32`) or, leaving it
empty, take the one-off link from `docker compose logs xexeu`; inside the
it, set `HARPIA_ADMIN_TOKEN` in `.env` (`openssl rand -hex 32`) or, leaving it
empty, take the one-off link from `docker compose logs harpia`; inside the
container it reads `http://0.0.0.0:8788/?token=…`, so swap the host for the
published address.
@@ -71,25 +71,25 @@ still works inside the remapped namespace.
If the capability isn't usable for any reason (remapping misconfigured, a
platform that strips it, a profile with `motor = "nativo"` running outside
this compose file at all), `xexeu` detects it automatically
(`xexeu doctor` reports it, and every sweep manifest records which engine
this compose file at all), `harpia` detects it automatically
(`harpia doctor` reports it, and every sweep manifest records which engine
actually ran) and falls back to `nativo-sem-raw` — never a hard failure.
## Volumes
- `xexeu-sweeps`: batches written by `scanner`, read-only from `xexeu`.
- `harpia-sweeps`: batches written by `scanner`, read-only from `harpia`.
Pruned by `scanner` past `retencao_lotes` (see `architecture.md`).
- `xexeu-data`: the SQLite state (`xexeu`'s only write target) and the
- `harpia-data`: the SQLite state (`harpia`'s only write target) and the
local CVE/KEV database.
- `./config` (bind mount, read-only in both containers): `xexeu.toml`.
- `./config` (bind mount, read-only in both containers): `harpia.toml`.
Mutations from the dashboard's Groups view write back to this file from
inside the `xexeu` container, so the host directory must be writable by
inside the `harpia` container, so the host directory must be writable by
the container's user even though the mount itself stays `:ro` for
`scanner`.
## Optional `nmap` variant
Profiles with `motor = "nmap"` require the separate `xexeu-scanner-nmap`
Profiles with `motor = "nmap"` require the separate `harpia-scanner-nmap`
image (not built by the default `Dockerfile`), which bundles the external
`nmap` binary the way `scan::nmap` expects it on `PATH`. It is not part of
the standard image specifically to keep nmap's NPSL-licensed code out of
+9 -9
View File
@@ -2,13 +2,13 @@
# Interface
`xexeu serve` embeds a vanilla HTML/CSS/JS dashboard (no build step, no
`harpia serve` embeds a vanilla HTML/CSS/JS dashboard (no build step, no
framework) — the same architectural pattern as Acauã's. It polls the API
every few seconds and never needs a page reload to reflect a new sweep.
## Overview
<p align="center"><img src="img/visao-geral-dark-pt.png" width="900" alt="Xexéu overview: KPI cards for active hosts, open ports, critical findings and the local CVE database size, a severity-distribution bar chart and a top-exposed-hosts chart, and a list of the highest-CVSS findings"></p>
<p align="center"><img src="img/visao-geral-dark-pt.png" width="900" alt="Harpia overview: KPI cards for active hosts, open ports, critical findings and the local CVE database size, a severity-distribution bar chart and a top-exposed-hosts chart, and a list of the highest-CVSS findings"></p>
KPIs (active hosts, open ports, critical/KEV findings, CVE database size),
two hand-drawn SVG charts (findings by CVSS severity band, top hosts by
@@ -18,7 +18,7 @@ across every view and the executive report.
## Hosts
<p align="center"><img src="img/hosts-dark-pt.png" width="900" alt="Xexéu hosts table, expanded to show one host's open port with its product, version, CPE and full list of correlated CVE findings"></p>
<p align="center"><img src="img/hosts-dark-pt.png" width="900" alt="Harpia hosts table, expanded to show one host's open port with its product, version, CPE and full list of correlated CVE findings"></p>
One row per discovered asset; expanding a row shows every open port with
its fingerprinted product/version/CPE and the findings correlated against
@@ -26,27 +26,27 @@ it, each with its CVSS, KEV status and match confidence.
## Findings
<p align="center"><img src="img/achados-dark-pt.png" width="900" alt="Xexéu findings view listing every correlated vulnerability across all hosts, filterable and sortable by CVSS"></p>
<p align="center"><img src="img/achados-dark-pt.png" width="900" alt="Harpia findings view listing every correlated vulnerability across all hosts, filterable and sortable by CVSS"></p>
Every `Finding` across every host, filterable by severity/KEV and
searchable, sorted by CVSS by default.
## Groups & scheduling
<p align="center"><img src="img/grupos-dark-pt.png" width="900" alt="Xexéu groups view: a card per target group with its cron expression and next scheduled run, plus an Add group form for CIDR/host/network targets with a custom cron"></p>
<p align="center"><img src="img/grupos-dark-pt.png" width="900" alt="Harpia groups view: a card per target group with its cron expression and next scheduled run, plus an Add group form for CIDR/host/network targets with a custom cron"></p>
Add, edit and delete target groups (CIDR ranges, single hosts, exclusions,
cron, port profile, criticality) without touching `xexeu.toml` by hand —
cron, port profile, criticality) without touching `harpia.toml` by hand —
see [`configuration.md`](configuration.md#editing-a-group-from-the-dashboard)
for how the change reaches the running `scanner`.
Changing groups needs the admin token: open the `?token=` link printed by
`xexeu serve` (or `docker compose logs xexeu`), or type the token when the
`harpia serve` (or `docker compose logs harpia`), or type the token when the
dashboard asks for it. It is kept for the browser tab only.
## Executive report
<p align="center"><img src="img/relatorio-executivo-pt.png" width="900" alt="Xexéu executive security report cover page: authorized-use and confidentiality badges, title, subtitle, KPI strip and the table of contents"></p>
<p align="center"><img src="img/relatorio-executivo-pt.png" width="900" alt="Harpia executive security report cover page: authorized-use and confidentiality badges, title, subtitle, KPI strip and the table of contents"></p>
`GET /relatorio` renders a print-oriented A4 report (cover, table of
contents, KPIs, prioritized findings table, host inventory, glossary),
@@ -56,7 +56,7 @@ a shareable document. See the dashboard's "Export executive report" link.
## Changes
The **Changes** view lists diff events (new host, new/closed port, new/
fixed vulnerability) from `/api/changes`, the same data `xexeu changes
fixed vulnerability) from `/api/changes`, the same data `harpia changes
--since <duration>` prints on the terminal.
## CSV exports
+16 -16
View File
@@ -2,11 +2,11 @@
[English](../architecture.md) · **Português**
A Xexéu é um sistema leve e contínuo de gestão de superfície de ataque e
A Harpia é um sistema leve e contínuo de gestão de superfície de ataque e
auditoria de vulnerabilidades. Segue uma arquitetura de dois serviços
desacoplados distribuídos via Docker Compose: um emissor de pacotes
privilegiado (`scanner`) e um servidor analítico não privilegiado
(`xexeu`), compartilhando um binário e uma biblioteca `crates/xexeu-core`.
(`harpia`), compartilhando um binário e uma biblioteca `crates/harpia-core`.
## Stack tecnológica
@@ -16,25 +16,25 @@ privilegiado (`scanner`) e um servidor analítico não privilegiado
| Camada de API | Axum + Tokio | Serviço HTTP assíncrono com overhead mínimo. |
| Dashboard web | HTML/CSS/JS puro | Frontend sem dependências, embutido direto no binário via `include_str!`/`include_bytes!` — sem `rust-embed`, sem etapa de build. |
| Motor de socket cru | `socket2`, cabeçalhos TCP montados à mão | Um único socket `SOCK_RAW`/`IPPROTO_TCP` tanto pra enviar sondas SYN quanto pra receber respostas — veja [Motor de varredura](#motor-de-varredura) abaixo. |
| Motor de armazenamento | SQLite (`rusqlite`, embutido) + Parquet | Armazenamento embutido, zero operação. **Não é DuckDB**: um rascunho inicial do design especificava DuckDB pelas forças dele em consultas analíticas, mas o SQLite foi escolhido pro v1.0 — sem `libduckdb.so` externo pra linkar ou distribuir, uma peça móvel a menos, e os padrões de consulta que o `xexeu serve` realmente precisa (busca pontual por chave de ativo, contagens agregadas pequenas) não se beneficiam de um motor colunar. Os lotes de varredura em si continuam em Parquet (imutáveis, um arquivo por varredura, não afetados por essa escolha). |
| Motor de armazenamento | SQLite (`rusqlite`, embutido) + Parquet | Armazenamento embutido, zero operação. **Não é DuckDB**: um rascunho inicial do design especificava DuckDB pelas forças dele em consultas analíticas, mas o SQLite foi escolhido pro v1.0 — sem `libduckdb.so` externo pra linkar ou distribuir, uma peça móvel a menos, e os padrões de consulta que o `harpia serve` realmente precisa (busca pontual por chave de ativo, contagens agregadas pequenas) não se beneficiam de um motor colunar. Os lotes de varredura em si continuam em Parquet (imutáveis, um arquivo por varredura, não afetados por essa escolha). |
| Implantação | Docker Compose | Isolamento estrito de privilégio, hardening de container, lotes imutáveis em volumes nomeados. |
## Topologia do sistema e fluxo de dados
```
config/xexeu.toml (rw pelo xexeu, montado ro no scanner)
config/harpia.toml (rw pelo harpia, montado ro no scanner)
│
┌─────────────────────┴──────────────────────┐
▼ ▼
scanner (NET_RAW, rede do host, uid 0) xexeu (uid 10001, zero capabilities)
scanner (NET_RAW, rede do host, uid 0) harpia (uid 10001, zero capabilities)
- Agendador multi-grupo, hot-reload - Ingestão de lotes (:ro)
- Descoberta TCP connect - Cálculo de diff por escopo
- Varredura de porta SYN (nativo) / - Correlação CPE -> CVE/KEV
connect (nativo-sem-raw) - Estado SQLite + base de CVE
- Fingerprint de banner de serviço - API Axum, dashboard, relatório
│ - CRUD de config (escreve xexeu.toml)
│ - CRUD de config (escreve harpia.toml)
▼ ▲
xexeu-sweeps (lotes Parquet + manifest.json) ─────┘
harpia-sweeps (lotes Parquet + manifest.json) ─────┘
```
### 1. Separação de privilégio
@@ -45,11 +45,11 @@ scanner (NET_RAW, rede do host, uid 0) xexeu (uid 10001, zero capabilities)
[`docker.md`](docker.md#por-que-o-scanner-roda-como-uid-0-restrito-a-net_raw)
pra entender por que o Docker torna isso necessário), mas descarta toda
outra capability (`cap_drop: [ALL]`), roda com sistema de arquivos raiz
somente leitura, e só escreve no volume `xexeu-sweeps`. Nunca abre porta
somente leitura, e só escreve no volume `harpia-sweeps`. Nunca abre porta
de escuta, não tem API, e nunca toca no banco SQLite.
- **`xexeu`:** roda como usuário não privilegiado (uid 10001) com zero
capabilities. Monta `xexeu-sweeps` como somente leitura, é o **único
escritor** do estado SQLite (`xexeu-data`), escreve o `xexeu.toml` de
- **`harpia`:** roda como usuário não privilegiado (uid 10001) com zero
capabilities. Monta `harpia-sweeps` como somente leitura, é o **único
escritor** do estado SQLite (`harpia-data`), escreve o `harpia.toml` de
volta quando a tela de Grupos do dashboard muta um grupo, correlaciona
achados contra a base local de vulnerabilidades, e serve a API Axum, o
dashboard e o relatório executivo vinculados a `127.0.0.1:8788` por
@@ -77,7 +77,7 @@ mudança:
documentado. Não precisa de capability; toda porta aberta é uma conexão
TCP real e completa.
A função `execute_scan_for_group` em `xexeu-cli` escolhe `nativo` sempre
A função `execute_scan_for_group` em `harpia-cli` escolhe `nativo` sempre
que um perfil pede e `CAP_NET_RAW` está realmente utilizável, e recorre ao
`nativo-sem-raw` com um aviso registrado caso contrário — o motor que
realmente rodou, não o pedido, é o que fica gravado no manifesto do lote,
@@ -86,7 +86,7 @@ adivinhar.
### 3. Contrato de lote e idempotência
A comunicação entre `scanner` e `xexeu` acontece inteiramente por lotes no
A comunicação entre `scanner` e `harpia` acontece inteiramente por lotes no
sistema de arquivos, nunca por uma chamada de rede entre os dois
containers:
@@ -94,12 +94,12 @@ containers:
`sweeps/<grupo>/<sweep_id>/observations.parquet`.
- Ao terminar com sucesso, o `scanner` cria `manifest.json` atomicamente
(id do lote, grupo, escopo, motor realmente usado, status).
- O `xexeu` sonda o volume de lotes, ingere de forma idempotente por
- O `harpia` sonda o volume de lotes, ingere de forma idempotente por
`sweep_id`, e o `scanner` poda lotes além da janela de retenção.
### 4. Agendamento em níveis e limites de escopo
A configuração de alvos no `xexeu.toml` desacopla a definição de ativos da
A configuração de alvos no `harpia.toml` desacopla a definição de ativos da
política de execução — veja [`configuracao.md`](configuracao.md) pra
referência completa:
@@ -115,7 +115,7 @@ referência completa:
### 5. Diffs por escopo e histórico de eventos
Em vez de relatórios desconectados num ponto no tempo, a Xexéu avalia
Em vez de relatórios desconectados num ponto no tempo, a Harpia avalia
diferenças de estado contra o escopo específico que a varredura concluída
realmente cobriu:
+48 -48
View File
@@ -2,58 +2,58 @@
# Terminal (CLI)
O `xexeu` é um único binário cobrindo os dois papéis do Docker Compose
O `harpia` é um único binário cobrindo os dois papéis do Docker Compose
(`serve` e `scanner`) mais todo comando de operador. Todo subcomando aceita
`-h`/`--help`.
## `xexeu serve`
## `harpia serve`
Roda o servidor de API, a ingestão de lotes, o motor de diff e o
dashboard/relatório executivo embutidos.
```
Usage: xexeu serve [OPTIONS]
Usage: harpia serve [OPTIONS]
Options:
--bind <BIND> [default: 0.0.0.0:8788]
--config <CONFIG> [default: config/xexeu.toml]
--config <CONFIG> [default: config/harpia.toml]
--sweeps <SWEEPS> [default: data/sweeps]
--data-dir <DATA_DIR> [default: data/xexeu]
--data-dir <DATA_DIR> [default: data/harpia]
--admin-token <ADMIN_TOKEN> Token required by the API routes that change state.
Without it, a random token is generated at startup
and printed once [env: XEXEU_ADMIN_TOKEN]
and printed once [env: HARPIA_ADMIN_TOKEN]
```
Esse é o entrypoint do serviço `xexeu` do Compose.
Esse é o entrypoint do serviço `harpia` do Compose.
Leituras (`GET`) são abertas; as rotas que mudam a configuração
(`POST`/`PUT`/`DELETE /api/config/groups…`) exigem o token de administração em
`Authorization: Bearer <token>` ou `X-Xexeu-Token`, e um `Origin` de navegador,
quando presente, precisa bater com o `Host`. Sem `XEXEU_ADMIN_TOKEN`, o `serve`
`Authorization: Bearer <token>` ou `X-Harpia-Token`, e um `Origin` de navegador,
quando presente, precisa bater com o `Host`. Sem `HARPIA_ADMIN_TOKEN`, o `serve`
imprime um link `http://…/?token=…` novo a cada partida; abri-lo autentica o
dashboard naquela aba.
`GET /metrics` serve texto Prometheus: `xexeu_build_info`,
`xexeu_sweeps_ingested_total`, `xexeu_assets{status}`, `xexeu_open_ports`,
`xexeu_findings{severidade}`, `xexeu_kev_findings`, `xexeu_vuln_db_cves`,
`xexeu_feeds_last_sync_timestamp_seconds`, por grupo
`xexeu_last_sweep_{timestamp_seconds,duration_seconds,complete,events}` e
`xexeu_webhook_deliveries_total{resultado}`. Como as outras leituras, não exige
token; um alerta em `time() - xexeu_last_sweep_timestamp_seconds` pega um
`GET /metrics` serve texto Prometheus: `harpia_build_info`,
`harpia_sweeps_ingested_total`, `harpia_assets{status}`, `harpia_open_ports`,
`harpia_findings{severidade}`, `harpia_kev_findings`, `harpia_vuln_db_cves`,
`harpia_feeds_last_sync_timestamp_seconds`, por grupo
`harpia_last_sweep_{timestamp_seconds,duration_seconds,complete,events}` e
`harpia_webhook_deliveries_total{resultado}`. Como as outras leituras, não exige
token; um alerta em `time() - harpia_last_sweep_timestamp_seconds` pega um
scanner que parou.
## `xexeu scanner`
## `harpia scanner`
Roda o agendador e o motor de varredura contínuos, gravando lotes — nunca
sai sozinho, mesmo ciclo de vida de um daemon.
```
Usage: xexeu scanner [OPTIONS]
Usage: harpia scanner [OPTIONS]
Options:
--config <CONFIG> [default: config/xexeu.toml]
--config <CONFIG> [default: config/harpia.toml]
--out <OUT> [default: data/sweeps]
--data-dir <DATA_DIR> [default: data/xexeu]
--data-dir <DATA_DIR> [default: data/harpia]
```
Escolhe o motor `nativo` (SYN cru) sempre que um perfil pede e o
@@ -62,47 +62,47 @@ Escolhe o motor `nativo` (SYN cru) sempre que um perfil pede e o
[`arquitetura.md`](arquitetura.md#2-motor-de-varredura). Esse é o
entrypoint do serviço `scanner` do Compose.
## `xexeu scan --group <nome> --once`
## `harpia scan --group <nome> --once`
Roda uma única varredura de um grupo, pra diagnóstico — grava um lote
exatamente como o `scanner` faria, e sai.
```
Usage: xexeu scan [OPTIONS]
Usage: harpia scan [OPTIONS]
Options:
--group <GROUP>
--once
--config <CONFIG> [default: config/xexeu.toml]
--config <CONFIG> [default: config/harpia.toml]
--out <OUT> [default: data/sweeps]
--data-dir <DATA_DIR> [default: data/xexeu]
--data-dir <DATA_DIR> [default: data/harpia]
```
```bash
xexeu scan --group dmz --once --config config/xexeu.toml --out data/sweeps --data-dir data/xexeu
harpia scan --group dmz --once --config config/harpia.toml --out data/sweeps --data-dir data/harpia
```
## `xexeu config check`
## `harpia config check`
Valida o `xexeu.toml` e imprime, por grupo, a contagem de endereços, o
Valida o `harpia.toml` e imprime, por grupo, a contagem de endereços, o
cron efetivo e qualquer sobreposição de cadência. Rode isso depois de toda
edição manual.
```
Usage: xexeu config check [OPTIONS]
Usage: harpia config check [OPTIONS]
Options:
--config <CONFIG> [default: config/xexeu.toml]
--config <CONFIG> [default: config/harpia.toml]
```
Sai com código não-zero numa configuração inválida — seguro de usar num
hook de pre-push ou passo de CI, que é exatamente o que
`scripts/check.sh` faz.
## `xexeu feeds sync` / `xexeu feeds import`
## `harpia feeds sync` / `harpia feeds import`
```
Usage: xexeu feeds <COMMAND>
Usage: harpia feeds <COMMAND>
Commands:
sync Download NVD and CISA KEV feeds incrementally
@@ -112,23 +112,23 @@ Commands:
```bash
# Sync ao vivo, único (também acontece automaticamente dentro do `serve`
# se padrao.feeds.sincronizar_automaticamente = true — veja configuracao.md)
xexeu feeds sync --config config/xexeu.toml --data-dir data/xexeu
harpia feeds sync --config config/harpia.toml --data-dir data/harpia
# Offline, pra redes isoladas
xexeu feeds import ./dump-nvd --data-dir data/xexeu
harpia feeds import ./dump-nvd --data-dir data/harpia
```
## `xexeu changes --since <duração>`
## `harpia changes --since <duração>`
Imprime eventos de diff (host novo/sumido, porta nova/fechada,
vulnerabilidade nova/corrigida) do estado local — os mesmos dados que
`/api/changes` serve.
```bash
xexeu changes --since 24h --data-dir data/xexeu
harpia changes --since 24h --data-dir data/harpia
```
## `xexeu export --format json|csv`
## `harpia export --format json|csv`
Exporta o estado atual deduplicado (hosts, portas, achados) —
compartilha a lógica de formatação com os endpoints `/api/export/*.csv` e
@@ -136,44 +136,44 @@ compartilha a lógica de formatação com os endpoints `/api/export/*.csv` e
dashboard nunca desalinham.
```
Usage: xexeu export [OPTIONS]
Usage: harpia export [OPTIONS]
Options:
--format <FORMAT> [default: json]
--data-dir <DATA_DIR> [default: data/xexeu]
--data-dir <DATA_DIR> [default: data/harpia]
--out <OUT>
```
```bash
xexeu export --format csv --data-dir data/xexeu --out hosts.csv
xexeu export --format json --data-dir data/xexeu # imprime no stdout
harpia export --format csv --data-dir data/harpia --out hosts.csv
harpia export --format json --data-dir data/harpia # imprime no stdout
```
## `xexeu doctor [--json]`
## `harpia doctor [--json]`
Diagnostica o ambiente de execução — rode isso primeiro quando algo
parecer errado, e sempre antes de reportar uma issue (veja
[`suporte.md`](suporte.md)).
```
Usage: xexeu doctor [OPTIONS]
Usage: harpia doctor [OPTIONS]
Options:
--json
--config <CONFIG> [default: config/xexeu.toml]
--data-dir <DATA_DIR> [default: data/xexeu]
--config <CONFIG> [default: config/harpia.toml]
--data-dir <DATA_DIR> [default: data/harpia]
```
```
$ xexeu doctor
Xexéu v1.0.0 - Diagnóstico do Ambiente
$ harpia doctor
Harpia v1.0.0 - Diagnóstico do Ambiente
================================================================================
Item Status Detalhe
--------------------------------------------------------------------------------
versao ok xexeu v1.0.0
versao ok harpia v1.0.0
config ok configuração válida (4 grupo(s))
net_raw ok CAP_NET_RAW disponível (motor nativo ativo)
sqlite ok banco SQLite acessível em data/xexeu/xexeu.db
sqlite ok banco SQLite acessível em data/harpia/harpia.db
vuln_db ok 135 CVE(s) carregados (12h atrás)
feeds_sync ok sincronizado há 12h (dentro do intervalo configurado)
--------------------------------------------------------------------------------
+15 -15
View File
@@ -2,9 +2,9 @@
# Configuração
A Xexéu é configurada por um único arquivo TOML, por padrão
`config/xexeu.toml` (troque com `--config` em qualquer comando).
`xexeu config check --config <caminho>` valida o arquivo e imprime, por
A Harpia é configurada por um único arquivo TOML, por padrão
`config/harpia.toml` (troque com `--config` em qualquer comando).
`harpia config check --config <caminho>` valida o arquivo e imprime, por
grupo, a contagem de endereços, o cron efetivo e as sobreposições de
cadência — rode depois de cada edição, antes de reiniciar `serve`/`scanner`.
@@ -40,7 +40,7 @@ perfil = "padrao"
criticidade = "critica"
```
Veja [`examples/xexeu.toml`](../../examples/xexeu.toml) pra uma referência
Veja [`examples/harpia.toml`](../../examples/harpia.toml) pra uma referência
comentada completa, cobrindo uma rede corporativa, uma DMZ e um núcleo
crítico com duas cadências (checagem leve a cada 5 minutos e varredura
completa às 03:00).
@@ -69,7 +69,7 @@ completa às 03:00).
varredura perdida gerar um falso "host sumiu".
- `[padrao.feeds]`: `sincronizar_automaticamente` (bool, padrão `false`) e
`intervalo_sincronizacao` (padrão `"24h"`) controlam a atualização
periódica de CVE/KEV em segundo plano dentro do `xexeu serve` — veja
periódica de CVE/KEV em segundo plano dentro do `harpia serve` — veja
[Feeds de vulnerabilidade](#feeds-de-vulnerabilidade) abaixo.
### `[perfis.<nome>]` — perfis de porta e motor
@@ -80,7 +80,7 @@ completa às 03:00).
- `motor`: `"nativo"` (tenta o motor SYN de socket cru, recorrendo
automaticamente a `nativo-sem-raw` se `CAP_NET_RAW` não estiver
disponível — veja [`docker.md`](docker.md)) ou `"nmap"` (exige a variante
de imagem `xexeu-scanner-nmap`).
de imagem `harpia-scanner-nmap`).
- `vulnerabilidades`: se a correlação de CVE/KEV e as checagens seguras de
configuração (certificado TLS expirado, porta administrativa sem
criptografia) rodam pros achados desse perfil.
@@ -108,7 +108,7 @@ sobreposição com a cadência efetiva (a mais curta) de cada host.
### `[[webhook]]` — alertas de mudança
Depois de cada varredura ingerida, o `xexeu serve` envia as mudanças de
Depois de cada varredura ingerida, o `harpia serve` envia as mudanças de
superfície encontradas para cada `[[webhook]]` (uma requisição por varredura,
só quando há algo a enviar):
@@ -118,7 +118,7 @@ url = "https://hooks.slack.com/services/T000/B000/XXXX"
formato = "slack" # json (padrão) | slack | discord
eventos = ["porta_nova", "host_novo"] # vazio ou ausente: todos os tipos
grupos = ["dmz"] # vazio ou ausente: todos os grupos
segredo_env = "XEXEU_WEBHOOK_KEY" # assinatura HMAC-SHA256 opcional
segredo_env = "HARPIA_WEBHOOK_KEY" # assinatura HMAC-SHA256 opcional
```
- `formato = "json"` envia `{"fonte", "versao", "grupo", "sweep_id", "eventos"}`
@@ -127,32 +127,32 @@ segredo_env = "XEXEU_WEBHOOK_KEY" # assinatura HMAC-SHA256 opcional
- `eventos`: `host_novo`, `host_voltou`, `host_sumiu`, `porta_nova`,
`porta_fechada`, `servico_alterado`.
- `segredo_env` é o nome de uma variável de ambiente; o valor dela assina o
corpo como `X-Xexeu-Signature: sha256=<HMAC em hex>`. A chave nunca vai no
corpo como `X-Harpia-Signature: sha256=<HMAC em hex>`. A chave nunca vai no
arquivo.
- A entrega roda em segundo plano e nunca segura a ingestão. Erros de rede,
`5xx` e `429` são repetidos duas vezes (após 2 s e 4 s); o resultado vai para
o log e para o `/metrics`.
- URLs de webhook de chat são credenciais: o `GET /api/config` e os logs mostram
só `esquema://host/…`.
- O `xexeu serve` lê os webhooks na partida (e nas edições pelo dashboard);
- O `harpia serve` lê os webhooks na partida (e nas edições pelo dashboard);
reinicie-o depois de mudá-los à mão.
## Editando um grupo pelo dashboard
A tela **Grupos** do `xexeu serve` cria, edita e remove grupos sem precisar
A tela **Grupos** do `harpia serve` cria, edita e remove grupos sem precisar
mexer no arquivo na mão (`POST`/`PUT`/`DELETE /api/config/groups`) — toda
mutação roda a mesma validação do `config check` e persiste de volta no
TOML de forma atômica. O `xexeu scanner`, rodando num processo separado,
TOML de forma atômica. O `harpia scanner`, rodando num processo separado,
pega a mudança no próximo tick comparando o `mtime` do arquivo; não precisa
reiniciar.
## Feeds de vulnerabilidade
`xexeu feeds import <dir> --data-dir <caminho>` carrega um dump local do
`harpia feeds import <dir> --data-dir <caminho>` carrega um dump local do
NVD CVE JSON 2.0 e um arquivo do CISA KEV sem acesso à rede (pra redes
isoladas). `xexeu feeds sync --config <caminho> --data-dir <caminho>` baixa
isoladas). `harpia feeds sync --config <caminho> --data-dir <caminho>` baixa
os dois ao vivo, uma vez, e funde no banco local existente. Definir
`padrao.feeds.sincronizar_automaticamente = true` faz o `xexeu serve`
`padrao.feeds.sincronizar_automaticamente = true` faz o `harpia serve`
repetir essa sincronização sozinho, a cada `intervalo_sincronizacao`,
durante toda a vida do processo — o banco de CVEs fica fresco independente
de rebuild de imagem ou binário, o mesmo princípio que o Trivy usa pro
+18 -18
View File
@@ -2,19 +2,19 @@
# Docker
A Xexéu roda como dois containers a partir de uma imagem, definidos no
A Harpia roda como dois containers a partir de uma imagem, definidos no
[`docker-compose.yml`](../../docker-compose.yml):
```
xexeu.toml (ro)
harpia.toml (ro)
│
┌─────────────────────┴──────────────────────┐
▼ ▼
scanner (NET_RAW, rede do host) xexeu (sem capabilities)
scanner (NET_RAW, rede do host) harpia (sem capabilities)
agenda e sonda os alvos ingere lotes
grava lotes imutáveis ──lotes──► correlaciona CVEs, calcula diffs
(volume xexeu-sweeps) serve a API + dashboard
(volume xexeu-data)
(volume harpia-sweeps) serve a API + dashboard
(volume harpia-data)
```
- **`scanner`** só emite pacotes pros alvos autorizados e grava lotes de
@@ -22,7 +22,7 @@ scanner (NET_RAW, rede do host) xexeu (sem capabilities)
nunca faz conexão de saída. `network_mode: host` é necessário pra ele
enxergar a rede igual ao host (endereços de origem corretos,
visibilidade de hosts do segmento local pra descoberta).
- **`xexeu`** nunca emite tráfego pros alvos. Ingere lotes (montados
- **`harpia`** nunca emite tráfego pros alvos. Ingere lotes (montados
`:ro`), é o único escritor do SQLite, serve a API/dashboard, e faz as
únicas conexões de saída de toda a stack (sync de feeds, checagem de
atualização) — ambas opt-in e desativadas por padrão.
@@ -31,16 +31,16 @@ scanner (NET_RAW, rede do host) xexeu (sem capabilities)
```bash
cp .env.example .env
cp examples/xexeu.toml config/xexeu.toml # edite o escopo/grupos primeiro
cp examples/harpia.toml config/harpia.toml # edite o escopo/grupos primeiro
docker compose pull && docker compose up -d # imagem publicada
# ou, buildando local:
docker compose up -d --build
```
O dashboard sobe em `http://127.0.0.1:8788` por padrão (`XEXEU_PUBLISH` no
O dashboard sobe em `http://127.0.0.1:8788` por padrão (`HARPIA_PUBLISH` no
`.env` pra trocar endereço/porta). Pra adicionar, editar ou remover grupos
por ele, defina `XEXEU_ADMIN_TOKEN` no `.env` (`openssl rand -hex 32`) ou,
deixando vazio, pegue o link avulso em `docker compose logs xexeu`; dentro do
por ele, defina `HARPIA_ADMIN_TOKEN` no `.env` (`openssl rand -hex 32`) ou,
deixando vazio, pegue o link avulso em `docker compose logs harpia`; dentro do
contêiner ele aparece como `http://0.0.0.0:8788/?token=…`, então troque o host
pelo endereço publicado.
@@ -74,28 +74,28 @@ o `NET_RAW` continua funcionando dentro do namespace remapeado.
Se a capability não estiver disponível por qualquer motivo (remapeamento
mal configurado, uma plataforma que remove ela, um perfil com
`motor = "nativo"` rodando fora deste compose de qualquer forma), a Xexéu
detecta isso automaticamente (`xexeu doctor` reporta, e todo manifesto de
`motor = "nativo"` rodando fora deste compose de qualquer forma), a Harpia
detecta isso automaticamente (`harpia doctor` reporta, e todo manifesto de
varredura registra qual motor realmente rodou) e recorre ao
`nativo-sem-raw` — nunca uma falha dura.
## Volumes
- `xexeu-sweeps`: lotes gravados pelo `scanner`, somente leitura a partir
do `xexeu`. Podado pelo `scanner` além de `retencao_lotes` (veja
- `harpia-sweeps`: lotes gravados pelo `scanner`, somente leitura a partir
do `harpia`. Podado pelo `scanner` além de `retencao_lotes` (veja
`arquitetura.md`).
- `xexeu-data`: o estado SQLite (único alvo de escrita do `xexeu`) e a
- `harpia-data`: o estado SQLite (único alvo de escrita do `harpia`) e a
base local de CVE/KEV.
- `./config` (bind mount, somente leitura nos dois containers):
`xexeu.toml`. Mutações pela tela de Grupos do dashboard escrevem de
volta nesse arquivo de dentro do container `xexeu`, então o diretório do
`harpia.toml`. Mutações pela tela de Grupos do dashboard escrevem de
volta nesse arquivo de dentro do container `harpia`, então o diretório do
host precisa ser gravável pelo usuário do container mesmo que o próprio
mount continue `:ro` pro `scanner`.
## Variante `nmap` opcional
Perfis com `motor = "nmap"` exigem a imagem separada
`xexeu-scanner-nmap` (não construída pelo `Dockerfile` padrão), que
`harpia-scanner-nmap` (não construída pelo `Dockerfile` padrão), que
empacota o binário externo `nmap` do jeito que `scan::nmap` espera
encontrá-lo no `PATH`. Não faz parte da imagem padrão justamente pra
manter o código licenciado sob NPSL do nmap fora da distribuição padrão.
+9 -9
View File
@@ -2,14 +2,14 @@
# Interface
O `xexeu serve` embute um dashboard HTML/CSS/JS puro (sem build, sem
O `harpia serve` embute um dashboard HTML/CSS/JS puro (sem build, sem
framework) — o mesmo padrão arquitetural do Acauã. Ele sonda a API a cada
poucos segundos e nunca precisa de recarregar a página pra refletir uma
varredura nova.
## Visão geral
<p align="center"><img src="../img/visao-geral-dark-pt.png" width="900" alt="Visão geral da Xexéu: cartões de KPI para hosts ativos, portas abertas, achados críticos e tamanho da base local de CVE, um gráfico de barras de distribuição por severidade e um gráfico de top hosts mais expostos, e uma lista dos achados com maior CVSS"></p>
<p align="center"><img src="../img/visao-geral-dark-pt.png" width="900" alt="Visão geral da Harpia: cartões de KPI para hosts ativos, portas abertas, achados críticos e tamanho da base local de CVE, um gráfico de barras de distribuição por severidade e um gráfico de top hosts mais expostos, e uma lista dos achados com maior CVSS"></p>
KPIs (hosts ativos, portas abertas, achados críticos/KEV, tamanho da base
de CVE), dois gráficos SVG feitos à mão (achados por faixa de severidade
@@ -20,7 +20,7 @@ executivo.
## Hosts
<p align="center"><img src="../img/hosts-dark-pt.png" width="900" alt="Tabela de hosts da Xexéu, expandida mostrando a porta aberta de um host com produto, versão, CPE e a lista completa de achados de CVE correlacionados"></p>
<p align="center"><img src="../img/hosts-dark-pt.png" width="900" alt="Tabela de hosts da Harpia, expandida mostrando a porta aberta de um host com produto, versão, CPE e a lista completa de achados de CVE correlacionados"></p>
Uma linha por ativo descoberto; expandir uma linha mostra toda porta
aberta com o produto/versão/CPE identificado e os achados correlacionados
@@ -28,28 +28,28 @@ contra ela, cada um com seu CVSS, status no KEV e nível de confiança.
## Achados
<p align="center"><img src="../img/achados-dark-pt.png" width="900" alt="Tela de achados da Xexéu listando toda vulnerabilidade correlacionada em todos os hosts, filtrável e ordenável por CVSS"></p>
<p align="center"><img src="../img/achados-dark-pt.png" width="900" alt="Tela de achados da Harpia listando toda vulnerabilidade correlacionada em todos os hosts, filtrável e ordenável por CVSS"></p>
Todo `Finding` de todo host, filtrável por severidade/KEV e buscável,
ordenado por CVSS por padrão.
## Grupos e agendamento
<p align="center"><img src="../img/grupos-dark-pt.png" width="900" alt="Tela de grupos da Xexéu: um card por grupo de alvos com sua expressão cron e próxima execução agendada, mais um formulário Adicionar grupo pra alvos CIDR/host/rede com cron personalizado"></p>
<p align="center"><img src="../img/grupos-dark-pt.png" width="900" alt="Tela de grupos da Harpia: um card por grupo de alvos com sua expressão cron e próxima execução agendada, mais um formulário Adicionar grupo pra alvos CIDR/host/rede com cron personalizado"></p>
Adicione, edite e remova grupos de alvos (faixas CIDR, hosts isolados,
exclusões, cron, perfil de portas, criticidade) sem mexer no
`xexeu.toml` na mão — veja
`harpia.toml` na mão — veja
[`configuracao.md`](configuracao.md#editando-um-grupo-pelo-dashboard) pra
como a mudança chega no `scanner` em execução.
Mexer em grupos exige o token de administração: abra o link `?token=` impresso
pelo `xexeu serve` (ou `docker compose logs xexeu`), ou digite o token quando o
pelo `harpia serve` (ou `docker compose logs harpia`), ou digite o token quando o
dashboard pedir. Ele fica guardado só naquela aba do navegador.
## Relatório executivo
<p align="center"><img src="../img/relatorio-executivo-pt.png" width="900" alt="Capa do relatório executivo de segurança da Xexéu: selos de uso autorizado e confidencialidade, título, subtítulo, faixa de KPIs e o sumário"></p>
<p align="center"><img src="../img/relatorio-executivo-pt.png" width="900" alt="Capa do relatório executivo de segurança da Harpia: selos de uso autorizado e confidencialidade, título, subtítulo, faixa de KPIs e o sumário"></p>
`GET /relatorio` renderiza um relatório A4 orientado a impressão (capa,
sumário, KPIs, tabela de achados prioritários, inventário de hosts,
@@ -61,7 +61,7 @@ executivo" no dashboard.
A tela **Mudanças** lista eventos de diff (host novo, porta nova/fechada,
vulnerabilidade nova/corrigida) de `/api/changes`, os mesmos dados que
`xexeu changes --since <duração>` imprime no terminal.
`harpia changes --since <duração>` imprime no terminal.
## Exportação CSV
+9 -9
View File
@@ -2,16 +2,16 @@
[English](../support.md) · **Português**
A Xexéu é distribuída como uma stack Docker Compose de dois containers. A
A Harpia é distribuída como uma stack Docker Compose de dois containers. A
forma mais rápida de conseguir ajuda é abrir uma issue no repositório
Gitea.
## Antes de abrir uma issue
1. Rode `docker exec xexeu xexeu doctor --json` (ou `xexeu doctor --json`
1. Rode `docker exec harpia harpia doctor --json` (ou `harpia doctor --json`
no binário do host) e anexe a saída.
2. Confirme a versão com `xexeu --version`.
3. Rode `xexeu config check --config <caminho>` pra descartar um problema
2. Confirme a versão com `harpia --version`.
3. Rode `harpia config check --config <caminho>` pra descartar um problema
de configuração antes de reportar um de varredura.
4. Revise [`configuracao.md`](configuracao.md), [`arquitetura.md`](arquitetura.md)
e [`docker.md`](docker.md) — principalmente a seção de `CAP_NET_RAW` se
@@ -19,13 +19,13 @@ Gitea.
## O que incluir
- SO do host, arquitetura (`uname -m`) e versão/tag da Xexéu.
- SO do host, arquitetura (`uname -m`) e versão/tag da Harpia.
- O `docker-compose.yml` exato (ou a invocação de CLI) usado.
- Logs completos dos containers: `docker compose logs scanner xexeu`.
- Logs completos dos containers: `docker compose logs scanner harpia`.
- O `motor` realmente usado na varredura afetada — confira o manifesto do
lote ou `/api/status`, já que `nativo` recorre silenciosamente a
`nativo-sem-raw` sem `CAP_NET_RAW`, o que muda o que é esperado.
- Um `xexeu.toml` redigido (nunca compartilhe faixas de escopo autorizado
- Um `harpia.toml` redigido (nunca compartilhe faixas de escopo autorizado
reais ou dados de contato de `responsavel` se forem sensíveis).
Audite só redes que você possui ou tem autorização explícita pra testar.
@@ -41,8 +41,8 @@ Não inclua detalhes de exploração numa issue pública. Siga o
| Sintoma | O que checar |
|---|---|
| O container `scanner` sai imediatamente | Confirme que `cap_add: [NET_RAW]` e `user: "0:0"` estão definidos — `nativo` sem a capability deveria recorrer ao modo degradado, não travar; um crash é um problema diferente |
| Toda varredura usa `nativo-sem-raw` mesmo com `NET_RAW` concedido | Confira o relatório de capabilities do `xexeu doctor`; num host com `--userns-remap`, verifique se o remapeamento mapeia o `uid 0` do container corretamente |
| `serve` fica inacessível de outro host | Vincula em `127.0.0.1:8788` por padrão (`XEXEU_PUBLISH` no `.env`); verifique a configuração do proxy reverso |
| Toda varredura usa `nativo-sem-raw` mesmo com `NET_RAW` concedido | Confira o relatório de capabilities do `harpia doctor`; num host com `--userns-remap`, verifique se o remapeamento mapeia o `uid 0` do container corretamente |
| `serve` fica inacessível de outro host | Vincula em `127.0.0.1:8788` por padrão (`HARPIA_PUBLISH` no `.env`); verifique a configuração do proxy reverso |
| `feeds sync` falha | Verifique conectividade de rede com as APIs do NVD e do CISA KEV; recorra a `feeds import` com um dump baixado manualmente pra redes isoladas |
| Dashboard aparece em português | `Auto` segue o idioma do navegador; selecione inglês nas Configurações |
| Um grupo adicionado pelo dashboard ainda não é varrido | O `scanner` recarrega a config no próximo tick pelo `mtime` do arquivo, não instantaneamente — espere um tick, ou confira os logs dele por um aviso de recarga se a config estava inválida |
+9 -9
View File
@@ -2,15 +2,15 @@
**English** · [Português](pt-BR/suporte.md)
Xexéu is distributed as a two-container Docker Compose stack. The fastest
Harpia is distributed as a two-container Docker Compose stack. The fastest
way to get help is opening an issue in the Gitea repository.
## Before opening an issue
1. Run `docker exec xexeu xexeu doctor --json` (or `xexeu doctor --json` on
1. Run `docker exec harpia harpia doctor --json` (or `harpia doctor --json` on
the host binary) and attach the output.
2. Confirm the version with `xexeu --version`.
3. Run `xexeu config check --config <path>` to rule out a configuration
2. Confirm the version with `harpia --version`.
3. Run `harpia config check --config <path>` to rule out a configuration
problem before reporting a scanning one.
4. Review [`configuration.md`](configuration.md), [`architecture.md`](architecture.md)
and [`docker.md`](docker.md) — especially the `CAP_NET_RAW` section if the
@@ -18,13 +18,13 @@ way to get help is opening an issue in the Gitea repository.
## What to include
- Host OS, architecture (`uname -m`) and Xexéu version/tag.
- Host OS, architecture (`uname -m`) and Harpia version/tag.
- The exact `docker-compose.yml` (or CLI invocation) used.
- Full container logs: `docker compose logs scanner xexeu`.
- Full container logs: `docker compose logs scanner harpia`.
- The `motor` actually used for the affected sweep — check the batch
manifest or `/api/status`, since `nativo` silently falls back to
`nativo-sem-raw` without `CAP_NET_RAW`, which changes what's expected.
- A redacted `xexeu.toml` (never share real authorized-scope ranges or
- A redacted `harpia.toml` (never share real authorized-scope ranges or
`responsavel` contact details if they're sensitive).
Only ever audit networks you own or are explicitly authorized to test. Do
@@ -40,8 +40,8 @@ Do not include exploit details in a public issue. Follow
| Symptom | What to check |
|---|---|
| `scanner` container exits immediately | Confirm `cap_add: [NET_RAW]` and `user: "0:0"` are both set — `nativo` without the capability should fall back, not crash; a crash means a different problem |
| Every sweep uses `nativo-sem-raw` even with `NET_RAW` granted | Check `xexeu doctor`'s capability report; on a `--userns-remap` host, verify the remap maps the container's `uid 0` correctly |
| `serve` is unreachable from another host | Binds to `127.0.0.1:8788` by default (`XEXEU_PUBLISH` in `.env`); verify reverse proxy configuration |
| Every sweep uses `nativo-sem-raw` even with `NET_RAW` granted | Check `harpia doctor`'s capability report; on a `--userns-remap` host, verify the remap maps the container's `uid 0` correctly |
| `serve` is unreachable from another host | Binds to `127.0.0.1:8788` by default (`HARPIA_PUBLISH` in `.env`); verify reverse proxy configuration |
| `feeds sync` fails | Check network connectivity to the NVD and CISA KEV APIs; fall back to `feeds import` with a manually downloaded dump for isolated networks |
| Dashboard shows Portuguese | `Auto` follows the browser language; select English in Settings |
| A group added from the dashboard isn't scanned yet | `scanner` reloads the config on its next tick by file `mtime`, not instantly — wait one tick, or check its logs for a reload warning if the config was invalid |
+3 -3
View File
@@ -1,5 +1,5 @@
# Escopo autorizado: nenhum alvo pode cair fora destas faixas.
# Alvos fora do escopo fazem `xexeu config check` e os dois serviços recusarem iniciar.
# Alvos fora do escopo fazem `harpia config check` e os dois serviços recusarem iniciar.
[escopo]
autorizado = ["10.0.0.0/8", "203.0.113.0/24"]
responsavel = "Equipe de Infraestrutura <infra@exemplo.org>"
@@ -26,7 +26,7 @@ vulnerabilidades = true
[perfis.servicos-ricos]
tcp = "top-1000"
motor = "nmap" # exige a imagem variante xexeu-scanner-nmap
motor = "nmap" # exige a imagem variante harpia-scanner-nmap
vulnerabilidades = true
# Rede corporativa: a maior parte do parque, cadência diária herdada.
@@ -63,4 +63,4 @@ criticidade = "critica"
# formato = "slack"
# eventos = ["host_novo", "porta_nova", "servico_alterado"]
# grupos = ["dmz", "nucleo"]
# segredo_env = "XEXEU_WEBHOOK_KEY"
# segredo_env = "HARPIA_WEBHOOK_KEY"
+44 -33
View File
@@ -363,6 +363,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
"subtle",
]
[[package]]
@@ -541,6 +542,40 @@ dependencies = [
"zerocopy",
]
[[package]]
name = "harpia-core"
version = "2.0.0"
dependencies = [
"arrow-array",
"arrow-schema",
"chrono",
"croner",
"hmac",
"ipnet",
"parquet",
"reqwest",
"rusqlite",
"rustls",
"serde",
"serde_json",
"sha2",
"socket2 0.5.10",
"tempfile",
"thiserror 1.0.69",
"tokio",
"tokio-rustls",
"toml",
"ulid",
]
[[package]]
name = "harpia-fuzz"
version = "0.0.0"
dependencies = [
"harpia-core",
"libfuzzer-sys",
]
[[package]]
name = "hashbrown"
version = "0.17.1"
@@ -565,6 +600,15 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "hmac"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
dependencies = [
"digest",
]
[[package]]
name = "http"
version = "1.5.0"
@@ -2060,39 +2104,6 @@ version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
[[package]]
name = "xexeu-core"
version = "1.0.0"
dependencies = [
"arrow-array",
"arrow-schema",
"chrono",
"croner",
"ipnet",
"parquet",
"reqwest",
"rusqlite",
"rustls",
"serde",
"serde_json",
"sha2",
"socket2 0.5.10",
"tempfile",
"thiserror 1.0.69",
"tokio",
"tokio-rustls",
"toml",
"ulid",
]
[[package]]
name = "xexeu-fuzz"
version = "0.0.0"
dependencies = [
"libfuzzer-sys",
"xexeu-core",
]
[[package]]
name = "yoke"
version = "0.8.4"
+2 -2
View File
@@ -1,5 +1,5 @@
[package]
name = "xexeu-fuzz"
name = "harpia-fuzz"
version = "0.0.0"
publish = false
edition = "2021"
@@ -9,7 +9,7 @@ cargo-fuzz = true
[dependencies]
libfuzzer-sys = "0.4"
xexeu-core = { path = "../crates/xexeu-core" }
harpia-core = { path = "../crates/harpia-core" }
# Kept out of the main workspace: it needs a nightly toolchain.
[workspace]
+1 -1
View File
@@ -2,7 +2,7 @@
//! TLS certificates come from any host in scope.
use libfuzzer_sys::fuzz_target;
use xexeu_core::vuln::checks::parse_x509_der_not_after;
use harpia_core::vuln::checks::parse_x509_der_not_after;
fuzz_target!(|der: &[u8]| {
let _ = parse_x509_der_not_after(der);
+2 -2
View File
@@ -3,8 +3,8 @@
//! from the dashboard's group form.
use libfuzzer_sys::fuzz_target;
use xexeu_core::schedule::{CronSpec, Jitter};
use xexeu_core::targets::{parse_exclusion, parse_scope_entry, parse_target};
use harpia_core::schedule::{CronSpec, Jitter};
use harpia_core::targets::{parse_exclusion, parse_scope_entry, parse_target};
fuzz_target!(|text: &str| {
let _ = parse_target(text);
+3 -3
View File
@@ -2,9 +2,9 @@
//! Banners and HTTP responses come from any host in scope.
use libfuzzer_sys::fuzz_target;
use xexeu_core::scan::fingerprint::extract_server_header;
use xexeu_core::vuln::checks::evaluate_http_admin_response;
use xexeu_core::vuln::matcher::parse_banner_to_cpe;
use harpia_core::scan::fingerprint::extract_server_header;
use harpia_core::vuln::checks::evaluate_http_admin_response;
use harpia_core::vuln::matcher::parse_banner_to_cpe;
fuzz_target!(|text: &str| {
let _ = parse_banner_to_cpe(text);
+1 -1
View File
@@ -4,7 +4,7 @@
use std::io::Cursor;
use libfuzzer_sys::fuzz_target;
use xexeu_core::vuln::feeds::{parse_kev_reader, parse_nvd_json, Cpe};
use harpia_core::vuln::feeds::{parse_kev_reader, parse_nvd_json, Cpe};
fuzz_target!(|data: &[u8]| {
let _ = parse_nvd_json(Cursor::new(data));
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 763 KiB

After

Width:  |  Height:  |  Size: 1.1 MiB

+2 -2
View File
@@ -81,14 +81,14 @@ const WORDS = [
'tentativas', 'ambas',
];
const BRAND = /Xexéu|Xexeu|Português|English/gi;
const BRAND = /Harpia|Harpia|Português|English/gi;
const isPortuguese = (raw) => {
const s = raw.replace(BRAND, ' ');
return ACCENT.test(s) || WORDS.some((w) => new RegExp(`(^|[^a-zà-ú])${w}([^a-zà-ú]|$)`, 'i').test(s));
};
const ALLOW = new Set([
'Xexéu', 'Português', 'English', 'Auto', 'Wi-Fi', 'Zeek', 'DuckDB', 'API', 'JSON', 'CLI',
'Harpia', 'Português', 'English', 'Auto', 'Wi-Fi', 'Zeek', 'DuckDB', 'API', 'JSON', 'CLI',
'MIT', 'Apache-2.0', 'OK', 'status-indicator {n}',
]);
const ALLOW_PREFIX = ['http://', 'https://', 'data:', 'file:', '#', '.', '/'];
+4 -4
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env bash
# Builds the CLI for a target platform and packages it for a release:
# xexeu-<tag>-<platform>.tar.gz alongside a .sha256 checksum file.
# harpia-<tag>-<platform>.tar.gz alongside a .sha256 checksum file.
#
# scripts/package-cli.sh v1.0.3 linux-x86_64 x86_64-unknown-linux-gnu
#
@@ -24,11 +24,11 @@ case "$target" in
esac
rustup target add "$target" >/dev/null 2>&1 || true
cargo build --release --locked -p xexeu-cli --target "$target"
cargo build --release --locked -p harpia-cli --target "$target"
name="xexeu-${tag}-${platform}"
name="harpia-${tag}-${platform}"
rm -rf "$name"; mkdir "$name"
cp "${CARGO_TARGET_DIR:-target}/${target}/release/xexeu" "$name/"
cp "${CARGO_TARGET_DIR:-target}/${target}/release/harpia" "$name/"
cp README.md LICENSE-MIT LICENSE-APACHE "$name/"
tar czf "$name.tar.gz" "$name"
+6 -6
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env bash
# Smoke-tests a Xexéu image: the API and the dashboard answer,
# xexeu doctor reports ok, a HEALTHCHECK is declared and SIGTERM stops the daemon cleanly.
# Smoke-tests a Harpia image: the API and the dashboard answer,
# harpia doctor reports ok, a HEALTHCHECK is declared and SIGTERM stops the daemon cleanly.
# Everything runs through `docker exec`, so no port has to be reachable from
# the CI job container. The container is always removed.
#
@@ -8,7 +8,7 @@
set -euo pipefail
image=${1:?usage: smoke-image.sh <image-ref>}
name="xexeu-smoke-$$-$RANDOM"
name="harpia-smoke-$$-$RANDOM"
trap 'docker rm -f "$name" >/dev/null 2>&1 || true' EXIT
fail() { echo "smoke: $*" >&2; docker logs "$name" >&2 2>&1 || true; exit 1; }
@@ -17,7 +17,7 @@ fail() { echo "smoke: $*" >&2; docker logs "$name" >&2 2>&1 || true; exit 1; }
cfg=$(mktemp -d)
trap 'rm -rf "$cfg"; docker rm -f "$name" >/dev/null 2>&1 || true' EXIT
mkdir "$cfg/config"
cp "$(dirname "$0")/../examples/xexeu.toml" "$cfg/config/xexeu.toml"
cp "$(dirname "$0")/../examples/harpia.toml" "$cfg/config/harpia.toml"
docker create --name "$name" "$image" >/dev/null
tar -C "$cfg" -c config | docker cp - "$name:/"
docker start "$name" >/dev/null
@@ -31,8 +31,8 @@ out=$(docker exec "$name" curl -fsS http://127.0.0.1:8788/api/health) || fail "/
grep -q '"status":"ok"' <<<"$out" || fail "/api/health is not ok"
out=$(docker exec "$name" curl -fsS http://127.0.0.1:8788/) || fail "dashboard did not answer"
grep -qi '<!doctype html' <<<"$out" || fail "dashboard is not served"
out=$(docker exec "$name" xexeu doctor --json --config /config/xexeu.toml --data-dir /data/xexeu) || { echo "$out" >&2; fail "xexeu doctor --json failed"; }
grep -q '"version"' <<<"$out" || fail "xexeu doctor --json has no version"
out=$(docker exec "$name" harpia doctor --json --config /config/harpia.toml --data-dir /data/harpia) || { echo "$out" >&2; fail "harpia doctor --json failed"; }
grep -q '"version"' <<<"$out" || fail "harpia 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 stop -t 10 "$name" >/dev/null