8 Commits
Author SHA1 Message Date
lucasrguerra 1dc754a561 Merge pull request 'Webhook alerts, Prometheus metrics, and 1.2.0' (#3) from feat/alertas-metricas into main
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and clippy (push) Successful in 23s
CI / Dependency audit (push) Successful in 14s
CI / Tests (Linux) (push) Successful in 1m41s
Release / Plan (reuse the published image?) (push) Successful in 5s
Release / ci (push) Skipped
Release / Build image (amd64) (push) Skipped
Release / Build image (arm64) (push) Skipped
Release / Publish tags (push) Successful in 21s
Release / Gitea release (push) Successful in 6s
Release / CLI (linux-aarch64) (push) Successful in 3m8s
Release / CLI (linux-x86_64) (push) Successful in 2m48s
2026-11-03 14:50:15 +00:00
lucasrguerra d8b8ff1150 Merge pull request 'Fuzzing, property tests, CLI split, and 1.1.0' (#2) from feat/robustez into main
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and clippy (push) Successful in 24s
CI / Dependency audit (push) Successful in 18s
CI / Tests (Linux) (push) Successful in 1m18s
Release / Build image (amd64) (push) Skipped
Release / Build image (arm64) (push) Skipped
Release / Plan (reuse the published image?) (push) Successful in 3s
Release / ci (push) Skipped
Release / Publish tags (push) Successful in 14s
Release / Gitea release (push) Successful in 5s
Release / CLI (linux-x86_64) (push) Successful in 2m38s
Release / CLI (linux-aarch64) (push) Successful in 8m8s
2026-11-03 14:38:10 +00:00
Lucas RayanandClaude Opus 5.5 a6e4d43c51 chore(release): 1.2.0
CI / Format and clippy (pull_request) Successful in 24s
CI / Dependency audit (pull_request) Successful in 10s
CI / Tests (Linux) (pull_request) Successful in 2m31s
CI / Docker image (build and smoke test) (pull_request) Successful in 5m47s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 11:06:46 -03:00
Lucas RayanandClaude Opus 5.5 cd1f3d0e8c feat: webhook alerts for surface changes and Prometheus /metrics
[[webhook]] receivers get each ingested sweep's changes, filtered by kind
and group, as Xexéu JSON or a Slack/Discord message, optionally signed with
HMAC-SHA256 from an environment variable. Delivery runs in the background
with retries and never blocks ingestion. GET /api/config and the logs show
webhook URLs as scheme://host/… because chat webhook URLs are credentials.

/metrics exposes hosts, ports, findings by severity, feed state, per-group
last sweep and webhook delivery counters.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 11:06:45 -03:00
Lucas RayanandClaude Opus 5.5 8b6e0d4a3f chore(release): 1.1.0
CI / Format and clippy (pull_request) Successful in 30s
CI / Tests (Linux) (pull_request) Successful in 2m39s
CI / Dependency audit (pull_request) Successful in 15s
CI / Docker image (build and smoke test) (pull_request) Successful in 6m37s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 10:53:26 -03:00
Lucas RayanandClaude Opus 5.5 d231033e42 refactor(cli): split main.rs into modules
server/ (state, ingestion, API, CSV exports, embedded assets), scanner,
feeds_cmd, config_cmd and commands. Code moved as is; no behavior change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 10:53:26 -03:00
Lucas RayanandClaude Opus 5.5 b70f36da09 test: property tests and fuzz targets for untrusted input and the diff engine
Every parser of data Xexéu does not control must return an error, never
panic; the diff engine's guarantees (no removal from a partial sweep, no
closed port that was not scanned, disappearance exactly at the threshold)
are now properties. The Weekly workflow runs cargo audit independently of
pushes and fuzzes each target on a persistent corpus.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 10:53:26 -03:00
Lucas RayanandClaude Opus 5.5 0d4fe01baf fix(tls): reject non-ASCII certificate validity times instead of panicking
parse_asn1_time_string sliced the time by byte offset, so a multi-byte
UTF-8 character in a hostile certificate put a boundary inside it and
panicked, aborting the sweep. Found by cargo fuzz.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 10:53:26 -03:00
46 changed files with 5936 additions and 1718 deletions

No files matched your search

+3
View File
@@ -9,3 +9,6 @@ XEXEU_PUBLISH=127.0.0.1:8788
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=
+61
View File
@@ -0,0 +1,61 @@
name: Weekly
# Checks that do not depend on a push: a new RustSec advisory can land on a
# dependency while the code stands still, and fuzzing finds more the longer
# its corpus grows. The corpus lives on the persistent runner volume, so every
# run starts where the last one stopped.
on:
schedule:
- cron: '17 6 * * 1'
workflow_dispatch:
concurrency:
group: weekly
cancel-in-progress: false
env:
CARGO_TERM_COLOR: always
CARGO_HOME: /opt/hostedtoolcache/cargo
RUSTUP_HOME: /opt/hostedtoolcache/rustup
jobs:
audit:
name: Dependency audit
runs-on: linux-arm64
steps:
- uses: actions/checkout@v7
- uses: dtolnay/rust-toolchain@stable
- name: cargo audit
run: |
command -v cargo-audit >/dev/null || cargo install cargo-audit --locked
cargo audit
fuzz:
name: Fuzz (${{ matrix.target }})
runs-on: linux-arm64
env:
CARGO_TARGET_DIR: /opt/hostedtoolcache/cargo-target/xexeu-fuzz
strategy:
fail-fast: false
max-parallel: 1
matrix:
target: [der_certificate, service_banner, vuln_feeds, operator_input]
steps:
- uses: actions/checkout@v7
- uses: dtolnay/rust-toolchain@nightly
- name: cargo-fuzz
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 }}
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
# with `cargo +nightly fuzz run <target> <file>` and turned into a test.
- name: Crash input
if: failure()
run: |
for f in fuzz/artifacts/${{ matrix.target }}/*; do
[ -f "$f" ] || continue
echo "== $f"; base64 -w0 "$f"; echo
done
+4
View File
@@ -8,3 +8,7 @@ __pycache__/
.DS_Store
/data
/config
/fuzz/target
/fuzz/corpus
/fuzz/artifacts
/fuzz/coverage
+22
View File
@@ -6,6 +6,28 @@ Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versio
## [Unreleased]
## [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.
- `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
- `GET /api/config` and the logs show webhook URLs reduced to `scheme://host/…`, since chat webhook URLs are credentials and reads are not authenticated.
## [1.1.0] - 2026-11-03
### Security
- A TLS certificate whose validity time held a multi-byte UTF-8 character crashed the parser (byte-offset slice inside a character), so a hostile host in scope could abort its sweep. Found by `cargo fuzz`; non-ASCII times are now rejected as an error.
### Added
- Property tests for every parser of untrusted input (certificates, banners, HTTP responses, NVD/KEV feeds, CPE, targets, cron) and for the diff engine's guarantees: no removal from a partial or aborted sweep, no closed port that was not scanned, disappearance exactly at the threshold, deterministic events, assets outside the swept scope untouched.
- `fuzz/`: cargo-fuzz targets for the same parsers.
- `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.
## [1.0.0] - 2026-11-03
### Security
+22
View File
@@ -6,6 +6,28 @@ Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/);
## [Não lançado]
## [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.
- `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
- O `GET /api/config` e os logs mostram as URLs de webhook reduzidas a `esquema://host/…`, já que URLs de webhook de chat são credenciais e as leituras não são autenticadas.
## [1.1.0] - 2026-11-03
### Segurança
- Um certificado TLS cuja data de validade tivesse um caractere UTF-8 de vários bytes derrubava o parser (corte por offset de byte no meio de um caractere), então um host hostil no escopo podia abortar a própria varredura. Encontrado pelo `cargo fuzz`; datas não ASCII agora são recusadas com erro.
### Adicionado
- Testes de propriedade para todos os parsers de entrada não confiável (certificados, banners, respostas HTTP, feeds NVD/KEV, CPE, alvos, cron) e para as garantias do motor de diff: nenhuma remoção a partir de varredura parcial ou abortada, nenhuma porta fechada que não foi varrida, desaparecimento exatamente no limite, eventos determinísticos, ativos fora do escopo varrido intocados.
- `fuzz/`: alvos de cargo-fuzz para os mesmos parsers.
- 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.
## [1.0.0] - 2026-11-03
### Segurança
+12
View File
@@ -22,6 +22,18 @@ scripts/check.sh
The interface source text is Portuguese. English translations reside in `apps/gui/ui/i18n-en.js` and are applied at runtime by `i18n.js`. When adding or updating visible text, run `node scripts/check-ui-i18n.mjs` and supply the English translation pair.
## 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/`.
For longer runs (nightly toolchain and `cargo install cargo-fuzz`):
```bash
cargo +nightly fuzz run der_certificate -- -max_total_time=300
```
The `Weekly` workflow fuzzes every target for ten minutes on a persistent corpus and runs `cargo audit`. A crash becomes a regression test before the fix.
## Documentation
Always maintain document pairs: every `*.md` and `docs/*` file has an English version and a Portuguese version (`*.pt-BR.md`, `docs/pt-BR/`). File names are translated only when the word changes (e.g. `architecture.md` → `arquitetura.md`).
+12
View File
@@ -22,6 +22,18 @@ scripts/check.sh
O texto original da interface é em português. O inglês reside em `apps/gui/ui/i18n-en.js`, aplicado em runtime por `i18n.js`. Ao adicionar texto visível, execute `node scripts/check-ui-i18n.mjs` e forneça o par correspondente em inglês.
## 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/`.
Para corridas longas (toolchain nightly e `cargo install cargo-fuzz`):
```bash
cargo +nightly fuzz run der_certificate -- -max_total_time=300
```
O workflow `Weekly` fuzza cada alvo por dez minutos sobre um corpus persistente e roda o `cargo audit`. Um crash vira teste de regressão antes da correção.
## Documentação
Mantenha sempre os pares: todo arquivo `*.md` e `docs/*` possui uma versão em inglês e uma em português (`*.pt-BR.md`, `docs/pt-BR/`). Nomes de arquivo são traduzidos apenas quando a palavra de fato muda (ex: `architecture.md` → `arquitetura.md`).
Generated
+157 -3
View File
@@ -240,6 +240,25 @@ version = "0.23.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
[[package]]
name = "bit-set"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c"
dependencies = [
"bit-vec",
]
[[package]]
name = "bit-vec"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5727b15fa97d4f4fee0a3b7c3d550ed0269f54329207b86388de918604e31269"
dependencies = [
"borsh",
"serde",
]
[[package]]
name = "bitflags"
version = "2.13.2"
@@ -255,6 +274,30 @@ dependencies = [
"generic-array",
]
[[package]]
name = "borsh"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a"
dependencies = [
"borsh-derive",
"bytes",
"cfg_aliases",
]
[[package]]
name = "borsh-derive"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56"
dependencies = [
"once_cell",
"proc-macro-crate",
"proc-macro2",
"quote",
"syn 3.0.9",
]
[[package]]
name = "bumpalo"
version = "3.20.3"
@@ -386,6 +429,12 @@ version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
[[package]]
name = "core_detect"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48"
[[package]]
name = "cpufeatures"
version = "0.2.17"
@@ -505,6 +554,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
"subtle",
]
[[package]]
@@ -707,6 +757,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"
@@ -1164,6 +1223,15 @@ dependencies = [
"zerovec",
]
[[package]]
name = "proc-macro-crate"
version = "3.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"
dependencies = [
"toml_edit",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
@@ -1173,6 +1241,32 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "proptest"
version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0"
dependencies = [
"bit-set",
"bit-vec",
"bitflags",
"chacha20",
"core_detect",
"num-traits",
"rand",
"rand_xorshift",
"regex-syntax",
"rusty-fork",
"tempfile",
"unarray",
]
[[package]]
name = "quick-error"
version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0"
[[package]]
name = "quinn"
version = "0.11.11"
@@ -1276,6 +1370,21 @@ dependencies = [
"rand_core",
]
[[package]]
name = "rand_xorshift"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf"
dependencies = [
"rand_core",
]
[[package]]
name = "regex-syntax"
version = "0.8.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
[[package]]
name = "reqwest"
version = "0.12.28"
@@ -1421,6 +1530,18 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
[[package]]
name = "rusty-fork"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2"
dependencies = [
"fnv",
"quick-error",
"tempfile",
"wait-timeout",
]
[[package]]
name = "ryu"
version = "1.0.23"
@@ -1677,7 +1798,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom 0.3.4",
"getrandom 0.4.3",
"once_cell",
"rustix",
"windows-sys 0.61.2",
@@ -1809,6 +1930,18 @@ dependencies = [
"serde_core",
]
[[package]]
name = "toml_edit"
version = "0.25.17+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c"
dependencies = [
"indexmap",
"toml_datetime",
"toml_parser",
"winnow",
]
[[package]]
name = "toml_parser"
version = "1.1.5+spec-1.1.0"
@@ -1919,6 +2052,12 @@ dependencies = [
"web-time",
]
[[package]]
name = "unarray"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94"
[[package]]
name = "unicode-ident"
version = "1.0.27"
@@ -1976,6 +2115,15 @@ version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "wait-timeout"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11"
dependencies = [
"libc",
]
[[package]]
name = "want"
version = "0.3.2"
@@ -2230,6 +2378,9 @@ name = "winnow"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"
dependencies = [
"memchr",
]
[[package]]
name = "wit-bindgen"
@@ -2245,12 +2396,13 @@ checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
[[package]]
name = "xexeu-cli"
version = "1.0.0"
version = "1.2.0"
dependencies = [
"axum",
"chrono",
"clap",
"libc",
"reqwest",
"serde",
"serde_json",
"tempfile",
@@ -2260,14 +2412,16 @@ dependencies = [
[[package]]
name = "xexeu-core"
version = "1.0.0"
version = "1.2.0"
dependencies = [
"arrow-array",
"arrow-schema",
"chrono",
"croner",
"hmac",
"ipnet",
"parquet",
"proptest",
"reqwest",
"rusqlite",
"rustls",
+1 -1
View File
@@ -3,7 +3,7 @@ resolver = "2"
members = ["crates/xexeu-core", "crates/xexeu-cli"]
[workspace.package]
version = "1.0.0"
version = "1.2.0"
edition = "2021"
license = "MIT OR Apache-2.0"
repository = "https://git.lucasrguerra.dev.br/ciberfauna/xexeu"
+3 -3
View File
@@ -134,9 +134,9 @@ Summary of the [ROADMAP](ROADMAP.md):
| | |
|---|---|
| **Done (1.0.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 |
| **Next** | Fuzzing and property tests, webhook alerts, Prometheus metrics |
| **Later** | `nmap` adapter and the `xexeu-scanner-nmap` variant, email alerts, OSV and distribution backport mapping |
| **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 |
| **Not planned** | Exploitation payloads, NASL engine, mandatory cloud services, desktop Tauri wrapper |
## License
+3 -3
View File
@@ -134,9 +134,9 @@ Resumo do [ROADMAP](ROADMAP.pt-BR.md):
| | |
|---|---|
| **Feito (1.0.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 |
| **Próximo** | Fuzzing e testes de propriedade, alertas por webhook, métricas Prometheus |
| **Depois** | Adaptador `nmap` e a variante `xexeu-scanner-nmap`, alertas por e-mail, OSV e mapeamento de backports de distribuição |
| **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 |
| **Não planejado** | Payloads de exploração, motor NASL, serviços de nuvem obrigatórios, wrapper desktop Tauri |
## Licença
+7 -9
View File
@@ -4,11 +4,12 @@
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.
## Done (1.0.0)
## Done
- **Admin token for configuration changes:** 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.
- **Design approval & specification:** formal design and task breakdown completed (`proposal.md`, `design.md`, `tasks.md`).
- **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.
- **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.
@@ -20,15 +21,12 @@ Xexéu does continuous attack-surface and vulnerability auditing: it sweeps auth
## Next
- **Robustness:** 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.
- **Alert notifications:** outbound webhooks for critical new findings or surface changes.
- **Prometheus metrics:** `/metrics` with sweep durations, host counts and feed age.
- **Distribution backport mapping:** automated detection of backported vulnerability fixes in Debian/Ubuntu packages, to reduce false positives in version-based CVE matching.
- **Email alerting:** the same events as the webhooks, delivered by SMTP.
## Later
- **`nmap` adapter & `xexeu-scanner-nmap` variant:** optional integration with the external `nmap` binary for richer service fingerprinting on profiles that opt in.
- **Email alerting:** the same events as the webhooks, delivered by SMTP.
- **Distribution backport mapping:** automated detection of backported vulnerability fixes in Debian/Ubuntu packages, to reduce false positives in version-based CVE matching.
- **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.
+7 -9
View File
@@ -4,11 +4,12 @@
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.
## Concluído (1.0.0)
## Concluído
- **Token de administração para mudanças de configuração:** 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.
- **Aprovação do design e especificação:** design formal e decomposição em tarefas concluídos (`proposal.md`, `design.md`, `tasks.md`).
- **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.
- **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.
@@ -20,15 +21,12 @@ O Xexéu faz auditoria contínua de superfície de ataque e de vulnerabilidades:
## Próximo
- **Robustez:** 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.
- **Notificações de alerta:** webhooks de saída para achados críticos novos ou mudanças na superfície.
- **Métricas Prometheus:** `/metrics` com duração das varreduras, contagem de hosts e idade dos feeds.
- **Mapeamento de backports de distribuições:** dedução automática de correções retroportadas em pacotes Debian/Ubuntu, pra reduzir falsos positivos na correlação de CVE por versão.
- **Alertas por e-mail:** os mesmos eventos dos webhooks, entregues por SMTP.
## 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.
- **Alertas por e-mail:** os mesmos eventos dos webhooks, entregues por SMTP.
- **Mapeamento de backports de distribuições:** dedução automática de correções retroportadas em pacotes Debian/Ubuntu, pra reduzir falsos positivos na correlação de CVE por versão.
- **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.
+1
View File
@@ -18,6 +18,7 @@ axum = "0.8"
chrono = { version = "0.4", features = ["clock"] }
clap = { version = "4", features = ["derive", "env"] }
libc = "0.2"
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "time", "sync"] }
+110
View File
@@ -0,0 +1,110 @@
//! `xexeu changes`, `xexeu doctor` and `xexeu export`.
use std::fs;
use std::path::Path;
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};
pub(crate) fn run_changes(since: &str, data_dir: &Path) -> ExitCode {
let db_path = data_dir.join("xexeu.db");
if !db_path.exists() {
return fail(&format!(
"banco de dados não encontrado em {}",
db_path.display()
));
}
let storage = match SqliteStorage::open(&db_path) {
Ok(s) => s,
Err(e) => return fail(&format!("falha ao abrir banco: {e}")),
};
let since_dt = parse_since(since);
match storage.events(since_dt) {
Ok(events) => match serde_json::to_string_pretty(&events) {
Ok(json) => {
println!("{json}");
ExitCode::SUCCESS
}
Err(e) => fail(&format!("falha ao serializar eventos: {e}")),
},
Err(e) => fail(&format!("falha ao consultar eventos: {e}")),
}
}
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);
if as_json {
match serde_json::to_string_pretty(&report) {
Ok(json) => println!("{json}"),
Err(error) => return fail(&format!("falha ao serializar o diagnóstico: {error}")),
}
} else {
print!("{}", report.render_table());
}
if report.ok {
ExitCode::SUCCESS
} else {
ExitCode::FAILURE
}
}
pub(crate) fn run_export(format: &str, data_dir: &Path, out_file: Option<&Path>) -> ExitCode {
let db_path = data_dir.join("xexeu.db");
let storage = match SqliteStorage::open(&db_path) {
Ok(s) => s,
Err(err) => {
return fail(&format!(
"falha ao abrir banco em {}: {err}",
db_path.display()
))
}
};
let state = match storage.load_state(&[]) {
Ok(s) => s,
Err(err) => return fail(&format!("falha ao carregar estado: {err}")),
};
let content = match format.to_ascii_lowercase().as_str() {
"json" => {
let dtos = current_state_to_dtos(&state);
match serde_json::to_string_pretty(&dtos) {
Ok(s) => s,
Err(err) => return fail(&format!("falha ao serializar JSON: {err}")),
}
}
"csv" => generate_hosts_csv(&state),
other => {
return fail(&format!(
"formato não suportado: '{other}' (use 'json' ou 'csv')"
))
}
};
if let Some(path) = out_file {
if let Some(parent) = path.parent() {
if !parent.as_os_str().is_empty() {
if let Err(e) = fs::create_dir_all(parent) {
return fail(&format!(
"falha ao criar diretório para {}: {e}",
path.display()
));
}
}
}
if let Err(e) = fs::write(path, &content) {
return fail(&format!(
"falha ao salvar export em {}: {e}",
path.display()
));
}
} else {
print!("{content}");
}
ExitCode::SUCCESS
}
+102
View File
@@ -0,0 +1,102 @@
//! `xexeu config check`: validation report, effective schedules and overlapping groups.
use std::collections::HashSet;
use std::net::IpAddr;
use std::path::Path;
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};
pub(crate) fn run_config_check(path: &Path) -> ExitCode {
let (config, report) = match validated_config(path) {
Ok(loaded) => loaded,
Err(message) => return fail(&message),
};
println!("Configuração válida: {}", path.display());
for group in &report.groups {
println!(
"grupo {}: {} endereço(s), {} nome(s), perfil {}, cron {}",
group.group, group.addresses, group.names, group.profile, group.cron
);
}
for warning in &report.warnings {
println!("aviso: grupo {}: {}", warning.group, warning.message);
}
let now = Utc::now();
match overlapping_ranges(&config) {
Ok(overlaps) if overlaps.is_empty() => {}
Ok(overlaps) => {
println!("\nSobreposições:");
for range in overlaps {
match effective_cadence(&config, range.start(), now) {
Ok(Some(cadence)) => println!(
" {} ({} endereço(s)): grupos [{}], efetivo {} a cada {}s, próxima {}",
range,
range.count(),
cadence.groups.join(", "),
cadence.effective_group,
cadence.interval_secs,
cadence.next_run.to_rfc3339()
),
Ok(None) => println!(
" {} ({} endereço(s)): nenhum grupo cobre a sobreposição",
range,
range.count()
),
Err(error) => {
println!(" {}: falha ao calcular a cadência efetiva: {error}", range)
}
}
}
}
Err(message) => return fail(&message),
}
ExitCode::SUCCESS
}
fn overlapping_ranges(config: &XexeuConfig) -> Result<Vec<IpRange>, String> {
let expansions = config
.groups
.iter()
.map(expand_group)
.collect::<Result<Vec<_>, _>>()
.map_err(|error| format!("falha ao expandir os grupos: {error}"))?;
let mut seen = HashSet::new();
let mut overlaps = Vec::new();
for (index, left_group) in expansions.iter().enumerate() {
for right_group in expansions.iter().skip(index + 1) {
for left in left_group.ranges() {
for right in right_group.ranges() {
let start = left.start().max(right.start());
let end = left.end().min(right.end());
if start > end {
continue;
}
if let Ok(range) = IpRange::new(start, end) {
if seen.insert(range.to_string()) {
overlaps.push(range);
}
}
}
}
}
}
overlaps.sort_by_key(|range| (range.start().is_ipv6(), ip_value(range.start())));
Ok(overlaps)
}
fn ip_value(address: IpAddr) -> u128 {
match address {
IpAddr::V4(ip) => u32::from(ip) as u128,
IpAddr::V6(ip) => u128::from(ip),
}
}
+147
View File
@@ -0,0 +1,147 @@
//! `xexeu feeds import` and `xexeu 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};
fn find_matching_file(dir: &Path, keyword: &str, ext: &str) -> Option<PathBuf> {
let entries = fs::read_dir(dir).ok()?;
for entry in entries.flatten() {
let path = entry.path();
if path.is_file() {
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
let lower = name.to_lowercase();
if lower.contains(keyword) && lower.ends_with(ext) {
return Some(path);
}
}
}
}
None
}
pub(crate) fn run_feeds_import(
directory: Option<PathBuf>,
nvd_path: Option<PathBuf>,
kev_path: Option<PathBuf>,
data_dir: &Path,
) -> ExitCode {
let nvd_file = nvd_path.or_else(|| {
directory.as_ref().map(|d| {
let direct = d.join("nvd.json");
if direct.exists() {
direct
} else {
find_matching_file(d, "nvd", "json").unwrap_or(direct)
}
})
});
let kev_file = kev_path.or_else(|| {
directory.as_ref().map(|d| {
let direct_json = d.join("kev.json");
if direct_json.exists() {
direct_json
} else {
let direct_csv = d.join("kev.csv");
if direct_csv.exists() {
direct_csv
} else {
find_matching_file(d, "kev", "json")
.or_else(|| find_matching_file(d, "kev", "csv"))
.unwrap_or(direct_json)
}
}
})
});
let nvd_file = match nvd_file {
Some(f) if f.exists() => f,
Some(f) => return fail(&format!("arquivo NVD não encontrado em: {}", f.display())),
None => return fail("informe o diretório com os feeds ou use --nvd <arquivo>"),
};
let nvd = match import_nvd(&nvd_file) {
Ok(c) => c,
Err(e) => return fail(&format!("falha ao importar feed NVD: {e}")),
};
let kev = if let Some(kf) = &kev_file {
if kf.exists() {
match import_kev(kf) {
Ok(c) => c,
Err(e) => return fail(&format!("falha ao importar feed CISA KEV: {e}")),
}
} else {
KevCatalog::default()
}
} else {
KevCatalog::default()
};
let db = VulnDatabase { nvd, kev };
let db_path = data_dir.join("vuln_db.json");
if let Err(e) = db.save_to_file(&db_path) {
return fail(&format!(
"falha ao salvar base de vulnerabilidades em {}: {e}",
db_path.display()
));
}
println!(
"Base de vulnerabilidades importada com sucesso: {} CVEs ({} no KEV) salvos em {}",
db.cve_count(),
db.kev_count(),
db_path.display()
);
ExitCode::SUCCESS
}
pub(crate) async fn run_feeds_sync(data_dir: &Path) -> ExitCode {
let db_path = data_dir.join("vuln_db.json");
let mut db = if db_path.exists() {
match VulnDatabase::load_from_file(&db_path) {
Ok(loaded) => loaded,
Err(e) => {
eprintln!(
"aviso: não foi possível carregar base anterior em {}: {e}; iniciando base nova",
db_path.display()
);
VulnDatabase::default()
}
}
} else {
VulnDatabase::default()
};
let sync_options = SyncOptions::default();
println!("Sincronizando feeds de vulnerabilidade (NVD e CISA KEV)...");
let downloaded = match sync_feeds(&sync_options).await {
Ok(d) => d,
Err(e) => {
eprintln!("falha na sincronização dos feeds: {e}");
return ExitCode::FAILURE;
}
};
db.merge(downloaded);
if let Err(e) = db.save_to_file(&db_path) {
return fail(&format!(
"falha ao salvar base atualizada em {}: {e}",
db_path.display()
));
}
println!(
"Sincronização de feeds concluída: {} CVEs totais ({} no KEV) gravados em {}",
db.cve_count(),
db.kev_count(),
db_path.display()
);
ExitCode::SUCCESS
}
File diff suppressed because it is too large. Load diff
+395
View File
@@ -0,0 +1,395 @@
//! `xexeu scanner` and `xexeu scan`: per-group sweeps written as batches.
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::net::IpAddr;
use std::path::{Path, PathBuf};
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::{
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;
struct ScanSummary {
batch: SweepBatch,
directory: PathBuf,
targets_count: usize,
alive_count: usize,
}
async fn execute_scan_for_group(
config: &XexeuConfig,
group_name: &str,
out: &Path,
data_dir: &Path,
) -> Result<ScanSummary, String> {
let group = config
.group(group_name)
.ok_or_else(|| format!("grupo '{group_name}' não existe na configuração"))?;
let expansion =
expand_group(group).map_err(|error| format!("grupo '{group_name}': {error}"))?;
let scope =
scope_ranges(&config.scope.authorized).map_err(|error| format!("escopo: {error}"))?;
let mut addresses: BTreeSet<IpAddr> = expansion.ips().collect();
for hostname in expansion.names() {
match resolve_name(hostname) {
Ok(resolved) => {
let (inside, outside) = filter_in_scope(&scope, &resolved);
for address in outside {
eprintln!(
"aviso: {hostname} resolve para {address}, fora do escopo autorizado; ignorado"
);
}
if inside.is_empty() {
eprintln!(
"aviso: {hostname} não resolve para nenhum endereço dentro do escopo autorizado"
);
}
addresses.extend(inside);
}
Err(error) => eprintln!("aviso: não foi possível resolver {hostname}: {error}"),
}
}
if addresses.is_empty() {
return Err("nenhum alvo dentro do escopo autorizado".to_string());
}
let profile_name = group.effective_profile(config);
let profile = config
.profiles
.get(profile_name)
.ok_or_else(|| format!("perfil '{profile_name}' não definido"))?;
if profile.engine != "nativo" && profile.engine != "nativo-sem-raw" {
return Err(format!(
"motor '{}' do perfil '{profile_name}' não implementado; use nativo",
profile.engine
));
}
let ports = PortTarget::parse(&profile.tcp)
.map_err(|error| format!("perfil '{profile_name}': {error}"))?
.to_ports();
if ports.is_empty() {
return Err(format!("perfil '{profile_name}' não seleciona portas TCP"));
}
let targets: Vec<IpAddr> = addresses.iter().copied().collect();
let concurrency = config.defaults.simultaneous_hosts.unwrap_or(16).max(1);
let started_at = Utc::now();
let hosts = discover_hosts_tcp(
&targets,
&DiscoveryConfig {
ports: DEFAULT_DISCOVERY_PORTS.to_vec(),
timeout: Duration::from_millis(600),
max_concurrency: concurrency,
},
)
.await;
let alive: Vec<IpAddr> = hosts
.iter()
.filter(|host| host.state == HostState::Alive)
.map(|host| host.ip)
.collect();
// `nativo` tries the raw-socket SYN engine first and only falls back to
// the unprivileged `nativo-sem-raw` TCP-connect engine when CAP_NET_RAW
// isn't actually usable (missing capability, or the raw socket fails to
// create for some other reason) — the engine mode actually used, not the
// one requested, is what gets recorded in the sweep manifest below, so an
// operator reading `/api/status` or the manifest never has to guess which
// mode really ran.
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() {
let syn_hosts = alive.clone();
let syn_ports = ports.clone();
let syn_config = SynScanConfig::default();
let syn_result = tokio::task::spawn_blocking(move || {
scan_hosts_syn(&syn_hosts, &syn_ports, &syn_config)
})
.await
.map_err(|error| format!("tarefa de varredura SYN falhou: {error}"))?;
match syn_result {
Ok(results) => (results, EngineMode::Native),
Err(error) => {
eprintln!(
"aviso: varredura SYN falhou ({error}), recorrendo ao modo nativo-sem-raw"
);
(
scan_hosts_tcp_connect(
&alive,
&ports,
&PortScanConfig {
timeout: Duration::from_millis(1200),
max_concurrency: concurrency.saturating_mul(4).max(16),
},
)
.await,
EngineMode::NativeWithoutRaw,
)
}
}
} else {
if wants_raw {
eprintln!(
"aviso: perfil '{profile_name}' pede o motor nativo, mas CAP_NET_RAW não está disponível; usando nativo-sem-raw"
);
}
(
scan_hosts_tcp_connect(
&alive,
&ports,
&PortScanConfig {
timeout: Duration::from_millis(1200),
max_concurrency: concurrency.saturating_mul(4).max(16),
},
)
.await,
EngineMode::NativeWithoutRaw,
)
};
let vuln_db = VulnDatabase::load_from_file(&data_dir.join("vuln_db.json")).unwrap_or_default();
let mut services = Vec::new();
for result in &port_results {
for port in &result.ports {
if port.state != PortState::Open {
continue;
}
let fp = fingerprint_service(result.ip, port.port, Duration::from_millis(1500)).await;
let mut findings = Vec::new();
let (product, version, cpe) = if let Some(info) = &fp.banner_info {
let mut matched = match_banner(info, &vuln_db);
findings.append(&mut matched);
(
Some(info.product_name.clone()),
info.version.clone(),
Some(info.cpe.to_cpe23()),
)
} else {
(None, None, None)
};
if let Some(der) = &fp.tls_cert_der {
if let Ok(Some(f)) = check_tls_certificate_der(der, None) {
findings.push(f);
}
}
if xexeu_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);
}
}
}
services.push(ServiceObservation {
ip: result.ip,
port: port.port,
product,
version,
cpe,
findings,
});
}
}
let mut manifest = SweepManifest::new(
group.name.clone(),
expansion.ranges().iter().map(ToString::to_string).collect(),
profile_name,
engine_used,
started_at,
);
manifest.finish(SweepStatus::Complete, Utc::now());
let batch = SweepBatch::new(manifest, hosts, port_results).with_services(services);
let directory = batch
.write(out)
.map_err(|error| format!("falha ao gravar o lote: {error}"))?;
Ok(ScanSummary {
targets_count: targets.len(),
alive_count: alive.len(),
batch,
directory,
})
}
pub(crate) async fn scan_once(
group: Option<String>,
once: bool,
config_path: &Path,
out: &Path,
data_dir: &Path,
) -> Result<(), String> {
if !once {
return Err("varredura contínua pertence ao comando scanner; use --once".to_string());
}
let name = group.ok_or_else(|| "informe o grupo com --group".to_string())?;
let (config, _report) = validated_config(config_path)?;
let summary = execute_scan_for_group(&config, &name, out, data_dir).await?;
let profile_name = summary.batch.manifest.profile.as_str();
println!(
"lote {} (grupo {}, perfil {}) gravado em {}",
summary.batch.manifest.sweep_id,
name,
profile_name,
summary.directory.display()
);
println!(
"alvos: {}; vivos: {}",
summary.targets_count, summary.alive_count
);
for result in &summary.batch.ports {
let open: Vec<String> = result
.ports
.iter()
.filter(|port| port.state == PortState::Open)
.map(|port| port.port.to_string())
.collect();
if !open.is_empty() {
println!(" {}: {}", result.ip, open.join(", "));
}
}
Ok(())
}
pub(crate) async fn run_scanner(
config_path: &Path,
out_dir: &Path,
data_dir: &Path,
) -> Result<(), String> {
let (mut config, _report) = validated_config(config_path)?;
fs::create_dir_all(out_dir)
.map_err(|error| format!("falha ao criar {}: {error}", out_dir.display()))?;
let mut histories: BTreeMap<String, RunHistory> = BTreeMap::new();
for group in &config.groups {
histories.insert(group.name.clone(), RunHistory::default());
}
println!(
"scanner contínuo iniciado com {} grupo(s) configurado(s)",
config.groups.len()
);
let tick_interval = std::env::var("XEXEU_SCANNER_TICK_SECS")
.ok()
.and_then(|val| val.parse().ok())
.map(Duration::from_secs)
.unwrap_or(Duration::from_secs(10));
let mut last_mtime = fs::metadata(config_path).and_then(|m| m.modified()).ok();
loop {
// Hot-reload configuration if file modified time changed
if let Ok(mtime) = fs::metadata(config_path).and_then(|m| m.modified()) {
if Some(mtime) != last_mtime {
last_mtime = Some(mtime);
match validated_config(config_path) {
Ok((new_config, _)) => {
println!(
"scanner: configuração recarregada com sucesso ({} grupos)",
new_config.groups.len()
);
let current_group_names: BTreeSet<String> =
new_config.groups.iter().map(|g| g.name.clone()).collect();
histories.retain(|name, _| current_group_names.contains(name));
for group in &new_config.groups {
histories.entry(group.name.clone()).or_default();
}
config = new_config;
}
Err(err) => {
eprintln!(
"aviso: configuração alterada em disco mas inválida ({err}); mantendo configuração anterior em memória"
);
}
}
}
}
let now = Utc::now();
for group in &config.groups {
let history = histories.entry(group.name.clone()).or_default();
match should_run_now(group, &config, now, history) {
Ok(RunDecision::Run) => {
history.running = true;
history.last_started = Some(now);
match execute_scan_for_group(&config, &group.name, out_dir, data_dir).await {
Ok(summary) => {
history.running = false;
history.last_finished = Some(Utc::now());
let open_count = summary
.batch
.ports
.iter()
.flat_map(|r| &r.ports)
.filter(|p| p.state == PortState::Open)
.count();
println!(
"[{}] grupo {}: {} alvo(s), {} vivo(s), {} porta(s) aberta(s) (lote {})",
Utc::now().to_rfc3339(),
group.name,
summary.targets_count,
summary.alive_count,
open_count,
summary.batch.manifest.sweep_id
);
}
Err(error) => {
history.running = false;
eprintln!("erro na varredura do grupo {}: {error}", group.name);
}
}
}
Ok(RunDecision::Deferred { .. }) => {
eprintln!(
"aviso: execução do grupo {} adiada (anterior ainda em andamento)",
group.name
);
}
Ok(RunDecision::Wait { .. }) => {}
Err(error) => {
eprintln!("erro no agendador para o grupo {}: {error}", group.name);
}
}
}
tokio::select! {
_ = shutdown_signal() => {
println!("scanner encerrado graciosamente");
break;
}
_ = tokio::time::sleep(tick_interval) => {}
}
}
Ok(())
}
+309
View File
@@ -0,0 +1,309 @@
//! JSON API and the executive report.
use std::sync::atomic::Ordering;
use super::export::{current_state_to_dtos, HostDto};
use super::ServerState;
use crate::parse_since;
use axum::extract::{Path as AxumPath, Query, State};
use axum::http::{header, StatusCode};
use axum::response::IntoResponse;
use axum::Json;
use chrono::Utc;
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 {
status: &'static str,
version: &'static str,
}
pub(crate) async fn health_handler() -> Json<HealthResponse> {
Json(HealthResponse {
status: "ok",
version: env!("CARGO_PKG_VERSION"),
})
}
#[derive(Serialize)]
pub(crate) struct StatusResponse {
status: &'static str,
version: &'static str,
config_path: String,
sweeps_ingested: usize,
feeds_cve_count: usize,
feeds_kev_count: usize,
feeds_last_sync: Option<String>,
groups: Vec<GroupScheduleDto>,
}
#[derive(Serialize)]
struct GroupScheduleDto {
group: String,
profile: String,
cron: String,
next_run: String,
}
pub(crate) async fn status_handler(State(state): State<ServerState>) -> Json<StatusResponse> {
let now = Utc::now();
let config = state.config.read().await;
let schedules = next_runs(&config, now).unwrap_or_default();
let groups = config
.groups
.iter()
.map(|group| {
let next_run = schedules
.iter()
.find(|s| s.group == group.name)
.map(|s| s.next_run.to_rfc3339())
.unwrap_or_default();
GroupScheduleDto {
group: group.name.clone(),
profile: group.effective_profile(&config).to_string(),
cron: group.effective_cron(&config).to_string(),
next_run,
}
})
.collect();
let (cve_count, kev_count) = {
let db = state.vuln_db.read().await;
(db.cve_count(), db.kev_count())
};
let last_sync = {
let sync = state.feeds_last_sync.read().await;
sync.map(|dt| dt.to_rfc3339())
};
Json(StatusResponse {
status: "ok",
version: env!("CARGO_PKG_VERSION"),
config_path: state.config_path.display().to_string(),
sweeps_ingested: state.sweeps_ingested.load(Ordering::SeqCst),
feeds_cve_count: cve_count,
feeds_kev_count: kev_count,
feeds_last_sync: last_sync,
groups,
})
}
pub(crate) async fn get_config_handler(State(state): State<ServerState>) -> Json<XexeuConfig> {
// Webhook URLs are credentials and reads are not authenticated.
let config = state.config.read().await;
Json(config.redacted())
}
pub(crate) async fn create_group_handler(
State(state): State<ServerState>,
Json(new_group): Json<GroupConfig>,
) -> Result<(StatusCode, Json<GroupConfig>), (StatusCode, String)> {
let group_name = new_group.name.trim().to_string();
if group_name.is_empty() {
return Err((
StatusCode::BAD_REQUEST,
"nome do grupo não pode ser vazio".to_string(),
));
}
// `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() {
return Err((
StatusCode::BAD_REQUEST,
format!(
"nome do grupo `{group_name}` inválido: use apenas letras, números, `-`, `_` ou `.`"
),
));
}
let mut config_guard = state.config.write().await;
let mut draft = config_guard.clone();
if draft.groups.iter().any(|g| g.name == group_name) {
return Err((
StatusCode::CONFLICT,
format!("grupo `{group_name}` já existe"),
));
}
draft.groups.push(new_group.clone());
if let Err(err) = draft.validate() {
return Err((
StatusCode::BAD_REQUEST,
format!("configuração inválida: {err}"),
));
}
draft.save_to_file(&state.config_path).map_err(|err| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("erro ao salvar configuração: {err}"),
)
})?;
*config_guard = draft;
Ok((StatusCode::CREATED, Json(new_group)))
}
pub(crate) async fn update_group_handler(
State(state): State<ServerState>,
AxumPath(group_name): AxumPath<String>,
Json(updated_group): Json<GroupConfig>,
) -> Result<Json<GroupConfig>, (StatusCode, String)> {
let mut config_guard = state.config.write().await;
let mut draft = config_guard.clone();
let pos = draft
.groups
.iter()
.position(|g| g.name == group_name)
.ok_or_else(|| {
(
StatusCode::NOT_FOUND,
format!("grupo `{group_name}` não encontrado"),
)
})?;
let new_name = updated_group.name.trim();
if new_name.is_empty() {
return Err((
StatusCode::BAD_REQUEST,
"nome do grupo não pode ser vazio".to_string(),
));
}
if xexeu_core::batch::safe_component(new_name).is_err() {
return Err((
StatusCode::BAD_REQUEST,
format!(
"nome do grupo `{new_name}` inválido: use apenas letras, números, `-`, `_` ou `.`"
),
));
}
if new_name != group_name && draft.groups.iter().any(|g| g.name == new_name) {
return Err((
StatusCode::CONFLICT,
format!("grupo `{new_name}` já existe"),
));
}
draft.groups[pos] = updated_group.clone();
if let Err(err) = draft.validate() {
return Err((
StatusCode::BAD_REQUEST,
format!("configuração inválida: {err}"),
));
}
draft.save_to_file(&state.config_path).map_err(|err| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("erro ao salvar configuração: {err}"),
)
})?;
*config_guard = draft;
Ok(Json(updated_group))
}
pub(crate) async fn delete_group_handler(
State(state): State<ServerState>,
AxumPath(group_name): AxumPath<String>,
) -> Result<StatusCode, (StatusCode, String)> {
let mut config_guard = state.config.write().await;
let mut draft = config_guard.clone();
if !draft.groups.iter().any(|g| g.name == group_name) {
return Err((
StatusCode::NOT_FOUND,
format!("grupo `{group_name}` não encontrado"),
));
}
if draft.groups.len() <= 1 {
return Err((
StatusCode::BAD_REQUEST,
"não é permitido remover o último grupo configurado".to_string(),
));
}
draft.groups.retain(|g| g.name != group_name);
if let Err(err) = draft.validate() {
return Err((
StatusCode::BAD_REQUEST,
format!("configuração inválida: {err}"),
));
}
draft.save_to_file(&state.config_path).map_err(|err| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("erro ao salvar configuração: {err}"),
)
})?;
*config_guard = draft;
Ok(StatusCode::OK)
}
pub(crate) async fn hosts_handler(
State(state): State<ServerState>,
) -> Result<Json<Vec<HostDto>>, (StatusCode, String)> {
let storage = state.storage.lock().await;
let current_state = storage.load_state(&[]).map_err(|error| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("erro ao consultar estado: {error}"),
)
})?;
let dtos = current_state_to_dtos(&current_state);
Ok(Json(dtos))
}
#[derive(Deserialize)]
pub(crate) struct ChangesQuery {
pub(crate) since: Option<String>,
}
pub(crate) async fn changes_handler(
State(state): State<ServerState>,
Query(query): Query<ChangesQuery>,
) -> Result<Json<Vec<xexeu_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| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("erro ao consultar eventos: {error}"),
)
})?;
Ok(Json(events))
}
pub(crate) async fn report_handler(
State(state): State<ServerState>,
) -> Result<impl IntoResponse, (StatusCode, String)> {
let config = state.config.read().await.clone();
let storage = state.storage.lock().await;
let current_state = storage.load_state(&[]).map_err(|error| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("erro ao consultar estado para relatório: {error}"),
)
})?;
let vuln_db = state.vuln_db.read().await.clone();
let last_sync = *state.feeds_last_sync.read().await;
let report = ExecutiveReport::build(&config, &current_state, &vuln_db, last_sync, Utc::now());
let html = report.render_html();
Ok(([(header::CONTENT_TYPE, "text/html; charset=utf-8")], html))
}
+73
View File
@@ -0,0 +1,73 @@
//! Dashboard files embedded in the binary.
use axum::http::header;
use axum::response::IntoResponse;
const INDEX_HTML: &str = include_str!("../../../../apps/gui/ui/index.html");
const APP_CSS: &str = include_str!("../../../../apps/gui/ui/app.css");
const APP_JS: &str = include_str!("../../../../apps/gui/ui/app.js");
const I18N_JS: &str = include_str!("../../../../apps/gui/ui/i18n.js");
const I18N_EN_JS: &str = include_str!("../../../../apps/gui/ui/i18n-en.js");
const PAGED_JS: &str = include_str!("../../../../apps/gui/ui/paged.polyfill.min.js");
const LOGO_PNG: &[u8] = include_bytes!("../../../../logo.png");
pub(crate) async fn index_handler() -> impl IntoResponse {
(
[(header::CONTENT_TYPE, "text/html; charset=utf-8")],
INDEX_HTML,
)
}
pub(crate) async fn css_handler() -> impl IntoResponse {
([(header::CONTENT_TYPE, "text/css; charset=utf-8")], APP_CSS)
}
pub(crate) async fn js_handler() -> impl IntoResponse {
(
[(
header::CONTENT_TYPE,
"application/javascript; charset=utf-8",
)],
APP_JS,
)
}
pub(crate) async fn i18n_js_handler() -> impl IntoResponse {
(
[(
header::CONTENT_TYPE,
"application/javascript; charset=utf-8",
)],
I18N_JS,
)
}
pub(crate) async fn i18n_en_js_handler() -> impl IntoResponse {
(
[(
header::CONTENT_TYPE,
"application/javascript; charset=utf-8",
)],
I18N_EN_JS,
)
}
pub(crate) async fn paged_js_handler() -> impl IntoResponse {
(
[(
header::CONTENT_TYPE,
"application/javascript; charset=utf-8",
)],
PAGED_JS,
)
}
pub(crate) async fn logo_handler() -> impl IntoResponse {
([(header::CONTENT_TYPE, "image/png")], LOGO_PNG)
}
+297
View File
@@ -0,0 +1,297 @@
//! CSV exports, shared with `xexeu export`.
use super::api::ChangesQuery;
use super::ServerState;
use crate::parse_since;
use axum::extract::{Query, State};
use axum::http::{header, HeaderMap, HeaderValue, StatusCode};
use axum::response::IntoResponse;
use chrono::Utc;
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
/// is interpreted as a formula by Excel/LibreOffice/Sheets when the export is
/// opened, which could execute attacker-influenced content (a CVE
/// description pulled from the NVD feed, or an operator-controlled config
/// value). Prefixing it with a single quote forces every spreadsheet
/// application to treat it as plain text, same as GitHub's and Google's own
/// CSV export sanitization.
fn csv_escape(s: &str) -> String {
let needs_formula_guard = s
.chars()
.next()
.is_some_and(|c| matches!(c, '=' | '+' | '-' | '@' | '\t'));
let s_owned;
let s = if needs_formula_guard {
s_owned = format!("'{s}");
&s_owned
} else {
s
};
if s.contains(',') || s.contains('"') || s.contains('\n') || s.contains('\r') {
let escaped = s.replace('"', "\"\"");
format!("\"{escaped}\"")
} else {
s.to_string()
}
}
#[derive(Serialize)]
pub(crate) struct HostDto {
asset_key: String,
network: String,
ip: String,
status: &'static str,
absences: u32,
first_seen: String,
last_seen: String,
ports: Vec<PortDto>,
}
#[derive(Serialize)]
struct PortDto {
protocol: String,
port: u16,
status: &'static str,
absences: u32,
first_seen: String,
last_seen: String,
product: Option<String>,
version: Option<String>,
cpe: Option<String>,
findings: Vec<Finding>,
}
pub(crate) fn current_state_to_dtos(current_state: &CurrentState) -> Vec<HostDto> {
current_state
.assets
.iter()
.map(|asset| HostDto {
asset_key: asset.asset_key.clone(),
network: asset.network.clone(),
ip: asset.ip.to_string(),
status: asset.status.as_str(),
absences: asset.absences,
first_seen: asset.first_seen.to_rfc3339(),
last_seen: asset.last_seen.to_rfc3339(),
ports: asset
.ports
.iter()
.map(|port| PortDto {
protocol: port.protocol.clone(),
port: port.port,
status: port.status.as_str(),
absences: port.absences,
first_seen: port.first_seen.to_rfc3339(),
last_seen: port.last_seen.to_rfc3339(),
product: port.product.clone(),
version: port.version.clone(),
cpe: port.cpe.clone(),
findings: port.findings.clone(),
})
.collect(),
})
.collect()
}
pub(crate) fn generate_hosts_csv(current_state: &CurrentState) -> String {
let mut csv = String::new();
csv.push_str("Endereço IP,Grupo,Status do Host,Protocolo,Porta,Status da Porta,Produto,Versão,CPE,Maior CVSS,Quantidade de Achados\r\n");
for asset in &current_state.assets {
if asset.ports.is_empty() {
let row = [
csv_escape(&asset.ip.to_string()),
csv_escape(&asset.network),
csv_escape(asset.status.as_str()),
String::new(),
String::new(),
String::new(),
String::new(),
String::new(),
String::new(),
String::new(),
"0".to_string(),
];
csv.push_str(&row.join(","));
csv.push_str("\r\n");
} else {
for port in &asset.ports {
let max_cvss = port
.findings
.iter()
.filter_map(|f| f.cvss)
.fold(None, |acc, v| Some(acc.map_or(v, |m: f32| m.max(v))));
let max_cvss_str = max_cvss.map(|c| format!("{c:.1}")).unwrap_or_default();
let findings_count = port.findings.len().to_string();
let row = [
csv_escape(&asset.ip.to_string()),
csv_escape(&asset.network),
csv_escape(asset.status.as_str()),
csv_escape(&port.protocol),
csv_escape(&port.port.to_string()),
csv_escape(port.status.as_str()),
csv_escape(port.product.as_deref().unwrap_or("")),
csv_escape(port.version.as_deref().unwrap_or("")),
csv_escape(port.cpe.as_deref().unwrap_or("")),
csv_escape(&max_cvss_str),
csv_escape(&findings_count),
];
csv.push_str(&row.join(","));
csv.push_str("\r\n");
}
}
}
csv
}
pub(crate) async fn export_hosts_csv_handler(
State(state): State<ServerState>,
) -> Result<impl IntoResponse, (StatusCode, String)> {
let storage = state.storage.lock().await;
let current_state = storage.load_state(&[]).map_err(|error| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("erro ao consultar estado: {error}"),
)
})?;
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 mut headers = HeaderMap::new();
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("text/csv; charset=utf-8"),
);
if let Ok(val) = HeaderValue::from_str(&disposition) {
headers.insert(header::CONTENT_DISPOSITION, val);
}
Ok((headers, csv))
}
pub(crate) async fn export_findings_csv_handler(
State(state): State<ServerState>,
) -> Result<impl IntoResponse, (StatusCode, String)> {
let storage = state.storage.lock().await;
let current_state = storage.load_state(&[]).map_err(|error| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("erro ao consultar estado: {error}"),
)
})?;
let mut csv = String::new();
csv.push_str("Endereço IP,Porta,CVE / ID,CVSS,No KEV,Confiança,Título,Descrição\r\n");
for asset in &current_state.assets {
for port in &asset.ports {
for finding in &port.findings {
let cvss_str = finding.cvss.map(|c| format!("{c:.1}")).unwrap_or_default();
let kev_str = if finding.kev { "Sim" } else { "Não" };
let confianca_str = match finding.confianca {
Confidence::Alto => "Alta",
Confidence::Medio => "Média",
Confidence::Baixo => "Baixa",
};
let row = [
csv_escape(&asset.ip.to_string()),
csv_escape(&port.port.to_string()),
csv_escape(&finding.id),
csv_escape(&cvss_str),
csv_escape(kev_str),
csv_escape(confianca_str),
csv_escape(&finding.title),
csv_escape(&finding.description),
];
csv.push_str(&row.join(","));
csv.push_str("\r\n");
}
}
}
let timestamp = Utc::now().format("%Y%m%d-%H%M%S");
let disposition = format!("attachment; filename=\"xexeu-findings-{timestamp}.csv\"");
let mut headers = HeaderMap::new();
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("text/csv; charset=utf-8"),
);
if let Ok(val) = HeaderValue::from_str(&disposition) {
headers.insert(header::CONTENT_DISPOSITION, val);
}
Ok((headers, csv))
}
pub(crate) async fn export_changes_csv_handler(
State(state): State<ServerState>,
Query(query): Query<ChangesQuery>,
) -> Result<impl IntoResponse, (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| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("erro ao consultar eventos: {error}"),
)
})?;
let mut csv = String::new();
csv.push_str("Data/Hora (UTC),Tipo de Evento,Alvo / Host,Grupo,Detalhe\r\n");
for event in &events {
let tipo_str = match event.kind {
EventKind::HostNew => "Novo Host",
EventKind::HostReturned => "Host Retornado",
EventKind::HostDisappeared => "Host Sumido",
EventKind::PortNew => "Nova Porta Aberta",
EventKind::PortClosed => "Porta Fechada",
EventKind::ServiceChanged => "Serviço Alterado",
};
let detail = if let Some(svc) = &event.service {
if let (Some(prev), Some(curr)) = (&event.previous, &event.current) {
format!("{}/{}: {} -> {}", svc.protocol, svc.port, prev, curr)
} else {
format!("{}/{}", svc.protocol, svc.port)
}
} else if !event.evidence.is_null() && event.evidence != serde_json::json!({}) {
event.evidence.to_string()
} else {
String::new()
};
let row = [
csv_escape(&event.occurred_at.to_rfc3339()),
csv_escape(tipo_str),
csv_escape(&event.asset_key),
csv_escape(&event.group),
csv_escape(&detail),
];
csv.push_str(&row.join(","));
csv.push_str("\r\n");
}
let timestamp = Utc::now().format("%Y%m%d-%H%M%S");
let disposition = format!("attachment; filename=\"xexeu-changes-{timestamp}.csv\"");
let mut headers = HeaderMap::new();
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("text/csv; charset=utf-8"),
);
if let Ok(val) = HeaderValue::from_str(&disposition) {
headers.insert(header::CONTENT_DISPOSITION, val);
}
Ok((headers, csv))
}
+323
View File
@@ -0,0 +1,323 @@
//! `/metrics` in the Prometheus text format, and the webhook deliveries that
//! feed some of its counters.
use std::collections::BTreeMap;
use std::fmt::Write as _;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::Duration;
use axum::extract::State;
use axum::http::{header, StatusCode};
use axum::response::IntoResponse;
use chrono::{DateTime, Utc};
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;
/// Last ingested sweep of a group.
struct SweepStat {
finished_at: DateTime<Utc>,
duration_secs: f64,
complete: bool,
events: usize,
}
#[derive(Default)]
pub(crate) struct Metrics {
webhook_ok: AtomicU64,
webhook_failed: AtomicU64,
sweeps: Mutex<BTreeMap<String, SweepStat>>,
}
impl Metrics {
pub(crate) async fn record_sweep(&self, manifest: &SweepManifest, events: usize) {
let finished_at = manifest.finished_at.unwrap_or(manifest.started_at);
let duration_secs = (finished_at - manifest.started_at)
.num_milliseconds()
.max(0) as f64
/ 1000.0;
self.sweeps.lock().await.insert(
manifest.group.clone(),
SweepStat {
finished_at,
duration_secs,
complete: manifest.status == xexeu_core::batch::SweepStatus::Complete,
events,
},
);
}
}
/// 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>,
metrics: &Arc<Metrics>,
client: &reqwest::Client,
manifest: &SweepManifest,
events: &[Event],
) {
let webhooks = config.read().await.webhooks.clone();
for webhook in webhooks {
let selected = alert::select_events(&webhook, &manifest.group, events);
if selected.is_empty() {
continue;
}
let body = alert::render(
webhook.format,
&manifest.group,
manifest.sweep_id,
&selected,
);
let key = webhook
.secret_env
.as_deref()
.and_then(|name| std::env::var(name).ok())
.filter(|key| !key.is_empty());
if webhook.secret_env.is_some() && key.is_none() {
eprintln!(
"aviso: webhook {} pede assinatura, mas a variável {} está vazia; enviando sem assinar",
webhook.redacted_url(),
webhook.secret_env.as_deref().unwrap_or_default()
);
}
let (metrics, client, count) = (Arc::clone(metrics), client.clone(), selected.len());
tokio::spawn(async move {
let key = key.as_deref().map(str::as_bytes);
match alert::deliver(&client, &webhook.url, &body, key, Duration::from_secs(2)).await {
Ok(()) => {
metrics.webhook_ok.fetch_add(1, Ordering::Relaxed);
println!(
"webhook {}: {count} evento(s) enviados",
webhook.redacted_url()
);
}
Err(error) => {
metrics.webhook_failed.fetch_add(1, Ordering::Relaxed);
eprintln!(
"aviso: webhook {} falhou após {} tentativas: {error}",
webhook.redacted_url(),
alert::MAX_ATTEMPTS
);
}
}
});
}
}
/// Label value with `\`, `"` and newlines escaped.
fn label(value: &str) -> String {
value
.replace('\\', "\\\\")
.replace('"', "\\\"")
.replace('\n', "\\n")
}
fn metric(out: &mut String, name: &str, kind: &str, help: &str, samples: &[(String, f64)]) {
let _ = writeln!(out, "# HELP {name} {help}");
let _ = writeln!(out, "# TYPE {name} {kind}");
for (labels, value) in samples {
let _ = writeln!(out, "{name}{labels} {value}");
}
}
fn severity(cvss: Option<f32>) -> &'static str {
match cvss {
Some(score) if score >= 9.0 => "critica",
Some(score) if score >= 7.0 => "alta",
Some(score) if score >= 4.0 => "media",
Some(score) if score > 0.0 => "baixa",
_ => "sem_cvss",
}
}
pub(crate) async fn metrics_handler(State(state): State<ServerState>) -> impl IntoResponse {
let current = match state.storage.lock().await.load_state(&[]) {
Ok(current) => current,
Err(error) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
[(header::CONTENT_TYPE, "text/plain; charset=utf-8")],
format!("falha ao carregar estado: {error}"),
)
}
};
let (mut active, mut gone, mut open_ports, mut kev) = (0u64, 0u64, 0u64, 0u64);
let mut findings: BTreeMap<&str, u64> = ["critica", "alta", "media", "baixa", "sem_cvss"]
.into_iter()
.map(|level| (level, 0))
.collect();
for asset in &current.assets {
match asset.status {
AssetStatus::Active => active += 1,
AssetStatus::Gone => gone += 1,
}
for port in asset
.ports
.iter()
.filter(|port| port.status == PortStatus::Open)
{
open_ports += 1;
for finding in &port.findings {
*findings.entry(severity(finding.cvss)).or_default() += 1;
kev += u64::from(finding.kev);
}
}
}
let mut out = String::new();
metric(
&mut out,
"xexeu_build_info",
"gauge",
"Running Xexéu version.",
&[(
format!("{{version=\"{}\"}}", env!("CARGO_PKG_VERSION")),
1.0,
)],
);
metric(
&mut out,
"xexeu_sweeps_ingested_total",
"counter",
"Sweep batches ingested since start.",
&[(
String::new(),
state.sweeps_ingested.load(Ordering::SeqCst) as f64,
)],
);
metric(
&mut out,
"xexeu_assets",
"gauge",
"Known hosts by status.",
&[
("{status=\"ativo\"}".into(), active as f64),
("{status=\"sumido\"}".into(), gone as f64),
],
);
metric(
&mut out,
"xexeu_open_ports",
"gauge",
"Open ports on known hosts.",
&[(String::new(), open_ports as f64)],
);
metric(
&mut out,
"xexeu_findings",
"gauge",
"Findings on open ports by CVSS severity.",
&findings
.iter()
.map(|(level, count)| (format!("{{severidade=\"{level}\"}}"), *count as f64))
.collect::<Vec<_>>(),
);
metric(
&mut out,
"xexeu_kev_findings",
"gauge",
"Findings listed in CISA KEV.",
&[(String::new(), kev as f64)],
);
let (cves, kev_entries) = {
let db = state.vuln_db.read().await;
(db.cve_count(), db.kev_count())
};
metric(
&mut out,
"xexeu_vuln_db_cves",
"gauge",
"CVEs in the local database.",
&[(String::new(), cves as f64)],
);
metric(
&mut out,
"xexeu_vuln_db_kev",
"gauge",
"KEV entries in the local database.",
&[(String::new(), kev_entries as f64)],
);
if let Some(last_sync) = *state.feeds_last_sync.read().await {
metric(
&mut out,
"xexeu_feeds_last_sync_timestamp_seconds",
"gauge",
"Unix time of the last successful feed sync.",
&[(String::new(), last_sync.timestamp() as f64)],
);
}
let sweeps = state.metrics.sweeps.lock().await;
let per_group = |value: &dyn Fn(&SweepStat) -> f64| -> Vec<(String, f64)> {
sweeps
.iter()
.map(|(group, stat)| (format!("{{grupo=\"{}\"}}", label(group)), value(stat)))
.collect()
};
if !sweeps.is_empty() {
metric(
&mut out,
"xexeu_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",
"gauge",
"Duration of the group's last ingested sweep.",
&per_group(&|stat| stat.duration_secs),
);
metric(
&mut out,
"xexeu_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",
"gauge",
"Surface changes found by the group's last sweep.",
&per_group(&|stat| stat.events as f64),
);
}
drop(sweeps);
metric(
&mut out,
"xexeu_webhook_deliveries_total",
"counter",
"Webhook deliveries by result.",
&[
(
"{resultado=\"ok\"}".into(),
state.metrics.webhook_ok.load(Ordering::Relaxed) as f64,
),
(
"{resultado=\"falha\"}".into(),
state.metrics.webhook_failed.load(Ordering::Relaxed) as f64,
),
],
);
(
StatusCode::OK,
[(
header::CONTENT_TYPE,
"text/plain; version=0.0.4; charset=utf-8",
)],
out,
)
}
+386
View File
@@ -0,0 +1,386 @@
//! `xexeu serve`: background batch ingestion, feed sync and the HTTP server.
mod api;
mod assets;
pub(crate) mod export;
mod metrics;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::Duration;
use crate::{auth, validated_config};
use api::{
changes_handler, create_group_handler, delete_group_handler, get_config_handler,
health_handler, hosts_handler, report_handler, status_handler, update_group_handler,
};
use assets::{
css_handler, i18n_en_js_handler, i18n_js_handler, index_handler, js_handler, logo_handler,
paged_js_handler,
};
use axum::Router;
use chrono::{DateTime, Utc};
use export::{export_changes_csv_handler, export_findings_csv_handler, export_hosts_csv_handler};
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();
let group_entries = match fs::read_dir(sweeps_dir) {
Ok(entries) => entries,
Err(_) => return manifests,
};
for group_entry in group_entries.flatten() {
if !group_entry.path().is_dir() {
continue;
}
let sweep_entries = match fs::read_dir(group_entry.path()) {
Ok(entries) => entries,
Err(_) => continue,
};
for sweep_entry in sweep_entries.flatten() {
let sweep_path = sweep_entry.path();
if sweep_path.is_dir() && sweep_path.join("manifest.json").exists() {
manifests.push(sweep_path);
}
}
}
// Lexicographical sorting by ULID directory name orders sweeps chronologically.
manifests.sort();
manifests
}
async fn poll_sweeps(
sweeps_dir: PathBuf,
storage: Arc<Mutex<SqliteStorage>>,
sweeps_ingested: Arc<AtomicUsize>,
config: Arc<RwLock<XexeuConfig>>,
metrics: Arc<Metrics>,
) {
let client = reqwest::Client::new();
loop {
let manifests = find_sweep_manifests(&sweeps_dir);
for sweep_path in manifests {
match SweepBatch::read(&sweep_path) {
Ok(batch) => {
let mut storage_guard = storage.lock().await;
match storage_guard.load_state(&[]) {
Ok(current_state) => {
match diff_batch(&current_state, &batch, &DiffOptions::default()) {
Ok(diff) => match storage_guard.ingest(&batch, &diff) {
Ok(true) => {
sweeps_ingested.fetch_add(1, Ordering::SeqCst);
println!(
"lote {} (grupo {}) ingerido com sucesso ({} eventos)",
batch.manifest.sweep_id,
batch.manifest.group,
diff.events.len()
);
metrics
.record_sweep(&batch.manifest, diff.events.len())
.await;
notify(
&config,
&metrics,
&client,
&batch.manifest,
&diff.events,
)
.await;
}
Ok(false) => {
// Sweep already recorded.
}
Err(err) => {
eprintln!(
"aviso: falha ao ingerir lote {}: {err}",
sweep_path.display()
);
}
},
Err(err) => {
eprintln!(
"aviso: falha ao calcular diff de {}: {err}",
sweep_path.display()
);
}
}
}
Err(err) => {
eprintln!("aviso: falha ao carregar estado do banco: {err}");
}
}
}
Err(err) => {
eprintln!(
"aviso: falha ao ler lote em {}: {err}",
sweep_path.display()
);
}
}
}
tokio::time::sleep(Duration::from_millis(1500)).await;
}
}
#[derive(Clone)]
pub(crate) struct ServerState {
config: Arc<RwLock<XexeuConfig>>,
config_path: PathBuf,
storage: Arc<Mutex<SqliteStorage>>,
sweeps_ingested: Arc<AtomicUsize>,
vuln_db: Arc<RwLock<VulnDatabase>>,
feeds_last_sync: Arc<RwLock<Option<DateTime<Utc>>>>,
metrics: Arc<Metrics>,
}
fn parse_duration_str(raw: &str) -> Option<Duration> {
let raw = raw.trim();
if raw.len() > 1 {
let (num_str, unit) = raw.split_at(raw.len() - 1);
if let Ok(n) = num_str.parse::<u64>() {
match unit {
"s" => return Some(Duration::from_secs(n)),
"m" => return Some(Duration::from_secs(n * 60)),
"h" => return Some(Duration::from_secs(n * 3600)),
"d" => return Some(Duration::from_secs(n * 86400)),
_ => {}
}
}
}
None
}
pub(crate) async fn run_serve(
bind: &str,
config_path: &Path,
sweeps_dir: &Path,
data_dir: &Path,
admin_token: Option<&str>,
) -> Result<(), String> {
let (config, _report) = validated_config(config_path)?;
// An empty XEXEU_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",
auth::MIN_TOKEN_LEN
))
}
None => (
auth::AdminToken::generate()
.map_err(|error| format!("falha ao gerar token de administração: {error}"))?,
true,
),
};
fs::create_dir_all(sweeps_dir)
.map_err(|error| format!("falha ao criar {}: {error}", sweeps_dir.display()))?;
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 storage = SqliteStorage::open(&db_path).map_err(|error| {
format!(
"falha ao abrir banco de dados em {}: {error}",
db_path.display()
)
})?;
let shared_storage = Arc::new(Mutex::new(storage));
let sweeps_ingested = Arc::new(AtomicUsize::new(0));
// Load initial vulnerability database if present on disk
let vuln_db_path = data_dir.join("vuln_db.json");
let (initial_db, last_sync) = if vuln_db_path.exists() {
match VulnDatabase::load_from_file(&vuln_db_path) {
Ok(db) => {
println!(
"Base de vulnerabilidades carregada: {} CVEs ({} no KEV)",
db.cve_count(),
db.kev_count()
);
(db, None)
}
Err(err) => {
eprintln!(
"aviso: falha ao carregar {}: {err}; iniciando base vazia",
vuln_db_path.display()
);
(VulnDatabase::default(), None)
}
}
} else {
(VulnDatabase::default(), None)
};
let shared_vuln_db = Arc::new(RwLock::new(initial_db));
let shared_last_sync = Arc::new(RwLock::new(last_sync));
let auto_sync = config.defaults.feeds.auto_sync;
let interval_str = config.defaults.feeds.sync_interval.clone();
let shared_config = Arc::new(RwLock::new(config));
let shared_metrics = Arc::new(Metrics::default());
// Spawn background poller for incoming sweeps.
let poller_storage = Arc::clone(&shared_storage);
let poller_ingested = Arc::clone(&sweeps_ingested);
let poller_sweeps = sweeps_dir.to_path_buf();
let poller_config = Arc::clone(&shared_config);
let poller_metrics = Arc::clone(&shared_metrics);
tokio::spawn(async move {
poll_sweeps(
poller_sweeps,
poller_storage,
poller_ingested,
poller_config,
poller_metrics,
)
.await;
});
// Spawn periodic background sync if auto_sync is enabled in config
if auto_sync {
let timer_db = Arc::clone(&shared_vuln_db);
let timer_last_sync = Arc::clone(&shared_last_sync);
let timer_db_path = vuln_db_path.clone();
tokio::spawn(async move {
let interval = parse_duration_str(&interval_str).unwrap_or(Duration::from_secs(86400));
println!("Sincronizador automático de feeds ativo (intervalo: {interval_str})");
loop {
tokio::time::sleep(interval).await;
println!("Iniciando sincronização periódica de feeds de vulnerabilidade...");
let sync_opts = SyncOptions::default();
match sync_feeds(&sync_opts).await {
Ok(downloaded) => {
let mut db_guard = timer_db.write().await;
db_guard.merge(downloaded);
if let Err(e) = db_guard.save_to_file(&timer_db_path) {
eprintln!(
"aviso: falha ao salvar base de vulnerabilidades atualizada: {e}"
);
}
let mut sync_guard = timer_last_sync.write().await;
*sync_guard = Some(Utc::now());
println!(
"Feeds sincronizados periodicamente com sucesso ({} CVEs)",
db_guard.cve_count()
);
}
Err(e) => {
eprintln!("aviso: falha na sincronização periódica de feeds: {e}");
}
}
}
});
}
let state = ServerState {
config: shared_config,
config_path: config_path.to_path_buf(),
storage: shared_storage,
sweeps_ingested,
vuln_db: shared_vuln_db,
feeds_last_sync: shared_last_sync,
metrics: shared_metrics,
};
let app = Router::new()
.route("/metrics", axum::routing::get(metrics_handler))
.route("/api/health", axum::routing::get(health_handler))
.route("/api/status", axum::routing::get(status_handler))
.route("/api/hosts", axum::routing::get(hosts_handler))
.route("/api/changes", axum::routing::get(changes_handler))
.route("/api/config", axum::routing::get(get_config_handler))
.route(
"/api/config/groups",
axum::routing::post(create_group_handler),
)
.route(
"/api/config/groups/{nome}",
axum::routing::put(update_group_handler).delete(delete_group_handler),
)
.route(
"/api/export/hosts.csv",
axum::routing::get(export_hosts_csv_handler),
)
.route(
"/api/export/findings.csv",
axum::routing::get(export_findings_csv_handler),
)
.route(
"/api/export/changes.csv",
axum::routing::get(export_changes_csv_handler),
)
.route("/relatorio", axum::routing::get(report_handler))
.route("/report", axum::routing::get(report_handler))
.route("/", axum::routing::get(index_handler))
.route("/dashboard", axum::routing::get(index_handler))
.route("/app.css", axum::routing::get(css_handler))
.route("/app.js", axum::routing::get(js_handler))
.route("/i18n.js", axum::routing::get(i18n_js_handler))
.route("/i18n-en.js", axum::routing::get(i18n_en_js_handler))
.route("/paged.polyfill.js", axum::routing::get(paged_js_handler))
.route("/logo.png", axum::routing::get(logo_handler))
.with_state(state)
.layer(axum::middleware::from_fn_with_state(
admin_token.clone(),
auth::require_admin,
));
let listener = tokio::net::TcpListener::bind(bind)
.await
.map_err(|error| format!("falha ao vincular endereço {bind}: {error}"))?;
let local_addr = listener
.local_addr()
.map_err(|error| format!("falha ao obter endereço local: {error}"))?;
println!("Xexéu listening on http://{local_addr}");
if token_generated {
println!(
"Token de administração gerado nesta execução (defina XEXEU_ADMIN_TOKEN para fixá-lo): \
http://{local_addr}/?token={}",
admin_token.as_str()
);
}
axum::serve(listener, app)
.with_graceful_shutdown(shutdown_signal())
.await
.map_err(|error| format!("erro no servidor HTTP: {error}"))?;
Ok(())
}
pub(crate) async fn shutdown_signal() {
let ctrl_c = async {
tokio::signal::ctrl_c()
.await
.expect("falha ao registrar listener de Ctrl+C");
};
#[cfg(unix)]
let terminate = async {
match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
Ok(mut signal) => signal.recv().await,
Err(_) => std::future::pending::<Option<()>>().await,
};
};
#[cfg(not(unix))]
let terminate = std::future::pending::<()>();
tokio::select! {
_ = ctrl_c => {},
_ = terminate => {},
}
}
@@ -0,0 +1,224 @@
use std::fs;
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::process::{Command, Stdio};
use std::sync::mpsc;
use std::time::{Duration, Instant};
use tempfile::TempDir;
struct ChildGuard(std::process::Child);
impl Drop for ChildGuard {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
const WEBHOOK_KEY: &str = "e2e-webhook-signing-key";
fn http_get(addr: &str, path: &str) -> (u16, String) {
let mut stream = TcpStream::connect(addr).expect("connect to server");
stream
.set_read_timeout(Some(Duration::from_secs(3)))
.expect("set read timeout");
let request = format!("GET {path} HTTP/1.1\r\nHost: {addr}\r\nConnection: close\r\n\r\n");
stream.write_all(request.as_bytes()).expect("write request");
let mut response = String::new();
stream.read_to_string(&mut response).expect("read response");
let code = response
.lines()
.next()
.and_then(|line| line.split_whitespace().nth(1))
.and_then(|code| code.parse().ok())
.unwrap_or(0);
let body = response.split("\r\n\r\n").nth(1).unwrap_or("").to_string();
(code, body)
}
/// Accepts one POST, answers 200 and hands over its headers (lowercased) and body.
fn webhook_receiver() -> (u16, mpsc::Receiver<(String, Vec<u8>)>) {
let listener = TcpListener::bind("127.0.0.1:0").expect("bind webhook receiver");
let port = listener.local_addr().expect("receiver address").port();
let (sender, receiver) = mpsc::channel();
std::thread::spawn(move || {
for stream in listener.incoming() {
let Ok(stream) = stream else { break };
let mut reader = BufReader::new(stream);
let mut headers = String::new();
loop {
let mut line = String::new();
if reader.read_line(&mut line).unwrap_or(0) == 0 || line == "\r\n" {
break;
}
headers.push_str(&line.to_ascii_lowercase());
}
let length = headers
.lines()
.find_map(|line| line.strip_prefix("content-length:"))
.and_then(|value| value.trim().parse().ok())
.unwrap_or(0);
let mut body = vec![0; length];
reader.read_exact(&mut body).expect("read webhook body");
let mut stream = reader.into_inner();
let _ = stream
.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
let _ = sender.send((headers, body));
}
});
(port, receiver)
}
#[test]
fn ingested_sweep_triggers_signed_webhook_and_updates_metrics() {
// Something to find: one open port on loopback.
let target = TcpListener::bind("127.0.0.1:0").expect("bind target");
let target_port = target.local_addr().expect("target address").port();
std::thread::spawn(move || for _ in target.incoming() {});
let (hook_port, deliveries) = webhook_receiver();
// Nothing listens here: deliveries fail and must be counted, not crash anything.
let dead_port = TcpListener::bind("127.0.0.1:0")
.expect("reserve a port")
.local_addr()
.expect("reserved address")
.port();
let workspace = TempDir::new().expect("temporary directory");
let config_path = workspace.path().join("xexeu.toml");
let sweeps_dir = workspace.path().join("sweeps");
let data_dir = workspace.path().join("data");
fs::write(
&config_path,
format!(
r#"
[escopo]
autorizado = ["127.0.0.1/32"]
[padrao]
cron = "@daily"
[perfis.padrao]
tcp = "{target_port}"
[[grupo]]
nome = "local"
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"
[[webhook]]
url = "http://127.0.0.1:{dead_port}/down"
formato = "slack"
"#
),
)
.expect("write configuration");
let mut child = Command::new(env!("CARGO_BIN_EXE_xexeu"))
.args([
"serve",
"--bind",
"127.0.0.1:0",
"--config",
config_path.to_str().expect("config path"),
"--sweeps",
sweeps_dir.to_str().expect("sweeps path"),
"--data-dir",
data_dir.to_str().expect("data dir"),
])
.env("XEXEU_E2E_WEBHOOK_KEY", WEBHOOK_KEY)
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()
.expect("spawn xexeu serve");
let mut reader = BufReader::new(child.stdout.take().expect("take stdout"));
let _guard = ChildGuard(child);
let mut addr = None;
let mut line = String::new();
while reader.read_line(&mut line).unwrap_or(0) > 0 {
if let Some(rest) = line.split("listening on http://").nth(1) {
addr = Some(rest.trim().to_string());
break;
}
line.clear();
}
let addr = addr.expect("server must print its address");
std::thread::spawn(move || for _ in reader.lines() {});
// The API never shows the webhook URL's path: chat webhook URLs are credentials.
let (status, body) = http_get(&addr, "/api/config");
assert_eq!(status, 200);
assert!(
body.contains(&format!("http://127.0.0.1:{hook_port}/…")),
"{body}"
);
assert!(!body.contains("secret-path"), "{body}");
let scan = Command::new(env!("CARGO_BIN_EXE_xexeu"))
.args([
"scan",
"--group",
"local",
"--once",
"--config",
config_path.to_str().expect("config path"),
"--out",
sweeps_dir.to_str().expect("sweeps path"),
])
.output()
.expect("run xexeu scan");
assert!(
scan.status.success(),
"{}",
String::from_utf8_lossy(&scan.stderr)
);
let (headers, body) = deliveries
.recv_timeout(Duration::from_secs(15))
.expect("the webhook receives the sweep's changes");
let payload: serde_json::Value = serde_json::from_slice(&body).expect("JSON body");
assert_eq!(payload["grupo"], "local");
let events = payload["eventos"].as_array().expect("events array");
assert!(!events.is_empty());
assert!(
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);
assert!(
headers.contains(&format!("x-xexeu-signature: {expected}")),
"signature header in: {headers}"
);
// The dead receiver is retried (2 s, then 4 s) before it counts as a failure.
let deadline = Instant::now() + Duration::from_secs(20);
let metrics = loop {
let (status, body) = http_get(&addr, "/metrics");
assert_eq!(status, 200);
if body.contains("xexeu_webhook_deliveries_total{resultado=\"falha\"} 1")
|| Instant::now() > deadline
{
break body;
}
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",
] {
assert!(
metrics.contains(expected),
"missing `{expected}` in:\n{metrics}"
);
}
}
+4
View File
@@ -22,9 +22,13 @@ tokio-rustls = { version = "0.26", default-features = false, features = ["ring"]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sha2 = "0.10"
hmac = "0.12"
socket2 = { version = "0.5", features = ["all"] }
tempfile = "3"
thiserror = "1"
ulid = { version = "3", features = ["serde"] }
toml = "1"
tokio = { version = "1", features = ["io-util", "macros", "net", "rt", "rt-multi-thread", "sync", "time"] }
[dev-dependencies]
proptest = "1"
+265
View File
@@ -0,0 +1,265 @@
//! 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
//! Discord. With `segredo_env`, the body is signed with HMAC-SHA256 in
//! `X-Xexeu-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.
use std::time::Duration;
use hmac::{Hmac, Mac};
use serde_json::{json, Value};
use sha2::Sha256;
use ulid::Ulid;
use crate::config::{WebhookConfig, WebhookFormat};
use crate::diff::Event;
/// Signature header, `sha256=<hex>` of the body.
pub const SIGNATURE_HEADER: &str = "X-Xexeu-Signature";
/// Attempts per delivery, including the first.
pub const MAX_ATTEMPTS: u32 = 3;
const REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
/// Discord rejects longer messages.
const DISCORD_LIMIT: usize = 2000;
/// Lines listed in a chat message before summarizing the rest.
const CHAT_LINES: usize = 20;
/// Events from a sweep of `group` that `webhook` subscribed to.
pub fn select_events<'a>(
webhook: &WebhookConfig,
group: &str,
events: &'a [Event],
) -> Vec<&'a Event> {
if !webhook.groups.is_empty() && !webhook.groups.iter().any(|name| name == group) {
return Vec::new();
}
events
.iter()
.filter(|event| {
webhook.events.is_empty()
|| webhook
.events
.iter()
.any(|kind| kind == event.kind.as_str())
})
.collect()
}
fn event_line(event: &Event) -> String {
let ip = event
.asset_key
.rsplit('/')
.next()
.unwrap_or(&event.asset_key);
match &event.service {
Some(service) => format!(
"{} {ip} {}/{}",
event.kind.as_str(),
service.protocol,
service.port
),
None => format!("{} {ip}", event.kind.as_str()),
}
}
fn chat_text(group: &str, events: &[&Event]) -> String {
let mut text = format!(
"Xexéu: {} mudança(s) na superfície do grupo {group}",
events.len()
);
for event in events.iter().take(CHAT_LINES) {
text.push_str("\n• ");
text.push_str(&event_line(event));
}
if events.len() > CHAT_LINES {
text.push_str(&format!("\n… e mais {}", events.len() - CHAT_LINES));
}
text
}
/// Request body for `format`.
pub fn render(format: WebhookFormat, group: &str, sweep_id: Ulid, events: &[&Event]) -> Value {
match format {
WebhookFormat::Json => json!({
"fonte": "xexeu",
"versao": env!("CARGO_PKG_VERSION"),
"grupo": group,
"sweep_id": sweep_id,
"eventos": events,
}),
WebhookFormat::Slack => json!({ "text": chat_text(group, events) }),
WebhookFormat::Discord => {
let mut text = chat_text(group, events);
if text.chars().count() > DISCORD_LIMIT {
text = text.chars().take(DISCORD_LIMIT - 1).collect::<String>() + "…";
}
json!({ "content": text })
}
}
}
/// `sha256=<hex>` HMAC of `body` under `key`.
pub fn sign(key: &[u8], body: &[u8]) -> String {
let mut mac = Hmac::<Sha256>::new_from_slice(key).expect("HMAC accepts keys of any length");
mac.update(body);
let digest = mac.finalize().into_bytes();
let hex: String = digest.iter().map(|byte| format!("{byte:02x}")).collect();
format!("sha256={hex}")
}
/// Whether a failed attempt is worth repeating.
fn retryable(status: reqwest::StatusCode) -> bool {
status.is_server_error() || status == reqwest::StatusCode::TOO_MANY_REQUESTS
}
/// POSTs `body` to `url`, retrying network errors, 5xx and 429 with backoff.
/// `backoff` is the wait before the second attempt; it doubles after that.
pub async fn deliver(
client: &reqwest::Client,
url: &str,
body: &Value,
key: Option<&[u8]>,
backoff: Duration,
) -> Result<(), String> {
let payload = serde_json::to_vec(body).map_err(|error| error.to_string())?;
let signature = key.map(|key| sign(key, &payload));
let mut wait = backoff;
let mut last_error = String::new();
for attempt in 1..=MAX_ATTEMPTS {
let mut request = client
.post(url)
.timeout(REQUEST_TIMEOUT)
.header(reqwest::header::CONTENT_TYPE, "application/json")
.header(
reqwest::header::USER_AGENT,
concat!("xexeu/", env!("CARGO_PKG_VERSION")),
)
.body(payload.clone());
if let Some(signature) = &signature {
request = request.header(SIGNATURE_HEADER, signature);
}
match request.send().await {
Ok(response) if response.status().is_success() => return Ok(()),
Ok(response) => {
last_error = format!("HTTP {}", response.status());
if !retryable(response.status()) {
break;
}
}
// Never echo the URL: chat webhook URLs are credentials.
Err(error) => last_error = error.without_url().to_string(),
}
if attempt < MAX_ATTEMPTS {
tokio::time::sleep(wait).await;
wait *= 2;
}
}
Err(last_error)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::diff::{EventKind, EventService};
use chrono::DateTime;
fn event(kind: EventKind, ip: &str, port: Option<u16>) -> Event {
Event {
event_id: Ulid::nil(),
sweep_id: Ulid::nil(),
group: "dmz".into(),
kind,
asset_key: format!("dmz/{ip}"),
service: port.map(|port| EventService {
protocol: "tcp".into(),
port,
product: None,
version: None,
cpe: None,
}),
previous: None,
current: None,
evidence: json!({}),
occurred_at: DateTime::from_timestamp(1_700_000_000, 0).unwrap(),
}
}
fn webhook(events: &[&str], groups: &[&str]) -> WebhookConfig {
WebhookConfig {
url: "https://hooks.example/abc".into(),
format: WebhookFormat::Json,
events: events.iter().map(|s| s.to_string()).collect(),
groups: groups.iter().map(|s| s.to_string()).collect(),
secret_env: None,
}
}
#[test]
fn filters_by_kind_and_group() {
let events = vec![
event(EventKind::HostNew, "10.0.0.5", None),
event(EventKind::PortNew, "10.0.0.5", Some(22)),
];
assert_eq!(select_events(&webhook(&[], &[]), "dmz", &events).len(), 2);
let only_ports = select_events(&webhook(&["porta_nova"], &[]), "dmz", &events);
assert_eq!(only_ports.len(), 1);
assert_eq!(only_ports[0].kind, EventKind::PortNew);
assert!(select_events(&webhook(&[], &["lan"]), "dmz", &events).is_empty());
assert_eq!(
select_events(&webhook(&[], &["lan", "dmz"]), "dmz", &events).len(),
2
);
}
#[test]
fn renders_each_format() {
let events = [event(EventKind::PortNew, "10.0.0.5", Some(22))];
let refs: Vec<&Event> = events.iter().collect();
let body = render(WebhookFormat::Json, "dmz", Ulid::nil(), &refs);
assert_eq!(body["grupo"], "dmz");
assert_eq!(body["eventos"][0]["tipo"], "porta_nova");
let slack = render(WebhookFormat::Slack, "dmz", Ulid::nil(), &refs);
assert!(slack["text"]
.as_str()
.unwrap()
.contains("porta_nova 10.0.0.5 tcp/22"));
let discord = render(WebhookFormat::Discord, "dmz", Ulid::nil(), &refs);
assert!(discord["content"]
.as_str()
.unwrap()
.starts_with("Xexéu: 1 mudança(s)"));
}
#[test]
fn long_chat_messages_are_summarized_and_fit_discord() {
let events: Vec<Event> = (0..500)
.map(|i| {
event(
EventKind::HostNew,
&format!("10.0.{}.{}", i / 250, i % 250),
None,
)
})
.collect();
let refs: Vec<&Event> = events.iter().collect();
let text = render(WebhookFormat::Slack, "dmz", Ulid::nil(), &refs)["text"]
.as_str()
.unwrap()
.to_string();
assert!(text.ends_with("… e mais 480"));
let discord = render(WebhookFormat::Discord, "dmz", Ulid::nil(), &refs);
assert!(discord["content"].as_str().unwrap().chars().count() <= DISCORD_LIMIT);
}
#[test]
fn signature_matches_rfc_4231_test_case_2() {
assert_eq!(
sign(b"Jefe", b"what do ya want for nothing?"),
"sha256=5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"
);
}
}
+199
View File
@@ -29,6 +29,114 @@ pub struct XexeuConfig {
/// Target groups.
#[serde(rename = "grupo", default)]
pub groups: Vec<GroupConfig>,
/// `[[webhook]]`: where surface changes are posted after each ingested sweep.
#[serde(rename = "webhook", default, skip_serializing_if = "Vec::is_empty")]
pub webhooks: Vec<WebhookConfig>,
}
/// Body shape a webhook receiver expects.
#[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.
#[default]
Json,
/// Slack incoming webhook (`{"text": ...}`); also Mattermost and Rocket.Chat.
Slack,
/// Discord webhook (`{"content": ...}`).
Discord,
}
/// `[[webhook]]`: one receiver of surface changes.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WebhookConfig {
/// `http(s)://` endpoint. Chat webhook URLs are credentials, so the API
/// only ever shows them redacted.
pub url: String,
#[serde(rename = "formato", default)]
pub format: WebhookFormat,
/// Event kinds to send (`host_novo`, `host_voltou`, `host_sumiu`,
/// `porta_nova`, `porta_fechada`, `servico_alterado`); empty means all.
#[serde(rename = "eventos", default, skip_serializing_if = "Vec::is_empty")]
pub events: Vec<String>,
/// Groups whose sweeps are sent; empty means all.
#[serde(rename = "grupos", default, skip_serializing_if = "Vec::is_empty")]
pub groups: Vec<String>,
/// Name of the environment variable holding the HMAC-SHA256 key; the key
/// itself never goes in the file.
#[serde(
rename = "segredo_env",
default,
skip_serializing_if = "Option::is_none"
)]
pub secret_env: Option<String>,
}
/// Event kinds a webhook can subscribe to.
pub const WEBHOOK_EVENTS: [&str; 6] = [
"host_novo",
"host_voltou",
"host_sumiu",
"porta_nova",
"porta_fechada",
"servico_alterado",
];
impl WebhookConfig {
/// URL safe to show: scheme and host only.
pub fn redacted_url(&self) -> String {
match self.url.split_once("://") {
Some((scheme, rest)) => {
let host = rest.split(['/', '?', '#']).next().unwrap_or("");
let host = host.rsplit('@').next().unwrap_or(host);
format!("{scheme}://{host}/…")
}
None => "…".to_string(),
}
}
fn validate(&self, index: usize, groups: &[GroupConfig]) -> Result<(), ConfigError> {
let invalid = |reason: String| ConfigError::InvalidWebhook { index, reason };
let Some((scheme, rest)) = self.url.split_once("://") else {
return Err(invalid(
"url precisa começar com http:// ou https://".into(),
));
};
if !matches!(scheme, "http" | "https") || rest.split('/').next().unwrap_or("").is_empty() {
return Err(invalid(
"url precisa começar com http:// ou https:// e ter host".into(),
));
}
if let Some(kind) = self
.events
.iter()
.find(|kind| !WEBHOOK_EVENTS.contains(&kind.as_str()))
{
return Err(invalid(format!(
"evento desconhecido `{kind}` (use: {})",
WEBHOOK_EVENTS.join(", ")
)));
}
if let Some(group) = self
.groups
.iter()
.find(|name| !groups.iter().any(|group| &group.name == *name))
{
return Err(invalid(format!("grupo desconhecido `{group}`")));
}
if let Some(name) = &self.secret_env {
let valid = !name.is_empty()
&& name
.chars()
.all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_');
if !valid {
return Err(invalid(format!(
"segredo_env `{name}` não é um nome de variável de ambiente (A-Z, 0-9, _)"
)));
}
}
Ok(())
}
}
/// `[escopo]`: what the operator is allowed to touch.
@@ -277,6 +385,14 @@ pub enum ConfigError {
/// Prefix length supplied.
prefix: u8,
},
/// A `[[webhook]]` entry is invalid.
#[error("webhook na posição {index} inválido: {reason}")]
InvalidWebhook {
/// Zero-based position in the document.
index: usize,
/// What is wrong with it.
reason: String,
},
/// I/O error reading or writing configuration.
#[error("erro de E/S na configuração: {0}")]
Io(String),
@@ -472,8 +588,21 @@ impl XexeuConfig {
});
}
for (index, webhook) in self.webhooks.iter().enumerate() {
webhook.validate(index, &self.groups)?;
}
Ok(report)
}
/// Copy safe to serve over the API: webhook URLs reduced to scheme and host.
pub fn redacted(&self) -> Self {
let mut copy = self.clone();
for webhook in &mut copy.webhooks {
webhook.url = webhook.redacted_url();
}
copy
}
}
fn scope_error(error: TargetError) -> ConfigError {
@@ -831,4 +960,74 @@ criticidade = "alta"
XexeuConfig::load_validated(&file_content).expect("from disk validates");
assert_eq!(config, from_disk);
}
const WEBHOOK_BASE: &str = r#"
[escopo]
autorizado = ["10.0.0.0/24"]
[perfis.padrao]
[[grupo]]
nome = "dmz"
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()
}
#[test]
fn webhooks_are_validated() {
assert!(with_webhook(r#"url = "https://hooks.example/T0/B0/x""#).is_ok());
assert!(with_webhook(
r#"url = "http://10.0.0.9:8080/in"
formato = "discord"
eventos = ["porta_nova", "host_sumiu"]
grupos = ["dmz"]
segredo_env = "XEXEU_WEBHOOK_KEY""#
)
.is_ok());
for bad in [
r#"url = "ftp://hooks.example/x""#,
r#"url = "hooks.example/x""#,
r#"url = "https:///x""#,
r#"url = "https://h.example/x"
eventos = ["porta_aberta"]"#,
r#"url = "https://h.example/x"
grupos = ["lan"]"#,
r#"url = "https://h.example/x"
segredo_env = "minha chave""#,
] {
assert!(
matches!(
with_webhook(bad),
Err(ConfigError::InvalidWebhook { index: 0, .. })
),
"{bad}"
);
}
assert!(matches!(
with_webhook(
r#"url = "https://h.example/x"
formato = "teams""#
),
Err(ConfigError::Toml { .. })
));
}
#[test]
fn redacted_config_hides_webhook_paths_and_credentials() {
let config = XexeuConfig::from_toml_str(&format!(
"{WEBHOOK_BASE}\n[[webhook]]\nurl = \"https://user:pw@hooks.slack.example/services/T0/B0/secret?x=1\"\n"
))
.unwrap();
let redacted = config.redacted();
assert_eq!(redacted.webhooks[0].url, "https://hooks.slack.example/…");
assert!(
config.webhooks[0].url.contains("secret"),
"the original is untouched"
);
let text = config.to_toml_string().unwrap();
assert!(text.contains("secret"), "saving keeps the real URL");
}
}
+170
View File
@@ -1043,4 +1043,174 @@ mod tests {
let findings = [1_u8, 2, 3];
assert!(diff_vulnerabilities(&findings, &findings).is_empty());
}
// Property tests for the guarantees in the module docs, over generated
// previous states and sweeps inside 203.0.113.0/28.
mod properties {
use super::*;
use proptest::prelude::*;
const SCOPE: &str = "203.0.113.0/28";
fn host_ip(index: u8) -> IpAddr {
IpAddr::from([203, 0, 113, index % 16])
}
fn previous_state() -> impl Strategy<Value = CurrentState> {
prop::collection::btree_map(
0u8..16,
(0u32..3, prop::collection::btree_set(1u16..40, 0..4)),
0..8,
)
.prop_map(|hosts| {
CurrentState::new(
hosts
.into_iter()
.map(|(index, (absences, ports))| {
asset(
&host_ip(index).to_string(),
absences,
ports.into_iter().map(open_port).collect(),
)
})
.collect(),
)
})
}
fn host_state() -> impl Strategy<Value = HostState> {
prop_oneof![Just(HostState::Alive), Just(HostState::Unresponsive)]
}
fn port_state() -> impl Strategy<Value = PortState> {
prop_oneof![
Just(PortState::Open),
Just(PortState::Closed),
Just(PortState::Filtered)
]
}
/// Hosts observed by a sweep and, for each, the ports it scanned.
type Observed = Vec<(u8, HostState, Vec<(u16, PortState)>)>;
fn observed() -> impl Strategy<Value = Observed> {
prop::collection::btree_map(
0u8..16,
(
host_state(),
prop::collection::btree_map(1u16..40, port_state(), 0..5),
),
0..10,
)
.prop_map(|hosts| {
hosts
.into_iter()
.map(|(index, (state, ports))| (index, state, ports.into_iter().collect()))
.collect()
})
}
fn sweep(status: SweepStatus, observed: &Observed) -> SweepBatch {
batch(
status,
&[SCOPE],
observed
.iter()
.map(|(index, state, _)| (host_ip(*index), *state))
.collect(),
observed
.iter()
.filter(|(_, state, _)| *state == HostState::Alive)
.map(|(index, _, ports)| (host_ip(*index), ports.clone()))
.collect(),
vec![],
)
}
fn is_removal(kind: EventKind) -> bool {
matches!(kind, EventKind::HostDisappeared | EventKind::PortClosed)
}
proptest! {
#[test]
fn partial_or_aborted_sweeps_never_remove_anything(
previous in previous_state(),
observed in observed(),
aborted in any::<bool>(),
threshold in 1u32..4,
) {
let status = if aborted { SweepStatus::Aborted } else { SweepStatus::Partial };
let options = DiffOptions { absences_before_disappear: threshold };
let result = diff_batch(&previous, &sweep(status, &observed), &options).unwrap();
prop_assert!(result.events.iter().all(|event| !is_removal(event.kind)));
}
#[test]
fn a_port_is_closed_only_if_the_sweep_scanned_it(
previous in previous_state(),
observed in observed(),
threshold in 1u32..4,
) {
let options = DiffOptions { absences_before_disappear: threshold };
let result = diff_batch(&previous, &sweep(SweepStatus::Complete, &observed), &options).unwrap();
for event in result.events.iter().filter(|event| event.kind == EventKind::PortClosed) {
let port = event.service.as_ref().expect("port events carry the service").port;
let scanned = observed.iter().any(|(index, state, ports)| {
event.asset_key == format!("dmz/{}", host_ip(*index))
&& *state == HostState::Alive
&& ports.iter().any(|(scanned, _)| *scanned == port)
});
prop_assert!(scanned, "{} closed port {port} it never scanned", event.asset_key);
}
}
#[test]
fn the_same_inputs_give_the_same_events(
previous in previous_state(),
observed in observed(),
) {
let batch = sweep(SweepStatus::Complete, &observed);
let options = DiffOptions::default();
let summary = |result: DiffResult| {
result
.events
.into_iter()
.map(|event| (event.kind, event.asset_key, event.service.map(|s| s.port)))
.collect::<Vec<_>>()
};
let first = summary(diff_batch(&previous, &batch, &options).unwrap());
let second = summary(diff_batch(&previous, &batch, &options).unwrap());
prop_assert_eq!(first, second);
}
#[test]
fn a_silent_host_disappears_exactly_at_the_threshold(threshold in 1u32..5) {
let options = DiffOptions { absences_before_disappear: threshold };
let silent: Observed = vec![(5, HostState::Unresponsive, vec![])];
let mut state = CurrentState::new(vec![asset("203.0.113.5", 0, vec![open_port(22)])]);
for round in 1..=threshold + 2 {
let result = diff_batch(&state, &sweep(SweepStatus::Complete, &silent), &options).unwrap();
let gone = result.events.iter().filter(|e| e.kind == EventKind::HostDisappeared).count();
prop_assert_eq!(gone, usize::from(round == threshold), "round {}", round);
state = CurrentState::new(result.state);
}
}
#[test]
fn assets_outside_the_swept_scope_are_untouched(
observed in observed(),
absences in 0u32..3,
) {
let outside = asset("198.51.100.7", absences, vec![open_port(443)]);
let previous = CurrentState::new(vec![outside.clone()]);
let result = diff_batch(&previous, &sweep(SweepStatus::Complete, &observed), &DiffOptions::default()).unwrap();
prop_assert!(result.events.iter().all(|event| event.asset_key != outside.asset_key));
// `state` holds the assets the sweep covered (storage upserts it), so an
// asset outside the scope is either left out or passed through unchanged.
if let Some(kept) = result.state.iter().find(|asset| asset.asset_key == outside.asset_key) {
prop_assert_eq!(kept, &outside);
}
}
}
}
}
+1
View File
@@ -1,6 +1,7 @@
//! Xexéu core: configuration, scheduling, scanning, vulnerability correlation,
//! storage and diffing for continuous attack-surface auditing.
pub mod alert;
pub mod batch;
pub mod caps;
pub mod config;
+2 -1
View File
@@ -73,7 +73,8 @@ impl ServerCertVerifier for CertCaptureVerifier {
}
}
fn extract_server_header(response: &str) -> Option<String> {
/// Value of the `Server:` header in a raw HTTP response, if any.
pub fn extract_server_header(response: &str) -> Option<String> {
for line in response.lines() {
let trimmed = line.trim();
if trimmed.is_empty() {
+5
View File
@@ -200,6 +200,11 @@ fn read_der_len(data: &[u8], offset: usize) -> Result<(usize, usize), String> {
}
fn parse_asn1_time_string(s: &str, is_utc: bool) -> Result<DateTime<Utc>, String> {
// The fields below are sliced by byte offset; a multi-byte character from a
// hostile certificate would put a slice boundary inside it and panic.
if !s.is_ascii() {
return Err(format!("ASN.1 time is not ASCII: '{s}'"));
}
let clean = s.trim_end_matches('Z');
if is_utc {
// YYMMDDHHMMSS
@@ -0,0 +1,7 @@
# Seeds for failure cases proptest has generated in the past. It is
# automatically read and these particular cases re-run before any
# novel cases are generated.
#
# It is recommended to check this file in to source control so that
# everyone who runs the test benefits from these saved cases.
cc db1aea305a4a09f7917f604c37fb8b18b04241a9a8101a9e7083a6634fae4848 # shrinks to serial = [0], filler = [], not_after = [226, 130, 172, 195, 169, 45, 90, 45, 45, 195, 169, 226, 130, 172, 48, 90], utc = false, flips = [], cut = Index(0)
+204
View File
@@ -0,0 +1,204 @@
//! Parsers that read data Xexéu 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.
//!
//! These run on stable with every `cargo test`; `fuzz/` drives the same entry
//! points with cargo-fuzz for longer runs.
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::{
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;
/// DER TLV with a definite length, short or long form.
fn tlv(tag: u8, body: &[u8]) -> Vec<u8> {
let mut out = vec![tag];
let len = body.len();
if len < 0x80 {
out.push(len as u8);
} else {
let bytes: Vec<u8> = len
.to_be_bytes()
.iter()
.copied()
.skip_while(|b| *b == 0)
.collect();
out.push(0x80 | bytes.len() as u8);
out.extend(bytes);
}
out.extend_from_slice(body);
out
}
/// A certificate skeleton shaped like the parser expects, with arbitrary contents.
fn certificate(serial: &[u8], filler: &[u8], not_after: &[u8], utc: bool) -> Vec<u8> {
let time_tag = if utc { 0x17 } else { 0x18 };
let validity = [tlv(time_tag, b"240101000000Z"), tlv(time_tag, not_after)].concat();
let tbs = [
tlv(0xA0, &tlv(0x02, &[2])),
tlv(0x02, serial),
tlv(0x30, filler),
tlv(0x30, filler),
tlv(0x30, &validity),
]
.concat();
tlv(0x30, &tlv(0x30, &tbs))
}
fn addr(low: u16) -> IpAddr {
IpAddr::from([10, 0, (low >> 8) as u8, low as u8])
}
fn range((start, len): (u16, u16)) -> IpRange {
IpRange::new(addr(start), addr(start.saturating_add(len))).expect("start <= end")
}
/// Found by `cargo fuzz run der_certificate`: a validity time with a multi-byte
/// UTF-8 character used to panic on a byte-offset slice.
#[test]
fn non_ascii_validity_is_rejected() {
for (stamp, utc) in [("20240ţ0101000000Z", false), ("2401ţ0100000Z", true)] {
let der = certificate(&[1], b"x", stamp.as_bytes(), utc);
assert!(parse_x509_der_not_after(&der).is_err(), "{stamp}");
}
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(512))]
#[test]
fn der_parser_never_panics_on_bytes(bytes in prop::collection::vec(any::<u8>(), 0..512)) {
let _ = parse_x509_der_not_after(&bytes);
}
#[test]
fn der_parser_never_panics_on_corrupted_certificates(
serial in prop::collection::vec(any::<u8>(), 1..24),
filler in prop::collection::vec(any::<u8>(), 0..300),
not_after in prop_oneof![
prop::collection::vec(any::<u8>(), 0..24),
"[0-9ţé€Z.+-]{10,20}".prop_map(String::into_bytes),
],
utc in any::<bool>(),
flips in prop::collection::vec((any::<prop::sample::Index>(), any::<u8>()), 0..4),
cut in any::<prop::sample::Index>(),
) {
let mut der = certificate(&serial, &filler, &not_after, utc);
let _ = parse_x509_der_not_after(&der);
for (index, byte) in flips {
let at = index.index(der.len());
der[at] = byte;
}
let _ = parse_x509_der_not_after(&der);
let _ = parse_x509_der_not_after(&der[..cut.index(der.len() + 1)]);
}
#[test]
fn well_formed_validity_is_read_back(
year in 50u32..150,
month in 1u32..13,
day in 1u32..29,
hour in 0u32..24,
) {
let (stamp, utc) = if year < 100 {
(format!("{year:02}{month:02}{day:02}{hour:02}0000Z"), true)
} else {
(format!("{}{month:02}{day:02}{hour:02}0000Z", 1900 + year), false)
};
let der = certificate(&[1], b"x", stamp.as_bytes(), utc);
prop_assert!(parse_x509_der_not_after(&der).is_ok(), "{}", stamp);
}
#[test]
fn banner_and_http_parsers_never_panic(text in ".{0,300}", port in any::<u16>()) {
let _ = parse_banner_to_cpe(&text);
let _ = extract_server_header(&text);
let _ = evaluate_http_admin_response(port, &text);
}
#[test]
fn banner_parser_never_panics_on_service_like_text(
product in "(SSH-2\\.0-OpenSSH|Apache|nginx|Microsoft-IIS|lighttpd|vsFTPd)[_/ -]?",
version in "[0-9a-z.p_-]{0,20}",
tail in "[ -~]{0,40}",
) {
let _ = parse_banner_to_cpe(&format!("{product}{version}{tail}"));
let _ = extract_server_header(&format!(
"HTTP/1.1 200 OK\r\nServer: {product}{version}{tail}\r\n\r\n"
));
}
#[test]
fn feed_parsers_never_panic(
bytes in prop::collection::vec(any::<u8>(), 0..1024),
text in ".{0,400}",
) {
let _ = parse_nvd_json(Cursor::new(&bytes));
let _ = parse_kev_reader(Cursor::new(&bytes));
let _ = parse_nvd_json(Cursor::new(text.as_bytes()));
let _ = parse_kev_reader(Cursor::new(text.as_bytes()));
let _ = Cpe::parse(&text);
}
#[test]
fn cpe_parser_never_panics_on_cpe_like_text(
parts in prop::collection::vec("[a-z0-9_.*\\\\:-]{0,12}", 0..14),
) {
let _ = Cpe::parse(&format!("cpe:2.3:{}", parts.join(":")));
let _ = Cpe::parse(&format!("cpe:/{}", parts.join(":")));
}
#[test]
fn operator_input_parsers_never_panic(text in ".{0,80}", like in "[0-9a-f.:/ -]{0,48}") {
for input in [&text, &like] {
let _ = parse_target(input);
let _ = parse_exclusion(input);
let _ = parse_scope_entry(input);
let _ = CronSpec::parse(input);
let _ = Jitter::parse(input);
}
}
#[test]
fn ipv4_cidr_covers_exactly_its_block(
a in any::<u8>(), b in any::<u8>(), c in any::<u8>(), d in any::<u8>(),
prefix in 8u8..=32,
) {
let spec = parse_target(&format!("{a}.{b}.{c}.{d}/{prefix}"));
prop_assert!(spec.is_ok());
let range = spec.unwrap().range().expect("CIDR targets are ranges");
prop_assert_eq!(range.count(), 1u128 << (32 - prefix));
prop_assert!(range.contains([a, b, c, d].into()));
}
#[test]
fn subtract_and_merge_keep_membership(
bounds in prop::collection::vec((any::<u16>(), 0u16..512), 1..6),
hole in (any::<u16>(), 0u16..512),
probes in prop::collection::vec(any::<u16>(), 16),
) {
let ranges: Vec<IpRange> = bounds.into_iter().map(range).collect();
let hole = range(hole);
let merged = merge_ranges(ranges.clone());
for pair in merged.windows(2) {
prop_assert!(pair[0].end() < pair[1].start(), "merged ranges overlap or are unsorted");
}
for probe in probes {
let ip = addr(probe);
let inside = ranges.iter().any(|range| range.contains(ip));
prop_assert_eq!(merged.iter().any(|range| range.contains(ip)), inside);
for range in &ranges {
let kept = range.subtract(&hole).iter().any(|part| part.contains(ip));
prop_assert_eq!(kept, range.contains(ip) && !hole.contains(ip));
}
}
}
}
+2
View File
@@ -32,6 +32,8 @@ services:
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:-}
ports:
- "${XEXEU_PUBLISH:-127.0.0.1:8788}:8788"
volumes:
+9
View File
@@ -33,6 +33,15 @@ present, must match `Host`. Without `XEXEU_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
scanner that stopped.
## `xexeu scanner`
Runs the continuous scheduler and scan engine, writing sweep batches —
+30
View File
@@ -102,6 +102,36 @@ and a broad daily one covering the same address). The storage layer
deduplicates by asset identity, and `config check` lists the overlap with
each host's effective (shortest) cadence.
### `[[webhook]]` — change alerts
After each ingested sweep, `xexeu serve` posts the surface changes it found to
every `[[webhook]]` (one request per sweep, only when there is something to
send):
```toml
[[webhook]]
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
```
- `formato = "json"` sends `{"fonte", "versao", "grupo", "sweep_id", "eventos"}`
with the same event objects as `/api/changes`. `slack` (also Mattermost and
Rocket.Chat) and `discord` send a short text listing up to 20 changes.
- `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.
- 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
after changing them by hand.
## Editing a group from the dashboard
`xexeu serve`'s **Groups** view can create, edit and delete groups without
+9
View File
@@ -33,6 +33,15 @@ quando presente, precisa bater com o `Host`. Sem `XEXEU_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
scanner que parou.
## `xexeu scanner`
Roda o agendador e o motor de varredura contínuos, gravando lotes — nunca
+31
View File
@@ -106,6 +106,37 @@ frequência e um amplo diário cobrindo o mesmo endereço). A camada de
armazenamento deduplica por identidade de ativo, e `config check` lista a
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
superfície encontradas para cada `[[webhook]]` (uma requisição por varredura,
só quando há algo a enviar):
```toml
[[webhook]]
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
```
- `formato = "json"` envia `{"fonte", "versao", "grupo", "sweep_id", "eventos"}`
com os mesmos objetos de evento do `/api/changes`. `slack` (também Mattermost
e Rocket.Chat) e `discord` enviam um texto curto listando até 20 mudanças.
- `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
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);
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
+8
View File
@@ -56,3 +56,11 @@ alvos = ["10.0.1.1", "10.0.1.2", "10.0.1.10-10.0.1.20", "db01.interno.exemplo.or
cron = "0 3 * * *" # varredura completa (1-65535 + vulnerabilidades) às 03:00
perfil = "completo"
criticidade = "critica"
# Alertas: as mudanças de cada varredura vão para um webhook (veja docs/configuration.md).
# [[webhook]]
# url = "https://hooks.slack.com/services/T000/B000/XXXX"
# formato = "slack"
# eventos = ["host_novo", "porta_nova", "servico_alterado"]
# grupos = ["dmz", "nucleo"]
# segredo_env = "XEXEU_WEBHOOK_KEY"
+2203
View File
File diff suppressed because it is too large. Load diff
+43
View File
@@ -0,0 +1,43 @@
[package]
name = "xexeu-fuzz"
version = "0.0.0"
publish = false
edition = "2021"
[package.metadata]
cargo-fuzz = true
[dependencies]
libfuzzer-sys = "0.4"
xexeu-core = { path = "../crates/xexeu-core" }
# Kept out of the main workspace: it needs a nightly toolchain.
[workspace]
[[bin]]
name = "der_certificate"
path = "fuzz_targets/der_certificate.rs"
test = false
doc = false
bench = false
[[bin]]
name = "service_banner"
path = "fuzz_targets/service_banner.rs"
test = false
doc = false
bench = false
[[bin]]
name = "vuln_feeds"
path = "fuzz_targets/vuln_feeds.rs"
test = false
doc = false
bench = false
[[bin]]
name = "operator_input"
path = "fuzz_targets/operator_input.rs"
test = false
doc = false
bench = false
+9
View File
@@ -0,0 +1,9 @@
#![no_main]
//! TLS certificates come from any host in scope.
use libfuzzer_sys::fuzz_target;
use xexeu_core::vuln::checks::parse_x509_der_not_after;
fuzz_target!(|der: &[u8]| {
let _ = parse_x509_der_not_after(der);
});
+15
View File
@@ -0,0 +1,15 @@
#![no_main]
//! Targets, exclusions, scope entries and cron come from the config file and
//! 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};
fuzz_target!(|text: &str| {
let _ = parse_target(text);
let _ = parse_exclusion(text);
let _ = parse_scope_entry(text);
let _ = CronSpec::parse(text);
let _ = Jitter::parse(text);
});
+13
View File
@@ -0,0 +1,13 @@
#![no_main]
//! 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;
fuzz_target!(|text: &str| {
let _ = parse_banner_to_cpe(text);
let _ = extract_server_header(text);
let _ = evaluate_http_admin_response(8080, text);
});
+15
View File
@@ -0,0 +1,15 @@
#![no_main]
//! NVD and KEV feeds are downloaded or imported from files.
use std::io::Cursor;
use libfuzzer_sys::fuzz_target;
use xexeu_core::vuln::feeds::{parse_kev_reader, parse_nvd_json, Cpe};
fuzz_target!(|data: &[u8]| {
let _ = parse_nvd_json(Cursor::new(data));
let _ = parse_kev_reader(Cursor::new(data));
if let Ok(text) = std::str::from_utf8(data) {
let _ = Cpe::parse(text);
}
});