diff --git a/.gitea/workflows/weekly.yml b/.gitea/workflows/weekly.yml new file mode 100644 index 0000000..97791eb --- /dev/null +++ b/.gitea/workflows/weekly.yml @@ -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 ` 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 diff --git a/.gitignore b/.gitignore index 52fa33f..023b17d 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,7 @@ __pycache__/ .DS_Store /data /config +/fuzz/target +/fuzz/corpus +/fuzz/artifacts +/fuzz/coverage diff --git a/CHANGELOG.md b/CHANGELOG.md index 98366d8..daf169f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,19 @@ Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versio ## [Unreleased] +## [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 diff --git a/CHANGELOG.pt-BR.md b/CHANGELOG.pt-BR.md index 6b70bcf..07917f6 100644 --- a/CHANGELOG.pt-BR.md +++ b/CHANGELOG.pt-BR.md @@ -6,6 +6,19 @@ Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/); ## [Não lançado] +## [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 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 45c68ba..5b160a2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -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`). diff --git a/CONTRIBUTING.pt-BR.md b/CONTRIBUTING.pt-BR.md index 7bc0f6f..462f5ad 100644 --- a/CONTRIBUTING.pt-BR.md +++ b/CONTRIBUTING.pt-BR.md @@ -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`). diff --git a/Cargo.lock b/Cargo.lock index 01236f7..7ffb530 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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" @@ -1164,6 +1213,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 +1231,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 +1360,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 +1520,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 +1788,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 +1920,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 +2042,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 +2105,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 +2368,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,7 +2386,7 @@ checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" [[package]] name = "xexeu-cli" -version = "1.0.0" +version = "1.1.0" dependencies = [ "axum", "chrono", @@ -2260,7 +2401,7 @@ dependencies = [ [[package]] name = "xexeu-core" -version = "1.0.0" +version = "1.1.0" dependencies = [ "arrow-array", "arrow-schema", @@ -2268,6 +2409,7 @@ dependencies = [ "croner", "ipnet", "parquet", + "proptest", "reqwest", "rusqlite", "rustls", diff --git a/Cargo.toml b/Cargo.toml index 2248f84..0ad313c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "2" members = ["crates/xexeu-core", "crates/xexeu-cli"] [workspace.package] -version = "1.0.0" +version = "1.1.0" edition = "2021" license = "MIT OR Apache-2.0" repository = "https://git.lucasrguerra.dev.br/ciberfauna/xexeu" diff --git a/README.md b/README.md index 9c2ec56..a5b9793 100644 --- a/README.md +++ b/README.md @@ -134,8 +134,8 @@ 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 | +| **Done (1.1.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 | +| **Next** | Webhook alerts, Prometheus metrics | | **Later** | `nmap` adapter and the `xexeu-scanner-nmap` variant, email alerts, OSV and distribution backport mapping | | **Not planned** | Exploitation payloads, NASL engine, mandatory cloud services, desktop Tauri wrapper | diff --git a/README.pt-BR.md b/README.pt-BR.md index d913b27..7a02c5e 100644 --- a/README.pt-BR.md +++ b/README.pt-BR.md @@ -134,8 +134,8 @@ 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 | +| **Feito (1.1.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 | +| **Próximo** | 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 | | **Não planejado** | Payloads de exploração, motor NASL, serviços de nuvem obrigatórios, wrapper desktop Tauri | diff --git a/ROADMAP.md b/ROADMAP.md index 96e9b05..993e53c 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -4,11 +4,10 @@ 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`). +- **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,7 +19,6 @@ 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. diff --git a/ROADMAP.pt-BR.md b/ROADMAP.pt-BR.md index 824074a..f9f3a58 100644 --- a/ROADMAP.pt-BR.md +++ b/ROADMAP.pt-BR.md @@ -4,11 +4,10 @@ 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`). +- **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,7 +19,6 @@ 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. diff --git a/crates/xexeu-cli/src/commands.rs b/crates/xexeu-cli/src/commands.rs new file mode 100644 index 0000000..f286803 --- /dev/null +++ b/crates/xexeu-cli/src/commands.rs @@ -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 +} diff --git a/crates/xexeu-cli/src/config_cmd.rs b/crates/xexeu-cli/src/config_cmd.rs new file mode 100644 index 0000000..051884a --- /dev/null +++ b/crates/xexeu-cli/src/config_cmd.rs @@ -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, String> { + let expansions = config + .groups + .iter() + .map(expand_group) + .collect::, _>>() + .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), + } +} diff --git a/crates/xexeu-cli/src/feeds_cmd.rs b/crates/xexeu-cli/src/feeds_cmd.rs new file mode 100644 index 0000000..d4bb9a4 --- /dev/null +++ b/crates/xexeu-cli/src/feeds_cmd.rs @@ -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 { + 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, + nvd_path: Option, + kev_path: Option, + 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 "), + }; + + 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 +} diff --git a/crates/xexeu-cli/src/main.rs b/crates/xexeu-cli/src/main.rs index 0816b67..9d7f11b 100644 --- a/crates/xexeu-cli/src/main.rs +++ b/crates/xexeu-cli/src/main.rs @@ -1,39 +1,22 @@ mod auth; +mod commands; +mod config_cmd; +mod feeds_cmd; +mod scanner; +mod server; -use std::collections::{BTreeMap, BTreeSet, HashSet}; use std::fs; -use std::net::IpAddr; use std::path::{Path, PathBuf}; use std::process::ExitCode; -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::Arc; -use std::time::Duration; -use axum::extract::{Path as AxumPath, Query, State}; -use axum::http::{header, HeaderMap, HeaderValue, StatusCode}; -use axum::response::IntoResponse; -use axum::{Json, Router}; use chrono::{DateTime, Utc}; use clap::{Parser, Subcommand}; -use serde::{Deserialize, Serialize}; -use tokio::sync::{Mutex, RwLock}; -use xexeu_core::batch::{EngineMode, ServiceObservation, SweepBatch, SweepManifest, SweepStatus}; -use xexeu_core::config::{GroupConfig, ValidationReport, XexeuConfig}; -use xexeu_core::diff::{diff_batch, CurrentState, DiffOptions, EventKind}; -use xexeu_core::report::ExecutiveReport; -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::{next_runs, should_run_now, RunDecision, RunHistory}; -use xexeu_core::storage::{SqliteStorage, Storage}; -use xexeu_core::targets::{ - effective_cadence, expand_group, filter_in_scope, resolve_name, scope_ranges, IpRange, -}; -use xexeu_core::vuln::checks::{check_tls_certificate_der, evaluate_http_admin_response}; -use xexeu_core::vuln::matcher::{match_banner, Confidence, Finding}; -use xexeu_core::vuln::{import_kev, import_nvd, sync_feeds, KevCatalog, SyncOptions, VulnDatabase}; +use commands::{run_changes, run_doctor, run_export}; +use config_cmd::run_config_check; +use feeds_cmd::{run_feeds_import, run_feeds_sync}; +use scanner::{run_scanner, scan_once}; +use server::run_serve; +use xexeu_core::config::{ValidationReport, XexeuConfig}; #[derive(Parser)] #[command( @@ -228,1101 +211,6 @@ fn validated_config(path: &Path) -> Result<(XexeuConfig, ValidationReport), Stri .map_err(|error| format!("configuração inválida em {}: {error}", path.display())) } -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, String> { - let expansions = config - .groups - .iter() - .map(expand_group) - .collect::, _>>() - .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), - } -} - -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 { - 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 = 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 = 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 = 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, 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, - }) -} - -async fn scan_once( - group: Option, - 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 = 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(()) -} - -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 = 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 = - 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(()) -} - -fn find_sweep_manifests(sweeps_dir: &Path) -> Vec { - 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>, - sweeps_ingested: Arc, -) { - 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(¤t_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() - ); - } - 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)] -struct ServerState { - config: Arc>, - config_path: PathBuf, - storage: Arc>, - sweeps_ingested: Arc, - vuln_db: Arc>, - feeds_last_sync: Arc>>>, -} - -#[derive(Serialize)] -struct HealthResponse { - status: &'static str, - version: &'static str, -} - -async fn health_handler() -> Json { - Json(HealthResponse { - status: "ok", - version: env!("CARGO_PKG_VERSION"), - }) -} - -#[derive(Serialize)] -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, - groups: Vec, -} - -#[derive(Serialize)] -struct GroupScheduleDto { - group: String, - profile: String, - cron: String, - next_run: String, -} - -async fn status_handler(State(state): State) -> Json { - 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, - }) -} - -async fn get_config_handler(State(state): State) -> Json { - let config = state.config.read().await; - Json(config.clone()) -} - -async fn create_group_handler( - State(state): State, - Json(new_group): Json, -) -> Result<(StatusCode, Json), (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///`, 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))) -} - -async fn update_group_handler( - State(state): State, - AxumPath(group_name): AxumPath, - Json(updated_group): Json, -) -> Result, (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)) -} - -async fn delete_group_handler( - State(state): State, - AxumPath(group_name): AxumPath, -) -> Result { - 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) -} - -/// 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)] -struct HostDto { - asset_key: String, - network: String, - ip: String, - status: &'static str, - absences: u32, - first_seen: String, - last_seen: String, - ports: Vec, -} - -#[derive(Serialize)] -struct PortDto { - protocol: String, - port: u16, - status: &'static str, - absences: u32, - first_seen: String, - last_seen: String, - product: Option, - version: Option, - cpe: Option, - findings: Vec, -} - -fn current_state_to_dtos(current_state: &CurrentState) -> Vec { - 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() -} - -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 ¤t_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 -} - -async fn export_hosts_csv_handler( - State(state): State, -) -> Result { - 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(¤t_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)) -} - -async fn export_findings_csv_handler( - State(state): State, -) -> Result { - 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 ¤t_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)) -} - -async fn export_changes_csv_handler( - State(state): State, - Query(query): Query, -) -> Result { - 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)) -} - -async fn hosts_handler( - State(state): State, -) -> Result>, (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(¤t_state); - Ok(Json(dtos)) -} - -#[derive(Deserialize)] -struct ChangesQuery { - since: Option, -} - fn parse_since(raw: &str) -> Option> { let raw = raw.trim(); if raw.is_empty() { @@ -1347,569 +235,3 @@ fn parse_since(raw: &str) -> Option> { .ok() .map(|date_time| date_time.with_timezone(&Utc)) } - -async fn changes_handler( - State(state): State, - Query(query): Query, -) -> Result>, (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)) -} - -async fn report_handler( - State(state): State, -) -> Result { - 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, ¤t_state, &vuln_db, last_sync, Utc::now()); - let html = report.render_html(); - Ok(([(header::CONTENT_TYPE, "text/html; charset=utf-8")], html)) -} - -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"); - -async fn index_handler() -> impl IntoResponse { - ( - [(header::CONTENT_TYPE, "text/html; charset=utf-8")], - INDEX_HTML, - ) -} - -async fn css_handler() -> impl IntoResponse { - ([(header::CONTENT_TYPE, "text/css; charset=utf-8")], APP_CSS) -} - -async fn js_handler() -> impl IntoResponse { - ( - [( - header::CONTENT_TYPE, - "application/javascript; charset=utf-8", - )], - APP_JS, - ) -} - -async fn i18n_js_handler() -> impl IntoResponse { - ( - [( - header::CONTENT_TYPE, - "application/javascript; charset=utf-8", - )], - I18N_JS, - ) -} - -async fn i18n_en_js_handler() -> impl IntoResponse { - ( - [( - header::CONTENT_TYPE, - "application/javascript; charset=utf-8", - )], - I18N_EN_JS, - ) -} - -async fn paged_js_handler() -> impl IntoResponse { - ( - [( - header::CONTENT_TYPE, - "application/javascript; charset=utf-8", - )], - PAGED_JS, - ) -} - -async fn logo_handler() -> impl IntoResponse { - ([(header::CONTENT_TYPE, "image/png")], LOGO_PNG) -} - -fn parse_duration_str(raw: &str) -> Option { - 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::() { - 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 -} - -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)); - - // 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(); - tokio::spawn(async move { - poll_sweeps(poller_sweeps, poller_storage, poller_ingested).await; - }); - - // Spawn periodic background sync if auto_sync is enabled in config - if config.defaults.feeds.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(); - let interval_str = config.defaults.feeds.sync_interval.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: Arc::new(RwLock::new(config)), - config_path: config_path.to_path_buf(), - storage: shared_storage, - sweeps_ingested, - vuln_db: shared_vuln_db, - feeds_last_sync: shared_last_sync, - }; - - let app = Router::new() - .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(()) -} - -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}")), - } -} - -fn find_matching_file(dir: &Path, keyword: &str, ext: &str) -> Option { - 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 -} - -fn run_feeds_import( - directory: Option, - nvd_path: Option, - kev_path: Option, - 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 "), - }; - - 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 -} - -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 -} - -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::>().await, - }; - }; - - #[cfg(not(unix))] - let terminate = std::future::pending::<()>(); - - tokio::select! { - _ = ctrl_c => {}, - _ = terminate => {}, - } -} - -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 - } -} - -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 -} diff --git a/crates/xexeu-cli/src/scanner.rs b/crates/xexeu-cli/src/scanner.rs new file mode 100644 index 0000000..e969169 --- /dev/null +++ b/crates/xexeu-cli/src/scanner.rs @@ -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 { + 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 = 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 = 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 = 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, 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, + 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 = 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 = 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 = + 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(()) +} diff --git a/crates/xexeu-cli/src/server/api.rs b/crates/xexeu-cli/src/server/api.rs new file mode 100644 index 0000000..bc501c5 --- /dev/null +++ b/crates/xexeu-cli/src/server/api.rs @@ -0,0 +1,308 @@ +//! 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 { + 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, + groups: Vec, +} + +#[derive(Serialize)] +struct GroupScheduleDto { + group: String, + profile: String, + cron: String, + next_run: String, +} + +pub(crate) async fn status_handler(State(state): State) -> Json { + 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) -> Json { + let config = state.config.read().await; + Json(config.clone()) +} + +pub(crate) async fn create_group_handler( + State(state): State, + Json(new_group): Json, +) -> Result<(StatusCode, Json), (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///`, 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, + AxumPath(group_name): AxumPath, + Json(updated_group): Json, +) -> Result, (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, + AxumPath(group_name): AxumPath, +) -> Result { + 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, +) -> Result>, (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(¤t_state); + Ok(Json(dtos)) +} + +#[derive(Deserialize)] +pub(crate) struct ChangesQuery { + pub(crate) since: Option, +} + +pub(crate) async fn changes_handler( + State(state): State, + Query(query): Query, +) -> Result>, (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, +) -> Result { + 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, ¤t_state, &vuln_db, last_sync, Utc::now()); + let html = report.render_html(); + Ok(([(header::CONTENT_TYPE, "text/html; charset=utf-8")], html)) +} diff --git a/crates/xexeu-cli/src/server/assets.rs b/crates/xexeu-cli/src/server/assets.rs new file mode 100644 index 0000000..7ee3e1f --- /dev/null +++ b/crates/xexeu-cli/src/server/assets.rs @@ -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) +} diff --git a/crates/xexeu-cli/src/server/export.rs b/crates/xexeu-cli/src/server/export.rs new file mode 100644 index 0000000..d67b6c4 --- /dev/null +++ b/crates/xexeu-cli/src/server/export.rs @@ -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, +} + +#[derive(Serialize)] +struct PortDto { + protocol: String, + port: u16, + status: &'static str, + absences: u32, + first_seen: String, + last_seen: String, + product: Option, + version: Option, + cpe: Option, + findings: Vec, +} + +pub(crate) fn current_state_to_dtos(current_state: &CurrentState) -> Vec { + 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 ¤t_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, +) -> Result { + 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(¤t_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, +) -> Result { + 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 ¤t_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, + Query(query): Query, +) -> Result { + 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)) +} diff --git a/crates/xexeu-cli/src/server/mod.rs b/crates/xexeu-cli/src/server/mod.rs new file mode 100644 index 0000000..673b83f --- /dev/null +++ b/crates/xexeu-cli/src/server/mod.rs @@ -0,0 +1,354 @@ +//! `xexeu serve`: background batch ingestion, feed sync and the HTTP server. + +mod api; +mod assets; +pub(crate) mod export; + +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 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 { + 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>, + sweeps_ingested: Arc, +) { + 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(¤t_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() + ); + } + 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>, + config_path: PathBuf, + storage: Arc>, + sweeps_ingested: Arc, + vuln_db: Arc>, + feeds_last_sync: Arc>>>, +} + +fn parse_duration_str(raw: &str) -> Option { + 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::() { + 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)); + + // 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(); + tokio::spawn(async move { + poll_sweeps(poller_sweeps, poller_storage, poller_ingested).await; + }); + + // Spawn periodic background sync if auto_sync is enabled in config + if config.defaults.feeds.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(); + let interval_str = config.defaults.feeds.sync_interval.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: Arc::new(RwLock::new(config)), + config_path: config_path.to_path_buf(), + storage: shared_storage, + sweeps_ingested, + vuln_db: shared_vuln_db, + feeds_last_sync: shared_last_sync, + }; + + let app = Router::new() + .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::>().await, + }; + }; + + #[cfg(not(unix))] + let terminate = std::future::pending::<()>(); + + tokio::select! { + _ = ctrl_c => {}, + _ = terminate => {}, + } +} diff --git a/crates/xexeu-core/Cargo.toml b/crates/xexeu-core/Cargo.toml index 30f3594..c254c78 100644 --- a/crates/xexeu-core/Cargo.toml +++ b/crates/xexeu-core/Cargo.toml @@ -28,3 +28,6 @@ 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" diff --git a/crates/xexeu-core/src/diff.rs b/crates/xexeu-core/src/diff.rs index b74b91d..80d2370 100644 --- a/crates/xexeu-core/src/diff.rs +++ b/crates/xexeu-core/src/diff.rs @@ -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 { + 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 { + prop_oneof![Just(HostState::Alive), Just(HostState::Unresponsive)] + } + + fn port_state() -> impl Strategy { + 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 { + 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::(), + 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::>() + }; + 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); + } + } + } + } } diff --git a/crates/xexeu-core/src/scan/fingerprint.rs b/crates/xexeu-core/src/scan/fingerprint.rs index 0545d9d..f2a38a9 100644 --- a/crates/xexeu-core/src/scan/fingerprint.rs +++ b/crates/xexeu-core/src/scan/fingerprint.rs @@ -73,7 +73,8 @@ impl ServerCertVerifier for CertCaptureVerifier { } } -fn extract_server_header(response: &str) -> Option { +/// Value of the `Server:` header in a raw HTTP response, if any. +pub fn extract_server_header(response: &str) -> Option { for line in response.lines() { let trimmed = line.trim(); if trimmed.is_empty() { diff --git a/crates/xexeu-core/src/vuln/checks.rs b/crates/xexeu-core/src/vuln/checks.rs index ace8eab..97fb5c5 100644 --- a/crates/xexeu-core/src/vuln/checks.rs +++ b/crates/xexeu-core/src/vuln/checks.rs @@ -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, 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 diff --git a/crates/xexeu-core/tests/untrusted_input.proptest-regressions b/crates/xexeu-core/tests/untrusted_input.proptest-regressions new file mode 100644 index 0000000..21207d6 --- /dev/null +++ b/crates/xexeu-core/tests/untrusted_input.proptest-regressions @@ -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) diff --git a/crates/xexeu-core/tests/untrusted_input.rs b/crates/xexeu-core/tests/untrusted_input.rs new file mode 100644 index 0000000..a1fad7a --- /dev/null +++ b/crates/xexeu-core/tests/untrusted_input.rs @@ -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 { + let mut out = vec![tag]; + let len = body.len(); + if len < 0x80 { + out.push(len as u8); + } else { + let bytes: Vec = 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 { + 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::(), 0..512)) { + let _ = parse_x509_der_not_after(&bytes); + } + + #[test] + fn der_parser_never_panics_on_corrupted_certificates( + serial in prop::collection::vec(any::(), 1..24), + filler in prop::collection::vec(any::(), 0..300), + not_after in prop_oneof![ + prop::collection::vec(any::(), 0..24), + "[0-9ţé€Z.+-]{10,20}".prop_map(String::into_bytes), + ], + utc in any::(), + flips in prop::collection::vec((any::(), any::()), 0..4), + cut in any::(), + ) { + let mut der = certificate(&serial, &filler, ¬_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::()) { + 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::(), 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::(), b in any::(), c in any::(), d in any::(), + 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::(), 0u16..512), 1..6), + hole in (any::(), 0u16..512), + probes in prop::collection::vec(any::(), 16), + ) { + let ranges: Vec = 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)); + } + } + } +} diff --git a/fuzz/Cargo.lock b/fuzz/Cargo.lock new file mode 100644 index 0000000..f563b8c --- /dev/null +++ b/fuzz/Cargo.lock @@ -0,0 +1,2203 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "const-random", + "getrandom 0.3.4", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" + +[[package]] +name = "arrow-array" +version = "60.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f3d22a41d3df78b71df0b685af219ae3a94188ab98d6fb29c958eb55c3247f4" +dependencies = [ + "ahash", + "arrow-buffer", + "arrow-data", + "arrow-schema", + "chrono", + "half", + "hashbrown", + "num-complex", + "num-integer", + "num-traits", +] + +[[package]] +name = "arrow-buffer" +version = "60.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7bd46a530bc1a8e763102fc36c1dc0f51f3ffa150c78e7f5658ccb54b1458ade" +dependencies = [ + "bytes", + "half", + "num-bigint", + "num-traits", +] + +[[package]] +name = "arrow-cmp" +version = "60.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1913e57a64fbf2c4502fa6d54b547d6a1ae59e3146cbc15321d47468c937abd1" +dependencies = [ + "arrow-array", + "arrow-buffer", + "arrow-schema", +] + +[[package]] +name = "arrow-data" +version = "60.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "415b7fbc4cf56b080bb5677a4ae74211b5c79e571ed37a1d547633ec07f3b43b" +dependencies = [ + "arrow-buffer", + "arrow-schema", + "half", + "num-integer", + "num-traits", +] + +[[package]] +name = "arrow-ipc" +version = "60.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45f3e766bccf5a0cb57a5de52a4cba450dea5171547c2cb5939b486d08887cba" +dependencies = [ + "arrow-array", + "arrow-buffer", + "arrow-data", + "arrow-schema", + "arrow-select", + "flatbuffers", +] + +[[package]] +name = "arrow-schema" +version = "60.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de2c8e714b466404cdc1189e89f892426efea614d938e16c15518c340cd43ba3" + +[[package]] +name = "arrow-select" +version = "60.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5af3f6656c5f2c6944f93d9a357a7f204c93d5f349385a44cf46c4a26fbcf30" +dependencies = [ + "ahash", + "arrow-array", + "arrow-buffer", + "arrow-cmp", + "arrow-data", + "arrow-schema", + "num-traits", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "375989decec1a0fa424442bed520fa12ede43a48475ce8c7417d2c69b32b5f6b" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core", +] + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "num-traits", + "serde", + "windows-link", +] + +[[package]] +name = "const-random" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87e00182fe74b066627d63b85fd550ac2998d4b0bd86bfed477a0ae4c7c71359" +dependencies = [ + "const-random-macro", +] + +[[package]] +name = "const-random-macro" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9d839f2a20b0aee515dc581a6172f2321f96cab76c1a38a4c584a194955390e" +dependencies = [ + "getrandom 0.2.17", + "once_cell", + "tiny-keccak", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "croner" +version = "4.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26d09284075f5c87675790d1ad74212a7863eb8bdf228cdbd364f08a152fc62d" +dependencies = [ + "chrono", + "derive_builder", + "strum", +] + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "darling" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 2.0.119", +] + +[[package]] +name = "darling_macro" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" +dependencies = [ + "darling_core", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "derive_builder" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "507dfb09ea8b7fa618fcf76e953f4f5e192547945816d5358edffe39f6f94947" +dependencies = [ + "derive_builder_macro", +] + +[[package]] +name = "derive_builder_core" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "derive_builder_macro" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c" +dependencies = [ + "derive_builder_core", + "syn 2.0.119", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flatbuffers" +version = "25.12.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35f6839d7b3b98adde531effaf34f0c2badc6f4735d26fe74709d8e513a96ef3" +dependencies = [ + "bitflags", + "rustc_version", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 6.0.0", + "rand_core", + "wasm-bindgen", +] + +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "num-traits", + "zerocopy", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashlink" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a596f1b20ed2cc5ecac41a164aaebc7258057060f06c0cf7a2ba3991ee7990fb" +dependencies = [ + "hashbrown", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2 0.6.5", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libfuzzer-sys" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9fd2f41a1cba099f79a0b6b6c35656cf7c03351a7bae8ff0f28f25270f929d2" +dependencies = [ + "arbitrary", + "cc", +] + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libsqlite3-sys" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14a5f01b87b92705d07b433c06f96cbc764637d81a0bffb5734ce17cf0f9a2b3" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "num-bigint" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93e7820bc0a80a0238e650327316f929ba18d5be054b647490a3a6a339f3e7c0" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "parquet" +version = "60.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "806eaa0f1c0436dcb43bee8e6a82bf2efff90521a60172f8281cb9ef577b43a4" +dependencies = [ + "ahash", + "arrow-array", + "arrow-buffer", + "arrow-data", + "arrow-ipc", + "arrow-schema", + "arrow-select", + "base64 0.23.1", + "bytes", + "chrono", + "half", + "hashbrown", + "num-bigint", + "num-integer", + "num-traits", + "seq-macro", + "snap", + "twox-hash", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2 0.6.5", + "thiserror 2.0.21", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror 2.0.21", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2 0.6.5", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core", +] + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "webpki-roots", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rsqlite-vfs" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353b74f9810d5b085b6c42c9d86a5f0fdb795553235cdd48753b32e3809d18a7" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "rusqlite" +version = "0.41.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da9bba6f3506135e120a6586df05be18b48d18896600646a4bec8f993d91a594" +dependencies = [ + "bitflags", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", + "sqlite-wasm-rs", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "seq-macro" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bc711410fbe7399f390ca1c3b60ad0f53f80e95c5eb935e52268a0e2cd49acc" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_spanned" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" + +[[package]] +name = "snap" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "199905e6153d6405f9728fe44daace35f8f837bbf830bb6e85fbd5828709a886" + +[[package]] +name = "socket2" +version = "0.5.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678" +dependencies = [ + "libc", + "windows-sys 0.52.0", +] + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "sqlite-wasm-rs" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36bd8e29bf08189a005b2df1df99823aa0861cabe9044e5f31ed54ca292ee618" +dependencies = [ + "cc", + "rsqlite-vfs", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "strum" +version = "0.27.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.27.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7695ce3845ea4b33927c055a39dc438a45b059f7c1b3d91d38d10355fb8cbca7" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tiny-keccak" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237" +dependencies = [ + "crunchy", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "socket2 0.6.5", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "toml" +version = "1.1.8+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "twox-hash" +version = "2.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "ulid" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "947dde63b6d514cc5e044edad4e0ca7261afd1099d16c83d942cb2b2f348689c" +dependencies = [ + "rand", + "serde", + "web-time", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.9", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "xexeu-core" +version = "1.0.0" +dependencies = [ + "arrow-array", + "arrow-schema", + "chrono", + "croner", + "ipnet", + "parquet", + "reqwest", + "rusqlite", + "rustls", + "serde", + "serde_json", + "sha2", + "socket2 0.5.10", + "tempfile", + "thiserror 1.0.69", + "tokio", + "tokio-rustls", + "toml", + "ulid", +] + +[[package]] +name = "xexeu-fuzz" +version = "0.0.0" +dependencies = [ + "libfuzzer-sys", + "xexeu-core", +] + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml new file mode 100644 index 0000000..b80b5ef --- /dev/null +++ b/fuzz/Cargo.toml @@ -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 diff --git a/fuzz/fuzz_targets/der_certificate.rs b/fuzz/fuzz_targets/der_certificate.rs new file mode 100644 index 0000000..f1484c4 --- /dev/null +++ b/fuzz/fuzz_targets/der_certificate.rs @@ -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); +}); diff --git a/fuzz/fuzz_targets/operator_input.rs b/fuzz/fuzz_targets/operator_input.rs new file mode 100644 index 0000000..60e159d --- /dev/null +++ b/fuzz/fuzz_targets/operator_input.rs @@ -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); +}); diff --git a/fuzz/fuzz_targets/service_banner.rs b/fuzz/fuzz_targets/service_banner.rs new file mode 100644 index 0000000..d8e1403 --- /dev/null +++ b/fuzz/fuzz_targets/service_banner.rs @@ -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); +}); diff --git a/fuzz/fuzz_targets/vuln_feeds.rs b/fuzz/fuzz_targets/vuln_feeds.rs new file mode 100644 index 0000000..5f825ad --- /dev/null +++ b/fuzz/fuzz_targets/vuln_feeds.rs @@ -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); + } +});